JAL-2296 unit test for reading Chimera attributes to Jalview features
[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.SearchResults;
31 import jalview.datamodel.SearchResults.Match;
32 import jalview.datamodel.SequenceFeature;
33 import jalview.datamodel.SequenceI;
34 import jalview.httpserver.AbstractRequestHandler;
35 import jalview.schemes.ColourSchemeI;
36 import jalview.schemes.ResidueProperties;
37 import jalview.structure.AtomSpec;
38 import jalview.structure.StructureMappingcommandSet;
39 import jalview.structure.StructureSelectionManager;
40 import jalview.structures.models.AAStructureBindingModel;
41 import jalview.util.MessageManager;
42
43 import java.awt.Color;
44 import java.io.File;
45 import java.io.FileOutputStream;
46 import java.io.IOException;
47 import java.io.PrintWriter;
48 import java.net.BindException;
49 import java.util.ArrayList;
50 import java.util.Collections;
51 import java.util.Hashtable;
52 import java.util.LinkedHashMap;
53 import java.util.List;
54 import java.util.Map;
55
56 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
57 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
58 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
59 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
60
61 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
62 {
63   public static final String CHIMERA_FEATURE_GROUP = "Chimera";
64
65   // Chimera clause to exclude alternate locations in atom selection
66   private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
67
68   private static final String COLOURING_CHIMERA = MessageManager
69           .getString("status.colouring_chimera");
70
71   private static final boolean debug = false;
72
73   private static final String PHOSPHORUS = "P";
74
75   private static final String ALPHACARBON = "CA";
76
77   private List<String> chainNames = new ArrayList<String>();
78
79   private Hashtable<String, String> chainFile = new Hashtable<String, String>();
80   
81   /*
82    * Object through which we talk to Chimera
83    */
84   private ChimeraManager viewer;
85
86   /*
87    * Object which listens to Chimera notifications
88    */
89   private AbstractRequestHandler chimeraListener;
90
91   /*
92    * set if chimera state is being restored from some source - instructs binding
93    * not to apply default display style when structure set is updated for first
94    * time.
95    */
96   private boolean loadingFromArchive = false;
97
98   /*
99    * flag to indicate if the Chimera viewer should ignore sequence colouring
100    * events from the structure manager because the GUI is still setting up
101    */
102   private boolean loadingFinished = true;
103
104   public String fileLoadingError;
105
106   /*
107    * Map of ChimeraModel objects keyed by PDB full local file name
108    */
109   private Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<String, List<ChimeraModel>>();
110
111   String lastHighlightCommand;
112
113   /*
114    * incremented every time a load notification is successfully handled -
115    * lightweight mechanism for other threads to detect when they can start
116    * referring to new structures.
117    */
118   private long loadNotifiesHandled = 0;
119
120   /**
121    * Open a PDB structure file in Chimera and set up mappings from Jalview.
122    * 
123    * We check if the PDB model id is already loaded in Chimera, if so don't
124    * reopen it. This is the case if Chimera has opened a saved session file.
125    * 
126    * @param pe
127    * @return
128    */
129   public boolean openFile(PDBEntry pe)
130   {
131     String file = pe.getFile();
132     try
133     {
134       List<ChimeraModel> modelsToMap = new ArrayList<ChimeraModel>();
135       List<ChimeraModel> oldList = viewer.getModelList();
136       boolean alreadyOpen = false;
137
138       /*
139        * If Chimera already has this model, don't reopen it, but do remap it.
140        */
141       for (ChimeraModel open : oldList)
142       {
143         if (open.getModelName().equals(pe.getId()))
144         {
145           alreadyOpen = true;
146           modelsToMap.add(open);
147         }
148       }
149
150       /*
151        * If Chimera doesn't yet have this model, ask it to open it, and retrieve
152        * the model name(s) added by Chimera.
153        */
154       if (!alreadyOpen)
155       {
156         viewer.openModel(file, pe.getId(), ModelType.PDB_MODEL);
157         List<ChimeraModel> newList = viewer.getModelList();
158         // JAL-1728 newList.removeAll(oldList) does not work
159         for (ChimeraModel cm : newList)
160         {
161           if (cm.getModelName().equals(pe.getId()))
162           {
163             modelsToMap.add(cm);
164           }
165         }
166       }
167
168       chimeraMaps.put(file, modelsToMap);
169
170       if (getSsm() != null)
171       {
172         getSsm().addStructureViewerListener(this);
173         // ssm.addSelectionListener(this);
174         FeatureRenderer fr = getFeatureRenderer(null);
175         if (fr != null)
176         {
177           fr.featuresAdded();
178         }
179         refreshGUI();
180       }
181       return true;
182     } catch (Exception q)
183     {
184       log("Exception when trying to open model " + file + "\n"
185               + q.toString());
186       q.printStackTrace();
187     }
188     return false;
189   }
190
191   /**
192    * Constructor
193    * 
194    * @param ssm
195    * @param pdbentry
196    * @param sequenceIs
197    * @param protocol
198    */
199   public JalviewChimeraBinding(StructureSelectionManager ssm,
200           PDBEntry[] pdbentry, SequenceI[][] sequenceIs, String protocol)
201   {
202     super(ssm, pdbentry, sequenceIs, protocol);
203     viewer = new ChimeraManager(
204             new ext.edu.ucsf.rbvi.strucviz2.StructureManager(true));
205   }
206
207   /**
208    * Start a dedicated HttpServer to listen for Chimera notifications, and tell
209    * it to start listening
210    */
211   public void startChimeraListener()
212   {
213     try
214     {
215       chimeraListener = new ChimeraListener(this);
216       viewer.startListening(chimeraListener.getUri());
217     } catch (BindException e)
218     {
219       System.err.println("Failed to start Chimera listener: "
220               + e.getMessage());
221     }
222   }
223
224   /**
225    * Construct a title string for the viewer window based on the data Jalview
226    * knows about
227    * 
228    * @param verbose
229    * @return
230    */
231   public String getViewerTitle(boolean verbose)
232   {
233     return getViewerTitle("Chimera", verbose);
234   }
235
236   /**
237    * Tells Chimera to display only the specified chains
238    * 
239    * @param toshow
240    */
241   public void showChains(List<String> toshow)
242   {
243     /*
244      * Construct a chimera command like
245      * 
246      * ~display #*;~ribbon #*;ribbon :.A,:.B
247      */
248     StringBuilder cmd = new StringBuilder(64);
249     boolean first = true;
250     for (String chain : toshow)
251     {
252       int modelNumber = getModelNoForChain(chain);
253       String showChainCmd = modelNumber == -1 ? "" : modelNumber + ":."
254               + chain.split(":")[1];
255       if (!first)
256       {
257         cmd.append(",");
258       }
259       cmd.append(showChainCmd);
260       first = false;
261     }
262
263     /*
264      * could append ";focus" to this command to resize the display to fill the
265      * window, but it looks more helpful not to (easier to relate chains to the
266      * whole)
267      */
268     final String command = "~display #*; ~ribbon #*; ribbon :"
269             + cmd.toString();
270     sendChimeraCommand(command, false);
271   }
272
273   /**
274    * Close down the Jalview viewer and listener, and (optionally) the associated
275    * Chimera window.
276    */
277   public void closeViewer(boolean closeChimera)
278   {
279     getSsm().removeStructureViewerListener(this, this.getPdbFile());
280     if (closeChimera)
281     {
282       viewer.exitChimera();
283     }
284     if (this.chimeraListener != null)
285     {
286       chimeraListener.shutdown();
287       chimeraListener = null;
288     }
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 and return any responses.
603    * <p>
604    * Does nothing, and returns null, if the command is the same as the last one
605    * sent [why?].
606    * 
607    * @param command
608    * @param getResponse
609    */
610   public List<String> sendChimeraCommand(final String command,
611           boolean getResponse)
612   {
613     if (viewer == null)
614     {
615       // ? thread running after viewer shut down
616       return null;
617     }
618     List<String> reply = null;
619     viewerCommandHistory(false);
620     if (true /*lastCommand == null || !lastCommand.equals(command)*/)
621     {
622       // trim command or it may never find a match in the replyLog!!
623       List<String> lastReply = viewer.sendChimeraCommand(command.trim(),
624               getResponse);
625       if (getResponse)
626       {
627         reply = lastReply;
628         if (debug)
629         {
630           log("Response from command ('" + command + "') was:\n"
631                   + lastReply);
632         }
633       }
634     }
635     viewerCommandHistory(true);
636
637     return reply;
638   }
639
640   /**
641    * Send a Chimera command asynchronously in a new thread. If the progress
642    * message is not null, display this message while the command is executing.
643    * 
644    * @param command
645    * @param progressMsg
646    */
647   protected abstract void sendAsynchronousCommand(String command,
648           String progressMsg);
649
650   /**
651    * colour any structures associated with sequences in the given alignment
652    * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
653    * if colourBySequence is enabled.
654    */
655   public void colourBySequence(boolean showFeatures,
656           jalview.api.AlignmentViewPanel alignmentv)
657   {
658     if (!colourBySequence || !loadingFinished)
659     {
660       return;
661     }
662     if (getSsm() == null)
663     {
664       return;
665     }
666     String[] files = getPdbFile();
667
668     SequenceRenderer sr = getSequenceRenderer(alignmentv);
669
670     FeatureRenderer fr = null;
671     if (showFeatures)
672     {
673       fr = getFeatureRenderer(alignmentv);
674     }
675     AlignmentI alignment = alignmentv.getAlignment();
676
677     StructureMappingcommandSet colourBySequenceCommands = ChimeraCommands
678             .getColourBySequenceCommand(getSsm(), files, getSequence(), sr,
679                     fr, alignment);
680     for (String command : colourBySequenceCommands.commands)
681     {
682       sendAsynchronousCommand(command, COLOURING_CHIMERA);
683     }
684   }
685
686   /**
687    * @param command
688    */
689   protected void executeWhenReady(String command)
690   {
691     waitForChimera();
692     sendChimeraCommand(command, false);
693     waitForChimera();
694   }
695
696   private void waitForChimera()
697   {
698     while (viewer != null && viewer.isBusy())
699     {
700       try
701       {
702         Thread.sleep(15);
703       } catch (InterruptedException q)
704       {
705       }
706     }
707   }
708
709   // End StructureListener
710   // //////////////////////////
711
712   /**
713    * returns the current featureRenderer that should be used to colour the
714    * structures
715    * 
716    * @param alignment
717    * 
718    * @return
719    */
720   public abstract FeatureRenderer getFeatureRenderer(
721           AlignmentViewPanel alignment);
722
723   /**
724    * instruct the Jalview binding to update the pdbentries vector if necessary
725    * prior to matching the viewer's contents to the list of structure files
726    * Jalview knows about.
727    */
728   public abstract void refreshPdbEntries();
729
730   // ////////////////////////////////
731   // /StructureListener
732   @Override
733   public synchronized String[] getPdbFile()
734   {
735     if (viewer == null)
736     {
737       return new String[0];
738     }
739
740     return chimeraMaps.keySet().toArray(
741             modelFileNames = new String[chimeraMaps.size()]);
742   }
743
744   /**
745    * returns the current sequenceRenderer that should be used to colour the
746    * structures
747    * 
748    * @param alignment
749    * 
750    * @return
751    */
752   public abstract SequenceRenderer getSequenceRenderer(
753           AlignmentViewPanel alignment);
754
755   /**
756    * Construct and send a command to highlight zero, one or more atoms. We do
757    * this by sending an "rlabel" command to show the residue label at that
758    * position.
759    */
760   @Override
761   public void highlightAtoms(List<AtomSpec> atoms)
762   {
763     if (atoms == null || atoms.size() == 0)
764     {
765       return;
766     }
767
768     StringBuilder cmd = new StringBuilder(128);
769     boolean first = true;
770     boolean found = false;
771
772     for (AtomSpec atom : atoms)
773     {
774       int pdbResNum = atom.getPdbResNum();
775       String chain = atom.getChain();
776       String pdbfile = atom.getPdbFile();
777       List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
778       if (cms != null && !cms.isEmpty())
779       {
780         if (first)
781         {
782           cmd.append("rlabel #").append(cms.get(0).getModelNumber())
783                   .append(":");
784         }
785         else
786         {
787           cmd.append(",");
788         }
789         first = false;
790         cmd.append(pdbResNum);
791         if (!chain.equals(" "))
792         {
793           cmd.append(".").append(chain);
794         }
795         found = true;
796       }
797     }
798     String command = cmd.toString();
799
800     /*
801      * avoid repeated commands for the same residue
802      */
803     if (command.equals(lastHighlightCommand))
804     {
805       return;
806     }
807
808     /*
809      * unshow the label for the previous residue
810      */
811     if (lastHighlightCommand != null)
812     {
813       viewer.sendChimeraCommand("~" + lastHighlightCommand, false);
814     }
815     if (found)
816     {
817       viewer.sendChimeraCommand(command, false);
818     }
819     this.lastHighlightCommand = command;
820   }
821
822   /**
823    * Query Chimera for its current selection, and highlight it on the alignment
824    */
825   public void highlightChimeraSelection()
826   {
827     /*
828      * Ask Chimera for its current selection
829      */
830     List<String> selection = viewer.getSelectedResidueSpecs();
831
832     /*
833      * Parse model number, residue and chain for each selected position,
834      * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
835      */
836     List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(selection);
837
838     /*
839      * Broadcast the selection (which may be empty, if the user just cleared all
840      * selections)
841      */
842     getSsm().mouseOverStructure(atomSpecs);
843   }
844
845   /**
846    * Converts a list of Chimera atomspecs to a list of AtomSpec representing the
847    * corresponding residues (if any) in Jalview
848    * 
849    * @param structureSelection
850    * @return
851    */
852   protected List<AtomSpec> convertStructureResiduesToAlignment(
853           List<String> structureSelection)
854   {
855     List<AtomSpec> atomSpecs = new ArrayList<AtomSpec>();
856     for (String atomSpec : structureSelection)
857     {
858       try
859       {
860         AtomSpec spec = AtomSpec.fromChimeraAtomspec(atomSpec);
861         String pdbfilename = getPdbFileForModel(spec.getModelNumber());
862         spec.setPdbFile(pdbfilename);
863         atomSpecs.add(spec);
864       } catch (IllegalArgumentException e)
865       {
866         System.err.println("Failed to parse atomspec: " + atomSpec);
867       }
868     }
869     return atomSpecs;
870   }
871
872   /**
873    * @param modelId
874    * @return
875    */
876   protected String getPdbFileForModel(int modelId)
877   {
878     /*
879      * Work out the pdbfilename from the model number
880      */
881     String pdbfilename = modelFileNames[0];
882     findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
883     {
884       for (ChimeraModel cm : chimeraMaps.get(pdbfile))
885       {
886         if (cm.getModelNumber() == modelId)
887         {
888           pdbfilename = pdbfile;
889           break findfileloop;
890         }
891       }
892     }
893     return pdbfilename;
894   }
895
896   private void log(String message)
897   {
898     System.err.println("## Chimera log: " + message);
899   }
900
901   private void viewerCommandHistory(boolean enable)
902   {
903     // log("(Not yet implemented) History "
904     // + ((debug || enable) ? "on" : "off"));
905   }
906
907   public long getLoadNotifiesHandled()
908   {
909     return loadNotifiesHandled;
910   }
911
912   public void setJalviewColourScheme(ColourSchemeI cs)
913   {
914     colourBySequence = false;
915
916     if (cs == null)
917     {
918       return;
919     }
920
921     // Chimera expects RBG values in the range 0-1
922     final double normalise = 255D;
923     viewerCommandHistory(false);
924     StringBuilder command = new StringBuilder(128);
925
926     List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
927             false);
928     for (String res : residueSet)
929     {
930       Color col = cs.findColour(res.charAt(0));
931       command.append("color " + col.getRed() / normalise + ","
932               + col.getGreen() / normalise + "," + col.getBlue()
933               / normalise + " ::" + res + ";");
934     }
935
936     sendAsynchronousCommand(command.toString(), COLOURING_CHIMERA);
937     viewerCommandHistory(true);
938   }
939
940   /**
941    * called when the binding thinks the UI needs to be refreshed after a Chimera
942    * state change. this could be because structures were loaded, or because an
943    * error has occurred.
944    */
945   public abstract void refreshGUI();
946
947   @Override
948   public void setLoadingFromArchive(boolean loadingFromArchive)
949   {
950     this.loadingFromArchive = loadingFromArchive;
951   }
952
953   /**
954    * 
955    * @return true if Chimeral is still restoring state or loading is still going
956    *         on (see setFinsihedLoadingFromArchive)
957    */
958   @Override
959   public boolean isLoadingFromArchive()
960   {
961     return loadingFromArchive && !loadingFinished;
962   }
963
964   /**
965    * modify flag which controls if sequence colouring events are honoured by the
966    * binding. Should be true for normal operation
967    * 
968    * @param finishedLoading
969    */
970   @Override
971   public void setFinishedLoadingFromArchive(boolean finishedLoading)
972   {
973     loadingFinished = finishedLoading;
974   }
975
976   /**
977    * Send the Chimera 'background solid <color>" command.
978    * 
979    * @see https 
980    *      ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
981    *      .html
982    * @param col
983    */
984   public void setBackgroundColour(Color col)
985   {
986     viewerCommandHistory(false);
987     double normalise = 255D;
988     final String command = "background solid " + col.getRed() / normalise
989             + "," + col.getGreen() / normalise + "," + col.getBlue()
990             / normalise + ";";
991     viewer.sendChimeraCommand(command, false);
992     viewerCommandHistory(true);
993   }
994
995   /**
996    * Ask Chimera to save its session to the given file. Returns true if
997    * successful, else false.
998    * 
999    * @param filepath
1000    * @return
1001    */
1002   public boolean saveSession(String filepath)
1003   {
1004     if (isChimeraRunning())
1005     {
1006       List<String> reply = viewer.sendChimeraCommand("save " + filepath,
1007               true);
1008       if (reply.contains("Session written"))
1009       {
1010         return true;
1011       }
1012       else
1013       {
1014         Cache.log
1015                 .error("Error saving Chimera session: " + reply.toString());
1016       }
1017     }
1018     return false;
1019   }
1020
1021   /**
1022    * Ask Chimera to open a session file. Returns true if successful, else false.
1023    * The filename must have a .py extension for this command to work.
1024    * 
1025    * @param filepath
1026    * @return
1027    */
1028   public boolean openSession(String filepath)
1029   {
1030     sendChimeraCommand("open " + filepath, true);
1031     // todo: test for failure - how?
1032     return true;
1033   }
1034
1035   /**
1036    * Returns a list of chains mapped in this viewer. Note this list is not
1037    * currently scoped per structure.
1038    * 
1039    * @return
1040    */
1041   @Override
1042   public List<String> getChainNames()
1043   {
1044     return chainNames;
1045   }
1046
1047   /**
1048    * Send a 'focus' command to Chimera to recentre the visible display
1049    */
1050   public void focusView()
1051   {
1052     sendChimeraCommand("focus", false);
1053   }
1054
1055   /**
1056    * Send a 'show' command for all atoms in the currently selected columns
1057    * 
1058    * TODO: pull up to abstract structure viewer interface
1059    * 
1060    * @param vp
1061    */
1062   public void highlightSelection(AlignmentViewPanel vp)
1063   {
1064     List<Integer> cols = vp.getAlignViewport().getColumnSelection()
1065             .getSelected();
1066     AlignmentI alignment = vp.getAlignment();
1067     StructureSelectionManager sm = getSsm();
1068     for (SequenceI seq : alignment.getSequences())
1069     {
1070       /*
1071        * convert selected columns into sequence positions
1072        */
1073       int[] positions = new int[cols.size()];
1074       int i = 0;
1075       for (Integer col : cols)
1076       {
1077         positions[i++] = seq.findPosition(col);
1078       }
1079       sm.highlightStructure(this, seq, positions);
1080     }
1081   }
1082
1083   /**
1084    * Constructs and send commands to Chimera to set attributes on residues for
1085    * features visible in Jalview
1086    * 
1087    * @param avp
1088    */
1089   public void sendFeaturesToViewer(AlignmentViewPanel avp)
1090   {
1091     // TODO refactor as required to pull up to an interface
1092     AlignmentI alignment = avp.getAlignment();
1093     FeatureRenderer fr = getFeatureRenderer(avp);
1094
1095     /*
1096      * fr is null if feature display is turned off
1097      */
1098     if (fr == null)
1099     {
1100       return;
1101     }
1102
1103     String[] files = getPdbFile();
1104     if (files == null)
1105     {
1106       return;
1107     }
1108
1109     StructureMappingcommandSet commandSet = ChimeraCommands
1110             .getSetAttributeCommandsForFeatures(getSsm(), files,
1111                     getSequence(), fr, alignment);
1112     String[] commands = commandSet.commands;
1113     if (commands.length > 10)
1114     {
1115       sendCommandsByFile(commands);
1116     }
1117     else
1118     {
1119       for (String command : commands)
1120       {
1121         sendAsynchronousCommand(command, null);
1122       }
1123     }
1124   }
1125
1126   /**
1127    * Write commands to a temporary file, and send a command to Chimera to open
1128    * the file as a commands script. For use when sending a large number of
1129    * separate commands would overload the REST interface mechanism.
1130    * 
1131    * @param commands
1132    */
1133   protected void sendCommandsByFile(String[] commands)
1134   {
1135     try
1136     {
1137       File tmp = File.createTempFile("chim", ".com");
1138       tmp.deleteOnExit();
1139       PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
1140       for (String command : commands)
1141       {
1142         out.println(command);
1143       }
1144       out.flush();
1145       out.close();
1146       String path = tmp.getAbsolutePath();
1147       sendAsynchronousCommand("open cmd:" + path, null);
1148     } catch (IOException e)
1149     {
1150       System.err
1151               .println("Sending commands to Chimera via file failed with "
1152                       + e.getMessage());
1153     }
1154   }
1155
1156   /**
1157    * Get Chimera residues which have the named attribute, find the mapped
1158    * positions in the Jalview sequence(s), and set as sequence features
1159    * 
1160    * @param attName
1161    * @param alignmentPanel
1162    */
1163   public void copyStructureAttributesToFeatures(String attName,
1164           AlignmentViewPanel alignmentPanel)
1165   {
1166     // todo pull up to AAStructureBindingModel (and interface?)
1167
1168     /*
1169      * ask Chimera to list residues with the attribute, reporting its value
1170      */
1171     // this alternative command
1172     // list residues spec ':*/attName' attr attName
1173     // doesn't report 'None' values (which is good), but
1174     // fails for 'average.bfactor' (which is bad):
1175
1176     String cmd = "list residues attr '" + attName + "'";
1177     List<String> residues = sendChimeraCommand(cmd, true);
1178
1179     boolean featureAdded = createFeaturesForAttributes(attName, residues);
1180     if (featureAdded)
1181     {
1182       alignmentPanel.getFeatureRenderer().featuresAdded();
1183     }
1184   }
1185
1186   /**
1187    * Create features in Jalview for the given attribute name and structure
1188    * residues.
1189    * 
1190    * <pre>
1191    * The residue list should be 0, 1 or more reply lines of the format: 
1192    *     residue id #0:5.A isHelix -155.000836316 index 5 
1193    * or 
1194    *     residue id #0:6.A isHelix None
1195    * </pre>
1196    * 
1197    * @param attName
1198    * @param residues
1199    * @return
1200    */
1201   protected boolean createFeaturesForAttributes(String attName,
1202           List<String> residues)
1203   {
1204     boolean featureAdded = false;
1205     String featureGroup = getViewerFeatureGroup();
1206
1207     for (String residue : residues)
1208     {
1209       AtomSpec spec = null;
1210       String[] tokens = residue.split(" ");
1211       if (tokens.length < 5)
1212       {
1213         continue;
1214       }
1215       String atomSpec = tokens[2];
1216       String attValue = tokens[4];
1217
1218       /*
1219        * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
1220        */
1221       if ("None".equalsIgnoreCase(attValue)
1222               || "False".equalsIgnoreCase(attValue))
1223       {
1224         continue;
1225       }
1226
1227       try
1228       {
1229         spec = AtomSpec.fromChimeraAtomspec(atomSpec);
1230       } catch (IllegalArgumentException e)
1231       {
1232         System.err.println("Problem parsing atomspec " + atomSpec);
1233         continue;
1234       }
1235
1236       String chainId = spec.getChain();
1237       String description = attValue;
1238       float score = Float.NaN;
1239       try
1240       {
1241         score = Float.valueOf(attValue);
1242         description = chainId;
1243       } catch (NumberFormatException e)
1244       {
1245         // was not a float value
1246       }
1247
1248       String pdbFile = getPdbFileForModel(spec.getModelNumber());
1249       spec.setPdbFile(pdbFile);
1250
1251       List<AtomSpec> atoms = Collections.singletonList(spec);
1252
1253       /*
1254        * locate the mapped position in the alignment (if any)
1255        */
1256       SearchResults sr = getSsm()
1257               .findAlignmentPositionsForStructurePositions(atoms);
1258
1259       /*
1260        * expect one matched alignment position, or none 
1261        * (if the structure position is not mapped)
1262        */
1263       for (Match m : sr.getResults())
1264       {
1265         SequenceI seq = m.getSequence();
1266         int start = m.getStart();
1267         int end = m.getEnd();
1268         SequenceFeature sf = new SequenceFeature(attName, description,
1269                 start, end, score, featureGroup);
1270         // todo: should SequenceFeature have an explicit property for chain?
1271         // note: repeating the action shouldn't duplicate features
1272         featureAdded |= seq.addSequenceFeature(sf);
1273       }
1274     }
1275     return featureAdded;
1276   }
1277
1278   /**
1279    * Answers the feature group name to apply to features created in Jalview from
1280    * Chimera attributes
1281    * 
1282    * @return
1283    */
1284   protected String getViewerFeatureGroup()
1285   {
1286     // todo pull up to interface
1287     return CHIMERA_FEATURE_GROUP;
1288   }
1289
1290
1291   public Hashtable<String, String> getChainFile()
1292   {
1293     return chainFile;
1294   }
1295
1296   public List<ChimeraModel> getChimeraModelByChain(String chain)
1297   {
1298     return chimeraMaps.get(chainFile.get(chain));
1299   }
1300
1301   public int getModelNoForChain(String chain)
1302   {
1303     List<ChimeraModel> foundModels = getChimeraModelByChain(chain);
1304     if (foundModels != null && !foundModels.isEmpty())
1305     {
1306       return foundModels.get(0).getModelNumber();
1307     }
1308     return -1;
1309   }
1310 }