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