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