2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
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;
43 import org.openscience.jmol.app.jmolpanel.AppConsole;
45 public class AppJmol extends GStructureViewer implements Runnable,
46 SequenceStructureBinding
55 RenderPanel renderPanel;
59 Vector atomsPicked = new Vector();
61 private boolean addingStructures = false;
71 * @deprecated defaults to AppJmol(String[] files, ... , viewid);
73 public AppJmol(String file, String id, SequenceI[] seq,
74 AlignmentPanel ap, String loadStatus, Rectangle bounds)
76 this(file, id, seq, ap, loadStatus, bounds, null);
82 public AppJmol(String file, String id, SequenceI[] seq,
83 AlignmentPanel ap, String loadStatus, Rectangle bounds,
87 { file }, new String[]
88 { id }, new SequenceI[][]
89 { seq }, ap, loadStatus, bounds, viewid);
102 public AppJmol(String[] files, String[] ids, SequenceI[][] seqs,
103 AlignmentPanel ap, String loadStatus, Rectangle bounds,
106 PDBEntry[] pdbentrys = new PDBEntry[files.length];
107 for (int i = 0; i < pdbentrys.length; i++)
109 PDBEntry pdbentry = new PDBEntry();
110 pdbentry.setFile(files[i]);
111 pdbentry.setId(ids[i]);
112 pdbentrys[i] = pdbentry;
114 // / TODO: check if protocol is needed to be set, and if chains are
116 jmb = new AppJmolBinding(this, pdbentrys, seqs, null, null);
118 jmb.setLoadingFromArchive(true);
120 this.setBounds(bounds);
121 jmb.setColourBySequence(false);
122 seqColour.setSelected(false);
124 // jalview.gui.Desktop.addInternalFrame(this, "Loading File",
125 // bounds.width,bounds.height);
127 this.addInternalFrameListener(new InternalFrameAdapter()
129 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
134 initJmol(loadStatus); // pdbentry, seq, JBPCHECK!
138 IProgressIndicator progressBar = null;
140 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
143 progressBar = ap.alignFrame;
144 // ////////////////////////////////
145 // Is the pdb file already loaded?
146 String alreadyMapped = StructureSelectionManager
147 .getStructureSelectionManager().alreadyMappedToFile(
150 if (alreadyMapped != null)
152 int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
153 pdbentry.getId() + " is already displayed."
154 + "\nDo you want to re-use this viewer ?",
155 "Map Sequences to Visible Window: " + pdbentry.getId(),
156 JOptionPane.YES_NO_OPTION);
158 if (option == JOptionPane.YES_OPTION)
160 StructureSelectionManager.getStructureSelectionManager()
161 .setMapping(seq, chains, alreadyMapped,
162 AppletFormatAdapter.FILE);
163 if (ap.seqPanel.seqCanvas.fr != null)
165 ap.seqPanel.seqCanvas.fr.featuresAdded();
166 ap.paintAlignment(true);
169 // Now this AppJmol is mapped to new sequences. We must add them to
170 // the exisiting array
171 JInternalFrame[] frames = Desktop.instance.getAllFrames();
173 for (int i = 0; i < frames.length; i++)
175 if (frames[i] instanceof AppJmol)
177 AppJmol topJmol = ((AppJmol) frames[i]);
178 // JBPNOTE: this looks like a binding routine, rather than a gui
180 for (int pe = 0; pe < topJmol.jmb.pdbentry.length; pe++)
182 if (topJmol.jmb.pdbentry[pe].getFile().equals(alreadyMapped))
184 topJmol.jmb.addSequence(pe, seq);
194 // /////////////////////////////////
195 // Check if there are other Jmol views involving this alignment
196 // and prompt user about adding this molecule to one of them
197 Vector existingViews = getJmolsFor(ap);
198 if (existingViews.size() > 0)
200 Enumeration jm = existingViews.elements();
201 while (jm.hasMoreElements())
203 AppJmol topJmol = (AppJmol) jm.nextElement();
204 // TODO: highlight topJmol in view somehow
205 int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
206 "Do you want to add " + pdbentry.getId()
207 + " to the view called\n'" + topJmol.getTitle()
208 + "'\n", "Align to existing structure view",
209 JOptionPane.YES_NO_OPTION);
210 if (option == JOptionPane.YES_OPTION)
212 topJmol.addStructure(pdbentry, seq, chains, true, ap.alignFrame);
217 // /////////////////////////////////
219 jmb = new AppJmolBinding(this, new PDBEntry[]
220 { pdbentry }, new SequenceI[][]
221 { seq }, null, null);
223 setSize(400, 400); // probably should be a configurable/dynamic default here
225 if (pdbentry.getFile() != null)
227 initJmol("load \"" + pdbentry.getFile() + "\"");
231 addingStructures = false;
232 worker = new Thread(this);
236 this.addInternalFrameListener(new InternalFrameAdapter()
238 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
247 * pdb retrieval thread.
249 private Thread worker = null;
252 * add a new structure (with associated sequences and chains) to this viewer,
253 * retrieving it if necessary first.
260 * if true, new structure(s) will be align using associated alignment
262 private void addStructure(final PDBEntry pdbentry, final SequenceI[] seq,
263 final String[] chains, final boolean b,
264 final IProgressIndicator alignFrame)
266 if (pdbentry.getFile() == null)
268 if (worker != null && worker.isAlive())
270 // a retrieval is in progress, wait around and add ourselves to the
272 new Thread(new Runnable()
276 while (worker != null && worker.isAlive() && _started)
280 Thread.sleep(100 + ((int) Math.random() * 100));
282 } catch (Exception e)
287 // and call ourselves again.
288 addStructure(pdbentry, seq, chains, b, alignFrame);
294 // otherwise, start adding the structure.
295 jmb.addSequenceAndChain(new PDBEntry[]
296 { pdbentry }, new SequenceI[][]
297 { seq }, new String[][]
299 addingStructures = true;
301 alignAddedStructures = b;
302 progressBar = alignFrame; // visual indication happens on caller frame.
303 (worker = new Thread(this)).start();
307 private Vector getJmolsFor(AlignmentPanel ap2)
309 Vector otherJmols = new Vector();
310 // Now this AppJmol is mapped to new sequences. We must add them to
311 // the exisiting array
312 JInternalFrame[] frames = Desktop.instance.getAllFrames();
314 for (int i = 0; i < frames.length; i++)
316 if (frames[i] instanceof AppJmol)
318 AppJmol topJmol = ((AppJmol) frames[i]);
319 if (topJmol.ap == ap2)
321 otherJmols.addElement(topJmol);
328 void initJmol(String command)
330 jmb.setFinishedInit(false);
331 renderPanel = new RenderPanel();
332 // TODO: consider waiting until the structure/view is fully loaded before
334 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
335 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
336 getBounds().width, getBounds().height);
337 if (scriptWindow == null)
339 BorderLayout bl = new BorderLayout();
342 scriptWindow = new JPanel(bl);
343 scriptWindow.setVisible(false);
346 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
348 jmb.newJmolPopup(true, "Jmol", true);
349 jmb.evalStateCommand(command);
350 jmb.setFinishedInit(true);
353 void setChainMenuItems(Vector chains)
355 chainMenu.removeAll();
360 JMenuItem menuItem = new JMenuItem("All");
361 menuItem.addActionListener(new ActionListener()
363 public void actionPerformed(ActionEvent evt)
365 allChainsSelected = true;
366 for (int i = 0; i < chainMenu.getItemCount(); i++)
368 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
369 ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
372 allChainsSelected = false;
376 chainMenu.add(menuItem);
378 for (int c = 0; c < chains.size(); c++)
380 menuItem = new JCheckBoxMenuItem(chains.elementAt(c).toString(), true);
381 menuItem.addItemListener(new ItemListener()
383 public void itemStateChanged(ItemEvent evt)
385 if (!allChainsSelected)
390 chainMenu.add(menuItem);
394 boolean allChainsSelected = false;
396 private boolean alignAddedStructures = false;
400 Vector toshow = new Vector();
402 int mlength, p, mnum;
403 for (int i = 0; i < chainMenu.getItemCount(); i++)
405 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
407 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
408 if (item.isSelected())
410 toshow.addElement(item.getText());
414 jmb.centerViewer(toshow);
421 // TODO: check for memory leaks where instance isn't finalised because jmb
422 // holds a reference to the window
427 * state flag for PDB retrieval thread
429 private boolean _started = false;
435 // todo - record which pdbids were successfuly imported.
436 StringBuffer errormsgs = new StringBuffer(), files = new StringBuffer();
439 String[] curfiles = jmb.getPdbFile(); // files currently in viewer
440 // TODO: replace with reference fetching/transfer code (validate PDBentry
442 jalview.ws.dbsources.Pdb pdbclient = new jalview.ws.dbsources.Pdb();
443 for (int pi = 0; pi < jmb.pdbentry.length; pi++)
445 String file = jmb.pdbentry[pi].getFile();
448 // retrieve the pdb and store it locally
449 AlignmentI pdbseq = null;
450 pdbid = jmb.pdbentry[pi].getId();
451 long hdl = pdbid.hashCode() - System.currentTimeMillis();
452 if (progressBar != null)
454 progressBar.setProgressBar("Fetching PDB " + pdbid, hdl);
458 pdbseq = pdbclient.getSequenceRecords(pdbid = jmb.pdbentry[pi]
460 } catch (OutOfMemoryError oomerror)
462 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
463 } catch (Exception ex)
465 ex.printStackTrace();
466 errormsgs.append("'" + pdbid + "'");
468 if (progressBar != null)
470 progressBar.setProgressBar("Finished.", hdl);
474 // just transfer the file name from the first sequence's first
476 jmb.pdbentry[pi].setFile(file = ((PDBEntry) pdbseq
477 .getSequenceAt(0).getPDBId().elementAt(0)).getFile());
478 files.append(" \"" + file + "\"");
482 errormsgs.append("'" + pdbid + "' ");
487 if (curfiles != null && curfiles.length > 0)
489 addingStructures = true; // already files loaded.
490 for (int c = 0; c < curfiles.length; c++)
492 if (curfiles[c].equals(file))
501 files.append(" \"" + file + "\"");
505 } catch (OutOfMemoryError oomerror)
507 new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
508 } catch (Exception ex)
510 ex.printStackTrace();
511 errormsgs.append("When retrieving pdbfiles : current was: '" + pdbid
514 if (errormsgs.length() > 0)
517 JOptionPane.showInternalMessageDialog(Desktop.desktop,
518 "The following pdb entries could not be retrieved from the PDB:\n"
519 + errormsgs.toString()
520 + "\nPlease try downloading them manually.",
521 "Couldn't load file", JOptionPane.ERROR_MESSAGE);
524 if (files.length() > 0)
526 if (!addingStructures)
531 initJmol("load FILES " + files.toString());
532 } catch (OutOfMemoryError oomerror)
534 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
535 Cache.log.debug("File locations are " + files);
536 } catch (Exception ex)
538 Cache.log.error("Couldn't open Jmol viewer!", ex);
543 StringBuffer cmd = new StringBuffer();
544 cmd.append("loadingJalviewdata=true\nload APPEND ");
545 cmd.append(files.toString());
546 cmd.append("\nloadingJalviewdata=null");
547 final String command = cmd.toString();
549 long lastnotify = jmb.getLoadNotifiesHandled();
552 jmb.evalStateCommand(command);
553 } catch (OutOfMemoryError oomerror)
556 "When trying to add structures to the Jmol viewer!",
558 Cache.log.debug("File locations are " + files);
559 } catch (Exception ex)
561 Cache.log.error("Couldn't add files to Jmol viewer!", ex);
563 // need to wait around until script has finished
564 while (lastnotify >= jmb.getLoadNotifiesHandled())
570 } catch (Exception e)
574 // refresh the sequence colours for the new structure(s)
575 jmb.updateColours(ap);
576 // do superposition if asked to
577 if (alignAddedStructures)
579 javax.swing.SwingUtilities.invokeLater(new Runnable()
583 jmb.superposeStructures(ap.av.getAlignment(), -1, null);
586 alignAddedStructures = false;
588 addingStructures = false;
595 public void pdbFile_actionPerformed(ActionEvent actionEvent)
597 JalviewFileChooser chooser = new JalviewFileChooser(
598 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
600 chooser.setFileView(new JalviewFileView());
601 chooser.setDialogTitle("Save PDB File");
602 chooser.setToolTipText("Save");
604 int value = chooser.showSaveDialog(this);
606 if (value == JalviewFileChooser.APPROVE_OPTION)
610 // TODO: cope with multiple PDB files in view
611 BufferedReader in = new BufferedReader(new FileReader(
612 jmb.getPdbFile()[0]));
613 File outFile = chooser.getSelectedFile();
615 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
617 while ((data = in.readLine()) != null)
619 if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
625 } catch (Exception ex)
627 ex.printStackTrace();
632 public void viewMapping_actionPerformed(ActionEvent actionEvent)
634 jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
637 for (int pdbe = 0; pdbe < jmb.pdbentry.length; pdbe++)
639 cap.appendText(StructureSelectionManager
640 .getStructureSelectionManager().printMapping(
641 jmb.pdbentry[pdbe].getFile()));
642 cap.appendText("\n");
644 } catch (OutOfMemoryError e)
647 "composing sequence-structure alignments for display in text box.",
652 jalview.gui.Desktop.addInternalFrame(cap, "PDB - Sequence Mapping",
662 public void eps_actionPerformed(ActionEvent e)
664 makePDBImage(jalview.util.ImageMaker.EPS);
673 public void png_actionPerformed(ActionEvent e)
675 makePDBImage(jalview.util.ImageMaker.PNG);
678 void makePDBImage(int type)
680 int width = getWidth();
681 int height = getHeight();
683 jalview.util.ImageMaker im;
685 if (type == jalview.util.ImageMaker.PNG)
687 im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.PNG,
688 "Make PNG image from view", width, height, null, null);
692 im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.EPS,
693 "Make EPS file from view", width, height, null,
697 if (im.getGraphics() != null)
699 Rectangle rect = new Rectangle(width, height);
700 jmb.viewer.renderScreenImage(im.getGraphics(), rect.getSize(), rect);
705 public void seqColour_actionPerformed(ActionEvent actionEvent)
707 jmb.setColourBySequence(seqColour.isSelected());
708 // Set the colour using the current view for the associated alignframe
709 jmb.colourBySequence(ap.alignFrame.viewport.showSequenceFeatures,
710 ap.alignFrame.viewport.alignment);
713 public void chainColour_actionPerformed(ActionEvent actionEvent)
715 chainColour.setSelected(true);
719 public void chargeColour_actionPerformed(ActionEvent actionEvent)
721 chargeColour.setSelected(true);
722 jmb.colourByCharge();
725 public void zappoColour_actionPerformed(ActionEvent actionEvent)
727 zappoColour.setSelected(true);
728 jmb.setJalviewColourScheme(new ZappoColourScheme());
731 public void taylorColour_actionPerformed(ActionEvent actionEvent)
733 taylorColour.setSelected(true);
734 jmb.setJalviewColourScheme(new TaylorColourScheme());
737 public void hydroColour_actionPerformed(ActionEvent actionEvent)
739 hydroColour.setSelected(true);
740 jmb.setJalviewColourScheme(new HydrophobicColourScheme());
743 public void helixColour_actionPerformed(ActionEvent actionEvent)
745 helixColour.setSelected(true);
746 jmb.setJalviewColourScheme(new HelixColourScheme());
749 public void strandColour_actionPerformed(ActionEvent actionEvent)
751 strandColour.setSelected(true);
752 jmb.setJalviewColourScheme(new StrandColourScheme());
755 public void turnColour_actionPerformed(ActionEvent actionEvent)
757 turnColour.setSelected(true);
758 jmb.setJalviewColourScheme(new TurnColourScheme());
761 public void buriedColour_actionPerformed(ActionEvent actionEvent)
763 buriedColour.setSelected(true);
764 jmb.setJalviewColourScheme(new BuriedColourScheme());
767 public void userColour_actionPerformed(ActionEvent actionEvent)
769 userColour.setSelected(true);
770 new UserDefinedColours(this, null);
773 public void backGround_actionPerformed(ActionEvent actionEvent)
775 java.awt.Color col = JColorChooser.showDialog(this,
776 "Select Background Colour", null);
779 jmb.setBackgroundColour(col);
783 public void jmolHelp_actionPerformed(ActionEvent actionEvent)
787 jalview.util.BrowserLauncher
788 .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
789 } catch (Exception ex)
794 public void showConsole(boolean showConsole)
799 if (splitPane == null)
801 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
802 splitPane.setTopComponent(renderPanel);
803 splitPane.setBottomComponent(scriptWindow);
804 this.getContentPane().add(splitPane, BorderLayout.CENTER);
805 splitPane.setDividerLocation(getHeight() - 200);
806 scriptWindow.setVisible(true);
807 scriptWindow.validate();
808 splitPane.validate();
814 if (splitPane != null)
816 splitPane.setVisible(false);
821 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
827 class RenderPanel extends JPanel
829 final Dimension currentSize = new Dimension();
831 final Rectangle rectClip = new Rectangle();
833 public void paintComponent(Graphics g)
835 getSize(currentSize);
836 g.getClipBounds(rectClip);
838 if (jmb.fileLoadingError != null)
840 g.setColor(Color.black);
841 g.fillRect(0, 0, currentSize.width, currentSize.height);
842 g.setColor(Color.white);
843 g.setFont(new Font("Verdana", Font.BOLD, 14));
844 g.drawString("Error loading file...", 20, currentSize.height / 2);
845 StringBuffer sb = new StringBuffer();
847 for (int e = 0; e < jmb.pdbentry.length; e++)
849 sb.append(jmb.pdbentry[e].getId());
850 if (e < jmb.pdbentry.length - 1)
855 if (e == jmb.pdbentry.length - 1 || sb.length() > 20)
858 g.drawString(sb.toString(), 20, currentSize.height / 2 - lines
859 * g.getFontMetrics().getHeight());
863 else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
865 g.setColor(Color.black);
866 g.fillRect(0, 0, currentSize.width, currentSize.height);
867 g.setColor(Color.white);
868 g.setFont(new Font("Verdana", Font.BOLD, 14));
869 g.drawString("Retrieving PDB data....", 20, currentSize.height / 2);
873 jmb.viewer.renderScreenImage(g, currentSize, rectClip);
878 String viewId = null;
880 public String getViewId()
884 viewId = System.currentTimeMillis() + "." + this.hashCode();
889 public void updateTitleAndMenus()
891 if (jmb.fileLoadingError != null && jmb.fileLoadingError.length() > 0)
896 setChainMenuItems(jmb.chainNames);
897 jmb.colourBySequence(ap.av.getShowSequenceFeatures(), ap.av.alignment);
899 this.setTitle(jmb.getViewerTitle());
900 if (jmb.getPdbFile().length > 1 && jmb.sequence.length > 1)
902 jmolActionMenu.setVisible(true);
910 * jalview.jbgui.GStructureViewer#alignStructs_actionPerformed(java.awt.event
914 protected void alignStructs_actionPerformed(ActionEvent actionEvent)
919 jmb.superposeStructures(ap.av.getAlignment(), -1,
920 ap.av.getColumnSelection());
921 } catch (Exception e)
923 Cache.log.info("Couldn't align structures in alignframe "
924 + ap.alignFrame.getTitle(), e);
929 public void setJalviewColourScheme(ColourSchemeI ucs)
931 jmb.setJalviewColourScheme(ucs);