Clover icon

Coverage Report

  1. Project Clover database Thu Jan 15 2026 16:11:02 GMT
  2. Package jalview.gui

File AppJmol.java

 

Coverage histogram

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

Code metrics

58
229
26
2
710
561
77
0.34
8.81
13
2.96

Classes

Class Line # Actions
AppJmol 60 203 67
0.550724655.1%
AppJmol.RenderPanel 632 26 10
0.918918991.9%
 

Contributing tests

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