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