JAL-1677 save/restore SplitFrame to Jalview project
[jalview.git] / src / jalview / gui / Desktop.java
index 7852253..393818b 100644 (file)
 package jalview.gui;
 
 import jalview.api.AlignViewportI;
+import jalview.api.AlignmentViewPanel;
 import jalview.bin.Cache;
 import jalview.io.FileLoader;
 import jalview.io.FormatAdapter;
 import jalview.io.IdentifyFile;
 import jalview.io.JalviewFileChooser;
 import jalview.io.JalviewFileView;
+import jalview.jbgui.GSplitFrame;
 import jalview.jbgui.GStructureViewer;
 import jalview.structure.StructureSelectionManager;
 import jalview.util.ImageMaker;
@@ -335,8 +337,7 @@ public class Desktop extends jalview.jbgui.GDesktop implements
             + jalview.bin.Cache.getProperty("VERSION") + "\n"
             + "Jalview Installation: "
             + jalview.bin.Cache.getDefault("INSTALLATION", "unknown")
-            + "\n"
-            + "Build Date: "
+            + "\n" + "Build Date: "
             + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown") + "\n"
             + "Java version: " + System.getProperty("java.version") + "\n"
             + System.getProperty("os.arch") + " "
@@ -437,9 +438,10 @@ public class Desktop extends jalview.jbgui.GDesktop implements
     {
       ssm.setAddTempFacAnnot(jalview.bin.Cache.getDefault(
               Preferences.ADD_TEMPFACT_ANN, true));
-    ssm.setProcessSecondaryStructure(jalview.bin.Cache.getDefault(Preferences.STRUCT_FROM_PDB, true));
-    ssm.setSecStructServices(jalview.bin.Cache.getDefault(Preferences.USE_RNAVIEW,
-            true));
+      ssm.setProcessSecondaryStructure(jalview.bin.Cache.getDefault(
+              Preferences.STRUCT_FROM_PDB, true));
+      ssm.setSecStructServices(jalview.bin.Cache.getDefault(
+              Preferences.USE_RNAVIEW, true));
     }
     else
     {
@@ -485,7 +487,9 @@ public class Desktop extends jalview.jbgui.GDesktop implements
           public void run()
           {
             long instance = System.currentTimeMillis();
-            Desktop.instance.setProgressBar(MessageManager.getString("status.refreshing_news"), instance);
+            Desktop.instance.setProgressBar(
+                    MessageManager.getString("status.refreshing_news"),
+                    instance);
             jvnews.refreshNews();
             Desktop.instance.setProgressBar(null, instance);
             jvnews.showNews();
@@ -653,7 +657,6 @@ public class Desktop extends jalview.jbgui.GDesktop implements
     addInternalFrame(frame, title, true, w, h, true);
   }
 
-
   /**
    * Add an internal frame to the Jalview desktop
    * 
@@ -1198,8 +1201,7 @@ public class Desktop extends jalview.jbgui.GDesktop implements
     if (shortv)
     {
       message.append("<h1><strong>Version: "
-              + jalview.bin.Cache.getProperty("VERSION")
-              + "</strong></h1>");
+              + jalview.bin.Cache.getProperty("VERSION") + "</strong></h1>");
       message.append("<strong>Last Updated: <em>"
               + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown")
               + "</em></strong>");
@@ -1245,8 +1247,7 @@ public class Desktop extends jalview.jbgui.GDesktop implements
     }
     message.append("<br>Authors:  "
             + jalview.bin.Cache
-                    .getDefault(
-                            "AUTHORFNAMES",
+                    .getDefault("AUTHORFNAMES",
                             "The Jalview Authors (See AUTHORS file for current list)")
             + "<br><br>Development managed by The Barton Group, University of Dundee, Scotland, UK.<br>"
             + "<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"
@@ -1483,8 +1484,9 @@ public class Desktop extends jalview.jbgui.GDesktop implements
         public void run()
         {
 
-          setProgressBar(MessageManager.formatMessage("label.saving_jalview_project", new Object[]{choice.getName()}),
-                  choice.hashCode());
+          setProgressBar(MessageManager.formatMessage(
+                  "label.saving_jalview_project", new Object[]
+                  { choice.getName() }), choice.hashCode());
           jalview.bin.Cache.setProperty("LAST_DIRECTORY",
                   choice.getParent());
           // TODO catch and handle errors for savestate
@@ -1501,10 +1503,11 @@ public class Desktop extends jalview.jbgui.GDesktop implements
             Cache.log.error(
                     "Problems whilst trying to save to " + choice.getName(),
                     ex);
-            JOptionPane.showMessageDialog(
-                    me,
-                    MessageManager.formatMessage("label.error_whilst_saving_current_state_to", new Object[]{ choice.getName()}),
-                    MessageManager.getString("label.couldnt_save_project"),
+            JOptionPane.showMessageDialog(me, MessageManager.formatMessage(
+                    "label.error_whilst_saving_current_state_to",
+                    new Object[]
+                    { choice.getName() }), MessageManager
+                    .getString("label.couldnt_save_project"),
                     JOptionPane.WARNING_MESSAGE);
           }
           setProgressBar(null, choice.hashCode());
@@ -1572,15 +1575,15 @@ public class Desktop extends jalview.jbgui.GDesktop implements
       final File selectedFile = chooser.getSelectedFile();
       setProjectFile(selectedFile);
       final String choice = selectedFile.getAbsolutePath();
-      jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedFile.getParent());
+      jalview.bin.Cache.setProperty("LAST_DIRECTORY",
+              selectedFile.getParent());
       new Thread(new Runnable()
       {
         public void run()
         {
           setProgressBar(MessageManager.formatMessage(
                   "label.loading_jalview_project", new Object[]
-                  { choice }),
-                  choice.hashCode());
+                  { choice }), choice.hashCode());
           try
           {
             new Jalview2XML().loadJalviewAlign(choice);
@@ -1591,13 +1594,13 @@ public class Desktop extends jalview.jbgui.GDesktop implements
           {
             Cache.log.error("Problems whilst loading project from "
                     + choice, ex);
-            JOptionPane.showMessageDialog(Desktop.desktop,
- MessageManager
+            JOptionPane.showMessageDialog(Desktop.desktop, MessageManager
                     .formatMessage(
                             "label.error_whilst_loading_project_from",
                             new Object[]
-                            { choice }),
-                    MessageManager.getString("label.couldnt_load_project"), JOptionPane.WARNING_MESSAGE);
+                            { choice }), MessageManager
+                    .getString("label.couldnt_load_project"),
+                    JOptionPane.WARNING_MESSAGE);
           }
           setProgressBar(null, choice.hashCode());
         }
@@ -1719,14 +1722,6 @@ public class Desktop extends jalview.jbgui.GDesktop implements
           aps.add(ap);
         }
       }
-      // for (int a = 0; a < af.alignPanels.size(); a++)
-      // {
-      // if (alignmentId.equals(af.alignPanels
-      // .get(a).av.getSequenceSetId()))
-      // {
-      // aps.add(af.alignPanels.get(a));
-      // }
-      // }
     }
     if (aps.size() == 0)
     {
@@ -1780,6 +1775,11 @@ public class Desktop extends jalview.jbgui.GDesktop implements
     return null;
   }
 
+  /**
+   * Explode the views in the given frame into separate AlignFrame
+   * 
+   * @param af
+   */
   public void explodeViews(AlignFrame af)
   {
     int size = af.alignPanels.size();
@@ -1792,13 +1792,19 @@ public class Desktop extends jalview.jbgui.GDesktop implements
     {
       AlignmentPanel ap = af.alignPanels.get(i);
       AlignFrame newaf = new AlignFrame(ap);
-      if (ap.av.explodedPosition != null
-              && !ap.av.explodedPosition.equals(af.getBounds()))
+
+      /*
+       * Restore the view's last exploded frame geometry if known. Multiple
+       * views from one exploded frame share and restore the same (frame)
+       * position and size.
+       */
+      Rectangle geometry = ap.av.getExplodedGeometry();
+      if (geometry != null)
       {
-        newaf.setBounds(ap.av.explodedPosition);
+        newaf.setBounds(geometry);
       }
 
-      ap.av.gatherViewsHere = false;
+      ap.av.setGatherViewsHere(false);
 
       addInternalFrame(newaf, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
               AlignFrame.DEFAULT_HEIGHT);
@@ -1809,10 +1815,18 @@ public class Desktop extends jalview.jbgui.GDesktop implements
 
   }
 
+  /**
+   * Gather expanded views (separate AlignFrame's) with the same sequence set
+   * identifier back in to this frame as additional views, and close the
+   * expanded views. Note the expanded frames may themselves have multiple
+   * views. We take the lot.
+   * 
+   * @param source
+   */
   public void gatherViews(AlignFrame source)
   {
-    source.viewport.gatherViewsHere = true;
-    source.viewport.explodedPosition = source.getBounds();
+    source.viewport.setGatherViewsHere(true);
+    source.viewport.setExplodedGeometry(source.getBounds());
     JInternalFrame[] frames = desktop.getAllFrames();
     String viewId = source.viewport.getSequenceSetId();
 
@@ -1828,8 +1842,8 @@ public class Desktop extends jalview.jbgui.GDesktop implements
           if (viewId.equals(ap.av.getSequenceSetId()))
           {
             gatherThis = true;
-            ap.av.gatherViewsHere = false;
-            ap.av.explodedPosition = af.getBounds();
+            ap.av.setGatherViewsHere(false);
+            ap.av.setExplodedGeometry(af.getBounds());
             source.addAlignmentPanel(ap, false);
           }
         }
@@ -1855,7 +1869,8 @@ public class Desktop extends jalview.jbgui.GDesktop implements
               jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
 
       chooser.setFileView(new JalviewFileView());
-      chooser.setDialogTitle(MessageManager.getString("label.open_saved_vamsas_session"));
+      chooser.setDialogTitle(MessageManager
+              .getString("label.open_saved_vamsas_session"));
       chooser.setToolTipText(MessageManager
               .getString("label.select_vamsas_session_opened_as_new_vamsas_session"));
 
@@ -1948,23 +1963,26 @@ public class Desktop extends jalview.jbgui.GDesktop implements
       return false;
     }
 
-    setProgressBar(MessageManager.formatMessage("status.importing_vamsas_session_from", new Object[]{file.getName()}),
-            file.hashCode());
+    setProgressBar(MessageManager.formatMessage(
+            "status.importing_vamsas_session_from", new Object[]
+            { file.getName() }), file.hashCode());
     try
     {
       v_client = new jalview.gui.VamsasApplication(this, file, null);
     } catch (Exception ex)
     {
-        setProgressBar(MessageManager.formatMessage("status.importing_vamsas_session_from", new Object[]{file.getName()}),
-                file.hashCode());
+      setProgressBar(MessageManager.formatMessage(
+              "status.importing_vamsas_session_from", new Object[]
+              { file.getName() }), file.hashCode());
       jalview.bin.Cache.log.error(
               "New vamsas session from existing session file failed:", ex);
       return false;
     }
     setupVamsasConnectedGui();
     v_client.initial_update(); // TODO: thread ?
-    setProgressBar(MessageManager.formatMessage("status.importing_vamsas_session_from", new Object[]{file.getName()}),
-            file.hashCode());
+    setProgressBar(MessageManager.formatMessage(
+            "status.importing_vamsas_session_from", new Object[]
+            { file.getName() }), file.hashCode());
     return v_client.inSession();
   }
 
