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