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