Statistics
| Revision:

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

History | View | Annotate | Download (33.7 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: 9403 $
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
        /** Almacena los grupos de selectableTools */
126
        private HashMap buttonGroupMap = new HashMap();
127

    
128
    /**
129
     * actionCommand del tool seleccionado
130
     */
131
    private String selectedTool;
132

    
133
        /** Asocia los nombres con los popupMenus */
134
        private HashMap popupMap = new HashMap();
135

    
136
        /** Asocia controles con la clase de la extension asociada */
137
        private HashMap controlClass = new HashMap();
138

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

    
145
        //private HashMap classControls = new HashMap();
146

    
147
        /** ProgressListeners (ver interfaz com.iver.mdiApp.ui.ProgressListener) */
148
        private ArrayList progressListeners = new ArrayList();
149

    
150
        /** Timer para invocar los enventos de la interfaz anterior */
151
        private Timer progressTimer = null;
152

    
153
        /** Tabla hash que asocia las clases con las extensiones */
154
        private HashMap classesExtensions = new HashMap();
155

    
156
        /** ?ltima clase que activ? etiquetas */
157
        private Class lastLabelClass;
158

    
159
        /** Instancia que pone los tooltip en la barra de estado */
160
        private TooltipListener tooltipListener = new TooltipListener();
161
        private HashMap infoCodedMenus = new HashMap();
162

    
163
        private String titlePrefix;
164

    
165
        /**
166
         * Realiza tareas para poner en marcha la aplicaci?n
167
         *
168
         * @throws RuntimeException DOCUMENT ME!
169
         */
170
        public void init() {
171
                JPopupMenu.setDefaultLightWeightPopupEnabled(false);
172
                if (!SwingUtilities.isEventDispatchThread()) {
173
                        throw new RuntimeException("Not Event Dispatch Thread");
174
                }
175

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

    
187
                                        if (option == JOptionPane.YES_OPTION) {
188
                                                Launcher.closeApplication();
189
                                        }
190
                                }
191
                        });
192
                this.addComponentListener(this);
193
                this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
194

    
195
                //Se configura la barra de menu
196
                setJMenuBar(menuBar);
197

    
198
                //Se configura el layout del JFrame principal
199
                this.getContentPane().setLayout(new BorderLayout());
200

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

    
211
                // Se a?ade la barra de estado a la aplicaci?n
212
                bEstado = new NewStatusBar();
213
                bEstado.setInfoText(Messages.getString("StatusBar.Aplicacion_iniciada"));
214
                getContentPane().add(bEstado, BorderLayout.SOUTH);
215

    
216
                this.toolBars.addContainerListener(this);
217

    
218
                pack();
219

    
220
                // TODO LWS Aqui deber?a cargar los valores salvados de la ?ltima ejecuci?n.
221
                setSize(700, 580);
222
                setLocation(10,10);
223
                setExtendedState(MAXIMIZED_BOTH);
224

    
225
                mdiManager.init(this);
226
        }
227

    
228
        public void setTitle(String title) {
229
                super.setTitle(titlePrefix + ":" + title);
230
        }
231

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

    
250
                // Para traducir
251
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
252

    
253
                JToolBarToggleButton btn;
254
                URL image = loader.getResource(selectableTool.getIcon());
255

    
256
                if (image != null) {
257
                        btn = new JToolBarToggleButton(selectableTool.getText(),
258
                                        new ImageIcon(image));
259
                } else {
260
                        btn = new JToolBarToggleButton(selectableTool.getText());
261
                }
262

    
263
                btn.setMargin(new Insets(0, 0, 0, 0));
264
                btn.addMouseListener(tooltipListener);
265
                btn.addActionListener(this);
266
                btn.setFocusable(false);
267
                btn.setActionCommand(selectableTool.getActionCommand());
268
                btn.setToolTipText(selectableTool.getTooltip());
269
                btn.setEnabled(false);
270
                btn.setVisible(false);
271

    
272
                if (selectableTool.getIsDefault()) {
273
                        btn.setSelected(true);
274
            selectedTool = btn.getActionCommand();
275
                }
276

    
277
                String name = getName(toolBar.getName(), loader);
278

    
279
                SelectableToolBar jtb = (SelectableToolBar) toolBarMap.get(name);
280

    
281
                if (jtb == null) {
282
                        jtb = new SelectableToolBar(toolBar.getName());
283
                        jtb.setRollover(true);
284
                        toolBarMap.put(name, jtb);
285
                        toolBars.add(jtb);
286

    
287
                }
288
                
289
                ButtonGroup group;
290
                if (buttonGroupMap.containsKey(selectableTool.getGroup())) {
291
                        group = (ButtonGroup) buttonGroupMap.get(selectableTool.getGroup());
292
                }
293
                else {
294
                        group = new ButtonGroup();
295
                        buttonGroupMap.put(selectableTool.getGroup(), group);
296
                        
297
                }
