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 @ 42969

History | View | Annotate | Download (68.9 KB)

1 40559 jjdelcerro
/**
2
 * gvSIG. Desktop Geographic Information System.
3 40435 jjdelcerro
 *
4 40559 jjdelcerro
 * Copyright (C) 2007-2013 gvSIG Association.
5 40435 jjdelcerro
 *
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 40559 jjdelcerro
 * as published by the Free Software Foundation; either version 3
9 40435 jjdelcerro
 * 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 41314 jjdelcerro
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 40435 jjdelcerro
 * 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 40559 jjdelcerro
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19 41314 jjdelcerro
 * MA 02110-1301, USA.
20 40435 jjdelcerro
 *
21 40559 jjdelcerro
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23 40435 jjdelcerro
 */
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 41080 jjdelcerro
import java.util.List;
47 41314 jjdelcerro
import java.util.Locale;
48 40435 jjdelcerro
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 41080 jjdelcerro
import javax.swing.KeyStroke;
67 40435 jjdelcerro
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 41334 jjdelcerro
import org.gvsig.andami.PluginsManager;
78 40435 jjdelcerro
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 41314 jjdelcerro
import org.gvsig.andami.ui.mdiFrame.TranslatableButtonHelper.TranslatableButton;
93 40435 jjdelcerro
import org.gvsig.andami.ui.mdiManager.MDIManager;
94
import org.gvsig.andami.ui.mdiManager.MDIManagerFactory;
95
import org.gvsig.gui.beans.controls.IControl;
96 41080 jjdelcerro
import org.gvsig.tools.ToolsLocator;
97
import org.gvsig.tools.i18n.I18nManager;
98 40435 jjdelcerro
import org.gvsig.tools.swing.api.ToolsSwingLocator;
99
import org.gvsig.tools.swing.icontheme.IconTheme;
100 41080 jjdelcerro
import org.slf4j.Logger;
101
import org.slf4j.LoggerFactory;
102 40435 jjdelcerro
103
/**
104
 * Main application window.
105 41314 jjdelcerro
 *
106
 * Use Launcher.getMDIFrame to get the instance of this class.
107
 *
108 40435 jjdelcerro
 * @version $Revision: 39484 $
109
 */
