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