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