Statistics
| Revision:

root / trunk / frameworks / _fwAndami / src / com / iver / andami / ui / mdiFrame / MDIFrame.java @ 35160

History | View | Annotate | Download (43.5 KB)

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

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

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

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

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

    
101

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

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

    
116
        /** Panel which contains the toolbars */
117
        private JPanel toolBars = new JPanel();
118

    
119
        /** Status bar */
120
        private NewStatusBar bEstado = null;
121

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

    
125
        /** Almacena los grupos de selectableTools */
126
        private HashMap buttonGroupMap = new HashMap();
127
        /**
128
         * Stores the initially selected tools.
129
         * It contains pairs (String groupName, JToolBarToggleButton button)
130
         */
131
        private HashMap initialSelectedTools = new HashMap();
132

    
133
        /**
134
         * Stores the actionCommand of the selected tool, for each group.
135
         * It contains pairs (String groupName, JToolBarToggleButton button)
136
         */
137
        private HashMap selectedTool = null;
138
        // this should be the same value defined at plugin-config.xsd
139
        private String defaultGroup = "unico";
140

    
141
        /** Asocia los nombres con los popupMenus */
142
        private HashMap popupMap = new HashMap();
143

    
144
        /** Asocia controles con la clase de la extension asociada */
145
        private HashMap controlClass = new HashMap();
146

    
147
        /**
148
         * Asocia la informaci�n sobre las etiquetas que van en la status bar con
149
         * cada extension
150
         */
151
        private HashMap classLabels = new HashMap();
152

    
153
        //private HashMap classControls = new HashMap();
154

    
155
        /** ProgressListeners (ver interfaz com.iver.mdiApp.ui.ProgressListener) */
156
        private ArrayList progressListeners = new ArrayList();
157

    
158
        /** Timer para invocar los enventos de la interfaz anterior */
159
        private Timer progressTimer = null;
160

    
161
        /** Tabla hash que asocia las clases con las extensiones */
162
        private HashMap classesExtensions = new HashMap();
163

    
164
        /** �ltima clase que activ� etiquetas */
165
        private Class lastLabelClass;
166

    
167
        /** Instancia que pone los tooltip en la barra de estado */
168
        private TooltipListener tooltipListener = new TooltipListener();
169
        private HashMap infoCodedMenus = new HashMap();
170

    
171
        private String titlePrefix;
172

    
173
        private static final String noIcon = "no-icon";
174

    
175
        /**
176
         * Makes some initialization tasks.
177
         *
178
         * @throws RuntimeException DOCUMENT ME!
179
         */
180
        public void init() {
181
                JPopupMenu.setDefaultLightWeightPopupEnabled(false);
182
                if (!SwingUtilities.isEventDispatchThread()) {
183
                        throw new RuntimeException("Not Event Dispatch Thread");
184
                }
185

    
186
                //Se a�aden los listeners del JFrame
187
                this.addWindowListener(new WindowAdapter() {
188
                        public void windowClosing(WindowEvent e) {
189
                                Launcher.closeApplication();
190
                        }
191
                });
192
                this.addComponentListener(this);
193
                this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
194

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

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

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

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

    
216
                this.toolBars.addContainerListener(this);
217

    
218
                pack();
219

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

    
225
                mdiManager.init(this);
226
        }
227

    
228
        /*
229
         * (non-javadoc)
230
         * @see java.awt.Frame.setTitle(String title)
231
         */
232
        public void setTitle(String title) {
233
                super.setTitle(titlePrefix + ":" + title);
234
        }
235

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

    
254
                // Para traducir
255
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
256

    
257
                JToolBarToggleButton btn;
258
                ImageIcon image = PluginServices.getIconTheme().get(selectableTool.getIcon());
259

    
260
                if (image != null) {
261
                        btn = new JToolBarToggleButton(selectableTool.getText(), image);
262
                } else {
263
                        logger.error(PluginServices.getText(this, "Unable_to_find_icon") +": "+selectableTool.getIcon());
264
                        btn = new JToolBarToggleButton(selectableTool.getText(),
265
                                        PluginServices.getIconTheme().get(noIcon));
266
                }
267

    
268
                com.iver.andami.ui.mdiFrame.ToggleButtonModel buttonModel = new com.iver.andami.ui.mdiFrame.ToggleButtonModel();
269
                btn.setModel(buttonModel);
270
                btn.setMargin(new Insets(0, 0, 0, 0));
271
                btn.addMouseListener(tooltipListener);
272
                btn.addActionListener(this);
273
                btn.setFocusable(false);
274
                btn.setActionCommand(selectableTool.getActionCommand());
275
                btn.setToolTipText(selectableTool.getTooltip());
276
                btn.setEnabled(false);
277
                btn.setVisible(false);
278
                String name = toolBar.getName();
279

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

    
282
                if (jtb == null) {
283
                        jtb = new SelectableToolBar(name);
284
                        jtb.setRollover(true);
285
                        jtb.setAndamiVisibility(toolBar.getIsVisible());
286
                        toolBarMap.put(name, jtb);
287
                        toolBars.add(jtb);
288
                }
289

    
290
                ButtonGroup group;
291
                if (buttonGroupMap.containsKey(selectableTool.getGroup())) {
292
                        group = (ButtonGroup) buttonGroupMap.get(selectableTool.getGroup());
293
                }
294
                else {
295
                        group = new ButtonGroup();
296
                        buttonGroupMap.put(selectableTool.getGroup(), group);
297

    
298
                }
299
                jtb.addButton(group, btn);
300
                buttonModel.setGroupName(selectableTool.getGroup());
301

    
302
                if (selectableTool.getIsDefault()) {
303
                        btn.setSelected(true);
304
                        initialSelectedTools.put(selectableTool.getGroup(), btn.getActionCommand());
305
                }
306

    
307
                controlClass.put(btn, loader.loadClass(ext.getClassName()));
308

    
309
                if (selectableTool.getName() != null) {
310
                        btn.setName(selectableTool.getName());
311
                }
312

    
313
                if (selectableTool.getTooltip() != null) {
314
                        btn.setToolTip(ps.getText(selectableTool.getTooltip()));
315
                }
316

    
317
                if (selectableTool.getEnableText() != null) {
318
                        btn.setEnableText(ps.getText(selectableTool.getEnableText()));
319
                }
320

    
321
                if (selectableTool.getLast() == true) {
322
                        jtb.addSeparator();
323
                }
324
        }
325

    
326
        /**
327
         * A�ade un bot�n a la barra de herramientas
328
         *
329
         * @param ext Texto del boton, si es null no aparece texto
330
         * @param ext Extensi�n asociada al control
331
         * @param toolBar Icono del boton, si es null no aparece texto
332
         * @param actionTool Tooltip de la barra de herramientas
333
         *
334
         * @throws ClassNotFoundException
335
         * @throws RuntimeException DOCUMENT ME!
336
         */
