Statistics
| Revision:

svn-gvsig-desktop / trunk / frameworks / _fwAndami / src / com / iver / andami / ui / mdiFrame / MDIFrame.java @ 2757

History | View | Annotate | Download (30.8 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 com.iver.andami.Launcher;
44
import com.iver.andami.PluginServices;
45
import com.iver.andami.messages.Messages;
46
import com.iver.andami.messages.NotificationManager;
47
import com.iver.andami.plugins.PluginClassLoader;
48
import com.iver.andami.plugins.config.generate.ActionTool;
49
import com.iver.andami.plugins.config.generate.Label;
50
import com.iver.andami.plugins.config.generate.Menu;
51
import com.iver.andami.plugins.config.generate.PopupMenu;
52
import com.iver.andami.plugins.config.generate.SelectableTool;
53
import com.iver.andami.plugins.config.generate.SkinExtensionType;
54
import com.iver.andami.plugins.config.generate.ToolBar;
55
import com.iver.andami.ui.mdiManager.MDIManager;
56
import com.iver.andami.ui.mdiManager.MDIManagerFactory;
57

    
58
import org.apache.log4j.Logger;
59

    
60
import java.awt.BorderLayout;
61
import java.awt.Component;
62
import java.awt.Cursor;
63
import java.awt.Dimension;
64
import java.awt.FlowLayout;
65
import java.awt.Insets;
66
import java.awt.event.ActionEvent;
67
import java.awt.event.ActionListener;
68
import java.awt.event.ComponentEvent;
69
import java.awt.event.ComponentListener;
70
import java.awt.event.ContainerEvent;
71
import java.awt.event.ContainerListener;
72
import java.awt.event.MouseAdapter;
73
import java.awt.event.MouseEvent;
74
import java.awt.event.WindowAdapter;
75
import java.awt.event.WindowEvent;
76

    
77
import java.net.URL;
78

    
79
import java.util.ArrayList;
80
import java.util.HashMap;
81
import java.util.Iterator;
82
import java.util.NoSuchElementException;
83
import java.util.Stack;
84
import java.util.Vector;
85

    
86
import javax.swing.AbstractButton;
87
import javax.swing.ImageIcon;
88
import javax.swing.JComponent;
89
import javax.swing.JFrame;
90
import javax.swing.JMenu;
91
import javax.swing.JMenuBar;
92
import javax.swing.JOptionPane;
93
import javax.swing.JPanel;
94
import javax.swing.JPopupMenu;
95
import javax.swing.JToolBar;
96
import javax.swing.KeyStroke;
97
import javax.swing.MenuElement;
98
import javax.swing.SwingUtilities;
99
import javax.swing.Timer;
100

    
101

    
102
/**
103
 * Frame principal de la aplicaci?n.
104
 *
105
 * @version $Revision: 2757 $
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
        /** ProgressListeners (ver interfaz com.iver.mdiApp.ui.ProgressListener) */
143
        private ArrayList progressListeners = new ArrayList();
144

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

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

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

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

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

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

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

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

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

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

    
205
                // Se a?ade la barra de estado a la aplicaci?n
206
                bEstado = new NewStatusBar();
207
                getContentPane().add(bEstado, BorderLayout.SOUTH);
208

    
209
                this.toolBars.addContainerListener(this);
210

    
211
                pack();
212

    
213
                this.setSize(500, 500);
214
                this.setExtendedState(MAXIMIZED_BOTH);
215

    
216
                mdiManager.init(this);
217
        }
218

    
219
        public void setTitle(String title) {
220
                super.setTitle(titlePrefix + ":" + title);
221
        }
222

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

    
241
                // Para traducir
242
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
243

    
244
                JToggleButton btn;
245
                URL image = loader.getResource(selectableTool.getIcon());
246

    
247
                if (image != null) {
248
                        btn = new JToggleButton(selectableTool.getText(),
249
                                        new ImageIcon(image));
250
                } else {
251
                        btn = new JToggleButton(selectableTool.getText());
252
                }
253

    
254
                btn.setMargin(new Insets(0, 0, 0, 0));
255
                btn.addMouseListener(tooltipListener);
256
                btn.addActionListener(this);
257
                btn.setFocusable(false);
258
                btn.setActionCommand(selectableTool.getActionCommand());
259
                btn.setToolTipText(selectableTool.getTooltip());
260
                btn.setEnabled(false);
