Statistics
| Revision:

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

History | View | Annotate | Download (33.8 KB)

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

    
43
import 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: 10972 $
106
 */
107
public class MDIFrame extends JFrame implements ComponentListener,
108
        ContainerListener, ActionListener, MainFrame {
109
        /** DOCUMENT ME! */
110
        private static Logger logger = Logger.getLogger(MDIFrame.class.getName());
111
        private MDIManager mdiManager = MDIManagerFactory.createManager();
112

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
192
                //Se configura la barra de menu
193
                setJMenuBar(menuBar);
194

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

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

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

    
213
                this.toolBars.addContainerListener(this);
214

    
215
                pack();
216

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

    
222
                mdiManager.init(this);
223
        }
224

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

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

    
247
                // Para traducir
248
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
249

    
250
                JToolBarToggleButton btn;
251
                URL image = loader.getResource(selectableTool.getIcon());
252

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

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

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

    
274
                String name = getName(toolBar.getName(), loader);
275

    
276
                SelectableToolBar jtb = (SelectableToolBar) toolBarMap.get(name);
277

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

    
284
                }
285

    
286
                jtb.addButton(buttonGroup, btn);
287
                controlClass.put(btn, loader.loadClass(ext.getClassName()));
288
                if (selectableTool.getName() != null) {
289
                        btn.setName(selectableTool.getName());
290
                }
291
                if (selectableTool.getTooltip() != null) {
292
                        btn.setToolTip(ps.getText(selectableTool.getTooltip()));
293
                }
294

    
295
                if (selectableTool.getEnableText() != null) {
296
                        btn.setEnableText(ps.getText(selectableTool.getEnableText()));
297
                }
298

    
299
                if (selectableTool.getLast() == true) {
300
                        jtb.addSeparator();
301
                }
302
        }
303

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

    
321
                // Para traducir los textos que vengan
322
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
323

    
324
                JToolBarButton btn;
325
                URL image = loader.getResource(actionTool.getIcon());
326

    
327
                if (image != null) {
328
                        btn = new JToolBarButton(actionTool.getText(), new ImageIcon(image));
329
                } else {
330
                        btn = new JToolBarButton(actionTool.getText());
331
                }
332

    
333
                btn.setMargin(new Insets(0, 0, 0, 0));
334
                btn.addMouseListener(tooltipListener);
335
                btn.addActionListener(this);
336
                btn.setFocusable(false);
337
                btn.setActionCommand(actionTool.getActionCommand());
338
                btn.setEnabled(false);
339
                btn.setVisible(false);
340

    
341
                String name = getName(toolBar.getName(), loader);
342

    
343
                SelectableToolBar jtb = (SelectableToolBar) toolBarMap.get(name);
344

    
345
                if (jtb == null) {
346
                        jtb = new SelectableToolBar(toolBar.getName());
347
                        jtb.setRollover(true);
348
                        toolBarMap.put(name, jtb);
349
                        toolBars.add(jtb);
350
                }
351

    
352
                jtb.add(btn);
353

    
354
                controlClass.put(btn, loader.loadClass(ext.getClassName()));
355

    
356
                if (actionTool.getName() != null) {
357
                        btn.setName(actionTool.getName());
358
                }
359
                
360
                if (actionTool.getTooltip() != null) {
361
                        btn.setToolTip(ps.getText(actionTool.getTooltip()));
362
                }
363

    
364
                if (actionTool.getEnableText() != null) {
365
                        btn.setEnableText(ps.getText(actionTool.getEnableText()));
366
                }
367

    
368
                if (actionTool.getLast() == true) {
369
                        jtb.addSeparator();
370
                }
371
        }
372

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

    
390
                String[] menues = menu.getText().split("/");
391
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
392

    
393
                for (int i = 0; i < menues.length; i++) {
394
                        menues[i] = ps.getText(menues[i]);
395
                }
396

    
397
                //Se busca el padre en la menuBar
