Statistics
| Revision:

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

History | View | Annotate | Download (33.6 KB)

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

    
862
                                        if (visible.booleanValue()) {
863
                                                if (PluginServices.getExclusiveUIExtension() == null) {
864
                                                        enabled = new Boolean(ext.isEnabled());
865
                                                }else {
866
                                                        enabled = new Boolean(PluginServices.getExclusiveUIExtension().isEnabled(ext.getExtension()));
867
                                                }
868
                                                
869
                                        }
870

    
871
                                        estadoExtensiones.put(ext, enabled);
872
                                        visibilidadExtensiones.put(ext, visible);
873
                                }
874
                        } catch (Throwable e1) {
875
                                NotificationManager.addError(Messages.getString(
876
                                                "MDIFrame.Error_no_capturado_por_el_usuario"), e1);
877
                                estadoExtensiones.put(ext, Boolean.FALSE);
878
                        }
879
                }
880

    
881
                //Se habilitan y deshabilitan los controles
882
                e = controlClass.keySet().iterator();
883

    
884
                while (e.hasNext()) {
885
                        JComponent control = (JComponent) e.next();
886

    
887
                        try {
888
                                com.iver.andami.plugins.IExtension ext = (com.iver.andami.plugins.IExtension) classesExtensions.get((Class) controlClass.get(
889
                                                        control));
890
                                boolean enabled = ((Boolean) estadoExtensiones.get(ext)).booleanValue();
891
                                boolean visible = ((Boolean) visibilidadExtensiones.get(ext)).booleanValue();
892
                                control.setEnabled(enabled);
893
                                control.setVisible(visible);
894
                        } catch (Exception ex) {
895
                                control.setEnabled(false);
896
                                control.setVisible(false);
897
                        }
898
                }
899

    
900
                //Se itera por los men?es para ocultar los que no tengan hijos visibles
901
                for (int i = 0; i < menuBar.getMenuCount(); i++) {
902
                        MenuElement menu = menuBar.getMenu(i);
903
                        ocultarMenus(menu);
904
                }
905

    
906
                //Se ocultan las barras que no tienen herramientas
907
                Iterator it = toolBarMap.values().iterator();
908

    
909
                while (it.hasNext()) {
910
                        SelectableToolBar t = (SelectableToolBar) it.next();
911
                        boolean todosOcultos = true;
912

    
913
                        for (int i = 0; i < t.getComponentCount(); i++) {
914
                                if (!(t.getComponent(i) instanceof JSeparator) // separators doesn't matter
915
                                                && t.getComponent(i).isVisible()) {
916
                                        todosOcultos = false;
917
                                }
918
                        }
919

    
920
                        if (todosOcultos) {
921
                                t.setVisible(false);
922
                        } else {
923
                                t.setVisible(true);
924
                        }
925
                }
926

    
927
                if (mdiManager != null) {
928
                        JPanel f = (JPanel) mdiManager.getActiveWindow();
929

    
930
                        if (f != null) {
931
                                if (lastLabelClass != f.getClass()) {
932
                                        lastLabelClass = f.getClass();
933

    
934
                                        Label[] lbls = (Label[]) classLabels.get(lastLabelClass);
935

    
936
                                        if (lbls != null) {
937
                                                bEstado.setLabelSet(lbls);
938
                                        }
939
                                }
940
                        }
941
                }
942

    
943
                ajustarToolBar();
944

    
945
                showMemory();
946
        }
947

    
948
        /**
949
         * Establece la visibilidad de un menu y todos sus descendientes en la
950
         * jerarquia teniendo en cuenta la visibilidad de todos los submenus.
951
         *
952
         * @param menu Menu que se quiere visualizar
953
         *
954
         * @return Devuelve true si el menu es visible y false en caso contrario
955
         */
