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