@@ -1972,11 +1990,14 @@ public class Desktop extends jalview.jbgui.GDesktop implements
   {
     if (v_client != null)
     {
-      throw new Error(MessageManager.getString("error.try_join_vamsas_session_another"));
+      throw new Error(
+              MessageManager
+                      .getString("error.try_join_vamsas_session_another"));
     }
     if (mysesid == null)
     {
-      throw new Error(MessageManager.getString("error.invalid_vamsas_session_id"));
+      throw new Error(
+              MessageManager.getString("error.invalid_vamsas_session_id"));
     }
     v_client = new VamsasApplication(this, mysesid);
     setupVamsasConnectedGui();
@@ -2123,14 +2144,17 @@ public class Desktop extends jalview.jbgui.GDesktop implements
               { "Vamsas Document" }, "Vamsas Document");
 
       chooser.setFileView(new JalviewFileView());
-      chooser.setDialogTitle(MessageManager.getString("label.save_vamsas_document_archive"));
+      chooser.setDialogTitle(MessageManager
+              .getString("label.save_vamsas_document_archive"));
 
       int value = chooser.showSaveDialog(this);
 
       if (value == JalviewFileChooser.APPROVE_OPTION)
       {
         java.io.File choice = chooser.getSelectedFile();
-        JPanel progpanel = addProgressPanel(MessageManager.formatMessage("label.saving_vamsas_doc", new Object[]{choice.getName()}));
+        JPanel progpanel = addProgressPanel(MessageManager.formatMessage(
+                "label.saving_vamsas_doc", new Object[]
+                { choice.getName() }));
         jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
         String warnmsg = null;
         String warnttl = null;
@@ -2182,7 +2206,8 @@ public class Desktop extends jalview.jbgui.GDesktop implements
     }
     if (b)
     {
-      vamUpdate = this.addProgressPanel(MessageManager.getString("label.updating_vamsas_session"));
+      vamUpdate = this.addProgressPanel(MessageManager
+              .getString("label.updating_vamsas_session"));
     }
     vamsasStart.setVisible(!b);
     vamsasStop.setVisible(!b);
