localizes Thread colourby so that it does not cause ThreadStateException
[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.security.AccessControlException;
48 import java.util.ArrayList;
49 import java.util.BitSet;
50 import java.util.Hashtable;
51 import java.util.List;
52 import java.util.Map;
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   boolean allChainsSelected = false;
69
70   /*
71    * when true, try to search the associated datamodel for sequences that are
72    * associated with any unknown structures in the Jmol view.
73    */
74   private boolean associateNewStructs = false;
75
76   Vector<String> atomsPicked = new Vector<>();
77
78   private List<String> chainNames;
79
80   Hashtable<String, String> chainFile;
81
82   /*
83    * the default or current model displayed if the model cannot be identified
84    * from the selection message
85    */
86   int frameNo = 0;
87
88   // protected JmolGenericPopup jmolpopup; // not used - remove?
89
90   String lastCommand;
91
92   String lastMessage;
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   // ////////////////////////////////
623   // /StructureListener
624   // @Override
625   public synchronized String[] getPdbFilex()
626   {
627     if (viewer == null)
628     {
629       return new String[0];
630     }
631     if (modelFileNames == null)
632     {
633       List<String> mset = new ArrayList<>();
634       _modelFileNameMap = new int[viewer.ms.mc];
635       String m = viewer.ms.getModelFileName(0);
636       if (m != null)
637       {
638         String filePath = m;
639         try
640         {
641           filePath = new File(m).getAbsolutePath();
642         } catch (AccessControlException x)
643         {
644           // usually not allowed to do this in applet
645           System.err.println(
646                   "jmolBinding: Using local file string from Jmol: " + m);
647         }
648         if (filePath.indexOf("/file:") != -1)
649         {
650           // applet path with docroot - discard as format won't match pdbfile
651           filePath = m;
652         }
653         mset.add(filePath);
654         _modelFileNameMap[0] = 0; // filename index for first model is always 0.
655       }
656       int j = 1;
657       for (int i = 1; i < viewer.ms.mc; i++)
658       {
659         m = viewer.ms.getModelFileName(i);
660         String filePath = m;
661         if (m != null)
662         {
663           try
664           {
665             filePath = new File(m).getAbsolutePath();
666           } catch (AccessControlException x)
667           {
668             // usually not allowed to do this in applet, so keep raw handle
669             // System.err.println("jmolBinding: Using local file string from
670             // Jmol: "+m);
671           }
672         }
673
674         /*
675          * add this model unless it is read from a structure file we have
676          * already seen (example: 2MJW is an NMR structure with 10 models)
677          */
678         if (!mset.contains(filePath))
679         {
680           mset.add(filePath);
681           _modelFileNameMap[j] = i; // record the model index for the filename
682           j++;
683         }
684       }
685       modelFileNames = mset.toArray(new String[mset.size()]);
686     }
687     return modelFileNames;
688   }
689
690   @Override
691   public synchronized String[] getStructureFiles()
692   {
693     List<String> mset = new ArrayList<>();
694     if (viewer == null)
695     {
696       return new String[0];
697     }
698
699     if (modelFileNames == null)
700     {
701       int modelCount = viewer.ms.mc;
702       String filePath = null;
703       for (int i = 0; i < modelCount; ++i)
704       {
705         filePath = viewer.ms.getModelFileName(i);
706         if (!mset.contains(filePath))
707         {
708           mset.add(filePath);
709         }
710       }
711       modelFileNames = mset.toArray(new String[mset.size()]);
712     }
713
714     return modelFileNames;
715   }
716
717   /**
718    * map from string to applet
719    */
720   @Override
721   public Map<String, Object> getRegistryInfo()
722   {
723     // TODO Auto-generated method stub
724     return null;
725   }
726
727   // ///////////////////////////////
728   // JmolStatusListener
729
730   public void handlePopupMenu(int x, int y)
731   {
732     // jmolpopup.show(x, y);
733     // jmolpopup.jpiShow(x, y);
734   }
735
736   /**
737    * Highlight zero, one or more atoms on the structure
738    */
739   @Override
740   public void highlightAtoms(List<AtomSpec> atoms)
741   {
742     if (atoms != null)
743     {
744       if (resetLastRes.length() > 0)
745       {
746         jmolScript(resetLastRes.toString());
747         resetLastRes.setLength(0);
748       }
749       for (AtomSpec atom : atoms)
750       {
751         highlightAtom(atom.getAtomIndex(), atom.getPdbResNum(),
752                 atom.getChain(), atom.getPdbFile());
753       }
754     }
755   }
756
757   // jmol/ssm only
758   public void highlightAtom(int atomIndex, int pdbResNum, String chain,
759           String pdbfile)
760   {
761     if (modelFileNames == null)
762     {
763       return;
764     }
765
766     // look up file model number for this pdbfile
767     int mdlNum = 0;
768     // may need to adjust for URLencoding here - we don't worry about that yet.
769     while (mdlNum < modelFileNames.length
770             && !pdbfile.equals(modelFileNames[mdlNum]))
771     {
772       mdlNum++;
773     }
774     if (mdlNum == modelFileNames.length)
775     {
776       return;
777     }
778
779     jmolHistory(false);
780
781     StringBuilder cmd = new StringBuilder(64);
782     cmd.append("select " + pdbResNum); // +modelNum
783
784     resetLastRes.append("select " + pdbResNum); // +modelNum
785
786     cmd.append(":");
787     resetLastRes.append(":");
788     if (!chain.equals(" "))
789     {
790       cmd.append(chain);
791       resetLastRes.append(chain);
792     }
793     {
794       cmd.append(" /" + (mdlNum + 1));
795       resetLastRes.append("/" + (mdlNum + 1));
796     }
797     cmd.append(";wireframe 100;" + cmd.toString() + " and not hetero;");
798
799     resetLastRes.append(";wireframe 0;" + resetLastRes.toString()
800             + " and not hetero; spacefill 0;");
801
802     cmd.append("spacefill 200;select none");
803
804     jmolScript(cmd.toString());
805     jmolHistory(true);
806
807   }
808
809   boolean debug = true;
810
811   private void jmolHistory(boolean enable)
812   {
813     jmolScript("History " + ((debug || enable) ? "on" : "off"));
814   }
815
816   public void loadInline(String string)
817   {
818     loadedInline = true;
819     // TODO: re JAL-623
820     // viewer.loadInline(strModel, isAppend);
821     // could do this:
822     // construct fake fullPathName and fileName so we can identify the file
823     // later.
824     // Then, construct pass a reader for the string to Jmol.
825     // ((org.jmol.Viewer.Viewer) viewer).loadModelFromFile(fullPathName,
826     // fileName, null, reader, false, null, null, 0);
827     viewer.openStringInline(string);
828   }
829
830   public void mouseOverStructure(int atomIndex, String strInfo)
831   {
832     int pdbResNum;
833     int alocsep = strInfo.indexOf("^");
834     int mdlSep = strInfo.indexOf("/");
835     int chainSeparator = strInfo.indexOf(":"), chainSeparator1 = -1;
836
837     if (chainSeparator == -1)
838     {
839       chainSeparator = strInfo.indexOf(".");
840       if (mdlSep > -1 && mdlSep < chainSeparator)
841       {
842         chainSeparator1 = chainSeparator;
843         chainSeparator = mdlSep;
844       }
845     }
846     // handle insertion codes
847     if (alocsep != -1)
848     {
849       pdbResNum = Integer.parseInt(
850               strInfo.substring(strInfo.indexOf("]") + 1, alocsep));
851
852     }
853     else
854     {
855       pdbResNum = Integer.parseInt(
856               strInfo.substring(strInfo.indexOf("]") + 1, chainSeparator));
857     }
858     String chainId;
859
860     if (strInfo.indexOf(":") > -1)
861     {
862       chainId = strInfo.substring(strInfo.indexOf(":") + 1,
863               strInfo.indexOf("."));
864     }
865     else
866     {
867       chainId = " ";
868     }
869
870     String pdbfilename = modelFileNames[frameNo]; // default is first or current
871     // model
872     if (mdlSep > -1)
873     {
874       if (chainSeparator1 == -1)
875       {
876         chainSeparator1 = strInfo.indexOf(".", mdlSep);
877       }
878       String mdlId = (chainSeparator1 > -1)
879               ? strInfo.substring(mdlSep + 1, chainSeparator1)
880               : strInfo.substring(mdlSep + 1);
881       try
882       {
883         // recover PDB filename for the model hovered over.
884         int mnumber = new Integer(mdlId).intValue() - 1;
885         if (_modelFileNameMap != null)
886         {
887           int _mp = _modelFileNameMap.length - 1;
888
889           while (mnumber < _modelFileNameMap[_mp])
890           {
891             _mp--;
892           }
893           pdbfilename = modelFileNames[_mp];
894         }
895         else
896         {
897           if (mnumber >= 0 && mnumber < modelFileNames.length)
898           {
899             pdbfilename = modelFileNames[mnumber];
900           }
901
902           if (pdbfilename == null)
903           {
904             pdbfilename = new File(viewer.ms.getModelFileName(mnumber))
905                     .getAbsolutePath();
906           }
907         }
908       } catch (Exception e)
909       {
910       }
911       ;
912     }
913     if (lastMessage == null || !lastMessage.equals(strInfo))
914     {
915       getSsm().mouseOverStructure(pdbResNum, chainId, pdbfilename);
916     }
917
918     lastMessage = strInfo;
919   }
920
921   public void notifyAtomHovered(int atomIndex, String strInfo, String data)
922   {
923     if (data != null)
924     {
925       System.err.println("Ignoring additional hover info: " + data
926               + " (other info: '" + strInfo + "' pos " + atomIndex + ")");
927     }
928     mouseOverStructure(atomIndex, strInfo);
929   }
930
931   /*
932    * { if (history != null && strStatus != null &&
933    * !strStatus.equals("Script completed")) { history.append("\n" + strStatus);
934    * } }
935    */
936
937   public void notifyAtomPicked(int atomIndex, String strInfo,
938           String strData)
939   {
940     /**
941      * this implements the toggle label behaviour copied from the original
942      * structure viewer, mc_view
943      */
944     if (strData != null)
945     {
946       System.err.println("Ignoring additional pick data string " + strData);
947     }
948     int chainSeparator = strInfo.indexOf(":");
949     int p = 0;
950     if (chainSeparator == -1)
951     {
952       chainSeparator = strInfo.indexOf(".");
953     }
954
955     String picked = strInfo.substring(strInfo.indexOf("]") + 1,
956             chainSeparator);
957     String mdlString = "";
958     if ((p = strInfo.indexOf(":")) > -1)
959     {
960       picked += strInfo.substring(p, strInfo.indexOf("."));
961     }
962
963     if ((p = strInfo.indexOf("/")) > -1)
964     {
965       mdlString += strInfo.substring(p, strInfo.indexOf(" #"));
966     }
967     picked = "((" + picked + ".CA" + mdlString + ")|(" + picked + ".P"
968             + mdlString + "))";
969     jmolHistory(false);
970
971     if (!atomsPicked.contains(picked))
972     {
973       jmolScript("select " + picked + ";label %n %r:%c");
974       atomsPicked.addElement(picked);
975     }
976     else
977     {
978       viewer.evalString("select " + picked + ";label off");
979       atomsPicked.removeElement(picked);
980     }
981     jmolHistory(true);
982     // TODO: in application this happens
983     //
984     // if (scriptWindow != null)
985     // {
986     // scriptWindow.sendConsoleMessage(strInfo);
987     // scriptWindow.sendConsoleMessage("\n");
988     // }
989
990   }
991
992   @Override
993   public void notifyCallback(CBK type, Object[] data)
994   {
995     try
996     {
997       switch (type)
998       {
999       case LOADSTRUCT:
1000         notifyFileLoaded((String) data[1], (String) data[2],
1001                 (String) data[3], (String) data[4],
1002                 ((Integer) data[5]).intValue());
1003
1004         break;
1005       case PICK:
1006         notifyAtomPicked(((Integer) data[2]).intValue(), (String) data[1],
1007                 (String) data[0]);
1008         // also highlight in alignment
1009         // deliberate fall through
1010       case HOVER:
1011         notifyAtomHovered(((Integer) data[2]).intValue(), (String) data[1],
1012                 (String) data[0]);
1013         break;
1014       case SCRIPT:
1015         notifyScriptTermination((String) data[2],
1016                 ((Integer) data[3]).intValue());
1017         break;
1018       case ECHO:
1019         sendConsoleEcho((String) data[1]);
1020         break;
1021       case MESSAGE:
1022         sendConsoleMessage(
1023                 (data == null) ? ((String) null) : (String) data[1]);
1024         break;
1025       case ERROR:
1026         // System.err.println("Ignoring error callback.");
1027         break;
1028       case SYNC:
1029       case RESIZE:
1030         refreshGUI();
1031         break;
1032       case MEASURE:
1033
1034       case CLICK:
1035       default:
1036         System.err.println(
1037                 "Unhandled callback " + type + " " + data[1].toString());
1038         break;
1039       }
1040     } catch (Exception e)
1041     {
1042       System.err.println("Squashed Jmol callback handler error:");
1043       e.printStackTrace();
1044     }
1045   }
1046
1047   @Override
1048   public boolean notifyEnabled(CBK callbackPick)
1049   {
1050     switch (callbackPick)
1051     {
1052     case ECHO:
1053     case LOADSTRUCT:
1054     case MEASURE:
1055     case MESSAGE:
1056     case PICK:
1057     case SCRIPT:
1058     case HOVER:
1059     case ERROR:
1060       return true;
1061     default:
1062       return false;
1063     }
1064   }
1065
1066   // incremented every time a load notification is successfully handled -
1067   // lightweight mechanism for other threads to detect when they can start
1068   // referrring to new structures.
1069   private long loadNotifiesHandled = 0;
1070
1071   public long getLoadNotifiesHandled()
1072   {
1073     return loadNotifiesHandled;
1074   }
1075
1076   public void notifyFileLoaded(String fullPathName, String fileName2,
1077           String modelName, String errorMsg, int modelParts)
1078   {
1079     if (errorMsg != null)
1080     {
1081       fileLoadingError = errorMsg;
1082       refreshGUI();
1083       return;
1084     }
1085     // TODO: deal sensibly with models loaded inLine:
1086     // modelName will be null, as will fullPathName.
1087
1088     // the rest of this routine ignores the arguments, and simply interrogates
1089     // the Jmol view to find out what structures it contains, and adds them to
1090     // the structure selection manager.
1091     fileLoadingError = null;
1092     String[] oldmodels = modelFileNames;
1093     modelFileNames = null;
1094     chainNames = new ArrayList<>();
1095     chainFile = new Hashtable<>();
1096     boolean notifyLoaded = false;
1097     String[] modelfilenames = getStructureFiles();
1098     // first check if we've lost any structures
1099     if (oldmodels != null && oldmodels.length > 0)
1100     {
1101       int oldm = 0;
1102       for (int i = 0; i < oldmodels.length; i++)
1103       {
1104         for (int n = 0; n < modelfilenames.length; n++)
1105         {
1106           if (modelfilenames[n] == oldmodels[i])
1107           {
1108             oldmodels[i] = null;
1109             break;
1110           }
1111         }
1112         if (oldmodels[i] != null)
1113         {
1114           oldm++;
1115         }
1116       }
1117       if (oldm > 0)
1118       {
1119         String[] oldmfn = new String[oldm];
1120         oldm = 0;
1121         for (int i = 0; i < oldmodels.length; i++)
1122         {
1123           if (oldmodels[i] != null)
1124           {
1125             oldmfn[oldm++] = oldmodels[i];
1126           }
1127         }
1128         // deregister the Jmol instance for these structures - we'll add
1129         // ourselves again at the end for the current structure set.
1130         getSsm().removeStructureViewerListener(this, oldmfn);
1131       }
1132     }
1133     refreshPdbEntries();
1134     for (int modelnum = 0; modelnum < modelfilenames.length; modelnum++)
1135     {
1136       String fileName = modelfilenames[modelnum];
1137       boolean foundEntry = false;
1138       StructureFile pdb = null;
1139       String pdbfile = null;
1140       // model was probably loaded inline - so check the pdb file hashcode
1141       if (loadedInline)
1142       {
1143         // calculate essential attributes for the pdb data imported inline.
1144         // prolly need to resolve modelnumber properly - for now just use our
1145         // 'best guess'
1146         pdbfile = viewer.getData(
1147                 "" + (1 + _modelFileNameMap[modelnum]) + ".0", "PDB");
1148       }
1149       // search pdbentries and sequences to find correct pdbentry for this
1150       // model
1151       for (int pe = 0; pe < getPdbCount(); pe++)
1152       {
1153         boolean matches = false;
1154         addSequence(pe, getSequence()[pe]);
1155         if (fileName == null)
1156         {
1157           if (false)
1158           // see JAL-623 - need method of matching pasted data up
1159           {
1160             pdb = getSsm().setMapping(getSequence()[pe], getChains()[pe],
1161                     pdbfile, DataSourceType.PASTE, getIProgressIndicator());
1162             getPdbEntry(modelnum).setFile("INLINE" + pdb.getId());
1163             matches = true;
1164             foundEntry = true;
1165           }
1166         }
1167         else
1168         {
1169           File fl = new File(getPdbEntry(pe).getFile());
1170           matches = fl.equals(new File(fileName));
1171           if (matches)
1172           {
1173             foundEntry = true;
1174             // TODO: Jmol can in principle retrieve from CLASSLOADER but
1175             // this
1176             // needs
1177             // to be tested. See mantis bug
1178             // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
1179             DataSourceType protocol = DataSourceType.URL;
1180             try
1181             {
1182               if (fl.exists())
1183               {
1184                 protocol = DataSourceType.FILE;
1185               }
1186             } catch (Exception e)
1187             {
1188             } catch (Error e)
1189             {
1190             }
1191             // Explicitly map to the filename used by Jmol ;
1192             pdb = getSsm().setMapping(getSequence()[pe], getChains()[pe],
1193                     fileName, protocol, getIProgressIndicator());
1194             // pdbentry[pe].getFile(), protocol);
1195
1196           }
1197         }
1198         if (matches)
1199         {
1200           // add an entry for every chain in the model
1201           for (int i = 0; i < pdb.getChains().size(); i++)
1202           {
1203             String chid = new String(
1204                     pdb.getId() + ":" + pdb.getChains().elementAt(i).id);
1205             chainFile.put(chid, fileName);
1206             chainNames.add(chid);
1207           }
1208           notifyLoaded = true;
1209         }
1210       }
1211
1212       if (!foundEntry && associateNewStructs)
1213       {
1214         // this is a foreign pdb file that jalview doesn't know about - add
1215         // it to the dataset and try to find a home - either on a matching
1216         // sequence or as a new sequence.
1217         String pdbcontent = viewer.getData("/" + (modelnum + 1) + ".1",
1218                 "PDB");
1219         // parse pdb file into a chain, etc.
1220         // locate best match for pdb in associated views and add mapping to
1221         // ssm
1222         // if properly registered then
1223         notifyLoaded = true;
1224
1225       }
1226     }
1227     // FILE LOADED OK
1228     // so finally, update the jmol bits and pieces
1229     // if (jmolpopup != null)
1230     // {
1231     // // potential for deadlock here:
1232     // // jmolpopup.updateComputedMenus();
1233     // }
1234     if (!isLoadingFromArchive())
1235     {
1236       jmolScript(
1237               "model *; select backbone;restrict;cartoon;wireframe off;spacefill off");
1238     }
1239     // register ourselves as a listener and notify the gui that it needs to
1240     // update itself.
1241     getSsm().addStructureViewerListener(this);
1242     if (notifyLoaded)
1243     {
1244       FeatureRenderer fr = getFeatureRenderer(null);
1245       if (fr != null)
1246       {
1247         fr.featuresAdded();
1248       }
1249       refreshGUI();
1250       loadNotifiesHandled++;
1251     }
1252     setLoadingFromArchive(false);
1253   }
1254
1255   @Override
1256   public List<String> getChainNames()
1257   {
1258     return chainNames;
1259   }
1260
1261   protected IProgressIndicator getIProgressIndicator()
1262   {
1263     return null;
1264   }
1265
1266   public void notifyNewPickingModeMeasurement(int iatom, String strMeasure)
1267   {
1268     notifyAtomPicked(iatom, strMeasure, null);
1269   }
1270
1271   public abstract void notifyScriptTermination(String strStatus,
1272           int msWalltime);
1273
1274   /**
1275    * display a message echoed from the jmol viewer
1276    * 
1277    * @param strEcho
1278    */
1279   public abstract void sendConsoleEcho(String strEcho); /*
1280                                                          * { showConsole(true);
1281                                                          * 
1282                                                          * history.append("\n" +
1283                                                          * strEcho); }
1284                                                          */
1285
1286   // /End JmolStatusListener
1287   // /////////////////////////////
1288
1289   /**
1290    * @param strStatus
1291    *          status message - usually the response received after a script
1292    *          executed
1293    */
1294   public abstract void sendConsoleMessage(String strStatus);
1295
1296   @Override
1297   public void setCallbackFunction(String callbackType,
1298           String callbackFunction)
1299   {
1300     System.err.println("Ignoring set-callback request to associate "
1301             + callbackType + " with function " + callbackFunction);
1302
1303   }
1304
1305   @Override
1306   public void setJalviewColourScheme(ColourSchemeI cs)
1307   {
1308     colourBySequence = false;
1309
1310     if (cs == null)
1311     {
1312       return;
1313     }
1314
1315     jmolHistory(false);
1316     StringBuilder command = new StringBuilder(128);
1317     command.append("select *;color white;");
1318     List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
1319             false);
1320     for (String resName : residueSet)
1321     {
1322       char res = resName.length() == 3
1323               ? ResidueProperties.getSingleCharacterCode(resName)
1324               : resName.charAt(0);
1325       Color col = cs.findColour(res, 0, null, null, 0f);
1326       command.append("select " + resName + ";color[" + col.getRed() + ","
1327               + col.getGreen() + "," + col.getBlue() + "];");
1328     }
1329
1330     evalStateCommand(command.toString());
1331     jmolHistory(true);
1332   }
1333
1334   public void showHelp()
1335   {
1336     showUrl("http://wiki.jmol.org"
1337     // BH 2018 "http://jmol.sourceforge.net/docs/JmolUserGuide/"
1338             , "jmolHelp");
1339   }
1340
1341   /**
1342    * open the URL somehow
1343    * 
1344    * @param target
1345    */
1346   public abstract void showUrl(String url, String target);
1347
1348   /**
1349    * called when the binding thinks the UI needs to be refreshed after a Jmol
1350    * state change. this could be because structures were loaded, or because an
1351    * error has occured.
1352    */
1353   public abstract void refreshGUI();
1354
1355   /**
1356    * called to show or hide the associated console window container.
1357    * 
1358    * @param show
1359    */
1360   public abstract void showConsole(boolean show);
1361
1362   public static Viewer getJmolData(JmolParser jmolParser)
1363   {
1364     return (Viewer) JmolViewer.allocateViewer(null, null, null, null, null,
1365             "-x -o -n", jmolParser);
1366   }
1367
1368   /**
1369    * 
1370    * 
1371    * 
1372    * @param renderPanel
1373    * @param jmolfileio
1374    *          - when true will initialise jmol's file IO system (should be false
1375    *          in applet context)
1376    * @param htmlName
1377    * @param documentBase
1378    * @param codeBase
1379    * @param commandOptions
1380    */
1381   public void allocateViewer(Container renderPanel, boolean jmolfileio,
1382           String htmlName, URL documentBase, URL codeBase,
1383           String commandOptions)
1384   {
1385     allocateViewer(renderPanel, jmolfileio, htmlName, documentBase,
1386             codeBase, commandOptions, null, null);
1387   }
1388
1389   /**
1390    * 
1391    * @param renderPanel
1392    * @param jmolfileio
1393    *          - when true will initialise jmol's file IO system (should be false
1394    *          in applet context)
1395    * @param htmlName
1396    * @param documentBase
1397    * @param codeBase
1398    * @param commandOptions
1399    * @param consolePanel
1400    *          - panel to contain Jmol console
1401    * @param buttonsToShow
1402    *          - buttons to show on the console, in order
1403    */
1404   public void allocateViewer(Container renderPanel, boolean jmolfileio,
1405           String htmlName, URL documentBase, URL codeBase,
1406           String commandOptions, final Container consolePanel,
1407           String buttonsToShow)
1408   {
1409
1410     System.err.println("Allocating Jmol Viewer: " + commandOptions);
1411
1412     if (commandOptions == null)
1413     {
1414       commandOptions = "";
1415     }
1416     viewer = (Viewer) JmolViewer.allocateViewer(renderPanel,
1417             (jmolfileio ? new SmarterJmolAdapter() : null),
1418             htmlName + ((Object) this).toString(), documentBase, codeBase,
1419             commandOptions, this);
1420
1421     viewer.setJmolStatusListener(this); // extends JmolCallbackListener
1422
1423     try
1424     {
1425       console = createJmolConsole(consolePanel, buttonsToShow);
1426     } catch (Throwable e)
1427     {
1428       System.err.println("Could not create Jmol application console. "
1429               + e.getMessage());
1430       e.printStackTrace();
1431     }
1432     if (consolePanel != null)
1433     {
1434       consolePanel.addComponentListener(this);
1435
1436     }
1437
1438   }
1439
1440   protected abstract JmolAppConsoleInterface createJmolConsole(
1441           Container consolePanel, String buttonsToShow);
1442
1443   // BH 2018 -- Jmol console is not working due to problems with styled
1444   // documents.
1445
1446   protected org.jmol.api.JmolAppConsoleInterface console = null;
1447
1448   @Override
1449   public void setBackgroundColour(java.awt.Color col)
1450   {
1451     jmolHistory(false);
1452     jmolScript("background [" + col.getRed() + "," + col.getGreen() + ","
1453             + col.getBlue() + "];");
1454     jmolHistory(true);
1455   }
1456
1457   private String jmolScript(String script)
1458   {
1459
1460     System.err.println(">>Jmol>> " + script);
1461
1462     String s = viewer.scriptWait(script);
1463
1464     System.err.println("<<Jmol<< " + s);
1465
1466     return s;
1467   }
1468
1469   @Override
1470   public int[] resizeInnerPanel(String data)
1471   {
1472     // Jalview doesn't honour resize panel requests
1473     return null;
1474   }
1475
1476   /**
1477    * 
1478    */
1479   protected void closeConsole()
1480   {
1481     if (console != null)
1482     {
1483       try
1484       {
1485         console.setVisible(false);
1486       } catch (Error e)
1487       {
1488       } catch (Exception x)
1489       {
1490       }
1491       ;
1492       console = null;
1493     }
1494   }
1495
1496   /**
1497    * ComponentListener method
1498    */
1499   @Override
1500   public void componentMoved(ComponentEvent e)
1501   {
1502   }
1503
1504   /**
1505    * ComponentListener method
1506    */
1507   @Override
1508   public void componentResized(ComponentEvent e)
1509   {
1510   }
1511
1512   /**
1513    * ComponentListener method
1514    */
1515   @Override
1516   public void componentShown(ComponentEvent e)
1517   {
1518     showConsole(true);
1519   }
1520
1521   /**
1522    * ComponentListener method
1523    */
1524   @Override
1525   public void componentHidden(ComponentEvent e)
1526   {
1527     showConsole(false);
1528   }
1529
1530 }