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