Statistics
| Revision:

svn-gvsig-desktop / trunk / frameworks / _fwAndami / src / com / iver / andami / PluginServices.java @ 2142

History | View | Annotate | Download (9.95 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.event.ActionListener;
45
import java.io.File;
46
import java.lang.reflect.InvocationTargetException;
47
import java.util.Iterator;
48
import java.util.Locale;
49
import java.util.MissingResourceException;
50
import java.util.PropertyResourceBundle;
51
import java.util.ResourceBundle;
52

    
53
import javax.swing.SwingUtilities;
54

    
55
import org.apache.log4j.Logger;
56

    
57
import com.iver.andami.messages.Messages;
58
import com.iver.andami.messages.NotificationManager;
59
import com.iver.andami.plugins.Extension;
60
import com.iver.andami.plugins.PluginClassLoader;
61
import com.iver.andami.ui.mdiFrame.MDIFrame;
62
import com.iver.andami.ui.mdiFrame.MainFrame;
63
import com.iver.andami.ui.mdiManager.MDIManager;
64
import com.iver.utiles.XMLEntity;
65

    
66

    
67
/**
68
 * Clase que proporciona servicios a los plugins.
69
 *
70
 * @author Fernando Gonz?lez Cort?s
71
 */
72
public class PluginServices {
73
        private static Logger logger = Logger.getLogger(PluginServices.class.getName());
74
        private PluginClassLoader loader;
75
        private PropertyResourceBundle resourceBundle;
76
        private XMLEntity persistentXML;
77

    
78
        /**
79
         * Crea un nuevo PluginServices
80
         *
81
         * @param loader ClassLoader del plugin
82
         */
83
        public PluginServices(PluginClassLoader loader) {
84
                this.loader = loader;
85
        }
86

    
87
        /**
88
         * Devuelve el mensaje en el idioma del locale actual del texto
89
         * correspondiente a la clave que se pasa como par?metro
90
         *
91
         * @param key Clave del texto que se quiere obtener
92
         *
93
         * @return Texto en el idioma que toca o la propia clave si no se encuentra
94
         *                    en el fichero
95
         */
96
        public String getText(String key) {
97
                if (resourceBundle == null) {
98
                        return key;
99
                }
100

    
101
                if (key == null) {
102
                        return null;
103
                }
104

    
105
                try {
106
                        return resourceBundle.getString(key);
107
                } catch (MissingResourceException e) {
108
                        logger.warn(Messages.getString("PluginServices.No_se_encontro_la_traduccion_para") + " " + key);
109

    
110
                        return key;
111
                }
112
        }
113

    
114
        /**
115
         * Obtiene el classloader del plugin
116
         *
117
         * @return Returns the loader.
118
         */
119
        public PluginClassLoader getClassLoader() {
120
                return loader;
121
        }
122

    
123
        /**
124
         * Obtiene el nombre del plugin
125
         *
126
         * @return String
127
         */
128
        String getPluginName() {
129
                return loader.getPluginName();
130
        }
131

    
132
        /**
133
         * Establece el paquete de traducciones del objeto
134
         * pluginservices asociado a un plugin
135
         *
136
         * @param name nombre del paquete
137
         * @param locale locale para obtener los recursos del paquete
138
         */
139
        void setResourceBundle(String name, Locale locale) {
140
                try {
141
                        resourceBundle = (PropertyResourceBundle) ResourceBundle.getBundle(name,
142
                                        locale, loader);
143
                } catch (MissingResourceException e) {
144
                        logger.error(Messages.getString("PluginServices.No_se_encontro_el_recurso_de_traducciones") + name, e);
145
                }
146
        }
147

    
148
        /**
149
         * Obtienen una referencia al PluginServices del plugin cuyo nombre se pasa
150
         * como par?metro
151
         *
152
         * @param pluginClassInstance Instancia de una clase propia del plugin a
153
         *                   cuyos servicios se quiere acceder
154
         *
155
         * @return Objeto PluginServices asociado al plugin
156
         *
157
         * @throws RuntimeException 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.getClass()
162
                                                                                                                                                          .getClassLoader();
163

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

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

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

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

    
204
        /**
205
         * Obtiene una referencia a la instancia de la extensi?n
206
         * cuya clase se pasa como par?metro
207
         *
208
         * @param extensionClass Clase de la extensi?n cuya instancia se quiere obtener
209
         *
210
         * @return Instancia de la extensi?n o null en caso de que no haya
211
         * una extensi?n con esa clase
212
         */
213
        public static Extension getExtension(Class extensionClass) {
214
                return (Extension) Launcher.getClassesExtensions().get(extensionClass);
215
        }
216

    
217
        /**
218
         * Obtiene un iterador sobre las extensiones
219
         *
220
         * @return Iterator
221
         */
222
        public static Iterator getExtensions() {
223
                return Launcher.getClassesExtensions().values().iterator();
224
        }
225

    
226
        /**
227
         * Obtiene una traducci?n de un plugin
228
         *
229
         * @param pluginObject Objeto cargado desde un plugin
230
         * @param key Nombre de la clave cuyo valor se quiere obtener
231
         *
232
         * @return El valor, si existe. La clave si no existe. Si el objeto que
233
         * se pasa como par?metro no ha sido cargado desde un plugin
234
         * se devuelve la clave.
235
         */
236
        public static String getText(Object pluginObject, String key) {
237
                try {
238
                        PluginServices ps = getPluginServices(pluginObject);
239
                        if (ps == null) return key;
240
                        return ps.getText(key);
241
                } catch (RuntimeException e) {
242
                        logger.error("GetText: Clave = " + key + ". ", e);
243

    
244
                        return key;
245
                }
246
        }
247

    
248
        /**
249
         * Establece los datos del plugin que deber?n persistir entre ejecuciones
250
         * en formato xml
251
         *
252
         * @param entity DOCUMENT ME!
253
         */
254
        public void setPersistentXML(XMLEntity entity) {
255
                persistentXML = entity;
256
        }
257

    
258
        /**
259
         * Obtiene un objeto que representa la persistencia del plugin en formato
260
         * xml.
261
         *
262
         * @return Devuelve null hasta que se invoca el m?todo setPersistentXML
263
         */
264
        public XMLEntity getPersistentXML() {
265
                if (persistentXML == null){
266
                        persistentXML = new XMLEntity();
267
                }
268
                return persistentXML;
269
        }
270

    
271
        /**
272
         * A?ade un listener a un popup menu registrado en el
273
         * config.xml de alg?n plugin
274
         *
275
         * @param name Nombre del men? contextual
276
         * @param c Componente que desplegar? el men? cuando
277
         * se haga click con el bot?n derecho
278
         * @param listener Listener que se ejecutar? cuando se 
279
         * seleccione cualquier entrada del men?
280
         *
281
         * @throws RuntimeException Si la interfaz no est? preparada
282
         * todav?a. S?lo puede darse durante el arranque
283
         */
284
        public void addPopupMenuListener(String name, Component c,
285
                ActionListener listener) {
286
                MDIFrame frame = Launcher.getFrame();
287

    
288
                if (frame == null) {
289
                        throw new RuntimeException("MDIFrame not loaded yet");
290
                }
291

    
292
                frame.addPopupMenuListener(name, c, listener, loader);
293
        }
294

    
295
        /**
296
         * Obtiene una referencia al directorio del plugin
297
         *
298
         * @return File
299
         */
300
        public File getPluginDirectory() {
301
                return new File(Launcher.getPluginsDir() + File.separator +
302
                        getPluginName());
303
        }
304

    
305
        /**
306
         * Ejecuta una tarea en segundo plano, dejando a la 
307
         * interfaz responder pero inhibiendo los eventos
308
         *
309
         * @param r Tarea a ejecutar
310
         *
311
         * @return Thread en el que se ejecuta la tarea
312
         */
313
        public static Thread backgroundExecution(Runnable r) {
314
                Thread t = new Thread(new RunnableDecorator(r));
315
                t.start();
316

    
317
                return t;
318
        }
319

    
320
        public static void closeApplication(){
321
            Launcher.closeApplication();
322
        }
323
        
324
        /**
325
         * DOCUMENT ME!
326
         *
327
         * @author Fernando Gonz?lez Cort?s
328
         */
329
        private static class RunnableDecorator implements Runnable {
330
                private Runnable r;
331

    
332
                /**
333
                 * Crea un nuevo RunnableDecorator.
334
                 *
335
                 * @param r DOCUMENT ME!
336
                 */
337
                public RunnableDecorator(Runnable r) {
338
                        this.r = r;
339
                }
340

    
341
                /**
342
                 * @see java.lang.Runnable#run()
343
                 */
344
                public void run() {
345
                        try {
346
                                SwingUtilities.invokeAndWait(new Runnable() {
347
                                                public void run() {
348
                                                        getMDIManager().setWaitCursor();
349
                                                }
350
                                        });
351
                        } catch (InterruptedException e) {
352
                                NotificationManager.addWarning(Messages.getString("PluginServices.No_se_pudo_poner_el_reloj_de_arena"),
353
                                        e);
354
                        } catch (InvocationTargetException e) {
355
                                NotificationManager.addWarning(Messages.getString("PluginServices.No_se_pudo_poner_el_reloj_de_arena"),
356
                                        e);
357
                        }
358

    
359
                        try{
360
                                r.run();
361
                        } catch(RuntimeException e){
362
                                NotificationManager.addError(Messages.getString("PluginServices.Bug_en_el_codigo"), e);
363
                        } catch (Error e){
364
                                NotificationManager.addError(Messages.getString("PluginServices.Error_grave_de_la_aplicaci?n"), e);
365
                        }
366

    
367
                        try {
368
                                SwingUtilities.invokeAndWait(new Runnable() {
369
                                                public void run() {
370
                                                        getMDIManager().restoreCursor();
371
                                                }
372
                                        });
373
                        } catch (InterruptedException e) {
374
                                NotificationManager.addWarning(Messages.getString("PluginServices.No_se_pudo_restaurar_el_cursor_del_raton"),
375
                                        e);
376
                        } catch (InvocationTargetException e) {
377
                                NotificationManager.addWarning(Messages.getString("PluginServices.No_se_pudo_restaurar_el_cursor_del_raton"),
378
                                        e);
379
                        }
380
                }
381
        }
382
}