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