337
        public void addTool(PluginClassLoader loader, SkinExtensionType ext,
338
                        ToolBar toolBar, ActionTool actionTool) throws ClassNotFoundException {
339
                if (!SwingUtilities.isEventDispatchThread()) {
340
                        throw new RuntimeException("No Event Dispatch Thread");
341
                }
342

    
343
                // Para traducir los textos que vengan
344
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
345

    
346
                JToolBarButton btn;
347
                ImageIcon image = PluginServices.getIconTheme().get(actionTool.getIcon(),ps.getClassLoader());
348

    
349
                if (image != null) {
350
                        btn = new JToolBarButton(actionTool.getText(), image);
351
                } else {
352
                        logger.error(PluginServices.getText(this, "Unable_to_find_icon") +": "+actionTool.getIcon());
353
                        btn = new JToolBarButton(actionTool.getText(),
354
                                        PluginServices.getIconTheme().get(noIcon));
355
                }
356

    
357
                btn.setMargin(new Insets(0, 0, 0, 0));
358
                btn.addMouseListener(tooltipListener);
359
                btn.addActionListener(this);
360
                btn.setFocusable(false);
361
                btn.setActionCommand(actionTool.getActionCommand());
362
                btn.setEnabled(false);
363
                btn.setVisible(false);
364

    
365
                String name = toolBar.getName();
366

    
367
                SelectableToolBar jtb = (SelectableToolBar) toolBarMap.get(name);
368

    
369
                if (jtb == null) {
370
                        jtb = new SelectableToolBar(name);
371
                        jtb.setRollover(true);
372
                        jtb.setAndamiVisibility(toolBar.getIsVisible());
373
                        toolBarMap.put(name, jtb);
374
                        toolBars.add(jtb);
375
                }
376

    
377
                jtb.add(btn);
378

    
379
                controlClass.put(btn, loader.loadClass(ext.getClassName()));
380

    
381
                if (actionTool.getName() != null) {
382
                        btn.setName(actionTool.getName());
383
                }
384

    
385
                if (actionTool.getTooltip() != null) {
386
                        btn.setToolTip(ps.getText(actionTool.getTooltip()));
387
                }
388

    
389
                if (actionTool.getEnableText() != null) {
390
                        btn.setEnableText(ps.getText(actionTool.getEnableText()));
391
                }
392

    
393
                if (actionTool.getLast() == true) {
394
                        jtb.addSeparator();
395
                }
396
        }
397

    
398
        /**
399
         * Creates the needed menu structure to add the menu to the bar.
400
         * Returns the father which must hold the menu which was
401
         * provided as parameter.
402
         *
403
         * Crea la estructura de men�s necesaria para a�adir el menu a la barra.
404
         * Devuelve el padre del cual debe colgar el menu que se pasa como
405
         * par�metro.
406
         *
407
         * @param menu The Menu whose support is going to be added
408
         * @param loader The plugin's class loader
409
         *
410
         * @return The proper father for the menu which was provided as parameter
411
         */
412
        private JMenu createMenuAncestors(Menu menu, PluginClassLoader loader) {
413
                MenuElement menuPadre = null;
414

    
415
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
416

    
417
                String[] menues = menu.getText().split("/");
418
                ArrayList menuList = new ArrayList();
419
                menuList.add(menues[0]);
420
                menuPadre = getMenu(menuList, menuBar);
421

    
422
                JMenu padre = null;
423

    
424
                if (menuPadre==null) {
425
                        padre = new JMenu(ps.getText(menues[0]));
426
                        padre.setName(menues[0]);
427
                        menuBar.add(padre);
428
                }
429
                else if (menuPadre instanceof JMenu) {
430
                        padre = (JMenu) menuPadre;
431
                }
432
                else {
433
                        logger.error(ps.getText("error_creating_menu_Ancestor_does_not_exist"));
434
                        return null;
435
                }
436

    
437
                //Se crea el resto de menus
438
                ArrayList temp = new ArrayList();
439

    
440
                for (int i = 1; i < (menues.length - 1); i++) {
441
                        temp.add(menues[i]);
442
                }
443

    
444
                menuPadre = createMenus(temp, padre);
445

    
446
                return (JMenu) menuPadre;
447
        }
448

    
449
        /**
450
         * A�ade la informaci�n del menu al framework. Debido a que los men�es se
451
         * pueden introducir en un orden determinado por el usuario, pero los
452
         * plugins se instalan en un orden arbitrario, primero se almacena la
453
         * informaci�n de todos los menus para luego ordenarlos y posteriormente
454
         * a�adirlos al interfaz
455
         *
456
         * @param loader Posicion del menu. Se ordena por este campo
457
         * @param ext Array con los nombres de los padres del menu
458
         * @param menu Texto del menu
459
         *
460
         * @throws ClassNotFoundException
461
         * @throws RuntimeException DOCUMENT ME!
462
         */
463
        public void addMenu(PluginClassLoader loader, SkinExtensionType ext,
464
                        Menu menu) throws ClassNotFoundException {
465
                if (!SwingUtilities.isEventDispatchThread()) {
466
                        throw new RuntimeException("No Event Dispatch Thread");
467
                }
468

    
469
                JMenu menuPadre = createMenuAncestors(menu, loader);
470

    
471
                //Se registra y a�ade el menu
472
                /* String[] aux = menu.getText().split("/");
473

474
        if (aux.length == 2)
475
            if (aux[1].equals("----"))
476
            {
477
                menuPadre.addSeparator();
478
                return;
479
            } */
480
                if (menu.getIs_separator())
481
                {
482
                        menuPadre.addSeparator();
483
                        return;
484
                }
485

    
486
                JMenuItem nuevoMenu = createJMenuItem(loader, menu);
487
                nuevoMenu.addMouseListener(tooltipListener);
488
                nuevoMenu.addActionListener(this);
489
                menuPadre.add(nuevoMenu);
490
                controlClass.put(nuevoMenu, loader.loadClass(ext.getClassName()));
491
        }
492

    
493

    
494
        /**
495
         * Dado un array de nombres de menu, encuentra el  men�
496
         *
497
         * @param nombres DOCUMENT ME!
498
         * @param padre DOCUMENT ME!
499
         *
500
         * @return DOCUMENT ME!
501
         */