110
@SuppressWarnings("unchecked")
111
public class MDIFrame extends JFrame implements ComponentListener,
112 41314 jjdelcerro
        ContainerListener, ActionListener, MainFrame {
113 40435 jjdelcerro
114
    private static final long serialVersionUID = -2472484309160847654L;
115
116
    private static Logger logger = LoggerFactory.getLogger(MDIFrame.class);
117 41314 jjdelcerro
118
    private static MDIFrame instance = null;
119
120 40435 jjdelcerro
    private MDIManager mdiManager = MDIManagerFactory.createManager();
121
122 42165 fdiaz
    private boolean refreshingControls = false;
123
124 41314 jjdelcerro
    /**
125 42350 jjdelcerro
     * Elementos de la aplicaci�n
126 41314 jjdelcerro
     */
127 40435 jjdelcerro
    private JMenuBar menuBar = new JMenuBar();
128
129 41314 jjdelcerro
    /**
130
     * Panel which contains the toolbars
131
     */
132 40435 jjdelcerro
    private JPanel toolBars = new JPanel();
133
134 41314 jjdelcerro
    /**
135
     * Status bar
136
     */
137 40435 jjdelcerro
    private NewStatusBar bEstado = null;
138
139 41314 jjdelcerro
    /**
140
     * Asocia los nombres con las barras de herramientas
141
     */
142 40435 jjdelcerro
    private HashMap toolBarMap = new HashMap();
143
144 41314 jjdelcerro
    /**
145
     * Almacena los grupos de selectableTools
146
     */
147 40435 jjdelcerro
    private HashMap buttonGroupMap = new HashMap();
148
    /**
149
     * Stores the initially selected tools.
150
     * It contains pairs (String groupName, JToolBarToggleButton button)
151
     */
152
    private HashMap initialSelectedTools = new HashMap();
153
154
    /**
155
     * Stores the actionCommand of the selected tool, for each group.
156
     * It contains pairs (String groupName, JToolBarToggleButton button)
157
     */
158
    private Map selectedTool = null;
159
    // this should be the same value defined at plugin-config.xsd
160
    private String defaultGroup = "unico";
161
162 41314 jjdelcerro
    /**
163
     * Asocia los nombres con los popupMenus
164
     */
165 40435 jjdelcerro
    private HashMap popupMap = new HashMap();
166
167 41314 jjdelcerro
    /**
168
     * Asocia controles con la clase de la extension asociada
169
     */
170
    private List<JComponent> controls = new ArrayList<JComponent>();
171 40435 jjdelcerro
172
    /**
173 42350 jjdelcerro
     * Asocia la informaci�n sobre las etiquetas que van en la status bar con
174 40435 jjdelcerro
     * cada extension
175
     */
176
    private HashMap classLabels = new HashMap();
177
178
    // private HashMap classControls = new HashMap();
179 41314 jjdelcerro
    /**
180
     * ProgressListeners (ver interfaz com.iver.mdiApp.ui.ProgressListener)
181
     */
182 40435 jjdelcerro
    private ArrayList progressListeners = new ArrayList();
183
184 41314 jjdelcerro
    /**
185
     * Timer para invocar los enventos de la interfaz anterior
186
     */
187
    private Timer progressTimer = null;
188 40435 jjdelcerro
189 41314 jjdelcerro
    /**
190
     * Tabla hash que asocia las clases con las extensiones
191
     */
192
    // private Map classesExtensions = new HashMap<Class<? extends IExtension>, ExtensionDecorator>();
193
    /**
194 42350 jjdelcerro
     * �ltima clase que activ� etiquetas
195 41314 jjdelcerro
     */
196 40435 jjdelcerro
    private Class lastLabelClass;
197
198 41314 jjdelcerro
    /**
199
     * Instancia que pone los tooltip en la barra de estado
200
     */
201 40435 jjdelcerro
    private TooltipListener tooltipListener = new TooltipListener();
202
203 41314 jjdelcerro
    private HashMap infoCodedMenus = new HashMap();
204
205 40435 jjdelcerro
    private String titlePrefix;
206
207
    private static final String noIcon = "no-icon";
208
209 41334 jjdelcerro
    private Map<JComponent,IExtension> control2extensions = new HashMap<JComponent, IExtension>();
210 42161 fdiaz
211 41314 jjdelcerro
    private MDIFrame() {
212
213
    }
214
215 41511 jjdelcerro
    public static boolean isInitialized() {
216
        return instance!=null ;
217
    }
218 42161 fdiaz
219 41314 jjdelcerro
    public static MDIFrame getInstance() {
220
        if ( instance == null ) {
221
            instance = new MDIFrame();
222
        }
223
        return instance;
224
    }
225
226 40435 jjdelcerro
    /**
227
     * Makes some initialization tasks.
228 41314 jjdelcerro
     *
229 40435 jjdelcerro
     * @throws RuntimeException
230
     */
231
    public void init() {
232 41314 jjdelcerro
        JPopupMenu.setDefaultLightWeightPopupEnabled(false);
233
        if ( !SwingUtilities.isEventDispatchThread() ) {
234 40435 jjdelcerro
            throw new RuntimeException("Not Event Dispatch Thread");
235
        }
236
237 42350 jjdelcerro
        // Se añaden los listeners del JFrame
238 40435 jjdelcerro
        this.addWindowListener(new WindowAdapter() {
239
240
            @Override
241
            public void windowClosing(WindowEvent e) {
242
                Launcher.closeApplication();
243
            }
244
        });
245
        this.addComponentListener(this);
246
        this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
247
248
        // Se configura la barra de menu
249
        setJMenuBar(menuBar);
250
251
        // Se configura el layout del JFrame principal
252
        this.getContentPane().setLayout(new BorderLayout());
253
254
        /*
255 42350 jjdelcerro
         * Se configura y se añade el JPanel de las barras de
256 40435 jjdelcerro
         * herramientas
257
         */
258
        FlowLayout layout = new FlowLayout(FlowLayout.LEFT);
259
        layout.setHgap(0);
260
        layout.setVgap(0);
261
        toolBars.setLayout(layout);
262
        getContentPane().add(toolBars, BorderLayout.PAGE_START);
263
264 41314 jjdelcerro
        // Add the status bar of the application
265 40435 jjdelcerro
        bEstado = new NewStatusBar();
266
        bEstado.message(Messages.getString("StatusBar.Aplicacion_iniciada"), JOptionPane.INFORMATION_MESSAGE);
267
        getContentPane().add(bEstado, BorderLayout.SOUTH);
268
269
        this.toolBars.addContainerListener(this);
270
271
272
        /*
273
         * Setting default values. Persistence is read
274
         * afterwards
275
         */
276
        setSize(
277 41314 jjdelcerro
                MainFrame.MAIN_FRAME_SIZE_DEFAULT[0],
278
                MainFrame.MAIN_FRAME_SIZE_DEFAULT[1]);
279 40435 jjdelcerro
        setLocation(
280 41314 jjdelcerro
                MainFrame.MAIN_FRAME_POS_DEFAULT[0],
281
                MainFrame.MAIN_FRAME_POS_DEFAULT[1]);
282 40435 jjdelcerro
        setExtendedState(
283 41314 jjdelcerro
                MainFrame.MAIN_FRAME_EXT_STATE_DEFAULT);
284 40435 jjdelcerro
285
        mdiManager.init(this);
286
    }
287
288
    @Override
289
    public void setTitle(final String title) {
290 41314 jjdelcerro
        if ( !SwingUtilities.isEventDispatchThread() ) {
291 40435 jjdelcerro
            SwingUtilities.invokeLater(new Runnable() {
292
                public void run() {
293 41314 jjdelcerro
                    setTitle(title);
294 40435 jjdelcerro
                }
295
            });
296
            return;
297
        }
298
        super.setTitle(titlePrefix + " : " + title);
299
    }
300
301 42351 jjdelcerro
    private SelectableToolBar getToolBar(final String toolBarName) {
302
        SelectableToolBar jtb = (SelectableToolBar) toolBarMap.get(toolBarName);
303
        if ( jtb == null ) {
304
            jtb = new SelectableToolBar(toolBarName);
305
            jtb.setRollover(true);
306
            jtb.setAndamiVisibility(true);
307
            toolBarMap.put(toolBarName, jtb);
308
            toolBars.add(jtb);
309
        }
310
        return jtb;
311
    }
312
313 41314 jjdelcerro
    public void addTool(final PluginClassLoader loader, final SkinExtensionType ext,
314
            final ToolBar toolBar, final SelectableTool selectableTool)
315
            throws ClassNotFoundException {
316
        if ( !SwingUtilities.isEventDispatchThread() ) {
317
            try {
318
                SwingUtilities.invokeAndWait(new Runnable() {
319
                    public void run() {
320
                        try {
321
                            addTool(loader, ext, toolBar, selectableTool);
322
                        } catch (ClassNotFoundException ex) {
323 42350 jjdelcerro
                            logger.warn("¿¿¿ Eehh????", ex);
324 41314 jjdelcerro
                        }
325
                    }
326
                });
327
            } catch (Exception ex) {
328
                // Do nothing
329
            }
330
            return;
331 40435 jjdelcerro
        }
332 41962 jjdelcerro
        String name = toolBar.getName();
333
        SelectableToolBar jtb = getToolBar(name);
334
        if( selectableTool.getDropDownGroup()!=null ) {
335
            ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
336
            ActionInfo action = actionManager.getAction(selectableTool.getName());
337
            if( action!=null ) {
338
                DropDownButton dropDownButton = (DropDownButton) jtb.findComponent(selectableTool.getDropDownGroup());
339
                if( dropDownButton==null ) {
340
                    dropDownButton = new DropDownButton();
341
                    dropDownButton.setName(selectableTool.getDropDownGroup());
342
                    jtb.add(dropDownButton);
343
                    addControl(dropDownButton);
344
                }
345 42161 fdiaz
                dropDownButton.add(actionManager.getTranslated(action));
346 41962 jjdelcerro
            }
347
            return;
348
        }
349 42161 fdiaz
350 41314 jjdelcerro
        I18nManager i18nManager = ToolsLocator.getI18nManager();
351 40435 jjdelcerro
352 42351 jjdelcerro
        ImageIcon image = PluginServices.getIconTheme().get(selectableTool.getIcon());
353 41314 jjdelcerro
        if ( image != null ) {
354
            logger.warn("Unable to find icon '" + selectableTool.getIcon() + "'.");
355 42351 jjdelcerro
            image = PluginServices.getIconTheme().get(noIcon);
356 40435 jjdelcerro
        }
357 42548 dmartinezizquierdo
358 42351 jjdelcerro
        ToggleButtonModel buttonModel = new ToggleButtonModel();
359
        JToolBarToggleButton btn = new JToolBarToggleButton(selectableTool.getText(), image);
360 40435 jjdelcerro
        btn.setModel(buttonModel);
361
        btn.setMargin(new Insets(0, 0, 0, 0));
362
        btn.addMouseListener(tooltipListener);
363
        btn.addActionListener(this);
364
        btn.setFocusable(false);
365
        btn.setActionCommand(selectableTool.getActionCommand());
366
        btn.setToolTipText(selectableTool.getTooltip());
367
        btn.setEnabled(false);
368
        btn.setVisible(false);
369
370 42351 jjdelcerro
        ButtonGroup group = (ButtonGroup) buttonGroupMap.get(selectableTool.getGroup());
371
        if ( group == null ) {
372 40435 jjdelcerro
            group = new ButtonGroup();
373
            buttonGroupMap.put(selectableTool.getGroup(), group);
374
        }
375 42548 dmartinezizquierdo
376 40435 jjdelcerro
        jtb.addButton(group, btn);
377 42548 dmartinezizquierdo
378 40435 jjdelcerro
        buttonModel.setGroupName(selectableTool.getGroup());
379 41314 jjdelcerro
        if ( selectableTool.getIsDefault() ) {
380 40435 jjdelcerro
            btn.setSelected(true);
381
            initialSelectedTools.put(selectableTool.getGroup(),
382 41314 jjdelcerro
                    btn.getActionCommand());
383 40435 jjdelcerro
        }
384
385 41314 jjdelcerro
        addControl(btn);
386 40435 jjdelcerro
387 41314 jjdelcerro
        if ( selectableTool.getName() != null ) {
388 40435 jjdelcerro
            btn.setName(selectableTool.getName());
389
        }
390
391 41314 jjdelcerro
        if ( selectableTool.getTooltip() != null ) {
392
            btn.setToolTip(i18nManager.getTranslation(selectableTool.getTooltip()));
393
            btn.setToolTipKey(selectableTool.getTooltip());
394 40435 jjdelcerro
        }
395
396 41314 jjdelcerro
        if ( selectableTool.getEnableText() != null ) {
397
            btn.setEnableText(i18nManager.getTranslation(selectableTool.getEnableText()));
398 40435 jjdelcerro
        }
399
400 41314 jjdelcerro
        if ( selectableTool.getLast() == true ) {
401 40435 jjdelcerro
            jtb.addSeparator();
402
        }
403
    }
404
405 41314 jjdelcerro
    public void addTool(final PluginClassLoader loader, final SkinExtensionType ext,
406
            final ToolBar toolBar, final ActionTool actionTool) throws ClassNotFoundException {
407
        if ( !SwingUtilities.isEventDispatchThread() ) {
408
            try {
409
                SwingUtilities.invokeAndWait(new Runnable() {
410
                    public void run() {
411
                        try {
412
                            addTool(loader, ext, toolBar, actionTool);
413
                        } catch (ClassNotFoundException ex) {
414 42350 jjdelcerro
                            logger.warn("¿¿¿ Eehh????", ex);
415 41314 jjdelcerro
                        }
416
                    }
417
                });
418
            } catch (Exception ex) {
419
                // Do nothing
420
            }
421
            return;
422 40435 jjdelcerro
        }
423
424 41962 jjdelcerro
        String name = toolBar.getName();
425
        SelectableToolBar jtb = getToolBar(name);
426
        if( actionTool.getDropDownGroup()!=null ) {
427
            ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
428
            ActionInfo action = actionManager.getAction(actionTool.getName());
429
            if( action!=null ) {
430
                DropDownButton dropDownButton = (DropDownButton) jtb.findComponent(actionTool.getDropDownGroup());
431
                if( dropDownButton==null ) {
432
                    dropDownButton = new DropDownButton();
433
                    dropDownButton.setName(actionTool.getDropDownGroup());
434
                    jtb.add(dropDownButton);
435
                    addControl(dropDownButton);
436
                }
437 42161 fdiaz
                dropDownButton.add(actionManager.getTranslated(action));
438 41962 jjdelcerro
            }
439
            return;
440
        }
441 42161 fdiaz
442 41314 jjdelcerro
        I18nManager i18nManager = ToolsLocator.getI18nManager();
443
444 40435 jjdelcerro
        ImageIcon image = IconThemeHelper.getImageIcon(actionTool.getIcon());
445 41314 jjdelcerro
        if ( image != null ) {
446
            logger.warn("Unable to find icon '" + actionTool.getIcon() + "'.");
447 42351 jjdelcerro
            image =  PluginServices.getIconTheme().get(noIcon);
448 40435 jjdelcerro
        }
449
450 42351 jjdelcerro
        JToolBarButton btn = new JToolBarButton(actionTool.getText(), image);
451 40435 jjdelcerro
        btn.setMargin(new Insets(0, 0, 0, 0));
452
        btn.addMouseListener(tooltipListener);
453
        btn.addActionListener(this);
454
        btn.setFocusable(false);
455
        btn.setActionCommand(actionTool.getActionCommand());
456
        btn.setEnabled(false);
457
        btn.setVisible(false);
458
459
        jtb.add(btn);
460
461 41314 jjdelcerro
        addControl(btn);
462 40435 jjdelcerro
463 41314 jjdelcerro
        if ( actionTool.getName() != null ) {
464 40435 jjdelcerro
            btn.setName(actionTool.getName());
465
        }
466
467 41314 jjdelcerro
        if ( actionTool.getTooltip() != null ) {
468
            btn.setToolTip(i18nManager.getTranslation(actionTool.getTooltip()));
469
            btn.setToolTipKey(actionTool.getTooltip());
470 40435 jjdelcerro
        }
471
472 41314 jjdelcerro
        if ( actionTool.getEnableText() != null ) {
473
            btn.setEnableText(i18nManager.getTranslation(actionTool.getEnableText()));
474 40435 jjdelcerro
        }
475
476 41314 jjdelcerro
        if ( actionTool.getLast() == true ) {
477 40435 jjdelcerro
            jtb.addSeparator();
478
        }
479
    }
480 42161 fdiaz
481 41962 jjdelcerro
    public void addTool(final ActionInfo action, final String toolBarName, final String dropDownName) {
482
        if ( !SwingUtilities.isEventDispatchThread() ) {
483
            SwingUtilities.invokeLater(new Runnable() {
484
                public void run() {
485
                    addTool(action, toolBarName,dropDownName);
486
                }
487
            });
488
            return;
489
        }
490
        SelectableToolBar jtb = getToolBar(toolBarName);
491
        DropDownButton dropDownButton = (DropDownButton) jtb.findComponent(dropDownName);
492
        if( dropDownButton == null ) {
493
            dropDownButton = new DropDownButton();
494
            jtb.add(dropDownButton);
495
        }
496 42161 fdiaz
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
497
        dropDownButton.add(actionManager.getTranslated(action));
498 41962 jjdelcerro
    }
499 42351 jjdelcerro
    public void addTool(final ActionInfo action, final String toolBarName) {
500
        addTool(action, toolBarName, false);
501
    }
502 42161 fdiaz
503 42351 jjdelcerro
    public void addTool(final ActionInfo action, final String toolBarName, final boolean useText) {
504 41314 jjdelcerro
        I18nManager i18nManager = ToolsLocator.getI18nManager();
505 41080 jjdelcerro
506 41314 jjdelcerro
        if ( !SwingUtilities.isEventDispatchThread() ) {
507
            SwingUtilities.invokeLater(new Runnable() {
508
                public void run() {
509 42351 jjdelcerro
                    addTool(action, toolBarName, useText);
510 41314 jjdelcerro
                }
511
            });
512
            return;
513
        }
514
        JToolBarButton btn = new JToolBarButton(action.getIcon());
515
        btn.setMargin(new Insets(0, 0, 0, 0));
516
        btn.addMouseListener(tooltipListener);
517
        btn.addActionListener(this);
518
        btn.setFocusable(false);
519
        btn.setActionCommand(action.getCommand());
520
        btn.setEnabled(false);
521
        btn.setVisible(false);
522
        btn.setName(action.getName());
523 42351 jjdelcerro
        if( useText ) {
524
            btn.setText(action.getLabel());
525
        }
526 41314 jjdelcerro
        if ( action.getTooltip() != null ) {
527
            btn.setToolTip(i18nManager.getTranslation(action.getTooltip()));
528
            btn.setToolTipKey(action.getTooltip());
529
        }
530 41080 jjdelcerro
531 41962 jjdelcerro
        SelectableToolBar jtb = getToolBar(toolBarName);
532 41314 jjdelcerro
        jtb.add(btn);
533 41080 jjdelcerro
534 41314 jjdelcerro
        addControl(btn);
535 41080 jjdelcerro
536 41314 jjdelcerro
    }
537 42351 jjdelcerro
538
    public void addSelectableTool(final ActionInfo action, final String toolBarName, final String groupName, final boolean useText) {
539
        I18nManager i18nManager = ToolsLocator.getI18nManager();
540
541
        if ( !SwingUtilities.isEventDispatchThread() ) {
542
            SwingUtilities.invokeLater(new Runnable() {
543
                public void run() {
544
                    addSelectableTool(action, toolBarName,groupName,useText);
545
                }
546
            });
547
            return;
548
        }
549
550
        ButtonGroup group = (ButtonGroup) buttonGroupMap.get(groupName);
551
        if ( group == null ) {
552
            group = new ButtonGroup();
553
            buttonGroupMap.put(groupName, group);
554
        }
555
        ToggleButtonModel buttonModel = new ToggleButtonModel();
556
        buttonModel.setGroupName(groupName);
557
558
        JToolBarToggleButton btn = new JToolBarToggleButton(action.getIcon());
559
        btn.setModel(buttonModel);
560
        btn.setMargin(new Insets(0, 0, 0, 0));
561
        btn.addMouseListener(tooltipListener);
562
        btn.addActionListener(this);
563
        btn.setFocusable(false);
564
        btn.setActionCommand(action.getCommand());
565
        btn.setEnabled(false);
566
        btn.setVisible(false);
567
        btn.setName(action.getName());
568
        if( useText ) {
569
            btn.setText(action.getLabel());
570
        }
571
        if ( action.getTooltip() != null ) {
572
            btn.setToolTip(i18nManager.getTranslation(action.getTooltip()));
573
            btn.setToolTipKey(action.getTooltip());
574
        }
575 42548 dmartinezizquierdo
576 42351 jjdelcerro
        SelectableToolBar jtb = getToolBar(toolBarName);
577
        jtb.addButton(group, btn);
578 42548 dmartinezizquierdo
579 42351 jjdelcerro
        addControl(btn);
580
581
    }
582
583 40435 jjdelcerro
    /**
584
     * Creates the needed menu structure to add the menu to the bar.
585
     * Returns the father which must hold the menu which was
586
     * provided as parameter.
587 41314 jjdelcerro
     *
588 42350 jjdelcerro
     * Crea la estructura de menus necesaria para añadir el menu a la barra.
589 40435 jjdelcerro
     * Devuelve el padre del cual debe colgar el menu que se pasa como
590 41314 jjdelcerro
     * parametro.
591
     *
592 40435 jjdelcerro
     * @param menu
593 41314 jjdelcerro
     * The Menu whose support is going to be added
594 40435 jjdelcerro
     * @param loader
595 41314 jjdelcerro
     * The plugin's class loader
596
     *
597 40435 jjdelcerro
     * @return The proper father for the menu which was provided as parameter
598
     */
599
    private JMenu createMenuAncestors(Menu menu, PluginClassLoader loader) {
600 41080 jjdelcerro
        return createMenuAncestors(menu.getText());
601
    }
602
603
    private JMenu createMenuAncestors(String text) {
604 41314 jjdelcerro
        I18nManager i18nManager = ToolsLocator.getI18nManager();
605
606 40435 jjdelcerro
        MenuElement menuPadre = null;
607
608 41080 jjdelcerro
        String[] menues = text.split("/");
609
        List menuList = new ArrayList();
610 40435 jjdelcerro
        menuList.add(menues[0]);
611
        menuPadre = getMenu(menuList, menuBar);
612
613
        JMenu padre = null;
614
615 41314 jjdelcerro
        if ( menuPadre == null ) {
616
            padre = new JMenuTraslatable(i18nManager.getTranslation(menues[0]));
617
            ((JMenuTraslatable) padre).setTextKey(menues[0]);
618 40435 jjdelcerro
            padre.setName(menues[0]);
619 41314 jjdelcerro
            addControl(padre);
620 40435 jjdelcerro
            menuBar.add(padre);
621 41314 jjdelcerro
        } else if ( menuPadre instanceof JMenu ) {
622
            padre = (JMenu) menuPadre;
623
        } else {
624
            logger.warn("Error creating menu. Ancestor does not exist (" + text + ").");
625
            return null;
626
        }
627 40435 jjdelcerro
628
        // Se crea el resto de menus
629
        ArrayList temp = new ArrayList();
630
631 41314 jjdelcerro
        for ( int i = 1; i < (menues.length - 1); i++ ) {
632 40435 jjdelcerro
            temp.add(menues[i]);
633
        }
634
635
        menuPadre = createMenus(temp, padre);
636
637
        return (JMenu) menuPadre;
638
    }
639
640
    /**
641 42350 jjdelcerro
     * Añade la informacion del menu al framework.
642
     * Debido a que los men�es se
643 40435 jjdelcerro
     * pueden introducir en un orden determinado por el usuario, pero los
644
     * plugins se instalan en un orden arbitrario, primero se almacena la
645 41314 jjdelcerro
     * informacion de todos los menus para luego ordenarlos y posteriormente
646 42350 jjdelcerro
     * añadirlos al interfaz
647 41314 jjdelcerro
     *
648 40435 jjdelcerro
     * @param loader
649 41314 jjdelcerro
     * Posicion del menu. Se ordena por este campo
650 40435 jjdelcerro
     * @param ext
651 41314 jjdelcerro
     * Array con los nombres de los padres del menu
652 40435 jjdelcerro
     * @param menu
653 41314 jjdelcerro
     * Texto del menu
654
     *
655 40435 jjdelcerro
     * @throws ClassNotFoundException
656
     * @throws RuntimeException
657
     */
658 41314 jjdelcerro
    public void addMenu(final PluginClassLoader loader, final SkinExtensionType ext,
659
            final Menu menu) throws ClassNotFoundException {
660
        if ( !SwingUtilities.isEventDispatchThread() ) {
661
            try {
662
                SwingUtilities.invokeAndWait(new Runnable() {
663
                    public void run() {
664
                        try {
665
                            addMenu(loader, ext, menu);
666
                        } catch (ClassNotFoundException ex) {
667 42350 jjdelcerro
                            logger.warn("¿¿¿ Eehh????", ex);
668 41314 jjdelcerro
                        }
669
                    }
670
                });
671
            } catch (Exception ex) {
672
                // Do nothing
673
            }
674
            return;
675 40435 jjdelcerro
        }
676 41314 jjdelcerro
        JMenu menuPadre = createMenuAncestors(menu, loader);
677 40435 jjdelcerro
678 41314 jjdelcerro
        if ( menu.getIs_separator() ) {
679 40435 jjdelcerro
            menuPadre.addSeparator();
680
            return;
681
        }
682
683
        JMenuItem nuevoMenu = createJMenuItem(loader, menu);
684
        nuevoMenu.addMouseListener(tooltipListener);
685
        menuPadre.add(nuevoMenu);
686 41314 jjdelcerro
        addControl(nuevoMenu);
687
688 40435 jjdelcerro
    }
689
690 41314 jjdelcerro
    public void addMenu(final ActionInfo action, final String text) {
691
        if ( !SwingUtilities.isEventDispatchThread() ) {
692
            SwingUtilities.invokeLater(new Runnable() {
693
                public void run() {
694
                    addMenu(action, text);
695
                }
696
            });
697
            return;
698 41080 jjdelcerro
        }
699 41314 jjdelcerro
        JMenu menuPadre = createMenuAncestors(text);
700 41080 jjdelcerro
        JMenuItem nuevoMenu = createJMenuItem(action, text);
701
        nuevoMenu.addMouseListener(tooltipListener);
702
        menuPadre.add(nuevoMenu);
703 42336 jjdelcerro
        menuPadre.invalidate();
704 41080 jjdelcerro
        Class<? extends IExtension> classExtension = action.getExtension().getClass();
705 41314 jjdelcerro
        addControl(nuevoMenu);
706 41080 jjdelcerro
    }
707 41314 jjdelcerro
708 40435 jjdelcerro
    /**
709 41314 jjdelcerro
     * Dado lista de nombres de menu, encuentra el menu
710
     *
711 40435 jjdelcerro
     * @param nombres
712
     * @param padre
713 41314 jjdelcerro
     * @return
714 40435 jjdelcerro
     */
715 41080 jjdelcerro
    private javax.swing.JMenuItem getMenu(List nombres, MenuElement parent) {
716 41314 jjdelcerro
        if ( parent instanceof javax.swing.JMenu ) {
717 40435 jjdelcerro
            javax.swing.JMenu parentItem = (javax.swing.JMenu) parent;
718
719 41314 jjdelcerro
            for ( int i = 0; i < parentItem.getMenuComponentCount(); i++ ) {
720
721
                String item_name = parentItem.getMenuComponent(i).getName();
722
                if ( ((item_name != null) && (item_name.compareTo((String) nombres.get(0)) == 0))
723
                        || /*
724
                         * We also accept "leaf menus" with no name
725
                         * (Project manager, View-1, View-2, etc)
726
                         */ lastMenuItemWithoutName(parentItem.getMenuComponent(i), nombres) ) {
727
728 40435 jjdelcerro
                    nombres.remove(0);
729 41314 jjdelcerro
                    if ( nombres.isEmpty() ) {
730
                        if ( parentItem.getMenuComponent(i) instanceof javax.swing.JMenuItem ) {
731 40435 jjdelcerro
                            return (javax.swing.JMenuItem) parentItem
732 41314 jjdelcerro
                                    .getMenuComponent(i);
733 40435 jjdelcerro
                        } else {
734
                            logger.error(PluginServices.getText(this,
735 41314 jjdelcerro
                                    "Menu_type_not_supported_")
736
                                    + " "
737
                                    + parentItem.getMenuComponent(i).getClass()
738 40435 jjdelcerro
                                    .getName());
739
                            return null;
740
                        }
741
                    } else {
742
                        return getMenu(nombres,
743 41314 jjdelcerro
                                (MenuElement) parentItem.getMenuComponent(i));
744 40435 jjdelcerro
                    }
745
                }
746
            }
747 41314 jjdelcerro
        } else if ( parent instanceof JMenuBar ) {
748
            javax.swing.JMenuBar parentItem = (javax.swing.JMenuBar) parent;
749 40435 jjdelcerro
750 41314 jjdelcerro
            for ( int i = 0; i < parentItem.getMenuCount(); i++ ) {
751
                if ( (parentItem.getMenu(i).getName() != null // not a
752
                        // JToolBar.Separator
753 40435 jjdelcerro
                        )
754
                        && (parentItem.getMenu(i).getName()
755 41314 jjdelcerro
                        .compareTo((String) nombres.get(0)) == 0) ) {
756
                    nombres.remove(0);
757
                    if ( nombres.isEmpty() ) {
758
                        if ( parentItem.getMenu(i) instanceof javax.swing.JMenuItem ) {
759
                            return parentItem.getMenu(i);
760
                        } else {
761
                            logger.error(PluginServices.getText(this,
762 40435 jjdelcerro
                                    "Menu_type_not_supported_")
763
                                    + " "
764
                                    + parentItem.getMenu(i).getClass()
765 41314 jjdelcerro
                                    .getName());
766
                            return null;
767 40435 jjdelcerro
                        }
768 41314 jjdelcerro
                    } else {
769
                        return getMenu(nombres, parentItem.getMenu(i));
770 40435 jjdelcerro
                    }
771
                }
772 41314 jjdelcerro
            }
773
        } else {
774
            logger.error(PluginServices.getText(this,
775 40435 jjdelcerro
                    "Menu_type_not_supported_")
776
                    + " "
777
                    + parent.getClass().getName() + " " + parent.toString());
778 41314 jjdelcerro
        }
779 40435 jjdelcerro
        return null;
780
    }
781
782
    /**
783
     * @param menuComponent
784
     * @param nombres
785
     * @return
786
     */
787 41080 jjdelcerro
    private boolean lastMenuItemWithoutName(Component mc, List names) {
788 41314 jjdelcerro
789 40435 jjdelcerro
        /*
790
         * names must have 1 string
791
         */
792 41314 jjdelcerro
        if ( names == null || names.size() != 1 ) {
793 40435 jjdelcerro
            return false;
794
        }
795 41314 jjdelcerro
        if ( !(mc instanceof JMenuItem) ) {
796 40435 jjdelcerro
            return false;
797
        }
798
        JMenuItem jmi = (JMenuItem) mc;
799 41314 jjdelcerro
        if ( jmi.getName() != null ) {
800 40435 jjdelcerro
            /*
801
             * Name must be null, so this is a menu leaf
802
             */
803
            return false;
804
        }
805 41314 jjdelcerro
        if ( jmi.getText() == null ) {
806 40435 jjdelcerro
            return false;
807
        }
808
        return jmi.getText().compareTo((String) names.get(0)) == 0;
809
    }
810
811 41314 jjdelcerro
    private class JMenuTraslatable extends JMenu implements TranslatableButton {
812
813
        private TranslatableButtonHelper i18nHelper = new TranslatableButtonHelper();
814
815
        public JMenuTraslatable(String text) {
816
            super(text);
817
        }
818
819
        public void setTextKey(String key) {
820
            this.i18nHelper.setText(key);
821
        }
822
823
        public void setToolTipKey(String key) {
824
            this.i18nHelper.setTooltip(key);
825
        }
826
827
        public void translate() {
828
            if ( this.i18nHelper.needTranslation() ) {
829
                this.i18nHelper.translate();
830
                this.setText(this.i18nHelper.getText());
831
            }
832
        }
833
834
    }
835
836 40435 jjdelcerro
    /**
837
     * Crea la estructura de menus recursivamente. Por ejemplo, si se le pasa
838 42350 jjdelcerro
     * en el par�metro nombres el array {"Search", "References", "Workspace"}
839
     * crear� un men� Search, un submen� del anterior que se llamar�
840
     * References y debajo de �ste �ltimo otro menu llamado Workspace
841 41314 jjdelcerro
     *
842 40435 jjdelcerro
     * @param nombres
843 42350 jjdelcerro
     * Array con los nombres de los men�s que se quieren crear
844 40435 jjdelcerro
     * @param padre
845 42350 jjdelcerro
     * Menu padre de los men�s creados. Es �til porque es un
846 41314 jjdelcerro
     * algoritmo recursivo
847
     *
848 42350 jjdelcerro
     * @return Devuelve el men� creado. Al final de toda la recursividad,
849
     * devolver� el men� de m�s abajo en la jerarqu�a
850 41314 jjdelcerro
     *
851 40435 jjdelcerro
     * @throws RuntimeException
852
     */
853
    private JMenu createMenus(ArrayList nombres, JMenu padre) {
854 41314 jjdelcerro
        if ( !SwingUtilities.isEventDispatchThread() ) {
855
            logger.warn("Este metodo requiere que se este ejecutando en el hilo de eventos de AWT.");
856 40435 jjdelcerro
            throw new RuntimeException("No Event Dispatch Thread");
857
        }
858 41314 jjdelcerro
        I18nManager i18nManager = ToolsLocator.getI18nManager();
859 40435 jjdelcerro
860
        // si no quedan nombres de menu por crear se vuelve: caso base
861 41314 jjdelcerro
        if ( nombres.isEmpty() ) {
862 40435 jjdelcerro
            return padre;
863
        }
864
865
        // Se busca el menu por si ya existiera para no crearlo otra vez
866
        JMenu buscado = null;
867
868 41314 jjdelcerro
        for ( int i = 0; i < padre.getMenuComponentCount(); i++ ) {
869 40435 jjdelcerro
            try {
870
                JMenu hijo = (JMenu) padre.getMenuComponent(i);
871
872 41314 jjdelcerro
                if ( hijo.getName().compareTo((String) nombres.get(0)) == 0 ) {
873 40435 jjdelcerro
                    buscado = hijo;
874
                }
875
            } catch (ClassCastException e) {
876
                /*
877 42350 jjdelcerro
                 * Se ha encontrado un elemento hoja del arbol de men�es
878 40435 jjdelcerro
                 */
879
            }
880
        }
881
882 41314 jjdelcerro
        if ( buscado != null ) {
883 40435 jjdelcerro
            // Si lo hemos encontrado creamos el resto
884
            nombres.remove(0);
885
886
            return createMenus(nombres, buscado);
887
        } else {
888 42350 jjdelcerro
            // Si no lo hemos encontrado se crea el menu, se a�ade al padre
889 40435 jjdelcerro
            // y se crea el resto
890
            String nombre = (String) nombres.get(0);
891 41314 jjdelcerro
            JMenuTraslatable menuPadre = new JMenuTraslatable(i18nManager.getTranslation(nombre));
892
            menuPadre.setTextKey(nombre);
893 40435 jjdelcerro
            menuPadre.setName(nombre);
894 41314 jjdelcerro
            addControl(menuPadre);
895 40435 jjdelcerro
            padre.add(menuPadre);
896
897
            nombres.remove(0);
898
899
            return createMenus(nombres, menuPadre);
900
        }
901
    }
902
903
    /**
904 42350 jjdelcerro
     * M�todo invocado en respuesta a ciertos eventos de la interfaz que
905 40435 jjdelcerro
     * pueden
906 42350 jjdelcerro
     * ocultar botones de las barras de herramientas y que redimensiona �sta
907 40435 jjdelcerro
     * de manera conveniente para que no se oculte ninguno
908
     */
909
    private void ajustarToolBar() {
910
        int margen = 8;
911
        int numFilas = 1;
912
        double acum = margen;
913
914
        int toolHeight = 0;
915
916 41314 jjdelcerro
        for ( int i = 0; i < toolBars.getComponentCount(); i++ ) {
917 40435 jjdelcerro
            Component c = toolBars.getComponent(i);
918
919 41314 jjdelcerro
            if ( !c.isVisible() ) {
920 40435 jjdelcerro
                continue;
921
            }
922
923
            double width = c.getPreferredSize().getWidth();
924
            acum = acum + width;
925
926 41314 jjdelcerro
            if ( acum > this.getWidth() ) {
927 40435 jjdelcerro
                numFilas++;
928
                acum = width + margen;
929
            }
930
931 41314 jjdelcerro
            if ( c.getPreferredSize().getHeight() > toolHeight ) {
932 40435 jjdelcerro
                toolHeight = c.getPreferredSize().height;
933
            }
934
        }
935
936
        toolBars.setPreferredSize(new Dimension(this.getWidth(),
937 41314 jjdelcerro
                (numFilas * toolHeight)));
938 40435 jjdelcerro
939
        toolBars.updateUI();
940
    }
941
942
    public void setClassesExtensions(Map<Class<? extends IExtension>, ExtensionDecorator> classesExtensions) {
943 41314 jjdelcerro
        // Ya no es necesario que se mantenga el Map con las extensiones.
944
945
//            Map<Class<? extends IExtension>, ExtensionDecorator> extensions = new HashMap<Class<? extends IExtension>, ExtensionDecorator>();
946
//            for ( Entry<Class<? extends IExtension>, ExtensionDecorator>  entry: classesExtensions.entrySet()) {
947
//                        if( ! (entry.getValue().getExtension() instanceof LibraryExtension) ) {
948
//                                extensions.put(entry.getKey(), entry.getValue());
949
//                        }
950
//                }
951
//        this.classesExtensions = extensions;
952 40435 jjdelcerro
    }
953
954
    /**
955
     * Metodo de callback invocado cuando se selecciona un menu o un boton
956
     * de
957 42350 jjdelcerro
     * la barra de herramientas. Se busca la extensi�n asociada y se ejecuta
958 41314 jjdelcerro
     *
959 40435 jjdelcerro
     * @param e
960 41314 jjdelcerro
     * Evento producido
961 40435 jjdelcerro
     */
962
    public void actionPerformed(ActionEvent e) {
963 41314 jjdelcerro
964
        String actionName = "(unknow)";
965 40435 jjdelcerro
        try {
966
            JComponent control = (JComponent) e.getSource();
967
            actionName = control.getName();
968 41314 jjdelcerro
969
            ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
970
            ActionInfo action = actionManager.getAction(control.getName());
971
            Object args = null;
972
            if ( control instanceof IControl ) {
973
                args = ((IControl) control).getValue();
974 40435 jjdelcerro
            }
975 41314 jjdelcerro
            if ( args == null ) {
976
                action.execute();
977 40435 jjdelcerro
            } else {
978 41314 jjdelcerro
                action.execute(args);
979 40435 jjdelcerro
            }
980 41314 jjdelcerro
            String actionCommand = e.getActionCommand();
981 40435 jjdelcerro
            try {
982
                JToolBarToggleButton toggle = (JToolBarToggleButton) control;
983
                ToggleButtonModel model = (ToggleButtonModel) toggle.getModel();
984
                selectedTool.put(model.getGroupName(), actionCommand);
985
            } catch (ClassCastException ex) {
986
            } catch (NullPointerException ex) {
987
            }
988
989
        } catch (Throwable ex) {
990 41314 jjdelcerro
            logger.error("Can't perform action '" + actionName + "'.", ex);
991 40435 jjdelcerro
        }
992
993
        enableControls();
994
        showMemory();
995
    }
996
997
    private String getName(String name, PluginClassLoader loader) {
998 41314 jjdelcerro
        if ( name.indexOf('.') == -1 ) {
999 40435 jjdelcerro
            return loader.getPluginName() + "." + name;
1000
        } else {
1001
            return name;
1002
        }
1003
    }
1004
1005
    public void addPopupMenu(PluginClassLoader loader, PopupMenu menu) {
1006 41314 jjdelcerro
        if ( !SwingUtilities.isEventDispatchThread() ) {
1007 40435 jjdelcerro
            throw new RuntimeException("No Event Dispatch Thread");
1008
        }
1009
1010
        String name = getName(menu.getName(), loader);
1011
1012
        // Se crea el control popupmenu
1013
        JPopUpMenu popupMenu = (JPopUpMenu) popupMap.get(name);
1014
1015 41314 jjdelcerro
        if ( popupMenu == null ) {
1016 40435 jjdelcerro
            popupMenu = new JPopUpMenu(menu.getName());
1017
            popupMap.put(name, popupMenu);
1018
        }
1019
1020
        Menu[] menues = menu.getMenu();
1021 41314 jjdelcerro
        for ( int i = 0; i < menues.length; i++ ) {
1022 40435 jjdelcerro
            JMenuItem nuevoMenu = createJMenuItem(loader, menues[i]);
1023
            popupMenu.add(nuevoMenu);
1024
        }
1025
    }
1026
1027
    private JMenuItem createJMenuItem(PluginClassLoader loader, Menu menu) {
1028
        JMenuItem nuevoMenu = null;
1029
1030 41314 jjdelcerro
        I18nManager i18nManager = ToolsLocator.getI18nManager();
1031
1032 40435 jjdelcerro
        String text = menu.getText();
1033
        int n = text.lastIndexOf('/');
1034 41314 jjdelcerro
        if ( n >= 0 ) {
1035
            text = text.substring(n + 1);
1036 40435 jjdelcerro
        }
1037 41314 jjdelcerro
        String translatedText = i18nManager.getTranslation(text);
1038 40435 jjdelcerro
1039
        IconTheme iconTheme = ToolsSwingLocator.getIconThemeManager().getCurrent();
1040 41314 jjdelcerro
        if ( menu.getIcon() != null ) {
1041
            if ( iconTheme.exists(menu.getIcon()) ) {
1042
                ImageIcon image = iconTheme.get(menu.getIcon());
1043 40435 jjdelcerro
                nuevoMenu = new JMenuItem(translatedText, image);
1044
            } else {
1045
                nuevoMenu = new JMenuItem(translatedText);
1046 41314 jjdelcerro
                logger.info("menu icon '" + menu.getIcon() + "' not exists.");
1047 40435 jjdelcerro
            }
1048
        } else {
1049
            nuevoMenu = new JMenuItem(translatedText);
1050
        }
1051 41314 jjdelcerro
        nuevoMenu.setTextKey(text);
1052 40435 jjdelcerro
        nuevoMenu.setName(menu.getName());
1053
1054 41314 jjdelcerro
        if ( menu.getKey() != null ) {
1055 40435 jjdelcerro
            nuevoMenu.setAccelerator(KeyMapping.getKeyStroke(menu.getKey()));
1056
        }
1057
1058
        nuevoMenu.setActionCommand(menu.getActionCommand());
1059
1060 41314 jjdelcerro
        if ( menu.getTooltip() != null ) {
1061
            nuevoMenu.setToolTip(i18nManager.getTranslation(menu.getTooltip()));
1062
            nuevoMenu.setToolTipKey(menu.getTooltip());
1063 40435 jjdelcerro
        }
1064
1065 41314 jjdelcerro
        if ( menu.getEnableText() != null ) {
1066
            nuevoMenu.setEnableText(i18nManager.getTranslation(menu.getEnableText()));
1067 40435 jjdelcerro
        }
1068
1069
        nuevoMenu.setEnabled(true);
1070
        nuevoMenu.setVisible(true);
1071
1072 41314 jjdelcerro
        if ( menu.getName() != null ) {
1073
            ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1074
            final ActionInfo actionInfo = actionManager.getAction(menu.getName());
1075
            if ( actionInfo != null ) {
1076
                nuevoMenu.addActionListener(actionInfo);
1077
            }
1078 40435 jjdelcerro
        }
1079
        return nuevoMenu;
1080
    }
1081
1082 41080 jjdelcerro
    private JMenuItem createJMenuItem(ActionInfo action, String text) {
1083 41314 jjdelcerro
        I18nManager i18nManager = ToolsLocator.getI18nManager();
1084 41080 jjdelcerro
        String label = null;
1085 41314 jjdelcerro
1086
        if ( text == null ) {
1087
            label = action.getLabel();
1088
        } else if ( text.contains("/") ) {
1089
            String[] ss = text.split("/");
1090
            label = ss[ss.length - 1];
1091 41080 jjdelcerro
        } else {
1092 41314 jjdelcerro
            label = text;
1093 41080 jjdelcerro
        }
1094 42351 jjdelcerro
        JMenuItem nuevoMenu = new JMenuItem();
1095 42969 jjdelcerro
        nuevoMenu.setTextKey(label);
1096 42351 jjdelcerro
        nuevoMenu.setText(i18nManager.getTranslation(label));
1097
        nuevoMenu.setName(action.getName());
1098 41314 jjdelcerro
        if ( action.getIconName() != null ) {
1099 42351 jjdelcerro
            nuevoMenu.setIcon(action.getIcon());
1100 41080 jjdelcerro
        }
1101
        KeyStroke key = action.getKeyStroke();
1102 41314 jjdelcerro
        if ( key != null ) {
1103 41080 jjdelcerro
            nuevoMenu.setAccelerator(key);
1104
        }
1105
        nuevoMenu.setActionCommand(action.getCommand());
1106 41314 jjdelcerro
        if ( action.getTooltip() != null ) {
1107 41080 jjdelcerro
            nuevoMenu.setToolTip(i18nManager.getTranslation(action.getTooltip()));
1108 42969 jjdelcerro
            nuevoMenu.setToolTipKey(action.getTooltip());
1109 41080 jjdelcerro
        }
1110
        nuevoMenu.setEnabled(true);
1111
        nuevoMenu.setVisible(true);
1112 41314 jjdelcerro
        nuevoMenu.addActionListener(action);
1113 41080 jjdelcerro
        return nuevoMenu;
1114
    }
1115
1116 40435 jjdelcerro
    /**
1117
     * Muestra u oculta el menu de nombre 'name'
1118 41314 jjdelcerro
     *
1119 40435 jjdelcerro
     * @param name
1120 41314 jjdelcerro
     * Nombre del menu que se quiere mostrar
1121 40435 jjdelcerro
     * @param x
1122 41314 jjdelcerro
     * Evento de raton
1123 40435 jjdelcerro
     * @param y
1124
     * @param c
1125
     */
1126
    private void showPopupMenu(String name, int x, int y, Component c) {
1127
        JPopupMenu menu = (JPopupMenu) popupMap.get(name);
1128
1129 41314 jjdelcerro
        if ( menu != null ) {
1130 40435 jjdelcerro
            menu.show(c, x, y);
1131
        }
1132
    }
1133
1134
    public void removePopupMenuListener(String name, ActionListener listener) {
1135
        JPopupMenu menu = (JPopupMenu) popupMap.get(name);
1136
1137 41314 jjdelcerro
        if ( menu != null ) {
1138 40435 jjdelcerro
            Component[] jmenuitems = menu.getComponents();
1139
1140 41314 jjdelcerro
            for ( int i = 0; i < jmenuitems.length; i++ ) {
1141
                if ( jmenuitems[i] instanceof JMenuItem ) {
1142 40435 jjdelcerro
                    ((JMenuItem) jmenuitems[i]).removeActionListener(listener);
1143
                }
1144
            }
1145
        }
1146
    }
1147
1148
    public void addPopupMenuListener(String popupName, Component c,
1149 41314 jjdelcerro
            ActionListener listener, PluginClassLoader loader) {
1150 40435 jjdelcerro
        final String name = getName(popupName, loader);
1151
1152
        JPopupMenu menu = (JPopupMenu) popupMap.get(name);
1153
1154 41314 jjdelcerro
        if ( menu != null ) {
1155 40435 jjdelcerro
            Component[] jmenuitems = menu.getComponents();
1156
1157 41314 jjdelcerro
            for ( int i = 0; i < jmenuitems.length; i++ ) {
1158
                if ( jmenuitems[i] instanceof JMenuItem ) {
1159 40435 jjdelcerro
                    ((JMenuItem) jmenuitems[i]).addActionListener(listener);
1160
                }
1161
            }
1162
        }
1163
1164
        c.addMouseListener(new MouseAdapter() {
1165
1166
            @Override
1167
            public void mousePressed(MouseEvent e) {
1168 41314 jjdelcerro
                if ( e.isPopupTrigger() ) {
1169 40435 jjdelcerro
                    showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
1170
                }
1171
            }
1172
1173
            @Override
1174
            public void mouseReleased(MouseEvent e) {
1175 41314 jjdelcerro
                if ( e.isPopupTrigger() ) {
1176 40435 jjdelcerro
                    showPopupMenu(name, e.getX(), e.getY(), e.getComponent());
1177
                }
1178
            }
1179
        });
1180
    }
1181
1182
    /**
1183
     * Loop on the controls to enable/disable and show/hide them, according to
1184 41314 jjdelcerro
     * its associated action (ActionInfo)
1185
     *
1186 40435 jjdelcerro
     * @throws RuntimeException
1187
     */
1188
    public void enableControls() {
1189 41314 jjdelcerro
        if ( !SwingUtilities.isEventDispatchThread() ) {
1190
            SwingUtilities.invokeLater(new Runnable() {
1191
                public void run() {
1192
                    enableControls();
1193
                }
1194
            });
1195
            return;
1196 40435 jjdelcerro
        }
1197
1198
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1199
        ActionInfoStatusCache cache = actionManager.createActionStatusCache();
1200
1201
        // Enable or disable controls, according to its associated extensions
1202 41314 jjdelcerro
        Iterator<JComponent> e = controlsIterator();
1203 40435 jjdelcerro
1204 41314 jjdelcerro
        while ( e.hasNext() ) {
1205 40435 jjdelcerro
            JComponent control = (JComponent) e.next();
1206 41334 jjdelcerro
            String actionName = control.getName();
1207
            ActionInfo action = actionManager.getAction(actionName);
1208 40435 jjdelcerro
            try {
1209
                boolean enabled = false;
1210
                boolean visible = false;
1211 41314 jjdelcerro
1212
                if ( action == null ) {
1213 41962 jjdelcerro
                    if( control instanceof DropDownButton ) {
1214
                        DropDownButton dropDownButton = (DropDownButton)control;
1215
                        visible = !dropDownButton.isAllHiden();
1216
                        enabled = !dropDownButton.isAllDisabled();
1217 42548 dmartinezizquierdo
                        if (visible && enabled){
1218
                            dropDownButton.updateMainButton();
1219
                        }
1220 41962 jjdelcerro
                    } else if( control instanceof JMenuTraslatable ) {
1221 41334 jjdelcerro
                        enabled = true;
1222
                        visible = true;
1223
                    } else {
1224
                        IExtension extension = this.control2extensions.get(control);
1225
                        if( extension!=null ) {
1226
                            enabled = extension.isEnabled();
1227
                            visible = extension.isVisible();
1228
                        } else {
1229
                            logger.warn("Can't enable/show control '"+control.getClass().getName()+"/"+control.getName()+".");
1230
                            enabled = true;
1231
                            visible = true;
1232
                        }
1233
                    }
1234 41314 jjdelcerro
                } else {
1235
                    enabled = false;
1236 40435 jjdelcerro
                    visible = cache.isVisible(action);
1237 41314 jjdelcerro
                    if ( visible ) {
1238
                        enabled = cache.isEnabled(action);
1239 40435 jjdelcerro
                    }
1240 41314 jjdelcerro
                }
1241 42969 jjdelcerro
                //logger.info(control.getClass().getName() +" - " +control.getName() + " visible " + visible );
1242 40435 jjdelcerro
                control.setEnabled(enabled);
1243
                control.setVisible(visible);
1244 41549 jjdelcerro
            } catch (Throwable ex) {
1245 42548 dmartinezizquierdo
                // Catch exceptions and errors (class not found)
1246 41334 jjdelcerro
                logger.info("Can't enable/show control '" + actionName + "'.", ex);
1247
                this.message("Can't enable/show control '" + actionName + "'.", JOptionPane.ERROR_MESSAGE);
1248 41314 jjdelcerro
                try {
1249
                    control.setEnabled(false);
1250
                    control.setVisible(false);
1251
                } catch (Exception ex2) {
1252
                    // Ignore errors
1253
                }
1254 40435 jjdelcerro
            }
1255
        }
1256
1257
        // Loop in the menus to hide the menus that don't have visible children
1258 41314 jjdelcerro
        for ( int i = 0; i < menuBar.getMenuCount(); i++ ) {
1259 40435 jjdelcerro
            MenuElement menu = menuBar.getMenu(i);
1260
            hideMenus(menu);
1261 41314 jjdelcerro
            if ( menu instanceof JMenu ) {
1262 40435 jjdelcerro
                // hide (ugly) redundant separators and assign keyboard
1263
                // mnemonics
1264
                Component[] comps = ((JMenu) menu).getMenuComponents();
1265
                // mnemonics have to be unique for each top-level menu
1266
                char mnemonics[] = new char[comps.length];
1267 41314 jjdelcerro
                if ( comps.length > 0 ) {
1268 40435 jjdelcerro
                    // Set keyboard mnemonic for this top-level entry
1269
                    String text = ((JMenu) menu).getText();
1270
                    char mnemonic = getMnemonic(text, mnemonics);
1271 41314 jjdelcerro
                    if ( ' ' != mnemonic ) {
1272 40435 jjdelcerro
                        ((JMenu) menu).setMnemonic(mnemonic);
1273
                        mnemonics[0] = mnemonic;
1274
                    }
1275
                }
1276
                // now go through all entries in this menu, hid
1277
                // separators if necessary and assing remaining mnemonics
1278
                hideSeparatorsAndMakeMnemonics(menu, mnemonics);
1279
            }
1280
        }
1281
1282
        // hide the toolbars that don't contain any visible tool
1283
        Iterator it = toolBarMap.values().iterator();
1284
1285 41314 jjdelcerro
        while ( it.hasNext() ) {
1286
            JComponent t = (JComponent) it.next();
1287 40435 jjdelcerro
            boolean todosOcultos = true;
1288
1289 41314 jjdelcerro
            for ( int i = 0; i < t.getComponentCount(); i++ ) {
1290
                if ( !(t.getComponent(i) instanceof JSeparator) // separators
1291
                        // don't matter
1292
                        && t.getComponent(i).isVisible() ) {
1293 40435 jjdelcerro
                    todosOcultos = false;
1294
                }
1295
            }
1296
1297 41314 jjdelcerro
            if ( todosOcultos ) {
1298 40435 jjdelcerro
                t.setVisible(false);
1299
            } else {
1300 41314 jjdelcerro
                if ( t instanceof SelectableToolBar ) {
1301
                    t.setVisible(((SelectableToolBar) t).getAndamiVisibility());
1302
                } else {
1303
                    t.setVisible(true);
1304
                }
1305 40435 jjdelcerro
            }
1306
        }
1307
1308 41314 jjdelcerro
        if ( mdiManager != null ) {
1309 40435 jjdelcerro
            JPanel f = (JPanel) mdiManager.getActiveWindow();
1310
1311 41314 jjdelcerro
            if ( f != null ) {
1312
                if ( lastLabelClass != f.getClass() ) {
1313 40435 jjdelcerro
                    lastLabelClass = f.getClass();
1314
1315
                    Label[] lbls = (Label[]) classLabels.get(lastLabelClass);
1316
1317 41314 jjdelcerro
                    if ( lbls != null ) {
1318 40435 jjdelcerro
                        bEstado.setLabelSet(lbls);
1319
                    }
1320
                }
1321
            }
1322
        }
1323
1324
        ajustarToolBar();
1325
1326
        showMemory();
1327
    }
1328 41314 jjdelcerro
1329 42165 fdiaz
    public synchronized void refreshControls() {
1330 41314 jjdelcerro
        if ( !SwingUtilities.isEventDispatchThread() ) {
1331
            SwingUtilities.invokeLater(new Runnable() {
1332
                public void run() {
1333
                    refreshControls();
1334
                }
1335
            });
1336
            return;
1337 40435 jjdelcerro
        }
1338
1339 42165 fdiaz
        if(refreshingControls){
1340
            return;
1341
        }
1342
        try {
1343
        refreshingControls = true;
1344 40435 jjdelcerro
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1345
        ActionInfoStatusCache cache = actionManager.createActionStatusCache();
1346
        IconTheme icontheme = ToolsSwingLocator.getIconThemeManager().getCurrent();
1347
1348 41314 jjdelcerro
        Iterator e = controlsIterator();
1349
1350
        while ( e.hasNext() ) {
1351 40435 jjdelcerro
            JComponent control = (JComponent) e.next();
1352 41314 jjdelcerro
            if ( control instanceof TranslatableButton ) {
1353
                ((TranslatableButton) control).translate();
1354
            }
1355 40435 jjdelcerro
            String actionlName = control.getName();
1356
            ActionInfo action = actionManager.getAction(actionlName);
1357 41314 jjdelcerro
            if ( action != null ) {
1358
                if ( control instanceof AbstractButton ) {
1359 40435 jjdelcerro
                    AbstractButton button = (AbstractButton) control;
1360 41314 jjdelcerro
                    if ( control instanceof javax.swing.JMenuItem ) {
1361
                        if ( action.getIconName() != null && action.getIconName().length() > 0 ) {
1362
                            if ( icontheme.exists(action.getIconName()) ) {
1363
                                button.setIcon(action.getIcon());
1364
                            }
1365
                        }
1366
                    } else {
1367
                        button.setIcon(action.getIcon());
1368
                    }
1369
                }
1370 40435 jjdelcerro
            }
1371
        }
1372 42548 dmartinezizquierdo
1373 40435 jjdelcerro
        enableControls();
1374 42165 fdiaz
        } finally {
1375
            refreshingControls = false;
1376
        }
1377 40435 jjdelcerro
    }
1378
1379
    public void message(String msg, int messageTyoe) {
1380 41314 jjdelcerro
        this.getStatusBar().message(msg, messageTyoe);
1381
    }
1382 40435 jjdelcerro
1383 41314 jjdelcerro
    /**
1384 40435 jjdelcerro
     * Establece la visibilidad de un menu y todos sus descendientes en la
1385
     * jerarquia teniendo en cuenta la visibilidad de todos los submenus.
1386 41314 jjdelcerro
     *
1387 40435 jjdelcerro
     * @param menu
1388 41314 jjdelcerro
     * Menu que se quiere visualizar
1389
     *
1390 40435 jjdelcerro
     * @return Devuelve true si el menu es visible y false en caso contrario
1391
     */
1392
    private boolean hideMenus(MenuElement menu) {
1393
        MenuElement[] submenus = menu.getSubElements();
1394
1395
        // Si no tiene hijos se devuelve su visibilidad
1396 41314 jjdelcerro
        if ( submenus.length == 0 ) {
1397 40435 jjdelcerro
            return menu.getComponent().isVisible();
1398
        }
1399
1400
        /*
1401 42350 jjdelcerro
         * Si tiene hijos se devuelve true si alg�no de ellos es visible,
1402 40435 jjdelcerro
         * pero se itera por todos ellos
1403
         */
1404
        boolean visible = false;
1405
1406 41314 jjdelcerro
        for ( int i = 0; i < submenus.length; i++ ) {
1407
            if ( hideMenus(submenus[i]) ) {
1408
                if ( !(menu instanceof JPopupMenu) ) {
1409 40435 jjdelcerro
                    menu.getComponent().setVisible(true);
1410
                }
1411
1412
                visible = true;
1413
            }
1414
        }
1415
1416 41314 jjdelcerro
        if ( visible ) {
1417 40435 jjdelcerro
            return true;
1418
        }
1419
1420
        menu.getComponent().setVisible(false);
1421
1422
        return false;
1423
    }
1424
1425
    /**
1426 41314 jjdelcerro
     *
1427 40435 jjdelcerro
     * Recurse through all menu elements and make sure there are no
1428
     * redundant separators.
1429
     * This method will make sure that a separator only becomes visible
1430
     * if at least one visible non-separator menu entry preceeded it.
1431 41314 jjdelcerro
     *
1432
     *
1433
     */
1434 40435 jjdelcerro
    private void hideSeparatorsAndMakeMnemonics(MenuElement menu,
1435 41314 jjdelcerro
            char[] mnemonics) {
1436 40435 jjdelcerro
        // flag that indicates whether a separator is to be displayed or not
1437
        boolean allowSeparator;
1438
1439
        allowSeparator = false; // separator not allowed as very first menu item
1440
        Component[] comps = ((JMenu) menu).getMenuComponents();
1441 41314 jjdelcerro
        if ( comps.length < 1 ) {
1442 40435 jjdelcerro
            // zero-length menu: skip
1443
            return;
1444
        }
1445
1446 41314 jjdelcerro
        for ( int i = 0; i < comps.length; i++ ) {
1447
            if ( comps[i] instanceof JSeparator ) {
1448 40435 jjdelcerro
                // got a separator: display only if allowed at this position
1449 41314 jjdelcerro
                if ( allowSeparator == true ) {
1450 40435 jjdelcerro
                    // look at all successive menu entries to make sure that at
1451
                    // least one
1452
                    // is visible and not a separator (otherwise, this separator
1453
                    // would
1454
                    // be the last visible item in this menu) -- we don't want
1455
                    // that
1456
                    comps[i].setVisible(false);
1457 41314 jjdelcerro
                    for ( int j = i; j < comps.length; j++ ) {
1458
                        if ( !(comps[j] instanceof JSeparator) ) {
1459
                            if ( comps[j].isVisible() ) {
1460 40435 jjdelcerro
                                comps[i].setVisible(true); // display separator!
1461
                                break;
1462
                            }
1463
                        }
1464
                    }
1465
                } else {
1466
                    comps[i].setVisible(false);
1467
                }
1468
                allowSeparator = false; // separator is not allowed right after
1469 41314 jjdelcerro
                // another separator
1470 40435 jjdelcerro
            } else {
1471 41314 jjdelcerro
                if ( comps[i] instanceof JMenu ) { // got a submenu: recurse
1472
                    // through it
1473 40435 jjdelcerro
                    // get number of submenu components
1474
                    Component[] scomps = ((JMenu) comps[i]).getMenuComponents();
1475
                    // make a new, fresh array to hold unique mnemonics for this
1476
                    // submenu
1477
                    char[] smnemonics = new char[scomps.length];
1478
                    hideSeparatorsAndMakeMnemonics(((MenuElement) comps[i]),
1479 41314 jjdelcerro
                            smnemonics);
1480
                    if ( comps[i].isVisible() ) {
1481 40435 jjdelcerro
                        allowSeparator = true; // separators are OK after
1482 41314 jjdelcerro
                        // visible submenus
1483 40435 jjdelcerro
                        // Set keyboard mnemonic for this submenu
1484
                        String text = ((JMenu) comps[i]).getText();
1485
                        char mnemonic = getMnemonic(text, mnemonics);
1486 41314 jjdelcerro
                        if ( ' ' != mnemonic ) {
1487 40435 jjdelcerro
                            ((JMenu) comps[i]).setMnemonic(mnemonic);
1488
                            mnemonics[i] = mnemonic;
1489
                        }
1490
                    }
1491
                } else {
1492 41314 jjdelcerro
                    if ( comps[i].isVisible() ) {
1493
                        if ( comps[i] instanceof JMenuItem ) {
1494 40435 jjdelcerro
                            // Set keyboard mnemonic for this menu item
1495
                            String text = ((JMenuItem) comps[i]).getText();
1496
                            char mnemonic = getMnemonic(text, mnemonics);
1497 41314 jjdelcerro
                            if ( ' ' != mnemonic ) {
1498 40435 jjdelcerro
                                ((JMenuItem) comps[i]).setMnemonic(mnemonic);
1499
                                mnemonics[i] = mnemonic;
1500
                            }
1501
                        }
1502
                        allowSeparator = true; // separators are OK after
1503 41314 jjdelcerro
                        // regular, visible entries
1504 40435 jjdelcerro
                    }
1505
                }
1506
            }
1507
        }
1508
    }
1509
1510
    /**
1511
     * Helper functios for assigning a unique mnemomic char from
1512
     * a pool of unassigned onces, stored in the array "mnemomnics"
1513
     */
1514
    private char getMnemonic(String text, char[] mnemonics) {
1515 41629 jjdelcerro
        if( text==null ) {
1516
            return ' ';
1517
        }
1518 40435 jjdelcerro
        Vector words = new Vector();
1519
        StringTokenizer t = new StringTokenizer(text);
1520
        int maxsize = 0;
1521
1522 41314 jjdelcerro
        while ( t.hasMoreTokens() ) {
1523 40435 jjdelcerro
            String word = t.nextToken();
1524 41314 jjdelcerro
            if ( word.length() > maxsize ) {
1525 40435 jjdelcerro
                maxsize = word.length();
1526
            }
1527
            words.addElement(word);
1528
        }
1529
        words.trimToSize();
1530
1531 41314 jjdelcerro
        for ( int i = 0; i < maxsize; ++i ) {
1532 40435 jjdelcerro
            char mnemonic = getMnemonic(words, mnemonics, i);
1533 41314 jjdelcerro
            if ( ' ' != mnemonic ) {
1534 40435 jjdelcerro
                return mnemonic;
1535
            }
1536
        }
1537
1538
        return ' ';
1539
    }
1540
1541
    private char getMnemonic(Vector words, char[] mnemonics, int index) {
1542
        int numwords = words.size();
1543
1544 41314 jjdelcerro
        for ( int i = 0; i < numwords; ++i ) {
1545 40435 jjdelcerro
            String word = (String) words.elementAt(i);
1546 41314 jjdelcerro
            if ( index >= word.length() ) {
1547 40435 jjdelcerro
                continue;
1548
            }
1549
1550
            char c = word.charAt(index);
1551 41314 jjdelcerro
            if ( !isMnemonicExists(c, mnemonics) ) {
1552 40435 jjdelcerro
                /* pick only valid chars */
1553 41314 jjdelcerro
                if ( (c != ':') && (c != '.') && (c != ',') && (c != ';')
1554
                        && (c != '-') && (c != '+') && (c != '/') && (c != '\\')
1555
                        && (c != '\'') && (c != '\"') && (c != ' ') && (c != '=')
1556
                        && (c != '(') && (c != ')') && (c != '[') && (c != ']')
1557
                        && (c != '{') && (c != '}') && (c != '$') && (c != '*')
1558
                        && (c != '&') && (c != '%') && (c != '!') && (c != '?')
1559
                        && (c != '#') && (c != '~') && (c != '_') ) {
1560 40435 jjdelcerro
                    return c;
1561
                }
1562
            }
1563
        }
1564
        return ' ';
1565
    }
1566
1567
    private boolean isMnemonicExists(char c, char[] mnemonics) {
1568
        int num = mnemonics.length;
1569 41314 jjdelcerro
        for ( int i = 0; i < num; ++i ) {
1570
            if ( mnemonics[i] == c ) {
1571 40435 jjdelcerro
                return true;
1572
            }
1573
        }
1574
        return false;
1575
    }
1576
1577
    /**
1578
     * Muestra la memoria consumida por el programa
1579
     */
1580
    private void showMemory() {
1581
        Runtime r = Runtime.getRuntime();
1582
        long mem = r.totalMemory() - r.freeMemory();
1583
        logger.debug(PluginServices.getText(this, "memory_usage") + " " + mem
1584 41314 jjdelcerro
                / 1024 + " KB");
1585 40435 jjdelcerro
    }
1586
1587
    public MDIManager getMDIManager() {
1588
        return mdiManager;
1589
    }
1590
1591
    public NewStatusBar getStatusBar() {
1592
        return bEstado;
1593
    }
1594
1595
    /**
1596
     * You can use this function to select the appropiate
1597
     * tool inside the toolbars
1598
     */
1599
    public void setSelectedTool(String actionCommand) {
1600
        setSelectedTool(defaultGroup, actionCommand);
1601
    }
1602
1603
    /**
1604
     * You can use this function to select the appropiate
1605
     * tool inside the toolbars
1606
     */
1607
    public void setSelectedTool(String groupName, String actionCommand) {
1608
        ButtonGroup group = (ButtonGroup) buttonGroupMap.get(groupName);
1609 41314 jjdelcerro
        if ( group == null ) {
1610 40435 jjdelcerro
            return;
1611
        }
1612
1613
        Enumeration enumeration = group.getElements();
1614 41314 jjdelcerro
        while ( enumeration.hasMoreElements() ) {
1615 40435 jjdelcerro
            AbstractButton button = (AbstractButton) enumeration.nextElement();
1616 41314 jjdelcerro
            if ( button.getActionCommand().equals(actionCommand) ) {
1617 40435 jjdelcerro
                button.setSelected(true);
1618
            }
1619
        }
1620
1621
        selectedTool.put(groupName, actionCommand);
1622
    }
1623
1624
    /**
1625
     * You can use this function to select the appropiate
1626
     * tool inside the toolbars
1627
     */
1628
    public void setSelectedTools(Map selectedTools) {
1629
        selectedTool = selectedTools;
1630 41314 jjdelcerro
        if ( selectedTools == null ) {
1631 40435 jjdelcerro
            return;
1632
        }
1633
        Iterator groupNames = selectedTools.keySet().iterator();
1634 41314 jjdelcerro
        while ( groupNames.hasNext() ) {
1635 40435 jjdelcerro
            try {
1636
                String groupName = (String) groupNames.next();
1637
                ButtonGroup group = (ButtonGroup) buttonGroupMap.get(groupName);
1638
                Enumeration enumeration = group.getElements();
1639
                String actionCommand = (String) selectedTools.get(groupName);
1640 41314 jjdelcerro
                if ( actionCommand == null ) {
1641 40435 jjdelcerro
                    continue;
1642
                }
1643 41314 jjdelcerro
                while ( enumeration.hasMoreElements() ) {
1644
                    AbstractButton button
1645
                            = (AbstractButton) enumeration.nextElement();
1646
                    if ( button.getActionCommand().equals(actionCommand) ) {
1647 40435 jjdelcerro
                        button.setSelected(true);
1648
                    }
1649
                }
1650
            } catch (ClassCastException ex) {
1651
                logger
1652 41314 jjdelcerro
                        .error("selectedTool should only contain pairs (String groupName, JToolBarToggleButton button)");
1653 40435 jjdelcerro
            }
1654
        }
1655
    }
1656
1657
    /**
1658
     * DOCUMENT ME!
1659 41314 jjdelcerro
     *
1660 40435 jjdelcerro
     * @param clase
1661
     * @param label
1662
     */
1663
    public void setStatusBarLabels(Class<?> clase, Label[] label) {
1664
        classLabels.put(clase, label);
1665
    }
1666
1667
    public void removeStatusBarLabels(Class<?> clase) {
1668
        classLabels.remove(clase);
1669
    }
1670
1671
    public void addStatusBarControl(Class<?> extensionClass, IControl control) {
1672
        control.addActionListener(this);
1673
        bEstado.addControl(control.getName(), (Component) control);
1674 41314 jjdelcerro
        if ( control instanceof JComponent ) {
1675
            addControl((JComponent) control);
1676 41334 jjdelcerro
            PluginsManager pluginsManager = PluginsLocator.getManager();
1677
            IExtension extension = pluginsManager.getExtension((Class<? extends IExtension>) extensionClass);
1678
            this.control2extensions.put((JComponent)control, extension);
1679 41314 jjdelcerro
        }
1680 40435 jjdelcerro
    }
1681 41314 jjdelcerro
1682 40435 jjdelcerro
    public void addToolBarControl(Class<?> extensionClass, JToolBar control, String name) {
1683
        toolBars.add(control);
1684 41314 jjdelcerro
        addControl(control);
1685 42161 fdiaz
1686 41334 jjdelcerro
        PluginsManager pluginsManager = PluginsLocator.getManager();
1687
        IExtension extension = pluginsManager.getExtension((Class<? extends IExtension>) extensionClass);
1688
        this.control2extensions.put(control, extension);
1689 40435 jjdelcerro
    }
1690
1691
    public void removeStatusBarControl(String name) {
1692
        Component c = bEstado.removeControl(name);
1693 41314 jjdelcerro
        if ( c instanceof JComponent ) {
1694
            removeControl((JComponent) c);
1695 40435 jjdelcerro
        }
1696
    }
1697
1698
    public void removeMenu(Menu menu) {
1699
        JMenuItem delete = (JMenuItem) infoCodedMenus.get(menu);
1700
1701 41314 jjdelcerro
        if ( delete == null ) {
1702 40435 jjdelcerro
            throw new NoSuchElementException(menu.getText());
1703
        }
1704
1705
        delete.getParent().remove(delete);
1706
        infoCodedMenus.remove(menu);
1707
    }
1708
1709
    public void addMenu(Menu menu, ActionListener listener,
1710 41314 jjdelcerro
            PluginClassLoader loader) {
1711 40435 jjdelcerro
        JMenu menuPadre = createMenuAncestors(menu, loader);
1712
1713 42350 jjdelcerro
        // Se registra y añaade el menu
1714 40435 jjdelcerro
        JMenuItem nuevoMenu = createJMenuItem(loader, menu);
1715
        nuevoMenu.addMouseListener(tooltipListener);
1716 41314 jjdelcerro
        if ( listener != null && menu.getName() != null && menu.getName().trim().length() > 0 ) {
1717
            ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1718
            final ActionInfo actionInfo = actionManager.getAction(menu.getName());
1719
            if ( actionInfo != null ) {
1720
                nuevoMenu.removeActionListener(actionInfo);
1721
            }
1722
            nuevoMenu.addActionListener(listener);
1723 40435 jjdelcerro
        } else {
1724
            /*
1725
             * We also add action listener for menu with
1726
             * no name but with text:
1727 42161 fdiaz
             *
1728 40435 jjdelcerro
             * Window/Project manager
1729
             * Window/View - 1
1730
             * Window/View - 2
1731
             * etc
1732
             */
1733 41314 jjdelcerro
            if ( listener != null && menu.getText() != null && menu.getText().trim().length() > 0 ) {
1734 40435 jjdelcerro
                nuevoMenu.addActionListener(listener);
1735
            }
1736 41314 jjdelcerro
1737 40435 jjdelcerro
        }
1738
        menuPadre.add(nuevoMenu);
1739
1740
        infoCodedMenus.put(menu, nuevoMenu);
1741
    }
1742
1743
    public void changeMenuName(String[] menu, String newName,
1744 41314 jjdelcerro
            PluginClassLoader loader) {
1745 40435 jjdelcerro
1746
        ArrayList menuList = new ArrayList();
1747 41314 jjdelcerro
        for ( int i = 0; i < menu.length; i++ ) {
1748 40435 jjdelcerro
            menuList.add(menu[i]);
1749
        }
1750
1751
        javax.swing.JMenuItem newMenu = getMenu(menuList, menuBar);
1752 41314 jjdelcerro
        if ( newMenu == null ) {
1753 40435 jjdelcerro
            throw new NoSuchMenuException(menu[0]);
1754
        } else {
1755
            newMenu.setText(PluginServices.getText(this, newName));
1756
        }
1757
    }
1758
1759
    public void componentHidden(ComponentEvent arg0) {
1760
    }
1761
1762
    public void componentMoved(ComponentEvent arg0) {
1763
    }
1764
1765
    public void componentResized(ComponentEvent arg0) {
1766
        ajustarToolBar();
1767
    }
1768
1769
    public void componentShown(ComponentEvent arg0) {
1770
    }
1771
1772
    public void componentAdded(ContainerEvent arg0) {
1773
        ajustarToolBar();
1774
    }
1775
1776
    public void componentRemoved(ContainerEvent arg0) {
1777
        ajustarToolBar();
1778
    }
1779
1780
    public class TooltipListener extends MouseAdapter {
1781
1782
        @Override
1783
        public void mouseEntered(MouseEvent e) {
1784
            JComponent control = (JComponent) e.getSource();
1785
            EnableTextSupport ets = (EnableTextSupport) e.getSource();
1786
1787
            String texto = null;
1788
            texto = control.getToolTipText();
1789
1790 41314 jjdelcerro
            if ( texto != null ) {
1791 40435 jjdelcerro
                bEstado.setInfoTextTemporal(texto);
1792
            }
1793
        }
1794
1795
        @Override
1796
        public void mouseExited(MouseEvent arg0) {
1797
            bEstado.restaurarTexto();
1798
        }
1799
1800
        @Override
1801
        public void mousePressed(MouseEvent e) {
1802
            bEstado.restaurarTexto();
1803
        }
1804
    }
1805
1806
    public String getTitlePrefix() {
1807
        return titlePrefix;
1808
    }
1809
1810
    public void setTitlePrefix(String titlePrefix) {
1811
        this.titlePrefix = titlePrefix;
1812
    }
1813
1814
    public Map getSelectedTools() {
1815
        return selectedTool;
1816
    }
1817
1818
    public HashMap getInitialSelectedTools() {
1819
        return initialSelectedTools;
1820
    }
1821
1822
    /**
1823 41314 jjdelcerro
     * Get a previously added JComponent by name.
1824
     * For example you can use it if you need to obtain a JToolBar to
1825 40435 jjdelcerro
     * add some customized component.
1826 41314 jjdelcerro
     *
1827 40435 jjdelcerro
     * @param name
1828
     * @return the JComponent or null if none has been found
1829
     */
1830
    public JComponent getComponentByName(String name) {
1831 41314 jjdelcerro
        Iterator e = controlsIterator();
1832 40435 jjdelcerro
1833 41314 jjdelcerro
        while ( e.hasNext() ) {
1834 40435 jjdelcerro
            JComponent control = (JComponent) e.next();
1835
            String nameCtrl = control.getName();
1836 41314 jjdelcerro
            if ( nameCtrl != null ) {
1837
                if ( nameCtrl.compareTo(name) == 0 ) {
1838 40435 jjdelcerro
                    return control;
1839
                }
1840
            }
1841
        }
1842
        Iterator it = toolBarMap.values().iterator();
1843 41314 jjdelcerro
        while ( it.hasNext() ) {
1844
            JComponent t = (JComponent) it.next();
1845 40435 jjdelcerro
            String nameCtrl = t.getName();
1846 41314 jjdelcerro
            if ( nameCtrl != null ) {
1847
                if ( nameCtrl.compareTo(name) == 0 ) {
1848 40435 jjdelcerro
                    return t;
1849
                }
1850
            }
1851
1852
        }
1853
1854
        return null;
1855
    }
1856
1857
    public SelectableToolBar[] getToolbars() {
1858
        return (SelectableToolBar[]) toolBarMap.values().toArray(
1859 41314 jjdelcerro
                new SelectableToolBar[0]);
1860 40435 jjdelcerro
    }
1861
1862
    public boolean getToolbarVisibility(String name) {
1863 41314 jjdelcerro
        JComponent component
1864
                = PluginServices.getMainFrame().getComponentByName(name);
1865
        if ( (component != null) && (component instanceof SelectableToolBar) ) {
1866 40435 jjdelcerro
            SelectableToolBar toolBar = (SelectableToolBar) component;
1867
            return toolBar.getAndamiVisibility();
1868
        }
1869
        return false;
1870
    }
1871
1872
    public boolean setToolbarVisibility(String name, boolean visibility) {
1873 41314 jjdelcerro
        JComponent component
1874
                = PluginServices.getMainFrame().getComponentByName(name);
1875
        if ( (component != null) && (component instanceof SelectableToolBar) ) {
1876 40435 jjdelcerro
            SelectableToolBar toolBar = (SelectableToolBar) component;
1877
            boolean oldVisibility = toolBar.getAndamiVisibility();
1878
            toolBar.setAndamiVisibility(visibility);
1879
            enableControls();
1880
            return oldVisibility;
1881
        }
1882
        return false;
1883
    }
1884
1885
    public javax.swing.JMenuItem getMenuEntry(String[] menuPath) {
1886
        ArrayList menu = new ArrayList();
1887 41314 jjdelcerro
        for ( int i = 0; i < menuPath.length; i++ ) {
1888 40435 jjdelcerro
            menu.add(menuPath[i]);
1889
        }
1890
        return getMenu(menu, menuBar);
1891
    }
1892
1893 41314 jjdelcerro
    public void messageDialog(String message, String title, int messageType) {
1894
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1895
        helper.messageDialog(message, title, messageType);
1896
    }
1897 40435 jjdelcerro
1898 41314 jjdelcerro
    public void messageDialog(String message, String[] messageArgs,
1899
            String title, int messageType) {
1900
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1901
        helper.messageDialog(message, messageArgs, title, messageType);
1902
    }
1903 40435 jjdelcerro
1904 41314 jjdelcerro
    public int confirmDialog(String message, String title, int optionType,
1905
            int messageType) {
1906
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1907
        return helper.confirmDialog(message, title, optionType, messageType);
1908
    }
1909 40435 jjdelcerro
1910 41314 jjdelcerro
    public String inputDialog(String message, String title, int messageType,
1911
            String initialValue) {
1912
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1913
        return helper.inputDialog(message, title, messageType, initialValue);
1914
    }
1915 40435 jjdelcerro
1916 41314 jjdelcerro
    public String inputDialog(String message, String title) {
1917
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1918
        return helper.inputDialog(message, title);
1919
    }
1920 40435 jjdelcerro
1921 41314 jjdelcerro
    public void showDialog(Component contents, String title) {
1922
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1923
        helper.showDialog(contents, title);
1924
    }
1925 40435 jjdelcerro
1926 41314 jjdelcerro
    public Component createComponent(Class<? extends Component> theClass,
1927
            Object... parameters) {
1928
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1929
        return helper.createComponentWithParams(theClass, parameters);
1930
    }
1931 40435 jjdelcerro
1932 41314 jjdelcerro
    public Component createComponentWithParams(
1933
            Class<? extends Component> theClass, Object[] parameters) {
1934
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1935
        return helper.createComponentWithParams(theClass, parameters);
1936
    }
1937 40435 jjdelcerro
1938 41314 jjdelcerro
    public File[] showChooserDialog(
1939
            final String title,
1940
            final int type, // SAVE_DIALOG / OPEN_DIALOG
1941
            final int selectionMode, //    JFileChooser.FILES_ONLY, JFileChooser.DIRECTORIES_ONLY, JFileChooser.FILES_AND_DIRECTORIES
1942
            final boolean multiselection,
1943
            final File initialPath,
1944
            final FileFilter filter,
1945
            final boolean fileHidingEnabled
1946
    ) {
1947
        DefaultThreadSafeDialogs helper = new DefaultThreadSafeDialogs(this, this.bEstado);
1948
        return helper.showChooserDialog(title, type, selectionMode, multiselection, initialPath, filter, fileHidingEnabled);
1949
    }
1950 40435 jjdelcerro
1951 41314 jjdelcerro
    public File[] showOpenDirectoryDialog(String title, File initialPath) {
1952
        return showChooserDialog(title, JFileChooser.OPEN_DIALOG, JFileChooser.DIRECTORIES_ONLY, false, initialPath, null, false);
1953
    }
1954 40435 jjdelcerro
1955 41314 jjdelcerro
    public File[] showOpenFileDialog(String title, File initialPath) {
1956
        return showChooserDialog(title, JFileChooser.OPEN_DIALOG, JFileChooser.FILES_ONLY, false, initialPath, null, false);
1957
    }
1958 40435 jjdelcerro
1959 41314 jjdelcerro
    public File[] showSaveFileDialog(String title, File initialPath) {
1960
        return showChooserDialog(title, JFileChooser.SAVE_DIALOG, JFileChooser.FILES_ONLY, false, initialPath, null, false);
1961
    }
1962
1963
    private void addControl(JComponent control) {
1964
        controls.add(control);
1965
    }
1966
1967
    private void removeControl(JComponent control) {
1968
        controls.remove(control);
1969
    }
1970
1971
    private Iterator<JComponent> controlsIterator() {
1972
        return this.controls.iterator();
1973
    }
1974
1975
    @Override
1976
    public void setLocale(Locale locale) {
1977
        super.setLocale(locale); //To change body of generated methods, choose Tools | Templates.
1978
        MDIManager mdiManager = MDIManagerFactory.createManager();
1979
        mdiManager.setLocale(locale);
1980
        if ( this.controls != null && !this.controls.isEmpty() ) {
1981
            this.refreshControls();
1982
        }
1983
    }
1984
1985 40435 jjdelcerro
}