JAL-2130 call viewer.dispose() on closing Jmol
[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.Hashtable;
47 import java.util.List;
48 import java.util.Map;
49 import java.util.Vector;
50
51 import javajs.awt.Dimension;
52
53 import org.jmol.adapter.smarter.SmarterJmolAdapter;
54 import org.jmol.api.JmolAppConsoleInterface;
55 import org.jmol.api.JmolSelectionListener;
56 import org.jmol.api.JmolStatusListener;
57 import org.jmol.api.JmolViewer;
58 import org.jmol.c.CBK;
59 import org.jmol.script.T;
60 import org.jmol.viewer.JC;
61 import org.jmol.viewer.Viewer;
62
63 public abstract class JalviewJmolBinding extends AAStructureBindingModel
64         implements JmolStatusListener, JmolSelectionListener,
65         ComponentListener
66 {
67   boolean allChainsSelected = false;
68
69   /*
70    * when true, try to search the associated datamodel for sequences that are
71    * associated with any unknown structures in the Jmol view.
72    */
73   private boolean associateNewStructs = false;
74
75   Vector<String> atomsPicked = new Vector<String>();
76
77   public Vector<String> chainNames;
78
79   Hashtable<String, String> chainFile;
80
81   public String fileLoadingError;
82
83   /*
84    * the default or current model displayed if the model cannot be identified
85    * from the selection message
86    */
87   int frameNo = 0;
88
89   // protected JmolGenericPopup jmolpopup; // not used - remove?
90
91   String lastCommand;
92
93   String lastMessage;
94
95   boolean loadedInline;
96
97   /**
98    * current set of model filenames loaded in the Jmol instance
99    */
100   String[] modelFileNames = null;
101
102   StringBuffer resetLastRes = new StringBuffer();
103
104   public Viewer viewer;
105
106   public JalviewJmolBinding(StructureSelectionManager ssm,
107           PDBEntry[] pdbentry, SequenceI[][] sequenceIs, String[][] chains,
108           String protocol)
109   {
110     super(ssm, pdbentry, sequenceIs, chains, protocol);
111     /*
112      * viewer = JmolViewer.allocateViewer(renderPanel, new SmarterJmolAdapter(),
113      * "jalviewJmol", ap.av.applet .getDocumentBase(),
114      * ap.av.applet.getCodeBase(), "", this);
115      * 
116      * jmolpopup = JmolPopup.newJmolPopup(viewer, true, "Jmol", true);
117      */
118   }
119
120   public JalviewJmolBinding(StructureSelectionManager ssm,
121           SequenceI[][] seqs, Viewer theViewer)
122   {
123     super(ssm, seqs);
124
125     viewer = theViewer;
126     viewer.setJmolStatusListener(this);
127     viewer.addSelectionListener(this);
128   }
129
130   /**
131    * construct a title string for the viewer window based on the data jalview
132    * knows about
133    * 
134    * @return
135    */
136   public String getViewerTitle()
137   {
138     return getViewerTitle("Jmol", true);
139   }
140
141   /**
142    * prepare the view for a given set of models/chains. chainList contains
143    * strings of the form 'pdbfilename:Chaincode'
144    * 
145    * @param chainList
146    *          list of chains to make visible
147    */
148   public void centerViewer(Vector<String> chainList)
149   {
150     StringBuilder cmd = new StringBuilder(128);
151     int mlength, p;
152     for (String lbl : chainList)
153     {
154       mlength = 0;
155       do
156       {
157         p = mlength;
158         mlength = lbl.indexOf(":", p);
159       } while (p < mlength && mlength < (lbl.length() - 2));
160       // TODO: lookup each pdb id and recover proper model number for it.
161       cmd.append(":" + lbl.substring(mlength + 1) + " /"
162               + (1 + getModelNum(chainFile.get(lbl))) + " or ");
163     }
164     if (cmd.length() > 0)
165     {
166       cmd.setLength(cmd.length() - 4);
167     }
168     evalStateCommand("select *;restrict " + cmd + ";cartoon;center " + cmd);
169   }
170
171   public void closeViewer()
172   {
173     viewer.acm.setModeMouse(JC.MOUSE_NONE);
174     // remove listeners for all structures in viewer
175     getSsm().removeStructureViewerListener(this, this.getPdbFile());
176     // and shut down jmol
177     viewer.evalStringQuiet("zap");
178     viewer.setJmolStatusListener(null);
179     viewer.dispose();
180     lastCommand = null;
181     viewer = null;
182     releaseUIResources();
183   }
184
185   public void colourByChain()
186   {
187     colourBySequence = false;
188     // TODO: colour by chain should colour each chain distinctly across all
189     // visible models
190     // TODO: http://issues.jalview.org/browse/JAL-628
191     evalStateCommand("select *;color chain");
192   }
193
194   public void colourByCharge()
195   {
196     colourBySequence = false;
197     evalStateCommand("select *;color white;select ASP,GLU;color red;"
198             + "select LYS,ARG;color blue;select CYS;color yellow");
199   }
200
201   /**
202    * superpose the structures associated with sequences in the alignment
203    * according to their corresponding positions.
204    */
205   public void superposeStructures(AlignmentI alignment)
206   {
207     superposeStructures(alignment, -1, null);
208   }
209
210   /**
211    * superpose the structures associated with sequences in the alignment
212    * according to their corresponding positions. ded)
213    * 
214    * @param refStructure
215    *          - select which pdb file to use as reference (default is -1 - the
216    *          first structure in the alignment)
217    */
218   public void superposeStructures(AlignmentI alignment, int refStructure)
219   {
220     superposeStructures(alignment, refStructure, null);
221   }
222
223   /**
224    * superpose the structures associated with sequences in the alignment
225    * according to their corresponding positions. ded)
226    * 
227    * @param refStructure
228    *          - select which pdb file to use as reference (default is -1 - the
229    *          first structure in the alignment)
230    * @param hiddenCols
231    *          TODO
232    */
233   public void superposeStructures(AlignmentI alignment, int refStructure,
234           ColumnSelection hiddenCols)
235   {
236     superposeStructures(new AlignmentI[] { alignment },
237             new int[] { refStructure },
238             new ColumnSelection[] { hiddenCols });
239   }
240
241   /**
242    * Construct and send a command to align structures against a reference
243    * structure, based on one or more sequence alignments
244    * 
245    * @param _alignment
246    *          an array of alignments to process
247    * @param _refStructure
248    *          an array of corresponding reference structures (index into pdb
249    *          file array); if a negative value is passed, the first PDB file
250    *          mapped to an alignment sequence is used as the reference for
251    *          superposition
252    * @param _hiddenCols
253    *          an array of corresponding hidden columns for each alignment
254    */
255   public void superposeStructures(AlignmentI[] _alignment,
256           int[] _refStructure, ColumnSelection[] _hiddenCols)
257   {
258     while (viewer.isScriptExecuting())
259     {
260       try
261       {
262         Thread.sleep(10);
263       } catch (InterruptedException i)
264       {
265       }
266       ;
267     }
268     String[] files = getPdbFile();
269     if (!waitForFileLoad(files))
270     {
271       return;
272     }
273
274     StringBuilder selectioncom = new StringBuilder(256);
275     // In principle - nSeconds specifies the speed of animation for each
276     // superposition - but is seems to behave weirdly, so we don't specify it.
277     String nSeconds = " ";
278     if (files.length > 10)
279     {
280       nSeconds = " 0.005 ";
281     }
282     else
283     {
284       nSeconds = " " + (2.0 / files.length) + " ";
285       // if (nSeconds).substring(0,5)+" ";
286     }
287     // see JAL-1345 - should really automatically turn off the animation for
288     // large numbers of structures, but Jmol doesn't seem to allow that.
289     // nSeconds = " ";
290     // union of all aligned positions are collected together.
291     for (int a = 0; a < _alignment.length; a++)
292     {
293       int refStructure = _refStructure[a];
294       AlignmentI alignment = _alignment[a];
295       ColumnSelection hiddenCols = _hiddenCols[a];
296       if (a > 0
297               && selectioncom.length() > 0
298               && !selectioncom.substring(selectioncom.length() - 1).equals(
299                       "|"))
300       {
301         selectioncom.append("|");
302       }
303       // process this alignment
304       if (refStructure >= files.length)
305       {
306         System.err.println("Invalid reference structure value "
307                 + refStructure);
308         refStructure = -1;
309       }
310
311       /*
312        * 'matched' array will hold 'true' for visible alignment columns where
313        * all sequences have a residue with a mapping to the PDB structure
314        */
315       boolean matched[] = new boolean[alignment.getWidth()];
316       for (int m = 0; m < matched.length; m++)
317       {
318         matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
319       }
320
321       SuperposeData[] structures = new SuperposeData[files.length];
322       for (int f = 0; f < files.length; f++)
323       {
324         structures[f] = new SuperposeData(alignment.getWidth());
325       }
326
327       /*
328        * Calculate the superposable alignment columns ('matched'), and the
329        * corresponding structure residue positions (structures.pdbResNo)
330        */
331       int candidateRefStructure = findSuperposableResidues(alignment,
332               matched, structures);
333       if (refStructure < 0)
334       {
335         /*
336          * If no reference structure was specified, pick the first one that has
337          * a mapping in the alignment
338          */
339         refStructure = candidateRefStructure;
340       }
341
342       String[] selcom = new String[files.length];
343       int nmatched = 0;
344       for (boolean b : matched)
345       {
346         if (b)
347         {
348           nmatched++;
349         }
350       }
351       if (nmatched < 4)
352       {
353         // TODO: bail out here because superposition illdefined?
354       }
355
356       /*
357        * generate select statements to select regions to superimpose structures
358        */
359       {
360         for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
361         {
362           String chainCd = ":" + structures[pdbfnum].chain;
363           int lpos = -1;
364           boolean run = false;
365           StringBuilder molsel = new StringBuilder();
366           molsel.append("{");
367           for (int r = 0; r < matched.length; r++)
368           {
369             if (matched[r])
370             {
371               int pdbResNo = structures[pdbfnum].pdbResNo[r];
372               if (lpos != pdbResNo - 1)
373               {
374                 // discontinuity
375                 if (lpos != -1)
376                 {
377                   molsel.append(lpos);
378                   molsel.append(chainCd);
379                   molsel.append("|");
380                 }
381                 run = false;
382               }
383               else
384               {
385                 // continuous run - and lpos >-1
386                 if (!run)
387                 {
388                   // at the beginning, so add dash
389                   molsel.append(lpos);
390                   molsel.append("-");
391                 }
392                 run = true;
393               }
394               lpos = pdbResNo;
395             }
396           }
397           /*
398            * add final selection phrase
399            */
400           if (lpos != -1)
401           {
402             molsel.append(lpos);
403             molsel.append(chainCd);
404             molsel.append("}");
405           }
406           if (molsel.length() > 1)
407           {
408             selcom[pdbfnum] = molsel.toString();
409             selectioncom.append("((");
410             selectioncom.append(selcom[pdbfnum].substring(1,
411                     selcom[pdbfnum].length() - 1));
412             selectioncom.append(" )& ");
413             selectioncom.append(pdbfnum + 1);
414             selectioncom.append(".1)");
415             if (pdbfnum < files.length - 1)
416             {
417               selectioncom.append("|");
418             }
419           }
420           else
421           {
422             selcom[pdbfnum] = null;
423           }
424         }
425       }
426       StringBuilder command = new StringBuilder(256);
427       for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
428       {
429         if (pdbfnum == refStructure || selcom[pdbfnum] == null
430                 || selcom[refStructure] == null)
431         {
432           continue;
433         }
434         command.append("echo ");
435         command.append("\"Superposing (");
436         command.append(structures[pdbfnum].pdbId);
437         command.append(") against reference (");
438         command.append(structures[refStructure].pdbId);
439         command.append(")\";\ncompare " + nSeconds);
440         command.append("{");
441         command.append(Integer.toString(1 + pdbfnum));
442         command.append(".1} {");
443         command.append(Integer.toString(1 + refStructure));
444         // conformation=1 excludes alternate locations for CA (JAL-1757)
445         command.append(".1} SUBSET {(*.CA | *.P) and conformation=1} ATOMS ");
446
447         // for (int s = 0; s < 2; s++)
448         // {
449         // command.append(selcom[(s == 0 ? pdbfnum : refStructure)]);
450         // }
451         command.append(selcom[pdbfnum]);
452         command.append(selcom[refStructure]);
453         command.append(" ROTATE TRANSLATE;\n");
454       }
455       if (selectioncom.length() > 0)
456       {
457         System.out.println("Select regions:\n" + selectioncom.toString());
458         evalStateCommand("select *; cartoons off; backbone; select ("
459                 + selectioncom.toString() + "); cartoons; ");
460         // selcom.append("; ribbons; ");
461         String cmdString = command.toString();
462         System.out.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(
520             files, sr, fr, alignment))
521     {
522       for (String cbyseq : cpdbbyseq.commands)
523       {
524         executeWhenReady(cbyseq);
525       }
526     }
527   }
528
529   /**
530    * @param files
531    * @param sr
532    * @param fr
533    * @param alignment
534    * @return
535    */
536   protected StructureMappingcommandSet[] getColourBySequenceCommands(
537           String[] files, SequenceRenderer sr, FeatureRenderer fr,
538           AlignmentI alignment)
539   {
540     return JmolCommands.getColourBySequenceCommand(getSsm(), files,
541             getSequence(), sr, fr, alignment);
542   }
543
544   /**
545    * @param command
546    */
547   protected void executeWhenReady(String command)
548   {
549     evalStateCommand(command);
550   }
551
552   public void createImage(String file, String type, int quality)
553   {
554     System.out.println("JMOL CREATE IMAGE");
555   }
556
557   @Override
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   @Override
566   public String eval(String strEval)
567   {
568     // System.out.println(strEval);
569     // "# 'eval' is implemented only for the applet.";
570     return null;
571   }
572
573   // End StructureListener
574   // //////////////////////////
575
576   @Override
577   public float[][] functionXY(String functionName, int x, int y)
578   {
579     return null;
580   }
581
582   @Override
583   public float[][][] functionXYZ(String functionName, int nx, int ny, int nz)
584   {
585     // TODO Auto-generated method stub
586     return null;
587   }
588
589   public Color getColour(int atomIndex, int pdbResNum, String chain,
590           String pdbfile)
591   {
592     if (getModelNum(pdbfile) < 0)
593     {
594       return null;
595     }
596     // TODO: verify atomIndex is selecting correct model.
597     // return new Color(viewer.getAtomArgb(atomIndex)); Jmol 12.2.4
598     int colour = viewer.ms.at[atomIndex].atomPropertyInt(T.color);
599     return new Color(colour);
600   }
601
602   /**
603    * returns the current featureRenderer that should be used to colour the
604    * structures
605    * 
606    * @param alignment
607    * 
608    * @return
609    */
610   public abstract FeatureRenderer getFeatureRenderer(
611           AlignmentViewPanel alignment);
612
613   /**
614    * instruct the Jalview binding to update the pdbentries vector if necessary
615    * prior to matching the jmol view's contents to the list of structure files
616    * Jalview knows about.
617    */
618   public abstract void refreshPdbEntries();
619
620   private int getModelNum(String modelFileName)
621   {
622     String[] mfn = getPdbFile();
623     if (mfn == null)
624     {
625       return -1;
626     }
627     for (int i = 0; i < mfn.length; i++)
628     {
629       if (mfn[i].equalsIgnoreCase(modelFileName))
630       {
631         return i;
632       }
633     }
634     return -1;
635   }
636
637   /**
638    * map between index of model filename returned from getPdbFile and the first
639    * index of models from this file in the viewer. Note - this is not trimmed -
640    * use getPdbFile to get number of unique models.
641    */
642   private int _modelFileNameMap[];
643
644   // ////////////////////////////////
645   // /StructureListener
646   @Override
647   public synchronized String[] getPdbFile()
648   {
649     if (viewer == null)
650     {
651       return new String[0];
652     }
653     if (modelFileNames == null)
654     {
655       String mset[] = new String[viewer.ms.mc];
656       _modelFileNameMap = new int[mset.length];
657       String m = viewer.ms.getModelFileName(0);
658       if (m != null)
659       {
660         mset[0] = m;
661         try
662         {
663           mset[0] = new File(m).getAbsolutePath();
664         } catch (AccessControlException x)
665         {
666           // usually not allowed to do this in applet
667           System.err
668                   .println("jmolBinding: Using local file string from Jmol: "
669                           + m);
670         }
671         if (mset[0].indexOf("/file:") != -1)
672         {
673           // applet path with docroot - discard as format won't match pdbfile
674           mset[0] = m;
675         }
676         _modelFileNameMap[0] = 0; // filename index for first model is always 0.
677       }
678       int j = 1;
679       for (int i = 1; i < mset.length; i++)
680       {
681         m = viewer.ms.getModelFileName(i);
682         mset[j] = m;
683         if (m != null)
684         {
685           try
686           {
687             mset[j] = new File(m).getAbsolutePath();
688           } catch (AccessControlException x)
689           {
690             // usually not allowed to do this in applet, so keep raw handle
691             // System.err.println("jmolBinding: Using local file string from Jmol: "+m);
692           }
693         }
694         _modelFileNameMap[j] = i; // record the model index for the filename
695         // skip any additional models in the same file (NMR structures)
696         if ((mset[j] == null ? mset[j] != mset[j - 1]
697                 : (mset[j - 1] == null || !mset[j].equals(mset[j - 1]))))
698         {
699           j++;
700         }
701       }
702       modelFileNames = new String[j];
703       System.arraycopy(mset, 0, modelFileNames, 0, j);
704     }
705     return modelFileNames;
706   }
707
708   /**
709    * map from string to applet
710    */
711   @Override
712   public Map<String, Object> getRegistryInfo()
713   {
714     // TODO Auto-generated method stub
715     return null;
716   }
717
718   /**
719    * returns the current sequenceRenderer that should be used to colour the
720    * structures
721    * 
722    * @param alignment
723    * 
724    * @return
725    */
726   public abstract SequenceRenderer getSequenceRenderer(
727           AlignmentViewPanel alignment);
728
729   // ///////////////////////////////
730   // JmolStatusListener
731
732   public void handlePopupMenu(int x, int y)
733   {
734     // jmolpopup.show(x, y);
735     // jmolpopup.jpiShow(x, y);
736   }
737
738   /**
739    * Highlight zero, one or more atoms on the structure
740    */
741   @Override
742   public void highlightAtoms(List<AtomSpec> atoms)
743   {
744     if (atoms != null)
745     {
746       if (resetLastRes.length() > 0)
747       {
748         viewer.evalStringQuiet(resetLastRes.toString());
749         resetLastRes.setLength(0);
750       }
751       for (AtomSpec atom : atoms)
752       {
753         highlightAtom(atom.getAtomIndex(), atom.getPdbResNum(),
754                 atom.getChain(), atom.getPdbFile());
755       }
756     }
757   }
758
759   // jmol/ssm only
760   public void highlightAtom(int atomIndex, int pdbResNum, String chain,
761           String pdbfile)
762   {
763     if (modelFileNames == null)
764     {
765       return;
766     }
767
768     // look up file model number for this pdbfile
769     int mdlNum = 0;
770     // may need to adjust for URLencoding here - we don't worry about that yet.
771     while (mdlNum < modelFileNames.length
772             && !pdbfile.equals(modelFileNames[mdlNum]))
773     {
774       mdlNum++;
775     }
776     if (mdlNum == modelFileNames.length)
777     {
778       return;
779     }
780
781     jmolHistory(false);
782
783     StringBuilder cmd = new StringBuilder(64);
784     cmd.append("select " + pdbResNum); // +modelNum
785
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(viewer.ms.getModelFileName(mnumber))
895                   .getAbsolutePath();
896         }
897
898       } catch (Exception e)
899       {
900       }
901       ;
902     }
903     if (lastMessage == null || !lastMessage.equals(strInfo))
904     {
905       getSsm().mouseOverStructure(pdbResNum, chainId, pdbfilename);
906     }
907
908     lastMessage = strInfo;
909   }
910
911   public void notifyAtomHovered(int atomIndex, String strInfo, String data)
912   {
913     if (data != null)
914     {
915       System.err.println("Ignoring additional hover info: " + data
916               + " (other info: '" + strInfo + "' pos " + atomIndex + ")");
917     }
918     mouseOverStructure(atomIndex, strInfo);
919   }
920
921   /*
922    * { if (history != null && strStatus != null &&
923    * !strStatus.equals("Script completed")) { history.append("\n" + strStatus);
924    * } }
925    */
926
927   public void notifyAtomPicked(int atomIndex, String strInfo, String strData)
928   {
929     /**
930      * this implements the toggle label behaviour copied from the original
931      * structure viewer, MCView
932      */
933     if (strData != null)
934     {
935       System.err.println("Ignoring additional pick data string " + strData);
936     }
937     int chainSeparator = strInfo.indexOf(":");
938     int p = 0;
939     if (chainSeparator == -1)
940     {
941       chainSeparator = strInfo.indexOf(".");
942     }
943
944     String picked = strInfo.substring(strInfo.indexOf("]") + 1,
945             chainSeparator);
946     String mdlString = "";
947     if ((p = strInfo.indexOf(":")) > -1)
948     {
949       picked += strInfo.substring(p, strInfo.indexOf("."));
950     }
951
952     if ((p = strInfo.indexOf("/")) > -1)
953     {
954       mdlString += strInfo.substring(p, strInfo.indexOf(" #"));
955     }
956     picked = "((" + picked + ".CA" + mdlString + ")|(" + picked + ".P"
957             + mdlString + "))";
958     jmolHistory(false);
959
960     if (!atomsPicked.contains(picked))
961     {
962       viewer.evalStringQuiet("select " + picked + ";label %n %r:%c");
963       atomsPicked.addElement(picked);
964     }
965     else
966     {
967       viewer.evalString("select " + picked + ";label off");
968       atomsPicked.removeElement(picked);
969     }
970     jmolHistory(true);
971     // TODO: in application this happens
972     //
973     // if (scriptWindow != null)
974     // {
975     // scriptWindow.sendConsoleMessage(strInfo);
976     // scriptWindow.sendConsoleMessage("\n");
977     // }
978
979   }
980
981   @Override
982   public void notifyCallback(CBK type, Object[] data)
983   {
984     try
985     {
986       switch (type)
987       {
988       case LOADSTRUCT:
989         notifyFileLoaded((String) data[1], (String) data[2],
990                 (String) data[3], (String) data[4],
991                 ((Integer) data[5]).intValue());
992
993         break;
994       case PICK:
995         notifyAtomPicked(((Integer) data[2]).intValue(), (String) data[1],
996                 (String) data[0]);
997         // also highlight in alignment
998       case HOVER:
999         notifyAtomHovered(((Integer) data[2]).intValue(), (String) data[1],
1000                 (String) data[0]);
1001         break;
1002       case SCRIPT:
1003         notifyScriptTermination((String) data[2],
1004                 ((Integer) data[3]).intValue());
1005         break;
1006       case ECHO:
1007         sendConsoleEcho((String) data[1]);
1008         break;
1009       case MESSAGE:
1010         sendConsoleMessage((data == null) ? ((String) null)
1011                 : (String) data[1]);
1012         break;
1013       case ERROR:
1014         // System.err.println("Ignoring error callback.");
1015         break;
1016       case SYNC:
1017       case RESIZE:
1018         refreshGUI();
1019         break;
1020       case MEASURE:
1021
1022       case CLICK:
1023       default:
1024         System.err.println("Unhandled callback " + type + " "
1025                 + data[1].toString());
1026         break;
1027       }
1028     } catch (Exception e)
1029     {
1030       System.err.println("Squashed Jmol callback handler error:");
1031       e.printStackTrace();
1032     }
1033   }
1034
1035   @Override
1036   public boolean notifyEnabled(CBK callbackPick)
1037   {
1038     switch (callbackPick)
1039     {
1040     case ECHO:
1041     case LOADSTRUCT:
1042     case MEASURE:
1043     case MESSAGE:
1044     case PICK:
1045     case SCRIPT:
1046     case HOVER:
1047     case ERROR:
1048       return true;
1049     default:
1050       return false;
1051     }
1052   }
1053
1054   // incremented every time a load notification is successfully handled -
1055   // lightweight mechanism for other threads to detect when they can start
1056   // referrring to new structures.
1057   private long loadNotifiesHandled = 0;
1058
1059   public long getLoadNotifiesHandled()
1060   {
1061     return loadNotifiesHandled;
1062   }
1063
1064   public void notifyFileLoaded(String fullPathName, String fileName2,
1065           String modelName, String errorMsg, int modelParts)
1066   {
1067     if (errorMsg != null)
1068     {
1069       fileLoadingError = errorMsg;
1070       refreshGUI();
1071       return;
1072     }
1073     // TODO: deal sensibly with models loaded inLine:
1074     // modelName will be null, as will fullPathName.
1075
1076     // the rest of this routine ignores the arguments, and simply interrogates
1077     // the Jmol view to find out what structures it contains, and adds them to
1078     // the structure selection manager.
1079     fileLoadingError = null;
1080     String[] oldmodels = modelFileNames;
1081     modelFileNames = null;
1082     chainNames = new Vector<String>();
1083     chainFile = new Hashtable<String, String>();
1084     boolean notifyLoaded = false;
1085     String[] modelfilenames = getPdbFile();
1086     // first check if we've lost any structures
1087     if (oldmodels != null && oldmodels.length > 0)
1088     {
1089       int oldm = 0;
1090       for (int i = 0; i < oldmodels.length; i++)
1091       {
1092         for (int n = 0; n < modelfilenames.length; n++)
1093         {
1094           if (modelfilenames[n] == oldmodels[i])
1095           {
1096             oldmodels[i] = null;
1097             break;
1098           }
1099         }
1100         if (oldmodels[i] != null)
1101         {
1102           oldm++;
1103         }
1104       }
1105       if (oldm > 0)
1106       {
1107         String[] oldmfn = new String[oldm];
1108         oldm = 0;
1109         for (int i = 0; i < oldmodels.length; i++)
1110         {
1111           if (oldmodels[i] != null)
1112           {
1113             oldmfn[oldm++] = oldmodels[i];
1114           }
1115         }
1116         // deregister the Jmol instance for these structures - we'll add
1117         // ourselves again at the end for the current structure set.
1118         getSsm().removeStructureViewerListener(this, oldmfn);
1119       }
1120     }
1121     refreshPdbEntries();
1122     for (int modelnum = 0; modelnum < modelfilenames.length; modelnum++)
1123     {
1124       String fileName = modelfilenames[modelnum];
1125       boolean foundEntry = false;
1126       StructureFile pdb = null;
1127       String pdbfile = null;
1128       // model was probably loaded inline - so check the pdb file hashcode
1129       if (loadedInline)
1130       {
1131         // calculate essential attributes for the pdb data imported inline.
1132         // prolly need to resolve modelnumber properly - for now just use our
1133         // 'best guess'
1134         pdbfile = viewer.getData("" + (1 + _modelFileNameMap[modelnum])
1135                 + ".0", "PDB");
1136       }
1137       // search pdbentries and sequences to find correct pdbentry for this
1138       // model
1139       for (int pe = 0; pe < getPdbCount(); pe++)
1140       {
1141         boolean matches = false;
1142         if (fileName == null)
1143         {
1144           if (false)
1145           // see JAL-623 - need method of matching pasted data up
1146           {
1147             pdb = getSsm().setMapping(getSequence()[pe], getChains()[pe],
1148                     pdbfile, AppletFormatAdapter.PASTE);
1149             getPdbEntry(modelnum).setFile("INLINE" + pdb.getId());
1150             matches = true;
1151             foundEntry = true;
1152           }
1153         }
1154         else
1155         {
1156           File fl = new File(getPdbEntry(pe).getFile());
1157           matches = fl.equals(new File(fileName));
1158           if (matches)
1159           {
1160             foundEntry = true;
1161             // TODO: Jmol can in principle retrieve from CLASSLOADER but
1162             // this
1163             // needs
1164             // to be tested. See mantis bug
1165             // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
1166             String protocol = AppletFormatAdapter.URL;
1167             try
1168             {
1169               if (fl.exists())
1170               {
1171                 protocol = AppletFormatAdapter.FILE;
1172               }
1173             } catch (Exception e)
1174             {
1175             } catch (Error e)
1176             {
1177             }
1178             // Explicitly map to the filename used by Jmol ;
1179             pdb = getSsm().setMapping(getSequence()[pe], getChains()[pe],
1180                     fileName, protocol);
1181             // pdbentry[pe].getFile(), protocol);
1182
1183           }
1184         }
1185         if (matches)
1186         {
1187           // add an entry for every chain in the model
1188           for (int i = 0; i < pdb.getChains().size(); i++)
1189           {
1190             String chid = new String(pdb.getId() + ":"
1191                     + pdb.getChains().elementAt(i).id);
1192             chainFile.put(chid, fileName);
1193             chainNames.addElement(chid);
1194           }
1195           notifyLoaded = true;
1196         }
1197       }
1198
1199       if (!foundEntry && associateNewStructs)
1200       {
1201         // this is a foreign pdb file that jalview doesn't know about - add
1202         // it to the dataset and try to find a home - either on a matching
1203         // sequence or as a new sequence.
1204         String pdbcontent = viewer.getData("/" + (modelnum + 1) + ".1",
1205                 "PDB");
1206         // parse pdb file into a chain, etc.
1207         // locate best match for pdb in associated views and add mapping to
1208         // ssm
1209         // if properly registered then
1210         notifyLoaded = true;
1211
1212       }
1213     }
1214     // FILE LOADED OK
1215     // so finally, update the jmol bits and pieces
1216     // if (jmolpopup != null)
1217     // {
1218     // // potential for deadlock here:
1219     // // jmolpopup.updateComputedMenus();
1220     // }
1221     if (!isLoadingFromArchive())
1222     {
1223       viewer.evalStringQuiet("model *; select backbone;restrict;cartoon;wireframe off;spacefill off");
1224     }
1225     // register ourselves as a listener and notify the gui that it needs to
1226     // update itself.
1227     getSsm().addStructureViewerListener(this);
1228     if (notifyLoaded)
1229     {
1230       FeatureRenderer fr = getFeatureRenderer(null);
1231       if (fr != null)
1232       {
1233         fr.featuresAdded();
1234       }
1235       refreshGUI();
1236       loadNotifiesHandled++;
1237     }
1238     setLoadingFromArchive(false);
1239   }
1240
1241   public void notifyNewPickingModeMeasurement(int iatom, String strMeasure)
1242   {
1243     notifyAtomPicked(iatom, strMeasure, null);
1244   }
1245
1246   public abstract void notifyScriptTermination(String strStatus,
1247           int msWalltime);
1248
1249   /**
1250    * display a message echoed from the jmol viewer
1251    * 
1252    * @param strEcho
1253    */
1254   public abstract void sendConsoleEcho(String strEcho); /*
1255                                                          * { showConsole(true);
1256                                                          * 
1257                                                          * history.append("\n" +
1258                                                          * strEcho); }
1259                                                          */
1260
1261   // /End JmolStatusListener
1262   // /////////////////////////////
1263
1264   /**
1265    * @param strStatus
1266    *          status message - usually the response received after a script
1267    *          executed
1268    */
1269   public abstract void sendConsoleMessage(String strStatus);
1270
1271   @Override
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 }