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