JAL-653 JAL-1780 reorder imports
[jalview.git] / src / jalview / bin / JalviewLite.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.bin;
22
23 import jalview.api.StructureSelectionManagerProvider;
24 import jalview.appletgui.AlignFrame;
25 import jalview.appletgui.AlignViewport;
26 import jalview.appletgui.EmbmenuFrame;
27 import jalview.appletgui.FeatureSettings;
28 import jalview.appletgui.SplitFrame;
29 import jalview.datamodel.Alignment;
30 import jalview.datamodel.AlignmentI;
31 import jalview.datamodel.AlignmentOrder;
32 import jalview.datamodel.ColumnSelection;
33 import jalview.datamodel.PDBEntry;
34 import jalview.datamodel.Sequence;
35 import jalview.datamodel.SequenceGroup;
36 import jalview.datamodel.SequenceI;
37 import jalview.io.AnnotationFile;
38 import jalview.io.AppletFormatAdapter;
39 import jalview.io.FileParse;
40 import jalview.io.IdentifyFile;
41 import jalview.io.JPredFile;
42 import jalview.io.JnetAnnotationMaker;
43 import jalview.io.NewickFile;
44 import jalview.javascript.JSFunctionExec;
45 import jalview.javascript.JalviewLiteJsApi;
46 import jalview.javascript.JsCallBack;
47 import jalview.structure.SelectionListener;
48 import jalview.structure.StructureSelectionManager;
49 import jalview.util.MessageManager;
50
51 import java.applet.Applet;
52 import java.awt.Button;
53 import java.awt.Color;
54 import java.awt.Component;
55 import java.awt.EventQueue;
56 import java.awt.Font;
57 import java.awt.Frame;
58 import java.awt.Graphics;
59 import java.awt.event.ActionEvent;
60 import java.awt.event.WindowAdapter;
61 import java.awt.event.WindowEvent;
62 import java.io.BufferedReader;
63 import java.io.IOException;
64 import java.io.InputStream;
65 import java.io.InputStreamReader;
66 import java.net.URL;
67 import java.util.Hashtable;
68 import java.util.List;
69 import java.util.StringTokenizer;
70 import java.util.Vector;
71
72 import netscape.javascript.JSException;
73 import netscape.javascript.JSObject;
74
75 /**
76  * Jalview Applet. Runs in Java 1.18 runtime
77  * 
78  * @author $author$
79  * @version $Revision: 1.92 $
80  */
81 public class JalviewLite extends Applet implements
82         StructureSelectionManagerProvider, JalviewLiteJsApi
83 {
84
85   private static final String TRUE = "true";
86
87   private static final String FALSE = "false";
88
89   public StructureSelectionManager getStructureSelectionManager()
90   {
91     return StructureSelectionManager.getStructureSelectionManager(this);
92   }
93
94   // /////////////////////////////////////////
95   // The following public methods maybe called
96   // externally, eg via javascript in HTML page
97   /*
98    * (non-Javadoc)
99    * 
100    * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences()
101    */
102   public String getSelectedSequences()
103   {
104     return getSelectedSequencesFrom(getDefaultTargetFrame());
105   }
106
107   /*
108    * (non-Javadoc)
109    * 
110    * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences(java.lang.String)
111    */
112   public String getSelectedSequences(String sep)
113   {
114     return getSelectedSequencesFrom(getDefaultTargetFrame(), sep);
115   }
116
117   /*
118    * (non-Javadoc)
119    * 
120    * @see
121    * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
122    * .AlignFrame)
123    */
124   public String getSelectedSequencesFrom(AlignFrame alf)
125   {
126     return getSelectedSequencesFrom(alf, separator); // ""+0x00AC);
127   }
128
129   /*
130    * (non-Javadoc)
131    * 
132    * @see
133    * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
134    * .AlignFrame, java.lang.String)
135    */
136   public String getSelectedSequencesFrom(AlignFrame alf, String sep)
137   {
138     StringBuffer result = new StringBuffer("");
139     if (sep == null || sep.length() == 0)
140     {
141       sep = separator; // "+0x00AC;
142     }
143     if (alf.viewport.getSelectionGroup() != null)
144     {
145       SequenceI[] seqs = alf.viewport.getSelectionGroup()
146               .getSequencesInOrder(alf.viewport.getAlignment());
147
148       for (int i = 0; i < seqs.length; i++)
149       {
150         result.append(seqs[i].getName());
151         result.append(sep);
152       }
153     }
154
155     return result.toString();
156   }
157
158   /*
159    * (non-Javadoc)
160    * 
161    * @see jalview.bin.JalviewLiteJsApi#highlight(java.lang.String,
162    * java.lang.String, java.lang.String)
163    */
164   public void highlight(String sequenceId, String position,
165           String alignedPosition)
166   {
167     highlightIn(getDefaultTargetFrame(), sequenceId, position,
168             alignedPosition);
169   }
170
171   /*
172    * (non-Javadoc)
173    * 
174    * @see jalview.bin.JalviewLiteJsApi#highlightIn(jalview.appletgui.AlignFrame,
175    * java.lang.String, java.lang.String, java.lang.String)
176    */
177   public void highlightIn(final AlignFrame alf, final String sequenceId,
178           final String position, final String alignedPosition)
179   {
180     // TODO: could try to highlight in all alignments if alf==null
181     jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
182             alf.viewport.getAlignment().getSequencesArray());
183     final SequenceI sq = matcher.findIdMatch(sequenceId);
184     if (sq != null)
185     {
186       int apos = -1;
187       try
188       {
189         apos = new Integer(position).intValue();
190         apos--;
191       } catch (NumberFormatException ex)
192       {
193         return;
194       }
195       final StructureSelectionManagerProvider me = this;
196       final int pos = apos;
197       // use vamsas listener to broadcast to all listeners in scope
198       if (alignedPosition != null
199               && (alignedPosition.trim().length() == 0 || alignedPosition
200                       .toLowerCase().indexOf("false") > -1))
201       {
202         java.awt.EventQueue.invokeLater(new Runnable()
203         {
204           @Override
205           public void run()
206           {
207             StructureSelectionManager.getStructureSelectionManager(me)
208                     .mouseOverVamsasSequence(sq, sq.findIndex(pos), null);
209           }
210         });
211       }
212       else
213       {
214         java.awt.EventQueue.invokeLater(new Runnable()
215         {
216           @Override
217           public void run()
218           {
219             StructureSelectionManager.getStructureSelectionManager(me)
220                     .mouseOverVamsasSequence(sq, pos, null);
221           }
222         });
223       }
224     }
225   }
226
227   /*
228    * (non-Javadoc)
229    * 
230    * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
231    * java.lang.String)
232    */
233   public void select(String sequenceIds, String columns)
234   {
235     selectIn(getDefaultTargetFrame(), sequenceIds, columns, separator);
236   }
237
238   /*
239    * (non-Javadoc)
240    * 
241    * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
242    * java.lang.String, java.lang.String)
243    */
244   public void select(String sequenceIds, String columns, String sep)
245   {
246     selectIn(getDefaultTargetFrame(), sequenceIds, columns, sep);
247   }
248
249   /*
250    * (non-Javadoc)
251    * 
252    * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
253    * java.lang.String, java.lang.String)
254    */
255   public void selectIn(AlignFrame alf, String sequenceIds, String columns)
256   {
257     selectIn(alf, sequenceIds, columns, separator);
258   }
259
260   /*
261    * (non-Javadoc)
262    * 
263    * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
264    * java.lang.String, java.lang.String, java.lang.String)
265    */
266   public void selectIn(final AlignFrame alf, String sequenceIds,
267           String columns, String sep)
268   {
269     if (sep == null || sep.length() == 0)
270     {
271       sep = separator;
272     }
273     else
274     {
275       if (debug)
276       {
277         System.err.println("Selecting region using separator string '"
278                 + separator + "'");
279       }
280     }
281     // deparse fields
282     String[] ids = separatorListToArray(sequenceIds, sep);
283     String[] cols = separatorListToArray(columns, sep);
284     final SequenceGroup sel = new SequenceGroup();
285     final ColumnSelection csel = new ColumnSelection();
286     AlignmentI al = alf.viewport.getAlignment();
287     jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
288             alf.viewport.getAlignment().getSequencesArray());
289     int start = 0, end = al.getWidth(), alw = al.getWidth();
290     boolean seqsfound = true;
291     if (ids != null && ids.length > 0)
292     {
293       seqsfound = false;
294       for (int i = 0; i < ids.length; i++)
295       {
296         if (ids[i].trim().length() == 0)
297         {
298           continue;
299         }
300         SequenceI sq = matcher.findIdMatch(ids[i]);
301         if (sq != null)
302         {
303           seqsfound = true;
304           sel.addSequence(sq, false);
305         }
306       }
307     }
308     boolean inseqpos = false;
309     if (cols != null && cols.length > 0)
310     {
311       boolean seset = false;
312       for (int i = 0; i < cols.length; i++)
313       {
314         String cl = cols[i].trim();
315         if (cl.length() == 0)
316         {
317           continue;
318         }
319         int p;
320         if ((p = cl.indexOf("-")) > -1)
321         {
322           int from = -1, to = -1;
323           try
324           {
325             from = new Integer(cl.substring(0, p)).intValue();
326             from--;
327           } catch (NumberFormatException ex)
328           {
329             System.err
330                     .println("ERROR: Couldn't parse first integer in range element column selection string '"
331                             + cl + "' - format is 'from-to'");
332             return;
333           }
334           try
335           {
336             to = new Integer(cl.substring(p + 1)).intValue();
337             to--;
338           } catch (NumberFormatException ex)
339           {
340             System.err
341                     .println("ERROR: Couldn't parse second integer in range element column selection string '"
342                             + cl + "' - format is 'from-to'");
343             return;
344           }
345           if (from >= 0 && to >= 0)
346           {
347             // valid range
348             if (from < to)
349             {
350               int t = to;
351               to = from;
352               to = t;
353             }
354             if (!seset)
355             {
356               start = from;
357               end = to;
358               seset = true;
359             }
360             else
361             {
362               // comment to prevent range extension
363               if (start > from)
364               {
365                 start = from;
366               }
367               if (end < to)
368               {
369                 end = to;
370               }
371             }
372             for (int r = from; r <= to; r++)
373             {
374               if (r >= 0 && r < alw)
375               {
376                 csel.addElement(r);
377               }
378             }
379             if (debug)
380             {
381               System.err.println("Range '" + cl + "' deparsed as [" + from
382                       + "," + to + "]");
383             }
384           }
385           else
386           {
387             System.err.println("ERROR: Invalid Range '" + cl
388                     + "' deparsed as [" + from + "," + to + "]");
389           }
390         }
391         else
392         {
393           int r = -1;
394           try
395           {
396             r = new Integer(cl).intValue();
397             r--;
398           } catch (NumberFormatException ex)
399           {
400             if (cl.toLowerCase().equals("sequence"))
401             {
402               // we are in the dataset sequence's coordinate frame.
403               inseqpos = true;
404             }
405             else
406             {
407               System.err
408                       .println("ERROR: Couldn't parse integer from point selection element of column selection string '"
409                               + cl + "'");
410               return;
411             }
412           }
413           if (r >= 0 && r <= alw)
414           {
415             if (!seset)
416             {
417               start = r;
418               end = r;
419               seset = true;
420             }
421             else
422             {
423               // comment to prevent range extension
424               if (start > r)
425               {
426                 start = r;
427               }
428               if (end < r)
429               {
430                 end = r;
431               }
432             }
433             csel.addElement(r);
434             if (debug)
435             {
436               System.err.println("Point selection '" + cl
437                       + "' deparsed as [" + r + "]");
438             }
439           }
440           else
441           {
442             System.err.println("ERROR: Invalid Point selection '" + cl
443                     + "' deparsed as [" + r + "]");
444           }
445         }
446       }
447     }
448     if (seqsfound)
449     {
450       // we only propagate the selection when it was the null selection, or the
451       // given sequences were found in the alignment.
452       if (inseqpos && sel.getSize() > 0)
453       {
454         // assume first sequence provides reference frame ?
455         SequenceI rs = sel.getSequenceAt(0);
456         start = rs.findIndex(start);
457         end = rs.findIndex(end);
458         if (csel != null)
459         {
460           List<Integer> cs = csel.getSelected();
461           csel.clear();
462           for (Integer selectedCol : cs)
463           {
464             csel.addElement(rs.findIndex(selectedCol));
465           }
466         }
467       }
468       sel.setStartRes(start);
469       sel.setEndRes(end);
470       EventQueue.invokeLater(new Runnable()
471       {
472         @Override
473         public void run()
474         {
475           alf.select(sel, csel);
476         }
477       });
478     }
479   }
480
481   /*
482    * (non-Javadoc)
483    * 
484    * @see
485    * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignment(java.lang.
486    * String, java.lang.String)
487    */
488   public String getSelectedSequencesAsAlignment(String format, String suffix)
489   {
490     return getSelectedSequencesAsAlignmentFrom(getDefaultTargetFrame(),
491             format, suffix);
492   }
493
494   /*
495    * (non-Javadoc)
496    * 
497    * @see
498    * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignmentFrom(jalview
499    * .appletgui.AlignFrame, java.lang.String, java.lang.String)
500    */
501   public String getSelectedSequencesAsAlignmentFrom(AlignFrame alf,
502           String format, String suffix)
503   {
504     try
505     {
506       boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
507       if (alf.viewport.getSelectionGroup() != null)
508       {
509         // JBPNote: getSelectionAsNewSequence behaviour has changed - this
510         // method now returns a full copy of sequence data
511         // TODO consider using getSequenceSelection instead here
512         String reply = new AppletFormatAdapter().formatSequences(format,
513                 new Alignment(alf.viewport.getSelectionAsNewSequence()),
514                 seqlimits);
515         return reply;
516       }
517     } catch (Exception ex)
518     {
519       ex.printStackTrace();
520       return "Error retrieving alignment in " + format + " format. ";
521     }
522     return "";
523   }
524
525   /*
526    * (non-Javadoc)
527    * 
528    * @see jalview.bin.JalviewLiteJsApi#getAlignmentOrder()
529    */
530   public String getAlignmentOrder()
531   {
532     return getAlignmentOrderFrom(getDefaultTargetFrame());
533   }
534
535   /*
536    * (non-Javadoc)
537    * 
538    * @see
539    * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
540    * )
541    */
542   public String getAlignmentOrderFrom(AlignFrame alf)
543   {
544     return getAlignmentOrderFrom(alf, separator);
545   }
546
547   /*
548    * (non-Javadoc)
549    * 
550    * @see
551    * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
552    * , java.lang.String)
553    */
554   public String getAlignmentOrderFrom(AlignFrame alf, String sep)
555   {
556     AlignmentI alorder = alf.getAlignViewport().getAlignment();
557     String[] order = new String[alorder.getHeight()];
558     for (int i = 0; i < order.length; i++)
559     {
560       order[i] = alorder.getSequenceAt(i).getName();
561     }
562     return arrayToSeparatorList(order);
563   }
564
565   /*
566    * (non-Javadoc)
567    * 
568    * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
569    * java.lang.String)
570    */
571   public String orderBy(String order, String undoName)
572   {
573     return orderBy(order, undoName, separator);
574   }
575
576   /*
577    * (non-Javadoc)
578    * 
579    * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
580    * java.lang.String, java.lang.String)
581    */
582   public String orderBy(String order, String undoName, String sep)
583   {
584     return orderAlignmentBy(getDefaultTargetFrame(), order, undoName, sep);
585   }
586
587   /*
588    * (non-Javadoc)
589    * 
590    * @see
591    * jalview.bin.JalviewLiteJsApi#orderAlignmentBy(jalview.appletgui.AlignFrame,
592    * java.lang.String, java.lang.String, java.lang.String)
593    */
594   public String orderAlignmentBy(AlignFrame alf, String order,
595           String undoName, String sep)
596   {
597     String[] ids = separatorListToArray(order, sep);
598     SequenceI[] sqs = null;
599     if (ids != null && ids.length > 0)
600     {
601       jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
602               alf.viewport.getAlignment().getSequencesArray());
603       int s = 0;
604       sqs = new SequenceI[ids.length];
605       for (int i = 0; i < ids.length; i++)
606       {
607         if (ids[i].trim().length() == 0)
608         {
609           continue;
610         }
611         SequenceI sq = matcher.findIdMatch(ids[i]);
612         if (sq != null)
613         {
614           sqs[s++] = sq;
615         }
616       }
617       if (s > 0)
618       {
619         SequenceI[] sqq = new SequenceI[s];
620         System.arraycopy(sqs, 0, sqq, 0, s);
621         sqs = sqq;
622       }
623       else
624       {
625         sqs = null;
626       }
627     }
628     if (sqs == null)
629     {
630       return "";
631     }
632     ;
633     final AlignmentOrder aorder = new AlignmentOrder(sqs);
634
635     if (undoName != null && undoName.trim().length() == 0)
636     {
637       undoName = null;
638     }
639     final String _undoName = undoName;
640     // TODO: deal with synchronization here: cannot raise any events until after
641     // this has returned.
642     return alf.sortBy(aorder, _undoName) ? TRUE : "";
643   }
644
645   /*
646    * (non-Javadoc)
647    * 
648    * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String)
649    */
650   public String getAlignment(String format)
651   {
652     return getAlignmentFrom(getDefaultTargetFrame(), format, TRUE);
653   }
654
655   /*
656    * (non-Javadoc)
657    * 
658    * @see
659    * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
660    * java.lang.String)
661    */
662   public String getAlignmentFrom(AlignFrame alf, String format)
663   {
664     return getAlignmentFrom(alf, format, TRUE);
665   }
666
667   /*
668    * (non-Javadoc)
669    * 
670    * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String,
671    * java.lang.String)
672    */
673   public String getAlignment(String format, String suffix)
674   {
675     return getAlignmentFrom(getDefaultTargetFrame(), format, suffix);
676   }
677
678   /*
679    * (non-Javadoc)
680    * 
681    * @see
682    * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
683    * java.lang.String, java.lang.String)
684    */
685   public String getAlignmentFrom(AlignFrame alf, String format,
686           String suffix)
687   {
688     try
689     {
690       boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
691
692       String reply = new AppletFormatAdapter().formatSequences(format,
693               alf.viewport.getAlignment(), seqlimits);
694       return reply;
695     } catch (Exception ex)
696     {
697       ex.printStackTrace();
698       return "Error retrieving alignment in " + format + " format. ";
699     }
700   }
701
702   /*
703    * (non-Javadoc)
704    * 
705    * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
706    */
707   public void loadAnnotation(String annotation)
708   {
709     loadAnnotationFrom(getDefaultTargetFrame(), annotation);
710   }
711
712   /*
713    * (non-Javadoc)
714    * 
715    * @see
716    * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
717    * , java.lang.String)
718    */
719   public void loadAnnotationFrom(AlignFrame alf, String annotation)
720   {
721     if (new AnnotationFile().annotateAlignmentView(alf.getAlignViewport(),
722             annotation, AppletFormatAdapter.PASTE))
723     {
724       alf.alignPanel.fontChanged();
725       alf.alignPanel.setScrollValues(0, 0);
726     }
727     else
728     {
729       alf.parseFeaturesFile(annotation, AppletFormatAdapter.PASTE);
730     }
731   }
732
733   /*
734    * (non-Javadoc)
735    * 
736    * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
737    */
738   public void loadFeatures(String features, boolean autoenabledisplay)
739   {
740     loadFeaturesFrom(getDefaultTargetFrame(), features, autoenabledisplay);
741   }
742
743   /*
744    * (non-Javadoc)
745    * 
746    * @see
747    * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
748    * , java.lang.String)
749    */
750   public boolean loadFeaturesFrom(AlignFrame alf, String features,
751           boolean autoenabledisplay)
752   {
753     return alf.parseFeaturesFile(features, AppletFormatAdapter.PASTE,
754             autoenabledisplay);
755   }
756
757   /*
758    * (non-Javadoc)
759    * 
760    * @see jalview.bin.JalviewLiteJsApi#getFeatures(java.lang.String)
761    */
762   public String getFeatures(String format)
763   {
764     return getFeaturesFrom(getDefaultTargetFrame(), format);
765   }
766
767   /*
768    * (non-Javadoc)
769    * 
770    * @see
771    * jalview.bin.JalviewLiteJsApi#getFeaturesFrom(jalview.appletgui.AlignFrame,
772    * java.lang.String)
773    */
774   public String getFeaturesFrom(AlignFrame alf, String format)
775   {
776     return alf.outputFeatures(false, format);
777   }
778
779   /*
780    * (non-Javadoc)
781    * 
782    * @see jalview.bin.JalviewLiteJsApi#getAnnotation()
783    */
784   public String getAnnotation()
785   {
786     return getAnnotationFrom(getDefaultTargetFrame());
787   }
788
789   /*
790    * (non-Javadoc)
791    * 
792    * @see
793    * jalview.bin.JalviewLiteJsApi#getAnnotationFrom(jalview.appletgui.AlignFrame
794    * )
795    */
796   public String getAnnotationFrom(AlignFrame alf)
797   {
798     return alf.outputAnnotations(false);
799   }
800
801   /*
802    * (non-Javadoc)
803    * 
804    * @see jalview.bin.JalviewLiteJsApi#newView()
805    */
806   public AlignFrame newView()
807   {
808     return newViewFrom(getDefaultTargetFrame());
809   }
810
811   /*
812    * (non-Javadoc)
813    * 
814    * @see jalview.bin.JalviewLiteJsApi#newView(java.lang.String)
815    */
816   public AlignFrame newView(String name)
817   {
818     return newViewFrom(getDefaultTargetFrame(), name);
819   }
820
821   /*
822    * (non-Javadoc)
823    * 
824    * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame)
825    */
826   public AlignFrame newViewFrom(AlignFrame alf)
827   {
828     return alf.newView(null);
829   }
830
831   /*
832    * (non-Javadoc)
833    * 
834    * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame,
835    * java.lang.String)
836    */
837   public AlignFrame newViewFrom(AlignFrame alf, String name)
838   {
839     return alf.newView(name);
840   }
841
842   /*
843    * (non-Javadoc)
844    * 
845    * @see jalview.bin.JalviewLiteJsApi#loadAlignment(java.lang.String,
846    * java.lang.String)
847    */
848   public AlignFrame loadAlignment(String text, String title)
849   {
850     Alignment al = null;
851
852     String format = new IdentifyFile().Identify(text,
853             AppletFormatAdapter.PASTE);
854     try
855     {
856       al = new AppletFormatAdapter().readFile(text,
857               AppletFormatAdapter.PASTE, format);
858       if (al.getHeight() > 0)
859       {
860         return new AlignFrame(al, this, title, false);
861       }
862     } catch (java.io.IOException ex)
863     {
864       ex.printStackTrace();
865     }
866     return null;
867   }
868
869   /*
870    * (non-Javadoc)
871    * 
872    * @see jalview.bin.JalviewLiteJsApi#setMouseoverListener(java.lang.String)
873    */
874   public void setMouseoverListener(String listener)
875   {
876     setMouseoverListener(currentAlignFrame, listener);
877   }
878
879   private Vector<jalview.javascript.JSFunctionExec> javascriptListeners = new Vector<jalview.javascript.JSFunctionExec>();
880
881   /*
882    * (non-Javadoc)
883    * 
884    * @see
885    * jalview.bin.JalviewLiteJsApi#setMouseoverListener(jalview.appletgui.AlignFrame
886    * , java.lang.String)
887    */
888   public void setMouseoverListener(AlignFrame af, String listener)
889   {
890     if (listener != null)
891     {
892       listener = listener.trim();
893       if (listener.length() == 0)
894       {
895         System.err
896                 .println("jalview Javascript error: Ignoring empty function for mouseover listener.");
897         return;
898       }
899     }
900     jalview.javascript.MouseOverListener mol = new jalview.javascript.MouseOverListener(
901             this, af, listener);
902     javascriptListeners.addElement(mol);
903     StructureSelectionManager.getStructureSelectionManager(this)
904             .addStructureViewerListener(mol);
905     if (debug)
906     {
907       System.err.println("Added a mouseover listener for "
908               + ((af == null) ? "All frames" : "Just views for "
909                       + af.getAlignViewport().getSequenceSetId()));
910       System.err.println("There are now " + javascriptListeners.size()
911               + " listeners in total.");
912     }
913   }
914
915   /*
916    * (non-Javadoc)
917    * 
918    * @see jalview.bin.JalviewLiteJsApi#setSelectionListener(java.lang.String)
919    */
920   public void setSelectionListener(String listener)
921   {
922     setSelectionListener(null, listener);
923   }
924
925   /*
926    * (non-Javadoc)
927    * 
928    * @see
929    * jalview.bin.JalviewLiteJsApi#setSelectionListener(jalview.appletgui.AlignFrame
930    * , java.lang.String)
931    */
932   public void setSelectionListener(AlignFrame af, String listener)
933   {
934     if (listener != null)
935     {
936       listener = listener.trim();
937       if (listener.length() == 0)
938       {
939         System.err
940                 .println("jalview Javascript error: Ignoring empty function for selection listener.");
941         return;
942       }
943     }
944     jalview.javascript.JsSelectionSender mol = new jalview.javascript.JsSelectionSender(
945             this, af, listener);
946     javascriptListeners.addElement(mol);
947     StructureSelectionManager.getStructureSelectionManager(this)
948             .addSelectionListener(mol);
949     if (debug)
950     {
951       System.err.println("Added a selection listener for "
952               + ((af == null) ? "All frames" : "Just views for "
953                       + af.getAlignViewport().getSequenceSetId()));
954       System.err.println("There are now " + javascriptListeners.size()
955               + " listeners in total.");
956     }
957   }
958
959   /*
960    * (non-Javadoc)
961    * 
962    * @see jalview.bin.JalviewLiteJsApi#setStructureListener(java.lang.String,
963    * java.lang.String)
964    */
965   public void setStructureListener(String listener, String modelSet)
966   {
967     if (listener != null)
968     {
969       listener = listener.trim();
970       if (listener.length() == 0)
971       {
972         System.err
973                 .println("jalview Javascript error: Ignoring empty function for selection listener.");
974         return;
975       }
976     }
977     jalview.javascript.MouseOverStructureListener mol = new jalview.javascript.MouseOverStructureListener(
978             this, listener, separatorListToArray(modelSet));
979     javascriptListeners.addElement(mol);
980     StructureSelectionManager.getStructureSelectionManager(this)
981             .addStructureViewerListener(mol);
982     if (debug)
983     {
984       System.err.println("Added a javascript structure viewer listener '"
985               + listener + "'");
986       System.err.println("There are now " + javascriptListeners.size()
987               + " listeners in total.");
988     }
989   }
990
991   /*
992    * (non-Javadoc)
993    * 
994    * @see
995    * jalview.bin.JalviewLiteJsApi#removeJavascriptListener(jalview.appletgui
996    * .AlignFrame, java.lang.String)
997    */
998   public void removeJavascriptListener(AlignFrame af, String listener)
999   {
1000     if (listener != null)
1001     {
1002       listener = listener.trim();
1003       if (listener.length() == 0)
1004       {
1005         listener = null;
1006       }
1007     }
1008     boolean rprt = false;
1009     for (int ms = 0, msSize = javascriptListeners.size(); ms < msSize;)
1010     {
1011       Object lstn = javascriptListeners.elementAt(ms);
1012       JsCallBack lstner = (JsCallBack) lstn;
1013       if ((af == null || lstner.getAlignFrame() == af)
1014               && (listener == null || lstner.getListenerFunction().equals(
1015                       listener)))
1016       {
1017         javascriptListeners.removeElement(lstner);
1018         msSize--;
1019         if (lstner instanceof SelectionListener)
1020         {
1021           StructureSelectionManager.getStructureSelectionManager(this)
1022                   .removeSelectionListener((SelectionListener) lstner);
1023         }
1024         else
1025         {
1026           StructureSelectionManager.getStructureSelectionManager(this)
1027                   .removeStructureViewerListener(lstner, null);
1028         }
1029         rprt = debug;
1030         if (debug)
1031         {
1032           System.err.println("Removed listener '" + listener + "'");
1033         }
1034       }
1035       else
1036       {
1037         ms++;
1038       }
1039     }
1040     if (rprt)
1041     {
1042       System.err.println("There are now " + javascriptListeners.size()
1043               + " listeners in total.");
1044     }
1045   }
1046
1047   public void stop()
1048   {
1049     System.err.println("Applet " + getName() + " stop().");
1050     tidyUp();
1051   }
1052
1053   public void destroy()
1054   {
1055     System.err.println("Applet " + getName() + " destroy().");
1056     tidyUp();
1057   }
1058
1059   private void tidyUp()
1060   {
1061     removeAll();
1062     if (currentAlignFrame != null && currentAlignFrame.viewport != null
1063             && currentAlignFrame.viewport.applet != null)
1064     {
1065       AlignViewport av = currentAlignFrame.viewport;
1066       currentAlignFrame.closeMenuItem_actionPerformed();
1067       av.applet = null;
1068       currentAlignFrame = null;
1069     }
1070     if (javascriptListeners != null)
1071     {
1072       while (javascriptListeners.size() > 0)
1073       {
1074         jalview.javascript.JSFunctionExec mol = javascriptListeners
1075                 .elementAt(0);
1076         javascriptListeners.removeElement(mol);
1077         if (mol instanceof SelectionListener)
1078         {
1079           StructureSelectionManager.getStructureSelectionManager(this)
1080                   .removeSelectionListener((SelectionListener) mol);
1081         }
1082         else
1083         {
1084           StructureSelectionManager.getStructureSelectionManager(this)
1085                   .removeStructureViewerListener(mol, null);
1086         }
1087         mol.jvlite = null;
1088       }
1089     }
1090     if (jsFunctionExec != null)
1091     {
1092       jsFunctionExec.stopQueue();
1093       jsFunctionExec.jvlite = null;
1094     }
1095     initialAlignFrame = null;
1096     jsFunctionExec = null;
1097     javascriptListeners = null;
1098     StructureSelectionManager.release(this);
1099   }
1100
1101   private jalview.javascript.JSFunctionExec jsFunctionExec;
1102
1103   /*
1104    * (non-Javadoc)
1105    * 
1106    * @see jalview.bin.JalviewLiteJsApi#mouseOverStructure(java.lang.String,
1107    * java.lang.String, java.lang.String)
1108    */
1109   public void mouseOverStructure(final String pdbResNum,
1110           final String chain, final String pdbfile)
1111   {
1112     final StructureSelectionManagerProvider me = this;
1113     java.awt.EventQueue.invokeLater(new Runnable()
1114     {
1115       @Override
1116       public void run()
1117       {
1118         try
1119         {
1120           StructureSelectionManager.getStructureSelectionManager(me)
1121                   .mouseOverStructure(new Integer(pdbResNum).intValue(),
1122                           chain, pdbfile);
1123           if (debug)
1124           {
1125             System.err.println("mouseOver for '" + pdbResNum
1126                     + "' in chain '" + chain + "' in structure '" + pdbfile
1127                     + "'");
1128           }
1129         } catch (NumberFormatException e)
1130         {
1131           System.err.println("Ignoring invalid residue number string '"
1132                   + pdbResNum + "'");
1133         }
1134
1135       }
1136     });
1137   }
1138
1139   /*
1140    * (non-Javadoc)
1141    * 
1142    * @see
1143    * jalview.bin.JalviewLiteJsApi#scrollViewToIn(jalview.appletgui.AlignFrame,
1144    * java.lang.String, java.lang.String)
1145    */
1146   public void scrollViewToIn(final AlignFrame alf, final String topRow,
1147           final String leftHandColumn)
1148   {
1149     java.awt.EventQueue.invokeLater(new Runnable()
1150     {
1151       @Override
1152       public void run()
1153       {
1154         try
1155         {
1156           alf.scrollTo(new Integer(topRow).intValue(), new Integer(
1157                   leftHandColumn).intValue());
1158
1159         } catch (Exception ex)
1160         {
1161           System.err.println("Couldn't parse integer arguments (topRow='"
1162                   + topRow + "' and leftHandColumn='" + leftHandColumn
1163                   + "')");
1164           ex.printStackTrace();
1165         }
1166       }
1167     });
1168   }
1169
1170   /*
1171    * (non-Javadoc)
1172    * 
1173    * @see
1174    * jalview.javascript.JalviewLiteJsApi#scrollViewToRowIn(jalview.appletgui
1175    * .AlignFrame, java.lang.String)
1176    */
1177   @Override
1178   public void scrollViewToRowIn(final AlignFrame alf, final String topRow)
1179   {
1180
1181     java.awt.EventQueue.invokeLater(new Runnable()
1182     {
1183       @Override
1184       public void run()
1185       {
1186         try
1187         {
1188           alf.scrollToRow(new Integer(topRow).intValue());
1189
1190         } catch (Exception ex)
1191         {
1192           System.err.println("Couldn't parse integer arguments (topRow='"
1193                   + topRow + "')");
1194           ex.printStackTrace();
1195         }
1196
1197       }
1198     });
1199   }
1200
1201   /*
1202    * (non-Javadoc)
1203    * 
1204    * @see
1205    * jalview.javascript.JalviewLiteJsApi#scrollViewToColumnIn(jalview.appletgui
1206    * .AlignFrame, java.lang.String)
1207    */
1208   @Override
1209   public void scrollViewToColumnIn(final AlignFrame alf,
1210           final String leftHandColumn)
1211   {
1212     java.awt.EventQueue.invokeLater(new Runnable()
1213     {
1214
1215       @Override
1216       public void run()
1217       {
1218         try
1219         {
1220           alf.scrollToColumn(new Integer(leftHandColumn).intValue());
1221
1222         } catch (Exception ex)
1223         {
1224           System.err
1225                   .println("Couldn't parse integer arguments (leftHandColumn='"
1226                           + leftHandColumn + "')");
1227           ex.printStackTrace();
1228         }
1229       }
1230     });
1231
1232   }
1233
1234   // //////////////////////////////////////////////
1235   // //////////////////////////////////////////////
1236
1237   public static int lastFrameX = 200;
1238
1239   public static int lastFrameY = 200;
1240
1241   boolean fileFound = true;
1242
1243   String file = "No file";
1244
1245   String file2 = null;
1246
1247   Button launcher = new Button(
1248           MessageManager.getString("label.start_jalview"));
1249
1250   /**
1251    * The currentAlignFrame is static, it will change if and when the user
1252    * selects a new window. Note that it will *never* point back to the embedded
1253    * AlignFrame if the applet is started as embedded on the page and then
1254    * afterwards a new view is created.
1255    */
1256   public AlignFrame currentAlignFrame = null;
1257
1258   /**
1259    * This is the first frame to be displayed, and does not change. API calls
1260    * will default to this instance if currentAlignFrame is null.
1261    */
1262   AlignFrame initialAlignFrame = null;
1263
1264   boolean embedded = false;
1265
1266   private boolean checkForJmol = true;
1267
1268   private boolean checkedForJmol = false; // ensure we don't check for jmol
1269
1270   // every time the app is re-inited
1271
1272   public boolean jmolAvailable = false;
1273
1274   private boolean alignPdbStructures = false;
1275
1276   /**
1277    * use an external structure viewer exclusively (no jmols or MCViews will be
1278    * opened by JalviewLite itself)
1279    */
1280   public boolean useXtrnalSviewer = false;
1281
1282   public static boolean debug = false;
1283
1284   static String builddate = null, version = null, installation = null;
1285
1286   private static void initBuildDetails()
1287   {
1288     if (builddate == null)
1289     {
1290       builddate = "unknown";
1291       version = "test";
1292       installation = "Webstart";
1293       java.net.URL url = JalviewLite.class
1294               .getResource("/.build_properties");
1295       if (url != null)
1296       {
1297         try
1298         {
1299           BufferedReader reader = new BufferedReader(new InputStreamReader(
1300                   url.openStream()));
1301           String line;
1302           while ((line = reader.readLine()) != null)
1303           {
1304             if (line.indexOf("VERSION") > -1)
1305             {
1306               version = line.substring(line.indexOf("=") + 1);
1307             }
1308             if (line.indexOf("BUILD_DATE") > -1)
1309             {
1310               builddate = line.substring(line.indexOf("=") + 1);
1311             }
1312             if (line.indexOf("INSTALLATION") > -1)
1313             {
1314               installation = line.substring(line.indexOf("=") + 1);
1315             }
1316           }
1317         } catch (Exception ex)
1318         {
1319           ex.printStackTrace();
1320         }
1321       }
1322     }
1323   }
1324
1325   public static String getBuildDate()
1326   {
1327     initBuildDetails();
1328     return builddate;
1329   }
1330
1331   public static String getInstallation()
1332   {
1333     initBuildDetails();
1334     return installation;
1335   }
1336
1337   public static String getVersion()
1338   {
1339     initBuildDetails();
1340     return version;
1341   }
1342
1343   // public JSObject scriptObject = null;
1344
1345   /**
1346    * init method for Jalview Applet
1347    */
1348   public void init()
1349   {
1350     // remove any handlers that might be hanging around from an earlier instance
1351     try
1352     {
1353       if (debug)
1354       {
1355         System.err.println("Applet context is '"
1356                 + getAppletContext().getClass().toString() + "'");
1357       }
1358       JSObject scriptObject = JSObject.getWindow(this);
1359       if (debug && scriptObject != null)
1360       {
1361         System.err.println("Applet has Javascript callback support.");
1362       }
1363
1364     } catch (Exception ex)
1365     {
1366       System.err
1367               .println("Warning: No JalviewLite javascript callbacks available.");
1368       if (debug)
1369       {
1370         ex.printStackTrace();
1371       }
1372     }
1373     /**
1374      * turn on extra applet debugging
1375      */
1376     debug = TRUE.equalsIgnoreCase(getParameter("debug"));
1377     if (debug)
1378     {
1379
1380       System.err.println("JalviewLite Version " + getVersion());
1381       System.err.println("Build Date : " + getBuildDate());
1382       System.err.println("Installation : " + getInstallation());
1383
1384     }
1385     String externalsviewer = getParameter("externalstructureviewer");
1386     if (externalsviewer != null)
1387     {
1388       useXtrnalSviewer = externalsviewer.trim().toLowerCase()
1389               .equals(TRUE);
1390     }
1391     /**
1392      * if true disable the check for jmol
1393      */
1394     String chkforJmol = getParameter("nojmol");
1395     if (chkforJmol != null)
1396     {
1397       checkForJmol = !chkforJmol.equals(TRUE);
1398     }
1399     /**
1400      * get the separator parameter if present
1401      */
1402     String sep = getParameter("separator");
1403     if (sep != null)
1404     {
1405       if (sep.length() > 0)
1406       {
1407         separator = sep;
1408         if (debug)
1409         {
1410           System.err.println("Separator set to '" + separator + "'");
1411         }
1412       }
1413       else
1414       {
1415         throw new Error(MessageManager.getString("error.invalid_separator_parameter"));
1416       }
1417     }
1418     int r = 255;
1419     int g = 255;
1420     int b = 255;
1421     String param = getParameter("RGB");
1422
1423     if (param != null)
1424     {
1425       try
1426       {
1427         r = Integer.parseInt(param.substring(0, 2), 16);
1428         g = Integer.parseInt(param.substring(2, 4), 16);
1429         b = Integer.parseInt(param.substring(4, 6), 16);
1430       } catch (Exception ex)
1431       {
1432         r = 255;
1433         g = 255;
1434         b = 255;
1435       }
1436     }
1437     param = getParameter("label");
1438     if (param != null)
1439     {
1440       launcher.setLabel(param);
1441     }
1442
1443     setBackground(new Color(r, g, b));
1444
1445     file = getParameter("file");
1446
1447     if (file == null)
1448     {
1449       // Maybe the sequences are added as parameters
1450       StringBuffer data = new StringBuffer("PASTE");
1451       int i = 1;
1452       while ((file = getParameter("sequence" + i)) != null)
1453       {
1454         data.append(file.toString() + "\n");
1455         i++;
1456       }
1457       if (data.length() > 5)
1458       {
1459         file = data.toString();
1460       }
1461     }
1462     if (TRUE.equalsIgnoreCase(getParameter("enableSplitFrame")))
1463     {
1464       file2 = getParameter("file2");
1465     }
1466
1467     embedded = TRUE.equalsIgnoreCase(getParameter("embedded"));
1468     if (embedded)
1469     {
1470       LoadingThread loader = new LoadingThread(file, file2, this);
1471       loader.start();
1472     }
1473     else if (file != null)
1474     {
1475       /*
1476        * Start the applet immediately or show a button to start it
1477        */
1478       if (FALSE.equalsIgnoreCase(getParameter("showbutton")))
1479       {
1480         LoadingThread loader = new LoadingThread(file, file2, this);
1481         loader.start();
1482       }
1483       else
1484       {
1485         add(launcher);
1486         launcher.addActionListener(new java.awt.event.ActionListener()
1487         {
1488           public void actionPerformed(ActionEvent e)
1489           {
1490             LoadingThread loader = new LoadingThread(file, file2,
1491                     JalviewLite.this);
1492             loader.start();
1493           }
1494         });
1495       }
1496     }
1497     else
1498     {
1499       // jalview initialisation with no alignment. loadAlignment() method can
1500       // still be called to open new alignments.
1501       file = "NO FILE";
1502       fileFound = false;
1503       callInitCallback();
1504     }
1505   }
1506
1507   private void initLiveConnect()
1508   {
1509     // try really hard to get the liveConnect thing working
1510     boolean notFailed = false;
1511     int tries = 0;
1512     while (!notFailed && tries < 10)
1513     {
1514       if (tries > 0)
1515       {
1516         System.err.println("LiveConnect request thread going to sleep.");
1517       }
1518       try
1519       {
1520         Thread.sleep(700 * (1 + tries));
1521       } catch (InterruptedException q)
1522       {
1523       }
1524       ;
1525       if (tries++ > 0)
1526       {
1527         System.err.println("LiveConnect request thread woken up.");
1528       }
1529       try
1530       {
1531         JSObject scriptObject = JSObject.getWindow(this);
1532         if (scriptObject.eval("navigator") != null)
1533         {
1534           notFailed = true;
1535         }
1536       } catch (JSException jsex)
1537       {
1538         System.err.println("Attempt " + tries
1539                 + " to access LiveConnect javascript failed.");
1540       }
1541     }
1542   }
1543
1544   private void callInitCallback()
1545   {
1546     String initjscallback = getParameter("oninit");
1547     if (initjscallback == null)
1548     {
1549       return;
1550     }
1551     initjscallback = initjscallback.trim();
1552     if (initjscallback.length() > 0)
1553     {
1554       JSObject scriptObject = null;
1555       try
1556       {
1557         scriptObject = JSObject.getWindow(this);
1558       } catch (Exception ex)
1559       {
1560       }
1561       ;
1562       // try really hard to let the browser plugin know we want liveconnect
1563       initLiveConnect();
1564
1565       if (scriptObject != null)
1566       {
1567         try
1568         {
1569           // do onInit with the JS executor thread
1570           new JSFunctionExec(this).executeJavascriptFunction(true,
1571                   initjscallback, null, "Calling oninit callback '"
1572                           + initjscallback + "'.");
1573         } catch (Exception e)
1574         {
1575           System.err.println("Exception when executing _oninit callback '"
1576                   + initjscallback + "'.");
1577           e.printStackTrace();
1578         }
1579       }
1580       else
1581       {
1582         System.err.println("Not executing _oninit callback '"
1583                 + initjscallback + "' - no scripting allowed.");
1584       }
1585     }
1586   }
1587
1588   /**
1589    * Initialises and displays a new java.awt.Frame
1590    * 
1591    * @param frame
1592    *          java.awt.Frame to be displayed
1593    * @param title
1594    *          title of new frame
1595    * @param width
1596    *          width if new frame
1597    * @param height
1598    *          height of new frame
1599    */
1600   public static void addFrame(final Frame frame, String title, int width,
1601           int height)
1602   {
1603     frame.setLocation(lastFrameX, lastFrameY);
1604     lastFrameX += 40;
1605     lastFrameY += 40;
1606     frame.setSize(width, height);
1607     frame.setTitle(title);
1608     frame.addWindowListener(new WindowAdapter()
1609     {
1610       public void windowClosing(WindowEvent e)
1611       {
1612         if (frame instanceof AlignFrame)
1613         {
1614           AlignViewport vp = ((AlignFrame) frame).viewport;
1615           ((AlignFrame) frame).closeMenuItem_actionPerformed();
1616           if (vp.applet.currentAlignFrame == frame)
1617           {
1618             vp.applet.currentAlignFrame = null;
1619           }
1620           vp.applet = null;
1621           vp = null;
1622
1623         }
1624         lastFrameX -= 40;
1625         lastFrameY -= 40;
1626         if (frame instanceof EmbmenuFrame)
1627         {
1628           ((EmbmenuFrame) frame).destroyMenus();
1629         }
1630         frame.setMenuBar(null);
1631         frame.dispose();
1632       }
1633
1634       public void windowActivated(WindowEvent e)
1635       {
1636         if (frame instanceof AlignFrame)
1637         {
1638           ((AlignFrame) frame).viewport.applet.currentAlignFrame = (AlignFrame) frame;
1639           if (debug)
1640           {
1641             System.err.println("Activated window " + frame);
1642           }
1643         }
1644         // be good.
1645         super.windowActivated(e);
1646       }
1647       /*
1648        * Probably not necessary to do this - see TODO above. (non-Javadoc)
1649        * 
1650        * @see
1651        * java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent
1652        * )
1653        * 
1654        * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
1655        * frame) { currentAlignFrame = null; if (debug) {
1656        * System.err.println("Deactivated window "+frame); } }
1657        * super.windowDeactivated(e); }
1658        */
1659     });
1660     frame.setVisible(true);
1661   }
1662
1663   /**
1664    * This paints the background surrounding the "Launch Jalview button" <br>
1665    * <br>
1666    * If file given in parameter not found, displays error message
1667    * 
1668    * @param g
1669    *          graphics context
1670    */
1671   public void paint(Graphics g)
1672   {
1673     if (!fileFound)
1674     {
1675       g.setColor(new Color(200, 200, 200));
1676       g.setColor(Color.cyan);
1677       g.fillRect(0, 0, getSize().width, getSize().height);
1678       g.setColor(Color.red);
1679       g.drawString(
1680               MessageManager.getString("label.jalview_cannot_open_file"),
1681               5, 15);
1682       g.drawString("\"" + file + "\"", 5, 30);
1683     }
1684     else if (embedded)
1685     {
1686       g.setColor(Color.black);
1687       g.setFont(new Font("Arial", Font.BOLD, 24));
1688       g.drawString(MessageManager.getString("label.jalview_applet"), 50,
1689               getSize().height / 2 - 30);
1690       g.drawString(MessageManager.getString("label.loading_data") + "...",
1691               50, getSize().height / 2);
1692     }
1693   }
1694
1695   /**
1696    * get all components associated with the applet of the given type
1697    * 
1698    * @param class1
1699    * @return
1700    */
1701   public Vector getAppletWindow(Class class1)
1702   {
1703     Vector wnds = new Vector();
1704     Component[] cmp = getComponents();
1705     if (cmp != null)
1706     {
1707       for (int i = 0; i < cmp.length; i++)
1708       {
1709         if (class1.isAssignableFrom(cmp[i].getClass()))
1710         {
1711           wnds.addElement(cmp);
1712         }
1713       }
1714     }
1715     return wnds;
1716   }
1717
1718   class LoadJmolThread extends Thread
1719   {
1720     private boolean running = false;
1721
1722     public void run()
1723     {
1724       if (running || checkedForJmol)
1725       {
1726         return;
1727       }
1728       running = true;
1729       if (checkForJmol)
1730       {
1731         try
1732         {
1733           if (!System.getProperty("java.version").startsWith("1.1"))
1734           {
1735             Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
1736             jmolAvailable = true;
1737           }
1738           if (!jmolAvailable)
1739           {
1740             System.out
1741                     .println("Jmol not available - Using MCview for structures");
1742           }
1743         } catch (java.lang.ClassNotFoundException ex)
1744         {
1745         }
1746       }
1747       else
1748       {
1749         jmolAvailable = false;
1750         if (debug)
1751         {
1752           System.err
1753                   .println("Skipping Jmol check. Will use MCView (probably)");
1754         }
1755       }
1756       checkedForJmol = true;
1757       running = false;
1758     }
1759
1760     public boolean notFinished()
1761     {
1762       return running || !checkedForJmol;
1763     }
1764   }
1765
1766   class LoadingThread extends Thread
1767   {
1768     /**
1769      * State variable: protocol for access to file source
1770      */
1771     String protocol;
1772
1773     String _file; // alignment file or URL spec
1774
1775     String _file2; // second alignment file or URL spec
1776
1777     JalviewLite applet;
1778
1779     private void dbgMsg(String msg)
1780     {
1781       if (JalviewLite.debug)
1782       {
1783         System.err.println(msg);
1784       }
1785     }
1786
1787     /**
1788      * update the protocol state variable for accessing the datasource located
1789      * by file.
1790      * 
1791      * @param file
1792      * @return possibly updated datasource string
1793      */
1794     public String setProtocolState(String file)
1795     {
1796       if (file.startsWith("PASTE"))
1797       {
1798         file = file.substring(5);
1799         protocol = AppletFormatAdapter.PASTE;
1800       }
1801       else if (inArchive(file))
1802       {
1803         protocol = AppletFormatAdapter.CLASSLOADER;
1804       }
1805       else
1806       {
1807         file = addProtocol(file);
1808         protocol = AppletFormatAdapter.URL;
1809       }
1810       dbgMsg("Protocol identified as '" + protocol + "'");
1811       return file;
1812     }
1813
1814     public LoadingThread(String file, String file2, JalviewLite _applet)
1815     {
1816       this._file = file;
1817       this._file2 = file2;
1818       applet = _applet;
1819     }
1820
1821     public void run()
1822     {
1823       LoadJmolThread jmolchecker = new LoadJmolThread();
1824       jmolchecker.start();
1825       while (jmolchecker.notFinished())
1826       {
1827         // wait around until the Jmol check is complete.
1828         try
1829         {
1830           Thread.sleep(2);
1831         } catch (Exception e)
1832         {
1833         }
1834       }
1835       startLoading();
1836       // applet.callInitCallback();
1837     }
1838
1839     /**
1840      * Load the alignment and any related files as specified by applet
1841      * parameters
1842      */
1843     private void startLoading()
1844     {
1845       dbgMsg("Loading thread started with:\n>>file\n" + _file + ">>endfile");
1846
1847       dbgMsg("Loading started.");
1848
1849       AlignFrame newAlignFrame = readAlignment(_file);
1850       AlignFrame newAlignFrame2 = readAlignment(_file2);
1851       if (newAlignFrame != null)
1852       {
1853         addToDisplay(newAlignFrame, newAlignFrame2);
1854         loadTree(newAlignFrame);
1855
1856         loadScoreFile(newAlignFrame);
1857
1858         loadFeatures(newAlignFrame);
1859
1860         loadAnnotations(newAlignFrame);
1861
1862         loadJnetFile(newAlignFrame);
1863
1864         loadPdbFiles(newAlignFrame);
1865       }
1866       else
1867       {
1868         fileFound = false;
1869         applet.remove(launcher);
1870         applet.repaint();
1871       }
1872       callInitCallback();
1873     }
1874
1875     /**
1876      * Add an AlignFrame to the display; or if two are provided, a SplitFrame.
1877      * 
1878      * @param af
1879      * @param af2
1880      */
1881     public void addToDisplay(AlignFrame af, AlignFrame af2)
1882     {
1883       if (af2 == null)
1884       {
1885         af.addToDisplay(embedded);
1886       }
1887       else
1888       {
1889         SplitFrame sf = new SplitFrame(af, af2);
1890         sf.addToDisplay(embedded, JalviewLite.this);
1891       }
1892     }
1893
1894     /**
1895      * Read the alignment file (from URL, text 'paste', or archive by
1896      * classloader).
1897      * 
1898      * @return
1899      */
1900     protected AlignFrame readAlignment(String fileParam)
1901     {
1902       if (fileParam == null)
1903       {
1904         return null;
1905       }
1906       String resolvedFile = setProtocolState(fileParam);
1907       String format = new IdentifyFile().Identify(resolvedFile, protocol);
1908       dbgMsg("File identified as '" + format + "'");
1909       AlignmentI al = null;
1910       try
1911       {
1912         al = new AppletFormatAdapter().readFile(resolvedFile, protocol, format);
1913         if ((al != null) && (al.getHeight() > 0))
1914         {
1915           dbgMsg("Successfully loaded file.");
1916           al.setDataset(null);
1917           AlignFrame newAlignFrame = new AlignFrame(al, applet,
1918                   resolvedFile, embedded, false);
1919           newAlignFrame.setTitle(resolvedFile);
1920           if (initialAlignFrame == null)
1921           {
1922             initialAlignFrame = newAlignFrame;
1923           }
1924           // update the focus.
1925           currentAlignFrame = newAlignFrame;
1926
1927           if (protocol == AppletFormatAdapter.PASTE)
1928           {
1929             newAlignFrame.setTitle(MessageManager.formatMessage(
1930                     "label.sequences_from", new Object[]
1931                     { applet.getDocumentBase().toString() }));
1932           }
1933
1934           newAlignFrame.statusBar.setText(MessageManager.formatMessage(
1935                   "label.successfully_loaded_file", new Object[]
1936                   { resolvedFile }));
1937
1938           return newAlignFrame;
1939         }
1940       } catch (java.io.IOException ex)
1941       {
1942         dbgMsg("File load exception.");
1943         ex.printStackTrace();
1944         if (debug)
1945         {
1946           try
1947           {
1948             FileParse fp = new FileParse(resolvedFile, protocol);
1949             String ln = null;
1950             dbgMsg(">>>Dumping contents of '" + resolvedFile + "' " + "("
1951                     + protocol + ")");
1952             while ((ln = fp.nextLine()) != null)
1953             {
1954               dbgMsg(ln);
1955             }
1956             dbgMsg(">>>Dump finished.");
1957           } catch (Exception e)
1958           {
1959             System.err
1960                     .println("Exception when trying to dump the content of the file parameter.");
1961             e.printStackTrace();
1962           }
1963         }
1964       }
1965       return null;
1966     }
1967
1968     /**
1969      * Load PDBFiles if any specified by parameter(s). Returns true if loaded,
1970      * else false.
1971      * 
1972      * @param alignFrame
1973      * @return
1974      */
1975     protected boolean loadPdbFiles(AlignFrame alignFrame)
1976     {
1977       boolean result = false;
1978       /*
1979        * <param name="alignpdbfiles" value="false/true"/> Undocumented for 2.6 -
1980        * related to JAL-434
1981        */
1982
1983       applet.setAlignPdbStructures(getDefaultParameter("alignpdbfiles",
1984               false));
1985       /*
1986        * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
1987        * PDB|1GAQ|1GAQ|C">
1988        * 
1989        * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
1990        * 
1991        * <param name="PDBfile3" value="1q0o Q45135_9MICO">
1992        */
1993
1994       int pdbFileCount = 0;
1995       // Accumulate pdbs here if they are heading for the same view (if
1996       // alignPdbStructures is true)
1997       Vector pdbs = new Vector();
1998       // create a lazy matcher if we're asked to
1999       jalview.analysis.SequenceIdMatcher matcher = (applet
2000               .getDefaultParameter("relaxedidmatch", false)) ? new jalview.analysis.SequenceIdMatcher(
2001               alignFrame.getAlignViewport().getAlignment()
2002                       .getSequencesArray()) : null;
2003
2004       String param;
2005       do
2006       {
2007         if (pdbFileCount > 0)
2008         {
2009           param = applet.getParameter("PDBFILE" + pdbFileCount);
2010         }
2011         else
2012         {
2013           param = applet.getParameter("PDBFILE");
2014         }
2015
2016         if (param != null)
2017         {
2018           PDBEntry pdb = new PDBEntry();
2019
2020           String seqstring;
2021           SequenceI[] seqs = null;
2022           String[] chains = null;
2023
2024           StringTokenizer st = new StringTokenizer(param, " ");
2025
2026           if (st.countTokens() < 2)
2027           {
2028             String sequence = applet.getParameter("PDBSEQ");
2029             if (sequence != null)
2030             {
2031               seqs = new SequenceI[]
2032               { matcher == null ? (Sequence) alignFrame.getAlignViewport()
2033                       .getAlignment().findName(sequence) : matcher
2034                       .findIdMatch(sequence) };
2035             }
2036
2037           }
2038           else
2039           {
2040             param = st.nextToken();
2041             Vector tmp = new Vector();
2042             Vector tmp2 = new Vector();
2043
2044             while (st.hasMoreTokens())
2045             {
2046               seqstring = st.nextToken();
2047               StringTokenizer st2 = new StringTokenizer(seqstring, "=");
2048               if (st2.countTokens() > 1)
2049               {
2050                 // This is the chain
2051                 tmp2.addElement(st2.nextToken());
2052                 seqstring = st2.nextToken();
2053               }
2054               tmp.addElement(matcher == null ? (Sequence) alignFrame
2055                       .getAlignViewport().getAlignment()
2056                       .findName(seqstring) : matcher.findIdMatch(seqstring));
2057             }
2058
2059             seqs = new SequenceI[tmp.size()];
2060             tmp.copyInto(seqs);
2061             if (tmp2.size() == tmp.size())
2062             {
2063               chains = new String[tmp2.size()];
2064               tmp2.copyInto(chains);
2065             }
2066           }
2067           param = setProtocolState(param);
2068
2069           if (// !jmolAvailable
2070           // &&
2071           protocol == AppletFormatAdapter.CLASSLOADER && !useXtrnalSviewer)
2072           {
2073             // Re: JAL-357 : the bug isn't a problem if we are using an
2074             // external viewer!
2075             // TODO: verify this Re:
2076             // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
2077             // This exception preserves the current behaviour where, even if
2078             // the local pdb file was identified in the class loader
2079             protocol = AppletFormatAdapter.URL; // this is probably NOT
2080             // CORRECT!
2081             param = addProtocol(param); //
2082           }
2083
2084           pdb.setFile(param);
2085
2086           if (seqs != null)
2087           {
2088             for (int i = 0; i < seqs.length; i++)
2089             {
2090               if (seqs[i] != null)
2091               {
2092                 ((Sequence) seqs[i]).addPDBId(pdb);
2093                 StructureSelectionManager.getStructureSelectionManager(
2094                         applet).registerPDBEntry(pdb);
2095               }
2096               else
2097               {
2098                 if (JalviewLite.debug)
2099                 {
2100                   // this may not really be a problem but we give a warning
2101                   // anyway
2102                   System.err
2103                           .println("Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
2104                                   + i + ")");
2105                 }
2106               }
2107             }
2108
2109             if (!alignPdbStructures)
2110             {
2111               alignFrame.newStructureView(applet, pdb, seqs, chains,
2112                       protocol);
2113             }
2114             else
2115             {
2116               pdbs.addElement(new Object[]
2117               { pdb, seqs, chains, new String(protocol) });
2118             }
2119           }
2120         }
2121
2122         pdbFileCount++;
2123       } while (param != null || pdbFileCount < 10);
2124       if (pdbs.size() > 0)
2125       {
2126         SequenceI[][] seqs = new SequenceI[pdbs.size()][];
2127         PDBEntry[] pdb = new PDBEntry[pdbs.size()];
2128         String[][] chains = new String[pdbs.size()][];
2129         String[] protocols = new String[pdbs.size()];
2130         for (int pdbsi = 0, pdbsiSize = pdbs.size(); pdbsi < pdbsiSize; pdbsi++)
2131         {
2132           Object[] o = (Object[]) pdbs.elementAt(pdbsi);
2133           pdb[pdbsi] = (PDBEntry) o[0];
2134           seqs[pdbsi] = (SequenceI[]) o[1];
2135           chains[pdbsi] = (String[]) o[2];
2136           protocols[pdbsi] = (String) o[3];
2137         }
2138         alignFrame.alignedStructureView(applet, pdb, seqs, chains,
2139                 protocols);
2140         result = true;
2141       }
2142       return result;
2143     }
2144
2145     /**
2146      * Load in a Jnetfile if specified by parameter. Returns true if loaded,
2147      * else false.
2148      * 
2149      * @param alignFrame
2150      * @return
2151      */
2152     protected boolean loadJnetFile(AlignFrame alignFrame)
2153     {
2154       boolean result = false;
2155       String param = applet.getParameter("jnetfile");
2156       if (param != null)
2157       {
2158         try
2159         {
2160           param = setProtocolState(param);
2161           JPredFile predictions = new JPredFile(param, protocol);
2162           JnetAnnotationMaker.add_annotation(predictions,
2163                   alignFrame.viewport.getAlignment(), 0, false);
2164           // false == do not add sequence profile from concise output
2165           SequenceI repseq = alignFrame.viewport.getAlignment()
2166                   .getSequenceAt(0);
2167           alignFrame.viewport.getAlignment().setSeqrep(repseq);
2168           ColumnSelection cs = new ColumnSelection();
2169           cs.hideInsertionsFor(repseq);
2170           alignFrame.viewport.setColumnSelection(cs);
2171           alignFrame.alignPanel.fontChanged();
2172           alignFrame.alignPanel.setScrollValues(0, 0);
2173           result = true;
2174         } catch (Exception ex)
2175         {
2176           ex.printStackTrace();
2177         }
2178       }
2179       return result;
2180     }
2181
2182     /**
2183      * Load annotations if specified by parameter. Returns true if loaded, else
2184      * false.
2185      * 
2186      * @param alignFrame
2187      * @return
2188      */
2189     protected boolean loadAnnotations(AlignFrame alignFrame)
2190     {
2191       boolean result = false;
2192       String param = applet.getParameter("annotations");
2193       if (param != null)
2194       {
2195         param = setProtocolState(param);
2196
2197         if (new AnnotationFile().annotateAlignmentView(alignFrame.viewport,
2198                 param, protocol))
2199         {
2200           alignFrame.alignPanel.fontChanged();
2201           alignFrame.alignPanel.setScrollValues(0, 0);
2202           result = true;
2203         }
2204         else
2205         {
2206           System.err
2207                   .println("Annotations were not added from annotation file '"
2208                           + param + "'");
2209         }
2210       }
2211       return result;
2212     }
2213
2214     /**
2215      * Load features file and view settings as specified by parameters. Returns
2216      * true if features were loaded, else false.
2217      * 
2218      * @param alignFrame
2219      * @return
2220      */
2221     protected boolean loadFeatures(AlignFrame alignFrame)
2222     {
2223       boolean result = false;
2224       // ///////////////////////////
2225       // modify display of features
2226       // we do this before any features have been loaded, ensuring any hidden
2227       // groups are hidden when features first displayed
2228       //
2229       // hide specific groups
2230       //
2231       String param = applet.getParameter("hidefeaturegroups");
2232       if (param != null)
2233       {
2234         alignFrame.setFeatureGroupState(separatorListToArray(param), false);
2235         // applet.setFeatureGroupStateOn(newAlignFrame, param, false);
2236       }
2237       // show specific groups
2238       param = applet.getParameter("showfeaturegroups");
2239       if (param != null)
2240       {
2241         alignFrame.setFeatureGroupState(separatorListToArray(param), true);
2242         // applet.setFeatureGroupStateOn(newAlignFrame, param, true);
2243       }
2244       // and now load features
2245       param = applet.getParameter("features");
2246       if (param != null)
2247       {
2248         param = setProtocolState(param);
2249
2250         result = alignFrame.parseFeaturesFile(param, protocol);
2251       }
2252
2253       param = applet.getParameter("showFeatureSettings");
2254       if (param != null && param.equalsIgnoreCase(TRUE))
2255       {
2256         alignFrame.viewport.setShowSequenceFeatures(true);
2257         new FeatureSettings(alignFrame.alignPanel);
2258       }
2259       return result;
2260     }
2261
2262     /**
2263      * Load a score file if specified by parameter. Returns true if file was
2264      * loaded, else false.
2265      * 
2266      * @param alignFrame
2267      */
2268     protected boolean loadScoreFile(AlignFrame alignFrame)
2269     {
2270       boolean result = false;
2271       String sScoreFile = applet.getParameter("scoreFile");
2272       if (sScoreFile != null && !"".equals(sScoreFile))
2273       {
2274         try
2275         {
2276           if (debug)
2277           {
2278             System.err
2279                     .println("Attempting to load T-COFFEE score file from the scoreFile parameter");
2280           }
2281           result = alignFrame.loadScoreFile(sScoreFile);
2282           if (!result)
2283           {
2284             System.err
2285                     .println("Failed to parse T-COFFEE parameter as a valid score file ('"
2286                             + sScoreFile + "')");
2287           }
2288         } catch (Exception e)
2289         {
2290           System.err.printf("Cannot read score file: '%s'. Cause: %s \n",
2291                   sScoreFile, e.getMessage());
2292         }
2293       }
2294       return result;
2295     }
2296
2297     /**
2298      * Load a tree for the alignment if specified by parameter. Returns true if
2299      * a tree was loaded, else false.
2300      * 
2301      * @param alignFrame
2302      * @return
2303      */
2304     protected boolean loadTree(AlignFrame alignFrame)
2305     {
2306       boolean result = false;
2307       String treeFile = applet.getParameter("tree");
2308       if (treeFile == null)
2309       {
2310         treeFile = applet.getParameter("treeFile");
2311       }
2312
2313       if (treeFile != null)
2314       {
2315         try
2316         {
2317           treeFile = setProtocolState(treeFile);
2318           NewickFile fin = new NewickFile(treeFile, protocol);
2319           fin.parse();
2320
2321           if (fin.getTree() != null)
2322           {
2323             alignFrame.loadTree(fin, treeFile);
2324             result = true;
2325             dbgMsg("Successfully imported tree.");
2326           }
2327           else
2328           {
2329             dbgMsg("Tree parameter did not resolve to a valid tree.");
2330           }
2331         } catch (Exception ex)
2332         {
2333           ex.printStackTrace();
2334         }
2335       }
2336       return result;
2337     }
2338
2339     /**
2340      * Discovers whether the given file is in the Applet Archive
2341      * 
2342      * @param file
2343      *          String
2344      * @return boolean
2345      */
2346     boolean inArchive(String file)
2347     {
2348       // This might throw a security exception in certain browsers
2349       // Netscape Communicator for instance.
2350       try
2351       {
2352         boolean rtn = (getClass().getResourceAsStream("/" + file) != null);
2353         if (debug)
2354         {
2355           System.err.println("Resource '" + file + "' was "
2356                   + (rtn ? "" : "not") + " located by classloader.");
2357         }
2358         return rtn;
2359       } catch (Exception ex)
2360       {
2361         System.out.println("Exception checking resources: " + file + " "
2362                 + ex);
2363         return false;
2364       }
2365     }
2366
2367     /**
2368      * If the file is not already in URL format, tries to locate it by resolving
2369      * as a URL.
2370      * 
2371      * @param file
2372      * @return
2373      */
2374     String addProtocol(final String file)
2375     {
2376       if (file.indexOf("://") == -1)
2377       {
2378         /*
2379          * Try relative to document base
2380          */
2381         String url = applet.resolveUrlForLocalOrAbsolute(file,
2382                 getDocumentBase());
2383         if (urlExists(url))
2384         {
2385           if (debug)
2386           {
2387             System.err.println("Prepended document base for resource: '"
2388                     + file + "'");
2389           }
2390           return url;
2391         }
2392
2393         /*
2394          * Try relative to codebase
2395          */
2396         url = applet.resolveUrlForLocalOrAbsolute(file, getCodeBase());
2397         if (urlExists(url))
2398         {
2399           if (debug)
2400           {
2401             System.err.println("Prepended codebase for resource: '" + file
2402                     + "'");
2403           }
2404           return url;
2405         }
2406       }
2407
2408       /*
2409        * Not resolved, leave unchanged
2410        */
2411       return file;
2412     }
2413
2414     /**
2415      * Returns true if an input stream can be opened on the specified URL, else
2416      * false.
2417      * 
2418      * @param url
2419      * @return
2420      */
2421     private boolean urlExists(String url)
2422     {
2423       InputStream is = null;
2424       try
2425       {
2426         is = new URL(url).openStream();
2427         if (is != null)
2428         {
2429           return true;
2430         }
2431       } catch (Exception x)
2432       {
2433         // ignore
2434       } finally
2435       {
2436         if (is != null)
2437         {
2438           try
2439           {
2440             is.close();
2441           } catch (IOException e)
2442           {
2443             // ignore
2444           }
2445         }
2446       }
2447       return false;
2448     }
2449   }
2450
2451   /**
2452    * @return the default alignFrame acted on by the public applet methods. May
2453    *         return null with an error message on System.err indicating the
2454    *         fact.
2455    */
2456   public AlignFrame getDefaultTargetFrame()
2457   {
2458     if (currentAlignFrame != null)
2459     {
2460       return currentAlignFrame;
2461     }
2462     if (initialAlignFrame != null)
2463     {
2464       return initialAlignFrame;
2465     }
2466     System.err
2467             .println("Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
2468     return null;
2469   }
2470
2471   /**
2472    * separator used for separatorList
2473    */
2474   protected String separator = "" + ((char) 0x00AC); // the default used to be
2475                                                      // '|' but many sequence
2476                                                      // IDS include pipes.
2477
2478   /**
2479    * set to enable the URL based javascript execution mechanism
2480    */
2481   public boolean jsfallbackEnabled = false;
2482
2483   /**
2484    * parse the string into a list
2485    * 
2486    * @param list
2487    * @return elements separated by separator
2488    */
2489   public String[] separatorListToArray(String list)
2490   {
2491     return separatorListToArray(list, separator);
2492   }
2493
2494   /**
2495    * parse the string into a list
2496    * 
2497    * @param list
2498    * @param separator
2499    * @return elements separated by separator
2500    */
2501   public String[] separatorListToArray(String list, String separator)
2502   {
2503     // note separator local variable intentionally masks object field
2504     int seplen = separator.length();
2505     if (list == null || list.equals("") || list.equals(separator))
2506     {
2507       return null;
2508     }
2509     java.util.Vector jv = new Vector();
2510     int cp = 0, pos;
2511     while ((pos = list.indexOf(separator, cp)) > cp)
2512     {
2513       jv.addElement(list.substring(cp, pos));
2514       cp = pos + seplen;
2515     }
2516     if (cp < list.length())
2517     {
2518       String c = list.substring(cp);
2519       if (!c.equals(separator))
2520       {
2521         jv.addElement(c);
2522       }
2523     }
2524     if (jv.size() > 0)
2525     {
2526       String[] v = new String[jv.size()];
2527       for (int i = 0; i < v.length; i++)
2528       {
2529         v[i] = (String) jv.elementAt(i);
2530       }
2531       jv.removeAllElements();
2532       if (debug)
2533       {
2534         System.err.println("Array from '" + separator
2535                 + "' separated List:\n" + v.length);
2536         for (int i = 0; i < v.length; i++)
2537         {
2538           System.err.println("item " + i + " '" + v[i] + "'");
2539         }
2540       }
2541       return v;
2542     }
2543     if (debug)
2544     {
2545       System.err.println("Empty Array from '" + separator
2546               + "' separated List");
2547     }
2548     return null;
2549   }
2550
2551   /**
2552    * concatenate the list with separator
2553    * 
2554    * @param list
2555    * @return concatenated string
2556    */
2557   public String arrayToSeparatorList(String[] list)
2558   {
2559     return arrayToSeparatorList(list, separator);
2560   }
2561
2562   /**
2563    * concatenate the list with separator
2564    * 
2565    * @param list
2566    * @param separator
2567    * @return concatenated string
2568    */
2569   public String arrayToSeparatorList(String[] list, String separator)
2570   {
2571     StringBuffer v = new StringBuffer();
2572     if (list != null && list.length > 0)
2573     {
2574       for (int i = 0, iSize = list.length; i < iSize; i++)
2575       {
2576         if (list[i] != null)
2577         {
2578           if (i > 0)
2579           {
2580             v.append(separator);
2581           }
2582           v.append(list[i]);
2583         }
2584       }
2585       if (debug)
2586       {
2587         System.err.println("Returning '" + separator
2588                 + "' separated List:\n");
2589         System.err.println(v);
2590       }
2591       return v.toString();
2592     }
2593     if (debug)
2594     {
2595       System.err.println("Returning empty '" + separator
2596               + "' separated List\n");
2597     }
2598     return "" + separator;
2599   }
2600
2601   /*
2602    * (non-Javadoc)
2603    * 
2604    * @see jalview.bin.JalviewLiteJsApi#getFeatureGroups()
2605    */
2606   public String getFeatureGroups()
2607   {
2608     String lst = arrayToSeparatorList(getDefaultTargetFrame()
2609             .getFeatureGroups());
2610     return lst;
2611   }
2612
2613   /*
2614    * (non-Javadoc)
2615    * 
2616    * @see
2617    * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOn(jalview.appletgui.AlignFrame
2618    * )
2619    */
2620   public String getFeatureGroupsOn(AlignFrame alf)
2621   {
2622     String lst = arrayToSeparatorList(alf.getFeatureGroups());
2623     return lst;
2624   }
2625
2626   /*
2627    * (non-Javadoc)
2628    * 
2629    * @see jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfState(boolean)
2630    */
2631   public String getFeatureGroupsOfState(boolean visible)
2632   {
2633     return arrayToSeparatorList(getDefaultTargetFrame()
2634             .getFeatureGroupsOfState(visible));
2635   }
2636
2637   /*
2638    * (non-Javadoc)
2639    * 
2640    * @see
2641    * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfStateOn(jalview.appletgui
2642    * .AlignFrame, boolean)
2643    */
2644   public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
2645   {
2646     return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
2647   }
2648
2649   /*
2650    * (non-Javadoc)
2651    * 
2652    * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupStateOn(jalview.appletgui.
2653    * AlignFrame, java.lang.String, boolean)
2654    */
2655   public void setFeatureGroupStateOn(final AlignFrame alf,
2656           final String groups, boolean state)
2657   {
2658     final boolean st = state;// !(state==null || state.equals("") ||
2659     // state.toLowerCase().equals("false"));
2660     java.awt.EventQueue.invokeLater(new Runnable()
2661     {
2662       @Override
2663       public void run()
2664       {
2665         alf.setFeatureGroupState(separatorListToArray(groups), st);
2666       }
2667     });
2668   }
2669
2670   /*
2671    * (non-Javadoc)
2672    * 
2673    * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupState(java.lang.String,
2674    * boolean)
2675    */
2676   public void setFeatureGroupState(String groups, boolean state)
2677   {
2678     setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
2679   }
2680
2681   /*
2682    * (non-Javadoc)
2683    * 
2684    * @see jalview.bin.JalviewLiteJsApi#getSeparator()
2685    */
2686   public String getSeparator()
2687   {
2688     return separator;
2689   }
2690
2691   /*
2692    * (non-Javadoc)
2693    * 
2694    * @see jalview.bin.JalviewLiteJsApi#setSeparator(java.lang.String)
2695    */
2696   public void setSeparator(String separator)
2697   {
2698     if (separator == null || separator.length() < 1)
2699     {
2700       // reset to default
2701       separator = "" + ((char) 0x00AC);
2702     }
2703     this.separator = separator;
2704     if (debug)
2705     {
2706       System.err.println("Default Separator now: '" + separator + "'");
2707     }
2708   }
2709
2710   /**
2711    * get boolean value of applet parameter 'name' and return default if
2712    * parameter is not set
2713    * 
2714    * @param name
2715    *          name of paremeter
2716    * @param def
2717    *          the value to return otherwise
2718    * @return true or false
2719    */
2720   public boolean getDefaultParameter(String name, boolean def)
2721   {
2722     String stn;
2723     if ((stn = getParameter(name)) == null)
2724     {
2725       return def;
2726     }
2727     if (stn.toLowerCase().equals(TRUE))
2728     {
2729       return true;
2730     }
2731     return false;
2732   }
2733
2734   /*
2735    * (non-Javadoc)
2736    * 
2737    * @see jalview.bin.JalviewLiteJsApi#addPdbFile(jalview.appletgui.AlignFrame,
2738    * java.lang.String, java.lang.String, java.lang.String)
2739    */
2740   public boolean addPdbFile(AlignFrame alFrame, String sequenceId,
2741           String pdbEntryString, String pdbFile)
2742   {
2743     return alFrame.addPdbFile(sequenceId, pdbEntryString, pdbFile);
2744   }
2745
2746   protected void setAlignPdbStructures(boolean alignPdbStructures)
2747   {
2748     this.alignPdbStructures = alignPdbStructures;
2749   }
2750
2751   public boolean isAlignPdbStructures()
2752   {
2753     return alignPdbStructures;
2754   }
2755
2756   public void start()
2757   {
2758     // callInitCallback();
2759   }
2760
2761   private Hashtable<String, long[]> jshashes = new Hashtable<String, long[]>();
2762
2763   private Hashtable<String, Hashtable<String, String[]>> jsmessages = new Hashtable<String, Hashtable<String, String[]>>();
2764
2765   public void setJsMessageSet(String messageclass, String viewId,
2766           String[] colcommands)
2767   {
2768     Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2769     if (msgset == null)
2770     {
2771       msgset = new Hashtable<String, String[]>();
2772       jsmessages.put(messageclass, msgset);
2773     }
2774     msgset.put(viewId, colcommands);
2775     long[] l = new long[colcommands.length];
2776     for (int i = 0; i < colcommands.length; i++)
2777     {
2778       l[i] = colcommands[i].hashCode();
2779     }
2780     jshashes.put(messageclass + "|" + viewId, l);
2781   }
2782
2783   /*
2784    * (non-Javadoc)
2785    * 
2786    * @see jalview.bin.JalviewLiteJsApi#getJsMessage(java.lang.String,
2787    * java.lang.String)
2788    */
2789   public String getJsMessage(String messageclass, String viewId)
2790   {
2791     Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2792     if (msgset != null)
2793     {
2794       String[] msgs = msgset.get(viewId);
2795       if (msgs != null)
2796       {
2797         for (int i = 0; i < msgs.length; i++)
2798         {
2799           if (msgs[i] != null)
2800           {
2801             String m = msgs[i];
2802             msgs[i] = null;
2803             return m;
2804           }
2805         }
2806       }
2807     }
2808     return "";
2809   }
2810
2811   public boolean isJsMessageSetChanged(String string, String string2,
2812           String[] colcommands)
2813   {
2814     long[] l = jshashes.get(string + "|" + string2);
2815     if (l == null && colcommands != null)
2816     {
2817       return true;
2818     }
2819     for (int i = 0; i < colcommands.length; i++)
2820     {
2821       if (l[i] != colcommands[i].hashCode())
2822       {
2823         return true;
2824       }
2825     }
2826     return false;
2827   }
2828
2829   private Vector jsExecQueue = new Vector();
2830
2831   public Vector getJsExecQueue()
2832   {
2833     return jsExecQueue;
2834   }
2835
2836   public void setExecutor(JSFunctionExec jsFunctionExec2)
2837   {
2838     jsFunctionExec = jsFunctionExec2;
2839   }
2840
2841   /**
2842    * return the given colour value parameter or the given default if parameter
2843    * not given
2844    * 
2845    * @param colparam
2846    * @param defcolour
2847    * @return
2848    */
2849   public Color getDefaultColourParameter(String colparam, Color defcolour)
2850   {
2851     String colprop = getParameter(colparam);
2852     if (colprop == null || colprop.trim().length() == 0)
2853     {
2854       return defcolour;
2855     }
2856     Color col = jalview.schemes.ColourSchemeProperty
2857             .getAWTColorFromName(colprop);
2858     if (col == null)
2859     {
2860       try
2861       {
2862         col = new jalview.schemes.UserColourScheme(colprop).findColour('A');
2863       } catch (Exception ex)
2864       {
2865         System.err.println("Couldn't parse '" + colprop
2866                 + "' as a colour for " + colparam);
2867         col = null;
2868       }
2869     }
2870     return (col == null) ? defcolour : col;
2871
2872   }
2873
2874   public void openJalviewHelpUrl()
2875   {
2876     String helpUrl = getParameter("jalviewhelpurl");
2877     if (helpUrl == null || helpUrl.trim().length() < 5)
2878     {
2879       helpUrl = "http://www.jalview.org/help.html";
2880     }
2881     showURL(helpUrl, "HELP");
2882   }
2883
2884   /**
2885    * form a complete URL given a path to a resource and a reference location on
2886    * the same server
2887    * 
2888    * @param url
2889    *          - an absolute path on the same server as localref or a document
2890    *          located relative to localref
2891    * @param localref
2892    *          - a URL on the same server as url
2893    * @return a complete URL for the resource located by url
2894    */
2895   private String resolveUrlForLocalOrAbsolute(String url, URL localref)
2896   {
2897     String codebase = localref.toString();
2898     if (url.indexOf("/") == 0)
2899     {
2900       url = codebase.substring(0, codebase.length()
2901               - localref.getFile().length())
2902               + url;
2903     }
2904     else
2905     {
2906       url = localref + url;
2907     }
2908     return url;
2909   }
2910
2911   /**
2912    * open a URL in the browser - resolving it according to relative refs and
2913    * coping with javascript: protocol if necessary.
2914    * 
2915    * @param url
2916    * @param target
2917    */
2918   public void showURL(String url, String target)
2919   {
2920     try
2921     {
2922       if (url.indexOf(":") == -1)
2923       {
2924         // TODO: verify (Bas Vroling bug) prepend codebase or server URL to
2925         // form valid URL
2926         // Should really use docbase, not codebase.
2927         URL prepend;
2928         url = resolveUrlForLocalOrAbsolute(
2929                 url,
2930                 prepend = getDefaultParameter("resolvetocodebase", false) ? getDocumentBase()
2931                         : getCodeBase());
2932         if (debug)
2933         {
2934           System.err
2935                   .println("Show url (prepended "
2936                           + prepend
2937                           + " - toggle resolvetocodebase if code/docbase resolution is wrong): "
2938                           + url);
2939         }
2940       }
2941       else
2942       {
2943         if (debug)
2944         {
2945           System.err.println("Show url: " + url);
2946         }
2947       }
2948       if (url.indexOf("javascript:") == 0)
2949       {
2950         // no target for the javascript context
2951         getAppletContext().showDocument(new java.net.URL(url));
2952       }
2953       else
2954       {
2955         getAppletContext().showDocument(new java.net.URL(url), target);
2956       }
2957     } catch (Exception ex)
2958     {
2959       ex.printStackTrace();
2960     }
2961   }
2962
2963   /**
2964    * bind structures in a viewer to any matching sequences in an alignFrame (use
2965    * sequenceIds to limit scope of search to specific sequences)
2966    * 
2967    * @param alFrame
2968    * @param viewer
2969    * @param sequenceIds
2970    * @return TODO: consider making an exception structure for indicating when
2971    *         binding fails public SequenceStructureBinding
2972    *         addStructureViewInstance( AlignFrame alFrame, Object viewer, String
2973    *         sequenceIds) {
2974    * 
2975    *         if (sequenceIds != null && sequenceIds.length() > 0) { return
2976    *         alFrame.addStructureViewInstance(viewer,
2977    *         separatorListToArray(sequenceIds)); } else { return
2978    *         alFrame.addStructureViewInstance(viewer, null); } // return null; }
2979    */
2980 }