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