JAL-3438 spotless for 2.11.2.0
[jalview.git] / src / jalview / gui / ImageExporter.java
1 package jalview.gui;
2
3 import jalview.bin.Cache;
4 import jalview.bin.Jalview;
5 import jalview.io.JalviewFileChooser;
6 import jalview.io.JalviewFileView;
7 import jalview.util.ImageMaker;
8 import jalview.util.ImageMaker.TYPE;
9 import jalview.util.MessageManager;
10 import jalview.util.Platform;
11
12 import java.awt.Component;
13 import java.awt.Graphics;
14 import java.io.File;
15 import java.util.concurrent.atomic.AtomicBoolean;
16
17 /**
18  * A class that marshals steps in exporting a view in image graphics format
19  * <ul>
20  * <li>prompts the user for the output file, if not already specified</li>
21  * <li>prompts the user for Text or Lineart character rendering, if
22  * necessary</li>
23  * <li>instantiates an ImageMaker to create the appropriate Graphics output
24  * context for the image format</li>
25  * <li>invokes a callback to do the work of writing to the graphics</li>
26  * </ul>
27  * 
28  * @author gmcarstairs
29  *
30  */
31 public class ImageExporter
32 {
33   // todo move interface to jalview.api? or replace with lambda?
34   /**
35    * An interface for the callback that can be run to write the image on to the
36    * graphics object. The callback should throw any exceptions arising so they
37    * can be reported by this class.
38    */
39   public interface ImageWriterI
40   {
41     void exportImage(Graphics g) throws Exception;
42   }
43
44   private IProgressIndicator messageBoard;
45
46   private ImageWriterI imageWriter;
47
48   TYPE imageType;
49
50   private String title;
51
52   /**
53    * Constructor given a callback handler to write graphics data, an (optional)
54    * target for status messages, image type and (optional) title for output file
55    * 
56    * @param writer
57    * @param statusBar
58    * @param type
59    * @param fileTitle
60    */
61   public ImageExporter(ImageWriterI writer, IProgressIndicator statusBar,
62           TYPE type, String fileTitle)
63   {
64     this.imageWriter = writer;
65     this.messageBoard = statusBar;
66     this.imageType = type;
67     this.title = fileTitle;
68   }
69
70   /**
71    * Prompts the user for output file and Text/Lineart options as required,
72    * configures a Graphics context for output, and makes a callback to the
73    * client code to perform the image output
74    * 
75    * @param file
76    *          output file (if null, user is prompted to choose)
77    * @param parent
78    *          parent component for any dialogs shown
79    * @param width
80    * @param height
81    * @param imageSource
82    *          what the image is of e.g. Tree, Alignment
83    */
84   public void doExport(File file, Component parent, int width, int height,
85           String imageSource)
86   {
87     final long messageId = System.currentTimeMillis();
88     setStatus(
89             MessageManager.formatMessage(
90                     "status.exporting_alignment_as_x_file", imageType),
91             messageId);
92
93     /*
94      * prompt user for output file if not provided
95      */
96     if (file == null && !Jalview.isHeadlessMode())
97     {
98       JalviewFileChooser chooser = imageType.getFileChooser();
99       chooser.setFileView(new JalviewFileView());
100       MessageManager.formatMessage("label.create_image_of",
101               imageType.getName(), imageSource);
102       String title = "Create " + imageType.getName()
103               + " image from alignment";
104       chooser.setDialogTitle(title);
105       chooser.setToolTipText(MessageManager.getString("action.save"));
106       int value = chooser.showSaveDialog(parent);
107       if (value != JalviewFileChooser.APPROVE_OPTION)
108       {
109         String msg = MessageManager.formatMessage(
110                 "status.cancelled_image_export_operation", imageType.name);
111         setStatus(msg, messageId);
112         return;
113       }
114       Cache.setProperty("LAST_DIRECTORY",
115               chooser.getSelectedFile().getParent());
116       file = chooser.getSelectedFile();
117     }
118
119     /*
120      * Prompt for Text or Lineart (EPS/SVG) unless a preference is already set
121      * for this as EPS_RENDERING / SVG_RENDERING
122      * Always set to Text for JalviewJS as Lineart (glyph fonts) not available
123      */
124     String renderStyle = Cache.getDefault(
125             imageType.getName() + "_RENDERING",
126             LineartOptions.PROMPT_EACH_TIME);
127     if (Platform.isJS())
128     {
129       renderStyle = "Text";
130     }
131     AtomicBoolean textSelected = new AtomicBoolean(
132             !"Lineart".equals(renderStyle));
133     if ((imageType == TYPE.EPS || imageType == TYPE.SVG)
134             && LineartOptions.PROMPT_EACH_TIME.equals(renderStyle)
135             && !Jalview.isHeadlessMode())
136     {
137       final File chosenFile = file;
138       Runnable okAction = new Runnable()
139       {
140         @Override
141         public void run()
142         {
143           exportImage(chosenFile, !textSelected.get(), width, height,
144                   messageId);
145         }
146       };
147       LineartOptions epsOption = new LineartOptions(TYPE.EPS.getName(),
148               textSelected);
149       epsOption.setResponseAction(1, new Runnable()
150       {
151         @Override
152         public void run()
153         {
154           setStatus(MessageManager.formatMessage(
155                   "status.cancelled_image_export_operation",
156                   imageType.getName()), messageId);
157         }
158       });
159       epsOption.setResponseAction(0, okAction);
160       epsOption.showDialog();
161       /* no code here - JalviewJS cannot execute it */
162     }
163     else
164     {
165       /*
166        * character rendering not required, or preference already set 
167        * - just do the export
168        */
169       exportImage(file, !textSelected.get(), width, height, messageId);
170     }
171   }
172
173   /**
174    * Constructs a suitable graphics context and passes it to the callback
175    * handler for the image to be written. Shows status messages for export in
176    * progress, complete, or failed as appropriate.
177    * 
178    * @param chosenFile
179    * @param asLineart
180    * @param width
181    * @param height
182    * @param messageId
183    */
184   protected void exportImage(File chosenFile, boolean asLineart, int width,
185           int height, long messageId)
186   {
187     String type = imageType.getName();
188     try
189     {
190       // setStatus(
191       // MessageManager.formatMessage(
192       // "status.exporting_alignment_as_x_file", type),
193       // messageId);
194       ImageMaker im = new ImageMaker(imageType, width, height, chosenFile,
195               title, asLineart);
196       imageWriter.exportImage(im.getGraphics());
197       im.writeImage();
198       setStatus(
199               MessageManager.formatMessage("status.export_complete", type),
200               messageId);
201     } catch (Exception e)
202     {
203       System.out.println(String.format("Error creating %s file: %s", type,
204               e.toString()));
205       setStatus(MessageManager.formatMessage("info.error_creating_file",
206               type), messageId);
207     }
208   }
209
210   /**
211    * Asks the callback to show a status message with given id
212    * 
213    * @param msg
214    * @param id
215    */
216   void setStatus(String msg, long id)
217   {
218     if (messageBoard != null && !Jalview.isHeadlessMode())
219     {
220       messageBoard.setProgressBar(msg, id);
221     }
222   }
223
224 }