398
                for (int i = 0; i < menuBar.getMenuCount(); i++) {
399
                        if (menuBar.getMenu(i).getText().compareToIgnoreCase(menues[0]) == 0) {
400
                                menuPadre = (JMenu) menuBar.getMenu(i);
401
                        }
402
                }
403

    
404
                //Si no se encuentra el padre se crea
405
                if (menuPadre == null) {
406
                        menuPadre = new JMenu(menues[0]);
407
                        menuBar.add(menuPadre);
408
                }
409

    
410
                //Se crea el resto de menus
411
                Vector temp = new Vector();
412

    
413
                for (int i = 1; i < (menues.length - 1); i++) {
414
                        temp.add(menues[i]);
415
                }
416

    
417
                menuPadre = createMenus(temp, menuPadre);
418

    
419
                return menuPadre;
420
        }
421

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

    
442
                JMenu menuPadre = createMenuAncestors(menu, loader);
443

    
444
                //Se registra y a?ade el menu
445
        /* String[] aux = menu.getText().split("/");
446

447
        if (aux.length == 2)
448
            if (aux[1].equals("----"))
449
            {
450
                menuPadre.addSeparator();
451
                return;
452
            } */
453
        if (menu.getIs_separator())
454
        {
455
            menuPadre.addSeparator();
456
            return;
457
        }
458

    
459
                JMenuItem nuevoMenu = createJMenuItem(loader, menu);
460
                nuevoMenu.addMouseListener(tooltipListener);
461
                nuevoMenu.addActionListener(this);
462
                menuPadre.add(nuevoMenu);
463
        controlClass.put(nuevoMenu, loader.loadClass(ext.getClassName()));
464
        }
465

    
466
        /**
467
         * Dado un array de nombres de menu traducidos, encuentra el  men?
468
         *
469
         * @param nombres DOCUMENT ME!
470
         * @param padre DOCUMENT ME!
471
         *
472
         * @return DOCUMENT ME!
473
         */
474
        private javax.swing.JMenuItem getMenu(Vector nombres, JMenu padre) {
475
                javax.swing.JMenuItem buscado = null;
476
                javax.swing.JMenuItem hijo;
477

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

    
482
                                if (hijo.getText().compareToIgnoreCase((String) nombres.get(0)) == 0) {
483
                                        buscado = hijo;
484
                                }
485
                        }
486
                }
487

    
488
                //Si no se encuentra el menu
489
                if (buscado == null) {
490
                        return null;
491
                }
492

    
493
                nombres.remove(0);
494

    
495
                //Si se ha llegado al fin de la ruta completa
496
                if (nombres.isEmpty()) {
497
                        return buscado;
498
                } else {
499
                        if (buscado instanceof JMenu) {
500
                                return getMenu(nombres, (JMenu) buscado);
501
                        } else {
502
                                return null;
503
                        }
504
                }
505
        }
506

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

    
527
                //si no quedan nombres de menu por crear se vuelve: caso base
528
                if (nombres.size() == 0) {
529
                        return padre;
530
                }
531

    
532
                //Se busca el menu por si ya existiera para no crearlo otra vez
533
                JMenu buscado = null;
534

    
535
                for (int i = 0; i < padre.getMenuComponentCount(); i++) {
536
                        try {
537
                                JMenu hijo = (JMenu) padre.getMenuComponent(i);
538

    
539
                                if (hijo.getText().compareToIgnoreCase((String) nombres.get(0)) == 0) {
540
                                        buscado = hijo;
541
                                }
542
                        } catch (ClassCastException e) {
543
                                /*
544
                                 * Se ha encontrado un elemento hoja del arbol de men?es
545
                                 */
546
                        }
547
                }
548

    
549
                if (buscado != null) {
550
                        //Si lo hemos encontrado creamos el resto
551
                        nombres.remove(0);
552

    
553
                        return createMenus(nombres, buscado);
554
                } else {
555
                        //Si no lo hemos encontrado se crea el menu, se a?ade al padre
556
                        //y se crea el resto
557
                        JMenu menuPadre = new JMenu((String) nombres.get(0));
558
                        padre.add(menuPadre);
559

    
560
                        nombres.remove(0);
561

    
562
                        return createMenus(nombres, menuPadre);
563
                }
