Statistics
| Revision:

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

History | View | Annotate | Download (33 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.ui.mdiFrame;
42

    
43
import java.awt.BorderLayout;
44
import java.awt.Component;
45
import java.awt.Dimension;
46
import java.awt.FlowLayout;
47
import java.awt.Insets;
48
import java.awt.Toolkit;
49
import java.awt.event.ActionEvent;
50
import java.awt.event.ActionListener;
51
import java.awt.event.ComponentEvent;
52
import java.awt.event.ComponentListener;
53
import java.awt.event.ContainerEvent;
54
import java.awt.event.ContainerListener;
55
import java.awt.event.MouseAdapter;
56
import java.awt.event.MouseEvent;
57
import java.awt.event.WindowAdapter;
58
import java.awt.event.WindowEvent;
59
import java.io.FileNotFoundException;
60
import java.net.URL;
61
import java.util.ArrayList;
62
import java.util.HashMap;
63
import java.util.Iterator;
64
import java.util.NoSuchElementException;
65
import java.util.Vector;
66

    
67
import javax.swing.ButtonGroup;
68
import javax.swing.ImageIcon;
69
import javax.swing.JComponent;
70
import javax.swing.JFrame;
71
import javax.swing.JMenu;
72
import javax.swing.JMenuBar;
73
import javax.swing.JOptionPane;
74
import javax.swing.JPanel;
75
import javax.swing.JPopupMenu;
76
import javax.swing.JSeparator;
77
import javax.swing.KeyStroke;
78
import javax.swing.MenuElement;
79
import javax.swing.SwingUtilities;
80
import javax.swing.Timer;
81

    
82
import org.apache.log4j.Logger;
83
import org.gvsig.gui.beans.controls.IControl;
84

    
85
import com.iver.andami.Launcher;
86
import com.iver.andami.PluginServices;
87
import com.iver.andami.messages.Messages;
88
import com.iver.andami.messages.NotificationManager;
89
import com.iver.andami.plugins.ExtensionDecorator;
90
import com.iver.andami.plugins.PluginClassLoader;
91
import com.iver.andami.plugins.config.generate.ActionTool;
92
import com.iver.andami.plugins.config.generate.Label;
93
import com.iver.andami.plugins.config.generate.Menu;
94
import com.iver.andami.plugins.config.generate.PopupMenu;
95
import com.iver.andami.plugins.config.generate.SelectableTool;
96
import com.iver.andami.plugins.config.generate.SkinExtensionType;
97
import com.iver.andami.plugins.config.generate.ToolBar;
98
import com.iver.andami.ui.mdiManager.MDIManager;
99
import com.iver.andami.ui.mdiManager.MDIManagerFactory;
100

    
101

    
102
/**
103
 * Frame principal de la aplicaci?n.
104
 *
105
 * @version $Revision: 9167 $
106
 */
107
public class MDIFrame extends JFrame implements ComponentListener,
108
        ContainerListener, ActionListener, MainFrame {
109
        /** DOCUMENT ME! */
110
        private static Logger logger = Logger.getLogger(MDIFrame.class.getName());
111
        private MDIManager mdiManager = MDIManagerFactory.createManager();
112

    
113
        /** Elementos de la aplicaci?n */
114
        private JMenuBar menuBar = new JMenuBar();
115

    
116
        /** DOCUMENT ME! */
117
        private JPanel toolBars = new JPanel();
118

    
119
        /** DOCUMENT ME! */
120
        private NewStatusBar bEstado = null;
121

    
122
        /** Asocia los nombres con las barras de herramientas */
123
        private HashMap toolBarMap = new HashMap();
124

    
125
    /**
126
     * actionCommand del tool seleccionado
127
     */
128
    private String selectedTool;
129

    
130
        /** Asocia los nombres con los popupMenus */
131
        private HashMap popupMap = new HashMap();
132

    
133
        /** Asocia controles con la clase de la extension asociada */
134
        private HashMap controlClass = new HashMap();
135

    
136
        /**
137
         * Asocia la informaci?n sobre las etiquetas que van en la status bar con
138
         * cada extension
139
         */
140
        private HashMap classLabels = new HashMap();
141

    
142
        //private HashMap classControls = new HashMap();
143

    
144
        /** ProgressListeners (ver interfaz com.iver.mdiApp.ui.ProgressListener) */
145
        private ArrayList progressListeners = new ArrayList();
146

    
147
        /** Timer para invocar los enventos de la interfaz anterior */
148
        private Timer progressTimer = null;
149

    
150
        /** Tabla hash que asocia las clases con las extensiones */
151
        private HashMap classesExtensions = new HashMap();
152

    
153
        /** ?ltima clase que activ? etiquetas */
154
        private Class lastLabelClass;
155

    
156
        /** Instancia que pone los tooltip en la barra de estado */
157
        private TooltipListener tooltipListener = new TooltipListener();
158
        private HashMap infoCodedMenus = new HashMap();
159

    
160
        private String titlePrefix;
161
        private ButtonGroup buttonGroup=new ButtonGroup();
162
        /**
163
         * Realiza tareas para poner en marcha la aplicaci?n
164
         *
165
         * @throws RuntimeException DOCUMENT ME!
166
         */
167
        public void init() {
168
                JPopupMenu.setDefaultLightWeightPopupEnabled(false);
169
                if (!SwingUtilities.isEventDispatchThread()) {
170
                        throw new RuntimeException("Not Event Dispatch Thread");
171
                }
172

    
173
                //Se a?aden los listeners del JFrame
174
                this.addWindowListener(new WindowAdapter() {
175
                                public void windowClosing(WindowEvent e) {
176
                                        /*JOptionPane dlgSalir = new JOptionPane(Utilities.getMessage(this,"quiere_salir"),
177
                                           JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
178
                                         */
179
                                        int option = JOptionPane.showConfirmDialog(MDIFrame.this,
180
                                                        Messages.getString("MDIFrame.quiere_salir"),
181
                                                        Messages.getString("MDIFrame.salir"),
182
                                                        JOptionPane.YES_NO_OPTION);
183

    
184
                                        if (option == JOptionPane.YES_OPTION) {
185
                                                Launcher.closeApplication();
186
                                        }
187
                                }
188
                        });
189
                this.addComponentListener(this);
190
                this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
191

    
192
                //Se configura la barra de menu
193
                setJMenuBar(menuBar);
194

    
195
                //Se configura el layout del JFrame principal
196
                this.getContentPane().setLayout(new BorderLayout());
197

    
198
                /*
199
                 * Se configura y se a?ade el JPanel de las barras de
200
                 * herramientas
201
                 */
202
                FlowLayout layout = new FlowLayout(FlowLayout.LEFT);
203
                layout.setHgap(0);
204
                layout.setVgap(0);
205
                toolBars.setLayout(layout);
206
                getContentPane().add(toolBars, BorderLayout.PAGE_START);
207

    
208
                // Se a?ade la barra de estado a la aplicaci?n
209
                bEstado = new NewStatusBar();
210
                bEstado.setInfoText(Messages.getString("StatusBar.Aplicacion_iniciada"));
211
                getContentPane().add(bEstado, BorderLayout.SOUTH);
212

    
213
                this.toolBars.addContainerListener(this);
214

    
215
                pack();
216

    
217
                // TODO LWS Aqui deber?a cargar los valores salvados de la ?ltima ejecuci?n.
218
                setSize(700, 580);
219
                setLocation(10,10);
220
                setExtendedState(MAXIMIZED_BOTH);
221

    
222
                mdiManager.init(this);
223
        }
224

    
225
        public void setTitle(String title) {
226
                super.setTitle(titlePrefix + ":" + title);
227
        }
228

    
229
        /**
230
         * A?ade un modo de operaci?n a la caja de herramientas
231
         *
232
         * @param ext Texto del boton, si es null no aparece texto
233
         * @param ext Icono del boton, si es null no aparece icono
234
         * @param ext Extensi?n asociada al control
235
         * @param selectableTool Enable text del control
236
         *
237
         * @throws ClassNotFoundException
238
         * @throws RuntimeException DOCUMENT ME!
239
         */
240
        public void addTool(PluginClassLoader loader, SkinExtensionType ext,
241
                ToolBar toolBar, SelectableTool selectableTool)
242
                throws ClassNotFoundException {
243
                if (!SwingUtilities.isEventDispatchThread()) {
244
                        throw new RuntimeException("No Event Dispatch Thread");
245
                }
246

    
247
                // Para traducir
248
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
249

    
250
                JToolBarToggleButton btn;
251
                URL image = loader.getResource(selectableTool.getIcon());
252

    
253
                if (image != null) {
254
                        btn = new JToolBarToggleButton(selectableTool.getText(),
255
                                        new ImageIcon(image));
256
                } else {
257
                        btn = new JToolBarToggleButton(selectableTool.getText());
258
                }
259

    
260
                btn.setMargin(new Insets(0, 0, 0, 0));
261
                btn.addMouseListener(tooltipListener);
262
                btn.addActionListener(this);
263
                btn.setFocusable(false);
264
                btn.setActionCommand(selectableTool.getActionCommand());
265
                btn.setToolTipText(selectableTool.getTooltip());
266
                btn.setEnabled(false);
267
                btn.setVisible(false);
268

    
269
                if (selectableTool.getIsDefault()) {
270
                        btn.setSelected(true);
271
            selectedTool = btn.getActionCommand();
272
                }
273

    
274
                String name = getName(toolBar.getName(), loader);
275

    
276
                SelectableToolBar jtb = (SelectableToolBar) toolBarMap.get(name);
277

    
278
                if (jtb == null) {
279
                        jtb = new SelectableToolBar(toolBar.getName());
280
                        jtb.setRollover(true);
281
                        toolBarMap.put(name, jtb);
282
                        toolBars.add(jtb);
283

    
284
                }
285

    
286
                jtb.addButton(buttonGroup, btn);
287
                controlClass.put(btn, loader.loadClass(ext.getClassName()));
288

    
289
                if (selectableTool.getTooltip() != null) {
290
                        btn.setToolTip(ps.getText(selectableTool.getTooltip()));
291
                }
292

    
293
                if (selectableTool.getEnableText() != null) {
294
                        btn.setEnableText(ps.getText(selectableTool.getEnableText()));
295
                }
296

    
297
                if (selectableTool.getLast() == true) {
298
                        jtb.addSeparator();
299
                }
300
        }
301

    
302
        /**
303
         * A?ade un bot?n a la barra de herramientas
304
         *
305
         * @param ext Texto del boton, si es null no aparece texto
306
         * @param ext Extensi?n asociada al control
307
         * @param toolBar Icono del boton, si es null no aparece texto
308
         * @param actionTool Tooltip de la barra de herramientas
309
         *
310
         * @throws ClassNotFoundException
311
         * @throws RuntimeException DOCUMENT ME!
312
         */
313
        public void addTool(PluginClassLoader loader, SkinExtensionType ext,
314
                ToolBar toolBar, ActionTool actionTool) throws ClassNotFoundException {
315
                if (!SwingUtilities.isEventDispatchThread()) {
316
                        throw new RuntimeException("No Event Dispatch Thread");
317
                }
318

    
319
                // Para traducir los textos que vengan
320
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
321

    
322
                JToolBarButton btn;
323
                URL image = loader.getResource(actionTool.getIcon());
324

    
325
                if (image != null) {
326
                        btn = new JToolBarButton(actionTool.getText(), new ImageIcon(image));
327
                } else {
328
                        btn = new JToolBarButton(actionTool.getText());
329
                }
330

    
331
                btn.setMargin(new Insets(0, 0, 0, 0));
332
                btn.addMouseListener(tooltipListener);
333
                btn.addActionListener(this);
334
                btn.setFocusable(false);
335
                btn.setActionCommand(actionTool.getActionCommand());
336
                btn.setEnabled(false);
337
                btn.setVisible(false);
338

    
339
                String name = getName(toolBar.getName(), loader);
340

    
341
                SelectableToolBar jtb = (SelectableToolBar) toolBarMap.get(name);
342

    
343
                if (jtb == null) {
344
                        jtb = new SelectableToolBar(toolBar.getName());
345
                        jtb.setRollover(true);
346
                        toolBarMap.put(name, jtb);
347
                        toolBars.add(jtb);
348
                }
349

    
350
                jtb.add(btn);
351

    
352
                controlClass.put(btn, loader.loadClass(ext.getClassName()));
353

    
354
                if (actionTool.getTooltip() != null) {
355
                        btn.setToolTip(ps.getText(actionTool.getTooltip()));
356
                }
357

    
358
                if (actionTool.getEnableText() != null) {
359
                        btn.setEnableText(ps.getText(actionTool.getEnableText()));
360
                }
361

    
362
                if (actionTool.getLast() == true) {
363
                        jtb.addSeparator();
364
                }
365
        }
366

    
367
        /**
368
         * Creates the needed menu structure to add the menu to the bar.
369
         * Returns the father which must hold the menu which was
370
         * provided as parameter.
371
         *
372
         * Crea la estructura de men?s necesaria para a?adir el menu a la barra.
373
         * Devuelve el padre del cual debe colgar el menu que se pasa como
374
         * par?metro.
375
         *
376
         * @param menu The Menu whose support is going to be added
377
         * @param loader The plugin's class loader
378
         *
379
         * @return The proper father for the menu which was provided as parameter
380
         */
381
        private JMenu createMenuAncestors(Menu menu, PluginClassLoader loader) {
382
                JMenu menuPadre = null;
383

    
384
                String[] menues = menu.getText().split("/");
385
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
386

    
387
                for (int i = 0; i < menues.length; i++) {
388
                        menues[i] = ps.getText(menues[i]);
389
                }
390

    
391
                //Se busca el padre en la menuBar
392
                for (int i = 0; i < menuBar.getMenuCount(); i++) {
393
                        if (menuBar.getMenu(i).getText().compareToIgnoreCase(menues[0]) == 0) {
394
                                menuPadre = (JMenu) menuBar.getMenu(i);
395
                        }
396
                }
397

    
398
                //Si no se encuentra el padre se crea
399
                if (menuPadre == null) {
400
                        menuPadre = new JMenu(menues[0]);
401
                        menuBar.add(menuPadre);
402
                }
403

    
404
                //Se crea el resto de menus
405
                Vector temp = new Vector();
406

    
407
                for (int i = 1; i < (menues.length - 1); i++) {
408
                        temp.add(menues[i]);
409
                }
410

    
411
                menuPadre = createMenus(temp, menuPadre);
412

    
413
                return menuPadre;
414
        }
415

    
416
        /**
417
         * A?ade la informaci?n del menu al framework. Debido a que los men?es se
418
         * pueden introducir en un orden determinado por el usuario, pero los
419
         * plugins se instalan en un orden arbitrario, primero se almacena la
420
         * informaci?n de todos los menus para luego ordenarlos y posteriormente
421
         * a?adirlos al interfaz
422
         *
423
         * @param loader Posicion del menu. Se ordena por este campo
424
         * @param ext Array con los nombres de los padres del menu
425
         * @param menu Texto del menu
426
         *
427
         * @throws ClassNotFoundException
428
         * @throws RuntimeException DOCUMENT ME!
429
         */
430
        public void addMenu(PluginClassLoader loader, SkinExtensionType ext,
431
                Menu menu) throws ClassNotFoundException {
432
                if (!SwingUtilities.isEventDispatchThread()) {
433
                        throw new RuntimeException("No Event Dispatch Thread");
434
                }
435

    
436
                JMenu menuPadre = createMenuAncestors(menu, loader);
437

    
438
                //Se registra y a?ade el menu
439
        /* String[] aux = menu.getText().split("/");
440

441
        if (aux.length == 2)
442
            if (aux[1].equals("----"))
443
            {
444
                menuPadre.addSeparator();
445
                return;
446
            } */
447
        if (menu.getIs_separator())
448
        {
449
            menuPadre.addSeparator();
450
            return;
451
        }
452

    
453
                JMenuItem nuevoMenu = createJMenuItem(loader, menu);
454
                nuevoMenu.addMouseListener(tooltipListener);
455
                nuevoMenu.addActionListener(this);
456
                menuPadre.add(nuevoMenu);
457
        controlClass.put(nuevoMenu, loader.loadClass(ext.getClassName()));
458
        }
459

    
460
        /**
461
         * Dado un array de nombres de menu traducidos, encuentra el  men?
462
         *
463
         * @param nombres DOCUMENT ME!
464
         * @param padre DOCUMENT ME!
465
         *
466
         * @return DOCUMENT ME!
467
         */
468
        private javax.swing.JMenuItem getMenu(Vector nombres, JMenu padre) {
469
                javax.swing.JMenuItem buscado = null;
470
                javax.swing.JMenuItem hijo;
471

    
472
                for (int i = 0; i < padre.getMenuComponentCount(); i++) {
473
                        if (padre.getMenuComponent(i) instanceof javax.swing.JMenuItem) { //we need to test that, as there are also separators
474
                                hijo = (javax.swing.JMenuItem) padre.getMenuComponent(i);
475

    
476
                                if (hijo.getText().compareToIgnoreCase((String) nombres.get(0)) == 0) {
477
                                        buscado = hijo;
478
                                }
479
                        }
480
                }
481

    
482
                //Si no se encuentra el menu
483
                if (buscado == null) {
484
                        return null;
485
                }
486

    
487
                nombres.remove(0);
488

    
489
                //Si se ha llegado al fin de la ruta completa
490
                if (nombres.isEmpty()) {
491
                        return buscado;
492
                } else {
493
                        if (buscado instanceof JMenu) {
494
                                return getMenu(nombres, (JMenu) buscado);
495
                        } else {
496
                                return null;
497
                        }
498
                }
499
        }
500

    
501
        /**
502
         * Crea la estructura de menus recursivamente. Por ejemplo, si se le pasa
503
         * en el par?metro nombres el array {"Search", "References", "Workspace"}
504
         * crear? un men? Search, un submen? del anterior que se llamar?
505
         * References y debajo de ?ste ?ltimo otro menu llamado Workspace
506
         *
507
         * @param nombres Array con los nombres de los men?s que se quieren crear
508
         * @param padre Menu padre de los men?s creados. Es ?til porque es un
509
         *                   algoritmo recursivo
510
         *
511
         * @return Devuelve el men? creado. Al final de toda la recursividad,
512
         *                    devolver? el men? de m?s abajo en la jerarqu?a
513
         *
514
         * @throws RuntimeException DOCUMENT ME!
515
         */
516
        private JMenu createMenus(Vector nombres, JMenu padre) {
517
                if (!SwingUtilities.isEventDispatchThread()) {
518
                        throw new RuntimeException("No Event Dispatch Thread");
519
                }
520

    
521
                //si no quedan nombres de menu por crear se vuelve: caso base
522
                if (nombres.size() == 0) {
523
                        return padre;
524
                }
525

    
526
                //Se busca el menu por si ya existiera para no crearlo otra vez
527
                JMenu buscado = null;
528

    
529
                for (int i = 0; i < padre.getMenuComponentCount(); i++) {
530
                        try {
531
                                JMenu hijo = (JMenu) padre.getMenuComponent(i);
532

    
533
                                if (hijo.getText().compareToIgnoreCase((String) nombres.get(0)) == 0) {
534
                                        buscado = hijo;
535
                                }
536
                        } catch (ClassCastException e) {
537
                                /*
538
                                 * Se ha encontrado un elemento hoja del arbol de men?es
539
                                 */
540
                        }
541
                }
542

    
543
                if (buscado != null) {
544
                        //Si lo hemos encontrado creamos el resto
545
                        nombres.remove(0);
546

    
547
                        return createMenus(nombres, buscado);
548
                } else {
549
                        //Si no lo hemos encontrado se crea el menu, se a?ade al padre
550
                        //y se crea el resto
551
                        JMenu menuPadre = new JMenu((String) nombres.get(0));
552
                        padre.add(menuPadre);
553

    
554
                        nombres.remove(0);
555

    
556
                        return createMenus(nombres, menuPadre);
557
                }
558
        }
559

    
560
        /**
561
         * M?todo invocado en respuesta a ciertos eventos de la interfaz que pueden
562
         * ocultar botones de las barras de herramientas y que redimensiona ?sta
563
         * de manera conveniente para que no se oculte ninguno
564
         */
565
        private void ajustarToolBar() {
566
                int margen = 8;
567
                int numFilas = 1;
568
                double acum = margen;
569

    
570
                int toolHeight = 0;
571

    
572
                for (int i = 0; i < toolBars.getComponentCount(); i++) {
573
                        Component c = toolBars.getComponent(i);
574

    
575
                        if (!c.isVisible()) {
576
                                continue;
577
                        }
578

    
579
                        double width = c.getPreferredSize().getWidth();
580
                        acum = acum + width;
581

    
582
                        if (acum > this.getWidth()) {
583
                                numFilas++;
584
                                acum = width + margen;
585
                        }
586

    
587
                        if (c.getPreferredSize().getHeight() > toolHeight) {
588
                                toolHeight = c.getPreferredSize().height;
589
                        }
590
                }
591

    
592
                toolBars.setPreferredSize(new Dimension(this.getWidth(),
593
                                (int) (numFilas * toolHeight)));
594

    
595
                toolBars.updateUI();
596
        }
597

    
598
        /**
599
         * DOCUMENT ME!
600
         *
601
         * @param classesExtensions
602
         */
603
        public void setClassesExtensions(HashMap classesExtensions) {
604
                this.classesExtensions = classesExtensions;
605
        }
606

    
607
        /**
608
         * M?todo de callback invocado cuando se selecciona un men? o un bot?n de
609
         * la barra de herramientas. Se busca la extensi?n asociada y se ejecuta
610
         *
611
         * @param e Evento producido
612
         */
613
        public void actionPerformed(ActionEvent e) {
614
                Object control = e.getSource();
615
                com.iver.andami.plugins.IExtension ext = (com.iver.andami.plugins.IExtension) classesExtensions.get((Class) controlClass.get(
616
                                control));
617
                String actionCommand = e.getActionCommand();
618
                try {
619
                        logger.debug(Messages.getString("Ejecutando comando: ") + actionCommand);
620
                        ext.execute(actionCommand);
621
                if (control instanceof JToolBarToggleButton)
622
                {
623
                    selectedTool = actionCommand;
624
                }
625
                } catch (RuntimeException t) {
626
                        if (ext==null) {
627
                                logger.error(Messages.getString("No_extension_associated_with_this_event_")+ e.getActionCommand());
628
                        }
629
                        NotificationManager.addError(Messages.getString(
630
                                        "MDIFrame.Error_no_capturado_por_el_usuario"), t);
631
                }
632

    
633
                enableControls();
634
                showMemory();
635
        }
636

    
637
        /**
638
         * DOCUMENT ME!
639
         *
640
         * @param name DOCUMENT ME!
641
         * @param loader DOCUMENT ME!
642
         *
643
         * @return DOCUMENT ME!
644
         */
645
        private String getName(String name, PluginClassLoader loader) {
646
                if (name.indexOf('.') == -1) {
647
                        return loader.getPluginName() + "." + name;
648
                } else {
649
                        return name;
650
                }
651
        }
652

    
653
        /**
654
         * DOCUMENT ME!
655
         *
656
         * @param loader DOCUMENT ME!
657
         * @param menu DOCUMENT ME!
658
         *
659
         * @throws RuntimeException DOCUMENT ME!
660
         */
661
        public void addPopupMenu(PluginClassLoader loader, PopupMenu menu) {
662
                if (!SwingUtilities.isEventDispatchThread()) {
663
                        throw new RuntimeException("No Event Dispatch Thread");
664
                }
665

    
666
                String name = getName(menu.getName(), loader);
667

    
668
                //Se crea el control popupmenu
669
                JPopUpMenu popupMenu = (JPopUpMenu) popupMap.get(name);
670

    
671
                if (popupMenu == null) {
672
                        popupMenu = new JPopUpMenu(menu.getName());
673
                        popupMap.put(name, popupMenu);
674
                }
675

    
676
                // Se a?aden las entradas
677
                Menu[] menues = menu.getMenu();
678

    
679
                for (int i = 0; i < menues.length; i++) {
680
                        //Se registra y a?ade el menu
681
                        JMenuItem nuevoMenu = createJMenuItem(loader, menues[i]);
682

    
683
                        popupMenu.add(nuevoMenu);
684
                }
685
        }
686

    
687
        /**
688
         * DOCUMENT ME!
689
         *
690
         * @param loader
691
         * @param menu
692
         *
693
         * @return
694
         *
695
         * @throws RuntimeException DOCUMENT ME!
696
         */
697
        private JMenuItem createJMenuItem(PluginClassLoader loader, Menu menu) {
698
                JMenuItem nuevoMenu = null;
699

    
700
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
701
                String texto = menu.getText();
702
                texto = texto.substring(texto.lastIndexOf('/') + 1);
703
                texto = ps.getText(texto);
704

    
705
                if (menu.getIcon() != null) {
706
                        URL url = loader.getResource(menu.getIcon());
707
                        if (url != null) {
708
                                nuevoMenu = new JMenuItem(texto, new ImageIcon(url));
709
                        } else {
710
                                NotificationManager.addError(PluginServices.getText(this, "Unable_to_find_icon") +": "+menu.getIcon(), new FileNotFoundException());
711
                        }
712
                } else {
713
                        nuevoMenu = new JMenuItem(texto);
714
                }
715

    
716
                if (menu.getMnemonic() != null) {
717
                        if (menu.getMnemonic().length() != 1) {
718
                                throw new RuntimeException(
719
                                        "Mnemonic must be 1 character length");
720
                        }
721

    
722
                        nuevoMenu.setMnemonic(KeyMapping.getKey(menu.getMnemonic().charAt(0)));
723
                }
724

    
725
                if (menu.getKey() != null) {
726
                        String osName = (String) System.getProperty("os.name");
727
                        if (osName.length() > 5 && osName.substring(0,6).toLowerCase().equals("mac os")) {
728
                                nuevoMenu.setAccelerator(KeyStroke.getKeyStroke(KeyMapping.getKey(
729
                                                menu.getKey().charAt(0)), Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
730
                        } else {
731
                                nuevoMenu.setAccelerator(KeyStroke.getKeyStroke(KeyMapping.getKey(
732
                                                menu.getKey().charAt(0)), ActionEvent.ALT_MASK));
733
                        }
734
                }
735

    
736
                nuevoMenu.setActionCommand(menu.getActionCommand());
737

    
738
                if (menu.getTooltip() != null) {
739
                        nuevoMenu.setToolTip(ps.getText(menu.getTooltip()));
740
                }
741

    
742
                if (menu.getEnableText() != null) {
743
                        nuevoMenu.setEnableText(ps.getText(menu.getEnableText()));
744
                }
745

    
746
                nuevoMenu.setEnabled(true);
747
                nuevoMenu.setVisible(true);
748

    
749
                return nuevoMenu;
750
        }
751

    
752
        /**
753
         * Muestra u oculta el menu de nombre 'name'
754
         *
755
         * @param name Nombre del menu que se quiere mostrar
756
         * @param x Evento de raton
757
         * @param y DOCUMENT ME!
758
         * @param c DOCUMENT ME!
759
         */
760
        private void showPopupMenu(String name, int x, int y, Component c) {
761
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
762

    
763
                if (menu != null) {
764
                        menu.show(c, x, y);
765
                }
766
        }
767

    
768
        /**
769
         * DOCUMENT ME!
770
         *
771
         * @param name DOCUMENT ME!
772
         * @param listener DOCUMENT ME!
773
         */
774
        public void removePopupMenuListener(String name, ActionListener listener) {
775
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
776

    
777
                if (menu != null) {
778
                        Component[] jmenuitems = menu.getComponents();
779

    
780
                        for (int i = 0; i < jmenuitems.length; i++) {
781
                                if (jmenuitems[i] instanceof JMenuItem) {
782
                                        ((JMenuItem) jmenuitems[i]).removeActionListener(listener);
783
                                }
784
                        }
785
                }
786
        }
787

    
788
        /**
789
         * DOCUMENT ME!
790
         *
791
         * @param popupName
792
         * @param c DOCUMENT ME!
793
         * @param listener
794
         * @param loader
795
         */
796
        public void addPopupMenuListener(String popupName, Component c,
797
                ActionListener listener, PluginClassLoader loader) {
798
                final String name = getName(popupName, loader);
799

    
800
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
801

    
802
                if (menu != null) {
803
                        Component[] jmenuitems = menu.getComponents();
804

    
805
                        for (int i = 0; i < jmenuitems.length; i++) {
806
                                if (jmenuitems[i] instanceof JMenuItem) {
807
                                        ((JMenuItem) jmenuitems[i]).addActionListener(listener);
808
                                }
809
                        }
810
                }
811

    
812
                c.addMouseListener(new MouseAdapter() {
813
                                public void mousePressed(MouseEvent e) {
814
                                        if (e.isPopupTrigger()) {
815
                                                showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
816
                                        }
817
                                }
818

    
819
                                public void mouseReleased(MouseEvent e) {
820
                                        if (e.isPopupTrigger()) {
821
                                                showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
822
                                        }
823
                                }
824
                        });
825
        }
826

    
827
        /**
828
         * Itera por los controles preguntando a las extensiones si estos est?n
829
         * habilitados y visibles
830
         *
831
         * @throws RuntimeException DOCUMENT ME!
832
         */
833
        public void enableControls() {
834
                if (!SwingUtilities.isEventDispatchThread()) {
835
                        throw new RuntimeException("No Event Dispatch Thread");
836
                }
837

    
838
                Iterator e = classesExtensions.values().iterator();
839
                HashMap estadoExtensiones = new HashMap();
840
                HashMap visibilidadExtensiones = new HashMap();
841

    
842
                while (e.hasNext()) {
843
                        ExtensionDecorator ext = (ExtensionDecorator) e.next();
844

    
845
                        try {
846
                                if (estadoExtensiones.get(ext) == null) {
847
                                        boolean b;
848
                                        if (ext.getVisibility() == ExtensionDecorator.ALWAYS_VISIBLE)
849
                                                b = true;
850
                                        else if (ext.getVisibility() == ExtensionDecorator.ALWAYS_INVISIBLE)
851
                                                b = false;
852
                                        else b = ext.isVisible();
853
                                        Boolean visible = new Boolean(b);
854
                                        Boolean enabled = new Boolean(false);
855

    
856
                                        if (visible.booleanValue()) {
857
                                                enabled = new Boolean(ext.isEnabled());
858
                                        }
859

    
860
                                        estadoExtensiones.put(ext, enabled);
861
                                        visibilidadExtensiones.put(ext, visible);
862
                                }
863
                        } catch (Throwable e1) {
864
                                NotificationManager.addError(Messages.getString(
865
                                                "MDIFrame.Error_no_capturado_por_el_usuario"), e1);
866
                                estadoExtensiones.put(ext, Boolean.FALSE);
867
                        }
868
                }
869

    
870
                //Se habilitan y deshabilitan los controles
871
                e = controlClass.keySet().iterator();
872

    
873
                while (e.hasNext()) {
874
                        JComponent control = (JComponent) e.next();
875

    
876
                        try {
877
                                com.iver.andami.plugins.IExtension ext = (com.iver.andami.plugins.IExtension) classesExtensions.get((Class) controlClass.get(
878
                                                        control));
879
                                boolean enabled = ((Boolean) estadoExtensiones.get(ext)).booleanValue();
880
                                boolean visible = ((Boolean) visibilidadExtensiones.get(ext)).booleanValue();
881
                                control.setEnabled(enabled);
882
                                control.setVisible(visible);
883
                        } catch (Exception ex) {
884
                                control.setEnabled(false);
885
                                control.setVisible(false);
886
                        }
887
                }
888

    
889
                //Se itera por los men?es para ocultar los que no tengan hijos visibles
890
                for (int i = 0; i < menuBar.getMenuCount(); i++) {
891
                        MenuElement menu = menuBar.getMenu(i);
892
                        ocultarMenus(menu);
893
                }
894

    
895
                //Se ocultan las barras que no tienen herramientas
896
                Iterator it = toolBarMap.values().iterator();
897

    
898
                while (it.hasNext()) {
899
                        SelectableToolBar t = (SelectableToolBar) it.next();
900
                        boolean todosOcultos = true;
901

    
902
                        for (int i = 0; i < t.getComponentCount(); i++) {
903
                                if (!(t.getComponent(i) instanceof JSeparator) // separators doesn't matter
904
                                                && t.getComponent(i).isVisible()) {
905
                                        todosOcultos = false;
906
                                }
907
                        }
908

    
909
                        if (todosOcultos) {
910
                                t.setVisible(false);
911
                        } else {
912
                                t.setVisible(true);
913
                        }
914
                }
915

    
916
                if (mdiManager != null) {
917
                        JPanel f = (JPanel) mdiManager.getActiveWindow();
918

    
919
                        if (f != null) {
920
                                if (lastLabelClass != f.getClass()) {
921
                                        lastLabelClass = f.getClass();
922

    
923
                                        Label[] lbls = (Label[]) classLabels.get(lastLabelClass);
924

    
925
                                        if (lbls != null) {
926
                                                bEstado.setLabelSet(lbls);
927
                                        }
928
                                }
929
                        }
930
                }
931

    
932
                ajustarToolBar();
933

    
934
                showMemory();
935
        }
936

    
937
        /**
938
         * Establece la visibilidad de un menu y todos sus descendientes en la
939
         * jerarquia teniendo en cuenta la visibilidad de todos los submenus.
940
         *
941
         * @param menu Menu que se quiere visualizar
942
         *
943
         * @return Devuelve true si el menu es visible y false en caso contrario
944
         */
945
        private boolean ocultarMenus(MenuElement menu) {
946
                MenuElement[] submenus = menu.getSubElements();
947

    
948
                //Si no tiene hijos se devuelve su visibilidad
949
                if (submenus.length == 0) {
950
                        return menu.getComponent().isVisible();
951
                }
952

    
953
                /*
954
                 * Si tiene hijos se devuelve true si alg?no de ellos es visible,
955
                 * pero se itera por todos ellos
956
                 */
957
                boolean visible = false;
958

    
959
                for (int i = 0; i < submenus.length; i++) {
960
                        if (ocultarMenus(submenus[i])) {
961
                                if (!(menu instanceof JPopupMenu)) {
962
                                        menu.getComponent().setVisible(true);
963
                                }
964

    
965
                                visible = true;
966
                        }
967
                }
968

    
969
                if (visible) {
970
                        return true;
971
                }
972

    
973
                menu.getComponent().setVisible(false);
974

    
975
                return false;
976
        }
977

    
978
        /**
979
         * Muestra la memoria consumida por el programa
980
         */
981
        private void showMemory() {
982
                Runtime r = Runtime.getRuntime();
983
                long mem = r.totalMemory() - r.freeMemory();
984
                logger.debug("Memoria total: " + mem);
985
        }
986

    
987
        /**
988
         * DOCUMENT ME!
989
         *
990
         * @return
991
         */
992
        public MDIManager getMDIManager() {
993
                return mdiManager;
994
        }
995

    
996
        /**
997
         * Establece el mensaje en la barra de estado asociado a una etiqueta
998
         *
999
         * @return DOCUMENT ME!
1000
         */
1001
        public NewStatusBar getStatusBar() {
1002
                return bEstado;
1003
        }
1004
        /**
1005
     * You can use this function to select the appropiate
1006
     * tool inside the toolbars
1007
     */
1008
    public void setSelectedTool(String actionCommand)
1009
    {
1010
        Iterator it = toolBarMap.values().iterator();
1011
        while (it.hasNext()) {
1012
            SelectableToolBar t = (SelectableToolBar) it.next();
1013
            t.setSelectedTool(actionCommand);
1014
        }
1015
        selectedTool = actionCommand;
1016

    
1017
    }
1018

    
1019
        /**
1020
         * DOCUMENT ME!
1021
         *
1022
         * @param clase
1023
         * @param label
1024
         */
1025
        public void setLabels(Class clase, Label[] label) {
1026
                classLabels.put(clase, label);
1027
        }
1028

    
1029
        public void addStatusBarControl(Class extensionClass, IControl control) {
1030
                control.addActionListener(this);
1031
                bEstado.addControl(control.getName(), (Component)control);
1032
                controlClass.put(control, extensionClass);
1033
        }
1034

    
1035
        /**
1036
         * @see com.iver.andami.ui.mdiFrame.MainFrame#removeMenu(com.iver.andami.plugins.config.generate.Menu)
1037
         */
1038
        public void removeMenu(Menu menu) {
1039
                JMenuItem delete = (JMenuItem) infoCodedMenus.get(menu);
1040

    
1041
                if (delete == null) {
1042
                        throw new NoSuchElementException(menu.getText());
1043
                }
1044

    
1045
                delete.getParent().remove(delete);
1046
                infoCodedMenus.remove(menu);
1047
        }
1048

    
1049
        /**
1050
         * @see com.iver.andami.ui.mdiFrame.MainFrame#addMenu(com.iver.andami.plugins.config.generate.Menu,
1051
         *                 java.awt.event.ActionListener, PluginClassLoader)
1052
         */
1053
        public void addMenu(Menu menu, ActionListener listener,
1054
                PluginClassLoader loader) {
1055
                JMenu menuPadre = createMenuAncestors(menu, loader);
1056

    
1057
                //Se registra y a?ade el menu
1058
                JMenuItem nuevoMenu = createJMenuItem(loader, menu);
1059
                nuevoMenu.addMouseListener(tooltipListener);
1060
                nuevoMenu.addActionListener(listener);
1061
                menuPadre.add(nuevoMenu);
1062

    
1063
                infoCodedMenus.put(menu, nuevoMenu);
1064
        }
1065

    
1066
        /**
1067
         * @see com.iver.andami.ui.mdiFrame.MainFrame#changeMenuName(java.lang.String[],
1068
         *                 String, com.iver.andami.plugins.PluginClassLoader)
1069
         */
1070
        public void changeMenuName(String[] menu, String newName,
1071
                PluginClassLoader loader) {
1072
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
1073

    
1074
                for (int i = 0; i < menu.length; i++) {
1075
                        menu[i] = ps.getText(menu[i]);
1076
                }
1077

    
1078
                JMenu menuPadre = null;
1079

    
1080
                //Se busca el padre en la menuBar
1081
                for (int i = 0; i < menuBar.getMenuCount(); i++) {
1082
                        if (menuBar.getMenu(i).getText().compareToIgnoreCase(menu[0]) == 0) {
1083
                                menuPadre = (JMenu) menuBar.getMenu(i);
1084
                        }
1085
                }
1086

    
1087
                if (menuPadre == null) {
1088
                        throw new NoSuchMenuException(menu[0]);
1089
                }
1090

    
1091
                Vector nombres = new Vector();
1092

    
1093
                for (int i = 1; i < menu.length; i++) {
1094
                        nombres.add(menu[i]);
1095
                }
1096

    
1097
                javax.swing.JMenuItem m = getMenu(nombres, menuPadre);
1098

    
1099
                if (m != null) {
1100
                        m.setText(newName);
1101
                }else{
1102
                        throw new NoSuchMenuException();
1103
                }
1104
        }
1105

    
1106
        /**
1107
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
1108
         */
1109
        public void componentHidden(ComponentEvent arg0) {
1110
        }
1111

    
1112
        /**
1113
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
1114
         */
1115
        public void componentMoved(ComponentEvent arg0) {
1116
        }
1117

    
1118
        /**
1119
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
1120
         */
1121
        public void componentResized(ComponentEvent arg0) {
1122
                ajustarToolBar();
1123
                bEstado.setFixedLabelWidth(this.getWidth() * 0.3);
1124
        }
1125

    
1126
        /**
1127
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
1128
         */
1129
        public void componentShown(ComponentEvent arg0) {
1130
        }
1131

    
1132
        /**
1133
         * @see java.awt.event.ContainerListener#componentAdded(java.awt.event.ContainerEvent)
1134
         */
1135
        public void componentAdded(ContainerEvent arg0) {
1136
                ajustarToolBar();
1137
        }
1138

    
1139
        /**
1140
         * @see java.awt.event.ContainerListener#componentRemoved(java.awt.event.ContainerEvent)
1141
         */
1142
        public void componentRemoved(ContainerEvent arg0) {
1143
                ajustarToolBar();
1144
        }
1145

    
1146
        /**
1147
         * DOCUMENT ME!
1148
         *
1149
         * @author $author$
1150
         * @version $Revision: 9167 $
1151
         */
1152
        public class TooltipListener extends MouseAdapter {
1153
                /**
1154
                 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1155
                 */
1156
                public void mouseEntered(MouseEvent e) {
1157
                        JComponent control = (JComponent) e.getSource();
1158
                        EnableTextSupport ets = (EnableTextSupport) e.getSource();
1159

    
1160
                        String texto = null;
1161
                        texto = control.getToolTipText();
1162

    
1163
                        if (texto != null) {
1164
                                bEstado.setInfoTextTemporal(texto);
1165
                        }
1166
                }
1167

    
1168
                /**
1169
                 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1170
                 */
1171
                public void mouseExited(MouseEvent arg0) {
1172
                        bEstado.restaurarTexto();
1173
                }
1174

    
1175
                /**
1176
                 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1177
                 */
1178
                public void mousePressed(MouseEvent e) {
1179
                        bEstado.restaurarTexto();
1180
                }
1181
        }
1182
        public String getTitlePrefix() {
1183
                return titlePrefix;
1184
        }
1185
        public void setTitlePrefix(String titlePrefix) {
1186
                this.titlePrefix = titlePrefix;
1187
        }
1188

    
1189
    public String getSelectedTool() {
1190
        return selectedTool;
1191
    }
1192

    
1193

    
1194
    /**
1195
     * Get a previously added JComponent by name. For example
1196
     * you can use it if you need to obtain a JToolBar to
1197
     * add some customized component.
1198
     * @param name
1199
     * @return the JComponent or null if none has been found
1200
     */
1201
    public JComponent getComponentByName(String name)
1202
    {
1203
        Iterator e = controlClass.keySet().iterator();
1204

    
1205
        while (e.hasNext()) {
1206
            JComponent control = (JComponent) e.next();
1207
            String nameCtrl = control.getName();
1208
            if (nameCtrl != null)
1209
                    if (nameCtrl.compareTo(name) == 0)
1210
                            return control;
1211
        }
1212
        Iterator it = toolBarMap.values().iterator();
1213
        while (it.hasNext()) {
1214
            SelectableToolBar t = (SelectableToolBar) it.next();
1215
            String nameCtrl = t.getName();
1216
            if (nameCtrl != null)
1217
                    if (nameCtrl.compareTo(name) == 0)
1218
                            return t;
1219

    
1220
        }
1221

    
1222
        return null;
1223
    }
1224
}