261
                btn.setVisible(false);
262

    
263
                if (selectableTool.getIsDefault()) {
264
                        btn.setSelected(true);
265
            selectedTool = btn.getActionCommand();
266
                }
267

    
268
                String name = getName(toolBar.getName(), loader);
269

    
270
                SelectableToolBar jtb = (SelectableToolBar) toolBarMap.get(name);
271

    
272
                if (jtb == null) {
273
                        jtb = new SelectableToolBar(toolBar.getName());
274
                        jtb.setRollover(true);
275
                        toolBarMap.put(name, jtb);
276
                        toolBars.add(jtb);
277
                }
278

    
279
                jtb.addButton(selectableTool.getGroup(), btn);
280

    
281
                controlClass.put(btn, loader.loadClass(ext.getClassName()));
282

    
283
                if (selectableTool.getTooltip() != null) {
284
                        btn.setToolTip(ps.getText(selectableTool.getTooltip()));
285
                }
286

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

    
291
                if (selectableTool.getLast() == true) {
292
                        jtb.addSeparator();
293
                }
294
        }
295

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

    
313
                // Para traducir los textos que vengan
314
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
315

    
316
                JButton btn;
317
                URL image = loader.getResource(actionTool.getIcon());
318

    
319
                if (image != null) {
320
                        btn = new JButton(actionTool.getText(), new ImageIcon(image));
321
                } else {
322
                        btn = new JButton(actionTool.getText());
323
                }
324

    
325
                btn.setMargin(new Insets(0, 0, 0, 0));
326
                btn.addMouseListener(tooltipListener);
327
                btn.addActionListener(this);
328
                btn.setFocusable(false);
329
                btn.setActionCommand(actionTool.getActionCommand());
330
                btn.setEnabled(false);
331
                btn.setVisible(false);
332

    
333
                String name = getName(toolBar.getName(), loader);
334

    
335
                SelectableToolBar jtb = (SelectableToolBar) toolBarMap.get(name);
336

    
337
                if (jtb == null) {
338
                        jtb = new SelectableToolBar(toolBar.getName());
339
                        jtb.setRollover(true);
340
                        toolBarMap.put(name, jtb);
341
                        toolBars.add(jtb);
342
                }
343

    
344
                jtb.add(btn);
345

    
346
                controlClass.put(btn, loader.loadClass(ext.getClassName()));
347

    
348
                if (actionTool.getTooltip() != null) {
349
                        btn.setToolTip(ps.getText(actionTool.getTooltip()));
350
                }
351

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

    
356
                if (actionTool.getLast() == true) {
357
                        jtb.addSeparator();
358
                }
359
        }
360

    
361
        /**
362
         * Crea la estructura de men?s necesaria para a?adir el menu a la barra.
363
         * Devuelve el padre del cual deve colgar el menu que se pasa como
364
         * par?metro
365
         *
366
         * @param menu Menu cuya soporte se quiere a?adir
367
         * @param loader DOCUMENT ME!
368
         *
369
         * @return Padre del men? que se pasa como par?metro
370
         */
371
        private JMenu createMenuAncestors(Menu menu, PluginClassLoader loader) {
372
                JMenu menuPadre = null;
373

    
374
                String[] menues = menu.getText().split("/");
375
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
376

    
377
                for (int i = 0; i < menues.length; i++) {
378
                        menues[i] = ps.getText(menues[i]);
379
                }
380

    
381
                //Se busca el padre en la menuBar
382
                for (int i = 0; i < menuBar.getMenuCount(); i++) {
383
                        if (menuBar.getMenu(i).getText().compareToIgnoreCase(menues[0]) == 0) {
384
                                menuPadre = (JMenu) menuBar.getMenu(i);
385
                        }
386
                }
387

    
388
                //Si no se encuentra el padre se crea
389
                if (menuPadre == null) {
390
                        menuPadre = new JMenu(menues[0]);
391
                        menuBar.add(menuPadre);
392
                }
393

    
394
                //Se crea el resto de menus
395
                Vector temp = new Vector();
396

    
397
                for (int i = 1; i < (menues.length - 1); i++) {
398
                        temp.add(menues[i]);
399
                }
400

    
401
                menuPadre = createMenus(temp, menuPadre);
402

    
403
                return menuPadre;
404
        }
405

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

    
426
                JMenu menuPadre = createMenuAncestors(menu, loader);