564
        }
565

    
566
        /**
567
         * M?todo invocado en respuesta a ciertos eventos de la interfaz que pueden
568
         * ocultar botones de las barras de herramientas y que redimensiona ?sta
569
         * de manera conveniente para que no se oculte ninguno
570
         */
571
        private void ajustarToolBar() {
572
                int margen = 8;
573
                int numFilas = 1;
574
                double acum = margen;
575

    
576
                int toolHeight = 0;
577

    
578
                for (int i = 0; i < toolBars.getComponentCount(); i++) {
579
                        Component c = toolBars.getComponent(i);
580

    
581
                        if (!c.isVisible()) {
582
                                continue;
583
                        }
584

    
585
                        double width = c.getPreferredSize().getWidth();
586
                        acum = acum + width;
587

    
588
                        if (acum > this.getWidth()) {
589
                                numFilas++;
590
                                acum = width + margen;
591
                        }
592

    
593
                        if (c.getPreferredSize().getHeight() > toolHeight) {
594
                                toolHeight = c.getPreferredSize().height;
595
                        }
596
                }
597

    
598
                toolBars.setPreferredSize(new Dimension(this.getWidth(),
599
                                (int) (numFilas * toolHeight)));
600

    
601
                toolBars.updateUI();
602
        }
603

    
604
        /**
605
         * DOCUMENT ME!
606
         *
607
         * @param classesExtensions
608
         */
609
        public void setClassesExtensions(HashMap classesExtensions) {
610
                this.classesExtensions = classesExtensions;
611
        }
612

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

    
639
                enableControls();
640
                showMemory();
641
        }
642

    
643
        /**
644
         * DOCUMENT ME!
645
         *
646
         * @param name DOCUMENT ME!
647
         * @param loader DOCUMENT ME!
648
         *
649
         * @return DOCUMENT ME!
650
         */
651
        private String getName(String name, PluginClassLoader loader) {
652
                if (name.indexOf('.') == -1) {
653
                        return loader.getPluginName() + "." + name;
654
                } else {
655
                        return name;
656
                }
657
        }
658

    
659
        /**
660
         * DOCUMENT ME!
661
         *
662
         * @param loader DOCUMENT ME!
663
         * @param menu DOCUMENT ME!
664
         *
665
         * @throws RuntimeException DOCUMENT ME!
666
         */
667
        public void addPopupMenu(PluginClassLoader loader, PopupMenu menu) {
668
                if (!SwingUtilities.isEventDispatchThread()) {
669
                        throw new RuntimeException("No Event Dispatch Thread");
670
                }
671

    
672
                String name = getName(menu.getName(), loader);
673

    
674
                //Se crea el control popupmenu
675
                JPopUpMenu popupMenu = (JPopUpMenu) popupMap.get(name);
676

    
677
                if (popupMenu == null) {
678
                        popupMenu = new JPopUpMenu(menu.getName());
679
                        popupMap.put(name, popupMenu);
680
                }
681

    
682
                // Se a?aden las entradas
683
                Menu[] menues = menu.getMenu();
684

    
685
                for (int i = 0; i < menues.length; i++) {
686
                        //Se registra y a?ade el menu
687
                        JMenuItem nuevoMenu = createJMenuItem(loader, menues[i]);
688

    
689
                        popupMenu.add(nuevoMenu);
690
                }
691
        }
692

    
693
        /**
694
         * DOCUMENT ME!
695
         *
696
         * @param loader
697
         * @param menu
698
         *
699
         * @return
700
         *
701
         * @throws RuntimeException DOCUMENT ME!
702
         */