502
        private javax.swing.JMenuItem getMenu(ArrayList nombres, MenuElement parent) {
503
                if (parent instanceof javax.swing.JMenu) {
504
                        javax.swing.JMenu parentItem = (javax.swing.JMenu) parent;
505

    
506
                        for (int i=0; i<parentItem.getMenuComponentCount(); i++) {
507
                                if (parentItem.getMenuComponent(i).getName()!=null // not a JToolBar.Separator
508
                                                && parentItem.getMenuComponent(i).getName().compareTo((String)nombres.get(0)) == 0) {
509
                                        nombres.remove(0);
510
                                        if (nombres.isEmpty()) {
511
                                                if (parentItem.getMenuComponent(i) instanceof javax.swing.JMenuItem) {
512
                                                        return (javax.swing.JMenuItem) parentItem.getMenuComponent(i);
513
                                                }
514
                                                else {
515
                                                        logger.error(PluginServices.getText(this, "Menu_type_not_supported_")+" "+parentItem.getMenuComponent(i).getClass().getName());
516
                                                        return null;
517
                                                }
518
                                        }
519
                                        else {
520
                                                return getMenu(nombres, (MenuElement) parentItem.getMenuComponent(i));
521
                                        }
522
                                }
523
                        }
524
                }
525
                else if (parent instanceof JMenuBar) {
526
                        javax.swing.JMenuBar parentItem = (javax.swing.JMenuBar) parent;
527

    
528
                        for (int i=0; i<parentItem.getMenuCount(); i++) {
529
                                if (parentItem.getMenu(i).getName()!=null // not a JToolBar.Separator
530
                                                && parentItem.getMenu(i).getName().compareTo((String)nombres.get(0)) == 0) {
531
                                        nombres.remove(0);
532
                                        if (nombres.isEmpty()) {
533
                                                if (parentItem.getMenu(i) instanceof javax.swing.JMenuItem) {
534
                                                        return (javax.swing.JMenuItem) parentItem.getMenu(i);
535
                                                }
536
                                                else {
537
                                                        logger.error(PluginServices.getText(this, "Menu_type_not_supported_")+" "+parentItem.getMenu(i).getClass().getName());
538
                                                        return null;
539
                                                }
540
                                        }
541
                                        else {
542
                                                return getMenu(nombres, (MenuElement) parentItem.getMenu(i));
543
                                        }
544
                                }
545
                        }
546
                }
547
                else {
548
                        logger.error(PluginServices.getText(this, "Menu_type_not_supported_")+" "+parent.getClass().getName()+" "+parent.toString());
549
                }
550
                return null;
551
        }
552

    
553
        /**
554
         * Crea la estructura de menus recursivamente. Por ejemplo, si se le pasa
555
         * en el par�metro nombres el array {"Search", "References", "Workspace"}
556
         * crear� un men� Search, un submen� del anterior que se llamar�
557
         * References y debajo de �ste �ltimo otro menu llamado Workspace
558
         *
559
         * @param nombres Array con los nombres de los men�s que se quieren crear
560
         * @param padre Menu padre de los men�s creados. Es �til porque es un
561
         *                   algoritmo recursivo
562
         *
563
         * @return Devuelve el men� creado. Al final de toda la recursividad,
564
         *                    devolver� el men� de m�s abajo en la jerarqu�a
565
         *
566
         * @throws RuntimeException DOCUMENT ME!
567
         */
568
        private JMenu createMenus(ArrayList nombres, JMenu padre) {
569
                if (!SwingUtilities.isEventDispatchThread()) {
570
                        throw new RuntimeException("No Event Dispatch Thread");
571
                }
572

    
573
                //si no quedan nombres de menu por crear se vuelve: caso base
574
                if (nombres.size() == 0) {
575
                        return padre;
576
                }
577

    
578
                //Se busca el menu por si ya existiera para no crearlo otra vez
579
                JMenu buscado = null;
580

    
581
                for (int i = 0; i < padre.getMenuComponentCount(); i++) {
582
                        try {
583
                                JMenu hijo = (JMenu) padre.getMenuComponent(i);
584

    
585
                                if (hijo.getName().compareTo((String) nombres.get(0)) == 0) {
586
                                        buscado = hijo;
587
                                }
588
                        } catch (ClassCastException e) {
589
                                /*
590
                                 * Se ha encontrado un elemento hoja del arbol de men�es
591
                                 */
592
                        }
593
                }
594

    
595
                if (buscado != null) {
596
                        //Si lo hemos encontrado creamos el resto
597
                        nombres.remove(0);
598

    
599
                        return createMenus(nombres, buscado);
600
                } else {
601
                        //Si no lo hemos encontrado se crea el menu, se a�ade al padre
602
                        //y se crea el resto
603
                        String nombre = (String) nombres.get(0);
604
                        JMenu menuPadre = new JMenu((String) PluginServices.getText(this, nombre));
605
                        menuPadre.setName(nombre);
606
                        padre.add(menuPadre);
607

    
608
                        nombres.remove(0);
609

    
610
                        return createMenus(nombres, menuPadre);
611
                }
612
        }
613

    
614
        /**
615
         * M�todo invocado en respuesta a ciertos eventos de la interfaz que pueden
616
         * ocultar botones de las barras de herramientas y que redimensiona �sta
617
         * de manera conveniente para que no se oculte ninguno
618
         */
619
        private void ajustarToolBar() {
620
                int margen = 8;
621
                int numFilas = 1;
622
                double acum = margen;
623

    
624
                int toolHeight = 0;
625

    
626
                for (int i = 0; i < toolBars.getComponentCount(); i++) {
627
                        Component c = toolBars.getComponent(i);
628

    
629
                        if (!c.isVisible()) {
630
                                continue;
631
                        }
632

    
633
                        double width = c.getPreferredSize().getWidth();
634
                        acum = acum + width;
635

    
636
                        if (acum > this.getWidth()) {
637
                                numFilas++;
638
                                acum = width + margen;
639
                        }
640

    
641
                        if (c.getPreferredSize().getHeight() > toolHeight) {
642
                                toolHeight = c.getPreferredSize().height;
643
                        }
644
                }
645

    
646
                toolBars.setPreferredSize(new Dimension(this.getWidth(),
647
                                (int) (numFilas * toolHeight)));
648

    
649
                toolBars.updateUI();
650
        }
651

    
652
        /**
653
         * DOCUMENT ME!
654
         *
655
         * @param classesExtensions
656
         */
657
        public void setClassesExtensions(HashMap classesExtensions) {
658
                this.classesExtensions = classesExtensions;
659
        }
660

    
661
        /**
662
         * M�todo de callback invocado cuando se selecciona un men� o un bot�n de
663
         * la barra de herramientas. Se busca la extensi�n asociada y se ejecuta
664
         *
665
         * @param e Evento producido
666
         */