298
                jtb.addButton(group, btn);
299
                
300
                controlClass.put(btn, loader.loadClass(ext.getClassName()));
301

    
302
                if (selectableTool.getTooltip() != null) {
303
                        btn.setToolTip(ps.getText(selectableTool.getTooltip()));
304
                }
305

    
306
                if (selectableTool.getEnableText() != null) {
307
                        btn.setEnableText(ps.getText(selectableTool.getEnableText()));
308
                }
309

    
310
                if (selectableTool.getLast() == true) {
311
                        jtb.addSeparator();
312
                }
313
        }
314

    
315
        /**
316
         * A?ade un bot?n a la barra de herramientas
317
         *
318
         * @param ext Texto del boton, si es null no aparece texto
319
         * @param ext Extensi?n asociada al control
320
         * @param toolBar Icono del boton, si es null no aparece texto
321
         * @param actionTool Tooltip de la barra de herramientas
322
         *
323
         * @throws ClassNotFoundException
324
         * @throws RuntimeException DOCUMENT ME!
325
         */
326
        public void addTool(PluginClassLoader loader, SkinExtensionType ext,
327
                ToolBar toolBar, ActionTool actionTool) throws ClassNotFoundException {
328
                if (!SwingUtilities.isEventDispatchThread()) {
329
                        throw new RuntimeException("No Event Dispatch Thread");
330
                }
331

    
332
                // Para traducir los textos que vengan
333
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
334

    
335
                JToolBarButton btn;
336
                URL image = loader.getResource(actionTool.getIcon());
337

    
338
                if (image != null) {
339
                        btn = new JToolBarButton(actionTool.getText(), new ImageIcon(image));
340
                } else {
341
                        btn = new JToolBarButton(actionTool.getText());
342
                }
343

    
344
                btn.setMargin(new Insets(0, 0, 0, 0));
345
                btn.addMouseListener(tooltipListener);
346
                btn.addActionListener(this);
347
                btn.setFocusable(false);
348
                btn.setActionCommand(actionTool.getActionCommand());
349
                btn.setEnabled(false);
350
                btn.setVisible(false);
351

    
352
                String name = getName(toolBar.getName(), loader);
353

    
354
                SelectableToolBar jtb = (SelectableToolBar) toolBarMap.get(name);
355

    
356
                if (jtb == null) {
357
                        jtb = new SelectableToolBar(toolBar.getName());
358
                        jtb.setRollover(true);
359
                        toolBarMap.put(name, jtb);
360
                        toolBars.add(jtb);
361
                }
362

    
363
                jtb.add(btn);
364

    
365
                controlClass.put(btn, loader.loadClass(ext.getClassName()));
366

    
367
                if (actionTool.getTooltip() != null) {
368
                        btn.setToolTip(ps.getText(actionTool.getTooltip()));
369
                }
370

    
371
                if (actionTool.getEnableText() != null) {
372
                        btn.setEnableText(ps.getText(actionTool.getEnableText()));
373
                }
374

    
375
                if (actionTool.getLast() == true) {
376
                        jtb.addSeparator();
377
                }
378
        }
379

    
380
        /**
381
         * Creates the needed menu structure to add the menu to the bar.
382
         * Returns the father which must hold the menu which was
383
         * provided as parameter.
384
         *
385
         * Crea la estructura de men?s necesaria para a?adir el menu a la barra.
386
         * Devuelve el padre del cual debe colgar el menu que se pasa como
387
         * par?metro.
388
         *
389
         * @param menu The Menu whose support is going to be added
390
         * @param loader The plugin's class loader
391
         *
392
         * @return The proper father for the menu which was provided as parameter
393
         */
394
        private JMenu createMenuAncestors(Menu menu, PluginClassLoader loader) {
395
                JMenu menuPadre = null;
396

    
397
                String[] menues = menu.getText().split("/");
398
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
399

    
400
                for (int i = 0; i < menues.length; i++) {
401
                        menues[i] = ps.getText(menues[i]);
402
                }
403

    
404
                //Se busca el padre en la menuBar
405
                for (int i = 0; i < menuBar.getMenuCount(); i++) {
406
                        if (menuBar.getMenu(i).getText().compareToIgnoreCase(menues[0]) == 0) {
407
                                menuPadre = (JMenu) menuBar.getMenu(i);
408
                        }
409
                }
410

    
411
                //Si no se encuentra el padre se crea
412
                if (menuPadre == null) {
413
                        menuPadre = new JMenu(menues[0]);
414
                        menuBar.add(menuPadre);
415
                }
416

    
417
                //Se crea el resto de menus
418
                Vector temp = new Vector();
419

    
420
                for (int i = 1; i < (menues.length - 1); i++) {
421
                        temp.add(menues[i]);
422
                }
423

    
424
                menuPadre = createMenus(temp, menuPadre);
425

    
426
                return menuPadre;
427
        }
