Clover icon

Coverage Report

  1. Project Clover database Tue Mar 10 2026 14:58:44 GMT
  2. Package jalview.gui

File AppJmol.java

 

Coverage histogram

../../img/srcFileCovDistChart0.png
0% 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.00%
AppJmol.RenderPanel 632 26 10
0.00%
 

Contributing tests

No tests hitting this source file were found.

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  0 toggle public AppJmol(StructureViewerModel viewerModel, AlignmentPanel ap,
97    String sessionFile, String viewid)
98    {
99  0 Map<File, StructureData> pdbData = viewerModel.getFileData();
100  0 PDBEntry[] pdbentrys = new PDBEntry[pdbData.size()];
101  0 SequenceI[][] seqs = new SequenceI[pdbData.size()][];
102  0 int i = 0;
103  0 for (StructureData data : pdbData.values())
104    {
105  0 PDBEntry pdbentry = new PDBEntry(data.getPdbId(), null,
106    PDBEntry.Type.PDB, data.getFilePath());
107  0 pdbentrys[i] = pdbentry;
108  0 List<SequenceI> sequencesForPdb = data.getSeqList();
109  0 seqs[i] = sequencesForPdb
110    .toArray(new SequenceI[sequencesForPdb.size()]);
111  0 i++;
112    }
113    // TODO: check if protocol is needed to be set, and if chains are
114    // autodiscovered.
115  0 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
116    pdbentrys, seqs, null);
117   
118  0 jmb.setLoadingFromArchive(true);
119  0 addAlignmentPanel(ap);
120  0 if (viewerModel.isAlignWithPanel())
121    {
122  0 useAlignmentPanelForSuperposition(ap);
123    }
124  0 initMenus();
125  0 boolean useToColour = viewerModel.isColourWithAlignPanel();
126  0 boolean leaveColouringToJmol = viewerModel.isColourByViewer();
127  0 if (leaveColouringToJmol || !useToColour)
128    {
129  0 jmb.setColourBySequence(false);
130  0 seqColour.setSelected(false);
131  0 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  0 this.setBounds(viewerModel.getX(), viewerModel.getY(),
141    viewerModel.getWidth(), viewerModel.getHeight());
142  0 setViewId(viewid);
143   
144  0 this.addInternalFrameListener(new InternalFrameAdapter()
145    {
 
146  0 toggle @Override
147    public void internalFrameClosing(
148    InternalFrameEvent internalFrameEvent)
149    {
150  0 closeViewer(false);
151    }
152    });
153  0 StringBuilder cmd = new StringBuilder();
154  0 cmd.append(jmb.getCommandGenerator().loadFile(sessionFile));
155  0 initJmol(cmd.toString());
156    }
157   
 
158  0 toggle @Override
159    protected void initMenus()
160    {
161  0 super.initMenus();
162   
163   
164  0 viewerColour
165    .setText(MessageManager.getString("label.colour_with_jmol"));
166  0 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  0 toggle public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
179    final AlignmentPanel ap)
180    {
181  0 setProgressIndicator(ap.alignFrame);
182   
183  0 openNewJmol(ap, alignAddedStructures, new PDBEntry[] { pdbentry },
184    new SequenceI[][]
185    { seq });
186    }
187   
 
