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