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