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