Statistics
| Revision:

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

History | View | Annotate | Download (43.4 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
import org.gvsig.tools.OsUtils;
85

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

    
102

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
172
        private String titlePrefix;
173

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

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

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

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

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

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

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

    
217
                this.toolBars.addContainerListener(this);
218

    
219
                pack();
220

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

    
226
                mdiManager.init(this);
227
        }
228

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
366
                String name = toolBar.getName();
367

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

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

    
378
                jtb.add(btn);
379

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

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

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

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

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

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

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

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

    
423
                JMenu padre = null;
424

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

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

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

    
445
                menuPadre = createMenus(temp, padre);
446

    
447
                return (JMenu) menuPadre;
448
        }
449

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

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

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

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

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

    
494

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

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

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

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

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

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

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

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

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

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

    
609
                        nombres.remove(0);
610

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

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

    
625
                int toolHeight = 0;
626

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

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

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

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

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

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

    
650
                toolBars.updateUI();
651
        }
652

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
787
                if (menu.getKey() != null) {
788
                        if (OsUtils.isMac()) {
789
                                //en OS X, en vez de hardwiring la ShortcutKey, usamos el default sugerido por el OS
790
                                nuevoMenu.setAccelerator(KeyStroke.getKeyStroke(KeyMapping.getKey(
791
                                                menu.getKey().charAt(0)), Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
792
                        } else {
793
                                nuevoMenu.setAccelerator(KeyStroke.getKeyStroke(KeyMapping.getKey(
794
                                                menu.getKey().charAt(0)), ActionEvent.ALT_MASK));
795
                        }
796
                }
797

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

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

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

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

    
811
                return nuevoMenu;
812
        }
813

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
931
                                        }
932

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1026
                ajustarToolBar();
1027

    
1028
                showMemory();
1029
        }
1030

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

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

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

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

    
1059
                                visible = true;
1060
                        }
1061
                }
1062

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

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

    
1069
                return false;
1070
        }        
1071

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

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

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

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

    
1153

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

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

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

    
1179
                return ' ';
1180
        }
1181

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

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

    
1191
                        char c = word.charAt(index);
1192
                        if (!isMnemonicExists(c, mnemonics)) {
1193
                                /* pick only valid chars */
1194
                                if ( c!=':' && c!='.' && c!=',' && 
1195
                                                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
                                {
1204
                                        return c;
1205
                                }
1206
                        }
1207
                }
1208
                return ' ';
1209
        }
1210

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1472

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

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

    
1501
                }
1502

    
1503
                return null;
1504
        }
1505

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

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

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

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