extended mouseover message with absolute sequence position info JAL-433, relaxed...
[jalview.git] / src / jalview / bin / JalviewLite.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3  * Copyright (C) 2010 J Procter, AM Waterhouse, 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.bin;
19
20 import jalview.appletgui.AlignFrame;
21 import jalview.appletgui.EmbmenuFrame;
22 import jalview.appletgui.FeatureSettings;
23 import jalview.datamodel.Alignment;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.AlignmentOrder;
26 import jalview.datamodel.ColumnSelection;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.Sequence;
29 import jalview.datamodel.SequenceGroup;
30 import jalview.datamodel.SequenceI;
31 import jalview.io.AnnotationFile;
32 import jalview.io.AppletFormatAdapter;
33 import jalview.io.FileParse;
34 import jalview.io.IdentifyFile;
35 import jalview.io.JnetAnnotationMaker;
36 import jalview.javascript.JSFunctionExec;
37 import jalview.javascript.JsCallBack;
38 import jalview.structure.SelectionListener;
39 import jalview.structure.StructureSelectionManager;
40
41 import java.applet.Applet;
42 import java.awt.Button;
43 import java.awt.Color;
44 import java.awt.Component;
45 import java.awt.Font;
46 import java.awt.Frame;
47 import java.awt.Graphics;
48 import java.awt.event.ActionEvent;
49 import java.awt.event.WindowAdapter;
50 import java.awt.event.WindowEvent;
51 import java.io.BufferedReader;
52 import java.io.InputStreamReader;
53 import java.util.StringTokenizer;
54 import java.util.Vector;
55
56 import netscape.javascript.JSObject;
57
58 /**
59  * Jalview Applet. Runs in Java 1.18 runtime
60  * 
61  * @author $author$
62  * @version $Revision$
63  */
64 public class JalviewLite extends Applet
65 {
66
67   // /////////////////////////////////////////
68   // The following public methods maybe called
69   // externally, eg via javascript in HTML page
70   /**
71    * @return String list of selected sequence IDs, each terminated by the
72    *         'boolean not' character (""+0x00AC) or (&#172;)
73    */
74   public String getSelectedSequences()
75   {
76     return getSelectedSequencesFrom(getDefaultTargetFrame());
77   }
78
79   /**
80    * @param sep
81    *          separator string or null for default
82    * @return String list of selected sequence IDs, each terminated by given
83    *         separator string
84    */
85   public String getSelectedSequences(String sep)
86   {
87     return getSelectedSequencesFrom(getDefaultTargetFrame(), sep);
88   }
89
90   /**
91    * @param alf
92    *          alignframe containing selection
93    * @return String list of selected sequence IDs, each terminated by current
94    *         default separator sequence
95    * 
96    */
97   public String getSelectedSequencesFrom(AlignFrame alf)
98   {
99     return getSelectedSequencesFrom(alf, separator); // ""+0x00AC);
100   }
101
102   /**
103    * get list of selected sequence IDs separated by given separator
104    * 
105    * @param alf
106    *          window containing selection
107    * @param sep
108    *          separator string to use - default is 'boolean not'
109    * @return String list of selected sequence IDs, each terminated by the given
110    *         separator
111    */
112   public String getSelectedSequencesFrom(AlignFrame alf, String sep)
113   {
114     StringBuffer result = new StringBuffer("");
115     if (sep == null || sep.length() == 0)
116     {
117       sep = separator; // "+0x00AC;
118     }
119     if (alf.viewport.getSelectionGroup() != null)
120     {
121       SequenceI[] seqs = alf.viewport.getSelectionGroup()
122               .getSequencesInOrder(alf.viewport.getAlignment());
123
124       for (int i = 0; i < seqs.length; i++)
125       {
126         result.append(seqs[i].getName());
127         result.append(sep);
128       }
129     }
130
131     return result.toString();
132   }
133
134   /**
135    * 
136    * @param sequenceId
137    *          id of sequence to highlight
138    * @param position
139    *          integer position [ tobe implemented or range ] on sequence
140    * @param alignedPosition
141    *          true/false/empty string - indicate if position is an alignment
142    *          column or unaligned sequence position
143    */
144   public void highlight(String sequenceId, String position,
145           String alignedPosition)
146   {
147     highlightIn(getDefaultTargetFrame(), sequenceId, position,
148             alignedPosition);
149   }
150
151   /**
152    * 
153    * @param sequenceId
154    *          id of sequence to highlight
155    * @param position
156    *          integer position [ tobe implemented or range ] on sequence
157    * @param alignedPosition
158    *          false, blank or something else - indicate if position is an
159    *          alignment column or unaligned sequence position
160    */
161   public void highlightIn(AlignFrame alf, String sequenceId,
162           String position, String alignedPosition)
163   {
164     // TODO: could try to highlight in all alignments if alf==null
165     jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
166             alf.viewport.getAlignment().getSequencesArray());
167     SequenceI sq = matcher.findIdMatch(sequenceId);
168     if (sq != null)
169     {
170       int pos, apos = -1;
171       try
172       {
173         apos = new Integer(position).intValue();
174         apos--;
175       } catch (NumberFormatException ex)
176       {
177         return;
178       }
179       // use vamsas listener to broadcast to all listeners in scope
180       if (alignedPosition != null
181               && (alignedPosition.trim().length() == 0 || alignedPosition
182                       .toLowerCase().indexOf("false") > -1))
183       {
184         StructureSelectionManager.getStructureSelectionManager()
185                 .mouseOverVamsasSequence(sq, sq.findIndex(apos), null);
186       }
187       else
188       {
189         StructureSelectionManager.getStructureSelectionManager()
190                 .mouseOverVamsasSequence(sq, apos, null);
191       }
192
193     }
194   }
195
196   /**
197    * select regions of the currrent alignment frame
198    * 
199    * @param sequenceIds
200    *          String separated list of sequence ids or empty string
201    * @param columns
202    *          String separated list { column range or column, ..} or empty
203    *          string
204    */
205   public void select(String sequenceIds, String columns)
206   {
207     selectIn(getDefaultTargetFrame(), sequenceIds, columns, separator);
208   }
209
210   /**
211    * select regions of the currrent alignment frame
212    * 
213    * @param toselect
214    *          String separated list { column range, seq1...seqn sequence ids }
215    * @param sep
216    *          separator between toselect fields
217    */
218   public void select(String sequenceIds, String columns, String sep)
219   {
220     selectIn(getDefaultTargetFrame(), sequenceIds, columns, sep);
221   }
222
223   /**
224    * select regions of the given alignment frame
225    * 
226    * @param alf
227    * @param toselect
228    *          String separated list { column range, seq1...seqn sequence ids }
229    * @param sep
230    *          separator between toselect fields
231    */
232   public void selectIn(AlignFrame alf, String sequenceIds, String columns)
233   {
234     selectIn(alf, sequenceIds, columns, separator);
235   }
236
237   /**
238    * select regions of the given alignment frame
239    * 
240    * @param alf
241    * @param toselect
242    *          String separated list { column range, seq1...seqn sequence ids }
243    * @param sep
244    *          separator between toselect fields
245    */
246   public void selectIn(AlignFrame alf, String sequenceIds, String columns,
247           String sep)
248   {
249     if (sep == null || sep.length() == 0)
250     {
251       sep = separator;
252     }
253     else
254     {
255       if (debug)
256       {
257         System.err.println("Selecting region using separator string '"
258                 + separator + "'");
259       }
260     }
261     // deparse fields
262     String[] ids = separatorListToArray(sequenceIds, sep);
263     String[] cols = separatorListToArray(columns, sep);
264     SequenceGroup sel = new SequenceGroup();
265     ColumnSelection csel = new ColumnSelection();
266     AlignmentI al = alf.viewport.getAlignment();
267     jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
268             alf.viewport.getAlignment().getSequencesArray());
269     int start = 0, end = al.getWidth(), alw = al.getWidth();
270     boolean seqsfound = true;
271     if (ids != null && ids.length > 0)
272     {
273       seqsfound = false;
274       for (int i = 0; i < ids.length; i++)
275       {
276         if (ids[i].trim().length() == 0)
277         {
278           continue;
279         }
280         SequenceI sq = matcher.findIdMatch(ids[i]);
281         if (sq != null)
282         {
283           seqsfound = true;
284           sel.addSequence(sq, false);
285         }
286       }
287     }
288     boolean inseqpos = false;
289     if (cols != null && cols.length > 0)
290     {
291       boolean seset = false;
292       for (int i = 0; i < cols.length; i++)
293       {
294         String cl = cols[i].trim();
295         if (cl.length() == 0)
296         {
297           continue;
298         }
299         int p;
300         if ((p = cl.indexOf("-")) > -1)
301         {
302           int from = -1, to = -1;
303           try
304           {
305             from = new Integer(cl.substring(0, p)).intValue();
306             from--;
307           } catch (NumberFormatException ex)
308           {
309             System.err
310                     .println("ERROR: Couldn't parse first integer in range element column selection string '"
311                             + cl + "' - format is 'from-to'");
312             return;
313           }
314           try
315           {
316             to = new Integer(cl.substring(p + 1)).intValue();
317             to--;
318           } catch (NumberFormatException ex)
319           {
320             System.err
321                     .println("ERROR: Couldn't parse second integer in range element column selection string '"
322                             + cl + "' - format is 'from-to'");
323             return;
324           }
325           if (from >= 0 && to >= 0)
326           {
327             // valid range
328             if (from < to)
329             {
330               int t = to;
331               to = from;
332               to = t;
333             }
334             if (!seset)
335             {
336               start = from;
337               end = to;
338               seset = true;
339             }
340             else
341             {
342               // comment to prevent range extension
343               if (start > from)
344               {
345                 start = from;
346               }
347               if (end < to)
348               {
349                 end = to;
350               }
351             }
352             for (int r = from; r <= to; r++)
353             {
354               if (r >= 0 && r < alw)
355               {
356                 csel.addElement(r);
357               }
358             }
359             if (debug)
360             {
361               System.err.println("Range '" + cl + "' deparsed as [" + from
362                       + "," + to + "]");
363             }
364           }
365           else
366           {
367             System.err.println("ERROR: Invalid Range '" + cl
368                     + "' deparsed as [" + from + "," + to + "]");
369           }
370         }
371         else
372         {
373           int r = -1;
374           try
375           {
376             r = new Integer(cl).intValue();
377             r--;
378           } catch (NumberFormatException ex)
379           {
380             if (cl.toLowerCase().equals("sequence"))
381             {
382               // we are in the dataset sequence's coordinate frame.
383               inseqpos = true;
384             }
385             else
386             {
387               System.err
388                       .println("ERROR: Couldn't parse integer from point selection element of column selection string '"
389                               + cl + "'");
390               return;
391             }
392           }
393           if (r >= 0 && r <= alw)
394           {
395             if (!seset)
396             {
397               start = r;
398               end = r;
399               seset = true;
400             }
401             else
402             {
403               // comment to prevent range extension
404               if (start > r)
405               {
406                 start = r;
407               }
408               if (end < r)
409               {
410                 end = r;
411               }
412             }
413             csel.addElement(r);
414             if (debug)
415             {
416               System.err.println("Point selection '" + cl
417                       + "' deparsed as [" + r + "]");
418             }
419           }
420           else
421           {
422             System.err.println("ERROR: Invalid Point selection '" + cl
423                     + "' deparsed as [" + r + "]");
424           }
425         }
426       }
427     }
428     if (seqsfound)
429     {
430       // we only propagate the selection when it was the null selection, or the
431       // given sequences were found in the alignment.
432       if (inseqpos && sel.getSize() > 0)
433       {
434         // assume first sequence provides reference frame ?
435         SequenceI rs = sel.getSequenceAt(0);
436         start = rs.findIndex(start);
437         end = rs.findIndex(end);
438         if (csel != null)
439         {
440           Vector cs = csel.getSelected();
441           csel.clear();
442           for (int csi = 0, csiS = cs.size(); csi < csiS; csi++)
443           {
444             csel.addElement(rs.findIndex(((Integer) cs.elementAt(csi))
445                     .intValue()));
446           }
447         }
448       }
449       sel.setStartRes(start);
450       sel.setEndRes(end);
451       alf.select(sel, csel);
452     }
453   }
454
455   /**
456    * get sequences selected in current alignFrame and return their alignment in
457    * format 'format' either with or without suffix
458    * 
459    * @param alf
460    *          - where selection is
461    * @param format
462    *          - format of alignment file
463    * @param suffix
464    *          - "true" to append /start-end string to each sequence ID
465    * @return selected sequences as flat file or empty string if there was no
466    *         current selection
467    */
468   public String getSelectedSequencesAsAlignment(String format, String suffix)
469   {
470     return getSelectedSequencesAsAlignmentFrom(getDefaultTargetFrame(),
471             format, suffix);
472   }
473
474   /**
475    * get sequences selected in alf and return their alignment in format 'format'
476    * either with or without suffix
477    * 
478    * @param alf
479    *          - where selection is
480    * @param format
481    *          - format of alignment file
482    * @param suffix
483    *          - "true" to append /start-end string to each sequence ID
484    * @return selected sequences as flat file or empty string if there was no
485    *         current selection
486    */
487   public String getSelectedSequencesAsAlignmentFrom(AlignFrame alf,
488           String format, String suffix)
489   {
490     try
491     {
492       boolean seqlimits = suffix.equalsIgnoreCase("true");
493       if (alf.viewport.getSelectionGroup() != null)
494       {
495         String reply = new AppletFormatAdapter().formatSequences(format,
496                 new Alignment(alf.viewport.getSelectionAsNewSequence()),
497                 seqlimits);
498         return reply;
499       }
500     } catch (Exception ex)
501     {
502       ex.printStackTrace();
503       return "Error retrieving alignment in " + format + " format. ";
504     }
505     return "";
506   }
507
508   public String getAlignmentOrder()
509   {
510     return getAlignmentOrderFrom(getDefaultTargetFrame());
511   }
512
513   public String getAlignmentOrderFrom(AlignFrame alf)
514   {
515     return getAlignmentOrderFrom(alf, separator);
516   }
517
518   public String getAlignmentOrderFrom(AlignFrame alf, String sep)
519   {
520     AlignmentI alorder = alf.getAlignViewport().getAlignment();
521     String[] order = new String[alorder.getHeight()];
522     for (int i = 0; i < order.length; i++)
523     {
524       order[i] = alorder.getSequenceAt(i).getName();
525     }
526     return arrayToSeparatorList(order);
527   }
528
529   public String orderBy(String order, String undoName)
530   {
531     return orderBy(order, undoName, separator);
532   }
533
534   public String orderBy(String order, String undoName, String sep)
535   {
536     return orderAlignmentBy(getDefaultTargetFrame(), order, undoName, sep);
537   }
538
539   public String orderAlignmentBy(AlignFrame alf, String order,
540           String undoName, String sep)
541   {
542     String[] ids = separatorListToArray(order, sep);
543     SequenceI[] sqs = null;
544     if (ids != null && ids.length > 0)
545     {
546       jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
547               alf.viewport.getAlignment().getSequencesArray());
548       int s = 0;
549       sqs = new SequenceI[ids.length];
550       for (int i = 0; i < ids.length; i++)
551       {
552         if (ids[i].trim().length() == 0)
553         {
554           continue;
555         }
556         SequenceI sq = matcher.findIdMatch(ids[i]);
557         if (sq != null)
558         {
559           sqs[s++] = sq;
560         }
561       }
562       if (s > 0)
563       {
564         SequenceI[] sqq = new SequenceI[s];
565         System.arraycopy(sqs, 0, sqq, 0, s);
566         sqs = sqq;
567       }
568       else
569       {
570         sqs = null;
571       }
572     }
573     if (sqs == null)
574     {
575       return "";
576     }
577     ;
578     AlignmentOrder aorder = new AlignmentOrder(sqs);
579
580     if (undoName != null && undoName.trim().length() == 0)
581     {
582       undoName = null;
583     }
584
585     return alf.sortBy(aorder, undoName) ? "true" : "";
586   }
587
588   public String getAlignment(String format)
589   {
590     return getAlignmentFrom(getDefaultTargetFrame(), format, "true");
591   }
592
593   public String getAlignmentFrom(AlignFrame alf, String format)
594   {
595     return getAlignmentFrom(alf, format, "true");
596   }
597
598   public String getAlignment(String format, String suffix)
599   {
600     return getAlignmentFrom(getDefaultTargetFrame(), format, suffix);
601   }
602
603   public String getAlignmentFrom(AlignFrame alf, String format,
604           String suffix)
605   {
606     try
607     {
608       boolean seqlimits = suffix.equalsIgnoreCase("true");
609
610       String reply = new AppletFormatAdapter().formatSequences(format,
611               alf.viewport.getAlignment(), seqlimits);
612       return reply;
613     } catch (Exception ex)
614     {
615       ex.printStackTrace();
616       return "Error retrieving alignment in " + format + " format. ";
617     }
618   }
619
620   public void loadAnnotation(String annotation)
621   {
622     loadAnnotationFrom(getDefaultTargetFrame(), annotation);
623   }
624
625   public void loadAnnotationFrom(AlignFrame alf, String annotation)
626   {
627     if (new AnnotationFile().readAnnotationFile(alf.getAlignViewport()
628             .getAlignment(), annotation, AppletFormatAdapter.PASTE))
629     {
630       alf.alignPanel.fontChanged();
631       alf.alignPanel.setScrollValues(0, 0);
632     }
633     else
634     {
635       alf.parseFeaturesFile(annotation, AppletFormatAdapter.PASTE);
636     }
637   }
638
639   public String getFeatures(String format)
640   {
641     return getFeaturesFrom(getDefaultTargetFrame(), format);
642   }
643
644   public String getFeaturesFrom(AlignFrame alf, String format)
645   {
646     return alf.outputFeatures(false, format);
647   }
648
649   public String getAnnotation()
650   {
651     return getAnnotationFrom(getDefaultTargetFrame());
652   }
653
654   public String getAnnotationFrom(AlignFrame alf)
655   {
656     return alf.outputAnnotations(false);
657   }
658
659   public AlignFrame newView()
660   {
661     return newViewFrom(getDefaultTargetFrame());
662   }
663
664   public AlignFrame newView(String name)
665   {
666     return newViewFrom(getDefaultTargetFrame(), name);
667   }
668
669   public AlignFrame newViewFrom(AlignFrame alf)
670   {
671     return alf.newView(null);
672   }
673
674   public AlignFrame newViewFrom(AlignFrame alf, String name)
675   {
676     return alf.newView(name);
677   }
678
679   /**
680    * 
681    * @param text
682    *          alignment file as a string
683    * @param title
684    *          window title
685    * @return null or new alignment frame
686    */
687   public AlignFrame loadAlignment(String text, String title)
688   {
689     Alignment al = null;
690
691     String format = new IdentifyFile().Identify(text,
692             AppletFormatAdapter.PASTE);
693     try
694     {
695       al = new AppletFormatAdapter().readFile(text,
696               AppletFormatAdapter.PASTE, format);
697       if (al.getHeight() > 0)
698       {
699         return new AlignFrame(al, this, title, false);
700       }
701     } catch (java.io.IOException ex)
702     {
703       ex.printStackTrace();
704     }
705     return null;
706   }
707
708   public void setMouseoverListener(String listener)
709   {
710     setMouseoverListener(currentAlignFrame, listener);
711   }
712
713   private Vector mouseoverListeners = new Vector();
714
715   public void setMouseoverListener(AlignFrame af, String listener)
716   {
717     if (listener != null)
718     {
719       listener = listener.trim();
720       if (listener.length() == 0)
721       {
722         System.err
723                 .println("jalview Javascript error: Ignoring empty function for mouseover listener.");
724         return;
725       }
726     }
727     jalview.javascript.MouseOverListener mol = new jalview.javascript.MouseOverListener(
728             this, af, listener);
729     mouseoverListeners.addElement(mol);
730     StructureSelectionManager.getStructureSelectionManager()
731             .addStructureViewerListener(mol);
732     if (debug)
733     {
734       System.err.println("Added a mouseover listener for "
735               + ((af == null) ? "All frames" : "Just views for "
736                       + af.getAlignViewport().getSequenceSetId()));
737       System.err.println("There are now " + mouseoverListeners.size()
738               + " listeners in total.");
739     }
740   }
741
742   public void setSelectionListener(String listener)
743   {
744     setSelectionListener(null, listener);
745   }
746
747   public void setSelectionListener(AlignFrame af, String listener)
748   {
749     if (listener != null)
750     {
751       listener = listener.trim();
752       if (listener.length() == 0)
753       {
754         System.err
755                 .println("jalview Javascript error: Ignoring empty function for selection listener.");
756         return;
757       }
758     }
759     jalview.javascript.JsSelectionSender mol = new jalview.javascript.JsSelectionSender(
760             this, af, listener);
761     mouseoverListeners.addElement(mol);
762     StructureSelectionManager.getStructureSelectionManager()
763             .addSelectionListener(mol);
764     if (debug)
765     {
766       System.err.println("Added a selection listener for "
767               + ((af == null) ? "All frames" : "Just views for "
768                       + af.getAlignViewport().getSequenceSetId()));
769       System.err.println("There are now " + mouseoverListeners.size()
770               + " listeners in total.");
771     }
772   }
773
774   /**
775    * remove any callback using the given listener function and associated with
776    * the given alignFrame (or null for all callbacks)
777    * 
778    * @param af
779    *          (may be null)
780    * @param listener
781    *          (may be null)
782    */
783   public void removeJavascriptListener(AlignFrame af, String listener)
784   {
785     if (listener != null)
786     {
787       listener = listener.trim();
788       if (listener.length() == 0)
789       {
790         listener = null;
791       }
792     }
793     boolean rprt = false;
794     for (int ms = 0, msSize = mouseoverListeners.size(); ms < msSize;)
795     {
796       Object lstn = mouseoverListeners.elementAt(ms);
797       JsCallBack lstner = (JsCallBack) lstn;
798       if ((af == null || lstner.getAlignFrame() == af)
799               && (listener == null || lstner.getListenerFunction().equals(
800                       listener)))
801       {
802         mouseoverListeners.removeElement(lstner);
803         msSize--;
804         if (lstner instanceof SelectionListener)
805         {
806           StructureSelectionManager.getStructureSelectionManager()
807                   .removeSelectionListener((SelectionListener) lstner);
808         }
809         else
810         {
811           StructureSelectionManager.getStructureSelectionManager()
812                   .removeStructureViewerListener(lstner, null);
813         }
814         rprt = debug;
815         if (debug)
816         {
817           System.err.println("Removed listener '" + listener + "'");
818         }
819       }
820       else
821       {
822         ms++;
823       }
824     }
825     if (rprt)
826     {
827       System.err.println("There are now " + mouseoverListeners.size()
828               + " listeners in total.");
829     }
830   }
831
832   public void stop()
833   {
834     if (mouseoverListeners != null)
835     {
836       while (mouseoverListeners.size() > 0)
837       {
838         Object mol = mouseoverListeners.elementAt(0);
839         mouseoverListeners.removeElement(mol);
840         if (mol instanceof SelectionListener)
841         {
842           StructureSelectionManager.getStructureSelectionManager()
843                   .removeSelectionListener((SelectionListener) mol);
844         }
845         else
846         {
847           StructureSelectionManager.getStructureSelectionManager()
848                   .removeStructureViewerListener(mol, null);
849         }
850       }
851     }
852     jalview.javascript.JSFunctionExec.stopQueue();
853   }
854
855   /**
856    * send a mouseover message to all the alignment windows associated with the
857    * given residue in the pdbfile
858    * 
859    * @param pdbResNum
860    * @param chain
861    * @param pdbfile
862    */
863   public void mouseOverStructure(int pdbResNum, String chain, String pdbfile)
864   {
865     StructureSelectionManager.getStructureSelectionManager()
866             .mouseOverStructure(pdbResNum, chain, pdbfile);
867   }
868
869   // //////////////////////////////////////////////
870   // //////////////////////////////////////////////
871
872   public static int lastFrameX = 200;
873
874   public static int lastFrameY = 200;
875
876   boolean fileFound = true;
877
878   String file = "No file";
879
880   Button launcher = new Button("Start Jalview");
881
882   /**
883    * The currentAlignFrame is static, it will change if and when the user
884    * selects a new window. Note that it will *never* point back to the embedded
885    * AlignFrame if the applet is started as embedded on the page and then
886    * afterwards a new view is created.
887    */
888   public AlignFrame currentAlignFrame = null;
889
890   /**
891    * This is the first frame to be displayed, and does not change. API calls
892    * will default to this instance if currentAlignFrame is null.
893    */
894   AlignFrame initialAlignFrame = null;
895
896   boolean embedded = false;
897
898   private boolean checkForJmol = true;
899
900   private boolean checkedForJmol = false; // ensure we don't check for jmol
901
902   // every time the app is re-inited
903
904   public boolean jmolAvailable = false;
905
906   private boolean alignPdbStructures = false;
907
908   public static boolean debug = false;
909
910   static String builddate = null, version = null;
911
912   private static void initBuildDetails()
913   {
914     if (builddate == null)
915     {
916       builddate = "unknown";
917       version = "test";
918       java.net.URL url = JalviewLite.class
919               .getResource("/.build_properties");
920       if (url != null)
921       {
922         try
923         {
924           BufferedReader reader = new BufferedReader(new InputStreamReader(
925                   url.openStream()));
926           String line;
927           while ((line = reader.readLine()) != null)
928           {
929             if (line.indexOf("VERSION") > -1)
930             {
931               version = line.substring(line.indexOf("=") + 1);
932             }
933             if (line.indexOf("BUILD_DATE") > -1)
934             {
935               builddate = line.substring(line.indexOf("=") + 1);
936             }
937           }
938         } catch (Exception ex)
939         {
940           ex.printStackTrace();
941         }
942       }
943     }
944   }
945
946   public static String getBuildDate()
947   {
948     initBuildDetails();
949     return builddate;
950   }
951
952   public static String getVersion()
953   {
954     initBuildDetails();
955     return version;
956   }
957
958   // public JSObject scriptObject = null;
959
960   /**
961    * init method for Jalview Applet
962    */
963   public void init()
964   {
965     // remove any handlers that might be hanging around from an earlier instance
966     try
967     {
968       if (debug)
969       {
970         System.err.println("Applet context is '"
971                 + getAppletContext().getClass().toString() + "'");
972       }
973       JSObject scriptObject = JSObject.getWindow(this);
974       if (debug && scriptObject != null)
975       {
976         System.err.println("Applet has Javascript callback support.");
977       }
978
979     } catch (Exception ex)
980     {
981       System.err
982               .println("Warning: No JalviewLite javascript callbacks available.");
983       if (debug)
984       {
985         ex.printStackTrace();
986       }
987     }
988     /**
989      * turn on extra applet debugging
990      */
991     String dbg = getParameter("debug");
992     if (dbg != null)
993     {
994       debug = dbg.toLowerCase().equals("true");
995     }
996     if (debug)
997     {
998
999       System.err.println("JalviewLite Version " + getVersion());
1000       System.err.println("Build Date : " + getBuildDate());
1001
1002     }
1003     /**
1004      * if true disable the check for jmol
1005      */
1006     String chkforJmol = getParameter("nojmol");
1007     if (chkforJmol != null)
1008     {
1009       checkForJmol = !chkforJmol.equals("true");
1010     }
1011     /**
1012      * get the separator parameter if present
1013      */
1014     String sep = getParameter("separator");
1015     if (sep != null)
1016     {
1017       if (sep.length() > 0)
1018       {
1019         separator = sep;
1020         if (debug)
1021         {
1022           System.err.println("Separator set to '" + separator + "'");
1023         }
1024       }
1025       else
1026       {
1027         throw new Error(
1028                 "Invalid separator parameter - must be non-zero length");
1029       }
1030     }
1031     int r = 255;
1032     int g = 255;
1033     int b = 255;
1034     String param = getParameter("RGB");
1035
1036     if (param != null)
1037     {
1038       try
1039       {
1040         r = Integer.parseInt(param.substring(0, 2), 16);
1041         g = Integer.parseInt(param.substring(2, 4), 16);
1042         b = Integer.parseInt(param.substring(4, 6), 16);
1043       } catch (Exception ex)
1044       {
1045         r = 255;
1046         g = 255;
1047         b = 255;
1048       }
1049     }
1050     param = getParameter("label");
1051     if (param != null)
1052     {
1053       launcher.setLabel(param);
1054     }
1055
1056     setBackground(new Color(r, g, b));
1057
1058     file = getParameter("file");
1059
1060     if (file == null)
1061     {
1062       // Maybe the sequences are added as parameters
1063       StringBuffer data = new StringBuffer("PASTE");
1064       int i = 1;
1065       while ((file = getParameter("sequence" + i)) != null)
1066       {
1067         data.append(file.toString() + "\n");
1068         i++;
1069       }
1070       if (data.length() > 5)
1071       {
1072         file = data.toString();
1073       }
1074     }
1075
1076     final JalviewLite jvapplet = this;
1077     if (getParameter("embedded") != null
1078             && getParameter("embedded").equalsIgnoreCase("true"))
1079     {
1080       // Launch as embedded applet in page
1081       embedded = true;
1082       LoadingThread loader = new LoadingThread(file, jvapplet);
1083       loader.start();
1084     }
1085     else if (file != null)
1086     {
1087       if (getParameter("showbutton") == null
1088               || !getParameter("showbutton").equalsIgnoreCase("false"))
1089       {
1090         // Add the JalviewLite 'Button' to the page
1091         add(launcher);
1092         launcher.addActionListener(new java.awt.event.ActionListener()
1093         {
1094           public void actionPerformed(ActionEvent e)
1095           {
1096             LoadingThread loader = new LoadingThread(file, jvapplet);
1097             loader.start();
1098           }
1099         });
1100       }
1101       else
1102       {
1103         // Open jalviewLite immediately.
1104         LoadingThread loader = new LoadingThread(file, jvapplet);
1105         loader.start();
1106       }
1107     }
1108     else
1109     {
1110       // jalview initialisation with no alignment. loadAlignment() method can
1111       // still be called to open new alignments.
1112       file = "NO FILE";
1113       fileFound = false;
1114       // callInitCallback();
1115     }
1116   }
1117
1118   private void callInitCallback()
1119   {
1120     String initjscallback = getParameter("oninit");
1121     if (initjscallback == null)
1122     {
1123       return;
1124     }
1125     initjscallback = initjscallback.trim();
1126     if (initjscallback.length() > 0)
1127     {
1128       JSObject scriptObject = null;
1129       try
1130       {
1131         scriptObject = JSObject.getWindow(this);
1132       } catch (Exception ex)
1133       {
1134       }
1135       ;
1136       if (scriptObject != null)
1137       {
1138         try
1139         {
1140           // do onInit with the JS executor thread
1141           new JSFunctionExec(this).executeJavascriptFunction(true,
1142                   initjscallback, null, "Calling oninit callback '"
1143                           + initjscallback + "'.");
1144         } catch (Exception e)
1145         {
1146           System.err.println("Exception when executing _oninit callback '"
1147                   + initjscallback + "'.");
1148           e.printStackTrace();
1149         }
1150       }
1151       else
1152       {
1153         System.err.println("Not executing _oninit callback '"
1154                 + initjscallback + "' - no scripting allowed.");
1155       }
1156     }
1157   }
1158
1159   /**
1160    * Initialises and displays a new java.awt.Frame
1161    * 
1162    * @param frame
1163    *          java.awt.Frame to be displayed
1164    * @param title
1165    *          title of new frame
1166    * @param width
1167    *          width if new frame
1168    * @param height
1169    *          height of new frame
1170    */
1171   public static void addFrame(final Frame frame, String title, int width,
1172           int height)
1173   {
1174     frame.setLocation(lastFrameX, lastFrameY);
1175     lastFrameX += 40;
1176     lastFrameY += 40;
1177     frame.setSize(width, height);
1178     frame.setTitle(title);
1179     frame.addWindowListener(new WindowAdapter()
1180     {
1181       public void windowClosing(WindowEvent e)
1182       {
1183         if (frame instanceof AlignFrame)
1184         {
1185           ((AlignFrame) frame).closeMenuItem_actionPerformed();
1186           if (((AlignFrame) frame).viewport.applet.currentAlignFrame == frame)
1187           {
1188             ((AlignFrame) frame).viewport.applet.currentAlignFrame = null;
1189           }
1190         }
1191         lastFrameX -= 40;
1192         lastFrameY -= 40;
1193         if (frame instanceof EmbmenuFrame)
1194         {
1195           ((EmbmenuFrame) frame).destroyMenus();
1196         }
1197         frame.setMenuBar(null);
1198         frame.dispose();
1199       }
1200
1201       public void windowActivated(WindowEvent e)
1202       {
1203         if (frame instanceof AlignFrame)
1204         {
1205           ((AlignFrame) frame).viewport.applet.currentAlignFrame = (AlignFrame) frame;
1206           if (debug)
1207           {
1208             System.err.println("Activated window " + frame);
1209           }
1210         }
1211         // be good.
1212         super.windowActivated(e);
1213       }
1214       /*
1215        * Probably not necessary to do this - see TODO above. (non-Javadoc)
1216        * 
1217        * @see
1218        * java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent
1219        * )
1220        * 
1221        * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
1222        * frame) { currentAlignFrame = null; if (debug) {
1223        * System.err.println("Deactivated window "+frame); } }
1224        * super.windowDeactivated(e); }
1225        */
1226     });
1227     frame.setVisible(true);
1228   }
1229
1230   /**
1231    * This paints the background surrounding the "Launch Jalview button" <br>
1232    * <br>
1233    * If file given in parameter not found, displays error message
1234    * 
1235    * @param g
1236    *          graphics context
1237    */
1238   public void paint(Graphics g)
1239   {
1240     if (!fileFound)
1241     {
1242       g.setColor(new Color(200, 200, 200));
1243       g.setColor(Color.cyan);
1244       g.fillRect(0, 0, getSize().width, getSize().height);
1245       g.setColor(Color.red);
1246       g.drawString("Jalview can't open file", 5, 15);
1247       g.drawString("\"" + file + "\"", 5, 30);
1248     }
1249     else if (embedded)
1250     {
1251       g.setColor(Color.black);
1252       g.setFont(new Font("Arial", Font.BOLD, 24));
1253       g.drawString("Jalview Applet", 50, getSize().height / 2 - 30);
1254       g.drawString("Loading Data...", 50, getSize().height / 2);
1255     }
1256   }
1257
1258   /**
1259    * get all components associated with the applet of the given type
1260    * 
1261    * @param class1
1262    * @return
1263    */
1264   public Vector getAppletWindow(Class class1)
1265   {
1266     Vector wnds = new Vector();
1267     Component[] cmp = getComponents();
1268     if (cmp != null)
1269     {
1270       for (int i = 0; i < cmp.length; i++)
1271       {
1272         if (class1.isAssignableFrom(cmp[i].getClass()))
1273         {
1274           wnds.addElement(cmp);
1275         }
1276       }
1277     }
1278     return wnds;
1279   }
1280
1281   class LoadJmolThread extends Thread
1282   {
1283     private boolean running = false;
1284
1285     public void run()
1286     {
1287       if (running || checkedForJmol)
1288       {
1289         return;
1290       }
1291       running = true;
1292       if (checkForJmol)
1293       {
1294         try
1295         {
1296           if (!System.getProperty("java.version").startsWith("1.1"))
1297           {
1298             Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
1299             jmolAvailable = true;
1300           }
1301           if (!jmolAvailable)
1302           {
1303             System.out
1304                     .println("Jmol not available - Using MCview for structures");
1305           }
1306         } catch (java.lang.ClassNotFoundException ex)
1307         {
1308         }
1309       }
1310       else
1311       {
1312         jmolAvailable = false;
1313         if (debug)
1314         {
1315           System.err
1316                   .println("Skipping Jmol check. Will use MCView (probably)");
1317         }
1318       }
1319       checkedForJmol = true;
1320       running = false;
1321     }
1322
1323     public boolean notFinished()
1324     {
1325       return running || !checkedForJmol;
1326     }
1327   }
1328
1329   class LoadingThread extends Thread
1330   {
1331     /**
1332      * State variable: File source
1333      */
1334     String file;
1335
1336     /**
1337      * State variable: protocol for access to file source
1338      */
1339     String protocol;
1340
1341     /**
1342      * State variable: format of file source
1343      */
1344     String format;
1345
1346     String _file;
1347
1348     JalviewLite applet;
1349
1350     private void dbgMsg(String msg)
1351     {
1352       if (applet.debug)
1353       {
1354         System.err.println(msg);
1355       }
1356     }
1357
1358     /**
1359      * update the protocol state variable for accessing the datasource located
1360      * by file.
1361      * 
1362      * @param file
1363      * @return possibly updated datasource string
1364      */
1365     public String setProtocolState(String file)
1366     {
1367       if (file.startsWith("PASTE"))
1368       {
1369         file = file.substring(5);
1370         protocol = AppletFormatAdapter.PASTE;
1371       }
1372       else if (inArchive(file))
1373       {
1374         protocol = AppletFormatAdapter.CLASSLOADER;
1375       }
1376       else
1377       {
1378         file = addProtocol(file);
1379         protocol = AppletFormatAdapter.URL;
1380       }
1381       dbgMsg("Protocol identified as '" + protocol + "'");
1382       return file;
1383     }
1384
1385     public LoadingThread(String _file, JalviewLite _applet)
1386     {
1387       this._file = _file;
1388       applet = _applet;
1389     }
1390
1391     public void run()
1392     {
1393       LoadJmolThread jmolchecker = new LoadJmolThread();
1394       jmolchecker.start();
1395       while (jmolchecker.notFinished())
1396       {
1397         // wait around until the Jmol check is complete.
1398         try
1399         {
1400           Thread.sleep(2);
1401         } catch (Exception e)
1402         {
1403         }
1404         ;
1405       }
1406       startLoading();
1407       // applet.callInitCallback();
1408     }
1409
1410     private void startLoading()
1411     {
1412       AlignFrame newAlignFrame;
1413       dbgMsg("Loading thread started with:\n>>file\n" + _file + ">>endfile");
1414       file = setProtocolState(_file);
1415
1416       format = new jalview.io.IdentifyFile().Identify(file, protocol);
1417       dbgMsg("File identified as '" + format + "'");
1418       dbgMsg("Loading started.");
1419       Alignment al = null;
1420       try
1421       {
1422         al = new AppletFormatAdapter().readFile(file, protocol, format);
1423       } catch (java.io.IOException ex)
1424       {
1425         dbgMsg("File load exception.");
1426         ex.printStackTrace();
1427         if (debug)
1428         {
1429           try
1430           {
1431             FileParse fp = new FileParse(file, protocol);
1432             String ln = null;
1433             dbgMsg(">>>Dumping contents of '" + file + "' " + "("
1434                     + protocol + ")");
1435             while ((ln = fp.nextLine()) != null)
1436             {
1437               dbgMsg(ln);
1438             }
1439             dbgMsg(">>>Dump finished.");
1440           } catch (Exception e)
1441           {
1442             System.err
1443                     .println("Exception when trying to dump the content of the file parameter.");
1444             e.printStackTrace();
1445           }
1446         }
1447       }
1448       if ((al != null) && (al.getHeight() > 0))
1449       {
1450         dbgMsg("Successfully loaded file.");
1451         newAlignFrame = new AlignFrame(al, applet, file, embedded);
1452         if (initialAlignFrame == null)
1453         {
1454           initialAlignFrame = newAlignFrame;
1455         }
1456         // update the focus.
1457         currentAlignFrame = newAlignFrame;
1458
1459         if (protocol == jalview.io.AppletFormatAdapter.PASTE)
1460         {
1461           newAlignFrame.setTitle("Sequences from "
1462                   + applet.getDocumentBase());
1463         }
1464
1465         newAlignFrame.statusBar.setText("Successfully loaded file " + file);
1466
1467         String treeFile = applet.getParameter("tree");
1468         if (treeFile == null)
1469         {
1470           treeFile = applet.getParameter("treeFile");
1471         }
1472
1473         if (treeFile != null)
1474         {
1475           try
1476           {
1477             treeFile = setProtocolState(treeFile);
1478             /*
1479              * if (inArchive(treeFile)) { protocol =
1480              * AppletFormatAdapter.CLASSLOADER; } else { protocol =
1481              * AppletFormatAdapter.URL; treeFile = addProtocol(treeFile); }
1482              */
1483             jalview.io.NewickFile fin = new jalview.io.NewickFile(treeFile,
1484                     protocol);
1485
1486             fin.parse();
1487
1488             if (fin.getTree() != null)
1489             {
1490               newAlignFrame.loadTree(fin, treeFile);
1491               dbgMsg("Successfuly imported tree.");
1492             }
1493             else
1494             {
1495               dbgMsg("Tree parameter did not resolve to a valid tree.");
1496             }
1497           } catch (Exception ex)
1498           {
1499             ex.printStackTrace();
1500           }
1501         }
1502
1503         String param = applet.getParameter("features");
1504         if (param != null)
1505         {
1506           param = setProtocolState(param);
1507
1508           newAlignFrame.parseFeaturesFile(param, protocol);
1509         }
1510
1511         param = applet.getParameter("showFeatureSettings");
1512         if (param != null && param.equalsIgnoreCase("true"))
1513         {
1514           newAlignFrame.viewport.showSequenceFeatures(true);
1515           new FeatureSettings(newAlignFrame.alignPanel);
1516         }
1517
1518         param = applet.getParameter("annotations");
1519         if (param != null)
1520         {
1521           param = setProtocolState(param);
1522
1523           if (new AnnotationFile().readAnnotationFile(
1524                   newAlignFrame.viewport.getAlignment(), param, protocol))
1525           {
1526             newAlignFrame.alignPanel.fontChanged();
1527             newAlignFrame.alignPanel.setScrollValues(0, 0);
1528           }
1529           else
1530           {
1531             System.err
1532                     .println("Annotations were not added from annotation file '"
1533                             + param + "'");
1534           }
1535
1536         }
1537
1538         param = applet.getParameter("jnetfile");
1539         if (param != null)
1540         {
1541           try
1542           {
1543             param = setProtocolState(param);
1544             jalview.io.JPredFile predictions = new jalview.io.JPredFile(
1545                     param, protocol);
1546             JnetAnnotationMaker.add_annotation(predictions,
1547                     newAlignFrame.viewport.getAlignment(), 0, false); // false==do
1548             // not
1549             // add
1550             // sequence
1551             // profile
1552             // from
1553             // concise
1554             // output
1555             newAlignFrame.alignPanel.fontChanged();
1556             newAlignFrame.alignPanel.setScrollValues(0, 0);
1557           } catch (Exception ex)
1558           {
1559             ex.printStackTrace();
1560           }
1561         }
1562         /*
1563          * <param name="alignpdbfiles" value="false/true"/> Undocumented for 2.6
1564          * - related to JAL-434
1565          */
1566         applet.setAlignPdbStructures(getDefaultParameter("alignpdbfiles",
1567                 false));
1568         /*
1569          * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
1570          * PDB|1GAQ|1GAQ|C">
1571          * 
1572          * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
1573          * 
1574          * <param name="PDBfile3" value="1q0o Q45135_9MICO">
1575          */
1576
1577         int pdbFileCount = 0;
1578         // Accumulate pdbs here if they are heading for the same view (if
1579         // alignPdbStructures is true)
1580         Vector pdbs = new Vector();
1581         do
1582         {
1583           if (pdbFileCount > 0)
1584             param = applet.getParameter("PDBFILE" + pdbFileCount);
1585           else
1586             param = applet.getParameter("PDBFILE");
1587
1588           if (param != null)
1589           {
1590             PDBEntry pdb = new PDBEntry();
1591
1592             String seqstring;
1593             SequenceI[] seqs = null;
1594             String[] chains = null;
1595
1596             StringTokenizer st = new StringTokenizer(param, " ");
1597
1598             if (st.countTokens() < 2)
1599             {
1600               String sequence = applet.getParameter("PDBSEQ");
1601               if (sequence != null)
1602                 seqs = new SequenceI[]
1603                 { (Sequence) newAlignFrame.getAlignViewport()
1604                         .getAlignment().findName(sequence) };
1605
1606             }
1607             else
1608             {
1609               param = st.nextToken();
1610               Vector tmp = new Vector();
1611               Vector tmp2 = new Vector();
1612
1613               while (st.hasMoreTokens())
1614               {
1615                 seqstring = st.nextToken();
1616                 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
1617                 if (st2.countTokens() > 1)
1618                 {
1619                   // This is the chain
1620                   tmp2.addElement(st2.nextToken());
1621                   seqstring = st2.nextToken();
1622                 }
1623                 tmp.addElement((Sequence) newAlignFrame.getAlignViewport()
1624                         .getAlignment().findName(seqstring));
1625               }
1626
1627               seqs = new SequenceI[tmp.size()];
1628               tmp.copyInto(seqs);
1629               if (tmp2.size() == tmp.size())
1630               {
1631                 chains = new String[tmp2.size()];
1632                 tmp2.copyInto(chains);
1633               }
1634             }
1635             param = setProtocolState(param);
1636
1637             if (// !jmolAvailable
1638             // &&
1639             protocol == AppletFormatAdapter.CLASSLOADER)
1640             {
1641               // TODO: verify this Re:
1642               // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
1643               // This exception preserves the current behaviour where, even if
1644               // the local pdb file was identified in the class loader
1645               protocol = AppletFormatAdapter.URL; // this is probably NOT
1646               // CORRECT!
1647               param = addProtocol(param); //
1648             }
1649
1650             pdb.setFile(param);
1651
1652             if (seqs != null)
1653             {
1654               for (int i = 0; i < seqs.length; i++)
1655               {
1656                 if (seqs[i] != null)
1657                 {
1658                   ((Sequence) seqs[i]).addPDBId(pdb);
1659                 }
1660                 else
1661                 {
1662                   if (JalviewLite.debug)
1663                   {
1664                     // this may not really be a problem but we give a warning
1665                     // anyway
1666                     System.err
1667                             .println("Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
1668                                     + i + ")");
1669                   }
1670                 }
1671               }
1672
1673               if (!alignPdbStructures)
1674               {
1675                 newAlignFrame.newStructureView(applet, pdb, seqs, chains,
1676                         protocol);
1677               }
1678               else
1679               {
1680                 pdbs.addElement(new Object[]
1681                 { pdb, seqs, chains, new String(protocol) });
1682               }
1683             }
1684           }
1685
1686           pdbFileCount++;
1687         } while (pdbFileCount < 10);
1688         if (pdbs.size() > 0)
1689         {
1690           SequenceI[][] seqs = new SequenceI[pdbs.size()][];
1691           PDBEntry[] pdb = new PDBEntry[pdbs.size()];
1692           String[][] chains = new String[pdbs.size()][];
1693           String[] protocols = new String[pdbs.size()];
1694           for (int pdbsi = 0, pdbsiSize = pdbs.size(); pdbsi < pdbsiSize; pdbsi++)
1695           {
1696             Object[] o = (Object[]) pdbs.elementAt(pdbsi);
1697             pdb[pdbsi] = (PDBEntry) o[0];
1698             seqs[pdbsi] = (SequenceI[]) o[1];
1699             chains[pdbsi] = (String[]) o[2];
1700             protocols[pdbsi] = (String) o[3];
1701           }
1702           newAlignFrame.alignedStructureView(applet, pdb, seqs, chains,
1703                   protocols);
1704
1705         }
1706         // ///////////////////////////
1707         // modify display of features
1708         //
1709         // hide specific groups
1710         param = applet.getParameter("hidefeaturegroups");
1711         if (param != null)
1712         {
1713           applet.setFeatureGroupStateOn(newAlignFrame, param, false);
1714         }
1715         // show specific groups
1716         param = applet.getParameter("showfeaturegroups");
1717         if (param != null)
1718         {
1719           applet.setFeatureGroupStateOn(newAlignFrame, param, true);
1720         }
1721       }
1722       else
1723       {
1724         fileFound = false;
1725         applet.remove(launcher);
1726         applet.repaint();
1727       }
1728     }
1729
1730     /**
1731      * Discovers whether the given file is in the Applet Archive
1732      * 
1733      * @param file
1734      *          String
1735      * @return boolean
1736      */
1737     boolean inArchive(String file)
1738     {
1739       // This might throw a security exception in certain browsers
1740       // Netscape Communicator for instance.
1741       try
1742       {
1743         boolean rtn = (getClass().getResourceAsStream("/" + file) != null);
1744         if (debug)
1745         {
1746           System.err.println("Resource '" + file + "' was "
1747                   + (rtn ? "" : "not") + " located by classloader.");
1748         }
1749         return rtn;
1750       } catch (Exception ex)
1751       {
1752         System.out.println("Exception checking resources: " + file + " "
1753                 + ex);
1754         return false;
1755       }
1756     }
1757
1758     String addProtocol(String file)
1759     {
1760       if (file.indexOf("://") == -1)
1761       {
1762         file = applet.getCodeBase() + file;
1763         if (debug)
1764         {
1765           System.err.println("Prepended codebase for resource: '" + file
1766                   + "'");
1767         }
1768       }
1769
1770       return file;
1771     }
1772   }
1773
1774   /**
1775    * @return the default alignFrame acted on by the public applet methods. May
1776    *         return null with an error message on System.err indicating the
1777    *         fact.
1778    */
1779   public AlignFrame getDefaultTargetFrame()
1780   {
1781     if (currentAlignFrame != null)
1782     {
1783       return currentAlignFrame;
1784     }
1785     if (initialAlignFrame != null)
1786     {
1787       return initialAlignFrame;
1788     }
1789     System.err
1790             .println("Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
1791     return null;
1792   }
1793
1794   /**
1795    * separator used for separatorList
1796    */
1797   protected String separator = "" + ((char) 0x00AC); // the default used to be
1798                                                      // '|' but many sequence
1799                                                      // IDS include pipes.
1800
1801   /**
1802    * parse the string into a list
1803    * 
1804    * @param list
1805    * @return elements separated by separator
1806    */
1807   public String[] separatorListToArray(String list)
1808   {
1809     return separatorListToArray(list, separator);
1810   }
1811
1812   /**
1813    * parse the string into a list
1814    * 
1815    * @param list
1816    * @param separator
1817    * @return elements separated by separator
1818    */
1819   public String[] separatorListToArray(String list, String separator)
1820   {
1821     // note separator local variable intentionally masks object field
1822     int seplen = separator.length();
1823     if (list == null || list.equals("") || list.equals(separator))
1824       return null;
1825     java.util.Vector jv = new Vector();
1826     int cp = 0, pos;
1827     while ((pos = list.indexOf(separator, cp)) > cp)
1828     {
1829       jv.addElement(list.substring(cp, pos));
1830       cp = pos + seplen;
1831     }
1832     if (cp < list.length())
1833     {
1834       String c = list.substring(cp);
1835       if (!c.equals(separator))
1836       {
1837         jv.addElement(c);
1838       }
1839     }
1840     if (jv.size() > 0)
1841     {
1842       String[] v = new String[jv.size()];
1843       for (int i = 0; i < v.length; i++)
1844       {
1845         v[i] = (String) jv.elementAt(i);
1846       }
1847       jv.removeAllElements();
1848       if (debug)
1849       {
1850         System.err.println("Array from '" + separator
1851                 + "' separated List:\n" + v.length);
1852         for (int i = 0; i < v.length; i++)
1853         {
1854           System.err.println("item " + i + " '" + v[i] + "'");
1855         }
1856       }
1857       return v;
1858     }
1859     if (debug)
1860     {
1861       System.err.println("Empty Array from '" + separator
1862               + "' separated List");
1863     }
1864     return null;
1865   }
1866
1867   /**
1868    * concatenate the list with separator
1869    * 
1870    * @param list
1871    * @return concatenated string
1872    */
1873   public String arrayToSeparatorList(String[] list)
1874   {
1875     return arrayToSeparatorList(list, separator);
1876   }
1877
1878   /**
1879    * concatenate the list with separator
1880    * 
1881    * @param list
1882    * @param separator
1883    * @return concatenated string
1884    */
1885   public String arrayToSeparatorList(String[] list, String separator)
1886   {
1887     StringBuffer v = new StringBuffer();
1888     if (list != null && list.length > 0)
1889     {
1890       for (int i = 0, iSize = list.length; i < iSize; i++)
1891       {
1892         if (list[i] != null)
1893         {
1894           if (i > 0)
1895           {
1896             v.append(separator);
1897           }
1898           v.append(list[i]);
1899         }
1900       }
1901       if (debug)
1902       {
1903         System.err.println("Returning '" + separator
1904                 + "' separated List:\n");
1905         System.err.println(v);
1906       }
1907       return v.toString();
1908     }
1909     if (debug)
1910     {
1911       System.err.println("Returning empty '" + separator
1912               + "' separated List\n");
1913     }
1914     return "" + separator;
1915   }
1916
1917   /**
1918    * @return
1919    * @see jalview.appletgui.AlignFrame#getFeatureGroups()
1920    */
1921   public String getFeatureGroups()
1922   {
1923     String lst = arrayToSeparatorList(getDefaultTargetFrame()
1924             .getFeatureGroups());
1925     return lst;
1926   }
1927
1928   /**
1929    * @param alf
1930    *          alignframe to get feature groups on
1931    * @return
1932    * @see jalview.appletgui.AlignFrame#getFeatureGroups()
1933    */
1934   public String getFeatureGroupsOn(AlignFrame alf)
1935   {
1936     String lst = arrayToSeparatorList(alf.getFeatureGroups());
1937     return lst;
1938   }
1939
1940   /**
1941    * @param visible
1942    * @return
1943    * @see jalview.appletgui.AlignFrame#getFeatureGroupsOfState(boolean)
1944    */
1945   public String getFeatureGroupsOfState(boolean visible)
1946   {
1947     return arrayToSeparatorList(getDefaultTargetFrame()
1948             .getFeatureGroupsOfState(visible));
1949   }
1950
1951   /**
1952    * @param alf
1953    *          align frame to get groups of state visible
1954    * @param visible
1955    * @return
1956    * @see jalview.appletgui.AlignFrame#getFeatureGroupsOfState(boolean)
1957    */
1958   public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
1959   {
1960     return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
1961   }
1962
1963   /**
1964    * @param groups
1965    *          tab separated list of group names
1966    * @param state
1967    *          true or false
1968    * @see jalview.appletgui.AlignFrame#setFeatureGroupState(java.lang.String[],
1969    *      boolean)
1970    */
1971   public void setFeatureGroupStateOn(AlignFrame alf, String groups,
1972           boolean state)
1973   {
1974     boolean st = state;// !(state==null || state.equals("") ||
1975     // state.toLowerCase().equals("false"));
1976     alf.setFeatureGroupState(separatorListToArray(groups), st);
1977   }
1978
1979   public void setFeatureGroupState(String groups, boolean state)
1980   {
1981     setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
1982   }
1983
1984   /**
1985    * List separator string
1986    * 
1987    * @return the separator
1988    */
1989   public String getSeparator()
1990   {
1991     return separator;
1992   }
1993
1994   /**
1995    * List separator string
1996    * 
1997    * @param separator
1998    *          the separator to set. empty string will reset separator to default
1999    */
2000   public void setSeparator(String separator)
2001   {
2002     if (separator == null || separator.length() < 1)
2003     {
2004       // reset to default
2005       separator = "" + ((char) 0x00AC);
2006     }
2007     this.separator = separator;
2008     if (debug)
2009     {
2010       System.err.println("Default Separator now: '" + separator + "'");
2011     }
2012   }
2013
2014   /**
2015    * get boolean value of applet parameter 'name' and return default if
2016    * parameter is not set
2017    * 
2018    * @param name
2019    *          name of paremeter
2020    * @param def
2021    *          the value to return otherwise
2022    * @return true or false
2023    */
2024   public boolean getDefaultParameter(String name, boolean def)
2025   {
2026     String stn;
2027     if ((stn = getParameter(name)) == null)
2028     {
2029       return def;
2030     }
2031     if (stn.toLowerCase().equals("true"))
2032     {
2033       return true;
2034     }
2035     return false;
2036   }
2037
2038   /**
2039    * bind a pdb file to a sequence in the given alignFrame.
2040    * 
2041    * @param alFrame
2042    *          - null or specific alignFrame. This specifies the dataset that
2043    *          will be searched for a seuqence called sequenceId
2044    * @param sequenceId
2045    *          - sequenceId within the dataset.
2046    * @param pdbEntryString
2047    *          - the short name for the PDB file
2048    * @param pdbFile
2049    *          - pdb file - either a URL or a valid PDB file.
2050    * @return true if binding was as success TODO: consider making an exception
2051    *         structure for indicating when PDB parsing or seqeunceId location
2052    *         fails.
2053    */
2054   public boolean addPdbFile(AlignFrame alFrame, String sequenceId,
2055           String pdbEntryString, String pdbFile)
2056   {
2057     return alFrame.addPdbFile(sequenceId, pdbEntryString, pdbFile);
2058   }
2059
2060   protected void setAlignPdbStructures(boolean alignPdbStructures)
2061   {
2062     this.alignPdbStructures = alignPdbStructures;
2063   }
2064
2065   public boolean isAlignPdbStructures()
2066   {
2067     return alignPdbStructures;
2068   }
2069
2070   public void start()
2071   {
2072     callInitCallback();
2073   }
2074
2075   /**
2076    * bind structures in a viewer to any matching sequences in an alignFrame (use
2077    * sequenceIds to limit scope of search to specific sequences)
2078    * 
2079    * @param alFrame
2080    * @param viewer
2081    * @param sequenceIds
2082    * @return TODO: consider making an exception structure for indicating when
2083    *         binding fails public SequenceStructureBinding
2084    *         addStructureViewInstance( AlignFrame alFrame, Object viewer, String
2085    *         sequenceIds) {
2086    * 
2087    *         if (sequenceIds != null && sequenceIds.length() > 0) { return
2088    *         alFrame.addStructureViewInstance(viewer,
2089    *         separatorListToArray(sequenceIds)); } else { return
2090    *         alFrame.addStructureViewInstance(viewer, null); } // return null; }
2091    */
2092 }