Statistics
| Revision:

root / trunk / frameworks / _fwAndami / src / com / iver / andami / ui / mdiFrame / MDIFrame.java @ 9209

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.event.ActionEvent;
49
import java.awt.event.ActionListener;
50
import java.awt.event.ComponentEvent;
51
import java.awt.event.ComponentListener;
52
import java.awt.event.ContainerEvent;
53
import java.awt.event.ContainerListener;
54
import java.awt.event.MouseAdapter;
55
import java.awt.event.MouseEvent;
56
import java.awt.event.WindowAdapter;
57
import java.awt.event.WindowEvent;
58
import java.io.FileNotFoundException;
59
import java.net.URL;
60
import java.util.ArrayList;
61
import java.util.HashMap;
62
import java.util.Iterator;
63
import java.util.NoSuchElementException;
64
import java.util.Vector;
65

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

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

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

    
100

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
212
                this.toolBars.addContainerListener(this);
213

    
214
                pack();
215

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

    
221
                mdiManager.init(this);
222
        }
223

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

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

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

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

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

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

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

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

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

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

    
283
                }
284

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

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

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

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

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

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

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

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

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

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

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

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

    
349
                jtb.add(btn);
350

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

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

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

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

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

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

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

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

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

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

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

    
410
                menuPadre = createMenus(temp, menuPadre);
411

    
412
                return menuPadre;
413
        }
414

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

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

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

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

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

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

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

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

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

    
486
                nombres.remove(0);
487

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

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

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

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

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

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

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

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

    
553
                        nombres.remove(0);
554

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

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

    
569
                int toolHeight = 0;
570

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

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

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

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

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

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

    
594
                toolBars.updateUI();
595
        }
596

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
724
                if (menu.getKey() != null) {
725
                        nuevoMenu.setAccelerator(KeyStroke.getKeyStroke(KeyMapping.getKey(
726
                                                menu.getKey().charAt(0)), ActionEvent.ALT_MASK));
727
                }
728

    
729
                nuevoMenu.setActionCommand(menu.getActionCommand());
730

    
731
                if (menu.getTooltip() != null) {
732
                        nuevoMenu.setToolTip(ps.getText(menu.getTooltip()));
733
                }
734

    
735
                if (menu.getEnableText() != null) {
736
                        nuevoMenu.setEnableText(ps.getText(menu.getEnableText()));
737
                }
738

    
739
                nuevoMenu.setEnabled(true);
740
                nuevoMenu.setVisible(true);
741

    
742
                return nuevoMenu;
743
        }
744

    
745
        /**
746
         * Muestra u oculta el menu de nombre 'name'
747
         *
748
         * @param name Nombre del menu que se quiere mostrar
749
         * @param x Evento de raton
750
         * @param y DOCUMENT ME!
751
         * @param c DOCUMENT ME!
752
         */
753
        private void showPopupMenu(String name, int x, int y, Component c) {
754
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
755

    
756
                if (menu != null) {
757
                        menu.show(c, x, y);
758
                }
759
        }
760

    
761
        /**
762
         * DOCUMENT ME!
763
         *
764
         * @param name DOCUMENT ME!
765
         * @param listener DOCUMENT ME!
766
         */
767
        public void removePopupMenuListener(String name, ActionListener listener) {
768
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
769

    
770
                if (menu != null) {
771
                        Component[] jmenuitems = menu.getComponents();
772

    
773
                        for (int i = 0; i < jmenuitems.length; i++) {
774
                                if (jmenuitems[i] instanceof JMenuItem) {
775
                                        ((JMenuItem) jmenuitems[i]).removeActionListener(listener);
776
                                }
777
                        }
778
                }
779
        }
780

    
781
        /**
782
         * DOCUMENT ME!
783
         *
784
         * @param popupName
785
         * @param c DOCUMENT ME!
786
         * @param listener
787
         * @param loader
788
         */
789
        public void addPopupMenuListener(String popupName, Component c,
790
                ActionListener listener, PluginClassLoader loader) {
791
                final String name = getName(popupName, loader);
792

    
793
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
794

    
795
                if (menu != null) {
796
                        Component[] jmenuitems = menu.getComponents();
797

    
798
                        for (int i = 0; i < jmenuitems.length; i++) {
799
                                if (jmenuitems[i] instanceof JMenuItem) {
800
                                        ((JMenuItem) jmenuitems[i]).addActionListener(listener);
801
                                }
802
                        }
803
                }
804

    
805
                c.addMouseListener(new MouseAdapter() {
806
                                public void mousePressed(MouseEvent e) {
807
                                        if (e.isPopupTrigger()) {
808
                                                showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
809
                                        }
810
                                }
811

    
812
                                public void mouseReleased(MouseEvent e) {
813
                                        if (e.isPopupTrigger()) {
814
                                                showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
815
                                        }
816
                                }
817
                        });
818
        }
