Merge remote-tracking branch 'origin/Jalview-BH/JAL-3048_dialogs' into Jalview-BH...
authorhansonr <hansonr@stolaf.edu>
Tue, 3 Jul 2018 09:19:08 +0000 (10:19 +0100)
committerhansonr <hansonr@stolaf.edu>
Tue, 3 Jul 2018 09:19:08 +0000 (10:19 +0100)
1  2 
src/jalview/gui/AlignFrame.java
src/jalview/gui/Desktop.java

@@@ -88,6 -88,7 +88,7 @@@ import jalview.schemes.ColourSchemes
  import jalview.schemes.ResidueColourScheme;
  import jalview.schemes.TCoffeeColourScheme;
  import jalview.util.MessageManager;
+ import jalview.util.dialogrunner.RunResponse;
  import jalview.viewmodel.AlignmentViewport;
  import jalview.viewmodel.ViewportRanges;
  import jalview.ws.DBRefFetcher;
@@@ -181,8 -182,6 +182,8 @@@ public class AlignFrame extends GAlignF
     */
    String fileName = null;
  
 +  File fileObject;
 +
    /**
     * Creates a new AlignFrame object with specific width and height.
     * 
      Desktop.getDesktop().propertyChange(evt);
    }
  
 +  
 +  /**
 +   *  BH 2018
 +   *   
 +   * @return true if we have any features
 +   */
 +  @Override
 +  protected boolean haveAlignmentFeatures() { 
 +    AlignmentI alignment = getViewport().getAlignment();
 +
 +    for (int i = 0; i < alignment.getHeight(); i++)
 +    {
 +      SequenceI seq = alignment.getSequenceAt(i);
 +      for (String group : seq.getFeatures().getFeatureGroups(true))
 +      {
 +        if (group != null)return true;
 +      }
 +    }
 +    return  false; 
 +  }
 +  
    /**
     * initalise the alignframe from the underlying viewport data and the
     * configurations
      setFileFormat(format);
      reload.setEnabled(true);
    }
 +  
 +  /**
 +   * JavaScript will have this, maybe others. More dependable than a file name
 +   * and maintains a reference to the actual bytes loaded.
 +   * 
 +   * @param file
 +   */
 +  public void setFileObject(File file) {
 +    this.fileObject = file;
 +  }
  
    /**
     * Add a KeyListener with handlers for various KeyPressed and KeyReleased
  
          FileLoader loader = new FileLoader();
          DataSourceType protocol = fileName.startsWith("http:")
 -                ? DataSourceType.URL
 -                : DataSourceType.FILE;
 +                ? DataSourceType.URL : DataSourceType.FILE;
          loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
        }
        else
          Rectangle bounds = this.getBounds();
  
          FileLoader loader = new FileLoader();
 -        DataSourceType protocol = fileName.startsWith("http:")
 -                ? DataSourceType.URL
 -                : DataSourceType.FILE;
 -        AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
 -                protocol, currentFileFormat);
 +
 +        AlignFrame newframe = null;
 +
 +        if (fileObject == null)
 +        {
 +
 +          DataSourceType protocol = (fileName.startsWith("http:")
 +                  ? DataSourceType.URL : DataSourceType.FILE);
 +          newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
 +                  currentFileFormat);
 +        }
 +        else
 +        {
 +          newframe = loader.LoadFileWaitTillLoaded(fileObject, DataSourceType.FILE, currentFileFormat);
 +        }
  
          newframe.setBounds(bounds);
          if (featureSettings != null && featureSettings.isShowing())
    @Override
    public void saveAs_actionPerformed(ActionEvent e)
    {
-     // TODO: JAL-3048 JalviewFileChooser - Save option
      String format = currentFileFormat == null ? null
              : currentFileFormat.getName();
-     JalviewFileChooser chooser = JalviewFileChooser
+     final JalviewFileChooser chooser = JalviewFileChooser
              .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
+     final AlignFrame us = this;
      chooser.setFileView(new JalviewFileView());
      chooser.setDialogTitle(
              MessageManager.getString("label.save_alignment_to_file"));
      chooser.setToolTipText(MessageManager.getString("action.save"));
  
-     int value = chooser.showSaveDialog(this);
-     if (value == JalviewFileChooser.APPROVE_OPTION)
+     chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION)
      {
-       currentFileFormat = chooser.getSelectedFormat();
-       while (currentFileFormat == null)
-       {
-         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
-                 MessageManager.getString(
-                         "label.select_file_format_before_saving"),
-                 MessageManager.getString("label.file_format_not_specified"),
-                 JvOptionPane.WARNING_MESSAGE);
+       @Override
+       public void run()
+         {
          currentFileFormat = chooser.getSelectedFormat();
-         value = chooser.showSaveDialog(this);
-         if (value != JalviewFileChooser.APPROVE_OPTION)
+         while (currentFileFormat == null)
          {
-           return;
+           JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+                   MessageManager.getString(
+                           "label.select_file_format_before_saving"),
+                   MessageManager
+                           .getString("label.file_format_not_specified"),
+                   JvOptionPane.WARNING_MESSAGE);
+           currentFileFormat = chooser.getSelectedFormat();
+           chooser.showSaveDialog(us);
          }
-       }
  
-       fileName = chooser.getSelectedFile().getPath();
+         fileName = chooser.getSelectedFile().getPath();
  
-       Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
+         Cache.setProperty("DEFAULT_FILE_FORMAT",
+                 currentFileFormat.getName());
  
-       Cache.setProperty("LAST_DIRECTORY", fileName);
-       saveAlignment(fileName, currentFileFormat);
-     }
+         Cache.setProperty("LAST_DIRECTORY", fileName);
+         saveAlignment(fileName, currentFileFormat);
+       }
+     }).showSaveDialog(this);
    }
  
    public boolean saveAlignment(String file, FileFormatI format)
    @Override
    protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
    {
-     // TODO: JAL-3048 JalviewFileChooser
      // Pick the tree file
      JalviewFileChooser chooser = new JalviewFileChooser(
              jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
      chooser.setToolTipText(
              MessageManager.getString("label.load_tree_file"));
  
-     int value = chooser.showOpenDialog(null);
-     if (value == JalviewFileChooser.APPROVE_OPTION)
-     {
-       String filePath = chooser.getSelectedFile().getPath();
-       Cache.setProperty("LAST_DIRECTORY", filePath);
-       NewickFile fin = null;
-       try
-       {
-         fin = new NewickFile(filePath, DataSourceType.FILE);
-         viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
-       } catch (Exception ex)
-       {
-         JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
-                 MessageManager.getString("label.problem_reading_tree_file"),
-                 JvOptionPane.WARNING_MESSAGE);
-         ex.printStackTrace();
-       }
-       if (fin != null && fin.hasWarningMessage())
-       {
-         JvOptionPane.showMessageDialog(Desktop.desktop,
-                 fin.getWarningMessage(),
-                 MessageManager
-                         .getString("label.possible_problem_with_tree_file"),
-                 JvOptionPane.WARNING_MESSAGE);
-       }
-     }
+     chooser.response(
+             new jalview.util.dialogrunner.RunResponse(JalviewFileChooser.APPROVE_OPTION)
+             {
+               @Override
+               public void run()
+               {
+                 String filePath = chooser.getSelectedFile().getPath();
+                 Cache.setProperty("LAST_DIRECTORY", filePath);
+                 NewickFile fin = null;
+                 try
+                 {
+                   fin = new NewickFile(new FileParse(
+                           chooser.getSelectedFile(), DataSourceType.FILE));
+                   viewport.setCurrentTree(
+                           showNewickTree(fin, filePath).getTree());
+                 } catch (Exception ex)
+                 {
+                   JvOptionPane.showMessageDialog(Desktop.desktop,
+                           ex.getMessage(),
+                           MessageManager.getString(
+                                   "label.problem_reading_tree_file"),
+                           JvOptionPane.WARNING_MESSAGE);
+                   ex.printStackTrace();
+                 }
+                 if (fin != null && fin.hasWarningMessage())
+                 {
+                   JvOptionPane.showMessageDialog(Desktop.desktop,
+                           fin.getWarningMessage(),
+                           MessageManager.getString(
+                                   "label.possible_problem_with_tree_file"),
+                           JvOptionPane.WARNING_MESSAGE);
+                 }
+               }
+             }).openDialog(this);
    }
  
    public TreePanel showNewickTree(NewickFile nf, String treeTitle)
    @Override
    protected void loadVcf_actionPerformed()
    {
-     // TODO: JAL-3048 - No VCF support in JsJalview
      JalviewFileChooser chooser = new JalviewFileChooser(
              Cache.getProperty("LAST_DIRECTORY"));
      chooser.setFileView(new JalviewFileView());
      chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
      chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
+     final AlignFrame us = this;
+     chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION)
+     {
+       @Override
+       public void run()
+       {
  
-     int value = chooser.showOpenDialog(null);
+         {
+           String choice = chooser.getSelectedFile().getPath();
+           Cache.setProperty("LAST_DIRECTORY", choice);
+           SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
+           new VCFLoader(choice).loadVCF(seqs, us);
+         }
  
-     if (value == JalviewFileChooser.APPROVE_OPTION)
-     {
-       String choice = chooser.getSelectedFile().getPath();
-       Cache.setProperty("LAST_DIRECTORY", choice);
-       SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
-       new VCFLoader(choice).loadVCF(seqs, this);
-     }
+       };
+     }).openDialog(null);
  
    }
  
@@@ -44,6 -44,7 +44,7 @@@ import jalview.util.ImageMaker
  import jalview.util.MessageManager;
  import jalview.util.Platform;
  import jalview.util.UrlConstants;
+ import jalview.util.dialogrunner.RunResponse;
  import jalview.viewmodel.AlignmentViewport;
  import jalview.ws.params.ParamManager;
  import jalview.ws.utils.UrlDownloadClient;
@@@ -105,7 -106,6 +106,6 @@@ import javax.swing.JCheckBox
  import javax.swing.JComboBox;
  import javax.swing.JComponent;
  import javax.swing.JDesktopPane;
- import javax.swing.JFileChooser;
  import javax.swing.JFrame;
  import javax.swing.JInternalFrame;
  import javax.swing.JLabel;
@@@ -344,9 -344,8 +344,8 @@@ public class Desktop extends jalview.jb
    public Desktop()
    {
      /**
-      * A note to implementors. It is ESSENTIAL that any activities that might
-      * block are spawned off as threads rather than waited for during this
-      * constructor.
+      * A note to implementors. It is ESSENTIAL that any activities that might block
+      * are spawned off as threads rather than waited for during this constructor.
       */
      instance = this;
      doVamsasClientCheck();
  
      // This line prevents Windows Look&Feel resizing all new windows to maximum
      // if previous window was maximised