427

    
428
                //Se registra y a?ade el menu
429
                JMenuItem nuevoMenu = createJMenuItem(loader, menu);
430
                nuevoMenu.addMouseListener(tooltipListener);
431
                nuevoMenu.addActionListener(this);
432
                menuPadre.add(nuevoMenu);
433

    
434
                controlClass.put(nuevoMenu, loader.loadClass(ext.getClassName()));
435
        }
436

    
437
        /**
438
         * Dado un array de nombres de menu traducidos, encuentra el  men?
439
         *
440
         * @param nombres DOCUMENT ME!
441
         * @param padre DOCUMENT ME!
442
         *
443
         * @return DOCUMENT ME!
444
         */
445
        private javax.swing.JMenuItem getMenu(Vector nombres, JMenu padre) {
446
                javax.swing.JMenuItem buscado = null;
447

    
448
                for (int i = 0; i < padre.getMenuComponentCount(); i++) {
449
                        javax.swing.JMenuItem hijo = (javax.swing.JMenuItem) padre.getMenuComponent(i);
450

    
451
                        if (hijo.getText().compareToIgnoreCase((String) nombres.get(0)) == 0) {
452
                                buscado = hijo;
453
                        }
454
                }
455

    
456
                //Si no se encuentra el menu
457
                if (buscado == null) {
458
                        return null;
459
                }
460

    
461
                nombres.remove(0);
462

    
463
                //Si se ha llegado al fin de la ruta completa
464
                if (nombres.isEmpty()) {
465
                        return buscado;
466
                } else {
467
                        if (buscado instanceof JMenu) {
468
                                return getMenu(nombres, (JMenu) buscado);
469
                        } else {
470
                                return null;
471
                        }
472
                }
473
        }
474

    
475
        /**
476
         * Crea la estructura de menus recursivamente. Por ejemplo, si se le pasa
477
         * en el par?metro nombres el array {"Search", "References", "Workspace"}
478
         * crear? un men? Search, un submen? del anterior que se llamar?
479
         * References y debajo de ?ste ?ltimo otro menu llamado Workspace
480
         *
481
         * @param nombres Array con los nombres de los men?s que se quieren crear
482
         * @param padre Menu padre de los men?s creados. Es ?til porque es un
483
         *                   algoritmo recursivo
484
         *
485
         * @return Devuelve el men? creado. Al final de toda la recursividad,
486
         *                    devolver? el men? de m?s abajo en la jerarqu?a
487
         *
488
         * @throws RuntimeException DOCUMENT ME!
489
         */
490
        private JMenu createMenus(Vector nombres, JMenu padre) {
491
                if (!SwingUtilities.isEventDispatchThread()) {
492
                        throw new RuntimeException("No Event Dispatch Thread");
493
                }
494

    
495
                //si no quedan nombres de menu por crear se vuelve: caso base
496
                if (nombres.size() == 0) {
497
                        return padre;
498
                }
499

    
500
                //Se busca el menu por si ya existiera para no crearlo otra vez
501
                JMenu buscado = null;
502

    
503
                for (int i = 0; i < padre.getMenuComponentCount(); i++) {
504
                        try {
505
                                JMenu hijo = (JMenu) padre.getMenuComponent(i);
506

    
507
                                if (hijo.getText().compareToIgnoreCase((String) nombres.get(0)) == 0) {
508
                                        buscado = hijo;
509
                                }
510
                        } catch (ClassCastException e) {
511
                                /*
512
                                 * Se ha encontrado un elemento hoja del arbol de men?es
513
                                 */
514
                        }
515
                }
516

    
517
                if (buscado != null) {
518
                        //Si lo hemos encontrado creamos el resto
519
                        nombres.remove(0);
520

    
521
                        return createMenus(nombres, buscado);
522
                } else {
523
                        //Si no lo hemos encontrado se crea el menu, se a?ade al padre
524
                        //y se crea el resto
525
                        JMenu menuPadre = new JMenu((String) nombres.get(0));
526
                        padre.add(menuPadre);
527

    
528
                        nombres.remove(0);
529

    
530
                        return createMenus(nombres, menuPadre);
531
                }
532
        }
533

    
534
        /**
535
         * M?todo invocado en respuesta a ciertos eventos de la interfaz que pueden
536
         * ocultar botones de las barras de herramientas y que redimensiona ?sta
537
         * de manera conveniente para que no se oculte ninguno
538
         */
