Statistics
| Revision:

root / branches / v2_0_0_prep / frameworks / _fwAndami / src / org / gvsig / andami / ui / mdiFrame / MDIFrame.java @ 38608

History | View | Annotate | Download (58.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 org.gvsig.andami.ui.mdiFrame;
42

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

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

    
84
import org.gvsig.andami.IconThemeHelper;
85
import org.gvsig.andami.Launcher;
86
import org.gvsig.andami.LibraryExtension;
87
import org.gvsig.andami.PluginServices;
88
import org.gvsig.andami.PluginsLocator;
89
import org.gvsig.andami.actioninfo.ActionInfo;
90
import org.gvsig.andami.actioninfo.ActionInfoManager;
91
import org.gvsig.andami.actioninfo.ActionInfoStatusCache;
92
import org.gvsig.andami.messages.Messages;
93
import org.gvsig.andami.plugins.ExtensionDecorator;
94
import org.gvsig.andami.plugins.IExtension;
95
import org.gvsig.andami.plugins.PluginClassLoader;
96
import org.gvsig.andami.plugins.config.generate.ActionTool;
97
import org.gvsig.andami.plugins.config.generate.Label;
98
import org.gvsig.andami.plugins.config.generate.Menu;
99
import org.gvsig.andami.plugins.config.generate.PopupMenu;
100
import org.gvsig.andami.plugins.config.generate.SelectableTool;
101
import org.gvsig.andami.plugins.config.generate.SkinExtensionType;
102
import org.gvsig.andami.plugins.config.generate.ToolBar;
103
import org.gvsig.andami.ui.mdiManager.MDIManager;
104
import org.gvsig.andami.ui.mdiManager.MDIManagerFactory;
105
import org.gvsig.gui.beans.controls.IControl;
106
import org.gvsig.tools.swing.api.ToolsSwingLocator;
107
import org.gvsig.tools.swing.icontheme.IconTheme;
108
import org.slf4j.Logger;
109
import org.slf4j.LoggerFactory;
110

    
111
/**
112
 * Main application window.
113
 * 
114
 * @version $Revision: 38608 $
115
 */
116
public class MDIFrame extends JFrame implements ComponentListener,
117
    ContainerListener, ActionListener, MainFrame {
118

    
119
    private static final long serialVersionUID = -2472484309160847654L;
120

    
121
    private static Logger logger = LoggerFactory.getLogger(MDIFrame.class);
122
    private MDIManager mdiManager = MDIManagerFactory.createManager();
123

    
124
    /** Elementos de la aplicaci�n */
125
    private JMenuBar menuBar = new JMenuBar();
126

    
127
    /** Panel which contains the toolbars */
128
    private JPanel toolBars = new JPanel();
129

    
130
    /** Status bar */
131
    private NewStatusBar bEstado = null;
132

    
133
    /** Asocia los nombres con las barras de herramientas */
134
    private HashMap toolBarMap = new HashMap();
135

    
136
    /** Almacena los grupos de selectableTools */
137
    private HashMap buttonGroupMap = new HashMap();
138
    /**
139
     * Stores the initially selected tools.
140
     * It contains pairs (String groupName, JToolBarToggleButton button)
141
     */
142
    private HashMap initialSelectedTools = new HashMap();
143

    
144
    /**
145
     * Stores the actionCommand of the selected tool, for each group.
146
     * It contains pairs (String groupName, JToolBarToggleButton button)
147
     */
148
    private Map selectedTool = null;
149
    // this should be the same value defined at plugin-config.xsd
150
    private String defaultGroup = "unico";
151

    
152
    /** Asocia los nombres con los popupMenus */
153
    private HashMap popupMap = new HashMap();
154

    
155
    /** Asocia controles con la clase de la extension asociada */
156
    private HashMap controlClass = new HashMap();
157

    
158
    /**
159
     * Asocia la informaci�n sobre las etiquetas que van en la status bar con
160
     * cada extension
161
     */
162
    private HashMap classLabels = new HashMap();
163

    
164
    // private HashMap classControls = new HashMap();
165

    
166
    /** ProgressListeners (ver interfaz com.iver.mdiApp.ui.ProgressListener) */
167
    private ArrayList progressListeners = new ArrayList();
168

    
169
    /** Timer para invocar los enventos de la interfaz anterior */
170
    private Timer progressTimer = null;
171

    
172
    /** Tabla hash que asocia las clases con las extensiones */
173
    private Map classesExtensions = new HashMap<Class<? extends IExtension>, ExtensionDecorator>();
174

    
175
    /** �ltima clase que activ� etiquetas */
176
    private Class lastLabelClass;
177

    
178
    /** Instancia que pone los tooltip en la barra de estado */
179
    private TooltipListener tooltipListener = new TooltipListener();
180
    private HashMap infoCodedMenus = new HashMap();
181

    
182
    private String titlePrefix;
183

    
184
    private static final String noIcon = "no-icon";
185

    
186
    /**
187
     * Makes some initialization tasks.
188
     * 
189
     * @throws RuntimeException
190
     *             DOCUMENT ME!
191
     */
192
    public void init() {
193
        JPopupMenu.setDefaultLightWeightPopupEnabled(false);
194
        if (!SwingUtilities.isEventDispatchThread()) {
195
            throw new RuntimeException("Not Event Dispatch Thread");
196
        }
197

    
198
        // Se a�aden los listeners del JFrame
199
        this.addWindowListener(new WindowAdapter() {
200

    
201
            @Override
202
            public void windowClosing(WindowEvent e) {
203
                Launcher.closeApplication();
204
            }
205
        });
206
        this.addComponentListener(this);
207
        this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
208

    
209
        // Se configura la barra de menu
210
        setJMenuBar(menuBar);
211

    
212
        // Se configura el layout del JFrame principal
213
        this.getContentPane().setLayout(new BorderLayout());
214

    
215
        /*
216
         * Se configura y se a�ade el JPanel de las barras de
217
         * herramientas
218
         */
219
        FlowLayout layout = new FlowLayout(FlowLayout.LEFT);
220
        layout.setHgap(0);
221
        layout.setVgap(0);
222
        toolBars.setLayout(layout);
223
        getContentPane().add(toolBars, BorderLayout.PAGE_START);
224

    
225
        // Se a�ade la barra de estado a la aplicaci�n
226
        bEstado = new NewStatusBar();
227
        bEstado
228
            .setInfoText(Messages.getString("StatusBar.Aplicacion_iniciada"));
229
        getContentPane().add(bEstado, BorderLayout.SOUTH);
230

    
231
        this.toolBars.addContainerListener(this);
232

    
233
        // TODO LWS Aqui deber�a cargar los valores salvados de la �ltima
234
        // ejecuci�n.
235
        setSize(700, 580);
236
        setLocation(10, 10);
237
        setExtendedState(MAXIMIZED_BOTH);
238

    
239
        mdiManager.init(this);
240

    
241
        pack();
242

    
243
    }
244

    
245
    /*
246
     * (non-javadoc)
247
     * 
248
     * @see java.awt.Frame.setTitle(String title)
249
     */
250
    @Override
251
    public void setTitle(String title) {
252
        super.setTitle(titlePrefix + ":" + title);
253
    }
254

    
255
    /**
256
     * A�ade un modo de operaci�n a la caja de herramientas
257
     * 
258
     * @param ext
259
     *            Texto del boton, si es null no aparece texto
260
     * @param ext
261
     *            Icono del boton, si es null no aparece icono
262
     * @param ext
263
     *            Extensi�n asociada al control
264
     * @param selectableTool
265
     *            Enable text del control
266
     * 
267
     * @throws ClassNotFoundException
268
     * @throws RuntimeException
269
     *             DOCUMENT ME!
270
     */
271
    public void addTool(PluginClassLoader loader, SkinExtensionType ext,
272
        ToolBar toolBar, SelectableTool selectableTool)
273
        throws ClassNotFoundException {
274
        if (!SwingUtilities.isEventDispatchThread()) {
275
            throw new RuntimeException("No Event Dispatch Thread");
276
        }
277
        
278
        Class<? extends IExtension> classExtension = (Class<? extends IExtension>) loader.loadClass(ext.getClassName());
279
        
280
        // Para traducir
281
        PluginServices ps =
282
            PluginServices.getPluginServices(loader.getPluginName());
283

    
284
        JToolBarToggleButton btn;
285
        ImageIcon image =
286
            PluginServices.getIconTheme().get(selectableTool.getIcon());
287

    
288
        if (image != null) {
289
            btn = new JToolBarToggleButton(selectableTool.getText(), image);
290
        } else {
291
            logger.error(PluginServices.getText(this, "Unable_to_find_icon")
292
                + ": " + selectableTool.getIcon());
293
            btn =
294
                new JToolBarToggleButton(selectableTool.getText(),
295
                    PluginServices.getIconTheme().get(noIcon));
296
        }
297

    
298
        org.gvsig.andami.ui.mdiFrame.ToggleButtonModel buttonModel =
299
            new org.gvsig.andami.ui.mdiFrame.ToggleButtonModel();
300
        btn.setModel(buttonModel);
301
        btn.setMargin(new Insets(0, 0, 0, 0));
302
        btn.addMouseListener(tooltipListener);
303
        btn.addActionListener(this);
304
        btn.setFocusable(false);
305
        btn.setActionCommand(selectableTool.getActionCommand());
306
        btn.setToolTipText(selectableTool.getTooltip());
307
        btn.setEnabled(false);
308
        btn.setVisible(false);
309
        String name = toolBar.getName();
310

    
311
        SelectableToolBar jtb = (SelectableToolBar) toolBarMap.get(name);
312

    
313
        if (jtb == null) {
314
            jtb = new SelectableToolBar(name);
315
            jtb.setRollover(true);
316
            jtb.setAndamiVisibility(toolBar.getIsVisible());
317
            toolBarMap.put(name, jtb);
318
            toolBars.add(jtb);
319
        }
320

    
321
        ButtonGroup group;
322
        if (buttonGroupMap.containsKey(selectableTool.getGroup())) {
323
            group = (ButtonGroup) buttonGroupMap.get(selectableTool.getGroup());
324
        } else {
325
            group = new ButtonGroup();
326
            buttonGroupMap.put(selectableTool.getGroup(), group);
327

    
328
        }
329
        jtb.addButton(group, btn);
330
        buttonModel.setGroupName(selectableTool.getGroup());
331

    
332
        if (selectableTool.getIsDefault()) {
333
            btn.setSelected(true);
334
            initialSelectedTools.put(selectableTool.getGroup(),
335
                btn.getActionCommand());
336
        }
337

    
338
        controlClass.put(btn, classExtension);
339

    
340
        if (selectableTool.getName() != null) {
341
            btn.setName(selectableTool.getName());
342
        }
343

    
344
        if (selectableTool.getTooltip() != null) {
345
            btn.setToolTip(ps.getText(selectableTool.getTooltip()));
346
        }
347

    
348
        if (selectableTool.getEnableText() != null) {
349
            btn.setEnableText(ps.getText(selectableTool.getEnableText()));
350
        }
351

    
352
        if (selectableTool.getLast() == true) {
353
            jtb.addSeparator();
354
        }
355
    }
356

    
357
    /**
358
     * A�ade un bot�n a la barra de herramientas
359
     * 
360
     * @param ext
361
     *            Texto del boton, si es null no aparece texto
362
     * @param ext
363
     *            Extensi�n asociada al control
364
     * @param toolBar
365
     *            Icono del boton, si es null no aparece texto
366
     * @param actionTool
367
     *            Tooltip de la barra de herramientas
368
     * 
369
     * @throws ClassNotFoundException
370
     * @throws RuntimeException
371
     *             DOCUMENT ME!
372
     */
373
    public void addTool(PluginClassLoader loader, SkinExtensionType ext,
374
        ToolBar toolBar, ActionTool actionTool) throws ClassNotFoundException {
375
        if (!SwingUtilities.isEventDispatchThread()) {
376
            throw new RuntimeException("No Event Dispatch Thread");
377
        }
378
        Class<? extends IExtension> classExtension = (Class<? extends IExtension>) loader.loadClass(ext.getClassName());
379
        
380
        // Para traducir los textos que vengan
381
        PluginServices ps =
382
            PluginServices.getPluginServices(loader.getPluginName());
383

    
384
        JToolBarButton btn;
385
        ImageIcon image = IconThemeHelper.getImageIcon(actionTool.getIcon());
386

    
387
        if (image != null) {
388
            btn = new JToolBarButton(actionTool.getText(), image);
389
        } else {
390
            logger.error(PluginServices.getText(this, "Unable_to_find_icon")
391
                + ": " + actionTool.getIcon());
392
            btn =
393
                new JToolBarButton(actionTool.getText(), PluginServices
394
                    .getIconTheme().get(noIcon));
395
        }
396

    
397
        btn.setMargin(new Insets(0, 0, 0, 0));
398
        btn.addMouseListener(tooltipListener);
399
        btn.addActionListener(this);
400
        btn.setFocusable(false);
401
        btn.setActionCommand(actionTool.getActionCommand());
402
        btn.setEnabled(false);
403
        btn.setVisible(false);
404

    
405
        String name = toolBar.getName();
406

    
407
        SelectableToolBar jtb = (SelectableToolBar) toolBarMap.get(name);
408

    
409
        if (jtb == null) {
410
            jtb = new SelectableToolBar(name);
411
            jtb.setRollover(true);
412
            jtb.setAndamiVisibility(toolBar.getIsVisible());
413
            toolBarMap.put(name, jtb);
414
            toolBars.add(jtb);
415
        }
416

    
417
        jtb.add(btn);
418

    
419
        controlClass.put(btn, classExtension);
420

    
421
        if (actionTool.getName() != null) {
422
            btn.setName(actionTool.getName());
423
        }
424

    
425
        if (actionTool.getTooltip() != null) {
426
            btn.setToolTip(ps.getText(actionTool.getTooltip()));
427
        }
428

    
429
        if (actionTool.getEnableText() != null) {
430
            btn.setEnableText(ps.getText(actionTool.getEnableText()));
431
        }
432

    
433
        if (actionTool.getLast() == true) {
434
            jtb.addSeparator();
435
        }
436
    }
437

    
438
    /**
439
     * Creates the needed menu structure to add the menu to the bar.
440
     * Returns the father which must hold the menu which was
441
     * provided as parameter.
442
     * 
443
     * Crea la estructura de men�s necesaria para a�adir el menu a la barra.
444
     * Devuelve el padre del cual debe colgar el menu que se pasa como
445
     * par�metro.
446
     * 
447
     * @param menu
448
     *            The Menu whose support is going to be added
449
     * @param loader
450
     *            The plugin's class loader
451
     * 
452
     * @return The proper father for the menu which was provided as parameter
453
     */
454
    private JMenu createMenuAncestors(Menu menu, PluginClassLoader loader) {
455
        MenuElement menuPadre = null;
456

    
457
        PluginServices ps =
458
            PluginServices.getPluginServices(loader.getPluginName());
459

    
460
        String[] menues = menu.getText().split("/");
461
        ArrayList menuList = new ArrayList();
462
        menuList.add(menues[0]);
463
        menuPadre = getMenu(menuList, menuBar);
464

    
465
        JMenu padre = null;
466

    
467
        if (menuPadre == null) {
468
            padre = new JMenu(ps.getText(menues[0]));
469
            padre.setName(menues[0]);
470
            menuBar.add(padre);
471
        } else
472
            if (menuPadre instanceof JMenu) {
473
                padre = (JMenu) menuPadre;
474
            } else {
475
                logger.error(ps
476
                    .getText("error_creating_menu_Ancestor_does_not_exist"));
477
                return null;
478
            }
479

    
480
        // Se crea el resto de menus
481
        ArrayList temp = new ArrayList();
482

    
483
        for (int i = 1; i < (menues.length - 1); i++) {
484
            temp.add(menues[i]);
485
        }
486

    
487
        menuPadre = createMenus(temp, padre);
488

    
489
        return (JMenu) menuPadre;
490
    }
491

    
492
    /**
493
     * A�ade la informaci�n del menu al framework. Debido a que los men�es
494
     * se
495
     * pueden introducir en un orden determinado por el usuario, pero los
496
     * plugins se instalan en un orden arbitrario, primero se almacena la
497
     * informaci�n de todos los menus para luego ordenarlos y posteriormente
498
     * a�adirlos al interfaz
499
     * 
500
     * @param loader
501
     *            Posicion del menu. Se ordena por este campo
502
     * @param ext
503
     *            Array con los nombres de los padres del menu
504
     * @param menu
505
     *            Texto del menu
506
     * 
507
     * @throws ClassNotFoundException
508
     * @throws RuntimeException
509
     *             DOCUMENT ME!
510
     */
511
    public void addMenu(PluginClassLoader loader, SkinExtensionType ext,
512
        Menu menu) throws ClassNotFoundException {
513
        if (!SwingUtilities.isEventDispatchThread()) {
514
            throw new RuntimeException("No Event Dispatch Thread");
515
        }
516
                JMenu menuPadre = createMenuAncestors(menu, loader);
517

    
518
        if (menu.getIs_separator()) {
519
            menuPadre.addSeparator();
520
            return;
521
        }
522

    
523
        JMenuItem nuevoMenu = createJMenuItem(loader, menu);
524
        nuevoMenu.addMouseListener(tooltipListener);
525
        //nuevoMenu.addActionListener(this);
526
        menuPadre.add(nuevoMenu);
527
        Class<? extends IExtension> classExtension = (Class<? extends IExtension>) loader.loadClass(ext.getClassName());
528
        controlClass.put(nuevoMenu, classExtension);
529
    }
530

    
531
    /**
532
     * Dado un array de nombres de menu, encuentra el men�
533
     * 
534
     * @param nombres
535
     *            DOCUMENT ME!
536
     * @param padre
537
     *            DOCUMENT ME!
538
     * 
539
     * @return DOCUMENT ME!
540
     */
541
    private javax.swing.JMenuItem getMenu(ArrayList nombres, MenuElement parent) {
542
        if (parent instanceof javax.swing.JMenu) {
543
            javax.swing.JMenu parentItem = (javax.swing.JMenu) parent;
544

    
545
            for (int i = 0; i < parentItem.getMenuComponentCount(); i++) {
546
                if ((parentItem.getMenuComponent(i).getName() != null // not a
547
                                                                      // JToolBar.Separator
548
                    )
549
                    && (parentItem.getMenuComponent(i).getName()
550
                        .compareTo((String) nombres.get(0)) == 0)) {
551
                    nombres.remove(0);
552
                    if (nombres.isEmpty()) {
553
                        if (parentItem.getMenuComponent(i) instanceof javax.swing.JMenuItem) {
554
                            return (javax.swing.JMenuItem) parentItem
555
                                .getMenuComponent(i);
556
                        } else {
557
                            logger.error(PluginServices.getText(this,
558
                                "Menu_type_not_supported_")
559
                                + " "
560
                                + parentItem.getMenuComponent(i).getClass()
561
                                    .getName());
562
                            return null;
563
                        }
564
                    } else {
565
                        return getMenu(nombres,
566
                            (MenuElement) parentItem.getMenuComponent(i));
567
                    }
568
                }
569
            }
570
        } else
571
            if (parent instanceof JMenuBar) {
572
                javax.swing.JMenuBar parentItem = (javax.swing.JMenuBar) parent;
573

    
574
                for (int i = 0; i < parentItem.getMenuCount(); i++) {
575
                    if ((parentItem.getMenu(i).getName() != null // not a
576
                                                                 // JToolBar.Separator
577
                        )
578
                        && (parentItem.getMenu(i).getName()
579
                            .compareTo((String) nombres.get(0)) == 0)) {
580
                        nombres.remove(0);
581
                        if (nombres.isEmpty()) {
582
                            if (parentItem.getMenu(i) instanceof javax.swing.JMenuItem) {
583
                                return parentItem.getMenu(i);
584
                            } else {
585
                                logger.error(PluginServices.getText(this,
586
                                    "Menu_type_not_supported_")
587
                                    + " "
588
                                    + parentItem.getMenu(i).getClass()
589
                                        .getName());
590
                                return null;
591
                            }
592
                        } else {
593
                            return getMenu(nombres, parentItem.getMenu(i));
594
                        }
595
                    }
596
                }
597
            } else {
598
                logger.error(PluginServices.getText(this,
599
                    "Menu_type_not_supported_")
600
                    + " "
601
                    + parent.getClass().getName() + " " + parent.toString());
602
            }
603
        return null;
604
    }
605

    
606
    /**
607
     * Crea la estructura de menus recursivamente. Por ejemplo, si se le pasa
608
     * en el par�metro nombres el array {"Search", "References", "Workspace"}
609
     * crear� un men� Search, un submen� del anterior que se llamar�
610
     * References y debajo de �ste �ltimo otro menu llamado Workspace
611
     * 
612
     * @param nombres
613
     *            Array con los nombres de los men�s que se quieren crear
614
     * @param padre
615
     *            Menu padre de los men�s creados. Es �til porque es un
616
     *            algoritmo recursivo
617
     * 
618
     * @return Devuelve el men� creado. Al final de toda la recursividad,
619
     *         devolver� el men� de m�s abajo en la jerarqu�a
620
     * 
621
     * @throws RuntimeException
622
     *             DOCUMENT ME!
623
     */
624
    private JMenu createMenus(ArrayList nombres, JMenu padre) {
625
        if (!SwingUtilities.isEventDispatchThread()) {
626
            throw new RuntimeException("No Event Dispatch Thread");
627
        }
628

    
629
        // si no quedan nombres de menu por crear se vuelve: caso base
630
        if (nombres.size() == 0) {
631
            return padre;
632
        }
633

    
634
        // Se busca el menu por si ya existiera para no crearlo otra vez
635
        JMenu buscado = null;
636

    
637
        for (int i = 0; i < padre.getMenuComponentCount(); i++) {
638
            try {
639
                JMenu hijo = (JMenu) padre.getMenuComponent(i);
640

    
641
                if (hijo.getName().compareTo((String) nombres.get(0)) == 0) {
642
                    buscado = hijo;
643
                }
644
            } catch (ClassCastException e) {
645
                /*
646
                 * Se ha encontrado un elemento hoja del arbol de men�es
647
                 */
648
            }
649
        }
650

    
651
        if (buscado != null) {
652
            // Si lo hemos encontrado creamos el resto
653
            nombres.remove(0);
654

    
655
            return createMenus(nombres, buscado);
656
        } else {
657
            // Si no lo hemos encontrado se crea el menu, se a�ade al padre
658
            // y se crea el resto
659
            String nombre = (String) nombres.get(0);
660
            JMenu menuPadre = new JMenu(PluginServices.getText(this, nombre));
661
            menuPadre.setName(nombre);
662
            padre.add(menuPadre);
663

    
664
            nombres.remove(0);
665

    
666
            return createMenus(nombres, menuPadre);
667
        }
668
    }
669

    
670
    /**
671
     * M�todo invocado en respuesta a ciertos eventos de la interfaz que
672
     * pueden
673
     * ocultar botones de las barras de herramientas y que redimensiona �sta
674
     * de manera conveniente para que no se oculte ninguno
675
     */
676
    private void ajustarToolBar() {
677
        int margen = 8;
678
        int numFilas = 1;
679
        double acum = margen;
680

    
681
        int toolHeight = 0;
682

    
683
        for (int i = 0; i < toolBars.getComponentCount(); i++) {
684
            Component c = toolBars.getComponent(i);
685

    
686
            if (!c.isVisible()) {
687
                continue;
688
            }
689

    
690
            double width = c.getPreferredSize().getWidth();
691
            acum = acum + width;
692

    
693
            if (acum > this.getWidth()) {
694
                numFilas++;
695
                acum = width + margen;
696
            }
697

    
698
            if (c.getPreferredSize().getHeight() > toolHeight) {
699
                toolHeight = c.getPreferredSize().height;
700
            }
701
        }
702

    
703
        toolBars.setPreferredSize(new Dimension(this.getWidth(),
704
            (numFilas * toolHeight)));
705

    
706
        toolBars.updateUI();
707
    }
708

    
709
    /**
710
     * DOCUMENT ME!
711
     * 
712
     * @param classesExtensions
713
     */
714
    public void setClassesExtensions(Map<Class<? extends IExtension>, ExtensionDecorator> classesExtensions) {
715
            Map<Class<? extends IExtension>, ExtensionDecorator> extensions = new HashMap<Class<? extends IExtension>, ExtensionDecorator>();
716
            for ( Entry<Class<? extends IExtension>, ExtensionDecorator>  entry: classesExtensions.entrySet()) {
717
                        if( ! (entry.getValue().getExtension() instanceof LibraryExtension) ) {
718
                                extensions.put(entry.getKey(), entry.getValue());
719
                        }
720
                }
721
        this.classesExtensions = extensions;
722
    }
723

    
724
    /**
725
     * Metodo de callback invocado cuando se selecciona un menu o un boton
726
     * de
727
     * la barra de herramientas. Se busca la extensi�n asociada y se ejecuta
728
     * 
729
     * @param e
730
     *            Evento producido
731
     */
732
    public void actionPerformed(ActionEvent e) {
733
        
734
//        org.gvsig.andami.plugins.IExtension ext =
735
//            (org.gvsig.andami.plugins.IExtension) classesExtensions
736
//                .get(controlClass.get(control));
737
            String actionName = "(unknow)";
738
        try {
739
            JComponent control = (JComponent) e.getSource();
740
            actionName = control.getName();
741
            
742
                ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
743
                ActionInfo action = actionManager.getAction(control.getName());
744
                Object args = null;
745
            if( control instanceof IControl ) {
746
                    args = ((IControl) control).getValue();
747
            }
748
            if( args == null ) {
749
                    action.execute();
750
            } else {
751
                    action.execute(args);                    
752
            }
753
                
754
//            logger.info("{}.execute('{}')", ext.getClass().getSimpleName(), actionCommand);
755
//            ext.execute(actionCommand);
756

    
757
                String actionCommand = e.getActionCommand();
758
            try {
759
                JToolBarToggleButton toggle = (JToolBarToggleButton) control;
760
                ToggleButtonModel model = (ToggleButtonModel) toggle.getModel();
761
                selectedTool.put(model.getGroupName(), actionCommand);
762
            } catch (ClassCastException ex) {
763
            } catch (NullPointerException ex) {
764
            }
765

    
766
        } catch (Throwable ex) {
767
                logger.error("Can't perform action '"+actionName+"'.",ex);
768
//            if (ext == null) {
769
//                logger.error(Messages
770
//                    .getString("No_extension_associated_with_this_event_")
771
//                    + e.getActionCommand());
772
//            }
773
//            NotificationManager.addError(Messages
774
//                .getString("MDIFrame.Error_no_capturado_por_el_usuario"), t);
775
        }
776

    
777
        enableControls();
778
        showMemory();
779
    }
780

    
781
    /**
782
     * DOCUMENT ME!
783
     * 
784
     * @param name
785
     *            DOCUMENT ME!
786
     * @param loader
787
     *            DOCUMENT ME!
788
     * 
789
     * @return DOCUMENT ME!
790
     */
791
    private String getName(String name, PluginClassLoader loader) {
792
        if (name.indexOf('.') == -1) {
793
            return loader.getPluginName() + "." + name;
794
        } else {
795
            return name;
796
        }
797
    }
798

    
799
    /**
800
     * DOCUMENT ME!
801
     * 
802
     * @param loader
803
     *            DOCUMENT ME!
804
     * @param menu
805
     *            DOCUMENT ME!
806
     * 
807
     * @throws RuntimeException
808
     *             DOCUMENT ME!
809
     */
810
    public void addPopupMenu(PluginClassLoader loader, PopupMenu menu) {
811
        if (!SwingUtilities.isEventDispatchThread()) {
812
            throw new RuntimeException("No Event Dispatch Thread");
813
        }
814

    
815
        String name = getName(menu.getName(), loader);
816

    
817
        // Se crea el control popupmenu
818
        JPopUpMenu popupMenu = (JPopUpMenu) popupMap.get(name);
819

    
820
        if (popupMenu == null) {
821
            popupMenu = new JPopUpMenu(menu.getName());
822
            popupMap.put(name, popupMenu);
823
        }
824

    
825
        Menu[] menues = menu.getMenu();
826
        for (int i = 0; i < menues.length; i++) {
827
            JMenuItem nuevoMenu = createJMenuItem(loader, menues[i]);
828
            popupMenu.add(nuevoMenu);
829
        }
830
    }
831

    
832
    /**
833
     * DOCUMENT ME!
834
     * 
835
     * @param loader
836
     * @param menu
837
     * 
838
     * @return
839
     * 
840
     * @throws RuntimeException
841
     *             DOCUMENT ME!
842
     */
843
    private JMenuItem createJMenuItem(PluginClassLoader loader, Menu menu) {
844
        JMenuItem nuevoMenu = null;
845

    
846
        PluginServices ps =
847
            PluginServices.getPluginServices(loader.getPluginName());
848
        
849
        String text = menu.getText();
850
        int n = text.lastIndexOf('/');
851
        if( n>=0  ) {
852
                text = text.substring(n + 1);
853
        }
854
        String translatedText = ps.getText(text);
855

    
856
        IconTheme iconTheme = ToolsSwingLocator.getIconThemeManager().getCurrent();
857
        if (menu.getIcon() != null) {
858
                if( iconTheme.exists(menu.getIcon()) ) {
859
                        ImageIcon image = iconTheme.get(menu.getIcon());
860
                nuevoMenu = new JMenuItem(translatedText, image);
861
            } else {
862
                nuevoMenu = new JMenuItem(translatedText);
863
                logger.info("menu icon '"+ menu.getIcon()+ "' not exists.");
864
            }
865
        } else {
866
            nuevoMenu = new JMenuItem(translatedText);
867
        }
868
        nuevoMenu.setName(menu.getName());
869
//                if (menu.getMnemonic() != null) {
870
//                        if (menu.getMnemonic().length() != 1) {
871
//                                throw new RuntimeException(
872
//                                                "Mnemonic must be 1 character length");
873
//                        }
874
//                        nuevoMenu.setMnemonic(KeyMapping.getKey(menu.getMnemonic()
875
//                                        .charAt(0)));
876
//                }
877

    
878
        if (menu.getKey() != null) {
879
            nuevoMenu.setAccelerator(KeyMapping.getKeyStroke(menu.getKey()));
880
        }
881

    
882
        nuevoMenu.setActionCommand(menu.getActionCommand());
883

    
884
        if (menu.getTooltip() != null) {
885
            nuevoMenu.setToolTip(ps.getText(menu.getTooltip()));
886
        }
887

    
888
        if (menu.getEnableText() != null) {
889
            nuevoMenu.setEnableText(ps.getText(menu.getEnableText()));
890
        }
891

    
892
        nuevoMenu.setEnabled(true);
893
        nuevoMenu.setVisible(true);
894

    
895
        if( menu.getName() != null ) {
896
                    ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
897
                    final ActionInfo actionInfo = actionManager.getAction(menu.getName());
898
                    if( actionInfo != null ) {
899
                            nuevoMenu.addActionListener(actionInfo);
900
                    }
901
        }
902
        return nuevoMenu;
903
    }
904

    
905
    /**
906
     * Muestra u oculta el menu de nombre 'name'
907
     * 
908
     * @param name
909
     *            Nombre del menu que se quiere mostrar
910
     * @param x
911
     *            Evento de raton
912
     * @param y
913
     *            DOCUMENT ME!
914
     * @param c
915
     *            DOCUMENT ME!
916
     */
917
    private void showPopupMenu(String name, int x, int y, Component c) {
918
        JPopupMenu menu = (JPopupMenu) popupMap.get(name);
919

    
920
        if (menu != null) {
921
            menu.show(c, x, y);
922
        }
923
    }
924

    
925
    /**
926
     * DOCUMENT ME!
927
     * 
928
     * @param name
929
     *            DOCUMENT ME!
930
     * @param listener
931
     *            DOCUMENT ME!
932
     */
933
    public void removePopupMenuListener(String name, ActionListener listener) {
934
        JPopupMenu menu = (JPopupMenu) popupMap.get(name);
935

    
936
        if (menu != null) {
937
            Component[] jmenuitems = menu.getComponents();
938

    
939
            for (int i = 0; i < jmenuitems.length; i++) {
940
                if (jmenuitems[i] instanceof JMenuItem) {
941
                    ((JMenuItem) jmenuitems[i]).removeActionListener(listener);
942
                }
943
            }
944
        }
945
    }
946

    
947
    /**
948
     * DOCUMENT ME!
949
     * 
950
     * @param popupName
951
     * @param c
952
     *            DOCUMENT ME!
953
     * @param listener
954
     * @param loader
955
     */
956
    public void addPopupMenuListener(String popupName, Component c,
957
        ActionListener listener, PluginClassLoader loader) {
958
        final String name = getName(popupName, loader);
959

    
960
        JPopupMenu menu = (JPopupMenu) popupMap.get(name);
961

    
962
        if (menu != null) {
963
            Component[] jmenuitems = menu.getComponents();
964

    
965
            for (int i = 0; i < jmenuitems.length; i++) {
966
                if (jmenuitems[i] instanceof JMenuItem) {
967
                    ((JMenuItem) jmenuitems[i]).addActionListener(listener);
968
                }
969
            }
970
        }
971

    
972
        c.addMouseListener(new MouseAdapter() {
973

    
974
            @Override
975
            public void mousePressed(MouseEvent e) {
976
                if (e.isPopupTrigger()) {
977
                    showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
978
                }
979
            }
980

    
981
            @Override
982
            public void mouseReleased(MouseEvent e) {
983
                if (e.isPopupTrigger()) {
984
                    showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
985
                }
986
            }
987
        });
988
    }
989

    
990
    /**
991
     * Loop on the controls to enable/disable and show/hide them, according to
992
     * its associated extension
993
     * 
994
     * @throws RuntimeException
995
     *             DOCUMENT ME!
996
     */
997
    public void enableControls() {
998
        if (!SwingUtilities.isEventDispatchThread()) {
999
                SwingUtilities.invokeLater(new Runnable() {
1000
                                public void run() {
1001
                                        enableControls();
1002
                                }
1003
                        });
1004
                        return;
1005
        }
1006

    
1007
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1008
        ActionInfoStatusCache cache = actionManager.createActionStatusCache();
1009
        
1010
        Iterator e = classesExtensions.values().iterator();
1011

    
1012
//        HashMap estadoExtensiones = new HashMap();
1013
//        HashMap visibilidadExtensiones = new HashMap();
1014
//
1015
//        while (e.hasNext()) {
1016
//            ExtensionDecorator ext = (ExtensionDecorator) e.next();
1017
//
1018
//            try {
1019
//                if (estadoExtensiones.get(ext) == null) {
1020
//                    boolean b;
1021
//                    if (ext.getVisibility() == ExtensionDecorator.ALWAYS_VISIBLE) {
1022
//                        b = true;
1023
//                    } else
1024
//                        if (ext.getVisibility() == ExtensionDecorator.ALWAYS_INVISIBLE) {
1025
//                            b = false;
1026
//                        } else {
1027
//                            if (PluginServices.getExclusiveUIExtension() == null) {
1028
//                                b = ext.isVisible();
1029
//                            } else {
1030
//                                b =
1031
//                                    PluginServices.getExclusiveUIExtension()
1032
//                                        .isVisible(ext.getExtension());
1033
//                            }
1034
//                        }
1035
//                    Boolean visible = new Boolean(b);
1036
//                    Boolean enabled = new Boolean(false);
1037
//
1038
//                    if (visible.booleanValue()) {
1039
//                        if (PluginServices.getExclusiveUIExtension() == null) {
1040
//                            enabled = new Boolean(ext.isEnabled());
1041
//                        } else {
1042
//                            enabled =
1043
//                                new Boolean(PluginServices
1044
//                                    .getExclusiveUIExtension().isEnabled(
1045
//                                        ext.getExtension()));
1046
//                        }
1047
//
1048
//                    }
1049
//
1050
//                    estadoExtensiones.put(ext, enabled);
1051
//                    visibilidadExtensiones.put(ext, visible);
1052
//                }
1053
//            } catch (Throwable e1) {
1054
//                NotificationManager.addError(Messages
1055
//                    .getString("MDIFrame.Error_no_capturado_por_el_usuario"),
1056
//                    e1);
1057
//                estadoExtensiones.put(ext, Boolean.FALSE);
1058
//            }
1059
//        }
1060

    
1061
        // Enable or disable controls, according to its associated extensions
1062
        e = controlClass.keySet().iterator();
1063

    
1064
        while (e.hasNext()) {
1065
            JComponent control = (JComponent) e.next();
1066
            String actionlName = control.getName();
1067
            ActionInfo action = actionManager.getAction(actionlName);
1068
            try {
1069
//                    
1070
//                org.gvsig.andami.plugins.IExtension ext =
1071
//                    (org.gvsig.andami.plugins.IExtension) classesExtensions
1072
//                        .get(controlClass.get(control));
1073
//                boolean enabled =
1074
//                    ((Boolean) estadoExtensiones.get(ext)).booleanValue();
1075
//                boolean visible =
1076
//                    ((Boolean) visibilidadExtensiones.get(ext)).booleanValue();
1077

    
1078
                boolean enabled = false;
1079
                boolean visible = cache.isVisible(action);
1080
                if( visible ) {
1081
                        enabled = cache.isEnabled(action);
1082
                }
1083
                    
1084
                control.setEnabled(enabled);
1085
                control.setVisible(visible);
1086
            } catch (Exception ex) {
1087
                    logger.info("Can't enable/show control '"+actionlName +"'.",ex);
1088
                    this.message("Can't enable/show control '"+actionlName +"'.", JOptionPane.ERROR_MESSAGE);
1089
                control.setEnabled(false);
1090
                control.setVisible(false);
1091
            }
1092
        }
1093

    
1094
        // Loop in the menus to hide the menus that don't have visible children
1095
        for (int i = 0; i < menuBar.getMenuCount(); i++) {
1096
            MenuElement menu = menuBar.getMenu(i);
1097
            hideMenus(menu);
1098
            if (menu instanceof JMenu) {
1099
                // hide (ugly) redundant separators and assign keyboard
1100
                // mnemonics
1101
                Component[] comps = ((JMenu) menu).getMenuComponents();
1102
                // mnemonics have to be unique for each top-level menu
1103
                char mnemonics[] = new char[comps.length];
1104
                if (comps.length > 0) {
1105
                    // Set keyboard mnemonic for this top-level entry
1106
                    String text = ((JMenu) menu).getText();
1107
                    char mnemonic = getMnemonic(text, mnemonics);
1108
                    if (' ' != mnemonic) {
1109
                        ((JMenu) menu).setMnemonic(mnemonic);
1110
                        mnemonics[0] = mnemonic;
1111
                    }
1112
                }
1113
                // now go through all entries in this menu, hid
1114
                // separators if necessary and assing remaining mnemonics
1115
                hideSeparatorsAndMakeMnemonics(menu, mnemonics);
1116
            }
1117
        }
1118

    
1119
        // hide the toolbars that don't contain any visible tool
1120
        Iterator it = toolBarMap.values().iterator();
1121

    
1122
        while (it.hasNext()) {
1123
            SelectableToolBar t = (SelectableToolBar) it.next();
1124
            boolean todosOcultos = true;
1125

    
1126
            for (int i = 0; i < t.getComponentCount(); i++) {
1127
                if (!(t.getComponent(i) instanceof JSeparator) // separators
1128
                                                               // don't matter
1129
                    && t.getComponent(i).isVisible()) {
1130
                    todosOcultos = false;
1131
                }
1132
            }
1133

    
1134
            if (todosOcultos) {
1135
                t.setVisible(false);
1136
            } else {
1137
                t.setVisible(t.getAndamiVisibility());
1138
            }
1139
        }
1140

    
1141
        if (mdiManager != null) {
1142
            JPanel f = (JPanel) mdiManager.getActiveWindow();
1143

    
1144
            if (f != null) {
1145
                if (lastLabelClass != f.getClass()) {
1146
                    lastLabelClass = f.getClass();
1147

    
1148
                    Label[] lbls = (Label[]) classLabels.get(lastLabelClass);
1149

    
1150
                    if (lbls != null) {
1151
                        bEstado.setLabelSet(lbls);
1152
                    }
1153
                }
1154
            }
1155
        }
1156

    
1157
        ajustarToolBar();
1158

    
1159
        showMemory();
1160
    }
1161
    
1162
    public void refreshControls() {
1163
        if (!SwingUtilities.isEventDispatchThread()) {
1164
                SwingUtilities.invokeLater(new Runnable() {
1165
                                public void run() {
1166
                                        enableControls();
1167
                                }
1168
                        });
1169
                        return;
1170
        }
1171

    
1172
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1173
        ActionInfoStatusCache cache = actionManager.createActionStatusCache();
1174
        
1175
        Iterator e = controlClass.keySet().iterator();
1176

    
1177
        while (e.hasNext()) {
1178
            JComponent control = (JComponent) e.next();
1179
            String actionlName = control.getName();
1180
            ActionInfo action = actionManager.getAction(actionlName);
1181
            if( action!=null ) {
1182
                    if( control instanceof AbstractButton ) {
1183
                            AbstractButton button = (AbstractButton) control;
1184
                            button.setIcon(action.getIcon());
1185
                    }
1186
            }
1187
        }
1188
        enableControls();
1189
    }
1190

    
1191
    public void message(String msg, int messageTyoe) {
1192
            this.getStatusBar().message(msg, messageTyoe);
1193
        }
1194

    
1195
        /**
1196
     * Establece la visibilidad de un menu y todos sus descendientes en la
1197
     * jerarquia teniendo en cuenta la visibilidad de todos los submenus.
1198
     * 
1199
     * @param menu
1200
     *            Menu que se quiere visualizar
1201
     * 
1202
     * @return Devuelve true si el menu es visible y false en caso contrario
1203
     */
1204
    private boolean hideMenus(MenuElement menu) {
1205
        MenuElement[] submenus = menu.getSubElements();
1206

    
1207
        // Si no tiene hijos se devuelve su visibilidad
1208
        if (submenus.length == 0) {
1209
            return menu.getComponent().isVisible();
1210
        }
1211

    
1212
        /*
1213
         * Si tiene hijos se devuelve true si alg�no de ellos es visible,
1214
         * pero se itera por todos ellos
1215
         */
1216
        boolean visible = false;
1217

    
1218
        for (int i = 0; i < submenus.length; i++) {
1219
            if (hideMenus(submenus[i])) {
1220
                if (!(menu instanceof JPopupMenu)) {
1221
                    menu.getComponent().setVisible(true);
1222
                }
1223

    
1224
                visible = true;
1225
            }
1226
        }
1227

    
1228
        if (visible) {
1229
            return true;
1230
        }
1231

    
1232
        menu.getComponent().setVisible(false);
1233

    
1234
        return false;
1235
    }
1236

    
1237
    /**
1238
     * 
1239
     * Recurse through all menu elements and make sure there are no
1240
     * redundant separators.
1241
     * This method will make sure that a separator only becomes visible
1242
     * if at least one visible non-separator menu entry preceeded it.
1243
     * 
1244
     **/
1245
    private void hideSeparatorsAndMakeMnemonics(MenuElement menu,
1246
        char[] mnemonics) {
1247
        // flag that indicates whether a separator is to be displayed or not
1248
        boolean allowSeparator;
1249

    
1250
        allowSeparator = false; // separator not allowed as very first menu item
1251
        Component[] comps = ((JMenu) menu).getMenuComponents();
1252
        if (comps.length < 1) {
1253
            // zero-length menu: skip
1254
            return;
1255
        }
1256

    
1257
        for (int i = 0; i < comps.length; i++) {
1258
            if (comps[i] instanceof JSeparator) {
1259
                // got a separator: display only if allowed at this position
1260
                if (allowSeparator == true) {
1261
                    // look at all successive menu entries to make sure that at
1262
                    // least one
1263
                    // is visible and not a separator (otherwise, this separator
1264
                    // would
1265
                    // be the last visible item in this menu) -- we don't want
1266
                    // that
1267
                    comps[i].setVisible(false);
1268
                    for (int j = i; j < comps.length; j++) {
1269
                        if (!(comps[j] instanceof JSeparator)) {
1270
                            if (comps[j].isVisible()) {
1271
                                comps[i].setVisible(true); // display separator!
1272
                                break;
1273
                            }
1274
                        }
1275
                    }
1276
                } else {
1277
                    comps[i].setVisible(false);
1278
                }
1279
                allowSeparator = false; // separator is not allowed right after
1280
                                        // another separator
1281
            } else {
1282
                if (comps[i] instanceof JMenu) { // got a submenu: recurse
1283
                                                 // through it
1284
                    // get number of submenu components
1285
                    Component[] scomps = ((JMenu) comps[i]).getMenuComponents();
1286
                    // make a new, fresh array to hold unique mnemonics for this
1287
                    // submenu
1288
                    char[] smnemonics = new char[scomps.length];
1289
                    hideSeparatorsAndMakeMnemonics(((MenuElement) comps[i]),
1290
                        smnemonics);
1291
                    if (comps[i].isVisible()) {
1292
                        allowSeparator = true; // separators are OK after
1293
                                               // visible submenus
1294
                        // Set keyboard mnemonic for this submenu
1295
                        String text = ((JMenu) comps[i]).getText();
1296
                        char mnemonic = getMnemonic(text, mnemonics);
1297
                        if (' ' != mnemonic) {
1298
                            ((JMenu) comps[i]).setMnemonic(mnemonic);
1299
                            mnemonics[i] = mnemonic;
1300
                        }
1301
                    }
1302
                } else {
1303
                    if (comps[i].isVisible()) {
1304
                        if (comps[i] instanceof JMenuItem) {
1305
                            // Set keyboard mnemonic for this menu item
1306
                            String text = ((JMenuItem) comps[i]).getText();
1307
                            char mnemonic = getMnemonic(text, mnemonics);
1308
                            if (' ' != mnemonic) {
1309
                                ((JMenuItem) comps[i]).setMnemonic(mnemonic);
1310
                                mnemonics[i] = mnemonic;
1311
                            }
1312
                        }
1313
                        allowSeparator = true; // separators are OK after
1314
                                               // regular, visible entries
1315
                    }
1316
                }
1317
            }
1318
        }
1319
    }
1320

    
1321
    /**
1322
     * Helper functios for assigning a unique mnemomic char from
1323
     * a pool of unassigned onces, stored in the array "mnemomnics"
1324
     */
1325
    private char getMnemonic(String text, char[] mnemonics) {
1326
        Vector words = new Vector();
1327
        StringTokenizer t = new StringTokenizer(text);
1328
        int maxsize = 0;
1329

    
1330
        while (t.hasMoreTokens()) {
1331
            String word = t.nextToken();
1332
            if (word.length() > maxsize) {
1333
                maxsize = word.length();
1334
            }
1335
            words.addElement(word);
1336
        }
1337
        words.trimToSize();
1338

    
1339
        for (int i = 0; i < maxsize; ++i) {
1340
            char mnemonic = getMnemonic(words, mnemonics, i);
1341
            if (' ' != mnemonic) {
1342
                return mnemonic;
1343
            }
1344
        }
1345

    
1346
        return ' ';
1347
    }
1348

    
1349
    private char getMnemonic(Vector words, char[] mnemonics, int index) {
1350
        int numwords = words.size();
1351

    
1352
        for (int i = 0; i < numwords; ++i) {
1353
            String word = (String) words.elementAt(i);
1354
            if (index >= word.length()) {
1355
                continue;
1356
            }
1357

    
1358
            char c = word.charAt(index);
1359
            if (!isMnemonicExists(c, mnemonics)) {
1360
                /* pick only valid chars */
1361
                if ((c != ':') && (c != '.') && (c != ',') && (c != ';')
1362
                    && (c != '-') && (c != '+') && (c != '/') && (c != '\\')
1363
                    && (c != '\'') && (c != '\"') && (c != ' ') && (c != '=')
1364
                    && (c != '(') && (c != ')') && (c != '[') && (c != ']')
1365
                    && (c != '{') && (c != '}') && (c != '$') && (c != '*')
1366
                    && (c != '&') && (c != '%') && (c != '!') && (c != '?')
1367
                    && (c != '#') && (c != '~') && (c != '_')) {
1368
                    return c;
1369
                }
1370
            }
1371
        }
1372
        return ' ';
1373
    }
1374

    
1375
    private boolean isMnemonicExists(char c, char[] mnemonics) {
1376
        int num = mnemonics.length;
1377
        for (int i = 0; i < num; ++i) {
1378
            if (mnemonics[i] == c) {
1379
                return true;
1380
            }
1381
        }
1382
        return false;
1383
    }
1384

    
1385
    /**
1386
     * Muestra la memoria consumida por el programa
1387
     */
1388
    private void showMemory() {
1389
        Runtime r = Runtime.getRuntime();
1390
        long mem = r.totalMemory() - r.freeMemory();
1391
        logger.debug(PluginServices.getText(this, "memory_usage") + " " + mem
1392
            / 1024 + " KB");
1393
    }
1394

    
1395
    /**
1396
     * DOCUMENT ME!
1397
     * 
1398
     * @return
1399
     */
1400
    public MDIManager getMDIManager() {
1401
        return mdiManager;
1402
    }
1403

    
1404
    /**
1405
     * Establece el mensaje en la barra de estado asociado a una etiqueta
1406
     * 
1407
     * @return DOCUMENT ME!
1408
     */
1409
    public NewStatusBar getStatusBar() {
1410
        return bEstado;
1411
    }
1412

    
1413
    /**
1414
     * You can use this function to select the appropiate
1415
     * tool inside the toolbars
1416
     */
1417
    public void setSelectedTool(String actionCommand) {
1418
        setSelectedTool(defaultGroup, actionCommand);
1419
    }
1420

    
1421
    /**
1422
     * You can use this function to select the appropiate
1423
     * tool inside the toolbars
1424
     */
1425
    public void setSelectedTool(String groupName, String actionCommand) {
1426
        ButtonGroup group = (ButtonGroup) buttonGroupMap.get(groupName);
1427
        if (group == null) {
1428
            return;
1429
        }
1430

    
1431
        Enumeration enumeration = group.getElements();
1432
        while (enumeration.hasMoreElements()) {
1433
            AbstractButton button = (AbstractButton) enumeration.nextElement();
1434
            if (button.getActionCommand().equals(actionCommand)) {
1435
                button.setSelected(true);
1436
            }
1437
        }
1438

    
1439
        selectedTool.put(groupName, actionCommand);
1440
    }
1441

    
1442
    /**
1443
     * You can use this function to select the appropiate
1444
     * tool inside the toolbars
1445
     */
1446
    public void setSelectedTools(Map selectedTools) {
1447
        selectedTool = selectedTools;
1448
        if (selectedTools == null) {
1449
            return;
1450
        }
1451
        Iterator groupNames = selectedTools.keySet().iterator();
1452
        while (groupNames.hasNext()) {
1453
            try {
1454
                String groupName = (String) groupNames.next();
1455
                ButtonGroup group = (ButtonGroup) buttonGroupMap.get(groupName);
1456
                Enumeration enumeration = group.getElements();
1457
                String actionCommand = (String) selectedTools.get(groupName);
1458
                if (actionCommand == null) {
1459
                    continue;
1460
                }
1461
                while (enumeration.hasMoreElements()) {
1462
                    AbstractButton button =
1463
                        (AbstractButton) enumeration.nextElement();
1464
                    if (button.getActionCommand().equals(actionCommand)) {
1465
                        button.setSelected(true);
1466
                    }
1467
                }
1468
            } catch (ClassCastException ex) {
1469
                logger
1470
                    .error("selectedTool should only contain pairs (String groupName, JToolBarToggleButton button)");
1471
            }
1472
        }
1473
    }
1474

    
1475
    /**
1476
     * DOCUMENT ME!
1477
     * 
1478
     * @param clase
1479
     * @param label
1480
     */
1481
    public void setStatusBarLabels(Class clase, Label[] label) {
1482
        classLabels.put(clase, label);
1483
    }
1484

    
1485
    public void removeStatusBarLabels(Class clase) {
1486
        classLabels.remove(clase);
1487
    }
1488

    
1489
    public void addStatusBarControl(Class extensionClass, IControl control) {
1490
        control.addActionListener(this);
1491
        bEstado.addControl(control.getName(), (Component) control);
1492
        controlClass.put(control, extensionClass);
1493
    }
1494

    
1495
    public void removeStatusBarControl(String name) {
1496
        Component c = bEstado.removeControl(name);
1497
        if (c != null) {
1498
            controlClass.remove(c);
1499
        }
1500
    }
1501

    
1502
    /**
1503
     * @see org.gvsig.andami.ui.mdiFrame.MainFrame#removeMenu(org.gvsig.andami.plugins.config.generate.Menu)
1504
     */
1505
    public void removeMenu(Menu menu) {
1506
        JMenuItem delete = (JMenuItem) infoCodedMenus.get(menu);
1507

    
1508
        if (delete == null) {
1509
            throw new NoSuchElementException(menu.getText());
1510
        }
1511

    
1512
        delete.getParent().remove(delete);
1513
        infoCodedMenus.remove(menu);
1514
    }
1515

    
1516
    /**
1517
     * @see org.gvsig.andami.ui.mdiFrame.MainFrame#addMenu(org.gvsig.andami.plugins.config.generate.Menu,
1518
     *      java.awt.event.ActionListener, PluginClassLoader)
1519
     */
1520
    public void addMenu(Menu menu, ActionListener listener,
1521
        PluginClassLoader loader) {
1522
        JMenu menuPadre = createMenuAncestors(menu, loader);
1523

    
1524
        // Se registra y a�ade el menu
1525
        JMenuItem nuevoMenu = createJMenuItem(loader, menu);
1526
        nuevoMenu.addMouseListener(tooltipListener);
1527
        if( listener != null && menu.getName() != null && menu.getName().trim().length()>0 ) {
1528
                    ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1529
                    final ActionInfo actionInfo = actionManager.getAction(menu.getName());
1530
                    if( actionInfo != null ) {
1531
                            nuevoMenu.removeActionListener(actionInfo);
1532
                    }
1533
                nuevoMenu.addActionListener(listener);
1534
        }
1535
        menuPadre.add(nuevoMenu);
1536

    
1537
        infoCodedMenus.put(menu, nuevoMenu);
1538
    }
1539

    
1540
    /**
1541
     * @see org.gvsig.andami.ui.mdiFrame.MainFrame#changeMenuName(java.lang.String[],
1542
     *      String, org.gvsig.andami.plugins.PluginClassLoader)
1543
     */
1544
    public void changeMenuName(String[] menu, String newName,
1545
        PluginClassLoader loader) {
1546

    
1547
        ArrayList menuList = new ArrayList();
1548
        for (int i = 0; i < menu.length; i++) {
1549
            menuList.add(menu[i]);
1550
        }
1551

    
1552
        javax.swing.JMenuItem newMenu = getMenu(menuList, menuBar);
1553
        if (newMenu == null) {
1554
            throw new NoSuchMenuException(menu[0]);
1555
        } else {
1556
            newMenu.setText(PluginServices.getText(this, newName));
1557
        }
1558
    }
1559

    
1560
    /**
1561
     * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
1562
     */
1563
    public void componentHidden(ComponentEvent arg0) {
1564
    }
1565

    
1566
    /**
1567
     * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
1568
     */
1569
    public void componentMoved(ComponentEvent arg0) {
1570
    }
1571

    
1572
    /**
1573
     * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
1574
     */
1575
    public void componentResized(ComponentEvent arg0) {
1576
        ajustarToolBar();
1577
    }
1578

    
1579
    /**
1580
     * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
1581
     */
1582
    public void componentShown(ComponentEvent arg0) {
1583
    }
1584

    
1585
    /**
1586
     * @see java.awt.event.ContainerListener#componentAdded(java.awt.event.ContainerEvent)
1587
     */
1588
    public void componentAdded(ContainerEvent arg0) {
1589
        ajustarToolBar();
1590
    }
1591

    
1592
    /**
1593
     * @see java.awt.event.ContainerListener#componentRemoved(java.awt.event.ContainerEvent)
1594
     */
1595
    public void componentRemoved(ContainerEvent arg0) {
1596
        ajustarToolBar();
1597
    }
1598

    
1599
    /**
1600
     * DOCUMENT ME!
1601
     * 
1602
     * @author $author$
1603
     * @version $Revision: 38608 $
1604
     */
1605
    public class TooltipListener extends MouseAdapter {
1606

    
1607
        /**
1608
         * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1609
         */
1610
        @Override
1611
        public void mouseEntered(MouseEvent e) {
1612
            JComponent control = (JComponent) e.getSource();
1613
            EnableTextSupport ets = (EnableTextSupport) e.getSource();
1614

    
1615
            String texto = null;
1616
            texto = control.getToolTipText();
1617

    
1618
            if (texto != null) {
1619
                bEstado.setInfoTextTemporal(texto);
1620
            }
1621
        }
1622

    
1623
        /**
1624
         * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1625
         */
1626
        @Override
1627
        public void mouseExited(MouseEvent arg0) {
1628
            bEstado.restaurarTexto();
1629
        }
1630

    
1631
        /**
1632
         * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1633
         */
1634
        @Override
1635
        public void mousePressed(MouseEvent e) {
1636
            bEstado.restaurarTexto();
1637
        }
1638
    }
1639

    
1640
    public String getTitlePrefix() {
1641
        return titlePrefix;
1642
    }
1643

    
1644
    public void setTitlePrefix(String titlePrefix) {
1645
        this.titlePrefix = titlePrefix;
1646
    }
1647

    
1648
    public Map getSelectedTools() {
1649
        return selectedTool;
1650
    }
1651

    
1652
    public HashMap getInitialSelectedTools() {
1653
        return initialSelectedTools;
1654
    }
1655

    
1656
    /**
1657
     * Get a previously added JComponent by name. For example
1658
     * you can use it if you need to obtain a JToolBar to
1659
     * add some customized component.
1660
     * 
1661
     * @param name
1662
     * @return the JComponent or null if none has been found
1663
     */
1664
    public JComponent getComponentByName(String name) {
1665
        Iterator e = controlClass.keySet().iterator();
1666

    
1667
        while (e.hasNext()) {
1668
            JComponent control = (JComponent) e.next();
1669
            String nameCtrl = control.getName();
1670
            if (nameCtrl != null) {
1671
                if (nameCtrl.compareTo(name) == 0) {
1672
                    return control;
1673
                }
1674
            }
1675
        }
1676
        Iterator it = toolBarMap.values().iterator();
1677
        while (it.hasNext()) {
1678
            SelectableToolBar t = (SelectableToolBar) it.next();
1679
            String nameCtrl = t.getName();
1680
            if (nameCtrl != null) {
1681
                if (nameCtrl.compareTo(name) == 0) {
1682
                    return t;
1683
                }
1684
            }
1685

    
1686
        }
1687

    
1688
        return null;
1689
    }
1690

    
1691
    public SelectableToolBar[] getToolbars() {
1692
        return (SelectableToolBar[]) toolBarMap.values().toArray(
1693
            new SelectableToolBar[0]);
1694
    }
1695

    
1696
    public boolean getToolbarVisibility(String name) {
1697
        JComponent component =
1698
            PluginServices.getMainFrame().getComponentByName(name);
1699
        if ((component != null) && (component instanceof SelectableToolBar)) {
1700
            SelectableToolBar toolBar = (SelectableToolBar) component;
1701
            return toolBar.getAndamiVisibility();
1702
        }
1703
        return false;
1704
    }
1705

    
1706
    public boolean setToolbarVisibility(String name, boolean visibility) {
1707
        JComponent component =
1708
            PluginServices.getMainFrame().getComponentByName(name);
1709
        if ((component != null) && (component instanceof SelectableToolBar)) {
1710
            SelectableToolBar toolBar = (SelectableToolBar) component;
1711
            boolean oldVisibility = toolBar.getAndamiVisibility();
1712
            toolBar.setAndamiVisibility(visibility);
1713
            enableControls();
1714
            return oldVisibility;
1715
        }
1716
        return false;
1717
    }
1718

    
1719
    public javax.swing.JMenuItem getMenuEntry(String[] menuPath) {
1720
        ArrayList menu = new ArrayList();
1721
        for (int i = 0; i < menuPath.length; i++) {
1722
            menu.add(menuPath[i]);
1723
        }
1724
        return getMenu(menu, menuBar);
1725
    }
1726

    
1727
        public void messageDialog(String message, String title, int messageType) {
1728
                messageDialog(message, null, title, messageType);
1729
        }
1730
        
1731
        public void messageDialog(String message, String messageArgs[], String title, int messageType) {
1732
                String msg = message;
1733
                String theTitle = title;
1734
                
1735
        if (message == null) {
1736
                logger.info("message if null, message dialog not show.");
1737
            return;
1738
        }
1739
        if( theTitle == null ) {
1740
                theTitle = "";
1741
        }
1742
        if (msg.startsWith("_")) {
1743
                msg = org.gvsig.i18n.Messages.getText(message, messageArgs);
1744
                if (msg == null) {
1745
                        msg = "_"+message.replace("_", " ");
1746
                }
1747
        }                
1748
        if (theTitle.startsWith("_")) {
1749
                theTitle = org.gvsig.i18n.Messages.getText(theTitle);
1750
                if (theTitle == null) {
1751
                        theTitle = "_"+title.replace("_", " ");
1752
                }
1753
        }                
1754
                JOptionPane.showMessageDialog(this, msg,theTitle, messageType);
1755
        }
1756
}