JAL-629 Much better way of dealing with list of filenames/URLs without an --open...
[jalview.git] / src / jalview / gui / AlignFrame.java
index 06298ba..eb98d98 100644 (file)
@@ -49,6 +49,7 @@ import java.beans.PropertyChangeEvent;
 import java.io.File;
 import java.io.FileWriter;
 import java.io.IOException;
+import java.io.OutputStreamWriter;
 import java.io.PrintWriter;
 import java.net.URL;
 import java.util.ArrayList;
@@ -59,7 +60,6 @@ import java.util.Hashtable;
 import java.util.List;
 import java.util.Locale;
 import java.util.Vector;
-import java.util.concurrent.Callable;
 
 import javax.swing.ButtonGroup;
 import javax.swing.JCheckBoxMenuItem;
@@ -112,6 +112,7 @@ import jalview.datamodel.AlignmentI;
 import jalview.datamodel.AlignmentOrder;
 import jalview.datamodel.AlignmentView;
 import jalview.datamodel.ColumnSelection;
+import jalview.datamodel.ContactMatrixI;
 import jalview.datamodel.HiddenColumns;
 import jalview.datamodel.PDBEntry;
 import jalview.datamodel.SeqCigar;
@@ -140,6 +141,7 @@ import jalview.io.JnetAnnotationMaker;
 import jalview.io.NewickFile;
 import jalview.io.ScoreMatrixFile;
 import jalview.io.TCoffeeScoreFile;
+import jalview.io.exceptions.ImageOutputException;
 import jalview.io.vcf.VCFLoader;
 import jalview.jbgui.GAlignFrame;
 import jalview.project.Jalview2XML;
@@ -151,11 +153,11 @@ import jalview.util.HttpUtils;
 import jalview.util.ImageMaker.TYPE;
 import jalview.util.MessageManager;
 import jalview.util.Platform;
+import jalview.util.imagemaker.BitmapImageSizing;
 import jalview.viewmodel.AlignmentViewport;
 import jalview.viewmodel.ViewportRanges;
 import jalview.ws.DBRefFetcher;
 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
-import jalview.ws.datamodel.alphafold.PAEContactMatrix;
 import jalview.ws.jws1.Discoverer;
 import jalview.ws.jws2.Jws2Discoverer;
 import jalview.ws.jws2.jabaws2.Jws2Instance;
@@ -622,12 +624,12 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
         // if (viewport.cursorMode)
         // {
         // alignPanel.seqPanel.insertNucAtCursor(false,"A");
-        // //System.out.println("A");
+        // //jalview.bin.Console.outPrintln("A");
         // }
         // break;
         /*
          * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
-         * System.out.println("closing bracket"); } break;
+         * jalview.bin.Console.outPrintln("closing bracket"); } break;
          */
         case KeyEvent.VK_DELETE:
         case KeyEvent.VK_BACK_SPACE:
@@ -828,7 +830,8 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
               @Override
               public void propertyChange(PropertyChangeEvent evt)
               {
-                // // System.out.println("Discoverer property change.");
+                // // jalview.bin.Console.outPrintln("Discoverer property
+                // change.");
                 // if (evt.getPropertyName().equals("services"))
                 {
                   SwingUtilities.invokeLater(new Runnable()
@@ -837,7 +840,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
                     @Override
                     public void run()
                     {
-                      System.err.println(
+                      jalview.bin.Console.errPrintln(
                               "Rebuild WS Menu for service change");
                       BuildWebServiceMenu();
                     }
@@ -852,7 +855,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
       public void internalFrameClosed(
               javax.swing.event.InternalFrameEvent evt)
       {
-        // System.out.println("deregistering discoverer listener");
+        // jalview.bin.Console.outPrintln("deregistering discoverer listener");
         Desktop.instance.removeJalviewPropertyChangeListener("services",
                 thisListener);
         closeMenuItem_actionPerformed(true);
@@ -981,7 +984,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
   @Override
   public void setProgressBar(String message, long id)
   {
-    if (!Platform.isHeadless())
+    if (!Platform.isHeadless() && progressBar != null)
       progressBar.setProgressBar(message, id);
   }
 
@@ -989,7 +992,8 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
   public void registerHandler(final long id,
           final IProgressIndicatorHandler handler)
   {
-    progressBar.registerHandler(id, handler);
+    if (progressBar != null)
+      progressBar.registerHandler(id, handler);
   }
 
   /**
@@ -999,7 +1003,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
   @Override
   public boolean operationInProgress()
   {
-    return progressBar.operationInProgress();
+    return progressBar == null ? false : progressBar.operationInProgress();
   }
 
   /**
@@ -1248,8 +1252,16 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
    */
   public void saveAlignment(String file, FileFormatI format)
   {
+    saveAlignment(file, format, false);
+  }
+
+  public void saveAlignment(String file, FileFormatI format, boolean stdout)
+  {
     lastSaveSuccessful = true;
-    lastFilenameSaved = file;
+    if (!stdout)
+    {
+      lastFilenameSaved = file;
+    }
     lastFormatSaved = format;
 
     if (FileFormat.Jalview.equals(format))
@@ -1260,6 +1272,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
         shortName = shortName
                 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
       }
+      // TODO deal with stdout=true
       lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
               shortName);
 
@@ -1277,11 +1290,10 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     }
 
     AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
-    Callable<Void> cancelAction = () -> {
+    Runnable cancelAction = () -> {
       lastSaveSuccessful = false;
-      return null;
     };
-    Callable<Void> outputAction = () -> {
+    Runnable outputAction = () -> {
       // todo defer this to inside formatSequences (or later)
       AlignmentExportData exportData = viewport.getAlignExportData(options);
       String output = new FormatAdapter(alignPanel, options)
@@ -1296,7 +1308,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
       else
       {
         // create backupfiles object and get new temp filename destination
-        boolean doBackup = BackupFiles.getEnabled();
+        boolean doBackup = BackupFiles.getEnabled() && !stdout;
         BackupFiles backupfiles = null;
         if (doBackup)
         {
@@ -1308,7 +1320,9 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
           String tempFilePath = doBackup ? backupfiles.getTempFilePath()
                   : file;
           Console.trace("ALIGNFRAME setting PrintWriter");
-          PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
+          PrintWriter out = stdout
+                  ? new PrintWriter(new OutputStreamWriter(System.out))
+                  : new PrintWriter(new FileWriter(tempFilePath));
 
           if (backupfiles != null)
           {
@@ -1317,13 +1331,28 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
           }
 
           out.print(output);
-          Console.trace("ALIGNFRAME about to close file");
-          out.close();
-          Console.trace("ALIGNFRAME closed file");
-          AlignFrame.this.setTitle(file);
-          statusBar.setText(MessageManager.formatMessage(
-                  "label.successfully_saved_to_file_in_format", new Object[]
-                  { fileName, format.getName() }));
+          out.flush();
+          if (!stdout)
+          {
+            Console.trace("ALIGNFRAME about to close file");
+            out.close();
+            Console.trace("ALIGNFRAME closed file");
+          }
+          AlignFrame.this.setTitle(stdout ? "STDOUT" : file);
+          if (stdout)
+          {
+            statusBar.setText(MessageManager.formatMessage(
+                    "label.successfully_printed_to_stdout_in_format",
+                    new Object[]
+                    { format.getName() }));
+          }
+          else
+          {
+            statusBar.setText(MessageManager.formatMessage(
+                    "label.successfully_saved_to_file_in_format",
+                    new Object[]
+                    { fileName, format.getName() }));
+          }
           lastSaveSuccessful = true;
         } catch (IOException e)
         {
@@ -1359,7 +1388,6 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
           AlignFrame.this.getViewport().setSavedUpToDate(true);
         }
       }
-      return null;
     };
 
     /*
@@ -1377,7 +1405,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     {
       try
       {
-        outputAction.call();
+        outputAction.run();
       } catch (Exception e)
       {
         // TODO Auto-generated catch block
@@ -1399,7 +1427,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     FileFormatI fileFormat = FileFormats.getInstance()
             .forName(fileFormatName);
     AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
-    Callable<Void> outputAction = () -> {
+    Runnable outputAction = () -> {
       // todo defer this to inside formatSequences (or later)
       AlignmentExportData exportData = viewport.getAlignExportData(options);
       CutAndPasteTransfer cap = new CutAndPasteTransfer();
@@ -1421,7 +1449,6 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
                 oom);
         cap.dispose();
       }
-      return null;
     };
 
     /*
@@ -1438,7 +1465,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     {
       try
       {
-        outputAction.call();
+        outputAction.run();
       } catch (Exception e)
       {
         e.printStackTrace();
@@ -1456,19 +1483,75 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
   protected void htmlMenuItem_actionPerformed(ActionEvent e)
   {
     HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
-    htmlSVG.exportHTML(null);
+    try
+    {
+      htmlSVG.exportHTML(null);
+    } catch (ImageOutputException x)
+    {
+      // report problem to console and raise dialog
+    }
   }
 
   @Override
   public void bioJSMenuItem_actionPerformed(ActionEvent e)
   {
     BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
-    bjs.exportHTML(null);
+    try
+    {
+      bjs.exportHTML(null);
+    } catch (ImageOutputException x)
+    {
+      // report problem to console and raise dialog
+    }
   }
 
   public void createImageMap(File file, String image)
   {
-    alignPanel.makePNGImageMap(file, image);
+    try
+    {
+      alignPanel.makePNGImageMap(file, image);
+    } catch (ImageOutputException x)
+    {
+      // report problem to console and raise dialog
+    }
+  }
+
+  @Override
+  public void createPNG_actionPerformed(ActionEvent e)
+  {
+    try
+    {
+      createPNG(null);
+    } catch (ImageOutputException ioex)
+    {
+      // raise dialog, and report via console
+    }
+  }
+
+  @Override
+  public void createEPS_actionPerformed(ActionEvent e)
+  {
+    try
+    {
+      createEPS(null);
+    } catch (ImageOutputException ioex)
+    {
+      // raise dialog, and report via console
+    }
+
+  }
+
+  @Override
+  public void createSVG_actionPerformed(ActionEvent e)
+  {
+    try
+    {
+      createSVG(null);
+    } catch (ImageOutputException ioex)
+    {
+      // raise dialog, and report via console
+    }
+
   }
 
   /**
@@ -1477,10 +1560,15 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
    * 
    * @param f
    */
-  @Override
-  public void createPNG(File f)
+  public void createPNG(File f) throws ImageOutputException
+  {
+    createPNG(f, null, BitmapImageSizing.nullBitmapImageSizing());
+  }
+
+  public void createPNG(File f, String renderer, BitmapImageSizing userBis)
+          throws ImageOutputException
   {
-    alignPanel.makeAlignmentImage(TYPE.PNG, f);
+    alignPanel.makeAlignmentImage(TYPE.PNG, f, renderer, userBis);
   }
 
   /**
@@ -1489,10 +1577,14 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
    * 
    * @param f
    */
-  @Override
-  public void createEPS(File f)
+  public void createEPS(File f) throws ImageOutputException
+  {
+    createEPS(f, null);
+  }
+
+  public void createEPS(File f, String renderer) throws ImageOutputException
   {
-    alignPanel.makeAlignmentImage(TYPE.EPS, f);
+    alignPanel.makeAlignmentImage(TYPE.EPS, f, renderer);
   }
 
   /**
@@ -1501,10 +1593,14 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
    * 
    * @param f
    */
-  @Override
-  public void createSVG(File f)
+  public void createSVG(File f) throws ImageOutputException
+  {
+    createSVG(f, null);
+  }
+
+  public void createSVG(File f, String renderer) throws ImageOutputException
   {
-    alignPanel.makeAlignmentImage(TYPE.SVG, f);
+    alignPanel.makeAlignmentImage(TYPE.SVG, f, renderer);
   }
 
   @Override
@@ -1554,7 +1650,6 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
       String choice = chooser.getSelectedFile().getPath();
       Cache.setProperty("LAST_DIRECTORY", choice);
       loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
-      return null;
     });
 
     chooser.showOpenDialog(this);
@@ -2286,10 +2381,17 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
                         .intValue();
               }
             }
-            alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
-            // was
-            // duplicated
-            // earlier
+            // annotation was duplicated earlier
+            alignment.addAnnotation(sequences[i].getAnnotation()[a]);
+            // take care of contact matrix too
+            ContactMatrixI cm = sequences[i]
+                    .getContactMatrixFor(sequences[i].getAnnotation()[a]);
+            if (cm != null)
+            {
+              alignment.addContactListFor(sequences[i].getAnnotation()[a],
+                      cm);
+            }
+
             alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
                     a);
           }