428

    
429
        /**
430
         * A?ade la informaci?n del menu al framework. Debido a que los men?es se
431
         * pueden introducir en un orden determinado por el usuario, pero los
432
         * plugins se instalan en un orden arbitrario, primero se almacena la
433
         * informaci?n de todos los menus para luego ordenarlos y posteriormente
434
         * a?adirlos al interfaz
435
         *
436
         * @param loader Posicion del menu. Se ordena por este campo
437
         * @param ext Array con los nombres de los padres del menu
438
         * @param menu Texto del menu
439
         *
440
         * @throws ClassNotFoundException
441
         * @throws RuntimeException DOCUMENT ME!
442
         */
443
        public void addMenu(PluginClassLoader loader, SkinExtensionType ext,
444
                Menu menu) throws ClassNotFoundException {
445
                if (!SwingUtilities.isEventDispatchThread()) {
446
                        throw new RuntimeException("No Event Dispatch Thread");
447
                }
448

    
449
                JMenu menuPadre = createMenuAncestors(menu, loader);
450

    
451
                //Se registra y a?ade el menu
452
        /* String[] aux = menu.getText().split("/");
453

454
        if (aux.length == 2)
455
            if (aux[1].equals("----"))
456
            {
457
                menuPadre.addSeparator();
458
                return;
459
            } */
460
        if (menu.getIs_separator())
461
        {
462
            menuPadre.addSeparator();
463
            return;
464
        }
465

    
466
                JMenuItem nuevoMenu = createJMenuItem(loader, menu);
467
                nuevoMenu.addMouseListener(tooltipListener);
468
                nuevoMenu.addActionListener(this);
469
                menuPadre.add(nuevoMenu);
470
        controlClass.put(nuevoMenu, loader.loadClass(ext.getClassName()));
471
        }
472

    
473
        /**
474
         * Dado un array de nombres de menu traducidos, encuentra el  men?
475
         *
476
         * @param nombres DOCUMENT ME!
477
         * @param padre DOCUMENT ME!
478
         *
479
         * @return DOCUMENT ME!
480
         */
481
        private javax.swing.JMenuItem getMenu(Vector nombres, JMenu padre) {
482
                javax.swing.JMenuItem buscado = null;
483
                javax.swing.JMenuItem hijo;
484

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

    
489
                                if (hijo.getText().compareToIgnoreCase((String) nombres.get(0)) == 0) {
490
                                        buscado = hijo;
491
                                }
492
                        }
493
                }
494

    
495
                //Si no se encuentra el menu
496
                if (buscado == null) {
497
                        return null;
498
                }
499

    
500
                nombres.remove(0);
501

    
502
                //Si se ha llegado al fin de la ruta completa
503
                if (nombres.isEmpty()) {
504
                        return buscado;
505
                } else {
506
                        if (buscado instanceof JMenu) {
507
                                return getMenu(nombres, (JMenu) buscado);
508
                        } else {
509
                                return null;
510
                        }
511
                }
512
        }
513

    
514
        /**
515
         * Crea la estructura de menus recursivamente. Por ejemplo, si se le pasa
516
         * en el par?metro nombres el array {"Search", "References", "Workspace"}
517
         * crear? un men? Search, un submen? del anterior que se llamar?
518
         * References y debajo de ?ste ?ltimo otro menu llamado Workspace
519
         *
520
         * @param nombres Array con los nombres de los men?s que se quieren crear
521
         * @param padre Menu padre de los men?s creados. Es ?til porque es un
522
         *                   algoritmo recursivo
523
         *
524
         * @return Devuelve el men? creado. Al final de toda la recursividad,
525
         *                    devolver? el men? de m?s abajo en la jerarqu?a
526
         *
527
         * @throws RuntimeException DOCUMENT ME!
528
         */
529
        private JMenu createMenus(Vector nombres, JMenu padre) {
530
                if (!SwingUtilities.isEventDispatchThread()) {
531
                        throw new RuntimeException("No Event Dispatch Thread");
532
                }
533

    
534
                //si no quedan nombres de menu por crear se vuelve: caso base
535
                if (nombres.size() == 0) {
536
                        return padre;
537
                }
538

    
539
                //Se busca el menu por si ya existiera para no crearlo otra vez
540
                JMenu buscado = null;
541

    
542
                for (int i = 0; i < padre.getMenuComponentCount(); i++) {
543
                        try {
544
                                JMenu hijo = (JMenu) padre.getMenuComponent(i);
545

    
546
                                if (hijo.getText().compareToIgnoreCase((String) nombres.get(0)) == 0) {
547
                                        buscado = hijo;
548
                                }
549
                        } catch (ClassCastException e) {
550
                                /*
551
                                 * Se ha encontrado un elemento hoja del arbol de men?es
552
                                 */
553
                        }
554
                }
555

    
556
                if (buscado != null) {
557
                        //Si lo hemos encontrado creamos el resto
558
                        nombres.remove(0);
559

    
560
                        return createMenus(nombres, buscado);
561
                } else {
562
                        //Si no lo hemos encontrado se crea el menu, se a?ade al padre
563
                        //y se crea el resto
564
                        JMenu menuPadre = new JMenu((String) nombres.get(0));
565
                        padre.add(menuPadre);
566

    
567
                        nombres.remove(0);
568

    
569
                        return createMenus(nombres, menuPadre);
570
                }
571
        }
