1   /*
2    *  Copyright (c) 1998-2001, The University of Sheffield.
3    *
4    *  This file is part of GATE (see http://gate.ac.uk/), and is free
5    *  software, licenced under the GNU Library General Public License,
6    *  Version 2, June 1991 (in the distribution as file licence.html,
7    *  and also available at http://gate.ac.uk/gate/licence.html).
8    *
9    *  Valentin Tablan 22/01/2001
10   *
11   *  $Id: MainFrame.java,v 1.174 2002/11/27 15:13:33 valyt Exp $
12   *
13   */
14  
15  package gate.gui;
16  
17  import java.awt.*;
18  import java.awt.event.*;
19  import java.beans.*;
20  import java.io.*;
21  import java.net.*;
22  import java.text.*;
23  import java.util.*;
24  import java.util.List;
25  
26  import javax.swing.*;
27  import javax.swing.event.*;
28  import javax.swing.tree.*;
29  
30  //import guk.im.*;
31  /**needed in order to register the Ontology Editor Tool
32   * ontotext.bp*/
33  import com.ontotext.gate.vr.*;
34  import gate.*;
35  import gate.creole.*;
36  import gate.event.*;
37  import gate.persist.*;
38  import gate.security.*;
39  import gate.swing.*;
40  import gate.util.*;
41  import junit.framework.*;
42  
43  /**
44   * The main Gate GUI frame.
45   */
46  public class MainFrame extends JFrame
47                      implements ProgressListener, StatusListener, CreoleListener{
48  
49    JMenuBar menuBar;
50    JSplitPane mainSplit;
51    JSplitPane leftSplit;
52    Box southBox;
53    JLabel statusBar;
54    JProgressBar progressBar;
55    XJTabbedPane mainTabbedPane;
56    JScrollPane projectTreeScroll;
57    JScrollPane lowerScroll;
58  
59    JPopupMenu appsPopup;
60    JPopupMenu dssPopup;
61    JPopupMenu lrsPopup;
62    JPopupMenu prsPopup;
63  
64    /** used in popups */
65    JMenu newLrsPopupMenu;
66    JMenu newPrsPopupMenu;
67    JMenu newAppPopupMenu;
68  
69    /** used in menu bar */
70    JMenu newLrMenu;
71    JMenu newPrMenu;
72    JMenu newAppMenu;
73    JMenu loadANNIEMenu = null;
74    JButton stopBtnx;
75    Action stopActionx;
76  
77    JTree resourcesTree;
78    JScrollPane resourcesTreeScroll;
79    DefaultTreeModel resourcesTreeModel;
80    DefaultMutableTreeNode resourcesTreeRoot;
81    DefaultMutableTreeNode applicationsRoot;
82    DefaultMutableTreeNode languageResourcesRoot;
83    DefaultMutableTreeNode processingResourcesRoot;
84    DefaultMutableTreeNode datastoresRoot;
85  
86  
87  
88  
89    Splash splash;
90    LogArea logArea;
91    JScrollPane logScroll;
92    JToolBar toolbar;
93    static JFileChooser fileChooser;
94  
95    AppearanceDialog appearanceDialog;
96    OptionsDialog optionsDialog;
97    CartoonMinder animator;
98    TabHighlighter logHighlighter;
99    NewResourceDialog newResourceDialog;
100   WaitDialog waitDialog;
101 
102   NewDSAction newDSAction;
103   OpenDSAction openDSAction;
104   HelpAboutAction helpAboutAction;
105   NewAnnotDiffAction newAnnotDiffAction = null;
106   NewCorpusAnnotDiffAction newCorpusAnnotDiffAction = null;
107   NewBootStrapAction newBootStrapAction = null;
108   NewCorpusEvalAction newCorpusEvalAction = null;
109   GenerateStoredCorpusEvalAction generateStoredCorpusEvalAction = null;
110   StoredMarkedCorpusEvalAction storedMarkedCorpusEvalAction = null;
111   CleanMarkedCorpusEvalAction cleanMarkedCorpusEvalAction = null;
112   VerboseModeCorpusEvalToolAction verboseModeCorpusEvalToolAction = null;
113 //  DatastoreModeCorpusEvalToolAction datastoreModeCorpusEvalToolAction = null;
114 
115   /**ontology editor action
116    * ontotext.bp*/
117   NewOntologyEditorAction newOntologyEditorAction = null;
118 
119   NewGazetteerEditorAction  newGazetteerEditorAction = null;
120 
121 
122   /**
123    * Holds all the icons used in the Gate GUI indexed by filename.
124    * This is needed so we do not need to decode the icon everytime
125    * we need it as that would use unecessary CPU time and memory.
126    * Access to this data is avaialable through the {@link #getIcon(String)}
127    * method.
128    */
129   static Map iconByName = new HashMap();
130 
131   /**
132    * A Map which holds listeners that are singletons (e.g. the status listener
133    * that updates the status bar on the main frame or the progress listener that
134    * updates the progress bar on the main frame).
135    * The keys used are the class names of the listener interface and the values
136    * are the actual listeners (e.g "gate.event.StatusListener" -> this).
137    */
138   private static java.util.Map listeners = new HashMap();
139   protected static java.util.Collection guiRoots = new ArrayList();
140 
141   private static JDialog guiLock = null;
142 
143   static public Icon getIcon(String filename){
144     Icon result = (Icon)iconByName.get(filename);
145     if(result == null){
146       try{
147         result = new ImageIcon(new URL("gate:/img/" + filename));
148         iconByName.put(filename, result);
149       }catch(MalformedURLException mue){
150         mue.printStackTrace(Err.getPrintWriter());
151       }
152     }
153     return result;
154   }
155 
156 
157 /*
158   static public MainFrame getInstance(){
159     if(instance == null) instance = new MainFrame();
160     return instance;
161   }
162 */
163 
164   static public JFileChooser getFileChooser(){
165     return fileChooser;
166   }
167 
168 
169   /**
170    * Selects a resource if loaded in the system and not invisible.
171    * @param res the resource to be selected.
172    */
173   public void select(Resource res){
174     //first find the handle for the resource
175     Handle handle = null;
176     //go through all the nodes
177     Enumeration nodesEnum = resourcesTreeRoot.breadthFirstEnumeration();
178     while(nodesEnum.hasMoreElements() && handle == null){
179       Object node = nodesEnum.nextElement();
180       if(node instanceof DefaultMutableTreeNode){
181         DefaultMutableTreeNode dmtNode = (DefaultMutableTreeNode)node;
182         if(dmtNode.getUserObject() instanceof Handle){
183           if(((Handle)dmtNode.getUserObject()).getTarget() == res){
184             handle = (Handle)dmtNode.getUserObject();
185           }
186         }
187       }
188     }
189 
190     //now select the handle if found
191     if(handle != null) select(handle);
192   }
193 
194   protected void select(Handle handle){
195     if(mainTabbedPane.indexOfComponent(handle.getLargeView()) != -1) {
196       //select
197       JComponent largeView = handle.getLargeView();
198       if(largeView != null) {
199         mainTabbedPane.setSelectedComponent(largeView);
200       }
201       JComponent smallView = handle.getSmallView();
202       if(smallView != null) {
203         lowerScroll.getViewport().setView(smallView);
204       } else {
205         lowerScroll.getViewport().setView(null);
206       }
207     } else {
208       //show
209       JComponent largeView = handle.getLargeView();
210       if(largeView != null) {
211         mainTabbedPane.addTab(handle.getTitle(), handle.getIcon(),
212                               largeView, handle.getTooltipText());
213         mainTabbedPane.setSelectedComponent(handle.getLargeView());
214       }
215       JComponent smallView = handle.getSmallView();
216       if(smallView != null) {
217         lowerScroll.getViewport().setView(smallView);
218       } else {
219         lowerScroll.getViewport().setView(null);
220       }
221     }
222   }//protected void select(ResourceHandle handle)
223 
224   public MainFrame() {
225     this(false);
226   } // MainFrame
227 
228   /**Construct the frame*/
229   public MainFrame(boolean isShellSlacGIU) {
230     guiRoots.add(this);
231     if(fileChooser == null){
232       fileChooser = new JFileChooser();
233       fileChooser.setMultiSelectionEnabled(false);
234       guiRoots.add(fileChooser);
235 
236       //the JFileChooser seems to size itself better once it's been added to a
237       //top level container such as a dialog.
238       JDialog dialog = new JDialog(this, "", true);
239       java.awt.Container contentPane = dialog.getContentPane();
240       contentPane.setLayout(new BorderLayout());
241       contentPane.add(fileChooser, BorderLayout.CENTER);
242       dialog.pack();
243       dialog.getContentPane().removeAll();
244       dialog.dispose();
245       dialog = null;
246     }
247     enableEvents(AWTEvent.WINDOW_EVENT_MASK);
248     initLocalData(isShellSlacGIU);
249     initGuiComponents(isShellSlacGIU);
250     initListeners(isShellSlacGIU);
251   } // MainFrame(boolean simple)
252 
253   protected void initLocalData(boolean isShellSlacGIU){
254     resourcesTreeRoot = new DefaultMutableTreeNode("Gate", true);
255     applicationsRoot = new DefaultMutableTreeNode("Applications", true);
256     if(isShellSlacGIU) {
257       languageResourcesRoot = new DefaultMutableTreeNode("Documents",
258                                                        true);
259     } else {
260       languageResourcesRoot = new DefaultMutableTreeNode("Language Resources",
261                                                        true);
262     } // if
263     processingResourcesRoot = new DefaultMutableTreeNode("Processing Resources",
264                                                          true);
265     datastoresRoot = new DefaultMutableTreeNode("Data stores", true);
266     resourcesTreeRoot.add(applicationsRoot);
267     resourcesTreeRoot.add(languageResourcesRoot);
268     resourcesTreeRoot.add(processingResourcesRoot);
269     resourcesTreeRoot.add(datastoresRoot);
270 
271     resourcesTreeModel = new ResourcesTreeModel(resourcesTreeRoot, true);
272 
273     newDSAction = new NewDSAction();
274     openDSAction = new OpenDSAction();
275     helpAboutAction = new HelpAboutAction();
276     newAnnotDiffAction = new NewAnnotDiffAction();
277     newCorpusAnnotDiffAction = new NewCorpusAnnotDiffAction();
278     newBootStrapAction = new NewBootStrapAction();
279     newCorpusEvalAction = new NewCorpusEvalAction();
280     storedMarkedCorpusEvalAction = new StoredMarkedCorpusEvalAction();
281     generateStoredCorpusEvalAction = new GenerateStoredCorpusEvalAction();
282     cleanMarkedCorpusEvalAction = new CleanMarkedCorpusEvalAction();
283     verboseModeCorpusEvalToolAction = new VerboseModeCorpusEvalToolAction();
284 //    datastoreModeCorpusEvalToolAction = new DatastoreModeCorpusEvalToolAction();
285 
286     /*ontology editor action initialization
287     ontotext.bp*/
288     newOntologyEditorAction = new NewOntologyEditorAction();
289 
290     newGazetteerEditorAction = new NewGazetteerEditorAction();
291 
292   }
293 
294   protected void initGuiComponents(boolean isShellSlacGIU){
295     this.getContentPane().setLayout(new BorderLayout());
296 
297     Integer width =Gate.getUserConfig().getInt(GateConstants.MAIN_FRAME_WIDTH);
298     Integer height =Gate.getUserConfig().getInt(GateConstants.MAIN_FRAME_HEIGHT);
299     this.setSize(new Dimension(width == null ? 800 : width.intValue(),
300                                height == null ? 600 : height.intValue()));
301 
302     try{
303       this.setIconImage(Toolkit.getDefaultToolkit().getImage(
304             new URL("gate:/img/gateIcon.gif")));
305     }catch(MalformedURLException mue){
306       mue.printStackTrace(Err.getPrintWriter());
307     }
308     resourcesTree = new JTree(resourcesTreeModel){
309       public void updateUI(){
310         super.updateUI();
311         setRowHeight(0);
312       }
313     };
314 
315     resourcesTree.setEditable(true);
316     ResourcesTreeCellRenderer treeCellRenderer =
317                               new ResourcesTreeCellRenderer();
318     resourcesTree.setCellRenderer(treeCellRenderer);
319     resourcesTree.setCellEditor(new ResourcesTreeCellEditor(resourcesTree,
320                                                           treeCellRenderer));
321 
322     resourcesTree.setRowHeight(0);
323     //expand all nodes
324     resourcesTree.expandRow(0);
325     resourcesTree.expandRow(1);
326     resourcesTree.expandRow(2);
327     resourcesTree.expandRow(3);
328     resourcesTree.expandRow(4);
329     resourcesTree.getSelectionModel().
330                   setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION
331                                    );
332     resourcesTree.setEnabled(true);
333     ToolTipManager.sharedInstance().registerComponent(resourcesTree);
334     resourcesTreeScroll = new JScrollPane(resourcesTree);
335 
336     lowerScroll = new JScrollPane();
337     JPanel lowerPane = new JPanel();
338     lowerPane.setLayout(new OverlayLayout(lowerPane));
339 
340     JPanel animationPane = new JPanel();
341     animationPane.setOpaque(false);
342     animationPane.setLayout(new BoxLayout(animationPane, BoxLayout.X_AXIS));
343 
344     JPanel vBox = new JPanel();
345     vBox.setLayout(new BoxLayout(vBox, BoxLayout.Y_AXIS));
346     vBox.setOpaque(false);
347 
348     JPanel hBox = new JPanel();
349     hBox.setLayout(new BoxLayout(hBox, BoxLayout.X_AXIS));
350     hBox.setOpaque(false);
351 
352     vBox.add(Box.createVerticalGlue());
353     vBox.add(animationPane);
354 
355     hBox.add(vBox);
356     hBox.add(Box.createHorizontalGlue());
357 
358     lowerPane.add(hBox);
359     lowerPane.add(lowerScroll);
360 
361     animator = new CartoonMinder(animationPane);
362     Thread thread = new Thread(Thread.currentThread().getThreadGroup(),
363                                animator,
364                                "MainFrame1");
365     thread.setPriority(Thread.MIN_PRIORITY);
366     thread.start();
367 
368     leftSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
369                                resourcesTreeScroll, lowerPane);
370 
371     leftSplit.setResizeWeight((double)0.7);
372 
373     // Create a new logArea and redirect the Out and Err output to it.
374     logArea = new LogArea();
375     logScroll = new JScrollPane(logArea);
376     // Out has been redirected to the logArea
377     Out.prln("Gate 2 started at: " + new Date().toString());
378     mainTabbedPane = new XJTabbedPane(JTabbedPane.TOP);
379     mainTabbedPane.insertTab("Messages",null, logScroll, "Gate log", 0);
380 
381     logHighlighter = new TabHighlighter(mainTabbedPane, logScroll, Color.red);
382 
383 
384     mainSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
385                                leftSplit, mainTabbedPane);
386 
387     mainSplit.setDividerLocation(leftSplit.getPreferredSize().width + 10);
388     this.getContentPane().add(mainSplit, BorderLayout.CENTER);
389 
390     southBox = Box.createHorizontalBox();
391     southBox.add(Box.createHorizontalStrut(5));
392 
393     statusBar = new JLabel();
394 
395     UIManager.put("ProgressBar.cellSpacing", new Integer(0));
396     progressBar = new JProgressBar(JProgressBar.HORIZONTAL){
397       public Dimension getPreferredSize(){
398         Dimension pSize = super.getPreferredSize();
399         pSize.height = 5;
400         return pSize;
401       }
402     };
403     progressBar.setBorder(BorderFactory.createEmptyBorder());
404     progressBar.setForeground(new Color(150, 75, 150));
405     progressBar.setBorderPainted(false);
406     progressBar.setStringPainted(false);
407     progressBar.setOrientation(JProgressBar.HORIZONTAL);
408     progressBar.setMaximumSize(new Dimension(Integer.MAX_VALUE, 5));
409 
410     Box sbBox = Box.createHorizontalBox();
411     sbBox.add(statusBar);
412     sbBox.add(new JLabel(" "));
413     sbBox.add(Box.createHorizontalGlue());
414     Box tempVBox = Box.createVerticalBox();
415     tempVBox.add(sbBox);
416     tempVBox.add(progressBar);
417 //    stopBtn = new JButton(stopAction);
418 //    stopBtn.setBorder(  BorderFactory.createLineBorder(Color.black, 1));BorderFactory.createEtchedBorder()
419 //    stopBtn.setBorder(BorderFactory.createCompoundBorder(
420 //                                    BorderFactory.createEmptyBorder(2,3,2,3),
421 //                                    BorderFactory.createLineBorder(Color.black,
422 //                                                                   1)));
423 //    stopBtn.setForeground(Color.red);
424 
425 //    southBox.add(Box.createRigidArea(
426 //                     new Dimension(5, stopBtn.getPreferredSize().height)));
427     southBox.add(tempVBox);
428     southBox.add(Box.createHorizontalStrut(5));
429 
430     this.getContentPane().add(southBox, BorderLayout.SOUTH);
431 
432     //TOOLBAR
433     toolbar = new JToolBar(JToolBar.HORIZONTAL);
434     toolbar.setFloatable(false);
435     //toolbar.add(new JGateButton(newProjectAction));
436 
437 
438     this.getContentPane().add(toolbar, BorderLayout.NORTH);
439 
440     //extra stuff
441     newResourceDialog = new NewResourceDialog(
442       this, "Resource parameters", true
443     );
444     waitDialog = new WaitDialog(this, "");
445     //build the Help->About dialog
446     JPanel splashBox = new JPanel();
447     splashBox.setLayout(new BoxLayout(splashBox, BoxLayout.Y_AXIS));
448     splashBox.setBackground(Color.white);
449 
450     JLabel gifLbl = new JLabel(getIcon("gateSplash.gif"));
451     Box box = new Box(BoxLayout.X_AXIS);
452     box.add(Box.createHorizontalGlue());
453     box.add(gifLbl);
454     box.add(Box.createHorizontalGlue());
455     splashBox.add(box);
456 
457     gifLbl = new JLabel(getIcon("gateHeader.gif"));
458     box = new Box(BoxLayout.X_AXIS);
459     box.add(gifLbl);
460     box.add(Box.createHorizontalGlue());
461     splashBox.add(box);
462     splashBox.add(Box.createVerticalStrut(10));
463 
464     JLabel verLbl = new JLabel(
465       "<HTML><FONT color=\"blue\">Version <B>"
466       + Main.version + "</B></FONT>" +
467       ", <FONT color=\"red\">build <B>" + Main.build + "</B></FONT></HTML>"
468     );
469     box = new Box(BoxLayout.X_AXIS);
470     box.add(Box.createHorizontalGlue());
471     box.add(verLbl);
472 
473     splashBox.add(box);
474     splashBox.add(Box.createVerticalStrut(10));
475 
476     verLbl = new JLabel(
477 "<HTML>" +
478 "<B>Hamish Cunningham, Valentin Tablan, Kalina Bontcheva, Diana Maynard,</B>" +
479 "<BR>Cristian Ursu, Marin Dimitrov, Oana Hamza, Horacio Saggion," +
480 "<BR>Atanas Kiryakov, Angel Kirilov, Bobby Popov, Damyan Ognyanoff," +
481 "<BR>Robert Gaizauskas, Mark Hepple, Mark Leisher, " +
482 "Kevin Humphreys, Yorick Wilks." +
483 "<P><B>JVM version</B>: " + System.getProperty("java.version") +
484 " from " + System.getProperty("java.vendor")
485     );
486     box = new Box(BoxLayout.X_AXIS);
487     box.add(verLbl);
488     box.add(Box.createHorizontalGlue());
489 
490     splashBox.add(box);
491 
492     JButton okBtn = new JButton("OK");
493     okBtn.addActionListener(new ActionListener() {
494       public void actionPerformed(ActionEvent e) {
495         splash.hide();
496       }
497     });
498     okBtn.setBackground(Color.white);
499     box = new Box(BoxLayout.X_AXIS);
500     box.add(Box.createHorizontalGlue());
501     box.add(okBtn);
502     box.add(Box.createHorizontalGlue());
503 
504     splashBox.add(Box.createVerticalStrut(10));
505     splashBox.add(box);
506     splashBox.add(Box.createVerticalStrut(10));
507     splash = new Splash(this, splashBox);
508 
509 
510     //MENUS
511     menuBar = new JMenuBar();
512 
513 
514     JMenu fileMenu = new JMenu("File");
515 
516     newLrMenu = new JMenu("New language resource");
517     fileMenu.add(newLrMenu);
518     newPrMenu = new JMenu("New processing resource");
519     fileMenu.add(newPrMenu);
520 
521     newAppMenu = new JMenu("New application");
522     fileMenu.add(newAppMenu);
523 
524     fileMenu.addSeparator();
525     fileMenu.add(new XJMenuItem(new LoadResourceFromFileAction(), this));
526 
527     fileMenu.addSeparator();
528     fileMenu.add(new XJMenuItem(newDSAction, this));
529     fileMenu.add(new XJMenuItem(openDSAction, this));
530     fileMenu.addSeparator();
531     loadANNIEMenu = new JMenu("Load ANNIE system");
532     fileMenu.add(loadANNIEMenu);
533     fileMenu.add(new XJMenuItem(new LoadCreoleRepositoryAction(), this));
534     fileMenu.addSeparator();
535 
536     fileMenu.add(new XJMenuItem(new ExitGateAction(), this));
537     menuBar.add(fileMenu);
538 
539 
540 
541     JMenu optionsMenu = new JMenu("Options");
542 
543     optionsDialog = new OptionsDialog(MainFrame.this);
544     optionsMenu.add(new XJMenuItem(new AbstractAction("Configuration"){
545       {
546         putValue(SHORT_DESCRIPTION, "Edit gate options");
547       }
548       public void actionPerformed(ActionEvent evt){
549         optionsDialog.show();
550       }
551     }, this));
552 
553 
554     JMenu imMenu = null;
555     List installedLocales = new ArrayList();
556     try{
557       //if this fails guk is not present
558       Class.forName("guk.im.GateIMDescriptor");
559       //add the Gate input methods
560       installedLocales.addAll(Arrays.asList(new guk.im.GateIMDescriptor().
561                                             getAvailableLocales()));
562     }catch(Exception e){
563       //something happened; most probably guk not present.
564       //just drop it, is not vital.
565     }
566     try{
567       //add the MPI IMs
568       //if this fails mpi IM is not present
569       Class.forName("mpi.alt.java.awt.im.spi.lookup.LookupDescriptor");
570 
571       installedLocales.addAll(Arrays.asList(
572             new mpi.alt.java.awt.im.spi.lookup.LookupDescriptor().
573             getAvailableLocales()));
574     }catch(Exception e){
575       //something happened; most probably MPI not present.
576       //just drop it, is not vital.
577     }
578 
579     Collections.sort(installedLocales, new Comparator(){
580       public int compare(Object o1, Object o2){
581         return ((Locale)o1).getDisplayName().compareTo(((Locale)o2).getDisplayName());
582       }
583     });
584     JMenuItem item;
585     if(!installedLocales.isEmpty()){
586       imMenu = new JMenu("Input methods");
587       ButtonGroup bg = new ButtonGroup();
588       item = new LocaleSelectorMenuItem();
589       imMenu.add(item);
590       item.setSelected(true);
591       imMenu.addSeparator();
592       bg.add(item);
593       for(int i = 0; i < installedLocales.size(); i++){
594         Locale locale = (Locale)installedLocales.get(i);
595         item = new LocaleSelectorMenuItem(locale);
596         imMenu.add(item);
597         bg.add(item);
598       }
599     }
600     if(imMenu != null) optionsMenu.add(imMenu);
601 
602     menuBar.add(optionsMenu);
603 
604     JMenu toolsMenu = new JMenu("Tools");
605     toolsMenu.add(newAnnotDiffAction);
606     toolsMenu.add(newCorpusAnnotDiffAction);
607     toolsMenu.add(newBootStrapAction);
608     //temporarily disabled till the evaluation tools are made to run within
609     //the GUI
610     JMenu corpusEvalMenu = new JMenu("Corpus Benchmark Tools");
611     toolsMenu.add(corpusEvalMenu);
612     corpusEvalMenu.add(newCorpusEvalAction);
613     corpusEvalMenu.addSeparator();
614     corpusEvalMenu.add(generateStoredCorpusEvalAction);
615     corpusEvalMenu.addSeparator();
616     corpusEvalMenu.add(storedMarkedCorpusEvalAction);
617     corpusEvalMenu.add(cleanMarkedCorpusEvalAction);
618     corpusEvalMenu.addSeparator();
619     JCheckBoxMenuItem verboseModeItem =
620       new JCheckBoxMenuItem(verboseModeCorpusEvalToolAction);
621     corpusEvalMenu.add(verboseModeItem);
622 //    JCheckBoxMenuItem datastoreModeItem =
623 //      new JCheckBoxMenuItem(datastoreModeCorpusEvalToolAction);
624 //    corpusEvalMenu.add(datastoreModeItem);
625     toolsMenu.add(
626       new AbstractAction("Unicode editor", getIcon("unicode.gif")){
627       public void actionPerformed(ActionEvent evt){
628         new guk.Editor();
629       }
630     });
631 
632     /*add the ontology editor to the tools menu
633     ontotext.bp */
634     toolsMenu.add(newOntologyEditorAction);
635 
636     menuBar.add(toolsMenu);
637 
638     JMenu helpMenu = new JMenu("Help");
639 //    helpMenu.add(new HelpUserGuideAction());
640     helpMenu.add(helpAboutAction);
641     menuBar.add(helpMenu);
642 
643     this.setJMenuBar(menuBar);
644 
645     //popups
646     newAppPopupMenu = new JMenu("New");
647     appsPopup = new JPopupMenu();
648     appsPopup.add(newAppPopupMenu);
649     appsPopup.addSeparator();
650     appsPopup.add(new XJMenuItem(new LoadResourceFromFileAction(), this));
651     guiRoots.add(newAppPopupMenu);
652     guiRoots.add(appsPopup);
653 
654     newLrsPopupMenu = new JMenu("New");
655     lrsPopup = new JPopupMenu();
656     lrsPopup.add(newLrsPopupMenu);
657     guiRoots.add(lrsPopup);
658     guiRoots.add(newLrsPopupMenu);
659 
660     newPrsPopupMenu = new JMenu("New");
661     prsPopup = new JPopupMenu();
662     prsPopup.add(newPrsPopupMenu);
663     guiRoots.add(newPrsPopupMenu);
664     guiRoots.add(prsPopup);
665 
666     dssPopup = new JPopupMenu();
667     dssPopup.add(newDSAction);
668     dssPopup.add(openDSAction);
669     guiRoots.add(dssPopup);
670   }
671 
672   protected void initListeners(boolean isShellSlacGIU){
673     Gate.getCreoleRegister().addCreoleListener(this);
674 
675     resourcesTree.addMouseListener(new MouseAdapter() {
676       public void mouseClicked(MouseEvent e) {
677         //where inside the tree?
678         int x = e.getX();
679         int y = e.getY();
680         TreePath path = resourcesTree.getPathForLocation(x, y);
681         JPopupMenu popup = null;
682         Handle handle = null;
683         if(path != null){
684           Object value = path.getLastPathComponent();
685           if(value == resourcesTreeRoot){
686           } else if(value == applicationsRoot){
687             popup = appsPopup;
688           } else if(value == languageResourcesRoot){
689             popup = lrsPopup;
690           } else if(value == processingResourcesRoot){
691             popup = prsPopup;
692           } else if(value == datastoresRoot){
693             popup = dssPopup;
694           }else{
695             value = ((DefaultMutableTreeNode)value).getUserObject();
696             if(value instanceof Handle){
697               handle = (Handle)value;
698               popup = handle.getPopup();
699             }
700           }
701         }
702         if (SwingUtilities.isRightMouseButton(e)) {
703           if(resourcesTree.getSelectionCount() > 1){
704             //multiple selection in tree-> show a popup for delete all
705             popup = new JPopupMenu();
706             popup.add(new XJMenuItem(new CloseSelectedResourcesAction(),
707                       MainFrame.this));
708             popup.show(resourcesTree, e.getX(), e.getY());
709           }else if(popup != null){
710             if(handle != null){
711               // Create a CloseViewAction and a menu item based on it
712               CloseViewAction cva = new CloseViewAction(handle);
713               XJMenuItem menuItem = new XJMenuItem(cva, MainFrame.this);
714               // Add an accelerator ATL+F4 for this action
715               menuItem.setAccelerator(
716                     KeyStroke.getKeyStroke(KeyEvent.VK_H,
717                                            ActionEvent.CTRL_MASK));
718               popup.insert(menuItem, 1);
719               popup.insert(new JPopupMenu.Separator(), 2);
720 
721               popup.insert(new XJMenuItem(new RenameResourceAction(path),
722                                           MainFrame.this), 3);
723 
724               // Put the action command in the component's action map
725               if (handle.getLargeView() != null){
726                 handle.getLargeView().getActionMap().
727                                       put("Hide current view",cva);
728               }
729             }
730 
731 
732             popup.show(resourcesTree, e.getX(), e.getY());
733           }
734         } else if(SwingUtilities.isLeftMouseButton(e)) {
735           if(e.getClickCount() == 2 && handle != null) {
736             //double click - show the resource
737             select(handle);
738           }
739         }
740       }
741 
742       public void mousePressed(MouseEvent e) {
743       }
744 
745       public void mouseReleased(MouseEvent e) {
746       }
747 
748       public void mouseEntered(MouseEvent e) {
749       }
750 
751       public void mouseExited(MouseEvent e) {
752       }
753     });
754 
755     // Add the keyboard listeners for CTRL+F4 and ALT+F4
756     this.addKeyListener(new KeyAdapter() {
757       public void keyTyped(KeyEvent e) {
758       }
759 
760       public void keyPressed(KeyEvent e) {
761         // If Ctrl+F4 was pressed then close the active resource
762         if (e.isControlDown() && e.getKeyCode()==KeyEvent.VK_F4){
763           JComponent resource = (JComponent)
764                                         mainTabbedPane.getSelectedComponent();
765           if (resource != null){
766             Action act = resource.getActionMap().get("Close resource");
767             if (act != null)
768               act.actionPerformed(null);
769           }// End if
770         }// End if
771         // If CTRL+H was pressed then hide the active view.
772         if (e.isControlDown() && e.getKeyCode()==KeyEvent.VK_H){
773           JComponent resource = (JComponent)
774                                         mainTabbedPane.getSelectedComponent();
775           if (resource != null){
776             Action act = resource.getActionMap().get("Hide current view");
777             if (act != null)
778               act.actionPerformed(null);
779           }// End if
780         }// End if
781         // If CTRL+X was pressed then save as XML
782         if (e.isControlDown() && e.getKeyCode()==KeyEvent.VK_X){
783           JComponent resource = (JComponent)
784                                         mainTabbedPane.getSelectedComponent();
785           if (resource != null){
786             Action act = resource.getActionMap().get("Save As XML");
787             if (act != null)
788               act.actionPerformed(null);
789           }// End if
790         }// End if
791       }// End keyPressed();
792 
793       public void keyReleased(KeyEvent e) {
794       }
795     });
796 
797     mainTabbedPane.getModel().addChangeListener(new ChangeListener() {
798       public void stateChanged(ChangeEvent e) {
799         JComponent largeView = (JComponent)mainTabbedPane.getSelectedComponent();
800         Enumeration nodesEnum = resourcesTreeRoot.preorderEnumeration();
801         boolean done = false;
802         DefaultMutableTreeNode node = resourcesTreeRoot;
803         while(!done && nodesEnum.hasMoreElements()){
804           node = (DefaultMutableTreeNode)nodesEnum.nextElement();
805           done = node.getUserObject() instanceof Handle &&
806                  ((Handle)node.getUserObject()).getLargeView()
807                   == largeView;
808         }
809         if(done){
810           select((Handle)node.getUserObject());
811         }else{
812           //the selected item is not a resource (maybe the log area?)
813           lowerScroll.getViewport().setView(null);
814         }
815       }
816     });
817 
818     mainTabbedPane.addMouseListener(new MouseAdapter() {
819       public void mouseClicked(MouseEvent e) {
820         if(SwingUtilities.isRightMouseButton(e)){
821           int index = mainTabbedPane.getIndexAt(e.getPoint());
822           if(index != -1){
823             JComponent view = (JComponent)mainTabbedPane.getComponentAt(index);
824             Enumeration nodesEnum = resourcesTreeRoot.preorderEnumeration();
825             boolean done = false;
826             DefaultMutableTreeNode node = resourcesTreeRoot;
827             while(!done && nodesEnum.hasMoreElements()){
828               node = (DefaultMutableTreeNode)nodesEnum.nextElement();
829               done = node.getUserObject() instanceof Handle &&
830                      ((Handle)node.getUserObject()).getLargeView()
831                       == view;
832             }
833             if(done){
834               Handle handle = (Handle)node.getUserObject();
835               JPopupMenu popup = handle.getPopup();
836               popup.show(mainTabbedPane, e.getX(), e.getY());
837             }
838           }
839         }
840       }
841 
842       public void mousePressed(MouseEvent e) {
843       }
844 
845       public void mouseReleased(MouseEvent e) {
846       }
847 
848       public void mouseEntered(MouseEvent e) {
849       }
850 
851       public void mouseExited(MouseEvent e) {
852       }
853     });
854 
855     addComponentListener(new ComponentAdapter() {
856       public void componentHidden(ComponentEvent e) {
857 
858       }
859 
860       public void componentMoved(ComponentEvent e) {
861       }
862 
863       public void componentResized(ComponentEvent e) {
864       }
865 
866       public void componentShown(ComponentEvent e) {
867         leftSplit.setDividerLocation((double)0.7);
868       }
869     });
870 
871     if(isShellSlacGIU) {
872       mainSplit.setDividerSize(0);
873       mainSplit.getTopComponent().setVisible(false);
874       mainSplit.getTopComponent().addComponentListener(new ComponentAdapter() {
875         public void componentHidden(ComponentEvent e) {
876         }
877         public void componentMoved(ComponentEvent e) {
878           mainSplit.setDividerLocation(0);
879         }
880         public void componentResized(ComponentEvent e) {
881           mainSplit.setDividerLocation(0);
882         }
883         public void componentShown(ComponentEvent e) {
884           mainSplit.setDividerLocation(0);
885         }
886       });
887     } // if
888 
889     //blink the messages tab when new information is displayed
890     logArea.getDocument().addDocumentListener(new javax.swing.event.DocumentListener(){
891       public void insertUpdate(javax.swing.event.DocumentEvent e){
892         changeOccured();
893       }
894       public void removeUpdate(javax.swing.event.DocumentEvent e){
895         changeOccured();
896       }
897       public void changedUpdate(javax.swing.event.DocumentEvent e){
898         changeOccured();
899       }
900       protected void changeOccured(){
901         logHighlighter.highlight();
902       }
903     });
904 
905     logArea.addPropertyChangeListener("document", new PropertyChangeListener(){
906       public void propertyChange(PropertyChangeEvent evt){
907         //add the document listener
908         logArea.getDocument().addDocumentListener(new javax.swing.event.DocumentListener(){
909           public void insertUpdate(javax.swing.event.DocumentEvent e){
910             changeOccured();
911           }
912           public void removeUpdate(javax.swing.event.DocumentEvent e){
913             changeOccured();
914           }
915           public void changedUpdate(javax.swing.event.DocumentEvent e){
916             changeOccured();
917           }
918           protected void changeOccured(){
919             logHighlighter.highlight();
920           }
921         });
922       }
923     });
924 
925     newLrMenu.addMenuListener(new MenuListener() {
926       public void menuCanceled(MenuEvent e) {
927       }
928       public void menuDeselected(MenuEvent e) {
929       }
930       public void menuSelected(MenuEvent e) {
931         newLrMenu.removeAll();
932         //find out the available types of LRs and repopulate the menu
933         CreoleRegister reg = Gate.getCreoleRegister();
934         List lrTypes = reg.getPublicLrTypes();
935         if(lrTypes != null && !lrTypes.isEmpty()){
936           HashMap resourcesByName = new HashMap();
937           Iterator lrIter = lrTypes.iterator();
938           while(lrIter.hasNext()){
939             ResourceData rData = (ResourceData)reg.get(lrIter.next());
940             resourcesByName.put(rData.getName(), rData);
941           }
942           List lrNames = new ArrayList(resourcesByName.keySet());
943           Collections.sort(lrNames);
944           lrIter = lrNames.iterator();
945           while(lrIter.hasNext()){
946             ResourceData rData = (ResourceData)resourcesByName.
947                                  get(lrIter.next());
948             newLrMenu.add(new XJMenuItem(new NewResourceAction(rData),
949                                          MainFrame.this));
950           }
951         }
952       }
953     });
954 
955     newPrMenu.addMenuListener(new MenuListener() {
956       public void menuCanceled(MenuEvent e) {
957       }
958       public void menuDeselected(MenuEvent e) {
959       }
960       public void menuSelected(MenuEvent e) {
961         newPrMenu.removeAll();
962         //find out the available types of LRs and repopulate the menu
963         CreoleRegister reg = Gate.getCreoleRegister();
964         List prTypes = reg.getPublicPrTypes();
965         if(prTypes != null && !prTypes.isEmpty()){
966           HashMap resourcesByName = new HashMap();
967           Iterator prIter = prTypes.iterator();
968           while(prIter.hasNext()){
969             ResourceData rData = (ResourceData)reg.get(prIter.next());
970             resourcesByName.put(rData.getName(), rData);
971           }
972           List prNames = new ArrayList(resourcesByName.keySet());
973           Collections.sort(prNames);
974           prIter = prNames.iterator();
975           while(prIter.hasNext()){
976             ResourceData rData = (ResourceData)resourcesByName.
977                                  get(prIter.next());
978             newPrMenu.add(new XJMenuItem(new NewResourceAction(rData),
979                                          MainFrame.this));
980           }
981         }
982       }
983     });
984 
985     newLrsPopupMenu.addMenuListener(new MenuListener() {
986       public void menuCanceled(MenuEvent e) {
987       }
988       public void menuDeselected(MenuEvent e) {
989       }
990       public void menuSelected(MenuEvent e) {
991         newLrsPopupMenu.removeAll();
992         //find out the available types of LRs and repopulate the menu
993         CreoleRegister reg = Gate.getCreoleRegister();
994         List lrTypes = reg.getPublicLrTypes();
995         if(lrTypes != null && !lrTypes.isEmpty()){
996           HashMap resourcesByName = new HashMap();
997           Iterator lrIter = lrTypes.iterator();
998           while(lrIter.hasNext()){
999             ResourceData rData = (ResourceData)reg.get(lrIter.next());
1000            resourcesByName.put(rData.getName(), rData);
1001          }
1002          List lrNames = new ArrayList(resourcesByName.keySet());
1003          Collections.sort(lrNames);
1004          lrIter = lrNames.iterator();
1005          while(lrIter.hasNext()){
1006            ResourceData rData = (ResourceData)resourcesByName.
1007                                 get(lrIter.next());
1008            newLrsPopupMenu.add(new XJMenuItem(new NewResourceAction(rData),
1009                                         MainFrame.this));
1010          }
1011        }
1012      }
1013    });
1014
1015    // Adding a listener for loading ANNIE with or without defaults
1016    loadANNIEMenu.addMenuListener(new MenuListener(){
1017      public void menuCanceled(MenuEvent e){}
1018      public void menuDeselected(MenuEvent e){}
1019      public void menuSelected(MenuEvent e){
1020        loadANNIEMenu.removeAll();
1021        loadANNIEMenu.add(new LoadANNIEWithDefaultsAction());
1022        loadANNIEMenu.add(new LoadANNIEWithoutDefaultsAction());
1023      }// menuSelected();
1024    });//loadANNIEMenu.addMenuListener(new MenuListener()
1025
1026    newPrsPopupMenu.addMenuListener(new MenuListener() {
1027      public void menuCanceled(MenuEvent e) {
1028      }
1029      public void menuDeselected(MenuEvent e) {
1030      }
1031      public void menuSelected(MenuEvent e) {
1032        newPrsPopupMenu.removeAll();
1033        //find out the available types of LRs and repopulate the menu
1034        CreoleRegister reg = Gate.getCreoleRegister();
1035        List prTypes = reg.getPublicPrTypes();
1036        if(prTypes != null && !prTypes.isEmpty()){
1037          HashMap resourcesByName = new HashMap();
1038          Iterator prIter = prTypes.iterator();
1039          while(prIter.hasNext()){
1040            ResourceData rData = (ResourceData)reg.get(prIter.next());
1041            resourcesByName.put(rData.getName(), rData);
1042          }
1043          List prNames = new ArrayList(resourcesByName.keySet());
1044          Collections.sort(prNames);
1045          prIter = prNames.iterator();
1046          while(prIter.hasNext()){
1047            ResourceData rData = (ResourceData)resourcesByName.
1048                                 get(prIter.next());
1049            newPrsPopupMenu.add(new XJMenuItem(new NewResourceAction(rData),
1050                                         MainFrame.this));
1051          }
1052        }
1053      }
1054    });
1055
1056
1057    newAppMenu.addMenuListener(new MenuListener() {
1058      public void menuCanceled(MenuEvent e) {
1059      }
1060      public void menuDeselected(MenuEvent e) {
1061      }
1062      public void menuSelected(MenuEvent e) {
1063        newAppMenu.removeAll();
1064        //find out the available types of Controllers and repopulate the menu
1065        CreoleRegister reg = Gate.getCreoleRegister();
1066        List controllerTypes = reg.getPublicControllerTypes();
1067        if(controllerTypes != null && !controllerTypes.isEmpty()){
1068          HashMap resourcesByName = new HashMap();
1069          Iterator controllerTypesIter = controllerTypes.iterator();
1070          while(controllerTypesIter.hasNext()){
1071            ResourceData rData = (ResourceData)reg.get(controllerTypesIter.next());
1072            resourcesByName.put(rData.getName(), rData);
1073          }
1074          List controllerNames = new ArrayList(resourcesByName.keySet());
1075          Collections.sort(controllerNames);
1076          controllerTypesIter = controllerNames.iterator();
1077          while(controllerTypesIter.hasNext()){
1078            ResourceData rData = (ResourceData)resourcesByName.
1079                                 get(controllerTypesIter.next());
1080            newAppMenu.add(new XJMenuItem(new NewResourceAction(rData),
1081                                         MainFrame.this));
1082          }
1083        }
1084      }
1085    });
1086
1087
1088    newAppPopupMenu.addMenuListener(new MenuListener() {
1089      public void menuCanceled(MenuEvent e) {
1090      }
1091      public void menuDeselected(MenuEvent e) {
1092      }
1093      public void menuSelected(MenuEvent e) {
1094        newAppPopupMenu.removeAll();
1095        //find out the available types of Controllers and repopulate the menu
1096        CreoleRegister reg = Gate.getCreoleRegister();
1097        List controllerTypes = reg.getPublicControllerTypes();
1098        if(controllerTypes != null && !controllerTypes.isEmpty()){
1099          HashMap resourcesByName = new HashMap();
1100          Iterator controllerTypesIter = controllerTypes.iterator();
1101          while(controllerTypesIter.hasNext()){
1102            ResourceData rData = (ResourceData)reg.get(controllerTypesIter.next());
1103            resourcesByName.put(rData.getName(), rData);
1104          }
1105          List controllerNames = new ArrayList(resourcesByName.keySet());
1106          Collections.sort(controllerNames);
1107          controllerTypesIter = controllerNames.iterator();
1108          while(controllerTypesIter.hasNext()){
1109            ResourceData rData = (ResourceData)resourcesByName.
1110                                 get(controllerTypesIter.next());
1111            newAppPopupMenu.add(new XJMenuItem(new NewResourceAction(rData),
1112                                         MainFrame.this));
1113          }
1114        }
1115      }
1116    });
1117
1118   listeners.put("gate.event.StatusListener", MainFrame.this);
1119   listeners.put("gate.event.ProgressListener", MainFrame.this);
1120  }//protected void initListeners()
1121
1122  public void progressChanged(int i) {
1123    //progressBar.setStringPainted(true);
1124    int oldValue = progressBar.getValue();
1125//    if((!stopAction.isEnabled()) &&
1126//       (Gate.getExecutable() != null)){
1127//      stopAction.setEnabled(true);
1128//      SwingUtilities.invokeLater(new Runnable(){
1129//        public void run(){
1130//          southBox.add(stopBtn, 0);
1131//        }
1132//      });
1133//    }
1134    if(!animator.isActive()) animator.activate();
1135    if(oldValue != i){
1136      SwingUtilities.invokeLater(new ProgressBarUpdater(i));
1137    }
1138  }
1139
1140  /**
1141   * Called when the process is finished.
1142   *
1143   */
1144  public void processFinished() {
1145    //progressBar.setStringPainted(false);
1146//    if(stopAction.isEnabled()){
1147//      stopAction.setEnabled(false);
1148//      SwingUtilities.invokeLater(new Runnable(){
1149//        public void run(){
1150//          southBox.remove(stopBtn);
1151//        }
1152//      });
1153//    }
1154    SwingUtilities.invokeLater(new ProgressBarUpdater(0));
1155    animator.deactivate();
1156  }
1157
1158  public void statusChanged(String text) {
1159    SwingUtilities.invokeLater(new StatusBarUpdater(text));
1160  }
1161
1162  public void resourceLoaded(CreoleEvent e) {
1163    Resource res = e.getResource();
1164    if(Gate.getHiddenAttribute(res.getFeatures())) return;
1165    NameBearerHandle handle = new NameBearerHandle(res, MainFrame.this);
1166    DefaultMutableTreeNode node = new DefaultMutableTreeNode(handle, false);
1167    if(res instanceof ProcessingResource){
1168      resourcesTreeModel.insertNodeInto(node, processingResourcesRoot, 0);
1169    }else if(res instanceof LanguageResource){
1170      resourcesTreeModel.insertNodeInto(node, languageResourcesRoot, 0);
1171    }else if(res instanceof Controller){
1172      resourcesTreeModel.insertNodeInto(node, applicationsRoot, 0);
1173    }
1174
1175    handle.addProgressListener(MainFrame.this);
1176    handle.addStatusListener(MainFrame.this);
1177
1178//    JPopupMenu popup = handle.getPopup();
1179//
1180//    // Create a CloseViewAction and a menu item based on it
1181//    CloseViewAction cva = new CloseViewAction(handle);
1182//    XJMenuItem menuItem = new XJMenuItem(cva, this);
1183//    // Add an accelerator ATL+F4 for this action
1184//    menuItem.setAccelerator(KeyStroke.getKeyStroke(
1185//                                      KeyEvent.VK_H, ActionEvent.CTRL_MASK));
1186//    popup.insert(menuItem, 1);
1187//    popup.insert(new JPopupMenu.Separator(), 2);
1188//
1189//    popup.insert(new XJMenuItem(
1190//                  new RenameResourceAction(
1191//                      new TreePath(resourcesTreeModel.getPathToRoot(node))),
1192//                  MainFrame.this) , 3);
1193//
1194//    // Put the action command in the component's action map
1195//    if (handle.getLargeView() != null)
1196//      handle.getLargeView().getActionMap().put("Hide current view",cva);
1197//
1198  }// resourceLoaded();
1199
1200
1201  public void resourceUnloaded(CreoleEvent e) {
1202    Resource res = e.getResource();
1203    if(Gate.getHiddenAttribute(res.getFeatures())) return;
1204    DefaultMutableTreeNode node;
1205    DefaultMutableTreeNode parent = null;
1206    if(res instanceof ProcessingResource){
1207      parent = processingResourcesRoot;
1208    }else if(res instanceof LanguageResource){
1209      parent = languageResourcesRoot;
1210    }else if(res instanceof Controller){
1211      parent = applicationsRoot;
1212    }
1213    if(parent != null){
1214      Enumeration children = parent.children();
1215      while(children.hasMoreElements()){
1216        node = (DefaultMutableTreeNode)children.nextElement();
1217        if(((NameBearerHandle)node.getUserObject()).getTarget() == res){
1218          resourcesTreeModel.removeNodeFromParent(node);
1219          Handle handle = (Handle)node.getUserObject();
1220          if(mainTabbedPane.indexOfComponent(handle.getLargeView()) != -1){
1221            mainTabbedPane.remove(handle.getLargeView());
1222          }
1223          if(lowerScroll.getViewport().getView() == handle.getSmallView()){
1224            lowerScroll.getViewport().setView(null);
1225          }
1226          return;
1227        }
1228      }
1229    }
1230  }
1231
1232  /**Called when a {@link gate.DataStore} has been opened*/
1233  public void datastoreOpened(CreoleEvent e){
1234    DataStore ds = e.getDatastore();
1235
1236    ds.setName(ds.getStorageUrl());
1237
1238    NameBearerHandle handle = new NameBearerHandle(ds, MainFrame.this);
1239    DefaultMutableTreeNode node = new DefaultMutableTreeNode(handle, false);
1240    resourcesTreeModel.insertNodeInto(node, datastoresRoot, 0);
1241    handle.addProgressListener(MainFrame.this);
1242    handle.addStatusListener(MainFrame.this);
1243
1244//    JPopupMenu popup = handle.getPopup();
1245//    popup.addSeparator();
1246//    // Create a CloseViewAction and a menu item based on it
1247//    CloseViewAction cva = new CloseViewAction(handle);
1248//    XJMenuItem menuItem = new XJMenuItem(cva, this);
1249//    // Add an accelerator ATL+F4 for this action
1250//    menuItem.setAccelerator(KeyStroke.getKeyStroke(
1251//                                      KeyEvent.VK_H, ActionEvent.CTRL_MASK));
1252//    popup.add(menuItem);
1253//    // Put the action command in the component's action map
1254//    if (handle.getLargeView() != null)
1255//      handle.getLargeView().getActionMap().put("Hide current view",cva);
1256  }// datastoreOpened();
1257
1258  /**Called when a {@link gate.DataStore} has been created*/
1259  public void datastoreCreated(CreoleEvent e){
1260    datastoreOpened(e);
1261  }
1262
1263  /**Called when a {@link gate.DataStore} has been closed*/
1264  public void datastoreClosed(CreoleEvent e){
1265    DataStore ds = e.getDatastore();
1266    DefaultMutableTreeNode node;
1267    DefaultMutableTreeNode parent = datastoresRoot;
1268    if(parent != null){
1269      Enumeration children = parent.children();
1270      while(children.hasMoreElements()){
1271        node = (DefaultMutableTreeNode)children.nextElement();
1272        if(((NameBearerHandle)node.getUserObject()).
1273            getTarget() == ds){
1274          resourcesTreeModel.removeNodeFromParent(node);
1275          NameBearerHandle handle = (NameBearerHandle)
1276                                          node.getUserObject();
1277          if(mainTabbedPane.indexOfComponent(handle.getLargeView()) != -1){
1278            mainTabbedPane.remove(handle.getLargeView());
1279          }
1280          if(lowerScroll.getViewport().getView() == handle.getSmallView()){
1281            lowerScroll.getViewport().setView(null);
1282          }
1283          return;
1284        }
1285      }
1286    }
1287  }
1288
1289  public void resourceRenamed(Resource resource, String oldName,
1290                              String newName){
1291    for(int i = 0; i < mainTabbedPane.getTabCount(); i++){
1292      if(mainTabbedPane.getTitleAt(i).equals(oldName)){
1293        mainTabbedPane.setTitleAt(i, newName);
1294
1295        return;
1296      }
1297    }
1298  }
1299
1300  /**
1301   * Overridden so we can exit when window is closed
1302   */
1303  protected void processWindowEvent(WindowEvent e) {
1304    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
1305      new ExitGateAction().actionPerformed(null);
1306    }
1307    super.processWindowEvent(e);
1308  }// processWindowEvent(WindowEvent e)
1309
1310  /**
1311   * Returns the listeners map, a map that holds all the listeners that are
1312   * singletons (e.g. the status listener that updates the status bar on the
1313   * main frame or the progress listener that updates the progress bar on the
1314   * main frame).
1315   * The keys used are the class names of the listener interface and the values
1316   * are the actual listeners (e.g "gate.event.StatusListener" -> this).
1317   * The returned map is the actual data member used to store the listeners so
1318   * any changes in this map will be visible to everyone.
1319   */
1320  public static java.util.Map getListeners() {
1321    return listeners;
1322  }
1323
1324  public static java.util.Collection getGuiRoots() {
1325    return guiRoots;
1326  }
1327
1328  /**
1329   * This method will lock all input to the gui by means of a modal dialog.
1330   * If Gate is not currently running in GUI mode this call will be ignored.
1331   * A call to this method while the GUI is locked will cause the GUI to be
1332   * unlocked and then locked again with the new message.
1333   * If a message is provided it will show in the dialog.
1334   * @param message the message to be displayed while the GUI is locked
1335   */
1336  public synchronized static void lockGUI(final String message){
1337    //check whether GUI is up
1338    if(getGuiRoots() == null || getGuiRoots().isEmpty()) return;
1339    //if the GUI is locked unlock it so we can show the new message
1340    unlockGUI();
1341
1342    //build the dialog contents
1343    Object[] options = new Object[]{new JButton(new StopAction())};
1344    JOptionPane pane = new JOptionPane(message, JOptionPane.WARNING_MESSAGE,
1345                                       JOptionPane.DEFAULT_OPTION,
1346                                       null, options, null);
1347
1348    //build the dialog
1349    Component parentComp = (Component)((ArrayList)getGuiRoots()).get(0);
1350    JDialog dialog;
1351    Window parentWindow;
1352    if(parentComp instanceof Window) parentWindow = (Window)parentComp;
1353    else parentWindow = SwingUtilities.getWindowAncestor(parentComp);
1354    if(parentWindow instanceof Frame){
1355      dialog = new JDialog((Frame)parentWindow, "Please wait", true){
1356        protected void processWindowEvent(WindowEvent e) {
1357          if (e.getID() == WindowEvent.WINDOW_CLOSING) {
1358            getToolkit().beep();
1359          }
1360        }
1361      };
1362    }else if(parentWindow instanceof Dialog){
1363      dialog = new JDialog((Dialog)parentWindow, "Please wait", true){
1364        protected void processWindowEvent(WindowEvent e) {
1365          if (e.getID() == WindowEvent.WINDOW_CLOSING) {
1366            getToolkit().beep();
1367          }
1368        }
1369      };
1370    }else{
1371      dialog = new JDialog(JOptionPane.getRootFrame(), "Please wait", true){
1372        protected void processWindowEvent(WindowEvent e) {
1373          if (e.getID() == WindowEvent.WINDOW_CLOSING) {
1374            getToolkit().beep();
1375          }
1376        }
1377      };
1378    }
1379    dialog.getContentPane().setLayout(new BorderLayout());
1380    dialog.getContentPane().add(pane, BorderLayout.CENTER);
1381    dialog.pack();
1382    dialog.setLocationRelativeTo(parentComp);
1383    dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
1384    guiLock = dialog;
1385
1386    //this call needs to return so we'll show the dialog from a different thread
1387    //the Swing thread sounds good for that
1388    SwingUtilities.invokeLater(new Runnable(){
1389      public void run(){
1390        guiLock.show();
1391      }
1392    });
1393
1394    //this call should not return until the dialog is up to ensure proper
1395    //sequentiality for lock - unlock calls
1396    while(!guiLock.isShowing()){
1397      try{
1398        Thread.sleep(100);
1399      }catch(InterruptedException ie){}
1400    }
1401  }
1402
1403  public synchronized static void unlockGUI(){
1404    //check whether GUI is up
1405    if(getGuiRoots() == null || getGuiRoots().isEmpty()) return;
1406
1407    if(guiLock != null) guiLock.hide();
1408    guiLock = null;
1409  }
1410
1411  /** Flag to protect Frame title to be changed */
1412  private boolean titleChangable = false;
1413
1414  public void setTitleChangable(boolean isChangable) {
1415    titleChangable = isChangable;
1416  } // setTitleChangable(boolean isChangable)
1417
1418  /** Override to avoid Protege to change Frame title */
1419  public synchronized void setTitle(String title) {
1420    if(titleChangable) {
1421      super.setTitle(title);
1422    } // if
1423  } // setTitle(String title)
1424
1425
1426
1427  /** Method is used in NewDSAction */
1428  protected DataStore createSerialDataStore() {
1429    DataStore ds = null;
1430
1431    //get the URL (a file in this case)
1432    fileChooser.setDialogTitle("Please create a new empty directory");
1433    fileChooser.setFileSelectionMode(fileChooser.DIRECTORIES_ONLY);
1434    if(fileChooser.showOpenDialog(MainFrame.this) ==
1435                                          fileChooser.APPROVE_OPTION){
1436      try {
1437        URL dsURL = fileChooser.getSelectedFile().toURL();
1438        ds = Factory.createDataStore("gate.persist.SerialDataStore",
1439                                               dsURL.toExternalForm());
1440      } catch(MalformedURLException mue) {
1441        JOptionPane.showMessageDialog(
1442            MainFrame.this, "Invalid location for the datastore\n " +
1443                              mue.toString(),
1444                              "Gate", JOptionPane.ERROR_MESSAGE);
1445      } catch(PersistenceException pe) {
1446        JOptionPane.showMessageDialog(
1447            MainFrame.this, "Datastore creation error!\n " +
1448                              pe.toString(),
1449                              "Gate", JOptionPane.ERROR_MESSAGE);
1450      } // catch
1451    } // if
1452
1453    return ds;
1454  } // createSerialDataStore()
1455
1456  /** Method is used in OpenDSAction */
1457  protected DataStore openSerialDataStore() {
1458    DataStore ds = null;
1459
1460    //get the URL (a file in this case)
1461    fileChooser.setDialogTitle("Select the datastore directory");
1462    fileChooser.setFileSelectionMode(fileChooser.DIRECTORIES_ONLY);
1463    if (fileChooser.showOpenDialog(MainFrame.this) ==
1464                                          fileChooser.APPROVE_OPTION){
1465      try {
1466        URL dsURL = fileChooser.getSelectedFile().toURL();
1467        ds = Factory.openDataStore("gate.persist.SerialDataStore",
1468                                             dsURL.toExternalForm());
1469      } catch(MalformedURLException mue) {
1470        JOptionPane.showMessageDialog(
1471            MainFrame.this, "Invalid location for the datastore\n " +
1472                              mue.toString(),
1473                              "Gate", JOptionPane.ERROR_MESSAGE);
1474      } catch(PersistenceException pe) {
1475        JOptionPane.showMessageDialog(
1476            MainFrame.this, "Datastore opening error!\n " +
1477                              pe.toString(),
1478                              "Gate", JOptionPane.ERROR_MESSAGE);
1479      } // catch
1480    } // if
1481
1482    return ds;
1483  } // openSerialDataStore()
1484
1485
1486/*
1487  synchronized void showWaitDialog() {
1488    Point location = getLocationOnScreen();
1489    location.translate(10,
1490              getHeight() - waitDialog.getHeight() - southBox.getHeight() - 10);
1491    waitDialog.setLocation(location);
1492    waitDialog.showDialog(new Component[]{});
1493  }
1494
1495  synchronized void  hideWaitDialog() {
1496    waitDialog.goAway();
1497  }
1498*/
1499
1500/*
1501  class NewProjectAction extends AbstractAction {
1502    public NewProjectAction(){
1503      super("New Project", new ImageIcon(MainFrame.class.getResource(
1504                                        "/gate/resources/img/newProject.gif")));
1505      putValue(SHORT_DESCRIPTION,"Create a new project");
1506    }
1507    public void actionPerformed(ActionEvent e){
1508      fileChooser.setDialogTitle("Select new project file");
1509      fileChooser.setFileSelectionMode(fileChooser.FILES_ONLY);
1510      if(fileChooser.showOpenDialog(parentFrame) == fileChooser.APPROVE_OPTION){
1511        ProjectData pData = new ProjectData(fileChooser.getSelectedFile(),
1512                                                                  parentFrame);
1513        addProject(pData);
1514      }
1515    }
1516  }
1517*/
1518
1519  /** This class represent an action which brings up the Annot Diff tool*/
1520  class NewAnnotDiffAction extends AbstractAction {
1521    public NewAnnotDiffAction() {
1522      super("Annotation Diff", getIcon("annDiff.gif"));
1523      putValue(SHORT_DESCRIPTION,"Create a new Annotation Diff Tool");
1524    }// NewAnnotDiffAction
1525    public void actionPerformed(ActionEvent e) {
1526      AnnotDiffDialog annotDiffDialog = new AnnotDiffDialog(MainFrame.this);
1527      annotDiffDialog.setTitle("Annotation Diff Tool");
1528      annotDiffDialog.setVisible(true);
1529    }// actionPerformed();
1530  }//class NewAnnotDiffAction
1531
1532  /** This class represent an action which brings up the Corpus Annot Diff tool*/
1533  class NewCorpusAnnotDiffAction extends AbstractAction {
1534    public NewCorpusAnnotDiffAction() {
1535      super("Corpus Annotation Diff", getIcon("annDiff.gif"));
1536      putValue(SHORT_DESCRIPTION,"Create a new Corpus Annotation Diff Tool");
1537    }// NewCorpusAnnotDiffAction
1538    public void actionPerformed(ActionEvent e) {
1539      CorpusAnnotDiffDialog annotDiffDialog =
1540        new CorpusAnnotDiffDialog(MainFrame.this);
1541      annotDiffDialog.setTitle("Corpus Annotation Diff Tool");
1542      annotDiffDialog.setVisible(true);
1543    }// actionPerformed();
1544  }//class NewCorpusAnnotDiffAction
1545
1546  /** This class represent an action which brings up the corpus evaluation tool*/
1547  class NewCorpusEvalAction extends AbstractAction {
1548    public NewCorpusEvalAction() {
1549      super("Default mode");
1550      putValue(SHORT_DESCRIPTION,"Run the Benchmark Tool in its default mode");
1551    }// newCorpusEvalAction
1552
1553    public void actionPerformed(ActionEvent e) {
1554      Runnable runnable = new Runnable(){
1555        public void run(){
1556          JFileChooser chooser = MainFrame.getFileChooser();
1557          chooser.setDialogTitle("Please select a directory which contains " +
1558                                 "the documents to be evaluated");
1559          chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1560          chooser.setMultiSelectionEnabled(false);
1561          int state = chooser.showOpenDialog(MainFrame.this);
1562          File startDir = chooser.getSelectedFile();
1563          if (state == JFileChooser.CANCEL_OPTION || startDir == null)
1564            return;
1565
1566          chooser.setDialogTitle("Please select the application that you want to run");
1567          chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
1568          state = chooser.showOpenDialog(MainFrame.this);
1569          File testApp = chooser.getSelectedFile();
1570          if (state == JFileChooser.CANCEL_OPTION || startDir == null)
1571            return;
1572
1573          //first create the tool and set its parameters
1574          CorpusBenchmarkTool theTool = new CorpusBenchmarkTool();
1575          theTool.setStartDirectory(startDir);
1576          theTool.setApplicationFile(testApp);
1577          theTool.setVerboseMode(
1578            MainFrame.this.verboseModeCorpusEvalToolAction.isVerboseMode());
1579
1580          Out.prln("Please wait while GATE tools are initialised.");
1581          //initialise the tool
1582          theTool.init();
1583          //and execute it
1584          theTool.execute();
1585          theTool.printStatistics();
1586
1587          Out.prln("Overall average precision: " + theTool.getPrecisionAverage());
1588          Out.prln("Overall average recall: " + theTool.getRecallAverage());
1589          Out.prln("Finished!");
1590          theTool.unloadPRs();
1591        }
1592      };
1593      Thread thread = new Thread(Thread.currentThread().getThreadGroup(),
1594                                 runnable, "Eval thread");
1595      thread.setPriority(Thread.MIN_PRIORITY);
1596      thread.start();
1597    }// actionPerformed();
1598  }//class NewCorpusEvalAction
1599
1600  /** This class represent an action which brings up the corpus evaluation tool*/
1601  class StoredMarkedCorpusEvalAction extends AbstractAction {
1602    public StoredMarkedCorpusEvalAction() {
1603      super("Human marked against stored processing results");
1604      putValue(SHORT_DESCRIPTION,"Run the Benchmark Tool -stored_clean");
1605    }// newCorpusEvalAction
1606
1607    public void actionPerformed(ActionEvent e) {
1608      Runnable runnable = new Runnable(){
1609        public void run(){
1610          JFileChooser chooser = MainFrame.getFileChooser();
1611          chooser.setDialogTitle("Please select a directory which contains " +
1612                                 "the documents to be evaluated");
1613          chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1614          chooser.setMultiSelectionEnabled(false);
1615          int state = chooser.showOpenDialog(MainFrame.this);
1616          File startDir = chooser.getSelectedFile();
1617          if (state == JFileChooser.CANCEL_OPTION || startDir == null)
1618            return;
1619
1620          //first create the tool and set its parameters
1621          CorpusBenchmarkTool theTool = new CorpusBenchmarkTool();
1622          theTool.setStartDirectory(startDir);
1623          theTool.setMarkedStored(true);
1624          theTool.setVerboseMode(
1625            MainFrame.this.verboseModeCorpusEvalToolAction.isVerboseMode());
1626//          theTool.setMarkedDS(
1627//            MainFrame.this.datastoreModeCorpusEvalToolAction.isDatastoreMode());
1628
1629
1630          Out.prln("Evaluating human-marked documents against pre-stored results.");
1631          //initialise the tool
1632          theTool.init();
1633          //and execute it
1634          theTool.execute();
1635          theTool.printStatistics();
1636
1637          Out.prln("Overall average precision: " + theTool.getPrecisionAverage());
1638          Out.prln("Overall average recall: " + theTool.getRecallAverage());
1639          Out.prln("Finished!");
1640          theTool.unloadPRs();
1641        }
1642      };
1643      Thread thread = new Thread(Thread.currentThread().getThreadGroup(),
1644                                 runnable, "Eval thread");
1645      thread.setPriority(Thread.MIN_PRIORITY);
1646      thread.start();
1647    }// actionPerformed();
1648  }//class StoredMarkedCorpusEvalActionpusEvalAction
1649
1650  /** This class represent an action which brings up the corpus evaluation tool*/
1651  class CleanMarkedCorpusEvalAction extends AbstractAction {
1652    public CleanMarkedCorpusEvalAction() {
1653      super("Human marked against current processing results");
1654      putValue(SHORT_DESCRIPTION,"Run the Benchmark Tool -marked_clean");
1655    }// newCorpusEvalAction
1656
1657    public void actionPerformed(ActionEvent e) {
1658      Runnable runnable = new Runnable(){
1659        public void run(){
1660          JFileChooser chooser = MainFrame.getFileChooser();
1661          chooser.setDialogTitle("Please select a directory which contains " +
1662                                 "the documents to be evaluated");
1663          chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1664          chooser.setMultiSelectionEnabled(false);
1665          int state = chooser.showOpenDialog(MainFrame.this);
1666          File startDir = chooser.getSelectedFile();
1667          if (state == JFileChooser.CANCEL_OPTION || startDir == null)
1668            return;
1669
1670          chooser.setDialogTitle("Please select the application that you want to run");
1671          chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
1672          state = chooser.showOpenDialog(MainFrame.this);
1673          File testApp = chooser.getSelectedFile();
1674          if (state == JFileChooser.CANCEL_OPTION || startDir == null)
1675            return;
1676
1677          //first create the tool and set its parameters
1678          CorpusBenchmarkTool theTool = new CorpusBenchmarkTool();
1679          theTool.setStartDirectory(startDir);
1680          theTool.setApplicationFile(testApp);
1681          theTool.setMarkedClean(true);
1682          theTool.setVerboseMode(
1683            MainFrame.this.verboseModeCorpusEvalToolAction.isVerboseMode());
1684
1685          Out.prln("Evaluating human-marked documents against current processing results.");
1686          //initialise the tool
1687          theTool.init();
1688          //and execute it
1689          theTool.execute();
1690          theTool.printStatistics();
1691
1692          Out.prln("Overall average precision: " + theTool.getPrecisionAverage());
1693          Out.prln("Overall average recall: " + theTool.getRecallAverage());
1694          Out.prln("Finished!");
1695          theTool.unloadPRs();
1696        }
1697      };
1698      Thread thread = new Thread(Thread.currentThread().getThreadGroup(),
1699                                 runnable, "Eval thread");
1700      thread.setPriority(Thread.MIN_PRIORITY);
1701      thread.start();
1702    }// actionPerformed();
1703  }//class CleanMarkedCorpusEvalActionpusEvalAction
1704
1705
1706  /** This class represent an action which brings up the corpus evaluation tool*/
1707  class GenerateStoredCorpusEvalAction extends AbstractAction {
1708    public GenerateStoredCorpusEvalAction() {
1709      super("Store corpus for future evaluation");
1710      putValue(SHORT_DESCRIPTION,"Run the Benchmark Tool -generate");
1711    }// newCorpusEvalAction
1712
1713    public void actionPerformed(ActionEvent e) {
1714      Runnable runnable = new Runnable(){
1715        public void run(){
1716          JFileChooser chooser = MainFrame.getFileChooser();
1717          chooser.setDialogTitle("Please select a directory which contains " +
1718                                 "the documents to be evaluated");
1719          chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1720          chooser.setMultiSelectionEnabled(false);
1721          int state = chooser.showOpenDialog(MainFrame.this);
1722          File startDir = chooser.getSelectedFile();
1723          if (state == JFileChooser.CANCEL_OPTION || startDir == null)
1724            return;
1725
1726          chooser.setDialogTitle("Please select the application that you want to run");
1727          chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
1728          state = chooser.showOpenDialog(MainFrame.this);
1729          File testApp = chooser.getSelectedFile();
1730          if (state == JFileChooser.CANCEL_OPTION || startDir == null)
1731            return;
1732
1733          //first create the tool and set its parameters
1734          CorpusBenchmarkTool theTool = new CorpusBenchmarkTool();
1735          theTool.setStartDirectory(startDir);
1736          theTool.setApplicationFile(testApp);
1737          theTool.setGenerateMode(true);
1738
1739          Out.prln("Processing and storing documents for future evaluation.");
1740          //initialise the tool
1741          theTool.init();
1742          //and execute it
1743          theTool.execute();
1744          theTool.unloadPRs();
1745          Out.prln("Finished!");
1746        }
1747      };
1748      Thread thread = new Thread(Thread.currentThread().getThreadGroup(),
1749                                 runnable, "Eval thread");
1750      thread.setPriority(Thread.MIN_PRIORITY);
1751      thread.start();
1752    }// actionPerformed();
1753  }//class GenerateStoredCorpusEvalAction
1754
1755  /** This class represent an action which brings up the corpus evaluation tool*/
1756  class VerboseModeCorpusEvalToolAction extends AbstractAction  {
1757    public VerboseModeCorpusEvalToolAction() {
1758      super("Verbose mode");
1759      putValue(SHORT_DESCRIPTION,"Run the Benchmark Tool in verbose mode");
1760    }// VerboseModeCorpusEvalToolAction
1761
1762    public boolean isVerboseMode() {return verboseMode;}
1763
1764    public void actionPerformed(ActionEvent e) {
1765      if (! (e.getSource() instanceof JCheckBoxMenuItem))
1766        return;
1767      verboseMode = ((JCheckBoxMenuItem)e.getSource()).getState();
1768    }// actionPerformed();
1769    protected boolean verboseMode = false;
1770  }//class f
1771
1772  /** This class represent an action which brings up the corpus evaluation tool*/
1773/*
1774  class DatastoreModeCorpusEvalToolAction extends AbstractAction  {
1775    public DatastoreModeCorpusEvalToolAction() {
1776      super("Use a datastore for human annotated texts");
1777      putValue(SHORT_DESCRIPTION,"Use a datastore for the human annotated texts");
1778    }// DatastoreModeCorpusEvalToolAction
1779
1780    public boolean isDatastoreMode() {return datastoreMode;}
1781
1782    public void actionPerformed(ActionEvent e) {
1783      if (! (e.getSource() instanceof JCheckBoxMenuItem))
1784        return;
1785      datastoreMode = ((JCheckBoxMenuItem)e.getSource()).getState();
1786    }// actionPerformed();
1787    protected boolean datastoreMode = false;
1788  }//class DatastoreModeCorpusEvalToolListener
1789*/
1790
1791  /** This class represent an action which loads ANNIE with default params*/
1792  class LoadANNIEWithDefaultsAction extends AbstractAction
1793                                    implements ANNIEConstants{
1794    public LoadANNIEWithDefaultsAction() {
1795      super("With defaults");
1796    }// NewAnnotDiffAction
1797    public void actionPerformed(ActionEvent e) {
1798      // Loads ANNIE with defaults
1799      Runnable runnable = new Runnable(){
1800        public void run(){
1801          long startTime = System.currentTimeMillis();
1802          FeatureMap params = Factory.newFeatureMap();
1803          try{
1804            //lock the gui
1805            lockGUI("ANNIE is being loaded...");
1806            // Create a serial analyser
1807            SerialAnalyserController sac = (SerialAnalyserController)
1808                Factory.createResource("gate.creole.SerialAnalyserController",
1809                                       Factory.newFeatureMap(),
1810                                       Factory.newFeatureMap(),
1811                                       "ANNIE_" + Gate.genSym());
1812            // Load each PR as defined in gate.creole.ANNIEConstants.PR_NAMES
1813            for(int i = 0; i < PR_NAMES.length; i++){
1814            ProcessingResource pr = (ProcessingResource)
1815                Factory.createResource(PR_NAMES[i], params);
1816              // Add the PR to the sac
1817              sac.add(pr);
1818            }// End for
1819
1820            long endTime = System.currentTimeMillis();
1821            statusChanged("ANNIE loaded in " +
1822                NumberFormat.getInstance().format(
1823                (double)(endTime - startTime) / 1000) + " seconds");
1824          }catch(gate.creole.ResourceInstantiationException ex){
1825            ex.printStackTrace(Err.getPrintWriter());
1826          }finally{
1827            unlockGUI();
1828          }
1829        }// run()
1830      };// End Runnable
1831      Thread thread = new Thread(runnable, "");
1832      thread.setPriority(Thread.MIN_PRIORITY);
1833      thread.start();
1834    }// actionPerformed();
1835  }//class LoadANNIEWithDefaultsAction
1836
1837  /** This class represent an action which loads ANNIE with default params*/
1838  class LoadANNIEWithoutDefaultsAction extends AbstractAction
1839                                    implements ANNIEConstants{
1840    public LoadANNIEWithoutDefaultsAction() {
1841      super("Without defaults");
1842    }// NewAnnotDiffAction
1843    public void actionPerformed(ActionEvent e) {
1844      // Loads ANNIE with defaults
1845      Runnable runnable = new Runnable(){
1846        public void run(){
1847          FeatureMap params = Factory.newFeatureMap();
1848          try{
1849            // Create a serial analyser
1850            SerialAnalyserController sac = (SerialAnalyserController)
1851                Factory.createResource("gate.creole.SerialAnalyserController",
1852                                       Factory.newFeatureMap(),
1853                                       Factory.newFeatureMap(),
1854                                       "ANNIE_" + Gate.genSym());
1855//            NewResourceDialog resourceDialog = new NewResourceDialog(
1856//                                  MainFrame.this, "Resource parameters", true );
1857            // Load each PR as defined in gate.creole.ANNIEConstants.PR_NAMES
1858            for(int i = 0; i < PR_NAMES.length; i++){
1859              //get the params for the Current PR
1860              ResourceData resData = (ResourceData)Gate.getCreoleRegister().
1861                                      get(PR_NAMES[i]);
1862              if(newResourceDialog.show(resData,
1863                                     "Parameters for the new " +
1864                                     resData.getName())){
1865                sac.add((ProcessingResource)Factory.createResource(
1866                          PR_NAMES[i],
1867                          newResourceDialog.getSelectedParameters()));
1868              }else{
1869                //the user got bored and aborted the operation
1870                statusChanged("Loading cancelled! Removing traces...");
1871                Iterator loadedPRsIter = new ArrayList(sac.getPRs()).iterator();
1872                while(loadedPRsIter.hasNext()){
1873                  Factory.deleteResource((ProcessingResource)
1874                                         loadedPRsIter.next());
1875                }
1876                Factory.deleteResource(sac);
1877                statusChanged("Loading cancelled!");
1878                return;
1879              }
1880            }// End for
1881            statusChanged("ANNIE loaded!");
1882          }catch(gate.creole.ResourceInstantiationException ex){
1883            ex.printStackTrace(Err.getPrintWriter());
1884          }// End try
1885        }// run()
1886      };// End Runnable
1887      SwingUtilities.invokeLater(runnable);
1888//      Thread thread = new Thread(runnable, "");
1889//      thread.setPriority(Thread.MIN_PRIORITY);
1890//      thread.start();
1891    }// actionPerformed();
1892  }//class LoadANNIEWithoutDefaultsAction
1893
1894  /** This class represent an action which loads ANNIE without default param*/
1895  class LoadANNIEWithoutDefaultsAction1 extends AbstractAction
1896                                       implements ANNIEConstants {
1897    public LoadANNIEWithoutDefaultsAction1() {
1898      super("Without defaults");
1899    }// NewAnnotDiffAction
1900    public void actionPerformed(ActionEvent e) {
1901      //Load ANNIE without defaults
1902      CreoleRegister reg = Gate.getCreoleRegister();
1903      // Load each PR as defined in gate.creole.ANNIEConstants.PR_NAMES
1904      for(int i = 0; i < PR_NAMES.length; i++){
1905        ResourceData resData = (ResourceData)reg.get(PR_NAMES[i]);
1906        if (resData != null){
1907          NewResourceDialog resourceDialog = new NewResourceDialog(
1908              MainFrame.this, "Resource parameters", true );
1909          resourceDialog.setTitle(
1910                            "Parameters for the new " + resData.getName());
1911          resourceDialog.show(resData);
1912        }else{
1913          Err.prln(PR_NAMES[i] + " not found in Creole register");
1914        }// End if
1915      }// End for
1916      try{
1917        // Create an application at the end.
1918        Factory.createResource("gate.creole.SerialAnalyserController",
1919                               Factory.newFeatureMap(), Factory.newFeatureMap(),
1920                               "ANNIE_" + Gate.genSym());
1921      }catch(gate.creole.ResourceInstantiationException ex){
1922        ex.printStackTrace(Err.getPrintWriter());
1923      }// End try
1924    }// actionPerformed();
1925  }//class LoadANNIEWithoutDefaultsAction
1926
1927  class NewBootStrapAction extends AbstractAction {
1928    public NewBootStrapAction() {
1929      super("BootStrap Wizard", getIcon("annDiff.gif"));
1930    }// NewBootStrapAction
1931    public void actionPerformed(ActionEvent e) {
1932      BootStrapDialog bootStrapDialog = new BootStrapDialog(MainFrame.this);
1933      bootStrapDialog.show();
1934    }// actionPerformed();
1935  }//class NewBootStrapAction
1936
1937
1938  class LoadCreoleRepositoryAction extends AbstractAction {
1939    public LoadCreoleRepositoryAction(){
1940      super("Load a CREOLE repository");
1941      putValue(SHORT_DESCRIPTION,"Load a CREOLE repository");
1942    }
1943
1944    public void actionPerformed(ActionEvent e) {
1945      Box messageBox = Box.createHorizontalBox();
1946      Box leftBox = Box.createVerticalBox();
1947      JTextField urlTextField = new JTextField(20);
1948      leftBox.add(new JLabel("Type an URL"));
1949      leftBox.add(urlTextField);
1950      messageBox.add(leftBox);
1951
1952      messageBox.add(Box.createHorizontalStrut(10));
1953      messageBox.add(new JLabel("or"));
1954      messageBox.add(Box.createHorizontalStrut(10));
1955
1956      class URLfromFileAction extends AbstractAction{
1957        URLfromFileAction(JTextField textField){
1958          super(null, getIcon("loadFile.gif"));
1959          putValue(SHORT_DESCRIPTION,"Click to select a directory");
1960          this.textField = textField;
1961        }
1962
1963        public void actionPerformed(ActionEvent e){
1964          fileChooser.setMultiSelectionEnabled(false);
1965          fileChooser.setFileSelectionMode(fileChooser.DIRECTORIES_ONLY);
1966          fileChooser.setFileFilter(fileChooser.getAcceptAllFileFilter());
1967          int result = fileChooser.showOpenDialog(MainFrame.this);
1968          if(result == fileChooser.APPROVE_OPTION){
1969            try{
1970              textField.setText(fileChooser.getSelectedFile().
1971                                            toURL().toExternalForm());
1972            }catch(MalformedURLException mue){
1973              throw new GateRuntimeException(mue.toString());
1974            }
1975          }
1976        }
1977        JTextField textField;
1978      };//class URLfromFileAction extends AbstractAction
1979
1980      Box rightBox = Box.createVerticalBox();
1981      rightBox.add(new JLabel("Select a directory"));
1982      JButton fileBtn = new JButton(new URLfromFileAction(urlTextField));
1983      rightBox.add(fileBtn);
1984      messageBox.add(rightBox);
1985
1986
1987//JOptionPane.showInputDialog(
1988//                            MainFrame.this,
1989//                            "Select type of Datastore",
1990//                            "Gate", JOptionPane.QUESTION_MESSAGE,
1991//                            null, names,
1992//                            names[0]);
1993
1994      int res = JOptionPane.showConfirmDialog(
1995                            MainFrame.this, messageBox,
1996                            "Enter an URL to the directory containig the " +
1997                            "\"creole.xml\" file", JOptionPane.OK_CANCEL_OPTION,
1998                            JOptionPane.QUESTION_MESSAGE, null);
1999      if(res == JOptionPane.OK_OPTION){
2000        try{
2001          URL creoleURL = new URL(urlTextField.getText());
2002          Gate.getCreoleRegister().registerDirectories(creoleURL);
2003        }catch(Exception ex){
2004          JOptionPane.showMessageDialog(
2005              MainFrame.this,
2006              "There was a problem with your selection:\n" +
2007              ex.toString() ,
2008              "Gate", JOptionPane.ERROR_MESSAGE);
2009          ex.printStackTrace(Err.getPrintWriter());
2010        }
2011      }
2012    }
2013  }//class LoadCreoleRepositoryAction extends AbstractAction
2014
2015
2016  class NewResourceAction extends AbstractAction {
2017    /** Used for creation of resource menu item and creation dialog */
2018    ResourceData rData;
2019
2020    public NewResourceAction(ResourceData rData) {
2021      super(rData.getName());
2022      putValue(SHORT_DESCRIPTION, rData.getComment());
2023      this.rData = rData;
2024    } // NewResourceAction(ResourceData rData)
2025
2026    public void actionPerformed(ActionEvent evt) {
2027      Runnable runnable = new Runnable(){
2028        public void run(){
2029          newResourceDialog.setTitle(
2030                              "Parameters for the new " + rData.getName());
2031          newResourceDialog.show(rData);
2032        }
2033      };
2034      SwingUtilities.invokeLater(runnable);
2035    } // actionPerformed
2036  } // class NewResourceAction extends AbstractAction
2037
2038
2039  static class StopAction extends AbstractAction {
2040    public StopAction(){
2041      super(" Stop! ");
2042      putValue(SHORT_DESCRIPTION,"Stops the current action");
2043    }
2044
2045    public boolean isEnabled(){
2046      return Gate.getExecutable() != null;
2047    }
2048
2049    public void actionPerformed(ActionEvent e) {
2050      Executable ex = Gate.getExecutable();
2051      if(ex != null) ex.interrupt();
2052    }
2053  }
2054
2055
2056  class NewDSAction extends AbstractAction {
2057    public NewDSAction(){
2058      super("Create datastore");
2059      putValue(SHORT_DESCRIPTION,"Create a new Datastore");
2060    }
2061
2062    public void actionPerformed(ActionEvent e) {
2063      DataStoreRegister reg = Gate.getDataStoreRegister();
2064      Map dsTypes = reg.getDataStoreClassNames();
2065      HashMap dsTypeByName = new HashMap();
2066      Iterator dsTypesIter = dsTypes.entrySet().iterator();
2067      while(dsTypesIter.hasNext()){
2068        Map.Entry entry = (Map.Entry)dsTypesIter.next();
2069        dsTypeByName.put(entry.getValue(), entry.getKey());
2070      }
2071
2072      if(!dsTypeByName.isEmpty()) {
2073        Object[] names = dsTypeByName.keySet().toArray();
2074        Object answer = JOptionPane.showInputDialog(
2075                            MainFrame.this,
2076                            "Select type of Datastore",
2077                            "Gate", JOptionPane.QUESTION_MESSAGE,
2078                            null, names,
2079                            names[0]);
2080        if(answer != null) {
2081          String className = (String)dsTypeByName.get(answer);
2082          if(className.equals("gate.persist.SerialDataStore")){
2083            createSerialDataStore();
2084          } else if(className.equals("gate.persist.OracleDataStore")) {
2085              JOptionPane.showMessageDialog(
2086                    MainFrame.this, "Oracle datastores can only be created " +
2087                                    "by your Oracle administrator!",
2088                                    "Gate", JOptionPane.ERROR_MESSAGE);
2089          }  else {
2090
2091            throw new UnsupportedOperationException("Unimplemented option!\n"+
2092                                                    "Use a serial datastore");
2093          }
2094        }
2095      } else {
2096        //no ds types
2097        JOptionPane.showMessageDialog(MainFrame.this,
2098                                      "Could not find any registered types " +
2099                                      "of datastores...\n" +
2100                                      "Check your Gate installation!",
2101                                      "Gate", JOptionPane.ERROR_MESSAGE);
2102
2103      }
2104    }
2105  }//class NewDSAction extends AbstractAction
2106
2107  class LoadResourceFromFileAction extends AbstractAction {
2108    public LoadResourceFromFileAction(){
2109      super("Restore application from file");
2110      putValue(SHORT_DESCRIPTION,"Restores a previously saved application");
2111    }
2112
2113    public void actionPerformed(ActionEvent e) {
2114      Runnable runnable = new Runnable(){
2115        public void run(){
2116          fileChooser.setDialogTitle("Select a file for this resource");
2117          fileChooser.setFileSelectionMode(fileChooser.FILES_AND_DIRECTORIES);
2118          if (fileChooser.showOpenDialog(MainFrame.this) ==
2119                                                fileChooser.APPROVE_OPTION){
2120            File file = fileChooser.getSelectedFile();
2121            try{
2122              gate.util.persistence.PersistenceManager.loadObjectFromFile(file);
2123            }catch(ResourceInstantiationException rie){
2124              processFinished();
2125              JOptionPane.showMessageDialog(MainFrame.this,
2126                              "Error!\n"+
2127                               rie.toString(),
2128                               "Gate", JOptionPane.ERROR_MESSAGE);
2129              rie.printStackTrace(Err.getPrintWriter());
2130            }catch(Exception ex){
2131              processFinished();
2132              JOptionPane.showMessageDialog(MainFrame.this,
2133                              "Error!\n"+
2134                               ex.toString(),
2135                               "Gate", JOptionPane.ERROR_MESSAGE);
2136              ex.printStackTrace(Err.getPrintWriter());
2137            }
2138          }
2139        }
2140      };
2141      Thread thread = new Thread(runnable);
2142      thread.setPriority(Thread.MIN_PRIORITY);
2143      thread.start();
2144    }
2145  }
2146
2147  /**
2148   * Closes the view associated to a resource.
2149   * Does not remove the resource from the system, only its view.
2150   */
2151  class CloseViewAction extends AbstractAction {
2152    public CloseViewAction(Handle handle) {
2153      super("Hide this view");
2154      putValue(SHORT_DESCRIPTION, "Hides this view");
2155      this.handle = handle;
2156    }
2157
2158    public void actionPerformed(ActionEvent e) {
2159      mainTabbedPane.remove(handle.getLargeView());
2160      mainTabbedPane.setSelectedIndex(mainTabbedPane.getTabCount() - 1);
2161    }//public void actionPerformed(ActionEvent e)
2162    Handle handle;
2163  }//class CloseViewAction
2164
2165  class RenameResourceAction extends AbstractAction{
2166    RenameResourceAction(TreePath path){
2167      super("Rename");
2168      putValue(SHORT_DESCRIPTION, "Renames the resource");
2169      this.path = path;
2170    }
2171    public void actionPerformed(ActionEvent e) {
2172      resourcesTree.startEditingAtPath(path);
2173    }
2174
2175    TreePath path;
2176  }
2177
2178  class CloseSelectedResourcesAction extends AbstractAction {
2179    public CloseSelectedResourcesAction() {
2180      super("Close all");
2181      putValue(SHORT_DESCRIPTION, "Closes the selected resources");
2182    }
2183
2184    public void actionPerformed(ActionEvent e) {
2185      TreePath[] paths = resourcesTree.getSelectionPaths();
2186      for(int i = 0; i < paths.length; i++){
2187        Object userObject = ((DefaultMutableTreeNode)paths[i].
2188                            getLastPathComponent()).getUserObject();
2189        if(userObject instanceof NameBearerHandle){
2190          ((NameBearerHandle)userObject).getCloseAction().actionPerformed(null);
2191        }
2192      }
2193    }
2194  }
2195
2196
2197  /**
2198   * Closes the view associated to a resource.
2199   * Does not remove the resource from the system, only its view.
2200   */
2201  class ExitGateAction extends AbstractAction {
2202    public ExitGateAction() {
2203      super("Exit GATE");
2204      putValue(SHORT_DESCRIPTION, "Closes the application");
2205    }
2206
2207    public void actionPerformed(ActionEvent e) {
2208      Runnable runnable = new Runnable(){
2209        public void run(){
2210          //save the options
2211          OptionsMap userConfig = Gate.getUserConfig();
2212          if(userConfig.getBoolean(GateConstants.SAVE_OPTIONS_ON_EXIT).
2213             booleanValue()){
2214            //save the window size
2215            Integer width = new Integer(MainFrame.this.getWidth());
2216            Integer height = new Integer(MainFrame.this.getHeight());
2217            userConfig.put(GateConstants.MAIN_FRAME_WIDTH, width);
2218            userConfig.put(GateConstants.MAIN_FRAME_HEIGHT, height);
2219            try{
2220              Gate.writeUserConfig();
2221            }catch(GateException ge){
2222              logArea.getOriginalErr().println("Failed to save config data:");
2223              ge.printStackTrace(logArea.getOriginalErr());
2224            }
2225          }else{
2226            //don't save options on close
2227            //save the option not to save the options
2228            OptionsMap originalUserConfig = Gate.getOriginalUserConfig();
2229            originalUserConfig.put(GateConstants.SAVE_OPTIONS_ON_EXIT,
2230                                   new Boolean(false));
2231            userConfig.clear();
2232            userConfig.putAll(originalUserConfig);
2233            try{
2234              Gate.writeUserConfig();
2235            }catch(GateException ge){
2236              logArea.getOriginalErr().println("Failed to save config data:");
2237              ge.printStackTrace(logArea.getOriginalErr());
2238            }
2239          }
2240
2241          //save the session;
2242          File sessionFile = new File(Gate.getUserSessionFileName());
2243          if(userConfig.getBoolean(GateConstants.SAVE_SESSION_ON_EXIT).
2244             booleanValue()){
2245            //save all the open applications
2246            try{
2247              ArrayList appList = new ArrayList(Gate.getCreoleRegister().
2248                                  getAllInstances("gate.Controller"));
2249              //remove all hidden instances
2250              Iterator appIter = appList.iterator();
2251              while(appIter.hasNext())
2252                if(Gate.getHiddenAttribute(((Controller)appIter.next()).
2253                   getFeatures())) appIter.remove();
2254
2255
2256              gate.util.persistence.PersistenceManager.
2257                                    saveObjectToFile(appList, sessionFile);
2258            }catch(Exception ex){
2259              logArea.getOriginalErr().println("Failed to save session data:");
2260              ex.printStackTrace(logArea.getOriginalErr());
2261            }
2262          }else{
2263            //we don't want to save the session
2264            if(sessionFile.exists()) sessionFile.delete();
2265          }
2266          setVisible(false);
2267          dispose();
2268          System.exit(0);
2269        }//run
2270      };//Runnable
2271      Thread thread = new Thread(Thread.currentThread().getThreadGroup(),
2272                                 runnable, "Session loader");
2273      thread.setPriority(Thread.MIN_PRIORITY);
2274      thread.start();
2275    }
2276  }
2277
2278
2279  class OpenDSAction extends AbstractAction {
2280    public OpenDSAction() {
2281      super("Open datastore");
2282      putValue(SHORT_DESCRIPTION,"Open a datastore");
2283    }
2284
2285    public void actionPerformed(ActionEvent e) {
2286      DataStoreRegister reg = Gate.getDataStoreRegister();
2287      Map dsTypes = reg.getDataStoreClassNames();
2288      HashMap dsTypeByName = new HashMap();
2289      Iterator dsTypesIter = dsTypes.entrySet().iterator();
2290      while(dsTypesIter.hasNext()){
2291        Map.Entry entry = (Map.Entry)dsTypesIter.next();
2292        dsTypeByName.put(entry.getValue(), entry.getKey());
2293      }
2294
2295      if(!dsTypeByName.isEmpty()) {
2296        Object[] names = dsTypeByName.keySet().toArray();
2297        Object answer = JOptionPane.showInputDialog(
2298                            MainFrame.this,
2299                            "Select type of Datastore",
2300                            "Gate", JOptionPane.QUESTION_MESSAGE,
2301                            null, names,
2302                            names[0]);
2303        if(answer != null) {
2304          String className = (String)dsTypeByName.get(answer);
2305          if(className.indexOf("SerialDataStore") != -1){
2306            openSerialDataStore();
2307          } else if(className.equals("gate.persist.OracleDataStore") ||
2308                    className.equals("gate.persist.PostgresDataStore")
2309                   ) {
2310              List dbPaths = new ArrayList();
2311              Iterator keyIter = reg.getConfigData().keySet().iterator();
2312              while (keyIter.hasNext()) {
2313                String keyName = (String) keyIter.next();
2314                if (keyName.startsWith("url"))
2315                  dbPaths.add(reg.getConfigData().get(keyName));
2316              }
2317              if (dbPaths.isEmpty())
2318                throw new
2319                  GateRuntimeException("JDBC URL not configured in gate.xml");
2320              //by default make it the first
2321              String storageURL = (String)dbPaths.get(0);
2322              if (dbPaths.size() > 1) {
2323                Object[] paths = dbPaths.toArray();
2324                answer = JOptionPane.showInputDialog(
2325                                    MainFrame.this,
2326                                    "Select a database",
2327                                    "Gate", JOptionPane.QUESTION_MESSAGE,
2328                                    null, paths,
2329                                    paths[0]);
2330                if (answer != null)
2331                  storageURL = (String) answer;
2332                else
2333                  return;
2334              }
2335              DataStore ds = null;
2336              AccessController ac = null;
2337              try {
2338                //1. login the user
2339//                ac = new AccessControllerImpl(storageURL);
2340                ac = Factory.createAccessController(storageURL);
2341                Assert.assertNotNull(ac);
2342                ac.open();
2343
2344                Session mySession = null;
2345                User usr = null;
2346                Group grp = null;
2347                try {
2348                  String userName = "";
2349                  String userPass = "";
2350                  String group = "";
2351
2352                  JPanel listPanel = new JPanel();
2353                  listPanel.setLayout(new BoxLayout(listPanel,BoxLayout.X_AXIS));
2354
2355                  JPanel panel1 = new JPanel();
2356                  panel1.setLayout(new BoxLayout(panel1,BoxLayout.Y_AXIS));
2357                  panel1.add(new JLabel("User name: "));
2358                  panel1.add(new JLabel("Password: "));
2359                  panel1.add(new JLabel("Group: "));
2360
2361                  JPanel panel2 = new JPanel();
2362                  panel2.setLayout(new BoxLayout(panel2,BoxLayout.Y_AXIS));
2363                  JTextField usrField = new JTextField(30);
2364                  panel2.add(usrField);
2365                  JPasswordField pwdField = new JPasswordField(30);
2366                  panel2.add(pwdField);
2367                  JComboBox grpField = new JComboBox(ac.listGroups().toArray());
2368                  grpField.setSelectedIndex(0);
2369                  panel2.add(grpField);
2370
2371                  listPanel.add(panel1);
2372                  listPanel.add(Box.createHorizontalStrut(20));
2373                  listPanel.add(panel2);
2374
2375                  if(OkCancelDialog.showDialog(MainFrame.this.getContentPane(),
2376                                                listPanel,
2377                                                "Please enter login details")){
2378
2379                    userName = usrField.getText();
2380                    userPass = new String(pwdField.getPassword());
2381                    group = (String) grpField.getSelectedItem();
2382
2383                    if(userName.equals("") || userPass.equals("") || group.equals("")) {
2384                      JOptionPane.showMessageDialog(
2385                        MainFrame.this,
2386                        "You must provide non-empty user name, password and group!",
2387                        "Login error",
2388                        JOptionPane.ERROR_MESSAGE
2389                        );
2390                      return;
2391                    }
2392                  }
2393                  else if(OkCancelDialog.userHasPressedCancel) {
2394                      return;
2395                  }
2396
2397                  grp = ac.findGroup(group);
2398                  usr = ac.findUser(userName);
2399                  mySession = ac.login(userName, userPass, grp.getID());
2400
2401                  //save here the user name, pass and group in local gate.xml
2402
2403                } catch (gate.security.SecurityException ex) {
2404                    JOptionPane.showMessageDialog(
2405                      MainFrame.this,
2406                      ex.getMessage(),
2407                      "Login error",
2408                      JOptionPane.ERROR_MESSAGE
2409                      );
2410                  ac.close();
2411                  return;
2412                }
2413
2414                if (! ac.isValidSession(mySession)){
2415                  JOptionPane.showMessageDialog(
2416                    MainFrame.this,
2417                    "Incorrect session obtained. "
2418                      + "Probably there is a problem with the database!",
2419                    "Login error",
2420                    JOptionPane.ERROR_MESSAGE
2421                    );
2422                  ac.close();
2423                  return;
2424                }
2425
2426                //2. open the oracle datastore
2427                ds = Factory.openDataStore(className, storageURL);
2428                //set the session, so all get/adopt/etc work
2429                ds.setSession(mySession);
2430
2431                //3. add the security data for this datastore
2432                //this saves the user and group information, so it can
2433                //be used later when resources are created with certain rights
2434                FeatureMap securityData = Factory.newFeatureMap();
2435                securityData.put("user", usr);
2436                securityData.put("group", grp);
2437                reg.addSecurityData(ds, securityData);
2438              } catch(PersistenceException pe) {
2439                JOptionPane.showMessageDialog(
2440                    MainFrame.this, "Datastore open error!\n " +
2441                                      pe.toString(),
2442                                      "Gate", JOptionPane.ERROR_MESSAGE);
2443              } catch(gate.security.SecurityException se) {
2444                JOptionPane.showMessageDialog(
2445                    MainFrame.this, "User identification error!\n " +
2446                                      se.toString(),
2447                                      "Gate", JOptionPane.ERROR_MESSAGE);
2448                try {
2449                  if (ac != null)
2450                    ac.close();
2451                  if (ds != null)
2452                    ds.close();
2453                } catch (gate.persist.PersistenceException ex) {
2454                  JOptionPane.showMessageDialog(
2455                      MainFrame.this, "Persistence error!\n " +
2456                                        ex.toString(),
2457                                        "Gate", JOptionPane.ERROR_MESSAGE);
2458                }
2459              }
2460
2461          }else{
2462            JOptionPane.showMessageDialog(
2463                MainFrame.this,
2464                "Support for this type of datastores is not implemenented!\n",
2465                "Gate", JOptionPane.ERROR_MESSAGE);
2466          }
2467        }
2468      } else {
2469        //no ds types
2470        JOptionPane.showMessageDialog(MainFrame.this,
2471                                      "Could not find any registered types " +
2472                                      "of datastores...\n" +
2473                                      "Check your Gate installation!",
2474                                      "Gate", JOptionPane.ERROR_MESSAGE);
2475
2476      }
2477    }
2478  }//class OpenDSAction extends AbstractAction
2479
2480  class HelpAboutAction extends AbstractAction {
2481    public HelpAboutAction(){
2482      super("About");
2483    }
2484
2485    public void actionPerformed(ActionEvent e) {
2486      splash.show();
2487    }
2488  }
2489
2490  class HelpUserGuideAction extends AbstractAction {
2491    public HelpUserGuideAction(){
2492      super("User Guide");
2493      putValue(SHORT_DESCRIPTION, "This option needs an internet connection");
2494    }
2495
2496    public void actionPerformed(ActionEvent e) {
2497
2498      Runnable runnable = new Runnable(){
2499        public void run(){
2500          try{
2501            HelpFrame helpFrame = new HelpFrame();
2502            helpFrame.setPage(new URL("http://www.gate.ac.uk/sale/tao/index.html"));
2503            helpFrame.setSize(800, 600);
2504            //center on screen
2505            Dimension frameSize = helpFrame.getSize();
2506            Dimension ownerSize = Toolkit.getDefaultToolkit().getScreenSize();
2507            Point ownerLocation = new Point(0, 0);
2508            helpFrame.setLocation(
2509                      ownerLocation.x + (ownerSize.width - frameSize.width) / 2,
2510                      ownerLocation.y + (ownerSize.height - frameSize.height) / 2);
2511
2512            helpFrame.setVisible(true);
2513          }catch(IOException ioe){
2514            ioe.printStackTrace(Err.getPrintWriter());
2515          }
2516        }
2517      };
2518      Thread thread = new Thread(runnable);
2519      thread.start();
2520    }
2521  }
2522
2523  protected class ResourcesTreeCellRenderer extends DefaultTreeCellRenderer {
2524    public ResourcesTreeCellRenderer() {
2525      setBorder(BorderFactory.createEmptyBorder(2,2,2,2));
2526    }
2527    public Component getTreeCellRendererComponent(JTree tree,
2528                                              Object value,
2529                                              boolean sel,
2530                                              boolean expanded,
2531                                              boolean leaf,
2532                                              int row,
2533                                              boolean hasFocus){
2534      super.getTreeCellRendererComponent(tree, value, sel, expanded,
2535                                         leaf, row, hasFocus);
2536      if(value == resourcesTreeRoot) {
2537        setIcon(MainFrame.getIcon("project.gif"));
2538        setToolTipText("Gate");
2539      } else if(value == applicationsRoot) {
2540        setIcon(MainFrame.getIcon("applications.gif"));
2541        setToolTipText("Gate applications");
2542      } else if(value == languageResourcesRoot) {
2543        setIcon(MainFrame.getIcon("lrs.gif"));
2544        setToolTipText("Language Resources");
2545      } else if(value == processingResourcesRoot) {
2546        setIcon(MainFrame.getIcon("prs.gif"));
2547        setToolTipText("Processing Resources");
2548      } else if(value == datastoresRoot) {
2549        setIcon(MainFrame.getIcon("dss.gif"));
2550        setToolTipText("Gate Datastores");
2551      }else{
2552        //not one of the default root nodes
2553        value = ((DefaultMutableTreeNode)value).getUserObject();
2554        if(value instanceof Handle) {
2555          setIcon(((Handle)value).getIcon());
2556          setText(((Handle)value).getTitle());
2557          setToolTipText(((Handle)value).getTooltipText());
2558        }
2559      }
2560      return this;
2561    }
2562
2563    public Component getTreeCellRendererComponent1(JTree tree,
2564                                              Object value,
2565                                              boolean sel,
2566                                              boolean expanded,
2567                                              boolean leaf,
2568                                              int row,
2569                                              boolean hasFocus) {
2570      super.getTreeCellRendererComponent(tree, value, selected, expanded,
2571                                         leaf, row, hasFocus);
2572      Object handle = ((DefaultMutableTreeNode)value).getUserObject();
2573      if(handle != null && handle instanceof Handle){
2574        setIcon(((Handle)handle).getIcon());
2575        setText(((Handle)handle).getTitle());
2576        setToolTipText(((Handle)handle).getTooltipText());
2577      }
2578      return this;
2579    }
2580  }
2581
2582  protected class ResourcesTreeCellEditor extends DefaultTreeCellEditor {
2583    ResourcesTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer){
2584      super(tree, renderer);
2585    }
2586
2587    /**
2588     * This is the original implementation from the super class with some
2589     * changes (i.e. shorter timer: 500 ms instead of 1200)
2590     */
2591    protected void startEditingTimer() {
2592      if(timer == null) {
2593        timer = new javax.swing.Timer(500, this);
2594        timer.setRepeats(false);
2595      }
2596      timer.start();
2597    }
2598
2599    /**
2600     * This is the original implementation from the super class with some
2601     * changes (i.e. correct discovery of icon)
2602     */
2603    public Component getTreeCellEditorComponent(JTree tree, Object value,
2604                                                boolean isSelected,
2605                                                boolean expanded,
2606                                                boolean leaf, int row) {
2607      Component retValue = super.getTreeCellEditorComponent(tree, value,
2608                                                            isSelected,
2609                                                            expanded,
2610                                                            leaf, row);
2611      //lets find the actual icon
2612      if(renderer != null) {
2613        renderer.getTreeCellRendererComponent(tree, value, isSelected, expanded,
2614                                              leaf, row, false);
2615        editingIcon = renderer.getIcon();
2616      }
2617      return retValue;
2618    }
2619  }//protected class ResourcesTreeCellEditor extends DefaultTreeCellEditor {
2620
2621  protected class ResourcesTreeModel extends DefaultTreeModel {
2622    ResourcesTreeModel(TreeNode root, boolean asksAllowChildren){
2623      super(root, asksAllowChildren);
2624    }
2625
2626    public void valueForPathChanged(TreePath path, Object newValue){
2627      DefaultMutableTreeNode   aNode = (DefaultMutableTreeNode)
2628                                       path.getLastPathComponent();
2629      Object userObject = aNode.getUserObject();
2630      if(userObject instanceof Handle){
2631        Object target = ((Handle)userObject).getTarget();
2632        if(target instanceof Resource){
2633          Gate.getCreoleRegister().setResourceName((Resource)target,
2634                                                   (String)newValue);
2635        }
2636      }
2637      nodeChanged(aNode);
2638    }
2639  }
2640
2641
2642  /**
2643   * Model for the tree representing the resources loaded in the system
2644   */
2645/*
2646  class ResourcesTreeModel extends DefaultTreeModel {
2647    ResourcesTreeModel(TreeNode root){
2648      super(root);
2649    }
2650
2651    public Object getRoot(){
2652      return resourcesTreeRoot;
2653    }
2654
2655    public Object getChild(Object parent,
2656                       int index){
2657      return getChildren(parent).get(index);
2658    }
2659
2660    public int getChildCount(Object parent){
2661      return getChildren(parent).size();
2662    }
2663
2664    public boolean isLeaf(Object node){
2665      return getChildren(node).isEmpty();
2666    }
2667
2668    public int getIndexOfChild(Object parent,
2669                           Object child){
2670      return getChildren(parent).indexOf(child);
2671    }
2672
2673    protected List getChildren(Object parent) {
2674      List result = new ArrayList();
2675      if(parent == resourcesTreeRoot){
2676        result.add(applicationsRoot);
2677        result.add(languageResourcesRoot);
2678        result.add(processingResourcesRoot);
2679        result.add(datastoresRoot);
2680      } else if(parent == applicationsRoot) {
2681//        result.addAll(currentProject.getApplicationsList());
2682      } else if(parent == languageResourcesRoot) {
2683        result.addAll(Gate.getCreoleRegister().getLrInstances());
2684      } else if(parent == processingResourcesRoot) {
2685        result.addAll(Gate.getCreoleRegister().getPrInstances());
2686      } else if(parent == datastoresRoot) {
2687        result.addAll(Gate.getDataStoreRegister());
2688      }
2689      ListIterator iter = result.listIterator();
2690      while(iter.hasNext()) {
2691        Object value = iter.next();
2692        ResourceData rData = (ResourceData)
2693                      Gate.getCreoleRegister().get(value.getClass().getName());
2694        if(rData != null && rData.isPrivate()) iter.remove();
2695      }
2696      return result;
2697    }
2698
2699    public synchronized void removeTreeModelListener(TreeModelListener l) {
2700      if (treeModelListeners != null && treeModelListeners.contains(l)) {
2701        Vector v = (Vector) treeModelListeners.clone();
2702        v.removeElement(l);
2703        treeModelListeners = v;
2704      }
2705    }
2706
2707    public synchronized void addTreeModelListener(TreeModelListener l) {
2708      Vector v = treeModelListeners ==
2709                    null ? new Vector(2) : (Vector) treeModelListeners.clone();
2710      if (!v.contains(l)) {
2711        v.addElement(l);
2712        treeModelListeners = v;
2713      }
2714    }
2715
2716    void treeChanged(){
2717      SwingUtilities.invokeLater(new Runnable(){
2718        public void run() {
2719          fireTreeStructureChanged(new TreeModelEvent(
2720                                        this,new Object[]{resourcesTreeRoot}));
2721        }
2722      });
2723    }
2724
2725    public void valueForPathChanged(TreePath path,
2726                                Object newValue){
2727      fireTreeNodesChanged(new TreeModelEvent(this,path));
2728    }
2729
2730    protected void fireTreeNodesChanged(TreeModelEvent e) {
2731      if (treeModelListeners != null) {
2732        Vector listeners = treeModelListeners;
2733        int count = listeners.size();
2734        for (int i = 0; i < count; i++) {
2735          ((TreeModelListener) listeners.elementAt(i)).treeNodesChanged(e);
2736        }
2737      }
2738    }
2739
2740    protected void fireTreeNodesInserted(TreeModelEvent e) {
2741      if (treeModelListeners != null) {
2742        Vector listeners = treeModelListeners;
2743        int count = listeners.size();
2744        for (int i = 0; i < count; i++) {
2745          ((TreeModelListener) listeners.elementAt(i)).treeNodesInserted(e);
2746        }
2747      }
2748    }
2749
2750    protected void fireTreeNodesRemoved(TreeModelEvent e) {
2751      if (treeModelListeners != null) {
2752        Vector listeners = treeModelListeners;
2753        int count = listeners.size();
2754        for (int i = 0; i < count; i++) {
2755          ((TreeModelListener) listeners.elementAt(i)).treeNodesRemoved(e);
2756        }
2757      }
2758    }
2759
2760    protected void fireTreeStructureChanged(TreeModelEvent e) {
2761      if (treeModelListeners != null) {
2762        Vector listeners = treeModelListeners;
2763        int count = listeners.size();
2764        for (int i = 0; i < count; i++) {
2765          ((TreeModelListener) listeners.elementAt(i)).treeStructureChanged(e);
2766        }
2767      }
2768    }
2769
2770    private transient Vector treeModelListeners;
2771  }
2772*/
2773
2774  class ProgressBarUpdater implements Runnable{
2775    ProgressBarUpdater(int newValue){
2776      value = newValue;
2777    }
2778    public void run(){
2779      progressBar.setValue(value);
2780    }
2781
2782    int value;
2783  }
2784
2785  class StatusBarUpdater implements Runnable {
2786    StatusBarUpdater(String text){
2787      this.text = text;
2788    }
2789    public void run(){
2790      statusBar.setText(text);
2791    }
2792    String text;
2793  }
2794
2795  /**
2796   * During longer operations it is nice to keep the user entertained so
2797   * (s)he doesn't fall asleep looking at a progress bar that seems have
2798   * stopped. Also there are some operations that do not support progress
2799   * reporting so the progress bar would not work at all so we need a way
2800   * to let the user know that things are happening. We chose for purpose
2801   * to show the user a small cartoon in the form of an animated gif.
2802   * This class handles the diplaying and updating of those cartoons.
2803   */
2804  class CartoonMinder implements Runnable{
2805
2806    CartoonMinder(JPanel targetPanel){
2807      active = false;
2808      dying = false;
2809      this.targetPanel = targetPanel;
2810      imageLabel = new JLabel(getIcon("working.gif"));
2811      imageLabel.setOpaque(false);
2812      imageLabel.setBorder(BorderFactory.createEmptyBorder(3,3,3,3));
2813    }
2814
2815    public boolean isActive(){
2816      boolean res;
2817      synchronized(lock){
2818        res = active;
2819      }
2820      return res;
2821    }
2822
2823    public void activate(){
2824      //add the label in the panel
2825      SwingUtilities.invokeLater(new Runnable(){
2826        public void run(){
2827          targetPanel.add(imageLabel);
2828        }
2829      });
2830      //wake the dorment thread
2831      synchronized(lock){
2832        active = true;
2833      }
2834    }
2835
2836    public void deactivate(){
2837      //send the thread to sleep
2838      synchronized(lock){
2839        active = false;
2840      }
2841      //clear the panel
2842      SwingUtilities.invokeLater(new Runnable(){
2843        public void run(){
2844          targetPanel.removeAll();
2845          targetPanel.repaint();
2846        }
2847      });
2848    }
2849
2850    public void dispose(){
2851      synchronized(lock){
2852        dying = true;
2853      }
2854    }
2855
2856    public void run(){
2857      boolean isDying;
2858      synchronized(lock){
2859        isDying = dying;
2860      }
2861      while(!isDying){
2862        boolean isActive;
2863        synchronized(lock){
2864          isActive = active;
2865        }
2866        if(isActive && targetPanel.isVisible()){
2867          SwingUtilities.invokeLater(new Runnable(){
2868            public void run(){
2869//              targetPanel.getParent().validate();
2870//              targetPanel.getParent().repaint();
2871//              ((JComponent)targetPanel.getParent()).paintImmediately(((JComponent)targetPanel.getParent()).getBounds());
2872//              targetPanel.doLayout();
2873
2874//              targetPanel.requestFocus();
2875              targetPanel.getParent().getParent().invalidate();
2876              targetPanel.getParent().getParent().repaint();
2877//              targetPanel.paintImmediately(targetPanel.getBounds());
2878            }
2879          });
2880        }
2881        //sleep
2882        try{
2883          Thread.sleep(300);
2884        }catch(InterruptedException ie){}
2885
2886        synchronized(lock){
2887          isDying = dying;
2888        }
2889      }//while(!isDying)
2890    }
2891
2892    boolean dying;
2893    boolean active;
2894    String lock = "lock";
2895    JPanel targetPanel;
2896    JLabel imageLabel;
2897  }
2898
2899/*
2900  class JGateMenuItem extends JMenuItem {
2901    JGateMenuItem(javax.swing.Action a){
2902      super(a);
2903      this.addMouseListener(new MouseAdapter() {
2904        public void mouseEntered(MouseEvent e) {
2905          oldText = statusBar.getText();
2906          statusChanged((String)getAction().
2907                        getValue(javax.swing.Action.SHORT_DESCRIPTION));
2908        }
2909
2910        public void mouseExited(MouseEvent e) {
2911          statusChanged(oldText);
2912        }
2913      });
2914    }
2915    String oldText;
2916  }
2917
2918  class JGateButton extends JButton {
2919    JGateButton(javax.swing.Action a){
2920      super(a);
2921      this.addMouseListener(new MouseAdapter() {
2922        public void mouseEntered(MouseEvent e) {
2923          oldText = statusBar.getText();
2924          statusChanged((String)getAction().
2925                        getValue(javax.swing.Action.SHORT_DESCRIPTION));
2926        }
2927
2928        public void mouseExited(MouseEvent e) {
2929          statusChanged(oldText);
2930        }
2931      });
2932    }
2933    String oldText;
2934  }
2935*/
2936  class LocaleSelectorMenuItem extends JRadioButtonMenuItem {
2937    public LocaleSelectorMenuItem(Locale locale) {
2938      super(locale.getDisplayName());
2939      me = this;
2940      myLocale = locale;
2941      this.addActionListener(new ActionListener()  {
2942        public void actionPerformed(ActionEvent e) {
2943          Iterator rootIter = MainFrame.getGuiRoots().iterator();
2944          while(rootIter.hasNext()){
2945            Object aRoot = rootIter.next();
2946            if(aRoot instanceof Window){
2947              me.setSelected(((Window)aRoot).getInputContext().
2948                              selectInputMethod(myLocale));
2949            }
2950          }
2951        }
2952      });
2953    }
2954
2955    public LocaleSelectorMenuItem() {
2956      super("System default  >>" +
2957            Locale.getDefault().getDisplayName() + "<<");
2958      me = this;
2959      myLocale = Locale.getDefault();
2960      this.addActionListener(new ActionListener()  {
2961        public void actionPerformed(ActionEvent e) {
2962          Iterator rootIter = MainFrame.getGuiRoots().iterator();
2963          while(rootIter.hasNext()){
2964            Object aRoot = rootIter.next();
2965            if(aRoot instanceof Window){
2966              me.setSelected(((Window)aRoot).getInputContext().
2967                              selectInputMethod(myLocale));
2968            }
2969          }
2970        }
2971      });
2972    }
2973
2974    Locale myLocale;
2975    JRadioButtonMenuItem me;
2976  }////class LocaleSelectorMenuItem extends JRadioButtonMenuItem
2977
2978  /**ontotext.bp
2979   * This class represent an action which brings up the Ontology Editor tool*/
2980  class NewOntologyEditorAction extends AbstractAction {
2981    public NewOntologyEditorAction(){
2982      super("Ontology Editor", getIcon("controller.gif"));
2983      putValue(SHORT_DESCRIPTION,"Start the Ontology Editor");
2984    }// NewAnnotDiffAction
2985
2986    public void actionPerformed(ActionEvent e) {
2987      OntologyEditorImpl editor = new OntologyEditorImpl();
2988      try {
2989        JFrame frame = new JFrame();
2990        editor.init();
2991        frame.setTitle("Ontology Editor");
2992        frame.getContentPane().add(editor);
2993        /*
2994          SET ONTOLOGY LIST AND ONTOLOGY
2995        */
2996        Set ontologies = new HashSet(Gate.getCreoleRegister().getLrInstances(
2997          "gate.creole.ontology.Ontology"));
2998
2999        editor.setOntologyList(new Vector(ontologies));
3000
3001        frame.setSize(editor.SIZE_X,editor.SIZE_Y);
3002        frame.setLocation(editor.POSITION_X,editor.POSITION_Y);
3003        frame.setVisible(true);
3004        editor.visualize();
3005      } catch ( ResourceInstantiationException ex ) {
3006        ex.printStackTrace(Err.getPrintWriter());
3007      }
3008    }// actionPerformed();
3009  }//class NewOntologyEditorAction
3010
3011  /** This class represent an action which brings up the Gazetteer Editor tool*/
3012  class NewGazetteerEditorAction extends AbstractAction {
3013    public NewGazetteerEditorAction(){
3014      super("Gazetteer Editor", getIcon("controller.gif"));
3015      putValue(SHORT_DESCRIPTION,"Start the Gazetteer Editor");
3016    }
3017
3018    public void actionPerformed(ActionEvent e) {
3019      com.ontotext.gate.vr.Gaze editor = new com.ontotext.gate.vr.Gaze();
3020      try {
3021        JFrame frame = new JFrame();
3022        editor.init();
3023        frame.setTitle("Gazetteer Editor");
3024        frame.getContentPane().add(editor);
3025
3026        Set gazetteers = new HashSet(Gate.getCreoleRegister().getLrInstances(
3027          "gate.creole.gazetteer.DefaultGazetteer"));
3028        if (gazetteers == null || gazetteers.isEmpty())
3029          return;
3030        Iterator iter = gazetteers.iterator();
3031        while (iter.hasNext()) {
3032          gate.creole.gazetteer.Gazetteer gaz =
3033            (gate.creole.gazetteer.Gazetteer) iter.next();
3034          if (gaz.getListsURL().toString().endsWith(System.getProperty("gate.slug.gazetteer")))
3035           editor.setTarget(gaz);
3036        }
3037
3038        frame.setSize(editor.SIZE_X,editor.SIZE_Y);
3039        frame.setLocation(editor.POSITION_X,editor.POSITION_Y);
3040        frame.setVisible(true);
3041        editor.setVisible(true);
3042      } catch ( ResourceInstantiationException ex ) {
3043        ex.printStackTrace(Err.getPrintWriter());
3044      }
3045    }// actionPerformed();
3046  }//class NewOntologyEditorAction
3047
3048} // class MainFrame
3049