956
        private boolean ocultarMenus(MenuElement menu) {
957
                MenuElement[] submenus = menu.getSubElements();
958

    
959
                //Si no tiene hijos se devuelve su visibilidad
960
                if (submenus.length == 0) {
961
                        return menu.getComponent().isVisible();
962
                }
963

    
964
                /*
965
                 * Si tiene hijos se devuelve true si alg?no de ellos es visible,
966
                 * pero se itera por todos ellos
967
                 */
968
                boolean visible = false;
969

    
970
                for (int i = 0; i < submenus.length; i++) {
971
                        if (ocultarMenus(submenus[i])) {
972
                                if (!(menu instanceof JPopupMenu)) {
973
                                        menu.getComponent().setVisible(true);
974
                                }
975

    
976
                                visible = true;
977
                        }
978
                }
979

    
980
                if (visible) {
981
                        return true;
982
                }
983

    
984
                menu.getComponent().setVisible(false);
985

    
986
                return false;
987
        }
988

    
989
        /**
990
         * Muestra la memoria consumida por el programa
991
         */
992
        private void showMemory() {
993
                Runtime r = Runtime.getRuntime();
994
                long mem = r.totalMemory() - r.freeMemory();
995
                logger.debug("Memoria total: " + mem);
996
        }
997

    
998
        /**
999
         * DOCUMENT ME!
1000
         *
1001
         * @return
1002
         */
1003
        public MDIManager getMDIManager() {
1004
                return mdiManager;
1005
        }
1006

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

    
1028
    }
1029

    
1030
        /**
1031
         * DOCUMENT ME!
1032
         *
1033
         * @param clase
1034
         * @param label
1035
         */
1036
        public void setLabels(Class clase, Label[] label) {
1037
                classLabels.put(clase, label);
1038
        }
1039

    
1040
        public void addStatusBarControl(Class extensionClass, IControl control) {
1041
                control.addActionListener(this);
1042
                bEstado.addControl(control.getName(), (Component)control);
1043
                controlClass.put(control, extensionClass);
1044
        }
1045

    
1046
        /**
1047
         * @see com.iver.andami.ui.mdiFrame.MainFrame#removeMenu(com.iver.andami.plugins.config.generate.Menu)
1048
         */
1049
        public void removeMenu(Menu menu) {
1050
                JMenuItem delete = (JMenuItem) infoCodedMenus.get(menu);
1051

    
1052
                if (delete == null) {
1053
                        throw new NoSuchElementException(menu.getText());
1054
                }
1055

    
1056
                delete.getParent().remove(delete);
1057
                infoCodedMenus.remove(menu);
1058
        }
1059

    
1060
        /**
1061
         * @see com.iver.andami.ui.mdiFrame.MainFrame#addMenu(com.iver.andami.plugins.config.generate.Menu,
1062
         *                 java.awt.event.ActionListener, PluginClassLoader)
1063
         */
1064
        public void addMenu(Menu menu, ActionListener listener,
1065
                PluginClassLoader loader) {
1066
                JMenu menuPadre = createMenuAncestors(menu, loader);
1067

    
1068
                //Se registra y a?ade el menu
1069
                JMenuItem nuevoMenu = createJMenuItem(loader, menu);
1070
                nuevoMenu.addMouseListener(tooltipListener);
1071
                nuevoMenu.addActionListener(listener);
1072
                menuPadre.add(nuevoMenu);
1073

    
1074
                infoCodedMenus.put(menu, nuevoMenu);
1075
        }
1076

    
1077
        /**
1078
         * @see com.iver.andami.ui.mdiFrame.MainFrame#changeMenuName(java.lang.String[],
1079
         *                 String, com.iver.andami.plugins.PluginClassLoader)
1080
         */
