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