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