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