JAL-3063 temporary extra menu option to save/load project as JAXB
[jalview.git] / src / jalview / gui / Desktop.java
index e14e991..bbdddbb 100644 (file)
@@ -69,6 +69,7 @@ import java.awt.dnd.DropTargetEvent;
 import java.awt.dnd.DropTargetListener;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
+import java.awt.event.InputEvent;
 import java.awt.event.KeyEvent;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
@@ -92,10 +93,13 @@ import java.util.concurrent.Executors;
 import java.util.concurrent.Semaphore;
 
 import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.ActionMap;
 import javax.swing.Box;
 import javax.swing.BoxLayout;
 import javax.swing.DefaultDesktopManager;
 import javax.swing.DesktopManager;
+import javax.swing.InputMap;
 import javax.swing.JButton;
 import javax.swing.JCheckBox;
 import javax.swing.JComboBox;
@@ -515,7 +519,7 @@ public class Desktop extends jalview.jbgui.GDesktop
   {
     final Desktop me = this;
     // Thread off the news reader, in case there are connection problems.
-    addDialogThread(new Runnable()
+    new Thread(new Runnable()
     {
       @Override
       public void run()
@@ -526,13 +530,13 @@ public class Desktop extends jalview.jbgui.GDesktop
         showNews.setVisible(true);
         Cache.log.debug("Completed news thread.");
       }
-    });
+    }).start();
   }
 
   public void getIdentifiersOrgData()
   {
     // Thread off the identifiers fetcher
-    addDialogThread(new Runnable()
+    new Thread(new Runnable()
     {
       @Override
       public void run()
@@ -549,7 +553,8 @@ public class Desktop extends jalview.jbgui.GDesktop
                   + e.getMessage());
         }
       }
-    });
+    }).start();
+    ;
   }
 
   @Override
@@ -903,8 +908,6 @@ public class Desktop extends jalview.jbgui.GDesktop
           menuItem.removeActionListener(menuItem.getActionListeners()[0]);
         }
         windowMenu.remove(menuItem);
-
-        System.gc();
       };
     });
 
@@ -924,6 +927,8 @@ public class Desktop extends jalview.jbgui.GDesktop
       }
     });
 
+    setKeyBindings(frame);
+
     desktop.add(frame);
 
     windowMenu.add(menuItem);
@@ -943,6 +948,42 @@ public class Desktop extends jalview.jbgui.GDesktop
     }
   }
 
+  /**
+   * Add key bindings to a JInternalFrame so that Ctrl-W and Cmd-W will close
+   * the window
+   * 
+   * @param frame
+   */
+  private static void setKeyBindings(JInternalFrame frame)
+  {
+    @SuppressWarnings("serial")
+    final Action closeAction = new AbstractAction()
+    {
+      @Override
+      public void actionPerformed(ActionEvent e)
+      {
+        frame.dispose();
+      }
+    };
+
+    /*
+     * set up key bindings for Ctrl-W and Cmd-W, with the same (Close) action
+     */
+    KeyStroke ctrlWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
+            InputEvent.CTRL_DOWN_MASK);
+    KeyStroke cmdWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
+            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
+
+    InputMap inputMap = frame
+            .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
+    String ctrlW = ctrlWKey.toString();
+    inputMap.put(ctrlWKey, ctrlW);
+    inputMap.put(cmdWKey, ctrlW);
+
+    ActionMap actionMap = frame.getActionMap();
+    actionMap.put(ctrlW, closeAction);
+  }
+
   @Override
   public void lostOwnership(Clipboard clipboard, Transferable contents)
   {
@@ -1392,7 +1433,6 @@ public class Desktop extends jalview.jbgui.GDesktop
     {
       ssm.resetAll();
     }
-    System.gc();
   }
 
   @Override
@@ -1565,9 +1605,10 @@ public class Desktop extends jalview.jbgui.GDesktop
    *          DOCUMENT ME!
    */
   @Override