539
        private void ajustarToolBar() {
540
                int margen = 8;
541
                int numFilas = 1;
542
                double acum = margen;
543

    
544
                int toolHeight = 0;
545

    
546
                for (int i = 0; i < toolBars.getComponentCount(); i++) {
547
                        Component c = toolBars.getComponent(i);
548

    
549
                        if (!c.isVisible()) {
550
                                continue;
551
                        }
552

    
553
                        double width = c.getPreferredSize().getWidth();
554
                        acum = acum + width;
555

    
556
                        if (acum > this.getWidth()) {
557
                                numFilas++;
558
                                acum = width + margen;
559
                        }
560

    
561
                        if (c.getPreferredSize().getHeight() > toolHeight) {
562
                                toolHeight = c.getPreferredSize().height;
563
                        }
564
                }
565

    
566
                toolBars.setPreferredSize(new Dimension(this.getWidth(),
567
                                (int) (numFilas * toolHeight)));
568

    
569
                toolBars.updateUI();
570
        }
571

    
572
        /**
573
         * DOCUMENT ME!
574
         *
575
         * @param classesExtensions
576
         */
577
        public void setClassesExtensions(HashMap classesExtensions) {
578
                this.classesExtensions = classesExtensions;
579
        }
580

    
581
        /**
582
         * M?todo de callback invocado cuando se selecciona un men? o un bot?n de
583
         * la barra de herramientas. Se busca la extensi?n asociada y se ejecuta
584
         *
585
         * @param e Evento producido
586
         */
587
        public void actionPerformed(ActionEvent e) {
588
                AbstractButton control = (AbstractButton) e.getSource();
589
                com.iver.andami.plugins.Extension ext = (com.iver.andami.plugins.Extension) classesExtensions.get((Class) controlClass.get(
590
                                        control));
591
                String actionCommand = control.getActionCommand();
592

    
593
                try {
594
                        ext.execute(actionCommand);
595
            if (control instanceof JToggleButton)
596
            {
597
                selectedTool = actionCommand;
598
            }
599
                } catch (RuntimeException t) {
600
                        NotificationManager.addError(Messages.getString(
601
                                        "MDIFrame.Error_no_capturado_por_el_usuario"), t);
602
                }
603

    
604
                enableControls();
605
                showMemory();
606
        }
607

    
608
        /**
609
         * DOCUMENT ME!
610
         *
611
         * @param name DOCUMENT ME!
612
         * @param loader DOCUMENT ME!
613
         *
614
         * @return DOCUMENT ME!
615
         */
616
        private String getName(String name, PluginClassLoader loader) {
617
                if (name.indexOf('.') == -1) {
618
                        return loader.getPluginName() + "." + name;
619
                } else {
620
                        return name;
621
                }
622
        }
623

    
624
        /**
625
         * DOCUMENT ME!
626
         *
627
         * @param loader DOCUMENT ME!
628
         * @param menu DOCUMENT ME!
629
         *
630
         * @throws RuntimeException DOCUMENT ME!
631
         */
632
        public void addPopupMenu(PluginClassLoader loader, PopupMenu menu) {
633
                if (!SwingUtilities.isEventDispatchThread()) {
634
                        throw new RuntimeException("No Event Dispatch Thread");
635
                }
636

    
637
                String name = getName(menu.getName(), loader);
638

    
639
                //Se crea el control popupmenu        
640
                JPopUpMenu popupMenu = (JPopUpMenu) popupMap.get(name);
641

    
642
                if (popupMenu == null) {
643
                        popupMenu = new JPopUpMenu(menu.getName());
644
                        popupMap.put(name, popupMenu);
645
                }
646

    
647
                // Se a?aden las entradas
648
                Menu[] menues = menu.getMenu();
649

    
650
                for (int i = 0; i < menues.length; i++) {
651
                        //Se registra y a?ade el menu
652
                        JMenuItem nuevoMenu = createJMenuItem(loader, menues[i]);
653

    
654
                        popupMenu.add(nuevoMenu);
655
                }
656
        }
657

    
658
        /**
659
         * DOCUMENT ME!
660
         *
661
         * @param loader
662
         * @param menu
663
         *
664
         * @return
665
         *
666
         * @throws RuntimeException DOCUMENT ME!
667
         */