@@ -2397,7 +2499,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     } catch (Exception ex)
     {
       ex.printStackTrace();
-      System.out.println("Exception whilst pasting: " + ex);
+      jalview.bin.Console.outPrintln("Exception whilst pasting: " + ex);
       // could be anything being pasted in here
     }
 
@@ -2445,7 +2547,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     } catch (Exception ex)
     {
       ex.printStackTrace();
-      System.out.println("Exception whilst pasting: " + ex);
+      jalview.bin.Console.outPrintln("Exception whilst pasting: " + ex);
       // could be anything being pasted in here
     } catch (OutOfMemoryError oom)
     {
@@ -2476,7 +2578,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
       return;
     }
 
-    Callable okAction = () -> {
+    Runnable okAction = () -> {
       SequenceI[] cut = sg.getSequences()
               .toArray(new SequenceI[sg.getSize()]);
 
@@ -2500,7 +2602,6 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
         {
         }
       }
-      return null;
     };
 
     /*
@@ -2526,7 +2627,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     {
       try
       {
-        okAction.call();
+        okAction.run();
       } catch (Exception e)
       {
         e.printStackTrace();
@@ -4118,7 +4219,6 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
                         .getString("label.possible_problem_with_tree_file"),
                 JvOptionPane.WARNING_MESSAGE);
       }
-      return null;
     });
     chooser.showOpenDialog(this);
   }
@@ -4184,8 +4284,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     return tp;
   }
 
-  public void showContactMapTree(AlignmentAnnotation aa,
-          PAEContactMatrix cm)
+  public void showContactMapTree(AlignmentAnnotation aa, ContactMatrixI cm)
   {
     int x = 4, y = 5;
     int w = 400, h = 500;
@@ -4194,8 +4293,10 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     {
       NewickFile fin = new NewickFile(
               new FileParse(cm.getNewick(), DataSourceType.PASTE));
-      String title = "PAE Matrix Tree for "
-              + cm.getReferenceSeq().getDisplayId(false);
+      String title = aa.label + " " + cm.getTreeMethod() + " tree"
+              + (aa.sequenceRef != null
+                      ? (" for " + aa.sequenceRef.getDisplayId(false))
+                      : "");
 
       showColumnWiseTree(fin, aa, title, w, h, x, y);
     } catch (Throwable xx)
@@ -4215,7 +4316,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
       {
         return null;
       }
-      TreePanel tp = new TreePanel(alignPanel, nf, aa, title);
+      TreePanel tp = new TreePanel(alignPanel, nf, aa, treeTitle);
 
       tp.setSize(w, h);
 
@@ -4224,7 +4325,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
         tp.setLocation(x, y);
       }
 
-      Desktop.addInternalFrame(tp, title, w, h);
+      Desktop.addInternalFrame(tp, treeTitle, w, h);
       return tp;
     } catch (Throwable xx)
     {
@@ -4246,7 +4347,8 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     {
       try
       {
-        System.err.println("Waiting for building menu to finish.");
+        jalview.bin.Console
+                .errPrintln("Waiting for building menu to finish.");
         Thread.sleep(10);
       } catch (Exception e)
       {
@@ -4262,7 +4364,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
         final List<JMenuItem> legacyItems = new ArrayList<>();
         try
         {
-          // System.err.println("Building ws menu again "
+          // jalview.bin.Console.errPrintln("Building ws menu again "
           // + Thread.currentThread());
           // TODO: add support for context dependent disabling of services based
           // on
@@ -4800,7 +4902,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
                                     Desktop.instance);
                     if (pe != null)
                     {
-                      System.err.println("Associated file : "
+                      jalview.bin.Console.errPrintln("Associated file : "
                               + (fm[0].toString()) + " with "
                               + toassoc.getDisplayId(true));
                       assocfiles++;
@@ -5698,7 +5800,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
    *          update non-sequence-related annotations
    */
   @Override
