Statistics
| Revision:

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

History | View | Annotate | Download (32.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.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: 8745 $
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
                if (!SwingUtilities.isEventDispatchThread()) {
168
                        throw new RuntimeException("Not Event Dispatch Thread");
169
                }
170

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

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

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

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

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

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

    
211
                this.toolBars.addContainerListener(this);
212

    
213
                pack();
214

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

    
220
                mdiManager.init(this);
221
        }
222

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

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

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

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

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

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

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

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

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

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

    
282
                }
283

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

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

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

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

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

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

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

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

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

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

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

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

    
348
                jtb.add(btn);
349

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

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

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

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

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

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

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

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

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

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

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

    
409
                menuPadre = createMenus(temp, menuPadre);
410

    
411
                return menuPadre;
412
        }
413

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

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

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

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

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

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

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

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

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

    
485
                nombres.remove(0);
486

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

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

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

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

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

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

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

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

    
552
                        nombres.remove(0);
553

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

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

    
568
                int toolHeight = 0;
569

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

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

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

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

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

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

    
593
                toolBars.updateUI();
594
        }
595

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
741
                return nuevoMenu;
742
        }
743

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
837
                        try {
838
                                if (estadoExtensiones.get(ext) == null) {
839
                                        boolean b;
840
                                        if (ext.getVisibility() == ExtensionDecorator.ALWAYS_VISIBLE)
841
                                                b = true;
842
                                        else if (ext.getVisibility() == ExtensionDecorator.ALWAYS_INVISIBLE)
843
                                                b = false;
844
                                        else b = ext.isVisible();
845
                                        Boolean visible = new Boolean(b);
846
                                        Boolean enabled = new Boolean(false);
847

    
848
                                        if (visible.booleanValue()) {
849
                                                enabled = new Boolean(ext.isEnabled());
850
                                        }
851

    
852
                                        estadoExtensiones.put(ext, enabled);
853
                                        visibilidadExtensiones.put(ext, visible);
854
                                }
855
                        } catch (Throwable e1) {
856
                                NotificationManager.addError(Messages.getString(
857
                                                "MDIFrame.Error_no_capturado_por_el_usuario"), e1);
858
                                estadoExtensiones.put(ext, Boolean.FALSE);
859
                        }
860
                }
861

    
862
                //Se habilitan y deshabilitan los controles
863
                e = controlClass.keySet().iterator();
864

    
865
                while (e.hasNext()) {
866
                        JComponent control = (JComponent) e.next();
867

    
868
                        try {
869
                                com.iver.andami.plugins.IExtension ext = (com.iver.andami.plugins.IExtension) classesExtensions.get((Class) controlClass.get(
870
                                                        control));
871
                                boolean enabled = ((Boolean) estadoExtensiones.get(ext)).booleanValue();
872
                                boolean visible = ((Boolean) visibilidadExtensiones.get(ext)).booleanValue();
873
                                control.setEnabled(enabled);
874
                                control.setVisible(visible);
875
                        } catch (Exception ex) {
876
                                control.setEnabled(false);
877
                                control.setVisible(false);
878
                        }
879
                }
880

    
881
                //Se itera por los men?es para ocultar los que no tengan hijos visibles
882
                for (int i = 0; i < menuBar.getMenuCount(); i++) {
883
                        MenuElement menu = menuBar.getMenu(i);
884
                        ocultarMenus(menu);
885
                }
886

    
887
                //Se ocultan las barras que no tienen herramientas
888
                Iterator it = toolBarMap.values().iterator();
889

    
890
                while (it.hasNext()) {
891
                        SelectableToolBar t = (SelectableToolBar) it.next();
892
                        boolean todosOcultos = true;
893

    
894
                        for (int i = 0; i < t.getComponentCount(); i++) {
895
                                if (!(t.getComponent(i) instanceof JSeparator) // separators doesn't matter
896
                                                && t.getComponent(i).isVisible()) {
897
                                        todosOcultos = false;
898
                                }
899
                        }
900

    
901
                        if (todosOcultos) {
902
                                t.setVisible(false);
903
                        } else {
904
                                t.setVisible(true);
905
                        }
906
                }
907

    
908
                if (mdiManager != null) {
909
                        JPanel f = (JPanel) mdiManager.getActiveWindow();
910

    
911
                        if (f != null) {
912
                                if (lastLabelClass != f.getClass()) {
913
                                        lastLabelClass = f.getClass();
914

    
915
                                        Label[] lbls = (Label[]) classLabels.get(lastLabelClass);
916

    
917
                                        if (lbls != null) {
918
                                                bEstado.setLabelSet(lbls);
919
                                        }
920
                                }
921
                        }
922
                }
