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