JAL-1759 corrected syntax for 'atom picked' callback (toggles label
[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[]
235     { alignment }, new int[]
236     { refStructure }, new ColumnSelection[]
237     { hiddenCols });
238   }
239
240   /**
241    * Construct and send a command to align structures against a reference
242    * structure, based on one or more sequence alignments
243    * 
244    * @param _alignment
245    *          an array of alignments to process
246    * @param _refStructure
247    *          an array of corresponding reference structures (index into pdb
248    *          file array); if a negative value is passed, the first PDB file
249    *          mapped to an alignment sequence is used as the reference for
250    *          superposition
251    * @param _hiddenCols
252    *          an array of corresponding hidden columns for each alignment
253    */
254   public void superposeStructures(AlignmentI[] _alignment,
255           int[] _refStructure, ColumnSelection[] _hiddenCols)
256   {
257     while (viewer.isScriptExecuting())
258     {
259       try
260       {
261         Thread.sleep(10);
262       } catch (InterruptedException i)
263       {
264       }
265       ;
266     }
267     String[] files = getPdbFile();
268     if (!waitForFileLoad(files))
269     {
270       return;
271     }
272
273     StringBuilder selectioncom = new StringBuilder(256);
274     // In principle - nSeconds specifies the speed of animation for each
275     // superposition - but is seems to behave weirdly, so we don't specify it.
276     String nSeconds = " ";
277     if (files.length > 10)
278     {
279       nSeconds = " 0.005 ";
280     }
281     else
282     {
283       nSeconds = " " + (2.0 / files.length) + " ";
284       // if (nSeconds).substring(0,5)+" ";
285     }
286     // see JAL-1345 - should really automatically turn off the animation for
287     // large numbers of structures, but Jmol doesn't seem to allow that.
288     // nSeconds = " ";
289     // union of all aligned positions are collected together.
290     for (int a = 0; a < _alignment.length; a++)
291     {
292       int refStructure = _refStructure[a];
293       AlignmentI alignment = _alignment[a];
294       ColumnSelection hiddenCols = _hiddenCols[a];
295       if (a > 0
296               && selectioncom.length() > 0
297               && !selectioncom.substring(selectioncom.length() - 1).equals(
298                       "|"))
299       {
300         selectioncom.append("|");
301       }
302       // process this alignment
303       if (refStructure >= files.length)
304       {
305         System.err.println("Invalid reference structure value "
306                 + refStructure);
307         refStructure = -1;
308       }
309
310       /*
311        * 'matched' array will hold 'true' for visible alignment columns where
312        * all sequences have a residue with a mapping to the PDB structure
313        */
314       boolean matched[] = new boolean[alignment.getWidth()];
315       for (int m = 0; m < matched.length; m++)
316       {
317         matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
318       }
319
320       SuperposeData[] structures = new SuperposeData[files.length];
321       for (int f = 0; f < files.length; f++)
322       {
323         structures[f] = new SuperposeData(alignment.getWidth());
324       }
325
326       /*
327        * Calculate the superposable alignment columns ('matched'), and the
328        * corresponding structure residue positions (structures.pdbResNo)
329        */
330       int candidateRefStructure = findSuperposableResidues(alignment,
331               matched, structures);
332       if (refStructure < 0)
333       {
334         /*
335          * If no reference structure was specified, pick the first one that has
336          * a mapping in the alignment
337          */
338         refStructure = candidateRefStructure;
339       }
340
341       String[] selcom = new String[files.length];
342       int nmatched = 0;
343       for (boolean b : matched)
344       {
345         if (b)
346         {
347           nmatched++;
348         }
349       }
350       if (nmatched < 4)
351       {
352         // TODO: bail out here because superposition illdefined?
353       }
354
355       /*
356        * generate select statements to select regions to superimpose structures
357        */
358       {
359         for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
360         {
361           String chainCd = ":" + structures[pdbfnum].chain;
362           int lpos = -1;
363           boolean run = false;
364           StringBuilder molsel = new StringBuilder();
365           molsel.append("{");
366           for (int r = 0; r < matched.length; r++)
367           {
368             if (matched[r])
369             {
370               int pdbResNo = structures[pdbfnum].pdbResNo[r];
371               if (lpos != pdbResNo - 1)
372               {
373                 // discontinuity
374                 if (lpos != -1)
375                 {
376                   molsel.append(lpos);
377                   molsel.append(chainCd);
378                   molsel.append("|");
379                 }
380                 run = false;
381               }
382               else
383               {
384                 // continuous run - and lpos >-1
385                 if (!run)
386                 {
387                   // at the beginning, so add dash
388                   molsel.append(lpos);
389                   molsel.append("-");
390                 }
391                 run = true;
392               }
393               lpos = pdbResNo;
394             }
395           }
396           /*
397            * add final selection phrase
398            */
399           if (lpos != -1)
400           {
401             molsel.append(lpos);
402             molsel.append(chainCd);
403             molsel.append("}");
404           }
405           if (molsel.length() > 1)
406           {
407             selcom[pdbfnum] = molsel.toString();
408             selectioncom.append("((");
409             selectioncom.append(selcom[pdbfnum].substring(1,
410                     selcom[pdbfnum].length() - 1));
411             selectioncom.append(" )& ");
412             selectioncom.append(pdbfnum + 1);
413             selectioncom.append(".1)");
414             if (pdbfnum < files.length - 1)
415             {
416               selectioncom.append("|");
417             }
418           }
419           else
420           {
421             selcom[pdbfnum] = null;
422           }
423         }
424       }
425       StringBuilder command = new StringBuilder(256);
426       for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
427       {
428         if (pdbfnum == refStructure || selcom[pdbfnum] == null
429                 || selcom[refStructure] == null)
430         {
431           continue;
432         }
433         command.append("echo ");
434         command.append("\"Superposing (");
435         command.append(structures[pdbfnum].pdbId);
436         command.append(") against reference (");
437         command.append(structures[refStructure].pdbId);
438         command.append(")\";\ncompare " + nSeconds);
439         command.append("{");
440         command.append(Integer.toString(1 + pdbfnum));
441         command.append(".1} {");
442         command.append(Integer.toString(1 + refStructure));
443         // conformation=1 excludes alternate locations for CA (JAL-1757)
444         command.append(".1} SUBSET {(*.CA | *.P) and conformation=1} ATOMS ");
445
446         // for (int s = 0; s < 2; s++)
447         // {
448         // command.append(selcom[(s == 0 ? pdbfnum : refStructure)]);
449         // }
450         command.append(selcom[pdbfnum]);
451         command.append(selcom[refStructure]);
452         command.append(" ROTATE TRANSLATE;\n");
453       }
454       if (selectioncom.length() > 0)
455       {
456         System.out.println("Select regions:\n" + selectioncom.toString());
457         evalStateCommand("select *; cartoons off; backbone; select ("
458                 + selectioncom.toString() + "); cartoons; ");
459         // selcom.append("; ribbons; ");
460         String cmdString = command.toString();
461         System.out
462 .println("Superimpose command(s):\n" + cmdString);
463
464         evalStateCommand(cmdString);
465       }
466     }
467     if (selectioncom.length() > 0)
468     {// finally, mark all regions that were superposed.
469       if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
470       {
471         selectioncom.setLength(selectioncom.length() - 1);
472       }
473       System.out.println("Select regions:\n" + selectioncom.toString());
474       evalStateCommand("select *; cartoons off; backbone; select ("
475               + selectioncom.toString() + "); cartoons; ");
476       // evalStateCommand("select *; backbone; select "+selcom.toString()+"; cartoons; center "+selcom.toString());
477     }
478   }
479
480   public void evalStateCommand(String command)
481   {
482     jmolHistory(false);
483     if (lastCommand == null || !lastCommand.equals(command))
484     {
485       viewer.evalStringQuiet(command + "\n");
486     }
487     jmolHistory(true);
488     lastCommand = command;
489   }
490
491   /**
492    * colour any structures associated with sequences in the given alignment
493    * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
494    * if colourBySequence is enabled.
495    */
496   public void colourBySequence(AlignmentViewPanel alignmentv)
497   {
498     boolean showFeatures = alignmentv.getAlignViewport()
499             .isShowSequenceFeatures();
500     if (!colourBySequence || !isLoadingFinished())
501     {
502       return;
503     }
504     if (getSsm() == null)
505     {
506       return;
507     }
508     String[] files = getPdbFile();
509
510     SequenceRenderer sr = getSequenceRenderer(alignmentv);
511
512     FeatureRenderer fr = null;
513     if (showFeatures)
514     {
515       fr = getFeatureRenderer(alignmentv);
516     }
517     AlignmentI alignment = alignmentv.getAlignment();
518
519     for (jalview.structure.StructureMappingcommandSet cpdbbyseq : getColourBySequenceCommands(files, sr, fr, alignment))
520     {
521       for (String cbyseq : cpdbbyseq.commands)
522       {
523         executeWhenReady(cbyseq);
524       }
525     }
526   }
527
528   /**
529    * @param files
530    * @param sr
531    * @param fr
532    * @param alignment
533    * @return
534    */
535   protected StructureMappingcommandSet[] getColourBySequenceCommands(
536           String[] files, SequenceRenderer sr, FeatureRenderer fr,
537           AlignmentI alignment)
538   {
539     return JmolCommands
540             .getColourBySequenceCommand(getSsm(), files, getSequence(), sr,
541                     fr,
542                     alignment);
543   }
544
545   /**
546    * @param command
547    */
548   protected void executeWhenReady(String command)
549   {
550     evalStateCommand(command);
551   }
552
553   public void createImage(String file, String type, int quality)
554   {
555     System.out.println("JMOL CREATE IMAGE");
556   }
557
558   public String createImage(String fileName, String type,
559           Object textOrBytes, int quality)
560   {
561     System.out.println("JMOL CREATE IMAGE");
562     return null;
563   }
564
565   public String eval(String strEval)
566   {
567     // System.out.println(strEval);
568     // "# 'eval' is implemented only for the applet.";
569     return null;
570   }
571
572   // End StructureListener
573   // //////////////////////////
574
575   public float[][] functionXY(String functionName, int x, int y)
576   {
577     return null;
578   }
579
580   public float[][][] functionXYZ(String functionName, int nx, int ny, int nz)
581   {
582     // TODO Auto-generated method stub
583     return null;
584   }
585
586   public Color getColour(int atomIndex, int pdbResNum, String chain,
587           String pdbfile)
588   {
589     if (getModelNum(pdbfile) < 0)
590     {
591       return null;
592     }
593     // TODO: verify atomIndex is selecting correct model.
594     // return new Color(viewer.getAtomArgb(atomIndex)); Jmol 12.2.4
595     int colour = viewer.ms.at[atomIndex]
596             .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       for (AtomSpec atom : atoms)
745       {
746         highlightAtom(atom.getAtomIndex(), atom.getPdbResNum(),
747                 atom.getChain(), atom.getPdbFile());
748       }
749     }
750   }
751
752   // jmol/ssm only
753   public void highlightAtom(int atomIndex, int pdbResNum, String chain,
754           String pdbfile)
755   {
756     if (modelFileNames == null)
757     {
758       return;
759     }
760
761     // look up file model number for this pdbfile
762     int mdlNum = 0;
763     // may need to adjust for URLencoding here - we don't worry about that yet.
764     while (mdlNum < modelFileNames.length
765             && !pdbfile.equals(modelFileNames[mdlNum]))
766     {
767       mdlNum++;
768     }
769     if (mdlNum == modelFileNames.length)
770     {
771       return;
772     }
773
774     jmolHistory(false);
775     // if (!pdbfile.equals(pdbentry.getFile()))
776     // return;
777     if (resetLastRes.length() > 0)
778     {
779       viewer.evalStringQuiet(resetLastRes.toString());
780     }
781
782     StringBuilder cmd = new StringBuilder(64);
783     cmd.append("select " + pdbResNum); // +modelNum
784
785     resetLastRes.setLength(0);
786     resetLastRes.append("select " + pdbResNum); // +modelNum
787
788     cmd.append(":");
789     resetLastRes.append(":");
790     if (!chain.equals(" "))
791     {
792       cmd.append(chain);
793       resetLastRes.append(chain);
794     }
795     {
796       cmd.append(" /" + (mdlNum + 1));
797       resetLastRes.append("/" + (mdlNum + 1));
798     }
799     cmd.append(";wireframe 100;" + cmd.toString() + " and not hetero;");
800
801     resetLastRes.append(";wireframe 0;" + resetLastRes.toString()
802             + " and not hetero; spacefill 0;");
803
804     cmd.append("spacefill 200;select none");
805
806     viewer.evalStringQuiet(cmd.toString());
807     jmolHistory(true);
808
809   }
810
811   boolean debug = true;
812
813   private void jmolHistory(boolean enable)
814   {
815     viewer.evalStringQuiet("History " + ((debug || enable) ? "on" : "off"));
816   }
817
818   public void loadInline(String string)
819   {
820     loadedInline = true;
821     // TODO: re JAL-623
822     // viewer.loadInline(strModel, isAppend);
823     // could do this:
824     // construct fake fullPathName and fileName so we can identify the file
825     // later.
826     // Then, construct pass a reader for the string to Jmol.
827     // ((org.jmol.Viewer.Viewer) viewer).loadModelFromFile(fullPathName,
828     // fileName, null, reader, false, null, null, 0);
829     viewer.openStringInline(string);
830   }
831
832   public void mouseOverStructure(int atomIndex, String strInfo)
833   {
834     int pdbResNum;
835     int alocsep = strInfo.indexOf("^");
836     int mdlSep = strInfo.indexOf("/");
837     int chainSeparator = strInfo.indexOf(":"), chainSeparator1 = -1;
838
839     if (chainSeparator == -1)
840     {
841       chainSeparator = strInfo.indexOf(".");
842       if (mdlSep > -1 && mdlSep < chainSeparator)
843       {
844         chainSeparator1 = chainSeparator;
845         chainSeparator = mdlSep;
846       }
847     }
848     // handle insertion codes
849     if (alocsep != -1)
850     {
851       pdbResNum = Integer.parseInt(strInfo.substring(
852               strInfo.indexOf("]") + 1, alocsep));
853
854     }
855     else
856     {
857       pdbResNum = Integer.parseInt(strInfo.substring(
858               strInfo.indexOf("]") + 1, chainSeparator));
859     }
860     String chainId;
861
862     if (strInfo.indexOf(":") > -1)
863     {
864       chainId = strInfo.substring(strInfo.indexOf(":") + 1,
865               strInfo.indexOf("."));
866     }
867     else
868     {
869       chainId = " ";
870     }
871
872     String pdbfilename = modelFileNames[frameNo]; // default is first or current
873     // model
874     if (mdlSep > -1)
875     {
876       if (chainSeparator1 == -1)
877       {
878         chainSeparator1 = strInfo.indexOf(".", mdlSep);
879       }
880       String mdlId = (chainSeparator1 > -1) ? strInfo.substring(mdlSep + 1,
881               chainSeparator1) : strInfo.substring(mdlSep + 1);
882       try
883       {
884         // recover PDB filename for the model hovered over.
885         int _mp = _modelFileNameMap.length - 1, mnumber = new Integer(mdlId)
886                 .intValue() - 1;
887         while (mnumber < _modelFileNameMap[_mp])
888         {
889           _mp--;
890         }
891         pdbfilename = modelFileNames[_mp];
892         if (pdbfilename == null)
893         {
894           pdbfilename = new File(
895                   viewer.ms.getModelFileName(mnumber))
896                   .getAbsolutePath();
897         }
898
899       } catch (Exception e)
900       {
901       }
902       ;
903     }
904     if (lastMessage == null || !lastMessage.equals(strInfo))
905     {
906       getSsm().mouseOverStructure(pdbResNum, chainId, pdbfilename);
907     }
908
909     lastMessage = strInfo;
910   }
911
912   public void notifyAtomHovered(int atomIndex, String strInfo, String data)
913   {
914     if (data != null)
915     {
916       System.err.println("Ignoring additional hover info: " + data
917               + " (other info: '" + strInfo + "' pos " + atomIndex + ")");
918     }
919     mouseOverStructure(atomIndex, strInfo);
920   }
921
922   /*
923    * { if (history != null && strStatus != null &&
924    * !strStatus.equals("Script completed")) { history.append("\n" + strStatus);
925    * } }
926    */
927
928   public void notifyAtomPicked(int atomIndex, String strInfo, String strData)
929   {
930     /**
931      * this implements the toggle label behaviour copied from the original
932      * structure viewer, MCView
933      */
934     if (strData != null)
935     {
936       System.err.println("Ignoring additional pick data string " + strData);
937     }
938     int chainSeparator = strInfo.indexOf(":");
939     int p = 0;
940     if (chainSeparator == -1)
941     {
942       chainSeparator = strInfo.indexOf(".");
943     }
944
945     String picked = strInfo.substring(strInfo.indexOf("]") + 1,
946             chainSeparator);
947     String mdlString = "";
948     if ((p = strInfo.indexOf(":")) > -1)
949     {
950       picked += strInfo.substring(p, strInfo.indexOf("."));
951     }
952
953     if ((p = strInfo.indexOf("/")) > -1)
954     {
955       mdlString += strInfo.substring(p, strInfo.indexOf(" #"));
956     }
957     picked = "((" + picked + ".CA" + mdlString + ")|(" + picked + ".P"
958             + mdlString + "))";
959     jmolHistory(false);
960
961     if (!atomsPicked.contains(picked))
962     {
963       viewer.evalStringQuiet("select " + picked + ";label %n %r:%c");
964       atomsPicked.addElement(picked);
965     }
966     else
967     {
968       viewer.evalString("select " + picked + ";label off");
969       atomsPicked.removeElement(picked);
970     }
971     jmolHistory(true);
972     // TODO: in application this happens
973     //
974     // if (scriptWindow != null)
975     // {
976     // scriptWindow.sendConsoleMessage(strInfo);
977     // scriptWindow.sendConsoleMessage("\n");
978     // }
979
980   }
981
982   @Override
983   public void notifyCallback(CBK type, Object[] data)
984   {
985     try
986     {
987       switch (type)
988       {
989       case LOADSTRUCT:
990         notifyFileLoaded((String) data[1], (String) data[2],
991                 (String) data[3], (String) data[4],
992                 ((Integer) data[5]).intValue());
993
994         break;
995       case PICK:
996         notifyAtomPicked(((Integer) data[2]).intValue(), (String) data[1],
997                 (String) data[0]);
998         // also highlight in alignment
999       case HOVER:
1000         notifyAtomHovered(((Integer) data[2]).intValue(), (String) data[1],
1001                 (String) data[0]);
1002         break;
1003       case SCRIPT:
1004         notifyScriptTermination((String) data[2],
1005                 ((Integer) data[3]).intValue());
1006         break;
1007       case ECHO:
1008         sendConsoleEcho((String) data[1]);
1009         break;
1010       case MESSAGE:
1011         sendConsoleMessage((data == null) ? ((String) null)
1012                 : (String) data[1]);
1013         break;
1014       case ERROR:
1015         // System.err.println("Ignoring error callback.");
1016         break;
1017       case SYNC:
1018       case RESIZE:
1019         refreshGUI();
1020         break;
1021       case MEASURE:
1022
1023       case CLICK:
1024       default:
1025         System.err.println("Unhandled callback " + type + " "
1026                 + data[1].toString());
1027         break;
1028       }
1029     } catch (Exception e)
1030     {
1031       System.err.println("Squashed Jmol callback handler error:");
1032       e.printStackTrace();
1033     }
1034   }
1035
1036   @Override
1037   public boolean notifyEnabled(CBK callbackPick)
1038   {
1039     switch (callbackPick)
1040     {
1041     case ECHO:
1042     case LOADSTRUCT:
1043     case MEASURE:
1044     case MESSAGE:
1045     case PICK:
1046     case SCRIPT:
1047     case HOVER:
1048     case ERROR:
1049       return true;
1050     default:
1051       return false;
1052     }
1053   }
1054
1055   // incremented every time a load notification is successfully handled -
1056   // lightweight mechanism for other threads to detect when they can start
1057   // referrring to new structures.
1058   private long loadNotifiesHandled = 0;
1059
1060   public long getLoadNotifiesHandled()
1061   {
1062     return loadNotifiesHandled;
1063   }
1064
1065   public void notifyFileLoaded(String fullPathName, String fileName2,
1066           String modelName, String errorMsg, int modelParts)
1067   {
1068     if (errorMsg != null)
1069     {
1070       fileLoadingError = errorMsg;
1071       refreshGUI();
1072       return;
1073     }
1074     // TODO: deal sensibly with models loaded inLine:
1075     // modelName will be null, as will fullPathName.
1076
1077     // the rest of this routine ignores the arguments, and simply interrogates
1078     // the Jmol view to find out what structures it contains, and adds them to
1079     // the structure selection manager.
1080     fileLoadingError = null;
1081     String[] oldmodels = modelFileNames;
1082     modelFileNames = null;
1083     chainNames = new Vector<String>();
1084     chainFile = new Hashtable<String, String>();
1085     boolean notifyLoaded = false;
1086     String[] modelfilenames = getPdbFile();
1087     // first check if we've lost any structures
1088     if (oldmodels != null && oldmodels.length > 0)
1089     {
1090       int oldm = 0;
1091       for (int i = 0; i < oldmodels.length; i++)
1092       {
1093         for (int n = 0; n < modelfilenames.length; n++)
1094         {
1095           if (modelfilenames[n] == oldmodels[i])
1096           {
1097             oldmodels[i] = null;
1098             break;
1099           }
1100         }
1101         if (oldmodels[i] != null)
1102         {
1103           oldm++;
1104         }
1105       }
1106       if (oldm > 0)
1107       {
1108         String[] oldmfn = new String[oldm];
1109         oldm = 0;
1110         for (int i = 0; i < oldmodels.length; i++)
1111         {
1112           if (oldmodels[i] != null)
1113           {
1114             oldmfn[oldm++] = oldmodels[i];
1115           }
1116         }
1117         // deregister the Jmol instance for these structures - we'll add
1118         // ourselves again at the end for the current structure set.
1119         getSsm().removeStructureViewerListener(this, oldmfn);
1120       }
1121     }
1122     refreshPdbEntries();
1123     for (int modelnum = 0; modelnum < modelfilenames.length; modelnum++)
1124     {
1125       String fileName = modelfilenames[modelnum];
1126       boolean foundEntry = false;
1127       MCview.PDBfile pdb = null;
1128       String pdbfile = null;
1129       // model was probably loaded inline - so check the pdb file hashcode
1130       if (loadedInline)
1131       {
1132         // calculate essential attributes for the pdb data imported inline.
1133         // prolly need to resolve modelnumber properly - for now just use our
1134         // 'best guess'
1135         pdbfile = viewer.getData("" + (1 + _modelFileNameMap[modelnum])
1136                 + ".0", "PDB");
1137       }
1138         // search pdbentries and sequences to find correct pdbentry for this
1139         // model
1140       for (int pe = 0; pe < getPdbCount(); pe++)
1141       {
1142         boolean matches = false;
1143         if (fileName == null)
1144         {
1145           if (false)
1146           // see JAL-623 - need method of matching pasted data up
1147           {
1148             pdb = getSsm().setMapping(getSequence()[pe], getChains()[pe],
1149                     pdbfile, AppletFormatAdapter.PASTE);
1150             getPdbEntry(modelnum).setFile("INLINE" + pdb.id);
1151             matches = true;
1152             foundEntry = true;
1153           }
1154         }
1155         else
1156         {
1157           File fl = new File(getPdbEntry(pe).getFile());
1158           matches = fl.equals(new File(fileName));
1159           if (matches)
1160           {
1161             foundEntry = true;
1162             // TODO: Jmol can in principle retrieve from CLASSLOADER but
1163             // this
1164             // needs
1165             // to be tested. See mantis bug
1166             // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
1167             String protocol = AppletFormatAdapter.URL;
1168             try
1169             {
1170               if (fl.exists())
1171               {
1172                 protocol = AppletFormatAdapter.FILE;
1173               }
1174             } catch (Exception e)
1175             {
1176             } catch (Error e)
1177             {
1178             }
1179             // Explicitly map to the filename used by Jmol ;
1180             pdb = getSsm().setMapping(getSequence()[pe], getChains()[pe],
1181                     fileName, protocol);
1182             // pdbentry[pe].getFile(), protocol);
1183
1184           }
1185         }
1186         if (matches)
1187         {
1188           // add an entry for every chain in the model
1189           for (int i = 0; i < pdb.chains.size(); i++)
1190           {
1191             String chid = new String(pdb.id + ":"
1192                     + pdb.chains.elementAt(i).id);
1193             chainFile.put(chid, fileName);
1194             chainNames.addElement(chid);
1195           }
1196           notifyLoaded = true;
1197         }
1198       }
1199
1200       if (!foundEntry && associateNewStructs)
1201       {
1202         // this is a foreign pdb file that jalview doesn't know about - add
1203         // it to the dataset and try to find a home - either on a matching
1204         // sequence or as a new sequence.
1205         String pdbcontent = viewer.getData("/" + (modelnum + 1) + ".1",
1206                 "PDB");
1207         // parse pdb file into a chain, etc.
1208         // locate best match for pdb in associated views and add mapping to
1209         // ssm
1210         // if properly registered then
1211         notifyLoaded = true;
1212
1213       }
1214     }
1215     // FILE LOADED OK
1216     // so finally, update the jmol bits and pieces
1217     // if (jmolpopup != null)
1218     // {
1219     // // potential for deadlock here:
1220     // // jmolpopup.updateComputedMenus();
1221     // }
1222     if (!isLoadingFromArchive())
1223     {
1224       viewer.evalStringQuiet("model *; select backbone;restrict;cartoon;wireframe off;spacefill off");
1225     }
1226     // register ourselves as a listener and notify the gui that it needs to
1227     // update itself.
1228     getSsm().addStructureViewerListener(this);
1229     if (notifyLoaded)
1230     {
1231       FeatureRenderer fr = getFeatureRenderer(null);
1232       if (fr != null)
1233       {
1234         fr.featuresAdded();
1235       }
1236       refreshGUI();
1237       loadNotifiesHandled++;
1238     }
1239     setLoadingFromArchive(false);
1240   }
1241
1242   public void notifyNewPickingModeMeasurement(int iatom, String strMeasure)
1243   {
1244     notifyAtomPicked(iatom, strMeasure, null);
1245   }
1246
1247   public abstract void notifyScriptTermination(String strStatus,
1248           int msWalltime);
1249
1250   /**
1251    * display a message echoed from the jmol viewer
1252    * 
1253    * @param strEcho
1254    */
1255   public abstract void sendConsoleEcho(String strEcho); /*
1256                                                          * { showConsole(true);
1257                                                          * 
1258                                                          * history.append("\n" +
1259                                                          * strEcho); }
1260                                                          */
1261
1262   // /End JmolStatusListener
1263   // /////////////////////////////
1264
1265   /**
1266    * @param strStatus
1267    *          status message - usually the response received after a script
1268    *          executed
1269    */
1270   public abstract void sendConsoleMessage(String strStatus);
1271
1272   public void setCallbackFunction(String callbackType,
1273           String callbackFunction)
1274   {
1275     System.err.println("Ignoring set-callback request to associate "
1276             + callbackType + " with function " + callbackFunction);
1277
1278   }
1279
1280   public void setJalviewColourScheme(ColourSchemeI cs)
1281   {
1282     colourBySequence = false;
1283
1284     if (cs == null)
1285     {
1286       return;
1287     }
1288
1289     jmolHistory(false);
1290     StringBuilder command = new StringBuilder(128);
1291     command.append("select *;color white;");
1292     List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
1293             false);
1294     for (String res : residueSet)
1295     {
1296       Color col = cs.findColour(res.charAt(0));
1297       command.append("select " + res + ";color[" + col.getRed() + ","
1298               + col.getGreen() + "," + col.getBlue() + "];");
1299     }
1300
1301     evalStateCommand(command.toString());
1302     jmolHistory(true);
1303   }
1304
1305   public void showHelp()
1306   {
1307     showUrl("http://jmol.sourceforge.net/docs/JmolUserGuide/", "jmolHelp");
1308   }
1309
1310   /**
1311    * open the URL somehow
1312    * 
1313    * @param target
1314    */
1315   public abstract void showUrl(String url, String target);
1316
1317   /**
1318    * called when the binding thinks the UI needs to be refreshed after a Jmol
1319    * state change. this could be because structures were loaded, or because an
1320    * error has occured.
1321    */
1322   public abstract void refreshGUI();
1323
1324   /**
1325    * called to show or hide the associated console window container.
1326    * 
1327    * @param show
1328    */
1329   public abstract void showConsole(boolean show);
1330
1331   /**
1332    * @param renderPanel
1333    * @param jmolfileio
1334    *          - when true will initialise jmol's file IO system (should be false
1335    *          in applet context)
1336    * @param htmlName
1337    * @param documentBase
1338    * @param codeBase
1339    * @param commandOptions
1340    */
1341   public void allocateViewer(Container renderPanel, boolean jmolfileio,
1342           String htmlName, URL documentBase, URL codeBase,
1343           String commandOptions)
1344   {
1345     allocateViewer(renderPanel, jmolfileio, htmlName, documentBase,
1346             codeBase, commandOptions, null, null);
1347   }
1348
1349   /**
1350    * 
1351    * @param renderPanel
1352    * @param jmolfileio
1353    *          - when true will initialise jmol's file IO system (should be false
1354    *          in applet context)
1355    * @param htmlName
1356    * @param documentBase
1357    * @param codeBase
1358    * @param commandOptions
1359    * @param consolePanel
1360    *          - panel to contain Jmol console
1361    * @param buttonsToShow
1362    *          - buttons to show on the console, in ordr
1363    */
1364   public void allocateViewer(Container renderPanel, boolean jmolfileio,
1365           String htmlName, URL documentBase, URL codeBase,
1366           String commandOptions, final Container consolePanel,
1367           String buttonsToShow)
1368   {
1369     if (commandOptions == null)
1370     {
1371       commandOptions = "";
1372     }
1373     viewer = (Viewer) JmolViewer.allocateViewer(renderPanel,
1374             (jmolfileio ? new SmarterJmolAdapter() : null), htmlName
1375                     + ((Object) this).toString(), documentBase, codeBase,
1376             commandOptions, this);
1377
1378     viewer.setJmolStatusListener(this); // extends JmolCallbackListener
1379
1380     console = createJmolConsole(consolePanel, buttonsToShow);
1381     if (consolePanel != null)
1382     {
1383       consolePanel.addComponentListener(this);
1384
1385     }
1386
1387   }
1388
1389   protected abstract JmolAppConsoleInterface createJmolConsole(
1390           Container consolePanel, String buttonsToShow);
1391
1392   protected org.jmol.api.JmolAppConsoleInterface console = null;
1393
1394   public void setBackgroundColour(java.awt.Color col)
1395   {
1396     jmolHistory(false);
1397     viewer.evalStringQuiet("background [" + col.getRed() + ","
1398             + col.getGreen() + "," + col.getBlue() + "];");
1399     jmolHistory(true);
1400   }
1401
1402   @Override
1403   public Dimension resizeInnerPanel(String data)
1404   {
1405     // Jalview doesn't honour resize panel requests
1406     return null;
1407   }
1408
1409   /**
1410    * 
1411    */
1412   protected void closeConsole()
1413   {
1414     if (console != null)
1415     {
1416       try
1417       {
1418         console.setVisible(false);
1419       } catch (Error e)
1420       {
1421       } catch (Exception x)
1422       {
1423       }
1424       ;
1425       console = null;
1426     }
1427   }
1428
1429   /**
1430    * ComponentListener method
1431    */
1432   @Override
1433   public void componentMoved(ComponentEvent e)
1434   {
1435   }
1436
1437   /**
1438    * ComponentListener method
1439    */
1440   @Override
1441   public void componentResized(ComponentEvent e)
1442   {
1443   }
1444
1445   /**
1446    * ComponentListener method
1447    */
1448   @Override
1449   public void componentShown(ComponentEvent e)
1450   {
1451     showConsole(true);
1452   }
1453
1454   /**
1455    * ComponentListener method
1456    */
1457   @Override
1458   public void componentHidden(ComponentEvent e)
1459   {
1460     showConsole(false);
1461   }
1462 }
1463