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