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