JAL-4195 add exception handling for all image output ops - still need to refactor...
[jalview.git] / src / jalview / gui / AppJmol.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.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Dimension;
26 import java.awt.Font;
27 import java.awt.Graphics;
28 import java.awt.Graphics2D;
29 import java.awt.RenderingHints;
30 import java.io.File;
31 import java.util.List;
32 import java.util.Locale;
33 import java.util.Map;
34
35 import javax.swing.JPanel;
36 import javax.swing.JSplitPane;
37 import javax.swing.SwingUtilities;
38 import javax.swing.event.InternalFrameAdapter;
39 import javax.swing.event.InternalFrameEvent;
40
41 import jalview.api.AlignmentViewPanel;
42 import jalview.bin.Console;
43 import jalview.datamodel.PDBEntry;
44 import jalview.datamodel.SequenceI;
45 import jalview.datamodel.StructureViewerModel;
46 import jalview.datamodel.StructureViewerModel.StructureData;
47 import jalview.gui.ImageExporter.ImageWriterI;
48 import jalview.gui.StructureViewer.ViewerType;
49 import jalview.io.exceptions.ImageOutputException;
50 import jalview.structure.StructureCommand;
51 import jalview.structures.models.AAStructureBindingModel;
52 import jalview.util.BrowserLauncher;
53 import jalview.util.ImageMaker;
54 import jalview.util.ImageMaker.TYPE;
55 import jalview.util.MessageManager;
56 import jalview.util.Platform;
57 import jalview.util.imagemaker.BitmapImageSizing;
58
59 public class AppJmol extends StructureViewerBase
60 {
61   // ms to wait for Jmol to load files
62   private static final int JMOL_LOAD_TIMEOUT = 20000;
63
64   private static final String SPACE = " ";
65
66   private static final String QUOTE = "\"";
67
68   AppJmolBinding jmb;
69
70   JPanel scriptWindow;
71
72   JSplitPane splitPane;
73
74   RenderPanel renderPanel;
75
76   /**
77    * 
78    * @param files
79    * @param ids
80    * @param seqs
81    * @param ap
82    * @param usetoColour
83    *          - add the alignment panel to the list used for colouring these
84    *          structures
85    * @param useToAlign
86    *          - add the alignment panel to the list used for aligning these
87    *          structures
88    * @param leaveColouringToJmol
89    *          - do not update the colours from any other source. Jmol is
90    *          handling them
91    * @param loadStatus
92    * @param bounds
93    * @param viewid
94    */
95   public AppJmol(StructureViewerModel viewerModel, AlignmentPanel ap,
96           String sessionFile, String viewid)
97   {
98     Map<File, StructureData> pdbData = viewerModel.getFileData();
99     PDBEntry[] pdbentrys = new PDBEntry[pdbData.size()];
100     SequenceI[][] seqs = new SequenceI[pdbData.size()][];
101     int i = 0;
102     for (StructureData data : pdbData.values())
103     {
104       PDBEntry pdbentry = new PDBEntry(data.getPdbId(), null,
105               PDBEntry.Type.PDB, data.getFilePath());
106       pdbentrys[i] = pdbentry;
107       List<SequenceI> sequencesForPdb = data.getSeqList();
108       seqs[i] = sequencesForPdb
109               .toArray(new SequenceI[sequencesForPdb.size()]);
110       i++;
111     }
112
113     // TODO: check if protocol is needed to be set, and if chains are
114     // autodiscovered.
115     jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
116             pdbentrys, seqs, null);
117
118     jmb.setLoadingFromArchive(true);
119     addAlignmentPanel(ap);
120     if (viewerModel.isAlignWithPanel())
121     {
122       useAlignmentPanelForSuperposition(ap);
123     }
124     initMenus();
125     boolean useToColour = viewerModel.isColourWithAlignPanel();
126     boolean leaveColouringToJmol = viewerModel.isColourByViewer();
127     if (leaveColouringToJmol || !useToColour)
128     {
129       jmb.setColourBySequence(false);
130       seqColour.setSelected(false);
131       viewerColour.setSelected(true);
132     }
133     else if (useToColour)
134     {
135       useAlignmentPanelForColourbyseq(ap);
136       jmb.setColourBySequence(true);
137       seqColour.setSelected(true);
138       viewerColour.setSelected(false);
139     }
140
141     this.setBounds(viewerModel.getX(), viewerModel.getY(),
142             viewerModel.getWidth(), viewerModel.getHeight());
143     setViewId(viewid);
144
145     this.addInternalFrameListener(new InternalFrameAdapter()
146     {
147       @Override
148       public void internalFrameClosing(
149               InternalFrameEvent internalFrameEvent)
150       {
151         closeViewer(false);
152       }
153     });
154     StringBuilder cmd = new StringBuilder();
155     cmd.append("load FILES ").append(QUOTE)
156             .append(Platform.escapeBackslashes(sessionFile)).append(QUOTE);
157     initJmol(cmd.toString());
158   }
159
160   @Override
161   protected void initMenus()
162   {
163     super.initMenus();
164
165     viewerColour
166             .setText(MessageManager.getString("label.colour_with_jmol"));
167     viewerColour.setToolTipText(MessageManager
168             .getString("label.let_jmol_manage_structure_colours"));
169   }
170
171   /**
172    * display a single PDB structure in a new Jmol view
173    * 
174    * @param pdbentry
175    * @param seq
176    * @param chains
177    * @param ap
178    */
179   public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
180           final AlignmentPanel ap)
181   {
182     setProgressIndicator(ap.alignFrame);
183
184     openNewJmol(ap, alignAddedStructures, new PDBEntry[] { pdbentry },
185             new SequenceI[][]
186             { seq });
187   }
188
189   private void openNewJmol(AlignmentPanel ap, boolean alignAdded,
190           PDBEntry[] pdbentrys, SequenceI[][] seqs)
191   {
192     setProgressIndicator(ap.alignFrame);
193     jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
194             pdbentrys, seqs, null);
195     addAlignmentPanel(ap);
196     useAlignmentPanelForColourbyseq(ap);
197
198     alignAddedStructures = alignAdded;
199     if (pdbentrys.length > 1)
200     {
201       useAlignmentPanelForSuperposition(ap);
202     }
203
204     jmb.setColourBySequence(true);
205     setSize(400, 400); // probably should be a configurable/dynamic default here
206     initMenus();
207     addingStructures = false;
208     worker = new Thread(this);
209     worker.start();
210
211     this.addInternalFrameListener(new InternalFrameAdapter()
212     {
213       @Override
214       public void internalFrameClosing(
215               InternalFrameEvent internalFrameEvent)
216       {
217         closeViewer(false);
218       }
219     });
220
221   }
222
223   /**
224    * create a new Jmol containing several structures optionally superimposed
225    * using the given alignPanel.
226    * 
227    * @param ap
228    * @param alignAdded
229    *          - true to superimpose
230    * @param pe
231    * @param seqs
232    */
233   public AppJmol(AlignmentPanel ap, boolean alignAdded, PDBEntry[] pe,
234           SequenceI[][] seqs)
235   {
236     openNewJmol(ap, alignAdded, pe, seqs);
237   }
238
239   void initJmol(String command)
240   {
241     jmb.setFinishedInit(false);
242     renderPanel = new RenderPanel();
243     // TODO: consider waiting until the structure/view is fully loaded before
244     // displaying
245     this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
246     jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
247             getBounds().width, getBounds().height);
248     if (scriptWindow == null)
249     {
250       BorderLayout bl = new BorderLayout();
251       bl.setHgap(0);
252       bl.setVgap(0);
253       scriptWindow = new JPanel(bl);
254       scriptWindow.setVisible(false);
255     }
256
257     jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
258             null);
259     // jmb.newJmolPopup("Jmol");
260     if (command == null)
261     {
262       command = "";
263     }
264     jmb.executeCommand(new StructureCommand(command), false);
265     jmb.executeCommand(new StructureCommand("set hoverDelay=0.1"), false);
266     jmb.setFinishedInit(true);
267   }
268
269   @Override
270   public void run()
271   {
272     _started = true;
273     try
274     {
275       List<String> files = jmb.fetchPdbFiles(this);
276       if (files.size() > 0)
277       {
278         showFilesInViewer(files);
279       }
280     } finally
281     {
282       _started = false;
283       worker = null;
284     }
285   }
286
287   /**
288    * Either adds the given files to a structure viewer or opens a new viewer to
289    * show them
290    * 
291    * @param files
292    *          list of absolute paths to structure files
293    */
294   void showFilesInViewer(List<String> files)
295   {
296     long lastnotify = jmb.getLoadNotifiesHandled();
297     StringBuilder fileList = new StringBuilder();
298     for (String s : files)
299     {
300       fileList.append(SPACE).append(QUOTE)
301               .append(Platform.escapeBackslashes(s)).append(QUOTE);
302     }
303     String filesString = fileList.toString();
304
305     if (!addingStructures)
306     {
307       try
308       {
309         initJmol("load FILES " + filesString);
310       } catch (OutOfMemoryError oomerror)
311       {
312         new OOMWarning("When trying to open the Jmol viewer!", oomerror);
313         Console.debug("File locations are " + filesString);
314       } catch (Exception ex)
315       {
316         Console.error("Couldn't open Jmol viewer!", ex);
317         ex.printStackTrace();
318         return;
319       }
320     }
321     else
322     {
323       StringBuilder cmd = new StringBuilder();
324       cmd.append("loadingJalviewdata=true\nload APPEND ");
325       cmd.append(filesString);
326       cmd.append("\nloadingJalviewdata=null");
327       final StructureCommand command = new StructureCommand(cmd.toString());
328       lastnotify = jmb.getLoadNotifiesHandled();
329
330       try
331       {
332         jmb.executeCommand(command, false);
333       } catch (OutOfMemoryError oomerror)
334       {
335         new OOMWarning("When trying to add structures to the Jmol viewer!",
336                 oomerror);
337         Console.debug("File locations are " + filesString);
338         return;
339       } catch (Exception ex)
340       {
341         Console.error("Couldn't add files to Jmol viewer!", ex);
342         ex.printStackTrace();
343         return;
344       }
345     }
346
347     // need to wait around until script has finished
348     int waitMax = JMOL_LOAD_TIMEOUT;
349     int waitFor = 35;
350     int waitTotal = 0;
351     while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
352             : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
353                     && jmb.getStructureFiles().length == files.size()))
354     {
355       try
356       {
357         Console.debug("Waiting around for jmb notify.");
358         waitTotal += waitFor;
359
360         // Thread.sleep() throws an exception in JS
361         Thread.sleep(waitFor);
362       } catch (Exception e)
363       {
364       }
365       if (waitTotal > waitMax)
366       {
367         System.err.println("Timed out waiting for Jmol to load files after "
368                 + waitTotal + "ms");
369         // System.err.println("finished: " + jmb.isFinishedInit()
370         // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
371         // + "; files: " + files.toString());
372         jmb.getStructureFiles();
373         break;
374       }
375     }
376
377     // refresh the sequence colours for the new structure(s)
378     for (AlignmentViewPanel ap : _colourwith)
379     {
380       jmb.updateColours(ap);
381     }
382     // do superposition if asked to
383     if (alignAddedStructures)
384     {
385       alignAddedStructures();
386     }
387     addingStructures = false;
388   }
389
390   /**
391    * Queues a thread to align structures with Jalview alignments
392    */
393   void alignAddedStructures()
394   {
395     javax.swing.SwingUtilities.invokeLater(new Runnable()
396     {
397       @Override
398       public void run()
399       {
400         if (jmb.jmolViewer.isScriptExecuting())
401         {
402           SwingUtilities.invokeLater(this);
403           try
404           {
405             Thread.sleep(5);
406           } catch (InterruptedException q)
407           {
408           }
409           return;
410         }
411         else
412         {
413           alignStructsWithAllAlignPanels();
414         }
415       }
416     });
417
418   }
419
420   /**
421    * Outputs the Jmol viewer image as an image file, after prompting the user to
422    * choose a file and (for EPS) choice of Text or Lineart character rendering
423    * (unless a preference for this is set)
424    * 
425    * @param type
426    */
427   @Override
428   public void makePDBImage(ImageMaker.TYPE type)
429   {
430     try {
431     makePDBImage(null, type, null,
432             BitmapImageSizing.nullBitmapImageSizing());
433     } catch (ImageOutputException ioex) {
434       Console.error("Unexpected error whilst writing "+type.toString(),ioex);
435     }
436   }
437
438   public void makePDBImage(File file, ImageMaker.TYPE type, String renderer,
439           BitmapImageSizing userBis) throws ImageOutputException
440   {
441     int width = getWidth();
442     int height = getHeight();
443
444     BitmapImageSizing bis = ImageMaker.getScaleWidthHeight(width, height,
445             userBis);
446     float usescale = bis.scale;
447     int usewidth = bis.width;
448     int useheight = bis.height;
449
450     ImageWriterI writer = new ImageWriterI()
451     {
452       @Override
453       public void exportImage(Graphics g) throws Exception
454       {
455         Graphics2D ig2 = (Graphics2D) g;
456         ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
457                 RenderingHints.VALUE_ANTIALIAS_ON);
458         if (type == TYPE.PNG && usescale > 0.0f)
459         {
460           // for a scaled image, this scales down a bigger image to give the
461           // right resolution
462           if (usescale > 0.0f)
463           {
464             ig2.scale(1 / usescale, 1 / usescale);
465           }
466         }
467
468         jmb.jmolViewer.antialiased = true;
469         jmb.jmolViewer.requestRepaintAndWait("image export");
470         jmb.jmolViewer.renderScreenImage(ig2, usewidth, useheight);
471       }
472     };
473     String view = MessageManager.getString("action.view")
474             .toLowerCase(Locale.ROOT);
475     ImageExporter exporter = new ImageExporter(writer,
476             getProgressIndicator(), type, getTitle());
477     
478     exporter.doExport(file, this, width, height, view, renderer, userBis);
479     
480   }
481
482   @Override
483   public void showHelp_actionPerformed()
484   {
485     try
486     {
487       BrowserLauncher // BH 2018
488               .openURL("http://wiki.jmol.org");// http://jmol.sourceforge.net/docs/JmolUserGuide/");
489     } catch (Exception ex)
490     {
491       System.err.println("Show Jmol help failed with: " + ex.getMessage());
492     }
493   }
494
495   @Override
496   public void showConsole(boolean showConsole)
497   {
498     if (showConsole)
499     {
500       if (splitPane == null)
501       {
502         splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
503         splitPane.setTopComponent(renderPanel);
504         splitPane.setBottomComponent(scriptWindow);
505         this.getContentPane().add(splitPane, BorderLayout.CENTER);
506         splitPane.setDividerLocation(getHeight() - 200);
507         scriptWindow.setVisible(true);
508         scriptWindow.validate();
509         splitPane.validate();
510       }
511
512     }
513     else
514     {
515       if (splitPane != null)
516       {
517         splitPane.setVisible(false);
518       }
519
520       splitPane = null;
521
522       this.getContentPane().add(renderPanel, BorderLayout.CENTER);
523     }
524
525     validate();
526   }
527
528   class RenderPanel extends JPanel
529   {
530     final Dimension currentSize = new Dimension();
531
532     @Override
533     public void paintComponent(Graphics g)
534     {
535       getSize(currentSize);
536
537       if (jmb != null && jmb.hasFileLoadingError())
538       {
539         g.setColor(Color.black);
540         g.fillRect(0, 0, currentSize.width, currentSize.height);
541         g.setColor(Color.white);
542         g.setFont(new Font("Verdana", Font.BOLD, 14));
543         g.drawString(MessageManager.getString("label.error_loading_file")
544                 + "...", 20, currentSize.height / 2);
545         StringBuffer sb = new StringBuffer();
546         int lines = 0;
547         for (int e = 0; e < jmb.getPdbCount(); e++)
548         {
549           sb.append(jmb.getPdbEntry(e).getId());
550           if (e < jmb.getPdbCount() - 1)
551           {
552             sb.append(",");
553           }
554
555           if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
556           {
557             lines++;
558             g.drawString(sb.toString(), 20, currentSize.height / 2
559                     - lines * g.getFontMetrics().getHeight());
560           }
561         }
562       }
563       else if (jmb == null || jmb.jmolViewer == null
564               || !jmb.isFinishedInit())
565       {
566         g.setColor(Color.black);
567         g.fillRect(0, 0, currentSize.width, currentSize.height);
568         g.setColor(Color.white);
569         g.setFont(new Font("Verdana", Font.BOLD, 14));
570         g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
571                 20, currentSize.height / 2);
572       }
573       else
574       {
575         jmb.jmolViewer.renderScreenImage(g, currentSize.width,
576                 currentSize.height);
577       }
578     }
579   }
580
581   @Override
582   public AAStructureBindingModel getBinding()
583   {
584     return this.jmb;
585   }
586
587   @Override
588   public ViewerType getViewerType()
589   {
590     return ViewerType.JMOL;
591   }
592
593   @Override
594   protected String getViewerName()
595   {
596     return "Jmol";
597   }
598 }