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