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