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