JAL-1747 close all windows on Quit (+small bug fix)
[jalview.git] / src / jalview / gui / Desktop.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Dimension;
26 import java.awt.FontMetrics;
27 import java.awt.Graphics;
28 import java.awt.GridLayout;
29 import java.awt.Point;
30 import java.awt.Rectangle;
31 import java.awt.Toolkit;
32 import java.awt.datatransfer.Clipboard;
33 import java.awt.datatransfer.ClipboardOwner;
34 import java.awt.datatransfer.DataFlavor;
35 import java.awt.datatransfer.Transferable;
36 import java.awt.dnd.DnDConstants;
37 import java.awt.dnd.DropTargetDragEvent;
38 import java.awt.dnd.DropTargetDropEvent;
39 import java.awt.dnd.DropTargetEvent;
40 import java.awt.dnd.DropTargetListener;
41 import java.awt.event.ActionEvent;
42 import java.awt.event.ActionListener;
43 import java.awt.event.FocusEvent;
44 import java.awt.event.FocusListener;
45 import java.awt.event.MouseAdapter;
46 import java.awt.event.MouseEvent;
47 import java.awt.event.MouseListener;
48 import java.awt.event.WindowAdapter;
49 import java.awt.event.WindowEvent;
50 import java.beans.PropertyChangeEvent;
51 import java.beans.PropertyChangeListener;
52 import java.beans.PropertyVetoException;
53 import java.io.BufferedInputStream;
54 import java.io.File;
55 import java.io.FileOutputStream;
56 import java.lang.reflect.Constructor;
57 import java.net.URL;
58 import java.util.ArrayList;
59 import java.util.Hashtable;
60 import java.util.List;
61 import java.util.StringTokenizer;
62 import java.util.Vector;
63 import java.util.concurrent.ExecutorService;
64 import java.util.concurrent.Executors;
65 import java.util.concurrent.Semaphore;
66
67 import javax.swing.DefaultDesktopManager;
68 import javax.swing.DesktopManager;
69 import javax.swing.JButton;
70 import javax.swing.JComboBox;
71 import javax.swing.JComponent;
72 import javax.swing.JDesktopPane;
73 import javax.swing.JFrame;
74 import javax.swing.JInternalFrame;
75 import javax.swing.JLabel;
76 import javax.swing.JMenuItem;
77 import javax.swing.JOptionPane;
78 import javax.swing.JPanel;
79 import javax.swing.JPopupMenu;
80 import javax.swing.JProgressBar;
81 import javax.swing.SwingUtilities;
82 import javax.swing.event.HyperlinkEvent;
83 import javax.swing.event.HyperlinkEvent.EventType;
84 import javax.swing.event.MenuEvent;
85 import javax.swing.event.MenuListener;
86
87 import jalview.api.AlignViewportI;
88 import jalview.api.AlignmentViewPanel;
89 import jalview.bin.Cache;
90 import jalview.io.FileLoader;
91 import jalview.io.FormatAdapter;
92 import jalview.io.IdentifyFile;
93 import jalview.io.JalviewFileChooser;
94 import jalview.io.JalviewFileView;
95 import jalview.jbgui.GSplitFrame;
96 import jalview.jbgui.GStructureViewer;
97 import jalview.structure.StructureSelectionManager;
98 import jalview.util.ImageMaker;
99 import jalview.util.MessageManager;
100 import jalview.viewmodel.AlignmentViewport;
101 import jalview.ws.params.ParamManager;
102
103 /**
104  * Jalview Desktop
105  * 
106  * 
107  * @author $author$
108  * @version $Revision: 1.155 $
109  */
110 public class Desktop extends jalview.jbgui.GDesktop implements
111         DropTargetListener, ClipboardOwner, IProgressIndicator,
112         jalview.api.StructureSelectionManagerProvider
113 {
114
115   private JalviewChangeSupport changeSupport = new JalviewChangeSupport();
116
117   /**
118    * news reader - null if it was never started.
119    */
120   private BlogReader jvnews = null;
121
122   private File projectFile;
123
124   /**
125    * @param listener
126    * @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.beans.PropertyChangeListener)
127    */
128   public void addJalviewPropertyChangeListener(
129           PropertyChangeListener listener)
130   {
131     changeSupport.addJalviewPropertyChangeListener(listener);
132   }
133
134   /**
135    * @param propertyName
136    * @param listener
137    * @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.lang.String,
138    *      java.beans.PropertyChangeListener)
139    */
140   public void addJalviewPropertyChangeListener(String propertyName,
141           PropertyChangeListener listener)
142   {
143     changeSupport.addJalviewPropertyChangeListener(propertyName, listener);
144   }
145
146   /**
147    * @param propertyName
148    * @param listener
149    * @see jalview.gui.JalviewChangeSupport#removeJalviewPropertyChangeListener(java.lang.String,
150    *      java.beans.PropertyChangeListener)
151    */
152   public void removeJalviewPropertyChangeListener(String propertyName,
153           PropertyChangeListener listener)
154   {
155     changeSupport.removeJalviewPropertyChangeListener(propertyName,
156             listener);
157   }
158
159   /** Singleton Desktop instance */
160   public static Desktop instance;
161
162   public static MyDesktopPane desktop;
163
164   static int openFrameCount = 0;
165
166   static final int xOffset = 30;
167
168   static final int yOffset = 30;
169
170   private static final int THREE = 3;
171
172   private static AlignFrame currentAlignFrame;
173
174   public static jalview.ws.jws1.Discoverer discoverer;
175
176   public static Object[] jalviewClipboard;
177
178   public static boolean internalCopy = false;
179
180   static int fileLoadingCount = 0;
181
182   class MyDesktopManager implements DesktopManager
183   {
184
185     private DesktopManager delegate;
186
187     public MyDesktopManager(DesktopManager delegate)
188     {
189       this.delegate = delegate;
190     }
191
192     public void activateFrame(JInternalFrame f)
193     {
194       try
195       {
196         delegate.activateFrame(f);
197       } catch (NullPointerException npe)
198       {
199         Point p = getMousePosition();
200         instance.showPasteMenu(p.x, p.y);
201       }
202     }
203
204     public void beginDraggingFrame(JComponent f)
205     {
206       delegate.beginDraggingFrame(f);
207     }
208
209     public void beginResizingFrame(JComponent f, int direction)
210     {
211       delegate.beginResizingFrame(f, direction);
212     }
213
214     public void closeFrame(JInternalFrame f)
215     {
216       delegate.closeFrame(f);
217     }
218
219     public void deactivateFrame(JInternalFrame f)
220     {
221       delegate.deactivateFrame(f);
222     }
223
224     public void deiconifyFrame(JInternalFrame f)
225     {
226       delegate.deiconifyFrame(f);
227     }
228
229     public void dragFrame(JComponent f, int newX, int newY)
230     {
231       if (newY < 0)
232       {
233         newY = 0;
234       }
235       delegate.dragFrame(f, newX, newY);
236     }
237
238     public void endDraggingFrame(JComponent f)
239     {
240       delegate.endDraggingFrame(f);
241     }
242
243     public void endResizingFrame(JComponent f)
244     {
245       delegate.endResizingFrame(f);
246     }
247
248     public void iconifyFrame(JInternalFrame f)
249     {
250       delegate.iconifyFrame(f);
251     }
252
253     public void maximizeFrame(JInternalFrame f)
254     {
255       delegate.maximizeFrame(f);
256     }
257
258     public void minimizeFrame(JInternalFrame f)
259     {
260       delegate.minimizeFrame(f);
261     }
262
263     public void openFrame(JInternalFrame f)
264     {
265       delegate.openFrame(f);
266     }
267
268     public void resizeFrame(JComponent f, int newX, int newY, int newWidth,
269             int newHeight)
270     {
271       Rectangle b = desktop.getBounds();
272       if (newY < 0)
273       {
274         newY = 0;
275       }
276       delegate.resizeFrame(f, newX, newY, newWidth, newHeight);
277     }
278
279     public void setBoundsForFrame(JComponent f, int newX, int newY,
280             int newWidth, int newHeight)
281     {
282       delegate.setBoundsForFrame(f, newX, newY, newWidth, newHeight);
283     }
284
285     // All other methods, simply delegate
286
287   }
288
289   /**
290    * Creates a new Desktop object.
291    */
292   public Desktop()
293   {
294     /**
295      * A note to implementors. It is ESSENTIAL that any activities that might
296      * block are spawned off as threads rather than waited for during this
297      * constructor.
298      */
299     instance = this;
300     doVamsasClientCheck();
301     doGroovyCheck();
302     doConfigureStructurePrefs();
303     setTitle("Jalview " + jalview.bin.Cache.getProperty("VERSION"));
304     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
305     boolean selmemusage = jalview.bin.Cache.getDefault("SHOW_MEMUSAGE",
306             false);
307     boolean showjconsole = jalview.bin.Cache.getDefault(
308             "SHOW_JAVA_CONSOLE", false);
309     desktop = new MyDesktopPane(selmemusage);
310     showMemusage.setSelected(selmemusage);
311     desktop.setBackground(Color.white);
312     getContentPane().setLayout(new BorderLayout());
313     // alternate config - have scrollbars - see notes in JAL-153
314     // JScrollPane sp = new JScrollPane();
315     // sp.getViewport().setView(desktop);
316     // getContentPane().add(sp, BorderLayout.CENTER);
317     getContentPane().add(desktop, BorderLayout.CENTER);
318     desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
319
320     // This line prevents Windows Look&Feel resizing all new windows to maximum
321     // if previous window was maximised
322     desktop.setDesktopManager(new MyDesktopManager(
323             new DefaultDesktopManager()));
324
325     Rectangle dims = getLastKnownDimensions("");
326     if (dims != null)
327     {
328       setBounds(dims);
329     }
330     else
331     {
332       Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
333       setBounds((screenSize.width - 900) / 2,
334               (screenSize.height - 650) / 2, 900, 650);
335     }
336     jconsole = new Console(this, showjconsole);
337     // add essential build information
338     jconsole.setHeader("Jalview Version: "
339             + jalview.bin.Cache.getProperty("VERSION") + "\n"
340             + "Jalview Installation: "
341             + jalview.bin.Cache.getDefault("INSTALLATION", "unknown")
342             + "\n" + "Build Date: "
343             + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown") + "\n"
344             + "Java version: " + System.getProperty("java.version") + "\n"
345             + System.getProperty("os.arch") + " "
346             + System.getProperty("os.name") + " "
347             + System.getProperty("os.version"));
348
349     showConsole(showjconsole);
350
351     showNews.setVisible(false);
352
353     this.addWindowListener(new WindowAdapter()
354     {
355       public void windowClosing(WindowEvent evt)
356       {
357         quit();
358       }
359     });
360
361     MouseAdapter ma;
362     this.addMouseListener(ma = new MouseAdapter()
363     {
364       public void mousePressed(MouseEvent evt)
365       {
366         if (SwingUtilities.isRightMouseButton(evt))
367         {
368           showPasteMenu(evt.getX(), evt.getY());
369         }
370       }
371     });
372     desktop.addMouseListener(ma);
373
374     this.addFocusListener(new FocusListener()
375     {
376
377       @Override
378       public void focusLost(FocusEvent e)
379       {
380         // TODO Auto-generated method stub
381
382       }
383
384       @Override
385       public void focusGained(FocusEvent e)
386       {
387         Cache.log.debug("Relaying windows after focus gain");
388         // make sure that we sort windows properly after we gain focus
389         instance.relayerWindows();
390       }
391     });
392     this.setDropTarget(new java.awt.dnd.DropTarget(desktop, this));
393     // Spawn a thread that shows the splashscreen
394     SwingUtilities.invokeLater(new Runnable()
395     {
396       public void run()
397       {
398         new SplashScreen();
399       }
400     });
401
402     // displayed.
403     // Thread off a new instance of the file chooser - this reduces the time it
404     // takes to open it later on.
405     new Thread(new Runnable()
406     {
407       public void run()
408       {
409         Cache.log.debug("Filechooser init thread started.");
410         JalviewFileChooser chooser = new JalviewFileChooser(
411                 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
412                 jalview.io.AppletFormatAdapter.READABLE_EXTENSIONS,
413                 jalview.io.AppletFormatAdapter.READABLE_FNAMES,
414                 jalview.bin.Cache.getProperty("DEFAULT_FILE_FORMAT"));
415         Cache.log.debug("Filechooser init thread finished.");
416       }
417     }).start();
418     // Add the service change listener
419     changeSupport.addJalviewPropertyChangeListener("services",
420             new PropertyChangeListener()
421             {
422
423               @Override
424               public void propertyChange(PropertyChangeEvent evt)
425               {
426                 Cache.log.debug("Firing service changed event for "
427                         + evt.getNewValue());
428                 JalviewServicesChanged(evt);
429               }
430
431             });
432   }
433
434   public void doConfigureStructurePrefs()
435   {
436     // configure services
437     StructureSelectionManager ssm = StructureSelectionManager
438             .getStructureSelectionManager(this);
439     if (jalview.bin.Cache.getDefault(Preferences.ADD_SS_ANN, true))
440     {
441       ssm.setAddTempFacAnnot(jalview.bin.Cache.getDefault(
442               Preferences.ADD_TEMPFACT_ANN, true));
443       ssm.setProcessSecondaryStructure(jalview.bin.Cache.getDefault(
444               Preferences.STRUCT_FROM_PDB, true));
445       ssm.setSecStructServices(jalview.bin.Cache.getDefault(
446               Preferences.USE_RNAVIEW, true));
447     }
448     else
449     {
450       ssm.setAddTempFacAnnot(false);
451       ssm.setProcessSecondaryStructure(false);
452       ssm.setSecStructServices(false);
453     }
454   }
455
456   public void checkForNews()
457   {
458     final Desktop me = this;
459     // Thread off the news reader, in case there are connection problems.
460     addDialogThread(new Runnable()
461     {
462       @Override
463       public void run()
464       {
465         Cache.log.debug("Starting news thread.");
466
467         jvnews = new BlogReader(me);
468         showNews.setVisible(true);
469         Cache.log.debug("Completed news thread.");
470       }
471     });
472   }
473
474   protected void showNews_actionPerformed(ActionEvent e)
475   {
476     showNews(showNews.isSelected());
477   }
478
479   void showNews(boolean visible)
480   {
481     {
482       Cache.log.debug((visible ? "Showing" : "Hiding") + " news.");
483       showNews.setSelected(visible);
484       if (visible && !jvnews.isVisible())
485       {
486         new Thread(new Runnable()
487         {
488           @Override
489           public void run()
490           {
491             long instance = System.currentTimeMillis();
492             Desktop.instance.setProgressBar(
493                     MessageManager.getString("status.refreshing_news"),
494                     instance);
495             jvnews.refreshNews();
496             Desktop.instance.setProgressBar(null, instance);
497             jvnews.showNews();
498           }
499         }).start();
500       }
501     }
502   }
503
504   /**
505    * recover the last known dimensions for a jalview window
506    * 
507    * @param windowName
508    *          - empty string is desktop, all other windows have unique prefix
509    * @return null or last known dimensions scaled to current geometry (if last
510    *         window geom was known)
511    */
512   Rectangle getLastKnownDimensions(String windowName)
513   {
514     // TODO: lock aspect ratio for scaling desktop Bug #0058199
515     Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
516     String x = jalview.bin.Cache.getProperty(windowName + "SCREEN_X");
517     String y = jalview.bin.Cache.getProperty(windowName + "SCREEN_Y");
518     String width = jalview.bin.Cache.getProperty(windowName
519             + "SCREEN_WIDTH");
520     String height = jalview.bin.Cache.getProperty(windowName
521             + "SCREEN_HEIGHT");
522     if ((x != null) && (y != null) && (width != null) && (height != null))
523     {
524       int ix = Integer.parseInt(x), iy = Integer.parseInt(y), iw = Integer
525               .parseInt(width), ih = Integer.parseInt(height);
526       if (jalview.bin.Cache.getProperty("SCREENGEOMETRY_WIDTH") != null)
527       {
528         // attempt #1 - try to cope with change in screen geometry - this
529         // version doesn't preserve original jv aspect ratio.
530         // take ratio of current screen size vs original screen size.
531         double sw = ((1f * screenSize.width) / (1f * Integer
532                 .parseInt(jalview.bin.Cache
533                         .getProperty("SCREENGEOMETRY_WIDTH"))));
534         double sh = ((1f * screenSize.height) / (1f * Integer
535                 .parseInt(jalview.bin.Cache
536                         .getProperty("SCREENGEOMETRY_HEIGHT"))));
537         // rescale the bounds depending upon the current screen geometry.
538         ix = (int) (ix * sw);
539         iw = (int) (iw * sw);
540         iy = (int) (iy * sh);
541         ih = (int) (ih * sh);
542         while (ix >= screenSize.width)
543         {
544           jalview.bin.Cache.log
545                   .debug("Window geometry location recall error: shifting horizontal to within screenbounds.");
546           ix -= screenSize.width;
547         }
548         while (iy >= screenSize.height)
549         {
550           jalview.bin.Cache.log
551                   .debug("Window geometry location recall error: shifting vertical to within screenbounds.");
552           iy -= screenSize.height;
553         }
554         jalview.bin.Cache.log.debug("Got last known dimensions for "
555                 + windowName + ": x:" + ix + " y:" + iy + " width:" + iw
556                 + " height:" + ih);
557       }
558       // return dimensions for new instance
559       return new Rectangle(ix, iy, iw, ih);
560     }
561     return null;
562   }
563
564   private void doVamsasClientCheck()
565   {
566     if (jalview.bin.Cache.vamsasJarsPresent())
567     {
568       setupVamsasDisconnectedGui();
569       VamsasMenu.setVisible(true);
570       final Desktop us = this;
571       VamsasMenu.addMenuListener(new MenuListener()
572       {
573         // this listener remembers when the menu was first selected, and
574         // doesn't rebuild the session list until it has been cleared and
575         // reselected again.
576         boolean refresh = true;
577
578         public void menuCanceled(MenuEvent e)
579         {
580           refresh = true;
581         }
582
583         public void menuDeselected(MenuEvent e)
584         {
585           refresh = true;
586         }
587
588         public void menuSelected(MenuEvent e)
589         {
590           if (refresh)
591           {
592             us.buildVamsasStMenu();
593             refresh = false;
594           }
595         }
596       });
597       vamsasStart.setVisible(true);
598     }
599   }
600
601   void showPasteMenu(int x, int y)
602   {
603     JPopupMenu popup = new JPopupMenu();
604     JMenuItem item = new JMenuItem(
605             MessageManager.getString("label.paste_new_window"));
606     item.addActionListener(new ActionListener()
607     {
608       public void actionPerformed(ActionEvent evt)
609       {
610         paste();
611       }
612     });
613
614     popup.add(item);
615     popup.show(this, x, y);
616   }
617
618   public void paste()
619   {
620     try
621     {
622       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
623       Transferable contents = c.getContents(this);
624
625       if (contents != null)
626       {
627         String file = (String) contents
628                 .getTransferData(DataFlavor.stringFlavor);
629
630         String format = new IdentifyFile().Identify(file,
631                 FormatAdapter.PASTE);
632
633         new FileLoader().LoadFile(file, FormatAdapter.PASTE, format);
634
635       }
636     } catch (Exception ex)
637     {
638       System.out
639               .println("Unable to paste alignment from system clipboard:\n"
640                       + ex);
641     }
642   }
643
644   /**
645    * Adds and opens the given frame to the desktop
646    * 
647    * @param frame
648    *          Frame to show
649    * @param title
650    *          Visible Title
651    * @param w
652    *          width
653    * @param h
654    *          height
655    */
656   public static synchronized void addInternalFrame(
657           final JInternalFrame frame, String title, int w, int h)
658   {
659     addInternalFrame(frame, title, true, w, h, true);
660   }
661
662   /**
663    * Add an internal frame to the Jalview desktop
664    * 
665    * @param frame
666    *          Frame to show
667    * @param title
668    *          Visible Title
669    * @param makeVisible
670    *          When true, display frame immediately, otherwise, caller must call
671    *          setVisible themselves.
672    * @param w
673    *          width
674    * @param h
675    *          height
676    */
677   public static synchronized void addInternalFrame(
678           final JInternalFrame frame, String title, boolean makeVisible,
679           int w, int h)
680   {
681     addInternalFrame(frame, title, makeVisible, w, h, true);
682   }
683
684   /**
685    * Add an internal frame to the Jalview desktop and make it visible
686    * 
687    * @param frame
688    *          Frame to show
689    * @param title
690    *          Visible Title
691    * @param w
692    *          width
693    * @param h
694    *          height
695    * @param resizable
696    *          Allow resize
697    */
698   public static synchronized void addInternalFrame(
699           final JInternalFrame frame, String title, int w, int h,
700           boolean resizable)
701   {
702     addInternalFrame(frame, title, true, w, h, resizable);
703   }
704
705   /**
706    * Add an internal frame to the Jalview desktop
707    * 
708    * @param frame
709    *          Frame to show
710    * @param title
711    *          Visible Title
712    * @param makeVisible
713    *          When true, display frame immediately, otherwise, caller must call
714    *          setVisible themselves.
715    * @param w
716    *          width
717    * @param h
718    *          height
719    * @param resizable
720    *          Allow resize
721    */
722   public static synchronized void addInternalFrame(
723           final JInternalFrame frame, String title, boolean makeVisible,
724           int w, int h, boolean resizable)
725   {
726
727     // TODO: allow callers to determine X and Y position of frame (eg. via
728     // bounds object).
729     // TODO: consider fixing method to update entries in the window submenu with
730     // the current window title
731
732     frame.setTitle(title);
733     if (frame.getWidth() < 1 || frame.getHeight() < 1)
734     {
735       frame.setSize(w, h);
736     }
737     // THIS IS A PUBLIC STATIC METHOD, SO IT MAY BE CALLED EVEN IN
738     // A HEADLESS STATE WHEN NO DESKTOP EXISTS. MUST RETURN
739     // IF JALVIEW IS RUNNING HEADLESS
740     // ///////////////////////////////////////////////
741     if (instance == null
742             || (System.getProperty("java.awt.headless") != null && System
743                     .getProperty("java.awt.headless").equals("true")))
744     {
745       return;
746     }
747
748     openFrameCount++;
749
750     frame.setVisible(makeVisible);
751     frame.setClosable(true);
752     frame.setResizable(resizable);
753     frame.setMaximizable(resizable);
754     frame.setIconifiable(resizable);
755     frame.setFrameIcon(null);
756
757     if (frame.getX() < 1 && frame.getY() < 1)
758     {
759       frame.setLocation(xOffset * openFrameCount, yOffset
760               * ((openFrameCount - 1) % 10) + yOffset);
761     }
762
763     final JMenuItem menuItem = new JMenuItem(title);
764     frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
765     {
766       public void internalFrameActivated(
767               javax.swing.event.InternalFrameEvent evt)
768       {
769         JInternalFrame itf = desktop.getSelectedFrame();
770         if (itf != null)
771         {
772           itf.requestFocus();
773         }
774
775       }
776
777       public void internalFrameClosed(
778               javax.swing.event.InternalFrameEvent evt)
779       {
780         PaintRefresher.RemoveComponent(frame);
781         openFrameCount--;
782         windowMenu.remove(menuItem);
783         JInternalFrame itf = desktop.getSelectedFrame();
784         if (itf != null)
785         {
786           itf.requestFocus();
787         }
788         System.gc();
789       };
790     });
791
792     menuItem.addActionListener(new ActionListener()
793     {
794       public void actionPerformed(ActionEvent e)
795       {
796         try
797         {
798           frame.setSelected(true);
799           frame.setIcon(false);
800         } catch (java.beans.PropertyVetoException ex)
801         {
802
803         }
804       }
805     });
806     menuItem.addMouseListener(new MouseListener()
807     {
808
809       @Override
810       public void mouseReleased(MouseEvent e)
811       {
812       }
813
814       @Override
815       public void mousePressed(MouseEvent e)
816       {
817       }
818
819       @Override
820       public void mouseExited(MouseEvent e)
821       {
822         try
823         {
824           frame.setSelected(false);
825         } catch (PropertyVetoException e1)
826         {
827         }
828       }
829
830       @Override
831       public void mouseEntered(MouseEvent e)
832       {
833         try
834         {
835           frame.setSelected(true);
836         } catch (PropertyVetoException e1)
837         {
838         }
839       }
840
841       @Override
842       public void mouseClicked(MouseEvent e)
843       {
844
845       }
846     });
847
848     windowMenu.add(menuItem);
849
850     desktop.add(frame);
851     frame.toFront();
852     try
853     {
854       frame.setSelected(true);
855       frame.requestFocus();
856     } catch (java.beans.PropertyVetoException ve)
857     {
858     } catch (java.lang.ClassCastException cex)
859     {
860       Cache.log
861               .warn("Squashed a possible GUI implementation error. If you can recreate this, please look at http://issues.jalview.org/browse/JAL-869",
862                       cex);
863     }
864   }
865
866   public void lostOwnership(Clipboard clipboard, Transferable contents)
867   {
868     if (!internalCopy)
869     {
870       Desktop.jalviewClipboard = null;
871     }
872
873     internalCopy = false;
874   }
875
876   public void dragEnter(DropTargetDragEvent evt)
877   {
878   }
879
880   public void dragExit(DropTargetEvent evt)
881   {
882   }
883
884   public void dragOver(DropTargetDragEvent evt)
885   {
886   }
887
888   public void dropActionChanged(DropTargetDragEvent evt)
889   {
890   }
891
892   /**
893    * DOCUMENT ME!
894    * 
895    * @param evt
896    *          DOCUMENT ME!
897    */
898   public void drop(DropTargetDropEvent evt)
899   {
900     boolean success = true;
901     Transferable t = evt.getTransferable();
902     java.util.List files = null;
903     java.util.List protocols = null;
904
905     try
906     {
907       DataFlavor uriListFlavor = new DataFlavor(
908               "text/uri-list;class=java.lang.String");
909       if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
910       {
911         // Works on Windows and MacOSX
912         evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
913         files = (java.util.List) t
914                 .getTransferData(DataFlavor.javaFileListFlavor);
915       }
916       else if (t.isDataFlavorSupported(uriListFlavor))
917       {
918         // This is used by Unix drag system
919         evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
920         String data = (String) t.getTransferData(uriListFlavor);
921         files = new java.util.ArrayList(1);
922         protocols = new java.util.ArrayList(1);
923         for (java.util.StringTokenizer st = new java.util.StringTokenizer(
924                 data, "\r\n"); st.hasMoreTokens();)
925         {
926           String s = st.nextToken();
927           if (s.startsWith("#"))
928           {
929             // the line is a comment (as per the RFC 2483)
930             continue;
931           }
932           java.net.URI uri = new java.net.URI(s);
933           if (uri.getScheme().toLowerCase().startsWith("http"))
934           {
935             protocols.add(FormatAdapter.URL);
936             files.add(uri.toString());
937           }
938           else
939           {
940             // otherwise preserve old behaviour: catch all for file objects
941             java.io.File file = new java.io.File(uri);
942             protocols.add(FormatAdapter.FILE);
943             files.add(file.toString());
944           }
945         }
946       }
947     } catch (Exception e)
948     {
949       success = false;
950     }
951
952     if (files != null)
953     {
954       try
955       {
956         for (int i = 0; i < files.size(); i++)
957         {
958           String file = files.get(i).toString();
959           String protocol = (protocols == null) ? FormatAdapter.FILE
960                   : (String) protocols.get(i);
961           String format = null;
962
963           if (file.endsWith(".jar"))
964           {
965             format = "Jalview";
966
967           }
968           else
969           {
970             format = new IdentifyFile().Identify(file, protocol);
971           }
972
973           new FileLoader().LoadFile(file, protocol, format);
974
975         }
976       } catch (Exception ex)
977       {
978         success = false;
979       }
980     }
981     evt.dropComplete(success); // need this to ensure input focus is properly
982                                // transfered to any new windows created
983   }
984
985   /**
986    * DOCUMENT ME!
987    * 
988    * @param e
989    *          DOCUMENT ME!
990    */
991   public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
992   {
993     JalviewFileChooser chooser = new JalviewFileChooser(
994             jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
995             jalview.io.AppletFormatAdapter.READABLE_EXTENSIONS,
996             jalview.io.AppletFormatAdapter.READABLE_FNAMES,
997             jalview.bin.Cache.getProperty("DEFAULT_FILE_FORMAT"));
998
999     chooser.setFileView(new JalviewFileView());
1000     chooser.setDialogTitle(MessageManager
1001             .getString("label.open_local_file"));
1002     chooser.setToolTipText(MessageManager.getString("action.open"));
1003
1004     int value = chooser.showOpenDialog(this);
1005
1006     if (value == JalviewFileChooser.APPROVE_OPTION)
1007     {
1008       String choice = chooser.getSelectedFile().getPath();
1009       jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
1010               .getSelectedFile().getParent());
1011
1012       String format = null;
1013       if (chooser.getSelectedFormat() != null
1014               && chooser.getSelectedFormat().equals("Jalview"))
1015       {
1016         format = "Jalview";
1017       }
1018       else
1019       {
1020         format = new IdentifyFile().Identify(choice, FormatAdapter.FILE);
1021       }
1022
1023       if (viewport != null)
1024       {
1025         new FileLoader().LoadFile(viewport, choice, FormatAdapter.FILE,
1026                 format);
1027         // viewport.setShowSequenceFeatures(JSONFile.isSeqFeaturesEnabled());
1028         // AlignFrame af = viewport.getAlignPanel().alignFrame;
1029         // if (af != null)
1030         // {
1031         // af.changeColour(JSONFile.getColourScheme());
1032         // af.setMenusForViewport();
1033         // }
1034       }
1035       else
1036       {
1037         new FileLoader().LoadFile(choice, FormatAdapter.FILE, format);
1038       }
1039     }
1040   }
1041
1042   /**
1043    * DOCUMENT ME!
1044    * 
1045    * @param e
1046    *          DOCUMENT ME!
1047    */
1048   public void inputURLMenuItem_actionPerformed(AlignViewport viewport)
1049   {
1050     // This construct allows us to have a wider textfield
1051     // for viewing
1052     JLabel label = new JLabel(
1053             MessageManager.getString("label.input_file_url"));
1054     final JComboBox history = new JComboBox();
1055
1056     JPanel panel = new JPanel(new GridLayout(2, 1));
1057     panel.add(label);
1058     panel.add(history);
1059     history.setPreferredSize(new Dimension(400, 20));
1060     history.setEditable(true);
1061     history.addItem("http://www.");
1062
1063     String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
1064
1065     StringTokenizer st;
1066
1067     if (historyItems != null)
1068     {
1069       st = new StringTokenizer(historyItems, "\t");
1070
1071       while (st.hasMoreTokens())
1072       {
1073         history.addItem(st.nextElement());
1074       }
1075     }
1076
1077     int reply = JOptionPane.showInternalConfirmDialog(desktop, panel,
1078             MessageManager.getString("label.input_alignment_from_url"),
1079             JOptionPane.OK_CANCEL_OPTION);
1080
1081     if (reply != JOptionPane.OK_OPTION)
1082     {
1083       return;
1084     }
1085
1086     String url = history.getSelectedItem().toString();
1087
1088     if (url.toLowerCase().endsWith(".jar"))
1089     {
1090       if (viewport != null)
1091       {
1092         new FileLoader().LoadFile(viewport, url, FormatAdapter.URL,
1093                 "Jalview");
1094       }
1095       else
1096       {
1097         new FileLoader().LoadFile(url, FormatAdapter.URL, "Jalview");
1098       }
1099     }
1100     else
1101     {
1102       String format = new IdentifyFile().Identify(url, FormatAdapter.URL);
1103
1104       if (format.equals("URL NOT FOUND"))
1105       {
1106         JOptionPane.showInternalMessageDialog(Desktop.desktop,
1107                 MessageManager.formatMessage("label.couldnt_locate",
1108                         new Object[]
1109                         { url }), MessageManager
1110                         .getString("label.url_not_found"),
1111                 JOptionPane.WARNING_MESSAGE);
1112
1113         return;
1114       }
1115
1116       if (viewport != null)
1117       {
1118         new FileLoader().LoadFile(viewport, url, FormatAdapter.URL, format);
1119       }
1120       else
1121       {
1122         new FileLoader().LoadFile(url, FormatAdapter.URL, format);
1123       }
1124     }
1125   }
1126
1127   /**
1128    * DOCUMENT ME!
1129    * 
1130    * @param e
1131    *          DOCUMENT ME!
1132    */
1133   public void inputTextboxMenuItem_actionPerformed(AlignViewport viewport)
1134   {
1135     CutAndPasteTransfer cap = new CutAndPasteTransfer();
1136     cap.setForInput(viewport);
1137     Desktop.addInternalFrame(cap,
1138             MessageManager.getString("label.cut_paste_alignmen_file"),
1139             true, 600, 500);
1140   }
1141
1142   /*
1143    * Exit the program
1144    */
1145   public void quit()
1146   {
1147     Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
1148     jalview.bin.Cache
1149             .setProperty("SCREENGEOMETRY_WIDTH", screen.width + "");
1150     jalview.bin.Cache.setProperty("SCREENGEOMETRY_HEIGHT", screen.height
1151             + "");
1152     storeLastKnownDimensions("", new Rectangle(getBounds().x,
1153             getBounds().y, getWidth(), getHeight()));
1154
1155     if (jconsole != null)
1156     {
1157       storeLastKnownDimensions("JAVA_CONSOLE_", jconsole.getBounds());
1158       jconsole.stopConsole();
1159     }
1160     if (jvnews != null)
1161     {
1162       storeLastKnownDimensions("JALVIEW_RSS_WINDOW_", jvnews.getBounds());
1163
1164     }
1165     if (dialogExecutor != null)
1166     {
1167       dialogExecutor.shutdownNow();
1168     }
1169     closeAll_actionPerformed(null);
1170     System.exit(0);
1171   }
1172
1173   private void storeLastKnownDimensions(String string, Rectangle jc)
1174   {
1175     jalview.bin.Cache.log.debug("Storing last known dimensions for "
1176             + string + ": x:" + jc.x + " y:" + jc.y + " width:" + jc.width
1177             + " height:" + jc.height);
1178
1179     jalview.bin.Cache.setProperty(string + "SCREEN_X", jc.x + "");
1180     jalview.bin.Cache.setProperty(string + "SCREEN_Y", jc.y + "");
1181     jalview.bin.Cache.setProperty(string + "SCREEN_WIDTH", jc.width + "");
1182     jalview.bin.Cache.setProperty(string + "SCREEN_HEIGHT", jc.height + "");
1183   }
1184
1185   /**
1186    * DOCUMENT ME!
1187    * 
1188    * @param e
1189    *          DOCUMENT ME!
1190    */
1191   public void aboutMenuItem_actionPerformed(ActionEvent e)
1192   {
1193     // StringBuffer message = getAboutMessage(false);
1194     // JOptionPane.showInternalMessageDialog(Desktop.desktop,
1195     //
1196     // message.toString(), "About Jalview", JOptionPane.INFORMATION_MESSAGE);
1197     new Thread(new Runnable()
1198     {
1199       public void run()
1200       {
1201         new SplashScreen(true);
1202       }
1203     }).start();
1204   }
1205
1206   public StringBuffer getAboutMessage(boolean shortv)
1207   {
1208     StringBuffer message = new StringBuffer();
1209     message.append("<html>");
1210     if (shortv)
1211     {
1212       message.append("<h1><strong>Version: "
1213               + jalview.bin.Cache.getProperty("VERSION") + "</strong></h1>");
1214       message.append("<strong>Last Updated: <em>"
1215               + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown")
1216               + "</em></strong>");
1217
1218     }
1219     else
1220     {
1221
1222       message.append("<strong>Version "
1223               + jalview.bin.Cache.getProperty("VERSION")
1224               + "; last updated: "
1225               + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
1226     }
1227
1228     if (jalview.bin.Cache.getDefault("LATEST_VERSION", "Checking").equals(
1229             "Checking"))
1230     {
1231       message.append("<br>...Checking latest version...</br>");
1232     }
1233     else if (!jalview.bin.Cache.getDefault("LATEST_VERSION", "Checking")
1234             .equals(jalview.bin.Cache.getProperty("VERSION")))
1235     {
1236       boolean red = false;
1237       if (jalview.bin.Cache.getProperty("VERSION").toLowerCase()
1238               .indexOf("automated build") == -1)
1239       {
1240         red = true;
1241         // Displayed when code version and jnlp version do not match and code
1242         // version is not a development build
1243         message.append("<div style=\"color: #FF0000;font-style: bold;\">");
1244       }
1245
1246       message.append("<br>!! Version "
1247               + jalview.bin.Cache.getDefault("LATEST_VERSION",
1248                       "..Checking..")
1249               + " is available for download from "
1250               + jalview.bin.Cache.getDefault("www.jalview.org",
1251                       "http://www.jalview.org") + " !!");
1252       if (red)
1253       {
1254         message.append("</div>");
1255       }
1256     }
1257     message.append("<br>Authors:  "
1258             + jalview.bin.Cache
1259                     .getDefault("AUTHORFNAMES",
1260                             "The Jalview Authors (See AUTHORS file for current list)")
1261             + "<br><br>Development managed by The Barton Group, University of Dundee, Scotland, UK.<br>"
1262             + "<br><br>For help, see the FAQ at <a href=\"http://www.jalview.org/faq\">www.jalview.org/faq</a> and/or join the jalview-discuss@jalview.org mailing list"
1263             + "<br><br>If  you use Jalview, please cite:"
1264             + "<br>Waterhouse, A.M., Procter, J.B., Martin, D.M.A, Clamp, M. and Barton, G. J. (2009)"
1265             + "<br>Jalview Version 2 - a multiple sequence alignment editor and analysis workbench"
1266             + "<br>Bioinformatics doi: 10.1093/bioinformatics/btp033"
1267             + "</html>");
1268     return message;
1269   }
1270
1271   /**
1272    * DOCUMENT ME!
1273    * 
1274    * @param e
1275    *          DOCUMENT ME!
1276    */
1277   public void documentationMenuItem_actionPerformed(ActionEvent e)
1278   {
1279     try
1280     {
1281       Help.showHelpWindow();
1282     } catch (Exception ex)
1283     {
1284     }
1285   }
1286
1287   public void closeAll_actionPerformed(ActionEvent e)
1288   {
1289     JInternalFrame[] frames = desktop.getAllFrames();
1290     for (int i = 0; i < frames.length; i++)
1291     {
1292       try
1293       {
1294         frames[i].setClosed(true);
1295       } catch (java.beans.PropertyVetoException ex)
1296       {
1297       }
1298     }
1299     System.out.println("ALL CLOSED");
1300     if (v_client != null)
1301     {
1302       // TODO clear binding to vamsas document objects on close_all
1303
1304     }
1305   }
1306
1307   public void raiseRelated_actionPerformed(ActionEvent e)
1308   {
1309     reorderAssociatedWindows(false, false);
1310   }
1311
1312   public void minimizeAssociated_actionPerformed(ActionEvent e)
1313   {
1314     reorderAssociatedWindows(true, false);
1315   }
1316
1317   void closeAssociatedWindows()
1318   {
1319     reorderAssociatedWindows(false, true);
1320   }
1321
1322   /*
1323    * (non-Javadoc)
1324    * 
1325    * @seejalview.jbgui.GDesktop#garbageCollect_actionPerformed(java.awt.event.
1326    * ActionEvent)
1327    */
1328   protected void garbageCollect_actionPerformed(ActionEvent e)
1329   {
1330     // We simply collect the garbage
1331     jalview.bin.Cache.log.debug("Collecting garbage...");
1332     System.gc();
1333     jalview.bin.Cache.log.debug("Finished garbage collection.");
1334   }
1335
1336   /*
1337    * (non-Javadoc)
1338    * 
1339    * @see
1340    * jalview.jbgui.GDesktop#showMemusage_actionPerformed(java.awt.event.ActionEvent
1341    * )
1342    */
1343   protected void showMemusage_actionPerformed(ActionEvent e)
1344   {
1345     desktop.showMemoryUsage(showMemusage.isSelected());
1346   }
1347
1348   /*
1349    * (non-Javadoc)
1350    * 
1351    * @see
1352    * jalview.jbgui.GDesktop#showConsole_actionPerformed(java.awt.event.ActionEvent
1353    * )
1354    */
1355   protected void showConsole_actionPerformed(ActionEvent e)
1356   {
1357     showConsole(showConsole.isSelected());
1358   }
1359
1360   Console jconsole = null;
1361
1362   /**
1363    * control whether the java console is visible or not
1364    * 
1365    * @param selected
1366    */
1367   void showConsole(boolean selected)
1368   {
1369     showConsole.setSelected(selected);
1370     // TODO: decide if we should update properties file
1371     Cache.setProperty("SHOW_JAVA_CONSOLE", Boolean.valueOf(selected)
1372             .toString());
1373     jconsole.setVisible(selected);
1374   }
1375
1376   void reorderAssociatedWindows(boolean minimize, boolean close)
1377   {
1378     JInternalFrame[] frames = desktop.getAllFrames();
1379     if (frames == null || frames.length < 1)
1380     {
1381       return;
1382     }
1383
1384     AlignmentViewport source = null, target = null;
1385     if (frames[0] instanceof AlignFrame)
1386     {
1387       source = ((AlignFrame) frames[0]).getCurrentView();
1388     }
1389     else if (frames[0] instanceof TreePanel)
1390     {
1391       source = ((TreePanel) frames[0]).getViewPort();
1392     }
1393     else if (frames[0] instanceof PCAPanel)
1394     {
1395       source = ((PCAPanel) frames[0]).av;
1396     }
1397     else if (frames[0].getContentPane() instanceof PairwiseAlignPanel)
1398     {
1399       source = ((PairwiseAlignPanel) frames[0].getContentPane()).av;
1400     }
1401
1402     if (source != null)
1403     {
1404       for (int i = 0; i < frames.length; i++)
1405       {
1406         target = null;
1407         if (frames[i] == null)
1408         {
1409           continue;
1410         }
1411         if (frames[i] instanceof AlignFrame)
1412         {
1413           target = ((AlignFrame) frames[i]).getCurrentView();
1414         }
1415         else if (frames[i] instanceof TreePanel)
1416         {
1417           target = ((TreePanel) frames[i]).getViewPort();
1418         }
1419         else if (frames[i] instanceof PCAPanel)
1420         {
1421           target = ((PCAPanel) frames[i]).av;
1422         }
1423         else if (frames[i].getContentPane() instanceof PairwiseAlignPanel)
1424         {
1425           target = ((PairwiseAlignPanel) frames[i].getContentPane()).av;
1426         }
1427
1428         if (source == target)
1429         {
1430           try
1431           {
1432             if (close)
1433             {
1434               frames[i].setClosed(true);
1435             }
1436             else
1437             {
1438               frames[i].setIcon(minimize);
1439               if (!minimize)
1440               {
1441                 frames[i].toFront();
1442               }
1443             }
1444
1445           } catch (java.beans.PropertyVetoException ex)
1446           {
1447           }
1448         }
1449       }
1450     }
1451   }
1452
1453   /**
1454    * DOCUMENT ME!
1455    * 
1456    * @param e
1457    *          DOCUMENT ME!
1458    */
1459   protected void preferences_actionPerformed(ActionEvent e)
1460   {
1461     new Preferences();
1462   }
1463
1464   /**
1465    * DOCUMENT ME!
1466    * 
1467    * @param e
1468    *          DOCUMENT ME!
1469    */
1470   public void saveState_actionPerformed(ActionEvent e)
1471   {
1472     JalviewFileChooser chooser = new JalviewFileChooser(
1473             jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
1474             { "jvp" }, new String[]
1475             { "Jalview Project" }, "Jalview Project");
1476
1477     chooser.setFileView(new JalviewFileView());
1478     chooser.setDialogTitle(MessageManager.getString("label.save_state"));
1479
1480     int value = chooser.showSaveDialog(this);
1481
1482     if (value == JalviewFileChooser.APPROVE_OPTION)
1483     {
1484       final Desktop me = this;
1485       final java.io.File choice = chooser.getSelectedFile();
1486       setProjectFile(choice);
1487
1488       // TODO or move inside the new Thread?
1489       saveChimeraSessions(choice.getAbsolutePath());
1490
1491       new Thread(new Runnable()
1492       {
1493         public void run()
1494         {
1495
1496           setProgressBar(MessageManager.formatMessage(
1497                   "label.saving_jalview_project", new Object[]
1498                   { choice.getName() }), choice.hashCode());
1499           jalview.bin.Cache.setProperty("LAST_DIRECTORY",
1500                   choice.getParent());
1501           // TODO catch and handle errors for savestate
1502           // TODO prevent user from messing with the Desktop whilst we're saving
1503           try
1504           {
1505             new Jalview2XML().saveState(choice);
1506           } catch (OutOfMemoryError oom)
1507           {
1508             new OOMWarning("Whilst saving current state to "
1509                     + choice.getName(), oom);
1510           } catch (Exception ex)
1511           {
1512             Cache.log.error(
1513                     "Problems whilst trying to save to " + choice.getName(),
1514                     ex);
1515             JOptionPane.showMessageDialog(me, MessageManager.formatMessage(
1516                     "label.error_whilst_saving_current_state_to",
1517                     new Object[]
1518                     { choice.getName() }), MessageManager
1519                     .getString("label.couldnt_save_project"),
1520                     JOptionPane.WARNING_MESSAGE);
1521           }
1522           setProgressBar(null, choice.hashCode());
1523         }
1524       }).start();
1525     }
1526   }
1527
1528   /**
1529    * Request any open, linked Chimera sessions to save their state.
1530    * 
1531    * @param jalviewProjectFilename
1532    *          the filename of the Jalview project; Chimera session files should
1533    *          be given distinct, but obviously related, names.
1534    */
1535   public void saveChimeraSessions(String jalviewProjectFilename)
1536   {
1537     int i = 0;
1538     for (JInternalFrame frame : getAllFrames())
1539     {
1540       if (frame instanceof ChimeraViewFrame)
1541       {
1542         /*
1543          * Construct a filename for the Chimera session by append _chimera<n>.py
1544          * to the Jalview project file name.
1545          */
1546         String chimeraPath = jalviewProjectFilename + "_chimera_" + i
1547                 + ".py";
1548         ((ChimeraViewFrame) frame).saveSession(chimeraPath);
1549         i++;
1550       }
1551     }
1552   }
1553
1554   private void setProjectFile(File choice)
1555   {
1556     this.projectFile = choice;
1557   }
1558
1559   public File getProjectFile()
1560   {
1561     return this.projectFile;
1562   }
1563
1564   /**
1565    * DOCUMENT ME!
1566    * 
1567    * @param e
1568    *          DOCUMENT ME!
1569    */
1570   public void loadState_actionPerformed(ActionEvent e)
1571   {
1572     JalviewFileChooser chooser = new JalviewFileChooser(
1573             jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
1574             { "jvp", "jar" }, new String[]
1575             { "Jalview Project", "Jalview Project (old)" },
1576             "Jalview Project");
1577     chooser.setFileView(new JalviewFileView());
1578     chooser.setDialogTitle(MessageManager.getString("label.restore_state"));
1579
1580     int value = chooser.showOpenDialog(this);
1581
1582     if (value == JalviewFileChooser.APPROVE_OPTION)
1583     {
1584       final File selectedFile = chooser.getSelectedFile();
1585       setProjectFile(selectedFile);
1586       final String choice = selectedFile.getAbsolutePath();
1587       jalview.bin.Cache.setProperty("LAST_DIRECTORY",
1588               selectedFile.getParent());
1589       new Thread(new Runnable()
1590       {
1591         public void run()
1592         {
1593           setProgressBar(MessageManager.formatMessage(
1594                   "label.loading_jalview_project", new Object[]
1595                   { choice }), choice.hashCode());
1596           try
1597           {
1598             new Jalview2XML().loadJalviewAlign(choice);
1599           } catch (OutOfMemoryError oom)
1600           {
1601             new OOMWarning("Whilst loading project from " + choice, oom);
1602           } catch (Exception ex)
1603           {
1604             Cache.log.error("Problems whilst loading project from "
1605                     + choice, ex);
1606             JOptionPane.showMessageDialog(Desktop.desktop, MessageManager
1607                     .formatMessage(
1608                             "label.error_whilst_loading_project_from",
1609                             new Object[]
1610                             { choice }), MessageManager
1611                     .getString("label.couldnt_load_project"),
1612                     JOptionPane.WARNING_MESSAGE);
1613           }
1614           setProgressBar(null, choice.hashCode());
1615         }
1616       }).start();
1617     }
1618   }
1619
1620   public void inputSequence_actionPerformed(ActionEvent e)
1621   {
1622     new SequenceFetcher(this);
1623   }
1624
1625   JPanel progressPanel;
1626
1627   ArrayList<JPanel> fileLoadingPanels = new ArrayList<JPanel>();
1628
1629   public void startLoading(final String fileName)
1630   {
1631     if (fileLoadingCount == 0)
1632     {
1633       fileLoadingPanels.add(addProgressPanel(MessageManager.formatMessage(
1634               "label.loading_file", new Object[]
1635               { fileName })));
1636     }
1637     fileLoadingCount++;
1638   }
1639
1640   private JPanel addProgressPanel(String string)
1641   {
1642     if (progressPanel == null)
1643     {
1644       progressPanel = new JPanel(new GridLayout(1, 1));
1645       totalProgressCount = 0;
1646       instance.getContentPane().add(progressPanel, BorderLayout.SOUTH);
1647     }
1648     JPanel thisprogress = new JPanel(new BorderLayout(10, 5));
1649     JProgressBar progressBar = new JProgressBar();
1650     progressBar.setIndeterminate(true);
1651
1652     thisprogress.add(new JLabel(string), BorderLayout.WEST);
1653
1654     thisprogress.add(progressBar, BorderLayout.CENTER);
1655     progressPanel.add(thisprogress);
1656     ((GridLayout) progressPanel.getLayout())
1657             .setRows(((GridLayout) progressPanel.getLayout()).getRows() + 1);
1658     ++totalProgressCount;
1659     instance.validate();
1660     return thisprogress;
1661   }
1662
1663   int totalProgressCount = 0;
1664
1665   private void removeProgressPanel(JPanel progbar)
1666   {
1667     if (progressPanel != null)
1668     {
1669       synchronized (progressPanel)
1670       {
1671         progressPanel.remove(progbar);
1672         GridLayout gl = (GridLayout) progressPanel.getLayout();
1673         gl.setRows(gl.getRows() - 1);
1674         if (--totalProgressCount < 1)
1675         {
1676           this.getContentPane().remove(progressPanel);
1677           progressPanel = null;
1678         }
1679       }
1680     }
1681     validate();
1682   }
1683
1684   public void stopLoading()
1685   {
1686     fileLoadingCount--;
1687     if (fileLoadingCount < 1)
1688     {
1689       while (fileLoadingPanels.size() > 0)
1690       {
1691         removeProgressPanel(fileLoadingPanels.remove(0));
1692       }
1693       fileLoadingPanels.clear();
1694       fileLoadingCount = 0;
1695     }
1696     validate();
1697   }
1698
1699   public static int getViewCount(String alignmentId)
1700   {
1701     AlignmentViewport[] aps = getViewports(alignmentId);
1702     return (aps == null) ? 0 : aps.length;
1703   }
1704
1705   /**
1706    * 
1707    * @param alignmentId
1708    *          - if null, all sets are returned
1709    * @return all AlignmentPanels concerning the alignmentId sequence set
1710    */
1711   public static AlignmentPanel[] getAlignmentPanels(String alignmentId)
1712   {
1713     if (Desktop.desktop == null)
1714     {
1715       // no frames created and in headless mode
1716       // TODO: verify that frames are recoverable when in headless mode
1717       return null;
1718     }
1719     List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>();
1720     AlignFrame[] frames = getAlignFrames();
1721     if (frames == null)
1722     {
1723       return null;
1724     }
1725     for (AlignFrame af : frames)
1726     {
1727       for (AlignmentPanel ap : af.alignPanels)
1728       {
1729         if (alignmentId==null || alignmentId.equals(ap.av.getSequenceSetId()))
1730         {
1731           aps.add(ap);
1732         }
1733       }
1734     }
1735     if (aps.size() == 0)
1736     {
1737       return null;
1738     }
1739     AlignmentPanel[] vap = aps.toArray(new AlignmentPanel[aps.size()]);
1740     return vap;
1741   }
1742
1743   /**
1744    * get all the viewports on an alignment.
1745    * 
1746    * @param sequenceSetId
1747    *          unique alignment id (may be null - all viewports returned in that
1748    *          case)
1749    * @return all viewports on the alignment bound to sequenceSetId
1750    */
1751   public static AlignmentViewport[] getViewports(String sequenceSetId)
1752   {
1753     List<AlignmentViewport> viewp = new ArrayList<AlignmentViewport>();
1754     if (desktop != null)
1755     {
1756       AlignFrame[] frames = Desktop.getAlignFrames();
1757
1758       for (AlignFrame afr : frames)
1759       {
1760         if (sequenceSetId==null || afr.getViewport().getSequenceSetId().equals(sequenceSetId))
1761         {
1762           if (afr.alignPanels != null)
1763           {
1764             for (AlignmentPanel ap : afr.alignPanels)
1765             {
1766               if (sequenceSetId == null
1767                       || sequenceSetId.equals(ap.av.getSequenceSetId()))
1768               {
1769                 viewp.add(ap.av);
1770               }
1771             }
1772           }
1773           else
1774           {
1775             viewp.add(afr.getViewport());
1776           }
1777         }
1778       }
1779       if (viewp.size() > 0)
1780       {
1781         return viewp.toArray(new AlignmentViewport[viewp.size()]);
1782       }
1783     }
1784     return null;
1785   }
1786
1787   /**
1788    * Explode the views in the given frame into separate AlignFrame
1789    * 
1790    * @param af
1791    */
1792   public void explodeViews(AlignFrame af)
1793   {
1794     int size = af.alignPanels.size();
1795     if (size < 2)
1796     {
1797       return;
1798     }
1799
1800     for (int i = 0; i < size; i++)
1801     {
1802       AlignmentPanel ap = af.alignPanels.get(i);
1803       AlignFrame newaf = new AlignFrame(ap);
1804
1805       /*
1806        * Restore the view's last exploded frame geometry if known. Multiple
1807        * views from one exploded frame share and restore the same (frame)
1808        * position and size.
1809        */
1810       Rectangle geometry = ap.av.getExplodedGeometry();
1811       if (geometry != null)
1812       {
1813         newaf.setBounds(geometry);
1814       }
1815
1816       ap.av.setGatherViewsHere(false);
1817
1818       addInternalFrame(newaf, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
1819               AlignFrame.DEFAULT_HEIGHT);
1820     }
1821
1822     af.alignPanels.clear();
1823     af.closeMenuItem_actionPerformed(true);
1824
1825   }
1826
1827   /**
1828    * Gather expanded views (separate AlignFrame's) with the same sequence set
1829    * identifier back in to this frame as additional views, and close the
1830    * expanded views. Note the expanded frames may themselves have multiple
1831    * views. We take the lot.
1832    * 
1833    * @param source
1834    */
1835   public void gatherViews(AlignFrame source)
1836   {
1837     source.viewport.setGatherViewsHere(true);
1838     source.viewport.setExplodedGeometry(source.getBounds());
1839     JInternalFrame[] frames = desktop.getAllFrames();
1840     String viewId = source.viewport.getSequenceSetId();
1841
1842     for (int t = 0; t < frames.length; t++)
1843     {
1844       if (frames[t] instanceof AlignFrame && frames[t] != source)
1845       {
1846         AlignFrame af = (AlignFrame) frames[t];
1847         boolean gatherThis = false;
1848         for (int a = 0; a < af.alignPanels.size(); a++)
1849         {
1850           AlignmentPanel ap = af.alignPanels.get(a);
1851           if (viewId.equals(ap.av.getSequenceSetId()))
1852           {
1853             gatherThis = true;
1854             ap.av.setGatherViewsHere(false);
1855             ap.av.setExplodedGeometry(af.getBounds());
1856             source.addAlignmentPanel(ap, false);
1857           }
1858         }
1859
1860         if (gatherThis)
1861         {
1862           af.alignPanels.clear();
1863           af.closeMenuItem_actionPerformed(true);
1864         }
1865       }
1866     }
1867
1868   }
1869
1870   jalview.gui.VamsasApplication v_client = null;
1871
1872   public void vamsasImport_actionPerformed(ActionEvent e)
1873   {
1874     if (v_client == null)
1875     {
1876       // Load and try to start a session.
1877       JalviewFileChooser chooser = new JalviewFileChooser(
1878               jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1879
1880       chooser.setFileView(new JalviewFileView());
1881       chooser.setDialogTitle(MessageManager
1882               .getString("label.open_saved_vamsas_session"));
1883       chooser.setToolTipText(MessageManager
1884               .getString("label.select_vamsas_session_opened_as_new_vamsas_session"));
1885
1886       int value = chooser.showOpenDialog(this);
1887
1888       if (value == JalviewFileChooser.APPROVE_OPTION)
1889       {
1890         String fle = chooser.getSelectedFile().toString();
1891         if (!vamsasImport(chooser.getSelectedFile()))
1892         {
1893           JOptionPane
1894                   .showInternalMessageDialog(
1895                           Desktop.desktop,
1896                           MessageManager.formatMessage(
1897                                   "label.couldnt_import_as_vamsas_session",
1898                                   new Object[]
1899                                   { fle }),
1900                           MessageManager
1901                                   .getString("label.vamsas_document_import_failed"),
1902                           JOptionPane.ERROR_MESSAGE);
1903         }
1904       }
1905     }
1906     else
1907     {
1908       jalview.bin.Cache.log
1909               .error("Implementation error - load session from a running session is not supported.");
1910     }
1911   }
1912
1913   /**
1914    * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
1915    * 
1916    * @param file
1917    * @return true if import was a success and a session was started.
1918    */
1919   public boolean vamsasImport(URL url)
1920   {
1921     // TODO: create progress bar
1922     if (v_client != null)
1923     {
1924
1925       jalview.bin.Cache.log
1926               .error("Implementation error - load session from a running session is not supported.");
1927       return false;
1928     }
1929
1930     try
1931     {
1932       // copy the URL content to a temporary local file
1933       // TODO: be a bit cleverer here with nio (?!)
1934       File file = File.createTempFile("vdocfromurl", ".vdj");
1935       FileOutputStream fos = new FileOutputStream(file);
1936       BufferedInputStream bis = new BufferedInputStream(url.openStream());
1937       byte[] buffer = new byte[2048];
1938       int ln;
1939       while ((ln = bis.read(buffer)) > -1)
1940       {
1941         fos.write(buffer, 0, ln);
1942       }
1943       bis.close();
1944       fos.close();
1945       v_client = new jalview.gui.VamsasApplication(this, file,
1946               url.toExternalForm());
1947     } catch (Exception ex)
1948     {
1949       jalview.bin.Cache.log.error(
1950               "Failed to create new vamsas session from contents of URL "
1951                       + url, ex);
1952       return false;
1953     }
1954     setupVamsasConnectedGui();
1955     v_client.initial_update(); // TODO: thread ?
1956     return v_client.inSession();
1957   }
1958
1959   /**
1960    * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
1961    * 
1962    * @param file
1963    * @return true if import was a success and a session was started.
1964    */
1965   public boolean vamsasImport(File file)
1966   {
1967     if (v_client != null)
1968     {
1969
1970       jalview.bin.Cache.log
1971               .error("Implementation error - load session from a running session is not supported.");
1972       return false;
1973     }
1974
1975     setProgressBar(MessageManager.formatMessage(
1976             "status.importing_vamsas_session_from", new Object[]
1977             { file.getName() }), file.hashCode());
1978     try
1979     {
1980       v_client = new jalview.gui.VamsasApplication(this, file, null);
1981     } catch (Exception ex)
1982     {
1983       setProgressBar(MessageManager.formatMessage(
1984               "status.importing_vamsas_session_from", new Object[]
1985               { file.getName() }), file.hashCode());
1986       jalview.bin.Cache.log.error(
1987               "New vamsas session from existing session file failed:", ex);
1988       return false;
1989     }
1990     setupVamsasConnectedGui();
1991     v_client.initial_update(); // TODO: thread ?
1992     setProgressBar(MessageManager.formatMessage(
1993             "status.importing_vamsas_session_from", new Object[]
1994             { file.getName() }), file.hashCode());
1995     return v_client.inSession();
1996   }
1997
1998   public boolean joinVamsasSession(String mysesid)
1999   {
2000     if (v_client != null)
2001     {
2002       throw new Error(
2003               MessageManager
2004                       .getString("error.try_join_vamsas_session_another"));
2005     }
2006     if (mysesid == null)
2007     {
2008       throw new Error(
2009               MessageManager.getString("error.invalid_vamsas_session_id"));
2010     }
2011     v_client = new VamsasApplication(this, mysesid);
2012     setupVamsasConnectedGui();
2013     v_client.initial_update();
2014     return (v_client.inSession());
2015   }
2016
2017   public void vamsasStart_actionPerformed(ActionEvent e)
2018   {
2019     if (v_client == null)
2020     {
2021       // Start a session.
2022       // we just start a default session for moment.
2023       /*
2024        * JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
2025        * getProperty("LAST_DIRECTORY"));
2026        * 
2027        * chooser.setFileView(new JalviewFileView());
2028        * chooser.setDialogTitle("Load Vamsas file");
2029        * chooser.setToolTipText("Import");
2030        * 
2031        * int value = chooser.showOpenDialog(this);
2032        * 
2033        * if (value == JalviewFileChooser.APPROVE_OPTION) { v_client = new
2034        * jalview.gui.VamsasApplication(this, chooser.getSelectedFile());
2035        */
2036       v_client = new VamsasApplication(this);
2037       setupVamsasConnectedGui();
2038       v_client.initial_update(); // TODO: thread ?
2039     }
2040     else
2041     {
2042       // store current data in session.
2043       v_client.push_update(); // TODO: thread
2044     }
2045   }
2046
2047   protected void setupVamsasConnectedGui()
2048   {
2049     vamsasStart.setText(MessageManager.getString("label.session_update"));
2050     vamsasSave.setVisible(true);
2051     vamsasStop.setVisible(true);
2052     vamsasImport.setVisible(false); // Document import to existing session is
2053     // not possible for vamsas-client-1.0.
2054   }
2055
2056   protected void setupVamsasDisconnectedGui()
2057   {
2058     vamsasSave.setVisible(false);
2059     vamsasStop.setVisible(false);
2060     vamsasImport.setVisible(true);
2061     vamsasStart.setText(MessageManager
2062             .getString("label.new_vamsas_session"));
2063   }
2064
2065   public void vamsasStop_actionPerformed(ActionEvent e)
2066   {
2067     if (v_client != null)
2068     {
2069       v_client.end_session();
2070       v_client = null;
2071       setupVamsasDisconnectedGui();
2072     }
2073   }
2074
2075   protected void buildVamsasStMenu()
2076   {
2077     if (v_client == null)
2078     {
2079       String[] sess = null;
2080       try
2081       {
2082         sess = VamsasApplication.getSessionList();
2083       } catch (Exception e)
2084       {
2085         jalview.bin.Cache.log.warn(
2086                 "Problem getting current sessions list.", e);
2087         sess = null;
2088       }
2089       if (sess != null)
2090       {
2091         jalview.bin.Cache.log.debug("Got current sessions list: "
2092                 + sess.length + " entries.");
2093         VamsasStMenu.removeAll();
2094         for (int i = 0; i < sess.length; i++)
2095         {
2096           JMenuItem sessit = new JMenuItem();
2097           sessit.setText(sess[i]);
2098           sessit.setToolTipText(MessageManager.formatMessage(
2099                   "label.connect_to_session", new Object[]
2100                   { sess[i] }));
2101           final Desktop dsktp = this;
2102           final String mysesid = sess[i];
2103           sessit.addActionListener(new ActionListener()
2104           {
2105
2106             public void actionPerformed(ActionEvent e)
2107             {
2108               if (dsktp.v_client == null)
2109               {
2110                 Thread rthr = new Thread(new Runnable()
2111                 {
2112
2113                   public void run()
2114                   {
2115                     dsktp.v_client = new VamsasApplication(dsktp, mysesid);
2116                     dsktp.setupVamsasConnectedGui();
2117                     dsktp.v_client.initial_update();
2118                   }
2119
2120                 });
2121                 rthr.start();
2122               }
2123             };
2124           });
2125           VamsasStMenu.add(sessit);
2126         }
2127         // don't show an empty menu.
2128         VamsasStMenu.setVisible(sess.length > 0);
2129
2130       }
2131       else
2132       {
2133         jalview.bin.Cache.log.debug("No current vamsas sessions.");
2134         VamsasStMenu.removeAll();
2135         VamsasStMenu.setVisible(false);
2136       }
2137     }
2138     else
2139     {
2140       // Not interested in the content. Just hide ourselves.
2141       VamsasStMenu.setVisible(false);
2142     }
2143   }
2144
2145   public void vamsasSave_actionPerformed(ActionEvent e)
2146   {
2147     if (v_client != null)
2148     {
2149       JalviewFileChooser chooser = new JalviewFileChooser(
2150               jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
2151               { "vdj" }, // TODO: VAMSAS DOCUMENT EXTENSION is VDJ
2152               new String[]
2153               { "Vamsas Document" }, "Vamsas Document");
2154
2155       chooser.setFileView(new JalviewFileView());
2156       chooser.setDialogTitle(MessageManager
2157               .getString("label.save_vamsas_document_archive"));
2158
2159       int value = chooser.showSaveDialog(this);
2160
2161       if (value == JalviewFileChooser.APPROVE_OPTION)
2162       {
2163         java.io.File choice = chooser.getSelectedFile();
2164         JPanel progpanel = addProgressPanel(MessageManager.formatMessage(
2165                 "label.saving_vamsas_doc", new Object[]
2166                 { choice.getName() }));
2167         jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
2168         String warnmsg = null;
2169         String warnttl = null;
2170         try
2171         {
2172           v_client.vclient.storeDocument(choice);
2173         } catch (Error ex)
2174         {
2175           warnttl = "Serious Problem saving Vamsas Document";
2176           warnmsg = ex.toString();
2177           jalview.bin.Cache.log.error("Error Whilst saving document to "
2178                   + choice, ex);
2179
2180         } catch (Exception ex)
2181         {
2182           warnttl = "Problem saving Vamsas Document.";
2183           warnmsg = ex.toString();
2184           jalview.bin.Cache.log.warn("Exception Whilst saving document to "
2185                   + choice, ex);
2186
2187         }
2188         removeProgressPanel(progpanel);
2189         if (warnmsg != null)
2190         {
2191           JOptionPane.showInternalMessageDialog(Desktop.desktop,
2192
2193           warnmsg, warnttl, JOptionPane.ERROR_MESSAGE);
2194         }
2195       }
2196     }
2197   }
2198
2199   JPanel vamUpdate = null;
2200
2201   /**
2202    * hide vamsas user gui bits when a vamsas document event is being handled.
2203    * 
2204    * @param b
2205    *          true to hide gui, false to reveal gui
2206    */
2207   public void setVamsasUpdate(boolean b)
2208   {
2209     jalview.bin.Cache.log.debug("Setting gui for Vamsas update "
2210             + (b ? "in progress" : "finished"));
2211
2212     if (vamUpdate != null)
2213     {
2214       this.removeProgressPanel(vamUpdate);
2215     }
2216     if (b)
2217     {
2218       vamUpdate = this.addProgressPanel(MessageManager
2219               .getString("label.updating_vamsas_session"));
2220     }
2221     vamsasStart.setVisible(!b);
2222     vamsasStop.setVisible(!b);
2223     vamsasSave.setVisible(!b);
2224   }
2225
2226   public JInternalFrame[] getAllFrames()
2227   {
2228     return desktop.getAllFrames();
2229   }
2230
2231   /**
2232    * Checks the given url to see if it gives a response indicating that the user
2233    * should be informed of a new questionnaire.
2234    * 
2235    * @param url
2236    */
2237   public void checkForQuestionnaire(String url)
2238   {
2239     UserQuestionnaireCheck jvq = new UserQuestionnaireCheck(url);
2240     // javax.swing.SwingUtilities.invokeLater(jvq);
2241     new Thread(jvq).start();
2242   }
2243
2244   /**
2245    * Proxy class for JDesktopPane which optionally displays the current memory
2246    * usage and highlights the desktop area with a red bar if free memory runs
2247    * low.
2248    * 
2249    * @author AMW
2250    */
2251   public class MyDesktopPane extends JDesktopPane implements Runnable
2252   {
2253
2254     private static final float ONE_MB = 1048576f;
2255
2256     boolean showMemoryUsage = false;
2257
2258     Runtime runtime;
2259
2260     java.text.NumberFormat df;
2261
2262     float maxMemory, allocatedMemory, freeMemory, totalFreeMemory,
2263             percentUsage;
2264
2265     public MyDesktopPane(boolean showMemoryUsage)
2266     {
2267       showMemoryUsage(showMemoryUsage);
2268     }
2269
2270     public void showMemoryUsage(boolean showMemoryUsage)
2271     {
2272       this.showMemoryUsage = showMemoryUsage;
2273       if (showMemoryUsage)
2274       {
2275         Thread worker = new Thread(this);
2276         worker.start();
2277       }
2278     }
2279
2280     public boolean isShowMemoryUsage()
2281     {
2282       return showMemoryUsage;
2283     }
2284
2285     public void run()
2286     {
2287       df = java.text.NumberFormat.getNumberInstance();
2288       df.setMaximumFractionDigits(2);
2289       runtime = Runtime.getRuntime();
2290
2291       while (showMemoryUsage)
2292       {
2293         try
2294         {
2295           maxMemory = runtime.maxMemory() / ONE_MB;
2296           allocatedMemory = runtime.totalMemory() / ONE_MB;
2297           freeMemory = runtime.freeMemory() / ONE_MB;
2298           totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);
2299
2300           percentUsage = (totalFreeMemory / maxMemory) * 100;
2301
2302           // if (percentUsage < 20)
2303           {
2304             // border1 = BorderFactory.createMatteBorder(12, 12, 12, 12,
2305             // Color.red);
2306             // instance.set.setBorder(border1);
2307           }
2308           repaint();
2309           // sleep after showing usage
2310           Thread.sleep(3000);
2311         } catch (Exception ex)
2312         {
2313           ex.printStackTrace();
2314         }
2315       }
2316     }
2317
2318     public void paintComponent(Graphics g)
2319     {
2320       if (showMemoryUsage && g != null && df != null)
2321       {
2322         if (percentUsage < 20)
2323         {
2324           g.setColor(Color.red);
2325         }
2326         FontMetrics fm = g.getFontMetrics();
2327         if (fm != null)
2328         {
2329           g.drawString(MessageManager.formatMessage(
2330                   "label.memory_stats",
2331                   new Object[]
2332                   { df.format(totalFreeMemory), df.format(maxMemory),
2333                       df.format(percentUsage) }), 10,
2334                   getHeight() - fm.getHeight());
2335         }
2336       }
2337     }
2338   }
2339
2340   /**
2341    * fixes stacking order after a modal dialog to ensure windows that should be
2342    * on top actually are
2343    */
2344   public void relayerWindows()
2345   {
2346
2347   }
2348
2349   protected JMenuItem groovyShell;
2350
2351   public void doGroovyCheck()
2352   {
2353     if (jalview.bin.Cache.groovyJarsPresent())
2354     {
2355       groovyShell = new JMenuItem();
2356       groovyShell.setText(MessageManager.getString("label.groovy_console"));
2357       groovyShell.addActionListener(new ActionListener()
2358       {
2359         public void actionPerformed(ActionEvent e)
2360         {
2361           groovyShell_actionPerformed(e);
2362         }
2363       });
2364       toolsMenu.add(groovyShell);
2365       groovyShell.setVisible(true);
2366     }
2367   }
2368
2369   /**
2370    * Accessor method to quickly get all the AlignmentFrames loaded.
2371    * 
2372    * @return an array of AlignFrame, or null if none found
2373    */
2374   public static AlignFrame[] getAlignFrames()
2375   {
2376     JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2377
2378     if (frames == null)
2379     {
2380       return null;
2381     }
2382     List<AlignFrame> avp = new ArrayList<AlignFrame>();
2383     // REVERSE ORDER
2384     for (int i = frames.length - 1; i > -1; i--)
2385     {
2386       if (frames[i] instanceof AlignFrame)
2387       {
2388         avp.add((AlignFrame) frames[i]);
2389       }
2390       else if (frames[i] instanceof SplitFrame)
2391       {
2392         /*
2393          * Also check for a split frame containing an AlignFrame
2394          */
2395         GSplitFrame sf = (GSplitFrame) frames[i];
2396         if (sf.getTopFrame() instanceof AlignFrame)
2397         {
2398           avp.add((AlignFrame) sf.getTopFrame());
2399         }
2400         if (sf.getBottomFrame() instanceof AlignFrame)
2401         {
2402           avp.add((AlignFrame) sf.getBottomFrame());
2403         }
2404       }
2405     }
2406     if (avp.size() == 0)
2407     {
2408       return null;
2409     }
2410     AlignFrame afs[] = avp.toArray(new AlignFrame[avp.size()]);
2411     return afs;
2412   }
2413
2414   /**
2415    * Returns an array of any AppJmol frames in the Desktop (or null if none).
2416    * 
2417    * @return
2418    */
2419   public GStructureViewer[] getJmols()
2420   {
2421     JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2422
2423     if (frames == null)
2424     {
2425       return null;
2426     }
2427     List<GStructureViewer> avp = new ArrayList<GStructureViewer>();
2428     // REVERSE ORDER
2429     for (int i = frames.length - 1; i > -1; i--)
2430     {
2431       if (frames[i] instanceof AppJmol)
2432       {
2433         GStructureViewer af = (GStructureViewer) frames[i];
2434         avp.add(af);
2435       }
2436     }
2437     if (avp.size() == 0)
2438     {
2439       return null;
2440     }
2441     GStructureViewer afs[] = avp.toArray(new GStructureViewer[avp.size()]);
2442     return afs;
2443   }
2444
2445   /**
2446    * Add Groovy Support to Jalview
2447    */
2448   public void groovyShell_actionPerformed(ActionEvent e)
2449   {
2450     // use reflection to avoid creating compilation dependency.
2451     if (!jalview.bin.Cache.groovyJarsPresent())
2452     {
2453       throw new Error(
2454               MessageManager
2455                       .getString("error.implementation_error_cannot_create_groovyshell"));
2456     }
2457     try
2458     {
2459       Class<?> gcClass = Desktop.class.getClassLoader().loadClass(
2460               "groovy.ui.Console");
2461       Constructor<?> gccons = gcClass.getConstructor();
2462       java.lang.reflect.Method setvar = gcClass.getMethod("setVariable",
2463               new Class[]
2464               { String.class, Object.class });
2465       java.lang.reflect.Method run = gcClass.getMethod("run");
2466       Object gc = gccons.newInstance();
2467       setvar.invoke(gc, new Object[]
2468       { "Jalview", this });
2469       run.invoke(gc);
2470     } catch (Exception ex)
2471     {
2472       jalview.bin.Cache.log.error("Groovy Shell Creation failed.", ex);
2473       JOptionPane.showInternalMessageDialog(Desktop.desktop,
2474
2475       MessageManager.getString("label.couldnt_create_groovy_shell"),
2476               MessageManager.getString("label.groovy_support_failed"),
2477               JOptionPane.ERROR_MESSAGE);
2478     }
2479   }
2480
2481   /**
2482    * Progress bars managed by the IProgressIndicator method.
2483    */
2484   private Hashtable<Long, JPanel> progressBars;
2485
2486   private Hashtable<Long, IProgressIndicatorHandler> progressBarHandlers;
2487
2488   /*
2489    * (non-Javadoc)
2490    * 
2491    * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
2492    */
2493   public void setProgressBar(String message, long id)
2494   {
2495     if (progressBars == null)
2496     {
2497       progressBars = new Hashtable<Long, JPanel>();
2498       progressBarHandlers = new Hashtable<Long, IProgressIndicatorHandler>();
2499     }
2500
2501     if (progressBars.get(new Long(id)) != null)
2502     {
2503       JPanel progressPanel = progressBars.remove(new Long(id));
2504       if (progressBarHandlers.contains(new Long(id)))
2505       {
2506         progressBarHandlers.remove(new Long(id));
2507       }
2508       removeProgressPanel(progressPanel);
2509     }
2510     else
2511     {
2512       progressBars.put(new Long(id), addProgressPanel(message));
2513     }
2514   }
2515
2516   /*
2517    * (non-Javadoc)
2518    * 
2519    * @see jalview.gui.IProgressIndicator#registerHandler(long,
2520    * jalview.gui.IProgressIndicatorHandler)
2521    */
2522   public void registerHandler(final long id,
2523           final IProgressIndicatorHandler handler)
2524   {
2525     if (progressBarHandlers == null
2526             || !progressBars.containsKey(new Long(id)))
2527     {
2528       throw new Error(
2529               MessageManager
2530                       .getString("error.call_setprogressbar_before_registering_handler"));
2531     }
2532     progressBarHandlers.put(new Long(id), handler);
2533     final JPanel progressPanel = progressBars.get(new Long(id));
2534     if (handler.canCancel())
2535     {
2536       JButton cancel = new JButton(
2537               MessageManager.getString("action.cancel"));
2538       final IProgressIndicator us = this;
2539       cancel.addActionListener(new ActionListener()
2540       {
2541
2542         public void actionPerformed(ActionEvent e)
2543         {
2544           handler.cancelActivity(id);
2545           us.setProgressBar(MessageManager.formatMessage(
2546                   "label.cancelled_params", new Object[]
2547                   { ((JLabel) progressPanel.getComponent(0)).getText() }),
2548                   id);
2549         }
2550       });
2551       progressPanel.add(cancel, BorderLayout.EAST);
2552     }
2553   }
2554
2555   /**
2556    * 
2557    * @return true if any progress bars are still active
2558    */
2559   @Override
2560   public boolean operationInProgress()
2561   {
2562     if (progressBars != null && progressBars.size() > 0)
2563     {
2564       return true;
2565     }
2566     return false;
2567   }
2568
2569   /**
2570    * This will return the first AlignFrame holding the given viewport instance. It
2571    * will break if there are more than one AlignFrames viewing a particular av.
2572    * 
2573    * @param viewport
2574    * @return alignFrame for viewport
2575    */
2576   public static AlignFrame getAlignFrameFor(AlignViewportI viewport)
2577   {
2578     if (desktop != null)
2579     {
2580       AlignmentPanel[] aps = getAlignmentPanels(viewport
2581               .getSequenceSetId());
2582       for (int panel = 0; aps != null && panel < aps.length; panel++)
2583       {
2584         if (aps[panel] != null && aps[panel].av == viewport)
2585         {
2586           return aps[panel].alignFrame;
2587         }
2588       }
2589     }
2590     return null;
2591   }
2592
2593   public VamsasApplication getVamsasApplication()
2594   {
2595     return v_client;
2596
2597   }
2598
2599   /**
2600    * flag set if jalview GUI is being operated programmatically
2601    */
2602   private boolean inBatchMode = false;
2603
2604   /**
2605    * check if jalview GUI is being operated programmatically
2606    * 
2607    * @return inBatchMode
2608    */
2609   public boolean isInBatchMode()
2610   {
2611     return inBatchMode;
2612   }
2613
2614   /**
2615    * set flag if jalview GUI is being operated programmatically
2616    * 
2617    * @param inBatchMode
2618    */
2619   public void setInBatchMode(boolean inBatchMode)
2620   {
2621     this.inBatchMode = inBatchMode;
2622   }
2623
2624   public void startServiceDiscovery()
2625   {
2626     startServiceDiscovery(false);
2627   }
2628
2629   public void startServiceDiscovery(boolean blocking)
2630   {
2631     boolean alive = true;
2632     Thread t0 = null, t1 = null, t2 = null;
2633     // JAL-940 - JALVIEW 1 services are now being EOLed as of JABA 2.1 release
2634     if (true)
2635     {
2636       // todo: changesupport handlers need to be transferred
2637       if (discoverer == null)
2638       {
2639         discoverer = new jalview.ws.jws1.Discoverer();
2640         // register PCS handler for desktop.
2641         discoverer.addPropertyChangeListener(changeSupport);
2642       }
2643       // JAL-940 - disabled JWS1 service configuration - always start discoverer
2644       // until we phase out completely
2645       (t0 = new Thread(discoverer)).start();
2646     }
2647
2648     // ENFIN services are EOLed as of Jalview 2.8.1 release
2649     if (false)
2650     {
2651       try
2652       {
2653         if (Cache.getDefault("SHOW_ENFIN_SERVICES", true))
2654         {
2655           // EnfinEnvision web service menu entries are rebuild every time the
2656           // menu is shown, so no changeSupport events are needed.
2657           jalview.ws.EnfinEnvision2OneWay.getInstance();
2658           (t1 = new Thread(jalview.ws.EnfinEnvision2OneWay.getInstance()))
2659                   .start();
2660         }
2661       } catch (Exception e)
2662       {
2663         Cache.log
2664                 .info("Exception when trying to launch Envision2 workflow discovery.",
2665                         e);
2666         Cache.log.info(e.getStackTrace());
2667       }
2668     }
2669
2670     if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
2671     {
2672       if (jalview.ws.jws2.Jws2Discoverer.getDiscoverer().isRunning())
2673       {
2674         jalview.ws.jws2.Jws2Discoverer.getDiscoverer().setAborted(true);
2675       }
2676       t2 = jalview.ws.jws2.Jws2Discoverer.getDiscoverer().startDiscoverer(
2677               changeSupport);
2678
2679     }
2680     Thread t3 = null;
2681     {
2682       // TODO: do rest service discovery
2683     }
2684     if (blocking)
2685     {
2686       while (alive)
2687       {
2688         try
2689         {
2690           Thread.sleep(15);
2691         } catch (Exception e)
2692         {
2693         }
2694         alive = (t1 != null && t1.isAlive())
2695                 || (t2 != null && t2.isAlive())
2696                 || (t3 != null && t3.isAlive())
2697                 || (t0 != null && t0.isAlive());
2698       }
2699     }
2700   }
2701
2702   /**
2703    * called to check if the service discovery process completed successfully.
2704    * 
2705    * @param evt
2706    */
2707   protected void JalviewServicesChanged(PropertyChangeEvent evt)
2708   {
2709     if (evt.getNewValue() == null || evt.getNewValue() instanceof Vector)
2710     {
2711       final String ermsg = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
2712               .getErrorMessages();
2713       if (ermsg != null)
2714       {
2715         if (Cache.getDefault("SHOW_WSDISCOVERY_ERRORS", true))
2716         {
2717           if (serviceChangedDialog == null)
2718           {
2719             // only run if we aren't already displaying one of these.
2720             addDialogThread(serviceChangedDialog = new Runnable()
2721             {
2722               public void run()
2723               {
2724
2725                 /*
2726                  * JalviewDialog jd =new JalviewDialog() {
2727                  * 
2728                  * @Override protected void cancelPressed() { // TODO
2729                  * Auto-generated method stub
2730                  * 
2731                  * }@Override protected void okPressed() { // TODO
2732                  * Auto-generated method stub
2733                  * 
2734                  * }@Override protected void raiseClosed() { // TODO
2735                  * Auto-generated method stub
2736                  * 
2737                  * } }; jd.initDialogFrame(new
2738                  * JLabel("<html><table width=\"450\"><tr><td>" + ermsg +
2739                  * "<br/>It may be that you have invalid JABA URLs in your web service preferences,"
2740                  * + " or mis-configured HTTP proxy settings.<br/>" +
2741                  * "Check the <em>Connections</em> and <em>Web services</em> tab of the"
2742                  * +
2743                  * " Tools->Preferences dialog box to change them.</td></tr></table></html>"
2744                  * ), true, true, "Web Service Configuration Problem", 450,
2745                  * 400);
2746                  * 
2747                  * jd.waitForInput();
2748                  */
2749                 JOptionPane
2750                         .showConfirmDialog(
2751                                 Desktop.desktop,
2752                                 new JLabel(
2753                                         "<html><table width=\"450\"><tr><td>"
2754                                                 + ermsg
2755                                                 + "</td></tr></table>"
2756                                                 + "<p>It may be that you have invalid JABA URLs<br/>in your web service preferences,"
2757                                                 + "<br>or as a command-line argument, or mis-configured HTTP proxy settings.</p>"
2758                                                 + "<p>Check the <em>Connections</em> and <em>Web services</em> tab<br/>of the"
2759                                                 + " Tools->Preferences dialog box to change them.</p></html>"),
2760                                 "Web Service Configuration Problem",
2761                                 JOptionPane.DEFAULT_OPTION,
2762                                 JOptionPane.ERROR_MESSAGE);
2763                 serviceChangedDialog = null;
2764
2765               }
2766             });
2767           }
2768         }
2769         else
2770         {
2771           Cache.log
2772                   .error("Errors reported by JABA discovery service. Check web services preferences.\n"
2773                           + ermsg);
2774         }
2775       }
2776     }
2777   }
2778
2779   private Runnable serviceChangedDialog = null;
2780
2781   /**
2782    * start a thread to open a URL in the configured browser. Pops up a warning
2783    * dialog to the user if there is an exception when calling out to the browser
2784    * to open the URL.
2785    * 
2786    * @param url
2787    */
2788   public static void showUrl(final String url)
2789   {
2790     showUrl(url, Desktop.instance);
2791   }
2792
2793   /**
2794    * Like showUrl but allows progress handler to be specified
2795    * 
2796    * @param url
2797    * @param progress
2798    *          (null) or object implementing IProgressIndicator
2799    */
2800   public static void showUrl(final String url,
2801           final IProgressIndicator progress)
2802   {
2803     new Thread(new Runnable()
2804     {
2805       public void run()
2806       {
2807         try
2808         {
2809           if (progress != null)
2810           {
2811             progress.setProgressBar(MessageManager.formatMessage(
2812                     "status.opening_params", new Object[]
2813                     { url }), this.hashCode());
2814           }
2815           jalview.util.BrowserLauncher.openURL(url);
2816         } catch (Exception ex)
2817         {
2818           JOptionPane.showInternalMessageDialog(Desktop.desktop,
2819                   MessageManager
2820                           .getString("label.web_browser_not_found_unix"),
2821                   MessageManager.getString("label.web_browser_not_found"),
2822                   JOptionPane.WARNING_MESSAGE);
2823
2824           ex.printStackTrace();
2825         }
2826         if (progress != null)
2827         {
2828           progress.setProgressBar(null, this.hashCode());
2829         }
2830       }
2831     }).start();
2832   }
2833
2834   public static WsParamSetManager wsparamManager = null;
2835
2836   public static ParamManager getUserParameterStore()
2837   {
2838     if (wsparamManager == null)
2839     {
2840       wsparamManager = new WsParamSetManager();
2841     }
2842     return wsparamManager;
2843   }
2844
2845   /**
2846    * static hyperlink handler proxy method for use by Jalview's internal windows
2847    * 
2848    * @param e
2849    */
2850   public static void hyperlinkUpdate(HyperlinkEvent e)
2851   {
2852     if (e.getEventType() == EventType.ACTIVATED)
2853     {
2854       String url = null;
2855       try
2856       {
2857         url = e.getURL().toString();
2858         Desktop.showUrl(url);
2859       } catch (Exception x)
2860       {
2861         if (url != null)
2862         {
2863           if (Cache.log != null)
2864           {
2865             Cache.log.error("Couldn't handle string " + url + " as a URL.");
2866           }
2867           else
2868           {
2869             System.err.println("Couldn't handle string " + url
2870                     + " as a URL.");
2871           }
2872         }
2873         // ignore any exceptions due to dud links.
2874       }
2875
2876     }
2877   }
2878
2879   /**
2880    * single thread that handles display of dialogs to user.
2881    */
2882   ExecutorService dialogExecutor = Executors.newSingleThreadExecutor();
2883
2884   /**
2885    * flag indicating if dialogExecutor should try to acquire a permit
2886    */
2887   private volatile boolean dialogPause = true;
2888
2889   /**
2890    * pause the queue
2891    */
2892   private java.util.concurrent.Semaphore block = new Semaphore(0);
2893
2894   /**
2895    * add another dialog thread to the queue
2896    * 
2897    * @param prompter
2898    */
2899   public void addDialogThread(final Runnable prompter)
2900   {
2901     dialogExecutor.submit(new Runnable()
2902     {
2903       public void run()
2904       {
2905         if (dialogPause)
2906         {
2907           try
2908           {
2909             block.acquire();
2910           } catch (InterruptedException x)
2911           {
2912           }
2913           ;
2914         }
2915         if (instance == null)
2916         {
2917           return;
2918         }
2919         try
2920         {
2921           SwingUtilities.invokeAndWait(prompter);
2922         } catch (Exception q)
2923         {
2924           Cache.log.warn("Unexpected Exception in dialog thread.", q);
2925         }
2926       }
2927     });
2928   }
2929
2930   public void startDialogQueue()
2931   {
2932     // set the flag so we don't pause waiting for another permit and semaphore
2933     // the current task to begin
2934     dialogPause = false;
2935     block.release();
2936   }
2937
2938   @Override
2939   protected void snapShotWindow_actionPerformed(ActionEvent e)
2940   {
2941     invalidate();
2942     File of;
2943     ImageMaker im = new jalview.util.ImageMaker(this, ImageMaker.TYPE.EPS,
2944             "View of Desktop", getWidth(), getHeight(), of = new File(
2945                     "Jalview_snapshot" + System.currentTimeMillis()
2946                             + ".eps"), "View of desktop");
2947     try
2948     {
2949       paintAll(im.getGraphics());
2950       im.writeImage();
2951     } catch (Exception q)
2952     {
2953       Cache.log.error("Couldn't write snapshot to " + of.getAbsolutePath(),
2954               q);
2955       return;
2956     }
2957     Cache.log.info("Successfully written snapshot to file "
2958             + of.getAbsolutePath());
2959   }
2960
2961   /**
2962    * Explode the views in the given frame into separate AlignFrame windows.
2963    * 
2964    * @param sf
2965    */
2966   public void explodeViews(SplitFrame sf)
2967   {
2968     AlignFrame oldTopFrame = (AlignFrame) sf.getTopFrame();
2969     AlignFrame oldBottomFrame = (AlignFrame) sf.getBottomFrame();
2970     List<? extends AlignmentViewPanel> topPanels = oldTopFrame
2971             .getAlignPanels();
2972     List<? extends AlignmentViewPanel> bottomPanels = oldBottomFrame
2973             .getAlignPanels();
2974     int viewCount = topPanels.size();
2975     if (viewCount < 2)
2976     {
2977       return;
2978     }
2979
2980     /*
2981      * Processing in reverse order works, forwards order leaves the first panels
2982      * not visible. I don't know why!
2983      */
2984     for (int i = viewCount - 1; i >= 0; i--)
2985     {
2986       /*
2987        * Make new top and bottom frames. These take over the respective
2988        * AlignmentPanel objects, including their AlignmentViewports, so the
2989        * cdna/protein relationships between the viewports is carried over to the
2990        * new split frames.
2991        */
2992       AlignmentPanel topPanel = (AlignmentPanel) topPanels.get(i);
2993       AlignFrame newTopFrame = new AlignFrame(topPanel);
2994       newTopFrame.setSize(new Dimension(AlignFrame.DEFAULT_WIDTH,
2995               AlignFrame.DEFAULT_HEIGHT));
2996       newTopFrame.setVisible(true);
2997       AlignmentPanel bottomPanel = (AlignmentPanel) bottomPanels.get(i);
2998       AlignFrame newBottomFrame = new AlignFrame(bottomPanel);
2999       newBottomFrame.setSize(new Dimension(AlignFrame.DEFAULT_WIDTH,
3000               AlignFrame.DEFAULT_HEIGHT));
3001       newBottomFrame.setVisible(true);
3002       topPanel.av.setGatherViewsHere(false);
3003       bottomPanel.av.setGatherViewsHere(false);
3004       JInternalFrame splitFrame = new SplitFrame(newTopFrame,
3005               newBottomFrame);
3006       // either panel may hold previous exploded frame geometry
3007       Rectangle geometry = ((AlignViewport) topPanel.getAlignViewport())
3008               .getExplodedGeometry();
3009       if (geometry != null)
3010       {
3011         splitFrame.setBounds(geometry);
3012       }
3013       Desktop.addInternalFrame(splitFrame, sf.getTitle(), -1, -1);
3014     }
3015
3016     /*
3017      * Clear references to the panels (now relocated in the new SplitFrames)
3018      * before closing the old SplitFrame.
3019      */
3020     topPanels.clear();
3021     bottomPanels.clear();
3022     sf.close();
3023   }
3024
3025   /**
3026    * Gather expanded split frames, sharing the same pairs of sequence set ids,
3027    * back into the given SplitFrame as additional views. Note that the gathered
3028    * frames may themselves have multiple views.
3029    * 
3030    * @param source
3031    */
3032   public void gatherViews(GSplitFrame source)
3033   {
3034     AlignFrame myTopFrame = (AlignFrame) source.getTopFrame();
3035     AlignFrame myBottomFrame = (AlignFrame) source.getBottomFrame();
3036     myTopFrame.viewport.setExplodedGeometry(source.getBounds());
3037     myBottomFrame.viewport.setExplodedGeometry(source.getBounds());
3038     myTopFrame.viewport.setGatherViewsHere(true);
3039     myBottomFrame.viewport.setGatherViewsHere(true);
3040     String topViewId = myTopFrame.viewport.getSequenceSetId();
3041     String bottomViewId = myBottomFrame.viewport.getSequenceSetId();
3042   
3043     JInternalFrame[] frames = desktop.getAllFrames();
3044     for (JInternalFrame frame : frames)
3045     {
3046       if (frame instanceof SplitFrame && frame != source)
3047       {
3048         SplitFrame sf = (SplitFrame) frame;
3049         AlignFrame topFrame = (AlignFrame) sf.getTopFrame();
3050         AlignFrame bottomFrame = (AlignFrame) sf.getBottomFrame();
3051         boolean gatherThis = false;
3052         for (int a = 0; a < topFrame.alignPanels.size(); a++)
3053         {
3054           AlignmentPanel topPanel = topFrame.alignPanels.get(a);
3055           AlignmentPanel bottomPanel = bottomFrame.alignPanels.get(a);
3056           if (topViewId.equals(topPanel.av.getSequenceSetId())
3057                   && bottomViewId.equals(bottomPanel.av.getSequenceSetId()))
3058           {
3059             gatherThis = true;
3060             topPanel.av.setGatherViewsHere(false);
3061             bottomPanel.av.setGatherViewsHere(false);
3062             // both panels refer to the same split frame geometry
3063             Rectangle position = sf.getBounds();
3064             topPanel.av.setExplodedGeometry(position);
3065             bottomPanel.av.setExplodedGeometry(position);
3066             myTopFrame.addAlignmentPanel(topPanel, false);
3067             myBottomFrame.addAlignmentPanel(bottomPanel, false);
3068           }
3069         }
3070   
3071         if (gatherThis)
3072         {
3073           topFrame.getAlignPanels().clear();
3074           bottomFrame.getAlignPanels().clear();
3075           sf.close();
3076         }
3077       }
3078     }
3079
3080     /*
3081      * The dust settles...give focus to the tab we did this from.
3082      */
3083     myTopFrame.setDisplayedView(myTopFrame.alignPanel);
3084
3085   }
3086
3087   // public static AlignFrame getCurrentAlignFrame()
3088   // {
3089   // return currentAlignFrame;
3090   // }
3091   //
3092   // public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
3093   // {
3094   // Desktop.currentAlignFrame = currentAlignFrame;
3095   // }
3096
3097
3098 }