Statistics
| Revision:

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

History | View | Annotate | Download (33.4 KB)

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

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

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

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

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

    
101

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
173
                //Se a?aden los listeners del JFrame
174
                this.addWindowListener(new WindowAdapter() {
175
                                public void windowClosing(WindowEvent e) {
176
                                        Launcher.closeApplication();
177
                                }
178
                        });
179
                this.addComponentListener(this);
180
                this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
181

    
182
                //Se configura la barra de menu
183
                setJMenuBar(menuBar);
184

    
185
                //Se configura el layout del JFrame principal
186
                this.getContentPane().setLayout(new BorderLayout());
187

    
188
                /*
189
                 * Se configura y se a?ade el JPanel de las barras de
190
                 * herramientas
191
                 */
192
                FlowLayout layout = new FlowLayout(FlowLayout.LEFT);
193
                layout.setHgap(0);
194
                layout.setVgap(0);
195
                toolBars.setLayout(layout);
196
                getContentPane().add(toolBars, BorderLayout.PAGE_START);
197

    
198
                // Se a?ade la barra de estado a la aplicaci?n
199
                bEstado = new NewStatusBar();
200
                bEstado.setInfoText(Messages.getString("StatusBar.Aplicacion_iniciada"));
201
                getContentPane().add(bEstado, BorderLayout.SOUTH);
202

    
203
                this.toolBars.addContainerListener(this);
204

    
205
                pack();
206

    
207
                // TODO LWS Aqui deber?a cargar los valores salvados de la ?ltima ejecuci?n.
208
                setSize(700, 580);
209
                setLocation(10,10);
210
                setExtendedState(MAXIMIZED_BOTH);
211

    
212
                mdiManager.init(this);
213
        }
214
        
215
        public void setTitle(String title) {
216
                super.setTitle(titlePrefix + ":" + title);
217
        }
218

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

    
237
                // Para traducir
238
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
239

    
240
                JToolBarToggleButton btn;
241
                URL image = loader.getResource(selectableTool.getIcon());
242

    
243
                if (image != null) {
244
                        btn = new JToolBarToggleButton(selectableTool.getText(),
245
                                        new ImageIcon(image));
246
                } else {
247
                        btn = new JToolBarToggleButton(selectableTool.getText());
248
                }
249

    
250
                btn.setMargin(new Insets(0, 0, 0, 0));
251
                btn.addMouseListener(tooltipListener);
252
                btn.addActionListener(this);
253
                btn.setFocusable(false);
254
                btn.setActionCommand(selectableTool.getActionCommand());
255
                btn.setToolTipText(selectableTool.getTooltip());
256
                btn.setEnabled(false);
257
                btn.setVisible(false);
258

    
259
                if (selectableTool.getIsDefault()) {
260
                        btn.setSelected(true);
261
            selectedTool = btn.getActionCommand();
262
                }
263

    
264
                String name = getName(toolBar.getName(), loader);
265

    
266
                SelectableToolBar jtb = (SelectableToolBar) toolBarMap.get(name);
267

    
268
                if (jtb == null) {
269
                        jtb = new SelectableToolBar(toolBar.getName());
270
                        jtb.setRollover(true);
271
                        toolBarMap.put(name, jtb);
272
                        toolBars.add(jtb);
273

    
274
                }
275

    
276
                jtb.addButton(buttonGroup, btn);
277
                controlClass.put(btn, loader.loadClass(ext.getClassName()));
278
                if (selectableTool.getName() != null) {
279
                        btn.setName(selectableTool.getName());
280
                }
281
                if (selectableTool.getTooltip() != null) {
282
                        btn.setToolTip(ps.getText(selectableTool.getTooltip()));
283
                }
284

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

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

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

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

    
314
                JToolBarButton btn;
315
                URL image = loader.getResource(actionTool.getIcon());
316

    
317
                if (image != null) {
318
                        btn = new JToolBarButton(actionTool.getText(), new ImageIcon(image));
319
                } else {
320
                        btn = new JToolBarButton(actionTool.getText());
321
                }
322

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

    
331
                String name = getName(toolBar.getName(), loader);
332

    
333
                SelectableToolBar jtb = (SelectableToolBar) toolBarMap.get(name);
334

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

    
342
                jtb.add(btn);
343

    
344
                controlClass.put(btn, loader.loadClass(ext.getClassName()));
345

    
346
                if (actionTool.getName() != null) {
347
                        btn.setName(actionTool.getName());
348
                }
349

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

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

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

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

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

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

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

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

    
400
                //Se crea el resto de menus
401
                Vector temp = new Vector();
402

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

    
407
                menuPadre = createMenus(temp, menuPadre);
408

    
409
                return menuPadre;
410
        }
411

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

    
432
                JMenu menuPadre = createMenuAncestors(menu, loader);
