PageRenderTime 52ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/BerichtsheftApp/src/com/applang/PluginUtils.java

https://github.com/sefirot/androidStuff
Java | 511 lines | 455 code | 50 blank | 6 comment | 75 complexity | 017a376d6f9954faf1a76b3a57355b6e MD5 | raw file
  1. package com.applang;
  2. import java.awt.Component;
  3. import java.awt.Container;
  4. import java.awt.Image;
  5. import java.awt.event.ActionListener;
  6. import java.awt.image.BufferedImage;
  7. import java.io.Closeable;
  8. import java.io.File;
  9. import java.io.FileInputStream;
  10. import java.io.FileWriter;
  11. import java.io.InputStream;
  12. import java.io.StringWriter;
  13. import java.io.Writer;
  14. import java.lang.reflect.Method;
  15. import java.net.MalformedURLException;
  16. import java.net.URL;
  17. import java.util.HashSet;
  18. import java.util.Properties;
  19. import java.util.Set;
  20. import java.util.jar.JarEntry;
  21. import java.util.jar.JarFile;
  22. import javax.swing.AbstractButton;
  23. import javax.swing.Action;
  24. import javax.swing.ImageIcon;
  25. import javax.swing.JComponent;
  26. import javax.swing.SwingUtilities;
  27. import javax.swing.text.JTextComponent;
  28. import org.gjt.sp.jedit.Buffer;
  29. import org.gjt.sp.jedit.EditAction;
  30. import org.gjt.sp.jedit.EditPane;
  31. import org.gjt.sp.jedit.GUIUtilities;
  32. import org.gjt.sp.jedit.View;
  33. import org.gjt.sp.jedit.jEdit;
  34. import org.gjt.sp.jedit.gui.RolloverButton;
  35. import org.gjt.sp.jedit.io.VFS;
  36. import org.gjt.sp.jedit.io.VFSManager;
  37. import org.gjt.sp.jedit.textarea.TextArea;
  38. import org.gjt.sp.jedit.visitors.JEditVisitorAdapter;
  39. import org.gjt.sp.util.IOUtilities;
  40. import org.gjt.sp.util.Log;
  41. import com.inet.jortho.FileUserDictionary;
  42. import com.inet.jortho.SpellChecker;
  43. import static com.applang.Util.*;
  44. import static com.applang.Util1.*;
  45. import static com.applang.Util2.*;
  46. import static com.applang.SwingUtil.*;
  47. public class PluginUtils {
  48. public static boolean insideJEdit() {
  49. try {
  50. jEdit.getProperty("tip.show");
  51. return true;
  52. } catch (NullPointerException ex) {
  53. return false;
  54. }
  55. }
  56. public static String getSettingsDirectory() {
  57. if (insideJEdit())
  58. return jEdit.getSettingsDirectory();
  59. else
  60. return System.getProperty("jedit.settings.dir");
  61. }
  62. public static Properties loadProperties(String fileName) {
  63. diag_println(DIAG_OFF, ".props : ", fileName);
  64. Properties props = new Properties();
  65. if (notNullOrEmpty(fileName)) {
  66. InputStream in = null;
  67. try {
  68. JarFile jarFile = null;
  69. if (isJarUri(fileName)) {
  70. URL url = new URL(fileName);
  71. url = new URL(url.getFile());
  72. String[] parts = url.getFile().split("!/");
  73. jarFile = new JarFile(new File(parts[0]));
  74. JarEntry jarEntry = jarFile.getJarEntry(parts[1]);
  75. in = jarFile.getInputStream(jarEntry);
  76. }
  77. else {
  78. File file = new File(fileName);
  79. if (file.isFile()) {
  80. in = new FileInputStream(file);
  81. } else {
  82. in = PluginUtils.class.getResourceAsStream(fileName);
  83. }
  84. }
  85. props.load(in);
  86. if (jarFile != null)
  87. jarFile.close();
  88. } catch (Exception e) {
  89. Log.log(Log.ERROR, PluginUtils.class + ".loadProperties", e);
  90. } finally {
  91. IOUtilities.closeQuietly((Closeable) in);
  92. }
  93. }
  94. return props;
  95. }
  96. // NOTE used in scripts
  97. public static String getProperty(String name) {
  98. return getProperty(name, null);
  99. }
  100. public static String getProperty(String name, String defaultValue) {
  101. String prop;
  102. if (insideJEdit())
  103. prop = jEdit.getProperty(name, defaultValue);
  104. else
  105. prop = properties.getProperty(name, defaultValue);
  106. if (nullOrEmpty(prop) && (name.endsWith("_COMMAND") || name.endsWith("_SDK")))
  107. prop = getSetting(name, "");
  108. return prop;
  109. }
  110. public static Properties properties = null;
  111. static {
  112. if (!insideJEdit()) {
  113. String part = System.getProperty("plugin.props");
  114. String fileName = pathCombine(relativePath(), part);
  115. if (!fileExists(fileName)) {
  116. fileName = resourceUrlOf(part, Constraint.END).toString();
  117. }
  118. properties = loadProperties(fileName);
  119. }
  120. messageRedirection();
  121. }
  122. // NOTE used in scripts
  123. public static void setProperty(String name, String value) {
  124. if (insideJEdit())
  125. jEdit.setProperty(name, value);
  126. else
  127. properties.setProperty(name, value);
  128. }
  129. public static void saveSettings() {
  130. if (insideJEdit())
  131. jEdit.saveSettings();
  132. }
  133. public static void setStatusMessage(String msg) {
  134. View view = jEdit.getActiveView();
  135. if (view != null)
  136. view.getStatus().setMessageAndClear(msg);
  137. else
  138. longToast(msg);
  139. }
  140. public static void messageRedirection() {
  141. messRedirection = new Function<String>() {
  142. public String apply(Object... params) {
  143. String message = param("", 0, params);
  144. setStatusMessage(message);
  145. return message;
  146. }
  147. };
  148. }
  149. // NOTE used in scripts
  150. public static void invokeAction(View view, String actionName) {
  151. EditAction action = jEdit.getAction(actionName);
  152. if (action != null)
  153. action.invoke(view);
  154. }
  155. // NOTE used in scripts
  156. public static ImageIcon loadIcon(String path) {
  157. if (path != null && path.endsWith(".icon"))
  158. path = getProperty(path);
  159. if (nullOrEmpty(path))
  160. return null;
  161. try {
  162. if (path.startsWith("/"))
  163. return iconFrom(path);
  164. else if (!insideJEdit()) {
  165. path = pathCombine("/org/gjt/sp/jedit/icons/themes/tango", path);
  166. return iconFrom(path);
  167. }
  168. else
  169. return (ImageIcon) GUIUtilities.loadIcon(path);
  170. } catch (Exception e) {
  171. path = "/org/gjt/sp/jedit/icons/themes/tango/22x22/emblems/emblem-unreadable.png";
  172. return iconFrom(path);
  173. }
  174. }
  175. public static AbstractButton makeCustomButton(String name, ActionListener listener, boolean flip) {
  176. String toolTip = getProperty(name.concat(".label"));
  177. ImageIcon icon = loadIcon(name + ".icon");
  178. if (flip && icon != null) {
  179. Image img = icon.getImage();
  180. BufferedImage bimg = horizontalflip(img);
  181. icon = new ImageIcon(bimg);
  182. }
  183. AbstractButton b = new RolloverButton(icon);
  184. if (listener != null) {
  185. b.addActionListener(listener);
  186. b.setEnabled(true);
  187. } else {
  188. b.setEnabled(false);
  189. }
  190. b.setToolTipText(toolTip);
  191. return b;
  192. }
  193. public static AbstractButton makeCustomButton(CustomAction customAction, boolean flip) {
  194. AbstractButton btn;
  195. CustomActionType type = customAction.getType();
  196. if (type != null) {
  197. btn = makeCustomButton(type.resourceName(), null, flip);
  198. btn.setEnabled(true);
  199. }
  200. else {
  201. btn = new RolloverButton();
  202. String name = customAction.getValue(Action.NAME).toString();
  203. btn.setName(name);
  204. btn.setText(name);
  205. }
  206. btn.setAction(customAction);
  207. return btn;
  208. }
  209. public static void jEditDebugLogging() {
  210. org.gjt.sp.util.Log.init(true,org.gjt.sp.util.Log.DEBUG);
  211. org.gjt.sp.jedit.Debug.TOKEN_MARKER_DEBUG = true;
  212. org.gjt.sp.jedit.Debug.CHUNK_CACHE_DEBUG = true;
  213. }
  214. // NOTE leaves standard-out going to log
  215. public static <T> T suppressJEditErrorLog(Function<T> func, Object...params) {
  216. try {
  217. org.gjt.sp.util.Log.init(true,org.gjt.sp.util.Log.ERROR + 1);
  218. return func.apply(params);
  219. }
  220. finally {
  221. org.gjt.sp.util.Log.init(false,org.gjt.sp.util.Log.WARNING);
  222. }
  223. }
  224. public static void setupSpellChecker(String path) {
  225. if (!fileExists(new File(path, "dictionaries.cnf")))
  226. return;
  227. SpellChecker.setUserDictionaryProvider( new FileUserDictionary(path) );
  228. try {
  229. SpellChecker.registerDictionaries( new URL("file", null, path + "/"), null );
  230. } catch (MalformedURLException e) {
  231. Log.log(Log.ERROR, PluginUtils.class + ".setupSpellChecker", e);
  232. }
  233. }
  234. public static void spellChecking(JTextComponent jtc, boolean register) {
  235. if (register)
  236. SpellChecker.register(jtc);
  237. else
  238. SpellChecker.unregister(jtc);
  239. }
  240. public static final String FEATURE = "feature";
  241. public static String featureFile(String name, String feature, Properties props) {
  242. String path = tempPath() + PATH_SEP + name;
  243. try {
  244. Writer writer = write(new StringWriter(), ":");
  245. writer = write_assoc(writer, FEATURE, feature);
  246. writer = write(writer, ":");
  247. writer = write_assoc(writer, "wrap", "none");
  248. writer = write(writer, ":");
  249. String comment = writer.toString();
  250. FileWriter fileWriter = new FileWriter(path);
  251. props.store(fileWriter, comment);
  252. fileWriter.close();
  253. }
  254. catch (Exception e) {
  255. Log.log(Log.ERROR, PluginUtils.class + ".featureFile", e);
  256. }
  257. return path;
  258. }
  259. public static String getNextFeatureTemp() {
  260. int featureTitledCount = 0;
  261. for (String name : new File(tempPath()).list())
  262. if (name.startsWith(FEATURE))
  263. try {
  264. featureTitledCount = Math.max(
  265. featureTitledCount,
  266. Integer.parseInt(name
  267. .substring(FEATURE.length())));
  268. }
  269. catch(NumberFormatException nf) {}
  270. return FEATURE + "_" + (featureTitledCount + 1);
  271. }
  272. public static Buffer createFeatureBuffer() {
  273. View view = jEdit.getActiveView();
  274. String parent = null;
  275. if (view != null) {
  276. Buffer buffer = view.getBuffer();
  277. parent = buffer.getDirectory();
  278. }
  279. if (parent == null) {
  280. parent = System.getProperty("user.home");
  281. }
  282. VFS vfs = VFSManager.getVFSForPath(parent);
  283. if ((vfs.getCapabilities() & VFS.WRITE_CAP) == 0) {
  284. // cannot write on that VFS, creating untitled buffer in home directory
  285. parent = System.getProperty("user.home");
  286. }
  287. Buffer buffer = jEdit.openTemporary(view, tempPath(), getNextFeatureTemp(),true, null);
  288. jEdit.commitTemporary(buffer);
  289. return buffer;
  290. }
  291. public static void parseBufferLocalProperties(Buffer buffer) {
  292. try {
  293. Class<?> cl = Class.forName("org.gjt.sp.jedit.buffer.JEditBuffer");
  294. Method method = cl.getDeclaredMethod("parseBufferLocalProperties");
  295. method.setAccessible(true);
  296. method.invoke(buffer);
  297. }
  298. catch (Exception e) {
  299. Log.log(Log.ERROR, PluginUtils.class + ".parseBufferLocalProperties", e);
  300. }
  301. }
  302. @SuppressWarnings("unchecked")
  303. public static EditPane[] getEditPanesFor(final Buffer buffer) {
  304. try {
  305. JEditVisitorAdapter visitor = new JEditVisitorAdapter() {
  306. public Set<EditPane> editPanes = new HashSet<EditPane>();
  307. @Override
  308. public void visit(EditPane editPane) {
  309. if (buffer.equals(editPane.getBuffer()))
  310. editPanes.add(editPane);
  311. }
  312. };
  313. jEdit.visit(visitor);
  314. return ((Set<EditPane>) visitor.getClass().getField("editPanes").get(visitor))
  315. .toArray(new EditPane[0]);
  316. }
  317. catch (Exception e) {
  318. return null;
  319. }
  320. }
  321. public static void setEditPane(EditPane editPane) {
  322. View view = editPane.getView();
  323. try {
  324. Class<?> cl = Class.forName("org.gjt.sp.jedit.View");
  325. Method method = cl.getDeclaredMethod("setEditPane", EditPane.class);
  326. method.setAccessible(true);
  327. method.invoke(view, editPane);
  328. }
  329. catch (Exception e) {
  330. Log.log(Log.ERROR, PluginUtils.class + ".setEditPane", e);
  331. }
  332. }
  333. public static class DoubleFeature
  334. {
  335. private JComponent widget = null;
  336. public void setWidget(JComponent widget) {
  337. this.widget = widget;
  338. }
  339. public JComponent getWidget() {
  340. return widget;
  341. }
  342. public DoubleFeature(TextArea textArea) {
  343. setTextArea(textArea);
  344. }
  345. @Override
  346. public String toString() {
  347. Writer writer = write(new StringWriter(), identity(this));
  348. String t = "";
  349. for (int i = 0; i < textAreas.length; i++) {
  350. t += textAreas[i] == null ? "-" : "+";
  351. }
  352. writer = write_assoc(writer, "textAreas", t, 1);
  353. writer = write_assoc(writer, "widget",
  354. functionValueOrElse("null",
  355. new Function<String>() {
  356. public String apply(Object...params) {
  357. return widget.getClass().getSimpleName();
  358. }
  359. }
  360. ),
  361. 1);
  362. Container container = getFeature().getParent();
  363. if (container instanceof EditPane) {
  364. EditPane editPane = (EditPane)container;
  365. Buffer buffer = editPane.getBuffer();
  366. if (buffer != null)
  367. writer = write_assoc(writer, "buffer", buffer, 1);
  368. }
  369. return writer.toString();
  370. }
  371. protected TextArea[] textAreas = {null,null};
  372. public void setTextArea(TextArea textArea) {
  373. textAreas[0] = textArea;
  374. }
  375. public TextArea getTextArea() {
  376. return textAreas[0];
  377. }
  378. public TextArea getTextArea2() {
  379. return textAreas[1];
  380. }
  381. public Component getFeature() {
  382. return textAreas[0] != null ? textAreas[0] : widget;
  383. }
  384. public void addFeatureTo(Container container) {
  385. addCenterComponent(getFeature(), container);
  386. container.validate();
  387. container.repaint();
  388. }
  389. protected boolean isolate(Object...params) {
  390. Component target = getFeature();
  391. Container container = target.getParent();
  392. if (container == null) {
  393. Log.log(Log.ERROR, getClass().getName() + ".isolate", String.format("%s cannot be isolated", identity(target)));
  394. return false;
  395. }
  396. container.remove(target);
  397. if (params.length > 0)
  398. params[0] = container;
  399. return true;
  400. }
  401. protected void integrate(Container container, boolean featured) {
  402. if (container != null) {
  403. if (featured) {
  404. if (textAreas[0] != null) {
  405. textAreas[1] = textAreas[0];
  406. setTextArea(null);
  407. }
  408. }
  409. else {
  410. if (textAreas[1] != null) {
  411. setTextArea(textAreas[1]);
  412. textAreas[1] = null;
  413. }
  414. }
  415. addFeatureTo(container);
  416. container = null;
  417. }
  418. }
  419. public void toggle(boolean featured, Job<Container> inIsolation, Object...args) {
  420. Object[] params = {null};
  421. if (isolate(params)) {
  422. Container container = (Container) params[0];
  423. if (inIsolation != null)
  424. try {
  425. inIsolation.perform(container, args);
  426. } catch (Exception e) {
  427. Log.log(Log.ERROR, getClass().getName() + ".toggle", e);
  428. }
  429. integrate(container, featured);
  430. }
  431. }
  432. public static final String FOCUS = "focus";
  433. public static final String REQUEST = "request";
  434. public boolean focused = false;
  435. public static Component[] focusRequestComponents(Container container) {
  436. final Component[] focused = findComponents(container, new Predicate<Component>() {
  437. public boolean apply(Component c) {
  438. String name = stringValueOf(c.getName());
  439. return check(name, Constraint.AMONG, DoubleFeature.FOCUS) ||
  440. check(name, Constraint.AMONG, DoubleFeature.REQUEST);
  441. }
  442. });
  443. no_println("focusRequest", identity(asList(focused).toArray()));
  444. return focused;
  445. }
  446. public void requestFocus() {
  447. TextArea textArea = getTextArea();
  448. if (textArea != null)
  449. textArea.requestFocus();
  450. else if (widget != null) {
  451. Component component = findFirstComponent(widget, FOCUS, Constraint.AMONG);
  452. if (component != null) {
  453. component.requestFocusInWindow();
  454. diag_println(DIAG_OFF, "focus",
  455. identity(component),
  456. identity(SwingUtilities.getAncestorOfClass(EditPane.class, component)));
  457. }
  458. }
  459. }
  460. }
  461. }