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