JAL-1333 more abstraction and refactoring and working demo of Jalview talking to...
[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);
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");
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");
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
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     StringBuffer selectioncom = new StringBuffer();
448     // In principle - nSeconds specifies the speed of animation for each
449     // superposition - but is seems to behave weirdly, so we don't specify it.
450     String nSeconds = " ";
451     if (files.length > 10)
452     {
453       nSeconds = " 0.00001 ";
454     }
455     else
456     {
457       nSeconds = " " + (2.0 / files.length) + " ";
458       // if (nSeconds).substring(0,5)+" ";
459     }
460     // see JAL-1345 - should really automatically turn off the animation for
461     // large numbers of structures, but Jmol doesn't seem to allow that.
462     nSeconds = " ";
463     // union of all aligned positions are collected together.
464     for (int a = 0; a < _alignment.length; a++)
465     {
466       int refStructure = _refStructure[a];
467       AlignmentI alignment = _alignment[a];
468       ColumnSelection hiddenCols = _hiddenCols[a];
469       if (a > 0
470               && selectioncom.length() > 0
471               && !selectioncom.substring(selectioncom.length() - 1).equals(
472                       "|"))
473       {
474         selectioncom.append("|");
475       }
476       // process this alignment
477       if (refStructure >= files.length)
478       {
479         System.err.println("Invalid reference structure value "
480                 + refStructure);
481         refStructure = -1;
482       }
483       if (refStructure < -1)
484       {
485         refStructure = -1;
486       }
487       StringBuffer command = new StringBuffer();
488
489       boolean matched[] = new boolean[alignment.getWidth()];
490       for (int m = 0; m < matched.length; m++)
491       {
492
493         matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
494       }
495
496       int commonrpositions[][] = new int[files.length][alignment.getWidth()];
497       String isel[] = new String[files.length];
498       // reference structure - all others are superposed in it
499       String[] targetC = new String[files.length];
500       String[] chainNames = new String[files.length];
501       for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
502       {
503         StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
504         // RACE CONDITION - getMapping only returns Jmol loaded filenames once
505         // Jmol callback has completed.
506         if (mapping == null || mapping.length < 1)
507         {
508           throw new Error(
509                   "Implementation error - Jmol seems to be still working on getting its data - report at http://issues.jalview.org/browse/JAL-1016");
510         }
511         int lastPos = -1;
512         for (int s = 0; s < sequence[pdbfnum].length; s++)
513         {
514           for (int sp, m = 0; m < mapping.length; m++)
515           {
516             if (mapping[m].getSequence() == sequence[pdbfnum][s]
517                     && (sp = alignment.findIndex(sequence[pdbfnum][s])) > -1)
518             {
519               if (refStructure == -1)
520               {
521                 refStructure = pdbfnum;
522               }
523               SequenceI asp = alignment.getSequenceAt(sp);
524               for (int r = 0; r < matched.length; r++)
525               {
526                 if (!matched[r])
527                 {
528                   continue;
529                 }
530                 matched[r] = false; // assume this is not a good site
531                 if (r >= asp.getLength())
532                 {
533                   continue;
534                 }
535
536                 if (jalview.util.Comparison.isGap(asp.getCharAt(r)))
537                 {
538                   // no mapping to gaps in sequence
539                   continue;
540                 }
541                 int t = asp.findPosition(r); // sequence position
542                 int apos = mapping[m].getAtomNum(t);
543                 int pos = mapping[m].getPDBResNum(t);
544
545                 if (pos < 1 || pos == lastPos)
546                 {
547                   // can't align unmapped sequence
548                   continue;
549                 }
550                 matched[r] = true; // this is a good ite
551                 lastPos = pos;
552                 // just record this residue position
553                 commonrpositions[pdbfnum][r] = pos;
554               }
555               // create model selection suffix
556               isel[pdbfnum] = "/" + (pdbfnum + 1) + ".1";
557               if (mapping[m].getChain() == null
558                       || mapping[m].getChain().trim().length() == 0)
559               {
560                 targetC[pdbfnum] = "";
561               }
562               else
563               {
564                 targetC[pdbfnum] = ":" + mapping[m].getChain();
565               }
566               chainNames[pdbfnum] = mapping[m].getPdbId()
567                       + targetC[pdbfnum];
568               // move on to next pdb file
569               s = sequence[pdbfnum].length;
570               break;
571             }
572           }
573         }
574       }
575
576       // TODO: consider bailing if nmatched less than 4 because superposition
577       // not
578       // well defined.
579       // TODO: refactor superposable position search (above) from jmol selection
580       // construction (below)
581
582       String[] selcom = new String[files.length];
583       int nmatched = 0;
584       // generate select statements to select regions to superimpose structures
585       {
586         for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
587         {
588           String chainCd = targetC[pdbfnum];
589           int lpos = -1;
590           boolean run = false;
591           StringBuffer molsel = new StringBuffer();
592           molsel.append("{");
593           for (int r = 0; r < matched.length; r++)
594           {
595             if (matched[r])
596             {
597               if (pdbfnum == 0)
598               {
599                 nmatched++;
600               }
601               if (lpos != commonrpositions[pdbfnum][r] - 1)
602               {
603                 // discontinuity
604                 if (lpos != -1)
605                 {
606                   molsel.append(lpos);
607                   molsel.append(chainCd);
608                   // molsel.append("} {");
609                   molsel.append("|");
610                 }
611               }
612               else
613               {
614                 // continuous run - and lpos >-1
615                 if (!run)
616                 {
617                   // at the beginning, so add dash
618                   molsel.append(lpos);
619                   molsel.append("-");
620                 }
621                 run = true;
622               }
623               lpos = commonrpositions[pdbfnum][r];
624               // molsel.append(lpos);
625             }
626           }
627           // add final selection phrase
628           if (lpos != -1)
629           {
630             molsel.append(lpos);
631             molsel.append(chainCd);
632             molsel.append("}");
633           }
634           if (molsel.length() > 1)
635           {
636             selcom[pdbfnum] = molsel.toString();
637             selectioncom.append("((");
638             selectioncom.append(selcom[pdbfnum].substring(1,
639                     selcom[pdbfnum].length() - 1));
640             selectioncom.append(" )& ");
641             selectioncom.append(pdbfnum + 1);
642             selectioncom.append(".1)");
643             if (pdbfnum < files.length - 1)
644             {
645               selectioncom.append("|");
646             }
647           }
648           else
649           {
650             selcom[pdbfnum] = null;
651           }
652         }
653       }
654       for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
655       {
656         if (pdbfnum == refStructure || selcom[pdbfnum] == null
657                 || selcom[refStructure] == null)
658         {
659           continue;
660         }
661         command.append("echo ");
662         command.append("\"Superposing (");
663         command.append(chainNames[pdbfnum]);
664         command.append(") against reference (");
665         command.append(chainNames[refStructure]);
666         command.append(")\";\ncompare " + nSeconds);
667         command.append("{");
668         command.append(1 + pdbfnum);
669         command.append(".1} {");
670         command.append(1 + refStructure);
671         command.append(".1} SUBSET {*.CA | *.P} ATOMS ");
672
673         // form the matched pair strings
674         String sep = "";
675         for (int s = 0; s < 2; s++)
676         {
677           command.append(selcom[(s == 0 ? pdbfnum : refStructure)]);
678         }
679         command.append(" ROTATE TRANSLATE;\n");
680       }
681       if (selectioncom.length() > 0)
682       {
683         System.out.println("Select regions:\n" + selectioncom.toString());
684         evalStateCommand("select *; cartoons off; backbone; select ("
685                 + selectioncom.toString() + "); cartoons; ");
686         // selcom.append("; ribbons; ");
687         System.out
688                 .println("Superimpose command(s):\n" + command.toString());
689
690         evalStateCommand(command.toString());
691       }
692     }
693     if (selectioncom.length() > 0)
694     {// finally, mark all regions that were superposed.
695       if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
696       {
697         selectioncom.setLength(selectioncom.length() - 1);
698       }
699       System.out.println("Select regions:\n" + selectioncom.toString());
700       evalStateCommand("select *; cartoons off; backbone; select ("
701               + selectioncom.toString() + "); cartoons; ");
702       // evalStateCommand("select *; backbone; select "+selcom.toString()+"; cartoons; center "+selcom.toString());
703     }
704   }
705
706   private void checkLaunched()
707   {
708     if (!viewer.isChimeraLaunched())
709     {
710       viewer.launchChimera(csm.getChimeraPaths());
711     }
712     if (!viewer.isChimeraLaunched())
713     {
714       log("Failed to launch Chimera!");
715     }
716   }
717
718   public void evalStateCommand(String command)
719   {
720     viewerCommandHistory(false);
721     checkLaunched();
722     if (lastCommand == null || !lastCommand.equals(command))
723     {
724
725       lastReply = viewer.sendChimeraCommand(command, true);
726       if (debug)
727       {
728         log("Response from command ('" + command + "') was:\n" + lastReply);
729       }
730     }
731     viewerCommandHistory(true);
732     lastCommand = command;
733   }
734
735   /**
736    * colour any structures associated with sequences in the given alignment
737    * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
738    * if colourBySequence is enabled.
739    */
740   public void colourBySequence(boolean showFeatures,
741           jalview.api.AlignmentViewPanel alignmentv)
742   {
743     if (!colourBySequence || !loadingFinished)
744       return;
745     if (ssm == null)
746     {
747       return;
748     }
749     String[] files = getPdbFile();
750
751     SequenceRenderer sr = getSequenceRenderer(alignmentv);
752
753     FeatureRenderer fr = null;
754     if (showFeatures)
755     {
756       fr = getFeatureRenderer(alignmentv);
757     }
758     AlignmentI alignment = alignmentv.getAlignment();
759
760     for (jalview.structure.StructureMappingcommandSet cpdbbyseq : ChimeraCommands
761             .getColourBySequenceCommand(ssm, files, sequence, sr, fr,
762                     alignment))
763       for (String cbyseq : cpdbbyseq.commands)
764       {
765         evalStateCommand(cbyseq);
766       }
767   }
768
769   public boolean isColourBySequence()
770   {
771     return colourBySequence;
772   }
773
774   public void setColourBySequence(boolean colourBySequence)
775   {
776     this.colourBySequence = colourBySequence;
777   }
778
779   public void createImage(String file, String type, int quality)
780   {
781     System.out.println("JMOL CREATE IMAGE");
782   }
783
784   public String createImage(String fileName, String type,
785           Object textOrBytes, int quality)
786   {
787     System.out.println("JMOL CREATE IMAGE");
788     return null;
789   }
790
791   public String eval(String strEval)
792   {
793     // System.out.println(strEval);
794     // "# 'eval' is implemented only for the applet.";
795     return null;
796   }
797
798   // End StructureListener
799   // //////////////////////////
800
801   public float[][] functionXY(String functionName, int x, int y)
802   {
803     return null;
804   }
805
806   public float[][][] functionXYZ(String functionName, int nx, int ny, int nz)
807   {
808     // TODO Auto-generated method stub
809     return null;
810   }
811
812   public Color getColour(int atomIndex, int pdbResNum, String chain,
813           String pdbfile)
814   {
815     if (getModelNum(pdbfile) < 0)
816       return null;
817     log("get model / residue colour attribute unimplemented");
818     return null;
819   }
820
821   /**
822    * returns the current featureRenderer that should be used to colour the
823    * structures
824    * 
825    * @param alignment
826    * 
827    * @return
828    */
829   public abstract FeatureRenderer getFeatureRenderer(
830           AlignmentViewPanel alignment);
831
832   /**
833    * instruct the Jalview binding to update the pdbentries vector if necessary
834    * prior to matching the jmol view's contents to the list of structure files
835    * Jalview knows about.
836    */
837   public abstract void refreshPdbEntries();
838
839   private int getModelNum(String modelFileName)
840   {
841     String[] mfn = getPdbFile();
842     if (mfn == null)
843     {
844       return -1;
845     }
846     for (int i = 0; i < mfn.length; i++)
847     {
848       if (mfn[i].equalsIgnoreCase(modelFileName))
849         return i;
850     }
851     return -1;
852   }
853
854   /**
855    * map between index of model filename returned from getPdbFile and the first
856    * index of models from this file in the viewer. Note - this is not trimmed -
857    * use getPdbFile to get number of unique models.
858    */
859   private int _modelFileNameMap[];
860
861   // ////////////////////////////////
862   // /StructureListener
863   public synchronized String[] getPdbFile()
864   {
865     if (viewer == null)
866     {
867       return new String[0];
868     }
869 //    if (modelFileNames == null)
870 //    {
871 //      Collection<ChimeraModel> chimodels = viewer.getChimeraModels();
872 //      _modelFileNameMap = new int[chimodels.size()];
873 //      int j = 0;
874 //      for (ChimeraModel chimodel : chimodels)
875 //      {
876 //        String mdlName = chimodel.getModelName();
877 //      }
878 //      modelFileNames = new String[j];
879 //      // System.arraycopy(mset, 0, modelFileNames, 0, j);
880 //    }
881
882     return chimmaps.keySet().toArray(
883             modelFileNames = new String[chimmaps.size()]);
884   }
885
886   /**
887    * map from string to applet
888    */
889   public Map getRegistryInfo()
890   {
891     // TODO Auto-generated method stub
892     return null;
893   }
894
895   /**
896    * returns the current sequenceRenderer that should be used to colour the
897    * structures
898    * 
899    * @param alignment
900    * 
901    * @return
902    */
903   public abstract SequenceRenderer getSequenceRenderer(
904           AlignmentViewPanel alignment);
905
906   // jmol/ssm only
907   public void highlightAtom(int atomIndex, int pdbResNum, String chain,
908           String pdbfile)
909   {
910     List<ChimeraModel> cms = chimmaps.get(pdbfile);
911     if (cms != null)
912     {
913       int mdlNum = cms.get(0).getModelNumber();
914
915       viewerCommandHistory(false);
916       viewer.stopListening();
917       if (resetLastRes.length() > 0)
918       {
919         viewer.sendChimeraCommand(resetLastRes.toString(), false);
920       }
921
922       eval.setLength(0);
923       eval.append("display "); // +modelNum
924
925       resetLastRes.setLength(0);
926       resetLastRes.append("~display ");
927       {
928         eval.append(" #" + (mdlNum));
929         resetLastRes.append("#" + (mdlNum));
930       }
931       // complete select string
932
933       eval.append(":" + pdbResNum);
934       resetLastRes.append(":" + pdbResNum);
935       if (!chain.equals(" "))
936       {
937         eval.append("." + chain);
938         resetLastRes.append("." + chain);
939       }
940       eval.append(eval.toString());
941
942       resetLastRes.append(resetLastRes.toString()
943               );
944
945       viewer.sendChimeraCommand(eval.toString(), false);
946       viewerCommandHistory(true);
947       viewer.startListening();
948     }
949   }
950
951   boolean debug = true;
952
953   private void log(String message)
954   {
955     System.err.println("## Chimera log: " + message);
956   }
957
958   private void viewerCommandHistory(boolean enable)
959   {
960     log("(Not yet implemented) History "
961             + ((debug || enable) ? "on" : "off"));
962   }
963
964   public void loadInline(String string)
965   {
966     loadedInline = true;
967     // TODO: re JAL-623
968     // viewer.loadInline(strModel, isAppend);
969     // could do this:
970     // construct fake fullPathName and fileName so we can identify the file
971     // later.
972     // Then, construct pass a reader for the string to Jmol.
973     // ((org.jmol.Viewer.Viewer) viewer).loadModelFromFile(fullPathName,
974     // fileName, null, reader, false, null, null, 0);
975     // viewer.openStringInline(string);
976     log("cannot load inline in Chimera, yet");
977   }
978
979   public void mouseOverStructure(int atomIndex, String strInfo)
980   {
981     // function to parse a mouseOver event from Chimera
982     //
983     int pdbResNum;
984     int alocsep = strInfo.indexOf("^");
985     int mdlSep = strInfo.indexOf("/");
986     int chainSeparator = strInfo.indexOf(":"), chainSeparator1 = -1;
987
988     if (chainSeparator == -1)
989     {
990       chainSeparator = strInfo.indexOf(".");
991       if (mdlSep > -1 && mdlSep < chainSeparator)
992       {
993         chainSeparator1 = chainSeparator;
994         chainSeparator = mdlSep;
995       }
996     }
997     // handle insertion codes
998     if (alocsep != -1)
999     {
1000       pdbResNum = Integer.parseInt(strInfo.substring(
1001               strInfo.indexOf("]") + 1, alocsep));
1002
1003     }
1004     else
1005     {
1006       pdbResNum = Integer.parseInt(strInfo.substring(
1007               strInfo.indexOf("]") + 1, chainSeparator));
1008     }
1009     String chainId;
1010
1011     if (strInfo.indexOf(":") > -1)
1012       chainId = strInfo.substring(strInfo.indexOf(":") + 1,
1013               strInfo.indexOf("."));
1014     else
1015     {
1016       chainId = " ";
1017     }
1018
1019     String pdbfilename = modelFileNames[frameNo]; // default is first or current
1020     // model
1021     if (mdlSep > -1)
1022     {
1023       if (chainSeparator1 == -1)
1024       {
1025         chainSeparator1 = strInfo.indexOf(".", mdlSep);
1026       }
1027       String mdlId = (chainSeparator1 > -1) ? strInfo.substring(mdlSep + 1,
1028               chainSeparator1) : strInfo.substring(mdlSep + 1);
1029       try
1030       {
1031         // recover PDB filename for the model hovered over.
1032         int _mp = _modelFileNameMap.length - 1, mnumber = new Integer(mdlId)
1033                 .intValue() - 1;
1034         while (mnumber < _modelFileNameMap[_mp])
1035         {
1036           _mp--;
1037         }
1038         pdbfilename = modelFileNames[_mp];
1039         if (pdbfilename == null)
1040         {
1041           // pdbfilename = new File(viewer.getModelFileName(mnumber))
1042           // .getAbsolutePath();
1043         }
1044
1045       } catch (Exception e)
1046       {
1047       }
1048       ;
1049     }
1050     if (lastMessage == null || !lastMessage.equals(strInfo))
1051       ssm.mouseOverStructure(pdbResNum, chainId, pdbfilename);
1052
1053     lastMessage = strInfo;
1054   }
1055
1056   public void notifyAtomPicked(int atomIndex, String strInfo, String strData)
1057   {
1058     /**
1059      * this implements the toggle label behaviour copied from the original
1060      * structure viewer, MCView
1061      */
1062     if (strData != null)
1063     {
1064       System.err.println("Ignoring additional pick data string " + strData);
1065     }
1066     // rewrite these selections for chimera (DNA, RNA and protein)
1067     int chainSeparator = strInfo.indexOf(":");
1068     int p = 0;
1069     if (chainSeparator == -1)
1070       chainSeparator = strInfo.indexOf(".");
1071
1072     String picked = strInfo.substring(strInfo.indexOf("]") + 1,
1073             chainSeparator);
1074     String mdlString = "";
1075     if ((p = strInfo.indexOf(":")) > -1)
1076       picked += strInfo.substring(p + 1, strInfo.indexOf("."));
1077
1078     if ((p = strInfo.indexOf("/")) > -1)
1079     {
1080       mdlString += strInfo.substring(p, strInfo.indexOf(" #"));
1081     }
1082     picked = "((" + picked + ".CA" + mdlString + ")|(" + picked + ".P"
1083             + mdlString + "))";
1084     viewerCommandHistory(false);
1085
1086     if (!atomsPicked.contains(picked))
1087     {
1088       viewer.select(picked);
1089       atomsPicked.addElement(picked);
1090     }
1091     else
1092     {
1093       viewer.select("not " + picked);
1094       atomsPicked.removeElement(picked);
1095     }
1096     viewerCommandHistory(true);
1097     // TODO: in application this happens
1098     //
1099     // if (scriptWindow != null)
1100     // {
1101     // scriptWindow.sendConsoleMessage(strInfo);
1102     // scriptWindow.sendConsoleMessage("\n");
1103     // }
1104
1105   }
1106
1107   // incremented every time a load notification is successfully handled -
1108   // lightweight mechanism for other threads to detect when they can start
1109   // referrring to new structures.
1110   private long loadNotifiesHandled = 0;
1111
1112   public long getLoadNotifiesHandled()
1113   {
1114     return loadNotifiesHandled;
1115   }
1116
1117   public void notifyFileLoaded(String fullPathName, String fileName2,
1118           String modelName, String errorMsg, int modelParts)
1119   {
1120     if (errorMsg != null)
1121     {
1122       fileLoadingError = errorMsg;
1123       refreshGUI();
1124       return;
1125     }
1126     // TODO: deal sensibly with models loaded inLine:
1127     // modelName will be null, as will fullPathName.
1128
1129     // the rest of this routine ignores the arguments, and simply interrogates
1130     // the Jmol view to find out what structures it contains, and adds them to
1131     // the structure selection manager.
1132     fileLoadingError = null;
1133     String[] oldmodels = modelFileNames;
1134     modelFileNames = null;
1135     chainNames = new Vector();
1136     chainFile = new Hashtable();
1137     boolean notifyLoaded = false;
1138     String[] modelfilenames = getPdbFile();
1139     // first check if we've lost any structures
1140     if (oldmodels != null && oldmodels.length > 0)
1141     {
1142       int oldm = 0;
1143       for (int i = 0; i < oldmodels.length; i++)
1144       {
1145         for (int n = 0; n < modelfilenames.length; n++)
1146         {
1147           if (modelfilenames[n] == oldmodels[i])
1148           {
1149             oldmodels[i] = null;
1150             break;
1151           }
1152         }
1153         if (oldmodels[i] != null)
1154         {
1155           oldm++;
1156         }
1157       }
1158       if (oldm > 0)
1159       {
1160         String[] oldmfn = new String[oldm];
1161         oldm = 0;
1162         for (int i = 0; i < oldmodels.length; i++)
1163         {
1164           if (oldmodels[i] != null)
1165           {
1166             oldmfn[oldm++] = oldmodels[i];
1167           }
1168         }
1169         // deregister the Jmol instance for these structures - we'll add
1170         // ourselves again at the end for the current structure set.
1171         ssm.removeStructureViewerListener(this, oldmfn);
1172       }
1173     }
1174
1175     // register ourselves as a listener and notify the gui that it needs to
1176     // update itself.
1177     ssm.addStructureViewerListener(this);
1178
1179     if (notifyLoaded)
1180     {
1181       FeatureRenderer fr = getFeatureRenderer(null);
1182       if (fr != null)
1183       {
1184         fr.featuresAdded();
1185       }
1186       refreshGUI();
1187       loadNotifiesHandled++;
1188     }
1189     setLoadingFromArchive(false);
1190   }
1191
1192   public void setJalviewColourScheme(ColourSchemeI cs)
1193   {
1194     colourBySequence = false;
1195
1196     if (cs == null)
1197       return;
1198
1199     String res;
1200     int index;
1201     Color col;
1202     viewerCommandHistory(false);
1203     // TODO: Switch between nucleotide or aa selection expressions
1204     Enumeration en = ResidueProperties.aa3Hash.keys();
1205     StringBuffer command = new StringBuffer("select *;color white;");
1206     while (en.hasMoreElements())
1207     {
1208       res = en.nextElement().toString();
1209       index = ((Integer) ResidueProperties.aa3Hash.get(res)).intValue();
1210       if (index > 20)
1211         continue;
1212
1213       col = cs.findColour(ResidueProperties.aa[index].charAt(0));
1214       // TODO: need colour string function and res selection here
1215       command.append("select " + res + ";color[" + col.getRed() + ","
1216               + col.getGreen() + "," + col.getBlue() + "];");
1217     }
1218
1219     evalStateCommand(command.toString());
1220     viewerCommandHistory(true);
1221   }
1222
1223   public void showHelp()
1224   {
1225     // chimera help
1226     showUrl("http://jmol.sourceforge.net/docs/JmolUserGuide/", "jmolHelp");
1227   }
1228
1229   /**
1230    * open the URL somehow
1231    * 
1232    * @param target
1233    */
1234   public abstract void showUrl(String url, String target);
1235
1236   /**
1237    * called when the binding thinks the UI needs to be refreshed after a Jmol
1238    * state change. this could be because structures were loaded, or because an
1239    * error has occured.
1240    */
1241   public abstract void refreshGUI();
1242
1243   public void componentResized(ComponentEvent e)
1244   {
1245
1246   }
1247
1248   public void componentMoved(ComponentEvent e)
1249   {
1250
1251   }
1252
1253   public void componentShown(ComponentEvent e)
1254   {
1255   }
1256
1257   public void componentHidden(ComponentEvent e)
1258   {
1259   }
1260
1261   public void setLoadingFromArchive(boolean loadingFromArchive)
1262   {
1263     this.loadingFromArchive = loadingFromArchive;
1264   }
1265
1266   /**
1267    * 
1268    * @return true if Jmol is still restoring state or loading is still going on
1269    *         (see setFinsihedLoadingFromArchive)
1270    */
1271   public boolean isLoadingFromArchive()
1272   {
1273     return loadingFromArchive && !loadingFinished;
1274   }
1275
1276   /**
1277    * modify flag which controls if sequence colouring events are honoured by the
1278    * binding. Should be true for normal operation
1279    * 
1280    * @param finishedLoading
1281    */
1282   public void setFinishedLoadingFromArchive(boolean finishedLoading)
1283   {
1284     loadingFinished = finishedLoading;
1285   }
1286
1287   public void setBackgroundColour(java.awt.Color col)
1288   {
1289     viewerCommandHistory(false);
1290     // todo set background colour
1291     viewer.sendChimeraCommand(
1292             "background [" + col.getRed() + "," + col.getGreen() + ","
1293                     + col.getBlue() + "];", false);
1294     viewerCommandHistory(true);
1295   }
1296
1297   /**
1298    * add structures and any known sequence associations
1299    * 
1300    * @returns the pdb entries added to the current set.
1301    */
1302   public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
1303           SequenceI[][] seq, String[][] chns)
1304   {
1305     int pe = -1;
1306     Vector v = new Vector();
1307     Vector rtn = new Vector();
1308     for (int i = 0; i < pdbentry.length; i++)
1309     {
1310       v.addElement(pdbentry[i]);
1311     }
1312     for (int i = 0; i < pdbe.length; i++)
1313     {
1314       int r = v.indexOf(pdbe[i]);
1315       if (r == -1 || r >= pdbentry.length)
1316       {
1317         rtn.addElement(new int[]
1318         { v.size(), i });
1319         v.addElement(pdbe[i]);
1320       }
1321       else
1322       {
1323         // just make sure the sequence/chain entries are all up to date
1324         addSequenceAndChain(r, seq[i], chns[i]);
1325       }
1326     }
1327     pdbe = new PDBEntry[v.size()];
1328     v.copyInto(pdbe);
1329     pdbentry = pdbe;
1330     if (rtn.size() > 0)
1331     {
1332       // expand the tied seuqence[] and string[] arrays
1333       SequenceI[][] sqs = new SequenceI[pdbentry.length][];
1334       String[][] sch = new String[pdbentry.length][];
1335       System.arraycopy(sequence, 0, sqs, 0, sequence.length);
1336       System.arraycopy(chains, 0, sch, 0, this.chains.length);
1337       sequence = sqs;
1338       chains = sch;
1339       pdbe = new PDBEntry[rtn.size()];
1340       for (int r = 0; r < pdbe.length; r++)
1341       {
1342         int[] stri = ((int[]) rtn.elementAt(r));
1343         // record the pdb file as a new addition
1344         pdbe[r] = pdbentry[stri[0]];
1345         // and add the new sequence/chain entries
1346         addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
1347       }
1348     }
1349     else
1350     {
1351       pdbe = null;
1352     }
1353     return pdbe;
1354   }
1355
1356   public void addSequence(int pe, SequenceI[] seq)
1357   {
1358     // add sequences to the pe'th pdbentry's seuqence set.
1359     addSequenceAndChain(pe, seq, null);
1360   }
1361
1362   private void addSequenceAndChain(int pe, SequenceI[] seq, String[] tchain)
1363   {
1364     if (pe < 0 || pe >= pdbentry.length)
1365     {
1366       throw new Error(
1367               "Implementation error - no corresponding pdbentry (for index "
1368                       + pe + ") to add sequences mappings to");
1369     }
1370     final String nullChain = "TheNullChain";
1371     Vector s = new Vector();
1372     Vector c = new Vector();
1373     if (chains == null)
1374     {
1375       chains = new String[pdbentry.length][];
1376     }
1377     if (sequence[pe] != null)
1378     {
1379       for (int i = 0; i < sequence[pe].length; i++)
1380       {
1381         s.addElement(sequence[pe][i]);
1382         if (chains[pe] != null)
1383         {
1384           if (i < chains[pe].length)
1385           {
1386             c.addElement(chains[pe][i]);
1387           }
1388           else
1389           {
1390             c.addElement(nullChain);
1391           }
1392         }
1393         else
1394         {
1395           if (tchain != null && tchain.length > 0)
1396           {
1397             c.addElement(nullChain);
1398           }
1399         }
1400       }
1401     }
1402     for (int i = 0; i < seq.length; i++)
1403     {
1404       if (!s.contains(seq[i]))
1405       {
1406         s.addElement(seq[i]);
1407         if (tchain != null && i < tchain.length)
1408         {
1409           c.addElement(tchain[i] == null ? nullChain : tchain[i]);
1410         }
1411       }
1412     }
1413     SequenceI[] tmp = new SequenceI[s.size()];
1414     s.copyInto(tmp);
1415     sequence[pe] = tmp;
1416     if (c.size() > 0)
1417     {
1418       String[] tch = new String[c.size()];
1419       c.copyInto(tch);
1420       for (int i = 0; i < tch.length; i++)
1421       {
1422         if (tch[i] == nullChain)
1423         {
1424           tch[i] = null;
1425         }
1426       }
1427       chains[pe] = tch;
1428     }
1429     else
1430     {
1431       chains[pe] = null;
1432     }
1433   }
1434
1435   /**
1436    * 
1437    * @param pdbfile
1438    * @return text report of alignment between pdbfile and any associated
1439    *         alignment sequences
1440    */
1441   public String printMapping(String pdbfile)
1442   {
1443     return ssm.printMapping(pdbfile);
1444   }
1445
1446 }