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