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