703
        private JMenuItem createJMenuItem(PluginClassLoader loader, Menu menu) {
704
                JMenuItem nuevoMenu = null;
705

    
706
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
707
                String texto = menu.getText();
708
                texto = texto.substring(texto.lastIndexOf('/') + 1);
709
                texto = ps.getText(texto);
710

    
711
                if (menu.getIcon() != null) {
712
                        URL url = loader.getResource(menu.getIcon());
713
                        if (url != null) {
714
                                nuevoMenu = new JMenuItem(texto, new ImageIcon(url));
715
                        } else {
716
                                NotificationManager.addError(PluginServices.getText(this, "Unable_to_find_icon") +": "+menu.getIcon(), new FileNotFoundException());
717
                        }
718
                } else {
719
                        nuevoMenu = new JMenuItem(texto);
720
                }
721

    
722
                if (menu.getMnemonic() != null) {
723
                        if (menu.getMnemonic().length() != 1) {
724
                                throw new RuntimeException(
725
                                        "Mnemonic must be 1 character length");
726
                        }
727

    
728
                        nuevoMenu.setMnemonic(KeyMapping.getKey(menu.getMnemonic().charAt(0)));
729
                }
730

    
731
                if (menu.getKey() != null) {
732
                        String osName = (String) System.getProperty("os.name");
733
                        if (osName.length() > 5 && osName.substring(0,6).toLowerCase().equals("mac os")) {
734
                                nuevoMenu.setAccelerator(KeyStroke.getKeyStroke(KeyMapping.getKey(
735
                                                menu.getKey().charAt(0)), Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
736
                        } else {
737
                                nuevoMenu.setAccelerator(KeyStroke.getKeyStroke(KeyMapping.getKey(
738
                                                menu.getKey().charAt(0)), ActionEvent.ALT_MASK));
739
                        }
740
                }
741

    
742
                nuevoMenu.setActionCommand(menu.getActionCommand());
743

    
744
                if (menu.getTooltip() != null) {
745
                        nuevoMenu.setToolTip(ps.getText(menu.getTooltip()));
746
                }
747

    
748
                if (menu.getEnableText() != null) {
749
                        nuevoMenu.setEnableText(ps.getText(menu.getEnableText()));
750
                }
751

    
752
                nuevoMenu.setEnabled(true);
753
                nuevoMenu.setVisible(true);
754

    
755
                return nuevoMenu;
756
        }
757

    
758
        /**
759
         * Muestra u oculta el menu de nombre 'name'
760
         *
761
         * @param name Nombre del menu que se quiere mostrar
762
         * @param x Evento de raton
763
         * @param y DOCUMENT ME!
764
         * @param c DOCUMENT ME!
765
         */
766
        private void showPopupMenu(String name, int x, int y, Component c) {
767
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
768

    
769
                if (menu != null) {
770
                        menu.show(c, x, y);
771
                }
772
        }
773

    
774
        /**
775
         * DOCUMENT ME!
776
         *
777
         * @param name DOCUMENT ME!
778
         * @param listener DOCUMENT ME!
779
         */
780
        public void removePopupMenuListener(String name, ActionListener listener) {
781
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
782

    
783
                if (menu != null) {
784
                        Component[] jmenuitems = menu.getComponents();
785

    
786
                        for (int i = 0; i < jmenuitems.length; i++) {
787
                                if (jmenuitems[i] instanceof JMenuItem) {
788
                                        ((JMenuItem) jmenuitems[i]).removeActionListener(listener);
789
                                }
790
                        }
791
                }
792
        }
793

    
794
        /**
795
         * DOCUMENT ME!
796
         *
797
         * @param popupName
798
         * @param c DOCUMENT ME!
799
         * @param listener
800
         * @param loader
801
         */
802
        public void addPopupMenuListener(String popupName, Component c,
803
                ActionListener listener, PluginClassLoader loader) {
804
                final String name = getName(popupName, loader);
805

    
806
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
807

    
808
                if (menu != null) {
809
                        Component[] jmenuitems = menu.getComponents();
810

    
811
                        for (int i = 0; i < jmenuitems.length; i++) {
812
                                if (jmenuitems[i] instanceof JMenuItem) {
813
                                        ((JMenuItem) jmenuitems[i]).addActionListener(listener);
814
                                }
815
                        }
816
                }
817

    
818
                c.addMouseListener(new MouseAdapter() {
819
                                public void mousePressed(MouseEvent e) {
820
                                        if (e.isPopupTrigger()) {
821
                                                showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
822
                                        }
823
                                }
824

    
825
                                public void mouseReleased(MouseEvent e) {
826
                                        if (e.isPopupTrigger()) {
827
                                                showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
828
                                        }
829
                                }
830
                        });
831
        }
832

    
833
        /**
834
         * Itera por los controles preguntando a las extensiones si estos est?n
835
         * habilitados y visibles
836
         *
837
         * @throws RuntimeException DOCUMENT ME!
838
         */
839
        public void enableControls() {
840
                if (!SwingUtilities.isEventDispatchThread()) {
841
                        throw new RuntimeException("No Event Dispatch Thread");
842
                }
843

    
844
                Iterator e = classesExtensions.values().iterator();
845
                HashMap estadoExtensiones = new HashMap();
846
                HashMap visibilidadExtensiones = new HashMap();
847

    
848
                while (e.hasNext()) {
849
                        ExtensionDecorator ext = (ExtensionDecorator) e.next();
850

    
851
                        try {
852
                                if (estadoExtensiones.get(ext) == null) {
853
                                        boolean b;
854
                                        if (ext.getVisibility() == ExtensionDecorator.ALWAYS_VISIBLE)
855
                                                b = true;
856
                                        else if (ext.getVisibility() == ExtensionDecorator.ALWAYS_INVISIBLE)
857
                                                b = false;
858
                                        else {
859
                                                if (PluginServices.getExclusiveUIExtension() == null) {
860
                                                        b = ext.isVisible();
861
                                                } else {
862
                                                        b = PluginServices.getExclusiveUIExtension().isVisible(ext.getExtension());
863
                                                }
864
                                        }
865
                                        Boolean visible = new Boolean(b);
866
                                        Boolean enabled = new Boolean(false);
867

    
868
                                        if (visible.booleanValue()) {
869
                                                if (PluginServices.getExclusiveUIExtension() == null) {
870
                                                        enabled = new Boolean(ext.isEnabled());
871
                                                }else {
872
                                                        enabled = new Boolean(PluginServices.getExclusiveUIExtension().isEnabled(ext.getExtension()));
873
                                                }
874
                                                
875
                                        }
876

    
877
                                        estadoExtensiones.put(ext, enabled);
878
                                        visibilidadExtensiones.put(ext, visible);
879
                                }
880
                        } catch (Throwable e1) {
881
                                NotificationManager.addError(Messages.getString(
882
                                                "MDIFrame.Error_no_capturado_por_el_usuario"), e1);
883
                                estadoExtensiones.put(ext, Boolean.FALSE);
884
                        }
885
                }
886

    
887
                //Se habilitan y deshabilitan los controles
888
                e = controlClass.keySet().iterator();
889

    
890
                while (e.hasNext()) {
891
                        JComponent control = (JComponent) e.next();
892

    
893
                        try {
894
                                com.iver.andami.plugins.IExtension ext = (com.iver.andami.plugins.IExtension) classesExtensions.get((Class) controlClass.get(
895
                                                        control));
896
                                boolean enabled = ((Boolean) estadoExtensiones.get(ext)).booleanValue();
897
                                boolean visible = ((Boolean) visibilidadExtensiones.get(ext)).booleanValue();
898
                                control.setEnabled(enabled);
899
                                control.setVisible(visible);
900
                        } catch (Exception ex) {
901
                                control.setEnabled(false);
902
                                control.setVisible(false);
903
                        }
904
                }
905

    
906
                //Se itera por los men?es para ocultar los que no tengan hijos visibles
907
                for (int i = 0; i < menuBar.getMenuCount(); i++) {
908
                        MenuElement menu = menuBar.getMenu(i);
909
                        ocultarMenus(menu);
910
                }
911

    
912
                //Se ocultan las barras que no tienen herramientas
913
                Iterator it = toolBarMap.values().iterator();
914

    
915
                while (it.hasNext()) {
916
                        SelectableToolBar t = (SelectableToolBar) it.next();
917
                        boolean todosOcultos = true;
918

    
919
                        for (int i = 0; i < t.getComponentCount(); i++) {
920
                                if (!(t.getComponent(i) instanceof JSeparator) // separators doesn't matter
921
                                                && t.getComponent(i).isVisible()) {
922
                                        todosOcultos = false;
923
                                }
924
                        }
925

    
926
                        if (todosOcultos) {
927
                                t.setVisible(false);
928
                        } else {
929
                                t.setVisible(true);
930
                        }
931
                }
932

    
933
                if (mdiManager != null) {
934
                        JPanel f = (JPanel) mdiManager.getActiveWindow();
935

    
936
                        if (f != null) {
937
                                if (lastLabelClass != f.getClass()) {
938
                                        lastLabelClass = f.getClass();
939

    
940
                                        Label[] lbls = (Label[]) classLabels.get(lastLabelClass);
941

    
942
                                        if (lbls != null) {
943
                                                bEstado.setLabelSet(lbls);
944
                                        }
945
                                }
946
                        }
947
                }
948

    
949
                ajustarToolBar();
950

    
951
                showMemory();
952
        }
953

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

    
965
                //Si no tiene hijos se devuelve su visibilidad
966
                if (submenus.length == 0) {
967
                        return menu.getComponent().isVisible();
968
                }
969

    
970
                /*
971
                 * Si tiene hijos se devuelve true si alg?no de ellos es visible,
972
                 * pero se itera por todos ellos
973
                 */
974
                boolean visible = false;
975

    
976
                for (int i = 0; i < submenus.length; i++) {
977
                        if (ocultarMenus(submenus[i])) {
978
                                if (!(menu instanceof JPopupMenu)) {
979
                                        menu.getComponent().setVisible(true);
980
                                }
981

    
982
                                visible = true;
983
                        }
984
                }
985

    
986
                if (visible) {
987
                        return true;
988
                }
989

    
990
                menu.getComponent().setVisible(false);
991

    
992
                return false;
993
        }
994

    
995
        /**
996
         * Muestra la memoria consumida por el programa
997
         */
998
        private void showMemory() {
999
                Runtime r = Runtime.getRuntime();
1000
                long mem = r.totalMemory() - r.freeMemory();
1001
                logger.debug("Memoria total: " + mem);
1002
        }
1003

    
1004
        /**
1005
         * DOCUMENT ME!
1006
         *
1007
         * @return
1008
         */
1009
        public MDIManager getMDIManager() {
1010
                return mdiManager;
1011
        }
1012

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

    
1034
    }
