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