668
        private JMenuItem createJMenuItem(PluginClassLoader loader, Menu menu) {
669
                JMenuItem nuevoMenu = null;
670

    
671
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
672
                String texto = menu.getText();
673
                texto = texto.substring(texto.lastIndexOf('/') + 1);
674
                texto = ps.getText(texto);
675

    
676
                if (menu.getIcon() != null) {
677
            System.out.println("Intentando cargar el icono " + menu.getIcon());
678
                        nuevoMenu = new JMenuItem(texto,
679
                                        new ImageIcon(loader.getResource(menu.getIcon())));
680
                } else {
681
                        nuevoMenu = new JMenuItem(texto);
682
                }
683

    
684
                if (menu.getMnemonic() != null) {
685
                        if (menu.getMnemonic().length() != 1) {
686
                                throw new RuntimeException(
687
                                        "Mnemonic must be 1 character length");
688
                        }
689

    
690
                        nuevoMenu.setMnemonic(KeyMapping.getKey(menu.getMnemonic().charAt(0)));
691
                }
692

    
693
                if (menu.getKey() != null) {
694
                        nuevoMenu.setAccelerator(KeyStroke.getKeyStroke(KeyMapping.getKey(
695
                                                menu.getKey().charAt(0)), ActionEvent.CTRL_MASK));
696
                }
697

    
698
                nuevoMenu.setActionCommand(menu.getActionCommand());
699

    
700
                if (menu.getTooltip() != null) {
701
                        nuevoMenu.setToolTip(ps.getText(menu.getTooltip()));
702
                }
703

    
704
                if (menu.getEnableText() != null) {
705
                        nuevoMenu.setEnableText(ps.getText(menu.getEnableText()));
706
                }
707

    
708
                nuevoMenu.setEnabled(true);
709
                nuevoMenu.setVisible(true);
710

    
711
                return nuevoMenu;
712
        }
713

    
714
        /**
715
         * Muestra u oculta el menu de nombre 'name'
716
         *
717
         * @param name Nombre del menu que se quiere mostrar
718
         * @param x Evento de raton
719
         * @param y DOCUMENT ME!
720
         * @param c DOCUMENT ME!
721
         */
722
        private void showPopupMenu(String name, int x, int y, Component c) {
723
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
724

    
725
                if (menu != null) {
726
                        menu.show(c, x, y);
727
                }
728
        }
729

    
730
        /**
731
         * DOCUMENT ME!
732
         *
733
         * @param name DOCUMENT ME!
734
         * @param listener DOCUMENT ME!
735
         */
736
        public void removePopupMenuListener(String name, ActionListener listener) {
737
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
738

    
739
                if (menu != null) {
740
                        Component[] jmenuitems = menu.getComponents();
741

    
742
                        for (int i = 0; i < jmenuitems.length; i++) {
743
                                if (jmenuitems[i] instanceof JMenuItem) {
744
                                        ((JMenuItem) jmenuitems[i]).removeActionListener(listener);
745
                                }
746
                        }
747
                }
748
        }
749

    
750
        /**
751
         * DOCUMENT ME!
752
         *
753
         * @param popupName
754
         * @param c DOCUMENT ME!
755
         * @param listener
756
         * @param loader
757
         */
758
        public void addPopupMenuListener(String popupName, Component c,
759
                ActionListener listener, PluginClassLoader loader) {
760
                final String name = getName(popupName, loader);
761

    
762
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
763

    
764
                if (menu != null) {
765
                        Component[] jmenuitems = menu.getComponents();
766

    
767
                        for (int i = 0; i < jmenuitems.length; i++) {
768
                                if (jmenuitems[i] instanceof JMenuItem) {
769
                                        ((JMenuItem) jmenuitems[i]).addActionListener(listener);
770
                                }
771
                        }
772
                }
773

    
774
                c.addMouseListener(new MouseAdapter() {
775
                                public void mousePressed(MouseEvent e) {
776
                                        if (e.isPopupTrigger()) {
777
                                                showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
778
                                        }
779
                                }
780

    
781
                                public void mouseReleased(MouseEvent e) {
782
                                        if (e.isPopupTrigger()) {
783
                                                showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
784
                                        }
785
                                }
786
                        });
787
        }
788

    
789
        /**
790
         * Itera por los controles preguntando a las extensiones si estos est?n
791
         * habilitados y visibles
792
         *
793
         * @throws RuntimeException DOCUMENT ME!
794
         */
