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