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