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