41afec531d5b5394c5aaabb1735c98fcc54557ea
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.wiki / src / net / sourceforge / phpeclipse / wiki / editor / WikiEditorPlugin.java
1 package net.sourceforge.phpeclipse.wiki.editor;
2
3 import java.io.IOException;
4 import java.lang.reflect.InvocationTargetException;
5 import java.lang.reflect.Method;
6 import java.net.MalformedURLException;
7 import java.net.URL;
8 import java.sql.SQLException;
9 import java.text.MessageFormat;
10 import java.util.ArrayList;
11 import java.util.Hashtable;
12 import java.util.List;
13 import java.util.MissingResourceException;
14 import java.util.ResourceBundle;
15
16 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.config.IWikipedia;
17 import net.sourceforge.phpeclipse.wiki.internal.ConfigurationManager;
18 import net.sourceforge.phpeclipse.wiki.internal.IConfigurationWorkingCopy;
19 import net.sourceforge.phpeclipse.wiki.sql.WikipediaDB;
20
21 import org.eclipse.core.runtime.CoreException;
22 import org.eclipse.core.runtime.IExtension;
23 import org.eclipse.core.runtime.IPluginDescriptor;
24 import org.eclipse.core.runtime.IStatus;
25 import org.eclipse.core.runtime.Platform;
26 import org.eclipse.core.runtime.Status;
27 import org.eclipse.jface.dialogs.MessageDialog;
28 import org.eclipse.jface.preference.IPreferenceStore;
29 import org.eclipse.jface.resource.ImageDescriptor;
30 import org.eclipse.jface.text.templates.ContextTypeRegistry;
31 import org.eclipse.jface.text.templates.persistence.TemplateStore;
32 import org.eclipse.swt.graphics.Image;
33 import org.eclipse.swt.widgets.Display;
34 import org.eclipse.swt.widgets.Shell;
35 import org.eclipse.ui.IWorkbenchPage;
36 import org.eclipse.ui.IWorkbenchWindow;
37 import org.eclipse.ui.PlatformUI;
38 import org.eclipse.ui.editors.text.templates.ContributionContextTypeRegistry;
39 import org.eclipse.ui.editors.text.templates.ContributionTemplateStore;
40 import org.eclipse.ui.plugin.AbstractUIPlugin;
41
42 public class WikiEditorPlugin extends AbstractUIPlugin {
43
44   private static WikiEditorPlugin fgPlugin;
45
46   public static final String HTTP_QUERY = "HTTP Query";
47
48   //  public static final String WIKIPEDIA_GET_TEXT = "Load WikipediaEN";
49   //
50   //  public static final String WIKIPEDIA_SET_TEXT = "Store WikipediaEN";
51   public static final String WIKIPEDIA_SQL = "Wikipedia SQL access";
52
53   public static final String BLOG_A_WIKI = "Blog as Wiki Text";
54
55   public static final String BLOG_A_HTML = "Blog as HTML Text";
56
57   public static final String[] PREDEFINED_TYPES = { HTTP_QUERY, WIKIPEDIA_SQL, BLOG_A_WIKI, BLOG_A_HTML };
58
59   public static final String[] PREDEFINED_WIKIS = {
60       "WikibooksDE",
61       "WikibooksEN",
62       "WikinewsDE",
63       "WikinewsEN",
64       "WikipediaAR",
65       "WikipediaCA",
66       "WikipediaDE",
67       "WikipediaEN",
68       "WikipediaEO",
69       "WikipediaES",
70       "WikipediaET",
71       "WikipediaFI",
72       "WikipediaFR" };
73
74   public static final String PREFIX_LOAD = "Load ";
75
76   public static final String PREFIX_STORE = "Store ";
77
78   public static final ArrayList CONFIGURATION_TYPES = new ArrayList();
79
80   //image paths
81   public static final String ICON_PATH = "icons/full/"; //$NON-NLS-1$
82
83   public final static String PLUGIN_ID = "net.sourceforge.phpeclipse.wiki";
84
85   public final static String HTML_OUTPUT_PATH = "__static_wiki_folder";
86
87   public final static String WIKI_TEXTS_BASE_PATH = "__wiki_texts_base_path";
88
89   public final static String LOCAL_TEMPLATE_FILE_NAME = "__local_template_file_name";
90
91   public final static String EXPORT_TEMPLATE_FILE_NAME = "__export_template_file_name";
92
93   public final static String LOCAL_CSS_URL = "__local_css_url";
94
95   public final static String EXPORT_CSS_URL = "__export_css_url";
96
97   public final static String PREF_STRING_CONFIGURATIONS = "__configurations2";
98
99   public final static String CONFIG_MEMENTO = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
100       + "<configurations>"
101       + "<config name=\"Google Search\" type-id=\"HTTP Query\" url=\"http://www.google.com/search?q=$text.selection\"/>"
102       + "<config name=\"Koders.com Search\" type-id=\"HTTP Query\" url=\"http://koders.com/?s=$text.selection\"/>"
103       + "<config name=\"Leo.org Translation\" type-id=\"HTTP Query\" url=\"http://dict.leo.org/?search=$text.selection\"/>"
104       + "<config name=\"WikipediaEN Dwonload\" type-id=\"Load WikipediaEN\" url=\"http://en.wikipedia.org/w/index.php?title=$text.wikiname&amp;action=raw\"/>"
105       + "<config name=\"WikibooksEN Download\" type-id=\"Load WikibooksEN\" url=\"http://en.wikibooks.org/w/index.php?title=$text.wikiname&amp;action=raw\"/>"
106       + "<config name=\"WikipediaEN Upload\" type-id=\"Store WikipediaEN\" url=\"http://en.wikipedia.org/w/index.php\"/>"
107       + "<config name=\"WikibooksEN Upload\" type-id=\"Store WikibooksEN\" url=\"http://en.wikibooks.org/w/index.php\"/>"
108       + "<config name=\"Wikipedia-SQL\" type-id=\"Wikipedia SQL access\" user=\"root\" url=\"jdbc:mysql://localhost/wikidb\"/>"
109       + "</configurations>";
110
111   public static WikipediaDB fWikiDB = null;
112
113   private static ConfigurationManager manager;
114
115   //
116   //  public static final String IMG_MONITOR_ON = "monitorOn";
117   //
118   //  public static final String IMG_MONITOR_OFF = "monitorOff";
119
120   /**
121    * Creates an image and places it in the image registry.
122    * 
123    * @param id
124    *          the identifier for the image
125    * @param baseURL
126    *          the base URL for the image
127    */
128   protected static void createImageDescriptor(WikiEditorPlugin plugin, String id, URL baseURL) {
129     // Delegate to the plugin instance to avoid concurrent class loading problems
130     plugin.privateCreateImageDescriptor(id, baseURL);
131   }
132
133   public static WikiEditorPlugin getDefault() {
134     return fgPlugin;
135   }
136
137   /**
138    * Returns the image descriptor for the given image ID. Returns null if there is no such image.
139    * 
140    * @param id
141    *          the identifier for the image to retrieve
142    * @return the image associated with the given ID
143    */
144   public static ImageDescriptor getImageDescriptor(String id) {
145     // Delegate to the plugin instance to avoid concurrent class loading problems
146     return getDefault().privateGetImageDescriptor(id);
147   }
148
149   /**
150    * Convenience method to get an image descriptor for an extension
151    * 
152    * @param extension
153    *          the extension declaring the image
154    * @param subdirectoryAndFilename
155    *          the path to the image
156    * @return the image
157    */
158   public static ImageDescriptor getImageDescriptorFromExtension(IExtension extension, String subdirectoryAndFilename) {
159     IPluginDescriptor pluginDescriptor = extension.getDeclaringPluginDescriptor();
160     URL path = pluginDescriptor.getInstallURL();
161     URL fullPathString = null;
162     try {
163       fullPathString = new URL(path, subdirectoryAndFilename);
164       return ImageDescriptor.createFromURL(fullPathString);
165     } catch (MalformedURLException e) {
166     }
167     return null;
168   }
169
170   public static String getResourceString(String key) {
171     ResourceBundle bundle = WikiEditorPlugin.getDefault().getResourceBundle();
172     try {
173       return (bundle != null) ? bundle.getString(key) : key;
174     } catch (MissingResourceException e) {
175       return key;
176     }
177   }
178
179   /**
180    * Returns the standard display to be used. The method first checks, if the thread calling this method has an associated display.
181    * If so, this display is returned. Otherwise the method returns the default display.
182    */
183   public static Display getStandardDisplay() {
184     Display display = Display.getCurrent();
185     if (display == null) {
186       display = Display.getDefault();
187     }
188     return display;
189   }
190
191   private ContributionContextTypeRegistry fContextTypeRegistry;
192
193   private ResourceBundle fResourceBundle;
194
195   private ContributionTemplateStore fTemplateStore;
196
197   private Hashtable imageDescriptors = new Hashtable(20);
198
199   public WikiEditorPlugin(IPluginDescriptor descriptor) {
200     super(descriptor);
201     initializeImages();
202     fgPlugin = this;
203     for (int i = 0; i < PREDEFINED_TYPES.length; i++) {
204       CONFIGURATION_TYPES.add(PREDEFINED_TYPES[i]);
205     }
206
207     for (int i = 0; i < PREDEFINED_WIKIS.length; i++) {
208       CONFIGURATION_TYPES.add(PREFIX_LOAD + PREDEFINED_WIKIS[i]);
209     }
210     for (int i = 0; i < PREDEFINED_WIKIS.length; i++) {
211       CONFIGURATION_TYPES.add(PREFIX_STORE + PREDEFINED_WIKIS[i]);
212     }
213     manager = ConfigurationManager.getInstance();
214     try {
215       fResourceBundle = ResourceBundle.getBundle("net.sourceforge.phpeclipse.wiki.editor.WikiEditorMessages");
216     } catch (MissingResourceException x) {
217       fResourceBundle = null;
218     }
219   }
220
221   /**
222    * Creates an image and places it in the image registry.
223    */
224   protected void createImageDescriptor(String id, URL baseURL) {
225     URL url = null;
226     try {
227       url = new URL(baseURL, ICON_PATH + id);
228     } catch (MalformedURLException e) {
229     }
230     ImageDescriptor desc = ImageDescriptor.createFromURL(url);
231     imageDescriptors.put(id, desc);
232   }
233
234   public IWorkbenchPage getActivePage() {
235     IWorkbenchWindow window = getWorkbench().getActiveWorkbenchWindow();
236     if (window != null)
237       return window.getActivePage();
238     return null;
239   }
240
241   public ContextTypeRegistry getContextTypeRegistry() {
242     if (fContextTypeRegistry == null) {
243       fContextTypeRegistry = new ContributionContextTypeRegistry();
244       fContextTypeRegistry.addContextType("net.sourceforge.phpeclipse.wiki.editor.templates");
245     }
246     return fContextTypeRegistry;
247   }
248
249   public Image getImage(String key) {
250     Image image = getImageRegistry().get(key);
251     if (image == null) {
252       ImageDescriptor d = getImageDescriptor(key);
253       image = d.createImage();
254       getImageRegistry().put(key, image);
255     }
256     return image;
257   }
258
259   public ResourceBundle getResourceBundle() {
260     return fResourceBundle;
261   }
262
263   public TemplateStore getTemplateStore() {
264     if (fTemplateStore == null) {
265       fTemplateStore = new ContributionTemplateStore(getContextTypeRegistry(), getDefault().getPreferenceStore(), "templates");
266       try {
267         fTemplateStore.load();
268       } catch (IOException e) {
269         e.printStackTrace();
270       }
271     }
272
273     return fTemplateStore;
274   }
275
276   /*
277    * (non-Javadoc)
278    * 
279    * @see org.eclipse.ui.plugin.AbstractUIPlugin#initializeDefaultPreferences(org.eclipse.jface.preference.IPreferenceStore)
280    */
281   protected void initializeDefaultPreferences(IPreferenceStore store) {
282     store.setDefault(PREF_STRING_CONFIGURATIONS, CONFIG_MEMENTO);
283   }
284
285   /*
286    * Initializes the table of images used in this plugin. The plugin is provided because this method is called before the plugin
287    * staic variable has been set. See the comment on the getPlugin() method for a description of why this is required.
288    */
289   private void initializeImages() {
290     URL baseURL = getDescriptor().getInstallURL();
291
292     //  special
293     createImageDescriptor("glyphs/glyph1.gif", baseURL); //$NON-NLS-1$
294     createImageDescriptor("glyphs/glyph2.gif", baseURL); //$NON-NLS-1$
295     createImageDescriptor("glyphs/glyph3.gif", baseURL); //$NON-NLS-1$
296     createImageDescriptor("glyphs/glyph4.gif", baseURL); //$NON-NLS-1$
297     createImageDescriptor("glyphs/glyph5.gif", baseURL); //$NON-NLS-1$
298     createImageDescriptor("glyphs/glyph6.gif", baseURL); //$NON-NLS-1$
299     createImageDescriptor("glyphs/glyph7.gif", baseURL); //$NON-NLS-1$
300     createImageDescriptor("glyphs/glyph8.gif", baseURL); //$NON-NLS-1$
301
302   }
303
304   public void log(String message) {
305     getDefault().getLog().log(new Status(IStatus.OK, PLUGIN_ID, IStatus.OK, message, null));
306   }
307
308   public void log(String message, Exception e) {
309     getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, "Caught exception", e));
310   }
311
312   public void logAndReport(String title, String message, Exception e) {
313     log(message, e);
314     reportError(title, message);
315   }
316
317   private void privateCreateImageDescriptor(String id, URL baseURL) {
318     URL url = null;
319     try {
320       url = new URL(baseURL, ICON_PATH + id);
321     } catch (MalformedURLException e) {
322     }
323     ImageDescriptor desc = ImageDescriptor.createFromURL(url);
324     imageDescriptors.put(id, desc);
325   }
326
327   private ImageDescriptor privateGetImageDescriptor(String id) {
328     if (!imageDescriptors.containsKey(id)) {
329       URL baseURL = WikiEditorPlugin.getDefault().getDescriptor().getInstallURL();
330       createImageDescriptor(getDefault(), id, baseURL);
331     }
332     return (ImageDescriptor) imageDescriptors.get(id);
333   }
334
335   public void reportError(String title, String message) {
336     try {
337       Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
338       MessageDialog.openError(shell, title, message);
339     } catch (RuntimeException e) {
340       log(e.getLocalizedMessage(), e);
341     }
342   }
343
344   public void startup() throws CoreException {
345     super.startup();
346   }
347
348   /**
349    * Returns the translated String found with the given key.
350    * 
351    * @return java.lang.String
352    * @param key
353    *          java.lang.String
354    */
355   public static String getResource(String key) {
356     try {
357       return Platform.getResourceString(getDefault().getBundle(), key);
358     } catch (Exception e) {
359       return key;
360     }
361   }
362
363   /**
364    * Returns the translated String found with the given key, and formatted with the given object.
365    * 
366    * @param key
367    *          java.lang.String
368    * @param obj
369    *          java.lang.Object[]
370    * @return java.lang.String
371    */
372   public static String getResource(String key, Object[] obj) {
373     try {
374       return MessageFormat.format(getResource(key), obj);
375     } catch (Exception e) {
376       return key;
377     }
378   }
379
380   /**
381    * Returns the translated String found with the given key, and formatted with the given object.
382    * 
383    * @param key
384    *          java.lang.String
385    * @param s
386    *          java.lang.String
387    * @return java.lang.String
388    */
389   public static String getResource(String key, String s) {
390     try {
391       return MessageFormat.format(getResource(key), new String[] { s });
392     } catch (Exception e) {
393       return key;
394     }
395   }
396
397   /**
398    * Return a list of all the existing configurations.
399    * 
400    * @return java.util.List
401    */
402   public static List getConfigurations() {
403     return manager.getConfigurations();
404   }
405
406   /**
407    * Create a new monitor.
408    * 
409    * @return working copy
410    */
411   public static IConfigurationWorkingCopy createConfiguration() {
412     return manager.createConfiguration();
413   }
414
415   public static ArrayList getTypes() {
416     return CONFIGURATION_TYPES;
417   }
418
419   public static void addType(String type) {
420     CONFIGURATION_TYPES.add(type);
421   }
422
423   /*
424    * (non-Javadoc)
425    * 
426    * @see org.eclipse.core.runtime.Plugin#shutdown()
427    */
428   public void shutdown() throws CoreException {
429     if (fWikiDB != null) {
430       try {
431         fWikiDB.shutdown();
432       } catch (SQLException e) {
433       }
434     }
435     super.shutdown();
436   }
437
438   public static void log(int severity, String message) {
439     Status status = new Status(severity, PLUGIN_ID, IStatus.OK, message, null);
440     log(status);
441   }
442
443   public static void log(IStatus status) {
444     getDefault().getLog().log(status);
445   }
446
447   public static void log(Throwable e) {
448     log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.ERROR, "PHPeclipsePlugin.internalErrorOccurred", e)); //$NON-NLS-1$
449   }
450
451   /**
452    * Get a IWikpedia singleton instance through reflection (i.e. Method#invoke() )
453    * 
454    * @param wikiLocale
455    * @return
456    * @throws NoSuchMethodException
457    * @throws IllegalAccessException
458    * @throws ClassNotFoundException
459    * @throws InvocationTargetException
460    */
461   public static IWikipedia getWikiInstance(String wikiLocale) throws NoSuchMethodException, IllegalAccessException,
462       ClassNotFoundException, InvocationTargetException {
463     String className = "net.sourceforge.phpeclipse.wiki.actions.mediawiki.config." + wikiLocale;
464     Class cls = Class.forName(className);
465     Method method = cls.getMethod("getInstance", new Class[0]);
466     return (IWikipedia) method.invoke(null, new Object[0]);
467   }
468
469   // test code
470   //  public static void main(String[] args) {
471   //    try {
472   //      getWikiInstance("WikipediaEN");
473   //    } catch (NoSuchMethodException e) {
474   //      // TODO Auto-generated catch block
475   //      e.printStackTrace();
476   //    } catch (IllegalAccessException e) {
477   //      // TODO Auto-generated catch block
478   //      e.printStackTrace();
479   //    } catch (ClassNotFoundException e) {
480   //      // TODO Auto-generated catch block
481   //      e.printStackTrace();
482   //    } catch (InvocationTargetException e) {
483   //      // TODO Auto-generated catch block
484   //      e.printStackTrace();
485   //    }
486   //  }
487
488 }