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