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