-  protected void setAnnotationsVisibility(boolean visible,
+  public void setAnnotationsVisibility(boolean visible,
           boolean forSequences, boolean forAlignment)
   {
     AlignmentAnnotation[] anns = alignPanel.getAlignment()
@@ -5833,7 +5935,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
               viewport.getAlignment()));
     } catch (Exception ex)
     {
-      System.err.println(ex.getMessage());
+      jalview.bin.Console.errPrintln(ex.getMessage());
       return;
     }
   }
@@ -5855,7 +5957,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
         console.runScript();
       } catch (Exception ex)
       {
-        System.err.println((ex.toString()));
+        jalview.bin.Console.errPrintln((ex.toString()));
         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
                 MessageManager.getString("label.couldnt_run_groovy_script"),
                 MessageManager.getString("label.groovy_support_failed"),
@@ -5864,7 +5966,8 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     }
     else
     {
-      System.err.println("Can't run Groovy script as console not found");
+      jalview.bin.Console
+              .errPrintln("Can't run Groovy script as console not found");
     }
   }
 
@@ -5964,7 +6067,6 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
       Cache.setProperty("LAST_DIRECTORY", choice);
       SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
       new VCFLoader(choice).loadVCF(seqs, us);
-      return null;
     });
     chooser.showOpenDialog(null);