2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.ext.rbvi.chimera;
23 import jalview.api.AlignmentViewPanel;
24 import jalview.api.FeatureRenderer;
25 import jalview.api.SequenceRenderer;
26 import jalview.bin.Cache;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.ColumnSelection;
29 import jalview.datamodel.PDBEntry;
30 import jalview.datamodel.SequenceI;
31 import jalview.schemes.ColourSchemeI;
32 import jalview.schemes.ResidueProperties;
33 import jalview.structure.StructureMapping;
34 import jalview.structure.StructureMappingcommandSet;
35 import jalview.structure.StructureSelectionManager;
36 import jalview.structures.models.AAStructureBindingModel;
37 import jalview.util.Comparison;
38 import jalview.util.MessageManager;
40 import java.awt.Color;
41 import java.util.ArrayList;
42 import java.util.Enumeration;
43 import java.util.HashMap;
44 import java.util.LinkedHashMap;
45 import java.util.List;
48 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
49 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
50 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
51 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
53 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
56 private static final boolean debug = false;
58 private static final String PHOSPHORUS = "P";
60 private static final String ALPHACARBON = "CA";
62 private StructureManager csm;
64 private ChimeraManager viewer;
67 * set if chimera state is being restored from some source - instructs binding
68 * not to apply default display style when structure set is updated for first
71 private boolean loadingFromArchive = false;
74 * flag to indicate if the Chimera viewer should ignore sequence colouring
75 * events from the structure manager because the GUI is still setting up
77 private boolean loadingFinished = true;
80 * state flag used to check if the Chimera viewer's paint method can be called
82 private boolean finishedInit = false;
84 private List<String> atomsPicked = new ArrayList<String>();
86 private List<String> chainNames;
88 private Map<String, String> chainFile;
90 private StringBuffer eval = new StringBuffer();
92 public String fileLoadingError;
95 * Map of ChimeraModel objects keyed by PDB full local file name
97 private Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<String, List<ChimeraModel>>();
100 * the default or current model displayed if the model cannot be identified
101 * from the selection message
103 private int frameNo = 0;
105 private String lastCommand;
107 private String lastMessage;
109 private boolean loadedInline;
112 * Open a PDB structure file in Chimera and set up mappings from Jalview.
114 * We check if the PDB model id is already loaded in Chimera, if so don't
115 * reopen it. This is the case if Chimera has opened a saved session file.
120 public boolean openFile(PDBEntry pe)
122 String file = pe.getFile();
125 List<ChimeraModel> modelsToMap = new ArrayList<ChimeraModel>();
126 List<ChimeraModel> oldList = viewer.getModelList();
127 boolean alreadyOpen = false;
130 * If Chimera already has this model, don't reopen it, but do remap it.
132 for (ChimeraModel open : oldList)
134 if (open.getModelName().equals(pe.getId()))
137 modelsToMap.add(open);
142 * If Chimera doesn't yet have this model, ask it to open it, and retrieve
143 * the model names added by Chimera.
147 viewer.openModel(file, pe.getId(), ModelType.PDB_MODEL);
148 modelsToMap = viewer.getModelList();
149 modelsToMap.removeAll(oldList);
152 chimeraMaps.put(file, modelsToMap);
154 if (getSsm() != null)
156 getSsm().addStructureViewerListener(this);
157 // ssm.addSelectionListener(this);
158 FeatureRenderer fr = getFeatureRenderer(null);
166 } catch (Exception q)
168 log("Exception when trying to open model " + file + "\n"
176 * current set of model filenames loaded
178 String[] modelFileNames = null;
181 StringBuffer resetLastRes = new StringBuffer();
183 private List<String> lastReply;
194 public JalviewChimeraBinding(StructureSelectionManager ssm,
195 PDBEntry[] pdbentry, SequenceI[][] sequenceIs, String[][] chains,
198 super(ssm, pdbentry, sequenceIs, chains, protocol);
199 viewer = new ChimeraManager(
200 csm = new ext.edu.ucsf.rbvi.strucviz2.StructureManager(true));
209 public JalviewChimeraBinding(StructureSelectionManager ssm,
210 ChimeraManager theViewer)
214 csm = viewer.getStructureManager();
218 * Construct a title string for the viewer window based on the data Jalview
224 public String getViewerTitle(boolean verbose)
226 return getViewerTitle("Chimera", verbose);
230 * prepare the view for a given set of models/chains. chainList contains
231 * strings of the form 'pdbfilename:Chaincode'
234 * list of chains to make visible
236 public void centerViewer(List<String> toshow)
238 StringBuilder cmd = new StringBuilder(64);
240 for (String lbl : toshow)
246 mlength = lbl.indexOf(":", p);
247 } while (p < mlength && mlength < (lbl.length() - 2));
248 // TODO: lookup each pdb id and recover proper model number for it.
249 cmd.append("#" + getModelNum(chainFile.get(lbl)) + "."
250 + lbl.substring(mlength + 1) + " or ");
252 if (cmd.length() > 0)
254 cmd.setLength(cmd.length() - 4);
256 String cmdstring = cmd.toString();
257 evalStateCommand("~display #*; ~ribbon #*; ribbon " + cmdstring
258 + ";focus " + cmdstring, false);
262 * Close down the Jalview viewer, and (optionally) the associated Chimera
265 public void closeViewer(boolean closeChimera)
267 getSsm().removeStructureViewerListener(this, this.getPdbFile());
270 viewer.exitChimera();
274 releaseUIResources();
277 public void colourByChain()
279 colourBySequence = false;
280 evalStateCommand("rainbow chain", false);
283 public void colourByCharge()
285 colourBySequence = false;
287 "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS",
292 * superpose the structures associated with sequences in the alignment
293 * according to their corresponding positions.
295 public void superposeStructures(AlignmentI alignment)
297 superposeStructures(alignment, -1, null);
301 * superpose the structures associated with sequences in the alignment
302 * according to their corresponding positions. ded)
304 * @param refStructure
305 * - select which pdb file to use as reference (default is -1 - the
306 * first structure in the alignment)
308 public void superposeStructures(AlignmentI alignment, int refStructure)
310 superposeStructures(alignment, refStructure, null);
314 * superpose the structures associated with sequences in the alignment
315 * according to their corresponding positions. ded)
317 * @param refStructure
318 * - select which pdb file to use as reference (default is -1 - the
319 * first structure in the alignment)
323 public void superposeStructures(AlignmentI alignment, int refStructure,
324 ColumnSelection hiddenCols)
326 superposeStructures(new AlignmentI[]
327 { alignment }, new int[]
328 { refStructure }, new ColumnSelection[]
332 public void superposeStructures(AlignmentI[] _alignment,
333 int[] _refStructure, ColumnSelection[] _hiddenCols)
335 assert (_alignment.length == _refStructure.length && _alignment.length != _hiddenCols.length);
336 StringBuilder allComs = new StringBuilder(128); // Chimera superposition cmd
337 String[] files = getPdbFile();
338 // check to see if we are still waiting for Chimera files
339 long starttime = System.currentTimeMillis();
340 boolean waiting = true;
344 for (String file : files)
348 // HACK - in Jalview 2.8 this call may not be threadsafe so we catch
349 // every possible exception
350 StructureMapping[] sm = getSsm().getMapping(file);
351 if (sm == null || sm.length == 0)
355 } catch (Exception x)
363 // we wait around for a reasonable time before we give up
365 && System.currentTimeMillis() < (10000 + 1000 * files.length + starttime));
369 .println("RUNTIME PROBLEM: Chimera seems to be taking a long time to process all the structures.");
373 StringBuffer selectioncom = new StringBuffer();
374 for (int a = 0; a < _alignment.length; a++)
376 int refStructure = _refStructure[a];
377 AlignmentI alignment = _alignment[a];
378 ColumnSelection hiddenCols = _hiddenCols[a];
380 && selectioncom.length() > 0
381 && !selectioncom.substring(selectioncom.length() - 1).equals(
384 selectioncom.append(" ");
386 // process this alignment
387 if (refStructure >= files.length)
389 System.err.println("Invalid reference structure value "
393 if (refStructure < -1)
398 boolean matched[] = new boolean[alignment.getWidth()];
399 for (int m = 0; m < matched.length; m++)
402 matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
405 int commonrpositions[][] = new int[files.length][alignment.getWidth()];
406 String isel[] = new String[files.length];
407 String[] targetC = new String[files.length];
408 String[] chainNames = new String[files.length];
409 String[] atomSpec = new String[files.length];
410 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
412 StructureMapping[] mapping = getSsm().getMapping(files[pdbfnum]);
413 // RACE CONDITION - getMapping only returns Jmol loaded filenames once
414 // Jmol callback has completed.
415 if (mapping == null || mapping.length < 1)
417 throw new Error(MessageManager.getString("error.implementation_error_chimera_getting_data"));
420 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
421 for (int s = 0; s < seqCountForPdbFile; s++)
423 for (int sp, m = 0; m < mapping.length; m++)
425 final SequenceI theSequence = getSequence()[pdbfnum][s];
426 if (mapping[m].getSequence() == theSequence
427 && (sp = alignment.findIndex(theSequence)) > -1)
429 if (refStructure == -1)
431 refStructure = pdbfnum;
433 SequenceI asp = alignment.getSequenceAt(sp);
434 for (int r = 0; r < matched.length; r++)
440 matched[r] = false; // assume this is not a good site
441 if (r >= asp.getLength())
446 if (Comparison.isGap(asp.getCharAt(r)))
448 // no mapping to gaps in sequence
451 int t = asp.findPosition(r); // sequence position
452 int apos = mapping[m].getAtomNum(t);
453 int pos = mapping[m].getPDBResNum(t);
455 if (pos < 1 || pos == lastPos)
457 // can't align unmapped sequence
460 matched[r] = true; // this is a good ite
462 // just record this residue position
463 commonrpositions[pdbfnum][r] = pos;
465 // create model selection suffix
466 isel[pdbfnum] = "#" + pdbfnum;
467 if (mapping[m].getChain() == null
468 || mapping[m].getChain().trim().length() == 0)
470 targetC[pdbfnum] = "";
474 targetC[pdbfnum] = "." + mapping[m].getChain();
476 chainNames[pdbfnum] = mapping[m].getPdbId()
478 atomSpec[pdbfnum] = asp.getRNA() != null ? PHOSPHORUS : ALPHACARBON;
479 // move on to next pdb file
480 s = seqCountForPdbFile;
487 // TODO: consider bailing if nmatched less than 4 because superposition
490 // TODO: refactor superposable position search (above) from jmol selection
491 // construction (below)
493 String[] selcom = new String[files.length];
496 // generate select statements to select regions to superimpose structures
498 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
500 String chainCd = targetC[pdbfnum];
503 StringBuffer molsel = new StringBuffer();
504 for (int r = 0; r < matched.length; r++)
512 if (lpos != commonrpositions[pdbfnum][r] - 1)
517 molsel.append((run ? "" : ":") + lpos);
518 molsel.append(chainCd);
524 // continuous run - and lpos >-1
527 // at the beginning, so add dash
528 molsel.append(":" + lpos);
533 lpos = commonrpositions[pdbfnum][r];
534 // molsel.append(lpos);
537 // add final selection phrase
540 molsel.append((run ? "" : ":") + lpos);
541 molsel.append(chainCd);
542 // molsel.append("");
544 if (molsel.length() > 1)
546 selcom[pdbfnum] = molsel.toString();
547 selectioncom.append("#" + pdbfnum);
548 selectioncom.append(selcom[pdbfnum]);
549 selectioncom.append(" ");
550 if (pdbfnum < files.length - 1)
552 selectioncom.append("| ");
557 selcom[pdbfnum] = null;
561 StringBuilder command = new StringBuilder(256);
562 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
564 if (pdbfnum == refStructure || selcom[pdbfnum] == null
565 || selcom[refStructure] == null)
569 if (command.length() > 0)
575 * Form Chimera match command, from the 'new' structure to the
576 * 'reference' structure e.g. (residues 1-91, chain B/A, alphacarbons):
578 * match #1:1-91.B@CA #0:1-91.A@CA
581 * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
583 command.append("match #" + pdbfnum /* +".1" */);
584 // TODO: handle sub-models
585 command.append(selcom[pdbfnum]);
586 command.append("@" + atomSpec[pdbfnum]);
587 command.append(" #" + refStructure /* +".1" */);
588 command.append(selcom[refStructure]);
589 command.append("@" + atomSpec[refStructure]);
591 if (selectioncom.length() > 0)
595 System.out.println("Select regions:\n" + selectioncom.toString());
596 System.out.println("Superimpose command(s):\n"
597 + command.toString());
599 allComs.append("~display all; chain @CA|P; ribbon "
600 + selectioncom.toString() + ";"+command.toString());
601 // selcom.append("; ribbons; ");
604 if (selectioncom.length() > 0)
605 {// finally, mark all regions that were superposed.
606 if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
608 selectioncom.setLength(selectioncom.length() - 1);
612 System.out.println("Select regions:\n" + selectioncom.toString());
614 allComs.append("; ~display all; chain @CA|P; ribbon "
615 + selectioncom.toString() + "; focus");
616 // evalStateCommand("select *; backbone; select "+selcom.toString()+"; cartoons; center "+selcom.toString());
617 evalStateCommand(allComs.toString(), true /* false */);
622 private void checkLaunched()
624 if (!viewer.isChimeraLaunched())
626 viewer.launchChimera(StructureManager.getChimeraPaths());
628 if (!viewer.isChimeraLaunched())
630 log("Failed to launch Chimera!");
635 * Answers true if the Chimera process is still running, false if ended or not
640 public boolean isChimeraRunning()
642 return viewer.isChimeraLaunched();
646 * Send a command to Chimera, launching it first if necessary, and optionally
652 public void evalStateCommand(final String command, boolean logResponse)
654 viewerCommandHistory(false);
656 if (lastCommand == null || !lastCommand.equals(command))
658 // trim command or it may never find a match in the replyLog!!
659 lastReply = viewer.sendChimeraCommand(command.trim(), logResponse);
660 if (debug && logResponse)
662 log("Response from command ('" + command + "') was:\n" + lastReply);
665 viewerCommandHistory(true);
666 lastCommand = command;
670 * colour any structures associated with sequences in the given alignment
671 * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
672 * if colourBySequence is enabled.
674 public void colourBySequence(boolean showFeatures,
675 jalview.api.AlignmentViewPanel alignmentv)
677 if (!colourBySequence || !loadingFinished)
681 if (getSsm() == null)
685 String[] files = getPdbFile();
687 SequenceRenderer sr = getSequenceRenderer(alignmentv);
689 FeatureRenderer fr = null;
692 fr = getFeatureRenderer(alignmentv);
694 AlignmentI alignment = alignmentv.getAlignment();
696 for (jalview.structure.StructureMappingcommandSet cpdbbyseq : getColourBySequenceCommands(files, sr, fr, alignment))
698 for (String command : cpdbbyseq.commands)
700 executeWhenReady(command);
712 protected StructureMappingcommandSet[] getColourBySequenceCommands(
713 String[] files, SequenceRenderer sr, FeatureRenderer fr,
714 AlignmentI alignment)
716 return ChimeraCommands
717 .getColourBySequenceCommand(getSsm(), files, getSequence(), sr,
725 protected void executeWhenReady(String command)
728 evalStateCommand(command, false);
732 private void waitForChimera()
734 while (viewer != null && viewer.isBusy())
738 } catch (InterruptedException q)
745 // End StructureListener
746 // //////////////////////////
748 public Color getColour(int atomIndex, int pdbResNum, String chain,
751 if (getModelNum(pdbfile) < 0)
755 log("get model / residue colour attribute unimplemented");
760 * returns the current featureRenderer that should be used to colour the
767 public abstract FeatureRenderer getFeatureRenderer(
768 AlignmentViewPanel alignment);
771 * instruct the Jalview binding to update the pdbentries vector if necessary
772 * prior to matching the jmol view's contents to the list of structure files
773 * Jalview knows about.
775 public abstract void refreshPdbEntries();
777 private int getModelNum(String modelFileName)
779 String[] mfn = getPdbFile();
784 for (int i = 0; i < mfn.length; i++)
786 if (mfn[i].equalsIgnoreCase(modelFileName))
795 * map between index of model filename returned from getPdbFile and the first
796 * index of models from this file in the viewer. Note - this is not trimmed -
797 * use getPdbFile to get number of unique models.
799 private int _modelFileNameMap[];
801 // ////////////////////////////////
802 // /StructureListener
803 public synchronized String[] getPdbFile()
807 return new String[0];
809 // if (modelFileNames == null)
811 // Collection<ChimeraModel> chimodels = viewer.getChimeraModels();
812 // _modelFileNameMap = new int[chimodels.size()];
814 // for (ChimeraModel chimodel : chimodels)
816 // String mdlName = chimodel.getModelName();
818 // modelFileNames = new String[j];
819 // // System.arraycopy(mset, 0, modelFileNames, 0, j);
822 return chimeraMaps.keySet().toArray(
823 modelFileNames = new String[chimeraMaps.size()]);
827 * map from string to applet
829 public Map getRegistryInfo()
831 // TODO Auto-generated method stub
836 * returns the current sequenceRenderer that should be used to colour the
843 public abstract SequenceRenderer getSequenceRenderer(
844 AlignmentViewPanel alignment);
847 public void highlightAtom(int atomIndex, int pdbResNum, String chain,
850 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
853 int mdlNum = cms.get(0).getModelNumber();
855 viewerCommandHistory(false);
856 // viewer.stopListening();
857 if (resetLastRes.length() > 0)
860 eval.append(resetLastRes.toString() + ";");
863 eval.append("display "); // +modelNum
865 resetLastRes.setLength(0);
866 resetLastRes.append("~display ");
868 eval.append(" #" + (mdlNum));
869 resetLastRes.append(" #" + (mdlNum));
871 // complete select string
873 eval.append(":" + pdbResNum);
874 resetLastRes.append(":" + pdbResNum);
875 if (!chain.equals(" "))
877 eval.append("." + chain);
878 resetLastRes.append("." + chain);
881 viewer.sendChimeraCommand(eval.toString(), false);
882 viewerCommandHistory(true);
883 // viewer.startListening();
887 private void log(String message)
889 System.err.println("## Chimera log: " + message);
892 private void viewerCommandHistory(boolean enable)
894 // log("(Not yet implemented) History "
895 // + ((debug || enable) ? "on" : "off"));
898 public void loadInline(String string)
902 // viewer.loadInline(strModel, isAppend);
904 // construct fake fullPathName and fileName so we can identify the file
906 // Then, construct pass a reader for the string to Jmol.
907 // ((org.jmol.Viewer.Viewer) viewer).loadModelFromFile(fullPathName,
908 // fileName, null, reader, false, null, null, 0);
909 // viewer.openStringInline(string);
910 log("cannot load inline in Chimera, yet");
913 public void mouseOverStructure(int atomIndex, String strInfo)
915 // function to parse a mouseOver event from Chimera
918 int alocsep = strInfo.indexOf("^");
919 int mdlSep = strInfo.indexOf("/");
920 int chainSeparator = strInfo.indexOf(":"), chainSeparator1 = -1;
922 if (chainSeparator == -1)
924 chainSeparator = strInfo.indexOf(".");
925 if (mdlSep > -1 && mdlSep < chainSeparator)
927 chainSeparator1 = chainSeparator;
928 chainSeparator = mdlSep;
931 // handle insertion codes
934 pdbResNum = Integer.parseInt(strInfo.substring(
935 strInfo.indexOf("]") + 1, alocsep));
940 pdbResNum = Integer.parseInt(strInfo.substring(
941 strInfo.indexOf("]") + 1, chainSeparator));
945 if (strInfo.indexOf(":") > -1)
947 chainId = strInfo.substring(strInfo.indexOf(":") + 1,
948 strInfo.indexOf("."));
955 String pdbfilename = modelFileNames[frameNo]; // default is first or current
959 if (chainSeparator1 == -1)
961 chainSeparator1 = strInfo.indexOf(".", mdlSep);
963 String mdlId = (chainSeparator1 > -1) ? strInfo.substring(mdlSep + 1,
964 chainSeparator1) : strInfo.substring(mdlSep + 1);
967 // recover PDB filename for the model hovered over.
968 int _mp = _modelFileNameMap.length - 1, mnumber = new Integer(mdlId)
970 while (mnumber < _modelFileNameMap[_mp])
974 pdbfilename = modelFileNames[_mp];
975 if (pdbfilename == null)
977 // pdbfilename = new File(viewer.getModelFileName(mnumber))
978 // .getAbsolutePath();
981 } catch (Exception e)
986 if (lastMessage == null || !lastMessage.equals(strInfo))
988 getSsm().mouseOverStructure(pdbResNum, chainId, pdbfilename);
991 lastMessage = strInfo;
994 public void notifyAtomPicked(int atomIndex, String strInfo, String strData)
997 * this implements the toggle label behaviour copied from the original
998 * structure viewer, MCView
1000 if (strData != null)
1002 System.err.println("Ignoring additional pick data string " + strData);
1004 // rewrite these selections for chimera (DNA, RNA and protein)
1005 int chainSeparator = strInfo.indexOf(":");
1007 if (chainSeparator == -1)
1009 chainSeparator = strInfo.indexOf(".");
1012 String picked = strInfo.substring(strInfo.indexOf("]") + 1,
1014 String mdlString = "";
1015 if ((p = strInfo.indexOf(":")) > -1)
1017 picked += strInfo.substring(p + 1, strInfo.indexOf("."));
1020 if ((p = strInfo.indexOf("/")) > -1)
1022 mdlString += strInfo.substring(p, strInfo.indexOf(" #"));
1024 picked = "((" + picked + ".CA" + mdlString + ")|(" + picked + ".P"
1026 viewerCommandHistory(false);
1028 if (!atomsPicked.contains(picked))
1030 viewer.select(picked);
1031 atomsPicked.add(picked);
1035 viewer.select("not " + picked);
1036 atomsPicked.remove(picked);
1038 viewerCommandHistory(true);
1039 // TODO: in application this happens
1041 // if (scriptWindow != null)
1043 // scriptWindow.sendConsoleMessage(strInfo);
1044 // scriptWindow.sendConsoleMessage("\n");
1049 // incremented every time a load notification is successfully handled -
1050 // lightweight mechanism for other threads to detect when they can start
1051 // referring to new structures.
1052 private long loadNotifiesHandled = 0;
1054 public long getLoadNotifiesHandled()
1056 return loadNotifiesHandled;
1059 public void notifyFileLoaded(String fullPathName, String fileName2,
1060 String modelName, String errorMsg, int modelParts)
1062 if (errorMsg != null)
1064 fileLoadingError = errorMsg;
1068 // TODO: deal sensibly with models loaded inLine:
1069 // modelName will be null, as will fullPathName.
1071 // the rest of this routine ignores the arguments, and simply interrogates
1072 // the Jmol view to find out what structures it contains, and adds them to
1073 // the structure selection manager.
1074 fileLoadingError = null;
1075 String[] oldmodels = modelFileNames;
1076 modelFileNames = null;
1077 chainNames = new ArrayList<String>();
1078 chainFile = new HashMap<String, String>();
1079 boolean notifyLoaded = false;
1080 String[] modelfilenames = getPdbFile();
1081 // first check if we've lost any structures
1082 if (oldmodels != null && oldmodels.length > 0)
1085 for (int i = 0; i < oldmodels.length; i++)
1087 for (int n = 0; n < modelfilenames.length; n++)
1089 if (modelfilenames[n] == oldmodels[i])
1091 oldmodels[i] = null;
1095 if (oldmodels[i] != null)
1102 String[] oldmfn = new String[oldm];
1104 for (int i = 0; i < oldmodels.length; i++)
1106 if (oldmodels[i] != null)
1108 oldmfn[oldm++] = oldmodels[i];
1111 // deregister the Jmol instance for these structures - we'll add
1112 // ourselves again at the end for the current structure set.
1113 getSsm().removeStructureViewerListener(this, oldmfn);
1117 // register ourselves as a listener and notify the gui that it needs to
1119 getSsm().addStructureViewerListener(this);
1123 FeatureRenderer fr = getFeatureRenderer(null);
1129 loadNotifiesHandled++;
1131 setLoadingFromArchive(false);
1134 public void setJalviewColourScheme(ColourSchemeI cs)
1136 colourBySequence = false;
1146 // Chimera expects RBG values in the range 0-1
1147 final double normalise = 255D;
1148 viewerCommandHistory(false);
1149 // TODO: Switch between nucleotide or aa selection expressions
1150 Enumeration en = ResidueProperties.aa3Hash.keys();
1151 StringBuilder command = new StringBuilder(128);
1152 command.append("color white;");
1153 while (en.hasMoreElements())
1155 res = en.nextElement().toString();
1156 index = ((Integer) ResidueProperties.aa3Hash.get(res)).intValue();
1162 col = cs.findColour(ResidueProperties.aa[index].charAt(0));
1163 command.append("color " + col.getRed() / normalise + ","
1164 + col.getGreen() / normalise + "," + col.getBlue()
1165 / normalise + " ::" + res + ";");
1168 evalStateCommand(command.toString(),false);
1169 viewerCommandHistory(true);
1173 * called when the binding thinks the UI needs to be refreshed after a Chimera
1174 * state change. this could be because structures were loaded, or because an
1175 * error has occurred.
1177 public abstract void refreshGUI();
1179 public void setLoadingFromArchive(boolean loadingFromArchive)
1181 this.loadingFromArchive = loadingFromArchive;
1186 * @return true if Chimeral is still restoring state or loading is still going
1187 * on (see setFinsihedLoadingFromArchive)
1189 public boolean isLoadingFromArchive()
1191 return loadingFromArchive && !loadingFinished;
1195 * modify flag which controls if sequence colouring events are honoured by the
1196 * binding. Should be true for normal operation
1198 * @param finishedLoading
1200 public void setFinishedLoadingFromArchive(boolean finishedLoading)
1202 loadingFinished = finishedLoading;
1206 * Send the Chimera 'background solid <color>" command.
1209 * ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
1213 public void setBackgroundColour(Color col)
1215 viewerCommandHistory(false);
1216 double normalise = 255D;
1217 final String command = "background solid " + col.getRed() / normalise + ","
1218 + col.getGreen() / normalise + "," + col.getBlue()
1220 viewer.sendChimeraCommand(command, false);
1221 viewerCommandHistory(true);
1227 * @return text report of alignment between pdbfile and any associated
1228 * alignment sequences
1230 public String printMapping(String pdbfile)
1232 return getSsm().printMapping(pdbfile);
1236 * Ask Chimera to save its session to the given file. Returns true if
1237 * successful, else false.
1242 public boolean saveSession(String filepath)
1244 if (isChimeraRunning())
1246 List<String> reply = viewer.sendChimeraCommand("save " + filepath,
1248 if (reply.contains("Session written"))
1255 .error("Error saving Chimera session: " + reply.toString());
1262 * Ask Chimera to open a session file. Returns true if successful, else false.
1263 * The filename must have a .py extension for this command to work.
1268 public boolean openSession(String filepath)
1270 evalStateCommand("open " + filepath, true);
1271 // todo: test for failure - how?
1275 public boolean isFinishedInit()
1277 return finishedInit;
1280 public void setFinishedInit(boolean finishedInit)
1282 this.finishedInit = finishedInit;
1285 public List<String> getChainNames()