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