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