-     desktop.setDesktopManager(
-             new MyDesktopManager(
-                     (Platform.isWindows() ? new DefaultDesktopManager()
-                             : Platform.isAMac()
-                                     ? new AquaInternalFrameManager(
-                                             desktop.getDesktopManager())
-                                     : desktop.getDesktopManager())));
+     desktop.setDesktopManager(new MyDesktopManager(
+             (Platform.isWindows() ? new DefaultDesktopManager()
+                     : Platform.isAMac()
+                             ? new AquaInternalFrameManager(
+                                     desktop.getDesktopManager())
+                             : desktop.getDesktopManager())));
  
      Rectangle dims = getLastKnownDimensions("");
      if (dims != null)
       * @j2sNative
       */
      {
-     final Desktop me = this;
-     // Thread off the news reader, in case there are connection problems.
-     addDialogThread(new Runnable()
-     {
+       final Desktop me = this;
+       // Thread off the news reader, in case there are connection problems.
+       addDialogThread(new Runnable()
+       {
          @Override
          public void run()
          {
            showNews.setVisible(true);
            Cache.log.debug("Completed news thread.");
          }
-     });
+       });
      }
    }
  
    }
  
    /**
-    * Add key bindings to a JInternalFrame so that Ctrl-W and Cmd-W will close
-    * the window
+    * Add key bindings to a JInternalFrame so that Ctrl-W and Cmd-W will close the
+    * window
     * 
     * @param frame
     */
    public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
    {
      String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
 -    final JalviewFileChooser chooser = JalviewFileChooser
 +    JalviewFileChooser chooser = JalviewFileChooser
              .forRead(Cache.getProperty("LAST_DIRECTORY"), fileFormat);
  
      chooser.setFileView(new JalviewFileView());
              MessageManager.getString("label.open_local_file"));
      chooser.setToolTipText(MessageManager.getString("action.open"));
  
