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