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