1035

    
1036
        /**
1037
         * DOCUMENT ME!
1038
         *
1039
         * @param clase
1040
         * @param label
1041
         */
1042
        public void setStatusBarLabels(Class clase, Label[] label) {
1043
                classLabels.put(clase, label);
1044
        }
1045
        
1046
        
1047
        public void removeStatusBarLabels(Class clase) {
1048
                classLabels.remove(clase);
1049
        }
1050

    
1051
        public void addStatusBarControl(Class extensionClass, IControl control) {
1052
                control.addActionListener(this);
1053
                bEstado.addControl(control.getName(), (Component)control);
1054
                controlClass.put(control, extensionClass);
1055
        }
1056

    
1057
        /**
1058
         * @see com.iver.andami.ui.mdiFrame.MainFrame#removeMenu(com.iver.andami.plugins.config.generate.Menu)
1059
         */
1060
        public void removeMenu(Menu menu) {
1061
                JMenuItem delete = (JMenuItem) infoCodedMenus.get(menu);
1062

    
1063
                if (delete == null) {
1064
                        throw new NoSuchElementException(menu.getText());
1065
                }
1066

    
1067
                delete.getParent().remove(delete);
1068
                infoCodedMenus.remove(menu);
1069
        }
1070

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

    
1079
                //Se registra y a?ade el menu
