2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.5)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
20 import java.util.regex.*;
24 import javax.swing.event.*;
25 import java.awt.event.*;
28 import jalview.jbgui.GStructureViewer;
29 import jalview.api.SequenceStructureBinding;
30 import jalview.bin.Cache;
31 import jalview.datamodel.*;
33 import jalview.structure.*;
34 import jalview.datamodel.PDBEntry;
36 import jalview.schemes.*;
37 import jalview.ws.ebi.EBIFetchClient;
39 import org.jmol.api.*;
40 import org.jmol.adapter.smarter.SmarterJmolAdapter;
41 import org.jmol.popup.*;
42 import org.jmol.viewer.JmolConstants;
44 public class AppJmol extends GStructureViewer implements Runnable,
45 SequenceStructureBinding
50 ScriptWindow scriptWindow;
54 RenderPanel renderPanel;
58 Vector atomsPicked = new Vector();
60 private boolean addingStructures = false;
62 public AppJmol(String file, String id, SequenceI[] seq,
63 AlignmentPanel ap, String loadStatus, Rectangle bounds)
65 this(file, id, seq, ap, loadStatus, bounds, null);
68 public AppJmol(String file, String id, SequenceI[] seq,
69 AlignmentPanel ap, String loadStatus, Rectangle bounds,
72 PDBEntry pdbentry = new PDBEntry();
73 pdbentry.setFile(file);
75 // / TODO: check if protocol is needed to be set, and if chains are
77 jmb = new AppJmolBinding(this, new PDBEntry[]
78 { pdbentry }, new SequenceI[][]
81 jmb.setLoadingFromArchive(true);
83 this.setBounds(bounds);
84 jmb.setColourBySequence(false);
85 seqColour.setSelected(false);
87 // jalview.gui.Desktop.addInternalFrame(this, "Loading File",
88 // bounds.width,bounds.height);
90 this.addInternalFrameListener(new InternalFrameAdapter()
92 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
97 initJmol(loadStatus); // pdbentry, seq, JBPCHECK!
101 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
104 // ////////////////////////////////
105 // Is the pdb file already loaded?
106 String alreadyMapped = StructureSelectionManager
107 .getStructureSelectionManager().alreadyMappedToFile(
110 if (alreadyMapped != null)
112 int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
113 pdbentry.getId() + " is already displayed."
114 + "\nDo you want to re-use this viewer ?",
115 "Map Sequences to Visible Window: " + pdbentry.getId(),
116 JOptionPane.YES_NO_OPTION);
118 if (option == JOptionPane.YES_OPTION)
120 StructureSelectionManager.getStructureSelectionManager()
121 .setMapping(seq, chains, alreadyMapped,
122 AppletFormatAdapter.FILE);
123 if (ap.seqPanel.seqCanvas.fr != null)
125 ap.seqPanel.seqCanvas.fr.featuresAdded();
126 ap.paintAlignment(true);
129 // Now this AppJmol is mapped to new sequences. We must add them to
130 // the exisiting array
131 JInternalFrame[] frames = Desktop.instance.getAllFrames();
133 for (int i = 0; i < frames.length; i++)
135 if (frames[i] instanceof AppJmol)
137 AppJmol topJmol = ((AppJmol) frames[i]);
138 // JBPNOTE: this looks like a binding routine, rather than a gui
140 for (int pe = 0; pe < topJmol.jmb.pdbentry.length; pe++)
142 if (topJmol.jmb.pdbentry[pe].getFile().equals(alreadyMapped))
144 topJmol.jmb.addSequence(pe, seq);
154 // /////////////////////////////////
155 // Check if there are other Jmol views involving this alignment
156 // and prompt user about adding this molecule to one of them
157 Vector existingViews = getJmolsFor(ap);
158 if (existingViews.size() > 0)
160 Enumeration jm = existingViews.elements();
161 while (jm.hasMoreElements())
163 AppJmol topJmol = (AppJmol) jm.nextElement();
164 // TODO: highlight topJmol in view somehow
165 int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
166 "Do you want to add " + pdbentry.getId()
167 + " to the view called\n'" + topJmol.getTitle()
168 + "'\n", "Align to existing structure view",
169 JOptionPane.YES_NO_OPTION);
170 if (option == JOptionPane.YES_OPTION)
172 topJmol.addStructure(pdbentry, seq, chains, true);
177 // /////////////////////////////////
179 jmb = new AppJmolBinding(this, new PDBEntry[]
180 { pdbentry }, new SequenceI[][]
181 { seq }, null, null);
183 setSize(400, 400); // probably should be a configurable/dynamic default here
185 if (pdbentry.getFile() != null)
187 initJmol("load \"" + pdbentry.getFile() + "\"");
191 addingStructures = false;
192 worker = new Thread(this);
196 this.addInternalFrameListener(new InternalFrameAdapter()
198 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
207 * pdb retrieval thread.
209 private Thread worker = null;
212 * add a new structure (with associated sequences and chains) to this viewer,
213 * retrieving it if necessary first.
219 * if true, new structure(s) will be align using associated alignment
221 private void addStructure(final PDBEntry pdbentry, final SequenceI[] seq,
222 final String[] chains, final boolean b)
224 if (pdbentry.getFile() == null)
226 if (worker != null && worker.isAlive())
228 // a retrieval is in progress, wait around and add ourselves to the
230 new Thread(new Runnable()
234 while (worker != null && worker.isAlive() && _started)
238 Thread.sleep(100 + ((int) Math.random() * 100));
240 } catch (Exception e)
245 // and call ourselves again.
246 addStructure(pdbentry, seq, chains, b);
252 // otherwise, start adding the structure.
253 jmb.addSequenceAndChain(new PDBEntry[]
254 { pdbentry }, new SequenceI[][]
255 { seq }, new String[][]
257 addingStructures = true;
259 (worker = new Thread(this)).start();
263 private Vector getJmolsFor(AlignmentPanel ap2)
265 Vector otherJmols = new Vector();
266 // Now this AppJmol is mapped to new sequences. We must add them to
267 // the exisiting array
268 JInternalFrame[] frames = Desktop.instance.getAllFrames();
270 for (int i = 0; i < frames.length; i++)
272 if (frames[i] instanceof AppJmol)
274 AppJmol topJmol = ((AppJmol) frames[i]);
275 if (topJmol.ap == ap2)
277 otherJmols.addElement(topJmol);
284 void initJmol(String command)
286 jmb.setFinishedInit(false);
287 renderPanel = new RenderPanel();
288 // TODO: consider waiting until the structure/view is fully loaded before
290 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
291 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
292 getBounds().width, getBounds().height);
293 jmb.allocateViewer(renderPanel, true, "", null, null, "");
294 jmb.newJmolPopup(true, "Jmol", true);
295 jmb.evalStateCommand(command);
296 jmb.setFinishedInit(true);
299 void setChainMenuItems(Vector chains)
301 chainMenu.removeAll();
306 JMenuItem menuItem = new JMenuItem("All");
307 menuItem.addActionListener(new ActionListener()
309 public void actionPerformed(ActionEvent evt)
311 allChainsSelected = true;
312 for (int i = 0; i < chainMenu.getItemCount(); i++)
314 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
315 ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
318 allChainsSelected = false;
322 chainMenu.add(menuItem);
324 for (int c = 0; c < chains.size(); c++)
326 menuItem = new JCheckBoxMenuItem(chains.elementAt(c).toString(), true);
327 menuItem.addItemListener(new ItemListener()
329 public void itemStateChanged(ItemEvent evt)
331 if (!allChainsSelected)
336 chainMenu.add(menuItem);
340 boolean allChainsSelected = false;
342 private boolean alignAddedStructures = false;
346 Vector toshow = new Vector();
348 int mlength, p, mnum;
349 for (int i = 0; i < chainMenu.getItemCount(); i++)
351 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
353 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
354 if (item.isSelected())
356 toshow.addElement(item.getText());
360 jmb.centerViewer(toshow);
366 // TODO: check for memory leaks where instance isn't finalised because jmb
367 // holds a reference to the window
372 * state flag for PDB retrieval thread
374 private boolean _started = false;
380 // todo - record which pdbids were successfuly imported.
381 StringBuffer errormsgs = new StringBuffer(), files = new StringBuffer();
384 String[] curfiles = jmb.getPdbFile(); // files currently in viewer
385 // TODO: replace with reference fetching/transfer code (validate PDBentry
387 jalview.ws.dbsources.Pdb pdbclient = new jalview.ws.dbsources.Pdb();
388 for (int pi = 0; pi < jmb.pdbentry.length; pi++)
390 String file = jmb.pdbentry[pi].getFile();
393 // retrieve the pdb and store it locally
394 AlignmentI pdbseq = null;
397 pdbseq = pdbclient.getSequenceRecords(pdbid = jmb.pdbentry[pi]
399 } catch (OutOfMemoryError oomerror)
401 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
402 } catch (Exception ex)
404 ex.printStackTrace();
405 errormsgs.append("'" + pdbid + "'");
409 // just transfer the file name from the first sequence's first
411 jmb.pdbentry[pi].setFile(file = ((PDBEntry) pdbseq
412 .getSequenceAt(0).getPDBId().elementAt(0)).getFile());
413 files.append(" \"" + file + "\"");
417 errormsgs.append("'" + pdbid + "' ");
422 if (curfiles != null && curfiles.length > 0)
424 addingStructures = true; // already files loaded.
425 for (int c = 0; c < curfiles.length; c++)
427 if (curfiles[c].equals(file))
436 files.append(" \"" + file + "\"");
440 } catch (OutOfMemoryError oomerror)
442 new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
443 } catch (Exception ex)
445 ex.printStackTrace();
446 errormsgs.append("When retrieving pdbfiles : current was: '" + pdbid
449 if (errormsgs.length() > 0)
452 JOptionPane.showInternalMessageDialog(Desktop.desktop,
453 "The following pdb entries could not be retrieved from the PDB:\n"
454 + errormsgs.toString()
455 + "\nPlease try downloading them manually.",
456 "Couldn't load file", JOptionPane.ERROR_MESSAGE);
459 if (files.length() > 0)
461 if (!addingStructures)
466 initJmol("load FILES " + files.toString());
467 } catch (OutOfMemoryError oomerror)
469 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
470 Cache.log.debug("File locations are " + files);
471 } catch (Exception ex)
473 Cache.log.error("Couldn't open Jmol viewer!", ex);
478 StringBuffer cmd = new StringBuffer();
479 cmd.append("load APPEND ");
480 cmd.append(files.toString());
482 final String command = cmd.toString();
486 jmb.evalStateCommand(command);
487 } catch (OutOfMemoryError oomerror)
489 new OOMWarning("When trying to add structures to the Jmol viewer!",
491 Cache.log.debug("File locations are " + files);
492 } catch (Exception ex)
494 Cache.log.error("Couldn't add files to Jmol viewer!", ex);
496 if (alignAddedStructures)
498 // may need to wait around until script has finished
499 while (jmb.viewer.isScriptExecuting())
504 } catch (Exception e)
509 javax.swing.SwingUtilities.invokeLater(new Runnable()
513 jmb.superposeStructures(ap.av.getAlignment(), -1, null);
516 alignAddedStructures = false;
518 addingStructures = false;
525 public void pdbFile_actionPerformed(ActionEvent actionEvent)
527 JalviewFileChooser chooser = new JalviewFileChooser(
528 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
530 chooser.setFileView(new JalviewFileView());
531 chooser.setDialogTitle("Save PDB File");
532 chooser.setToolTipText("Save");
534 int value = chooser.showSaveDialog(this);
536 if (value == JalviewFileChooser.APPROVE_OPTION)
540 // TODO: cope with multiple PDB files in view
541 BufferedReader in = new BufferedReader(new FileReader(
542 jmb.getPdbFile()[0]));
543 File outFile = chooser.getSelectedFile();
545 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
547 while ((data = in.readLine()) != null)
549 if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
555 } catch (Exception ex)
557 ex.printStackTrace();
562 public void viewMapping_actionPerformed(ActionEvent actionEvent)
564 jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
567 for (int pdbe = 0; pdbe < jmb.pdbentry.length; pdbe++)
569 cap.appendText(StructureSelectionManager
570 .getStructureSelectionManager().printMapping(
571 jmb.pdbentry[pdbe].getFile()));
572 cap.appendText("\n");
574 } catch (OutOfMemoryError e)
577 "composing sequence-structure alignments for display in text box.",
582 jalview.gui.Desktop.addInternalFrame(cap, "PDB - Sequence Mapping",
592 public void eps_actionPerformed(ActionEvent e)
594 makePDBImage(jalview.util.ImageMaker.EPS);
603 public void png_actionPerformed(ActionEvent e)
605 makePDBImage(jalview.util.ImageMaker.PNG);
608 void makePDBImage(int type)
610 int width = getWidth();
611 int height = getHeight();
613 jalview.util.ImageMaker im;
615 if (type == jalview.util.ImageMaker.PNG)
617 im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.PNG,
618 "Make PNG image from view", width, height, null, null);
622 im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.EPS,
623 "Make EPS file from view", width, height, null,
627 if (im.getGraphics() != null)
629 Rectangle rect = new Rectangle(width, height);
630 jmb.viewer.renderScreenImage(im.getGraphics(), rect.getSize(), rect);
635 public void seqColour_actionPerformed(ActionEvent actionEvent)
637 jmb.setColourBySequence(seqColour.isSelected());
638 // Set the colour using the current view for the associated alignframe
639 jmb.colourBySequence(ap.alignFrame.viewport.showSequenceFeatures,
640 ap.alignFrame.viewport.alignment);
643 public void chainColour_actionPerformed(ActionEvent actionEvent)
645 chainColour.setSelected(true);
649 public void chargeColour_actionPerformed(ActionEvent actionEvent)
651 chargeColour.setSelected(true);
652 jmb.colourByCharge();
655 public void zappoColour_actionPerformed(ActionEvent actionEvent)
657 zappoColour.setSelected(true);
658 jmb.setJalviewColourScheme(new ZappoColourScheme());
661 public void taylorColour_actionPerformed(ActionEvent actionEvent)
663 taylorColour.setSelected(true);
664 jmb.setJalviewColourScheme(new TaylorColourScheme());
667 public void hydroColour_actionPerformed(ActionEvent actionEvent)
669 hydroColour.setSelected(true);
670 jmb.setJalviewColourScheme(new HydrophobicColourScheme());
673 public void helixColour_actionPerformed(ActionEvent actionEvent)
675 helixColour.setSelected(true);
676 jmb.setJalviewColourScheme(new HelixColourScheme());
679 public void strandColour_actionPerformed(ActionEvent actionEvent)
681 strandColour.setSelected(true);
682 jmb.setJalviewColourScheme(new StrandColourScheme());
685 public void turnColour_actionPerformed(ActionEvent actionEvent)
687 turnColour.setSelected(true);
688 jmb.setJalviewColourScheme(new TurnColourScheme());
691 public void buriedColour_actionPerformed(ActionEvent actionEvent)
693 buriedColour.setSelected(true);
694 jmb.setJalviewColourScheme(new BuriedColourScheme());
697 public void userColour_actionPerformed(ActionEvent actionEvent)
699 userColour.setSelected(true);
700 new UserDefinedColours(this, null);
703 public void backGround_actionPerformed(ActionEvent actionEvent)
705 java.awt.Color col = JColorChooser.showDialog(this,
706 "Select Background Colour", null);
709 jmb.setBackgroundColour(col);
713 public void jmolHelp_actionPerformed(ActionEvent actionEvent)
717 jalview.util.BrowserLauncher
718 .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
719 } catch (Exception ex)
724 public void showConsole(boolean showConsole)
726 if (scriptWindow == null)
727 scriptWindow = new ScriptWindow(this);
731 if (splitPane == null)
733 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
734 splitPane.setTopComponent(renderPanel);
735 splitPane.setBottomComponent(scriptWindow);
736 this.getContentPane().add(splitPane, BorderLayout.CENTER);
739 splitPane.setDividerLocation(getHeight() - 200);
740 splitPane.validate();
744 if (splitPane != null)
745 splitPane.setVisible(false);
749 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
755 class RenderPanel extends JPanel
757 final Dimension currentSize = new Dimension();
759 final Rectangle rectClip = new Rectangle();
761 public void paintComponent(Graphics g)
763 getSize(currentSize);
764 g.getClipBounds(rectClip);
766 if (jmb.fileLoadingError != null)
768 g.setColor(Color.black);
769 g.fillRect(0, 0, currentSize.width, currentSize.height);
770 g.setColor(Color.white);
771 g.setFont(new Font("Verdana", Font.BOLD, 14));
772 g.drawString("Error loading file...", 20, currentSize.height / 2);
773 StringBuffer sb = new StringBuffer();
775 for (int e = 0; e < jmb.pdbentry.length; e++)
777 sb.append(jmb.pdbentry[e].getId());
778 if (e < jmb.pdbentry.length - 1)
783 if (e == jmb.pdbentry.length - 1 || sb.length() > 20)
786 g.drawString(sb.toString(), 20, currentSize.height / 2 - lines
787 * g.getFontMetrics().getHeight());
791 else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
793 g.setColor(Color.black);
794 g.fillRect(0, 0, currentSize.width, currentSize.height);
795 g.setColor(Color.white);
796 g.setFont(new Font("Verdana", Font.BOLD, 14));
797 g.drawString("Retrieving PDB data....", 20, currentSize.height / 2);
801 jmb.viewer.renderScreenImage(g, currentSize, rectClip);
806 String viewId = null;
808 public String getViewId()
812 viewId = System.currentTimeMillis() + "." + this.hashCode();
817 public void updateTitleAndMenus()
819 if (jmb.fileLoadingError != null && jmb.fileLoadingError.length() > 0)
824 setChainMenuItems(jmb.chainNames);
825 jmb.colourBySequence(ap.av.getShowSequenceFeatures(), ap.av.alignment);
827 this.setTitle(jmb.getViewerTitle());
828 if (jmb.getPdbFile().length > 1 && jmb.sequence.length > 1)
830 jmolActionMenu.setVisible(true);
838 * jalview.jbgui.GStructureViewer#alignStructs_actionPerformed(java.awt.event
842 protected void alignStructs_actionPerformed(ActionEvent actionEvent)
847 jmb.superposeStructures(ap.av.getAlignment(), -1,
848 ap.av.getColumnSelection());
849 } catch (Exception e)
851 Cache.log.info("Couldn't align structures in alignframe "
852 + ap.alignFrame.getTitle(), e);
857 public void setJalviewColourScheme(ColourSchemeI ucs)
859 jmb.setJalviewColourScheme(ucs);