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;
70 * @deprecated defaults to AppJmol(String[] files, ... , viewid);
72 public AppJmol(String file, String id, SequenceI[] seq,
73 AlignmentPanel ap, String loadStatus, Rectangle bounds)
75 this(file, id, seq, ap, loadStatus, bounds, null);
81 public AppJmol(String file, String id, SequenceI[] seq,
82 AlignmentPanel ap, String loadStatus, Rectangle bounds,
86 { file }, new String[]
87 { id }, new SequenceI[][]
88 { seq }, ap, loadStatus, bounds, viewid);
101 public AppJmol(String[] files, String[] ids, SequenceI[][] seqs,
102 AlignmentPanel ap, String loadStatus, Rectangle bounds,
105 PDBEntry[] pdbentrys = new PDBEntry[files.length];
106 for (int i = 0; i < pdbentrys.length; i++)
108 PDBEntry pdbentry = new PDBEntry();
109 pdbentry.setFile(files[i]);
110 pdbentry.setId(ids[i]);
111 pdbentrys[i] = pdbentry;
113 // / TODO: check if protocol is needed to be set, and if chains are
115 jmb = new AppJmolBinding(this, pdbentrys, seqs, null, null);
117 jmb.setLoadingFromArchive(true);
119 this.setBounds(bounds);
120 jmb.setColourBySequence(false);
121 seqColour.setSelected(false);
123 // jalview.gui.Desktop.addInternalFrame(this, "Loading File",
124 // bounds.width,bounds.height);
126 this.addInternalFrameListener(new InternalFrameAdapter()
128 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
133 initJmol(loadStatus); // pdbentry, seq, JBPCHECK!
137 IProgressIndicator progressBar = null;
139 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
142 progressBar = ap.alignFrame;
143 // ////////////////////////////////
144 // Is the pdb file already loaded?
145 String alreadyMapped = StructureSelectionManager
146 .getStructureSelectionManager().alreadyMappedToFile(
149 if (alreadyMapped != null)
151 int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
152 pdbentry.getId() + " is already displayed."
153 + "\nDo you want to re-use this viewer ?",
154 "Map Sequences to Visible Window: " + pdbentry.getId(),
155 JOptionPane.YES_NO_OPTION);
157 if (option == JOptionPane.YES_OPTION)
159 StructureSelectionManager.getStructureSelectionManager()
160 .setMapping(seq, chains, alreadyMapped,
161 AppletFormatAdapter.FILE);
162 if (ap.seqPanel.seqCanvas.fr != null)
164 ap.seqPanel.seqCanvas.fr.featuresAdded();
165 ap.paintAlignment(true);
168 // Now this AppJmol is mapped to new sequences. We must add them to
169 // the exisiting array
170 JInternalFrame[] frames = Desktop.instance.getAllFrames();
172 for (int i = 0; i < frames.length; i++)
174 if (frames[i] instanceof AppJmol)
176 AppJmol topJmol = ((AppJmol) frames[i]);
177 // JBPNOTE: this looks like a binding routine, rather than a gui
179 for (int pe = 0; pe < topJmol.jmb.pdbentry.length; pe++)
181 if (topJmol.jmb.pdbentry[pe].getFile().equals(alreadyMapped))
183 topJmol.jmb.addSequence(pe, seq);
193 // /////////////////////////////////
194 // Check if there are other Jmol views involving this alignment
195 // and prompt user about adding this molecule to one of them
196 Vector existingViews = getJmolsFor(ap);
197 if (existingViews.size() > 0)
199 Enumeration jm = existingViews.elements();
200 while (jm.hasMoreElements())
202 AppJmol topJmol = (AppJmol) jm.nextElement();
203 // TODO: highlight topJmol in view somehow
204 int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
205 "Do you want to add " + pdbentry.getId()
206 + " to the view called\n'" + topJmol.getTitle()
207 + "'\n", "Align to existing structure view",
208 JOptionPane.YES_NO_OPTION);
209 if (option == JOptionPane.YES_OPTION)
211 topJmol.addStructure(pdbentry, seq, chains, true, ap.alignFrame);
216 // /////////////////////////////////
218 jmb = new AppJmolBinding(this, new PDBEntry[]
219 { pdbentry }, new SequenceI[][]
220 { seq }, null, null);
222 setSize(400, 400); // probably should be a configurable/dynamic default here
224 if (pdbentry.getFile() != null)
226 initJmol("load \"" + pdbentry.getFile() + "\"");
230 addingStructures = false;
231 worker = new Thread(this);
235 this.addInternalFrameListener(new InternalFrameAdapter()
237 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
246 * pdb retrieval thread.
248 private Thread worker = null;
251 * add a new structure (with associated sequences and chains) to this viewer,
252 * retrieving it if necessary first.
259 * if true, new structure(s) will be align using associated alignment
261 private void addStructure(final PDBEntry pdbentry, final SequenceI[] seq,
262 final String[] chains, final boolean b, final IProgressIndicator alignFrame)
264 if (pdbentry.getFile() == null)
266 if (worker != null && worker.isAlive())
268 // a retrieval is in progress, wait around and add ourselves to the
270 new Thread(new Runnable()
274 while (worker != null && worker.isAlive() && _started)
278 Thread.sleep(100 + ((int) Math.random() * 100));
280 } catch (Exception e)
285 // and call ourselves again.
286 addStructure(pdbentry, seq, chains, b, alignFrame);
292 // otherwise, start adding the structure.
293 jmb.addSequenceAndChain(new PDBEntry[]
294 { pdbentry }, new SequenceI[][]
295 { seq }, new String[][]
297 addingStructures = true;
299 alignAddedStructures = b;
300 progressBar = alignFrame; // visual indication happens on caller frame.
301 (worker = new Thread(this)).start();
305 private Vector getJmolsFor(AlignmentPanel ap2)
307 Vector otherJmols = new Vector();
308 // Now this AppJmol is mapped to new sequences. We must add them to
309 // the exisiting array
310 JInternalFrame[] frames = Desktop.instance.getAllFrames();
312 for (int i = 0; i < frames.length; i++)
314 if (frames[i] instanceof AppJmol)
316 AppJmol topJmol = ((AppJmol) frames[i]);
317 if (topJmol.ap == ap2)
319 otherJmols.addElement(topJmol);
326 void initJmol(String command)
328 jmb.setFinishedInit(false);
329 renderPanel = new RenderPanel();
330 // TODO: consider waiting until the structure/view is fully loaded before
332 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
333 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
334 getBounds().width, getBounds().height);
335 jmb.allocateViewer(renderPanel, true, "", null, null, "");
336 jmb.newJmolPopup(true, "Jmol", true);
337 jmb.evalStateCommand(command);
338 jmb.setFinishedInit(true);
341 void setChainMenuItems(Vector chains)
343 chainMenu.removeAll();
348 JMenuItem menuItem = new JMenuItem("All");
349 menuItem.addActionListener(new ActionListener()
351 public void actionPerformed(ActionEvent evt)
353 allChainsSelected = true;
354 for (int i = 0; i < chainMenu.getItemCount(); i++)
356 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
357 ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
360 allChainsSelected = false;
364 chainMenu.add(menuItem);
366 for (int c = 0; c < chains.size(); c++)
368 menuItem = new JCheckBoxMenuItem(chains.elementAt(c).toString(), true);
369 menuItem.addItemListener(new ItemListener()
371 public void itemStateChanged(ItemEvent evt)
373 if (!allChainsSelected)
378 chainMenu.add(menuItem);
382 boolean allChainsSelected = false;
384 private boolean alignAddedStructures = false;
388 Vector toshow = new Vector();
390 int mlength, p, mnum;
391 for (int i = 0; i < chainMenu.getItemCount(); i++)
393 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
395 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
396 if (item.isSelected())
398 toshow.addElement(item.getText());
402 jmb.centerViewer(toshow);
408 // TODO: check for memory leaks where instance isn't finalised because jmb
409 // holds a reference to the window
414 * state flag for PDB retrieval thread
416 private boolean _started = false;
422 // todo - record which pdbids were successfuly imported.
423 StringBuffer errormsgs = new StringBuffer(), files = new StringBuffer();
426 String[] curfiles = jmb.getPdbFile(); // files currently in viewer
427 // TODO: replace with reference fetching/transfer code (validate PDBentry
429 jalview.ws.dbsources.Pdb pdbclient = new jalview.ws.dbsources.Pdb();
430 for (int pi = 0; pi < jmb.pdbentry.length; pi++)
432 String file = jmb.pdbentry[pi].getFile();
435 // retrieve the pdb and store it locally
436 AlignmentI pdbseq = null;
437 pdbid = jmb.pdbentry[pi].getId();
438 long hdl=pdbid.hashCode()-System.currentTimeMillis();
439 if (progressBar != null)
441 progressBar.setProgressBar("Fetching PDB " + pdbid,
446 pdbseq = pdbclient.getSequenceRecords(pdbid = jmb.pdbentry[pi]
448 } catch (OutOfMemoryError oomerror)
450 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
451 } catch (Exception ex)
453 ex.printStackTrace();
454 errormsgs.append("'" + pdbid + "'");
456 if (progressBar != null)
458 progressBar.setProgressBar("Finished.", hdl);
462 // just transfer the file name from the first sequence's first
464 jmb.pdbentry[pi].setFile(file = ((PDBEntry) pdbseq
465 .getSequenceAt(0).getPDBId().elementAt(0)).getFile());
466 files.append(" \"" + file + "\"");
470 errormsgs.append("'" + pdbid + "' ");
475 if (curfiles != null && curfiles.length > 0)
477 addingStructures = true; // already files loaded.
478 for (int c = 0; c < curfiles.length; c++)
480 if (curfiles[c].equals(file))
489 files.append(" \"" + file + "\"");
493 } catch (OutOfMemoryError oomerror)
495 new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
496 } catch (Exception ex)
498 ex.printStackTrace();
499 errormsgs.append("When retrieving pdbfiles : current was: '" + pdbid
502 if (errormsgs.length() > 0)
505 JOptionPane.showInternalMessageDialog(Desktop.desktop,
506 "The following pdb entries could not be retrieved from the PDB:\n"
507 + errormsgs.toString()
508 + "\nPlease try downloading them manually.",
509 "Couldn't load file", JOptionPane.ERROR_MESSAGE);
512 if (files.length() > 0)
514 if (!addingStructures)
519 initJmol("load FILES " + files.toString());
520 } catch (OutOfMemoryError oomerror)
522 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
523 Cache.log.debug("File locations are " + files);
524 } catch (Exception ex)
526 Cache.log.error("Couldn't open Jmol viewer!", ex);
531 StringBuffer cmd = new StringBuffer();
532 cmd.append("loadingJalviewdata=true\nload APPEND ");
533 cmd.append(files.toString());
534 cmd.append("\nloadingJalviewdata=null");
535 final String command = cmd.toString();
539 jmb.evalStateCommand(command);
540 } catch (OutOfMemoryError oomerror)
543 "When trying to add structures to the Jmol viewer!",
545 Cache.log.debug("File locations are " + files);
546 } catch (Exception ex)
548 Cache.log.error("Couldn't add files to Jmol viewer!", ex);
550 long lastnotify=jmb.getLoadNotifiesHandled();
551 // need to wait around until script has finished
552 while (lastnotify>=jmb.getLoadNotifiesHandled());
557 } catch (Exception e)
561 // refresh the sequence colours for the new structure(s)
562 jmb.updateColours(ap);
563 // do superposition if asked to
564 if (alignAddedStructures)
566 javax.swing.SwingUtilities.invokeLater(new Runnable()
570 jmb.superposeStructures(ap.av.getAlignment(), -1, null);
573 alignAddedStructures = false;
575 addingStructures = false;
582 public void pdbFile_actionPerformed(ActionEvent actionEvent)
584 JalviewFileChooser chooser = new JalviewFileChooser(
585 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
587 chooser.setFileView(new JalviewFileView());
588 chooser.setDialogTitle("Save PDB File");
589 chooser.setToolTipText("Save");
591 int value = chooser.showSaveDialog(this);
593 if (value == JalviewFileChooser.APPROVE_OPTION)
597 // TODO: cope with multiple PDB files in view
598 BufferedReader in = new BufferedReader(new FileReader(
599 jmb.getPdbFile()[0]));
600 File outFile = chooser.getSelectedFile();
602 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
604 while ((data = in.readLine()) != null)
606 if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
612 } catch (Exception ex)
614 ex.printStackTrace();
619 public void viewMapping_actionPerformed(ActionEvent actionEvent)
621 jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
624 for (int pdbe = 0; pdbe < jmb.pdbentry.length; pdbe++)
626 cap.appendText(StructureSelectionManager
627 .getStructureSelectionManager().printMapping(
628 jmb.pdbentry[pdbe].getFile()));
629 cap.appendText("\n");
631 } catch (OutOfMemoryError e)
634 "composing sequence-structure alignments for display in text box.",
639 jalview.gui.Desktop.addInternalFrame(cap, "PDB - Sequence Mapping",
649 public void eps_actionPerformed(ActionEvent e)
651 makePDBImage(jalview.util.ImageMaker.EPS);
660 public void png_actionPerformed(ActionEvent e)
662 makePDBImage(jalview.util.ImageMaker.PNG);
665 void makePDBImage(int type)
667 int width = getWidth();
668 int height = getHeight();
670 jalview.util.ImageMaker im;
672 if (type == jalview.util.ImageMaker.PNG)
674 im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.PNG,
675 "Make PNG image from view", width, height, null, null);
679 im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.EPS,
680 "Make EPS file from view", width, height, null,
684 if (im.getGraphics() != null)
686 Rectangle rect = new Rectangle(width, height);
687 jmb.viewer.renderScreenImage(im.getGraphics(), rect.getSize(), rect);
692 public void seqColour_actionPerformed(ActionEvent actionEvent)
694 jmb.setColourBySequence(seqColour.isSelected());
695 // Set the colour using the current view for the associated alignframe
696 jmb.colourBySequence(ap.alignFrame.viewport.showSequenceFeatures,
697 ap.alignFrame.viewport.alignment);
700 public void chainColour_actionPerformed(ActionEvent actionEvent)
702 chainColour.setSelected(true);
706 public void chargeColour_actionPerformed(ActionEvent actionEvent)
708 chargeColour.setSelected(true);
709 jmb.colourByCharge();
712 public void zappoColour_actionPerformed(ActionEvent actionEvent)
714 zappoColour.setSelected(true);
715 jmb.setJalviewColourScheme(new ZappoColourScheme());
718 public void taylorColour_actionPerformed(ActionEvent actionEvent)
720 taylorColour.setSelected(true);
721 jmb.setJalviewColourScheme(new TaylorColourScheme());
724 public void hydroColour_actionPerformed(ActionEvent actionEvent)
726 hydroColour.setSelected(true);
727 jmb.setJalviewColourScheme(new HydrophobicColourScheme());
730 public void helixColour_actionPerformed(ActionEvent actionEvent)
732 helixColour.setSelected(true);
733 jmb.setJalviewColourScheme(new HelixColourScheme());
736 public void strandColour_actionPerformed(ActionEvent actionEvent)
738 strandColour.setSelected(true);
739 jmb.setJalviewColourScheme(new StrandColourScheme());
742 public void turnColour_actionPerformed(ActionEvent actionEvent)
744 turnColour.setSelected(true);
745 jmb.setJalviewColourScheme(new TurnColourScheme());
748 public void buriedColour_actionPerformed(ActionEvent actionEvent)
750 buriedColour.setSelected(true);
751 jmb.setJalviewColourScheme(new BuriedColourScheme());
754 public void userColour_actionPerformed(ActionEvent actionEvent)
756 userColour.setSelected(true);
757 new UserDefinedColours(this, null);
760 public void backGround_actionPerformed(ActionEvent actionEvent)
762 java.awt.Color col = JColorChooser.showDialog(this,
763 "Select Background Colour", null);
766 jmb.setBackgroundColour(col);
770 public void jmolHelp_actionPerformed(ActionEvent actionEvent)
774 jalview.util.BrowserLauncher
775 .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
776 } catch (Exception ex)
781 public void showConsole(boolean showConsole)
783 if (scriptWindow == null)
784 scriptWindow = new ScriptWindow(this);
788 if (splitPane == null)
790 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
791 splitPane.setTopComponent(renderPanel);
792 splitPane.setBottomComponent(scriptWindow);
793 this.getContentPane().add(splitPane, BorderLayout.CENTER);
796 splitPane.setDividerLocation(getHeight() - 200);
797 splitPane.validate();
801 if (splitPane != null)
802 splitPane.setVisible(false);
806 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
812 class RenderPanel extends JPanel
814 final Dimension currentSize = new Dimension();
816 final Rectangle rectClip = new Rectangle();
818 public void paintComponent(Graphics g)
820 getSize(currentSize);
821 g.getClipBounds(rectClip);
823 if (jmb.fileLoadingError != null)
825 g.setColor(Color.black);
826 g.fillRect(0, 0, currentSize.width, currentSize.height);
827 g.setColor(Color.white);
828 g.setFont(new Font("Verdana", Font.BOLD, 14));
829 g.drawString("Error loading file...", 20, currentSize.height / 2);
830 StringBuffer sb = new StringBuffer();
832 for (int e = 0; e < jmb.pdbentry.length; e++)
834 sb.append(jmb.pdbentry[e].getId());
835 if (e < jmb.pdbentry.length - 1)
840 if (e == jmb.pdbentry.length - 1 || sb.length() > 20)
843 g.drawString(sb.toString(), 20, currentSize.height / 2 - lines
844 * g.getFontMetrics().getHeight());
848 else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
850 g.setColor(Color.black);
851 g.fillRect(0, 0, currentSize.width, currentSize.height);
852 g.setColor(Color.white);
853 g.setFont(new Font("Verdana", Font.BOLD, 14));
854 g.drawString("Retrieving PDB data....", 20, currentSize.height / 2);
858 jmb.viewer.renderScreenImage(g, currentSize, rectClip);
863 String viewId = null;
865 public String getViewId()
869 viewId = System.currentTimeMillis() + "." + this.hashCode();
874 public void updateTitleAndMenus()
876 if (jmb.fileLoadingError != null && jmb.fileLoadingError.length() > 0)
881 setChainMenuItems(jmb.chainNames);
882 jmb.colourBySequence(ap.av.getShowSequenceFeatures(), ap.av.alignment);
884 this.setTitle(jmb.getViewerTitle());
885 if (jmb.getPdbFile().length > 1 && jmb.sequence.length > 1)
887 jmolActionMenu.setVisible(true);
895 * jalview.jbgui.GStructureViewer#alignStructs_actionPerformed(java.awt.event
899 protected void alignStructs_actionPerformed(ActionEvent actionEvent)
904 jmb.superposeStructures(ap.av.getAlignment(), -1,
905 ap.av.getColumnSelection());
906 } catch (Exception e)
908 Cache.log.info("Couldn't align structures in alignframe "
909 + ap.alignFrame.getTitle(), e);
914 public void setJalviewColourScheme(ColourSchemeI ucs)
916 jmb.setJalviewColourScheme(ucs);