Skip to main content
summaryrefslogtreecommitdiffstats
blob: 89b1c0e9a6c184923e599d345e91b87104c5f588 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/*******************************************************************************
 * Copyright (c) 2007 Pascal Essiembre.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Pascal Essiembre - initial API and implementation
 ******************************************************************************/
package org.eclipse.babel.editor.plugin;

import java.io.IOException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.Stack;

import org.eclipse.babel.core.message.internal.AbstractIFileChangeListener;
import org.eclipse.babel.core.message.internal.AbstractIFileChangeListener.IFileChangeListenerRegistry;
import org.eclipse.babel.editor.builder.ToggleNatureAction;
import org.eclipse.babel.editor.preferences.MsgEditorPreferences;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.pde.nls.internal.ui.model.ResourceBundleModel;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

/**
 * The activator class controls the plug-in life cycle
 * 
 * @author Pascal Essiembre (pascal@essiembre.com)
 */
public class MessagesEditorPlugin extends AbstractUIPlugin implements
        IFileChangeListenerRegistry {

    // TODO move somewhere more appropriate
    public static final String MARKER_TYPE = "org.eclipse.babel.editor.nlsproblem"; //$NON-NLS-1$

    // The plug-in ID
    public static final String PLUGIN_ID = "org.eclipse.babel.editor";

    // The shared instance
    private static MessagesEditorPlugin plugin;

    // Resource bundle.
    // TODO Use Eclipse MessagesBundle instead.
    private ResourceBundle resourceBundle;

    // The resource change litener for the entire plugin.
    // objects interested in changes in the workspace resources must
    // subscribe to this listener by calling subscribe/unsubscribe on the
    // plugin.
    private IResourceChangeListener resourceChangeListener;

    // The map of resource change subscribers.
    // The key is the full path of the resource listened. The value as set of
    // SimpleResourceChangeListners
    // private Map<String,Set<SimpleResourceChangeListners>>
    // resourceChangeSubscribers;
    private Map<String, Set<AbstractIFileChangeListener>> resourceChangeSubscribers;

    private ResourceBundleModel model;

    /**
     * The constructor
     */
    public MessagesEditorPlugin() {
        resourceChangeSubscribers = new HashMap<String, Set<AbstractIFileChangeListener>>();
    }

    private static class UndoKeyListener implements Listener {

        public void handleEvent(Event event) {
            Control focusControl = event.display.getFocusControl();
            if (event.stateMask == SWT.CONTROL && focusControl instanceof Text) {

                Text txt = (Text) focusControl;
                String actText = txt.getText();
                Stack<String> undoStack = (Stack<String>) txt.getData("UNDO");
                Stack<String> redoStack = (Stack<String>) txt.getData("REDO");

                if (event.keyCode == 'z' && undoStack != null
                        && redoStack != null) { // Undo
                    event.doit = false;

                    if (undoStack.size() > 0) {
                        String peek = undoStack.peek();
                        if (actText != null && !txt.getText().equals(peek)) {
                            String pop = undoStack.pop();
                            txt.setText(pop);
                            txt.setSelection(pop.length());
                            redoStack.push(actText);
                        }
                    }
                } else if (event.keyCode == 'y' && undoStack != null
                        && redoStack != null) { // Redo

                    event.doit = false;

                    if (redoStack.size() > 0) {
                        String peek = redoStack.peek();

                        if (actText != null && !txt.getText().equals(peek)) {
                            String pop = redoStack.pop();
                            txt.setText(pop);
                            txt.setSelection(pop.length());
                            undoStack.push(actText);
                        }
                    }
                }
            }
        }

    }

    /**
     * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
     */
    public void start(BundleContext context) throws Exception {
        super.start(context);
        plugin = this;

        // make sure the rbe nature and builder are set on java projects
        // if that is what the users prefers.
        if (MsgEditorPreferences.getInstance().isBuilderSetupAutomatically()) {
            ToggleNatureAction.addOrRemoveNatureOnAllJavaProjects(true);
        }

        // TODO replace deprecated
        try {
            URL messagesUrl = FileLocator.find(getBundle(), new Path(
                    "$nl$/messages.properties"), null);//$NON-NLS-1$
            if (messagesUrl != null) {
                resourceBundle = new PropertyResourceBundle(
                        messagesUrl.openStream());
            }
        } catch (IOException x) {
            resourceBundle = null;
        }

        // the unique file change listener
        resourceChangeListener = new IResourceChangeListener() {
            public void resourceChanged(IResourceChangeEvent event) {
                IResource resource = event.getResource();
                if (resource != null) {
                    String fullpath = resource.getFullPath().toString();
                    Set<AbstractIFileChangeListener> listeners = resourceChangeSubscribers
                            .get(fullpath);
                    if (listeners != null) {
                        AbstractIFileChangeListener[] larray = listeners
                                .toArray(new AbstractIFileChangeListener[0]);// avoid
                                                                             // concurrency
                                                                             // issues.
                                                                             // kindof.
                        for (int i = 0; i < larray.length; i++) {
                            larray[i].listenedFileChanged(event);
                        }
                    }
                }
            }
        };
        ResourcesPlugin.getWorkspace().addResourceChangeListener(
                resourceChangeListener);
        try {
        Display.getDefault().asyncExec(new Runnable() {

            public void run() {
                    Display.getDefault().addFilter(SWT.KeyUp,
                            new UndoKeyListener());

            }
        });
        } catch (NullPointerException e) {
            // TODO [RAP] Non UI-Thread, no default display available, in RAP
            // multiple clients and displays
        }
    }

    /**
     * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
     */
    public void stop(BundleContext context) throws Exception {
        plugin = null;
        ResourcesPlugin.getWorkspace().removeResourceChangeListener(
                resourceChangeListener);
        super.stop(context);
    }

    /**
     * @param rcl
     *            Adds a subscriber to a resource change event.
     */
    public void subscribe(AbstractIFileChangeListener fileChangeListener) {
        synchronized (resourceChangeListener) {
            String channel = fileChangeListener.getListenedFileFullPath();
            Set<AbstractIFileChangeListener> channelListeners = resourceChangeSubscribers
                    .get(channel);
            if (channelListeners == null) {
                channelListeners = new HashSet<AbstractIFileChangeListener>();
                resourceChangeSubscribers.put(channel, channelListeners);
            }
            channelListeners.add(fileChangeListener);
        }
    }

    /**
     * @param rcl
     *            Removes a subscriber to a resource change event.
     */
    public void unsubscribe(AbstractIFileChangeListener fileChangeListener) {
        synchronized (resourceChangeListener) {
            String channel = fileChangeListener.getListenedFileFullPath();
            Set<AbstractIFileChangeListener> channelListeners = resourceChangeSubscribers
                    .get(channel);
            if (channelListeners != null
                    && channelListeners.remove(fileChangeListener)
                    && channelListeners.isEmpty()) {
                // nobody left listening to this file.
                resourceChangeSubscribers.remove(channel);
            }
        }
    }

    /**
     * Returns the shared instance
     * 
     * @return the shared instance
     */
    public static MessagesEditorPlugin getDefault() {
        return plugin;
    }

    // --------------------------------------------------------------------------
    // TODO Better way/location for these methods?

    /**
     * Returns the string from the plugin's resource bundle, or 'key' if not
     * found.
     * 
     * @param key
     *            the key for which to fetch a localized text
     * @return localized string corresponding to key
     */
    public static String getString(String key) {
        ResourceBundle bundle = MessagesEditorPlugin.getDefault()
                .getResourceBundle();
        try {
            return (bundle != null) ? bundle.getString(key) : key;
        } catch (MissingResourceException e) {
            return key;
        }
    }

    /**
     * Returns the string from the plugin's resource bundle, or 'key' if not
     * found.
     * 
     * @param key
     *            the key for which to fetch a localized text
     * @param arg1
     *            runtime argument to replace in key value
     * @return localized string corresponding to key
     */
    public static String getString(String key, String arg1) {
        return MessageFormat.format(getString(key), new Object[] { arg1 });
    }

    /**
     * Returns the string from the plugin's resource bundle, or 'key' if not
     * found.
     * 
     * @param key
     *            the key for which to fetch a localized text
     * @param arg1
     *            runtime first argument to replace in key value
     * @param arg2
     *            runtime second argument to replace in key value
     * @return localized string corresponding to key
     */
    public static String getString(String key, String arg1, String arg2) {
        return MessageFormat
                .format(getString(key), new Object[] { arg1, arg2 });
    }

    /**
     * Returns the string from the plugin's resource bundle, or 'key' if not
     * found.
     * 
     * @param key
     *            the key for which to fetch a localized text
     * @param arg1
     *            runtime argument to replace in key value
     * @param arg2
     *            runtime second argument to replace in key value
     * @param arg3
     *            runtime third argument to replace in key value
     * @return localized string corresponding to key
     */
    public static String getString(String key, String arg1, String arg2,
            String arg3) {
        return MessageFormat.format(getString(key), new Object[] { arg1, arg2,
                arg3 });
    }

    /**
     * Returns the plugin's resource bundle.
     * 
     * @return resource bundle
     */
    protected ResourceBundle getResourceBundle() {
        return resourceBundle;
    }

    // Stefan's activator methods:

    /**
     * Returns an image descriptor for the given icon filename.
     * 
     * @param filename
     *            the icon filename relative to the icons path
     * @return the image descriptor
     */
    public static ImageDescriptor getImageDescriptor(String filename) {
        String iconPath = "icons/"; //$NON-NLS-1$
        return imageDescriptorFromPlugin(PLUGIN_ID, iconPath + filename);
    }

    public static ResourceBundleModel getModel(IProgressMonitor monitor) {
        if (plugin.model == null) {
            plugin.model = new ResourceBundleModel(monitor);
        }
        return plugin.model;
    }

    public static void disposeModel() {
        if (plugin != null) {
            plugin.model = null;
        }
    }

    // Logging

    /**
     * Adds the given exception to the log.
     * 
     * @param e
     *            the exception to log
     * @return the logged status
     */
    public static IStatus log(Throwable e) {
        return log(new Status(IStatus.ERROR, PLUGIN_ID, 0, "Internal error.", e));
    }

    /**
     * Adds the given exception to the log.
     * 
     * @param exception
     *            the exception to log
     * @return the logged status
     */
    public static IStatus log(String message, Throwable exception) {
        return log(new Status(IStatus.ERROR, PLUGIN_ID, -1, message, exception));
    }

    /**
     * Adds the given <code>IStatus</code> to the log.
     * 
     * @param status
     *            the status to log
     * @return the logged status
     */
    public static IStatus log(IStatus status) {
        getDefault().getLog().log(status);
        return status;
    }

}

Back to the top