Statistics
| Revision:

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

History | View | Annotate | Download (59 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.JToolBar;
80
import javax.swing.MenuElement;
81
import javax.swing.SwingUtilities;
82
import javax.swing.Timer;
83
import javax.swing.WindowConstants;
84

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

    
112
/**
113
 * Main application window.
114
 * 
115
 * @version $Revision: 38611 $
116
 */
117
@SuppressWarnings("unchecked")
118
public class MDIFrame extends JFrame implements ComponentListener,
119
    ContainerListener, ActionListener, MainFrame {
120

    
121
    private static final long serialVersionUID = -2472484309160847654L;
122

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

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

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

    
132
    /** Status bar */
133
    private NewStatusBar bEstado = null;
134

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

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

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

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

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

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

    
166
    // private HashMap classControls = new HashMap();
167

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

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

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

    
177
    /** �ltima clase que activ� etiquetas */
178
    private Class lastLabelClass;
179

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

    
185
    private String titlePrefix;
186

    
187
    private static final String noIcon = "no-icon";
188

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

    
201
        // Se a�aden los listeners del JFrame
202
        this.addWindowListener(new WindowAdapter() {
203

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

    
212
        // Se configura la barra de menu
213
        setJMenuBar(menuBar);
214

    
215
        // Se configura el layout del JFrame principal
216
        this.getContentPane().setLayout(new BorderLayout());
217

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

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

    
234
        this.toolBars.addContainerListener(this);
235

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

    
242
        mdiManager.init(this);
243

    
244
        pack();
245

    
246
    }
247

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

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

    
287
        JToolBarToggleButton btn;
288
        ImageIcon image =
289
            PluginServices.getIconTheme().get(selectableTool.getIcon());
290

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

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

    
314
        SelectableToolBar jtb = (SelectableToolBar) toolBarMap.get(name);
315

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

    
324
        ButtonGroup group;
325
        if (buttonGroupMap.containsKey(selectableTool.getGroup())) {
326
            group = (ButtonGroup) buttonGroupMap.get(selectableTool.getGroup());
327
        } else {
328
            group = new ButtonGroup();
329
            buttonGroupMap.put(selectableTool.getGroup(), group);
330

    
331
        }
332
        jtb.addButton(group, btn);
333
        buttonModel.setGroupName(selectableTool.getGroup());
334

    
335
        if (selectableTool.getIsDefault()) {
336
            btn.setSelected(true);
337
            initialSelectedTools.put(selectableTool.getGroup(),
338
                btn.getActionCommand());
339
        }
340

    
341
        controlClass.put(btn, classExtension);
342

    
343
        if (selectableTool.getName() != null) {
344
            btn.setName(selectableTool.getName());
345
        }
346

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

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

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

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

    
387
        JToolBarButton btn;
388
        ImageIcon image = IconThemeHelper.getImageIcon(actionTool.getIcon());
389

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

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

    
408
        String name = toolBar.getName();
409

    
410
        SelectableToolBar jtb = (SelectableToolBar) toolBarMap.get(name);
411

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

    
420
        jtb.add(btn);
421

    
422
        controlClass.put(btn, classExtension);
423

    
424
        if (actionTool.getName() != null) {
425
            btn.setName(actionTool.getName());
426
        }
427

    
428
        if (actionTool.getTooltip() != null) {
429
            btn.setToolTip(ps.getText(actionTool.getTooltip()));
430
        }
431

    
432
        if (actionTool.getEnableText() != null) {
433
            btn.setEnableText(ps.getText(actionTool.getEnableText()));
434
        }
435

    
436
        if (actionTool.getLast() == true) {
437
            jtb.addSeparator();
438
        }
439
    }
440

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

    
460
        PluginServices ps =
461
            PluginServices.getPluginServices(loader.getPluginName());
462

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

    
468
        JMenu padre = null;
469

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

    
483
        // Se crea el resto de menus
484
        ArrayList temp = new ArrayList();
485

    
486
        for (int i = 1; i < (menues.length - 1); i++) {
487
            temp.add(menues[i]);
488
        }
489

    
490
        menuPadre = createMenus(temp, padre);
491

    
492
        return (JMenu) menuPadre;
493
    }
494

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

    
521
        if (menu.getIs_separator()) {
522
            menuPadre.addSeparator();
523
            return;
524
        }
525

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

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

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

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

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

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

    
637
        // Se busca el menu por si ya existiera para no crearlo otra vez
638
        JMenu buscado = null;
639

    
640
        for (int i = 0; i < padre.getMenuComponentCount(); i++) {
641
            try {
642
                JMenu hijo = (JMenu) padre.getMenuComponent(i);
643

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

    
654
        if (buscado != null) {
655
            // Si lo hemos encontrado creamos el resto
656
            nombres.remove(0);
657

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

    
667
            nombres.remove(0);
668

    
669
            return createMenus(nombres, menuPadre);
670
        }
671
    }
672

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

    
684
        int toolHeight = 0;
685

    
686
        for (int i = 0; i < toolBars.getComponentCount(); i++) {
687
            Component c = toolBars.getComponent(i);
688

    
689
            if (!c.isVisible()) {
690
                continue;
691
            }
692

    
693
            double width = c.getPreferredSize().getWidth();
694
            acum = acum + width;
695

    
696
            if (acum > this.getWidth()) {
697
                numFilas++;
698
                acum = width + margen;
699
            }
700

    
701
            if (c.getPreferredSize().getHeight() > toolHeight) {
702
                toolHeight = c.getPreferredSize().height;
703
            }
704
        }
705

    
706
        toolBars.setPreferredSize(new Dimension(this.getWidth(),
707
            (numFilas * toolHeight)));
708

    
709
        toolBars.updateUI();
710
    }
711

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

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

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

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

    
780
        enableControls();
781
        showMemory();
782
    }