923

    
924
                ajustarToolBar();
925

    
926
                showMemory();
927
        }
928

    
929
        /**
930
         * Establece la visibilidad de un menu y todos sus descendientes en la
931
         * jerarquia teniendo en cuenta la visibilidad de todos los submenus.
932
         *
933
         * @param menu Menu que se quiere visualizar
934
         *
935
         * @return Devuelve true si el menu es visible y false en caso contrario
936
         */
937
        private boolean ocultarMenus(MenuElement menu) {
938
                MenuElement[] submenus = menu.getSubElements();
939

    
940
                //Si no tiene hijos se devuelve su visibilidad
941
                if (submenus.length == 0) {
942
                        return menu.getComponent().isVisible();
943
                }
944

    
945
                /*
946
                 * Si tiene hijos se devuelve true si alg?no de ellos es visible,
947
                 * pero se itera por todos ellos
948
                 */
949
                boolean visible = false;
950

    
951
                for (int i = 0; i < submenus.length; i++) {
952
                        if (ocultarMenus(submenus[i])) {
953
                                if (!(menu instanceof JPopupMenu)) {
954
                                        menu.getComponent().setVisible(true);
955
                                }
956

    
957
                                visible = true;
958
                        }
959
                }
960

    
961
                if (visible) {
962
                        return true;
963
                }
964

    
965
                menu.getComponent().setVisible(false);
966

    
967
                return false;
968
        }
969

    
970
        /**
971
         * Muestra la memoria consumida por el programa
972
         */
973
        private void showMemory() {
974
                Runtime r = Runtime.getRuntime();
975
                long mem = r.totalMemory() - r.freeMemory();
976
                logger.debug("Memoria total: " + mem);
977
        }
978

    
979
        /**
980
         * DOCUMENT ME!
981
         *
982
         * @return
983
         */
984
        public MDIManager getMDIManager() {
985
                return mdiManager;
986
        }
987

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

    
1009
    }
1010

    
1011
        /**
1012
         * DOCUMENT ME!
1013
         *
1014
         * @param clase
1015
         * @param label
1016
         */
1017
        public void setLabels(Class clase, Label[] label) {
1018
                classLabels.put(clase, label);
1019
        }
1020

    
1021
        public void addStatusBarControl(Class extensionClass, IControl control) {
1022
                control.addActionListener(this);
1023
                bEstado.addControl(control.getName(), (Component)control);
1024
                controlClass.put(control, extensionClass);
1025
        }
1026

    
1027
        /**
1028
         * @see com.iver.andami.ui.mdiFrame.MainFrame#removeMenu(com.iver.andami.plugins.config.generate.Menu)
1029
         */
1030
        public void removeMenu(Menu menu) {
1031
                JMenuItem delete = (JMenuItem) infoCodedMenus.get(menu);
1032

    
1033
                if (delete == null) {
1034
                        throw new NoSuchElementException(menu.getText());
1035
                }
1036

    
1037
                delete.getParent().remove(delete);
1038
                infoCodedMenus.remove(menu);
1039
        }
1040

    
1041
        /**
1042
         * @see com.iver.andami.ui.mdiFrame.MainFrame#addMenu(com.iver.andami.plugins.config.generate.Menu,
1043
         *                 java.awt.event.ActionListener, PluginClassLoader)
1044
         */
1045
        public void addMenu(Menu menu, ActionListener listener,
1046
                PluginClassLoader loader) {
1047
                JMenu menuPadre = createMenuAncestors(menu, loader);
1048

    
1049
                //Se registra y a?ade el menu
1050
                JMenuItem nuevoMenu = createJMenuItem(loader, menu);
1051
                nuevoMenu.addMouseListener(tooltipListener);
1052
                nuevoMenu.addActionListener(listener);
1053
                menuPadre.add(nuevoMenu);
1054

    
1055
                infoCodedMenus.put(menu, nuevoMenu);
1056
        }
1057

    
1058
        /**
1059
         * @see com.iver.andami.ui.mdiFrame.MainFrame#changeMenuName(java.lang.String[],
1060
         *                 String, com.iver.andami.plugins.PluginClassLoader)
1061
         */
