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