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