Clover icon

Coverage Report

  1. Project Clover database Mon Dec 8 2025 13:21:36 GMT
  2. Package jalview.gui

File AppJmol.java

 

Coverage histogram

../../img/srcFileCovDistChart7.png
30% of files have more coverage

Code metrics

58
229
26
2
711
561
77
0.34
8.81
13
2.96

Classes

Class Line # Actions
AppJmol 61 203 67
0.69202969.2%
AppJmol.RenderPanel 633 26 10
0.4324324443.2%
 

Contributing tests

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