JAL-3048 JalviewJS compliant use of LineartOptions dialog
[jalview.git] / src / jalview / util / ImageMaker.java
index fcea21d..64771c4 100755 (executable)
  */
 package jalview.util;
 
+import jalview.bin.Cache;
 import jalview.bin.Jalview;
-import jalview.gui.EPSOptions;
 import jalview.gui.IProgressIndicator;
-import jalview.gui.SVGOptions;
+import jalview.gui.LineartOptions;
 import jalview.io.JalviewFileChooser;
+import jalview.util.dialogrunner.RunResponse;
 
 import java.awt.Component;
 import java.awt.Graphics;
@@ -33,8 +34,10 @@ import java.awt.RenderingHints;
 import java.awt.image.BufferedImage;
 import java.io.File;
 import java.io.FileOutputStream;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 import javax.imageio.ImageIO;
+import javax.swing.JOptionPane;
 
 import org.jfree.graphics2d.svg.SVGGraphics2D;
 import org.jfree.graphics2d.svg.SVGHints;
@@ -42,9 +45,23 @@ import org.jibble.epsgraphics.EpsGraphics2D;
 
 public class ImageMaker
 {
-  EpsGraphics2D pg;
+  public static final String SVG_DESCRIPTION = "Scalable Vector Graphics";
+
+  public static final String SVG_EXTENSION = "svg";
+
+  public static final String EPS_DESCRIPTION = "Encapsulated Postscript";
+
+  public static final String EPS_EXTENSION = "eps";
+
+  public static final String PNG_EXTENSION = "png";
 
-  SVGGraphics2D g2;
+  public static final String PNG_DESCRIPTION = "Portable  network graphics";
+
+  public static final String HTML_EXTENSION = "html";
+
+  public static final String HTML_DESCRIPTION = "Hypertext Markup Language";
+
+  EpsGraphics2D pg;
 
   Graphics graphics;
 
@@ -62,21 +79,26 @@ public class ImageMaker
 
   public enum TYPE
   {
-    EPS("EPS", MessageManager.getString("label.eps_file"), getEPSChooser()), PNG(
-            "PNG", MessageManager.getString("label.png_image"),
-            getPNGChooser()), SVG("SVG", "SVG", getSVGChooser());
+    EPS("EPS", MessageManager.getString("label.eps_file"), EPS_EXTENSION,
+            EPS_DESCRIPTION),
+    PNG("PNG", MessageManager.getString("label.png_image"), PNG_EXTENSION,
+            PNG_DESCRIPTION),
+    SVG("SVG", "SVG", SVG_EXTENSION, SVG_DESCRIPTION);
 
-    private JalviewFileChooser chooser;
+    public final String name;
 
-    private String name;
+    public final String label;
 
-    private String label;
+    public final String extension;
 
-    TYPE(String name, String label, JalviewFileChooser chooser)
+    public final String description;
+
+    TYPE(String name, String label, String ext, String desc)
     {
       this.name = name;
       this.label = label;
-      this.chooser = chooser;
+      this.extension = ext;
+      this.description = desc;
     }
 
     public String getName()
@@ -84,9 +106,9 @@ public class ImageMaker
       return name;
     }
 
-    public JalviewFileChooser getChooser()
+    public JalviewFileChooser getFileChooser()
     {
-      return chooser;
+      return new JalviewFileChooser(extension, description);
     }
 
     public String getLabel()
@@ -96,6 +118,21 @@ public class ImageMaker
 
   }
 
+  /**
+   * Constructor builds the image and writes it to file. If the supplied file
+   * name is null, the user is prompted for the output file.
+   * 
+   * @param parent
+   * @param type
+   * @param title
+   * @param width
+   * @param height
+   * @param file
+   * @param fileTitle
+   * @param pIndicator
+   * @param pSessionId
+   * @param headless
+   */
   public ImageMaker(Component parent, TYPE type, String title, int width,
           int height, File file, String fileTitle,
           IProgressIndicator pIndicator, long pSessionId, boolean headless)
@@ -104,21 +141,20 @@ public class ImageMaker
     this.type = type;
     this.pSessionId = pSessionId;
     this.headless = headless;
-    if (file == null)
+    if (file == null && !Jalview.isHeadlessMode())
     {
       setProgressMessage(MessageManager.formatMessage(
               "status.waiting_for_user_to_select_output_file", type.name));
-      JalviewFileChooser chooser;
-      chooser = type.getChooser();
+      JalviewFileChooser chooser = type.getFileChooser();
       chooser.setFileView(new jalview.io.JalviewFileView());
       chooser.setDialogTitle(title);
       chooser.setToolTipText(MessageManager.getString("action.save"));
       int value = chooser.showSaveDialog(parent);
 
-      if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
+      if (value == JalviewFileChooser.APPROVE_OPTION)
       {
-        jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
-                .getSelectedFile().getParent());
+        Cache.setProperty("LAST_DIRECTORY",
+                chooser.getSelectedFile().getParent());
         file = chooser.getSelectedFile();
       }
       else
