Statistics
| Revision:

svn-gvsig-desktop / tags / v1_0_RELEASE / frameworks / _fwAndami / src / com / iver / andami / PluginServices.java @ 9167

History | View | Annotate | Download (14.6 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.andami;
42

    
43
import java.awt.Component;
44
import java.awt.Frame;
45
import java.awt.KeyEventDispatcher;
46
import java.awt.Toolkit;
47
import java.awt.datatransfer.DataFlavor;
48
import java.awt.datatransfer.StringSelection;
49
import java.awt.datatransfer.UnsupportedFlavorException;
50
import java.awt.event.ActionListener;
51
import java.io.File;
52
import java.io.IOException;
53
import java.lang.reflect.InvocationTargetException;
54
import java.util.HashMap;
55
import java.util.Iterator;
56

    
57
import javax.swing.KeyStroke;
58
import javax.swing.SwingUtilities;
59
import javax.swing.Timer;
60

    
61
import org.apache.log4j.Logger;
62

    
63
import com.iver.andami.authentication.IAuthentication;
64
import com.iver.andami.messages.Messages;
65
import com.iver.andami.messages.NotificationManager;
66
import com.iver.andami.plugins.ExtensionDecorator;
67
import com.iver.andami.plugins.IExtension;
68
import com.iver.andami.plugins.PluginClassLoader;
69
import com.iver.andami.preferences.DlgPreferences;
70
import com.iver.andami.ui.mdiFrame.MDIFrame;
71
import com.iver.andami.ui.mdiFrame.MainFrame;
72
import com.iver.andami.ui.mdiManager.MDIManager;
73
import com.iver.utiles.XMLEntity;
74
import com.iver.utiles.swing.threads.IMonitorableTask;
75
import com.iver.utiles.swing.threads.IProgressMonitorIF;
76
import com.iver.utiles.swing.threads.TaskMonitorTimerListener;
77
import com.iver.utiles.swing.threads.UndefinedProgressMonitor;
78

    
79
/**
80
 * Clase que proporciona servicios a los plugins.
81
 *
82
 * @author Fernando Gonz?lez Cort?s
83
 */
84
public class PluginServices {
85
        private static Logger logger = Logger.getLogger(PluginServices.class
86
                        .getName());
87

    
88
        private static String[] arguments;
89

    
90
        private static IAuthentication authentication;
91

    
92
        private PluginClassLoader loader;
93

    
94
        private XMLEntity persistentXML;
95

    
96
        /**
97
         * Crea un nuevo PluginServices
98
         *
99
         * @param loader
100
         *            ClassLoader del plugin
101
         */
102
        public PluginServices(PluginClassLoader loader) {
103
                this.loader = loader;
104
        }
105

    
106
        /**
107
         * Devuelve el mensaje en el idioma del locale actual del texto
108
         * correspondiente a la clave que se pasa como par?metro
109
         *
110
         * @param key
111
         *            Clave del texto que se quiere obtener
112
         *
113
         * @return Texto en el idioma que toca o la propia clave si no se encuentra
114
         *         en el fichero
115
         */
116
        public String getText(String key) {
117
                if (key == null) return null;
118
                String translation = org.gvsig.i18n.Messages.getText(key, false);
119
                if (translation != null)
120
                        return translation;
121
                else
122
                {
123
                        logger.warn("Plugin "+getPluginName()+" -- "+org.gvsig.i18n.Messages.getText("No_se_encontro_la_traduccion_para", false)+ " " + key);
124
                        return key;
125
                }
126
        }
127

    
128
        /**
129
         * Obtiene el classloader del plugin
130
         *
131
         * @return Returns the loader.
132
         */
133
        public PluginClassLoader getClassLoader() {
134
                return loader;
135
        }
136

    
137
        /**
138
         * Obtiene el nombre del plugin
139
         *
140
         * @return String
141
         */
142
        String getPluginName() {
143
                return loader.getPluginName();
144
        }
145

    
146
        /**
147
         * Obtienen una referencia al PluginServices del plugin cuyo nombre se pasa
148
         * como par?metro
149
         *
150
         * @param pluginClassInstance
151
         *            Instancia de una clase propia del plugin a cuyos servicios se
152
         *            quiere acceder
153
         *
154
         * @return Objeto PluginServices asociado al plugin
155
         *
156
         * @throws RuntimeException
157
         *             Si el par?metro no es un objeto cargado desde un plugin
158
         */
159
        public static PluginServices getPluginServices(Object pluginClassInstance) {
160
                try {
161
                        PluginClassLoader loader = (PluginClassLoader) pluginClassInstance
162
                                        .getClass().getClassLoader();
163

    
164
                        return Launcher.getPluginServices(loader.getPluginName());
165
                } catch (ClassCastException e) {
166
                        /*
167
                         * throw new RuntimeException( "Parameter is not a plugin class
168
                         * instance");
169
                         */
170
                        return null;
171
                }
172
        }
173

    
174
        /**
175
         * Obtienen una referencia al PluginServices del plugin cuyo nombre se pasa
176
         * como par?metro
177
         *
178
         * @param pluginName
179
         *            Instancia de una clase propia del plugin a cuyos servicios se
180
         *            quiere acceder
181
         *
182
         * @return Objeto PluginServices asociado al plugin
183
         */
184
        public static PluginServices getPluginServices(String pluginName) {
185
                return Launcher.getPluginServices(pluginName);
186
        }
187

    
188
        /**
189
         * Obtiene una referencia al gestor de ventanas
190
         *
191
         * @return MDIManager
192
         */
193
        public static MDIManager getMDIManager() {
194
                return Launcher.getFrame().getMDIManager();
195
        }
196

    
197
        /**
198
         * Obtiene una referencia al marco principal de la aplicaci?n
199
         *
200
         * @return MainFrame
201
         */
202
        public static MainFrame getMainFrame() {
203
                return Launcher.getFrame();
204
        }
205

    
206
        public static void registerKeyStroke(KeyStroke key, KeyEventDispatcher a)
207
        {
208
                GlobalKeyEventDispatcher.getInstance().registerKeyStroke(key, a);
209
        }
210

    
211
        public static void unRegisterKeyStroke(KeyStroke key)
212
        {
213
                GlobalKeyEventDispatcher.getInstance().removeKeyStrokeBinding(key);
214
        }
215

    
216
        /**
217
         * Obtiene una referencia a la instancia de la extensi?n cuya clase se pasa
218
         * como par?metro
219
         *
220
         * @param extensionClass
221
         *            Clase de la extensi?n cuya instancia se quiere obtener
222
         *
223
         * @return Instancia de la extensi?n o null en caso de que no haya una
224
         *         extensi?n con esa clase
225
         */
226
        public static IExtension getExtension(Class extensionClass) {
227
                ExtensionDecorator extAux = (ExtensionDecorator) Launcher
228
                                .getClassesExtensions().get(extensionClass);
229
                return extAux.getExtension();
230
                // return (Extension)
231
                // Launcher.getClassesExtensions().get(extensionClass);
232

    
233
        }
234

    
235
        /**
236
         * Gets a reference to the Extension Decorator with support for several more
237
         * options
238
         *
239
         * @param extensionClass
240
         * @return
241
         */
242
        public static ExtensionDecorator getDecoratedExtension(Class extensionClass) {
243
                return (ExtensionDecorator) Launcher.getClassesExtensions().get(
244
                                extensionClass);
245
        }
246

    
247
        /**
248
         * Returns an array containing references to all the loaded extensions.
249
         * @return ExtensionDecorator[]
250
         */
251
        public static ExtensionDecorator[] getDecoratedExtensions() {
252
                HashMap map = Launcher.getClassesExtensions();
253
                ExtensionDecorator[] extensions = (ExtensionDecorator[]) map.
254
                                values().toArray(new ExtensionDecorator[0]);
255
                return extensions;
256
        }
257

    
258
        /**
259
         * Obtiene un iterador sobre las extensiones
260
         *
261
         * @return Iterator
262
         */
263
        public static Iterator getExtensions() {
264
                return Launcher.getClassesExtensions().values().iterator();
265
        }
266

    
267
        /**
268
         * Obtiene una traducci?n de un plugin
269
         *
270
         * @param pluginObject
271
         *            Objeto cargado desde un plugin
272
         * @param key
273
         *            Nombre de la clave cuyo valor se quiere obtener
274
         *
275
         * @return El valor, si existe. La clave si no existe. Si el objeto que se
276
         *         pasa como par?metro no ha sido cargado desde un plugin se
277
         *         devuelve la clave.
278
         */
279
        public static String getText(Object pluginObject, String key) {
280
                if (key == null) return null;
281
                String translation = org.gvsig.i18n.Messages.getText(key, false);
282
                if (translation != null)
283
                        return translation;
284
                else
285
                {
286
                        logger.warn(org.gvsig.i18n.Messages.getText("No_se_encontro_la_traduccion_para",false) + " "+ key);
287
                        return key;
288
                }
289
        }
290

    
291
        /**
292
         * Establece los datos del plugin que deber?n persistir entre ejecuciones en
293
         * formato xml
294
         *
295
         * @param entity
296
         *            DOCUMENT ME!
297
         */
298
        public void setPersistentXML(XMLEntity entity) {
299
                persistentXML = entity;
300
        }
301

    
302
        /**
303
         * Obtiene un objeto que representa la persistencia del plugin en formato
304
         * xml.
305
         *
306
         * @return Devuelve null hasta que se invoca el m?todo setPersistentXML
307
         */
308
        public XMLEntity getPersistentXML() {
309
                if (persistentXML == null) {
310
                        persistentXML = new XMLEntity();
311
                }
312
                return persistentXML;
313
        }
314

    
315
        /**
316
         * A?ade un listener a un popup menu registrado en el config.xml de alg?n
317
         * plugin
318
         *
319
         * @param name
320
         *            Nombre del men? contextual
321
         * @param c
322
         *            Componente que desplegar? el men? cuando se haga click con el
323
         *            bot?n derecho
324
         * @param listener
325
         *            Listener que se ejecutar? cuando se seleccione cualquier
326
         *            entrada del men?
327
         *
328
         * @throws RuntimeException
329
         *             Si la interfaz no est? preparada todav?a. S?lo puede darse
330
         *             durante el arranque
331
         */
332
        public void addPopupMenuListener(String name, Component c,
333
                        ActionListener listener) {
334
                MDIFrame frame = Launcher.getFrame();
335

    
336
                if (frame == null) {
337
                        throw new RuntimeException("MDIFrame not loaded yet");
338
                }
339

    
340
                frame.addPopupMenuListener(name, c, listener, loader);
341
        }
342

    
343
        /**
344
         * Obtiene una referencia al directorio del plugin
345
         *
346
         * @return File
347
         */
348
        public File getPluginDirectory() {
349
                return new File(Launcher.getPluginsDir() + File.separator
350
                                + getPluginName());
351
        }
352

    
353
        /**
354
         * Ejecuta una tarea en segundo plano, dejando a la interfaz responder pero
355
         * inhibiendo los eventos
356
         *
357
         * @param r
358
         *            Tarea a ejecutar
359
         *
360
         * @return Thread en el que se ejecuta la tarea
361
         */
362
        public static Thread backgroundExecution(Runnable r) {
363
                Thread t = new Thread(new RunnableDecorator(r));
364
                t.start();
365

    
366
                return t;
367
        }
368

    
369
        /**
370
         * Runs a task in background. This task could be monitored and canceled, and
371
         * doesnt inhibed any event.
372
         *
373
         * @param task
374
         *            IMonitorableTask
375
         */
376
        public static void cancelableBackgroundExecution(final IMonitorableTask task) {
377
                final com.iver.utiles.swing.threads.SwingWorker worker = new com.iver.utiles.swing.threads.SwingWorker() {
378
                        public Object construct() {
379
                                try {
380
                                        task.run();
381
                                        return task;
382
                                } catch (Exception e) {
383
                                        NotificationManager.addError(null, e);
384
                                }
385
                                return null;
386
                        }
387
                };
388

    
389
                Component mainFrame = (Component) PluginServices.getMainFrame();
390

    
391
                IProgressMonitorIF progressMonitor = null;
392
                String title = getText(null, "PluginServices.Procesando");
393
                progressMonitor = new UndefinedProgressMonitor((Frame) mainFrame, title);
394
                progressMonitor.setIndeterminated(!task.isDefined());
395
                progressMonitor.setInitialStep(task.getInitialStep());
396
                progressMonitor.setLastStep(task.getFinishStep());
397
                progressMonitor.setCurrentStep(task.getCurrentStep());
398
                progressMonitor.setMainTitleLabel(task.getStatusMessage());
399
                progressMonitor.setNote(task.getNote());
400
                progressMonitor.open();
401
                int delay = 500;
402
                TaskMonitorTimerListener timerListener = new TaskMonitorTimerListener(
403
                                progressMonitor, task);
404
                Timer timer = new Timer(delay, timerListener);
405
                timerListener.setTimer(timer);
406
                timer.start();
407

    
408
                worker.start();
409

    
410
        }
411

    
412
        public static void closeApplication() {
413
                Launcher.closeApplication();
414
        }
415

    
416
        /**
417
         * DOCUMENT ME!
418
         *
419
         * @author Fernando Gonz?lez Cort?s
420
         */
421
        private static class RunnableDecorator implements Runnable {
422
                private Runnable r;
423

    
424
                /**
425
                 * Crea un nuevo RunnableDecorator.
426
                 *
427
                 * @param r
428
                 *            DOCUMENT ME!
429
                 */
430
                public RunnableDecorator(Runnable r) {
431
                        this.r = r;
432
                }
433

    
434
                /**
435
                 * @see java.lang.Runnable#run()
436
                 */
437
                public void run() {
438
                        /*
439
                         * try { SwingUtilities.invokeAndWait(new Runnable() { public void
440
                         * run() { getMDIManager().setWaitCursor(); } }); } catch
441
                         * (InterruptedException e) {
442
                         * NotificationManager.addWarning(Messages.getString("PluginServices.No_se_pudo_poner_el_reloj_de_arena"),
443
                         * e); } catch (InvocationTargetException e) {
444
                         * NotificationManager.addWarning(Messages.getString("PluginServices.No_se_pudo_poner_el_reloj_de_arena"),
445
                         * e); }
446
                         */
447

    
448
                        try {
449
                                SwingUtilities.invokeAndWait(new Runnable() {
450
                                        public void run() {
451
                                                try {
452
                                                        r.run();
453
                                                } catch (RuntimeException e) {
454
                                                        NotificationManager
455
                                                                        .addError(
456
                                                                                        Messages
457
                                                                                                        .getString("PluginServices.Bug_en_el_codigo"),
458
                                                                                        e);
459
                                                } catch (Error e) {
460
                                                        NotificationManager
461
                                                                        .addError(
462
                                                                                        Messages
463
                                                                                                        .getString("PluginServices.Error_grave_de_la_aplicaci?n"),
464
                                                                                        e);
465
                                                }
466
                                        }
467
                                });
468
                        } catch (InterruptedException e) {
469
                                NotificationManager
470
                                                .addWarning(
471
                                                                Messages
472
                                                                                .getString("PluginServices.No_se_pudo_poner_el_reloj_de_arena"),
473
                                                                e);
474
                        } catch (InvocationTargetException e) {
475
                                NotificationManager
476
                                                .addWarning(
477
                                                                Messages
478
                                                                                .getString("PluginServices.No_se_pudo_poner_el_reloj_de_arena"),
479
                                                                e);
480
                        }
481

    
482
                        /*
483
                         * try { SwingUtilities.invokeAndWait(new Runnable() { public void
484
                         * run() { getMDIManager().restoreCursor(); } }); } catch
485
                         * (InterruptedException e) {
486
                         * NotificationManager.addWarning(Messages.getString("PluginServices.No_se_pudo_restaurar_el_cursor_del_raton"),
487
                         * e); } catch (InvocationTargetException e) {
488
                         * NotificationManager.addWarning(Messages.getString("PluginServices.No_se_pudo_restaurar_el_cursor_del_raton"),
489
                         * e); }
490
                         */
491
                }
492
        }
493

    
494
        /**
495
         * Usually appName plugins-directory [locale] [other args]
496
         *
497
         * @return the original arguments that Andami received. (app-name
498
         *         plugins-directory, locale, etc)
499
         */
500
        public static String[] getArguments() {
501
                return arguments;
502
        }
503

    
504
        public static void setArguments(String[] arguments) {
505
                PluginServices.arguments = arguments;
506
        }
507

    
508
        public static Logger getLogger() {
509
                return logger;
510
        }
511

    
512
        public static IAuthentication getAuthentication() {
513
                return authentication;
514
        }
515

    
516
        public static void setAuthentication(IAuthentication authen) {
517
                authentication = authen;
518
        }
519
        public static DlgPreferences getDlgPreferences() {
520
                return DlgPreferences.getInstance();
521
        }
522

    
523
        public static void putInClipboard(String data) {
524
                StringSelection ss = new StringSelection(data);
525

    
526
                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,ss);
527
        }
528

    
529
        public static String getFromClipboard() {
530

    
531
                 try {
532
                        return (String)Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null).getTransferData(DataFlavor.stringFlavor);
533
                } catch (UnsupportedFlavorException e) {
534
                        return null;
535
                } catch (IOException e) {
536
                        // TODO Auto-generated catch block
537
                        return null;
538
                }
539
        }
540

    
541
}