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