@@ -153,8 +189,8 @@ public class ImageMaker
       {
         System.out.println("Error creating " + type.getName() + " file.");
 
-        setProgressMessage(MessageManager.formatMessage(
-                "info.error_creating_file", type.getName()));
+        setProgressMessage(MessageManager
+                .formatMessage("info.error_creating_file", type.getName()));
       }
     }
   }
@@ -164,6 +200,11 @@ public class ImageMaker
     return graphics;
   }
 
+  /**
+   * For SVG or PNG, writes the generated graphics data to the file output
+   * stream. For EPS, flushes the output graphics (which is written to file as
+   * it is generated).
+   */
   public void writeImage()
   {
     try
@@ -181,7 +222,7 @@ public class ImageMaker
         out.close();
         break;
       case PNG:
-        ImageIO.write(bi, "png", out);
+        ImageIO.write(bi, PNG_EXTENSION, out);
         out.flush();
         out.close();
         break;
@@ -192,52 +233,71 @@ public class ImageMaker
     }
   }
 
+  /**
+   * Generates an EPS image and writes it to the (previously set) output buffer.
+   * The user is first prompted for choice of Text or Lineart rendering, unless
+   * a preference for this has been set.
+   * 
+   * @param width
+   * @param height
+   * @param title
+   */
   void setupEPS(int width, int height, String title)
   {
-    boolean accurateText = true;
-
-    String renderStyle = jalview.bin.Cache.getDefault("EPS_RENDERING",
+    String renderStyle = Cache.getDefault("EPS_RENDERING",
             "Prompt each time");
+    AtomicBoolean textOption = new AtomicBoolean(
+            !"Lineart".equals(renderStyle));
 
-    // If we need to prompt, and if the GUI is visible then
-    // Prompt for EPS rendering style
-    if (renderStyle.equalsIgnoreCase("Prompt each time")
-            && !(System.getProperty("java.awt.headless") != null && System
-                    .getProperty("java.awt.headless").equals("true")))
+    /*
+     * configure the action to run on OK in the dialog
+     */
+    RunResponse okAction = new RunResponse(JOptionPane.OK_OPTION)
     {
-      EPSOptions eps = new EPSOptions();
-      renderStyle = eps.getValue();
-
-      if (renderStyle == null || eps.cancelled)
+      @Override
+      public void run()
       {
-        setProgressMessage(MessageManager.formatMessage(
-                "status.cancelled_image_export_operation", "EPS"));
-        return;
+        writeEPS(width, height, title, textOption.get());
       }
-    }
+    };
 
-    if (renderStyle.equalsIgnoreCase("text"))
+    /*
+     * Prompt for character rendering style if preference is not set
+     */
+    if (renderStyle.equalsIgnoreCase("Prompt each time")
+            && !(System.getProperty("java.awt.headless") != null && System
+                    .getProperty("java.awt.headless").equals("true")))
     {
-      accurateText = false;
+      LineartOptions epsOption = new LineartOptions("EPS_RENDERING",
+              TYPE.EPS.getName(), textOption);
+      epsOption.setResponseAction(new RunResponse(JOptionPane.NO_OPTION)
+      {
+        @Override
+        public void run()
+        {
+          setProgressMessage(MessageManager.formatMessage(
+                  "status.cancelled_image_export_operation", "EPS"));
+        }
+      });
+      epsOption.setResponseAction(okAction);
+      epsOption.showDialog();
+      /* no code here - JalviewJS cannot execute it */
     }
-
-    try
-    {
-      pg = new EpsGraphics2D(title, out, 0, 0, width, height);
-      Graphics2D ig2 = pg;
-      ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
-              RenderingHints.VALUE_ANTIALIAS_ON);
-
-      pg.setAccurateTextMode(accurateText);
-
-      graphics = pg;
-      setProgressMessage(MessageManager.formatMessage(
-              "status.export_complete", type.getName()));
-    } catch (Exception ex)
+    else
     {
+      /*
+       * else (if preference set) just do the export action
+       */
+      writeEPS(width, height, title, textOption.get());
     }
   }
 
+  /**
+   * Sets up a graphics object for the PNG image to be written on
+   * 
+   * @param width
+   * @param height
+   */
   void setupPNG(int width, int height)
   {
     bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
@@ -245,79 +305,125 @@ public class ImageMaker
     Graphics2D ig2 = (Graphics2D) graphics;
     ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
             RenderingHints.VALUE_ANTIALIAS_ON);
-    setProgressMessage(MessageManager.formatMessage(
-            "status.export_complete", type.getName()));
-
+    setProgressMessage(MessageManager
+            .formatMessage("status.export_complete", type.getName()));
   }
 