-     chooser.setCallback(new Runnable()
+     chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION)
      {
  
        @Override
          new FileLoader().LoadFile(viewport, selectedFile,
                  DataSourceType.FILE, format);
        }
-     });
-     int value = chooser.showOpenDialog(this);
-     if (value == JFileChooser.APPROVE_OPTION)
-     {
-       chooser.getCallback().run();
-     }
+     }).openDialog(this);
    }
  
    /**
  
      String dialogOption = "label.input_alignment_from_url";
      desktop.dialogData = new Object[] { dialogOption, viewport, history };
-     desktop.onDialogReturn(
-             JvOptionPane.showInternalConfirmDialog(desktop, panel,
-             MessageManager.getString(dialogOption),
+     desktop.onDialogReturn(JvOptionPane.showInternalConfirmDialog(desktop,
+             panel, MessageManager.getString(dialogOption),
              JvOptionPane.OK_CANCEL_OPTION));
  
      // no code may follow this, as SwingJS will not block
  
    }
  
    /**
     * Opens the CutAndPaste window for the user to paste an alignment in to
     * 
  
    /**
     * 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.
+    * 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
     */
  
    /**
     * Proxy class for JDesktopPane which optionally displays the current memory
-    * usage and highlights the desktop area with a red bar if free memory runs
-    * low.
+    * usage and highlights the desktop area with a red bar if free memory runs low.
     * 
     * @author AMW
     */
              JvOptionPane.showInternalMessageDialog(Desktop.desktop,
                      MessageManager.formatMessage("label.couldnt_locate",
                              new Object[]
-                     { url }),
+                             { url }),
                      MessageManager.getString("label.url_not_found"),
                      JvOptionPane.WARNING_MESSAGE);
  
      }
    }
  
    /**
     * Accessor method to quickly get all the AlignmentFrames loaded.
     * 
    }
  
    /**
-    * Bind Ctrl/Cmd-Q to Quit - for reset as Groovy Console takes over this
-    * binding when opened
+    * Bind Ctrl/Cmd-Q to Quit - for reset as Groovy Console takes over this binding
+    * when opened
     */
    protected void addQuitHandler()
    {
    }
  
    /**
-    * 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.
+    * 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
     * @return alignFrame for viewport
  
    /**
     * Explode the views in the given SplitFrame into separate SplitFrame windows.
-    * This respects (remembers) any previous 'exploded geometry' i.e. the size
-    * and location last time the view was expanded (if any). However it does not
+    * This respects (remembers) any previous 'exploded geometry' i.e. the size and
+    * location last time the view was expanded (if any). However it does not
     * remember the split pane divider location - this is set to match the
     * 'exploding' frame.
     * 
            List<DataSourceType> protocols, DropTargetDropEvent evt,
            Transferable t) throws Exception
    {
-     
      // BH 2018 changed List<String> to List<Object> to allow for File from SwingJS
  
- //    DataFlavor[] flavors = t.getTransferDataFlavors();
- //    for (int i = 0; i < flavors.length; i++) {
- //      if (flavors[i].isFlavorJavaFileListType()) {
- //              evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
- //              List<File> list = (List<File>) t.getTransferData(flavors[i]);
- //              for (int j = 0; j < list.size(); j++) {
- //                      File file = (File) list.get(j);
- //                      byte[] data = getDroppedFileBytes(file);
- //                      fileName.setText(file.getName() + " - " + data.length + " " + evt.getLocation());
- //                      JTextArea target = (JTextArea) ((DropTarget) evt.getSource()).getComponent();
- //                      target.setText(new String(data));
- //              }
- //              dtde.dropComplete(true);
- //              return;
- //      }
- //
+     // DataFlavor[] flavors = t.getTransferDataFlavors();
+     // for (int i = 0; i < flavors.length; i++) {
+     // if (flavors[i].isFlavorJavaFileListType()) {
+     // evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
+     // List<File> list = (List<File>) t.getTransferData(flavors[i]);
+     // for (int j = 0; j < list.size(); j++) {
+     // File file = (File) list.get(j);
+     // byte[] data = getDroppedFileBytes(file);
+     // fileName.setText(file.getName() + " - " + data.length + " " +
+     // evt.getLocation());
+     // JTextArea target = (JTextArea) ((DropTarget) evt.getSource()).getComponent();
+     // target.setText(new String(data));
+     // }
+     // dtde.dropComplete(true);
+     // return;
+     // }
+     //
  
      DataFlavor uriListFlavor = new DataFlavor(
              "text/uri-list;class=java.lang.String"), urlFlavour = null;
  
        try
        {
-       java.net.URL url = (URL) t.getTransferData(urlFlavour);
+         java.net.URL url = (URL) t.getTransferData(urlFlavour);
          // nb: java 8 osx bug https://bugs.openjdk.java.net/browse/JDK-8156099
          // means url may be null.
-       if (url != null)
-       {
-         protocols.add(DataSourceType.URL);
-         files.add(url.toString());
-         Cache.log.debug("Drop handled as URL dataflavor "
-                 + files.get(files.size() - 1));
+         if (url != null)
+         {
+           protocols.add(DataSourceType.URL);
+           files.add(url.toString());
+           Cache.log.debug("Drop handled as URL dataflavor "
+                   + files.get(files.size() - 1));
            return;
          }
          else
                      "Please ignore plist error - occurs due to problem with java 8 on OSX");
            }
            ;
-       }
+         }
        } catch (Throwable ex)
        {
          Cache.log.debug("URL drop handler failed.", ex);
                  && (source.endsWith(".lnk") || source.endsWith(".url")
                          || source.endsWith(".site")))
          {
-           try {
+           try
+           {
              Object obj = files.get(f);
-             File lf = (obj instanceof File ? (File) obj : new File((String) obj));
+             File lf = (obj instanceof File ? (File) obj
+                     : new File((String) obj));
              // process link file to get a URL
              Cache.log.debug("Found potential link file: " + lf);
              WindowsShortcut wscfile = new WindowsShortcut(lf);
              files.set(f, fullname);
              Cache.log.debug("Parsed real filename " + fullname
                      + " to extract protocol: " + protocols.get(f));
-           }
-           catch (Exception ex)
+           } catch (Exception ex)
            {
-             Cache.log.error("Couldn't parse "+files.get(f)+" as a link file.",ex);
+             Cache.log.error(
+                     "Couldn't parse " + files.get(f) + " as a link file.",
+                     ex);
            }
          }
        }
    }
  
    /**
-    * Answers a (possibly empty) list of any structure viewer frames (currently
-    * for either Jmol or Chimera) which are currently open. This may optionally
-    * be restricted to viewers of a specified class, or viewers linked to a
-    * specified alignment panel.
+    * Answers a (possibly empty) list of any structure viewer frames (currently for
+    * either Jmol or Chimera) which are currently open. This may optionally be
+    * restricted to viewers of a specified class, or viewers linked to a specified
+    * alignment panel.
     * 
     * @param apanel
     *          if not null, only return viewers linked to this panel