2 * Jalview - A Sequence Alignment Editor and Viewer
3 * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
21 import java.util.regex.*;
25 import javax.swing.event.*;
26 import java.awt.event.*;
29 import jalview.jbgui.GStructureViewer;
30 import jalview.datamodel.*;
32 import jalview.structure.*;
33 import jalview.datamodel.PDBEntry;
35 import jalview.schemes.*;
36 import jalview.ws.ebi.EBIFetchClient;
38 import org.jmol.api.*;
39 import org.jmol.adapter.smarter.SmarterJmolAdapter;
40 import org.jmol.popup.*;
44 extends GStructureViewer
45 implements StructureListener, JmolStatusListener, Runnable
50 ScriptWindow scriptWindow;
54 StructureSelectionManager ssm;
56 RenderPanel renderPanel;
58 String fileLoadingError;
59 boolean colourBySequence = true;
60 boolean loadingFromArchive = false;
61 Vector atomsPicked = new Vector();
63 public AppJmol(String file, String id,
69 loadingFromArchive = true;
70 pdbentry = new PDBEntry();
71 pdbentry.setFile(file);
76 this.setBounds(bounds);
78 colourBySequence = false;
79 seqColour.setSelected(false);
81 jalview.gui.Desktop.addInternalFrame(this, "Loading File",
82 bounds.width,bounds.height);
86 this.addInternalFrameListener(new InternalFrameAdapter()
88 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
95 public synchronized void addSequence(SequenceI [] seq)
97 Vector v = new Vector();
98 for(int i=0; i<sequence.length; i++)
99 v.addElement(sequence[i]);
101 for(int i=0; i<seq.length; i++)
102 if(!v.contains(seq[i]))
103 v.addElement(seq[i]);
105 SequenceI [] tmp = new SequenceI[v.size()];
110 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String [] chains, AlignmentPanel ap)
112 //////////////////////////////////
113 //Is the pdb file already loaded?
114 String alreadyMapped = StructureSelectionManager
115 .getStructureSelectionManager()
116 .alreadyMappedToFile(pdbentry.getId());
118 if (alreadyMapped != null)
120 int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
121 pdbentry.getId() + " is already displayed."
122 + "\nDo you want to map sequences to the visible structure?",
123 "Map Sequences to Visible Window: " + pdbentry.getId(),
124 JOptionPane.YES_NO_OPTION);
126 if (option == JOptionPane.YES_OPTION)
128 StructureSelectionManager.getStructureSelectionManager()
129 .setMapping(seq, chains, alreadyMapped, AppletFormatAdapter.FILE);
130 if (ap.seqPanel.seqCanvas.fr!=null) {
131 ap.seqPanel.seqCanvas.fr.featuresAdded();
132 ap.paintAlignment(true);
135 //Now this AppJmol is mapped to new sequences. We must add them to
136 // the exisiting array
137 JInternalFrame [] frames = Desktop.instance.getAllFrames();
139 for(int i=0; i<frames.length; i++)
141 if(frames[i] instanceof AppJmol)
143 AppJmol topJmol = ((AppJmol)frames[i]);
144 if(topJmol.pdbentry.getFile().equals(alreadyMapped))
146 topJmol.addSequence(seq);
155 ///////////////////////////////////
158 this.pdbentry = pdbentry;
161 jalview.gui.Desktop.addInternalFrame(this, "Loading File", 400, 400);
163 if (pdbentry.getFile() != null)
165 initJmol("load \""+pdbentry.getFile()+"\"");
169 Thread worker = new Thread(this);
173 this.addInternalFrameListener(new InternalFrameAdapter()
175 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
183 void initJmol(String command)
185 renderPanel = new RenderPanel();
187 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
189 StringBuffer title = new StringBuffer(sequence[0].getName() + ":" +
192 if (pdbentry.getProperty() != null)
194 if (pdbentry.getProperty().get("method") != null)
196 title.append(" Method: ");
197 title.append(pdbentry.getProperty().get("method"));
199 if (pdbentry.getProperty().get("chains") != null)
201 title.append(" Chain:");
202 title.append(pdbentry.getProperty().get("chains"));
206 this.setTitle(title.toString());
208 viewer = org.jmol.api.JmolViewer.allocateViewer(renderPanel,
209 new SmarterJmolAdapter());
212 viewer.setAppletContext("", null, null, "");
214 viewer.setJmolStatusListener(this);
216 jmolpopup = JmolPopup.newJmolPopup(viewer);
218 viewer.evalStringQuiet(command);
222 void setChainMenuItems(Vector chains)
224 chainMenu.removeAll();
226 JMenuItem menuItem = new JMenuItem("All");
227 menuItem.addActionListener(new ActionListener()
229 public void actionPerformed(ActionEvent evt)
231 allChainsSelected = true;
232 for(int i=0; i<chainMenu.getItemCount(); i++)
234 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
235 ( (JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
238 allChainsSelected = false;
242 chainMenu.add(menuItem);
244 for (int c = 0; c < chains.size(); c++)
246 menuItem = new JCheckBoxMenuItem(chains.elementAt(c).toString(), true);
247 menuItem.addItemListener(new ItemListener()
249 public void itemStateChanged(ItemEvent evt)
251 if (!allChainsSelected)
256 chainMenu.add(menuItem);
260 boolean allChainsSelected = false;
263 StringBuffer cmd = new StringBuffer();
264 for(int i=0; i<chainMenu.getItemCount(); i++)
266 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
268 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
269 if(item.isSelected())
270 cmd.append(":"+item.getText()+" or ");
274 if (cmd.length() > 0)
275 cmd.setLength(cmd.length() - 4);
277 viewer.evalStringQuiet("select *;restrict "
278 +cmd+";cartoon;center "+cmd);
283 viewer.setModeMouse(org.jmol.viewer.JmolConstants.MOUSE_NONE);
284 viewer.evalStringQuiet("zap");
285 viewer.setJmolStatusListener(null);
288 //We'll need to find out what other
289 // listeners need to be shut down in Jmol
290 StructureSelectionManager
291 .getStructureSelectionManager()
292 .removeStructureViewerListener(this, pdbentry.getFile());
299 EBIFetchClient ebi = new EBIFetchClient();
300 String query = "pdb:" + pdbentry.getId();
301 pdbentry.setFile(ebi.fetchDataAsFile(query, "default", "raw")
303 initJmol("load "+pdbentry.getFile());
307 ex.printStackTrace();
311 public void pdbFile_actionPerformed(ActionEvent actionEvent)
313 JalviewFileChooser chooser = new JalviewFileChooser(
314 jalview.bin.Cache.getProperty(
317 chooser.setFileView(new JalviewFileView());
318 chooser.setDialogTitle("Save PDB File");
319 chooser.setToolTipText("Save");
321 int value = chooser.showSaveDialog(this);
323 if (value == JalviewFileChooser.APPROVE_OPTION)
327 BufferedReader in = new BufferedReader(new FileReader(pdbentry.getFile()));
328 File outFile = chooser.getSelectedFile();
330 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
332 while ( (data = in.readLine()) != null)
335 ! (data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1)
345 ex.printStackTrace();
350 public void viewMapping_actionPerformed(ActionEvent actionEvent)
352 jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
353 jalview.gui.Desktop.addInternalFrame(cap, "PDB - Sequence Mapping", 550,
356 StructureSelectionManager.getStructureSelectionManager().printMapping(
364 * @param e DOCUMENT ME!
366 public void eps_actionPerformed(ActionEvent e)
368 makePDBImage(jalview.util.ImageMaker.EPS);
374 * @param e DOCUMENT ME!
376 public void png_actionPerformed(ActionEvent e)
378 makePDBImage(jalview.util.ImageMaker.PNG);
381 void makePDBImage(int type)
383 int width = getWidth();
384 int height = getHeight();
386 jalview.util.ImageMaker im;
388 if (type == jalview.util.ImageMaker.PNG)
390 im = new jalview.util.ImageMaker(this,
391 jalview.util.ImageMaker.PNG,
392 "Make PNG image from view",
398 im = new jalview.util.ImageMaker(this,
399 jalview.util.ImageMaker.EPS,
400 "Make EPS file from view",
402 null, this.getTitle());
405 if (im.getGraphics() != null)
407 Rectangle rect = new Rectangle(width, height);
408 viewer.renderScreenImage(im.getGraphics(),
409 rect.getSize(), rect);
415 public void seqColour_actionPerformed(ActionEvent actionEvent)
418 colourBySequence = seqColour.isSelected();
419 colourBySequence(ap.alignFrame.alignPanel);
422 public void chainColour_actionPerformed(ActionEvent actionEvent)
424 colourBySequence = false;
425 seqColour.setSelected(false);
426 viewer.evalStringQuiet("select *;color chain");
429 public void chargeColour_actionPerformed(ActionEvent actionEvent)
431 colourBySequence = false;
432 seqColour.setSelected(false);
433 viewer.evalStringQuiet("select *;color white;select ASP,GLU;color red;"
434 +"select LYS,ARG;color blue;select CYS;color yellow");
437 public void zappoColour_actionPerformed(ActionEvent actionEvent)
439 setJalviewColourScheme(new ZappoColourScheme());
442 public void taylorColour_actionPerformed(ActionEvent actionEvent)
444 setJalviewColourScheme(new TaylorColourScheme());
447 public void hydroColour_actionPerformed(ActionEvent actionEvent)
449 setJalviewColourScheme(new HydrophobicColourScheme());
452 public void helixColour_actionPerformed(ActionEvent actionEvent)
454 setJalviewColourScheme(new HelixColourScheme());
457 public void strandColour_actionPerformed(ActionEvent actionEvent)
459 setJalviewColourScheme(new StrandColourScheme());
462 public void turnColour_actionPerformed(ActionEvent actionEvent)
464 setJalviewColourScheme(new TurnColourScheme());
467 public void buriedColour_actionPerformed(ActionEvent actionEvent)
469 setJalviewColourScheme(new BuriedColourScheme());
472 public void setJalviewColourScheme(ColourSchemeI cs)
474 colourBySequence = false;
475 seqColour.setSelected(false);
484 Enumeration en = ResidueProperties.aa3Hash.keys();
485 StringBuffer command = new StringBuffer("select *;color white;");
486 while(en.hasMoreElements())
488 res = en.nextElement().toString();
489 index = ((Integer) ResidueProperties.aa3Hash.get(res)).intValue();
493 col = cs.findColour(ResidueProperties.aa[index].charAt(0));
495 command.append("select "+res+";color["
497 + col.getGreen() + ","
498 + col.getBlue() + "];");
501 viewer.evalStringQuiet(command.toString());
504 public void userColour_actionPerformed(ActionEvent actionEvent)
506 new UserDefinedColours(this, null);
509 public void backGround_actionPerformed(ActionEvent actionEvent)
511 java.awt.Color col = JColorChooser.showDialog(this,
512 "Select Background Colour",
517 viewer.evalStringQuiet("background ["
519 + col.getGreen() + ","
520 + col.getBlue() + "];");
525 public void jmolHelp_actionPerformed(ActionEvent actionEvent)
528 jalview.util.BrowserLauncher.openURL(
529 "http://jmol.sourceforge.net/docs/JmolUserGuide/");
530 }catch(Exception ex){}
534 //////////////////////////////////
536 public String getPdbFile()
538 return pdbentry.getFile();
541 Pattern pattern = Pattern.compile(
542 "\\[(.*)\\]([0-9]+)(:[a-zA-Z]*)?\\.([a-zA-Z]+)(/[0-9]*)?"
546 public void mouseOverStructure(int atomIndex, String strInfo)
548 Matcher matcher = pattern.matcher(strInfo);
551 int pdbResNum = Integer.parseInt(matcher.group(2));
552 String chainId = matcher.group(3);
555 chainId = chainId.substring(1, chainId.length());
561 if (lastMessage == null || !lastMessage.equals(strInfo))
563 ssm.mouseOverStructure(pdbResNum, chainId, pdbentry.getFile());
565 lastMessage = strInfo;
568 StringBuffer resetLastRes = new StringBuffer();
569 StringBuffer eval = new StringBuffer();
571 public void highlightAtom(int atomIndex, int pdbResNum, String chain, String pdbfile)
573 if (!pdbfile.equals(pdbentry.getFile()))
576 if (resetLastRes.length() > 0)
578 viewer.evalStringQuiet(resetLastRes.toString());
582 eval.append("select " + pdbResNum);
584 resetLastRes.setLength(0);
585 resetLastRes.append("select " + pdbResNum);
587 if (!chain.equals(" "))
589 eval.append(":" + chain);
590 resetLastRes.append(":" + chain);
593 eval.append(";wireframe 100;"+eval.toString()+".CA;");
595 resetLastRes.append(";wireframe 0;"+resetLastRes.toString()+".CA;spacefill 0;");
597 eval.append("spacefill 200;select none");
599 viewer.evalStringQuiet(eval.toString());
602 public Color getColour(int atomIndex, int pdbResNum, String chain, String pdbfile)
604 if (!pdbfile.equals(pdbentry.getFile()))
607 return new Color(viewer.getAtomArgb(atomIndex));
610 public void updateColours(Object source)
612 colourBySequence( (AlignmentPanel) source);
616 //End StructureListener
617 ////////////////////////////
620 FeatureRenderer fr=null;
621 public void colourBySequence(AlignmentPanel sourceap)
625 if(!colourBySequence || ap.alignFrame.getCurrentView()!=ap.av)
628 StructureMapping[] mapping = ssm.getMapping(pdbentry.getFile());
630 if (mapping.length < 1)
634 SequenceRenderer sr = new SequenceRenderer(ap.av);
636 boolean showFeatures = false;
638 if (ap.av.showSequenceFeatures)
643 fr = new jalview.gui.FeatureRenderer(ap);
646 fr.transferSettings(ap.seqPanel.seqCanvas.getFeatureRenderer());
649 StringBuffer command = new StringBuffer();
652 for (int sp,s = 0; s < sequence.length; s++)
654 for (int m = 0; m < mapping.length; m++)
656 if (mapping[m].getSequence() == sequence[s]
657 && (sp=ap.av.alignment.findIndex(sequence[s]))>-1)
659 SequenceI asp = ap.av.alignment.getSequenceAt(sp);
660 for (int r = 0; r < asp.getLength(); r++)
662 // No mapping to gaps in sequence.
663 if (jalview.util.Comparison.isGap(asp.getCharAt(r)))
667 int pos = mapping[m].getPDBResNum(
668 asp.findPosition(r));
670 if (pos < 1 || pos==lastPos)
675 Color col = sr.getResidueBoxColour(asp, r);
678 col = fr.findFeatureColour(col, asp, r);
680 if (command.toString().endsWith(":" + mapping[m].getChain()+
683 + col.getGreen() + ","
684 + col.getBlue() + "]"))
686 command = condenseCommand(command, pos);
690 command.append(";select " + pos);
692 if (!mapping[m].getChain().equals(" "))
694 command.append(":" + mapping[m].getChain());
697 command.append(";color["
699 + col.getGreen() + ","
700 + col.getBlue() + "]");
708 if (lastCommand == null || !lastCommand.equals(command.toString()))
710 viewer.evalStringQuiet(command.toString());
712 lastCommand = command.toString();
715 StringBuffer condenseCommand(StringBuffer command, int pos)
717 StringBuffer sb = new StringBuffer(command.substring(0, command.lastIndexOf("select")+7));
719 command.delete(0, sb.length());
723 if (command.indexOf("-") > -1)
725 start = command.substring(0,command.indexOf("-"));
729 start = command.substring(0, command.indexOf(":"));
732 sb.append(start+"-"+pos+command.substring(command.indexOf(":")));
737 /////////////////////////////////
740 public String eval(String strEval)
742 // System.out.println(strEval);
743 //"# 'eval' is implemented only for the applet.";
747 public void createImage(String file, String type, int quality)
749 System.out.println("JMOL CREATE IMAGE");
752 public void setCallbackFunction(String callbackType,
753 String callbackFunction)
756 public void notifyFileLoaded(String fullPathName, String fileName,
757 String modelName, Object clientFile,
762 fileLoadingError = errorMsg;
767 fileLoadingError = null;
769 if (fileName != null)
773 ssm = StructureSelectionManager.getStructureSelectionManager();
774 MCview.PDBfile pdbFile = ssm.setMapping(sequence,chains,pdbentry.getFile(), AppletFormatAdapter.FILE);
775 ssm.addStructureViewerListener(this);
776 Vector chains = new Vector();
777 for(int i=0; i<pdbFile.chains.size(); i++)
779 chains.addElement(((MCview.PDBChain)pdbFile.chains.elementAt(i)).id);
781 setChainMenuItems(chains);
783 jmolpopup.updateComputedMenus();
785 if(!loadingFromArchive)
787 viewer.evalStringQuiet(
788 "select backbone;restrict;cartoon;wireframe off;spacefill off");
790 colourBySequence(ap);
795 loadingFromArchive = false;
801 public void notifyFrameChanged(int frameNo)
803 boolean isAnimationRunning = (frameNo <= -2);
806 public void notifyScriptStart(String statusMessage, String additionalInfo)
809 public void sendConsoleEcho(String strEcho)
811 if (scriptWindow != null)
812 scriptWindow.sendConsoleEcho(strEcho);
815 public void sendConsoleMessage(String strStatus)
817 if (scriptWindow != null)
818 scriptWindow.sendConsoleMessage(strStatus);
821 public void notifyScriptTermination(String strStatus, int msWalltime)
823 if (scriptWindow != null)
824 scriptWindow.notifyScriptTermination(strStatus, msWalltime);
827 public void handlePopupMenu(int x, int y)
829 jmolpopup.show(x, y);
832 public void notifyNewPickingModeMeasurement(int iatom, String strMeasure)
834 notifyAtomPicked(iatom, strMeasure);
837 public void notifyNewDefaultModeMeasurement(int count, String strInfo)
840 public void notifyAtomPicked(int atomIndex, String strInfo)
842 Matcher matcher = pattern.matcher(strInfo);
846 String resnum = new String(matcher.group(2));
847 String chainId = matcher.group(3);
849 String picked = resnum;
852 picked+=(":"+chainId.substring(1, chainId.length()));
857 if (!atomsPicked.contains(picked))
860 viewer.evalString("select "+picked+";label %n %r:%c");
862 viewer.evalString("select "+picked+";label %n %r");
863 atomsPicked.addElement(picked);
867 viewer.evalString("select "+picked+";label off");
868 atomsPicked.removeElement(picked);
871 if (scriptWindow != null)
873 scriptWindow.sendConsoleMessage(strInfo);
874 scriptWindow.sendConsoleMessage("\n");
878 public void notifyAtomHovered(int atomIndex, String strInfo)
880 mouseOverStructure(atomIndex, strInfo);
883 public void sendSyncScript(String script, String appletName)
886 public void showUrl(String url)
889 public void showConsole(boolean showConsole)
891 if (scriptWindow == null)
892 scriptWindow = new ScriptWindow(this);
898 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
899 splitPane.setTopComponent(renderPanel);
900 splitPane.setBottomComponent(scriptWindow);
901 this.getContentPane().add(splitPane, BorderLayout.CENTER);
904 splitPane.setDividerLocation(getHeight()-200);
905 splitPane.validate();
909 if (splitPane != null)
910 splitPane.setVisible(false);
914 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
920 public float functionXY(String functionName, int x, int y)
925 ///End JmolStatusListener
926 ///////////////////////////////
932 final Dimension currentSize = new Dimension();
933 final Rectangle rectClip = new Rectangle();
935 public void paintComponent(Graphics g)
937 getSize(currentSize);
938 g.getClipBounds(rectClip);
942 g.setColor(Color.black);
943 g.fillRect(0, 0, currentSize.width, currentSize.height);
944 g.setColor(Color.white);
945 g.setFont(new Font("Verdana", Font.BOLD, 14));
946 g.drawString("Retrieving PDB data....", 20, currentSize.height / 2);
948 else if(fileLoadingError!=null)
950 g.setColor(Color.black);
951 g.fillRect(0, 0, currentSize.width, currentSize.height);
952 g.setColor(Color.white);
953 g.setFont(new Font("Verdana", Font.BOLD, 14));
954 g.drawString("Error loading file..." + pdbentry.getId(), 20,
955 currentSize.height / 2);
959 viewer.renderScreenImage(g, currentSize, rectClip);