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