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