@@ -2358,14 +2383,14 @@ public class Desktop extends jalview.jbgui.GDesktop implements
         /*
          * Also check for a split frame containing an AlignFrame
          */
-        SplitFrame sf = (SplitFrame) frames[i];
-        if (sf.getTopComponent() instanceof AlignFrame)
+        GSplitFrame sf = (GSplitFrame) frames[i];
+        if (sf.getTopFrame() instanceof AlignFrame)
         {
-          avp.add((AlignFrame) sf.getTopComponent());
+          avp.add((AlignFrame) sf.getTopFrame());
         }
-        if (sf.getBottomComponent() instanceof AlignFrame)
+        if (sf.getBottomFrame() instanceof AlignFrame)
         {
-          avp.add((AlignFrame) sf.getBottomComponent());
+          avp.add((AlignFrame) sf.getBottomFrame());
         }
       }
     }
@@ -2416,7 +2441,9 @@ public class Desktop extends jalview.jbgui.GDesktop implements
     // use reflection to avoid creating compilation dependency.
     if (!jalview.bin.Cache.groovyJarsPresent())
     {
-      throw new Error(MessageManager.getString("error.implementation_error_cannot_create_groovyshell"));
+      throw new Error(
+              MessageManager
+                      .getString("error.implementation_error_cannot_create_groovyshell"));
     }
     try
     {
@@ -2434,13 +2461,11 @@ public class Desktop extends jalview.jbgui.GDesktop implements
     } catch (Exception ex)
     {
       jalview.bin.Cache.log.error("Groovy Shell Creation failed.", ex);
-      JOptionPane
-              .showInternalMessageDialog(
-                      Desktop.desktop,
+      JOptionPane.showInternalMessageDialog(Desktop.desktop,
 
-                      MessageManager.getString("label.couldnt_create_groovy_shell"),
-                      MessageManager.getString("label.groovy_support_failed"),
-                      JOptionPane.ERROR_MESSAGE);
+      MessageManager.getString("label.couldnt_create_groovy_shell"),
+              MessageManager.getString("label.groovy_support_failed"),
+              JOptionPane.ERROR_MESSAGE);
     }
   }
 