795
        public void enableControls() {
796
                if (!SwingUtilities.isEventDispatchThread()) {
797
                        throw new RuntimeException("No Event Dispatch Thread");
798
                }
799

    
800
                Iterator e = classesExtensions.values().iterator();
801
                HashMap estadoExtensiones = new HashMap();
802
                HashMap visibilidadExtensiones = new HashMap();
803

    
804
                while (e.hasNext()) {
805
                        com.iver.andami.plugins.Extension ext = (com.iver.andami.plugins.Extension) e.next();
806

    
807
                        try {
808
                                if (estadoExtensiones.get(ext) == null) {
809
                                        Boolean visible = new Boolean(ext.isVisible());
810
                                        Boolean enabled = new Boolean(false);
811

    
812
                                        if (visible.booleanValue()) {
813
                                                enabled = new Boolean(ext.isEnabled());
814
                                        }
815

    
816
                                        estadoExtensiones.put(ext, enabled);
817
                                        visibilidadExtensiones.put(ext, visible);
818
                                }
819
                        } catch (Throwable e1) {
820
                                NotificationManager.addError(Messages.getString(
821
                                                "MDIFrame.Error_no_capturado_por_el_usuario"), e1);
822
                                estadoExtensiones.put(ext, Boolean.FALSE);
823
                        }
824
                }
825

    
826
                //Se habilitan y deshabilitan los controles
827
                e = controlClass.keySet().iterator();
828

    
829
                while (e.hasNext()) {
830
                        JComponent control = (JComponent) e.next();
831

    
832
                        try {
833
                                com.iver.andami.plugins.Extension ext = (com.iver.andami.plugins.Extension) classesExtensions.get((Class) controlClass.get(
834
                                                        control));
835
                                boolean enabled = ((Boolean) estadoExtensiones.get(ext)).booleanValue();
836
                                boolean visible = ((Boolean) visibilidadExtensiones.get(ext)).booleanValue();
837
                                control.setEnabled(enabled);
838
                                control.setVisible(visible);
839
                        } catch (Exception ex) {
840
                                control.setEnabled(false);
841
                                control.setVisible(false);
842
                        }
843
                }
844

    
845
                //Se itera por los men?es para ocultar los que no tengan hijos visibles
846
                for (int i = 0; i < menuBar.getMenuCount(); i++) {
847
                        MenuElement menu = menuBar.getMenu(i);
848
                        ocultarMenus(menu);
849
                }
850

    
851
                //Se ocultan las barras que no tienen herramientas
852
                Iterator it = toolBarMap.values().iterator();
853

    
854
                while (it.hasNext()) {
855
                        SelectableToolBar t = (SelectableToolBar) it.next();
856
                        boolean todosOcultos = true;
857

    
858
                        for (int i = 0; i < t.getComponentCount(); i++) {
859
                                if (t.getComponent(i).isVisible()) {
860
                                        todosOcultos = false;
861
                                }
862
                        }
863

    
864
                        if (todosOcultos) {
865
                                t.setVisible(false);
866
                        } else {
867
                                t.setVisible(true);
868
                        }
869
                }
870

    
871
                if (mdiManager != null) {
872
                        JPanel f = (JPanel) mdiManager.getActiveView();
873

    
874
                        if (f != null) {
875
                                if (lastLabelClass != f.getClass()) {
876
                                        lastLabelClass = f.getClass();
877

    
878
                                        Label[] lbls = (Label[]) classLabels.get(lastLabelClass);
879

    
880
                                        if (lbls != null) {
881
                                                bEstado.setLabelSet(lbls);
882
                                        }
883
                                }
884
                        }
885
                }
886

    
887
                ajustarToolBar();
888

    
889
                showMemory();
890
        }
891

    
892
        /**
893
         * Establece la visibilidad de un menu y todos sus descendientes en la
894
         * jerarquia teniendo en cuenta la visibilidad de todos los submenus.
895
         *
896
         * @param menu Menu que se quiere visualizar
897
         *
898
         * @return Devuelve true si el menu es visible y false en caso contrario
899
         */