1062
        public void changeMenuName(String[] menu, String newName,
1063
                PluginClassLoader loader) {
1064
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
1065

    
1066
                for (int i = 0; i < menu.length; i++) {
1067
                        menu[i] = ps.getText(menu[i]);
1068
                }
1069

    
1070
                JMenu menuPadre = null;
1071

    
1072
                //Se busca el padre en la menuBar
1073
                for (int i = 0; i < menuBar.getMenuCount(); i++) {
1074
                        if (menuBar.getMenu(i).getText().compareToIgnoreCase(menu[0]) == 0) {
1075
                                menuPadre = (JMenu) menuBar.getMenu(i);
1076
                        }
1077
                }
1078

    
1079
                if (menuPadre == null) {
1080
                        throw new NoSuchMenuException(menu[0]);
1081
                }
1082

    
1083
                Vector nombres = new Vector();
1084

    
1085
                for (int i = 1; i < menu.length; i++) {
1086
                        nombres.add(menu[i]);
1087
                }
1088

    
1089
                javax.swing.JMenuItem m = getMenu(nombres, menuPadre);
1090

    
1091
                if (m != null) {
1092
                        m.setText(newName);
1093
                }else{
1094
                        throw new NoSuchMenuException();
1095
                }
1096
        }
1097

    
1098
        /**
1099
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
1100
         */
1101
        public void componentHidden(ComponentEvent arg0) {
1102
        }
1103

    
1104
        /**
1105
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
1106
         */
1107
        public void componentMoved(ComponentEvent arg0) {
1108
        }
1109

    
1110
        /**
1111
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
1112
         */
1113
        public void componentResized(ComponentEvent arg0) {
1114
                ajustarToolBar();
1115
                bEstado.setFixedLabelWidth(this.getWidth() * 0.3);
1116
        }
1117

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

    
1124
        /**
1125
         * @see java.awt.event.ContainerListener#componentAdded(java.awt.event.ContainerEvent)
1126
         */
1127
        public void componentAdded(ContainerEvent arg0) {
1128
                ajustarToolBar();
1129
        }
1130

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

    
1138
        /**
1139
         * DOCUMENT ME!
1140
         *
1141
         * @author $author$
1142
         * @version $Revision: 8745 $
1143
         */
1144
        public class TooltipListener extends MouseAdapter {
1145
                /**
1146
                 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1147
                 */
1148
                public void mouseEntered(MouseEvent e) {
1149
                        JComponent control = (JComponent) e.getSource();
1150
                        EnableTextSupport ets = (EnableTextSupport) e.getSource();
1151

    
1152
                        String texto = null;
1153
                        texto = control.getToolTipText();
1154

    
1155
                        if (texto != null) {
1156
                                bEstado.setInfoTextTemporal(texto);
1157
                        }
1158
                }
1159

    
1160
                /**
1161
                 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1162
                 */
1163
                public void mouseExited(MouseEvent arg0) {
1164
                        bEstado.restaurarTexto();
1165
                }
1166

    
1167
                /**
1168
                 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1169
                 */
1170
                public void mousePressed(MouseEvent e) {
1171
                        bEstado.restaurarTexto();
1172
                }
1173
        }
1174
        public String getTitlePrefix() {
1175
                return titlePrefix;
1176
        }
1177
        public void setTitlePrefix(String titlePrefix) {
1178
                this.titlePrefix = titlePrefix;
1179
        }
1180

    
1181
    public String getSelectedTool() {
1182
        return selectedTool;
1183
    }
1184

    
1185

    
1186
    /**
1187
     * Get a previously added JComponent by name. For example
1188
     * you can use it if you need to obtain a JToolBar to
1189
     * add some customized component.
1190
     * @param name
1191
     * @return the JComponent or null if none has been found
1192
     */
1193
    public JComponent getComponentByName(String name)
1194
    {
1195
        Iterator e = controlClass.keySet().iterator();
1196

    
1197
        while (e.hasNext()) {
1198
            JComponent control = (JComponent) e.next();
1199
            String nameCtrl = control.getName();
1200
            if (nameCtrl != null)
1201
                    if (nameCtrl.compareTo(name) == 0)
1202
                            return control;
1203
        }
1204
        Iterator it = toolBarMap.values().iterator();
1205
        while (it.hasNext()) {
1206
            SelectableToolBar t = (SelectableToolBar) it.next();
1207
            String nameCtrl = t.getName();
1208
            if (nameCtrl != null)
1209
                    if (nameCtrl.compareTo(name) == 0)
1210
                            return t;
1211

    
1212
        }
1213

    
1214
        return null;
1215
    }
1216
}