+  /**
+   * Sets up a graphics object for the SVG image to be written on. The user is
+   * first prompted for choice of Text or Lineart rendering, unless a preference
+   * for this has been set.
+   * 
+   * @param width
+   * @param height
+   * @param title
+   */
   void setupSVG(int width, int height, String title)
   {
-
-    g2 = new SVGGraphics2D(width, height);
-    Graphics2D ig2 = g2;
-
-    String renderStyle = jalview.bin.Cache.getDefault("SVG_RENDERING",
+    String renderStyle = Cache.getDefault("SVG_RENDERING",
             "Prompt each time");
+    AtomicBoolean textOption = new AtomicBoolean(
+            !"Lineart".equals(renderStyle));
 
-    // If we need to prompt, and if the GUI is visible then
-    // Prompt for EPS rendering style
+    /*
+     * configure the action to run on OK in the dialog
+     */
+    RunResponse okAction = new RunResponse(JOptionPane.OK_OPTION)
+    {
+      @Override
+      public void run()
+      {
+        setupSVG(width, height, textOption.get());
+      }
+    };
+
+    /*
+     * Prompt for character rendering style if preference is not set
+     */
     if (renderStyle.equalsIgnoreCase("Prompt each time")
             && !(System.getProperty("java.awt.headless") != null && System
                     .getProperty("java.awt.headless").equals("true")))
     {
-      SVGOptions svgOption = new SVGOptions();
-      renderStyle = svgOption.getValue();
-
-      if (renderStyle == null || svgOption.cancelled)
+      LineartOptions svgOption = new LineartOptions("SVG_RENDERING",
+              TYPE.SVG.getName(), textOption);
+      svgOption.setResponseAction(new RunResponse(JOptionPane.NO_OPTION)
       {
-        setProgressMessage(MessageManager.formatMessage(
-                "status.cancelled_image_export_operation", "SVG"));
-        return;
-      }
+        @Override
+        public void run()
+        {
+          setProgressMessage(MessageManager.formatMessage(
+                  "status.cancelled_image_export_operation", "SVG"));
+        }
+      });
+      svgOption.setResponseAction(okAction);
+      svgOption.showDialog();
+      /* no code here - JalviewJS cannot execute it */
     }
-
-    if (renderStyle.equalsIgnoreCase("Lineart"))
+    else
     {
-      ig2.setRenderingHint(SVGHints.KEY_DRAW_STRING_TYPE,
-              SVGHints.VALUE_DRAW_STRING_TYPE_VECTOR);
+      /*
+       * else (if preference set) just do the export action
+       */
+      setupSVG(width, height, textOption.get());
     }
-
-    setProgressMessage(MessageManager.formatMessage(
-            "status.export_complete", type.getName()));
-    graphics = g2;
   }
 
-  static JalviewFileChooser getPNGChooser()
+  void setProgressMessage(String message)
   {
-    if (Jalview.isHeadlessMode())
+    if (pIndicator != null && !headless)
     {
-      return null;
+      pIndicator.setProgressBar(message, pSessionId);
     }
-    return new jalview.io.JalviewFileChooser(
-            jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
-            new String[] { "png" },
-            new String[] { "Portable network graphics" },
-            "Portable network graphics");
   }
 
-  static JalviewFileChooser getEPSChooser()
+  /**
+   * A helper method to configure the SVG output graphics, with choice of Text
+   * or Lineart character rendering
+   * 
+   * @param width
+   * @param height
+   * @param textOption
+   *          true for Text, false for Lineart
+   */
+  protected void setupSVG(int width, int height, boolean textOption)
   {
-    if (Jalview.isHeadlessMode())
+    SVGGraphics2D g2 = new SVGGraphics2D(width, height);
+    if (!textOption) // Lineart selected
     {
-      return null;
+      g2.setRenderingHint(SVGHints.KEY_DRAW_STRING_TYPE,
+              SVGHints.VALUE_DRAW_STRING_TYPE_VECTOR);
     }
-    return new jalview.io.JalviewFileChooser(
-            jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
-            new String[] { "eps" },
-            new String[] { "Encapsulated Postscript" },
-            "Encapsulated Postscript");
+    setProgressMessage(MessageManager
+            .formatMessage("status.export_complete", type.getName()));
+    graphics = g2;
   }
 
-  private void setProgressMessage(String message)
+  /**
+   * A helper method that sets up the EPS graphics output with user choice of
+   * Text or Lineart character rendering
+   * 
+   * @param width
+   * @param height
+   * @param title
+   * @param textOption
+   *          true for Text, false for Lineart
+   */
+  protected void writeEPS(int width, int height, String title,
+          boolean textOption)
   {
-    if (pIndicator != null && !headless)
+    try
     {
-      pIndicator.setProgressBar(message, pSessionId);
+      pg = new EpsGraphics2D(title, out, 0, 0, width, height);
+      Graphics2D ig2 = pg;
+      ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+              RenderingHints.VALUE_ANTIALIAS_ON);
+      pg.setAccurateTextMode(!textOption); // true = Lineart
+      graphics = pg;
+      setProgressMessage(MessageManager
+              .formatMessage("status.export_complete", type.getName()));
+    } catch (Exception ex)
+    {
+      System.err.println("Error writing PNG: " + ex.toString());
     }
   }
 
@@ -327,10 +433,6 @@ public class ImageMaker
     {
       return null;
     }
-    return new jalview.io.JalviewFileChooser(
-            jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
-            new String[] { "svg" },
-            new String[] { "Scalable Vector Graphics" },
-            "Scalable Vector Graphics");
+    return new JalviewFileChooser(SVG_EXTENSION, SVG_DESCRIPTION);
   }
 }