7c3d1924023a656927e0f8f9541e6bb8ddff8d0b
[jalview.git] / src / jalview / ext / jmol / JalviewJmolBinding.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ 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.jmol;
22
23 import jalview.api.AlignmentViewPanel;
24 import jalview.api.FeatureRenderer;
25 import jalview.api.SequenceRenderer;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.ColumnSelection;
28 import jalview.datamodel.PDBEntry;
29 import jalview.datamodel.SequenceI;
30 import jalview.io.AppletFormatAdapter;
31 import jalview.schemes.ColourSchemeI;
32 import jalview.schemes.ResidueProperties;
33 import jalview.structure.AtomSpec;
34 import jalview.structure.StructureMappingcommandSet;
35 import jalview.structure.StructureSelectionManager;
36 import jalview.structures.models.AAStructureBindingModel;
37
38 import java.awt.Color;
39 import java.awt.Container;
40 import java.awt.event.ComponentEvent;
41 import java.awt.event.ComponentListener;
42 import java.io.File;
43 import java.net.URL;
44 import java.security.AccessControlException;
45 import java.util.Hashtable;
46 import java.util.List;
47 import java.util.Map;
48 import java.util.Vector;
49
50 import javajs.awt.Dimension;
51
52 import org.jmol.adapter.smarter.SmarterJmolAdapter;
53 import org.jmol.api.JmolAppConsoleInterface;
54 import org.jmol.api.JmolSelectionListener;
55 import org.jmol.api.JmolStatusListener;
56 import org.jmol.api.JmolViewer;
57 import org.jmol.c.CBK;
58 import org.jmol.script.T;
59 import org.jmol.viewer.JC;
60 import org.jmol.viewer.Viewer;
61
62 public abstract class JalviewJmolBinding extends AAStructureBindingModel
63         implements JmolStatusListener, JmolSelectionListener,
64         ComponentListener
65 {
66   boolean allChainsSelected = false;
67
68   /*
69    * when true, try to search the associated datamodel for sequences that are
70    * associated with any unknown structures in the Jmol view.
71    */
72   private boolean associateNewStructs = false;
73
74   Vector<String> atomsPicked = new Vector<String>();
75
76   public Vector<String> chainNames;
77
78   Hashtable<String, String> chainFile;
79
80   public String fileLoadingError;
81
82   /*
83    * the default or current model displayed if the model cannot be identified
84    * from the selection message
85    */
86   int frameNo = 0;
87
88   // protected JmolGenericPopup jmolpopup; // not used - remove?
89
90   String lastCommand;
91
92   String lastMessage;
93
94   boolean loadedInline;
95
96   /**
97    * current set of model filenames loaded in the Jmol instance
98    */
99   String[] modelFileNames = null;
100
101   StringBuffer resetLastRes = new StringBuffer();
102
103   public Viewer viewer;
104
105   public JalviewJmolBinding(StructureSelectionManager ssm,
106           PDBEntry[] pdbentry, SequenceI[][] sequenceIs, String[][] chains,
107           String protocol)
108   {
109     super(ssm, pdbentry, sequenceIs, chains, protocol);
110     /*
111      * viewer = JmolViewer.allocateViewer(renderPanel, new SmarterJmolAdapter(),
112      * "jalviewJmol", ap.av.applet .getDocumentBase(),
113      * ap.av.applet.getCodeBase(), "", this);
114      * 
115      * jmolpopup = JmolPopup.newJmolPopup(viewer, true, "Jmol", true);
116      */
117   }
118
119   public JalviewJmolBinding(StructureSelectionManager ssm,
120           SequenceI[][] seqs, Viewer theViewer)
121   {
122     super(ssm, seqs);
123
124     viewer = theViewer;
125     viewer.setJmolStatusListener(this);
126     viewer.addSelectionListener(this);
127   }
128
129   /**
130    * construct a title string for the viewer window based on the data jalview
131    * knows about
132    * 
133    * @return
134    */
135   public String getViewerTitle()
136   {
137     return getViewerTitle("Jmol", true);
138   }
139
140   /**
141    * prepare the view for a given set of models/chains. chainList contains
142    * strings of the form 'pdbfilename:Chaincode'
143    * 
144    * @param chainList
145    *          list of chains to make visible
146    */
147   public void centerViewer(Vector<String> chainList)
148   {
149     StringBuilder cmd = new StringBuilder(128);
150     int mlength, p;
151     for (String lbl : chainList)
152     {
153       mlength = 0;
154       do
155       {
156         p = mlength;
157         mlength = lbl.indexOf(":", p);
158       } while (p < mlength && mlength < (lbl.length() - 2));
159       // TODO: lookup each pdb id and recover proper model number for it.
160       cmd.append(":" + lbl.substring(mlength + 1) + " /"
161               + (1 + getModelNum(chainFile.get(lbl))) + " or ");
162     }
163     if (cmd.length() > 0)
164     {
165       cmd.setLength(cmd.length() - 4);
166     }
167     evalStateCommand("select *;restrict " + cmd + ";cartoon;center " + cmd);
168   }
169
170   public void closeViewer()
171   {
172     viewer.acm.setModeMouse(JC.MOUSE_NONE);
173     // remove listeners for all structures in viewer
174     getSsm().removeStructureViewerListener(this, this.getPdbFile());
175     // and shut down jmol
176     viewer.evalStringQuiet("zap");
177     viewer.setJmolStatusListener(null);
178     lastCommand = null;
179     viewer = null;
180     releaseUIResources();
181   }
182
183   public void colourByChain()
184   {
185     colourBySequence = false;
186     // TODO: colour by chain should colour each chain distinctly across all
187     // visible models
188     // TODO: http://issues.jalview.org/browse/JAL-628
189     evalStateCommand("select *;color chain");
190   }
191
192   public void colourByCharge()
193   {
194     colourBySequence = false;
195     evalStateCommand("select *;color white;select ASP,GLU;color red;"
196             + "select LYS,ARG;color blue;select CYS;color yellow");
197   }
198
199   /**
200    * superpose the structures associated with sequences in the alignment
201    * according to their corresponding positions.
202    */
203   public void superposeStructures(AlignmentI alignment)
204   {
205     superposeStructures(alignment, -1, null);
206   }
207
208   /**
209    * superpose the structures associated with sequences in the alignment
210    * according to their corresponding positions. ded)
211    * 
212    * @param refStructure
213    *          - select which pdb file to use as reference (default is -1 - the
214    *          first structure in the alignment)
215    */
216   public void superposeStructures(AlignmentI alignment, int refStructure)
217   {
218     superposeStructures(alignment, refStructure, null);
219   }
220
221   /**
222    * superpose the structures associated with sequences in the alignment
223    * according to their corresponding positions. ded)
224    * 
225    * @param refStructure
226    *          - select which pdb file to use as reference (default is -1 - the
227    *          first structure in the alignment)
228    * @param hiddenCols
229    *          TODO
230    */
231   public void superposeStructures(AlignmentI alignment, int refStructure,
232           ColumnSelection hiddenCols)
233   {
234     superposeStructures(new AlignmentI[] { alignment },
235             new int[] { refStructure },
236             new ColumnSelection[] { hiddenCols });
237   }
238
239   /**
240    * Construct and send a command to align structures against a reference
241    * structure, based on one or more sequence alignments
242    * 
243    * @param _alignment
244    *          an array of alignments to process
245    * @param _refStructure
246    *          an array of corresponding reference structures (index into pdb
247    *          file array); if a negative value is passed, the first PDB file
248    *          mapped to an alignment sequence is used as the reference for
249    *          superposition
250    * @param _hiddenCols
251    *          an array of corresponding hidden columns for each alignment
252    */
253   public void superposeStructures(AlignmentI[] _alignment,
254           int[] _refStructure, ColumnSelection[] _hiddenCols)
255   {
256     while (viewer.isScriptExecuting())
257     {
258       try
259       {
260         Thread.sleep(10);
261       } catch (InterruptedException i)
262       {
263       }
264       ;
265     }
266     String[] files = getPdbFile();
267     if (!waitForFileLoad(files))
268     {
269       return;
270     }
271
272     StringBuilder selectioncom = new StringBuilder(256);
273     // In principle - nSeconds specifies the speed of animation for each
274     // superposition - but is seems to behave weirdly, so we don't specify it.
275     String nSeconds = " ";
276     if (files.length > 10)
277     {
278       nSeconds = " 0.005 ";
279     }
280     else
281     {
282       nSeconds = " " + (2.0 / files.length) + " ";
283       // if (nSeconds).substring(0,5)+" ";
284     }
285     // see JAL-1345 - should really automatically turn off the animation for
286     // large numbers of structures, but Jmol doesn't seem to allow that.
287     // nSeconds = " ";
288     // union of all aligned positions are collected together.
289     for (int a = 0; a < _alignment.length; a++)
290     {
291       int refStructure = _refStructure[a];
292       AlignmentI alignment = _alignment[a];
293       ColumnSelection hiddenCols = _hiddenCols[a];
294       if (a > 0
295               && selectioncom.length() > 0
296               && !selectioncom.substring(selectioncom.length() - 1).equals(
297                       "|"))
298       {
299         selectioncom.append("|");
300       }
301       // process this alignment
302       if (refStructure >= files.length)
303       {
304         System.err.println("Invalid reference structure value "
305                 + refStructure);
306         refStructure = -1;
307       }
308
309       /*
310        * 'matched' array will hold 'true' for visible alignment columns where
311        * all sequences have a residue with a mapping to the PDB structure
312        */
313       boolean matched[] = new boolean[alignment.getWidth()];
314       for (int m = 0; m < matched.length; m++)
315       {
316         matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
317       }
318
319       SuperposeData[] structures = new SuperposeData[files.length];
320       for (int f = 0; f < files.length; f++)
321       {
322         structures[f] = new SuperposeData(alignment.getWidth());
323       }
324
325       /*
326        * Calculate the superposable alignment columns ('matched'), and the
327        * corresponding structure residue positions (structures.pdbResNo)
328        */
329       int candidateRefStructure = findSuperposableResidues(alignment,
330               matched, structures);
331       if (refStructure < 0)
332       {
333         /*
334          * If no reference structure was specified, pick the first one that has
335          * a mapping in the alignment
336          */
337         refStructure = candidateRefStructure;
338       }
339
340       String[] selcom = new String[files.length];
341       int nmatched = 0;
342       for (boolean b : matched)
343       {
344         if (b)
345         {
346           nmatched++;
347         }
348       }
349       if (nmatched < 4)
350       {
351         // TODO: bail out here because superposition illdefined?
352       }
353
354       /*
355        * generate select statements to select regions to superimpose structures
356        */
357       {
358         for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
359         {
360           String chainCd = ":" + structures[pdbfnum].chain;
361           int lpos = -1;
362           boolean run = false;
363           StringBuilder molsel = new StringBuilder();
364           molsel.append("{");
365           for (int r = 0; r < matched.length; r++)
366           {
367             if (matched[r])
368             {
369               int pdbResNo = structures[pdbfnum].pdbResNo[r];
370               if (lpos != pdbResNo - 1)
371               {
372                 // discontinuity
373                 if (lpos != -1)
374                 {
375                   molsel.append(lpos);
376                   molsel.append(chainCd);
377                   molsel.append("|");
378                 }
379                 run = false;
380               }
381               else
382               {
383                 // continuous run - and lpos >-1
384                 if (!run)
385                 {
386                   // at the beginning, so add dash
387                   molsel.append(lpos);
388                   molsel.append("-");
389                 }
390                 run = true;
391               }
392               lpos = pdbResNo;
393             }
394           }
395           /*
396            * add final selection phrase
397            */
398           if (lpos != -1)
399           {
400             molsel.append(lpos);
401             molsel.append(chainCd);
402             molsel.append("}");
403           }
404           if (molsel.length() > 1)
405           {
406             selcom[pdbfnum] = molsel.toString();
407             selectioncom.append("((");
408             selectioncom.append(selcom[pdbfnum].substring(1,
409                     selcom[pdbfnum].length() - 1));
410             selectioncom.append(" )& ");
411             selectioncom.append(pdbfnum + 1);
412             selectioncom.append(".1)");
413             if (pdbfnum < files.length - 1)
414             {
415               selectioncom.append("|");
416             }
417           }
418           else
419           {
420             selcom[pdbfnum] = null;
421           }
422         }
423       }
424       StringBuilder command = new StringBuilder(256);
425       for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
426       {
427         if (pdbfnum == refStructure || selcom[pdbfnum] == null
428                 || selcom[refStructure] == null)
429         {
430           continue;
431         }
432         command.append("echo ");
433         command.append("\"Superposing (");
434         command.append(structures[pdbfnum].pdbId);
435         command.append(") against reference (");
436         command.append(structures[refStructure].pdbId);
437         command.append(")\";\ncompare " + nSeconds);
438         command.append("{");
439         command.append(Integer.toString(1 + pdbfnum));
440         command.append(".1} {");
441         command.append(Integer.toString(1 + refStructure));
442         // conformation=1 excludes alternate locations for CA (JAL-1757)
443         command.append(".1} SUBSET {(*.CA | *.P) and conformation=1} ATOMS ");
444
445         // for (int s = 0; s < 2; s++)
446         // {
447         // command.append(selcom[(s == 0 ? pdbfnum : refStructure)]);
448         // }
449         command.append(selcom[pdbfnum]);
450         command.append(selcom[refStructure]);
451         command.append(" ROTATE TRANSLATE;\n");
452       }
453       if (selectioncom.length() > 0)
454       {
455         System.out.println("Select regions:\n" + selectioncom.toString());
456         evalStateCommand("select *; cartoons off; backbone; select ("
457                 + selectioncom.toString() + "); cartoons; ");
458         // selcom.append("; ribbons; ");
459         String cmdString = command.toString();
460         System.out.println("Superimpose command(s):\n" + cmdString);
461
462         evalStateCommand(cmdString);
463       }
464     }
465     if (selectioncom.length() > 0)
466     {// finally, mark all regions that were superposed.
467       if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
468       {
469         selectioncom.setLength(selectioncom.length() - 1);
470       }
471       System.out.println("Select regions:\n" + selectioncom.toString());
472       evalStateCommand("select *; cartoons off; backbone; select ("
473               + selectioncom.toString() + "); cartoons; ");
474       // evalStateCommand("select *; backbone; select "+selcom.toString()+"; cartoons; center "+selcom.toString());
475     }
476   }
477
478   public void evalStateCommand(String command)
479   {
480     jmolHistory(false);
481     if (lastCommand == null || !lastCommand.equals(command))
482     {
483       viewer.evalStringQuiet(command + "\n");
484     }
485     jmolHistory(true);
486     lastCommand = command;
487   }
488
489   /**
490    * colour any structures associated with sequences in the given alignment
491    * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
492    * if colourBySequence is enabled.
493    */
494   public void colourBySequence(AlignmentViewPanel alignmentv)
495   {
496     boolean showFeatures = alignmentv.getAlignViewport()
497             .isShowSequenceFeatures();
498     if (!colourBySequence || !isLoadingFinished())
499     {
500       return;
501     }
502     if (getSsm() == null)
503     {
504       return;
505     }
506     String[] files = getPdbFile();
507
508     SequenceRenderer sr = getSequenceRenderer(alignmentv);
509
510     FeatureRenderer fr = null;
511     if (showFeatures)
512     {
513       fr = getFeatureRenderer(alignmentv);
514     }
515     AlignmentI alignment = alignmentv.getAlignment();
516
517     for (jalview.structure.StructureMappingcommandSet cpdbbyseq : getColourBySequenceCommands(
518             files, sr, fr, alignment))
519     {
520       for (String cbyseq : cpdbbyseq.commands)
521       {
522         executeWhenReady(cbyseq);
523       }
524     }
525   }
526
527   /**
528    * @param files
529    * @param sr
530    * @param fr
531    * @param alignment
532    * @return
533    */
534   protected StructureMappingcommandSet[] getColourBySequenceCommands(
535           String[] files, SequenceRenderer sr, FeatureRenderer fr,
536           AlignmentI alignment)
537   {
538     return JmolCommands.getColourBySequenceCommand(getSsm(), files,
539             getSequence(), sr, fr, alignment);
540   }
541
542   /**
543    * @param command
544    */
545   protected void executeWhenReady(String command)
546   {
547     evalStateCommand(command);
548   }
549
550   public void createImage(String file, String type, int quality)
551   {
552     System.out.println("JMOL CREATE IMAGE");
553   }
554
555   @Override
556   public String createImage(String fileName, String type,
557           Object textOrBytes, int quality)
558   {
559     System.out.println("JMOL CREATE IMAGE");
560     return null;
561   }
562
563   @Override
564   public String eval(String strEval)
565   {
566     // System.out.println(strEval);
567     // "# 'eval' is implemented only for the applet.";
568     return null;
569   }
570
571   // End StructureListener
572   // //////////////////////////
573
574   @Override
575   public float[][] functionXY(String functionName, int x, int y)
576   {
577     return null;
578   }
579
580   @Override
581   public float[][][] functionXYZ(String functionName, int nx, int ny, int nz)
582   {
583     // TODO Auto-generated method stub
584     return null;
585   }
586
587   public Color getColour(int atomIndex, int pdbResNum, String chain,
588           String pdbfile)
589   {
590     if (getModelNum(pdbfile) < 0)
591     {
592       return null;
593     }
594     // TODO: verify atomIndex is selecting correct model.
595     // return new Color(viewer.getAtomArgb(atomIndex)); Jmol 12.2.4
596     int colour = viewer.ms.at[atomIndex].atomPropertyInt(T.color);
597     return new Color(colour);
598   }
599
600   /**
601    * returns the current featureRenderer that should be used to colour the
602    * structures
603    * 
604    * @param alignment
605    * 
606    * @return
607    */
608   public abstract FeatureRenderer getFeatureRenderer(
609           AlignmentViewPanel alignment);
610
611   /**
612    * instruct the Jalview binding to update the pdbentries vector if necessary
613    * prior to matching the jmol view's contents to the list of structure files
614    * Jalview knows about.
615    */
616   public abstract void refreshPdbEntries();
617
618   private int getModelNum(String modelFileName)
619   {
620     String[] mfn = getPdbFile();
621     if (mfn == null)
622     {
623       return -1;
624     }
625     for (int i = 0; i < mfn.length; i++)
626     {
627       if (mfn[i].equalsIgnoreCase(modelFileName))
628       {
629         return i;
630       }
631     }
632     return -1;
633   }
634
635   /**
636    * map between index of model filename returned from getPdbFile and the first
637    * index of models from this file in the viewer. Note - this is not trimmed -
638    * use getPdbFile to get number of unique models.
639    */
640   private int _modelFileNameMap[];
641
642   // ////////////////////////////////
643   // /StructureListener
644   @Override
645   public synchronized String[] getPdbFile()
646   {
647     if (viewer == null)
648     {
649       return new String[0];
650     }
651     if (modelFileNames == null)
652     {
653       String mset[] = new String[viewer.ms.mc];
654       _modelFileNameMap = new int[mset.length];
655       String m = viewer.ms.getModelFileName(0);
656       if (m != null)
657       {
658         mset[0] = m;
659         try
660         {
661           mset[0] = new File(m).getAbsolutePath();
662         } catch (AccessControlException x)
663         {
664           // usually not allowed to do this in applet
665           System.err
666                   .println("jmolBinding: Using local file string from Jmol: "
667                           + m);
668         }
669         if (mset[0].indexOf("/file:") != -1)
670         {
671           // applet path with docroot - discard as format won't match pdbfile
672           mset[0] = m;
673         }
674         _modelFileNameMap[0] = 0; // filename index for first model is always 0.
675       }
676       int j = 1;
677       for (int i = 1; i < mset.length; i++)
678       {
679         m = viewer.ms.getModelFileName(i);
680         mset[j] = m;
681         if (m != null)
682         {
683           try
684           {
685             mset[j] = new File(m).getAbsolutePath();
686           } catch (AccessControlException x)
687           {
688             // usually not allowed to do this in applet, so keep raw handle
689             // System.err.println("jmolBinding: Using local file string from Jmol: "+m);
690           }
691         }
692         _modelFileNameMap[j] = i; // record the model index for the filename
693         // skip any additional models in the same file (NMR structures)
694         if ((mset[j] == null ? mset[j] != mset[j - 1]
695                 : (mset[j - 1] == null || !mset[j].equals(mset[j - 1]))))
696         {
697           j++;
698         }
699       }
700       modelFileNames = new String[j];
701       System.arraycopy(mset, 0, modelFileNames, 0, j);
702     }
703     return modelFileNames;
704   }
705
706   /**
707    * map from string to applet
708    */
709   @Override
710   public Map<String, Object> getRegistryInfo()
711   {
712     // TODO Auto-generated method stub
713     return null;
714   }
715
716   /**
717    * returns the current sequenceRenderer that should be used to colour the
718    * structures
719    * 
720    * @param alignment
721    * 
722    * @return
723    */
724   public abstract SequenceRenderer getSequenceRenderer(
725           AlignmentViewPanel alignment);
726
727   // ///////////////////////////////
728   // JmolStatusListener
729
730   public void handlePopupMenu(int x, int y)
731   {
732     // jmolpopup.show(x, y);
733     // jmolpopup.jpiShow(x, y);
734   }
735
736   /**
737    * Highlight zero, one or more atoms on the structure
738    */
739   @Override
740   public void highlightAtoms(List<AtomSpec> atoms)
741   {
742     if (atoms != null)
743     {
744       if (resetLastRes.length() > 0)
745       {
746         viewer.evalStringQuiet(resetLastRes.toString());
747         resetLastRes.setLength(0);
748       }
749       for (AtomSpec atom : atoms)
750       {
751         highlightAtom(atom.getAtomIndex(), atom.getPdbResNum(),
752                 atom.getChain(), atom.getPdbFile());
753       }
754     }
755   }
756
757   // jmol/ssm only
758   public void highlightAtom(int atomIndex, int pdbResNum, String chain,
759           String pdbfile)
760   {
761     if (modelFileNames == null)
762     {
763       return;
764     }
765
766     // look up file model number for this pdbfile
767     int mdlNum = 0;
768     // may need to adjust for URLencoding here - we don't worry about that yet.
769     while (mdlNum < modelFileNames.length
770             && !pdbfile.equals(modelFileNames[mdlNum]))
771     {
772       mdlNum++;
773     }
774     if (mdlNum == modelFileNames.length)
775     {
776       return;
777     }
778
779     jmolHistory(false);
780
781     StringBuilder cmd = new StringBuilder(64);
782     cmd.append("select " + pdbResNum); // +modelNum
783
784     resetLastRes.append("select " + pdbResNum); // +modelNum
785
786     cmd.append(":");
787     resetLastRes.append(":");
788     if (!chain.equals(" "))
789     {
790       cmd.append(chain);
791       resetLastRes.append(chain);
792     }
793     {
794       cmd.append(" /" + (mdlNum + 1));
795       resetLastRes.append("/" + (mdlNum + 1));
796     }
797     cmd.append(";wireframe 100;" + cmd.toString() + " and not hetero;");
798
799     resetLastRes.append(";wireframe 0;" + resetLastRes.toString()
800             + " and not hetero; spacefill 0;");
801
802     cmd.append("spacefill 200;select none");
803
804     viewer.evalStringQuiet(cmd.toString());
805     jmolHistory(true);
806
807   }
808
809   boolean debug = true;
810
811   private void jmolHistory(boolean enable)
812   {
813     viewer.evalStringQuiet("History " + ((debug || enable) ? "on" : "off"));
814   }
815
816   public void loadInline(String string)
817   {
818     loadedInline = true;
819     // TODO: re JAL-623
820     // viewer.loadInline(strModel, isAppend);
821     // could do this:
822     // construct fake fullPathName and fileName so we can identify the file
823     // later.
824     // Then, construct pass a reader for the string to Jmol.
825     // ((org.jmol.Viewer.Viewer) viewer).loadModelFromFile(fullPathName,
826     // fileName, null, reader, false, null, null, 0);
827     viewer.openStringInline(string);
828   }
829
830   public void mouseOverStructure(int atomIndex, String strInfo)
831   {
832     int pdbResNum;
833     int alocsep = strInfo.indexOf("^");
834     int mdlSep = strInfo.indexOf("/");
835     int chainSeparator = strInfo.indexOf(":"), chainSeparator1 = -1;
836
837     if (chainSeparator == -1)
838     {
839       chainSeparator = strInfo.indexOf(".");
840       if (mdlSep > -1 && mdlSep < chainSeparator)
841       {
842         chainSeparator1 = chainSeparator;
843         chainSeparator = mdlSep;
844       }
845     }
846     // handle insertion codes
847     if (alocsep != -1)
848     {
849       pdbResNum = Integer.parseInt(strInfo.substring(
850               strInfo.indexOf("]") + 1, alocsep));
851
852     }
853     else
854     {
855       pdbResNum = Integer.parseInt(strInfo.substring(
856               strInfo.indexOf("]") + 1, chainSeparator));
857     }
858     String chainId;
859
860     if (strInfo.indexOf(":") > -1)
861     {
862       chainId = strInfo.substring(strInfo.indexOf(":") + 1,
863               strInfo.indexOf("."));
864     }
865     else
866     {
867       chainId = " ";
868     }
869
870     String pdbfilename = modelFileNames[frameNo]; // default is first or current
871     // model
872     if (mdlSep > -1)
873     {
874       if (chainSeparator1 == -1)
875       {
876         chainSeparator1 = strInfo.indexOf(".", mdlSep);
877       }
878       String mdlId = (chainSeparator1 > -1) ? strInfo.substring(mdlSep + 1,
879               chainSeparator1) : strInfo.substring(mdlSep + 1);
880       try
881       {
882         // recover PDB filename for the model hovered over.
883         int _mp = _modelFileNameMap.length - 1, mnumber = new Integer(mdlId)
884                 .intValue() - 1;
885         while (mnumber < _modelFileNameMap[_mp])
886         {
887           _mp--;
888         }
889         pdbfilename = modelFileNames[_mp];
890         if (pdbfilename == null)
891         {
892           pdbfilename = new File(viewer.ms.getModelFileName(mnumber))
893                   .getAbsolutePath();
894         }
895
896       } catch (Exception e)
897       {
898       }
899       ;
900     }
901     if (lastMessage == null || !lastMessage.equals(strInfo))
902     {
903       getSsm().mouseOverStructure(pdbResNum, chainId, pdbfilename);
904     }
905
906     lastMessage = strInfo;
907   }
908
909   public void notifyAtomHovered(int atomIndex, String strInfo, String data)
910   {
911     if (data != null)
912     {
913       System.err.println("Ignoring additional hover info: " + data
914               + " (other info: '" + strInfo + "' pos " + atomIndex + ")");
915     }
916     mouseOverStructure(atomIndex, strInfo);
917   }
918
919   /*
920    * { if (history != null && strStatus != null &&
921    * !strStatus.equals("Script completed")) { history.append("\n" + strStatus);
922    * } }
923    */
924
925   public void notifyAtomPicked(int atomIndex, String strInfo, String strData)
926   {
927     /**
928      * this implements the toggle label behaviour copied from the original
929      * structure viewer, MCView
930      */
931     if (strData != null)
932     {
933       System.err.println("Ignoring additional pick data string " + strData);
934     }
935     int chainSeparator = strInfo.indexOf(":");
936     int p = 0;
937     if (chainSeparator == -1)
938     {
939       chainSeparator = strInfo.indexOf(".");
940     }
941
942     String picked = strInfo.substring(strInfo.indexOf("]") + 1,
943             chainSeparator);
944     String mdlString = "";
945     if ((p = strInfo.indexOf(":")) > -1)
946     {
947       picked += strInfo.substring(p, strInfo.indexOf("."));
948     }
949
950     if ((p = strInfo.indexOf("/")) > -1)
951     {
952       mdlString += strInfo.substring(p, strInfo.indexOf(" #"));
953     }
954     picked = "((" + picked + ".CA" + mdlString + ")|(" + picked + ".P"
955             + mdlString + "))";
956     jmolHistory(false);
957
958     if (!atomsPicked.contains(picked))
959     {
960       viewer.evalStringQuiet("select " + picked + ";label %n %r:%c");
961       atomsPicked.addElement(picked);
962     }
963     else
964     {
965       viewer.evalString("select " + picked + ";label off");
966       atomsPicked.removeElement(picked);
967     }
968     jmolHistory(true);
969     // TODO: in application this happens
970     //
971     // if (scriptWindow != null)
972     // {
973     // scriptWindow.sendConsoleMessage(strInfo);
974     // scriptWindow.sendConsoleMessage("\n");
975     // }
976
977   }
978
979   @Override
980   public void notifyCallback(CBK type, Object[] data)
981   {
982     try
983     {
984       switch (type)
985       {
986       case LOADSTRUCT:
987         notifyFileLoaded((String) data[1], (String) data[2],
988                 (String) data[3], (String) data[4],
989                 ((Integer) data[5]).intValue());
990
991         break;
992       case PICK:
993         notifyAtomPicked(((Integer) data[2]).intValue(), (String) data[1],
994                 (String) data[0]);
995         // also highlight in alignment
996       case HOVER:
997         notifyAtomHovered(((Integer) data[2]).intValue(), (String) data[1],
998                 (String) data[0]);
999         break;
1000       case SCRIPT:
1001         notifyScriptTermination((String) data[2],
1002                 ((Integer) data[3]).intValue());
1003         break;
1004       case ECHO:
1005         sendConsoleEcho((String) data[1]);
1006         break;
1007       case MESSAGE:
1008         sendConsoleMessage((data == null) ? ((String) null)
1009                 : (String) data[1]);
1010         break;
1011       case ERROR:
1012         // System.err.println("Ignoring error callback.");
1013         break;
1014       case SYNC:
1015       case RESIZE:
1016         refreshGUI();
1017         break;
1018       case MEASURE:
1019
1020       case CLICK:
1021       default:
1022         System.err.println("Unhandled callback " + type + " "
1023                 + data[1].toString());
1024         break;
1025       }
1026     } catch (Exception e)
1027     {
1028       System.err.println("Squashed Jmol callback handler error:");
1029       e.printStackTrace();
1030     }
1031   }
1032
1033   @Override
1034   public boolean notifyEnabled(CBK callbackPick)
1035   {
1036     switch (callbackPick)
1037     {
1038     case ECHO:
1039     case LOADSTRUCT:
1040     case MEASURE:
1041     case MESSAGE:
1042     case PICK:
1043     case SCRIPT:
1044     case HOVER:
1045     case ERROR:
1046       return true;
1047     default:
1048       return false;
1049     }
1050   }
1051
1052   // incremented every time a load notification is successfully handled -
1053   // lightweight mechanism for other threads to detect when they can start
1054   // referrring to new structures.
1055   private long loadNotifiesHandled = 0;
1056
1057   public long getLoadNotifiesHandled()
1058   {
1059     return loadNotifiesHandled;
1060   }
1061
1062   public void notifyFileLoaded(String fullPathName, String fileName2,
1063           String modelName, String errorMsg, int modelParts)
1064   {
1065     if (errorMsg != null)
1066     {
1067       fileLoadingError = errorMsg;
1068       refreshGUI();
1069       return;
1070     }
1071     // TODO: deal sensibly with models loaded inLine:
1072     // modelName will be null, as will fullPathName.
1073
1074     // the rest of this routine ignores the arguments, and simply interrogates
1075     // the Jmol view to find out what structures it contains, and adds them to
1076     // the structure selection manager.
1077     fileLoadingError = null;
1078     String[] oldmodels = modelFileNames;
1079     modelFileNames = null;
1080     chainNames = new Vector<String>();
1081     chainFile = new Hashtable<String, String>();
1082     boolean notifyLoaded = false;
1083     String[] modelfilenames = getPdbFile();
1084     // first check if we've lost any structures
1085     if (oldmodels != null && oldmodels.length > 0)
1086     {
1087       int oldm = 0;
1088       for (int i = 0; i < oldmodels.length; i++)
1089       {
1090         for (int n = 0; n < modelfilenames.length; n++)
1091         {
1092           if (modelfilenames[n] == oldmodels[i])
1093           {
1094             oldmodels[i] = null;
1095             break;
1096           }
1097         }
1098         if (oldmodels[i] != null)
1099         {
1100           oldm++;
1101         }
1102       }
1103       if (oldm > 0)
1104       {
1105         String[] oldmfn = new String[oldm];
1106         oldm = 0;
1107         for (int i = 0; i < oldmodels.length; i++)
1108         {
1109           if (oldmodels[i] != null)
1110           {
1111             oldmfn[oldm++] = oldmodels[i];
1112           }
1113         }
1114         // deregister the Jmol instance for these structures - we'll add
1115         // ourselves again at the end for the current structure set.
1116         getSsm().removeStructureViewerListener(this, oldmfn);
1117       }
1118     }
1119     refreshPdbEntries();
1120     for (int modelnum = 0; modelnum < modelfilenames.length; modelnum++)
1121     {
1122       String fileName = modelfilenames[modelnum];
1123       boolean foundEntry = false;
1124       MCview.PDBfile pdb = null;
1125       String pdbfile = null;
1126       // model was probably loaded inline - so check the pdb file hashcode
1127       if (loadedInline)
1128       {
1129         // calculate essential attributes for the pdb data imported inline.
1130         // prolly need to resolve modelnumber properly - for now just use our
1131         // 'best guess'
1132         pdbfile = viewer.getData("" + (1 + _modelFileNameMap[modelnum])
1133                 + ".0", "PDB");
1134       }
1135       // search pdbentries and sequences to find correct pdbentry for this
1136       // model
1137       for (int pe = 0; pe < getPdbCount(); pe++)
1138       {
1139         boolean matches = false;
1140         if (fileName == null)
1141         {
1142           if (false)
1143           // see JAL-623 - need method of matching pasted data up
1144           {
1145             pdb = getSsm().setMapping(getSequence()[pe], getChains()[pe],
1146                     pdbfile, AppletFormatAdapter.PASTE);
1147             getPdbEntry(modelnum).setFile("INLINE" + pdb.getId());
1148             matches = true;
1149             foundEntry = true;
1150           }
1151         }
1152         else
1153         {
1154           File fl = new File(getPdbEntry(pe).getFile());
1155           matches = fl.equals(new File(fileName));
1156           if (matches)
1157           {
1158             foundEntry = true;
1159             // TODO: Jmol can in principle retrieve from CLASSLOADER but
1160             // this
1161             // needs
1162             // to be tested. See mantis bug
1163             // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
1164             String protocol = AppletFormatAdapter.URL;
1165             try
1166             {
1167               if (fl.exists())
1168               {
1169                 protocol = AppletFormatAdapter.FILE;
1170               }
1171             } catch (Exception e)
1172             {
1173             } catch (Error e)
1174             {
1175             }
1176             // Explicitly map to the filename used by Jmol ;
1177             pdb = getSsm().setMapping(getSequence()[pe], getChains()[pe],
1178                     fileName, protocol);
1179             // pdbentry[pe].getFile(), protocol);
1180
1181           }
1182         }
1183         if (matches)
1184         {
1185           // add an entry for every chain in the model
1186           for (int i = 0; i < pdb.getChains().size(); i++)
1187           {
1188             String chid = new String(pdb.getId() + ":"
1189                     + pdb.getChains().elementAt(i).id);
1190             chainFile.put(chid, fileName);
1191             chainNames.addElement(chid);
1192           }
1193           notifyLoaded = true;
1194         }
1195       }
1196
1197       if (!foundEntry && associateNewStructs)
1198       {
1199         // this is a foreign pdb file that jalview doesn't know about - add
1200         // it to the dataset and try to find a home - either on a matching
1201         // sequence or as a new sequence.
1202         String pdbcontent = viewer.getData("/" + (modelnum + 1) + ".1",
1203                 "PDB");
1204         // parse pdb file into a chain, etc.
1205         // locate best match for pdb in associated views and add mapping to
1206         // ssm
1207         // if properly registered then
1208         notifyLoaded = true;
1209
1210       }
1211     }
1212     // FILE LOADED OK
1213     // so finally, update the jmol bits and pieces
1214     // if (jmolpopup != null)
1215     // {
1216     // // potential for deadlock here:
1217     // // jmolpopup.updateComputedMenus();
1218     // }
1219     if (!isLoadingFromArchive())
1220     {
1221       viewer.evalStringQuiet("model *; select backbone;restrict;cartoon;wireframe off;spacefill off");
1222     }
1223     // register ourselves as a listener and notify the gui that it needs to
1224     // update itself.
1225     getSsm().addStructureViewerListener(this);
1226     if (notifyLoaded)
1227     {
1228       FeatureRenderer fr = getFeatureRenderer(null);
1229       if (fr != null)
1230       {
1231         fr.featuresAdded();
1232       }
1233       refreshGUI();
1234       loadNotifiesHandled++;
1235     }
1236     setLoadingFromArchive(false);
1237   }
1238
1239   public void notifyNewPickingModeMeasurement(int iatom, String strMeasure)
1240   {
1241     notifyAtomPicked(iatom, strMeasure, null);
1242   }
1243
1244   public abstract void notifyScriptTermination(String strStatus,
1245           int msWalltime);
1246
1247   /**
1248    * display a message echoed from the jmol viewer
1249    * 
1250    * @param strEcho
1251    */
1252   public abstract void sendConsoleEcho(String strEcho); /*
1253                                                          * { showConsole(true);
1254                                                          * 
1255                                                          * history.append("\n" +
1256                                                          * strEcho); }
1257                                                          */
1258
1259   // /End JmolStatusListener
1260   // /////////////////////////////
1261
1262   /**
1263    * @param strStatus
1264    *          status message - usually the response received after a script
1265    *          executed
1266    */
1267   public abstract void sendConsoleMessage(String strStatus);
1268
1269   @Override
1270   public void setCallbackFunction(String callbackType,
1271           String callbackFunction)
1272   {
1273     System.err.println("Ignoring set-callback request to associate "
1274             + callbackType + " with function " + callbackFunction);
1275
1276   }
1277
1278   public void setJalviewColourScheme(ColourSchemeI cs)
1279   {
1280     colourBySequence = false;
1281
1282     if (cs == null)
1283     {
1284       return;
1285     }
1286
1287     jmolHistory(false);
1288     StringBuilder command = new StringBuilder(128);
1289     command.append("select *;color white;");
1290     List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
1291             false);
1292     for (String res : residueSet)
1293     {
1294       Color col = cs.findColour(res.charAt(0));
1295       command.append("select " + res + ";color[" + col.getRed() + ","
1296               + col.getGreen() + "," + col.getBlue() + "];");
1297     }
1298
1299     evalStateCommand(command.toString());
1300     jmolHistory(true);
1301   }
1302
1303   public void showHelp()
1304   {
1305     showUrl("http://jmol.sourceforge.net/docs/JmolUserGuide/", "jmolHelp");
1306   }
1307
1308   /**
1309    * open the URL somehow
1310    * 
1311    * @param target
1312    */
1313   public abstract void showUrl(String url, String target);
1314
1315   /**
1316    * called when the binding thinks the UI needs to be refreshed after a Jmol
1317    * state change. this could be because structures were loaded, or because an
1318    * error has occured.
1319    */
1320   public abstract void refreshGUI();
1321
1322   /**
1323    * called to show or hide the associated console window container.
1324    * 
1325    * @param show
1326    */
1327   public abstract void showConsole(boolean show);
1328
1329   /**
1330    * @param renderPanel
1331    * @param jmolfileio
1332    *          - when true will initialise jmol's file IO system (should be false
1333    *          in applet context)
1334    * @param htmlName
1335    * @param documentBase
1336    * @param codeBase
1337    * @param commandOptions
1338    */
1339   public void allocateViewer(Container renderPanel, boolean jmolfileio,
1340           String htmlName, URL documentBase, URL codeBase,
1341           String commandOptions)
1342   {
1343     allocateViewer(renderPanel, jmolfileio, htmlName, documentBase,
1344             codeBase, commandOptions, null, null);
1345   }
1346
1347   /**
1348    * 
1349    * @param renderPanel
1350    * @param jmolfileio
1351    *          - when true will initialise jmol's file IO system (should be false
1352    *          in applet context)
1353    * @param htmlName
1354    * @param documentBase
1355    * @param codeBase
1356    * @param commandOptions
1357    * @param consolePanel
1358    *          - panel to contain Jmol console
1359    * @param buttonsToShow
1360    *          - buttons to show on the console, in ordr
1361    */
1362   public void allocateViewer(Container renderPanel, boolean jmolfileio,
1363           String htmlName, URL documentBase, URL codeBase,
1364           String commandOptions, final Container consolePanel,
1365           String buttonsToShow)
1366   {
1367     if (commandOptions == null)
1368     {
1369       commandOptions = "";
1370     }
1371     viewer = (Viewer) JmolViewer.allocateViewer(renderPanel,
1372             (jmolfileio ? new SmarterJmolAdapter() : null), htmlName
1373                     + ((Object) this).toString(), documentBase, codeBase,
1374             commandOptions, this);
1375
1376     viewer.setJmolStatusListener(this); // extends JmolCallbackListener
1377
1378     console = createJmolConsole(consolePanel, buttonsToShow);
1379     if (consolePanel != null)
1380     {
1381       consolePanel.addComponentListener(this);
1382
1383     }
1384
1385   }
1386
1387   protected abstract JmolAppConsoleInterface createJmolConsole(
1388           Container consolePanel, String buttonsToShow);
1389
1390   protected org.jmol.api.JmolAppConsoleInterface console = null;
1391
1392   public void setBackgroundColour(java.awt.Color col)
1393   {
1394     jmolHistory(false);
1395     viewer.evalStringQuiet("background [" + col.getRed() + ","
1396             + col.getGreen() + "," + col.getBlue() + "];");
1397     jmolHistory(true);
1398   }
1399
1400   @Override
1401   public Dimension resizeInnerPanel(String data)
1402   {
1403     // Jalview doesn't honour resize panel requests
1404     return null;
1405   }
1406
1407   /**
1408    * 
1409    */
1410   protected void closeConsole()
1411   {
1412     if (console != null)
1413     {
1414       try
1415       {
1416         console.setVisible(false);
1417       } catch (Error e)
1418       {
1419       } catch (Exception x)
1420       {
1421       }
1422       ;
1423       console = null;
1424     }
1425   }
1426
1427   /**
1428    * ComponentListener method
1429    */
1430   @Override
1431   public void componentMoved(ComponentEvent e)
1432   {
1433   }
1434
1435   /**
1436    * ComponentListener method
1437    */
1438   @Override
1439   public void componentResized(ComponentEvent e)
1440   {
1441   }
1442
1443   /**
1444    * ComponentListener method
1445    */
1446   @Override
1447   public void componentShown(ComponentEvent e)
1448   {
1449     showConsole(true);
1450   }
1451
1452   /**
1453    * ComponentListener method
1454    */
1455   @Override
1456   public void componentHidden(ComponentEvent e)
1457   {
1458     showConsole(false);
1459   }
1460 }