JAL-1742 suppress 'add chain' option for Jmol, pull up shared code for
[jalview.git] / src / jalview / ext / rbvi / chimera / JalviewChimeraBinding.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.ext.rbvi.chimera;
22
23 import java.awt.Color;
24 import java.net.BindException;
25 import java.util.ArrayList;
26 import java.util.LinkedHashMap;
27 import java.util.List;
28 import java.util.Map;
29
30 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
31 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
32 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
33 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
34
35 import jalview.api.AlignmentViewPanel;
36 import jalview.api.FeatureRenderer;
37 import jalview.api.SequenceRenderer;
38 import jalview.bin.Cache;
39 import jalview.datamodel.AlignmentI;
40 import jalview.datamodel.ColumnSelection;
41 import jalview.datamodel.PDBEntry;
42 import jalview.datamodel.SequenceI;
43 import jalview.httpserver.AbstractRequestHandler;
44 import jalview.schemes.ColourSchemeI;
45 import jalview.schemes.ResidueProperties;
46 import jalview.structure.AtomSpec;
47 import jalview.structure.StructureMappingcommandSet;
48 import jalview.structure.StructureSelectionManager;
49 import jalview.structures.models.AAStructureBindingModel;
50 import jalview.util.MessageManager;
51
52 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
53 {
54   // Chimera clause to exclude alternate locations in atom selection
55   private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
56
57   private static final String COLOURING_CHIMERA = MessageManager
58           .getString("status.colouring_chimera");
59
60   private static final boolean debug = false;
61
62   private static final String PHOSPHORUS = "P";
63
64   private static final String ALPHACARBON = "CA";
65
66   /*
67    * Object through which we talk to Chimera
68    */
69   private ChimeraManager viewer;
70
71   /*
72    * Object which listens to Chimera notifications
73    */
74   private AbstractRequestHandler chimeraListener;
75
76   /*
77    * set if chimera state is being restored from some source - instructs binding
78    * not to apply default display style when structure set is updated for first
79    * time.
80    */
81   private boolean loadingFromArchive = false;
82
83   /*
84    * flag to indicate if the Chimera viewer should ignore sequence colouring
85    * events from the structure manager because the GUI is still setting up
86    */
87   private boolean loadingFinished = true;
88
89   public String fileLoadingError;
90
91   /*
92    * Map of ChimeraModel objects keyed by PDB full local file name
93    */
94   private Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<String, List<ChimeraModel>>();
95
96   /*
97    * the default or current model displayed if the model cannot be identified
98    * from the selection message
99    */
100   private int frameNo = 0;
101
102   private String lastCommand;
103
104   private boolean loadedInline;
105
106   /**
107    * current set of model filenames loaded
108    */
109   String[] modelFileNames = null;
110
111   String lastMousedOverAtomSpec;
112
113   private List<String> lastReply;
114
115   /*
116    * incremented every time a load notification is successfully handled -
117    * lightweight mechanism for other threads to detect when they can start
118    * referring to new structures.
119    */
120   private long loadNotifiesHandled = 0;
121
122   /**
123    * Open a PDB structure file in Chimera and set up mappings from Jalview.
124    * 
125    * We check if the PDB model id is already loaded in Chimera, if so don't
126    * reopen it. This is the case if Chimera has opened a saved session file.
127    * 
128    * @param pe
129    * @return
130    */
131   public boolean openFile(PDBEntry pe)
132   {
133     String file = pe.getFile();
134     try
135     {
136       List<ChimeraModel> modelsToMap = new ArrayList<ChimeraModel>();
137       List<ChimeraModel> oldList = viewer.getModelList();
138       boolean alreadyOpen = false;
139
140       /*
141        * If Chimera already has this model, don't reopen it, but do remap it.
142        */
143       for (ChimeraModel open : oldList)
144       {
145         if (open.getModelName().equals(pe.getId()))
146         {
147           alreadyOpen = true;
148           modelsToMap.add(open);
149         }
150       }
151
152       /*
153        * If Chimera doesn't yet have this model, ask it to open it, and retrieve
154        * the model name(s) added by Chimera.
155        */
156       if (!alreadyOpen)
157       {
158         viewer.openModel(file, pe.getId(), ModelType.PDB_MODEL);
159         List<ChimeraModel> newList = viewer.getModelList();
160         // JAL-1728 newList.removeAll(oldList) does not work
161         for (ChimeraModel cm : newList)
162         {
163           if (cm.getModelName().equals(pe.getId()))
164           {
165             modelsToMap.add(cm);
166           }
167         }
168       }
169
170       chimeraMaps.put(file, modelsToMap);
171
172       if (getSsm() != null)
173       {
174         getSsm().addStructureViewerListener(this);
175         // ssm.addSelectionListener(this);
176         FeatureRenderer fr = getFeatureRenderer(null);
177         if (fr != null)
178         {
179           fr.featuresAdded();
180         }
181         refreshGUI();
182       }
183       return true;
184     } catch (Exception q)
185     {
186       log("Exception when trying to open model " + file + "\n"
187               + q.toString());
188       q.printStackTrace();
189     }
190     return false;
191   }
192
193   /**
194    * Constructor
195    * 
196    * @param ssm
197    * @param pdbentry
198    * @param sequenceIs
199    * @param chains
200    * @param protocol
201    */
202   public JalviewChimeraBinding(StructureSelectionManager ssm,
203           PDBEntry[] pdbentry, SequenceI[][] sequenceIs, String[][] chains,
204           String protocol)
205   {
206     super(ssm, pdbentry, sequenceIs, chains, protocol);
207     viewer = new ChimeraManager(
208             new ext.edu.ucsf.rbvi.strucviz2.StructureManager(true));
209   }
210
211   /**
212    * Start a dedicated HttpServer to listen for Chimera notifications, and tell
213    * it to start listening
214    */
215   public void startChimeraListener()
216   {
217     try
218     {
219       chimeraListener = new ChimeraListener(this);
220       viewer.startListening(chimeraListener.getUri());
221     } catch (BindException e)
222     {
223       System.err.println("Failed to start Chimera listener: "
224               + e.getMessage());
225     }
226   }
227
228   /**
229    * Construct a title string for the viewer window based on the data Jalview
230    * knows about
231    * 
232    * @param verbose
233    * @return
234    */
235   public String getViewerTitle(boolean verbose)
236   {
237     return getViewerTitle("Chimera", verbose);
238   }
239
240   /**
241    * Tells Chimera to display only the specified chains
242    * 
243    * @param toshow
244    */
245   public void showChains(List<String> toshow)
246   {
247     /*
248      * Construct a chimera command like
249      * 
250      * ~display #*;~ribbon #*;ribbon :.A,:.B
251      */
252     StringBuilder cmd = new StringBuilder(64);
253     boolean first = true;
254     for (String chain : toshow)
255     {
256       if (!first)
257       {
258         cmd.append(",");
259       }
260       cmd.append(":.").append(chain);
261       first = false;
262     }
263
264     /*
265      * could append ";focus" to this command to resize the display to fill the
266      * window, but it looks more helpful not to (easier to relate chains to the
267      * whole)
268      */
269     final String command = "~display #*; ~ribbon #*; ribbon "
270             + cmd.toString();
271     sendChimeraCommand(command, false);
272   }
273
274   /**
275    * Close down the Jalview viewer and listener, and (optionally) the associated
276    * Chimera window.
277    */
278   public void closeViewer(boolean closeChimera)
279   {
280     getSsm().removeStructureViewerListener(this, this.getPdbFile());
281     if (closeChimera)
282     {
283       viewer.exitChimera();
284     }
285     if (this.chimeraListener != null)
286     {
287       chimeraListener.shutdown();
288       chimeraListener = null;
289     }
290     lastCommand = null;
291     viewer = null;
292
293     releaseUIResources();
294   }
295
296   public void colourByChain()
297   {
298     colourBySequence = false;
299     sendAsynchronousCommand("rainbow chain", COLOURING_CHIMERA);
300   }
301
302   /**
303    * Constructs and sends a Chimera command to colour by charge
304    * <ul>
305    * <li>Aspartic acid and Glutamic acid (negative charge) red</li>
306    * <li>Lysine and Arginine (positive charge) blue</li>
307    * <li>Cysteine - yellow</li>
308    * <li>all others - white</li>
309    * </ul>
310    */
311   public void colourByCharge()
312   {
313     colourBySequence = false;
314     String command = "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS";
315     sendAsynchronousCommand(command, COLOURING_CHIMERA);
316   }
317
318   /**
319    * Construct and send a command to align structures against a reference
320    * structure, based on one or more sequence alignments
321    * 
322    * @param _alignment
323    *          an array of alignments to process
324    * @param _refStructure
325    *          an array of corresponding reference structures (index into pdb
326    *          file array); if a negative value is passed, the first PDB file
327    *          mapped to an alignment sequence is used as the reference for
328    *          superposition
329    * @param _hiddenCols
330    *          an array of corresponding hidden columns for each alignment
331    */
332   public void superposeStructures(AlignmentI[] _alignment,
333           int[] _refStructure, ColumnSelection[] _hiddenCols)
334   {
335     StringBuilder allComs = new StringBuilder(128);
336     String[] files = getPdbFile();
337
338     if (!waitForFileLoad(files))
339     {
340       return;
341     }
342
343     refreshPdbEntries();
344     StringBuilder selectioncom = new StringBuilder(256);
345     for (int a = 0; a < _alignment.length; a++)
346     {
347       int refStructure = _refStructure[a];
348       AlignmentI alignment = _alignment[a];
349       ColumnSelection hiddenCols = _hiddenCols[a];
350
351       if (refStructure >= files.length)
352       {
353         System.err.println("Ignoring invalid reference structure value "
354                 + refStructure);
355         refStructure = -1;
356       }
357
358       /*
359        * 'matched' array will hold 'true' for visible alignment columns where
360        * all sequences have a residue with a mapping to the PDB structure
361        */
362       boolean matched[] = new boolean[alignment.getWidth()];
363       for (int m = 0; m < matched.length; m++)
364       {
365         matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
366       }
367
368       SuperposeData[] structures = new SuperposeData[files.length];
369       for (int f = 0; f < files.length; f++)
370       {
371         structures[f] = new SuperposeData(alignment.getWidth());
372       }
373
374       /*
375        * Calculate the superposable alignment columns ('matched'), and the
376        * corresponding structure residue positions (structures.pdbResNo)
377        */
378       int candidateRefStructure = findSuperposableResidues(alignment,
379               matched, structures);
380       if (refStructure < 0)
381       {
382         /*
383          * If no reference structure was specified, pick the first one that has
384          * a mapping in the alignment
385          */
386         refStructure = candidateRefStructure;
387       }
388
389       int nmatched = 0;
390       for (boolean b : matched)
391       {
392         if (b)
393         {
394           nmatched++;
395         }
396       }
397       if (nmatched < 4)
398       {
399         // TODO: bail out here because superposition illdefined?
400       }
401
402       /*
403        * Generate select statements to select regions to superimpose structures
404        */
405       String[] selcom = new String[files.length];
406       for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
407       {
408         String chainCd = "." + structures[pdbfnum].chain;
409         int lpos = -1;
410         boolean run = false;
411         StringBuilder molsel = new StringBuilder();
412         for (int r = 0; r < matched.length; r++)
413         {
414           if (matched[r])
415           {
416             int pdbResNum = structures[pdbfnum].pdbResNo[r];
417             if (lpos != pdbResNum - 1)
418             {
419               /*
420                * discontiguous - append last residue now
421                */
422               if (lpos != -1)
423               {
424                 molsel.append(String.valueOf(lpos));
425                 molsel.append(chainCd);
426                 molsel.append(",");
427               }
428               run = false;
429             }
430             else
431             {
432               /*
433                * extending a contiguous run
434                */
435               if (!run)
436               {
437                 /*
438                  * start the range selection
439                  */
440                 molsel.append(String.valueOf(lpos));
441                 molsel.append("-");
442               }
443               run = true;
444             }
445             lpos = pdbResNum;
446           }
447         }
448
449         /*
450          * and terminate final selection
451          */
452         if (lpos != -1)
453         {
454           molsel.append(String.valueOf(lpos));
455           molsel.append(chainCd);
456         }
457         if (molsel.length() > 1)
458         {
459           selcom[pdbfnum] = molsel.toString();
460           selectioncom.append("#").append(String.valueOf(pdbfnum))
461                   .append(":");
462           selectioncom.append(selcom[pdbfnum]);
463           selectioncom.append(" ");
464           if (pdbfnum < files.length - 1)
465           {
466             selectioncom.append("| ");
467           }
468         }
469         else
470         {
471           selcom[pdbfnum] = null;
472         }
473       }
474
475       StringBuilder command = new StringBuilder(256);
476       for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
477       {
478         if (pdbfnum == refStructure || selcom[pdbfnum] == null
479                 || selcom[refStructure] == null)
480         {
481           continue;
482         }
483         if (command.length() > 0)
484         {
485           command.append(";");
486         }
487
488         /*
489          * Form Chimera match command, from the 'new' structure to the
490          * 'reference' structure e.g. (50 residues, chain B/A, alphacarbons):
491          * 
492          * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
493          * 
494          * @see
495          * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
496          */
497         command.append("match ").append(getModelSpec(pdbfnum)).append(":");
498         command.append(selcom[pdbfnum]);
499         command.append("@").append(
500                 structures[pdbfnum].isRna ? PHOSPHORUS : ALPHACARBON);
501         // JAL-1757 exclude alternate CA locations
502         command.append(NO_ALTLOCS);
503         command.append(" ").append(getModelSpec(refStructure)).append(":");
504         command.append(selcom[refStructure]);
505         command.append("@").append(
506                 structures[refStructure].isRna ? PHOSPHORUS : ALPHACARBON);
507         command.append(NO_ALTLOCS);
508       }
509       if (selectioncom.length() > 0)
510       {
511         if (debug)
512         {
513           System.out.println("Select regions:\n" + selectioncom.toString());
514           System.out.println("Superimpose command(s):\n"
515                   + command.toString());
516         }
517         allComs.append("~display all; chain @CA|P; ribbon ")
518                 .append(selectioncom.toString())
519                 .append(";" + command.toString());
520       }
521     }
522     if (selectioncom.length() > 0)
523     {
524       // TODO: visually distinguish regions that were superposed
525       if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
526       {
527         selectioncom.setLength(selectioncom.length() - 1);
528       }
529       if (debug)
530       {
531         System.out.println("Select regions:\n" + selectioncom.toString());
532       }
533       allComs.append("; ~display all; chain @CA|P; ribbon ")
534               .append(selectioncom.toString()).append("; focus");
535       sendChimeraCommand(allComs.toString(), false);
536     }
537
538   }
539
540   /**
541    * Helper method to construct model spec in Chimera format:
542    * <ul>
543    * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
544    * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
545    * <ul>
546    * Note for now we only ever choose the first of multiple models. This
547    * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
548    * future if there is a need to select specific sub-models.
549    * 
550    * @param pdbfnum
551    * @return
552    */
553   protected String getModelSpec(int pdbfnum)
554   {
555     if (pdbfnum < 0 || pdbfnum >= getPdbCount())
556     {
557       return "";
558     }
559
560     /*
561      * For now, the test for having sub-models is whether multiple Chimera
562      * models are mapped for the PDB file; the models are returned as a response
563      * to the Chimera command 'list models type molecule', see
564      * ChimeraManager.getModelList().
565      */
566     List<ChimeraModel> maps = chimeraMaps.get(getPdbFile()[pdbfnum]);
567     boolean hasSubModels = maps != null && maps.size() > 1;
568     return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
569   }
570
571   /**
572    * Launch Chimera, unless an instance linked to this object is already
573    * running. Returns true if chimera is successfully launched, or already
574    * running, else false.
575    * 
576    * @return
577    */
578   public boolean launchChimera()
579   {
580     if (!viewer.isChimeraLaunched())
581     {
582       return viewer.launchChimera(StructureManager.getChimeraPaths());
583     }
584     if (viewer.isChimeraLaunched())
585     {
586       return true;
587     }
588     log("Failed to launch Chimera!");
589     return false;
590   }
591
592   /**
593    * Answers true if the Chimera process is still running, false if ended or not
594    * started.
595    * 
596    * @return
597    */
598   public boolean isChimeraRunning()
599   {
600     return viewer.isChimeraLaunched();
601   }
602
603   /**
604    * Send a command to Chimera, and optionally log any responses.
605    * 
606    * @param command
607    * @param logResponse
608    */
609   public void sendChimeraCommand(final String command, boolean logResponse)
610   {
611     viewerCommandHistory(false);
612     if (lastCommand == null || !lastCommand.equals(command))
613     {
614       // trim command or it may never find a match in the replyLog!!
615       lastReply = viewer.sendChimeraCommand(command.trim(), logResponse);
616       if (logResponse && debug)
617       {
618         log("Response from command ('" + command + "') was:\n" + lastReply);
619       }
620     }
621     viewerCommandHistory(true);
622     lastCommand = command;
623   }
624
625   /**
626    * Send a Chimera command asynchronously in a new thread. If the progress
627    * message is not null, display this message while the command is executing.
628    * 
629    * @param command
630    * @param progressMsg
631    */
632   protected abstract void sendAsynchronousCommand(String command,
633           String progressMsg);
634
635   /**
636    * colour any structures associated with sequences in the given alignment
637    * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
638    * if colourBySequence is enabled.
639    */
640   public void colourBySequence(boolean showFeatures,
641           jalview.api.AlignmentViewPanel alignmentv)
642   {
643     if (!colourBySequence || !loadingFinished)
644     {
645       return;
646     }
647     if (getSsm() == null)
648     {
649       return;
650     }
651     String[] files = getPdbFile();
652
653     SequenceRenderer sr = getSequenceRenderer(alignmentv);
654
655     FeatureRenderer fr = null;
656     if (showFeatures)
657     {
658       fr = getFeatureRenderer(alignmentv);
659     }
660     AlignmentI alignment = alignmentv.getAlignment();
661
662     for (jalview.structure.StructureMappingcommandSet cpdbbyseq : getColourBySequenceCommands(
663             files, sr, fr, alignment))
664     {
665       for (String command : cpdbbyseq.commands)
666       {
667         sendAsynchronousCommand(command, COLOURING_CHIMERA);
668       }
669     }
670   }
671
672   /**
673    * @param files
674    * @param sr
675    * @param fr
676    * @param alignment
677    * @return
678    */
679   protected StructureMappingcommandSet[] getColourBySequenceCommands(
680           String[] files, SequenceRenderer sr, FeatureRenderer fr,
681           AlignmentI alignment)
682   {
683     return ChimeraCommands.getColourBySequenceCommand(getSsm(), files,
684             getSequence(), sr, fr, alignment);
685   }
686
687   /**
688    * @param command
689    */
690   protected void executeWhenReady(String command)
691   {
692     waitForChimera();
693     sendChimeraCommand(command, false);
694     waitForChimera();
695   }
696
697   private void waitForChimera()
698   {
699     while (viewer != null && viewer.isBusy())
700     {
701       try
702       {
703         Thread.sleep(15);
704       } catch (InterruptedException q)
705       {
706       }
707     }
708   }
709
710   // End StructureListener
711   // //////////////////////////
712
713   public Color getColour(int atomIndex, int pdbResNum, String chain,
714           String pdbfile)
715   {
716     if (getModelNum(pdbfile) < 0)
717     {
718       return null;
719     }
720     log("get model / residue colour attribute unimplemented");
721     return null;
722   }
723
724   /**
725    * returns the current featureRenderer that should be used to colour the
726    * structures
727    * 
728    * @param alignment
729    * 
730    * @return
731    */
732   public abstract FeatureRenderer getFeatureRenderer(
733           AlignmentViewPanel alignment);
734
735   /**
736    * instruct the Jalview binding to update the pdbentries vector if necessary
737    * prior to matching the viewer's contents to the list of structure files
738    * Jalview knows about.
739    */
740   public abstract void refreshPdbEntries();
741
742   private int getModelNum(String modelFileName)
743   {
744     String[] mfn = getPdbFile();
745     if (mfn == null)
746     {
747       return -1;
748     }
749     for (int i = 0; i < mfn.length; i++)
750     {
751       if (mfn[i].equalsIgnoreCase(modelFileName))
752       {
753         return i;
754       }
755     }
756     return -1;
757   }
758
759   /**
760    * map between index of model filename returned from getPdbFile and the first
761    * index of models from this file in the viewer. Note - this is not trimmed -
762    * use getPdbFile to get number of unique models.
763    */
764   private int _modelFileNameMap[];
765
766   // ////////////////////////////////
767   // /StructureListener
768   @Override
769   public synchronized String[] getPdbFile()
770   {
771     if (viewer == null)
772     {
773       return new String[0];
774     }
775     // if (modelFileNames == null)
776     // {
777     // Collection<ChimeraModel> chimodels = viewer.getChimeraModels();
778     // _modelFileNameMap = new int[chimodels.size()];
779     // int j = 0;
780     // for (ChimeraModel chimodel : chimodels)
781     // {
782     // String mdlName = chimodel.getModelName();
783     // }
784     // modelFileNames = new String[j];
785     // // System.arraycopy(mset, 0, modelFileNames, 0, j);
786     // }
787
788     return chimeraMaps.keySet().toArray(
789             modelFileNames = new String[chimeraMaps.size()]);
790   }
791
792   /**
793    * map from string to applet
794    */
795   public Map getRegistryInfo()
796   {
797     // TODO Auto-generated method stub
798     return null;
799   }
800
801   /**
802    * returns the current sequenceRenderer that should be used to colour the
803    * structures
804    * 
805    * @param alignment
806    * 
807    * @return
808    */
809   public abstract SequenceRenderer getSequenceRenderer(
810           AlignmentViewPanel alignment);
811
812   /**
813    * Construct and send a command to highlight zero, one or more atoms.
814    * 
815    * <pre>
816    * Done by generating a command like (to 'highlight' position 44)
817    *   show #0:44.C
818    * </pre>
819    */
820   @Override
821   public void highlightAtoms(List<AtomSpec> atoms)
822   {
823     if (atoms == null)
824     {
825       return;
826     }
827     StringBuilder atomSpecs = new StringBuilder();
828     boolean first = true;
829     for (AtomSpec atom : atoms)
830     {
831       int pdbResNum = atom.getPdbResNum();
832       String chain = atom.getChain();
833       String pdbfile = atom.getPdbFile();
834       List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
835       if (cms != null && !cms.isEmpty())
836       {
837         /*
838          * Formatting as #0:34.A,#1:33.A doesn't work as desired, so instead we
839          * concatenate multiple 'show' commands
840          */
841         atomSpecs.append(first ? "" : ";show ");
842         first = false;
843         atomSpecs.append("#" + cms.get(0).getModelNumber());
844         atomSpecs.append(":" + pdbResNum);
845         if (!chain.equals(" "))
846         {
847           atomSpecs.append("." + chain);
848         }
849       }
850     }
851     String atomSpec = atomSpecs.toString();
852
853     /*
854      * Avoid repeated commands for the same residue
855      */
856     if (atomSpec.equals(lastMousedOverAtomSpec))
857     {
858       return;
859     }
860
861     StringBuilder command = new StringBuilder(32);
862     viewerCommandHistory(false);
863     if (atomSpec.length() > 0)
864     {
865       command.append("show ").append(atomSpec);
866       viewer.sendChimeraCommand(command.toString(), false);
867     }
868     viewerCommandHistory(true);
869     this.lastMousedOverAtomSpec = atomSpec;
870   }
871
872   /**
873    * Query Chimera for its current selection, and highlight it on the alignment
874    */
875   public void highlightChimeraSelection()
876   {
877     /*
878      * Ask Chimera for its current selection
879      */
880     List<String> selection = viewer.getSelectedResidueSpecs();
881
882     /*
883      * Parse model number, residue and chain for each selected position,
884      * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
885      */
886     List<AtomSpec> atomSpecs = new ArrayList<AtomSpec>();
887     for (String atomSpec : selection)
888     {
889       int colonPos = atomSpec.indexOf(":");
890       if (colonPos == -1)
891       {
892         continue; // malformed
893       }
894
895       int hashPos = atomSpec.indexOf("#");
896       String modelSubmodel = atomSpec.substring(hashPos + 1, colonPos);
897       int dotPos = modelSubmodel.indexOf(".");
898       int modelId = 0;
899       try
900       {
901         modelId = Integer.valueOf(dotPos == -1 ? modelSubmodel
902                 : modelSubmodel.substring(0, dotPos));
903       } catch (NumberFormatException e)
904       {
905         // ignore, default to model 0
906       }
907
908       String residueChain = atomSpec.substring(colonPos + 1);
909       dotPos = residueChain.indexOf(".");
910       int pdbResNum = Integer.parseInt(dotPos == -1 ? residueChain
911               : residueChain.substring(0, dotPos));
912
913       String chainId = dotPos == -1 ? "" : residueChain
914               .substring(dotPos + 1);
915
916       /*
917        * Work out the pdbfilename from the model number
918        */
919       String pdbfilename = modelFileNames[frameNo];
920       findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
921       {
922         for (ChimeraModel cm : chimeraMaps.get(pdbfile))
923         {
924           if (cm.getModelNumber() == modelId)
925           {
926             pdbfilename = pdbfile;
927             break findfileloop;
928           }
929         }
930       }
931       atomSpecs.add(new AtomSpec(pdbfilename, chainId, pdbResNum, 0));
932     }
933
934     /*
935      * Broadcast the selection (which may be empty, if the user just cleared all
936      * selections)
937      */
938     getSsm().mouseOverStructure(atomSpecs);
939   }
940
941   private void log(String message)
942   {
943     System.err.println("## Chimera log: " + message);
944   }
945
946   private void viewerCommandHistory(boolean enable)
947   {
948     // log("(Not yet implemented) History "
949     // + ((debug || enable) ? "on" : "off"));
950   }
951
952   public long getLoadNotifiesHandled()
953   {
954     return loadNotifiesHandled;
955   }
956
957   public void setJalviewColourScheme(ColourSchemeI cs)
958   {
959     colourBySequence = false;
960
961     if (cs == null)
962     {
963       return;
964     }
965
966     // Chimera expects RBG values in the range 0-1
967     final double normalise = 255D;
968     viewerCommandHistory(false);
969     StringBuilder command = new StringBuilder(128);
970
971     List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
972             false);
973     for (String res : residueSet)
974     {
975       Color col = cs.findColour(res.charAt(0));
976       command.append("color " + col.getRed() / normalise + ","
977               + col.getGreen() / normalise + "," + col.getBlue()
978               / normalise + " ::" + res + ";");
979     }
980
981     sendAsynchronousCommand(command.toString(), COLOURING_CHIMERA);
982     viewerCommandHistory(true);
983   }
984
985   /**
986    * called when the binding thinks the UI needs to be refreshed after a Chimera
987    * state change. this could be because structures were loaded, or because an
988    * error has occurred.
989    */
990   public abstract void refreshGUI();
991
992   public void setLoadingFromArchive(boolean loadingFromArchive)
993   {
994     this.loadingFromArchive = loadingFromArchive;
995   }
996
997   /**
998    * 
999    * @return true if Chimeral is still restoring state or loading is still going
1000    *         on (see setFinsihedLoadingFromArchive)
1001    */
1002   public boolean isLoadingFromArchive()
1003   {
1004     return loadingFromArchive && !loadingFinished;
1005   }
1006
1007   /**
1008    * modify flag which controls if sequence colouring events are honoured by the
1009    * binding. Should be true for normal operation
1010    * 
1011    * @param finishedLoading
1012    */
1013   public void setFinishedLoadingFromArchive(boolean finishedLoading)
1014   {
1015     loadingFinished = finishedLoading;
1016   }
1017
1018   /**
1019    * Send the Chimera 'background solid <color>" command.
1020    * 
1021    * @see https 
1022    *      ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
1023    *      .html
1024    * @param col
1025    */
1026   public void setBackgroundColour(Color col)
1027   {
1028     viewerCommandHistory(false);
1029     double normalise = 255D;
1030     final String command = "background solid " + col.getRed() / normalise
1031             + "," + col.getGreen() / normalise + "," + col.getBlue()
1032             / normalise + ";";
1033     viewer.sendChimeraCommand(command, false);
1034     viewerCommandHistory(true);
1035   }
1036
1037   /**
1038    * Ask Chimera to save its session to the given file. Returns true if
1039    * successful, else false.
1040    * 
1041    * @param filepath
1042    * @return
1043    */
1044   public boolean saveSession(String filepath)
1045   {
1046     if (isChimeraRunning())
1047     {
1048       List<String> reply = viewer.sendChimeraCommand("save " + filepath,
1049               true);
1050       if (reply.contains("Session written"))
1051       {
1052         return true;
1053       }
1054       else
1055       {
1056         Cache.log
1057                 .error("Error saving Chimera session: " + reply.toString());
1058       }
1059     }
1060     return false;
1061   }
1062
1063   /**
1064    * Ask Chimera to open a session file. Returns true if successful, else false.
1065    * The filename must have a .py extension for this command to work.
1066    * 
1067    * @param filepath
1068    * @return
1069    */
1070   public boolean openSession(String filepath)
1071   {
1072     sendChimeraCommand("open " + filepath, true);
1073     // todo: test for failure - how?
1074     return true;
1075   }
1076
1077   /**
1078    * Returns a list of chains mapped in this viewer. Note this list is not
1079    * currently scoped per structure.
1080    * 
1081    * @return
1082    */
1083   public List<String> getChainNames()
1084   {
1085     List<String> names = new ArrayList<String>();
1086     String[][] allNames = getChains();
1087     if (allNames != null)
1088     {
1089       for (String[] chainsForPdb : allNames)
1090       {
1091         if (chainsForPdb != null)
1092         {
1093           for (String chain : chainsForPdb)
1094           {
1095             if (chain != null && !names.contains(chain))
1096             {
1097               names.add(chain);
1098             }
1099           }
1100         }
1101       }
1102     }
1103     return names;
1104   }
1105
1106   /**
1107    * Send a 'focus' command to Chimera to recentre the visible display
1108    */
1109   public void focusView()
1110   {
1111     sendChimeraCommand("focus", false);
1112   }
1113 }