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.io.exceptions.ImageOutputException;
50 import jalview.structure.StructureCommand;
51 import jalview.structures.models.AAStructureBindingModel;
52 import jalview.util.BrowserLauncher;
53 import jalview.util.ImageMaker;
54 import jalview.util.ImageMaker.TYPE;
55 import jalview.util.MessageManager;
56 import jalview.util.Platform;
57 import jalview.util.imagemaker.BitmapImageSizing;
59 public class AppJmol extends StructureViewerBase
61 // ms to wait for Jmol to load files
62 private static final int JMOL_LOAD_TIMEOUT = 20000;
64 private static final String SPACE = " ";
66 private static final String QUOTE = "\"";
74 RenderPanel renderPanel;
83 * - add the alignment panel to the list used for colouring these
86 * - add the alignment panel to the list used for aligning these
88 * @param leaveColouringToJmol
89 * - do not update the colours from any other source. Jmol is
95 public AppJmol(StructureViewerModel viewerModel, AlignmentPanel ap,
96 String sessionFile, String viewid)
98 Map<File, StructureData> pdbData = viewerModel.getFileData();
99 PDBEntry[] pdbentrys = new PDBEntry[pdbData.size()];
100 SequenceI[][] seqs = new SequenceI[pdbData.size()][];
102 for (StructureData data : pdbData.values())
104 PDBEntry pdbentry = new PDBEntry(data.getPdbId(), null,
105 PDBEntry.Type.PDB, data.getFilePath());
106 pdbentrys[i] = pdbentry;
107 List<SequenceI> sequencesForPdb = data.getSeqList();
108 seqs[i] = sequencesForPdb
109 .toArray(new SequenceI[sequencesForPdb.size()]);
113 // TODO: check if protocol is needed to be set, and if chains are
115 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
116 pdbentrys, seqs, null);
118 jmb.setLoadingFromArchive(true);
119 addAlignmentPanel(ap);
120 if (viewerModel.isAlignWithPanel())
122 useAlignmentPanelForSuperposition(ap);
125 boolean useToColour = viewerModel.isColourWithAlignPanel();
126 boolean leaveColouringToJmol = viewerModel.isColourByViewer();
127 if (leaveColouringToJmol || !useToColour)
129 jmb.setColourBySequence(false);
130 seqColour.setSelected(false);
131 viewerColour.setSelected(true);
133 else if (useToColour)
135 useAlignmentPanelForColourbyseq(ap);
136 jmb.setColourBySequence(true);
137 seqColour.setSelected(true);
138 viewerColour.setSelected(false);
141 this.setBounds(viewerModel.getX(), viewerModel.getY(),
142 viewerModel.getWidth(), viewerModel.getHeight());
145 this.addInternalFrameListener(new InternalFrameAdapter()
148 public void internalFrameClosing(
149 InternalFrameEvent internalFrameEvent)
154 StringBuilder cmd = new StringBuilder();
155 cmd.append("load FILES ").append(QUOTE)
156 .append(Platform.escapeBackslashes(sessionFile)).append(QUOTE);
157 initJmol(cmd.toString());
161 protected void initMenus()
166 .setText(MessageManager.getString("label.colour_with_jmol"));
167 viewerColour.setToolTipText(MessageManager
168 .getString("label.let_jmol_manage_structure_colours"));
172 * display a single PDB structure in a new Jmol view
179 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
180 final AlignmentPanel ap)
182 setProgressIndicator(ap.alignFrame);
184 openNewJmol(ap, alignAddedStructures, new PDBEntry[] { pdbentry },
189 private void openNewJmol(AlignmentPanel ap, boolean alignAdded,
190 PDBEntry[] pdbentrys, SequenceI[][] seqs)
192 setProgressIndicator(ap.alignFrame);
193 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
194 pdbentrys, seqs, null);
195 addAlignmentPanel(ap);
196 useAlignmentPanelForColourbyseq(ap);
198 alignAddedStructures = alignAdded;
199 if (pdbentrys.length > 1)
201 useAlignmentPanelForSuperposition(ap);
204 jmb.setColourBySequence(true);
205 setSize(400, 400); // probably should be a configurable/dynamic default here
207 addingStructures = false;
208 worker = new Thread(this);
211 this.addInternalFrameListener(new InternalFrameAdapter()
214 public void internalFrameClosing(
215 InternalFrameEvent internalFrameEvent)
224 * create a new Jmol containing several structures optionally superimposed
225 * using the given alignPanel.
229 * - true to superimpose
233 public AppJmol(AlignmentPanel ap, boolean alignAdded, PDBEntry[] pe,
236 openNewJmol(ap, alignAdded, pe, seqs);
239 void initJmol(String command)
241 jmb.setFinishedInit(false);
242 renderPanel = new RenderPanel();
243 // TODO: consider waiting until the structure/view is fully loaded before
245 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
246 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
247 getBounds().width, getBounds().height);
248 if (scriptWindow == null)
250 BorderLayout bl = new BorderLayout();
253 scriptWindow = new JPanel(bl);
254 scriptWindow.setVisible(false);
257 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
259 // jmb.newJmolPopup("Jmol");
264 jmb.executeCommand(new StructureCommand(command), false);
265 jmb.executeCommand(new StructureCommand("set hoverDelay=0.1"), false);
266 jmb.setFinishedInit(true);
275 List<String> files = jmb.fetchPdbFiles(this);
276 if (files.size() > 0)
278 showFilesInViewer(files);
288 * Either adds the given files to a structure viewer or opens a new viewer to
292 * list of absolute paths to structure files
294 void showFilesInViewer(List<String> files)
296 long lastnotify = jmb.getLoadNotifiesHandled();
297 StringBuilder fileList = new StringBuilder();
298 for (String s : files)
300 fileList.append(SPACE).append(QUOTE)
301 .append(Platform.escapeBackslashes(s)).append(QUOTE);
303 String filesString = fileList.toString();
305 if (!addingStructures)
309 initJmol("load FILES " + filesString);
310 } catch (OutOfMemoryError oomerror)
312 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
313 Console.debug("File locations are " + filesString);
314 } catch (Exception ex)
316 Console.error("Couldn't open Jmol viewer!", ex);
317 ex.printStackTrace();
323 StringBuilder cmd = new StringBuilder();
324 cmd.append("loadingJalviewdata=true\nload APPEND ");
325 cmd.append(filesString);
326 cmd.append("\nloadingJalviewdata=null");
327 final StructureCommand command = new StructureCommand(cmd.toString());
328 lastnotify = jmb.getLoadNotifiesHandled();
332 jmb.executeCommand(command, false);
333 } catch (OutOfMemoryError oomerror)
335 new OOMWarning("When trying to add structures to the Jmol viewer!",
337 Console.debug("File locations are " + filesString);
339 } catch (Exception ex)
341 Console.error("Couldn't add files to Jmol viewer!", ex);
342 ex.printStackTrace();
347 // need to wait around until script has finished
348 int waitMax = JMOL_LOAD_TIMEOUT;
351 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
352 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
353 && jmb.getStructureFiles().length == files.size()))
357 Console.debug("Waiting around for jmb notify.");
358 waitTotal += waitFor;
360 // Thread.sleep() throws an exception in JS
361 Thread.sleep(waitFor);
362 } catch (Exception e)
365 if (waitTotal > waitMax)
367 System.err.println("Timed out waiting for Jmol to load files after "
369 // System.err.println("finished: " + jmb.isFinishedInit()
370 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
371 // + "; files: " + files.toString());
372 jmb.getStructureFiles();
377 // refresh the sequence colours for the new structure(s)
378 for (AlignmentViewPanel ap : _colourwith)
380 jmb.updateColours(ap);
382 // do superposition if asked to
383 if (alignAddedStructures)
385 alignAddedStructures();
387 addingStructures = false;
391 * Queues a thread to align structures with Jalview alignments
393 void alignAddedStructures()
395 javax.swing.SwingUtilities.invokeLater(new Runnable()
400 if (jmb.jmolViewer.isScriptExecuting())
402 SwingUtilities.invokeLater(this);
406 } catch (InterruptedException q)
413 alignStructsWithAllAlignPanels();
421 * Outputs the Jmol viewer image as an image file, after prompting the user to
422 * choose a file and (for EPS) choice of Text or Lineart character rendering
423 * (unless a preference for this is set)
428 public void makePDBImage(ImageMaker.TYPE type)
431 makePDBImage(null, type, null,
432 BitmapImageSizing.nullBitmapImageSizing());
433 } catch (ImageOutputException ioex) {
434 Console.error("Unexpected error whilst writing "+type.toString(),ioex);
438 public void makePDBImage(File file, ImageMaker.TYPE type, String renderer,
439 BitmapImageSizing userBis) throws ImageOutputException
441 int width = getWidth();
442 int height = getHeight();
444 BitmapImageSizing bis = ImageMaker.getScaleWidthHeight(width, height,
446 float usescale = bis.scale;
447 int usewidth = bis.width;
448 int useheight = bis.height;
450 ImageWriterI writer = new ImageWriterI()
453 public void exportImage(Graphics g) throws Exception
455 Graphics2D ig2 = (Graphics2D) g;
456 ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
457 RenderingHints.VALUE_ANTIALIAS_ON);
458 if (type == TYPE.PNG && usescale > 0.0f)
460 // for a scaled image, this scales down a bigger image to give the
464 ig2.scale(1 / usescale, 1 / usescale);
468 jmb.jmolViewer.antialiased = true;
469 jmb.jmolViewer.requestRepaintAndWait("image export");
470 jmb.jmolViewer.renderScreenImage(ig2, usewidth, useheight);
473 String view = MessageManager.getString("action.view")
474 .toLowerCase(Locale.ROOT);
475 ImageExporter exporter = new ImageExporter(writer,
476 getProgressIndicator(), type, getTitle());
478 exporter.doExport(file, this, width, height, view, renderer, userBis);
483 public void showHelp_actionPerformed()
487 BrowserLauncher // BH 2018
488 .openURL("http://wiki.jmol.org");// http://jmol.sourceforge.net/docs/JmolUserGuide/");
489 } catch (Exception ex)
491 System.err.println("Show Jmol help failed with: " + ex.getMessage());
496 public void showConsole(boolean showConsole)
500 if (splitPane == null)
502 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
503 splitPane.setTopComponent(renderPanel);
504 splitPane.setBottomComponent(scriptWindow);
505 this.getContentPane().add(splitPane, BorderLayout.CENTER);
506 splitPane.setDividerLocation(getHeight() - 200);
507 scriptWindow.setVisible(true);
508 scriptWindow.validate();
509 splitPane.validate();
515 if (splitPane != null)
517 splitPane.setVisible(false);
522 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
528 class RenderPanel extends JPanel
530 final Dimension currentSize = new Dimension();
533 public void paintComponent(Graphics g)
535 getSize(currentSize);
537 if (jmb != null && jmb.hasFileLoadingError())
539 g.setColor(Color.black);
540 g.fillRect(0, 0, currentSize.width, currentSize.height);
541 g.setColor(Color.white);
542 g.setFont(new Font("Verdana", Font.BOLD, 14));
543 g.drawString(MessageManager.getString("label.error_loading_file")
544 + "...", 20, currentSize.height / 2);
545 StringBuffer sb = new StringBuffer();
547 for (int e = 0; e < jmb.getPdbCount(); e++)
549 sb.append(jmb.getPdbEntry(e).getId());
550 if (e < jmb.getPdbCount() - 1)
555 if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
558 g.drawString(sb.toString(), 20, currentSize.height / 2
559 - lines * g.getFontMetrics().getHeight());
563 else if (jmb == null || jmb.jmolViewer == null
564 || !jmb.isFinishedInit())
566 g.setColor(Color.black);
567 g.fillRect(0, 0, currentSize.width, currentSize.height);
568 g.setColor(Color.white);
569 g.setFont(new Font("Verdana", Font.BOLD, 14));
570 g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
571 20, currentSize.height / 2);
575 jmb.jmolViewer.renderScreenImage(g, currentSize.width,
582 public AAStructureBindingModel getBinding()
588 public ViewerType getViewerType()
590 return ViewerType.JMOL;
594 protected String getViewerName()