572

    
573
        /**
574
         * M?todo invocado en respuesta a ciertos eventos de la interfaz que pueden
575
         * ocultar botones de las barras de herramientas y que redimensiona ?sta
576
         * de manera conveniente para que no se oculte ninguno
577
         */
578
        private void ajustarToolBar() {
579
                int margen = 8;
580
                int numFilas = 1;
581
                double acum = margen;
582

    
583
                int toolHeight = 0;
584

    
585
                for (int i = 0; i < toolBars.getComponentCount(); i++) {
586
                        Component c = toolBars.getComponent(i);
587

    
588
                        if (!c.isVisible()) {
589
                                continue;
590
                        }
591

    
592
                        double width = c.getPreferredSize().getWidth();
593
                        acum = acum + width;
594

    
595
                        if (acum > this.getWidth()) {
596
                                numFilas++;
597
                                acum = width + margen;
598
                        }
599

    
600
                        if (c.getPreferredSize().getHeight() > toolHeight) {
601
                                toolHeight = c.getPreferredSize().height;
602
                        }
603
                }
604

    
605
                toolBars.setPreferredSize(new Dimension(this.getWidth(),
606
                                (int) (numFilas * toolHeight)));
607

    
608
                toolBars.updateUI();
609
        }
610

    
611
        /**
612
         * DOCUMENT ME!
613
         *
614
         * @param classesExtensions
615
         */
616
        public void setClassesExtensions(HashMap classesExtensions) {
617
                this.classesExtensions = classesExtensions;
618
        }
619

    
620
        /**
621
         * M?todo de callback invocado cuando se selecciona un men? o un bot?n de
622
         * la barra de herramientas. Se busca la extensi?n asociada y se ejecuta
623
         *
624
         * @param e Evento producido
625
         */
626
        public void actionPerformed(ActionEvent e) {
627
                Object control = e.getSource();
628
                com.iver.andami.plugins.IExtension ext = (com.iver.andami.plugins.IExtension) classesExtensions.get((Class) controlClass.get(
629
                                control));
630
                String actionCommand = e.getActionCommand();
631
                try {
632
                        logger.debug(Messages.getString("Ejecutando comando: ") + actionCommand);
633
                        ext.execute(actionCommand);
634
                if (control instanceof JToolBarToggleButton)
635
                {
636
                    selectedTool = actionCommand;
637
                }
638
                } catch (RuntimeException t) {
639
                        if (ext==null) {
640
                                logger.error(Messages.getString("No_extension_associated_with_this_event_")+ e.getActionCommand());
641
                        }
642
                        NotificationManager.addError(Messages.getString(
643
                                        "MDIFrame.Error_no_capturado_por_el_usuario"), t);
644
                }
645

    
646
                enableControls();
647
                showMemory();
648
        }
649

    
650
        /**
651
         * DOCUMENT ME!
652
         *
653
         * @param name DOCUMENT ME!
654
         * @param loader DOCUMENT ME!
655
         *
656
         * @return DOCUMENT ME!
657
         */
658
        private String getName(String name, PluginClassLoader loader) {
659
                if (name.indexOf('.') == -1) {
660
                        return loader.getPluginName() + "." + name;
661
                } else {
662
                        return name;
663
                }
664
        }
665

    
666
        /**
667
         * DOCUMENT ME!
668
         *
669
         * @param loader DOCUMENT ME!
670
         * @param menu DOCUMENT ME!
671
         *
672
         * @throws RuntimeException DOCUMENT ME!
673
         */
674
        public void addPopupMenu(PluginClassLoader loader, PopupMenu menu) {
675
                if (!SwingUtilities.isEventDispatchThread()) {
676
                        throw new RuntimeException("No Event Dispatch Thread");
677
                }
678

    
679
                String name = getName(menu.getName(), loader);
680

    
681
                //Se crea el control popupmenu
682
                JPopUpMenu popupMenu = (JPopUpMenu) popupMap.get(name);
683

    
684
                if (popupMenu == null) {
685
                        popupMenu = new JPopUpMenu(menu.getName());
686
                        popupMap.put(name, popupMenu);
687
                }
688

    
689
                // Se a?aden las entradas
690
                Menu[] menues = menu.getMenu();
691

    
692
                for (int i = 0; i < menues.length; i++) {
693
                        //Se registra y a?ade el menu
694
                        JMenuItem nuevoMenu = createJMenuItem(loader, menues[i]);
695

    
696
                        popupMenu.add(nuevoMenu);
697
                }
698
        }