1080
                JMenuItem nuevoMenu = createJMenuItem(loader, menu);
1081
                nuevoMenu.addMouseListener(tooltipListener);
1082
                nuevoMenu.addActionListener(listener);
1083
                menuPadre.add(nuevoMenu);
1084

    
1085
                infoCodedMenus.put(menu, nuevoMenu);
1086
        }
1087

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

    
1096
                for (int i = 0; i < menu.length; i++) {
1097
                        menu[i] = ps.getText(menu[i]);
1098
                }
1099

    
1100
                JMenu menuPadre = null;
1101

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

    
1109
                if (menuPadre == null) {
1110
                        throw new NoSuchMenuException(menu[0]);
1111
                }
1112

    
1113
                Vector nombres = new Vector();
1114

    
1115
                for (int i = 1; i < menu.length; i++) {
1116
                        nombres.add(menu[i]);
1117
                }
1118

    
1119
                javax.swing.JMenuItem m = getMenu(nombres, menuPadre);
1120

    
1121
                if (m != null) {
1122
                        m.setText(newName);
1123
                }else{
1124
                        throw new NoSuchMenuException();
1125
                }
1126
        }
1127

    
1128
        /**
1129
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
1130
         */
1131
        public void componentHidden(ComponentEvent arg0) {
1132
        }