433

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

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

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

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

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

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

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

    
483
                nombres.remove(0);
484

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

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

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

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

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

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

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

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

    
550
                        nombres.remove(0);
551

    
552
                        return createMenus(nombres, menuPadre);
553
                }
554
        }
555

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

    
566
                int toolHeight = 0;
567

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

    
571
                        if (!c.isVisible()) {
572
                                continue;
573
                        }
574

    
575
                        double width = c.getPreferredSize().getWidth();
576
                        acum = acum + width;
577

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

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

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

    
591
                toolBars.updateUI();
592
        }
593

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

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

    
629
                enableControls();
630
                showMemory();
631
        }
632

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

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

    
662
                String name = getName(menu.getName(), loader);
663

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

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

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

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

    
679
                        popupMenu.add(nuevoMenu);
680
                }
681
        }
682

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

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

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

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

    
718
                        nuevoMenu.setMnemonic(KeyMapping.getKey(menu.getMnemonic().charAt(0)));
719
                }
720

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

    
732
                nuevoMenu.setActionCommand(menu.getActionCommand());
733

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

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

    
742
                nuevoMenu.setEnabled(true);
743
                nuevoMenu.setVisible(true);
744

    
745
                return nuevoMenu;
746
        }
747

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

    
759
                if (menu != null) {
760
                        menu.show(c, x, y);
761
                }
762
        }
763

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

    
773
                if (menu != null) {
774
                        Component[] jmenuitems = menu.getComponents();
775

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

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

    
796
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
797

    
798
                if (menu != null) {
799
                        Component[] jmenuitems = menu.getComponents();
800

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

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

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

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

    
834
                Iterator e = classesExtensions.values().iterator();
835
                HashMap estadoExtensiones = new HashMap();
836
                HashMap visibilidadExtensiones = new HashMap();
837

    
838
                while (e.hasNext()) {
839
                        ExtensionDecorator ext = (ExtensionDecorator) e.next();
840

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

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

    
865
                                        }
866

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

    
877
                //Se habilitan y deshabilitan los controles
878
                e = controlClass.keySet().iterator();
879

    
880
                while (e.hasNext()) {
881
                        JComponent control = (JComponent) e.next();
882

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

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

    
902
                //Se ocultan las barras que no tienen herramientas
903
                Iterator it = toolBarMap.values().iterator();
904

    
905
                while (it.hasNext()) {
906
                        SelectableToolBar t = (SelectableToolBar) it.next();
907
                        boolean todosOcultos = true;
908

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

    
916
                        if (todosOcultos) {
917
                                t.setVisible(false);
918
                        } else {
919
                                t.setVisible(true);
920
                        }
921
                }
922

    
923
                if (mdiManager != null) {
924
                        JPanel f = (JPanel) mdiManager.getActiveWindow();
925

    
926
                        if (f != null) {
927
                                if (lastLabelClass != f.getClass()) {
928
                                        lastLabelClass = f.getClass();
929

    
930
                                        Label[] lbls = (Label[]) classLabels.get(lastLabelClass);
931

    
932
                                        if (lbls != null) {
933
                                                bEstado.setLabelSet(lbls);
934
                                        }
935
                                }
936
                        }
937
                }
938

    
939
                ajustarToolBar();
940

    
941
                showMemory();
942
        }
943

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

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

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

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

    
972
                                visible = true;
973
                        }
974
                }
975

    
976
                if (visible) {
977
                        return true;
978
                }
979

    
980
                menu.getComponent().setVisible(false);
981

    
982
                return false;
983
        }
984

    
985
        /**
986
         * Muestra la memoria consumida por el programa
987
         */
988
        public void showMemory() {
989
                Runtime r = Runtime.getRuntime();
990
                long mem = (r.totalMemory() - r.freeMemory())/1048576 ;
991
                logger.debug("Memoria total: " + mem + " MB");
992
        }
993

    
994
        /**
995
         * DOCUMENT ME!
996
         *
997
         * @return
998
         */
999
        public MDIManager getMDIManager() {
1000
                return mdiManager;
1001
        }
1002

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

    
1024
    }
1025

    
1026
        /**
1027
         * DOCUMENT ME!
1028
         *
1029
         * @param clase
1030
         * @param label
1031
         */
1032
        public void setStatusBarLabels(Class clase, Label[] label) {
1033
                classLabels.put(clase, label);
1034
        }
1035

    
1036

    
1037
        public void removeStatusBarLabels(Class clase) {
1038
                classLabels.remove(clase);
1039
        }
1040

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

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

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

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

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

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

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

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

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

    
1090
                JMenu menuPadre = null;
1091

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

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

    
1103
                Vector nombres = new Vector();
1104

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1204

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

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

    
1237
        }
1238

    
1239
        return null;
1240
    }
1241

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