1081
        public void changeMenuName(String[] menu, String newName,
1082
                PluginClassLoader loader) {
1083
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
1084

    
1085
                for (int i = 0; i < menu.length; i++) {
1086
                        menu[i] = ps.getText(menu[i]);
1087
                }
1088

    
1089
                JMenu menuPadre = null;
1090

    
1091
                //Se busca el padre en la menuBar
1092
                for (int i = 0; i < menuBar.getMenuCount(); i++) {
1093
                        if (menuBar.getMenu(i).getText().compareToIgnoreCase(menu[0]) == 0) {
1094
                                menuPadre = (JMenu) menuBar.getMenu(i);
1095
                        }
1096
                }
1097

    
1098
                if (menuPadre == null) {
1099
                        throw new NoSuchMenuException(menu[0]);
1100
                }
1101

    
1102
                Vector nombres = new Vector();
1103

    
1104
                for (int i = 1; i < menu.length; i++) {
1105
                        nombres.add(menu[i]);
1106
                }
1107

    
1108
                javax.swing.JMenuItem m = getMenu(nombres, menuPadre);
1109

    
1110
                if (m != null) {
1111
                        m.setText(newName);
1112
                }else{
1113
                        throw new NoSuchMenuException();
1114
                }
1115
        }
1116

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

    
1123
        /**
1124
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
1125
         */
1126
        public void componentMoved(ComponentEvent arg0) {
1127
        }
1128

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

    
1136
        /**
1137
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
1138
         */
1139
        public void componentShown(ComponentEvent arg0) {
1140
        }
1141

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

    
1149
        /**
1150
         * @see java.awt.event.ContainerListener#componentRemoved(java.awt.event.ContainerEvent)
1151
         */
1152
        public void componentRemoved(ContainerEvent arg0) {
1153
                ajustarToolBar();
1154
        }
1155

    
1156
        /**
1157
         * DOCUMENT ME!
1158
         *
1159
         * @author $author$
1160
         * @version $Revision: 10444 $
1161
         */
1162
        public class TooltipListener extends MouseAdapter {
1163
                /**
1164
                 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1165
                 */
1166
                public void mouseEntered(MouseEvent e) {
1167
                        JComponent control = (JComponent) e.getSource();
1168
                        EnableTextSupport ets = (EnableTextSupport) e.getSource();
1169

    
1170
                        String texto = null;
1171
                        texto = control.getToolTipText();
1172

    
1173
                        if (texto != null) {
1174
                                bEstado.setInfoTextTemporal(texto);
1175
                        }
1176
                }
1177

    
1178
                /**
1179
                 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1180
                 */
1181
                public void mouseExited(MouseEvent arg0) {
1182
                        bEstado.restaurarTexto();
1183
                }
1184

    
1185
                /**
1186
                 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1187
                 */
1188
                public void mousePressed(MouseEvent e) {
1189
                        bEstado.restaurarTexto();
1190
                }
1191
        }
1192
        public String getTitlePrefix() {
1193
                return titlePrefix;
1194
        }
1195
        public void setTitlePrefix(String titlePrefix) {
1196
                this.titlePrefix = titlePrefix;
1197
        }
1198

    
1199
    public String getSelectedTool() {
1200
        return selectedTool;
1201
    }
1202

    
1203

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

    
1215
//        JComponent control = (JComponent) controlClass.get(name);
1216
//        if (control != null) return control;
1217
//        SelectableToolBar t = (SelectableToolBar) toolBarMap.get(name);
1218
//        if (t != null) return t;
1219
        while (e.hasNext()) {
1220
            JComponent control = (JComponent) e.next();
1221
            String nameCtrl = control.getName();
1222
            if (nameCtrl != null)
1223
            {
1224
                    if (nameCtrl.compareTo(name) == 0)
1225
                            return control;
1226
            }
1227
        }
1228
        Iterator it = toolBarMap.values().iterator();
1229
        while (it.hasNext()) {
1230
            SelectableToolBar t = (SelectableToolBar) it.next();
1231
            String nameCtrl = t.getName();
1232
            if (nameCtrl != null)
1233
                    if (nameCtrl.compareTo(name) == 0)
1234
                            return t;
1235

    
1236
        }
1237

    
1238
        return null;
1239
    }
1240

    
1241
    public JMenuBar getJMenuBar() {
1242
            return menuBar;
1243
    }
1244
}