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