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