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