900
        private boolean ocultarMenus(MenuElement menu) {
901
                MenuElement[] submenus = menu.getSubElements();
902

    
903
                //Si no tiene hijos se devuelve su visibilidad
904
                if (submenus.length == 0) {
905
                        return menu.getComponent().isVisible();
906
                }
907

    
908
                /*
909
                 * Si tiene hijos se devuelve true si alg?no de ellos es visible,
910
                 * pero se itera por todos ellos
911
                 */
912
                boolean visible = false;
913

    
914
                for (int i = 0; i < submenus.length; i++) {
915
                        if (ocultarMenus(submenus[i])) {
916
                                if (!(menu instanceof JPopupMenu)) {
917
                                        menu.getComponent().setVisible(true);
918
                                }
919

    
920
                                visible = true;
921
                        }
922
                }
923

    
924
                if (visible) {
925
                        return true;
926
                }
927

    
928
                menu.getComponent().setVisible(false);
929

    
930
                return false;
931
        }
932

    
933
        /**
934
         * Muestra la memoria consumida por el programa
935
         */
936
        private void showMemory() {
937
                Runtime r = Runtime.getRuntime();
938
                long mem = r.totalMemory() - r.freeMemory();
939
                logger.debug("Memoria total: " + mem);
940
        }
941

    
942
        /**
943
         * DOCUMENT ME!
944
         *
945
         * @return
946
         */
947
        public MDIManager getMDIManager() {
948
                return mdiManager;
949
        }
950

    
951
        /**
952
         * Establece el mensaje en la barra de estado asociado a una etiqueta
953
         *
954
         * @return DOCUMENT ME!
955
         */
956
        public NewStatusBar getStatusBar() {
957
                return bEstado;
958
        }
959
    
960
    /**
961
     * You can use this function to select the appropiate
962
     * tool inside the toolbars
963
     */
964
    public void setSelectedTool(String actionCommand)
965
    {
966
        Iterator it = toolBarMap.values().iterator();
967
        while (it.hasNext()) {
968
            SelectableToolBar t = (SelectableToolBar) it.next();
969
            t.setSelectedTool(actionCommand);
970
        }
971
        selectedTool = actionCommand;
972

    
973
    }
974
    
975
        /**
976
         * DOCUMENT ME!
977
         *
978
         * @param clase
979
         * @param label
980
         */
981
        public void setLabels(Class clase, Label[] label) {
982
                classLabels.put(clase, label);
983
        }
984

    
985
        /**
986
         * @see com.iver.andami.ui.mdiFrame.MainFrame#removeMenu(com.iver.andami.plugins.config.generate.Menu)
987
         */
988
        public void removeMenu(Menu menu) {
989
                JMenuItem delete = (JMenuItem) infoCodedMenus.get(menu);
990

    
991
                if (delete == null) {
992
                        throw new NoSuchElementException(menu.getText());
993
                }
994

    
995
                delete.getParent().remove(delete);
996
                infoCodedMenus.remove(menu);
997
        }
998

    
999
        /**
1000
         * @see com.iver.andami.ui.mdiFrame.MainFrame#addMenu(com.iver.andami.plugins.config.generate.Menu,
1001
         *                 java.awt.event.ActionListener, PluginClassLoader)
1002
         */
1003
        public void addMenu(Menu menu, ActionListener listener,
1004
                PluginClassLoader loader) {
1005
                JMenu menuPadre = createMenuAncestors(menu, loader);
1006

    
1007
                //Se registra y a?ade el menu
1008
                JMenuItem nuevoMenu = createJMenuItem(loader, menu);
1009
                nuevoMenu.addMouseListener(tooltipListener);
1010
                nuevoMenu.addActionListener(listener);
1011
                menuPadre.add(nuevoMenu);
1012

    
1013
                infoCodedMenus.put(menu, nuevoMenu);
1014
        }
1015

    
1016
        /**
1017
         * @see com.iver.andami.ui.mdiFrame.MainFrame#changeMenuName(java.lang.String[],
1018
         *                 String, com.iver.andami.plugins.PluginClassLoader)
1019
         */
1020
        public void changeMenuName(String[] menu, String newName,
1021
                PluginClassLoader loader) {
1022
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
1023

    
1024
                for (int i = 0; i < menu.length; i++) {
1025
                        menu[i] = ps.getText(menu[i]);
1026
                }
1027

    
1028
                JMenu menuPadre = null;
1029

    
1030
                //Se busca el padre en la menuBar
1031
                for (int i = 0; i < menuBar.getMenuCount(); i++) {
1032
                        if (menuBar.getMenu(i).getText().compareToIgnoreCase(menu[0]) == 0) {
1033
                                menuPadre = (JMenu) menuBar.getMenu(i);
1034
                        }
1035
                }
1036

    
1037
                if (menuPadre == null) {
1038
                        throw new NoSuchMenuException(menu[0]);
1039
                }
1040

    
1041
                Vector nombres = new Vector();
1042

    
1043
                for (int i = 1; i < menu.length; i++) {
1044
                        nombres.add(menu[i]);
1045
                }
1046

    
1047
                javax.swing.JMenuItem m = getMenu(nombres, menuPadre);
1048

    
1049
                if (m != null) {
1050
                        m.setText(newName);
1051
                }else{
1052
                        throw new NoSuchMenuException();
1053
                }
1054
        }
