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