1133

    
1134
        /**
1135
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
1136
         */
1137
        public void componentMoved(ComponentEvent arg0) {
1138
        }
1139

    
1140
        /**
1141
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
1142
         */
1143
        public void componentResized(ComponentEvent arg0) {
1144
                ajustarToolBar();
1145
        }
1146

    
1147
        /**
1148
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
1149
         */
1150
        public void componentShown(ComponentEvent arg0) {
1151
        }
1152

    
1153
        /**
1154
         * @see java.awt.event.ContainerListener#componentAdded(java.awt.event.ContainerEvent)
1155
         */
1156
        public void componentAdded(ContainerEvent arg0) {
1157
                ajustarToolBar();
1158
        }
1159

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

    
1167
        /**
1168
         * DOCUMENT ME!
1169
         *
1170
         * @author $author$
1171
         * @version $Revision: 10972 $
1172
         */
1173
        public class TooltipListener extends MouseAdapter {
1174
                /**
1175
                 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1176
                 */
1177
                public void mouseEntered(MouseEvent e) {
1178
                        JComponent control = (JComponent) e.getSource();
1179
                        EnableTextSupport ets = (EnableTextSupport) e.getSource();
1180

    
1181
                        String texto = null;
1182
                        texto = control.getToolTipText();
1183

    
1184
                        if (texto != null) {
1185
                                bEstado.setInfoTextTemporal(texto);
1186
                        }
1187
                }
1188

    
1189
                /**
1190
                 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1191
                 */
1192
                public void mouseExited(MouseEvent arg0) {
1193
                        bEstado.restaurarTexto();
1194
                }
1195

    
1196
                /**
1197
                 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1198
                 */
1199
                public void mousePressed(MouseEvent e) {
1200
                        bEstado.restaurarTexto();
1201
                }
1202
        }
1203
        public String getTitlePrefix() {
1204
                return titlePrefix;
1205
        }
1206
        public void setTitlePrefix(String titlePrefix) {
1207
                this.titlePrefix = titlePrefix;
1208
        }
1209

    
1210
    public String getSelectedTool() {
1211
        return selectedTool;
1212
    }
1213

    
1214

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

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

    
1247
        }
1248

    
1249
        return null;
1250
    }
1251

    
1252
    public JMenuBar getJMenuBar() {
1253
            return menuBar;
1254
    }
1255
}