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