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