1055

    
1056
        /**
1057
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
1058
         */
1059
        public void componentHidden(ComponentEvent arg0) {
1060
        }
1061

    
1062
        /**
1063
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
1064
         */
1065
        public void componentMoved(ComponentEvent arg0) {
1066
        }
1067

    
1068
        /**
1069
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
1070
         */
1071
        public void componentResized(ComponentEvent arg0) {
1072
                ajustarToolBar();
1073
                bEstado.setFixedLabelWidth(this.getWidth() * 0.3);
1074
        }
1075

    
1076
        /**
1077
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
1078
         */
1079
        public void componentShown(ComponentEvent arg0) {
1080
        }
1081

    
1082
        /**
1083
         * @see java.awt.event.ContainerListener#componentAdded(java.awt.event.ContainerEvent)
1084
         */
1085
        public void componentAdded(ContainerEvent arg0) {
1086
                ajustarToolBar();
1087
        }
1088

    
1089
        /**
1090
         * @see java.awt.event.ContainerListener#componentRemoved(java.awt.event.ContainerEvent)
1091
         */
1092
        public void componentRemoved(ContainerEvent arg0) {
1093
                ajustarToolBar();
1094
        }
1095

    
1096
        /**
1097
         * DOCUMENT ME!
1098
         *
1099
         * @author $author$
1100
         * @version $Revision: 2757 $
1101
         */
1102
        public class TooltipListener extends MouseAdapter {
1103
                /**
1104
                 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1105
                 */
1106
                public void mouseEntered(MouseEvent e) {
1107
                        JComponent control = (JComponent) e.getSource();
1108
                        EnableTextSupport ets = (EnableTextSupport) e.getSource();
1109

    
1110
                        String texto = null;
1111
                        texto = control.getToolTipText();
1112

    
1113
                        if (texto != null) {
1114
                                bEstado.setInfoTextTemporal(texto);
1115
                        }
1116
                }
1117

    
1118
                /**
1119
                 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1120
                 */
1121
                public void mouseExited(MouseEvent arg0) {
1122
                        bEstado.restaurarTexto();
1123
                }
1124

    
1125
                /**
1126
                 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1127
                 */
1128
                public void mousePressed(MouseEvent e) {
1129
                        bEstado.restaurarTexto();
1130
                }
1131
        }
1132
        public String getTitlePrefix() {
1133
                return titlePrefix;
1134
        }
1135
        public void setTitlePrefix(String titlePrefix) {
1136
                this.titlePrefix = titlePrefix;
1137
        }
1138

    
1139
    public String getSelectedTool() {
1140
        return selectedTool;
1141
    }
1142
    
1143

    
1144
    /**
1145
     * Get a previously added JComponent by name. For example
1146
     * you can use it if you need to obtain a JToolBar to
1147
     * add some customized component.
1148
     * @param name
1149
     * @return the JComponent or null if none has been found
1150
     */
1151
    public JComponent getComponentByName(String name)
1152
    {
1153
        Iterator e = controlClass.keySet().iterator();
1154

    
1155
        while (e.hasNext()) {
1156
            JComponent control = (JComponent) e.next();
1157
            String nameCtrl = control.getName();
1158
            if (nameCtrl != null)
1159
                    if (nameCtrl.compareTo(name) == 0)
1160
                            return control;
1161
        }
1162
        Iterator it = toolBarMap.values().iterator();
1163
        while (it.hasNext()) {
1164
            SelectableToolBar t = (SelectableToolBar) it.next();
1165
            String nameCtrl = t.getName();
1166
            if (nameCtrl != null)
1167
                    if (nameCtrl.compareTo(name) == 0)
1168
                            return t;
1169

    
1170
        }
1171
        
1172
        return null;
1173
    }
1174
}