188  0 toggle private void openNewJmol(AlignmentPanel ap, boolean alignAdded,
189    PDBEntry[] pdbentrys, SequenceI[][] seqs)
190    {
191  0 setProgressIndicator(ap.alignFrame);
192  0 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
193    pdbentrys, seqs, null);
194  0 addAlignmentPanel(ap);
195  0 useAlignmentPanelForColourbyseq(ap);
196   
197  0 alignAddedStructures = alignAdded;
198  0 if (pdbentrys.length > 1)
199    {
200  0 useAlignmentPanelForSuperposition(ap);
201    }
202   
203  0 jmb.setColourBySequence(true);
204  0 setSize(400, 400); // probably should be a configurable/dynamic default here
205  0 initMenus();
206  0 addingStructures = false;
207  0 worker = new Thread(this);
208  0 worker.start();
209   
210  0 this.addInternalFrameListener(new InternalFrameAdapter()
211    {
 
212  0 toggle @Override
213    public void internalFrameClosing(
214    InternalFrameEvent internalFrameEvent)
215    {
216  0 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  0 toggle public AppJmol(AlignmentPanel ap, boolean alignAdded, PDBEntry[] pe,
233    SequenceI[][] seqs)
234    {
235  0 openNewJmol(ap, alignAdded, pe, seqs);
236    }
237   
 
238  0 toggle void initJmol(String command)
239    {
240  0 jmb.setFinishedInit(false);
241  0 renderPanel = new RenderPanel();
242    // TODO: consider waiting until the structure/view is fully loaded before
243    // displaying
244  0 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
245  0 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
246    getBounds().width, getBounds().height);
247  0 if (scriptWindow == null)
248    {
249  0 BorderLayout bl = new BorderLayout();
250  0 bl.setHgap(0);
251  0 bl.setVgap(0);
252  0 scriptWindow = new JPanel(bl);
253  0 scriptWindow.setVisible(false);
254    }
255   
256  0 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
257    null);
258    // jmb.newJmolPopup("Jmol");
259  0 if (command == null)
260    {
261  0 command = "";
262    }
263  0 jmb.executeCommand(new StructureCommand(command), false);
264  0 jmb.executeCommand(new StructureCommand("set hoverDelay=0.1"), false);
265  0 jmb.executeCommand(new StructureCommand("set antialiasdisplay on"),
266    false);
267  0 jmb.setFinishedInit(true);
268    }
269   
 
270  0 toggle @Override
271    public void run()
272    {
273  0 _started = true;
274  0 try
275    {
276  0 List<String> files = jmb.fetchPdbFiles(this);
277  0 if (files.size() > 0)
278    {
279  0 showFilesInViewer(files);
280    }
281    } catch (Throwable t)
282    {
283  0 Console.warn("Unexpected exception ",t);
284    }
285    finally
286    {
287  0 _started = false;
288  0 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  0 toggle void showFilesInViewer(List<String> files)
300    {
301  0 long lastnotify = jmb.getLoadNotifiesHandled();
302  0 StringBuilder fileList = new StringBuilder();
303  0 for (String s : files)
304    {
305  0 fileList.append(SPACE).append(QUOTE)
306    .append(JmolCommands.escapeQuotedFilename(s)).append(QUOTE);
307    }
308  0 String filesString = fileList.toString();
309   
310  0 if (!addingStructures)
311    {
312  0 try
313    {
314  0 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  0 StringBuilder cmd = new StringBuilder();
329  0 cmd.append("loadingJalviewdata=true\nload APPEND ");
330  0 cmd.append(filesString);
331  0 cmd.append("\nloadingJalviewdata=null");
332  0 final StructureCommand command = new StructureCommand(cmd.toString());
333  0 lastnotify = jmb.getLoadNotifiesHandled();
334   
335  0 try
336    {
337  0 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  0 int waitMax = JMOL_LOAD_TIMEOUT;
354  0 int waitFor = 35;
355  0 int waitTotal = 0;
356  0 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
357    : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
358    && jmb.getStructureFiles().length == files.size()))
359    {
360  0 try
361    {
362  0 Console.debug("Waiting around for jmb notify.");
363  0 waitTotal += waitFor;
364   
365    // Thread.sleep() throws an exception in JS
366  0 Thread.sleep(waitFor);
367    } catch (Exception e)
368    {
369    }
370  0 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  0 for (AlignmentViewPanel ap : _colourwith)
385    {
386  0 jmb.updateColours(ap);
387    }
388    // do superposition if asked to
389  0 if (alignAddedStructures)
390    {
391  0 alignAddedStructures();
392    }
393  0 addingStructures = false;
394    }
395   
396    /**
397    * Queues a thread to align structures with Jalview alignments
398    */
 
399  0 toggle void alignAddedStructures()
400    {
401  0 javax.swing.SwingUtilities.invokeLater(new Runnable()
402    {
 
403  0 toggle @Override
404    public void run()
405    {
406  0 if (jmb.jmolViewer.isScriptExecuting())
407    {
408  0 Thread timer = new Thread(new Runnable()
409    {
 
410  0 toggle @Override
411    public void run()
412    {
413  0 try
414    {
415  0 Thread.sleep(5);
416  0 SwingUtilities.invokeLater(this);
417   
418    } catch (InterruptedException q)
419    {
420    }
421    }
422    });
423  0 timer.start();
424  0 return;
425    }
426    else
427    {
428  0 Thread aligner = new Thread(new Runnable()
429    {
 
430  0 toggle @Override
431    public void run()
432    {
433  0 alignStructsWithAllAlignPanels();
434   
435    }
436    });
437  0 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  0 toggle @Override
637    public void paintComponent(Graphics g)
638    {
639  0 getSize(currentSize);
640   
641  0 if (jmb != null && jmb.hasFileLoadingError())
642    {
643  0 g.setColor(Color.black);
644  0 g.fillRect(0, 0, currentSize.width, currentSize.height);
645  0 g.setColor(Color.white);
646  0 g.setFont(new Font("Verdana", Font.BOLD, 14));
647  0 g.drawString(MessageManager.getString("label.error_loading_file")
648    + "...", 20, currentSize.height / 2);
649  0 StringBuffer sb = new StringBuffer();
650  0 int lines = 0;
651  0 for (int e = 0; e < jmb.getPdbCount(); e++)
652    {
653  0 sb.append(jmb.getPdbEntry(e).getId());
654  0 if (e < jmb.getPdbCount() - 1)
655    {
656  0 sb.append(",");
657    }
658   
659  0 if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
660    {
661  0 lines++;
662  0 g.drawString(sb.toString(), 20, currentSize.height / 2
663    - lines * g.getFontMetrics().getHeight());
664    }
665    }
666    }
667  0 else if (jmb == null || jmb.jmolViewer == null
668    || !jmb.isFinishedInit())
669    {
670  0 g.setColor(Color.black);
671  0 g.fillRect(0, 0, currentSize.width, currentSize.height);
672  0 g.setColor(Color.white);
673  0 g.setFont(new Font("Verdana", Font.BOLD, 14));
674  0 g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
675    20, currentSize.height / 2);
676    }
677    else
678    {
679  0 repainting = true;
680  0 synchronized (jmb)
681    {
682  0 jmb.jmolViewer.renderScreenImage(g, currentSize.width,
683    currentSize.height);
684   
685    }
686  0 repainting = false;
687    }
688    }
689   
690    volatile boolean repainting = false;
691    }
692   
 
693  0 toggle @Override
694    public AAStructureBindingModel getBinding()
695    {
696  0 return this.jmb;
697    }
698   
 
699  0 toggle @Override
700    public ViewerType getViewerType()
701    {
702  0 return ViewerType.JMOL;
703    }
704   
 
705  0 toggle @Override
706    protected String getViewerName()
707    {
708  0 return "Jmol";
709    }
710    }