699

    
700
        /**
701
         * DOCUMENT ME!
702
         *
703
         * @param loader
704
         * @param menu
705
         *
706
         * @return
707
         *
708
         * @throws RuntimeException DOCUMENT ME!
709
         */
710
        private JMenuItem createJMenuItem(PluginClassLoader loader, Menu menu) {
711
                JMenuItem nuevoMenu = null;
712

    
713
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
714
                String texto = menu.getText();
715
                texto = texto.substring(texto.lastIndexOf('/') + 1);
716
                texto = ps.getText(texto);
717

    
718
                if (menu.getIcon() != null) {
719
                        URL url = loader.getResource(menu.getIcon());
720
                        if (url != null) {
721
                                nuevoMenu = new JMenuItem(texto, new ImageIcon(url));
722
                        } else {
723
                                NotificationManager.addError(PluginServices.getText(this, "Unable_to_find_icon") +": "+menu.getIcon(), new FileNotFoundException());
724
                        }
725
                } else {
726
                        nuevoMenu = new JMenuItem(texto);
727
                }
728

    
729
                if (menu.getMnemonic() != null) {
730
                        if (menu.getMnemonic().length() != 1) {
731
                                throw new RuntimeException(
732
                                        "Mnemonic must be 1 character length");
733
                        }
734

    
735
                        nuevoMenu.setMnemonic(KeyMapping.getKey(menu.getMnemonic().charAt(0)));
736
                }
737

    
738
                if (menu.getKey() != null) {
739
                        String osName = (String) System.getProperty("os.name");
740
                        boolean MAC_OS_X = osName.toLowerCase().startsWith("mac os x");
741
                        if (MAC_OS_X) {
742
                                //en OS X, en vez de hardwiring la ShortcutKey, usamos el default sugerido por el OS
743
                                nuevoMenu.setAccelerator(KeyStroke.getKeyStroke(KeyMapping.getKey(
744
                                                menu.getKey().charAt(0)), Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
745
                        } else {
746
                                nuevoMenu.setAccelerator(KeyStroke.getKeyStroke(KeyMapping.getKey(
747
                                                menu.getKey().charAt(0)), ActionEvent.ALT_MASK));
748
                        }
749
                }
750

    
751
                nuevoMenu.setActionCommand(menu.getActionCommand());
752

    
753
                if (menu.getTooltip() != null) {
754
                        nuevoMenu.setToolTip(ps.getText(menu.getTooltip()));
755
                }
756

    
757
                if (menu.getEnableText() != null) {
758
                        nuevoMenu.setEnableText(ps.getText(menu.getEnableText()));
759
                }
760

    
761
                nuevoMenu.setEnabled(true);
762
                nuevoMenu.setVisible(true);
763

    
764
                return nuevoMenu;
765
        }
766

    
767
        /**
768
         * Muestra u oculta el menu de nombre 'name'
769
         *
770
         * @param name Nombre del menu que se quiere mostrar
771
         * @param x Evento de raton
772
         * @param y DOCUMENT ME!
773
         * @param c DOCUMENT ME!
774
         */
775
        private void showPopupMenu(String name, int x, int y, Component c) {
776
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
777

    
778
                if (menu != null) {
779
                        menu.show(c, x, y);
780
                }
781
        }
782

    
783
        /**
784
         * DOCUMENT ME!
785
         *
786
         * @param name DOCUMENT ME!
787
         * @param listener DOCUMENT ME!
788
         */
789
        public void removePopupMenuListener(String name, ActionListener listener) {
790
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
791

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

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

    
803
        /**
804
         * DOCUMENT ME!
805
         *
806
         * @param popupName
807
         * @param c DOCUMENT ME!
808
         * @param listener
809
         * @param loader
810
         */
811
        public void addPopupMenuListener(String popupName, Component c,
812
                ActionListener listener, PluginClassLoader loader) {
813
                final String name = getName(popupName, loader);
814

    
815
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
816

    
817
                if (menu != null) {
818
                        Component[] jmenuitems = menu.getComponents();
819

    
820
                        for (int i = 0; i < jmenuitems.length; i++) {
821
                                if (jmenuitems[i] instanceof JMenuItem) {
822
                                        ((JMenuItem) jmenuitems[i]).addActionListener(listener);
823
                                }
824
                        }
825
                }
826

    
827
                c.addMouseListener(new MouseAdapter() {
828
                                public void mousePressed(MouseEvent e) {
829
                                        if (e.isPopupTrigger()) {
830
                                                showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
831
                                        }
832
                                }
833

    
834
                                public void mouseReleased(MouseEvent e) {
835
                                        if (e.isPopupTrigger()) {
836
                                                showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
837
                                        }
838
                                }
839
                        });
840
        }
841

    
842
        /**
843
         * Itera por los controles preguntando a las extensiones si estos est?n
844
         * habilitados y visibles
845
         *
846
         * @throws RuntimeException DOCUMENT ME!
847
         */
848
        public void enableControls() {
849
                if (!SwingUtilities.isEventDispatchThread()) {
850
                        throw new RuntimeException("No Event Dispatch Thread");
851
                }
852

    
853
                Iterator e = classesExtensions.values().iterator();
854
                HashMap estadoExtensiones = new HashMap();
855
                HashMap visibilidadExtensiones = new HashMap();
856

    
857
                while (e.hasNext()) {
858
                        ExtensionDecorator ext = (ExtensionDecorator) e.next();
859

    
860
                        try {
861
                                if (estadoExtensiones.get(ext) == null) {
862
                                        boolean b;
863
                                        if (ext.getVisibility() == ExtensionDecorator.ALWAYS_VISIBLE)
864
                                                b = true;
865
                                        else if (ext.getVisibility() == ExtensionDecorator.ALWAYS_INVISIBLE)
866
                                                b = false;
867
                                        else {
868
                                                if (PluginServices.getExclusiveUIExtension() == null) {
869
                                                        b = ext.isVisible();
870
                                                } else {
871
                                                        b = PluginServices.getExclusiveUIExtension().isVisible(ext.getExtension());
872
                                                }
873
                                        }
874
                                        Boolean visible = new Boolean(b);
875
                                        Boolean enabled = new Boolean(false);
876

    
877
                                        if (visible.booleanValue()) {
878
                                                if (PluginServices.getExclusiveUIExtension() == null) {
879
                                                        enabled = new Boolean(ext.isEnabled());
880
                                                }else {
881
                                                        enabled = new Boolean(PluginServices.getExclusiveUIExtension().isEnabled(ext.getExtension()));
882
                                                }
883
                                                
884
                                        }
885

    
886
                                        estadoExtensiones.put(ext, enabled);
887
                                        visibilidadExtensiones.put(ext, visible);
888
                                }
889
                        } catch (Throwable e1) {
890
                                NotificationManager.addError(Messages.getString(
891
                                                "MDIFrame.Error_no_capturado_por_el_usuario"), e1);
892
                                estadoExtensiones.put(ext, Boolean.FALSE);
893
                        }
894
                }
895

    
896
                //Se habilitan y deshabilitan los controles
897
                e = controlClass.keySet().iterator();
898

    
899
                while (e.hasNext()) {
900
                        JComponent control = (JComponent) e.next();
901

    
902
                        try {
903
                                com.iver.andami.plugins.IExtension ext = (com.iver.andami.plugins.IExtension) classesExtensions.get((Class) controlClass.get(
904
                                                        control));
905
                                boolean enabled = ((Boolean) estadoExtensiones.get(ext)).booleanValue();
906
                                boolean visible = ((Boolean) visibilidadExtensiones.get(ext)).booleanValue();
907
                                control.setEnabled(enabled);
908
                                control.setVisible(visible);
909
                        } catch (Exception ex) {
910
                                control.setEnabled(false);
911
                                control.setVisible(false);
912
                        }
913
                }
914

    
915
                //Se itera por los men?es para ocultar los que no tengan hijos visibles
916
                for (int i = 0; i < menuBar.getMenuCount(); i++) {
917
                        MenuElement menu = menuBar.getMenu(i);
918
                        ocultarMenus(menu);
919
                }
920

    
921
                //Se ocultan las barras que no tienen herramientas
922
                Iterator it = toolBarMap.values().iterator();
923

    
924
                while (it.hasNext()) {
925
                        SelectableToolBar t = (SelectableToolBar) it.next();
926
                        boolean todosOcultos = true;
927

    
928
                        for (int i = 0; i < t.getComponentCount(); i++) {
929
                                if (!(t.getComponent(i) instanceof JSeparator) // separators doesn't matter
930
                                                && t.getComponent(i).isVisible()) {
931
                                        todosOcultos = false;
932
                                }
933
                        }
934

    
935
                        if (todosOcultos) {
936
                                t.setVisible(false);
937
                        } else {
938
                                t.setVisible(true);
939
                        }
940
                }
941

    
942
                if (mdiManager != null) {
943
                        JPanel f = (JPanel) mdiManager.getActiveWindow();
944

    
945
                        if (f != null) {
946
                                if (lastLabelClass != f.getClass()) {
947
                                        lastLabelClass = f.getClass();
948

    
949
                                        Label[] lbls = (Label[]) classLabels.get(lastLabelClass);
950

    
951
                                        if (lbls != null) {
952
                                                bEstado.setLabelSet(lbls);
953
                                        }
954
                                }
955
                        }
956
                }
957

    
958
                ajustarToolBar();
959

    
960
                showMemory();
961
        }
962

    
963
        /**
964
         * Establece la visibilidad de un menu y todos sus descendientes en la
965
         * jerarquia teniendo en cuenta la visibilidad de todos los submenus.
966
         *
967
         * @param menu Menu que se quiere visualizar
968
         *
969
         * @return Devuelve true si el menu es visible y false en caso contrario
970
         */
971
        private boolean ocultarMenus(MenuElement menu) {
972
                MenuElement[] submenus = menu.getSubElements();
973

    
974
                //Si no tiene hijos se devuelve su visibilidad
975
                if (submenus.length == 0) {
976
                        return menu.getComponent().isVisible();
977
                }
978

    
979
                /*
980
                 * Si tiene hijos se devuelve true si alg?no de ellos es visible,
981
                 * pero se itera por todos ellos
982
                 */
983
                boolean visible = false;
984

    
985
                for (int i = 0; i < submenus.length; i++) {
986
                        if (ocultarMenus(submenus[i])) {
987
                                if (!(menu instanceof JPopupMenu)) {
988
                                        menu.getComponent().setVisible(true);
989
                                }
990

    
991
                                visible = true;
992
                        }
993
                }
994

    
995
                if (visible) {
996
                        return true;
997
                }
998

    
999
                menu.getComponent().setVisible(false);
1000

    
1001
                return false;
1002
        }
1003

    
1004
        /**
1005
         * Muestra la memoria consumida por el programa
1006
         */
1007
        private void showMemory() {
1008
                Runtime r = Runtime.getRuntime();
1009
                long mem = r.totalMemory() - r.freeMemory();
1010
                logger.debug("Memoria total: " + mem);
1011
        }
1012

    
1013
        /**
1014
         * DOCUMENT ME!
1015
         *
1016
         * @return
1017
         */
1018
        public MDIManager getMDIManager() {
1019
                return mdiManager;
1020
        }
1021

    
1022
        /**
1023
         * Establece el mensaje en la barra de estado asociado a una etiqueta
1024
         *
1025
         * @return DOCUMENT ME!
1026
         */
1027
        public NewStatusBar getStatusBar() {
1028
                return bEstado;
1029
        }
1030
        /**
1031
     * You can use this function to select the appropiate
1032
     * tool inside the toolbars
1033
     */
1034
    public void setSelectedTool(String actionCommand)
1035
    {
1036
        Iterator it = toolBarMap.values().iterator();
1037
        while (it.hasNext()) {
1038
            SelectableToolBar t = (SelectableToolBar) it.next();
1039
            t.setSelectedTool(actionCommand);
1040
        }
1041
        selectedTool = actionCommand;
1042

    
1043
    }
1044

    
1045
        /**
1046
         * DOCUMENT ME!
1047
         *
1048
         * @param clase
1049
         * @param label
1050
         */
1051
        public void setLabels(Class clase, Label[] label) {
1052
                classLabels.put(clase, label);
1053
        }
1054

    
1055
        public void addStatusBarControl(Class extensionClass, IControl control) {
1056
                control.addActionListener(this);
1057
                bEstado.addControl(control.getName(), (Component)control);
1058
                controlClass.put(control, extensionClass);
1059
        }
1060

    
1061
        /**
1062
         * @see com.iver.andami.ui.mdiFrame.MainFrame#removeMenu(com.iver.andami.plugins.config.generate.Menu)
1063
         */
1064
        public void removeMenu(Menu menu) {
1065
                JMenuItem delete = (JMenuItem) infoCodedMenus.get(menu);
1066

    
1067
                if (delete == null) {
1068
                        throw new NoSuchElementException(menu.getText());
1069
                }
1070

    
1071
                delete.getParent().remove(delete);
1072
                infoCodedMenus.remove(menu);
1073
        }
1074

    
1075
        /**
1076
         * @see com.iver.andami.ui.mdiFrame.MainFrame#addMenu(com.iver.andami.plugins.config.generate.Menu,
1077
         *                 java.awt.event.ActionListener, PluginClassLoader)
1078
         */
1079
        public void addMenu(Menu menu, ActionListener listener,
1080
                PluginClassLoader loader) {
1081
                JMenu menuPadre = createMenuAncestors(menu, loader);
1082

    
1083
                //Se registra y a?ade el menu
1084
                JMenuItem nuevoMenu = createJMenuItem(loader, menu);
1085
                nuevoMenu.addMouseListener(tooltipListener);
1086
                nuevoMenu.addActionListener(listener);
1087
                menuPadre.add(nuevoMenu);
1088

    
1089
                infoCodedMenus.put(menu, nuevoMenu);
1090
        }
1091

    
1092
        /**
1093
         * @see com.iver.andami.ui.mdiFrame.MainFrame#changeMenuName(java.lang.String[],
1094
         *                 String, com.iver.andami.plugins.PluginClassLoader)
1095
         */
1096
        public void changeMenuName(String[] menu, String newName,
1097
                PluginClassLoader loader) {
1098
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
1099

    
1100
                for (int i = 0; i < menu.length; i++) {
1101
                        menu[i] = ps.getText(menu[i]);
1102
                }
1103

    
1104
                JMenu menuPadre = null;
1105

    
1106
                //Se busca el padre en la menuBar
1107
                for (int i = 0; i < menuBar.getMenuCount(); i++) {
1108
                        if (menuBar.getMenu(i).getText().compareToIgnoreCase(menu[0]) == 0) {
1109
                                menuPadre = (JMenu) menuBar.getMenu(i);
1110
                        }
1111
                }
1112

    
1113
                if (menuPadre == null) {
1114
                        throw new NoSuchMenuException(menu[0]);
1115
                }
1116

    
1117
                Vector nombres = new Vector();
1118

    
1119
                for (int i = 1; i < menu.length; i++) {
1120
                        nombres.add(menu[i]);
1121
                }
1122

    
1123
                javax.swing.JMenuItem m = getMenu(nombres, menuPadre);
1124

    
1125
                if (m != null) {
1126
                        m.setText(newName);
1127
                }else{
1128
                        throw new NoSuchMenuException();
1129
                }
1130
        }
1131

    
1132
        /**
1133
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
1134
         */
1135
        public void componentHidden(ComponentEvent arg0) {
1136
        }
1137

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

    
1144
        /**
1145
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
1146
         */
1147
        public void componentResized(ComponentEvent arg0) {
1148
                ajustarToolBar();
1149
                bEstado.setFixedLabelWidth(this.getWidth() * 0.3);
1150
        }
1151

    
1152
        /**
1153
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
1154
         */
1155
        public void componentShown(ComponentEvent arg0) {
1156
        }
1157

    
1158
        /**
1159
         * @see java.awt.event.ContainerListener#componentAdded(java.awt.event.ContainerEvent)
1160
         */
1161
        public void componentAdded(ContainerEvent arg0) {
1162
                ajustarToolBar();
1163
        }
1164

    
1165
        /**
1166
         * @see java.awt.event.ContainerListener#componentRemoved(java.awt.event.ContainerEvent)
1167
         */
1168
        public void componentRemoved(ContainerEvent arg0) {
1169
                ajustarToolBar();
1170
        }
1171

    
1172
        /**
1173
         * DOCUMENT ME!
1174
         *
1175
         * @author $author$
1176
         * @version $Revision: 9403 $
1177
         */
1178
        public class TooltipListener extends MouseAdapter {
1179
                /**
1180
                 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1181
                 */
1182
                public void mouseEntered(MouseEvent e) {
1183
                        JComponent control = (JComponent) e.getSource();
1184
                        EnableTextSupport ets = (EnableTextSupport) e.getSource();
1185

    
1186
                        String texto = null;
1187
                        texto = control.getToolTipText();
1188

    
1189
                        if (texto != null) {
1190
                                bEstado.setInfoTextTemporal(texto);
1191
                        }
1192
                }
1193

    
1194
                /**
1195
                 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1196
                 */
1197
                public void mouseExited(MouseEvent arg0) {
1198
                        bEstado.restaurarTexto();
1199
                }
1200

    
1201
                /**
1202
                 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1203
                 */
1204
                public void mousePressed(MouseEvent e) {
1205
                        bEstado.restaurarTexto();
1206
                }
1207
        }
1208
        public String getTitlePrefix() {
1209
                return titlePrefix;
1210
        }
1211
        public void setTitlePrefix(String titlePrefix) {
1212
                this.titlePrefix = titlePrefix;
1213
        }
1214

    
1215
    public String getSelectedTool() {
1216
        return selectedTool;
1217
    }
1218

    
1219

    
1220
    /**
1221
     * Get a previously added JComponent by name. For example
1222
     * you can use it if you need to obtain a JToolBar to
1223
     * add some customized component.
1224
     * @param name
1225
     * @return the JComponent or null if none has been found
1226
     */
1227
    public JComponent getComponentByName(String name)
1228
    {
1229
        Iterator e = controlClass.keySet().iterator();
1230

    
1231
        while (e.hasNext()) {
1232
            JComponent control = (JComponent) e.next();
1233
            String nameCtrl = control.getName();
1234
            if (nameCtrl != null)
1235
                    if (nameCtrl.compareTo(name) == 0)
1236
                            return control;
1237
        }
1238
        Iterator it = toolBarMap.values().iterator();
1239
        while (it.hasNext()) {
1240
            SelectableToolBar t = (SelectableToolBar) it.next();
1241
            String nameCtrl = t.getName();
1242
            if (nameCtrl != null)
1243
                    if (nameCtrl.compareTo(name) == 0)
1244
                            return t;
1245

    
1246
        }
1247

    
1248
        return null;
1249
    }
1250
}