819

    
820
        /**
821
         * Itera por los controles preguntando a las extensiones si estos est?n
822
         * habilitados y visibles
823
         *
824
         * @throws RuntimeException DOCUMENT ME!
825
         */
826
        public void enableControls() {
827
                if (!SwingUtilities.isEventDispatchThread()) {
828
                        throw new RuntimeException("No Event Dispatch Thread");
829
                }
830

    
831
                Iterator e = classesExtensions.values().iterator();
832
                HashMap estadoExtensiones = new HashMap();
833
                HashMap visibilidadExtensiones = new HashMap();
834

    
835
                while (e.hasNext()) {
836
                        ExtensionDecorator ext = (ExtensionDecorator) e.next();
837

    
838
                        try {
839
                                if (estadoExtensiones.get(ext) == null) {
840
                                        boolean b;
841
                                        if (ext.getVisibility() == ExtensionDecorator.ALWAYS_VISIBLE)
842
                                                b = true;
843
                                        else if (ext.getVisibility() == ExtensionDecorator.ALWAYS_INVISIBLE)
844
                                                b = false;
845
                                        else {
846
                                                if (PluginServices.getExclusiveUIExtension() == null) {
847
                                                        b = ext.isVisible();
848
                                                } else {
849
                                                        b = PluginServices.getExclusiveUIExtension().isVisible(ext.getExtension());
850
                                                }
851
                                        }
852
                                        Boolean visible = new Boolean(b);
853
                                        Boolean enabled = new Boolean(false);
854

    
855
                                        if (visible.booleanValue()) {
856
                                                if (PluginServices.getExclusiveUIExtension() == null) {
857
                                                        enabled = new Boolean(ext.isEnabled());
858
                                                }else {
859
                                                        enabled = new Boolean(PluginServices.getExclusiveUIExtension().isEnabled(ext.getExtension()));
860
                                                }
861
                                                
862
                                        }
863

    
864
                                        estadoExtensiones.put(ext, enabled);
865
                                        visibilidadExtensiones.put(ext, visible);
866
                                }
867
                        } catch (Throwable e1) {
868
                                NotificationManager.addError(Messages.getString(
869
                                                "MDIFrame.Error_no_capturado_por_el_usuario"), e1);
870
                                estadoExtensiones.put(ext, Boolean.FALSE);
871
                        }
872
                }
873

    
874
                //Se habilitan y deshabilitan los controles
875
                e = controlClass.keySet().iterator();
876

    
877
                while (e.hasNext()) {
878
                        JComponent control = (JComponent) e.next();
879

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

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

    
899
                //Se ocultan las barras que no tienen herramientas
900
                Iterator it = toolBarMap.values().iterator();
901

    
902
                while (it.hasNext()) {
903
                        SelectableToolBar t = (SelectableToolBar) it.next();
904
                        boolean todosOcultos = true;
905

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

    
913
                        if (todosOcultos) {
914
                                t.setVisible(false);
915
                        } else {
916
                                t.setVisible(true);
917
                        }
918
                }
919

    
920
                if (mdiManager != null) {
921
                        JPanel f = (JPanel) mdiManager.getActiveWindow();
922

    
923
                        if (f != null) {
924
                                if (lastLabelClass != f.getClass()) {
925
                                        lastLabelClass = f.getClass();
926

    
927
                                        Label[] lbls = (Label[]) classLabels.get(lastLabelClass);
928

    
929
                                        if (lbls != null) {
930
                                                bEstado.setLabelSet(lbls);
931
                                        }
932
                                }
933
                        }
934
                }
935

    
936
                ajustarToolBar();
937

    
938
                showMemory();
939
        }
940

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

    
952
                //Si no tiene hijos se devuelve su visibilidad
953
                if (submenus.length == 0) {
954
                        return menu.getComponent().isVisible();
955
                }
956

    
957
                /*
958
                 * Si tiene hijos se devuelve true si alg?no de ellos es visible,
959
                 * pero se itera por todos ellos
960
                 */
961
                boolean visible = false;
962

    
963
                for (int i = 0; i < submenus.length; i++) {
964
                        if (ocultarMenus(submenus[i])) {
965
                                if (!(menu instanceof JPopupMenu)) {
966
                                        menu.getComponent().setVisible(true);
967
                                }
968

    
969
                                visible = true;
970
                        }
971
                }
972

    
973
                if (visible) {
974
                        return true;
975
                }
976

    
977
                menu.getComponent().setVisible(false);
978

    
979
                return false;
980
        }