@@ -2490,7 +2515,9 @@ public class Desktop extends jalview.jbgui.GDesktop implements
   {
     if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
     {
-      throw new Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
+      throw new Error(
+              MessageManager
+                      .getString("error.call_setprogressbar_before_registering_handler"));
     }
     progressBarHandlers.put(new Long(id), handler);
     final JPanel progressPanel = progressBars.get(new Long(id));
@@ -2505,7 +2532,10 @@ public class Desktop extends jalview.jbgui.GDesktop implements
         public void actionPerformed(ActionEvent e)
         {
           handler.cancelActivity(id);
-          us.setProgressBar(MessageManager.formatMessage("label.cancelled_params", new Object[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
+          us.setProgressBar(MessageManager.formatMessage(
+                  "label.cancelled_params", new Object[]
+                  { ((JLabel) progressPanel.getComponent(0)).getText() }),
+                  id);
         }
       });
       progressPanel.add(cancel, BorderLayout.EAST);
@@ -2527,7 +2557,7 @@ public class Desktop extends jalview.jbgui.GDesktop implements
   }
 
   /**
-   * This will return the AlignFrame holding the given viewport instance. It
+   * This will return the first AlignFrame holding the given viewport instance. It
    * will break if there are more than one AlignFrames viewing a particular av.
    * 
    * @param viewport
@@ -2768,17 +2798,18 @@ public class Desktop extends jalview.jbgui.GDesktop implements
         {
           if (progress != null)
           {
-            progress.setProgressBar(MessageManager.formatMessage("status.opening_params", new Object[]{url}), this.hashCode());
+            progress.setProgressBar(MessageManager.formatMessage(
+                    "status.opening_params", new Object[]
+                    { url }), this.hashCode());
           }
           jalview.util.BrowserLauncher.openURL(url);
         } catch (Exception ex)
         {
-          JOptionPane
-                  .showInternalMessageDialog(
-                          Desktop.desktop,
-                          MessageManager.getString("label.web_browser_not_found_unix"),
-                          MessageManager.getString("label.web_browser_not_found"),
-                          JOptionPane.WARNING_MESSAGE);
+          JOptionPane.showInternalMessageDialog(Desktop.desktop,
+                  MessageManager
+                          .getString("label.web_browser_not_found_unix"),
+                  MessageManager.getString("label.web_browser_not_found"),
+                  JOptionPane.WARNING_MESSAGE);
 
           ex.printStackTrace();
         }
@@ -2893,6 +2924,7 @@ public class Desktop extends jalview.jbgui.GDesktop implements
     dialogPause = false;
     block.release();
   }
+
   @Override
   protected void snapShotWindow_actionPerformed(ActionEvent e)
   {
@@ -2902,14 +2934,139 @@ public class Desktop extends jalview.jbgui.GDesktop implements
             "View of Desktop", getWidth(), getHeight(), of = new File(
                     "Jalview_snapshot" + System.currentTimeMillis()
                             + ".eps"), "View of desktop");
-    try {
+    try
+    {
       paintAll(im.getGraphics());
       im.writeImage();
     } catch (Exception q)
     {
-      Cache.log.error("Couldn't write snapshot to "+of.getAbsolutePath(),q);
+      Cache.log.error("Couldn't write snapshot to " + of.getAbsolutePath(),
+              q);
+      return;
+    }
+    Cache.log.info("Successfully written snapshot to file "
+            + of.getAbsolutePath());
+  }
+
+  /**
+   * Explode the views in the given frame into separate AlignFrame windows.
+   * 
+   * @param sf
+   */
+  public void explodeViews(SplitFrame sf)
+  {
+    AlignFrame oldTopFrame = (AlignFrame) sf.getTopFrame();
+    AlignFrame oldBottomFrame = (AlignFrame) sf.getBottomFrame();
+    List<? extends AlignmentViewPanel> topPanels = oldTopFrame
+            .getAlignPanels();
+    List<? extends AlignmentViewPanel> bottomPanels = oldBottomFrame
+            .getAlignPanels();
+    int viewCount = topPanels.size();
+    if (viewCount < 2)
+    {
       return;
     }
-    Cache.log.info("Successfully written snapshot to file "+of.getAbsolutePath());
+
+    /*
+     * Processing in reverse order works, forwards order leaves the first panels
+     * not visible. I don't know why!
+     */
+    for (int i = viewCount - 1; i >= 0; i--)
+    {
+      /*
+       * Make new top and bottom frames. These take over the respective
+       * AlignmentPanel objects, including their AlignmentViewports, so the
+       * cdna/protein relationships between the viewports is carried over to the
+       * new split frames.
+       */
+      AlignmentPanel topPanel = (AlignmentPanel) topPanels.get(i);
+      AlignFrame newTopFrame = new AlignFrame(topPanel);
+      newTopFrame.setVisible(true);
+      AlignmentPanel bottomPanel = (AlignmentPanel) bottomPanels.get(i);
+      AlignFrame newBottomFrame = new AlignFrame(bottomPanel);
+      newBottomFrame.setVisible(true);
+      topPanel.av.setGatherViewsHere(false);
+      bottomPanel.av.setGatherViewsHere(false);
+      JInternalFrame splitFrame = new SplitFrame(newTopFrame,
+              newBottomFrame);
+      // either panel may hold previous exploded frame geometry
+      Rectangle geometry = ((AlignViewport) topPanel.getAlignViewport())
+              .getExplodedGeometry();
+      if (geometry != null)
+      {
+        splitFrame.setBounds(geometry);
+      }
+      Desktop.addInternalFrame(splitFrame, sf.getTitle(), -1, -1);
+    }
+
+    /*
+     * Clear references to the panels (now relocated in the new SplitFrames)
+     * before closing the old SplitFrame.
+     */
+    topPanels.clear();
+    bottomPanels.clear();
+    sf.close();
+  }
+
+  /**
+   * Gather expanded split frames, sharing the same pairs of sequence set ids,
+   * back into the given SplitFrame as additional views. Note that the gathered
+   * frames may themselves have multiple views.
+   * 
+   * @param source
+   */
+  public void gatherViews(GSplitFrame source)
+  {
+    AlignFrame myTopFrame = (AlignFrame) source.getTopFrame();
+    AlignFrame myBottomFrame = (AlignFrame) source.getBottomFrame();
+    myTopFrame.viewport.setExplodedGeometry(source.getBounds());
+    myBottomFrame.viewport.setExplodedGeometry(source.getBounds());
+    myTopFrame.viewport.setGatherViewsHere(true);
+    myBottomFrame.viewport.setGatherViewsHere(true);
+    String topViewId = myTopFrame.viewport.getSequenceSetId();
+    String bottomViewId = myBottomFrame.viewport.getSequenceSetId();
+  
+    JInternalFrame[] frames = desktop.getAllFrames();
+    for (JInternalFrame frame : frames)
+    {
+      if (frame instanceof SplitFrame && frame != source)
+      {
+        SplitFrame sf = (SplitFrame) frame;
+        AlignFrame topFrame = (AlignFrame) sf.getTopFrame();
+        AlignFrame bottomFrame = (AlignFrame) sf.getBottomFrame();
+        boolean gatherThis = false;
+        for (int a = 0; a < topFrame.alignPanels.size(); a++)
+        {
+          AlignmentPanel topPanel = topFrame.alignPanels.get(a);
+          AlignmentPanel bottomPanel = bottomFrame.alignPanels.get(a);
+          if (topViewId.equals(topPanel.av.getSequenceSetId())
+                  && bottomViewId.equals(bottomPanel.av.getSequenceSetId()))
+          {
+            gatherThis = true;
+            topPanel.av.setGatherViewsHere(false);
+            bottomPanel.av.setGatherViewsHere(false);
+            // both panels refer to the same split frame geometry
+            Rectangle position = sf.getBounds();
+            topPanel.av.setExplodedGeometry(position);
+            bottomPanel.av.setExplodedGeometry(position);
+            myTopFrame.addAlignmentPanel(topPanel, false);
+            myBottomFrame.addAlignmentPanel(bottomPanel, false);
+          }
+        }
+  
+        if (gatherThis)
+        {
+          topFrame.getAlignPanels().clear();
+          bottomFrame.getAlignPanels().clear();
+          sf.close();
+        }
+      }
+    }
+
+    /*
+     * The dust settles...give focus to the tab we did this from.
+     */
+    myTopFrame.setDisplayedView(myTopFrame.alignPanel);
+
   }
 }