667
        public void actionPerformed(ActionEvent e) {
668
                Object control = e.getSource();
669
                com.iver.andami.plugins.IExtension ext = (com.iver.andami.plugins.IExtension) classesExtensions.get((Class) controlClass.get(
670
                                control));
671
                String actionCommand = e.getActionCommand();
672
                try {
673
                        logger.debug(Messages.getString("Ejecutando comando: ") + actionCommand);
674
                        ext.execute(actionCommand);
675

    
676
                        try {
677
                                JToolBarToggleButton toggle = (JToolBarToggleButton) control;
678
                                ToggleButtonModel model = (ToggleButtonModel)toggle.getModel();
679
                                selectedTool.put(model.getGroupName(), actionCommand);
680
                        }
681
                        catch (ClassCastException ex) {}
682
                        catch (NullPointerException ex) {}
683

    
684
                } catch (RuntimeException t) {
685
                        if (ext==null) {
686
                                logger.error(Messages.getString("No_extension_associated_with_this_event_")+ e.getActionCommand());
687
                        }
688
                        NotificationManager.addError(
689
                                        Messages.getString("PluginServices.Bug_en_el_codigo") + ": " + t.getMessage(),
690
                                        t);
691
                }
692

    
693
                enableControls();
694
                showMemory();
695
        }
696

    
697
        /**
698
         * DOCUMENT ME!
699
         *
700
         * @param name DOCUMENT ME!
701
         * @param loader DOCUMENT ME!
702
         *
703
         * @return DOCUMENT ME!
704
         */
705
        private String getName(String name, PluginClassLoader loader) {
706
                if (name.indexOf('.') == -1) {
707
                        return loader.getPluginName() + "." + name;
708
                } else {
709
                        return name;
710
                }
711
        }
712

    
713
        /**
714
         * DOCUMENT ME!
715
         *
716
         * @param loader DOCUMENT ME!
717
         * @param menu DOCUMENT ME!
718
         *
719
         * @throws RuntimeException DOCUMENT ME!
720
         */
721
        public void addPopupMenu(PluginClassLoader loader, PopupMenu menu) {
722
                if (!SwingUtilities.isEventDispatchThread()) {
723
                        throw new RuntimeException("No Event Dispatch Thread");
724
                }
725

    
726
                String name = getName(menu.getName(), loader);
727

    
728
                //Se crea el control popupmenu
729
                JPopUpMenu popupMenu = (JPopUpMenu) popupMap.get(name);
730

    
731
                if (popupMenu == null) {
732
                        popupMenu = new JPopUpMenu(menu.getName());
733
                        popupMap.put(name, popupMenu);
734
                }
735

    
736
                // Se a�aden las entradas
737
                Menu[] menues = menu.getMenu();
738

    
739
                for (int i = 0; i < menues.length; i++) {
740
                        //Se registra y a�ade el menu
741
                        JMenuItem nuevoMenu = createJMenuItem(loader, menues[i]);
742

    
743
                        popupMenu.add(nuevoMenu);
744
                }
745
        }
746

    
747
        /**
748
         * DOCUMENT ME!
749
         *
750
         * @param loader
751
         * @param menu
752
         *
753
         * @return
754
         *
755
         * @throws RuntimeException DOCUMENT ME!
756
         */
