JAL-3390 new View menu option to hide hidden regions in structure
[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.gui.IProgressIndicator;
31 import jalview.io.DataSourceType;
32 import jalview.io.StructureFile;
33 import jalview.schemes.ColourSchemeI;
34 import jalview.schemes.ResidueProperties;
35 import jalview.structure.AtomSpec;
36 import jalview.structure.StructureMappingcommandSet;
37 import jalview.structure.StructureSelectionManager;
38 import jalview.structures.models.AAStructureBindingModel;
39 import jalview.util.MessageManager;
40
41 import java.awt.Color;
42 import java.awt.Container;
43 import java.awt.event.ComponentEvent;
44 import java.awt.event.ComponentListener;
45 import java.io.File;
46 import java.net.URL;
47 import java.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.Vector;
53
54 import org.jmol.adapter.smarter.SmarterJmolAdapter;
55 import org.jmol.api.JmolAppConsoleInterface;
56 import org.jmol.api.JmolSelectionListener;
57 import org.jmol.api.JmolStatusListener;
58 import org.jmol.api.JmolViewer;
59 import org.jmol.c.CBK;
60 import org.jmol.script.T;
61 import org.jmol.viewer.Viewer;
62
63 public abstract class JalviewJmolBinding extends AAStructureBindingModel
64         implements JmolStatusListener, JmolSelectionListener,
65         ComponentListener
66 {
67   boolean allChainsSelected = false;
68
69   /*
70    * when true, try to search the associated datamodel for sequences that are
71    * associated with any unknown structures in the Jmol view.
72    */
73   private boolean associateNewStructs = false;
74
75   Vector<String> atomsPicked = new Vector<>();
76
77   private List<String> chainNames;
78
79   Hashtable<String, String> chainFile;
80
81   /*
82    * the default or current model displayed if the model cannot be identified
83    * from the selection message
84    */
85   int frameNo = 0;
86
87   // protected JmolGenericPopup jmolpopup; // not used - remove?
88
89   String lastCommand;
90
91   String lastMessage;
92
93   boolean loadedInline;
94
95   StringBuffer resetLastRes = new StringBuffer();
96
97   public Viewer viewer;
98
99   public JalviewJmolBinding(StructureSelectionManager ssm,
100           PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
101           DataSourceType protocol)
102   {
103     super(ssm, pdbentry, sequenceIs, protocol);
104     /*
105      * viewer = JmolViewer.allocateViewer(renderPanel, new SmarterJmolAdapter(),
106      * "jalviewJmol", ap.av.applet .getDocumentBase(),
107      * ap.av.applet.getCodeBase(), "", this);
108      * 
109      * jmolpopup = JmolPopup.newJmolPopup(viewer, true, "Jmol", true);
110      */
111   }
112
113   public JalviewJmolBinding(StructureSelectionManager ssm,
114           SequenceI[][] seqs, Viewer theViewer)
115   {
116     super(ssm, seqs);
117
118     viewer = theViewer;
119     viewer.setJmolStatusListener(this);
120     viewer.addSelectionListener(this);
121   }
122
123   /**
124    * construct a title string for the viewer window based on the data jalview
125    * knows about
126    * 
127    * @return
128    */
129   public String getViewerTitle()
130   {
131     return getViewerTitle("Jmol", true);
132   }
133
134   /**
135    * prepare the view for a given set of models/chains. chainList contains
136    * strings of the form 'pdbfilename:Chaincode'
137    */
138   public void centerViewer()
139   {
140     StringBuilder cmd = new StringBuilder(128);
141     int mlength, p;
142     for (String lbl : chainsToShow)
143     {
144       mlength = 0;
145       do
146       {
147         p = mlength;
148         mlength = lbl.indexOf(":", p);
149       } while (p < mlength && mlength < (lbl.length() - 2));
150       // TODO: lookup each pdb id and recover proper model number for it.
151       cmd.append(":" + lbl.substring(mlength + 1) + " /"
152               + (1 + getModelNum(chainFile.get(lbl))) + " or ");
153     }
154     if (cmd.length() > 0)
155     {
156       cmd.setLength(cmd.length() - 4);
157     }
158     String command = "select *;restrict " + cmd + ";cartoon;center " + cmd;
159     evalStateCommand(command);
160   }
161
162   public void closeViewer()
163   {
164     // remove listeners for all structures in viewer
165     getSsm().removeStructureViewerListener(this, this.getStructureFiles());
166     viewer.dispose();
167     lastCommand = null;
168     viewer = null;
169     releaseUIResources();
170   }
171
172   @Override
173   public void colourByChain()
174   {
175     colourBySequence = false;
176     // TODO: colour by chain should colour each chain distinctly across all
177     // visible models
178     // TODO: http://issues.jalview.org/browse/JAL-628
179     evalStateCommand("select *;color chain");
180   }
181
182   @Override
183   public void colourByCharge()
184   {
185     colourBySequence = false;
186     evalStateCommand("select *;color white;select ASP,GLU;color red;"
187             + "select LYS,ARG;color blue;select CYS;color yellow");
188   }
189
190   /**
191    * superpose the structures associated with sequences in the alignment
192    * according to their corresponding positions.
193    */
194   public void superposeStructures(AlignmentI alignment)
195   {
196     superposeStructures(alignment, -1, null);
197   }
198
199   /**
200    * superpose the structures associated with sequences in the alignment
201    * according to their corresponding positions. ded)
202    * 
203    * @param refStructure
204    *          - select which pdb file to use as reference (default is -1 - the
205    *          first structure in the alignment)
206    */
207   public void superposeStructures(AlignmentI alignment, int refStructure)
208   {
209     superposeStructures(alignment, refStructure, null);
210   }
211
212   /**
213    * superpose the structures associated with sequences in the alignment
214    * according to their corresponding positions. ded)
215    * 
216    * @param refStructure
217    *          - select which pdb file to use as reference (default is -1 - the
218    *          first structure in the alignment)
219    * @param hiddenCols
220    *          TODO
221    */
222   public void superposeStructures(AlignmentI alignment, int refStructure,
223           HiddenColumns hiddenCols)
224   {
225     superposeStructures(new AlignmentI[] { alignment },
226             new int[]
227             { refStructure }, new HiddenColumns[] { hiddenCols });
228   }
229
230   /**
231    * {@inheritDoc}
232    */
233   @Override
234   public String superposeStructures(AlignmentI[] _alignment,
235           int[] _refStructure, HiddenColumns[] _hiddenCols)
236   {
237     while (viewer.isScriptExecuting())
238     {
239       try
240       {
241         Thread.sleep(10);
242       } catch (InterruptedException i)
243       {
244       }
245     }
246
247     /*
248      * get the distinct structure files modelled
249      * (a file with multiple chains may map to multiple sequences)
250      */
251     String[] files = getStructureFiles();
252     if (!waitForFileLoad(files))
253     {
254       return null;
255     }
256
257     StringBuilder selectioncom = new StringBuilder(256);
258     // In principle - nSeconds specifies the speed of animation for each
259     // superposition - but is seems to behave weirdly, so we don't specify it.
260     String nSeconds = " ";
261     if (files.length > 10)
262     {
263       nSeconds = " 0.005 ";
264     }
265     else
266     {
267       nSeconds = " " + (2.0 / files.length) + " ";
268       // if (nSeconds).substring(0,5)+" ";
269     }
270
271     // see JAL-1345 - should really automatically turn off the animation for
272     // large numbers of structures, but Jmol doesn't seem to allow that.
273     // nSeconds = " ";
274     // union of all aligned positions are collected together.
275     for (int a = 0; a < _alignment.length; a++)
276     {
277       int refStructure = _refStructure[a];
278       AlignmentI alignment = _alignment[a];
279       HiddenColumns hiddenCols = _hiddenCols[a];
280       if (a > 0 && selectioncom.length() > 0 && !selectioncom
281               .substring(selectioncom.length() - 1).equals("|"))
282       {
283         selectioncom.append("|");
284       }
285       // process this alignment
286       if (refStructure >= files.length)
287       {
288         System.err.println(
289                 "Invalid reference structure value " + refStructure);
290         refStructure = -1;
291       }
292
293       /*
294        * 'matched' bit j will be set for visible alignment columns j where
295        * all sequences have a residue with a mapping to the PDB structure
296        */
297       BitSet matched = new BitSet();
298       for (int m = 0; m < alignment.getWidth(); m++)
299       {
300         if (hiddenCols == null || hiddenCols.isVisible(m))
301         {
302           matched.set(m);
303         }
304       }
305
306       SuperposeData[] structures = new SuperposeData[files.length];
307       for (int f = 0; f < files.length; f++)
308       {
309         structures[f] = new SuperposeData(alignment.getWidth());
310       }
311
312       /*
313        * Calculate the superposable alignment columns ('matched'), and the
314        * corresponding structure residue positions (structures.pdbResNo)
315        */
316       int candidateRefStructure = findSuperposableResidues(alignment,
317               matched, structures);
318       if (refStructure < 0)
319       {
320         /*
321          * If no reference structure was specified, pick the first one that has
322          * a mapping in the alignment
323          */
324         refStructure = candidateRefStructure;
325       }
326
327       String[] selcom = new String[files.length];
328       int nmatched = matched.cardinality();
329       if (nmatched < 4)
330       {
331         return (MessageManager.formatMessage("label.insufficient_residues",
332                 nmatched));
333       }
334
335       /*
336        * generate select statements to select regions to superimpose structures
337        */
338       {
339         // TODO extract method to construct selection statements
340         for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
341         {
342           String chainCd = ":" + structures[pdbfnum].chain;
343           int lpos = -1;
344           boolean run = false;
345           StringBuilder molsel = new StringBuilder();
346           molsel.append("{");
347
348           int nextColumnMatch = matched.nextSetBit(0);
349           while (nextColumnMatch != -1)
350           {
351             int pdbResNo = structures[pdbfnum].pdbResNo[nextColumnMatch];
352             if (lpos != pdbResNo - 1)
353             {
354               // discontinuity
355               if (lpos != -1)
356               {
357                 molsel.append(lpos);
358                 molsel.append(chainCd);
359                 molsel.append("|");
360               }
361               run = false;
362             }
363             else
364             {
365               // continuous run - and lpos >-1
366               if (!run)
367               {
368                 // at the beginning, so add dash
369                 molsel.append(lpos);
370                 molsel.append("-");
371               }
372               run = true;
373             }
374             lpos = pdbResNo;
375             nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
376           }
377           /*
378            * add final selection phrase
379            */
380           if (lpos != -1)
381           {
382             molsel.append(lpos);
383             molsel.append(chainCd);
384             molsel.append("}");
385           }
386           if (molsel.length() > 1)
387           {
388             selcom[pdbfnum] = molsel.toString();
389             selectioncom.append("((");
390             selectioncom.append(selcom[pdbfnum].substring(1,
391                     selcom[pdbfnum].length() - 1));
392             selectioncom.append(" )& ");
393             selectioncom.append(pdbfnum + 1);
394             selectioncom.append(".1)");
395             if (pdbfnum < files.length - 1)
396             {
397               selectioncom.append("|");
398             }
399           }
400           else
401           {
402             selcom[pdbfnum] = null;
403           }
404         }
405       }
406       StringBuilder command = new StringBuilder(256);
407       // command.append("set spinFps 10;\n");
408
409       for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
410       {
411         if (pdbfnum == refStructure || selcom[pdbfnum] == null
412                 || selcom[refStructure] == null)
413         {
414           continue;
415         }
416         command.append("echo ");
417         command.append("\"Superposing (");
418         command.append(structures[pdbfnum].pdbId);
419         command.append(") against reference (");
420         command.append(structures[refStructure].pdbId);
421         command.append(")\";\ncompare " + nSeconds);
422         command.append("{");
423         command.append(Integer.toString(1 + pdbfnum));
424         command.append(".1} {");
425         command.append(Integer.toString(1 + refStructure));
426         // conformation=1 excludes alternate locations for CA (JAL-1757)
427         command.append(
428                 ".1} SUBSET {(*.CA | *.P) and conformation=1} ATOMS ");
429
430         // for (int s = 0; s < 2; s++)
431         // {
432         // command.append(selcom[(s == 0 ? pdbfnum : refStructure)]);
433         // }
434         command.append(selcom[pdbfnum]);
435         command.append(selcom[refStructure]);
436         command.append(" ROTATE TRANSLATE;\n");
437       }
438       if (selectioncom.length() > 0)
439       {
440         // TODO is performing selectioncom redundant here? is done later on
441         // System.out.println("Select regions:\n" + selectioncom.toString());
442         evalStateCommand("select *; cartoons off; backbone; select ("
443                 + selectioncom.toString() + "); cartoons; ");
444         // selcom.append("; ribbons; ");
445         String cmdString = command.toString();
446         // System.out.println("Superimpose command(s):\n" + cmdString);
447
448         evalStateCommand(cmdString);
449       }
450     }
451     if (selectioncom.length() > 0)
452     {// finally, mark all regions that were superposed.
453       if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
454       {
455         selectioncom.setLength(selectioncom.length() - 1);
456       }
457       // System.out.println("Select regions:\n" + selectioncom.toString());
458       evalStateCommand("select *; cartoons off; backbone; select ("
459               + selectioncom.toString() + "); cartoons; ");
460       // evalStateCommand("select *; backbone; select "+selcom.toString()+";
461       // cartoons; center "+selcom.toString());
462     }
463
464     return null;
465   }
466
467   public void evalStateCommand(String command)
468   {
469     jmolHistory(false);
470     if (lastCommand == null || !lastCommand.equals(command))
471     {
472       viewer.evalStringQuiet(command + "\n");
473     }
474     jmolHistory(true);
475     lastCommand = command;
476   }
477
478   Thread colourby = null;
479   /**
480    * Sends a set of colour commands to the structure viewer
481    * 
482    * @param colourBySequenceCommands
483    */
484   @Override
485   protected void colourBySequence(
486           final StructureMappingcommandSet[] colourBySequenceCommands)
487   {
488     if (colourby != null)
489     {
490       colourby.interrupt();
491       colourby = null;
492     }
493     colourby = new Thread(new Runnable()
494     {
495       @Override
496       public void run()
497       {
498         for (StructureMappingcommandSet cpdbbyseq : colourBySequenceCommands)
499         {
500           for (String cbyseq : cpdbbyseq.commands)
501           {
502             executeWhenReady(cbyseq);
503           }
504         }
505       }
506     });
507     colourby.start();
508   }
509
510   /**
511    * @param files
512    * @param viewPanel
513    * @return
514    */
515   @Override
516   protected StructureMappingcommandSet[] getColourBySequenceCommands(
517           String[] files, AlignmentViewPanel viewPanel)
518   {
519     return JmolCommands.getColourBySequenceCommand(getSsm(), files,
520             this, viewPanel);
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   public void mouseOverStructure(int atomIndex, 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     if (lastMessage == null || !lastMessage.equals(strInfo))
837     {
838       getSsm().mouseOverStructure(pdbResNum, chainId, pdbfilename);
839     }
840
841     lastMessage = strInfo;
842   }
843
844   public void notifyAtomHovered(int atomIndex, String strInfo, String data)
845   {
846     if (data != null)
847     {
848       System.err.println("Ignoring additional hover info: " + data
849               + " (other info: '" + strInfo + "' pos " + atomIndex + ")");
850     }
851     mouseOverStructure(atomIndex, strInfo);
852   }
853
854   /*
855    * { if (history != null && strStatus != null &&
856    * !strStatus.equals("Script completed")) { history.append("\n" + strStatus);
857    * } }
858    */
859
860   public void notifyAtomPicked(int atomIndex, String strInfo,
861           String strData)
862   {
863     /**
864      * this implements the toggle label behaviour copied from the original
865      * structure viewer, MCView
866      */
867     if (strData != null)
868     {
869       System.err.println("Ignoring additional pick data string " + strData);
870     }
871     int chainSeparator = strInfo.indexOf(":");
872     int p = 0;
873     if (chainSeparator == -1)
874     {
875       chainSeparator = strInfo.indexOf(".");
876     }
877
878     String picked = strInfo.substring(strInfo.indexOf("]") + 1,
879             chainSeparator);
880     String mdlString = "";
881     if ((p = strInfo.indexOf(":")) > -1)
882     {
883       picked += strInfo.substring(p, strInfo.indexOf("."));
884     }
885
886     if ((p = strInfo.indexOf("/")) > -1)
887     {
888       mdlString += strInfo.substring(p, strInfo.indexOf(" #"));
889     }
890     picked = "((" + picked + ".CA" + mdlString + ")|(" + picked + ".P"
891             + mdlString + "))";
892     jmolHistory(false);
893
894     if (!atomsPicked.contains(picked))
895     {
896       viewer.evalStringQuiet("select " + picked + ";label %n %r:%c");
897       atomsPicked.addElement(picked);
898     }
899     else
900     {
901       viewer.evalString("select " + picked + ";label off");
902       atomsPicked.removeElement(picked);
903     }
904     jmolHistory(true);
905     // TODO: in application this happens
906     //
907     // if (scriptWindow != null)
908     // {
909     // scriptWindow.sendConsoleMessage(strInfo);
910     // scriptWindow.sendConsoleMessage("\n");
911     // }
912
913   }
914
915   @Override
916   public void notifyCallback(CBK type, Object[] data)
917   {
918     try
919     {
920       switch (type)
921       {
922       case LOADSTRUCT:
923         notifyFileLoaded((String) data[1], (String) data[2],
924                 (String) data[3], (String) data[4],
925                 ((Integer) data[5]).intValue());
926
927         break;
928       case PICK:
929         notifyAtomPicked(((Integer) data[2]).intValue(), (String) data[1],
930                 (String) data[0]);
931         // also highlight in alignment
932         // deliberate fall through
933       case HOVER:
934         notifyAtomHovered(((Integer) data[2]).intValue(), (String) data[1],
935                 (String) data[0]);
936         break;
937       case SCRIPT:
938         notifyScriptTermination((String) data[2],
939                 ((Integer) data[3]).intValue());
940         break;
941       case ECHO:
942         sendConsoleEcho((String) data[1]);
943         break;
944       case MESSAGE:
945         sendConsoleMessage(
946                 (data == null) ? ((String) null) : (String) data[1]);
947         break;
948       case ERROR:
949         // System.err.println("Ignoring error callback.");
950         break;
951       case SYNC:
952       case RESIZE:
953         refreshGUI();
954         break;
955       case MEASURE:
956
957       case CLICK:
958       default:
959         System.err.println(
960                 "Unhandled callback " + type + " " + data[1].toString());
961         break;
962       }
963     } catch (Exception e)
964     {
965       System.err.println("Squashed Jmol callback handler error:");
966       e.printStackTrace();
967     }
968   }
969
970   @Override
971   public boolean notifyEnabled(CBK callbackPick)
972   {
973     switch (callbackPick)
974     {
975     case ECHO:
976     case LOADSTRUCT:
977     case MEASURE:
978     case MESSAGE:
979     case PICK:
980     case SCRIPT:
981     case HOVER:
982     case ERROR:
983       return true;
984     default:
985       return false;
986     }
987   }
988
989   // incremented every time a load notification is successfully handled -
990   // lightweight mechanism for other threads to detect when they can start
991   // referrring to new structures.
992   private long loadNotifiesHandled = 0;
993
994   public long getLoadNotifiesHandled()
995   {
996     return loadNotifiesHandled;
997   }
998
999   public void notifyFileLoaded(String fullPathName, String fileName2,
1000           String modelName, String errorMsg, int modelParts)
1001   {
1002     if (errorMsg != null)
1003     {
1004       fileLoadingError = errorMsg;
1005       refreshGUI();
1006       return;
1007     }
1008     // TODO: deal sensibly with models loaded inLine:
1009     // modelName will be null, as will fullPathName.
1010
1011     // the rest of this routine ignores the arguments, and simply interrogates
1012     // the Jmol view to find out what structures it contains, and adds them to
1013     // the structure selection manager.
1014     fileLoadingError = null;
1015     String[] oldmodels = modelFileNames;
1016     modelFileNames = null;
1017     chainNames = new ArrayList<>();
1018     chainFile = new Hashtable<>();
1019     boolean notifyLoaded = false;
1020     String[] modelfilenames = getStructureFiles();
1021     // first check if we've lost any structures
1022     if (oldmodels != null && oldmodels.length > 0)
1023     {
1024       int oldm = 0;
1025       for (int i = 0; i < oldmodels.length; i++)
1026       {
1027         for (int n = 0; n < modelfilenames.length; n++)
1028         {
1029           if (modelfilenames[n] == oldmodels[i])
1030           {
1031             oldmodels[i] = null;
1032             break;
1033           }
1034         }
1035         if (oldmodels[i] != null)
1036         {
1037           oldm++;
1038         }
1039       }
1040       if (oldm > 0)
1041       {
1042         String[] oldmfn = new String[oldm];
1043         oldm = 0;
1044         for (int i = 0; i < oldmodels.length; i++)
1045         {
1046           if (oldmodels[i] != null)
1047           {
1048             oldmfn[oldm++] = oldmodels[i];
1049           }
1050         }
1051         // deregister the Jmol instance for these structures - we'll add
1052         // ourselves again at the end for the current structure set.
1053         getSsm().removeStructureViewerListener(this, oldmfn);
1054       }
1055     }
1056     refreshPdbEntries();
1057     for (int modelnum = 0; modelnum < modelfilenames.length; modelnum++)
1058     {
1059       String fileName = modelfilenames[modelnum];
1060       boolean foundEntry = false;
1061       StructureFile pdb = null;
1062       String pdbfile = null;
1063       // model was probably loaded inline - so check the pdb file hashcode
1064       if (loadedInline)
1065       {
1066         // calculate essential attributes for the pdb data imported inline.
1067         // prolly need to resolve modelnumber properly - for now just use our
1068         // 'best guess'
1069         pdbfile = viewer.getData(
1070                 "" + (1 + _modelFileNameMap[modelnum]) + ".0", "PDB");
1071       }
1072       // search pdbentries and sequences to find correct pdbentry for this
1073       // model
1074       for (int pe = 0; pe < getPdbCount(); pe++)
1075       {
1076         boolean matches = false;
1077         addSequence(pe, getSequence()[pe]);
1078         if (fileName == null)
1079         {
1080           if (false)
1081           // see JAL-623 - need method of matching pasted data up
1082           {
1083             pdb = getSsm().setMapping(getSequence()[pe], getChains()[pe],
1084                     pdbfile, DataSourceType.PASTE,
1085                     getIProgressIndicator());
1086             getPdbEntry(modelnum).setFile("INLINE" + pdb.getId());
1087             matches = true;
1088             foundEntry = true;
1089           }
1090         }
1091         else
1092         {
1093           File fl = new File(getPdbEntry(pe).getFile());
1094           matches = fl.equals(new File(fileName));
1095           if (matches)
1096           {
1097             foundEntry = true;
1098             // TODO: Jmol can in principle retrieve from CLASSLOADER but
1099             // this
1100             // needs
1101             // to be tested. See mantis bug
1102             // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
1103             DataSourceType protocol = DataSourceType.URL;
1104             try
1105             {
1106               if (fl.exists())
1107               {
1108                 protocol = DataSourceType.FILE;
1109               }
1110             } catch (Exception e)
1111             {
1112             } catch (Error e)
1113             {
1114             }
1115             // Explicitly map to the filename used by Jmol ;
1116             pdb = getSsm().setMapping(getSequence()[pe], getChains()[pe],
1117                     fileName, protocol, getIProgressIndicator());
1118             // pdbentry[pe].getFile(), protocol);
1119
1120           }
1121         }
1122         if (matches)
1123         {
1124           // add an entry for every chain in the model
1125           for (int i = 0; i < pdb.getChains().size(); i++)
1126           {
1127             String chid = new String(
1128                     pdb.getId() + ":" + pdb.getChains().elementAt(i).id);
1129             chainFile.put(chid, fileName);
1130             chainNames.add(chid);
1131           }
1132           notifyLoaded = true;
1133         }
1134       }
1135
1136       if (!foundEntry && associateNewStructs)
1137       {
1138         // this is a foreign pdb file that jalview doesn't know about - add
1139         // it to the dataset and try to find a home - either on a matching
1140         // sequence or as a new sequence.
1141         String pdbcontent = viewer.getData("/" + (modelnum + 1) + ".1",
1142                 "PDB");
1143         // parse pdb file into a chain, etc.
1144         // locate best match for pdb in associated views and add mapping to
1145         // ssm
1146         // if properly registered then
1147         notifyLoaded = true;
1148
1149       }
1150     }
1151     // FILE LOADED OK
1152     // so finally, update the jmol bits and pieces
1153     // if (jmolpopup != null)
1154     // {
1155     // // potential for deadlock here:
1156     // // jmolpopup.updateComputedMenus();
1157     // }
1158     if (!isLoadingFromArchive())
1159     {
1160       viewer.evalStringQuiet(
1161               "model *; select backbone;restrict;cartoon;wireframe off;spacefill off");
1162     }
1163     // register ourselves as a listener and notify the gui that it needs to
1164     // update itself.
1165     getSsm().addStructureViewerListener(this);
1166     if (notifyLoaded)
1167     {
1168       FeatureRenderer fr = getFeatureRenderer(null);
1169       if (fr != null)
1170       {
1171         fr.featuresAdded();
1172       }
1173       refreshGUI();
1174       loadNotifiesHandled++;
1175     }
1176     setLoadingFromArchive(false);
1177   }
1178
1179   @Override
1180   public List<String> getChainNames()
1181   {
1182     return chainNames;
1183   }
1184
1185   protected IProgressIndicator getIProgressIndicator()
1186   {
1187     return null;
1188   }
1189
1190   public void notifyNewPickingModeMeasurement(int iatom, String strMeasure)
1191   {
1192     notifyAtomPicked(iatom, strMeasure, null);
1193   }
1194
1195   public abstract void notifyScriptTermination(String strStatus,
1196           int msWalltime);
1197
1198   /**
1199    * display a message echoed from the jmol viewer
1200    * 
1201    * @param strEcho
1202    */
1203   public abstract void sendConsoleEcho(String strEcho); /*
1204                                                          * { showConsole(true);
1205                                                          * 
1206                                                          * history.append("\n" +
1207                                                          * strEcho); }
1208                                                          */
1209
1210   // /End JmolStatusListener
1211   // /////////////////////////////
1212
1213   /**
1214    * @param strStatus
1215    *          status message - usually the response received after a script
1216    *          executed
1217    */
1218   public abstract void sendConsoleMessage(String strStatus);
1219
1220   @Override
1221   public void setCallbackFunction(String callbackType,
1222           String callbackFunction)
1223   {
1224     System.err.println("Ignoring set-callback request to associate "
1225             + callbackType + " with function " + callbackFunction);
1226
1227   }
1228
1229   @Override
1230   public void setJalviewColourScheme(ColourSchemeI cs)
1231   {
1232     colourBySequence = false;
1233
1234     if (cs == null)
1235     {
1236       return;
1237     }
1238
1239     jmolHistory(false);
1240     StringBuilder command = new StringBuilder(128);
1241     command.append("select *;color white;");
1242     List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
1243             false);
1244     for (String resName : residueSet)
1245     {
1246       char res = resName.length() == 3
1247               ? ResidueProperties.getSingleCharacterCode(resName)
1248               : resName.charAt(0);
1249       Color col = cs.findColour(res, 0, null, null, 0f);
1250       command.append("select " + resName + ";color[" + col.getRed() + ","
1251               + col.getGreen() + "," + col.getBlue() + "];");
1252     }
1253
1254     evalStateCommand(command.toString());
1255     jmolHistory(true);
1256   }
1257
1258   public void showHelp()
1259   {
1260     showUrl("http://jmol.sourceforge.net/docs/JmolUserGuide/", "jmolHelp");
1261   }
1262
1263   /**
1264    * open the URL somehow
1265    * 
1266    * @param target
1267    */
1268   public abstract void showUrl(String url, String target);
1269
1270   /**
1271    * called when the binding thinks the UI needs to be refreshed after a Jmol
1272    * state change. this could be because structures were loaded, or because an
1273    * error has occured.
1274    */
1275   public abstract void refreshGUI();
1276
1277   /**
1278    * called to show or hide the associated console window container.
1279    * 
1280    * @param show
1281    */
1282   public abstract void showConsole(boolean show);
1283
1284   /**
1285    * @param renderPanel
1286    * @param jmolfileio
1287    *          - when true will initialise jmol's file IO system (should be false
1288    *          in applet context)
1289    * @param htmlName
1290    * @param documentBase
1291    * @param codeBase
1292    * @param commandOptions
1293    */
1294   public void allocateViewer(Container renderPanel, boolean jmolfileio,
1295           String htmlName, URL documentBase, URL codeBase,
1296           String commandOptions)
1297   {
1298     allocateViewer(renderPanel, jmolfileio, htmlName, documentBase,
1299             codeBase, commandOptions, null, null);
1300   }
1301
1302   /**
1303    * 
1304    * @param renderPanel
1305    * @param jmolfileio
1306    *          - when true will initialise jmol's file IO system (should be false
1307    *          in applet context)
1308    * @param htmlName
1309    * @param documentBase
1310    * @param codeBase
1311    * @param commandOptions
1312    * @param consolePanel
1313    *          - panel to contain Jmol console
1314    * @param buttonsToShow
1315    *          - buttons to show on the console, in ordr
1316    */
1317   public void allocateViewer(Container renderPanel, boolean jmolfileio,
1318           String htmlName, URL documentBase, URL codeBase,
1319           String commandOptions, final Container consolePanel,
1320           String buttonsToShow)
1321   {
1322     if (commandOptions == null)
1323     {
1324       commandOptions = "";
1325     }
1326     viewer = (Viewer) JmolViewer.allocateViewer(renderPanel,
1327             (jmolfileio ? new SmarterJmolAdapter() : null),
1328             htmlName + ((Object) this).toString(), documentBase, codeBase,
1329             commandOptions, this);
1330
1331     viewer.setJmolStatusListener(this); // extends JmolCallbackListener
1332
1333     console = createJmolConsole(consolePanel, buttonsToShow);
1334     if (consolePanel != null)
1335     {
1336       consolePanel.addComponentListener(this);
1337
1338     }
1339
1340   }
1341
1342   protected abstract JmolAppConsoleInterface createJmolConsole(
1343           Container consolePanel, String buttonsToShow);
1344
1345   protected org.jmol.api.JmolAppConsoleInterface console = null;
1346
1347   @Override
1348   public void setBackgroundColour(java.awt.Color col)
1349   {
1350     jmolHistory(false);
1351     viewer.evalStringQuiet("background [" + col.getRed() + ","
1352             + col.getGreen() + "," + col.getBlue() + "];");
1353     jmolHistory(true);
1354   }
1355
1356   @Override
1357   public int[] resizeInnerPanel(String data)
1358   {
1359     // Jalview doesn't honour resize panel requests
1360     return null;
1361   }
1362
1363   /**
1364    * 
1365    */
1366   protected void closeConsole()
1367   {
1368     if (console != null)
1369     {
1370       try
1371       {
1372         console.setVisible(false);
1373       } catch (Error e)
1374       {
1375       } catch (Exception x)
1376       {
1377       }
1378       ;
1379       console = null;
1380     }
1381   }
1382
1383   /**
1384    * ComponentListener method
1385    */
1386   @Override
1387   public void componentMoved(ComponentEvent e)
1388   {
1389   }
1390
1391   /**
1392    * ComponentListener method
1393    */
1394   @Override
1395   public void componentResized(ComponentEvent e)
1396   {
1397   }
1398
1399   /**
1400    * ComponentListener method
1401    */
1402   @Override
1403   public void componentShown(ComponentEvent e)
1404   {
1405     showConsole(true);
1406   }
1407
1408   /**
1409    * ComponentListener method
1410    */
1411   @Override
1412   public void componentHidden(ComponentEvent e)
1413   {
1414     showConsole(false);
1415   }
1416
1417   @Override
1418   public void showStructures(AlignViewportI av, boolean refocus)
1419   {
1420     // TODO show Jmol structure optionally restricted to visible alignment
1421     // and/or selected chains
1422   }
1423 }