Clover icon

Coverage Report

  1. Project Clover database Thu Dec 4 2025 16:11:35 GMT
  2. Package jalview.gui

File AppJmol.java

 

Coverage histogram

../../img/srcFileCovDistChart6.png
37% of files have more coverage

Code metrics

58
224
24
2
688
541
74
0.33
9.33
12
3.08

Classes

Class Line # Actions
AppJmol 60 198 64
0.565055856.5%
AppJmol.RenderPanel 610 26 10
0.918918991.9%
 

Contributing tests

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