981

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

    
991
        /**
992
         * DOCUMENT ME!
993
         *
994
         * @return
995
         */
996
        public MDIManager getMDIManager() {
997
                return mdiManager;
998
        }
999

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

    
1021
    }
1022

    
1023
        /**
1024
         * DOCUMENT ME!
1025
         *
1026
         * @param clase
1027
         * @param label
1028
         */
1029
        public void setLabels(Class clase, Label[] label) {
1030
                classLabels.put(clase, label);
1031
        }
1032

    
1033
        public void addStatusBarControl(Class extensionClass, IControl control) {
1034
                control.addActionListener(this);
1035
                bEstado.addControl(control.getName(), (Component)control);
1036
                controlClass.put(control, extensionClass);
1037
        }
1038

    
1039
        /**
1040
         * @see com.iver.andami.ui.mdiFrame.MainFrame#removeMenu(com.iver.andami.plugins.config.generate.Menu)
1041
         */
1042
        public void removeMenu(Menu menu) {
1043
                JMenuItem delete = (JMenuItem) infoCodedMenus.get(menu);
1044

    
1045
                if (delete == null) {
1046
                        throw new NoSuchElementException(menu.getText());
1047
                }
1048

    
1049
                delete.getParent().remove(delete);
1050
                infoCodedMenus.remove(menu);
1051
        }
1052

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

    
1061
                //Se registra y a?ade el menu
1062
                JMenuItem nuevoMenu = createJMenuItem(loader, menu);
1063
                nuevoMenu.addMouseListener(tooltipListener);
1064
                nuevoMenu.addActionListener(listener);
1065
                menuPadre.add(nuevoMenu);
1066

    
1067
                infoCodedMenus.put(menu, nuevoMenu);
1068
        }
1069

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

    
1078
                for (int i = 0; i < menu.length; i++) {
1079
                        menu[i] = ps.getText(menu[i]);
1080
                }
1081

    
1082
                JMenu menuPadre = null;
1083

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

    
1091
                if (menuPadre == null) {
1092
                        throw new NoSuchMenuException(menu[0]);
1093
                }
1094

    
1095
                Vector nombres = new Vector();
1096

    
1097
                for (int i = 1; i < menu.length; i++) {
1098
                        nombres.add(menu[i]);
1099
                }
1100

    
1101
                javax.swing.JMenuItem m = getMenu(nombres, menuPadre);
1102

    
1103
                if (m != null) {
1104
                        m.setText(newName);
1105
                }else{
1106
                        throw new NoSuchMenuException();
1107
                }
1108
        }
1109

    
1110
        /**
1111
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
1112
         */
1113
        public void componentHidden(ComponentEvent arg0) {
1114
        }
1115

    
1116
        /**
1117
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
1118
         */
1119
        public void componentMoved(ComponentEvent arg0) {
1120
        }
1121

    
1122
        /**
1123
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
1124
         */
1125
        public void componentResized(ComponentEvent arg0) {
1126
                ajustarToolBar();
1127
                bEstado.setFixedLabelWidth(this.getWidth() * 0.3);
1128
        }
1129

    
1130
        /**
1131
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
1132
         */
1133
        public void componentShown(ComponentEvent arg0) {
1134
        }
1135

    
1136
        /**
1137
         * @see java.awt.event.ContainerListener#componentAdded(java.awt.event.ContainerEvent)
1138
         */
1139
        public void componentAdded(ContainerEvent arg0) {
1140
                ajustarToolBar();
1141
        }
1142

    
1143
        /**
1144
         * @see java.awt.event.ContainerListener#componentRemoved(java.awt.event.ContainerEvent)
1145
         */
1146
        public void componentRemoved(ContainerEvent arg0) {
1147
                ajustarToolBar();
1148
        }
1149

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

    
1164
                        String texto = null;
1165
                        texto = control.getToolTipText();
1166

    
1167
                        if (texto != null) {
1168
                                bEstado.setInfoTextTemporal(texto);
1169
                        }
1170
                }
1171

    
1172
                /**
1173
                 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1174
                 */
1175
                public void mouseExited(MouseEvent arg0) {
1176
                        bEstado.restaurarTexto();
1177
                }
1178

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

    
1193
    public String getSelectedTool() {
1194
        return selectedTool;
1195
    }
1196

    
1197

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

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

    
1224
        }
1225

    
1226
        return null;
1227
    }
1228
}