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