757
        private JMenuItem createJMenuItem(PluginClassLoader loader, Menu menu) {
758
                JMenuItem nuevoMenu = null;
759

    
760
                PluginServices ps = PluginServices.getPluginServices(loader.getPluginName());
761
                String text = menu.getText();
762
                text = text.substring(text.lastIndexOf('/') + 1);
763
                String translatedText = ps.getText(text);
764

    
765
                if (menu.getIcon() != null) {
766
                        ImageIcon image = PluginServices.getIconTheme().get(menu.getIcon(),ps.getClassLoader());
767
                        if (image != null) {
768
                                nuevoMenu = new JMenuItem(translatedText, image);
769
                        } else {
770
                                nuevoMenu = new JMenuItem(translatedText, PluginServices.getIconTheme().get(noIcon));
771
                                logger.error(PluginServices.getText(this, "Unable_to_find_icon") +": "+menu.getIcon());
772
                        }
773
                } else {
774
                        nuevoMenu = new JMenuItem(translatedText);
775
                }
776
                nuevoMenu.setName(text);
777
                if (menu.getMnemonic() != null) {
778
                        if (menu.getMnemonic().length() != 1) {
779
                                throw new RuntimeException(
780
                                "Mnemonic must be 1 character length");
781
                        }
782

    
783
                        nuevoMenu.setMnemonic(KeyMapping.getKey(menu.getMnemonic().charAt(0)));
784
                }
785

    
786
                if (menu.getKey() != null) {
787
                        String osName = (String) System.getProperty("os.name");
788
                        boolean MAC_OS_X = osName.toLowerCase().startsWith("mac os x");
789
                        if (MAC_OS_X) {
790
                                //en OS X, en vez de hardwiring la ShortcutKey, usamos el default sugerido por el OS
791
                                nuevoMenu.setAccelerator(KeyStroke.getKeyStroke(KeyMapping.getKey(
792
                                                menu.getKey().charAt(0)), Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
793
                        } else {
794
                                nuevoMenu.setAccelerator(KeyStroke.getKeyStroke(KeyMapping.getKey(
795
                                                menu.getKey().charAt(0)), ActionEvent.ALT_MASK));
796
                        }
797
                }
798

    
799
                nuevoMenu.setActionCommand(menu.getActionCommand());
800

    
801
                if (menu.getTooltip() != null) {
802
                        nuevoMenu.setToolTip(ps.getText(menu.getTooltip()));
803
                }
804

    
805
                if (menu.getEnableText() != null) {
806
                        nuevoMenu.setEnableText(ps.getText(menu.getEnableText()));
807
                }
808

    
809
                nuevoMenu.setEnabled(true);
810
                nuevoMenu.setVisible(true);
811

    
812
                return nuevoMenu;
813
        }
814

    
815
        /**
816
         * Muestra u oculta el menu de nombre 'name'
817
         *
818
         * @param name Nombre del menu que se quiere mostrar
819
         * @param x Evento de raton
820
         * @param y DOCUMENT ME!
821
         * @param c DOCUMENT ME!
822
         */
823
        private void showPopupMenu(String name, int x, int y, Component c) {
824
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
825

    
826
                if (menu != null) {
827
                        menu.show(c, x, y);
828
                }
829
        }
830

    
831
        /**
832
         * DOCUMENT ME!
833
         *
834
         * @param name DOCUMENT ME!
835
         * @param listener DOCUMENT ME!
836
         */
837
        public void removePopupMenuListener(String name, ActionListener listener) {
838
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
839

    
840
                if (menu != null) {
841
                        Component[] jmenuitems = menu.getComponents();
842

    
843
                        for (int i = 0; i < jmenuitems.length; i++) {
844
                                if (jmenuitems[i] instanceof JMenuItem) {
845
                                        ((JMenuItem) jmenuitems[i]).removeActionListener(listener);
846
                                }
847
                        }
848
                }
849
        }
850

    
851
        /**
852
         * DOCUMENT ME!
853
         *
854
         * @param popupName
855
         * @param c DOCUMENT ME!
856
         * @param listener
857
         * @param loader
858
         */
859
        public void addPopupMenuListener(String popupName, Component c,
860
                        ActionListener listener, PluginClassLoader loader) {
861
                final String name = getName(popupName, loader);
862

    
863
                JPopupMenu menu = (JPopupMenu) popupMap.get(name);
864

    
865
                if (menu != null) {
866
                        Component[] jmenuitems = menu.getComponents();
867

    
868
                        for (int i = 0; i < jmenuitems.length; i++) {
869
                                if (jmenuitems[i] instanceof JMenuItem) {
870
                                        ((JMenuItem) jmenuitems[i]).addActionListener(listener);
871
                                }
872
                        }
873
                }
874

    
875
                c.addMouseListener(new MouseAdapter() {
876
                        public void mousePressed(MouseEvent e) {
877
                                if (e.isPopupTrigger()) {
878
                                        showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
879
                                }
880
                        }
881

    
882
                        public void mouseReleased(MouseEvent e) {
883
                                if (e.isPopupTrigger()) {
884
                                        showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
885
                                }
886
                        }
887
                });
888
        }
889

    
890
        /**
891
         * Loop on the controls to enable/disable and show/hide them, according to
892
         * its associated extension
893
         *
894
         * @throws RuntimeException DOCUMENT ME!
895
         */
896
        public void enableControls() {
897
                if (!SwingUtilities.isEventDispatchThread()) {
898
                        throw new RuntimeException("No Event Dispatch Thread");
899
                }
900

    
901
                Iterator e = classesExtensions.values().iterator();
902
                HashMap estadoExtensiones = new HashMap();
903
                HashMap visibilidadExtensiones = new HashMap();
904

    
905
                while (e.hasNext()) {
906
                        ExtensionDecorator ext = (ExtensionDecorator) e.next();
907

    
908
                        try {
909
                                if (estadoExtensiones.get(ext) == null) {
910
                                        boolean b;
911
                                        if (ext.getVisibility() == ExtensionDecorator.ALWAYS_VISIBLE)
912
                                                b = true;
913
                                        else if (ext.getVisibility() == ExtensionDecorator.ALWAYS_INVISIBLE)
914
                                                b = false;
915
                                        else {
916
                                                if (PluginServices.getExclusiveUIExtension() == null) {
917
                                                        b = ext.isVisible();
918
                                                } else {
919
                                                        b = PluginServices.getExclusiveUIExtension().isVisible(ext.getExtension());
920
                                                }
921
                                        }
922
                                        Boolean visible = new Boolean(b);
923
                                        Boolean enabled = new Boolean(false);
924

    
925
                                        if (visible.booleanValue()) {
926
                                                if (PluginServices.getExclusiveUIExtension() == null) {
927
                                                        enabled = new Boolean(ext.isEnabled());
928
                                                }else {
929
                                                        enabled = new Boolean(PluginServices.getExclusiveUIExtension().isEnabled(ext.getExtension()));
930
                                                }
931

    
932
                                        }
933

    
934
                                        estadoExtensiones.put(ext, enabled);
935
                                        visibilidadExtensiones.put(ext, visible);
936
                                }
937
                        } catch (Throwable e1) {
938
                                NotificationManager.addError(
939
                                                Messages.getString("PluginServices.Bug_en_el_codigo") + ": " + e1.getMessage(),
940
                                                e1);
941
                                estadoExtensiones.put(ext, Boolean.FALSE);
942
                        }
943
                }
944

    
945
                // Enable or disable controls, according to its associated extensions
946
                e = controlClass.keySet().iterator();
947

    
948
                while (e.hasNext()) {
949
                        JComponent control = (JComponent) e.next();
950

    
951
                        try {
952
                                com.iver.andami.plugins.IExtension ext = (com.iver.andami.plugins.IExtension) classesExtensions.get((Class) controlClass.get(
953
                                                control));
954
                                boolean enabled = ((Boolean) estadoExtensiones.get(ext)).booleanValue();
955
                                boolean visible = ((Boolean) visibilidadExtensiones.get(ext)).booleanValue();
956
                                control.setEnabled(enabled);
957
                                control.setVisible(visible);
958
                        } catch (Exception ex) {
959
                                control.setEnabled(false);
960
                                control.setVisible(false);
961
                        }
962
                }
963

    
964
                // Loop in the menus to hide the menus that don't have visible children
965
                for (int i = 0; i < menuBar.getMenuCount(); i++) {
966
                        MenuElement menu = menuBar.getMenu(i);
967
                        hideMenus(menu);
968
                        if (menu instanceof JMenu) {
969
                                //hide (ugly) redundant separators and assign keyboard mnemonics
970
                                Component[] comps = ((JMenu)menu).getMenuComponents();                                
971
                                // mnemonics have to be unique for each top-level menu
972
                                char mnemonics[] = new char[comps.length];
973
                                if ( comps.length > 0 ) {
974
                                        // Set keyboard mnemonic for this top-level entry
975
                                        String text = ((JMenu)menu).getText();
976
                                        char mnemonic = getMnemonic(text, mnemonics);                        
977
                                        if (' ' != mnemonic)
978
                                        {
979
                                                ((JMenu)menu).setMnemonic(mnemonic);
980
                                                mnemonics[0] = mnemonic;                
981
                                        }
982
                                }
983
                                // now go through all entries in this menu, hid
984
                                // separators if necessary and assing remaining mnemonics
985
                                hideSeparatorsAndMakeMnemonics(menu, mnemonics);
986
                        }
987
                }
988

    
989
                // hide the toolbars that don't contain any visible tool
990
                Iterator it = toolBarMap.values().iterator();
991

    
992
                while (it.hasNext()) {
993
                        SelectableToolBar t = (SelectableToolBar) it.next();
994
                        boolean todosOcultos = true;
995

    
996
                        for (int i = 0; i < t.getComponentCount(); i++) {
997
                                if (!(t.getComponent(i) instanceof JSeparator) // separators don't matter
998
                                                && t.getComponent(i).isVisible()) {
999
                                        todosOcultos = false;
1000
                                }
1001
                        }
1002

    
1003
                        if (todosOcultos) {
1004
                                t.setVisible(false);
1005
                        }
1006
                        else {
1007
                                t.setVisible(t.getAndamiVisibility());
1008
                        }
1009
                }
1010

    
1011
                if (mdiManager != null) {
1012
                        JPanel f = (JPanel) mdiManager.getActiveWindow();
1013

    
1014
                        if (f != null) {
1015
                                if (lastLabelClass != f.getClass()) {
1016
                                        lastLabelClass = f.getClass();
1017

    
1018
                                        Label[] lbls = (Label[]) classLabels.get(lastLabelClass);
1019

    
1020
                                        if (lbls != null) {
1021
                                                bEstado.setLabelSet(lbls);
1022
                                        }
1023
                                }
1024
                        }
1025
                }
1026

    
1027
                ajustarToolBar();
1028

    
1029
                showMemory();
1030
        }
1031

    
1032
        /**
1033
         * Establece la visibilidad de un menu y todos sus descendientes en la
1034
         * jerarquia teniendo en cuenta la visibilidad de todos los submenus.
1035
         *
1036
         * @param menu Menu que se quiere visualizar
1037
         *
1038
         * @return Devuelve true si el menu es visible y false en caso contrario
1039
         */
1040
        private boolean hideMenus(MenuElement menu) {
1041
                MenuElement[] submenus = menu.getSubElements();
1042

    
1043
                //Si no tiene hijos se devuelve su visibilidad
1044
                if (submenus.length == 0) {
1045
                        return menu.getComponent().isVisible();
1046
                }
1047

    
1048
                /*
1049
                 * Si tiene hijos se devuelve true si alg�no de ellos es visible,
1050
                 * pero se itera por todos ellos
1051
                 */
1052
                boolean visible = false;
1053

    
1054
                for (int i = 0; i < submenus.length; i++) {
1055
                        if (hideMenus(submenus[i])) {
1056
                                if (!(menu instanceof JPopupMenu)) {
1057
                                        menu.getComponent().setVisible(true);
1058
                                }
1059

    
1060
                                visible = true;
1061
                        }
1062
                }
1063

    
1064
                if (visible) {
1065
                        return true;
1066
                }
1067

    
1068
                menu.getComponent().setVisible(false);
1069

    
1070
                return false;
1071
        }        
1072

    
1073
        /**
1074
         * 
1075
         * Recurse through all menu elements and make sure there are no
1076
         * redundant separators.
1077
         * This method will make sure that a separator only becomes visible
1078
         * if at least one visible non-separator menu entry preceeded it.
1079
         *         
1080
         **/
1081
        private void hideSeparatorsAndMakeMnemonics(MenuElement menu, char[] mnemonics ) {
1082
                // flag that indicates whether a separator is to be displayed or not
1083
                boolean allowSeparator;
1084

    
1085
                allowSeparator = false; // separator not allowed as very first menu item
1086
                Component[] comps = ((JMenu)menu).getMenuComponents();
1087
                if ( comps.length < 1 ) {
1088
                        //zero-length menu: skip
1089
                        return;
1090
                }
1091

    
1092
                for ( int i=0; i < comps.length; i++ ) {                                
1093
                        if ( comps[i] instanceof JSeparator ) {
1094
                                // got a separator: display only if allowed at this position
1095
                                if ( allowSeparator == true ) {
1096
                                        // look at all successive menu entries to make sure that at least one
1097
                                        // is visible and not a separator (otherwise, this separator would
1098
                                        // be the last visible item in this menu) -- we don't want that
1099
                                        comps[i].setVisible( false );
1100
                                        for ( int j = i; j < comps.length; j ++ ) {
1101
                                                if ( !(comps[j] instanceof JSeparator)) {
1102
                                                        if ( comps[j].isVisible() ) {
1103
                                                                comps[i].setVisible( true ); // display separator!
1104
                                                                break;
1105
                                                        }
1106
                                                }
1107
                                        }                                                
1108
                                } else {
1109
                                        comps[i].setVisible( false );
1110
                                }
1111
                                allowSeparator = false; // separator is not allowed right after another separator
1112
                        } else {                                        
1113
                                if (comps[i] instanceof JMenu) { // got a submenu: recurse through it
1114
                                        // get number of submenu components
1115
                                        Component[] scomps = ((JMenu)comps[i]).getMenuComponents();                                        
1116
                                        // make a new, fresh array to hold unique mnemonics for this submenu
1117
                                        char[] smnemonics = new char[scomps.length];
1118
                                        hideSeparatorsAndMakeMnemonics ( ((MenuElement)comps[i]), smnemonics );
1119
                                        if ( comps[i].isVisible() ) {
1120
                                                allowSeparator = true; // separators are OK after visible submenus
1121
                                                // Set keyboard mnemonic for this submenu
1122
                                                String text = ((JMenu)comps[i]).getText();
1123
                                                char mnemonic = getMnemonic(text, mnemonics);
1124
                                                if (' ' != mnemonic)
1125
                                                {
1126
                                                        ((JMenu)comps[i]).setMnemonic(mnemonic);
1127
                                                        mnemonics[i] = mnemonic;                
1128
                                                }                                                        
1129
                                        }
1130
                                } else {
1131
                                        if ( comps[i].isVisible() ) {                                                        
1132
                                                if ( comps[i] instanceof JMenuItem) {
1133
                                                        // Set keyboard mnemonic for this menu item
1134
                                                        String text = ((JMenuItem)comps[i]).getText();
1135
                                                        char mnemonic = getMnemonic(text, mnemonics);
1136
                                                        if (' ' != mnemonic)
1137
                                                        {
1138
                                                                ((JMenuItem)comps[i]).setMnemonic(mnemonic);
1139

    
1140
//                                                                if (((JMenuItem)comps[i]).getAccelerator() == null){                                                                
1141
//                                                                        char[] mnemonicsLower = new char[]{mnemonic};                                                        
1142
//                                                                        ((JMenuItem)comps[i]).setAccelerator(KeyStroke.getKeyStroke(KeyMapping.getKey(new String(mnemonicsLower).toLowerCase().charAt(0)), ActionEvent.ALT_MASK));
1143
//                                                                }
1144
                                                                mnemonics[i] = mnemonic;                
1145
                                                        }
1146
                                                }
1147
                                                allowSeparator = true; // separators are OK after regular, visible entries
1148
                                        }
1149
                                }
1150
                        }
1151
                } 
1152
        }
1153

    
1154

    
1155
        /**
1156
         * Helper functios for assigning a unique mnemomic char from
1157
         * a pool of unassigned onces, stored in the array "mnemomnics"
1158
         */
1159
        private char getMnemonic(String text, char[] mnemonics)
1160
        {
1161
                Vector words = new Vector();
1162
                StringTokenizer t = new StringTokenizer(text);
1163
                int maxsize = 0;
1164

    
1165
                while (t.hasMoreTokens())
1166
                {
1167
                        String word = (String) t.nextToken();
1168
                        if (word.length() > maxsize) maxsize = word.length();
1169
                        words.addElement(word);
1170
                }
1171
                words.trimToSize();
1172

    
1173
                for (int i = 0; i < maxsize; ++i)
1174
                {
1175
                        char mnemonic = getMnemonic(words, mnemonics, i);
1176
                        if (' ' != mnemonic)
1177
                                return mnemonic;
1178
                }
1179

    
1180
                return ' ';
1181
        }
1182

    
1183
        private char getMnemonic(Vector words, char[] mnemonics, int index)
1184
        {
1185
                int numwords = words.size();
1186

    
1187
                for (int i = 0; i < numwords; ++i)
1188
                {
1189
                        String word = (String) words.elementAt(i);
1190
                        if (index >= word.length()) continue;
1191

    
1192
                        char c = word.charAt(index);
1193
                        if (!isMnemonicExists(c, mnemonics)) {
1194
                                /* pick only valid chars */
1195
                                if ( c!=':' && c!='.' && c!=',' && 
1196
                                                c!=';' && c!='-' && c!='+' && 
1197
                                                c!='/' && c!='\\' && c!='\'' &&
1198
                                                c!='\"' && c!=' ' && c!='=' &&
1199
                                                c!='(' && c!=')' && c!='[' &&
1200
                                                c!=']' && c!='{' && c!='}' &&
1201
                                                c!='$' && c!='*' && c!='&' &&
1202
                                                c!='%' && c!='!' && c!='?' &&
1203
                                                c!='#' && c!='~' && c!='_' ) 
1204
                                {
1205
                                        return c;
1206
                                }
1207
                        }
1208
                }
1209
                return ' ';
1210
        }
1211

    
1212
        private boolean isMnemonicExists(char c, char[] mnemonics)
1213
        {
1214
                int num = mnemonics.length;
1215
                for (int i = 0; i < num; ++i)
1216
                        if (mnemonics[i] == c) return true;
1217
                return false;
1218
        }         
1219

    
1220
        /**
1221
         * Muestra la memoria consumida por el programa
1222
         */
1223
        private void showMemory() {
1224
                Runtime r = Runtime.getRuntime();
1225
                long mem = r.totalMemory() - r.freeMemory();
1226
                logger.debug(PluginServices.getText(this, "memory_usage") + " " + mem/1024 +" KB");
1227
        }
1228

    
1229
        /**
1230
         * DOCUMENT ME!
1231
         *
1232
         * @return
1233
         */
1234
        public MDIManager getMDIManager() {
1235
                return mdiManager;
1236
        }
1237

    
1238
        /**
1239
         * Establece el mensaje en la barra de estado asociado a una etiqueta
1240
         *
1241
         * @return DOCUMENT ME!
1242
         */
1243
        public NewStatusBar getStatusBar() {
1244
                return bEstado;
1245
        }
1246
        /**
1247
         * You can use this function to select the appropiate
1248
         * tool inside the toolbars
1249
         */
1250
        public void setSelectedTool(String actionCommand)
1251
        {
1252
                setSelectedTool(defaultGroup, actionCommand);
1253
        }
1254

    
1255
        /**
1256
         * You can use this function to select the appropiate
1257
         * tool inside the toolbars
1258
         */
1259
        public void setSelectedTool(String groupName, String actionCommand)
1260
        {
1261
                ButtonGroup group = (ButtonGroup) buttonGroupMap.get(groupName);
1262
                if (group==null)
1263
                        return;
1264

    
1265
                Enumeration enumeration = group.getElements();
1266
                while (enumeration.hasMoreElements()) {
1267
                        AbstractButton button = (AbstractButton) enumeration.nextElement();
1268
                        if (button.getActionCommand().equals(actionCommand)) {
1269
                                button.setSelected(true);
1270
                        }
1271
                }
1272

    
1273
                selectedTool.put(groupName, actionCommand);
1274
        }
1275

    
1276
        /**
1277
         * You can use this function to select the appropiate
1278
         * tool inside the toolbars
1279
         */
1280
        public void setSelectedTools(HashMap selectedTools)
1281
        {
1282
                selectedTool = selectedTools;
1283
                if (selectedTools==null) return;
1284
                Iterator groupNames = selectedTools.keySet().iterator();
1285
                while (groupNames.hasNext()) {
1286
                        try {
1287
                                String groupName = (String) groupNames.next();
1288
                                ButtonGroup group = (ButtonGroup) buttonGroupMap.get(groupName);
1289
                                Enumeration enumeration = group.getElements();
1290
                                String actionCommand = (String) selectedTools.get(groupName);
1291
                                if (actionCommand==null) continue;
1292
                                while (enumeration.hasMoreElements()) {
1293
                                        AbstractButton button = (AbstractButton) enumeration.nextElement();
1294
                                        if (button.getActionCommand().equals(actionCommand)) {
1295
                                                button.setSelected(true);
1296
                                        }
1297
                                }
1298
                        }
1299
                        catch (ClassCastException ex) {
1300
                                logger.error("selectedTool should only contain pairs (String groupName, JToolBarToggleButton button)");
1301
                        }
1302
                }
1303
        }
1304

    
1305
        /**
1306
         * DOCUMENT ME!
1307
         *
1308
         * @param clase
1309
         * @param label
1310
         */
1311
        public void setStatusBarLabels(Class clase, Label[] label) {
1312
                classLabels.put(clase, label);
1313
        }
1314

    
1315
        public void removeStatusBarLabels(Class clase) {
1316
                classLabels.remove(clase);
1317
        }
1318

    
1319
        public void addStatusBarControl(Class extensionClass, IControl control) {
1320
                control.addActionListener(this);
1321
                bEstado.addControl(control.getName(), (Component)control);
1322
                controlClass.put(control, extensionClass);
1323
        }
1324

    
1325
        public void removeStatusBarControl(String name) {
1326
                Component c = bEstado.removeControl(name);
1327
                if (c!=null)
1328
                        controlClass.remove(c);
1329
        }
1330

    
1331
        /**
1332
         * @see com.iver.andami.ui.mdiFrame.MainFrame#removeMenu(com.iver.andami.plugins.config.generate.Menu)
1333
         */
1334
        public void removeMenu(Menu menu) {
1335
                JMenuItem delete = (JMenuItem) infoCodedMenus.get(menu);
1336

    
1337
                if (delete == null) {
1338
                        throw new NoSuchElementException(menu.getText());
1339
                }
1340

    
1341
                delete.getParent().remove(delete);
1342
                infoCodedMenus.remove(menu);
1343
        }
1344

    
1345
        /**
1346
         * @see com.iver.andami.ui.mdiFrame.MainFrame#addMenu(com.iver.andami.plugins.config.generate.Menu,
1347
         *                 java.awt.event.ActionListener, PluginClassLoader)
1348
         */
1349
        public void addMenu(Menu menu, ActionListener listener,
1350
                        PluginClassLoader loader) {
1351
                JMenu menuPadre = createMenuAncestors(menu, loader);
1352

    
1353
                //Se registra y a�ade el menu
1354
                JMenuItem nuevoMenu = createJMenuItem(loader, menu);
1355
                nuevoMenu.addMouseListener(tooltipListener);
1356
                nuevoMenu.addActionListener(listener);
1357
                menuPadre.add(nuevoMenu);
1358

    
1359
                infoCodedMenus.put(menu, nuevoMenu);
1360
        }
1361

    
1362
        /**
1363
         * @see com.iver.andami.ui.mdiFrame.MainFrame#changeMenuName(java.lang.String[],
1364
         *                 String, com.iver.andami.plugins.PluginClassLoader)
1365
         */
1366
        public void changeMenuName(String[] menu, String newName,
1367
                        PluginClassLoader loader) {
1368

    
1369
                ArrayList menuList = new ArrayList();
1370
                for (int i = 0; i < menu.length; i++) {
1371
                        menuList.add(menu[i]);
1372
                }
1373

    
1374
                javax.swing.JMenuItem newMenu = getMenu(menuList, menuBar);
1375
                if (newMenu==null) {
1376
                        throw new NoSuchMenuException(menu[0]);
1377
                }
1378
                else {
1379
                        newMenu.setText(PluginServices.getText(this, newName));
1380
                }
1381
        }
1382

    
1383
        /**
1384
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
1385
         */
1386
        public void componentHidden(ComponentEvent arg0) {
1387
        }
1388

    
1389
        /**
1390
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
1391
         */
1392
        public void componentMoved(ComponentEvent arg0) {
1393
        }
1394

    
1395
        /**
1396
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
1397
         */
1398
        public void componentResized(ComponentEvent arg0) {
1399
                ajustarToolBar();
1400
        }
1401

    
1402
        /**
1403
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
1404
         */
1405
        public void componentShown(ComponentEvent arg0) {
1406
        }
1407

    
1408
        /**
1409
         * @see java.awt.event.ContainerListener#componentAdded(java.awt.event.ContainerEvent)
1410
         */
1411
        public void componentAdded(ContainerEvent arg0) {
1412
                ajustarToolBar();
1413
        }
1414

    
1415
        /**
1416
         * @see java.awt.event.ContainerListener#componentRemoved(java.awt.event.ContainerEvent)
1417
         */
1418
        public void componentRemoved(ContainerEvent arg0) {
1419
                ajustarToolBar();
1420
        }
1421

    
1422
        /**
1423
         * DOCUMENT ME!
1424
         *
1425
         * @author $author$
1426
         * @version $Revision: 35160 $
1427
         */
1428
        public class TooltipListener extends MouseAdapter {
1429
                /**
1430
                 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1431
                 */
1432
                public void mouseEntered(MouseEvent e) {
1433
                        JComponent control = (JComponent) e.getSource();
1434
                        EnableTextSupport ets = (EnableTextSupport) e.getSource();
1435

    
1436
                        String texto = null;
1437
                        texto = control.getToolTipText();
1438

    
1439
                        if (texto != null) {
1440
                                bEstado.setInfoTextTemporal(texto);
1441
                        }
1442
                }
1443

    
1444
                /**
1445
                 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1446
                 */
1447
                public void mouseExited(MouseEvent arg0) {
1448
                        bEstado.restaurarTexto();
1449
                }
1450

    
1451
                /**
1452
                 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1453
                 */
1454
                public void mousePressed(MouseEvent e) {
1455
                        bEstado.restaurarTexto();
1456
                }
1457
        }
1458
        public String getTitlePrefix() {
1459
                return titlePrefix;
1460
        }
1461
        public void setTitlePrefix(String titlePrefix) {
1462
                this.titlePrefix = titlePrefix;
1463
        }
1464

    
1465
        public HashMap getSelectedTools() {
1466
                return selectedTool;
1467
        }
1468

    
1469
        public HashMap getInitialSelectedTools() {
1470
                return initialSelectedTools;
1471
        }
1472

    
1473

    
1474
        /**
1475
         * Get a previously added JComponent by name. For example
1476
         * you can use it if you need to obtain a JToolBar to
1477
         * add some customized component.
1478
         * @param name
1479
         * @return the JComponent or null if none has been found
1480
         */
1481
        public JComponent getComponentByName(String name)
1482
        {
1483
                Iterator e = controlClass.keySet().iterator();
1484

    
1485
                while (e.hasNext()) {
1486
                        JComponent control = (JComponent) e.next();
1487
                        String nameCtrl = control.getName();
1488
                        if (nameCtrl != null)
1489
                        {
1490
                                if (nameCtrl.compareTo(name) == 0)
1491
                                        return control;
1492
                        }
1493
                }
1494
                Iterator it = toolBarMap.values().iterator();
1495
                while (it.hasNext()) {
1496
                        SelectableToolBar t = (SelectableToolBar) it.next();
1497
                        String nameCtrl = t.getName();
1498
                        if (nameCtrl != null)
1499
                                if (nameCtrl.compareTo(name) == 0)
1500
                                        return t;
1501

    
1502
                }
1503

    
1504
                return null;
1505
        }
1506

    
1507
        public SelectableToolBar[] getToolbars() {
1508
                return (SelectableToolBar[]) toolBarMap.values().toArray(new SelectableToolBar[0]);
1509
        }
1510

    
1511
        public boolean getToolbarVisibility(String name) {
1512
                JComponent component = PluginServices.getMainFrame().getComponentByName(name);
1513
                if (component!=null && component instanceof SelectableToolBar) {
1514
                        SelectableToolBar toolBar = (SelectableToolBar) component;
1515
                        return toolBar.getAndamiVisibility();
1516
                }
1517
                return false;
1518
        }
1519

    
1520
        public boolean setToolbarVisibility(String name, boolean visibility) {
1521
                JComponent component = PluginServices.getMainFrame().getComponentByName(name);
1522
                if (component!=null && component instanceof SelectableToolBar) {
1523
                        SelectableToolBar toolBar = (SelectableToolBar) component;
1524
                        boolean oldVisibility = toolBar.getAndamiVisibility();
1525
                        toolBar.setAndamiVisibility(visibility);
1526
                        enableControls();
1527
                        return oldVisibility;
1528
                }
1529
                return false;
1530
        }
1531

    
1532
        public javax.swing.JMenuItem getMenuEntry(String[] menuPath) {
1533
                ArrayList menu = new ArrayList();
1534
                for (int i=0; i<menuPath.length; i++)
1535
                        menu.add(menuPath[i]);
1536
                return getMenu(menu, menuBar);
1537
        }
1538
}