Clover icon

Coverage Report

  1. Project Clover database Mon Nov 18 2024 09:38:20 GMT
  2. Package jalview.gui

File AppJmol.java

 

Coverage histogram

../../img/srcFileCovDistChart4.png
40% of files have more coverage

Code metrics

58
222
23
2
679
532
73
0.33
9.65
11.5
3.17

Classes

Class Line # Actions
AppJmol 61 196 63
0.3834586438.3%
AppJmol.RenderPanel 601 26 10
0.4324324443.2%
 

Contributing tests

This file is covered by 5 tests. .

Source view

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