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