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