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.*;
37 import org.jmol.api.*;
38 import org.jmol.adapter.smarter.SmarterJmolAdapter;
39 import org.jmol.popup.*;
43 extends GStructureViewer
44 implements StructureListener, JmolStatusListener, Runnable
49 ScriptWindow scriptWindow;
53 StructureSelectionManager ssm;
55 RenderPanel renderPanel;
57 String fileLoadingError;
58 boolean colourBySequence = true;
59 boolean loadingFromArchive = false;
60 Vector atomsPicked = new Vector();
62 public AppJmol(String file, String id,
68 loadingFromArchive = true;
69 pdbentry = new PDBEntry();
70 pdbentry.setFile(file);
75 this.setBounds(bounds);
77 colourBySequence = false;
78 seqColour.setSelected(false);
80 jalview.gui.Desktop.addInternalFrame(this, "Loading File",
81 bounds.width,bounds.height);
85 this.addInternalFrameListener(new InternalFrameAdapter()
87 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
94 public synchronized void addSequence(SequenceI [] seq)
96 Vector v = new Vector();
97 for(int i=0; i<sequence.length; i++)
98 v.addElement(sequence[i]);
100 for(int i=0; i<seq.length; i++)
101 if(!v.contains(seq[i]))
102 v.addElement(seq[i]);
104 SequenceI [] tmp = new SequenceI[v.size()];
109 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String [] chains, AlignmentPanel ap)
111 //////////////////////////////////
112 //Is the pdb file already loaded?
113 String alreadyMapped = StructureSelectionManager
114 .getStructureSelectionManager()
115 .alreadyMappedToFile(pdbentry.getId());
117 if (alreadyMapped != null)
119 int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
120 pdbentry.getId() + " is already displayed."
121 + "\nDo you want to map sequences to the visible structure?",
122 "Map Sequences to Visible Window: " + pdbentry.getId(),
123 JOptionPane.YES_NO_OPTION);
125 if (option == JOptionPane.YES_OPTION)
127 StructureSelectionManager.getStructureSelectionManager()
128 .setMapping(seq, chains, alreadyMapped, AppletFormatAdapter.FILE);
129 if (ap.seqPanel.seqCanvas.fr!=null) {
130 ap.seqPanel.seqCanvas.fr.featuresAdded();
131 ap.paintAlignment(true);
134 //Now this AppJmol is mapped to new sequences. We must add them to
135 // the exisiting array
136 JInternalFrame [] frames = Desktop.instance.getAllFrames();
138 for(int i=0; i<frames.length; i++)
140 if(frames[i] instanceof AppJmol)
142 AppJmol topJmol = ((AppJmol)frames[i]);
143 if(topJmol.pdbentry.getFile().equals(alreadyMapped))
145 topJmol.addSequence(seq);
154 ///////////////////////////////////
157 this.pdbentry = pdbentry;
160 jalview.gui.Desktop.addInternalFrame(this, "Loading File", 400, 400);
162 if (pdbentry.getFile() != null)
164 initJmol("load \""+pdbentry.getFile()+"\"");
168 Thread worker = new Thread(this);
172 this.addInternalFrameListener(new InternalFrameAdapter()
174 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
182 void initJmol(String command)
184 renderPanel = new RenderPanel();
186 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
188 StringBuffer title = new StringBuffer(sequence[0].getName() + ":" +
191 if (pdbentry.getProperty() != null)
193 if (pdbentry.getProperty().get("method") != null)
195 title.append(" Method: ");
196 title.append(pdbentry.getProperty().get("method"));
198 if (pdbentry.getProperty().get("chains") != null)
200 title.append(" Chain:");
201 title.append(pdbentry.getProperty().get("chains"));
205 this.setTitle(title.toString());
207 viewer = org.jmol.api.JmolViewer.allocateViewer(renderPanel,
208 new SmarterJmolAdapter());
211 viewer.setAppletContext("", null, null, "");
213 viewer.setJmolStatusListener(this);
215 jmolpopup = JmolPopup.newJmolPopup(viewer);
217 viewer.evalStringQuiet(command);
221 void setChainMenuItems(Vector chains)
223 chainMenu.removeAll();
225 JMenuItem menuItem = new JMenuItem("All");
226 menuItem.addActionListener(new ActionListener()
228 public void actionPerformed(ActionEvent evt)
230 allChainsSelected = true;
231 for(int i=0; i<chainMenu.getItemCount(); i++)
233 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
234 ( (JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
237 allChainsSelected = false;
241 chainMenu.add(menuItem);
243 for (int c = 0; c < chains.size(); c++)
245 menuItem = new JCheckBoxMenuItem(chains.elementAt(c).toString(), true);
246 menuItem.addItemListener(new ItemListener()
248 public void itemStateChanged(ItemEvent evt)
250 if (!allChainsSelected)
255 chainMenu.add(menuItem);
259 boolean allChainsSelected = false;
262 StringBuffer cmd = new StringBuffer();
263 for(int i=0; i<chainMenu.getItemCount(); i++)
265 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
267 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
268 if(item.isSelected())
269 cmd.append(":"+item.getText()+" or ");
273 if (cmd.length() > 0)
274 cmd.setLength(cmd.length() - 4);
276 viewer.evalStringQuiet("select *;restrict "
277 +cmd+";cartoon;center "+cmd);
282 viewer.setModeMouse(org.jmol.viewer.JmolConstants.MOUSE_NONE);
283 viewer.evalStringQuiet("zap");
284 viewer.setJmolStatusListener(null);
287 //We'll need to find out what other
288 // listeners need to be shut down in Jmol
289 StructureSelectionManager
290 .getStructureSelectionManager()
291 .removeStructureViewerListener(this, pdbentry.getFile());
298 EBIFetchClient ebi = new EBIFetchClient();
299 String query = "pdb:" + pdbentry.getId();
300 pdbentry.setFile(ebi.fetchDataAsFile(query, "default", "raw")
302 initJmol("load "+pdbentry.getFile());
306 ex.printStackTrace();
310 public void pdbFile_actionPerformed(ActionEvent actionEvent)
312 JalviewFileChooser chooser = new JalviewFileChooser(
313 jalview.bin.Cache.getProperty(
316 chooser.setFileView(new JalviewFileView());
317 chooser.setDialogTitle("Save PDB File");
318 chooser.setToolTipText("Save");
320 int value = chooser.showSaveDialog(this);
322 if (value == JalviewFileChooser.APPROVE_OPTION)
326 BufferedReader in = new BufferedReader(new FileReader(pdbentry.getFile()));
327 File outFile = chooser.getSelectedFile();
329 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
331 while ( (data = in.readLine()) != null)
334 ! (data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1)
344 ex.printStackTrace();
349 public void viewMapping_actionPerformed(ActionEvent actionEvent)
351 jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
352 jalview.gui.Desktop.addInternalFrame(cap, "PDB - Sequence Mapping", 550,
355 StructureSelectionManager.getStructureSelectionManager().printMapping(
363 * @param e DOCUMENT ME!
365 public void eps_actionPerformed(ActionEvent e)
367 makePDBImage(jalview.util.ImageMaker.EPS);
373 * @param e DOCUMENT ME!
375 public void png_actionPerformed(ActionEvent e)
377 makePDBImage(jalview.util.ImageMaker.PNG);
380 void makePDBImage(int type)
382 int width = getWidth();
383 int height = getHeight();
385 jalview.util.ImageMaker im;
387 if (type == jalview.util.ImageMaker.PNG)
389 im = new jalview.util.ImageMaker(this,
390 jalview.util.ImageMaker.PNG,
391 "Make PNG image from view",
397 im = new jalview.util.ImageMaker(this,
398 jalview.util.ImageMaker.EPS,
399 "Make EPS file from view",
401 null, this.getTitle());
404 if (im.getGraphics() != null)
406 Rectangle rect = new Rectangle(width, height);
407 viewer.renderScreenImage(im.getGraphics(),
408 rect.getSize(), rect);
414 public void seqColour_actionPerformed(ActionEvent actionEvent)
416 colourBySequence = seqColour.isSelected();
417 colourBySequence(ap.alignFrame.alignPanel);
420 public void chainColour_actionPerformed(ActionEvent actionEvent)
422 colourBySequence = false;
423 seqColour.setSelected(false);
424 viewer.evalStringQuiet("select *;color chain");
427 public void chargeColour_actionPerformed(ActionEvent actionEvent)
429 colourBySequence = false;
430 seqColour.setSelected(false);
431 viewer.evalStringQuiet("select *;color white;select ASP,GLU;color red;"
432 +"select LYS,ARG;color blue;select CYS;color yellow");
435 public void zappoColour_actionPerformed(ActionEvent actionEvent)
437 setJalviewColourScheme(new ZappoColourScheme());
440 public void taylorColour_actionPerformed(ActionEvent actionEvent)
442 setJalviewColourScheme(new TaylorColourScheme());
445 public void hydroColour_actionPerformed(ActionEvent actionEvent)
447 setJalviewColourScheme(new HydrophobicColourScheme());
450 public void helixColour_actionPerformed(ActionEvent actionEvent)
452 setJalviewColourScheme(new HelixColourScheme());
455 public void strandColour_actionPerformed(ActionEvent actionEvent)
457 setJalviewColourScheme(new StrandColourScheme());
460 public void turnColour_actionPerformed(ActionEvent actionEvent)
462 setJalviewColourScheme(new TurnColourScheme());
465 public void buriedColour_actionPerformed(ActionEvent actionEvent)
467 setJalviewColourScheme(new BuriedColourScheme());
470 public void setJalviewColourScheme(ColourSchemeI cs)
472 colourBySequence = false;
473 seqColour.setSelected(false);
482 Enumeration en = ResidueProperties.aa3Hash.keys();
483 StringBuffer command = new StringBuffer("select *;color white;");
484 while(en.hasMoreElements())
486 res = en.nextElement().toString();
487 index = ((Integer) ResidueProperties.aa3Hash.get(res)).intValue();
491 col = cs.findColour(ResidueProperties.aa[index].charAt(0));
493 command.append("select "+res+";color["
495 + col.getGreen() + ","
496 + col.getBlue() + "];");
499 viewer.evalStringQuiet(command.toString());
502 public void userColour_actionPerformed(ActionEvent actionEvent)
504 new UserDefinedColours(this, null);
507 public void backGround_actionPerformed(ActionEvent actionEvent)
509 java.awt.Color col = JColorChooser.showDialog(this,
510 "Select Background Colour",
515 viewer.evalStringQuiet("background ["
517 + col.getGreen() + ","
518 + col.getBlue() + "];");
523 public void jmolHelp_actionPerformed(ActionEvent actionEvent)
526 jalview.util.BrowserLauncher.openURL(
527 "http://jmol.sourceforge.net/docs/JmolUserGuide/");
528 }catch(Exception ex){}
532 //////////////////////////////////
534 public String getPdbFile()
536 return pdbentry.getFile();
539 Pattern pattern = Pattern.compile(
540 "\\[(.*)\\]([0-9]+)(:[a-zA-Z]*)?\\.([a-zA-Z]+)(/[0-9]*)?"
544 public void mouseOverStructure(int atomIndex, String strInfo)
546 Matcher matcher = pattern.matcher(strInfo);
549 int pdbResNum = Integer.parseInt(matcher.group(2));
550 String chainId = matcher.group(3);
553 chainId = chainId.substring(1, chainId.length());
559 if (lastMessage == null || !lastMessage.equals(strInfo))
561 ssm.mouseOverStructure(pdbResNum, chainId, pdbentry.getFile());
563 lastMessage = strInfo;
566 StringBuffer resetLastRes = new StringBuffer();
567 StringBuffer eval = new StringBuffer();
569 public void highlightAtom(int atomIndex, int pdbResNum, String chain, String pdbfile)
571 if (!pdbfile.equals(pdbentry.getFile()))
574 if (resetLastRes.length() > 0)
576 viewer.evalStringQuiet(resetLastRes.toString());
580 eval.append("select " + pdbResNum);
582 resetLastRes.setLength(0);
583 resetLastRes.append("select " + pdbResNum);
585 if (!chain.equals(" "))
587 eval.append(":" + chain);
588 resetLastRes.append(":" + chain);
591 eval.append(";wireframe 100;"+eval.toString()+".CA;");
593 resetLastRes.append(";wireframe 0;"+resetLastRes.toString()+".CA;spacefill 0;");
595 eval.append("spacefill 200;select none");
597 viewer.evalStringQuiet(eval.toString());
600 public Color getColour(int atomIndex, int pdbResNum, String chain, String pdbfile)
602 if (!pdbfile.equals(pdbentry.getFile()))
605 return new Color(viewer.getAtomArgb(atomIndex));
608 public void updateColours(Object source)
610 colourBySequence( (AlignmentPanel) source);
614 //End StructureListener
615 ////////////////////////////
618 FeatureRenderer fr=null;
619 public void colourBySequence(AlignmentPanel sourceap)
623 if(!colourBySequence || ap.alignFrame.getCurrentView()!=ap.av)
626 StructureMapping[] mapping = ssm.getMapping(pdbentry.getFile());
628 if (mapping.length < 1)
632 SequenceRenderer sr = new SequenceRenderer(ap.av);
634 boolean showFeatures = false;
636 if (ap.av.showSequenceFeatures)
641 fr = new jalview.gui.FeatureRenderer(ap);
644 fr.transferSettings(ap.seqPanel.seqCanvas.getFeatureRenderer());
647 StringBuffer command = new StringBuffer();
650 for (int s = 0; s < sequence.length; s++)
652 for (int m = 0; m < mapping.length; m++)
654 if (mapping[m].getSequence() == sequence[s]
655 && ap.av.alignment.findIndex(sequence[s])>-1)
657 for (int r = 0; r < sequence[s].getLength(); r++)
659 int pos = mapping[m].getPDBResNum(
660 sequence[s].findPosition(r));
662 if (pos < 1 || pos==lastPos)
667 Color col = sr.getResidueBoxColour(sequence[s], r);
670 col = fr.findFeatureColour(col, sequence[s], r);
672 if (command.toString().endsWith(":" + mapping[m].getChain()+
675 + col.getGreen() + ","
676 + col.getBlue() + "]"))
678 command = condenseCommand(command, pos);
682 command.append(";select " + pos);
684 if (!mapping[m].getChain().equals(" "))
686 command.append(":" + mapping[m].getChain());
689 command.append(";color["
691 + col.getGreen() + ","
692 + col.getBlue() + "]");
700 if (lastCommand == null || !lastCommand.equals(command.toString()))
702 viewer.evalStringQuiet(command.toString());
704 lastCommand = command.toString();
707 StringBuffer condenseCommand(StringBuffer command, int pos)
709 StringBuffer sb = new StringBuffer(command.substring(0, command.lastIndexOf("select")+7));
711 command.delete(0, sb.length());
715 if (command.indexOf("-") > -1)
717 start = command.substring(0,command.indexOf("-"));
721 start = command.substring(0, command.indexOf(":"));
724 sb.append(start+"-"+pos+command.substring(command.indexOf(":")));
729 /////////////////////////////////
732 public String eval(String strEval)
734 // System.out.println(strEval);
735 //"# 'eval' is implemented only for the applet.";
739 public void createImage(String file, String type, int quality)
741 System.out.println("JMOL CREATE IMAGE");
744 public void setCallbackFunction(String callbackType,
745 String callbackFunction)
748 public void notifyFileLoaded(String fullPathName, String fileName,
749 String modelName, Object clientFile,
754 fileLoadingError = errorMsg;
759 fileLoadingError = null;
761 if (fileName != null)
765 ssm = StructureSelectionManager.getStructureSelectionManager();
766 MCview.PDBfile pdbFile = ssm.setMapping(sequence,chains,pdbentry.getFile(), AppletFormatAdapter.FILE);
767 ssm.addStructureViewerListener(this);
768 Vector chains = new Vector();
769 for(int i=0; i<pdbFile.chains.size(); i++)
771 chains.addElement(((MCview.PDBChain)pdbFile.chains.elementAt(i)).id);
773 setChainMenuItems(chains);
775 jmolpopup.updateComputedMenus();
777 if(!loadingFromArchive)
779 viewer.evalStringQuiet(
780 "select backbone;restrict;cartoon;wireframe off;spacefill off");
782 colourBySequence(ap);
787 loadingFromArchive = false;
793 public void notifyFrameChanged(int frameNo)
795 boolean isAnimationRunning = (frameNo <= -2);
798 public void notifyScriptStart(String statusMessage, String additionalInfo)
801 public void sendConsoleEcho(String strEcho)
803 if (scriptWindow != null)
804 scriptWindow.sendConsoleEcho(strEcho);
807 public void sendConsoleMessage(String strStatus)
809 if (scriptWindow != null)
810 scriptWindow.sendConsoleMessage(strStatus);
813 public void notifyScriptTermination(String strStatus, int msWalltime)
815 if (scriptWindow != null)
816 scriptWindow.notifyScriptTermination(strStatus, msWalltime);
819 public void handlePopupMenu(int x, int y)
821 jmolpopup.show(x, y);
824 public void notifyNewPickingModeMeasurement(int iatom, String strMeasure)
826 notifyAtomPicked(iatom, strMeasure);
829 public void notifyNewDefaultModeMeasurement(int count, String strInfo)
832 public void notifyAtomPicked(int atomIndex, String strInfo)
834 Matcher matcher = pattern.matcher(strInfo);
838 String resnum = new String(matcher.group(2));
839 String chainId = matcher.group(3);
841 String picked = resnum;
844 picked+=(":"+chainId.substring(1, chainId.length()));
849 if (!atomsPicked.contains(picked))
852 viewer.evalString("select "+picked+";label %n %r:%c");
854 viewer.evalString("select "+picked+";label %n %r");
855 atomsPicked.addElement(picked);
859 viewer.evalString("select "+picked+";label off");
860 atomsPicked.removeElement(picked);
863 if (scriptWindow != null)
865 scriptWindow.sendConsoleMessage(strInfo);
866 scriptWindow.sendConsoleMessage("\n");
870 public void notifyAtomHovered(int atomIndex, String strInfo)
872 mouseOverStructure(atomIndex, strInfo);
875 public void sendSyncScript(String script, String appletName)
878 public void showUrl(String url)
881 public void showConsole(boolean showConsole)
883 if (scriptWindow == null)
884 scriptWindow = new ScriptWindow(this);
890 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
891 splitPane.setTopComponent(renderPanel);
892 splitPane.setBottomComponent(scriptWindow);
893 this.getContentPane().add(splitPane, BorderLayout.CENTER);
896 splitPane.setDividerLocation(getHeight()-200);
897 splitPane.validate();
901 if (splitPane != null)
902 splitPane.setVisible(false);
906 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
912 public float functionXY(String functionName, int x, int y)
917 ///End JmolStatusListener
918 ///////////////////////////////
924 final Dimension currentSize = new Dimension();
925 final Rectangle rectClip = new Rectangle();
927 public void paintComponent(Graphics g)
929 getSize(currentSize);
930 g.getClipBounds(rectClip);
934 g.setColor(Color.black);
935 g.fillRect(0, 0, currentSize.width, currentSize.height);
936 g.setColor(Color.white);
937 g.setFont(new Font("Verdana", Font.BOLD, 14));
938 g.drawString("Retrieving PDB data....", 20, currentSize.height / 2);
940 else if(fileLoadingError!=null)
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("Error loading file..." + pdbentry.getId(), 20,
947 currentSize.height / 2);
951 viewer.renderScreenImage(g, currentSize, rectClip);