JAL-3390 redraw structures if alignment only and hidden regions change
[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.StructureMapping;
40 import jalview.structure.StructureMappingcommandSet;
41 import jalview.structure.StructureSelectionManager;
42 import jalview.structures.models.AAStructureBindingModel;
43 import jalview.util.MessageManager;
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.Iterator;
56 import java.util.LinkedHashMap;
57 import java.util.List;
58 import java.util.Map;
59
60 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
61 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
62 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
63 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
64
65 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
66 {
67   public static final String CHIMERA_FEATURE_GROUP = "Chimera";
68
69   // Chimera clause to exclude alternate locations in atom selection
70   private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
71
72   private static final String COLOURING_CHIMERA = MessageManager
73           .getString("status.colouring_chimera");
74
75   private static final boolean debug = false;
76
77   private static final String PHOSPHORUS = "P";
78
79   private static final String ALPHACARBON = "CA";
80
81   private List<String> chainNames = new ArrayList<>();
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)).append(":");
468         command.append(selcom[pdbfnum]);
469         command.append("@").append(
470                 structures[pdbfnum].isRna ? PHOSPHORUS : ALPHACARBON);
471         // JAL-1757 exclude alternate CA locations
472         command.append(NO_ALTLOCS);
473         command.append(" ").append(getModelSpec(refStructure)).append(":");
474         command.append(selcom[refStructure]);
475         command.append("@").append(
476                 structures[refStructure].isRna ? PHOSPHORUS : ALPHACARBON);
477         command.append(NO_ALTLOCS);
478       }
479       if (selectioncom.length() > 0)
480       {
481         if (debug)
482         {
483           System.out.println("Select regions:\n" + selectioncom.toString());
484           System.out.println(
485                   "Superimpose command(s):\n" + command.toString());
486         }
487         allComs/*.append("~display all; chain @CA|P; ribbon ")
488                 .append(selectioncom.toString())*/
489                 .append(";" + command.toString());
490       }
491     }
492
493     String error = null;
494     if (selectioncom.length() > 0)
495     {
496       // TODO: visually distinguish regions that were superposed
497       if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
498       {
499         selectioncom.setLength(selectioncom.length() - 1);
500       }
501       if (debug)
502       {
503         System.out.println("Select regions:\n" + selectioncom.toString());
504       }
505       allComs.append("; ~display "); // all");
506       if (!isShowAlignmentOnly())
507       {
508         allComs.append("; ribbon; chain @CA|P");
509       }
510       else
511       {
512         allComs.append("; ~ribbon");
513       }
514       allComs.append("; ribbon ").append(selectioncom.toString())
515               .append("; focus");
516       List<String> chimeraReplies = sendChimeraCommand(allComs.toString(),
517               true);
518       for (String reply : chimeraReplies)
519       {
520         String lowerCase = reply.toLowerCase();
521         if (lowerCase.contains("unequal numbers of atoms")
522                 || lowerCase.contains("at least"))
523         {
524           error = reply;
525         }
526       }
527     }
528     return error;
529   }
530
531   /**
532    * Helper method to construct model spec in Chimera format:
533    * <ul>
534    * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
535    * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
536    * <ul>
537    * Note for now we only ever choose the first of multiple models. This
538    * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
539    * future if there is a need to select specific sub-models.
540    * 
541    * @param pdbfnum
542    * @return
543    */
544   protected String getModelSpec(int pdbfnum)
545   {
546     if (pdbfnum < 0 || pdbfnum >= getPdbCount())
547     {
548       return "";
549     }
550
551     /*
552      * For now, the test for having sub-models is whether multiple Chimera
553      * models are mapped for the PDB file; the models are returned as a response
554      * to the Chimera command 'list models type molecule', see
555      * ChimeraManager.getModelList().
556      */
557     List<ChimeraModel> maps = chimeraMaps.get(getStructureFiles()[pdbfnum]);
558     boolean hasSubModels = maps != null && maps.size() > 1;
559     return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
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 colourBySequenceCommands
653    */
654   @Override
655   protected void colourBySequence(
656           StructureMappingcommandSet[] colourBySequenceCommands)
657   {
658     for (StructureMappingcommandSet cpdbbyseq : colourBySequenceCommands)
659     {
660       for (String command : cpdbbyseq.commands)
661       {
662         sendAsynchronousCommand(command, COLOURING_CHIMERA);
663       }
664     }
665   }
666
667   /**
668    * @param files
669    * @param viewPanel
670    * @return
671    */
672   @Override
673   protected StructureMappingcommandSet[] getColourBySequenceCommands(
674           String[] files, AlignmentViewPanel viewPanel)
675   {
676     return ChimeraCommands.getColourBySequenceCommand(getSsm(), files,
677             this, viewPanel);
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    * Returns a list of chains mapped in this viewer. Note this list is not
1024    * currently scoped per structure.
1025    * 
1026    * @return
1027    */
1028   @Override
1029   public List<String> getChainNames()
1030   {
1031     return chainNames;
1032   }
1033
1034   /**
1035    * Send a 'focus' command to Chimera to recentre the visible display
1036    */
1037   public void focusView()
1038   {
1039     sendChimeraCommand("focus", false);
1040   }
1041
1042   /**
1043    * Send a 'show' command for all atoms in the currently selected columns
1044    * 
1045    * TODO: pull up to abstract structure viewer interface
1046    * 
1047    * @param vp
1048    */
1049   public void highlightSelection(AlignmentViewPanel vp)
1050   {
1051     List<Integer> cols = vp.getAlignViewport().getColumnSelection()
1052             .getSelected();
1053     AlignmentI alignment = vp.getAlignment();
1054     StructureSelectionManager sm = getSsm();
1055     for (SequenceI seq : alignment.getSequences())
1056     {
1057       /*
1058        * convert selected columns into sequence positions
1059        */
1060       int[] positions = new int[cols.size()];
1061       int i = 0;
1062       for (Integer col : cols)
1063       {
1064         positions[i++] = seq.findPosition(col);
1065       }
1066       sm.highlightStructure(this, seq, positions);
1067     }
1068   }
1069
1070   /**
1071    * Constructs and send commands to Chimera to set attributes on residues for
1072    * features visible in Jalview
1073    * 
1074    * @param avp
1075    * @return
1076    */
1077   public int sendFeaturesToViewer(AlignmentViewPanel avp)
1078   {
1079     // TODO refactor as required to pull up to an interface
1080     AlignmentI alignment = avp.getAlignment();
1081
1082     String[] files = getStructureFiles();
1083     if (files == null)
1084     {
1085       return 0;
1086     }
1087
1088     StructureMappingcommandSet commandSet = ChimeraCommands
1089             .getSetAttributeCommandsForFeatures(getSsm(), files,
1090                     getSequence(), avp);
1091     String[] commands = commandSet.commands;
1092     if (commands.length > 10)
1093     {
1094       sendCommandsByFile(commands);
1095     }
1096     else
1097     {
1098       for (String command : commands)
1099       {
1100         sendAsynchronousCommand(command, null);
1101       }
1102     }
1103     return commands.length;
1104   }
1105
1106   /**
1107    * Write commands to a temporary file, and send a command to Chimera to open
1108    * the file as a commands script. For use when sending a large number of
1109    * separate commands would overload the REST interface mechanism.
1110    * 
1111    * @param commands
1112    */
1113   protected void sendCommandsByFile(String[] commands)
1114   {
1115     try
1116     {
1117       File tmp = File.createTempFile("chim", ".com");
1118       tmp.deleteOnExit();
1119       PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
1120       for (String command : commands)
1121       {
1122         out.println(command);
1123       }
1124       out.flush();
1125       out.close();
1126       String path = tmp.getAbsolutePath();
1127       sendAsynchronousCommand("open cmd:" + path, null);
1128     } catch (IOException e)
1129     {
1130       System.err.println("Sending commands to Chimera via file failed with "
1131               + e.getMessage());
1132     }
1133   }
1134
1135   /**
1136    * Get Chimera residues which have the named attribute, find the mapped
1137    * positions in the Jalview sequence(s), and set as sequence features
1138    * 
1139    * @param attName
1140    * @param alignmentPanel
1141    */
1142   public void copyStructureAttributesToFeatures(String attName,
1143           AlignmentViewPanel alignmentPanel)
1144   {
1145     // todo pull up to AAStructureBindingModel (and interface?)
1146
1147     /*
1148      * ask Chimera to list residues with the attribute, reporting its value
1149      */
1150     // this alternative command
1151     // list residues spec ':*/attName' attr attName
1152     // doesn't report 'None' values (which is good), but
1153     // fails for 'average.bfactor' (which is bad):
1154
1155     String cmd = "list residues attr '" + attName + "'";
1156     List<String> residues = sendChimeraCommand(cmd, true);
1157
1158     boolean featureAdded = createFeaturesForAttributes(attName, residues);
1159     if (featureAdded)
1160     {
1161       alignmentPanel.getFeatureRenderer().featuresAdded();
1162     }
1163   }
1164
1165   /**
1166    * Create features in Jalview for the given attribute name and structure
1167    * residues.
1168    * 
1169    * <pre>
1170    * The residue list should be 0, 1 or more reply lines of the format: 
1171    *     residue id #0:5.A isHelix -155.000836316 index 5 
1172    * or 
1173    *     residue id #0:6.A isHelix None
1174    * </pre>
1175    * 
1176    * @param attName
1177    * @param residues
1178    * @return
1179    */
1180   protected boolean createFeaturesForAttributes(String attName,
1181           List<String> residues)
1182   {
1183     boolean featureAdded = false;
1184     String featureGroup = getViewerFeatureGroup();
1185
1186     for (String residue : residues)
1187     {
1188       AtomSpec spec = null;
1189       String[] tokens = residue.split(" ");
1190       if (tokens.length < 5)
1191       {
1192         continue;
1193       }
1194       String atomSpec = tokens[2];
1195       String attValue = tokens[4];
1196
1197       /*
1198        * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
1199        */
1200       if ("None".equalsIgnoreCase(attValue)
1201               || "False".equalsIgnoreCase(attValue))
1202       {
1203         continue;
1204       }
1205
1206       try
1207       {
1208         spec = AtomSpec.fromChimeraAtomspec(atomSpec);
1209       } catch (IllegalArgumentException e)
1210       {
1211         System.err.println("Problem parsing atomspec " + atomSpec);
1212         continue;
1213       }
1214
1215       String chainId = spec.getChain();
1216       String description = attValue;
1217       float score = Float.NaN;
1218       try
1219       {
1220         score = Float.valueOf(attValue);
1221         description = chainId;
1222       } catch (NumberFormatException e)
1223       {
1224         // was not a float value
1225       }
1226
1227       String pdbFile = getPdbFileForModel(spec.getModelNumber());
1228       spec.setPdbFile(pdbFile);
1229
1230       List<AtomSpec> atoms = Collections.singletonList(spec);
1231
1232       /*
1233        * locate the mapped position in the alignment (if any)
1234        */
1235       SearchResultsI sr = getSsm()
1236               .findAlignmentPositionsForStructurePositions(atoms);
1237
1238       /*
1239        * expect one matched alignment position, or none 
1240        * (if the structure position is not mapped)
1241        */
1242       for (SearchResultMatchI m : sr.getResults())
1243       {
1244         SequenceI seq = m.getSequence();
1245         int start = m.getStart();
1246         int end = m.getEnd();
1247         SequenceFeature sf = new SequenceFeature(attName, description,
1248                 start, end, score, featureGroup);
1249         // todo: should SequenceFeature have an explicit property for chain?
1250         // note: repeating the action shouldn't duplicate features
1251         featureAdded |= seq.addSequenceFeature(sf);
1252       }
1253     }
1254     return featureAdded;
1255   }
1256
1257   /**
1258    * Answers the feature group name to apply to features created in Jalview from
1259    * Chimera attributes
1260    * 
1261    * @return
1262    */
1263   protected String getViewerFeatureGroup()
1264   {
1265     // todo pull up to interface
1266     return CHIMERA_FEATURE_GROUP;
1267   }
1268
1269   public Hashtable<String, String> getChainFile()
1270   {
1271     return chainFile;
1272   }
1273
1274   public List<ChimeraModel> getChimeraModelByChain(String chain)
1275   {
1276     return chimeraMaps.get(chainFile.get(chain));
1277   }
1278
1279   public int getModelNoForChain(String chain)
1280   {
1281     List<ChimeraModel> foundModels = getChimeraModelByChain(chain);
1282     if (foundModels != null && !foundModels.isEmpty())
1283     {
1284       return foundModels.get(0).getModelNumber();
1285     }
1286     return -1;
1287   }
1288
1289   @Override
1290   public void showStructures(AlignViewportI av, boolean refocus)
1291   {
1292     StringBuilder cmd = new StringBuilder(128);
1293     cmd.append("~display; ~ribbon;");
1294     String atomSpec = getMappedResidues(av);
1295     cmd.append("ribbon ").append(atomSpec);
1296     if (!isShowAlignmentOnly())
1297     {
1298       cmd.append("chain @CA|P; ribbon");
1299     }
1300     if (refocus)
1301     {
1302       cmd.append("; focus");
1303     }
1304     sendChimeraCommand(cmd.toString(), false);
1305   }
1306
1307   /**
1308    * Builds a Chimera atomSpec of residues mapped from sequences, of the format
1309    * (#model:residues.chain)
1310    * 
1311    * <pre>
1312    * #0:2-94.A | #1:1-93.C | #2:1-93.A
1313    * </pre>
1314    * 
1315    * Only residues visible in the alignment are included, that is, hidden columns
1316    * and sequences are excluded.
1317    * 
1318    * @param av
1319    * @return
1320    */
1321   private String getMappedResidues(AlignViewportI av)
1322   {
1323     AlignmentI alignment = av.getAlignment();
1324     final int width = alignment.getWidth();
1325   
1326     String[] files = getStructureFiles();
1327
1328     StringBuilder atomSpec = new StringBuilder(256);
1329
1330     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1331     {
1332       StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
1333
1334       /*
1335        * Find the first mapped sequence (if any) for this PDB entry which is in
1336        * the alignment
1337        */
1338       final int seqCountForPdbFile = getSequence()[pdbfnum].length;
1339       for (int s = 0; s < seqCountForPdbFile; s++)
1340       {
1341         for (StructureMapping mapping : mappings)
1342         {
1343           final SequenceI theSequence = getSequence()[pdbfnum][s];
1344           if (mapping.getSequence() == theSequence
1345                   && alignment.findIndex(theSequence) > -1)
1346           {
1347             String chainCd = mapping.getChain();
1348             if (!isShowChain(mapping.getPdbId(), chainCd))
1349             {
1350               continue;
1351             }
1352             Iterator<int[]> visible;
1353             if (isShowAlignmentOnly() && isHideHiddenRegions())
1354             {
1355               visible = alignment.getHiddenColumns()
1356                     .getVisContigsIterator(0, width, true);
1357             }
1358             else
1359             {
1360               visible = Collections.singletonList(new int[] { 0, width })
1361                       .iterator();
1362             }
1363             while (visible.hasNext())
1364             {
1365               int[] visibleRegion = visible.next();
1366               int seqStartPos = theSequence.findPosition(visibleRegion[0]);
1367               int seqEndPos = theSequence.findPosition(visibleRegion[1]);
1368               List<int[]> residueRanges = mapping
1369                       .getPDBResNumRanges(seqStartPos, seqEndPos);
1370               if (!residueRanges.isEmpty())
1371               {
1372                 if (atomSpec.length() > 0)
1373                 {
1374                   atomSpec.append("| ");
1375                 }
1376                 atomSpec.append(getModelSpec(pdbfnum)).append(":");
1377                 boolean first = true;
1378                 for (int[] range : residueRanges)
1379                 {
1380                   if (!first)
1381                   {
1382                     atomSpec.append(",");
1383                   }
1384                   first = false;
1385                   atomSpec.append(range[0]).append("-").append(range[1]);
1386                   atomSpec.append(".").append(chainCd);
1387                 }
1388               }
1389             }
1390           }
1391         }
1392       }
1393     }
1394
1395     return atomSpec.toString();
1396   }
1397 }