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