783

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

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

    
818
        String name = getName(menu.getName(), loader);
819

    
820
        // Se crea el control popupmenu
821
        JPopUpMenu popupMenu = (JPopUpMenu) popupMap.get(name);
822

    
823
        if (popupMenu == null) {
824
            popupMenu = new JPopUpMenu(menu.getName());
825
            popupMap.put(name, popupMenu);
826
        }
827

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

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

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

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

    
881
        if (menu.getKey() != null) {
882
            nuevoMenu.setAccelerator(KeyMapping.getKeyStroke(menu.getKey()));
883
        }
884

    
885
        nuevoMenu.setActionCommand(menu.getActionCommand());
886

    
887
        if (menu.getTooltip() != null) {
888
            nuevoMenu.setToolTip(ps.getText(menu.getTooltip()));
889
        }
890

    
891
        if (menu.getEnableText() != null) {
892
            nuevoMenu.setEnableText(ps.getText(menu.getEnableText()));
893
        }
894

    
895
        nuevoMenu.setEnabled(true);
896
        nuevoMenu.setVisible(true);
897

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

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

    
923
        if (menu != null) {
924
            menu.show(c, x, y);
925
        }
926
    }
927

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

    
939
        if (menu != null) {
940
            Component[] jmenuitems = menu.getComponents();
941

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

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

    
963
        JPopupMenu menu = (JPopupMenu) popupMap.get(name);
964

    
965
        if (menu != null) {
966
            Component[] jmenuitems = menu.getComponents();
967

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

    
975
        c.addMouseListener(new MouseAdapter() {
976

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

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

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

    
1010
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1011
        ActionInfoStatusCache cache = actionManager.createActionStatusCache();
1012
        
1013
        Iterator e = classesExtensions.values().iterator();
1014

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

    
1064
        // Enable or disable controls, according to its associated extensions
1065
        e = controlClass.keySet().iterator();
1066

    
1067
        while (e.hasNext()) {
1068
            JComponent control = (JComponent) e.next();
1069
            String actionlName = control.getName();
1070
            ActionInfo action = actionManager.getAction(actionlName);
1071
            try {
1072
                boolean enabled = false;
1073
                boolean visible = false;
1074
                
1075
                    if(action == null) {
1076
                  IExtension ext =
1077
                          (IExtension) classesExtensions.get(controlClass.get(control));
1078
                  enabled = ext.isEnabled();
1079
                  visible = ext.isVisible(); 
1080
                    } else {
1081
                            enabled = false;
1082
                    visible = cache.isVisible(action);
1083
                    if( visible ) {
1084
                            enabled = cache.isEnabled(action);
1085
                    }
1086
                    }
1087
                control.setEnabled(enabled);
1088
                control.setVisible(visible);
1089
            } catch (Exception ex) {
1090
                    logger.info("Can't enable/show control '"+actionlName +"'.",ex);
1091
                    this.message("Can't enable/show control '"+actionlName +"'.", JOptionPane.ERROR_MESSAGE);
1092
                control.setEnabled(false);
1093
                control.setVisible(false);
1094
            }
1095
        }
1096

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

    
1122
        // hide the toolbars that don't contain any visible tool
1123
        Iterator it = toolBarMap.values().iterator();
1124

    
1125
        while (it.hasNext()) {
1126
                JComponent t = (JComponent) it.next();
1127
            boolean todosOcultos = true;
1128

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

    
1137
            if (todosOcultos) {
1138
                t.setVisible(false);
1139
            } else {
1140
                    if(t instanceof SelectableToolBar) {
1141
                            t.setVisible(((SelectableToolBar)t).getAndamiVisibility());
1142
                    } else
1143
                            t.setVisible(true);
1144
            }
1145
        }
1146

    
1147
        if (mdiManager != null) {
1148
            JPanel f = (JPanel) mdiManager.getActiveWindow();
1149

    
1150
            if (f != null) {
1151
                if (lastLabelClass != f.getClass()) {
1152
                    lastLabelClass = f.getClass();
1153

    
1154
                    Label[] lbls = (Label[]) classLabels.get(lastLabelClass);
1155

    
1156
                    if (lbls != null) {
1157
                        bEstado.setLabelSet(lbls);
1158
                    }
1159
                }
1160
            }
1161
        }
1162

    
1163
        ajustarToolBar();
1164

    
1165
        showMemory();
1166
    }
1167
    
1168
    public void refreshControls() {
1169
        if (!SwingUtilities.isEventDispatchThread()) {
1170
                SwingUtilities.invokeLater(new Runnable() {
1171
                                public void run() {
1172
                                        enableControls();
1173
                                }
1174
                        });
1175
                        return;
1176
        }
1177

    
1178
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1179
        ActionInfoStatusCache cache = actionManager.createActionStatusCache();
1180
        
1181
        Iterator e = controlClass.keySet().iterator();
1182

    
1183
        while (e.hasNext()) {
1184
            JComponent control = (JComponent) e.next();
1185
            String actionlName = control.getName();
1186
            ActionInfo action = actionManager.getAction(actionlName);
1187
            if( action!=null ) {
1188
                    if( control instanceof AbstractButton ) {
1189
                            AbstractButton button = (AbstractButton) control;
1190
                            button.setIcon(action.getIcon());
1191
                    }
1192
            }
1193
        }
1194
        enableControls();
1195
    }
1196

    
1197
    public void message(String msg, int messageTyoe) {
1198
            this.getStatusBar().message(msg, messageTyoe);
1199
        }
1200

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

    
1213
        // Si no tiene hijos se devuelve su visibilidad
1214
        if (submenus.length == 0) {
1215
            return menu.getComponent().isVisible();
1216
        }
1217

    
1218
        /*
1219
         * Si tiene hijos se devuelve true si alg�no de ellos es visible,
1220
         * pero se itera por todos ellos
1221
         */
1222
        boolean visible = false;
1223

    
1224
        for (int i = 0; i < submenus.length; i++) {
1225
            if (hideMenus(submenus[i])) {
1226
                if (!(menu instanceof JPopupMenu)) {
1227
                    menu.getComponent().setVisible(true);
1228
                }
1229

    
1230
                visible = true;
1231
            }
1232
        }
1233

    
1234
        if (visible) {
1235
            return true;
1236
        }
1237

    
1238
        menu.getComponent().setVisible(false);
1239

    
1240
        return false;
1241
    }
1242

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

    
1256
        allowSeparator = false; // separator not allowed as very first menu item
1257
        Component[] comps = ((JMenu) menu).getMenuComponents();
1258
        if (comps.length < 1) {
1259
            // zero-length menu: skip
1260
            return;
1261
        }
1262

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

    
1327
    /**
1328
     * Helper functios for assigning a unique mnemomic char from
1329
     * a pool of unassigned onces, stored in the array "mnemomnics"
1330
     */
1331
    private char getMnemonic(String text, char[] mnemonics) {
1332
        Vector words = new Vector();
1333
        StringTokenizer t = new StringTokenizer(text);
1334
        int maxsize = 0;
1335

    
1336
        while (t.hasMoreTokens()) {
1337
            String word = t.nextToken();
1338
            if (word.length() > maxsize) {
1339
                maxsize = word.length();
1340
            }
1341
            words.addElement(word);
1342
        }
1343
        words.trimToSize();
1344

    
1345
        for (int i = 0; i < maxsize; ++i) {
1346
            char mnemonic = getMnemonic(words, mnemonics, i);
1347
            if (' ' != mnemonic) {
1348
                return mnemonic;
1349
            }
1350
        }
1351

    
1352
        return ' ';
1353
    }
1354

    
1355
    private char getMnemonic(Vector words, char[] mnemonics, int index) {
1356
        int numwords = words.size();
1357

    
1358
        for (int i = 0; i < numwords; ++i) {
1359
            String word = (String) words.elementAt(i);
1360
            if (index >= word.length()) {
1361
                continue;
1362
            }
1363

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

    
1381
    private boolean isMnemonicExists(char c, char[] mnemonics) {
1382
        int num = mnemonics.length;
1383
        for (int i = 0; i < num; ++i) {
1384
            if (mnemonics[i] == c) {
1385
                return true;
1386
            }
1387
        }
1388
        return false;
1389
    }
1390

    
1391
    /**
1392
     * Muestra la memoria consumida por el programa
1393
     */
1394
    private void showMemory() {
1395
        Runtime r = Runtime.getRuntime();
1396
        long mem = r.totalMemory() - r.freeMemory();
1397
        logger.debug(PluginServices.getText(this, "memory_usage") + " " + mem
1398
            / 1024 + " KB");
1399
    }
1400

    
1401
    /**
1402
     * DOCUMENT ME!
1403
     * 
1404
     * @return
1405
     */
1406
    public MDIManager getMDIManager() {
1407
        return mdiManager;
1408
    }
1409

    
1410
    /**
1411
     * Establece el mensaje en la barra de estado asociado a una etiqueta
1412
     * 
1413
     * @return DOCUMENT ME!
1414
     */
1415
    public NewStatusBar getStatusBar() {
1416
        return bEstado;
1417
    }
1418

    
1419
    /**
1420
     * You can use this function to select the appropiate
1421
     * tool inside the toolbars
1422
     */
1423
    public void setSelectedTool(String actionCommand) {
1424
        setSelectedTool(defaultGroup, actionCommand);
1425
    }
1426

    
1427
    /**
1428
     * You can use this function to select the appropiate
1429
     * tool inside the toolbars
1430
     */
1431
    public void setSelectedTool(String groupName, String actionCommand) {
1432
        ButtonGroup group = (ButtonGroup) buttonGroupMap.get(groupName);
1433
        if (group == null) {
1434
            return;
1435
        }
1436

    
1437
        Enumeration enumeration = group.getElements();
1438
        while (enumeration.hasMoreElements()) {
1439
            AbstractButton button = (AbstractButton) enumeration.nextElement();
1440
            if (button.getActionCommand().equals(actionCommand)) {
1441
                button.setSelected(true);
1442
            }
1443
        }
1444

    
1445
        selectedTool.put(groupName, actionCommand);
1446
    }
1447

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

    
1481
    /**
1482
     * DOCUMENT ME!
1483
     * 
1484
     * @param clase
1485
     * @param label
1486
     */
1487
    public void setStatusBarLabels(Class clase, Label[] label) {
1488
        classLabels.put(clase, label);
1489
    }
1490

    
1491
    public void removeStatusBarLabels(Class clase) {
1492
        classLabels.remove(clase);
1493
    }
1494

    
1495
    public void addStatusBarControl(Class extensionClass, IControl control) {
1496
        control.addActionListener(this);
1497
        bEstado.addControl(control.getName(), (Component) control);
1498
        controlClass.put(control, extensionClass);
1499
    }
1500
    
1501
    public void addToolBarControl(Class extensionClass, JToolBar control, String name) {
1502
        //toolBarMap.put(name, control); 
1503
        toolBars.add(control);
1504
        controlClass.put(control, extensionClass);
1505
    }
1506

    
1507
    public void removeStatusBarControl(String name) {
1508
        Component c = bEstado.removeControl(name);
1509
        if (c != null) {
1510
            controlClass.remove(c);
1511
        }
1512
    }
1513

    
1514
    /**
1515
     * @see org.gvsig.andami.ui.mdiFrame.MainFrame#removeMenu(org.gvsig.andami.plugins.config.generate.Menu)
1516
     */
1517
    public void removeMenu(Menu menu) {
1518
        JMenuItem delete = (JMenuItem) infoCodedMenus.get(menu);
1519

    
1520
        if (delete == null) {
1521
            throw new NoSuchElementException(menu.getText());
1522
        }
1523

    
1524
        delete.getParent().remove(delete);
1525
        infoCodedMenus.remove(menu);
1526
    }
1527

    
1528
    /**
1529
     * @see org.gvsig.andami.ui.mdiFrame.MainFrame#addMenu(org.gvsig.andami.plugins.config.generate.Menu,
1530
     *      java.awt.event.ActionListener, PluginClassLoader)
1531
     */
1532
    public void addMenu(Menu menu, ActionListener listener,
1533
        PluginClassLoader loader) {
1534
        JMenu menuPadre = createMenuAncestors(menu, loader);
1535

    
1536
        // Se registra y a�ade el menu
1537
        JMenuItem nuevoMenu = createJMenuItem(loader, menu);
1538
        nuevoMenu.addMouseListener(tooltipListener);
1539
        if( listener != null && menu.getName() != null && menu.getName().trim().length()>0 ) {
1540
                    ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1541
                    final ActionInfo actionInfo = actionManager.getAction(menu.getName());
1542
                    if( actionInfo != null ) {
1543
                            nuevoMenu.removeActionListener(actionInfo);
1544
                    }
1545
                nuevoMenu.addActionListener(listener);
1546
        }
1547
        menuPadre.add(nuevoMenu);
1548

    
1549
        infoCodedMenus.put(menu, nuevoMenu);
1550
    }
1551

    
1552
    /**
1553
     * @see org.gvsig.andami.ui.mdiFrame.MainFrame#changeMenuName(java.lang.String[],
1554
     *      String, org.gvsig.andami.plugins.PluginClassLoader)
1555
     */
1556
    public void changeMenuName(String[] menu, String newName,
1557
        PluginClassLoader loader) {
1558

    
1559
        ArrayList menuList = new ArrayList();
1560
        for (int i = 0; i < menu.length; i++) {
1561
            menuList.add(menu[i]);
1562
        }
1563

    
1564
        javax.swing.JMenuItem newMenu = getMenu(menuList, menuBar);
1565
        if (newMenu == null) {
1566
            throw new NoSuchMenuException(menu[0]);
1567
        } else {
1568
            newMenu.setText(PluginServices.getText(this, newName));
1569
        }
1570
    }
1571

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

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

    
1584
    /**
1585
     * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
1586
     */
1587
    public void componentResized(ComponentEvent arg0) {
1588
        ajustarToolBar();
1589
    }
1590

    
1591
    /**
1592
     * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
1593
     */
1594
    public void componentShown(ComponentEvent arg0) {
1595
    }
1596

    
1597
    /**
1598
     * @see java.awt.event.ContainerListener#componentAdded(java.awt.event.ContainerEvent)
1599
     */
1600
    public void componentAdded(ContainerEvent arg0) {
1601
        ajustarToolBar();
1602
    }
1603

    
1604
    /**
1605
     * @see java.awt.event.ContainerListener#componentRemoved(java.awt.event.ContainerEvent)
1606
     */
1607
    public void componentRemoved(ContainerEvent arg0) {
1608
        ajustarToolBar();
1609
    }
1610

    
1611
    /**
1612
     * DOCUMENT ME!
1613
     * 
1614
     * @author $author$
1615
     * @version $Revision: 38611 $
1616
     */
1617
    public class TooltipListener extends MouseAdapter {
1618

    
1619
        /**
1620
         * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1621
         */
1622
        @Override
1623
        public void mouseEntered(MouseEvent e) {
1624
            JComponent control = (JComponent) e.getSource();
1625
            EnableTextSupport ets = (EnableTextSupport) e.getSource();
1626

    
1627
            String texto = null;
1628
            texto = control.getToolTipText();
1629

    
1630
            if (texto != null) {
1631
                bEstado.setInfoTextTemporal(texto);
1632
            }
1633
        }
1634

    
1635
        /**
1636
         * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1637
         */
1638
        @Override
1639
        public void mouseExited(MouseEvent arg0) {
1640
            bEstado.restaurarTexto();
1641
        }
1642

    
1643
        /**
1644
         * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1645
         */
1646
        @Override
1647
        public void mousePressed(MouseEvent e) {
1648
            bEstado.restaurarTexto();
1649
        }
1650
    }
1651

    
1652
    public String getTitlePrefix() {
1653
        return titlePrefix;
1654
    }
1655

    
1656
    public void setTitlePrefix(String titlePrefix) {
1657
        this.titlePrefix = titlePrefix;
1658
    }
1659

    
1660
    public Map getSelectedTools() {
1661
        return selectedTool;
1662
    }
1663

    
1664
    public HashMap getInitialSelectedTools() {
1665
        return initialSelectedTools;
1666
    }
1667

    
1668
    /**
1669
     * Get a previously added JComponent by name. For example
1670
     * you can use it if you need to obtain a JToolBar to
1671
     * add some customized component.
1672
     * 
1673
     * @param name
1674
     * @return the JComponent or null if none has been found
1675
     */
1676
    public JComponent getComponentByName(String name) {
1677
        Iterator e = controlClass.keySet().iterator();
1678

    
1679
        while (e.hasNext()) {
1680
            JComponent control = (JComponent) e.next();
1681
            String nameCtrl = control.getName();
1682
            if (nameCtrl != null) {
1683
                if (nameCtrl.compareTo(name) == 0) {
1684
                    return control;
1685
                }
1686
            }
1687
        }
1688
        Iterator it = toolBarMap.values().iterator();
1689
        while (it.hasNext()) {
1690
                JComponent t = (JComponent) it.next();
1691
            String nameCtrl = t.getName();
1692
            if (nameCtrl != null) {
1693
                if (nameCtrl.compareTo(name) == 0) {
1694
                    return t;
1695
                }
1696
            }
1697

    
1698
        }
1699

    
1700
        return null;
1701
    }
1702

    
1703
    public SelectableToolBar[] getToolbars() {
1704
        return (SelectableToolBar[]) toolBarMap.values().toArray(
1705
            new SelectableToolBar[0]);
1706
    }
1707

    
1708
    public boolean getToolbarVisibility(String name) {
1709
        JComponent component =
1710
            PluginServices.getMainFrame().getComponentByName(name);
1711
        if ((component != null) && (component instanceof SelectableToolBar)) {
1712
            SelectableToolBar toolBar = (SelectableToolBar) component;
1713
            return toolBar.getAndamiVisibility();
1714
        }
1715
        return false;
1716
    }
1717

    
1718
    public boolean setToolbarVisibility(String name, boolean visibility) {
1719
        JComponent component =
1720
            PluginServices.getMainFrame().getComponentByName(name);
1721
        if ((component != null) && (component instanceof SelectableToolBar)) {
1722
            SelectableToolBar toolBar = (SelectableToolBar) component;
1723
            boolean oldVisibility = toolBar.getAndamiVisibility();
1724
            toolBar.setAndamiVisibility(visibility);
1725
            enableControls();
1726
            return oldVisibility;
1727
        }
1728
        return false;
1729
    }
1730

    
1731
    public javax.swing.JMenuItem getMenuEntry(String[] menuPath) {
1732
        ArrayList menu = new ArrayList();
1733
        for (int i = 0; i < menuPath.length; i++) {
1734
            menu.add(menuPath[i]);
1735
        }
1736
        return getMenu(menu, menuBar);
1737
    }
1738

    
1739
        public void messageDialog(String message, String title, int messageType) {
1740
                messageDialog(message, null, title, messageType);
1741
        }
1742
        
1743
        public void messageDialog(String message, String messageArgs[], String title, int messageType) {
1744
                String msg = message;
1745
                String theTitle = title;
1746
                
1747
        if (message == null) {
1748
                logger.info("message if null, message dialog not show.");
1749
            return;
1750
        }
1751
        if( theTitle == null ) {
1752
                theTitle = "";
1753
        }
1754
        if (msg.startsWith("_")) {
1755
                msg = org.gvsig.i18n.Messages.getText(message, messageArgs);
1756
                if (msg == null) {
1757
                        msg = "_"+message.replace("_", " ");
1758
                }
1759
        }                
1760
        if (theTitle.startsWith("_")) {
1761
                theTitle = org.gvsig.i18n.Messages.getText(theTitle);
1762
                if (theTitle == null) {
1763
                        theTitle = "_"+title.replace("_", " ");
1764
                }
1765
        }                
1766
                JOptionPane.showMessageDialog(this, msg,theTitle, messageType);
1767
        }
1768
}