JAL-1620 version bump and release notes
[jalview.git] / src / jalview / ext / rbvi / chimera / JalviewChimeraBinding.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2b1)
3  * Copyright (C) 2014 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.SequenceStructureBinding;
27 import jalview.api.StructureSelectionManagerProvider;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.ColumnSelection;
30 import jalview.datamodel.PDBEntry;
31 import jalview.datamodel.SequenceI;
32 import jalview.io.AppletFormatAdapter;
33 import jalview.schemes.ColourSchemeI;
34 import jalview.schemes.ResidueProperties;
35 import jalview.structure.StructureListener;
36 import jalview.structure.StructureMapping;
37 import jalview.structure.StructureSelectionManager;
38 import jalview.structures.models.SequenceStructureBindingModel;
39 import jalview.util.MessageManager;
40
41 import java.awt.Color;
42 import java.awt.event.ComponentEvent;
43 import java.io.File;
44 import java.util.ArrayList;
45 import java.util.Enumeration;
46 import java.util.HashMap;
47 import java.util.LinkedHashMap;
48 import java.util.List;
49 import java.util.Map;
50
51 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
52 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
53 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
54 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
55
56 public abstract class JalviewChimeraBinding extends
57         SequenceStructureBindingModel implements StructureListener,
58         SequenceStructureBinding, StructureSelectionManagerProvider
59
60 {
61   private static final String PHOSPHORUS = "P";
62
63   private static final String ALPHACARBON = "CA";
64
65   private StructureManager csm;
66
67   private ChimeraManager viewer;
68
69   /**
70    * set if chimera state is being restored from some source - instructs binding
71    * not to apply default display style when structure set is updated for first
72    * time.
73    */
74   private boolean loadingFromArchive = false;
75
76   /**
77    * second flag to indicate if the Chimera viewer should ignore sequence
78    * colouring events from the structure manager because the GUI is still
79    * setting up
80    */
81   private boolean loadingFinished = true;
82
83   /**
84    * state flag used to check if the Chimera viewer's paint method can be called
85    */
86   private boolean finishedInit = false;
87
88   public boolean isFinishedInit()
89   {
90     return finishedInit;
91   }
92
93   public void setFinishedInit(boolean finishedInit)
94   {
95     this.finishedInit = finishedInit;
96   }
97
98   boolean allChainsSelected = false;
99
100   /**
101    * when true, try to search the associated datamodel for sequences that are
102    * associated with any unknown structures in the Chimera view.
103    */
104   private boolean associateNewStructs = false;
105
106   List<String> atomsPicked = new ArrayList<String>();
107
108   public List<String> chainNames;
109
110   private Map<String, String> chainFile;
111
112   /**
113    * array of target chains for sequences - tied to pdbentry and sequence[]
114    */
115   protected String[][] chains;
116
117   boolean colourBySequence = true;
118
119   StringBuffer eval = new StringBuffer();
120
121   public String fileLoadingError;
122
123   private Map<String, List<ChimeraModel>> chimmaps = new LinkedHashMap<String, List<ChimeraModel>>();
124
125   private List<String> mdlToFile = new ArrayList<String>();
126
127   /**
128    * the default or current model displayed if the model cannot be identified
129    * from the selection message
130    */
131   int frameNo = 0;
132
133   String lastCommand;
134
135   String lastMessage;
136
137   boolean loadedInline;
138
139   public boolean openFile(PDBEntry pe)
140   {
141     String file = pe.getFile();
142     try
143     {
144       List<ChimeraModel> oldList = viewer.getModelList();
145       viewer.openModel(file, pe.getId(), ModelType.PDB_MODEL);
146       List<ChimeraModel> newList = viewer.getModelList();
147       if (oldList.size() < newList.size())
148       {
149         while (oldList.size() > 0)
150         {
151           oldList.remove(0);
152           newList.remove(0);
153         }
154         chimmaps.put(file, newList);
155         for (ChimeraModel cm : newList)
156         {
157           while (mdlToFile.size() < 1 + cm.getModelNumber())
158           {
159             mdlToFile.add(new String(""));
160           }
161           mdlToFile.set(cm.getModelNumber(), file);
162         }
163
164         File fl = new File(file);
165         String protocol = AppletFormatAdapter.URL;
166         try
167         {
168           if (fl.exists())
169           {
170             protocol = AppletFormatAdapter.FILE;
171           }
172         } catch (Exception e)
173         {
174         } catch (Error e)
175         {
176         }
177         // Explicitly map to the filename used by Chimera ;
178         // pdbentry[pe].getFile(), protocol);
179
180         if (ssm != null)
181         {
182           ssm.addStructureViewerListener(this);
183           // ssm.addSelectionListener(this);
184           FeatureRenderer fr = getFeatureRenderer(null);
185           if (fr != null)
186           {
187             fr.featuresAdded();
188           }
189           refreshGUI();
190         }
191         return true;
192       }
193     } catch (Exception q)
194     {
195       log("Exception when trying to open model " + file + "\n"
196               + q.toString());
197       q.printStackTrace();
198     }
199     return false;
200   }
201
202   /**
203    * current set of model filenames loaded
204    */
205   String[] modelFileNames = null;
206
207   public PDBEntry[] pdbentry;
208
209   /**
210    * datasource protocol for access to PDBEntrylatest
211    */
212   String protocol = null;
213
214   StringBuffer resetLastRes = new StringBuffer();
215
216   /**
217    * sequences mapped to each pdbentry
218    */
219   public SequenceI[][] sequence;
220
221   public StructureSelectionManager ssm;
222
223   private List<String> lastReply;
224
225   public JalviewChimeraBinding(StructureSelectionManager ssm,
226           PDBEntry[] pdbentry, SequenceI[][] sequenceIs, String[][] chains,
227           String protocol)
228   {
229     this.ssm = ssm;
230     this.sequence = sequenceIs;
231     this.chains = chains;
232     this.pdbentry = pdbentry;
233     this.protocol = protocol;
234     if (chains == null)
235     {
236       this.chains = new String[pdbentry.length][];
237     }
238     viewer = new ChimeraManager(
239             csm = new ext.edu.ucsf.rbvi.strucviz2.StructureManager(true));
240   }
241
242   public JalviewChimeraBinding(StructureSelectionManager ssm,
243           ChimeraManager viewer2)
244   {
245     this.ssm = ssm;
246     viewer = viewer2;
247     csm = viewer.getStructureManager();
248   }
249
250   /**
251    * Construct a title string for the viewer window based on the data Jalview
252    * knows about
253    * 
254    * @param verbose
255    * @return
256    */
257   public String getViewerTitle(boolean verbose)
258   {
259     if (sequence == null || pdbentry == null || sequence.length < 1
260             || pdbentry.length < 1 || sequence[0].length < 1)
261     {
262       return ("Jalview Chimera Window");
263     }
264     // TODO: give a more informative title when multiple structures are
265     // displayed.
266     StringBuilder title = new StringBuilder(64);
267     title.append("Chimera view for " + sequence[0][0].getName() + ":"
268             + pdbentry[0].getId());
269
270     if (verbose)
271     {
272       if (pdbentry[0].getProperty() != null)
273       {
274         if (pdbentry[0].getProperty().get("method") != null)
275         {
276           title.append(" Method: ");
277           title.append(pdbentry[0].getProperty().get("method"));
278         }
279         if (pdbentry[0].getProperty().get("chains") != null)
280         {
281           title.append(" Chain:");
282           title.append(pdbentry[0].getProperty().get("chains"));
283         }
284       }
285     }
286     return title.toString();
287   }
288
289   /**
290    * prepare the view for a given set of models/chains. chainList contains
291    * strings of the form 'pdbfilename:Chaincode'
292    * 
293    * @param toshow
294    *          list of chains to make visible
295    */
296   public void centerViewer(List<String> toshow)
297   {
298     StringBuilder cmd = new StringBuilder(64);
299     int mlength, p;
300     for (String lbl : toshow)
301     {
302       mlength = 0;
303       do
304       {
305         p = mlength;
306         mlength = lbl.indexOf(":", p);
307       } while (p < mlength && mlength < (lbl.length() - 2));
308       // TODO: lookup each pdb id and recover proper model number for it.
309       cmd.append("#" + getModelNum(chainFile.get(lbl)) + "."
310               + lbl.substring(mlength + 1) + " or ");
311     }
312     if (cmd.length() > 0)
313     {
314       cmd.setLength(cmd.length() - 4);
315     }
316     String cmdstring = cmd.toString();
317     evalStateCommand("~display #*; ~ribbon #*; ribbon " + cmdstring
318             + ";focus " + cmdstring, false);
319   }
320
321   /**
322    * Close down the Jalview viewer, and (optionally) the associate Chimera
323    * window.
324    */
325   public void closeViewer(boolean closeChimera)
326   {
327     ssm.removeStructureViewerListener(this, this.getPdbFile());
328     if (closeChimera)
329     {
330       viewer.exitChimera();
331     }
332     lastCommand = null;
333     viewer = null;
334     releaseUIResources();
335   }
336
337   /**
338    * called by JalviewChimerabinding after closeViewer is called - release any
339    * resources and references so they can be garbage collected.
340    */
341   protected abstract void releaseUIResources();
342
343   public void colourByChain()
344   {
345     colourBySequence = false;
346     evalStateCommand("rainbow chain", false);
347   }
348
349   public void colourByCharge()
350   {
351     colourBySequence = false;
352     evalStateCommand(
353             "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS",
354             false);
355   }
356
357   /**
358    * superpose the structures associated with sequences in the alignment
359    * according to their corresponding positions.
360    */
361   public void superposeStructures(AlignmentI alignment)
362   {
363     superposeStructures(alignment, -1, null);
364   }
365
366   /**
367    * superpose the structures associated with sequences in the alignment
368    * according to their corresponding positions. ded)
369    * 
370    * @param refStructure
371    *          - select which pdb file to use as reference (default is -1 - the
372    *          first structure in the alignment)
373    */
374   public void superposeStructures(AlignmentI alignment, int refStructure)
375   {
376     superposeStructures(alignment, refStructure, null);
377   }
378
379   /**
380    * superpose the structures associated with sequences in the alignment
381    * according to their corresponding positions. ded)
382    * 
383    * @param refStructure
384    *          - select which pdb file to use as reference (default is -1 - the
385    *          first structure in the alignment)
386    * @param hiddenCols
387    *          TODO
388    */
389   public void superposeStructures(AlignmentI alignment, int refStructure,
390           ColumnSelection hiddenCols)
391   {
392     superposeStructures(new AlignmentI[]
393     { alignment }, new int[]
394     { refStructure }, new ColumnSelection[]
395     { hiddenCols });
396   }
397
398   public void superposeStructures(AlignmentI[] _alignment,
399           int[] _refStructure, ColumnSelection[] _hiddenCols)
400   {
401     assert (_alignment.length == _refStructure.length && _alignment.length != _hiddenCols.length);
402     StringBuilder allComs = new StringBuilder(128); // Chimera superposition cmd
403     String[] files = getPdbFile();
404     // check to see if we are still waiting for Chimera files
405     long starttime = System.currentTimeMillis();
406     boolean waiting = true;
407     do
408     {
409       waiting = false;
410       for (String file : files)
411       {
412         try
413         {
414           // HACK - in Jalview 2.8 this call may not be threadsafe so we catch
415           // every possible exception
416           StructureMapping[] sm = ssm.getMapping(file);
417           if (sm == null || sm.length == 0)
418           {
419             waiting = true;
420           }
421         } catch (Exception x)
422         {
423           waiting = true;
424         } catch (Error q)
425         {
426           waiting = true;
427         }
428       }
429       // we wait around for a reasonable time before we give up
430     } while (waiting
431             && System.currentTimeMillis() < (10000 + 1000 * files.length + starttime));
432     if (waiting)
433     {
434       System.err
435               .println("RUNTIME PROBLEM: Chimera seems to be taking a long time to process all the structures.");
436       return;
437     }
438     refreshPdbEntries();
439     StringBuffer selectioncom = new StringBuffer();
440     for (int a = 0; a < _alignment.length; a++)
441     {
442       int refStructure = _refStructure[a];
443       AlignmentI alignment = _alignment[a];
444       ColumnSelection hiddenCols = _hiddenCols[a];
445       if (a > 0
446               && selectioncom.length() > 0
447               && !selectioncom.substring(selectioncom.length() - 1).equals(
448                       " "))
449       {
450         selectioncom.append(" ");
451       }
452       // process this alignment
453       if (refStructure >= files.length)
454       {
455         System.err.println("Invalid reference structure value "
456                 + refStructure);
457         refStructure = -1;
458       }
459       if (refStructure < -1)
460       {
461         refStructure = -1;
462       }
463
464       boolean matched[] = new boolean[alignment.getWidth()];
465       for (int m = 0; m < matched.length; m++)
466       {
467
468         matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
469       }
470
471       int commonrpositions[][] = new int[files.length][alignment.getWidth()];
472       String isel[] = new String[files.length];
473       String[] targetC = new String[files.length];
474       String[] chainNames = new String[files.length];
475       String[] atomSpec = new String[files.length];
476       for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
477       {
478         StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
479         // RACE CONDITION - getMapping only returns Jmol loaded filenames once
480         // Jmol callback has completed.
481         if (mapping == null || mapping.length < 1)
482         {
483           throw new Error(MessageManager.getString("error.implementation_error_chimera_getting_data"));
484         }
485         int lastPos = -1;
486         for (int s = 0; s < sequence[pdbfnum].length; s++)
487         {
488           for (int sp, m = 0; m < mapping.length; m++)
489           {
490             if (mapping[m].getSequence() == sequence[pdbfnum][s]
491                     && (sp = alignment.findIndex(sequence[pdbfnum][s])) > -1)
492             {
493               if (refStructure == -1)
494               {
495                 refStructure = pdbfnum;
496               }
497               SequenceI asp = alignment.getSequenceAt(sp);
498               for (int r = 0; r < matched.length; r++)
499               {
500                 if (!matched[r])
501                 {
502                   continue;
503                 }
504                 matched[r] = false; // assume this is not a good site
505                 if (r >= asp.getLength())
506                 {
507                   continue;
508                 }
509
510                 if (jalview.util.Comparison.isGap(asp.getCharAt(r)))
511                 {
512                   // no mapping to gaps in sequence
513                   continue;
514                 }
515                 int t = asp.findPosition(r); // sequence position
516                 int apos = mapping[m].getAtomNum(t);
517                 int pos = mapping[m].getPDBResNum(t);
518
519                 if (pos < 1 || pos == lastPos)
520                 {
521                   // can't align unmapped sequence
522                   continue;
523                 }
524                 matched[r] = true; // this is a good ite
525                 lastPos = pos;
526                 // just record this residue position
527                 commonrpositions[pdbfnum][r] = pos;
528               }
529               // create model selection suffix
530               isel[pdbfnum] = "#" + pdbfnum;
531               if (mapping[m].getChain() == null
532                       || mapping[m].getChain().trim().length() == 0)
533               {
534                 targetC[pdbfnum] = "";
535               }
536               else
537               {
538                 targetC[pdbfnum] = "." + mapping[m].getChain();
539               }
540               chainNames[pdbfnum] = mapping[m].getPdbId()
541                       + targetC[pdbfnum];
542               atomSpec[pdbfnum] = asp.getRNA() != null ? PHOSPHORUS : ALPHACARBON;
543               // move on to next pdb file
544               s = sequence[pdbfnum].length;
545               break;
546             }
547           }
548         }
549       }
550
551       // TODO: consider bailing if nmatched less than 4 because superposition
552       // not
553       // well defined.
554       // TODO: refactor superposable position search (above) from jmol selection
555       // construction (below)
556
557       String[] selcom = new String[files.length];
558       int nmatched = 0;
559       String sep = "";
560       // generate select statements to select regions to superimpose structures
561       {
562         for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
563         {
564           String chainCd = targetC[pdbfnum];
565           int lpos = -1;
566           boolean run = false;
567           StringBuffer molsel = new StringBuffer();
568           for (int r = 0; r < matched.length; r++)
569           {
570             if (matched[r])
571             {
572               if (pdbfnum == 0)
573               {
574                 nmatched++;
575               }
576               if (lpos != commonrpositions[pdbfnum][r] - 1)
577               {
578                 // discontinuity
579                 if (lpos != -1)
580                 {
581                   molsel.append((run ? "" : ":") + lpos);
582                   molsel.append(chainCd);
583                   molsel.append(",");
584                 }
585               }
586               else
587               {
588                 // continuous run - and lpos >-1
589                 if (!run)
590                 {
591                   // at the beginning, so add dash
592                   molsel.append(":" + lpos);
593                   molsel.append("-");
594                 }
595                 run = true;
596               }
597               lpos = commonrpositions[pdbfnum][r];
598               // molsel.append(lpos);
599             }
600           }
601           // add final selection phrase
602           if (lpos != -1)
603           {
604             molsel.append((run ? "" : ":") + lpos);
605             molsel.append(chainCd);
606             // molsel.append("");
607           }
608           if (molsel.length() > 1)
609           {
610             selcom[pdbfnum] = molsel.toString();
611             selectioncom.append("#" + pdbfnum);
612             selectioncom.append(selcom[pdbfnum]);
613             selectioncom.append(" ");
614             if (pdbfnum < files.length - 1)
615             {
616               selectioncom.append("| ");
617             }
618           }
619           else
620           {
621             selcom[pdbfnum] = null;
622           }
623         }
624       }
625       StringBuilder command = new StringBuilder(256);
626       for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
627       {
628         if (pdbfnum == refStructure || selcom[pdbfnum] == null
629                 || selcom[refStructure] == null)
630         {
631           continue;
632         }
633         if (command.length() > 0)
634         {
635           command.append(";");
636         }
637
638         /*
639          * Form Chimera match command, from the 'new' structure to the
640          * 'reference' structure e.g. (residues 1-91, chain B/A, alphacarbons):
641          * 
642          * match #1:1-91.B@CA #0:1-91.A@CA
643          * 
644          * @see
645          * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
646          */
647         command.append("match #" + pdbfnum /* +".1" */);
648         // TODO: handle sub-models
649         command.append(selcom[pdbfnum]);
650         command.append("@" + atomSpec[pdbfnum]);
651         command.append(" #" + refStructure /* +".1" */);
652         command.append(selcom[refStructure]);
653         command.append("@" + atomSpec[refStructure]);
654       }
655       if (selectioncom.length() > 0)
656       {
657         // TODO remove debug output
658         System.out.println("Select regions:\n" + selectioncom.toString());
659         System.out
660                 .println("Superimpose command(s):\n" + command.toString());
661         allComs.append("~display all; chain @CA|P; ribbon "
662                 + selectioncom.toString() + ";"+command.toString());
663         // selcom.append("; ribbons; ");
664       }
665     }
666     if (selectioncom.length() > 0)
667     {// finally, mark all regions that were superposed.
668       if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
669       {
670         selectioncom.setLength(selectioncom.length() - 1);
671       }
672       System.out.println("Select regions:\n" + selectioncom.toString());
673       allComs.append("; ~display all; chain @CA|P; ribbon "
674               + selectioncom.toString() + "; focus");
675       // evalStateCommand("select *; backbone; select "+selcom.toString()+"; cartoons; center "+selcom.toString());
676       evalStateCommand(allComs.toString(), true /* false */);
677     }
678     
679   }
680
681   private void checkLaunched()
682   {
683     if (!viewer.isChimeraLaunched())
684     {
685       viewer.launchChimera(csm.getChimeraPaths());
686     }
687     if (!viewer.isChimeraLaunched())
688     {
689       log("Failed to launch Chimera!");
690     }
691   }
692
693   /**
694    * Answers true if the Chimera process is still running, false if ended or not
695    * started.
696    * 
697    * @return
698    */
699   public boolean isChimeraRunning()
700   {
701     return viewer.isChimeraLaunched();
702   }
703
704   /**
705    * Send a command to Chimera, and optionally log any responses.
706    * 
707    * @param command
708    * @param logResponse
709    */
710   public void evalStateCommand(final String command, boolean logResponse)
711   {
712     viewerCommandHistory(false);
713     checkLaunched();
714     if (lastCommand == null || !lastCommand.equals(command))
715     {
716 //      Thread t = new Thread(new Runnable()
717 //      {
718 //        @Override
719 //        public void run()
720 //        {
721       // trim command or it may never find a match in the replyLog!!
722       lastReply = viewer.sendChimeraCommand(command.trim(), logResponse);
723       if (debug && logResponse)
724           {
725             log("Response from command ('" + command + "') was:\n"
726                     + lastReply);
727           }
728 //        }
729 //      });
730       // TODO - use j7/8 thread management
731 //      try
732 //      {
733 //        t.join();
734 //      } catch (InterruptedException foo)
735 //      {
736 //      }
737 //      ;
738     }
739     viewerCommandHistory(true);
740     lastCommand = command;
741   }
742
743   /**
744    * colour any structures associated with sequences in the given alignment
745    * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
746    * if colourBySequence is enabled.
747    */
748   public void colourBySequence(boolean showFeatures,
749           jalview.api.AlignmentViewPanel alignmentv)
750   {
751     if (!colourBySequence || !loadingFinished)
752     {
753       return;
754     }
755     if (ssm == null)
756     {
757       return;
758     }
759     String[] files = getPdbFile();
760
761     SequenceRenderer sr = getSequenceRenderer(alignmentv);
762
763     FeatureRenderer fr = null;
764     if (showFeatures)
765     {
766       fr = getFeatureRenderer(alignmentv);
767     }
768     AlignmentI alignment = alignmentv.getAlignment();
769
770     for (jalview.structure.StructureMappingcommandSet cpdbbyseq : ChimeraCommands
771             .getColourBySequenceCommand(ssm, files, sequence, sr, fr,
772                     alignment))
773     {
774       for (String cbyseq : cpdbbyseq.commands)
775       {
776         waitForChimera();
777         evalStateCommand(cbyseq, false);
778         waitForChimera();
779       }
780     }
781   }
782
783   private void waitForChimera()
784   {
785     while (viewer != null && viewer.isBusy())
786     {
787       try {
788         Thread.sleep(15);
789       } catch (InterruptedException q)
790       {}
791     }
792   }
793
794   public boolean isColourBySequence()
795   {
796     return colourBySequence;
797   }
798
799   public void setColourBySequence(boolean colourBySequence)
800   {
801     this.colourBySequence = colourBySequence;
802   }
803
804   // End StructureListener
805   // //////////////////////////
806
807   public float[][] functionXY(String functionName, int x, int y)
808   {
809     return null;
810   }
811
812   public float[][][] functionXYZ(String functionName, int nx, int ny, int nz)
813   {
814     // TODO Auto-generated method stub
815     return null;
816   }
817
818   public Color getColour(int atomIndex, int pdbResNum, String chain,
819           String pdbfile)
820   {
821     if (getModelNum(pdbfile) < 0)
822     {
823       return null;
824     }
825     log("get model / residue colour attribute unimplemented");
826     return null;
827   }
828
829   /**
830    * returns the current featureRenderer that should be used to colour the
831    * structures
832    * 
833    * @param alignment
834    * 
835    * @return
836    */
837   public abstract FeatureRenderer getFeatureRenderer(
838           AlignmentViewPanel alignment);
839
840   /**
841    * instruct the Jalview binding to update the pdbentries vector if necessary
842    * prior to matching the jmol view's contents to the list of structure files
843    * Jalview knows about.
844    */
845   public abstract void refreshPdbEntries();
846
847   private int getModelNum(String modelFileName)
848   {
849     String[] mfn = getPdbFile();
850     if (mfn == null)
851     {
852       return -1;
853     }
854     for (int i = 0; i < mfn.length; i++)
855     {
856       if (mfn[i].equalsIgnoreCase(modelFileName))
857       {
858         return i;
859       }
860     }
861     return -1;
862   }
863
864   /**
865    * map between index of model filename returned from getPdbFile and the first
866    * index of models from this file in the viewer. Note - this is not trimmed -
867    * use getPdbFile to get number of unique models.
868    */
869   private int _modelFileNameMap[];
870
871   // ////////////////////////////////
872   // /StructureListener
873   public synchronized String[] getPdbFile()
874   {
875     if (viewer == null)
876     {
877       return new String[0];
878     }
879     // if (modelFileNames == null)
880     // {
881     // Collection<ChimeraModel> chimodels = viewer.getChimeraModels();
882     // _modelFileNameMap = new int[chimodels.size()];
883     // int j = 0;
884     // for (ChimeraModel chimodel : chimodels)
885     // {
886     // String mdlName = chimodel.getModelName();
887     // }
888     // modelFileNames = new String[j];
889     // // System.arraycopy(mset, 0, modelFileNames, 0, j);
890     // }
891
892     return chimmaps.keySet().toArray(
893             modelFileNames = new String[chimmaps.size()]);
894   }
895
896   /**
897    * map from string to applet
898    */
899   public Map getRegistryInfo()
900   {
901     // TODO Auto-generated method stub
902     return null;
903   }
904
905   /**
906    * returns the current sequenceRenderer that should be used to colour the
907    * structures
908    * 
909    * @param alignment
910    * 
911    * @return
912    */
913   public abstract SequenceRenderer getSequenceRenderer(
914           AlignmentViewPanel alignment);
915
916   // jmol/ssm only
917   public void highlightAtom(int atomIndex, int pdbResNum, String chain,
918           String pdbfile)
919   {
920     List<ChimeraModel> cms = chimmaps.get(pdbfile);
921     if (cms != null)
922     {
923       int mdlNum = cms.get(0).getModelNumber();
924
925       viewerCommandHistory(false);
926       // viewer.stopListening();
927       if (resetLastRes.length() > 0)
928       {
929         eval.setLength(0);
930         eval.append(resetLastRes.toString() + ";");
931       }
932
933       eval.append("display "); // +modelNum
934
935       resetLastRes.setLength(0);
936       resetLastRes.append("~display ");
937       {
938         eval.append(" #" + (mdlNum));
939         resetLastRes.append(" #" + (mdlNum));
940       }
941       // complete select string
942
943       eval.append(":" + pdbResNum);
944       resetLastRes.append(":" + pdbResNum);
945       if (!chain.equals(" "))
946       {
947         eval.append("." + chain);
948         resetLastRes.append("." + chain);
949       }
950       
951       viewer.sendChimeraCommand(eval.toString(), false);
952       viewerCommandHistory(true);
953       // viewer.startListening();
954     }
955   }
956
957   boolean debug = false;
958
959   private void log(String message)
960   {
961     System.err.println("## Chimera log: " + message);
962   }
963
964   private void viewerCommandHistory(boolean enable)
965   {
966     // log("(Not yet implemented) History "
967     // + ((debug || enable) ? "on" : "off"));
968   }
969
970   public void loadInline(String string)
971   {
972     loadedInline = true;
973     // TODO: re JAL-623
974     // viewer.loadInline(strModel, isAppend);
975     // could do this:
976     // construct fake fullPathName and fileName so we can identify the file
977     // later.
978     // Then, construct pass a reader for the string to Jmol.
979     // ((org.jmol.Viewer.Viewer) viewer).loadModelFromFile(fullPathName,
980     // fileName, null, reader, false, null, null, 0);
981     // viewer.openStringInline(string);
982     log("cannot load inline in Chimera, yet");
983   }
984
985   public void mouseOverStructure(int atomIndex, String strInfo)
986   {
987     // function to parse a mouseOver event from Chimera
988     //
989     int pdbResNum;
990     int alocsep = strInfo.indexOf("^");
991     int mdlSep = strInfo.indexOf("/");
992     int chainSeparator = strInfo.indexOf(":"), chainSeparator1 = -1;
993
994     if (chainSeparator == -1)
995     {
996       chainSeparator = strInfo.indexOf(".");
997       if (mdlSep > -1 && mdlSep < chainSeparator)
998       {
999         chainSeparator1 = chainSeparator;
1000         chainSeparator = mdlSep;
1001       }
1002     }
1003     // handle insertion codes
1004     if (alocsep != -1)
1005     {
1006       pdbResNum = Integer.parseInt(strInfo.substring(
1007               strInfo.indexOf("]") + 1, alocsep));
1008
1009     }
1010     else
1011     {
1012       pdbResNum = Integer.parseInt(strInfo.substring(
1013               strInfo.indexOf("]") + 1, chainSeparator));
1014     }
1015     String chainId;
1016
1017     if (strInfo.indexOf(":") > -1)
1018     {
1019       chainId = strInfo.substring(strInfo.indexOf(":") + 1,
1020               strInfo.indexOf("."));
1021     }
1022     else
1023     {
1024       chainId = " ";
1025     }
1026
1027     String pdbfilename = modelFileNames[frameNo]; // default is first or current
1028     // model
1029     if (mdlSep > -1)
1030     {
1031       if (chainSeparator1 == -1)
1032       {
1033         chainSeparator1 = strInfo.indexOf(".", mdlSep);
1034       }
1035       String mdlId = (chainSeparator1 > -1) ? strInfo.substring(mdlSep + 1,
1036               chainSeparator1) : strInfo.substring(mdlSep + 1);
1037       try
1038       {
1039         // recover PDB filename for the model hovered over.
1040         int _mp = _modelFileNameMap.length - 1, mnumber = new Integer(mdlId)
1041                 .intValue() - 1;
1042         while (mnumber < _modelFileNameMap[_mp])
1043         {
1044           _mp--;
1045         }
1046         pdbfilename = modelFileNames[_mp];
1047         if (pdbfilename == null)
1048         {
1049           // pdbfilename = new File(viewer.getModelFileName(mnumber))
1050           // .getAbsolutePath();
1051         }
1052
1053       } catch (Exception e)
1054       {
1055       }
1056       ;
1057     }
1058     if (lastMessage == null || !lastMessage.equals(strInfo))
1059     {
1060       ssm.mouseOverStructure(pdbResNum, chainId, pdbfilename);
1061     }
1062
1063     lastMessage = strInfo;
1064   }
1065
1066   public void notifyAtomPicked(int atomIndex, String strInfo, String strData)
1067   {
1068     /**
1069      * this implements the toggle label behaviour copied from the original
1070      * structure viewer, MCView
1071      */
1072     if (strData != null)
1073     {
1074       System.err.println("Ignoring additional pick data string " + strData);
1075     }
1076     // rewrite these selections for chimera (DNA, RNA and protein)
1077     int chainSeparator = strInfo.indexOf(":");
1078     int p = 0;
1079     if (chainSeparator == -1)
1080     {
1081       chainSeparator = strInfo.indexOf(".");
1082     }
1083
1084     String picked = strInfo.substring(strInfo.indexOf("]") + 1,
1085             chainSeparator);
1086     String mdlString = "";
1087     if ((p = strInfo.indexOf(":")) > -1)
1088     {
1089       picked += strInfo.substring(p + 1, strInfo.indexOf("."));
1090     }
1091
1092     if ((p = strInfo.indexOf("/")) > -1)
1093     {
1094       mdlString += strInfo.substring(p, strInfo.indexOf(" #"));
1095     }
1096     picked = "((" + picked + ".CA" + mdlString + ")|(" + picked + ".P"
1097             + mdlString + "))";
1098     viewerCommandHistory(false);
1099
1100     if (!atomsPicked.contains(picked))
1101     {
1102       viewer.select(picked);
1103       atomsPicked.add(picked);
1104     }
1105     else
1106     {
1107       viewer.select("not " + picked);
1108       atomsPicked.remove(picked);
1109     }
1110     viewerCommandHistory(true);
1111     // TODO: in application this happens
1112     //
1113     // if (scriptWindow != null)
1114     // {
1115     // scriptWindow.sendConsoleMessage(strInfo);
1116     // scriptWindow.sendConsoleMessage("\n");
1117     // }
1118
1119   }
1120
1121   // incremented every time a load notification is successfully handled -
1122   // lightweight mechanism for other threads to detect when they can start
1123   // referring to new structures.
1124   private long loadNotifiesHandled = 0;
1125
1126   public long getLoadNotifiesHandled()
1127   {
1128     return loadNotifiesHandled;
1129   }
1130
1131   public void notifyFileLoaded(String fullPathName, String fileName2,
1132           String modelName, String errorMsg, int modelParts)
1133   {
1134     if (errorMsg != null)
1135     {
1136       fileLoadingError = errorMsg;
1137       refreshGUI();
1138       return;
1139     }
1140     // TODO: deal sensibly with models loaded inLine:
1141     // modelName will be null, as will fullPathName.
1142
1143     // the rest of this routine ignores the arguments, and simply interrogates
1144     // the Jmol view to find out what structures it contains, and adds them to
1145     // the structure selection manager.
1146     fileLoadingError = null;
1147     String[] oldmodels = modelFileNames;
1148     modelFileNames = null;
1149     chainNames = new ArrayList<String>();
1150     chainFile = new HashMap<String, String>();
1151     boolean notifyLoaded = false;
1152     String[] modelfilenames = getPdbFile();
1153     // first check if we've lost any structures
1154     if (oldmodels != null && oldmodels.length > 0)
1155     {
1156       int oldm = 0;
1157       for (int i = 0; i < oldmodels.length; i++)
1158       {
1159         for (int n = 0; n < modelfilenames.length; n++)
1160         {
1161           if (modelfilenames[n] == oldmodels[i])
1162           {
1163             oldmodels[i] = null;
1164             break;
1165           }
1166         }
1167         if (oldmodels[i] != null)
1168         {
1169           oldm++;
1170         }
1171       }
1172       if (oldm > 0)
1173       {
1174         String[] oldmfn = new String[oldm];
1175         oldm = 0;
1176         for (int i = 0; i < oldmodels.length; i++)
1177         {
1178           if (oldmodels[i] != null)
1179           {
1180             oldmfn[oldm++] = oldmodels[i];
1181           }
1182         }
1183         // deregister the Jmol instance for these structures - we'll add
1184         // ourselves again at the end for the current structure set.
1185         ssm.removeStructureViewerListener(this, oldmfn);
1186       }
1187     }
1188
1189     // register ourselves as a listener and notify the gui that it needs to
1190     // update itself.
1191     ssm.addStructureViewerListener(this);
1192
1193     if (notifyLoaded)
1194     {
1195       FeatureRenderer fr = getFeatureRenderer(null);
1196       if (fr != null)
1197       {
1198         fr.featuresAdded();
1199       }
1200       refreshGUI();
1201       loadNotifiesHandled++;
1202     }
1203     setLoadingFromArchive(false);
1204   }
1205
1206   public void setJalviewColourScheme(ColourSchemeI cs)
1207   {
1208     colourBySequence = false;
1209
1210     if (cs == null)
1211     {
1212       return;
1213     }
1214
1215     String res;
1216     int index;
1217     Color col;
1218     // Chimera expects RBG values in the range 0-1
1219     final double normalise = 255D;
1220     viewerCommandHistory(false);
1221     // TODO: Switch between nucleotide or aa selection expressions
1222     Enumeration en = ResidueProperties.aa3Hash.keys();
1223     StringBuilder command = new StringBuilder(128);
1224     command.append("color white;");
1225     while (en.hasMoreElements())
1226     {
1227       res = en.nextElement().toString();
1228       index = ((Integer) ResidueProperties.aa3Hash.get(res)).intValue();
1229       if (index > 20)
1230       {
1231         continue;
1232       }
1233
1234       col = cs.findColour(ResidueProperties.aa[index].charAt(0));
1235       command.append("color " + col.getRed() / normalise + ","
1236               + col.getGreen() / normalise + "," + col.getBlue()
1237               / normalise + " ::" + res + ";");
1238     }
1239
1240     evalStateCommand(command.toString(),false);
1241     viewerCommandHistory(true);
1242   }
1243
1244   /**
1245    * called when the binding thinks the UI needs to be refreshed after a Chimera
1246    * state change. this could be because structures were loaded, or because an
1247    * error has occurred.
1248    */
1249   public abstract void refreshGUI();
1250
1251   public void componentResized(ComponentEvent e)
1252   {
1253
1254   }
1255
1256   public void componentMoved(ComponentEvent e)
1257   {
1258
1259   }
1260
1261   public void componentShown(ComponentEvent e)
1262   {
1263   }
1264
1265   public void componentHidden(ComponentEvent e)
1266   {
1267   }
1268
1269   public void setLoadingFromArchive(boolean loadingFromArchive)
1270   {
1271     this.loadingFromArchive = loadingFromArchive;
1272   }
1273
1274   /**
1275    * 
1276    * @return true if Chimeral is still restoring state or loading is still going
1277    *         on (see setFinsihedLoadingFromArchive)
1278    */
1279   public boolean isLoadingFromArchive()
1280   {
1281     return loadingFromArchive && !loadingFinished;
1282   }
1283
1284   /**
1285    * modify flag which controls if sequence colouring events are honoured by the
1286    * binding. Should be true for normal operation
1287    * 
1288    * @param finishedLoading
1289    */
1290   public void setFinishedLoadingFromArchive(boolean finishedLoading)
1291   {
1292     loadingFinished = finishedLoading;
1293   }
1294
1295   /**
1296    * Send the Chimera 'background solid <color>" command.
1297    * 
1298    * @see https
1299    *      ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
1300    *      .html
1301    * @param col
1302    */
1303   public void setBackgroundColour(Color col)
1304   {
1305     viewerCommandHistory(false);
1306     double normalise = 255D;
1307     final String command = "background solid " + col.getRed() / normalise + ","
1308             + col.getGreen() / normalise + "," + col.getBlue()
1309             / normalise + ";";
1310     viewer.sendChimeraCommand(command, false);
1311     viewerCommandHistory(true);
1312   }
1313
1314   /**
1315    * add structures and any known sequence associations
1316    * 
1317    * @returns the pdb entries added to the current set.
1318    */
1319   public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
1320           SequenceI[][] seq, String[][] chns)
1321   {
1322     List<PDBEntry> v = new ArrayList<PDBEntry>();
1323     List<int[]> rtn = new ArrayList<int[]>();
1324     for (int i = 0; i < pdbentry.length; i++)
1325     {
1326       v.add(pdbentry[i]);
1327     }
1328     for (int i = 0; i < pdbe.length; i++)
1329     {
1330       int r = v.indexOf(pdbe[i]);
1331       if (r == -1 || r >= pdbentry.length)
1332       {
1333         rtn.add(new int[]
1334         { v.size(), i });
1335         v.add(pdbe[i]);
1336       }
1337       else
1338       {
1339         // just make sure the sequence/chain entries are all up to date
1340         addSequenceAndChain(r, seq[i], chns[i]);
1341       }
1342     }
1343     pdbe = v.toArray(new PDBEntry[v.size()]);
1344     pdbentry = pdbe;
1345     if (rtn.size() > 0)
1346     {
1347       // expand the tied sequence[] and string[] arrays
1348       SequenceI[][] sqs = new SequenceI[pdbentry.length][];
1349       String[][] sch = new String[pdbentry.length][];
1350       System.arraycopy(sequence, 0, sqs, 0, sequence.length);
1351       System.arraycopy(chains, 0, sch, 0, this.chains.length);
1352       sequence = sqs;
1353       chains = sch;
1354       pdbe = new PDBEntry[rtn.size()];
1355       for (int r = 0; r < pdbe.length; r++)
1356       {
1357         int[] stri = (rtn.get(r));
1358         // record the pdb file as a new addition
1359         pdbe[r] = pdbentry[stri[0]];
1360         // and add the new sequence/chain entries
1361         addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
1362       }
1363     }
1364     else
1365     {
1366       pdbe = null;
1367     }
1368     return pdbe;
1369   }
1370
1371   /**
1372    * Adds sequences to the pe'th pdbentry's sequence set.
1373    * 
1374    * @param pe
1375    * @param seq
1376    */
1377   public void addSequence(int pe, SequenceI[] seq)
1378   {
1379     addSequenceAndChain(pe, seq, null);
1380   }
1381
1382   private void addSequenceAndChain(int pe, SequenceI[] seq, String[] tchain)
1383   {
1384     if (pe < 0 || pe >= pdbentry.length)
1385     {
1386       throw new Error(MessageManager.formatMessage(
1387               "error.implementation_error_no_pdbentry_from_index",
1388               new Object[]
1389               { Integer.valueOf(pe).toString() }));
1390     }
1391     final String nullChain = "TheNullChain";
1392     List<SequenceI> s = new ArrayList<SequenceI>();
1393     List<String> c = new ArrayList<String>();
1394     if (chains == null)
1395     {
1396       chains = new String[pdbentry.length][];
1397     }
1398     if (sequence[pe] != null)
1399     {
1400       for (int i = 0; i < sequence[pe].length; i++)
1401       {
1402         s.add(sequence[pe][i]);
1403         if (chains[pe] != null)
1404         {
1405           if (i < chains[pe].length)
1406           {
1407             c.add(chains[pe][i]);
1408           }
1409           else
1410           {
1411             c.add(nullChain);
1412           }
1413         }
1414         else
1415         {
1416           if (tchain != null && tchain.length > 0)
1417           {
1418             c.add(nullChain);
1419           }
1420         }
1421       }
1422     }
1423     for (int i = 0; i < seq.length; i++)
1424     {
1425       if (!s.contains(seq[i]))
1426       {
1427         s.add(seq[i]);
1428         if (tchain != null && i < tchain.length)
1429         {
1430           c.add(tchain[i] == null ? nullChain : tchain[i]);
1431         }
1432       }
1433     }
1434     SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
1435     sequence[pe] = tmp;
1436     if (c.size() > 0)
1437     {
1438       String[] tch = c.toArray(new String[c.size()]);
1439       for (int i = 0; i < tch.length; i++)
1440       {
1441         if (tch[i] == nullChain)
1442         {
1443           tch[i] = null;
1444         }
1445       }
1446       chains[pe] = tch;
1447     }
1448     else
1449     {
1450       chains[pe] = null;
1451     }
1452   }
1453
1454   /**
1455    * 
1456    * @param pdbfile
1457    * @return text report of alignment between pdbfile and any associated
1458    *         alignment sequences
1459    */
1460   public String printMapping(String pdbfile)
1461   {
1462     return ssm.printMapping(pdbfile);
1463   }
1464
1465 }