FileFormat enum wip changes
[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.bin.Cache;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.ColumnSelection;
29 import jalview.datamodel.PDBEntry;
30 import jalview.datamodel.SequenceI;
31 import jalview.httpserver.AbstractRequestHandler;
32 import jalview.io.DataSourceType;
33 import jalview.schemes.ColourSchemeI;
34 import jalview.schemes.ResidueProperties;
35 import jalview.structure.AtomSpec;
36 import jalview.structure.StructureMappingcommandSet;
37 import jalview.structure.StructureSelectionManager;
38 import jalview.structures.models.AAStructureBindingModel;
39 import jalview.util.MessageManager;
40
41 import java.awt.Color;
42 import java.net.BindException;
43 import java.util.ArrayList;
44 import java.util.LinkedHashMap;
45 import java.util.List;
46 import java.util.Map;
47
48 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
49 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
50 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
51 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
52
53 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
54 {
55   // Chimera clause to exclude alternate locations in atom selection
56   private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
57
58   private static final String COLOURING_CHIMERA = MessageManager
59           .getString("status.colouring_chimera");
60
61   private static final boolean debug = false;
62
63   private static final String PHOSPHORUS = "P";
64
65   private static final String ALPHACARBON = "CA";
66
67   /*
68    * Object through which we talk to Chimera
69    */
70   private ChimeraManager viewer;
71
72   /*
73    * Object which listens to Chimera notifications
74    */
75   private AbstractRequestHandler chimeraListener;
76
77   /*
78    * set if chimera state is being restored from some source - instructs binding
79    * not to apply default display style when structure set is updated for first
80    * time.
81    */
82   private boolean loadingFromArchive = false;
83
84   /*
85    * flag to indicate if the Chimera viewer should ignore sequence colouring
86    * events from the structure manager because the GUI is still setting up
87    */
88   private boolean loadingFinished = true;
89
90   public String fileLoadingError;
91
92   /*
93    * Map of ChimeraModel objects keyed by PDB full local file name
94    */
95   private Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<String, List<ChimeraModel>>();
96
97   /*
98    * the default or current model displayed if the model cannot be identified
99    * from the selection message
100    */
101   private int frameNo = 0;
102
103   private String lastCommand;
104
105   /*
106    * current set of model filenames loaded
107    */
108   String[] modelFileNames = null;
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   /**
120    * Open a PDB structure file in Chimera and set up mappings from Jalview.
121    * 
122    * We check if the PDB model id is already loaded in Chimera, if so don't
123    * reopen it. This is the case if Chimera has opened a saved session file.
124    * 
125    * @param pe
126    * @return
127    */
128   public boolean openFile(PDBEntry pe)
129   {
130     String file = pe.getFile();
131     try
132     {
133       List<ChimeraModel> modelsToMap = new ArrayList<ChimeraModel>();
134       List<ChimeraModel> oldList = viewer.getModelList();
135       boolean alreadyOpen = false;
136
137       /*
138        * If Chimera already has this model, don't reopen it, but do remap it.
139        */
140       for (ChimeraModel open : oldList)
141       {
142         if (open.getModelName().equals(pe.getId()))
143         {
144           alreadyOpen = true;
145           modelsToMap.add(open);
146         }
147       }
148
149       /*
150        * If Chimera doesn't yet have this model, ask it to open it, and retrieve
151        * the model name(s) added by Chimera.
152        */
153       if (!alreadyOpen)
154       {
155         viewer.openModel(file, pe.getId(), ModelType.PDB_MODEL);
156         List<ChimeraModel> newList = viewer.getModelList();
157         // JAL-1728 newList.removeAll(oldList) does not work
158         for (ChimeraModel cm : newList)
159         {
160           if (cm.getModelName().equals(pe.getId()))
161           {
162             modelsToMap.add(cm);
163           }
164         }
165       }
166
167       chimeraMaps.put(file, modelsToMap);
168
169       if (getSsm() != null)
170       {
171         getSsm().addStructureViewerListener(this);
172         // ssm.addSelectionListener(this);
173         FeatureRenderer fr = getFeatureRenderer(null);
174         if (fr != null)
175         {
176           fr.featuresAdded();
177         }
178         refreshGUI();
179       }
180       return true;
181     } catch (Exception q)
182     {
183       log("Exception when trying to open model " + file + "\n"
184               + q.toString());
185       q.printStackTrace();
186     }
187     return false;
188   }
189
190   /**
191    * Constructor
192    * 
193    * @param ssm
194    * @param pdbentry
195    * @param sequenceIs
196    * @param chains
197    * @param protocol
198    */
199   public JalviewChimeraBinding(StructureSelectionManager ssm,
200           PDBEntry[] pdbentry, SequenceI[][] sequenceIs, String[][] chains,
201           DataSourceType protocol)
202   {
203     super(ssm, pdbentry, sequenceIs, chains, protocol);
204     viewer = new ChimeraManager(
205             new ext.edu.ucsf.rbvi.strucviz2.StructureManager(true));
206   }
207
208   /**
209    * Start a dedicated HttpServer to listen for Chimera notifications, and tell
210    * it to start listening
211    */
212   public void startChimeraListener()
213   {
214     try
215     {
216       chimeraListener = new ChimeraListener(this);
217       viewer.startListening(chimeraListener.getUri());
218     } catch (BindException e)
219     {
220       System.err.println("Failed to start Chimera listener: "
221               + e.getMessage());
222     }
223   }
224
225   /**
226    * Construct a title string for the viewer window based on the data Jalview
227    * knows about
228    * 
229    * @param verbose
230    * @return
231    */
232   public String getViewerTitle(boolean verbose)
233   {
234     return getViewerTitle("Chimera", verbose);
235   }
236
237   /**
238    * Tells Chimera to display only the specified chains
239    * 
240    * @param toshow
241    */
242   public void showChains(List<String> toshow)
243   {
244     /*
245      * Construct a chimera command like
246      * 
247      * ~display #*;~ribbon #*;ribbon :.A,:.B
248      */
249     StringBuilder cmd = new StringBuilder(64);
250     boolean first = true;
251     for (String chain : toshow)
252     {
253       if (!first)
254       {
255         cmd.append(",");
256       }
257       cmd.append(":.").append(chain);
258       first = false;
259     }
260
261     /*
262      * could append ";focus" to this command to resize the display to fill the
263      * window, but it looks more helpful not to (easier to relate chains to the
264      * whole)
265      */
266     final String command = "~display #*; ~ribbon #*; ribbon "
267             + cmd.toString();
268     sendChimeraCommand(command, false);
269   }
270
271   /**
272    * Close down the Jalview viewer and listener, and (optionally) the associated
273    * Chimera window.
274    */
275   public void closeViewer(boolean closeChimera)
276   {
277     getSsm().removeStructureViewerListener(this, this.getPdbFile());
278     if (closeChimera)
279     {
280       viewer.exitChimera();
281     }
282     if (this.chimeraListener != null)
283     {
284       chimeraListener.shutdown();
285       chimeraListener = null;
286     }
287     lastCommand = null;
288     viewer = null;
289
290     releaseUIResources();
291   }
292
293   public void colourByChain()
294   {
295     colourBySequence = false;
296     sendAsynchronousCommand("rainbow chain", COLOURING_CHIMERA);
297   }
298
299   /**
300    * Constructs and sends a Chimera command to colour by charge
301    * <ul>
302    * <li>Aspartic acid and Glutamic acid (negative charge) red</li>
303    * <li>Lysine and Arginine (positive charge) blue</li>
304    * <li>Cysteine - yellow</li>
305    * <li>all others - white</li>
306    * </ul>
307    */
308   public void colourByCharge()
309   {
310     colourBySequence = false;
311     String command = "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS";
312     sendAsynchronousCommand(command, COLOURING_CHIMERA);
313   }
314
315   /**
316    * Construct and send a command to align structures against a reference
317    * structure, based on one or more sequence alignments
318    * 
319    * @param _alignment
320    *          an array of alignments to process
321    * @param _refStructure
322    *          an array of corresponding reference structures (index into pdb
323    *          file array); if a negative value is passed, the first PDB file
324    *          mapped to an alignment sequence is used as the reference for
325    *          superposition
326    * @param _hiddenCols
327    *          an array of corresponding hidden columns for each alignment
328    */
329   public void superposeStructures(AlignmentI[] _alignment,
330           int[] _refStructure, ColumnSelection[] _hiddenCols)
331   {
332     StringBuilder allComs = new StringBuilder(128);
333     String[] files = getPdbFile();
334
335     if (!waitForFileLoad(files))
336     {
337       return;
338     }
339
340     refreshPdbEntries();
341     StringBuilder selectioncom = new StringBuilder(256);
342     for (int a = 0; a < _alignment.length; a++)
343     {
344       int refStructure = _refStructure[a];
345       AlignmentI alignment = _alignment[a];
346       ColumnSelection hiddenCols = _hiddenCols[a];
347
348       if (refStructure >= files.length)
349       {
350         System.err.println("Ignoring invalid reference structure value "
351                 + refStructure);
352         refStructure = -1;
353       }
354
355       /*
356        * 'matched' array will hold 'true' for visible alignment columns where
357        * all sequences have a residue with a mapping to the PDB structure
358        */
359       boolean matched[] = new boolean[alignment.getWidth()];
360       for (int m = 0; m < matched.length; m++)
361       {
362         matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
363       }
364
365       SuperposeData[] structures = new SuperposeData[files.length];
366       for (int f = 0; f < files.length; f++)
367       {
368         structures[f] = new SuperposeData(alignment.getWidth());
369       }
370
371       /*
372        * Calculate the superposable alignment columns ('matched'), and the
373        * corresponding structure residue positions (structures.pdbResNo)
374        */
375       int candidateRefStructure = findSuperposableResidues(alignment,
376               matched, structures);
377       if (refStructure < 0)
378       {
379         /*
380          * If no reference structure was specified, pick the first one that has
381          * a mapping in the alignment
382          */
383         refStructure = candidateRefStructure;
384       }
385
386       int nmatched = 0;
387       for (boolean b : matched)
388       {
389         if (b)
390         {
391           nmatched++;
392         }
393       }
394       if (nmatched < 4)
395       {
396         // TODO: bail out here because superposition illdefined?
397       }
398
399       /*
400        * Generate select statements to select regions to superimpose structures
401        */
402       String[] selcom = new String[files.length];
403       for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
404       {
405         String chainCd = "." + structures[pdbfnum].chain;
406         int lpos = -1;
407         boolean run = false;
408         StringBuilder molsel = new StringBuilder();
409         for (int r = 0; r < matched.length; r++)
410         {
411           if (matched[r])
412           {
413             int pdbResNum = structures[pdbfnum].pdbResNo[r];
414             if (lpos != pdbResNum - 1)
415             {
416               /*
417                * discontiguous - append last residue now
418                */
419               if (lpos != -1)
420               {
421                 molsel.append(String.valueOf(lpos));
422                 molsel.append(chainCd);
423                 molsel.append(",");
424               }
425               run = false;
426             }
427             else
428             {
429               /*
430                * extending a contiguous run
431                */
432               if (!run)
433               {
434                 /*
435                  * start the range selection
436                  */
437                 molsel.append(String.valueOf(lpos));
438                 molsel.append("-");
439               }
440               run = true;
441             }
442             lpos = pdbResNum;
443           }
444         }
445
446         /*
447          * and terminate final selection
448          */
449         if (lpos != -1)
450         {
451           molsel.append(String.valueOf(lpos));
452           molsel.append(chainCd);
453         }
454         if (molsel.length() > 1)
455         {
456           selcom[pdbfnum] = molsel.toString();
457           selectioncom.append("#").append(String.valueOf(pdbfnum))
458                   .append(":");
459           selectioncom.append(selcom[pdbfnum]);
460           selectioncom.append(" ");
461           if (pdbfnum < files.length - 1)
462           {
463             selectioncom.append("| ");
464           }
465         }
466         else
467         {
468           selcom[pdbfnum] = null;
469         }
470       }
471
472       StringBuilder command = new StringBuilder(256);
473       for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
474       {
475         if (pdbfnum == refStructure || selcom[pdbfnum] == null
476                 || selcom[refStructure] == null)
477         {
478           continue;
479         }
480         if (command.length() > 0)
481         {
482           command.append(";");
483         }
484
485         /*
486          * Form Chimera match command, from the 'new' structure to the
487          * 'reference' structure e.g. (50 residues, chain B/A, alphacarbons):
488          * 
489          * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
490          * 
491          * @see
492          * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
493          */
494         command.append("match ").append(getModelSpec(pdbfnum)).append(":");
495         command.append(selcom[pdbfnum]);
496         command.append("@").append(
497                 structures[pdbfnum].isRna ? PHOSPHORUS : ALPHACARBON);
498         // JAL-1757 exclude alternate CA locations
499         command.append(NO_ALTLOCS);
500         command.append(" ").append(getModelSpec(refStructure)).append(":");
501         command.append(selcom[refStructure]);
502         command.append("@").append(
503                 structures[refStructure].isRna ? PHOSPHORUS : ALPHACARBON);
504         command.append(NO_ALTLOCS);
505       }
506       if (selectioncom.length() > 0)
507       {
508         if (debug)
509         {
510           System.out.println("Select regions:\n" + selectioncom.toString());
511           System.out.println("Superimpose command(s):\n"
512                   + command.toString());
513         }
514         allComs.append("~display all; chain @CA|P; ribbon ")
515                 .append(selectioncom.toString())
516                 .append(";" + command.toString());
517       }
518     }
519     if (selectioncom.length() > 0)
520     {
521       // TODO: visually distinguish regions that were superposed
522       if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
523       {
524         selectioncom.setLength(selectioncom.length() - 1);
525       }
526       if (debug)
527       {
528         System.out.println("Select regions:\n" + selectioncom.toString());
529       }
530       allComs.append("; ~display all; chain @CA|P; ribbon ")
531               .append(selectioncom.toString()).append("; focus");
532       sendChimeraCommand(allComs.toString(), false);
533     }
534
535   }
536
537   /**
538    * Helper method to construct model spec in Chimera format:
539    * <ul>
540    * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
541    * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
542    * <ul>
543    * Note for now we only ever choose the first of multiple models. This
544    * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
545    * future if there is a need to select specific sub-models.
546    * 
547    * @param pdbfnum
548    * @return
549    */
550   protected String getModelSpec(int pdbfnum)
551   {
552     if (pdbfnum < 0 || pdbfnum >= getPdbCount())
553     {
554       return "";
555     }
556
557     /*
558      * For now, the test for having sub-models is whether multiple Chimera
559      * models are mapped for the PDB file; the models are returned as a response
560      * to the Chimera command 'list models type molecule', see
561      * ChimeraManager.getModelList().
562      */
563     List<ChimeraModel> maps = chimeraMaps.get(getPdbFile()[pdbfnum]);
564     boolean hasSubModels = maps != null && maps.size() > 1;
565     return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
566   }
567
568   /**
569    * Launch Chimera, unless an instance linked to this object is already
570    * running. Returns true if chimera is successfully launched, or already
571    * running, else false.
572    * 
573    * @return
574    */
575   public boolean launchChimera()
576   {
577     if (!viewer.isChimeraLaunched())
578     {
579       return viewer.launchChimera(StructureManager.getChimeraPaths());
580     }
581     if (viewer.isChimeraLaunched())
582     {
583       return true;
584     }
585     log("Failed to launch Chimera!");
586     return false;
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 any responses.
602    * 
603    * @param command
604    * @param logResponse
605    */
606   public void sendChimeraCommand(final String command, boolean logResponse)
607   {
608     if (viewer == null)
609     {
610       // ? thread running after viewer shut down
611       return;
612     }
613     viewerCommandHistory(false);
614     if (lastCommand == null || !lastCommand.equals(command))
615     {
616       // trim command or it may never find a match in the replyLog!!
617       List<String> lastReply = viewer.sendChimeraCommand(command.trim(),
618               logResponse);
619       if (logResponse && debug)
620       {
621         log("Response from command ('" + command + "') was:\n" + lastReply);
622       }
623     }
624     viewerCommandHistory(true);
625     lastCommand = command;
626   }
627
628   /**
629    * Send a Chimera command asynchronously in a new thread. If the progress
630    * message is not null, display this message while the command is executing.
631    * 
632    * @param command
633    * @param progressMsg
634    */
635   protected abstract void sendAsynchronousCommand(String command,
636           String progressMsg);
637
638   /**
639    * colour any structures associated with sequences in the given alignment
640    * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
641    * if colourBySequence is enabled.
642    */
643   public void colourBySequence(boolean showFeatures,
644           jalview.api.AlignmentViewPanel alignmentv)
645   {
646     if (!colourBySequence || !loadingFinished)
647     {
648       return;
649     }
650     if (getSsm() == null)
651     {
652       return;
653     }
654     String[] files = getPdbFile();
655
656     SequenceRenderer sr = getSequenceRenderer(alignmentv);
657
658     FeatureRenderer fr = null;
659     if (showFeatures)
660     {
661       fr = getFeatureRenderer(alignmentv);
662     }
663     AlignmentI alignment = alignmentv.getAlignment();
664
665     for (jalview.structure.StructureMappingcommandSet cpdbbyseq : getColourBySequenceCommands(
666             files, sr, fr, alignment))
667     {
668       for (String command : cpdbbyseq.commands)
669       {
670         sendAsynchronousCommand(command, COLOURING_CHIMERA);
671       }
672     }
673   }
674
675   /**
676    * @param files
677    * @param sr
678    * @param fr
679    * @param alignment
680    * @return
681    */
682   protected StructureMappingcommandSet[] getColourBySequenceCommands(
683           String[] files, SequenceRenderer sr, FeatureRenderer fr,
684           AlignmentI alignment)
685   {
686     return ChimeraCommands.getColourBySequenceCommand(getSsm(), files,
687             getSequence(), sr, fr, alignment);
688   }
689
690   /**
691    * @param command
692    */
693   protected void executeWhenReady(String command)
694   {
695     waitForChimera();
696     sendChimeraCommand(command, false);
697     waitForChimera();
698   }
699
700   private void waitForChimera()
701   {
702     while (viewer != null && viewer.isBusy())
703     {
704       try
705       {
706         Thread.sleep(15);
707       } catch (InterruptedException q)
708       {
709       }
710     }
711   }
712
713   // End StructureListener
714   // //////////////////////////
715
716   /**
717    * returns the current featureRenderer that should be used to colour the
718    * structures
719    * 
720    * @param alignment
721    * 
722    * @return
723    */
724   public abstract FeatureRenderer getFeatureRenderer(
725           AlignmentViewPanel alignment);
726
727   /**
728    * instruct the Jalview binding to update the pdbentries vector if necessary
729    * prior to matching the viewer's contents to the list of structure files
730    * Jalview knows about.
731    */
732   public abstract void refreshPdbEntries();
733
734   private int getModelNum(String modelFileName)
735   {
736     String[] mfn = getPdbFile();
737     if (mfn == null)
738     {
739       return -1;
740     }
741     for (int i = 0; i < mfn.length; i++)
742     {
743       if (mfn[i].equalsIgnoreCase(modelFileName))
744       {
745         return i;
746       }
747     }
748     return -1;
749   }
750
751   /**
752    * map between index of model filename returned from getPdbFile and the first
753    * index of models from this file in the viewer. Note - this is not trimmed -
754    * use getPdbFile to get number of unique models.
755    */
756   private int _modelFileNameMap[];
757
758   // ////////////////////////////////
759   // /StructureListener
760   @Override
761   public synchronized String[] getPdbFile()
762   {
763     if (viewer == null)
764     {
765       return new String[0];
766     }
767     // if (modelFileNames == null)
768     // {
769     // Collection<ChimeraModel> chimodels = viewer.getChimeraModels();
770     // _modelFileNameMap = new int[chimodels.size()];
771     // int j = 0;
772     // for (ChimeraModel chimodel : chimodels)
773     // {
774     // String mdlName = chimodel.getModelName();
775     // }
776     // modelFileNames = new String[j];
777     // // System.arraycopy(mset, 0, modelFileNames, 0, j);
778     // }
779
780     return chimeraMaps.keySet().toArray(
781             modelFileNames = new String[chimeraMaps.size()]);
782   }
783
784   /**
785    * returns the current sequenceRenderer that should be used to colour the
786    * structures
787    * 
788    * @param alignment
789    * 
790    * @return
791    */
792   public abstract SequenceRenderer getSequenceRenderer(
793           AlignmentViewPanel alignment);
794
795   /**
796    * Construct and send a command to highlight zero, one or more atoms. We do
797    * this by sending an "rlabel" command to show the residue label at that
798    * position.
799    */
800   @Override
801   public void highlightAtoms(List<AtomSpec> atoms)
802   {
803     if (atoms == null || atoms.size() == 0)
804     {
805       return;
806     }
807
808     StringBuilder cmd = new StringBuilder(128);
809     boolean first = true;
810     boolean found = false;
811
812     for (AtomSpec atom : atoms)
813     {
814       int pdbResNum = atom.getPdbResNum();
815       String chain = atom.getChain();
816       String pdbfile = atom.getPdbFile();
817       List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
818       if (cms != null && !cms.isEmpty())
819       {
820         if (first)
821         {
822           cmd.append("rlabel #").append(cms.get(0).getModelNumber())
823                   .append(":");
824         }
825         else
826         {
827           cmd.append(",");
828         }
829         first = false;
830         cmd.append(pdbResNum);
831         if (!chain.equals(" "))
832         {
833           cmd.append(".").append(chain);
834         }
835         found = true;
836       }
837     }
838     String command = cmd.toString();
839
840     /*
841      * avoid repeated commands for the same residue
842      */
843     if (command.equals(lastHighlightCommand))
844     {
845       return;
846     }
847
848     /*
849      * unshow the label for the previous residue
850      */
851     if (lastHighlightCommand != null)
852     {
853       viewer.sendChimeraCommand("~" + lastHighlightCommand, false);
854     }
855     if (found)
856     {
857       viewer.sendChimeraCommand(command, false);
858     }
859     this.lastHighlightCommand = command;
860   }
861
862   /**
863    * Query Chimera for its current selection, and highlight it on the alignment
864    */
865   public void highlightChimeraSelection()
866   {
867     /*
868      * Ask Chimera for its current selection
869      */
870     List<String> selection = viewer.getSelectedResidueSpecs();
871
872     /*
873      * Parse model number, residue and chain for each selected position,
874      * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
875      */
876     List<AtomSpec> atomSpecs = new ArrayList<AtomSpec>();
877     for (String atomSpec : selection)
878     {
879       int colonPos = atomSpec.indexOf(":");
880       if (colonPos == -1)
881       {
882         continue; // malformed
883       }
884
885       int hashPos = atomSpec.indexOf("#");
886       String modelSubmodel = atomSpec.substring(hashPos + 1, colonPos);
887       int dotPos = modelSubmodel.indexOf(".");
888       int modelId = 0;
889       try
890       {
891         modelId = Integer.valueOf(dotPos == -1 ? modelSubmodel
892                 : modelSubmodel.substring(0, dotPos));
893       } catch (NumberFormatException e)
894       {
895         // ignore, default to model 0
896       }
897
898       String residueChain = atomSpec.substring(colonPos + 1);
899       dotPos = residueChain.indexOf(".");
900       int pdbResNum = Integer.parseInt(dotPos == -1 ? residueChain
901               : residueChain.substring(0, dotPos));
902
903       String chainId = dotPos == -1 ? "" : residueChain
904               .substring(dotPos + 1);
905
906       /*
907        * Work out the pdbfilename from the model number
908        */
909       String pdbfilename = modelFileNames[frameNo];
910       findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
911       {
912         for (ChimeraModel cm : chimeraMaps.get(pdbfile))
913         {
914           if (cm.getModelNumber() == modelId)
915           {
916             pdbfilename = pdbfile;
917             break findfileloop;
918           }
919         }
920       }
921       atomSpecs.add(new AtomSpec(pdbfilename, chainId, pdbResNum, 0));
922     }
923
924     /*
925      * Broadcast the selection (which may be empty, if the user just cleared all
926      * selections)
927      */
928     getSsm().mouseOverStructure(atomSpecs);
929   }
930
931   private void log(String message)
932   {
933     System.err.println("## Chimera log: " + message);
934   }
935
936   private void viewerCommandHistory(boolean enable)
937   {
938     // log("(Not yet implemented) History "
939     // + ((debug || enable) ? "on" : "off"));
940   }
941
942   public long getLoadNotifiesHandled()
943   {
944     return loadNotifiesHandled;
945   }
946
947   public void setJalviewColourScheme(ColourSchemeI cs)
948   {
949     colourBySequence = false;
950
951     if (cs == null)
952     {
953       return;
954     }
955
956     // Chimera expects RBG values in the range 0-1
957     final double normalise = 255D;
958     viewerCommandHistory(false);
959     StringBuilder command = new StringBuilder(128);
960
961     List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
962             false);
963     for (String res : residueSet)
964     {
965       Color col = cs.findColour(res.charAt(0));
966       command.append("color " + col.getRed() / normalise + ","
967               + col.getGreen() / normalise + "," + col.getBlue()
968               / normalise + " ::" + res + ";");
969     }
970
971     sendAsynchronousCommand(command.toString(), COLOURING_CHIMERA);
972     viewerCommandHistory(true);
973   }
974
975   /**
976    * called when the binding thinks the UI needs to be refreshed after a Chimera
977    * state change. this could be because structures were loaded, or because an
978    * error has occurred.
979    */
980   public abstract void refreshGUI();
981
982   @Override
983   public void setLoadingFromArchive(boolean loadingFromArchive)
984   {
985     this.loadingFromArchive = loadingFromArchive;
986   }
987
988   /**
989    * 
990    * @return true if Chimeral is still restoring state or loading is still going
991    *         on (see setFinsihedLoadingFromArchive)
992    */
993   @Override
994   public boolean isLoadingFromArchive()
995   {
996     return loadingFromArchive && !loadingFinished;
997   }
998
999   /**
1000    * modify flag which controls if sequence colouring events are honoured by the
1001    * binding. Should be true for normal operation
1002    * 
1003    * @param finishedLoading
1004    */
1005   @Override
1006   public void setFinishedLoadingFromArchive(boolean finishedLoading)
1007   {
1008     loadingFinished = finishedLoading;
1009   }
1010
1011   /**
1012    * Send the Chimera 'background solid <color>" command.
1013    * 
1014    * @see https 
1015    *      ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
1016    *      .html
1017    * @param col
1018    */
1019   public void setBackgroundColour(Color col)
1020   {
1021     viewerCommandHistory(false);
1022     double normalise = 255D;
1023     final String command = "background solid " + col.getRed() / normalise
1024             + "," + col.getGreen() / normalise + "," + col.getBlue()
1025             / normalise + ";";
1026     viewer.sendChimeraCommand(command, false);
1027     viewerCommandHistory(true);
1028   }
1029
1030   /**
1031    * Ask Chimera to save its session to the given file. Returns true if
1032    * successful, else false.
1033    * 
1034    * @param filepath
1035    * @return
1036    */
1037   public boolean saveSession(String filepath)
1038   {
1039     if (isChimeraRunning())
1040     {
1041       List<String> reply = viewer.sendChimeraCommand("save " + filepath,
1042               true);
1043       if (reply.contains("Session written"))
1044       {
1045         return true;
1046       }
1047       else
1048       {
1049         Cache.log
1050                 .error("Error saving Chimera session: " + reply.toString());
1051       }
1052     }
1053     return false;
1054   }
1055
1056   /**
1057    * Ask Chimera to open a session file. Returns true if successful, else false.
1058    * The filename must have a .py extension for this command to work.
1059    * 
1060    * @param filepath
1061    * @return
1062    */
1063   public boolean openSession(String filepath)
1064   {
1065     sendChimeraCommand("open " + filepath, true);
1066     // todo: test for failure - how?
1067     return true;
1068   }
1069
1070   /**
1071    * Returns a list of chains mapped in this viewer. Note this list is not
1072    * currently scoped per structure.
1073    * 
1074    * @return
1075    */
1076   public List<String> getChainNames()
1077   {
1078     List<String> names = new ArrayList<String>();
1079     String[][] allNames = getChains();
1080     if (allNames != null)
1081     {
1082       for (String[] chainsForPdb : allNames)
1083       {
1084         if (chainsForPdb != null)
1085         {
1086           for (String chain : chainsForPdb)
1087           {
1088             if (chain != null && !names.contains(chain))
1089             {
1090               names.add(chain);
1091             }
1092           }
1093         }
1094       }
1095     }
1096     return names;
1097   }
1098
1099   /**
1100    * Send a 'focus' command to Chimera to recentre the visible display
1101    */
1102   public void focusView()
1103   {
1104     sendChimeraCommand("focus", false);
1105   }
1106
1107   /**
1108    * Send a 'show' command for all atoms in the currently selected columns
1109    * 
1110    * TODO: pull up to abstract structure viewer interface
1111    * 
1112    * @param vp
1113    */
1114   public void highlightSelection(AlignmentViewPanel vp)
1115   {
1116     List<Integer> cols = vp.getAlignViewport().getColumnSelection()
1117             .getSelected();
1118     AlignmentI alignment = vp.getAlignment();
1119     StructureSelectionManager sm = getSsm();
1120     for (SequenceI seq : alignment.getSequences())
1121     {
1122       /*
1123        * convert selected columns into sequence positions
1124        */
1125       int[] positions = new int[cols.size()];
1126       int i = 0;
1127       for (Integer col : cols)
1128       {
1129         positions[i++] = seq.findPosition(col);
1130       }
1131       sm.highlightStructure(this, seq, positions);
1132     }
1133   }
1134 }