From ea1bc94cb0d4ea4b877101cb7d93283ed4a199fe Mon Sep 17 00:00:00 2001 From: amwaterhouse Date: Tue, 27 Feb 2007 13:27:58 +0000 Subject: [PATCH] jmol added --- src/jalview/appletgui/AppletJmol.java | 590 ++++++++++++++++++++ src/jalview/commands/SlideSequencesCommand.java | 93 ++++ src/jalview/gui/AppJMol.java | 665 +++++++++++++++++++++++ src/jalview/gui/ScriptWindow.java | 619 +++++++++++++++++++++ src/jalview/jbgui/GStructureViewer.java | 120 ++++ 5 files changed, 2087 insertions(+) create mode 100644 src/jalview/appletgui/AppletJmol.java create mode 100644 src/jalview/commands/SlideSequencesCommand.java create mode 100644 src/jalview/gui/AppJMol.java create mode 100644 src/jalview/gui/ScriptWindow.java create mode 100644 src/jalview/jbgui/GStructureViewer.java diff --git a/src/jalview/appletgui/AppletJmol.java b/src/jalview/appletgui/AppletJmol.java new file mode 100644 index 0000000..b03775b --- /dev/null +++ b/src/jalview/appletgui/AppletJmol.java @@ -0,0 +1,590 @@ +/* + * Jalview - A Sequence Alignment Editor and Viewer + * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +package jalview.appletgui; + +import java.util.*; +import java.awt.*; +import java.awt.event.*; + +import jalview.datamodel.*; +import jalview.structure.*; +import jalview.io.*; + +import org.jmol.api.*; +import org.jmol.adapter.smarter.SmarterJmolAdapter; +import org.jmol.popup.*; + + +public class AppletJmol extends Frame + implements StructureListener, JmolStatusListener, + KeyListener, ActionListener, ItemListener + +{ + Menu fileMenu = new Menu("File"); + Menu viewMenu = new Menu("View"); + Menu chainMenu = new Menu("Show Chain"); + MenuItem mappingMenuItem = new MenuItem("View Mapping"); + + JmolViewer viewer; + JmolPopup jmolpopup; + + Panel scriptWindow; + TextField inputLine; + TextArea history; + SequenceI[] sequence; + StructureSelectionManager ssm; + RenderPanel renderPanel; + AlignmentPanel ap; + String fileLoadingError; + boolean loadedInline; + PDBEntry pdbentry; + + public AppletJmol(PDBEntry pdbentry, + SequenceI[] seq, + AlignmentPanel ap, + String protocol) + { + this.ap = ap; + this.sequence = seq; + this.pdbentry = pdbentry; + + String alreadyMapped = StructureSelectionManager + .getStructureSelectionManager() + .alreadyMappedToFile(pdbentry.getId()); + + if (alreadyMapped != null) + { + StructureSelectionManager.getStructureSelectionManager() + .setMapping(seq, pdbentry.getFile(), protocol); + return; + } + + renderPanel = new RenderPanel(); + + this.add(renderPanel, BorderLayout.CENTER); + + viewer = JmolViewer.allocateViewer(renderPanel, new SmarterJmolAdapter()); + + viewer.setAppletContext("jalview", + ap.av.applet.getDocumentBase(), + ap.av.applet.getCodeBase(), + null); + + viewer.setJmolStatusListener(this); + + jmolpopup = JmolPopup.newJmolPopup(viewer); + + this.addWindowListener(new WindowAdapter() + { + public void windowClosing(WindowEvent evt) + { + closeViewer(); + } + }); + + MenuBar menuBar = new MenuBar(); + menuBar.add(fileMenu); + fileMenu.add(mappingMenuItem); + menuBar.add(viewMenu); + mappingMenuItem.addActionListener(this); + viewMenu.add(chainMenu); + this.setMenuBar(menuBar); + + if(pdbentry.getFile()!=null) + { + if (protocol.equals(AppletFormatAdapter.PASTE)) + loadInline(pdbentry.getFile()); + else + viewer.openFile(pdbentry.getFile()); + } + + this.setBounds(400, 400, 400, 400); + + this.setVisible(true); + } + + public void loadInline(String string) + { + loadedInline = true; + viewer.openStringInline(string); + } + + + void setChainMenuItems(Vector chains) + { + chainMenu.removeAll(); + + MenuItem menuItem = new MenuItem("All"); + menuItem.addActionListener(this); + + chainMenu.add(menuItem); + + CheckboxMenuItem menuItemCB; + for (int c = 0; c < chains.size(); c++) + { + menuItemCB = new CheckboxMenuItem(chains.elementAt(c).toString(), true); + menuItemCB.addItemListener(this); + chainMenu.add(menuItemCB); + } + } + + boolean allChainsSelected = false; + void centerViewer() + { + StringBuffer cmd = new StringBuffer(); + for (int i = 0; i < chainMenu.getItemCount(); i++) + { + if (chainMenu.getItem(i) instanceof CheckboxMenuItem) + { + CheckboxMenuItem item = (CheckboxMenuItem) chainMenu.getItem(i); + if (item.getState()) + cmd.append(":" + item.getLabel() + " or "); + } + } + + if (cmd.length() > 0) + cmd.setLength(cmd.length() - 4); + + viewer.evalString("select *;restrict " + + cmd + ";cartoon;center " + cmd); + } + + + void closeViewer() + { + viewer.setModeMouse(org.jmol.viewer.JmolConstants.MOUSE_NONE); + viewer.evalStringQuiet("zap"); + viewer.setJmolStatusListener(null); + viewer = null; + + //We'll need to find out what other + // listeners need to be shut down in Jmol + StructureSelectionManager + .getStructureSelectionManager() + .removeStructureViewerListener(this, pdbentry.getId()); + + this.setVisible(false); + } + + public void actionPerformed(ActionEvent evt) + { + if(evt.getSource()==mappingMenuItem) + { + jalview.appletgui.CutAndPasteTransfer cap + = new jalview.appletgui.CutAndPasteTransfer(false, null); + Frame frame = new Frame(); + frame.add(cap); + + jalview.bin.JalviewLite.addFrame(frame, "PDB - Sequence Mapping", 550, + 600); + cap.setText( + StructureSelectionManager.getStructureSelectionManager().printMapping( + pdbentry.getFile()) + ); + } + else + { + allChainsSelected = true; + for (int i = 0; i < chainMenu.getItemCount(); i++) + { + if (chainMenu.getItem(i) instanceof CheckboxMenuItem) + ( (CheckboxMenuItem) chainMenu.getItem(i)).setState(true); + } + centerViewer(); + allChainsSelected = false; + } + } + + public void itemStateChanged(ItemEvent evt) + { + if (!allChainsSelected) + centerViewer(); + } + + public void keyPressed(KeyEvent evt) + { + if (evt.getKeyCode() == KeyEvent.VK_ENTER + && scriptWindow.isVisible()) + { + viewer.evalString(inputLine.getText()); + + history.append("\n"+inputLine.getText()); + + inputLine.setText(""); + } + + } + + public void keyTyped(KeyEvent evt) + { } + + public void keyReleased(KeyEvent evt){} + + ////////////////////////////////// + ///StructureListener + public String getPdbFile() + { + return "???"; + } + + + + String lastMessage; + public void mouseOverStructure(int atomIndex, String strInfo) + { + int pdbResNum = Integer.parseInt( + strInfo.substring(strInfo.indexOf("]")+ 1, strInfo.indexOf(":"))); + + String chainId = strInfo.substring + (strInfo.indexOf(":"), strInfo.indexOf(".")); + + if (chainId != null) + chainId = chainId.substring(1, chainId.length()); + else + { + chainId = " "; + } + + if (lastMessage == null || !lastMessage.equals(strInfo)) + ssm.mouseOverStructure(pdbResNum, chainId, pdbentry.getFile()); + + lastMessage = strInfo; + } + + StringBuffer resetLastRes = new StringBuffer(); + StringBuffer eval = new StringBuffer(); + + public void highlightAtom(int atomIndex, int pdbResNum, String chain, String pdbfile) + { + if (!pdbfile.equals(pdbentry.getFile())) + return; + + if (resetLastRes.length() > 0) + { + viewer.evalStringQuiet(resetLastRes.toString()); + } + + eval.setLength(0); + eval.append("select " + pdbResNum); + + resetLastRes.setLength(0); + resetLastRes.append("select " + pdbResNum); + + if (!chain.equals(" ")) + { + eval.append(":" + chain); + resetLastRes.append(":" + chain); + } + + eval.append(";color gold;wireframe 100"); + + Color col = new Color(viewer.getAtomArgb(atomIndex)); + + resetLastRes.append(";color[" + + col.getRed() + "," + + col.getGreen() + "," + + col.getBlue() + "];wireframe 0"); + + viewer.evalStringQuiet(eval.toString()); + + } + + public void updateColours(Object source) + { + colourBySequence( (AlignmentPanel) source); + } + +//End StructureListener +//////////////////////////// + + FeatureRenderer fr; + public void colourBySequence(AlignmentPanel ap) + { + StructureMapping[] mapping = ssm.getMapping(pdbentry.getFile()); + + if (mapping.length < 1) + return; + + SequenceRenderer sr = ap.seqPanel.seqCanvas.getSequenceRenderer(); + + boolean showFeatures = false; + if (ap.av.showSequenceFeatures) + { + showFeatures = true; + if (fr == null) + { + fr = new jalview.appletgui.FeatureRenderer(ap.av); + } + + fr.transferSettings(ap.seqPanel.seqCanvas.getFeatureRenderer()); + } + + StringBuffer command = new StringBuffer(); + + for (int s = 0; s < sequence.length; s++) + { + for (int m = 0; m < mapping.length; m++) + { + if (mapping[m].getSequence() == sequence[s]) + { + for (int r = 0; r < sequence[s].getLength(); r++) + { + int pos = mapping[m].getPDBResNum( + sequence[s].findPosition(r)); + + if (pos < 1) + continue; + + command.append(";select " + pos); + + if (!mapping[m].getChain().equals(" ")) + { + command.append(":" + mapping[m].getChain()); + } + + Color col = sr.getResidueBoxColour(sequence[s], r); + + if (showFeatures) + col = fr.findFeatureColour(col, sequence[s], r); + + command.append("; color [" + + col.getRed() + "," + + col.getGreen() + "," + + col.getBlue() + "]"); + + } + } + } + } + + viewer.evalStringQuiet(command.toString()); + } + + ///////////////////////////////// + //JmolStatusListener + + public String eval(String strEval) + { + // System.out.println(strEval); + //"# 'eval' is implemented only for the applet."; + return null; + } + + public void createImage(String file, String type, int quality) + { + System.out.println("JMOL CREATE IMAGE"); + } + + public void setCallbackFunction(String callbackType, + String callbackFunction) + {} + + public void notifyFileLoaded(String fullPathName, String fileName, + String modelName, Object clientFile, + String errorMsg) + { + if(errorMsg!=null) + { + fileLoadingError = errorMsg; + repaint(); + return; + } + + fileLoadingError = null; + + if (fileName != null) + { + //FILE LOADED OK + jmolpopup.updateComputedMenus(); + viewer.evalStringQuiet( + "select backbone;restrict;cartoon;wireframe off;spacefill off"); + + ssm = StructureSelectionManager.getStructureSelectionManager(); + + MCview.PDBfile pdb; + if (loadedInline) + { + pdb = ssm.setMapping(sequence, + pdbentry.getFile(), + AppletFormatAdapter.PASTE); + pdbentry.setFile("INLINE"+pdb.id); + + } + else + { + pdb = ssm.setMapping(sequence, + pdbentry.getFile(), + AppletFormatAdapter.URL); + } + + pdbentry.setId(pdb.id); + + ssm.addStructureViewerListener(this); + + Vector chains = new Vector(); + for (int i = 0; i < pdb.chains.size(); i++) + { + chains.addElement( ( (MCview.PDBChain) pdb.chains.elementAt(i)).id); + } + setChainMenuItems(chains); + + colourBySequence(ap); + + StringBuffer title = new StringBuffer(sequence[0].getName() + ":" + + pdbentry.getId()); + + if (pdbentry.getProperty() != null) + { + if (pdbentry.getProperty().get("method") != null) + { + title.append(" Method: "); + title.append(pdbentry.getProperty().get("method")); + } + if (pdbentry.getProperty().get("chains") != null) + { + title.append(" Chain:"); + title.append(pdbentry.getProperty().get("chains")); + } + } + + this.setTitle(title.toString()); + + } + else + return; + } + + public void notifyFrameChanged(int frameNo) + { + boolean isAnimationRunning = (frameNo <= -2); + } + + public void notifyScriptStart(String statusMessage, String additionalInfo) + {} + + public void sendConsoleEcho(String strEcho) + { + // if (scriptWindow != null) + // scriptWindow.sendConsoleEcho(strEcho); + } + + public void sendConsoleMessage(String strStatus) + { + // if (scriptWindow != null) + // scriptWindow.sendConsoleMessage(strStatus); + } + + public void notifyScriptTermination(String strStatus, int msWalltime) + { + // if (scriptWindow != null) + // scriptWindow.notifyScriptTermination(strStatus, msWalltime); + } + + public void handlePopupMenu(int x, int y) + { + jmolpopup.show(x, y); + } + + public void notifyNewPickingModeMeasurement(int iatom, String strMeasure) + { + notifyAtomPicked(iatom, strMeasure); + } + + public void notifyNewDefaultModeMeasurement(int count, String strInfo) + {} + + public void notifyAtomPicked(int atomIndex, String strInfo) + { + // if (scriptWindow != null) + { + // scriptWindow.sendConsoleMessage(strInfo); + // scriptWindow.sendConsoleMessage("\n"); + } + } + + public void notifyAtomHovered(int atomIndex, String strInfo) + { + mouseOverStructure(atomIndex, strInfo); + } + + public void sendSyncScript(String script, String appletName) + {} + + public void showUrl(String url) + {} + + public void showConsole(boolean showConsole) + { + if (scriptWindow == null) + { + scriptWindow = new Panel(new BorderLayout()); + inputLine = new TextField(); + history = new TextArea(5, 40); + scriptWindow.add(history, BorderLayout.CENTER); + scriptWindow.add(inputLine, BorderLayout.SOUTH); + add(scriptWindow, BorderLayout.SOUTH); + scriptWindow.setVisible(false); + history.setEditable(false); + inputLine.addKeyListener(this); + } + + scriptWindow.setVisible(!scriptWindow.isVisible()); + validate(); + } + + public float functionXY(String functionName, int x, int y) + { + return 0; + } + + ///End JmolStatusListener + /////////////////////////////// + + + class RenderPanel + extends Panel + { + Dimension currentSize = new Dimension(); + Rectangle rectClip = new Rectangle(); + + public void update(Graphics g) { + paint(g); + } + public void paint(Graphics g) + { + currentSize = this.getSize(); + rectClip = g.getClipBounds(); + + if (viewer == null) + { + g.setColor(Color.black); + g.fillRect(0, 0, currentSize.width, currentSize.height); + g.setColor(Color.white); + g.setFont(new Font("Verdana", Font.BOLD, 14)); + g.drawString("Retrieving PDB data....", 20, currentSize.height / 2); + } + else + { + viewer.renderScreenImage(g, currentSize, rectClip); + } + } + } + +} diff --git a/src/jalview/commands/SlideSequencesCommand.java b/src/jalview/commands/SlideSequencesCommand.java new file mode 100644 index 0000000..21385ad --- /dev/null +++ b/src/jalview/commands/SlideSequencesCommand.java @@ -0,0 +1,93 @@ + +/* +* Jalview - A Sequence Alignment Editor and Viewer +* Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +*/ + +package jalview.commands; + +import jalview.datamodel.*; + +public class SlideSequencesCommand extends EditCommand +{ + boolean gapsInsertedBegin = false; + + public SlideSequencesCommand(String description, + SequenceI[] seqsLeft, + SequenceI[] seqsRight, + int slideSize, + char gapChar) + { + this.description = description; + + int lSize = seqsLeft.length; + gapsInsertedBegin = false; + int i, j; + for (i = 0; i < lSize; i++) + { + for (j = 0; j < slideSize; j++) + if (!jalview.util.Comparison.isGap(seqsLeft[i].getCharAt(j))) + { + gapsInsertedBegin = true; + break; + } + } + + if (!gapsInsertedBegin) + edits = new Edit[] + { new Edit(DELETE_GAP, seqsLeft, 0, slideSize, gapChar)}; + else + edits = new Edit[] + { new Edit(INSERT_GAP, seqsRight, 0, slideSize, gapChar)}; + + performEdit(0); + } + + public boolean getGapsInsertedBegin() + { + return gapsInsertedBegin; + } + + public boolean appendSlideCommand(SlideSequencesCommand command) + { + boolean same = false; + + if(command.edits[0].seqs.length==edits[0].seqs.length) + { + same = true; + for (int i = 0; i < command.edits[0].seqs.length; i++) + { + if (edits[0].seqs[i] != command.edits[0].seqs[i]) + { + same = false; + } + } + } + + if(same) + { + Edit[] temp = new Edit[command.edits.length + 1]; + System.arraycopy(command.edits, 0, temp, 0, command.edits.length); + command.edits = temp; + command.edits[command.edits.length - 1] = edits[0]; + } + + return same; + } +} + + diff --git a/src/jalview/gui/AppJMol.java b/src/jalview/gui/AppJMol.java new file mode 100644 index 0000000..7b17d68 --- /dev/null +++ b/src/jalview/gui/AppJMol.java @@ -0,0 +1,665 @@ +/* + * Jalview - A Sequence Alignment Editor and Viewer + * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ +package jalview.gui; + +import java.util.regex.*; +import java.util.*; +import java.awt.*; +import javax.swing.*; +import javax.swing.event.*; +import java.awt.event.*; +import java.io.*; + +import jalview.jbgui.GStructureViewer; +import jalview.datamodel.*; +import jalview.gui.*; +import jalview.structure.*; +import jalview.datamodel.PDBEntry; +import jalview.io.*; + +import org.jmol.api.*; +import org.jmol.adapter.smarter.SmarterJmolAdapter; +import org.jmol.popup.*; + + +public class AppJMol + extends GStructureViewer + implements StructureListener, JmolStatusListener, Runnable + +{ + JmolViewer viewer; + JmolPopup jmolpopup; + ScriptWindow scriptWindow; + PDBEntry pdbentry; + SequenceI[] sequence; + StructureSelectionManager ssm; + RenderPanel renderPanel; + AlignmentPanel ap; + String fileLoadingError; + + public AppJMol(PDBEntry pdbentry, SequenceI[] seq, AlignmentPanel ap) + { + ////////////////////////////////// + //Is the pdb file already loaded? + String alreadyMapped = StructureSelectionManager + .getStructureSelectionManager() + .alreadyMappedToFile(pdbentry.getId()); + if (alreadyMapped != null) + { + int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop, + pdbentry.getId() + " is already displayed." + + "\nDo you want to map sequences to the visible structure?", + "Map Sequences to Visible Window: " + pdbentry.getId(), + JOptionPane.YES_NO_OPTION); + + if (option == JOptionPane.YES_OPTION) + { + StructureSelectionManager.getStructureSelectionManager() + .setMapping(seq, alreadyMapped, AppletFormatAdapter.FILE); + return; + } + } + /////////////////////////////////// + + this.ap = ap; + this.pdbentry = pdbentry; + this.sequence = seq; + + renderPanel = new RenderPanel(); + this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER); + + jalview.gui.Desktop.addInternalFrame(this, "Loading File", 400, 400); + + if (pdbentry.getFile() != null) + { + initJmol(); + } + else + { + Thread worker = new Thread(this); + worker.start(); + } + + this.addInternalFrameListener(new InternalFrameAdapter() + { + public void internalFrameClosing(InternalFrameEvent internalFrameEvent) + { + closeViewer(); + } + }); + } + + void initJmol() + { + StringBuffer title = new StringBuffer(sequence[0].getName() + ":" + + pdbentry.getId()); + + if (pdbentry.getProperty() != null) + { + if (pdbentry.getProperty().get("method") != null) + { + title.append(" Method: "); + title.append(pdbentry.getProperty().get("method")); + } + if (pdbentry.getProperty().get("chains") != null) + { + title.append(" Chain:"); + title.append(pdbentry.getProperty().get("chains")); + } + } + + this.setTitle(title.toString()); + + viewer = org.jmol.api.JmolViewer.allocateViewer(renderPanel, + new SmarterJmolAdapter()); + + viewer.setAppletContext("", null, null, ""); + + viewer.setJmolStatusListener(this); + + scriptWindow = new ScriptWindow(viewer); + + jmolpopup = JmolPopup.newJmolPopup(viewer); + + viewer.openFile(pdbentry.getFile()); + + } + + + void setChainMenuItems(Vector chains) + { + chainMenu.removeAll(); + + JMenuItem menuItem = new JMenuItem("All"); + menuItem.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent evt) + { + allChainsSelected = true; + for(int i=0; i 0) + cmd.setLength(cmd.length() - 4); + + viewer.evalStringQuiet("select *;restrict " + +cmd+";cartoon;center "+cmd); + } + + void closeViewer() + { + viewer.setModeMouse(org.jmol.viewer.JmolConstants.MOUSE_NONE); + viewer.evalStringQuiet("zap"); + viewer.setJmolStatusListener(null); + viewer = null; + + //We'll need to find out what other + // listeners need to be shut down in Jmol + StructureSelectionManager + .getStructureSelectionManager() + .removeStructureViewerListener(this, pdbentry.getFile()); + } + + public void run() + { + try + { + EBIFetchClient ebi = new EBIFetchClient(); + String query = "pdb:" + pdbentry.getId(); + pdbentry.setFile(ebi.fetchDataAsFile(query, "default", "raw") + .getAbsolutePath()); + initJmol(); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + } + + public void pdbFile_actionPerformed(ActionEvent actionEvent) + { + JalviewFileChooser chooser = new JalviewFileChooser( + jalview.bin.Cache.getProperty( + "LAST_DIRECTORY")); + + chooser.setFileView(new JalviewFileView()); + chooser.setDialogTitle("Save PDB File"); + chooser.setToolTipText("Save"); + + int value = chooser.showSaveDialog(this); + + if (value == JalviewFileChooser.APPROVE_OPTION) + { + try + { + BufferedReader in = new BufferedReader(new FileReader(pdbentry.getFile())); + File outFile = chooser.getSelectedFile(); + + PrintWriter out = new PrintWriter(new FileOutputStream(outFile)); + String data; + while ( (data = in.readLine()) != null) + { + if ( + ! (data.indexOf("
") > -1 || data.indexOf("
") > -1) + ) + { + out.println(data); + } + } + out.close(); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + } + } + + public void viewMapping_actionPerformed(ActionEvent actionEvent) + { + jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer(); + jalview.gui.Desktop.addInternalFrame(cap, "PDB - Sequence Mapping", 550, + 600); + cap.setText( + StructureSelectionManager.getStructureSelectionManager().printMapping( + pdbentry.getFile()) + ); + } + + /** + * DOCUMENT ME! + * + * @param e DOCUMENT ME! + */ + public void eps_actionPerformed(ActionEvent e) + { + makePDBImage(jalview.util.ImageMaker.EPS); + } + + /** + * DOCUMENT ME! + * + * @param e DOCUMENT ME! + */ + public void png_actionPerformed(ActionEvent e) + { + makePDBImage(jalview.util.ImageMaker.PNG); + } + + void makePDBImage(int type) + { + int width = getWidth(); + int height = getHeight(); + + jalview.util.ImageMaker im; + + if (type == jalview.util.ImageMaker.PNG) + { + im = new jalview.util.ImageMaker(this, + jalview.util.ImageMaker.PNG, + "Make PNG image from view", + width, height, + null, null); + } + else + { + im = new jalview.util.ImageMaker(this, + jalview.util.ImageMaker.EPS, + "Make EPS file from view", + width, height, + null, this.getTitle()); + } + + if (im.getGraphics() != null) + { + Rectangle rect = new Rectangle(width, height); + viewer.renderScreenImage(im.getGraphics(), + rect.getSize(), rect); + im.writeImage(); + } + } + + ////////////////////////////////// + ///StructureListener + public String getPdbFile() + { + return pdbentry.getFile(); + } + + Pattern pattern = Pattern.compile( + "\\[(.*)\\]([0-9]+)(:[a-zA-Z]*)?\\.([a-zA-Z]+)(/[0-9]*)?" + ); + + String lastMessage; + public void mouseOverStructure(int atomIndex, String strInfo) + { + Matcher matcher = pattern.matcher(strInfo); + matcher.find(); + matcher.group(1); + int pdbResNum = Integer.parseInt(matcher.group(2)); + String chainId = matcher.group(3); + + if (chainId != null) + chainId = chainId.substring(1, chainId.length()); + else + { + chainId = " "; + } + + if (lastMessage == null || !lastMessage.equals(strInfo)) + ssm.mouseOverStructure(pdbResNum, chainId, pdbentry.getFile()); + + lastMessage = strInfo; + } + + StringBuffer resetLastRes = new StringBuffer(); + StringBuffer eval = new StringBuffer(); + + public void highlightAtom(int atomIndex, int pdbResNum, String chain, String pdbfile) + { + if (!pdbfile.equals(pdbentry.getFile())) + return; + + if (resetLastRes.length() > 0) + { + viewer.evalStringQuiet(resetLastRes.toString()); + } + + eval.setLength(0); + eval.append("select " + pdbResNum); + + resetLastRes.setLength(0); + resetLastRes.append("select " + pdbResNum); + + if (!chain.equals(" ")) + { + eval.append(":" + chain); + resetLastRes.append(":" + chain); + } + + eval.append(";color gold;wireframe 100"); + + Color col = new Color(viewer.getAtomArgb(atomIndex)); + + resetLastRes.append(";color[" + + col.getRed() + "," + + col.getGreen() + "," + + col.getBlue() + "];wireframe 0"); + + viewer.evalStringQuiet(eval.toString()); + + } + + public void updateColours(Object source) + { + colourBySequence( (AlignmentPanel) source); + } + +//End StructureListener +//////////////////////////// + + FeatureRenderer fr; + public void colourBySequence(AlignmentPanel ap) + { + StructureMapping[] mapping = ssm.getMapping(pdbentry.getFile()); + + if (mapping.length < 1) + return; + + SequenceRenderer sr = ap.seqPanel.seqCanvas.getSequenceRenderer(); + + boolean showFeatures = false; + if (ap.av.showSequenceFeatures) + { + showFeatures = true; + if (fr == null) + { + fr = new jalview.gui.FeatureRenderer(ap.av); + } + + fr.transferSettings(ap.seqPanel.seqCanvas.getFeatureRenderer()); + } + + StringBuffer command = new StringBuffer(); + + int lastPos = -1; + for (int s = 0; s < sequence.length; s++) + { + for (int m = 0; m < mapping.length; m++) + { + if (mapping[m].getSequence() == sequence[s]) + { + for (int r = 0; r < sequence[s].getLength(); r++) + { + int pos = mapping[m].getPDBResNum( + sequence[s].findPosition(r)); + + if (pos < 1 || pos==lastPos) + continue; + + lastPos = pos; + + command.append(";select " + pos); + + if (!mapping[m].getChain().equals(" ")) + { + command.append(":" + mapping[m].getChain()); + } + + Color col = sr.getResidueBoxColour(sequence[s], r); + + if (showFeatures) + col = fr.findFeatureColour(col, sequence[s], r); + + command.append("; color [" + + col.getRed() + "," + + col.getGreen() + "," + + col.getBlue() + "]"); + + } + } + } + } + + viewer.evalStringQuiet(command.toString()); + } + + ///////////////////////////////// + //JmolStatusListener + + public String eval(String strEval) + { + // System.out.println(strEval); + //"# 'eval' is implemented only for the applet."; + return null; + } + + public void createImage(String file, String type, int quality) + { + System.out.println("JMOL CREATE IMAGE"); + } + + public void setCallbackFunction(String callbackType, + String callbackFunction) + {} + + public void notifyFileLoaded(String fullPathName, String fileName, + String modelName, Object clientFile, + String errorMsg) + { + if(errorMsg!=null) + { + fileLoadingError = errorMsg; + repaint(); + return; + } + + fileLoadingError = null; + + if (fileName != null) + { + + //FILE LOADED OK + ssm = StructureSelectionManager.getStructureSelectionManager(); + MCview.PDBfile pdbFile = ssm.setMapping(sequence, pdbentry.getFile(), AppletFormatAdapter.FILE); + ssm.addStructureViewerListener(this); + + Vector chains = new Vector(); + for(int i=0; i= 0) { + console.outputError(strStatus); + isError = true; + } else if (!isError) { + console.outputStatus(strStatus); + } + } + + public void notifyScriptTermination(String strMsg, int msWalltime) { + if (strMsg != null && strMsg.indexOf("ERROR") >= 0) { + console.outputError(strMsg); + } + runButton.setEnabled(true); + haltButton.setEnabled(false); + } + + public void enterPressed() { + runButton.doClick(100); + // executeCommand(); + } + + + class ExecuteCommandThread extends Thread { + + String strCommand; + ExecuteCommandThread (String command) { + strCommand = command; + } + + public void run() { + try { + executeCommand(strCommand); + } catch (Exception ie) { + Logger.debug("execution command interrupted!"+ie); + } + } + } + + ExecuteCommandThread execThread; + void executeCommandAsThread(){ + String strCommand = console.getCommandString().trim(); + if (strCommand.length() > 0) { + execThread = new ExecuteCommandThread(strCommand); + execThread.start(); + } + } + + void executeCommand(String strCommand) { + boolean doWait; + setError(false); + console.appendNewline(); + console.setPrompt(); + if (strCommand.length() > 0) { + String strErrorMessage = null; + doWait = (strCommand.indexOf("WAIT ") == 0); + if (doWait) { //for testing, mainly + // demonstrates using the statusManager system. + runButton.setEnabled(false); + haltButton.setEnabled(true); + + Vector info = (Vector) viewer + .scriptWaitStatus(strCommand.substring(5), + "+fileLoaded,+scriptStarted,+scriptStatus,+scriptEcho,+scriptTerminated"); + runButton.setEnabled(true); + haltButton.setEnabled(false); + /* + * info = [ statusRecortSet0, statusRecortSet1, statusRecortSet2, ...] + * statusRecordSet = [ statusRecord0, statusRecord1, statusRecord2, ...] + * statusRecord = [int msgPtr, String statusName, int intInfo, String msg] + */ + for (int i = 0; i < info.size(); i++) { + Vector statusRecordSet = (Vector) info.get(i); + for (int j = 0; j < statusRecordSet.size(); j++) { + Vector statusRecord = (Vector) statusRecordSet.get(j); + Logger.info("msg#=" + statusRecord.get(0) + " " + + statusRecord.get(1) + " intInfo=" + statusRecord.get(2) + + " stringInfo=" + statusRecord.get(3)); + } + } + console.appendNewline(); + } else { + boolean isScriptExecuting = viewer.isScriptExecuting(); + if (viewer.checkHalt(strCommand)) + strErrorMessage = (isScriptExecuting ? "string execution halted with " + strCommand : "no script was executing"); + else + strErrorMessage = "";//viewer.scriptCheck(strCommand); + //the problem is that scriptCheck is synchronized, so these might get backed up. + if (strErrorMessage != null && strErrorMessage.length() > 0) { + console.outputError(strErrorMessage); + } else { + //runButton.setEnabled(false); + haltButton.setEnabled(true); + viewer.script(strCommand); + } + } + } + console.grabFocus(); + } + + public void actionPerformed(ActionEvent e) { + Object source = e.getSource(); + if (source == closeButton) { + hide(); + } else if (source == runButton) { + executeCommandAsThread(); + } else if (source == clearButton) { + console.clearContent(); + } else if (source == historyButton) { + console.clearContent(viewer.getSetHistory(Integer.MAX_VALUE)); + } else if (source == stateButton) { + console.clearContent(viewer.getStateInfo()); + } else if (source == haltButton) { + viewer.haltScriptExecution(); + } else if (source == helpButton) { + try{ + jalview.util.BrowserLauncher.openURL( + "http://jmol.sourceforge.net/docs/JmolUserGuide/ch04.html"); + }catch(Exception ex){} + + } + console.grabFocus(); // always grab the focus (e.g., after clear) + } +} + +class ConsoleTextPane extends JTextPane { + + ConsoleDocument consoleDoc; + EnterListener enterListener; + JmolViewer viewer; + + ConsoleTextPane(ScriptWindow scriptWindow) { + super(new ConsoleDocument()); + consoleDoc = (ConsoleDocument)getDocument(); + consoleDoc.setConsoleTextPane(this); + this.enterListener = (EnterListener) scriptWindow; + this.viewer = scriptWindow.viewer; + } + + public String getCommandString() { + String cmd = consoleDoc.getCommandString(); + return cmd; + } + + public void setPrompt() { + consoleDoc.setPrompt(); + } + + public void appendNewline() { + consoleDoc.appendNewline(); + } + + public void outputError(String strError) { + consoleDoc.outputError(strError); + } + + public void outputErrorForeground(String strError) { + consoleDoc.outputErrorForeground(strError); + } + + public void outputEcho(String strEcho) { + consoleDoc.outputEcho(strEcho); + } + + public void outputStatus(String strStatus) { + consoleDoc.outputStatus(strStatus); + } + + public void enterPressed() { + if (enterListener != null) + enterListener.enterPressed(); + } + + public void clearContent() { + clearContent(null); + } + public void clearContent(String text) { + consoleDoc.clearContent(); + if (text != null) + consoleDoc.outputEcho(text); + setPrompt(); + } + + /* (non-Javadoc) + * @see java.awt.Component#processKeyEvent(java.awt.event.KeyEvent) + */ + + /** + * Custom key event processing for command 0 implementation. + * + * Captures key up and key down strokes to call command history + * and redefines the same events with control down to allow + * caret vertical shift. + * + * @see java.awt.Component#processKeyEvent(java.awt.event.KeyEvent) + */ + protected void processKeyEvent(KeyEvent ke) + { + // Id Control key is down, captures events does command + // history recall and inhibits caret vertical shift. + if (ke.getKeyCode() == KeyEvent.VK_UP + && ke.getID() == KeyEvent.KEY_PRESSED + && !ke.isControlDown()) + { + recallCommand(true); + } + else if ( + ke.getKeyCode() == KeyEvent.VK_DOWN + && ke.getID() == KeyEvent.KEY_PRESSED + && !ke.isControlDown()) + { + recallCommand(false); + } + // If Control key is down, redefines the event as if it + // where a key up or key down stroke without modifiers. + // This allows to move the caret up and down + // with no command history recall. + else if ( + (ke.getKeyCode() == KeyEvent.VK_DOWN + || ke.getKeyCode() == KeyEvent.VK_UP) + && ke.getID() == KeyEvent.KEY_PRESSED + && ke.isControlDown()) + { + super + .processKeyEvent(new KeyEvent( + (Component) ke.getSource(), + ke.getID(), + ke.getWhen(), + 0, // No modifiers + ke.getKeyCode(), + ke.getKeyChar(), + ke.getKeyLocation())); + } + // Standard processing for other events. + else + { + super.processKeyEvent(ke); + //check command for compiler-identifyable syntax issues + //this may have to be taken out if people start complaining + //that only some of the commands are being checked + //that is -- that the script itself is not being fully checked + + //not perfect -- help here? + if (ke.getID() == KeyEvent.KEY_RELEASED + && (ke.getKeyCode() > KeyEvent.VK_DOWN) || ke.getKeyCode() == KeyEvent.VK_BACK_SPACE) + checkCommand(); + } + } + + /** + * Recall command history. + * + * @param up - history up or down + */ + void recallCommand(boolean up) { + String cmd = viewer.getSetHistory(up ? -1 : 1); + if (cmd == null) { + return; + } + try { + if (cmd.endsWith(CommandHistory.ERROR_FLAG)) { + cmd = cmd.substring(0, cmd.indexOf(CommandHistory.ERROR_FLAG)); + consoleDoc.replaceCommand(cmd, true); + } else { + consoleDoc.replaceCommand(cmd, false); + } + } catch (BadLocationException e) { + e.printStackTrace(); + } + } + + void checkCommand() { + String strCommand = consoleDoc.getCommandString(); + if (strCommand.length() == 0) + return; + consoleDoc + .colorCommand(viewer.scriptCheck(strCommand) == null ? consoleDoc.attUserInput + : consoleDoc.attError); + } + + +} + +class ConsoleDocument extends DefaultStyledDocument { + + ConsoleTextPane consoleTextPane; + + SimpleAttributeSet attError; + SimpleAttributeSet attEcho; + SimpleAttributeSet attPrompt; + SimpleAttributeSet attUserInput; + SimpleAttributeSet attStatus; + + ConsoleDocument() { + super(); + + attError = new SimpleAttributeSet(); + StyleConstants.setForeground(attError, Color.red); + + attPrompt = new SimpleAttributeSet(); + StyleConstants.setForeground(attPrompt, Color.magenta); + + attUserInput = new SimpleAttributeSet(); + StyleConstants.setForeground(attUserInput, Color.black); + + attEcho = new SimpleAttributeSet(); + StyleConstants.setForeground(attEcho, Color.blue); + StyleConstants.setBold(attEcho, true); + + attStatus = new SimpleAttributeSet(); + StyleConstants.setForeground(attStatus, Color.black); + StyleConstants.setItalic(attStatus, true); + } + + void setConsoleTextPane(ConsoleTextPane consoleTextPane) { + this.consoleTextPane = consoleTextPane; + } + + Position positionBeforePrompt; // starts at 0, so first time isn't tracked (at least on Mac OS X) + Position positionAfterPrompt; // immediately after $, so this will track + int offsetAfterPrompt; // only still needed for the insertString override and replaceCommand + + /** + * Removes all content of the script window, and add a new prompt. + */ + void clearContent() { + try { + super.remove(0, getLength()); + } catch (BadLocationException exception) { + System.out.println("Could not clear script window content: " + exception.getMessage()); + } + } + + void setPrompt() { + try { + super.insertString(getLength(), "$ ", attPrompt); + setOffsetPositions(); + consoleTextPane.setCaretPosition(offsetAfterPrompt); + } catch (BadLocationException e) { + e.printStackTrace(); + } + } + + void setOffsetPositions() { + try { + offsetAfterPrompt = getLength(); + positionBeforePrompt = createPosition(offsetAfterPrompt - 2); + // after prompt should be immediately after $ otherwise tracks the end + // of the line (and no command will be found) at least on Mac OS X it did. + positionAfterPrompt = createPosition(offsetAfterPrompt - 1); + } catch (BadLocationException e) { + e.printStackTrace(); + } + } + + void setNoPrompt() { + try { + offsetAfterPrompt = getLength(); + positionAfterPrompt = positionBeforePrompt = createPosition(offsetAfterPrompt); + consoleTextPane.setCaretPosition(offsetAfterPrompt); + } catch (BadLocationException e) { + e.printStackTrace(); + } + } + + // it looks like the positionBeforePrompt does not track when it started out as 0 + // and a insertString at location 0 occurs. It may be better to track the + // position after the prompt in stead + void outputBeforePrompt(String str, SimpleAttributeSet attribute) { + try { + int pt = consoleTextPane.getCaretPosition(); + Position caretPosition = createPosition(pt); + pt = positionBeforePrompt.getOffset(); + super.insertString(pt, str+"\n", attribute); + setOffsetPositions(); + pt = caretPosition.getOffset(); + consoleTextPane.setCaretPosition(pt); + } catch (BadLocationException e) { + e.printStackTrace(); + } + } + + void outputError(String strError) { + outputBeforePrompt(strError, attError); + } + + void outputErrorForeground(String strError) { + try { + super.insertString(getLength(), strError+"\n", attError); + consoleTextPane.setCaretPosition(getLength()); + } catch (BadLocationException e) { + e.printStackTrace(); + + } + } + + void outputEcho(String strEcho) { + outputBeforePrompt(strEcho, attEcho); + } + + void outputStatus(String strStatus) { + outputBeforePrompt(strStatus, attStatus); + } + + void appendNewline() { + try { + super.insertString(getLength(), "\n", attUserInput); + consoleTextPane.setCaretPosition(getLength()); + } catch (BadLocationException e) { + e.printStackTrace(); + } + } + + // override the insertString to make sure everything typed ends up at the end + // or in the 'command line' using the proper font, and the newline is processed. + public void insertString(int offs, String str, AttributeSet a) + throws BadLocationException { + int ichNewline = str.indexOf('\n'); + if (ichNewline > 0) + str = str.substring(0, ichNewline); + if (ichNewline != 0) { + if (offs < offsetAfterPrompt) { + offs = getLength(); + } + super.insertString(offs, str, a == attError ? a : attUserInput); + consoleTextPane.setCaretPosition(offs+str.length()); + } + if (ichNewline >= 0) { + consoleTextPane.enterPressed(); + } + } + + String getCommandString() { + String strCommand = ""; + try { + int cmdStart = positionAfterPrompt.getOffset(); + strCommand = getText(cmdStart, getLength() - cmdStart); + while (strCommand.length() > 0 && strCommand.charAt(0) == ' ') + strCommand = strCommand.substring(1); + } catch (BadLocationException e) { + e.printStackTrace(); + } + return strCommand; + } + + public void remove(int offs, int len) + throws BadLocationException { + if (offs < offsetAfterPrompt) { + len -= offsetAfterPrompt - offs; + if (len <= 0) + return; + offs = offsetAfterPrompt; + } + super.remove(offs, len); +// consoleTextPane.setCaretPosition(offs); + } + + public void replace(int offs, int length, String str, AttributeSet attrs) + throws BadLocationException { + if (offs < offsetAfterPrompt) { + if (offs + length < offsetAfterPrompt) { + offs = getLength(); + length = 0; + } else { + length -= offsetAfterPrompt - offs; + offs = offsetAfterPrompt; + } + } + super.replace(offs, length, str, attrs); +// consoleTextPane.setCaretPosition(offs + str.length()); + } + + /** + * Replaces current command on script. + * + * @param newCommand new command value + * @param isError true to set error color ends with #?? + * + * @throws BadLocationException + */ + void replaceCommand(String newCommand, boolean isError) throws BadLocationException { + if (positionAfterPrompt == positionBeforePrompt) + return; + replace(offsetAfterPrompt, getLength() - offsetAfterPrompt, newCommand, + isError ? attError : attUserInput); + } + + void colorCommand(SimpleAttributeSet att) { + if (positionAfterPrompt == positionBeforePrompt) + return; + setCharacterAttributes(offsetAfterPrompt, getLength() - offsetAfterPrompt, att, true); + } +} + +interface EnterListener { + public void enterPressed(); +} + diff --git a/src/jalview/jbgui/GStructureViewer.java b/src/jalview/jbgui/GStructureViewer.java new file mode 100644 index 0000000..d60e5fa --- /dev/null +++ b/src/jalview/jbgui/GStructureViewer.java @@ -0,0 +1,120 @@ +/* + * Jalview - A Sequence Alignment Editor and Viewer + * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +package jalview.jbgui; + +import javax.swing.*; +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; + +public class GStructureViewer extends JInternalFrame +{ + public GStructureViewer() + { + try + { + jbInit(); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + } + + private void jbInit() + throws Exception + { + this.setJMenuBar(menuBar); + fileMenu.setText("File"); + savemenu.setActionCommand("Save Image"); + savemenu.setText("Save As"); + pdbFile.setText("PDB File"); + pdbFile.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent actionEvent) + { + pdbFile_actionPerformed(actionEvent); + } + }); + png.setText("PNG"); + png.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent actionEvent) + { + png_actionPerformed(actionEvent); + } + }); + eps.setText("EPS"); + eps.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent actionEvent) + { + eps_actionPerformed(actionEvent); + } + }); + viewMapping.setText("View Mapping"); + viewMapping.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent actionEvent) + { + viewMapping_actionPerformed(actionEvent); + } + }); + viewMenu.setText("View"); + chainMenu.setText("Show Chain"); + menuBar.add(fileMenu); + menuBar.add(viewMenu); + fileMenu.add(savemenu); + fileMenu.add(viewMapping); + savemenu.add(pdbFile); + savemenu.add(png); + savemenu.add(eps); + viewMenu.add(chainMenu); + } + + JMenuBar menuBar = new JMenuBar(); + JMenu fileMenu = new JMenu(); + JMenu savemenu = new JMenu(); + JMenuItem pdbFile = new JMenuItem(); + JMenuItem png = new JMenuItem(); + JMenuItem eps = new JMenuItem(); + JMenuItem viewMapping = new JMenuItem(); + JMenu viewMenu = new JMenu(); + protected JMenu chainMenu = new JMenu(); + JMenu jMenu1 = new JMenu(); + public void pdbFile_actionPerformed(ActionEvent actionEvent) + { + + } + + public void png_actionPerformed(ActionEvent actionEvent) + { + + } + + public void eps_actionPerformed(ActionEvent actionEvent) + { + + } + + public void viewMapping_actionPerformed(ActionEvent actionEvent) + { + + } +} -- 1.7.10.2