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