JAL=1759 fix Jmol state command bug; remove debug output
[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     String[] files = getPdbFile();
263
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.00001 ";
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
458 .println("Superimpose command(s):\n" + cmdString);
459
460         evalStateCommand(cmdString);
461       }
462     }
463     if (selectioncom.length() > 0)
464     {// finally, mark all regions that were superposed.
465       if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
466       {
467         selectioncom.setLength(selectioncom.length() - 1);
468       }
469       System.out.println("Select regions:\n" + selectioncom.toString());
470       evalStateCommand("select *; cartoons off; backbone; select ("
471               + selectioncom.toString() + "); cartoons; ");
472       // evalStateCommand("select *; backbone; select "+selcom.toString()+"; cartoons; center "+selcom.toString());
473     }
474   }
475
476   public void evalStateCommand(String command)
477   {
478     jmolHistory(false);
479     if (lastCommand == null || !lastCommand.equals(command))
480     {
481       viewer.evalStringQuiet(command + "\n");
482     }
483     jmolHistory(true);
484     lastCommand = command;
485   }
486
487   /**
488    * colour any structures associated with sequences in the given alignment
489    * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
490    * if colourBySequence is enabled.
491    */
492   public void colourBySequence(AlignmentViewPanel alignmentv)
493   {
494     boolean showFeatures = alignmentv.getAlignViewport()
495             .isShowSequenceFeatures();
496     if (!colourBySequence || !isLoadingFinished())
497     {
498       return;
499     }
500     if (getSsm() == null)
501     {
502       return;
503     }
504     String[] files = getPdbFile();
505
506     SequenceRenderer sr = getSequenceRenderer(alignmentv);
507
508     FeatureRenderer fr = null;
509     if (showFeatures)
510     {
511       fr = getFeatureRenderer(alignmentv);
512     }
513     AlignmentI alignment = alignmentv.getAlignment();
514
515     for (jalview.structure.StructureMappingcommandSet cpdbbyseq : getColourBySequenceCommands(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
536             .getColourBySequenceCommand(getSsm(), files, getSequence(), sr,
537                     fr,
538                     alignment);
539   }
540
541   /**
542    * @param command
543    */
544   protected void executeWhenReady(String command)
545   {
546     evalStateCommand(command);
547   }
548
549   public void createImage(String file, String type, int quality)
550   {
551     System.out.println("JMOL CREATE IMAGE");
552   }
553
554   public String createImage(String fileName, String type,
555           Object textOrBytes, int quality)
556   {
557     System.out.println("JMOL CREATE IMAGE");
558     return null;
559   }
560
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   public float[][] functionXY(String functionName, int x, int y)
572   {
573     return null;
574   }
575
576   public float[][][] functionXYZ(String functionName, int nx, int ny, int nz)
577   {
578     // TODO Auto-generated method stub
579     return null;
580   }
581
582   public Color getColour(int atomIndex, int pdbResNum, String chain,
583           String pdbfile)
584   {
585     if (getModelNum(pdbfile) < 0)
586     {
587       return null;
588     }
589     // TODO: verify atomIndex is selecting correct model.
590     // return new Color(viewer.getAtomArgb(atomIndex)); Jmol 12.2.4
591     int colour = viewer.ms.at[atomIndex]
592             .atomPropertyInt(T.color);
593     return new Color(colour);
594   }
595
596   /**
597    * returns the current featureRenderer that should be used to colour the
598    * structures
599    * 
600    * @param alignment
601    * 
602    * @return
603    */
604   public abstract FeatureRenderer getFeatureRenderer(
605           AlignmentViewPanel alignment);
606
607   /**
608    * instruct the Jalview binding to update the pdbentries vector if necessary
609    * prior to matching the jmol view's contents to the list of structure files
610    * Jalview knows about.
611    */
612   public abstract void refreshPdbEntries();
613
614   private int getModelNum(String modelFileName)
615   {
616     String[] mfn = getPdbFile();
617     if (mfn == null)
618     {
619       return -1;
620     }
621     for (int i = 0; i < mfn.length; i++)
622     {
623       if (mfn[i].equalsIgnoreCase(modelFileName))
624       {
625         return i;
626       }
627     }
628     return -1;
629   }
630
631   /**
632    * map between index of model filename returned from getPdbFile and the first
633    * index of models from this file in the viewer. Note - this is not trimmed -
634    * use getPdbFile to get number of unique models.
635    */
636   private int _modelFileNameMap[];
637
638   // ////////////////////////////////
639   // /StructureListener
640   @Override
641   public synchronized String[] getPdbFile()
642   {
643     if (viewer == null)
644     {
645       return new String[0];
646     }
647     if (modelFileNames == null)
648     {
649       String mset[] = new String[viewer.ms.mc];
650       _modelFileNameMap = new int[mset.length];
651       String m = viewer.ms.getModelFileName(0);
652       if (m != null)
653       {
654         mset[0] = m;
655         try
656         {
657           mset[0] = new File(m).getAbsolutePath();
658         } catch (AccessControlException x)
659         {
660           // usually not allowed to do this in applet
661           System.err
662                   .println("jmolBinding: Using local file string from Jmol: "
663                           + m);
664         }
665         if (mset[0].indexOf("/file:") != -1)
666         {
667           // applet path with docroot - discard as format won't match pdbfile
668           mset[0] = m;
669         }
670       }
671       int j = 1;
672       for (int i = 1; i < mset.length; i++)
673       {
674         m = viewer.ms.getModelFileName(i);
675         mset[j] = m;
676         if (m != null)
677         {
678           try
679           {
680             mset[j] = new File(m).getAbsolutePath();
681           } catch (AccessControlException x)
682           {
683             // usually not allowed to do this in applet, so keep raw handle
684             // System.err.println("jmolBinding: Using local file string from Jmol: "+m);
685           }
686         }
687         _modelFileNameMap[j] = i; // record the model index for the filename
688         // skip any additional models in the same file (NMR structures)
689         if ((mset[j] == null ? mset[j] != mset[j - 1]
690                 : (mset[j - 1] == null || !mset[j].equals(mset[j - 1]))))
691         {
692           j++;
693         }
694       }
695       modelFileNames = new String[j];
696       System.arraycopy(mset, 0, modelFileNames, 0, j);
697     }
698     return modelFileNames;
699   }
700
701   /**
702    * map from string to applet
703    */
704   @Override
705   public Map<String, Object> getRegistryInfo()
706   {
707     // TODO Auto-generated method stub
708     return null;
709   }
710
711   /**
712    * returns the current sequenceRenderer that should be used to colour the
713    * structures
714    * 
715    * @param alignment
716    * 
717    * @return
718    */
719   public abstract SequenceRenderer getSequenceRenderer(
720           AlignmentViewPanel alignment);
721
722   // ///////////////////////////////
723   // JmolStatusListener
724
725   public void handlePopupMenu(int x, int y)
726   {
727     // jmolpopup.show(x, y);
728     // jmolpopup.jpiShow(x, y);
729   }
730
731   /**
732    * Highlight zero, one or more atoms on the structure
733    */
734   @Override
735   public void highlightAtoms(List<AtomSpec> atoms)
736   {
737     if (atoms != null)
738     {
739       for (AtomSpec atom : atoms)
740       {
741         highlightAtom(atom.getAtomIndex(), atom.getPdbResNum(),
742                 atom.getChain(), atom.getPdbFile());
743       }
744     }
745   }
746
747   // jmol/ssm only
748   public void highlightAtom(int atomIndex, int pdbResNum, String chain,
749           String pdbfile)
750   {
751     if (modelFileNames == null)
752     {
753       return;
754     }
755
756     // look up file model number for this pdbfile
757     int mdlNum = 0;
758     // may need to adjust for URLencoding here - we don't worry about that yet.
759     while (mdlNum < modelFileNames.length
760             && !pdbfile.equals(modelFileNames[mdlNum]))
761     {
762       mdlNum++;
763     }
764     if (mdlNum == modelFileNames.length)
765     {
766       return;
767     }
768
769     jmolHistory(false);
770     // if (!pdbfile.equals(pdbentry.getFile()))
771     // return;
772     if (resetLastRes.length() > 0)
773     {
774       viewer.evalStringQuiet(resetLastRes.toString());
775     }
776
777     StringBuilder cmd = new StringBuilder(64);
778     cmd.append("select " + pdbResNum); // +modelNum
779
780     resetLastRes.setLength(0);
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(
890                   viewer.ms.getModelFileName(mnumber))
891                   .getAbsolutePath();
892         }
893
894       } catch (Exception e)
895       {
896       }
897       ;
898     }
899     if (lastMessage == null || !lastMessage.equals(strInfo))
900     {
901       getSsm().mouseOverStructure(pdbResNum, chainId, pdbfilename);
902     }
903
904     lastMessage = strInfo;
905   }
906
907   public void notifyAtomHovered(int atomIndex, String strInfo, String data)
908   {
909     if (data != null)
910     {
911       System.err.println("Ignoring additional hover info: " + data
912               + " (other info: '" + strInfo + "' pos " + atomIndex + ")");
913     }
914     mouseOverStructure(atomIndex, strInfo);
915   }
916
917   /*
918    * { if (history != null && strStatus != null &&
919    * !strStatus.equals("Script completed")) { history.append("\n" + strStatus);
920    * } }
921    */
922
923   public void notifyAtomPicked(int atomIndex, String strInfo, String strData)
924   {
925     /**
926      * this implements the toggle label behaviour copied from the original
927      * structure viewer, MCView
928      */
929     if (strData != null)
930     {
931       System.err.println("Ignoring additional pick data string " + strData);
932     }
933     int chainSeparator = strInfo.indexOf(":");
934     int p = 0;
935     if (chainSeparator == -1)
936     {
937       chainSeparator = strInfo.indexOf(".");
938     }
939
940     String picked = strInfo.substring(strInfo.indexOf("]") + 1,
941             chainSeparator);
942     String mdlString = "";
943     if ((p = strInfo.indexOf(":")) > -1)
944     {
945       picked += strInfo.substring(p + 1, strInfo.indexOf("."));
946     }
947
948     if ((p = strInfo.indexOf("/")) > -1)
949     {
950       mdlString += strInfo.substring(p, strInfo.indexOf(" #"));
951     }
952     picked = "((" + picked + ".CA" + mdlString + ")|(" + picked + ".P"
953             + mdlString + "))";
954     jmolHistory(false);
955
956     if (!atomsPicked.contains(picked))
957     {
958       viewer.evalStringQuiet("select " + picked + ";label %n %r:%c");
959       atomsPicked.addElement(picked);
960     }
961     else
962     {
963       viewer.evalString("select " + picked + ";label off");
964       atomsPicked.removeElement(picked);
965     }
966     jmolHistory(true);
967     // TODO: in application this happens
968     //
969     // if (scriptWindow != null)
970     // {
971     // scriptWindow.sendConsoleMessage(strInfo);
972     // scriptWindow.sendConsoleMessage("\n");
973     // }
974
975   }
976
977   @Override
978   public void notifyCallback(CBK type, Object[] data)
979   {
980     try
981     {
982       switch (type)
983       {
984       case LOADSTRUCT:
985         notifyFileLoaded((String) data[1], (String) data[2],
986                 (String) data[3], (String) data[4],
987                 ((Integer) data[5]).intValue());
988
989         break;
990       case PICK:
991         notifyAtomPicked(((Integer) data[2]).intValue(), (String) data[1],
992                 (String) data[0]);
993         // also highlight in alignment
994       case HOVER:
995         notifyAtomHovered(((Integer) data[2]).intValue(), (String) data[1],
996                 (String) data[0]);
997         break;
998       case SCRIPT:
999         notifyScriptTermination((String) data[2],
1000                 ((Integer) data[3]).intValue());
1001         break;
1002       case ECHO:
1003         sendConsoleEcho((String) data[1]);
1004         break;
1005       case MESSAGE:
1006         sendConsoleMessage((data == null) ? ((String) null)
1007                 : (String) data[1]);
1008         break;
1009       case ERROR:
1010         // System.err.println("Ignoring error callback.");
1011         break;
1012       case SYNC:
1013       case RESIZE:
1014         refreshGUI();
1015         break;
1016       case MEASURE:
1017
1018       case CLICK:
1019       default:
1020         System.err.println("Unhandled callback " + type + " "
1021                 + data[1].toString());
1022         break;
1023       }
1024     } catch (Exception e)
1025     {
1026       System.err.println("Squashed Jmol callback handler error:");
1027       e.printStackTrace();
1028     }
1029   }
1030
1031   @Override
1032   public boolean notifyEnabled(CBK callbackPick)
1033   {
1034     switch (callbackPick)
1035     {
1036     case ECHO:
1037     case LOADSTRUCT:
1038     case MEASURE:
1039     case MESSAGE:
1040     case PICK:
1041     case SCRIPT:
1042     case HOVER:
1043     case ERROR:
1044       return true;
1045     default:
1046       return false;
1047     }
1048   }
1049
1050   // incremented every time a load notification is successfully handled -
1051   // lightweight mechanism for other threads to detect when they can start
1052   // referrring to new structures.
1053   private long loadNotifiesHandled = 0;
1054
1055   public long getLoadNotifiesHandled()
1056   {
1057     return loadNotifiesHandled;
1058   }
1059
1060   public void notifyFileLoaded(String fullPathName, String fileName2,
1061           String modelName, String errorMsg, int modelParts)
1062   {
1063     if (errorMsg != null)
1064     {
1065       fileLoadingError = errorMsg;
1066       refreshGUI();
1067       return;
1068     }
1069     // TODO: deal sensibly with models loaded inLine:
1070     // modelName will be null, as will fullPathName.
1071
1072     // the rest of this routine ignores the arguments, and simply interrogates
1073     // the Jmol view to find out what structures it contains, and adds them to
1074     // the structure selection manager.
1075     fileLoadingError = null;
1076     String[] oldmodels = modelFileNames;
1077     modelFileNames = null;
1078     chainNames = new Vector<String>();
1079     chainFile = new Hashtable<String, String>();
1080     boolean notifyLoaded = false;
1081     String[] modelfilenames = getPdbFile();
1082     // first check if we've lost any structures
1083     if (oldmodels != null && oldmodels.length > 0)
1084     {
1085       int oldm = 0;
1086       for (int i = 0; i < oldmodels.length; i++)
1087       {
1088         for (int n = 0; n < modelfilenames.length; n++)
1089         {
1090           if (modelfilenames[n] == oldmodels[i])
1091           {
1092             oldmodels[i] = null;
1093             break;
1094           }
1095         }
1096         if (oldmodels[i] != null)
1097         {
1098           oldm++;
1099         }
1100       }
1101       if (oldm > 0)
1102       {
1103         String[] oldmfn = new String[oldm];
1104         oldm = 0;
1105         for (int i = 0; i < oldmodels.length; i++)
1106         {
1107           if (oldmodels[i] != null)
1108           {
1109             oldmfn[oldm++] = oldmodels[i];
1110           }
1111         }
1112         // deregister the Jmol instance for these structures - we'll add
1113         // ourselves again at the end for the current structure set.
1114         getSsm().removeStructureViewerListener(this, oldmfn);
1115       }
1116     }
1117     refreshPdbEntries();
1118     for (int modelnum = 0; modelnum < modelfilenames.length; modelnum++)
1119     {
1120       String fileName = modelfilenames[modelnum];
1121       boolean foundEntry = false;
1122       MCview.PDBfile pdb = null;
1123       String pdbfile = null;
1124       // model was probably loaded inline - so check the pdb file hashcode
1125       if (loadedInline)
1126       {
1127         // calculate essential attributes for the pdb data imported inline.
1128         // prolly need to resolve modelnumber properly - for now just use our
1129         // 'best guess'
1130         pdbfile = viewer.getData("" + (1 + _modelFileNameMap[modelnum])
1131                 + ".0", "PDB");
1132       }
1133         // search pdbentries and sequences to find correct pdbentry for this
1134         // model
1135       for (int pe = 0; pe < getPdbCount(); pe++)
1136       {
1137         boolean matches = false;
1138         if (fileName == null)
1139         {
1140           if (false)
1141           // see JAL-623 - need method of matching pasted data up
1142           {
1143             pdb = getSsm().setMapping(getSequence()[pe], getChains()[pe],
1144                     pdbfile, AppletFormatAdapter.PASTE);
1145             getPdbEntry(modelnum).setFile("INLINE" + pdb.id);
1146             matches = true;
1147             foundEntry = true;
1148           }
1149         }
1150         else
1151         {
1152           File fl = new File(getPdbEntry(pe).getFile());
1153           matches = fl.equals(new File(fileName));
1154           if (matches)
1155           {
1156             foundEntry = true;
1157             // TODO: Jmol can in principle retrieve from CLASSLOADER but
1158             // this
1159             // needs
1160             // to be tested. See mantis bug
1161             // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
1162             String protocol = AppletFormatAdapter.URL;
1163             try
1164             {
1165               if (fl.exists())
1166               {
1167                 protocol = AppletFormatAdapter.FILE;
1168               }
1169             } catch (Exception e)
1170             {
1171             } catch (Error e)
1172             {
1173             }
1174             // Explicitly map to the filename used by Jmol ;
1175             pdb = getSsm().setMapping(getSequence()[pe], getChains()[pe],
1176                     fileName, protocol);
1177             // pdbentry[pe].getFile(), protocol);
1178
1179           }
1180         }
1181         if (matches)
1182         {
1183           // add an entry for every chain in the model
1184           for (int i = 0; i < pdb.chains.size(); i++)
1185           {
1186             String chid = new String(pdb.id + ":"
1187                     + pdb.chains.elementAt(i).id);
1188             chainFile.put(chid, fileName);
1189             chainNames.addElement(chid);
1190           }
1191           notifyLoaded = true;
1192         }
1193       }
1194
1195       if (!foundEntry && associateNewStructs)
1196       {
1197         // this is a foreign pdb file that jalview doesn't know about - add
1198         // it to the dataset and try to find a home - either on a matching
1199         // sequence or as a new sequence.
1200         String pdbcontent = viewer.getData("/" + (modelnum + 1) + ".1",
1201                 "PDB");
1202         // parse pdb file into a chain, etc.
1203         // locate best match for pdb in associated views and add mapping to
1204         // ssm
1205         // if properly registered then
1206         notifyLoaded = true;
1207
1208       }
1209     }
1210     // FILE LOADED OK
1211     // so finally, update the jmol bits and pieces
1212     // if (jmolpopup != null)
1213     // {
1214     // // potential for deadlock here:
1215     // // jmolpopup.updateComputedMenus();
1216     // }
1217     if (!isLoadingFromArchive())
1218     {
1219       viewer.evalStringQuiet("model 0; select backbone;restrict;cartoon;wireframe off;spacefill off");
1220     }
1221     // register ourselves as a listener and notify the gui that it needs to
1222     // update itself.
1223     getSsm().addStructureViewerListener(this);
1224     if (notifyLoaded)
1225     {
1226       FeatureRenderer fr = getFeatureRenderer(null);
1227       if (fr != null)
1228       {
1229         fr.featuresAdded();
1230       }
1231       refreshGUI();
1232       loadNotifiesHandled++;
1233     }
1234     setLoadingFromArchive(false);
1235   }
1236
1237   public void notifyNewPickingModeMeasurement(int iatom, String strMeasure)
1238   {
1239     notifyAtomPicked(iatom, strMeasure, null);
1240   }
1241
1242   public abstract void notifyScriptTermination(String strStatus,
1243           int msWalltime);
1244
1245   /**
1246    * display a message echoed from the jmol viewer
1247    * 
1248    * @param strEcho
1249    */
1250   public abstract void sendConsoleEcho(String strEcho); /*
1251                                                          * { showConsole(true);
1252                                                          * 
1253                                                          * history.append("\n" +
1254                                                          * strEcho); }
1255                                                          */
1256
1257   // /End JmolStatusListener
1258   // /////////////////////////////
1259
1260   /**
1261    * @param strStatus
1262    *          status message - usually the response received after a script
1263    *          executed
1264    */
1265   public abstract void sendConsoleMessage(String strStatus);
1266
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   public boolean isFinishedInit()
1405   {
1406     return finishedInit;
1407   }
1408
1409   public void setFinishedInit(boolean finishedInit)
1410   {
1411     this.finishedInit = finishedInit;
1412   }
1413
1414   /**
1415    * 
1416    */
1417   protected void closeConsole()
1418   {
1419     if (console != null)
1420     {
1421       try
1422       {
1423         console.setVisible(false);
1424       } catch (Error e)
1425       {
1426       } catch (Exception x)
1427       {
1428       }
1429       ;
1430       console = null;
1431     }
1432   }
1433
1434   /**
1435    * ComponentListener method
1436    */
1437   @Override
1438   public void componentMoved(ComponentEvent e)
1439   {
1440   }
1441
1442   /**
1443    * ComponentListener method
1444    */
1445   @Override
1446   public void componentResized(ComponentEvent e)
1447   {
1448   }
1449
1450   /**
1451    * ComponentListener method
1452    */
1453   @Override
1454   public void componentShown(ComponentEvent e)
1455   {
1456     showConsole(true);
1457   }
1458
1459   /**
1460    * ComponentListener method
1461    */
1462   @Override
1463   public void componentHidden(ComponentEvent e)
1464   {
1465     showConsole(false);
1466   }
1467 }
1468