2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
23 import java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Dimension;
27 import java.awt.Graphics;
28 import java.awt.Graphics2D;
29 import java.awt.RenderingHints;
31 import java.util.List;
32 import java.util.Locale;
35 import javax.swing.JPanel;
36 import javax.swing.JSplitPane;
37 import javax.swing.SwingUtilities;
38 import javax.swing.event.InternalFrameAdapter;
39 import javax.swing.event.InternalFrameEvent;
41 import jalview.api.AlignmentViewPanel;
42 import jalview.bin.Console;
43 import jalview.datamodel.PDBEntry;
44 import jalview.datamodel.SequenceI;
45 import jalview.datamodel.StructureViewerModel;
46 import jalview.datamodel.StructureViewerModel.StructureData;
47 import jalview.gui.ImageExporter.ImageWriterI;
48 import jalview.gui.StructureViewer.ViewerType;
49 import jalview.structure.StructureCommand;
50 import jalview.structures.models.AAStructureBindingModel;
51 import jalview.util.BrowserLauncher;
52 import jalview.util.ImageMaker;
53 import jalview.util.ImageMaker.TYPE;
54 import jalview.util.MessageManager;
55 import jalview.util.Platform;
56 import jalview.util.imagemaker.BitmapImageSizing;
58 public class AppJmol extends StructureViewerBase
60 // ms to wait for Jmol to load files
61 private static final int JMOL_LOAD_TIMEOUT = 20000;
63 private static final String SPACE = " ";
65 private static final String QUOTE = "\"";
73 RenderPanel renderPanel;
82 * - add the alignment panel to the list used for colouring these
85 * - add the alignment panel to the list used for aligning these
87 * @param leaveColouringToJmol
88 * - do not update the colours from any other source. Jmol is
94 public AppJmol(StructureViewerModel viewerModel, AlignmentPanel ap,
95 String sessionFile, String viewid)
97 Map<File, StructureData> pdbData = viewerModel.getFileData();
98 PDBEntry[] pdbentrys = new PDBEntry[pdbData.size()];
99 SequenceI[][] seqs = new SequenceI[pdbData.size()][];
101 for (StructureData data : pdbData.values())
103 PDBEntry pdbentry = new PDBEntry(data.getPdbId(), null,
104 PDBEntry.Type.PDB, data.getFilePath());
105 pdbentrys[i] = pdbentry;
106 List<SequenceI> sequencesForPdb = data.getSeqList();
107 seqs[i] = sequencesForPdb
108 .toArray(new SequenceI[sequencesForPdb.size()]);
112 // TODO: check if protocol is needed to be set, and if chains are
114 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
115 pdbentrys, seqs, null);
117 jmb.setLoadingFromArchive(true);
118 addAlignmentPanel(ap);
119 if (viewerModel.isAlignWithPanel())
121 useAlignmentPanelForSuperposition(ap);
124 boolean useToColour = viewerModel.isColourWithAlignPanel();
125 boolean leaveColouringToJmol = viewerModel.isColourByViewer();
126 if (leaveColouringToJmol || !useToColour)
128 jmb.setColourBySequence(false);
129 seqColour.setSelected(false);
130 viewerColour.setSelected(true);
132 else if (useToColour)
134 useAlignmentPanelForColourbyseq(ap);
135 jmb.setColourBySequence(true);
136 seqColour.setSelected(true);
137 viewerColour.setSelected(false);
140 this.setBounds(viewerModel.getX(), viewerModel.getY(),
141 viewerModel.getWidth(), viewerModel.getHeight());
144 this.addInternalFrameListener(new InternalFrameAdapter()
147 public void internalFrameClosing(
148 InternalFrameEvent internalFrameEvent)
153 StringBuilder cmd = new StringBuilder();
154 cmd.append("load FILES ").append(QUOTE)
155 .append(Platform.escapeBackslashes(sessionFile)).append(QUOTE);
156 initJmol(cmd.toString());
160 protected void initMenus()
165 .setText(MessageManager.getString("label.colour_with_jmol"));
166 viewerColour.setToolTipText(MessageManager
167 .getString("label.let_jmol_manage_structure_colours"));
171 * display a single PDB structure in a new Jmol view
178 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
179 final AlignmentPanel ap)
181 setProgressIndicator(ap.alignFrame);
183 openNewJmol(ap, alignAddedStructures, new PDBEntry[] { pdbentry },
188 private void openNewJmol(AlignmentPanel ap, boolean alignAdded,
189 PDBEntry[] pdbentrys, SequenceI[][] seqs)
191 setProgressIndicator(ap.alignFrame);
192 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
193 pdbentrys, seqs, null);
194 addAlignmentPanel(ap);
195 useAlignmentPanelForColourbyseq(ap);
197 alignAddedStructures = alignAdded;
198 if (pdbentrys.length > 1)
200 useAlignmentPanelForSuperposition(ap);
203 jmb.setColourBySequence(true);
204 setSize(400, 400); // probably should be a configurable/dynamic default here
206 addingStructures = false;
207 worker = new Thread(this);
210 this.addInternalFrameListener(new InternalFrameAdapter()
213 public void internalFrameClosing(
214 InternalFrameEvent internalFrameEvent)
223 * create a new Jmol containing several structures optionally superimposed
224 * using the given alignPanel.
228 * - true to superimpose
232 public AppJmol(AlignmentPanel ap, boolean alignAdded, PDBEntry[] pe,
235 openNewJmol(ap, alignAdded, pe, seqs);
238 void initJmol(String command)
240 jmb.setFinishedInit(false);
241 renderPanel = new RenderPanel();
242 // TODO: consider waiting until the structure/view is fully loaded before
244 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
245 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
246 getBounds().width, getBounds().height);
247 if (scriptWindow == null)
249 BorderLayout bl = new BorderLayout();
252 scriptWindow = new JPanel(bl);
253 scriptWindow.setVisible(false);
256 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
258 // jmb.newJmolPopup("Jmol");
263 jmb.executeCommand(new StructureCommand(command), false);
264 jmb.executeCommand(new StructureCommand("set hoverDelay=0.1"), false);
265 jmb.setFinishedInit(true);
274 List<String> files = jmb.fetchPdbFiles(this);
275 if (files.size() > 0)
277 showFilesInViewer(files);
287 * Either adds the given files to a structure viewer or opens a new viewer to
291 * list of absolute paths to structure files
293 void showFilesInViewer(List<String> files)
295 long lastnotify = jmb.getLoadNotifiesHandled();
296 StringBuilder fileList = new StringBuilder();
297 for (String s : files)
299 fileList.append(SPACE).append(QUOTE)
300 .append(Platform.escapeBackslashes(s)).append(QUOTE);
302 String filesString = fileList.toString();
304 if (!addingStructures)
308 initJmol("load FILES " + filesString);
309 } catch (OutOfMemoryError oomerror)
311 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
312 Console.debug("File locations are " + filesString);
313 } catch (Exception ex)
315 Console.error("Couldn't open Jmol viewer!", ex);
316 ex.printStackTrace();
322 StringBuilder cmd = new StringBuilder();
323 cmd.append("loadingJalviewdata=true\nload APPEND ");
324 cmd.append(filesString);
325 cmd.append("\nloadingJalviewdata=null");
326 final StructureCommand command = new StructureCommand(cmd.toString());
327 lastnotify = jmb.getLoadNotifiesHandled();
331 jmb.executeCommand(command, false);
332 } catch (OutOfMemoryError oomerror)
334 new OOMWarning("When trying to add structures to the Jmol viewer!",
336 Console.debug("File locations are " + filesString);
338 } catch (Exception ex)
340 Console.error("Couldn't add files to Jmol viewer!", ex);
341 ex.printStackTrace();
346 // need to wait around until script has finished
347 int waitMax = JMOL_LOAD_TIMEOUT;
350 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
351 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
352 && jmb.getStructureFiles().length == files.size()))
356 Console.debug("Waiting around for jmb notify.");
357 waitTotal += waitFor;
359 // Thread.sleep() throws an exception in JS
360 Thread.sleep(waitFor);
361 } catch (Exception e)
364 if (waitTotal > waitMax)
366 System.err.println("Timed out waiting for Jmol to load files after "
368 // System.err.println("finished: " + jmb.isFinishedInit()
369 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
370 // + "; files: " + files.toString());
371 jmb.getStructureFiles();
376 // refresh the sequence colours for the new structure(s)
377 for (AlignmentViewPanel ap : _colourwith)
379 jmb.updateColours(ap);
381 // do superposition if asked to
382 if (alignAddedStructures)
384 alignAddedStructures();
386 addingStructures = false;
390 * Queues a thread to align structures with Jalview alignments
392 void alignAddedStructures()
394 javax.swing.SwingUtilities.invokeLater(new Runnable()
399 if (jmb.jmolViewer.isScriptExecuting())
401 SwingUtilities.invokeLater(this);
405 } catch (InterruptedException q)
412 alignStructsWithAllAlignPanels();
420 * Outputs the Jmol viewer image as an image file, after prompting the user to
421 * choose a file and (for EPS) choice of Text or Lineart character rendering
422 * (unless a preference for this is set)
427 public void makePDBImage(ImageMaker.TYPE type)
429 makePDBImage(null, type, null,
430 BitmapImageSizing.nullBitmapImageSizing());
433 public void makePDBImage(File file, ImageMaker.TYPE type, String renderer,
434 BitmapImageSizing userBis)
436 int width = getWidth();
437 int height = getHeight();
439 BitmapImageSizing bis = ImageMaker.getScaleWidthHeight(width, height,
441 float usescale = bis.scale;
442 int usewidth = bis.width;
443 int useheight = bis.height;
445 ImageWriterI writer = new ImageWriterI()
448 public void exportImage(Graphics g) throws Exception
450 Graphics2D ig2 = (Graphics2D) g;
451 ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
452 RenderingHints.VALUE_ANTIALIAS_ON);
453 if (type == TYPE.PNG && usescale > 0.0f)
455 // for a scaled image, this scales down a bigger image to give the
459 ig2.scale(1 / usescale, 1 / usescale);
463 jmb.jmolViewer.antialiased = true;
464 jmb.jmolViewer.requestRepaintAndWait("image export");
465 jmb.jmolViewer.renderScreenImage(ig2, usewidth, useheight);
468 String view = MessageManager.getString("action.view")
469 .toLowerCase(Locale.ROOT);
470 ImageExporter exporter = new ImageExporter(writer,
471 getProgressIndicator(), type, getTitle());
472 exporter.doExport(file, this, width, height, view, renderer, userBis);
476 public void showHelp_actionPerformed()
480 BrowserLauncher // BH 2018
481 .openURL("http://wiki.jmol.org");// http://jmol.sourceforge.net/docs/JmolUserGuide/");
482 } catch (Exception ex)
484 System.err.println("Show Jmol help failed with: " + ex.getMessage());
489 public void showConsole(boolean showConsole)
493 if (splitPane == null)
495 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
496 splitPane.setTopComponent(renderPanel);
497 splitPane.setBottomComponent(scriptWindow);
498 this.getContentPane().add(splitPane, BorderLayout.CENTER);
499 splitPane.setDividerLocation(getHeight() - 200);
500 scriptWindow.setVisible(true);
501 scriptWindow.validate();
502 splitPane.validate();
508 if (splitPane != null)
510 splitPane.setVisible(false);
515 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
521 class RenderPanel extends JPanel
523 final Dimension currentSize = new Dimension();
526 public void paintComponent(Graphics g)
528 getSize(currentSize);
530 if (jmb != null && jmb.hasFileLoadingError())
532 g.setColor(Color.black);
533 g.fillRect(0, 0, currentSize.width, currentSize.height);
534 g.setColor(Color.white);
535 g.setFont(new Font("Verdana", Font.BOLD, 14));
536 g.drawString(MessageManager.getString("label.error_loading_file")
537 + "...", 20, currentSize.height / 2);
538 StringBuffer sb = new StringBuffer();
540 for (int e = 0; e < jmb.getPdbCount(); e++)
542 sb.append(jmb.getPdbEntry(e).getId());
543 if (e < jmb.getPdbCount() - 1)
548 if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
551 g.drawString(sb.toString(), 20, currentSize.height / 2
552 - lines * g.getFontMetrics().getHeight());
556 else if (jmb == null || jmb.jmolViewer == null
557 || !jmb.isFinishedInit())
559 g.setColor(Color.black);
560 g.fillRect(0, 0, currentSize.width, currentSize.height);
561 g.setColor(Color.white);
562 g.setFont(new Font("Verdana", Font.BOLD, 14));
563 g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
564 20, currentSize.height / 2);
568 jmb.jmolViewer.renderScreenImage(g, currentSize.width,
575 public AAStructureBindingModel getBinding()
581 public ViewerType getViewerType()
583 return ViewerType.JMOL;
587 protected String getViewerName()