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