Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.framework / org.gvsig.andami / src / main / java / org / gvsig / andami / ui / mdiFrame / MDIFrame.java @ 42351

History | View | Annotate | Download (68.6 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA 02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.andami.ui.mdiFrame;
25

    
26
import java.awt.BorderLayout;
27
import java.awt.Component;
28
import java.awt.Dimension;
29
import java.awt.FlowLayout;
30
import java.awt.Insets;
31
import java.awt.event.ActionEvent;
32
import java.awt.event.ActionListener;
33
import java.awt.event.ComponentEvent;
34
import java.awt.event.ComponentListener;
35
import java.awt.event.ContainerEvent;
36
import java.awt.event.ContainerListener;
37
import java.awt.event.MouseAdapter;
38
import java.awt.event.MouseEvent;
39
import java.awt.event.WindowAdapter;
40
import java.awt.event.WindowEvent;
41
import java.io.File;
42
import java.util.ArrayList;
43
import java.util.Enumeration;
44
import java.util.HashMap;
45
import java.util.Iterator;
46
import java.util.List;
47
import java.util.Locale;
48
import java.util.Map;
49
import java.util.NoSuchElementException;
50
import java.util.StringTokenizer;
51
import java.util.Vector;
52

    
53
import javax.swing.AbstractButton;
54
import javax.swing.ButtonGroup;
55
import javax.swing.ImageIcon;
56
import javax.swing.JComponent;
57
import javax.swing.JFileChooser;
58
import javax.swing.JFrame;
59
import javax.swing.JMenu;
60
import javax.swing.JMenuBar;
61
import javax.swing.JOptionPane;
62
import javax.swing.JPanel;
63
import javax.swing.JPopupMenu;
64
import javax.swing.JSeparator;
65
import javax.swing.JToolBar;
66
import javax.swing.KeyStroke;
67
import javax.swing.MenuElement;
68
import javax.swing.SwingUtilities;
69
import javax.swing.Timer;
70
import javax.swing.WindowConstants;
71
import javax.swing.filechooser.FileFilter;
72

    
73
import org.gvsig.andami.IconThemeHelper;
74
import org.gvsig.andami.Launcher;
75
import org.gvsig.andami.PluginServices;
76
import org.gvsig.andami.PluginsLocator;
77
import org.gvsig.andami.PluginsManager;
78
import org.gvsig.andami.actioninfo.ActionInfo;
79
import org.gvsig.andami.actioninfo.ActionInfoManager;
80
import org.gvsig.andami.actioninfo.ActionInfoStatusCache;
81
import org.gvsig.andami.messages.Messages;
82
import org.gvsig.andami.plugins.ExtensionDecorator;
83
import org.gvsig.andami.plugins.IExtension;
84
import org.gvsig.andami.plugins.PluginClassLoader;
85
import org.gvsig.andami.plugins.config.generate.ActionTool;
86
import org.gvsig.andami.plugins.config.generate.Label;
87
import org.gvsig.andami.plugins.config.generate.Menu;
88
import org.gvsig.andami.plugins.config.generate.PopupMenu;
89
import org.gvsig.andami.plugins.config.generate.SelectableTool;
90
import org.gvsig.andami.plugins.config.generate.SkinExtensionType;
91
import org.gvsig.andami.plugins.config.generate.ToolBar;
92
import org.gvsig.andami.ui.mdiFrame.TranslatableButtonHelper.TranslatableButton;
93
import org.gvsig.andami.ui.mdiManager.MDIManager;
94
import org.gvsig.andami.ui.mdiManager.MDIManagerFactory;
95
import org.gvsig.gui.beans.controls.IControl;
96
import org.gvsig.tools.ToolsLocator;
97
import org.gvsig.tools.i18n.I18nManager;
98
import org.gvsig.tools.swing.api.ToolsSwingLocator;
99
import org.gvsig.tools.swing.icontheme.IconTheme;
100

    
101
import org.slf4j.Logger;
102
import org.slf4j.LoggerFactory;
103

    
104
/**
105
 * Main application window.
106
 *
107
 * Use Launcher.getMDIFrame to get the instance of this class.
108
 *
109
 * @version $Revision: 39484 $
110
 */
111
@SuppressWarnings("unchecked")
112
public class MDIFrame extends JFrame implements ComponentListener,
113
        ContainerListener, ActionListener, MainFrame {
114

    
115
    private static final long serialVersionUID = -2472484309160847654L;
116

    
117
    private static Logger logger = LoggerFactory.getLogger(MDIFrame.class);
118

    
119
    private static MDIFrame instance = null;
120

    
121
    private MDIManager mdiManager = MDIManagerFactory.createManager();
122

    
123
    private boolean refreshingControls = false;
124

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

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

    
135
    /**
136
     * Status bar
137
     */
138
    private NewStatusBar bEstado = null;
139

    
140
    /**
141
     * Asocia los nombres con las barras de herramientas
142
     */
143
    private HashMap toolBarMap = new HashMap();
144

    
145
    /**
146
     * Almacena los grupos de selectableTools
147
     */
148
    private HashMap buttonGroupMap = new HashMap();
149
    /**
150
     * Stores the initially selected tools.
151
     * It contains pairs (String groupName, JToolBarToggleButton button)
152
     */
153
    private HashMap initialSelectedTools = new HashMap();
154

    
155
    /**
156
     * Stores the actionCommand of the selected tool, for each group.
157
     * It contains pairs (String groupName, JToolBarToggleButton button)
158
     */
159
    private Map selectedTool = null;
160
    // this should be the same value defined at plugin-config.xsd
161
    private String defaultGroup = "unico";
162

    
163
    /**
164
     * Asocia los nombres con los popupMenus
165
     */
166
    private HashMap popupMap = new HashMap();
167

    
168
    /**
169
     * Asocia controles con la clase de la extension asociada
170
     */
171
    private List<JComponent> controls = new ArrayList<JComponent>();
172

    
173
    /**
174
     * Asocia la informaci�n sobre las etiquetas que van en la status bar con
175
     * cada extension
176
     */
177
    private HashMap classLabels = new HashMap();
178

    
179
    // private HashMap classControls = new HashMap();
180
    /**
181
     * ProgressListeners (ver interfaz com.iver.mdiApp.ui.ProgressListener)
182
     */
183
    private ArrayList progressListeners = new ArrayList();
184

    
185
    /**
186
     * Timer para invocar los enventos de la interfaz anterior
187
     */
188
    private Timer progressTimer = null;
189

    
190
    /**
191
     * Tabla hash que asocia las clases con las extensiones
192
     */
193
    // private Map classesExtensions = new HashMap<Class<? extends IExtension>, ExtensionDecorator>();
194
    /**
195
     * �ltima clase que activ� etiquetas
196
     */
197
    private Class lastLabelClass;
198

    
199
    /**
200
     * Instancia que pone los tooltip en la barra de estado
201
     */
202
    private TooltipListener tooltipListener = new TooltipListener();
203

    
204
    private HashMap infoCodedMenus = new HashMap();
205

    
206
    private String titlePrefix;
207

    
208
    private static final String noIcon = "no-icon";
209

    
210
    private Map<JComponent,IExtension> control2extensions = new HashMap<JComponent, IExtension>();
211

    
212
    private MDIFrame() {
213

    
214
    }
215

    
216
    public static boolean isInitialized() {
217
        return instance!=null ;
218
    }
219

    
220
    public static MDIFrame getInstance() {
221
        if ( instance == null ) {
222
            instance = new MDIFrame();
223
        }
224
        return instance;
225
    }
226

    
227
    /**
228
     * Makes some initialization tasks.
229
     *
230
     * @throws RuntimeException
231
     */
232
    public void init() {
233
        JPopupMenu.setDefaultLightWeightPopupEnabled(false);
234
        if ( !SwingUtilities.isEventDispatchThread() ) {
235
            throw new RuntimeException("Not Event Dispatch Thread");
236
        }
237

    
238
        // Se añaden los listeners del JFrame
239
        this.addWindowListener(new WindowAdapter() {
240

    
241
            @Override
242
            public void windowClosing(WindowEvent e) {
243
                Launcher.closeApplication();
244
            }
245
        });
246
        this.addComponentListener(this);
247
        this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
248

    
249
        // Se configura la barra de menu
250
        setJMenuBar(menuBar);
251

    
252
        // Se configura el layout del JFrame principal
253
        this.getContentPane().setLayout(new BorderLayout());
254

    
255
        /*
256
         * Se configura y se añade el JPanel de las barras de
257
         * herramientas
258
         */
259
        FlowLayout layout = new FlowLayout(FlowLayout.LEFT);
260
        layout.setHgap(0);
261
        layout.setVgap(0);
262
        toolBars.setLayout(layout);
263
        getContentPane().add(toolBars, BorderLayout.PAGE_START);
264

    
265
        // Add the status bar of the application
266
        bEstado = new NewStatusBar();
267
        bEstado.message(Messages.getString("StatusBar.Aplicacion_iniciada"), JOptionPane.INFORMATION_MESSAGE);
268
        getContentPane().add(bEstado, BorderLayout.SOUTH);
269

    
270
        this.toolBars.addContainerListener(this);
271

    
272

    
273
        /*
274
         * Setting default values. Persistence is read
275
         * afterwards
276
         */
277
        setSize(
278
                MainFrame.MAIN_FRAME_SIZE_DEFAULT[0],
279
                MainFrame.MAIN_FRAME_SIZE_DEFAULT[1]);
280
        setLocation(
281
                MainFrame.MAIN_FRAME_POS_DEFAULT[0],
282
                MainFrame.MAIN_FRAME_POS_DEFAULT[1]);
283
        setExtendedState(
284
                MainFrame.MAIN_FRAME_EXT_STATE_DEFAULT);
285

    
286
        mdiManager.init(this);
287
    }
288

    
289
    @Override
290
    public void setTitle(final String title) {
291
        if ( !SwingUtilities.isEventDispatchThread() ) {
292
            SwingUtilities.invokeLater(new Runnable() {
293
                public void run() {
294
                    setTitle(title);
295
                }
296
            });
297
            return;
298
        }
299
        super.setTitle(titlePrefix + " : " + title);
300
    }
301

    
302
    private SelectableToolBar getToolBar(final String toolBarName) {
303
        SelectableToolBar jtb = (SelectableToolBar) toolBarMap.get(toolBarName);
304
        if ( jtb == null ) {
305
            jtb = new SelectableToolBar(toolBarName);
306
            jtb.setRollover(true);
307
            jtb.setAndamiVisibility(true);
308
            toolBarMap.put(toolBarName, jtb);
309
            toolBars.add(jtb);
310
        }
311
        return jtb;
312
    }
313

    
314
    public void addTool(final PluginClassLoader loader, final SkinExtensionType ext,
315
            final ToolBar toolBar, final SelectableTool selectableTool)
316
            throws ClassNotFoundException {
317
        if ( !SwingUtilities.isEventDispatchThread() ) {
318
            try {
319
                SwingUtilities.invokeAndWait(new Runnable() {
320
                    public void run() {
321
                        try {
322
                            addTool(loader, ext, toolBar, selectableTool);
323
                        } catch (ClassNotFoundException ex) {
324
                            logger.warn("¿¿¿ Eehh????", ex);
325
                        }
326
                    }
327
                });
328
            } catch (Exception ex) {
329
                // Do nothing
330
            }
331
            return;
332
        }
333
        String name = toolBar.getName();
334
        SelectableToolBar jtb = getToolBar(name);
335
        if( selectableTool.getDropDownGroup()!=null ) {
336
            ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
337
            ActionInfo action = actionManager.getAction(selectableTool.getName());
338
            if( action!=null ) {
339
                DropDownButton dropDownButton = (DropDownButton) jtb.findComponent(selectableTool.getDropDownGroup());
340
                if( dropDownButton==null ) {
341
                    dropDownButton = new DropDownButton();
342
                    dropDownButton.setName(selectableTool.getDropDownGroup());
343
                    jtb.add(dropDownButton);
344
                    addControl(dropDownButton);
345
                }
346
                dropDownButton.add(actionManager.getTranslated(action));
347
            }
348
            return;
349
        }
350

    
351
        I18nManager i18nManager = ToolsLocator.getI18nManager();
352

    
353
        ImageIcon image = PluginServices.getIconTheme().get(selectableTool.getIcon());
354
        if ( image != null ) {
355
            logger.warn("Unable to find icon '" + selectableTool.getIcon() + "'.");
356
            image = PluginServices.getIconTheme().get(noIcon);
357
        }
358
        
359
        ToggleButtonModel buttonModel = new ToggleButtonModel();
360
        JToolBarToggleButton btn = new JToolBarToggleButton(selectableTool.getText(), image);
361
        btn.setModel(buttonModel);
362
        btn.setMargin(new Insets(0, 0, 0, 0));
363
        btn.addMouseListener(tooltipListener);
364
        btn.addActionListener(this);
365
        btn.setFocusable(false);
366
        btn.setActionCommand(selectableTool.getActionCommand());
367
        btn.setToolTipText(selectableTool.getTooltip());
368
        btn.setEnabled(false);
369
        btn.setVisible(false);
370

    
371
        ButtonGroup group = (ButtonGroup) buttonGroupMap.get(selectableTool.getGroup());
372
        if ( group == null ) {
373
            group = new ButtonGroup();
374
            buttonGroupMap.put(selectableTool.getGroup(), group);
375
        }
376
        
377
        jtb.addButton(group, btn);
378
        
379
        buttonModel.setGroupName(selectableTool.getGroup());
380
        if ( selectableTool.getIsDefault() ) {
381
            btn.setSelected(true);
382
            initialSelectedTools.put(selectableTool.getGroup(),
383
                    btn.getActionCommand());
384
        }
385

    
386
        addControl(btn);
387

    
388
        if ( selectableTool.getName() != null ) {
389
            btn.setName(selectableTool.getName());
390
        }
391

    
392
        if ( selectableTool.getTooltip() != null ) {
393
            btn.setToolTip(i18nManager.getTranslation(selectableTool.getTooltip()));
394
            btn.setToolTipKey(selectableTool.getTooltip());
395
        }
396

    
397
        if ( selectableTool.getEnableText() != null ) {
398
            btn.setEnableText(i18nManager.getTranslation(selectableTool.getEnableText()));
399
        }
400

    
401
        if ( selectableTool.getLast() == true ) {
402
            jtb.addSeparator();
403
        }
404
    }
405

    
406
    public void addTool(final PluginClassLoader loader, final SkinExtensionType ext,
407
            final ToolBar toolBar, final ActionTool actionTool) throws ClassNotFoundException {
408
        if ( !SwingUtilities.isEventDispatchThread() ) {
409
            try {
410
                SwingUtilities.invokeAndWait(new Runnable() {
411
                    public void run() {
412
                        try {
413
                            addTool(loader, ext, toolBar, actionTool);
414
                        } catch (ClassNotFoundException ex) {
415
                            logger.warn("¿¿¿ Eehh????", ex);
416
                        }
417
                    }
418
                });
419
            } catch (Exception ex) {
420
                // Do nothing
421
            }
422
            return;
423
        }
424

    
425
        String name = toolBar.getName();
426
        SelectableToolBar jtb = getToolBar(name);
427
        if( actionTool.getDropDownGroup()!=null ) {
428
            ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
429
            ActionInfo action = actionManager.getAction(actionTool.getName());
430
            if( action!=null ) {
431
                DropDownButton dropDownButton = (DropDownButton) jtb.findComponent(actionTool.getDropDownGroup());
432
                if( dropDownButton==null ) {
433
                    dropDownButton = new DropDownButton();
434
                    dropDownButton.setName(actionTool.getDropDownGroup());
435
                    jtb.add(dropDownButton);
436
                    addControl(dropDownButton);
437
                }
438
                dropDownButton.add(actionManager.getTranslated(action));
439
            }
440
            return;
441
        }
442

    
443
        I18nManager i18nManager = ToolsLocator.getI18nManager();
444

    
445
        ImageIcon image = IconThemeHelper.getImageIcon(actionTool.getIcon());
446
        if ( image != null ) {
447
            logger.warn("Unable to find icon '" + actionTool.getIcon() + "'.");
448
            image =  PluginServices.getIconTheme().get(noIcon);
449
        }
450

    
451
        JToolBarButton btn = new JToolBarButton(actionTool.getText(), image);
452
        btn.setMargin(new Insets(0, 0, 0, 0));
453
        btn.addMouseListener(tooltipListener);
454
        btn.addActionListener(this);
455
        btn.setFocusable(false);
456
        btn.setActionCommand(actionTool.getActionCommand());
457
        btn.setEnabled(false);
458
        btn.setVisible(false);
459

    
460
        jtb.add(btn);
461

    
462
        addControl(btn);
463

    
464
        if ( actionTool.getName() != null ) {
465
            btn.setName(actionTool.getName());
466
        }
467

    
468
        if ( actionTool.getTooltip() != null ) {
469
            btn.setToolTip(i18nManager.getTranslation(actionTool.getTooltip()));
470
            btn.setToolTipKey(actionTool.getTooltip());
471
        }
472

    
473
        if ( actionTool.getEnableText() != null ) {
474
            btn.setEnableText(i18nManager.getTranslation(actionTool.getEnableText()));
475
        }
476

    
477
        if ( actionTool.getLast() == true ) {
478
            jtb.addSeparator();
479
        }
480
    }
481

    
482
    public void addTool(final ActionInfo action, final String toolBarName, final String dropDownName) {
483
        if ( !SwingUtilities.isEventDispatchThread() ) {
484
            SwingUtilities.invokeLater(new Runnable() {
485
                public void run() {
486
                    addTool(action, toolBarName,dropDownName);
487
                }
488
            });
489
            return;
490
        }
491
        SelectableToolBar jtb = getToolBar(toolBarName);
492
        DropDownButton dropDownButton = (DropDownButton) jtb.findComponent(dropDownName);
493
        if( dropDownButton == null ) {
494
            dropDownButton = new DropDownButton();
495
            jtb.add(dropDownButton);
496
        }
497
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
498
        dropDownButton.add(actionManager.getTranslated(action));
499
    }
500
    public void addTool(final ActionInfo action, final String toolBarName) {
501
        addTool(action, toolBarName, false);
502
    }
503

    
504
    public void addTool(final ActionInfo action, final String toolBarName, final boolean useText) {
505
        I18nManager i18nManager = ToolsLocator.getI18nManager();
506

    
507
        if ( !SwingUtilities.isEventDispatchThread() ) {
508
            SwingUtilities.invokeLater(new Runnable() {
509
                public void run() {
510
                    addTool(action, toolBarName, useText);
511
                }
512
            });
513
            return;
514
        }
515
        JToolBarButton btn = new JToolBarButton(action.getIcon());
516
        btn.setMargin(new Insets(0, 0, 0, 0));
517
        btn.addMouseListener(tooltipListener);
518
        btn.addActionListener(this);
519
        btn.setFocusable(false);
520
        btn.setActionCommand(action.getCommand());
521
        btn.setEnabled(false);
522
        btn.setVisible(false);
523
        btn.setName(action.getName());
524
        if( useText ) {
525
            btn.setText(action.getLabel());
526
        }
527
        if ( action.getTooltip() != null ) {
528
            btn.setToolTip(i18nManager.getTranslation(action.getTooltip()));
529
            btn.setToolTipKey(action.getTooltip());
530
        }
531

    
532
        SelectableToolBar jtb = getToolBar(toolBarName);
533
        jtb.add(btn);
534

    
535
        addControl(btn);
536

    
537
    }
538

    
539
    public void addSelectableTool(final ActionInfo action, final String toolBarName, final String groupName, final boolean useText) {
540
        I18nManager i18nManager = ToolsLocator.getI18nManager();
541

    
542
        if ( !SwingUtilities.isEventDispatchThread() ) {
543
            SwingUtilities.invokeLater(new Runnable() {
544
                public void run() {
545
                    addSelectableTool(action, toolBarName,groupName,useText);
546
                }
547
            });
548
            return;
549
        }
550

    
551
        ButtonGroup group = (ButtonGroup) buttonGroupMap.get(groupName);
552
        if ( group == null ) {
553
            group = new ButtonGroup();
554
            buttonGroupMap.put(groupName, group);
555
        }
556
        ToggleButtonModel buttonModel = new ToggleButtonModel();
557
        buttonModel.setGroupName(groupName);
558

    
559
        JToolBarToggleButton btn = new JToolBarToggleButton(action.getIcon());
560
        btn.setModel(buttonModel);
561
        btn.setMargin(new Insets(0, 0, 0, 0));
562
        btn.addMouseListener(tooltipListener);
563
        btn.addActionListener(this);
564
        btn.setFocusable(false);
565
        btn.setActionCommand(action.getCommand());
566
        btn.setEnabled(false);
567
        btn.setVisible(false);
568
        btn.setName(action.getName());
569
        if( useText ) {
570
            btn.setText(action.getLabel());
571
        }
572
        if ( action.getTooltip() != null ) {
573
            btn.setToolTip(i18nManager.getTranslation(action.getTooltip()));
574
            btn.setToolTipKey(action.getTooltip());
575
        }
576
        
577
        SelectableToolBar jtb = getToolBar(toolBarName);
578
        jtb.addButton(group, btn);
579
        
580
        addControl(btn);
581

    
582
    }
583

    
584
    /**
585
     * Creates the needed menu structure to add the menu to the bar.
586
     * Returns the father which must hold the menu which was
587
     * provided as parameter.
588
     *
589
     * Crea la estructura de menus necesaria para añadir el menu a la barra.
590
     * Devuelve el padre del cual debe colgar el menu que se pasa como
591
     * parametro.
592
     *
593
     * @param menu
594
     * The Menu whose support is going to be added
595
     * @param loader
596
     * The plugin's class loader
597
     *
598
     * @return The proper father for the menu which was provided as parameter
599
     */
600
    private JMenu createMenuAncestors(Menu menu, PluginClassLoader loader) {
601
        return createMenuAncestors(menu.getText());
602
    }
603

    
604
    private JMenu createMenuAncestors(String text) {
605
        I18nManager i18nManager = ToolsLocator.getI18nManager();
606

    
607
        MenuElement menuPadre = null;
608

    
609
        String[] menues = text.split("/");
610
        List menuList = new ArrayList();
611
        menuList.add(menues[0]);
612
        menuPadre = getMenu(menuList, menuBar);
613

    
614
        JMenu padre = null;
615

    
616
        if ( menuPadre == null ) {
617
            padre = new JMenuTraslatable(i18nManager.getTranslation(menues[0]));
618
            ((JMenuTraslatable) padre).setTextKey(menues[0]);
619
            padre.setName(menues[0]);
620
            addControl(padre);
621
            menuBar.add(padre);
622
        } else if ( menuPadre instanceof JMenu ) {
623
            padre = (JMenu) menuPadre;
624
        } else {
625
            logger.warn("Error creating menu. Ancestor does not exist (" + text + ").");
626
            return null;
627
        }
628

    
629
        // Se crea el resto de menus
630
        ArrayList temp = new ArrayList();
631

    
632
        for ( int i = 1; i < (menues.length - 1); i++ ) {
633
            temp.add(menues[i]);
634
        }
635

    
636
        menuPadre = createMenus(temp, padre);
637

    
638
        return (JMenu) menuPadre;
639
    }
640

    
641
    /**
642
     * Añade la informacion del menu al framework.
643
     * Debido a que los men�es se
644
     * pueden introducir en un orden determinado por el usuario, pero los
645
     * plugins se instalan en un orden arbitrario, primero se almacena la
646
     * informacion de todos los menus para luego ordenarlos y posteriormente
647
     * añadirlos al interfaz
648
     *
649
     * @param loader
650
     * Posicion del menu. Se ordena por este campo
651
     * @param ext
652
     * Array con los nombres de los padres del menu
653
     * @param menu
654
     * Texto del menu
655
     *
656
     * @throws ClassNotFoundException
657
     * @throws RuntimeException
658
     */
659
    public void addMenu(final PluginClassLoader loader, final SkinExtensionType ext,
660
            final Menu menu) throws ClassNotFoundException {
661
        if ( !SwingUtilities.isEventDispatchThread() ) {
662
            try {
663
                SwingUtilities.invokeAndWait(new Runnable() {
664
                    public void run() {
665
                        try {
666
                            addMenu(loader, ext, menu);
667
                        } catch (ClassNotFoundException ex) {
668
                            logger.warn("¿¿¿ Eehh????", ex);
669
                        }
670
                    }
671
                });
672
            } catch (Exception ex) {
673
                // Do nothing
674
            }
675
            return;
676
        }
677
        JMenu menuPadre = createMenuAncestors(menu, loader);
678

    
679
        if ( menu.getIs_separator() ) {
680
            menuPadre.addSeparator();
681
            return;
682
        }
683

    
684
        JMenuItem nuevoMenu = createJMenuItem(loader, menu);
685
        nuevoMenu.addMouseListener(tooltipListener);
686
        menuPadre.add(nuevoMenu);
687
        addControl(nuevoMenu);
688

    
689
    }
690

    
691
    public void addMenu(final ActionInfo action, final String text) {
692
        if ( !SwingUtilities.isEventDispatchThread() ) {
693
            SwingUtilities.invokeLater(new Runnable() {
694
                public void run() {
695
                    addMenu(action, text);
696
                }
697
            });
698
            return;
699
        }
700
        JMenu menuPadre = createMenuAncestors(text);
701
        JMenuItem nuevoMenu = createJMenuItem(action, text);
702
        nuevoMenu.addMouseListener(tooltipListener);
703
        menuPadre.add(nuevoMenu);
704
        menuPadre.invalidate();
705
        Class<? extends IExtension> classExtension = action.getExtension().getClass();
706
        addControl(nuevoMenu);
707
    }
708

    
709
    /**
710
     * Dado lista de nombres de menu, encuentra el menu
711
     *
712
     * @param nombres
713
     * @param padre
714
     * @return
715
     */
716
    private javax.swing.JMenuItem getMenu(List nombres, MenuElement parent) {
717
        if ( parent instanceof javax.swing.JMenu ) {
718
            javax.swing.JMenu parentItem = (javax.swing.JMenu) parent;
719

    
720
            for ( int i = 0; i < parentItem.getMenuComponentCount(); i++ ) {
721

    
722
                String item_name = parentItem.getMenuComponent(i).getName();
723
                if ( ((item_name != null) && (item_name.compareTo((String) nombres.get(0)) == 0))
724
                        || /*
725
                         * We also accept "leaf menus" with no name
726
                         * (Project manager, View-1, View-2, etc)
727
                         */ lastMenuItemWithoutName(parentItem.getMenuComponent(i), nombres) ) {
728

    
729
                    nombres.remove(0);
730
                    if ( nombres.isEmpty() ) {
731
                        if ( parentItem.getMenuComponent(i) instanceof javax.swing.JMenuItem ) {
732
                            return (javax.swing.JMenuItem) parentItem
733
                                    .getMenuComponent(i);
734
                        } else {
735
                            logger.error(PluginServices.getText(this,
736
                                    "Menu_type_not_supported_")
737
                                    + " "
738
                                    + parentItem.getMenuComponent(i).getClass()
739
                                    .getName());
740
                            return null;
741
                        }
742
                    } else {
743
                        return getMenu(nombres,
744
                                (MenuElement) parentItem.getMenuComponent(i));
745
                    }
746
                }
747
            }
748
        } else if ( parent instanceof JMenuBar ) {
749
            javax.swing.JMenuBar parentItem = (javax.swing.JMenuBar) parent;
750

    
751
            for ( int i = 0; i < parentItem.getMenuCount(); i++ ) {
752
                if ( (parentItem.getMenu(i).getName() != null // not a
753
                        // JToolBar.Separator
754
                        )
755
                        && (parentItem.getMenu(i).getName()
756
                        .compareTo((String) nombres.get(0)) == 0) ) {
757
                    nombres.remove(0);
758
                    if ( nombres.isEmpty() ) {
759
                        if ( parentItem.getMenu(i) instanceof javax.swing.JMenuItem ) {
760
                            return parentItem.getMenu(i);
761
                        } else {
762
                            logger.error(PluginServices.getText(this,
763
                                    "Menu_type_not_supported_")
764
                                    + " "
765
                                    + parentItem.getMenu(i).getClass()
766
                                    .getName());
767
                            return null;
768
                        }
769
                    } else {
770
                        return getMenu(nombres, parentItem.getMenu(i));
771
                    }
772
                }
773
            }
774
        } else {
775
            logger.error(PluginServices.getText(this,
776
                    "Menu_type_not_supported_")
777
                    + " "
778
                    + parent.getClass().getName() + " " + parent.toString());
779
        }
780
        return null;
781
    }
782

    
783
    /**
784
     * @param menuComponent
785
     * @param nombres
786
     * @return
787
     */
788
    private boolean lastMenuItemWithoutName(Component mc, List names) {
789

    
790
        /*
791
         * names must have 1 string
792
         */
793
        if ( names == null || names.size() != 1 ) {
794
            return false;
795
        }
796
        if ( !(mc instanceof JMenuItem) ) {
797
            return false;
798
        }
799
        JMenuItem jmi = (JMenuItem) mc;
800
        if ( jmi.getName() != null ) {
801
            /*
802
             * Name must be null, so this is a menu leaf
803
             */
804
            return false;
805
        }
806
        if ( jmi.getText() == null ) {
807
            return false;
808
        }
809
        return jmi.getText().compareTo((String) names.get(0)) == 0;
810
    }
811

    
812
    private class JMenuTraslatable extends JMenu implements TranslatableButton {
813

    
814
        private TranslatableButtonHelper i18nHelper = new TranslatableButtonHelper();
815

    
816
        public JMenuTraslatable(String text) {
817
            super(text);
818
        }
819

    
820
        public void setTextKey(String key) {
821
            this.i18nHelper.setText(key);
822
        }
823

    
824
        public void setToolTipKey(String key) {
825
            this.i18nHelper.setTooltip(key);
826
        }
827

    
828
        public void translate() {
829
            if ( this.i18nHelper.needTranslation() ) {
830
                this.i18nHelper.translate();
831
                this.setText(this.i18nHelper.getText());
832
            }
833
        }
834

    
835
    }
836

    
837
    /**
838
     * Crea la estructura de menus recursivamente. Por ejemplo, si se le pasa
839
     * en el par�metro nombres el array {"Search", "References", "Workspace"}
840
     * crear� un men� Search, un submen� del anterior que se llamar�
841
     * References y debajo de �ste �ltimo otro menu llamado Workspace
842
     *
843
     * @param nombres
844
     * Array con los nombres de los men�s que se quieren crear
845
     * @param padre
846
     * Menu padre de los men�s creados. Es �til porque es un
847
     * algoritmo recursivo
848
     *
849
     * @return Devuelve el men� creado. Al final de toda la recursividad,
850
     * devolver� el men� de m�s abajo en la jerarqu�a
851
     *
852
     * @throws RuntimeException
853
     */
854
    private JMenu createMenus(ArrayList nombres, JMenu padre) {
855
        if ( !SwingUtilities.isEventDispatchThread() ) {
856
            logger.warn("Este metodo requiere que se este ejecutando en el hilo de eventos de AWT.");
857
            throw new RuntimeException("No Event Dispatch Thread");
858
        }
859
        I18nManager i18nManager = ToolsLocator.getI18nManager();
860

    
861
        // si no quedan nombres de menu por crear se vuelve: caso base
862
        if ( nombres.isEmpty() ) {
863
            return padre;
864
        }
865

    
866
        // Se busca el menu por si ya existiera para no crearlo otra vez
867
        JMenu buscado = null;
868

    
869
        for ( int i = 0; i < padre.getMenuComponentCount(); i++ ) {
870
            try {
871
                JMenu hijo = (JMenu) padre.getMenuComponent(i);
872

    
873
                if ( hijo.getName().compareTo((String) nombres.get(0)) == 0 ) {
874
                    buscado = hijo;
875
                }
876
            } catch (ClassCastException e) {
877
                /*
878
                 * Se ha encontrado un elemento hoja del arbol de men�es
879
                 */
880
            }
881
        }
882

    
883
        if ( buscado != null ) {
884
            // Si lo hemos encontrado creamos el resto
885
            nombres.remove(0);
886

    
887
            return createMenus(nombres, buscado);
888
        } else {
889
            // Si no lo hemos encontrado se crea el menu, se a�ade al padre
890
            // y se crea el resto
891
            String nombre = (String) nombres.get(0);
892
            JMenuTraslatable menuPadre = new JMenuTraslatable(i18nManager.getTranslation(nombre));
893
            menuPadre.setTextKey(nombre);
894
            menuPadre.setName(nombre);
895
            addControl(menuPadre);
896
            padre.add(menuPadre);
897

    
898
            nombres.remove(0);
899

    
900
            return createMenus(nombres, menuPadre);
901
        }
902
    }
903

    
904
    /**
905
     * M�todo invocado en respuesta a ciertos eventos de la interfaz que
906
     * pueden
907
     * ocultar botones de las barras de herramientas y que redimensiona �sta
908
     * de manera conveniente para que no se oculte ninguno
909
     */
910
    private void ajustarToolBar() {
911
        int margen = 8;
912
        int numFilas = 1;
913
        double acum = margen;
914

    
915
        int toolHeight = 0;
916

    
917
        for ( int i = 0; i < toolBars.getComponentCount(); i++ ) {
918
            Component c = toolBars.getComponent(i);
919

    
920
            if ( !c.isVisible() ) {
921
                continue;
922
            }
923

    
924
            double width = c.getPreferredSize().getWidth();
925
            acum = acum + width;
926

    
927
            if ( acum > this.getWidth() ) {
928
                numFilas++;
929
                acum = width + margen;
930
            }
931

    
932
            if ( c.getPreferredSize().getHeight() > toolHeight ) {
933
                toolHeight = c.getPreferredSize().height;
934
            }
935
        }
936

    
937
        toolBars.setPreferredSize(new Dimension(this.getWidth(),
938
                (numFilas * toolHeight)));
939

    
940
        toolBars.updateUI();
941
    }
942

    
943
    public void setClassesExtensions(Map<Class<? extends IExtension>, ExtensionDecorator> classesExtensions) {
944
        // Ya no es necesario que se mantenga el Map con las extensiones.
945

    
946
//            Map<Class<? extends IExtension>, ExtensionDecorator> extensions = new HashMap<Class<? extends IExtension>, ExtensionDecorator>();
947
//            for ( Entry<Class<? extends IExtension>, ExtensionDecorator>  entry: classesExtensions.entrySet()) {
948
//                        if( ! (entry.getValue().getExtension() instanceof LibraryExtension) ) {
949
//                                extensions.put(entry.getKey(), entry.getValue());
950
//                        }
951
//                }
952
//        this.classesExtensions = extensions;
953
    }
954

    
955
    /**
956
     * Metodo de callback invocado cuando se selecciona un menu o un boton
957
     * de
958
     * la barra de herramientas. Se busca la extensi�n asociada y se ejecuta
959
     *
960
     * @param e
961
     * Evento producido
962
     */
963
    public void actionPerformed(ActionEvent e) {
964

    
965
        String actionName = "(unknow)";
966
        try {
967
            JComponent control = (JComponent) e.getSource();
968
            actionName = control.getName();
969

    
970
            ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
971
            ActionInfo action = actionManager.getAction(control.getName());
972
            Object args = null;
973
            if ( control instanceof IControl ) {
974
                args = ((IControl) control).getValue();
975
            }
976
            if ( args == null ) {
977
                action.execute();
978
            } else {
979
                action.execute(args);
980
            }
981
            String actionCommand = e.getActionCommand();
982
            try {
983
                JToolBarToggleButton toggle = (JToolBarToggleButton) control;
984
                ToggleButtonModel model = (ToggleButtonModel) toggle.getModel();
985
                selectedTool.put(model.getGroupName(), actionCommand);
986
            } catch (ClassCastException ex) {
987
            } catch (NullPointerException ex) {
988
            }
989

    
990
        } catch (Throwable ex) {
991
            logger.error("Can't perform action '" + actionName + "'.", ex);
992
        }
993

    
994
        enableControls();
995
        showMemory();
996
    }
997

    
998
    private String getName(String name, PluginClassLoader loader) {
999
        if ( name.indexOf('.') == -1 ) {
1000
            return loader.getPluginName() + "." + name;
1001
        } else {
1002
            return name;
1003
        }
1004
    }
1005

    
1006
    public void addPopupMenu(PluginClassLoader loader, PopupMenu menu) {
1007
        if ( !SwingUtilities.isEventDispatchThread() ) {
1008
            throw new RuntimeException("No Event Dispatch Thread");
1009
        }
1010

    
1011
        String name = getName(menu.getName(), loader);
1012

    
1013
        // Se crea el control popupmenu
1014
        JPopUpMenu popupMenu = (JPopUpMenu) popupMap.get(name);
1015

    
1016
        if ( popupMenu == null ) {
1017
            popupMenu = new JPopUpMenu(menu.getName());
1018
            popupMap.put(name, popupMenu);
1019
        }
1020

    
1021
        Menu[] menues = menu.getMenu();
1022
        for ( int i = 0; i < menues.length; i++ ) {
1023
            JMenuItem nuevoMenu = createJMenuItem(loader, menues[i]);
1024
            popupMenu.add(nuevoMenu);
1025
        }
1026
    }
1027

    
1028
    private JMenuItem createJMenuItem(PluginClassLoader loader, Menu menu) {
1029
        JMenuItem nuevoMenu = null;
1030

    
1031
        I18nManager i18nManager = ToolsLocator.getI18nManager();
1032

    
1033
        String text = menu.getText();
1034
        int n = text.lastIndexOf('/');
1035
        if ( n >= 0 ) {
1036
            text = text.substring(n + 1);
1037
        }
1038
        String translatedText = i18nManager.getTranslation(text);
1039

    
1040
        IconTheme iconTheme = ToolsSwingLocator.getIconThemeManager().getCurrent();
1041
        if ( menu.getIcon() != null ) {
1042
            if ( iconTheme.exists(menu.getIcon()) ) {
1043
                ImageIcon image = iconTheme.get(menu.getIcon());
1044
                nuevoMenu = new JMenuItem(translatedText, image);
1045
            } else {
1046
                nuevoMenu = new JMenuItem(translatedText);
1047
                logger.info("menu icon '" + menu.getIcon() + "' not exists.");
1048
            }
1049
        } else {
1050
            nuevoMenu = new JMenuItem(translatedText);
1051
        }
1052
        nuevoMenu.setTextKey(text);
1053
        nuevoMenu.setName(menu.getName());
1054

    
1055
        if ( menu.getKey() != null ) {
1056
            nuevoMenu.setAccelerator(KeyMapping.getKeyStroke(menu.getKey()));
1057
        }
1058

    
1059
        nuevoMenu.setActionCommand(menu.getActionCommand());
1060

    
1061
        if ( menu.getTooltip() != null ) {
1062
            nuevoMenu.setToolTip(i18nManager.getTranslation(menu.getTooltip()));
1063
            nuevoMenu.setToolTipKey(menu.getTooltip());
1064
        }
1065

    
1066
        if ( menu.getEnableText() != null ) {
1067
            nuevoMenu.setEnableText(i18nManager.getTranslation(menu.getEnableText()));
1068
        }
1069

    
1070
        nuevoMenu.setEnabled(true);
1071
        nuevoMenu.setVisible(true);
1072

    
1073
        if ( menu.getName() != null ) {
1074
            ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1075
            final ActionInfo actionInfo = actionManager.getAction(menu.getName());
1076
            if ( actionInfo != null ) {
1077
                nuevoMenu.addActionListener(actionInfo);
1078
            }
1079
        }
1080
        return nuevoMenu;
1081
    }
1082

    
1083
    private JMenuItem createJMenuItem(ActionInfo action, String text) {
1084
        I18nManager i18nManager = ToolsLocator.getI18nManager();
1085
        String label = null;
1086

    
1087
        if ( text == null ) {
1088
            label = action.getLabel();
1089
        } else if ( text.contains("/") ) {
1090
            String[] ss = text.split("/");
1091
            label = ss[ss.length - 1];
1092
        } else {
1093
            label = text;
1094
        }
1095
        JMenuItem nuevoMenu = new JMenuItem();
1096
        nuevoMenu.setText(i18nManager.getTranslation(label));
1097
        nuevoMenu.setName(action.getName());
1098
        if ( action.getIconName() != null ) {
1099
            nuevoMenu.setIcon(action.getIcon());
1100
        }
1101
        KeyStroke key = action.getKeyStroke();
1102
        if ( key != null ) {
1103
            nuevoMenu.setAccelerator(key);
1104
        }
1105
        nuevoMenu.setActionCommand(action.getCommand());
1106
        if ( action.getTooltip() != null ) {
1107
            nuevoMenu.setToolTip(i18nManager.getTranslation(action.getTooltip()));
1108
        }
1109
        nuevoMenu.setEnabled(true);
1110
        nuevoMenu.setVisible(true);
1111
        nuevoMenu.addActionListener(action);
1112
        return nuevoMenu;
1113
    }
1114

    
1115
    /**
1116
     * Muestra u oculta el menu de nombre 'name'
1117
     *
1118
     * @param name
1119
     * Nombre del menu que se quiere mostrar
1120
     * @param x
1121
     * Evento de raton
1122
     * @param y
1123
     * @param c
1124
     */
1125
    private void showPopupMenu(String name, int x, int y, Component c) {
1126
        JPopupMenu menu = (JPopupMenu) popupMap.get(name);
1127

    
1128
        if ( menu != null ) {
1129
            menu.show(c, x, y);
1130
        }
1131
    }
1132

    
1133
    public void removePopupMenuListener(String name, ActionListener listener) {
1134
        JPopupMenu menu = (JPopupMenu) popupMap.get(name);
1135

    
1136
        if ( menu != null ) {
1137
            Component[] jmenuitems = menu.getComponents();
1138

    
1139
            for ( int i = 0; i < jmenuitems.length; i++ ) {
1140
                if ( jmenuitems[i] instanceof JMenuItem ) {
1141
                    ((JMenuItem) jmenuitems[i]).removeActionListener(listener);
1142
                }
1143
            }
1144
        }
1145
    }
1146

    
1147
    public void addPopupMenuListener(String popupName, Component c,
1148
            ActionListener listener, PluginClassLoader loader) {
1149
        final String name = getName(popupName, loader);
1150

    
1151
        JPopupMenu menu = (JPopupMenu) popupMap.get(name);
1152

    
1153
        if ( menu != null ) {
1154
            Component[] jmenuitems = menu.getComponents();
1155

    
1156
            for ( int i = 0; i < jmenuitems.length; i++ ) {
1157
                if ( jmenuitems[i] instanceof JMenuItem ) {
1158
                    ((JMenuItem) jmenuitems[i]).addActionListener(listener);
1159
                }
1160
            }
1161
        }
1162

    
1163
        c.addMouseListener(new MouseAdapter() {
1164

    
1165
            @Override
1166
            public void mousePressed(MouseEvent e) {
1167
                if ( e.isPopupTrigger() ) {
1168
                    showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
1169
                }
1170
            }
1171

    
1172
            @Override
1173
            public void mouseReleased(MouseEvent e) {
1174
                if ( e.isPopupTrigger() ) {
1175
                    showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
1176
                }
1177
            }
1178
        });
1179
    }
1180

    
1181
    /**
1182
     * Loop on the controls to enable/disable and show/hide them, according to
1183
     * its associated action (ActionInfo)
1184
     *
1185
     * @throws RuntimeException
1186
     */
1187
    public void enableControls() {
1188
        if ( !SwingUtilities.isEventDispatchThread() ) {
1189
            SwingUtilities.invokeLater(new Runnable() {
1190
                public void run() {
1191
                    enableControls();
1192
                }
1193
            });
1194
            return;
1195
        }
1196

    
1197
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1198
        ActionInfoStatusCache cache = actionManager.createActionStatusCache();
1199

    
1200
        // Enable or disable controls, according to its associated extensions
1201
        Iterator<JComponent> e = controlsIterator();
1202

    
1203
        while ( e.hasNext() ) {
1204
            JComponent control = (JComponent) e.next();
1205
            String actionName = control.getName();
1206
            ActionInfo action = actionManager.getAction(actionName);
1207
            try {
1208
                boolean enabled = false;
1209
                boolean visible = false;
1210

    
1211
                if ( action == null ) {
1212
                    if( control instanceof DropDownButton ) {
1213
                        DropDownButton dropDownButton = (DropDownButton)control;
1214
                        visible = !dropDownButton.isAllHiden();
1215
                        enabled = !dropDownButton.isAllDisabled();
1216
                    } else if( control instanceof JMenuTraslatable ) {
1217
                        enabled = true;
1218
                        visible = true;
1219
                    } else {
1220
                        IExtension extension = this.control2extensions.get(control);
1221
                        if( extension!=null ) {
1222
                            enabled = extension.isEnabled();
1223
                            visible = extension.isVisible();
1224
                        } else {
1225
                            logger.warn("Can't enable/show control '"+control.getClass().getName()+"/"+control.getName()+".");
1226
                            enabled = true;
1227
                            visible = true;
1228
                        }
1229
                    }
1230
                } else {
1231
                    enabled = false;
1232
                    visible = cache.isVisible(action);
1233
                    if ( visible ) {
1234
                        enabled = cache.isEnabled(action);
1235
                    }
1236
                }
1237
                control.setEnabled(enabled);
1238
                control.setVisible(visible);
1239
            } catch (Throwable ex) {
1240
                // Catch exceptins and errors (class not found)
1241
                logger.info("Can't enable/show control '" + actionName + "'.", ex);
1242
                this.message("Can't enable/show control '" + actionName + "'.", JOptionPane.ERROR_MESSAGE);
1243
                try {
1244
                    control.setEnabled(false);
1245
                    control.setVisible(false);
1246
                } catch (Exception ex2) {
1247
                    // Ignore errors
1248
                }
1249
            }
1250
        }
1251

    
1252
        // Loop in the menus to hide the menus that don't have visible children
1253
        for ( int i = 0; i < menuBar.getMenuCount(); i++ ) {
1254
            MenuElement menu = menuBar.getMenu(i);
1255
            hideMenus(menu);
1256
            if ( menu instanceof JMenu ) {
1257
                // hide (ugly) redundant separators and assign keyboard
1258
                // mnemonics
1259
                Component[] comps = ((JMenu) menu).getMenuComponents();
1260
                // mnemonics have to be unique for each top-level menu
1261
                char mnemonics[] = new char[comps.length];
1262
                if ( comps.length > 0 ) {
1263
                    // Set keyboard mnemonic for this top-level entry
1264
                    String text = ((JMenu) menu).getText();
1265
                    char mnemonic = getMnemonic(text, mnemonics);
1266
                    if ( ' ' != mnemonic ) {
1267
                        ((JMenu) menu).setMnemonic(mnemonic);
1268
                        mnemonics[0] = mnemonic;
1269
                    }
1270
                }
1271
                // now go through all entries in this menu, hid
1272
                // separators if necessary and assing remaining mnemonics
1273
                hideSeparatorsAndMakeMnemonics(menu, mnemonics);
1274
            }
1275
        }
1276

    
1277
        // hide the toolbars that don't contain any visible tool
1278
        Iterator it = toolBarMap.values().iterator();
1279

    
1280
        while ( it.hasNext() ) {
1281
            JComponent t = (JComponent) it.next();
1282
            boolean todosOcultos = true;
1283

    
1284
            for ( int i = 0; i < t.getComponentCount(); i++ ) {
1285
                if ( !(t.getComponent(i) instanceof JSeparator) // separators
1286
                        // don't matter
1287
                        && t.getComponent(i).isVisible() ) {
1288
                    todosOcultos = false;
1289
                }
1290
            }
1291

    
1292
            if ( todosOcultos ) {
1293
                t.setVisible(false);
1294
            } else {
1295
                if ( t instanceof SelectableToolBar ) {
1296
                    t.setVisible(((SelectableToolBar) t).getAndamiVisibility());
1297
                } else {
1298
                    t.setVisible(true);
1299
                }
1300
            }
1301
        }
1302

    
1303
        if ( mdiManager != null ) {
1304
            JPanel f = (JPanel) mdiManager.getActiveWindow();
1305

    
1306
            if ( f != null ) {
1307
                if ( lastLabelClass != f.getClass() ) {
1308
                    lastLabelClass = f.getClass();
1309

    
1310
                    Label[] lbls = (Label[]) classLabels.get(lastLabelClass);
1311

    
1312
                    if ( lbls != null ) {
1313
                        bEstado.setLabelSet(lbls);
1314
                    }
1315
                }
1316
            }
1317
        }
1318

    
1319
        ajustarToolBar();
1320

    
1321
        showMemory();
1322
    }
1323

    
1324
    public synchronized void refreshControls() {
1325
        if ( !SwingUtilities.isEventDispatchThread() ) {
1326
            SwingUtilities.invokeLater(new Runnable() {
1327
                public void run() {
1328
                    refreshControls();
1329
                }
1330
            });
1331
            return;
1332
        }
1333

    
1334
        if(refreshingControls){
1335
            return;
1336
        }
1337
        try {
1338
        refreshingControls = true;
1339
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1340
        ActionInfoStatusCache cache = actionManager.createActionStatusCache();
1341
        IconTheme icontheme = ToolsSwingLocator.getIconThemeManager().getCurrent();
1342

    
1343
        Iterator e = controlsIterator();
1344

    
1345
        while ( e.hasNext() ) {
1346
            JComponent control = (JComponent) e.next();
1347
            if ( control instanceof TranslatableButton ) {
1348
                ((TranslatableButton) control).translate();
1349
            }
1350
            String actionlName = control.getName();
1351
            ActionInfo action = actionManager.getAction(actionlName);
1352
            if ( action != null ) {
1353
                if ( control instanceof AbstractButton ) {
1354
                    AbstractButton button = (AbstractButton) control;
1355
                    if ( control instanceof javax.swing.JMenuItem ) {
1356
                        if ( action.getIconName() != null && action.getIconName().length() > 0 ) {
1357
                            if ( icontheme.exists(action.getIconName()) ) {
1358
                                button.setIcon(action.getIcon());
1359
                            }
1360
                        }
1361
                    } else {
1362
                        button.setIcon(action.getIcon());
1363
                    }
1364
                }
1365
            }
1366
        }
1367
        enableControls();
1368
        } finally {
1369
            refreshingControls = false;
1370
        }
1371
    }
1372

    
1373
    public void message(String msg, int messageTyoe) {
1374
        this.getStatusBar().message(msg, messageTyoe);
1375
    }
1376

    
1377
    /**
1378
     * Establece la visibilidad de un menu y todos sus descendientes en la
1379
     * jerarquia teniendo en cuenta la visibilidad de todos los submenus.
1380
     *
1381
     * @param menu
1382
     * Menu que se quiere visualizar
1383
     *
1384
     * @return Devuelve true si el menu es visible y false en caso contrario
1385
     */
1386
    private boolean hideMenus(MenuElement menu) {
1387
        MenuElement[] submenus = menu.getSubElements();
1388

    
1389
        // Si no tiene hijos se devuelve su visibilidad
1390
        if ( submenus.length == 0 ) {
1391
            return menu.getComponent().isVisible();
1392
        }
1393

    
1394
        /*
1395
         * Si tiene hijos se devuelve true si alg�no de ellos es visible,
1396
         * pero se itera por todos ellos
1397
         */
1398
        boolean visible = false;
1399

    
1400
        for ( int i = 0; i < submenus.length; i++ ) {
1401
            if ( hideMenus(submenus[i]) ) {
1402
                if ( !(menu instanceof JPopupMenu) ) {
1403
                    menu.getComponent().setVisible(true);
1404
                }
1405

    
1406
                visible = true;
1407
            }
1408
        }
1409

    
1410
        if ( visible ) {
1411
            return true;
1412
        }
1413

    
1414
        menu.getComponent().setVisible(false);
1415

    
1416
        return false;
1417
    }
1418

    
1419
    /**
1420
     *
1421
     * Recurse through all menu elements and make sure there are no
1422
     * redundant separators.
1423
     * This method will make sure that a separator only becomes visible
1424
     * if at least one visible non-separator menu entry preceeded it.
1425
     *
1426
     *
1427
     */
1428
    private void hideSeparatorsAndMakeMnemonics(MenuElement menu,
1429
            char[] mnemonics) {
1430
        // flag that indicates whether a separator is to be displayed or not
1431
        boolean allowSeparator;
1432

    
1433
        allowSeparator = false; // separator not allowed as very first menu item
1434
        Component[] comps = ((JMenu) menu).getMenuComponents();
1435
        if ( comps.length < 1 ) {
1436
            // zero-length menu: skip
1437
            return;
1438
        }
1439

    
1440
        for ( int i = 0; i < comps.length; i++ ) {
1441
            if ( comps[i] instanceof JSeparator ) {
1442
                // got a separator: display only if allowed at this position
1443
                if ( allowSeparator == true ) {
1444
                    // look at all successive menu entries to make sure that at
1445
                    // least one
1446
                    // is visible and not a separator (otherwise, this separator
1447
                    // would
1448
                    // be the last visible item in this menu) -- we don't want
1449
                    // that
1450
                    comps[i].setVisible(false);
1451
                    for ( int j = i; j < comps.length; j++ ) {
1452
                        if ( !(comps[j] instanceof JSeparator) ) {
1453
                            if ( comps[j].isVisible() ) {
1454
                                comps[i].setVisible(true); // display separator!
1455
                                break;
1456
                            }
1457
                        }
1458
                    }
1459
                } else {
1460
                    comps[i].setVisible(false);
1461
                }
1462
                allowSeparator = false; // separator is not allowed right after
1463
                // another separator
1464
            } else {
1465
                if ( comps[i] instanceof JMenu ) { // got a submenu: recurse
1466
                    // through it
1467
                    // get number of submenu components
1468
                    Component[] scomps = ((JMenu) comps[i]).getMenuComponents();
1469
                    // make a new, fresh array to hold unique mnemonics for this
1470
                    // submenu
1471
                    char[] smnemonics = new char[scomps.length];
1472
                    hideSeparatorsAndMakeMnemonics(((MenuElement) comps[i]),
1473
                            smnemonics);
1474
                    if ( comps[i].isVisible() ) {
1475
                        allowSeparator = true; // separators are OK after
1476
                        // visible submenus
1477
                        // Set keyboard mnemonic for this submenu
1478
                        String text = ((JMenu) comps[i]).getText();
1479
                        char mnemonic = getMnemonic(text, mnemonics);
1480
                        if ( ' ' != mnemonic ) {
1481
                            ((JMenu) comps[i]).setMnemonic(mnemonic);
1482
                            mnemonics[i] = mnemonic;
1483
                        }
1484
                    }
1485
                } else {
1486
                    if ( comps[i].isVisible() ) {
1487
                        if ( comps[i] instanceof JMenuItem ) {
1488
                            // Set keyboard mnemonic for this menu item
1489
                            String text = ((JMenuItem) comps[i]).getText();
1490
                            char mnemonic = getMnemonic(text, mnemonics);
1491
                            if ( ' ' != mnemonic ) {
1492
                                ((JMenuItem) comps[i]).setMnemonic(mnemonic);
1493
                                mnemonics[i] = mnemonic;
1494
                            }
1495
                        }
1496
                        allowSeparator = true; // separators are OK after
1497
                        // regular, visible entries
1498
                    }
1499
                }
1500
            }
1501
        }
1502
    }
1503

    
1504
    /**
1505
     * Helper functios for assigning a unique mnemomic char from
1506
     * a pool of unassigned onces, stored in the array "mnemomnics"
1507
     */
1508
    private char getMnemonic(String text, char[] mnemonics) {
1509
        if( text==null ) {
1510
            return ' ';
1511
        }
1512
        Vector words = new Vector();
1513
        StringTokenizer t = new StringTokenizer(text);
1514
        int maxsize = 0;
1515

    
1516
        while ( t.hasMoreTokens() ) {
1517
            String word = t.nextToken();
1518
            if ( word.length() > maxsize ) {
1519
                maxsize = word.length();
1520
            }
1521
            words.addElement(word);
1522
        }
1523
        words.trimToSize();
1524

    
1525
        for ( int i = 0; i < maxsize; ++i ) {
1526
            char mnemonic = getMnemonic(words, mnemonics, i);
1527
            if ( ' ' != mnemonic ) {
1528
                return mnemonic;
1529
            }
1530
        }
1531

    
1532
        return ' ';
1533
    }
1534

    
1535
    private char getMnemonic(Vector words, char[] mnemonics, int index) {
1536
        int numwords = words.size();
1537

    
1538
        for ( int i = 0; i < numwords; ++i ) {
1539
            String word = (String) words.elementAt(i);
1540
            if ( index >= word.length() ) {
1541
                continue;
1542
            }
1543

    
1544
            char c = word.charAt(index);
1545
            if ( !isMnemonicExists(c, mnemonics) ) {
1546
                /* pick only valid chars */
1547
                if ( (c != ':') && (c != '.') && (c != ',') && (c != ';')
1548
                        && (c != '-') && (c != '+') && (c != '/') && (c != '\\')
1549
                        && (c != '\'') && (c != '\"') && (c != ' ') && (c != '=')
1550
                        && (c != '(') && (c != ')') && (c != '[') && (c != ']')
1551
                        && (c != '{') && (c != '}') && (c != '$') && (c != '*')
1552
                        && (c != '&') && (c != '%') && (c != '!') && (c != '?')
1553
                        && (c != '#') && (c != '~') && (c != '_') ) {
1554
                    return c;
1555
                }
1556
            }
1557
        }
1558
        return ' ';
1559
    }
1560

    
1561
    private boolean isMnemonicExists(char c, char[] mnemonics) {
1562
        int num = mnemonics.length;
1563
        for ( int i = 0; i < num; ++i ) {
1564
            if ( mnemonics[i] == c ) {
1565
                return true;
1566
            }
1567
        }
1568
        return false;
1569
    }
1570

    
1571
    /**
1572
     * Muestra la memoria consumida por el programa
1573
     */
1574
    private void showMemory() {
1575
        Runtime r = Runtime.getRuntime();
1576
        long mem = r.totalMemory() - r.freeMemory();
1577
        logger.debug(PluginServices.getText(this, "memory_usage") + " " + mem
1578
                / 1024 + " KB");
1579
    }
1580

    
1581
    public MDIManager getMDIManager() {
1582
        return mdiManager;
1583
    }
1584

    
1585
    public NewStatusBar getStatusBar() {
1586
        return bEstado;
1587
    }
1588

    
1589
    /**
1590
     * You can use this function to select the appropiate
1591
     * tool inside the toolbars
1592
     */
1593
    public void setSelectedTool(String actionCommand) {
1594
        setSelectedTool(defaultGroup, actionCommand);
1595
    }
1596

    
1597
    /**
1598
     * You can use this function to select the appropiate
1599
     * tool inside the toolbars
1600
     */
1601
    public void setSelectedTool(String groupName, String actionCommand) {
1602
        ButtonGroup group = (ButtonGroup) buttonGroupMap.get(groupName);
1603
        if ( group == null ) {
1604
            return;
1605
        }
1606

    
1607
        Enumeration enumeration = group.getElements();
1608
        while ( enumeration.hasMoreElements() ) {
1609
            AbstractButton button = (AbstractButton) enumeration.nextElement();
1610
            if ( button.getActionCommand().equals(actionCommand) ) {
1611
                button.setSelected(true);
1612
            }
1613
        }
1614

    
1615
        selectedTool.put(groupName, actionCommand);
1616
    }
1617

    
1618
    /**
1619
     * You can use this function to select the appropiate
1620
     * tool inside the toolbars
1621
     */
1622
    public void setSelectedTools(Map selectedTools) {
1623
        selectedTool = selectedTools;
1624
        if ( selectedTools == null ) {
1625
            return;
1626
        }
1627
        Iterator groupNames = selectedTools.keySet().iterator();
1628
        while ( groupNames.hasNext() ) {
1629
            try {
1630
                String groupName = (String) groupNames.next();
1631
                ButtonGroup group = (ButtonGroup) buttonGroupMap.get(groupName);
1632
                Enumeration enumeration = group.getElements();
1633
                String actionCommand = (String) selectedTools.get(groupName);
1634
                if ( actionCommand == null ) {
1635
                    continue;
1636
                }
1637
                while ( enumeration.hasMoreElements() ) {
1638
                    AbstractButton button
1639
                            = (AbstractButton) enumeration.nextElement();
1640
                    if ( button.getActionCommand().equals(actionCommand) ) {
1641
                        button.setSelected(true);
1642
                    }
1643
                }
1644
            } catch (ClassCastException ex) {
1645
                logger
1646
                        .error("selectedTool should only contain pairs (String groupName, JToolBarToggleButton button)");
1647
            }
1648
        }
1649
    }
1650

    
1651
    /**
1652
     * DOCUMENT ME!
1653
     *
1654
     * @param clase
1655
     * @param label
1656
     */
1657
    public void setStatusBarLabels(Class<?> clase, Label[] label) {
1658
        classLabels.put(clase, label);
1659
    }
1660

    
1661
    public void removeStatusBarLabels(Class<?> clase) {
1662
        classLabels.remove(clase);
1663
    }
1664

    
1665
    public void addStatusBarControl(Class<?> extensionClass, IControl control) {
1666
        control.addActionListener(this);
1667
        bEstado.addControl(control.getName(), (Component) control);
1668
        if ( control instanceof JComponent ) {
1669
            addControl((JComponent) control);
1670
            PluginsManager pluginsManager = PluginsLocator.getManager();
1671
            IExtension extension = pluginsManager.getExtension((Class<? extends IExtension>) extensionClass);
1672
            this.control2extensions.put((JComponent)control, extension);
1673
        }
1674
    }
1675

    
1676
    public void addToolBarControl(Class<?> extensionClass, JToolBar control, String name) {
1677
        toolBars.add(control);
1678
        addControl(control);
1679

    
1680
        PluginsManager pluginsManager = PluginsLocator.getManager();
1681
        IExtension extension = pluginsManager.getExtension((Class<? extends IExtension>) extensionClass);
1682
        this.control2extensions.put(control, extension);
1683
    }
1684

    
1685
    public void removeStatusBarControl(String name) {
1686
        Component c = bEstado.removeControl(name);
1687
        if ( c instanceof JComponent ) {
1688
            removeControl((JComponent) c);
1689
        }
1690
    }
1691

    
1692
    public void removeMenu(Menu menu) {
1693
        JMenuItem delete = (JMenuItem) infoCodedMenus.get(menu);
1694

    
1695
        if ( delete == null ) {
1696
            throw new NoSuchElementException(menu.getText());
1697
        }
1698

    
1699
        delete.getParent().remove(delete);
1700
        infoCodedMenus.remove(menu);
1701
    }
1702

    
1703
    public void addMenu(Menu menu, ActionListener listener,
1704
            PluginClassLoader loader) {
1705
        JMenu menuPadre = createMenuAncestors(menu, loader);
1706

    
1707
        // Se registra y añaade el menu
1708
        JMenuItem nuevoMenu = createJMenuItem(loader, menu);
1709
        nuevoMenu.addMouseListener(tooltipListener);
1710
        if ( listener != null && menu.getName() != null && menu.getName().trim().length() > 0 ) {
1711
            ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1712
            final ActionInfo actionInfo = actionManager.getAction(menu.getName());
1713
            if ( actionInfo != null ) {
1714
                nuevoMenu.removeActionListener(actionInfo);
1715
            }
1716
            nuevoMenu.addActionListener(listener);
1717
        } else {
1718
            /*
1719
             * We also add action listener for menu with
1720
             * no name but with text:
1721
             *
1722
             * Window/Project manager
1723
             * Window/View - 1
1724
             * Window/View - 2
1725
             * etc
1726
             */
1727
            if ( listener != null && menu.getText() != null && menu.getText().trim().length() > 0 ) {
1728
                nuevoMenu.addActionListener(listener);
1729
            }
1730

    
1731
        }
1732
        menuPadre.add(nuevoMenu);
1733

    
1734
        infoCodedMenus.put(menu, nuevoMenu);
1735
    }
1736

    
1737
    public void changeMenuName(String[] menu, String newName,
1738
            PluginClassLoader loader) {
1739

    
1740
        ArrayList menuList = new ArrayList();
1741
        for ( int i = 0; i < menu.length; i++ ) {
1742
            menuList.add(menu[i]);
1743
        }
1744

    
1745
        javax.swing.JMenuItem newMenu = getMenu(menuList, menuBar);
1746
        if ( newMenu == null ) {
1747
            throw new NoSuchMenuException(menu[0]);
1748
        } else {
1749
            newMenu.setText(PluginServices.getText(this, newName));
1750
        }
1751
    }
1752

    
1753
    public void componentHidden(ComponentEvent arg0) {
1754
    }
1755

    
1756
    public void componentMoved(ComponentEvent arg0) {
1757
    }
1758

    
1759
    public void componentResized(ComponentEvent arg0) {
1760
        ajustarToolBar();
1761
    }
1762

    
1763
    public void componentShown(ComponentEvent arg0) {
1764
    }
1765

    
1766
    public void componentAdded(ContainerEvent arg0) {
1767
        ajustarToolBar();
1768
    }
1769

    
1770
    public void componentRemoved(ContainerEvent arg0) {
1771
        ajustarToolBar();
1772
    }
1773

    
1774
    public class TooltipListener extends MouseAdapter {
1775

    
1776
        @Override
1777
        public void mouseEntered(MouseEvent e) {
1778
            JComponent control = (JComponent) e.getSource();
1779
            EnableTextSupport ets = (EnableTextSupport) e.getSource();
1780

    
1781
            String texto = null;
1782
            texto = control.getToolTipText();
1783

    
1784
            if ( texto != null ) {
1785
                bEstado.setInfoTextTemporal(texto);
1786
            }
1787
        }
1788

    
1789
        @Override
1790
        public void mouseExited(MouseEvent arg0) {
1791
            bEstado.restaurarTexto();
1792
        }
1793

    
1794
        @Override
1795
        public void mousePressed(MouseEvent e) {
1796
            bEstado.restaurarTexto();
1797
        }
1798
    }
1799

    
1800
    public String getTitlePrefix() {
1801
        return titlePrefix;
1802
    }
1803

    
1804
    public void setTitlePrefix(String titlePrefix) {
1805
        this.titlePrefix = titlePrefix;
1806
    }
1807

    
1808
    public Map getSelectedTools() {
1809
        return selectedTool;
1810
    }
1811

    
1812
    public HashMap getInitialSelectedTools() {
1813
        return initialSelectedTools;
1814
    }
1815

    
1816
    /**
1817
     * Get a previously added JComponent by name.
1818
     * For example you can use it if you need to obtain a JToolBar to
1819
     * add some customized component.
1820
     *
1821
     * @param name
1822
     * @return the JComponent or null if none has been found
1823
     */
1824
    public JComponent getComponentByName(String name) {
1825
        Iterator e = controlsIterator();
1826

    
1827
        while ( e.hasNext() ) {
1828
            JComponent control = (JComponent) e.next();
1829
            String nameCtrl = control.getName();
1830
            if ( nameCtrl != null ) {
1831
                if ( nameCtrl.compareTo(name) == 0 ) {
1832
                    return control;
1833
                }
1834
            }
1835
        }
1836
        Iterator it = toolBarMap.values().iterator();
1837
        while ( it.hasNext() ) {
1838
            JComponent t = (JComponent) it.next();
1839
            String nameCtrl = t.getName();
1840
            if ( nameCtrl != null ) {
1841
                if ( nameCtrl.compareTo(name) == 0 ) {
1842
                    return t;
1843
                }
1844
            }
1845

    
1846
        }
1847

    
1848
        return null;
1849
    }
1850

    
1851
    public SelectableToolBar[] getToolbars() {
1852
        return (SelectableToolBar[]) toolBarMap.values().toArray(
1853
                new SelectableToolBar[0]);
1854
    }
1855

    
1856
    public boolean getToolbarVisibility(String name) {
1857
        JComponent component
1858
                = PluginServices.getMainFrame().getComponentByName(name);
1859
        if ( (component != null) && (component instanceof SelectableToolBar) ) {
1860
            SelectableToolBar toolBar = (SelectableToolBar) component;
1861
            return toolBar.getAndamiVisibility();
1862
        }
1863
        return false;
1864
    }
1865

    
1866
    public boolean setToolbarVisibility(String name, boolean visibility) {
1867
        JComponent component
1868
                = PluginServices.getMainFrame().getComponentByName(name);
1869
        if ( (component != null) && (component instanceof SelectableToolBar) ) {
1870
            SelectableToolBar toolBar = (SelectableToolBar) component;
1871
            boolean oldVisibility = toolBar.getAndamiVisibility();
1872
            toolBar.setAndamiVisibility(visibility);
1873
            enableControls();
1874
            return oldVisibility;
1875
        }
1876
        return false;
1877
    }
1878

    
1879
    public javax.swing.JMenuItem getMenuEntry(String[] menuPath) {
1880
        ArrayList menu = new ArrayList();
1881
        for ( int i = 0; i < menuPath.length; i++ ) {
1882
            menu.add(menuPath[i]);
1883
        }
1884
        return getMenu(menu, menuBar);
1885
    }
1886

    
1887
    public void messageDialog(String message, String title, int messageType) {
1888
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1889
        helper.messageDialog(message, title, messageType);
1890
    }
1891

    
1892
    public void messageDialog(String message, String[] messageArgs,
1893
            String title, int messageType) {
1894
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1895
        helper.messageDialog(message, messageArgs, title, messageType);
1896
    }
1897

    
1898
    public int confirmDialog(String message, String title, int optionType,
1899
            int messageType) {
1900
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1901
        return helper.confirmDialog(message, title, optionType, messageType);
1902
    }
1903

    
1904
    public String inputDialog(String message, String title, int messageType,
1905
            String initialValue) {
1906
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1907
        return helper.inputDialog(message, title, messageType, initialValue);
1908
    }
1909

    
1910
    public String inputDialog(String message, String title) {
1911
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1912
        return helper.inputDialog(message, title);
1913
    }
1914

    
1915
    public void showDialog(Component contents, String title) {
1916
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1917
        helper.showDialog(contents, title);
1918
    }
1919

    
1920
    public Component createComponent(Class<? extends Component> theClass,
1921
            Object... parameters) {
1922
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1923
        return helper.createComponentWithParams(theClass, parameters);
1924
    }
1925

    
1926
    public Component createComponentWithParams(
1927
            Class<? extends Component> theClass, Object[] parameters) {
1928
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1929
        return helper.createComponentWithParams(theClass, parameters);
1930
    }
1931

    
1932
    public File[] showChooserDialog(
1933
            final String title,
1934
            final int type, // SAVE_DIALOG / OPEN_DIALOG
1935
            final int selectionMode, //    JFileChooser.FILES_ONLY, JFileChooser.DIRECTORIES_ONLY, JFileChooser.FILES_AND_DIRECTORIES
1936
            final boolean multiselection,
1937
            final File initialPath,
1938
            final FileFilter filter,
1939
            final boolean fileHidingEnabled
1940
    ) {
1941
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1942
        return helper.showChooserDialog(title, type, selectionMode, multiselection, initialPath, filter, fileHidingEnabled);
1943
    }
1944

    
1945
    public File[] showOpenDirectoryDialog(String title, File initialPath) {
1946
        return showChooserDialog(title, JFileChooser.OPEN_DIALOG, JFileChooser.DIRECTORIES_ONLY, false, initialPath, null, false);
1947
    }
1948

    
1949
    public File[] showOpenFileDialog(String title, File initialPath) {
1950
        return showChooserDialog(title, JFileChooser.OPEN_DIALOG, JFileChooser.FILES_ONLY, false, initialPath, null, false);
1951
    }
1952

    
1953
    public File[] showSaveFileDialog(String title, File initialPath) {
1954
        return showChooserDialog(title, JFileChooser.SAVE_DIALOG, JFileChooser.FILES_ONLY, false, initialPath, null, false);
1955
    }
1956

    
1957
    private void addControl(JComponent control) {
1958
        controls.add(control);
1959
    }
1960

    
1961
    private void removeControl(JComponent control) {
1962
        controls.remove(control);
1963
    }
1964

    
1965
    private Iterator<JComponent> controlsIterator() {
1966
        return this.controls.iterator();
1967
    }
1968

    
1969
    @Override
1970
    public void setLocale(Locale locale) {
1971
        super.setLocale(locale); //To change body of generated methods, choose Tools | Templates.
1972
        MDIManager mdiManager = MDIManagerFactory.createManager();
1973
        mdiManager.setLocale(locale);
1974
        if ( this.controls != null && !this.controls.isEmpty() ) {
1975
            this.refreshControls();
1976
        }
1977
    }
1978

    
1979
}