-  public void saveState_actionPerformed(ActionEvent e)
+  public void saveState_actionPerformed(boolean asCastor)
   {
-    JalviewFileChooser chooser = new JalviewFileChooser("jvp",
+    JalviewFileChooser chooser = new JalviewFileChooser(
+            asCastor ? "jvp" : "jvx",
             "Jalview Project");
 
     chooser.setFileView(new JalviewFileView());
@@ -1596,7 +1637,14 @@ public class Desktop extends jalview.jbgui.GDesktop
           // TODO prevent user from messing with the Desktop whilst we're saving
           try
           {
-            new Jalview2XML().saveState(choice);
+            if (asCastor)
+            {
+              new Jalview2XML().saveState(choice);
+            }
+            else
+            {
+              new jalview.project.Jalview2XML().saveState(choice);
+            }
           } catch (OutOfMemoryError oom)
           {
             new OOMWarning(
@@ -1638,13 +1686,19 @@ public class Desktop extends jalview.jbgui.GDesktop
    *          DOCUMENT ME!
    */
   @Override
-  public void loadState_actionPerformed(ActionEvent e)
-  {
+  public void loadState_actionPerformed(boolean asCastor)
+  {
+    final String[] suffix = asCastor ? new String[] { "jvp", "jar" }
+            : new String[]
+            { "jvx" };
+    final String[] desc = asCastor
+            ? new String[]
+            { "Jalview Project", "Jalview Project (old)" }
+            : new String[]
+            { "Jalview Project" };
     JalviewFileChooser chooser = new JalviewFileChooser(
-            Cache.getProperty("LAST_DIRECTORY"), new String[]
-            { "jvp", "jar" },
-            new String[]
-            { "Jalview Project", "Jalview Project (old)" },
+            Cache.getProperty("LAST_DIRECTORY"), suffix,
+            desc,
             "Jalview Project");
     chooser.setFileView(new JalviewFileView());
     chooser.setDialogTitle(MessageManager.getString("label.restore_state"));
@@ -1667,7 +1721,14 @@ public class Desktop extends jalview.jbgui.GDesktop
                   { choice }), choice.hashCode());
           try
           {
-            new Jalview2XML().loadJalviewAlign(choice);
+            if (asCastor)
+            {
+              new Jalview2XML().loadJalviewAlign(choice);
+            }
+            else
+            {
+              new jalview.project.Jalview2XML().loadJalviewAlign(choice);
+            }
           } catch (OutOfMemoryError oom)
           {
             new OOMWarning("Whilst loading project from " + choice, oom);
@@ -3297,6 +3358,21 @@ public class Desktop extends jalview.jbgui.GDesktop
     return groovyConsole;
   }
 
+  /**
+   * handles the payload of a drag and drop event.
+   * 
+   * TODO refactor to desktop utilities class
+   * 
+   * @param files
+   *          - Data source strings extracted from the drop event
+   * @param protocols
+   *          - protocol for each data source extracted from the drop event
+   * @param evt
+   *          - the drop event
+   * @param t
+   *          - the payload from the drop event
+   * @throws Exception
+   */
   public static void transferFromDropTarget(List<String> files,
           List<DataSourceType> protocols, DropTargetDropEvent evt,
           Transferable t) throws Exception
@@ -3370,85 +3446,112 @@ public class Desktop extends jalview.jbgui.GDesktop
         // fallback to text: workaround - on OSX where there's a JVM bug
         Cache.log.debug("standard URIListFlavor failed. Trying text");
         // try text fallback
-        data = (String) t.getTransferData(
-                new DataFlavor("text/plain;class=java.lang.String"));
-        if (Cache.log.isDebugEnabled())
+        DataFlavor textDf = new DataFlavor(
+                "text/plain;class=java.lang.String");
+        if (t.isDataFlavorSupported(textDf))
         {
-          Cache.log.debug("Plain text drop content returned " + data);
+          data = (String) t.getTransferData(textDf);
         }
+
+        Cache.log.debug("Plain text drop content returned "
+                + (data == null ? "Null - failed" : data));
+
       }
-      while (protocols.size() < files.size())
-      {
-        Cache.log.debug("Adding missing FILE protocol for "
-                + files.get(protocols.size()));
-        protocols.add(DataSourceType.FILE);
-      }
-      for (java.util.StringTokenizer st = new java.util.StringTokenizer(
-              data, "\r\n"); st.hasMoreTokens();)
+      if (data != null)
       {
-        added = true;
-        String s = st.nextToken();
-        if (s.startsWith("#"))
-        {
-          // the line is a comment (as per the RFC 2483)
-          continue;
-        }
-        java.net.URI uri = new java.net.URI(s);
-        if (uri.getScheme().toLowerCase().startsWith("http"))
-        {
-          protocols.add(DataSourceType.URL);
-          files.add(uri.toString());
-        }
-        else
+        while (protocols.size() < files.size())
         {
-          // otherwise preserve old behaviour: catch all for file objects
-          java.io.File file = new java.io.File(uri);
+          Cache.log.debug("Adding missing FILE protocol for "
+                  + files.get(protocols.size()));
           protocols.add(DataSourceType.FILE);
-          files.add(file.toString());
         }
-      }
-      if (Platform.isWindows())
-      {
-        Cache.log.debug("Scanning dropped content for Windows Link Files");
-
-         // resolve any .lnk files in the file drop
-        for (int f=0;f<files.size();f++)
+        for (java.util.StringTokenizer st = new java.util.StringTokenizer(
+                data, "\r\n"); st.hasMoreTokens();)
         {
-          if (protocols.get(f).equals(DataSourceType.FILE)) {
-              File lf = new File(files.get(f));
-              if (WindowsShortcut.isPotentialValidLink(lf)) {
-                // process link file to get a URL
-                Cache.log.debug("Found potential link file: "+lf);
-                WindowsShortcut wscfile = new WindowsShortcut(lf);
-                String fullname = wscfile.getRealFilename();
-                protocols.set(f,FormatAdapter.checkProtocol(fullname));
-                files.set(f,fullname);
-                Cache.log.debug("Parsed real filename "+fullname+" to extract protocol: "+protocols.get(f));
-            }
+          added = true;
+          String s = st.nextToken();
+          if (s.startsWith("#"))
+          {
+            // the line is a comment (as per the RFC 2483)
+            continue;
+          }
+          java.net.URI uri = new java.net.URI(s);
+          if (uri.getScheme().toLowerCase().startsWith("http"))
+          {
+            protocols.add(DataSourceType.URL);
+            files.add(uri.toString());
+          }
+          else
+          {
+            // otherwise preserve old behaviour: catch all for file objects
+            java.io.File file = new java.io.File(uri);
+            protocols.add(DataSourceType.FILE);
+            files.add(file.toString());
           }
         }
       }
-        
+
       if (Cache.log.isDebugEnabled())
       {
         if (data == null || !added)
         {
-          Cache.log.debug(
-                  "Couldn't resolve drop data. Here are the supported flavors:");
-          for (DataFlavor fl : t.getTransferDataFlavors())
+
+          if (t.getTransferDataFlavors() != null
+                  && t.getTransferDataFlavors().length > 0)
           {
             Cache.log.debug(
-                    "Supported transfer dataflavor: " + fl.toString());
-            Object df = t.getTransferData(fl);
-            if (df != null)
-            {
-              Cache.log.debug("Retrieves: " + df);
-            }
-            else
+                    "Couldn't resolve drop data. Here are the supported flavors:");
+            for (DataFlavor fl : t.getTransferDataFlavors())
             {
-              Cache.log.debug("Retrieved nothing");
+              Cache.log.debug(
+                      "Supported transfer dataflavor: " + fl.toString());
+              Object df = t.getTransferData(fl);
+              if (df != null)
+              {
+                Cache.log.debug("Retrieves: " + df);
+              }
+              else
+              {
+                Cache.log.debug("Retrieved nothing");
+              }
             }
           }
+          else
+          {
+            Cache.log.debug("Couldn't resolve dataflavor for drop: "
+                    + t.toString());
+          }
+        }
+      }
+    }
+    if (Platform.isWindows())
+
+    {
+      Cache.log.debug("Scanning dropped content for Windows Link Files");
+
+      // resolve any .lnk files in the file drop
+      for (int f = 0; f < files.size(); f++)
+      {
+        String source = files.get(f).toLowerCase();
+        if (protocols.get(f).equals(DataSourceType.FILE)
+                && (source.endsWith(".lnk") || source.endsWith(".url")
+                        || source.endsWith(".site")))
+        {
+          try {
+            File lf = new File(files.get(f));
+            // process link file to get a URL
+            Cache.log.debug("Found potential link file: " + lf);
+            WindowsShortcut wscfile = new WindowsShortcut(lf);
+            String fullname = wscfile.getRealFilename();
+            protocols.set(f, FormatAdapter.checkProtocol(fullname));
+            files.set(f, fullname);
+            Cache.log.debug("Parsed real filename " + fullname
+                    + " to extract protocol: " + protocols.get(f));
+          }
+          catch (Exception ex)
+          {
+            Cache.log.error("Couldn't parse "+files.get(f)+" as a link file.",ex);
+          }
         }
       }
     }