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