bugfix for Jmol and new classloader reading capability
[jalview.git] / src / jalview / bin / JalviewLite.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4)
3  * Copyright (C) 2008 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  * 
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.bin;
20
21 import java.applet.*;
22
23 import java.awt.*;
24 import java.awt.event.*;
25 import java.util.*;
26
27 import jalview.appletgui.*;
28 import jalview.datamodel.*;
29 import jalview.io.*;
30
31 /**
32  * Jalview Applet. Runs in Java 1.18 runtime
33  * 
34  * @author $author$
35  * @version $Revision$
36  */
37 public class JalviewLite extends Applet
38 {
39
40   // /////////////////////////////////////////
41   // The following public methods maybe called
42   // externally, eg via javascript in HTML page
43   /**
44    * @return String list of selected sequence IDs, each terminated by "¬"
45    *         (¬)
46    */
47   public String getSelectedSequences()
48   {
49     return getSelectedSequencesFrom(getDefaultTargetFrame());
50   }
51
52   /**
53    * @param sep
54    *                separator string or null for default
55    * @return String list of selected sequence IDs, each terminated by sep or
56    *         ("¬" as default)
57    */
58   public String getSelectedSequences(String sep)
59   {
60     return getSelectedSequencesFrom(getDefaultTargetFrame(), sep);
61   }
62
63   /**
64    * @param alf
65    *                alignframe containing selection
66    * @return String list of selected sequence IDs, each terminated by "¬"
67    * 
68    */
69   public String getSelectedSequencesFrom(AlignFrame alf)
70   {
71     return getSelectedSequencesFrom(alf, "¬");
72   }
73
74   /**
75    * get list of selected sequence IDs separated by given separator
76    * 
77    * @param alf
78    *                window containing selection
79    * @param sep
80    *                separator string to use - default is "¬"
81    * @return String list of selected sequence IDs, each terminated by the given
82    *         separator
83    */
84   public String getSelectedSequencesFrom(AlignFrame alf, String sep)
85   {
86     StringBuffer result = new StringBuffer("");
87     if (sep == null || sep.length() == 0)
88     {
89       sep = "¬";
90     }
91     if (alf.viewport.getSelectionGroup() != null)
92     {
93       SequenceI[] seqs = alf.viewport.getSelectionGroup()
94               .getSequencesInOrder(alf.viewport.getAlignment());
95
96       for (int i = 0; i < seqs.length; i++)
97       {
98         result.append(seqs[i].getName());
99         result.append(sep);
100       }
101     }
102
103     return result.toString();
104   }
105
106   /**
107    * get sequences selected in current alignFrame and return their alignment in
108    * format 'format' either with or without suffix
109    * 
110    * @param alf -
111    *                where selection is
112    * @param format -
113    *                format of alignment file
114    * @param suffix -
115    *                "true" to append /start-end string to each sequence ID
116    * @return selected sequences as flat file or empty string if there was no
117    *         current selection
118    */
119   public String getSelectedSequencesAsAlignment(String format, String suffix)
120   {
121     return getSelectedSequencesAsAlignmentFrom(currentAlignFrame, format,
122             suffix);
123   }
124
125   /**
126    * get sequences selected in alf and return their alignment in format 'format'
127    * either with or without suffix
128    * 
129    * @param alf -
130    *                where selection is
131    * @param format -
132    *                format of alignment file
133    * @param suffix -
134    *                "true" to append /start-end string to each sequence ID
135    * @return selected sequences as flat file or empty string if there was no
136    *         current selection
137    */
138   public String getSelectedSequencesAsAlignmentFrom(AlignFrame alf,
139           String format, String suffix)
140   {
141     try
142     {
143       boolean seqlimits = suffix.equalsIgnoreCase("true");
144       if (alf.viewport.getSelectionGroup() != null)
145       {
146         String reply = new AppletFormatAdapter().formatSequences(format,
147                 new Alignment(alf.viewport.getSelectionAsNewSequence()),
148                 seqlimits);
149         return reply;
150       }
151     } catch (Exception ex)
152     {
153       ex.printStackTrace();
154       return "Error retrieving alignment in " + format + " format. ";
155     }
156     return "";
157   }
158
159   public String getAlignment(String format)
160   {
161     return getAlignmentFrom(getDefaultTargetFrame(), format, "true");
162   }
163
164   public String getAlignmentFrom(AlignFrame alf, String format)
165   {
166     return getAlignmentFrom(alf, format, "true");
167   }
168
169   public String getAlignment(String format, String suffix)
170   {
171     return getAlignmentFrom(getDefaultTargetFrame(), format, suffix);
172   }
173
174   public String getAlignmentFrom(AlignFrame alf, String format,
175           String suffix)
176   {
177     try
178     {
179       boolean seqlimits = suffix.equalsIgnoreCase("true");
180
181       String reply = new AppletFormatAdapter().formatSequences(format,
182               alf.viewport.getAlignment(), seqlimits);
183       return reply;
184     } catch (Exception ex)
185     {
186       ex.printStackTrace();
187       return "Error retrieving alignment in " + format + " format. ";
188     }
189   }
190
191   public void loadAnnotation(String annotation)
192   {
193     loadAnnotationFrom(getDefaultTargetFrame(), annotation);
194   }
195
196   public void loadAnnotationFrom(AlignFrame alf, String annotation)
197   {
198     if (new AnnotationFile().readAnnotationFile(alf.getAlignViewport()
199             .getAlignment(), annotation, AppletFormatAdapter.PASTE))
200     {
201       alf.alignPanel.fontChanged();
202       alf.alignPanel.setScrollValues(0, 0);
203     }
204     else
205     {
206       alf.parseFeaturesFile(annotation, AppletFormatAdapter.PASTE);
207     }
208   }
209
210   public String getFeatures(String format)
211   {
212     return getFeaturesFrom(getDefaultTargetFrame(), format);
213   }
214
215   public String getFeaturesFrom(AlignFrame alf, String format)
216   {
217     return alf.outputFeatures(false, format);
218   }
219
220   public String getAnnotation()
221   {
222     return getAnnotationFrom(getDefaultTargetFrame());
223   }
224
225   public String getAnnotationFrom(AlignFrame alf)
226   {
227     return alf.outputAnnotations(false);
228   }
229
230   public AlignFrame newView()
231   {
232     return newViewFrom(getDefaultTargetFrame());
233   }
234
235   public AlignFrame newView(String name)
236   {
237     return newViewFrom(getDefaultTargetFrame(), name);
238   }
239
240   public AlignFrame newViewFrom(AlignFrame alf)
241   {
242     return alf.newView(null);
243   }
244
245   public AlignFrame newViewFrom(AlignFrame alf, String name)
246   {
247     return alf.newView(name);
248   }
249
250   /**
251    * 
252    * @param text
253    *                alignment file as a string
254    * @param title
255    *                window title
256    * @return null or new alignment frame
257    */
258   public AlignFrame loadAlignment(String text, String title)
259   {
260     Alignment al = null;
261     String format = new IdentifyFile().Identify(text,
262             AppletFormatAdapter.PASTE);
263     try
264     {
265       al = new AppletFormatAdapter().readFile(text,
266               AppletFormatAdapter.PASTE, format);
267       if (al.getHeight() > 0)
268       {
269         return new AlignFrame(al, this, title, false);
270       }
271     } catch (java.io.IOException ex)
272     {
273       ex.printStackTrace();
274     }
275     return null;
276   }
277
278   // //////////////////////////////////////////////
279   // //////////////////////////////////////////////
280
281   static int lastFrameX = 200;
282
283   static int lastFrameY = 200;
284
285   boolean fileFound = true;
286
287   String file = "No file";
288
289   Button launcher = new Button("Start Jalview");
290
291   /**
292    * The currentAlignFrame is static, it will change if and when the user
293    * selects a new window. Note that it will *never* point back to the embedded
294    * AlignFrame if the applet is started as embedded on the page and then
295    * afterwards a new view is created.
296    */
297   public static AlignFrame currentAlignFrame;
298
299   /**
300    * This is the first frame to be displayed, and does not change. API calls
301    * will default to this instance if currentAlignFrame is null.
302    */
303   AlignFrame initialAlignFrame;
304
305   boolean embedded = false;
306
307   private boolean checkForJmol = true;
308
309   public boolean jmolAvailable = false;
310
311   public static boolean debug;
312
313   /**
314    * init method for Jalview Applet
315    */
316   public void init()
317   {
318     /**
319      * turn on extra applet debugging
320      */
321     String dbg = getParameter("debug");
322     if (dbg != null)
323     {
324       debug = dbg.toLowerCase().equals("true");
325     }
326     /**
327      * if true disable the check for jmol
328      */
329     String chkforJmol = getParameter("nojmol");
330     if (chkforJmol!=null)
331     {
332       checkForJmol = !chkforJmol.equals("true");
333     }
334     /**
335      * get the separator parameter if present
336      */
337     String sep = getParameter("separator");
338     if (sep != null)
339     {
340       if (sep.length() > 0)
341       {
342         separator = sep;
343         if (debug)
344         {
345           System.err.println("Separator set to '" + separator + "'");
346         }
347       }
348       else
349       {
350         throw new Error(
351                 "Invalid separator parameter - must be non-zero length");
352       }
353     }
354     int r = 255;
355     int g = 255;
356     int b = 255;
357     String param = getParameter("RGB");
358
359     if (param != null)
360     {
361       try
362       {
363         r = Integer.parseInt(param.substring(0, 2), 16);
364         g = Integer.parseInt(param.substring(2, 4), 16);
365         b = Integer.parseInt(param.substring(4, 6), 16);
366       } catch (Exception ex)
367       {
368         r = 255;
369         g = 255;
370         b = 255;
371       }
372     }
373
374     param = getParameter("label");
375     if (param != null)
376     {
377       launcher.setLabel(param);
378     }
379
380     this.setBackground(new Color(r, g, b));
381
382     file = getParameter("file");
383
384     if (file == null)
385     {
386       // Maybe the sequences are added as parameters
387       StringBuffer data = new StringBuffer("PASTE");
388       int i = 1;
389       while ((file = getParameter("sequence" + i)) != null)
390       {
391         data.append(file.toString() + "\n");
392         i++;
393       }
394       if (data.length() > 5)
395       {
396         file = data.toString();
397       }
398     }
399
400     LoadJmolThread jmolAvailable = new LoadJmolThread();
401     jmolAvailable.start();
402
403     final JalviewLite applet = this;
404     if (getParameter("embedded") != null
405             && getParameter("embedded").equalsIgnoreCase("true"))
406     {
407       // Launch as embedded applet in page
408       embedded = true;
409       LoadingThread loader = new LoadingThread(file, applet);
410       loader.start();
411     }
412     else if (file != null)
413     {
414       if (getParameter("showbutton") == null
415               || !getParameter("showbutton").equalsIgnoreCase("false"))
416       {
417         // Add the JalviewLite 'Button' to the page
418         add(launcher);
419         launcher.addActionListener(new java.awt.event.ActionListener()
420         {
421           public void actionPerformed(ActionEvent e)
422           {
423             LoadingThread loader = new LoadingThread(file, applet);
424             loader.start();
425           }
426         });
427       }
428       else
429       {
430         // Open jalviewLite immediately.
431         LoadingThread loader = new LoadingThread(file, applet);
432         loader.start();
433       }
434     }
435     else
436     {
437       // jalview initialisation with no alignment. loadAlignment() method can
438       // still be called to open new alignments.
439       file = "NO FILE";
440       fileFound = false;
441     }
442   }
443
444   /**
445    * Initialises and displays a new java.awt.Frame
446    * 
447    * @param frame
448    *                java.awt.Frame to be displayed
449    * @param title
450    *                title of new frame
451    * @param width
452    *                width if new frame
453    * @param height
454    *                height of new frame
455    */
456   public static void addFrame(final Frame frame, String title, int width,
457           int height)
458   {
459     frame.setLocation(lastFrameX, lastFrameY);
460     lastFrameX += 40;
461     lastFrameY += 40;
462     frame.setSize(width, height);
463     frame.setTitle(title);
464     frame.addWindowListener(new WindowAdapter()
465     {
466       public void windowClosing(WindowEvent e)
467       {
468         if (frame instanceof AlignFrame)
469         {
470           ((AlignFrame) frame).closeMenuItem_actionPerformed();
471         }
472         if (currentAlignFrame == frame)
473         {
474           currentAlignFrame = null;
475         }
476         lastFrameX -= 40;
477         lastFrameY -= 40;
478         if (frame instanceof EmbmenuFrame)
479         {
480           ((EmbmenuFrame) frame).destroyMenus();
481         }
482         frame.setMenuBar(null);
483         frame.dispose();
484       }
485
486       public void windowActivated(WindowEvent e)
487       {
488         if (frame instanceof AlignFrame)
489         {
490           currentAlignFrame = (AlignFrame) frame;
491           if (debug)
492           {
493             System.err.println("Activated window " + frame);
494           }
495         }
496         // be good.
497         super.windowActivated(e);
498       }
499       /*
500        * Probably not necessary to do this - see TODO above. (non-Javadoc)
501        * 
502        * @see java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent)
503        * 
504        * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
505        * frame) { currentAlignFrame = null; if (debug) {
506        * System.err.println("Deactivated window "+frame); } }
507        * super.windowDeactivated(e); }
508        */
509     });
510     frame.setVisible(true);
511   }
512
513   /**
514    * This paints the background surrounding the "Launch Jalview button" <br>
515    * <br>
516    * If file given in parameter not found, displays error message
517    * 
518    * @param g
519    *                graphics context
520    */
521   public void paint(Graphics g)
522   {
523     if (!fileFound)
524     {
525       g.setColor(new Color(200, 200, 200));
526       g.setColor(Color.cyan);
527       g.fillRect(0, 0, getSize().width, getSize().height);
528       g.setColor(Color.red);
529       g.drawString("Jalview can't open file", 5, 15);
530       g.drawString("\"" + file + "\"", 5, 30);
531     }
532     else if (embedded)
533     {
534       g.setColor(Color.black);
535       g.setFont(new Font("Arial", Font.BOLD, 24));
536       g.drawString("Jalview Applet", 50, this.getSize().height / 2 - 30);
537       g.drawString("Loading Data...", 50, this.getSize().height / 2);
538     }
539   }
540
541   class LoadJmolThread extends Thread
542   {
543     public void run()
544     {
545       if (checkForJmol)
546       {
547         try
548         {
549           if (!System.getProperty("java.version").startsWith("1.1"))
550           {
551             Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
552             jmolAvailable = true;
553           }
554           if (!jmolAvailable)
555           {
556             System.out
557                     .println("Jmol not available - Using MCview for structures");
558           }
559         } catch (java.lang.ClassNotFoundException ex)
560         {
561         }
562       } else {
563         jmolAvailable=false;
564         if (debug)
565         {
566           System.err.println("Skipping Jmol check. Will use MCView (probably)");
567         }
568       }
569     }
570   }
571
572   class LoadingThread extends Thread
573   {
574     /**
575      * State variable: File source
576      */
577     String file;
578
579     /**
580      * State variable: protocol for access to file source
581      */
582     String protocol;
583
584     /**
585      * State variable: format of file source
586      */
587     String format;
588
589     JalviewLite applet;
590
591     private void dbgMsg(String msg)
592     {
593       if (applet.debug)
594       {
595         System.err.println(msg);
596       }
597     }
598
599     /**
600      * update the protocol state variable for accessing the datasource located
601      * by file.
602      * 
603      * @param file
604      * @return possibly updated datasource string
605      */
606     public String setProtocolState(String file)
607     {
608       if (file.startsWith("PASTE"))
609       {
610         file = file.substring(5);
611         protocol = AppletFormatAdapter.PASTE;
612       }
613       else if (inArchive(file))
614       {
615         protocol = AppletFormatAdapter.CLASSLOADER;
616       }
617       else
618       {
619         file = addProtocol(file);
620         protocol = AppletFormatAdapter.URL;
621       }
622       dbgMsg("Protocol identified as '" + protocol + "'");
623       return file;
624     }
625
626     public LoadingThread(String _file, JalviewLite _applet)
627     {
628       dbgMsg("Loading thread started with:\n>>file\n" + _file + ">>endfile");
629       file = setProtocolState(_file);
630
631       format = new jalview.io.IdentifyFile().Identify(file, protocol);
632       dbgMsg("File identified as '" + format + "'");
633       applet = _applet;
634     }
635
636     public void run()
637     {
638       startLoading();
639     }
640
641     private void startLoading()
642     {
643       dbgMsg("Loading started.");
644       Alignment al = null;
645       try
646       {
647         al = new AppletFormatAdapter().readFile(file, protocol, format);
648       } catch (java.io.IOException ex)
649       {
650         dbgMsg("File load exception.");
651         ex.printStackTrace();
652       }
653       if ((al != null) && (al.getHeight() > 0))
654       {
655         dbgMsg("Successfully loaded file.");
656         initialAlignFrame = new AlignFrame(al, applet, file, embedded);
657         // update the focus.
658         currentAlignFrame = initialAlignFrame;
659
660         if (protocol == jalview.io.AppletFormatAdapter.PASTE)
661         {
662           currentAlignFrame.setTitle("Sequences from " + getDocumentBase());
663         }
664
665         currentAlignFrame.statusBar.setText("Successfully loaded file "
666                 + file);
667
668         String treeFile = applet.getParameter("tree");
669         if (treeFile == null)
670         {
671           treeFile = applet.getParameter("treeFile");
672         }
673
674         if (treeFile != null)
675         {
676           try
677           {
678             treeFile = setProtocolState(treeFile);
679             /*
680              * if (inArchive(treeFile)) { protocol =
681              * AppletFormatAdapter.CLASSLOADER; } else { protocol =
682              * AppletFormatAdapter.URL; treeFile = addProtocol(treeFile); }
683              */
684             jalview.io.NewickFile fin = new jalview.io.NewickFile(treeFile,
685                     protocol);
686
687             fin.parse();
688
689             if (fin.getTree() != null)
690             {
691               currentAlignFrame.loadTree(fin, treeFile);
692               dbgMsg("Successfuly imported tree.");
693             }
694             else
695             {
696               dbgMsg("Tree parameter did not resolve to a valid tree.");
697             }
698           } catch (Exception ex)
699           {
700             ex.printStackTrace();
701           }
702         }
703
704         String param = getParameter("features");
705         if (param != null)
706         {
707           param = setProtocolState(param);
708
709           currentAlignFrame.parseFeaturesFile(param, protocol);
710         }
711
712         param = getParameter("showFeatureSettings");
713         if (param != null && param.equalsIgnoreCase("true"))
714         {
715           currentAlignFrame.viewport.showSequenceFeatures(true);
716           new FeatureSettings(currentAlignFrame.alignPanel);
717         }
718
719         param = getParameter("annotations");
720         if (param != null)
721         {
722           param = setProtocolState(param);
723
724           if (new AnnotationFile().readAnnotationFile(
725                   currentAlignFrame.viewport.getAlignment(), param,
726                   protocol))
727           {
728             currentAlignFrame.alignPanel.fontChanged();
729             currentAlignFrame.alignPanel.setScrollValues(0, 0);
730           }
731           else
732           {
733             System.err
734                     .println("Annotations were not added from annotation file '"
735                             + param + "'");
736           }
737
738         }
739
740         param = getParameter("jnetfile");
741         if (param != null)
742         {
743           try
744           {
745             param = setProtocolState(param);
746             jalview.io.JPredFile predictions = new jalview.io.JPredFile(
747                     param, protocol);
748             JnetAnnotationMaker.add_annotation(predictions,
749                     currentAlignFrame.viewport.getAlignment(), 0, false); // false==do
750                                                                           // not
751                                                                           // add
752                                                                           // sequence
753                                                                           // profile
754                                                                           // from
755                                                                           // concise
756                                                                           // output
757             currentAlignFrame.alignPanel.fontChanged();
758             currentAlignFrame.alignPanel.setScrollValues(0, 0);
759           } catch (Exception ex)
760           {
761             ex.printStackTrace();
762           }
763         }
764
765         /*
766          * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
767          * PDB|1GAQ|1GAQ|C">
768          * 
769          * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
770          * 
771          * <param name="PDBfile3" value="1q0o Q45135_9MICO">
772          */
773
774         int pdbFileCount = 0;
775         do
776         {
777           if (pdbFileCount > 0)
778             param = getParameter("PDBFILE" + pdbFileCount);
779           else
780             param = getParameter("PDBFILE");
781
782           if (param != null)
783           {
784             PDBEntry pdb = new PDBEntry();
785
786             String seqstring;
787             SequenceI[] seqs = null;
788             String[] chains = null;
789
790             StringTokenizer st = new StringTokenizer(param, " ");
791
792             if (st.countTokens() < 2)
793             {
794               String sequence = applet.getParameter("PDBSEQ");
795               if (sequence != null)
796                 seqs = new SequenceI[]
797                 { (Sequence) currentAlignFrame.getAlignViewport()
798                         .getAlignment().findName(sequence) };
799
800             }
801             else
802             {
803               param = st.nextToken();
804               Vector tmp = new Vector();
805               Vector tmp2 = new Vector();
806
807               while (st.hasMoreTokens())
808               {
809                 seqstring = st.nextToken();
810                 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
811                 if (st2.countTokens() > 1)
812                 {
813                   // This is the chain
814                   tmp2.addElement(st2.nextToken());
815                   seqstring = st2.nextToken();
816                 }
817                 tmp.addElement((Sequence) currentAlignFrame
818                         .getAlignViewport().getAlignment().findName(
819                                 seqstring));
820               }
821
822               seqs = new SequenceI[tmp.size()];
823               tmp.copyInto(seqs);
824               if (tmp2.size() == tmp.size())
825               {
826                 chains = new String[tmp2.size()];
827                 tmp2.copyInto(chains);
828               }
829             }
830             param = setProtocolState(param);
831
832             if (//!jmolAvailable
833                     // &&
834                     protocol == AppletFormatAdapter.CLASSLOADER)
835             {
836               // TODO: verify this Re: https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
837               // This exception preserves the current behaviour where, even if
838               // the local pdb file was identified in the class loader
839               protocol = AppletFormatAdapter.URL; // this is probably NOT
840                                                   // CORRECT!
841               param = addProtocol(param); // 
842             }
843
844             pdb.setFile(param);
845
846             if (seqs != null)
847             {
848               for (int i = 0; i < seqs.length; i++)
849               {
850                 if (seqs[i] != null)
851                 {
852                   ((Sequence) seqs[i]).addPDBId(pdb);
853                 }
854                 else
855                 {
856                   if (JalviewLite.debug)
857                   {
858                     // this may not really be a problem but we give a warning
859                     // anyway
860                     System.err
861                             .println("Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
862                                     + i + ")");
863                   }
864                 }
865               }
866
867               if (jmolAvailable)
868               {
869                 new jalview.appletgui.AppletJmol(pdb, seqs, chains,
870                         currentAlignFrame.alignPanel, protocol);
871                 lastFrameX += 40;
872                 lastFrameY += 40;
873               }
874               else
875                 new MCview.AppletPDBViewer(pdb, seqs, chains,
876                         currentAlignFrame.alignPanel, protocol);
877             }
878           }
879
880           pdbFileCount++;
881         } while (pdbFileCount < 10);
882
883         // ///////////////////////////
884         // modify display of features
885         //
886         // hide specific groups
887         param = getParameter("hidefeaturegroups");
888         if (param != null)
889         {
890           applet.setFeatureGroupState(param, false);
891         }
892         // show specific groups
893         param = getParameter("showfeaturegroups");
894         if (param != null)
895         {
896           applet.setFeatureGroupState(param, true);
897         }
898       }
899       else
900       {
901         fileFound = false;
902         remove(launcher);
903         repaint();
904       }
905     }
906
907     /**
908      * Discovers whether the given file is in the Applet Archive
909      * 
910      * @param file
911      *                String
912      * @return boolean
913      */
914     boolean inArchive(String file)
915     {
916       // This might throw a security exception in certain browsers
917       // Netscape Communicator for instance.
918       try
919       {
920         boolean rtn = (getClass().getResourceAsStream("/" + file) != null);
921         if (debug)
922         {
923           System.err.println("Resource '" + file + "' was "
924                   + (rtn ? "" : "not") + " located by classloader.");
925         }
926         return rtn;
927       } catch (Exception ex)
928       {
929         System.out.println("Exception checking resources: " + file + " "
930                 + ex);
931         return false;
932       }
933     }
934
935     String addProtocol(String file)
936     {
937       if (file.indexOf("://") == -1)
938       {
939         file = getCodeBase() + file;
940         if (debug)
941         {
942           System.err.println("Prepended codebase for resource: '" + file
943                   + "'");
944         }
945       }
946
947       return file;
948     }
949   }
950
951   /**
952    * @return the default alignFrame acted on by the public applet methods. May
953    *         return null with an error message on System.err indicating the
954    *         fact.
955    */
956   protected AlignFrame getDefaultTargetFrame()
957   {
958     if (currentAlignFrame != null)
959     {
960       return currentAlignFrame;
961     }
962     if (initialAlignFrame != null)
963     {
964       return initialAlignFrame;
965     }
966     System.err
967             .println("Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
968     return null;
969   }
970
971   /**
972    * separator used for separatorList
973    */
974   protected String separator = "|"; // this is a safe(ish) separator - tabs
975                                     // don't work for firefox
976
977   /**
978    * parse the string into a list
979    * 
980    * @param list
981    * @return elements separated by separator
982    */
983   public String[] separatorListToArray(String list)
984   {
985     int seplen = separator.length();
986     if (list == null || list.equals(""))
987       return null;
988     java.util.Vector jv = new Vector();
989     int cp = 0, pos;
990     while ((pos = list.indexOf(separator, cp)) > cp)
991     {
992       jv.addElement(list.substring(cp, pos));
993       cp = pos + seplen;
994     }
995     if (cp < list.length())
996     {
997       jv.addElement(list.substring(cp));
998     }
999     if (jv.size() > 0)
1000     {
1001       String[] v = new String[jv.size()];
1002       for (int i = 0; i < v.length; i++)
1003       {
1004         v[i] = (String) jv.elementAt(i);
1005       }
1006       jv.removeAllElements();
1007       if (debug)
1008       {
1009         System.err.println("Array from '" + separator
1010                 + "' separated List:\n" + v.length);
1011         for (int i = 0; i < v.length; i++)
1012         {
1013           System.err.println("item " + i + " '" + v[i] + "'");
1014         }
1015       }
1016       return v;
1017     }
1018     if (debug)
1019     {
1020       System.err.println("Empty Array from '" + separator
1021               + "' separated List");
1022     }
1023     return null;
1024   }
1025
1026   /**
1027    * concatenate the list with separator
1028    * 
1029    * @param list
1030    * @return concatenated string
1031    */
1032   public String arrayToSeparatorList(String[] list)
1033   {
1034     StringBuffer v = new StringBuffer();
1035     if (list != null)
1036     {
1037       for (int i = 0, iSize = list.length - 1; i < iSize; i++)
1038       {
1039         if (list[i] != null)
1040         {
1041           v.append(list[i]);
1042         }
1043         v.append(separator);
1044       }
1045       if (list[list.length - 1] != null)
1046       {
1047         v.append(list[list.length - 1]);
1048       }
1049       if (debug)
1050       {
1051         System.err.println("Returning '" + separator
1052                 + "' separated List:\n");
1053         System.err.println(v);
1054       }
1055       return v.toString();
1056     }
1057     if (debug)
1058     {
1059       System.err.println("Returning empty '" + separator
1060               + "' separated List\n");
1061     }
1062     return "";
1063   }
1064
1065   /**
1066    * @return
1067    * @see jalview.appletgui.AlignFrame#getFeatureGroups()
1068    */
1069   public String getFeatureGroups()
1070   {
1071     String lst = arrayToSeparatorList(getDefaultTargetFrame()
1072             .getFeatureGroups());
1073     return lst;
1074   }
1075
1076   /**
1077    * @param alf
1078    *                alignframe to get feature groups on
1079    * @return
1080    * @see jalview.appletgui.AlignFrame#getFeatureGroups()
1081    */
1082   public String getFeatureGroupsOn(AlignFrame alf)
1083   {
1084     String lst = arrayToSeparatorList(alf.getFeatureGroups());
1085     return lst;
1086   }
1087
1088   /**
1089    * @param visible
1090    * @return
1091    * @see jalview.appletgui.AlignFrame#getFeatureGroupsOfState(boolean)
1092    */
1093   public String getFeatureGroupsOfState(boolean visible)
1094   {
1095     return arrayToSeparatorList(getDefaultTargetFrame()
1096             .getFeatureGroupsOfState(visible));
1097   }
1098
1099   /**
1100    * @param alf
1101    *                align frame to get groups of state visible
1102    * @param visible
1103    * @return
1104    * @see jalview.appletgui.AlignFrame#getFeatureGroupsOfState(boolean)
1105    */
1106   public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
1107   {
1108     return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
1109   }
1110
1111   /**
1112    * @param groups
1113    *                tab separated list of group names
1114    * @param state
1115    *                true or false
1116    * @see jalview.appletgui.AlignFrame#setFeatureGroupState(java.lang.String[],
1117    *      boolean)
1118    */
1119   public void setFeatureGroupStateOn(AlignFrame alf, String groups,
1120           boolean state)
1121   {
1122     boolean st = state;// !(state==null || state.equals("") ||
1123                         // state.toLowerCase().equals("false"));
1124     alf.setFeatureGroupState(separatorListToArray(groups), st);
1125   }
1126
1127   public void setFeatureGroupState(String groups, boolean state)
1128   {
1129     setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
1130   }
1131
1132   /**
1133    * List separator string
1134    * 
1135    * @return the separator
1136    */
1137   public String getSeparator()
1138   {
1139     return separator;
1140   }
1141
1142   /**
1143    * List separator string
1144    * 
1145    * @param separator
1146    *                the separator to set
1147    */
1148   public void setSeparator(String separator)
1149   {
1150     this.separator = separator;
1151   }
1152 }