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