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(";color gold;wireframe 100");
593 Color col = new Color(viewer.getAtomArgb(atomIndex));
595 resetLastRes.append(";color["
597 + col.getGreen() + ","
598 + col.getBlue() + "];wireframe 0");
600 viewer.evalStringQuiet(eval.toString());
604 public Color getColour(int atomIndex, int pdbResNum, String chain, String pdbfile)
606 if (!pdbfile.equals(pdbentry.getFile()))
609 return new Color(viewer.getAtomArgb(atomIndex));
612 public void updateColours(Object source)
614 colourBySequence( (AlignmentPanel) source);
618 //End StructureListener
619 ////////////////////////////
622 FeatureRenderer fr=null;
623 public void colourBySequence(AlignmentPanel sourceap)
627 if(!colourBySequence || ap.alignFrame.getCurrentView()!=ap.av)
630 StructureMapping[] mapping = ssm.getMapping(pdbentry.getFile());
632 if (mapping.length < 1)
636 SequenceRenderer sr = new SequenceRenderer(ap.av);
638 boolean showFeatures = false;
640 if (ap.av.showSequenceFeatures)
645 fr = new jalview.gui.FeatureRenderer(ap);
648 fr.transferSettings(ap.seqPanel.seqCanvas.getFeatureRenderer());
651 StringBuffer command = new StringBuffer();
654 for (int s = 0; s < sequence.length; s++)
656 for (int m = 0; m < mapping.length; m++)
658 System.out.println(mapping[m].getSequence().getName()+" "+sequence[s].getName()+" "
659 +((mapping[m].getSequence() == sequence[s])
660 +" "+(ap.av.alignment.findIndex(sequence[s]))));
662 if (mapping[m].getSequence() == sequence[s]
663 && ap.av.alignment.findIndex(sequence[s])>-1)
665 for (int r = 0; r < sequence[s].getLength(); r++)
667 int pos = mapping[m].getPDBResNum(
668 sequence[s].findPosition(r));
670 if (pos < 1 || pos==lastPos)
675 Color col = sr.getResidueBoxColour(sequence[s], r);
678 col = fr.findFeatureColour(col, sequence[s], 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()));
856 if (!atomsPicked.contains(picked))
859 viewer.evalString("select "+picked+";label %n %r:%c");
861 viewer.evalString("select "+picked+";label %n %r");
862 atomsPicked.addElement(picked);
866 viewer.evalString("select "+picked+";label off");
867 atomsPicked.removeElement(picked);
870 if (scriptWindow != null)
872 scriptWindow.sendConsoleMessage(strInfo);
873 scriptWindow.sendConsoleMessage("\n");
877 public void notifyAtomHovered(int atomIndex, String strInfo)
879 mouseOverStructure(atomIndex, strInfo);
882 public void sendSyncScript(String script, String appletName)
885 public void showUrl(String url)
888 public void showConsole(boolean showConsole)
890 if (scriptWindow == null)
891 scriptWindow = new ScriptWindow(this);
897 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
898 splitPane.setTopComponent(renderPanel);
899 splitPane.setBottomComponent(scriptWindow);
900 this.getContentPane().add(splitPane, BorderLayout.CENTER);
903 splitPane.setDividerLocation(getHeight()-200);
904 splitPane.validate();
908 if (splitPane != null)
909 splitPane.setVisible(false);
913 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
919 public float functionXY(String functionName, int x, int y)
924 ///End JmolStatusListener
925 ///////////////////////////////
931 final Dimension currentSize = new Dimension();
932 final Rectangle rectClip = new Rectangle();
934 public void paintComponent(Graphics g)
936 getSize(currentSize);
937 g.getClipBounds(rectClip);
941 g.setColor(Color.black);
942 g.fillRect(0, 0, currentSize.width, currentSize.height);
943 g.setColor(Color.white);
944 g.setFont(new Font("Verdana", Font.BOLD, 14));
945 g.drawString("Retrieving PDB data....", 20, currentSize.height / 2);
947 else if(fileLoadingError!=null)
949 g.setColor(Color.black);
950 g.fillRect(0, 0, currentSize.width, currentSize.height);
951 g.setColor(Color.white);
952 g.setFont(new Font("Verdana", Font.BOLD, 14));
953 g.drawString("Error loading file..." + pdbentry.getId(), 20,
954 currentSize.height / 2);
958 viewer.renderScreenImage(g, currentSize, rectClip);