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