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