Jalview 2.6 source licence
[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"/>
905          * Undocumented for 2.6 - related to JAL-434
906          */
907         applet.setAlignPdbStructures(getDefaultParameter("alignpdbfiles",false));
908         /*
909          * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
910          * PDB|1GAQ|1GAQ|C">
911          * 
912          * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
913          * 
914          * <param name="PDBfile3" value="1q0o Q45135_9MICO">
915          */
916         
917         int pdbFileCount = 0;
918         // Accumulate pdbs here if they are heading for the same view (if alignPdbStructures is true)
919         Vector pdbs=new Vector();
920         do
921         {
922           if (pdbFileCount > 0)
923             param = getParameter("PDBFILE" + pdbFileCount);
924           else
925             param = getParameter("PDBFILE");
926
927           if (param != null)
928           {
929             PDBEntry pdb = new PDBEntry();
930
931             String seqstring;
932             SequenceI[] seqs = null;
933             String[] chains = null;
934
935             StringTokenizer st = new StringTokenizer(param, " ");
936
937             if (st.countTokens() < 2)
938             {
939               String sequence = applet.getParameter("PDBSEQ");
940               if (sequence != null)
941                 seqs = new SequenceI[]
942                 { (Sequence) newAlignFrame.getAlignViewport()
943                         .getAlignment().findName(sequence) };
944
945             }
946             else
947             {
948               param = st.nextToken();
949               Vector tmp = new Vector();
950               Vector tmp2 = new Vector();
951
952               while (st.hasMoreTokens())
953               {
954                 seqstring = st.nextToken();
955                 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
956                 if (st2.countTokens() > 1)
957                 {
958                   // This is the chain
959                   tmp2.addElement(st2.nextToken());
960                   seqstring = st2.nextToken();
961                 }
962                 tmp.addElement((Sequence) newAlignFrame.getAlignViewport()
963                         .getAlignment().findName(seqstring));
964               }
965
966               seqs = new SequenceI[tmp.size()];
967               tmp.copyInto(seqs);
968               if (tmp2.size() == tmp.size())
969               {
970                 chains = new String[tmp2.size()];
971                 tmp2.copyInto(chains);
972               }
973             }
974             param = setProtocolState(param);
975
976             if (// !jmolAvailable
977             // &&
978             protocol == AppletFormatAdapter.CLASSLOADER)
979             {
980               // TODO: verify this Re:
981               // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
982               // This exception preserves the current behaviour where, even if
983               // the local pdb file was identified in the class loader
984               protocol = AppletFormatAdapter.URL; // this is probably NOT
985               // CORRECT!
986               param = addProtocol(param); //
987             }
988
989             pdb.setFile(param);
990
991             if (seqs != null)
992             {
993               for (int i = 0; i < seqs.length; i++)
994               {
995                 if (seqs[i] != null)
996                 {
997                   ((Sequence) seqs[i]).addPDBId(pdb);
998                 }
999                 else
1000                 {
1001                   if (JalviewLite.debug)
1002                   {
1003                     // this may not really be a problem but we give a warning
1004                     // anyway
1005                     System.err
1006                             .println("Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
1007                                     + i + ")");
1008                   }
1009                 }
1010               }
1011               
1012               if (!alignPdbStructures) {
1013                 newAlignFrame.newStructureView(applet, pdb, seqs, chains,
1014                       protocol);
1015               } else {
1016                 pdbs.addElement(new Object[] { pdb, seqs, chains, new String(protocol)});
1017               }
1018             }
1019           }
1020
1021           pdbFileCount++;
1022         } while (pdbFileCount < 10);
1023         if (pdbs.size()>0)
1024         {
1025           SequenceI[][] seqs = new SequenceI[pdbs.size()][];
1026           PDBEntry[] pdb = new PDBEntry[pdbs.size()];
1027           String[][] chains = new String[pdbs.size()][];
1028           String[] protocols = new String[pdbs.size()];
1029           for (int pdbsi=0,pdbsiSize=pdbs.size(); pdbsi<pdbsiSize;pdbsi++)
1030           {
1031             Object[] o = (Object[]) pdbs.elementAt(pdbsi);
1032             pdb[pdbsi] = (PDBEntry) o[0];
1033             seqs[pdbsi] = (SequenceI[]) o[1];
1034             chains[pdbsi] = (String[]) o[2];
1035             protocols[pdbsi] = (String) o[3];
1036           }
1037           newAlignFrame.alignedStructureView(applet, pdb, seqs, chains, protocols);
1038           
1039         }
1040         // ///////////////////////////
1041         // modify display of features
1042         //
1043         // hide specific groups
1044         param = getParameter("hidefeaturegroups");
1045         if (param != null)
1046         {
1047           applet.setFeatureGroupStateOn(newAlignFrame, param, false);
1048         }
1049         // show specific groups
1050         param = getParameter("showfeaturegroups");
1051         if (param != null)
1052         {
1053           applet.setFeatureGroupStateOn(newAlignFrame, param, true);
1054         }
1055       }
1056       else
1057       {
1058         fileFound = false;
1059         remove(launcher);
1060         repaint();
1061       }
1062     }
1063
1064     /**
1065      * Discovers whether the given file is in the Applet Archive
1066      * 
1067      * @param file
1068      *          String
1069      * @return boolean
1070      */
1071     boolean inArchive(String file)
1072     {
1073       // This might throw a security exception in certain browsers
1074       // Netscape Communicator for instance.
1075       try
1076       {
1077         boolean rtn = (getClass().getResourceAsStream("/" + file) != null);
1078         if (debug)
1079         {
1080           System.err.println("Resource '" + file + "' was "
1081                   + (rtn ? "" : "not") + " located by classloader.");
1082         }
1083         return rtn;
1084       } catch (Exception ex)
1085       {
1086         System.out.println("Exception checking resources: " + file + " "
1087                 + ex);
1088         return false;
1089       }
1090     }
1091
1092     String addProtocol(String file)
1093     {
1094       if (file.indexOf("://") == -1)
1095       {
1096         file = getCodeBase() + file;
1097         if (debug)
1098         {
1099           System.err.println("Prepended codebase for resource: '" + file
1100                   + "'");
1101         }
1102       }
1103
1104       return file;
1105     }
1106   }
1107
1108   /**
1109    * @return the default alignFrame acted on by the public applet methods. May
1110    *         return null with an error message on System.err indicating the
1111    *         fact.
1112    */
1113   protected AlignFrame getDefaultTargetFrame()
1114   {
1115     if (currentAlignFrame != null)
1116     {
1117       return currentAlignFrame;
1118     }
1119     if (initialAlignFrame != null)
1120     {
1121       return initialAlignFrame;
1122     }
1123     System.err
1124             .println("Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
1125     return null;
1126   }
1127
1128   /**
1129    * separator used for separatorList
1130    */
1131   protected String separator = "|"; // this is a safe(ish) separator - tabs
1132
1133   // don't work for firefox
1134
1135   /**
1136    * parse the string into a list
1137    * 
1138    * @param list
1139    * @return elements separated by separator
1140    */
1141   public String[] separatorListToArray(String list)
1142   {
1143     int seplen = separator.length();
1144     if (list == null || list.equals(""))
1145       return null;
1146     java.util.Vector jv = new Vector();
1147     int cp = 0, pos;
1148     while ((pos = list.indexOf(separator, cp)) > cp)
1149     {
1150       jv.addElement(list.substring(cp, pos));
1151       cp = pos + seplen;
1152     }
1153     if (cp < list.length())
1154     {
1155       jv.addElement(list.substring(cp));
1156     }
1157     if (jv.size() > 0)
1158     {
1159       String[] v = new String[jv.size()];
1160       for (int i = 0; i < v.length; i++)
1161       {
1162         v[i] = (String) jv.elementAt(i);
1163       }
1164       jv.removeAllElements();
1165       if (debug)
1166       {
1167         System.err.println("Array from '" + separator
1168                 + "' separated List:\n" + v.length);
1169         for (int i = 0; i < v.length; i++)
1170         {
1171           System.err.println("item " + i + " '" + v[i] + "'");
1172         }
1173       }
1174       return v;
1175     }
1176     if (debug)
1177     {
1178       System.err.println("Empty Array from '" + separator
1179               + "' separated List");
1180     }
1181     return null;
1182   }
1183
1184   /**
1185    * concatenate the list with separator
1186    * 
1187    * @param list
1188    * @return concatenated string
1189    */
1190   public String arrayToSeparatorList(String[] list)
1191   {
1192     StringBuffer v = new StringBuffer();
1193     if (list != null && list.length>0)
1194     {
1195       for (int i = 0, iSize = list.length - 1; i < iSize; i++)
1196       {
1197         if (list[i] != null)
1198         {
1199           v.append(list[i]);
1200         }
1201         v.append(separator);
1202       }
1203       if (list[list.length - 1] != null)
1204       {
1205         v.append(list[list.length - 1]);
1206       }
1207       if (debug)
1208       {
1209         System.err.println("Returning '" + separator
1210                 + "' separated List:\n");
1211         System.err.println(v);
1212       }
1213       return v.toString();
1214     }
1215     if (debug)
1216     {
1217       System.err.println("Returning empty '" + separator
1218               + "' separated List\n");
1219     }
1220     return "";
1221   }
1222
1223   /**
1224    * @return
1225    * @see jalview.appletgui.AlignFrame#getFeatureGroups()
1226    */
1227   public String getFeatureGroups()
1228   {
1229     String lst = arrayToSeparatorList(getDefaultTargetFrame()
1230             .getFeatureGroups());
1231     return lst;
1232   }
1233
1234   /**
1235    * @param alf
1236    *          alignframe to get feature groups on
1237    * @return
1238    * @see jalview.appletgui.AlignFrame#getFeatureGroups()
1239    */
1240   public String getFeatureGroupsOn(AlignFrame alf)
1241   {
1242     String lst = arrayToSeparatorList(alf.getFeatureGroups());
1243     return lst;
1244   }
1245
1246   /**
1247    * @param visible
1248    * @return
1249    * @see jalview.appletgui.AlignFrame#getFeatureGroupsOfState(boolean)
1250    */
1251   public String getFeatureGroupsOfState(boolean visible)
1252   {
1253     return arrayToSeparatorList(getDefaultTargetFrame()
1254             .getFeatureGroupsOfState(visible));
1255   }
1256
1257   /**
1258    * @param alf
1259    *          align frame to get groups of state visible
1260    * @param visible
1261    * @return
1262    * @see jalview.appletgui.AlignFrame#getFeatureGroupsOfState(boolean)
1263    */
1264   public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
1265   {
1266     return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
1267   }
1268
1269   /**
1270    * @param groups
1271    *          tab separated list of group names
1272    * @param state
1273    *          true or false
1274    * @see jalview.appletgui.AlignFrame#setFeatureGroupState(java.lang.String[],
1275    *      boolean)
1276    */
1277   public void setFeatureGroupStateOn(AlignFrame alf, String groups,
1278           boolean state)
1279   {
1280     boolean st = state;// !(state==null || state.equals("") ||
1281     // state.toLowerCase().equals("false"));
1282     alf.setFeatureGroupState(separatorListToArray(groups), st);
1283   }
1284
1285   public void setFeatureGroupState(String groups, boolean state)
1286   {
1287     setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
1288   }
1289
1290   /**
1291    * List separator string
1292    * 
1293    * @return the separator
1294    */
1295   public String getSeparator()
1296   {
1297     return separator;
1298   }
1299
1300   /**
1301    * List separator string
1302    * 
1303    * @param separator
1304    *          the separator to set
1305    */
1306   public void setSeparator(String separator)
1307   {
1308     this.separator = separator;
1309   }
1310
1311   /**
1312    * get boolean value of applet parameter 'name' and return default if
1313    * parameter is not set
1314    * 
1315    * @param name
1316    *          name of paremeter
1317    * @param def
1318    *          the value to return otherwise
1319    * @return true or false
1320    */
1321   public boolean getDefaultParameter(String name, boolean def)
1322   {
1323     String stn;
1324     if ((stn = getParameter(name)) == null)
1325     {
1326       return def;
1327     }
1328     if (stn.toLowerCase().equals("true"))
1329     {
1330       return true;
1331     }
1332     return false;
1333   }
1334
1335   /**
1336    * bind a pdb file to a sequence in the given alignFrame.
1337    * 
1338    * @param alFrame
1339    *          - null or specific alignFrame. This specifies the dataset that
1340    *          will be searched for a seuqence called sequenceId
1341    * @param sequenceId
1342    *          - sequenceId within the dataset.
1343    * @param pdbEntryString
1344    *          - the short name for the PDB file
1345    * @param pdbFile
1346    *          - pdb file - either a URL or a valid PDB file.
1347    * @return true if binding was as success TODO: consider making an exception
1348    *         structure for indicating when PDB parsing or seqeunceId location
1349    *         fails.
1350    */
1351   public boolean addPdbFile(AlignFrame alFrame, String sequenceId,
1352           String pdbEntryString, String pdbFile)
1353   {
1354     return alFrame.addPdbFile(sequenceId, pdbEntryString, pdbFile);
1355   }
1356
1357   protected void setAlignPdbStructures(boolean alignPdbStructures)
1358   {
1359     this.alignPdbStructures = alignPdbStructures;
1360   }
1361
1362   public boolean isAlignPdbStructures()
1363   {
1364     return alignPdbStructures;
1365   }
1366
1367   /**
1368    * get all components associated with the applet of the given type 
1369    * @param class1
1370    * @return
1371    */
1372   public Vector getAppletWindow(Class class1)
1373   {
1374     Vector wnds = new Vector();
1375     Component[] cmp = getComponents();
1376     if (cmp!=null)
1377     {
1378     for (int i=0;i<cmp.length;i++)
1379     {
1380       if (class1.isAssignableFrom(cmp[i].getClass()))
1381       {
1382         wnds.addElement(cmp);
1383       }
1384     }}
1385     return wnds;
1386   }
1387
1388
1389   /**
1390    * bind structures in a viewer to any matching sequences in an alignFrame (use
1391    * sequenceIds to limit scope of search to specific sequences)
1392    * 
1393    * @param alFrame
1394    * @param viewer
1395    * @param sequenceIds
1396    * @return TODO: consider making an exception structure for indicating when
1397    *         binding fails
1398   public SequenceStructureBinding addStructureViewInstance(
1399           AlignFrame alFrame, Object viewer, String sequenceIds)
1400   {
1401
1402     if (sequenceIds != null && sequenceIds.length() > 0)
1403     {
1404       return alFrame.addStructureViewInstance(viewer,
1405               separatorListToArray(sequenceIds));
1406     }
1407     else
1408     {
1409       return alFrame.addStructureViewInstance(viewer, null);
1410     }
1411     // return null;
1412   }
1413    */
1414 }