Statistics
| Revision:

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

History | View | Annotate | Download (15.8 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 static IExtension exclusiveUIExtension = null;
93

    
94
        private PluginClassLoader loader;
95

    
96
        private XMLEntity persistentXML;
97

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

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

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

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

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

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

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

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

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

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

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

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

    
235
        }
236

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

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

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

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

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

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

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

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

    
342
                frame.addPopupMenuListener(name, c, listener, loader);
343
        }
344

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

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

    
368
                return t;
369
        }
370

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

    
391
                Component mainFrame = (Component) PluginServices.getMainFrame();
392

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

    
410
                worker.start();
411

    
412
        }
413

    
414
        public static void closeApplication() {
415
                Launcher.closeApplication();
416
        }
417

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

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

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

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

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

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

    
507
        public static void setArguments(String[] arguments) {
508
                PluginServices.arguments = arguments;
509
        }
510
        
511
        /**
512
         * Return the value of a command line named argument.
513
         *<br>
514
         *<br>
515
         * The argument format is:
516
         *<br>
517
         * -{argumentName}={argumentValue}
518
         *<br>
519
         *<br>
520
         *example:
521
         * <br>
522
         * ' -language=en '
523
         * @return String value
524
         */        
525
        public static String getArgumentByName(String name) {                
526
        for (int i=2; i < PluginServices.arguments.length; i++)
527
        {
528
                int index = PluginServices.arguments[i].indexOf(name +"=");
529
                if (index != -1)
530
                        return PluginServices.arguments[i].substring(index+name.length()+1);
531
        }
532
        return null;
533
        }
534

    
535
        public static Logger getLogger() {
536
                return logger;
537
        }
538

    
539
        public static IAuthentication getAuthentication() {
540
                return authentication;
541
        }
542

    
543
        public static void setAuthentication(IAuthentication authen) {
544
                authentication = authen;
545
        }
546
        public static DlgPreferences getDlgPreferences() {
547
                return DlgPreferences.getInstance();
548
        }
549

    
550
        public static void putInClipboard(String data) {
551
                StringSelection ss = new StringSelection(data);
552

    
553
                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,ss);
554
        }
555

    
556
        public static String getFromClipboard() {
557

    
558
                 try {
559
                        return (String)Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null).getTransferData(DataFlavor.stringFlavor);
560
                } catch (UnsupportedFlavorException e) {
561
                        return null;
562
                } catch (IOException e) {
563
                        // TODO Auto-generated catch block
564
                        return null;
565
                }
566
        }
567
        
568
        
569
        /**
570
         * Gets the extesion that have to take the control
571
         *  of the state of action controls of the UI of all extensions.
572
         * <br>
573
         * <br>
574
         * -exclusiveUI={pathToExtensionClass}
575
         * <br>
576
         *  @see com.iver.andami.Launcher#initializeExclusiveUIExtension()
577
         *  @see com.iver.andami.plugins.IExtension#isEnabled(IExtension extension)
578
         *  @see com.iver.andami.plugins.IExtension#isVisible(IExtension extension)
579
         */
580
        
581
        public static IExtension getExclusiveUIExtension() {
582
                return PluginServices.exclusiveUIExtension;
583
        }
584
        
585
        public static void setExclusiveUIExtension(IExtension extension) {
586
                PluginServices.exclusiveUIExtension = extension;
587
        }
588

    
589
}