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