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