Updated PDB loading params
[jalview.git] / src / jalview / bin / JalviewLite.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2007 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
38     extends Applet
39 {
40
41
42
43   ///////////////////////////////////////////
44   //The following public methods maybe called
45   //externally, eg via javascript in HTML page
46
47   public String getSelectedSequences()
48   {
49     StringBuffer result = new StringBuffer("");
50
51     if (initialAlignFrame.viewport.getSelectionGroup() != null)
52     {
53       SequenceI[] seqs = initialAlignFrame.viewport.getSelectionGroup().
54           getSequencesInOrder(
55               initialAlignFrame.viewport.getAlignment());
56
57       for (int i = 0; i < seqs.length; i++)
58       {
59         result.append(seqs[i].getName() + "¬");
60       }
61     }
62
63     return result.toString();
64   }
65
66   public String getAlignment(String format)
67   {
68     return getAlignment(format, "true");
69   }
70
71   public String getAlignment(String format, String suffix)
72   {
73     try
74     {
75       boolean seqlimits = suffix.equalsIgnoreCase("true");
76
77       String reply = new AppletFormatAdapter().formatSequences(format,
78           currentAlignFrame.viewport.getAlignment(), seqlimits);
79       return reply;
80     }
81     catch (Exception ex)
82     {
83       ex.printStackTrace();
84       return "Error retrieving alignment in " + format + " format. ";
85     }
86   }
87
88   public void loadAnnotation(String annotation)
89   {
90     if (new AnnotationFile().readAnnotationFile(
91         currentAlignFrame.getAlignViewport().getAlignment(), annotation,
92         AppletFormatAdapter.PASTE))
93     {
94       currentAlignFrame.alignPanel.fontChanged();
95       currentAlignFrame.alignPanel.setScrollValues(0, 0);
96     }
97     else
98     {
99       currentAlignFrame.parseFeaturesFile(annotation, AppletFormatAdapter.PASTE);
100     }
101   }
102
103   public String getFeatures(String format)
104   {
105     return currentAlignFrame.outputFeatures(false, format);
106   }
107
108   public String getAnnotation()
109   {
110     return currentAlignFrame.outputAnnotations(false);
111   }
112
113   public void loadAlignment(String text, String title)
114   {
115     Alignment al = null;
116     String format = new IdentifyFile().Identify(text, AppletFormatAdapter.PASTE);
117     try
118     {
119       al = new AppletFormatAdapter().readFile(text,
120                                               AppletFormatAdapter.PASTE,
121                                               format);
122       if (al.getHeight() > 0)
123       {
124         new AlignFrame(al, this, title, false);
125       }
126     }
127     catch (java.io.IOException ex)
128     {
129       ex.printStackTrace();
130     }
131   }
132
133   ////////////////////////////////////////////////
134   ////////////////////////////////////////////////
135
136
137
138   static int lastFrameX = 200;
139   static int lastFrameY = 200;
140   boolean fileFound = true;
141   String file = "No file";
142   Button launcher = new Button("Start Jalview");
143
144   //The currentAlignFrame is static, it will change
145   //if and when the user selects a new window
146   public static AlignFrame currentAlignFrame;
147
148   //This is the first frame to be displayed, and does not change
149   AlignFrame initialAlignFrame;
150
151   boolean embedded = false;
152
153   public boolean jmolAvailable = false;
154
155   /**
156    * init method for Jalview Applet
157    */
158   public void init()
159   {
160     try
161     {
162       Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
163
164       jmolAvailable = true;
165     }
166     catch (java.lang.ClassNotFoundException ex)
167     {
168       System.out.println("Jmol not found - Using MCview for structures");
169     }
170
171     int r = 255;
172     int g = 255;
173     int b = 255;
174     String param = getParameter("RGB");
175
176     if (param != null)
177     {
178       try
179       {
180         r = Integer.parseInt(param.substring(0, 2), 16);
181         g = Integer.parseInt(param.substring(2, 4), 16);
182         b = Integer.parseInt(param.substring(4, 6), 16);
183       }
184       catch (Exception ex)
185       {
186         r = 255;
187         g = 255;
188         b = 255;
189       }
190     }
191
192     param = getParameter("label");
193     if (param != null)
194     {
195       launcher.setLabel(param);
196     }
197
198     this.setBackground(new Color(r, g, b));
199
200     file = getParameter("file");
201
202     if (file == null)
203     {
204       //Maybe the sequences are added as parameters
205       StringBuffer data = new StringBuffer("PASTE");
206       int i = 1;
207       while ( (file = getParameter("sequence" + i)) != null)
208       {
209         data.append(file.toString() + "\n");
210         i++;
211       }
212       if (data.length() > 5)
213       {
214         file = data.toString();
215       }
216     }
217
218     final JalviewLite applet = this;
219     if (getParameter("embedded") != null
220         && getParameter("embedded").equalsIgnoreCase("true"))
221     {
222       embedded = true;
223       LoadingThread loader = new LoadingThread(file, applet);
224       loader.start();
225     }
226     else if (file != null)
227     {
228       add(launcher);
229
230       launcher.addActionListener(new java.awt.event.ActionListener()
231       {
232         public void actionPerformed(ActionEvent e)
233         {
234           LoadingThread loader = new LoadingThread(file,
235               applet);
236           loader.start();
237         }
238       });
239     }
240     else
241     {
242       file = "NO FILE";
243       fileFound = false;
244     }
245   }
246
247   public static void main(String[] args)
248   {
249     if (args.length != 1)
250     {
251       System.out.println("\nUsage: java -jar jalviewApplet.jar fileName\n");
252       System.exit(1);
253     }
254
255     String format = new jalview.io.IdentifyFile().Identify(args[0],
256         AppletFormatAdapter.FILE);
257
258     Alignment al = null;
259     try
260     {
261       al = new AppletFormatAdapter().readFile(args[0], AppletFormatAdapter.FILE,
262                                               format);
263     }
264     catch (java.io.IOException ex)
265     {
266       ex.printStackTrace();
267     }
268     if ( (al != null) && (al.getHeight() > 0))
269     {
270       AlignFrame af = new AlignFrame(al, null, args[0], false);
271       af.statusBar.setText("Successfully loaded file " + args[0]);
272     }
273   }
274
275   /**
276    * Initialises and displays a new java.awt.Frame
277    *
278    * @param frame java.awt.Frame to be displayed
279    * @param title title of new frame
280    * @param width width if new frame
281    * @param height height of new frame
282    */
283   public static void addFrame(final Frame frame, String title, int width,
284                               int height)
285   {
286     frame.setLocation(lastFrameX, lastFrameY);
287     lastFrameX += 40;
288     lastFrameY += 40;
289     frame.setSize(width, height);
290     frame.setTitle(title);
291     frame.addWindowListener(new WindowAdapter()
292     {
293       public void windowClosing(WindowEvent e)
294       {
295         if (frame instanceof AlignFrame)
296         {
297           ( (AlignFrame) frame).closeMenuItem_actionPerformed();
298         }
299         if (currentAlignFrame == frame)
300         {
301           currentAlignFrame = null;
302         }
303         lastFrameX -= 40;
304         lastFrameY -= 40;
305         frame.setMenuBar(null);
306         frame.dispose();
307       }
308
309       public void windowActivated(WindowEvent e)
310       {
311         if (frame instanceof AlignFrame)
312         {
313           currentAlignFrame = (AlignFrame) frame;
314         }
315       }
316
317     });
318     frame.setVisible(true);
319   }
320
321   /**
322    * This paints the background surrounding the "Launch Jalview button"
323    * <br>
324    * <br>If file given in parameter not found, displays error message
325    *
326    * @param g graphics context
327    */
328   public void paint(Graphics g)
329   {
330     if (!fileFound)
331     {
332       g.setColor(new Color(200, 200, 200));
333       g.setColor(Color.cyan);
334       g.fillRect(0, 0, getSize().width, getSize().height);
335       g.setColor(Color.red);
336       g.drawString("Jalview can't open file", 5, 15);
337       g.drawString("\"" + file + "\"", 5, 30);
338     }
339     else if (embedded)
340     {
341       g.setColor(Color.black);
342       g.setFont(new Font("Arial", Font.BOLD, 24));
343       g.drawString("Jalview Applet", 50, this.getSize().height / 2 - 30);
344       g.drawString("Loading Data...", 50, this.getSize().height / 2);
345     }
346
347   }
348
349   class LoadingThread
350       extends Thread
351   {
352     String file;
353     String protocol;
354     String format;
355     JalviewLite applet;
356
357     public LoadingThread(String _file,
358                          JalviewLite _applet)
359     {
360       file = _file;
361       if (file.startsWith("PASTE"))
362       {
363         file = file.substring(5);
364         protocol = AppletFormatAdapter.PASTE;
365       }
366       else if (inArchive(file))
367       {
368         protocol = AppletFormatAdapter.CLASSLOADER;
369       }
370       else
371       {
372         file = addProtocol(file);
373         protocol = AppletFormatAdapter.URL;
374       }
375       format = new jalview.io.IdentifyFile().Identify(file, protocol);
376       applet = _applet;
377     }
378
379     public void run()
380     {
381       Alignment al = null;
382       try
383       {
384         al = new AppletFormatAdapter().readFile(file, protocol,
385                                                 format);
386       }
387       catch (java.io.IOException ex)
388       {
389         ex.printStackTrace();
390       }
391       if ( (al != null) && (al.getHeight() > 0))
392       {
393         currentAlignFrame = new AlignFrame(al,
394                                            applet,
395                                            file,
396                                            embedded);
397
398         if (protocol == jalview.io.AppletFormatAdapter.PASTE)
399         {
400           currentAlignFrame.setTitle("Sequences from " + getDocumentBase());
401         }
402
403         initialAlignFrame = currentAlignFrame;
404
405         currentAlignFrame.statusBar.setText("Successfully loaded file " + file);
406
407         String treeFile = applet.getParameter("tree");
408         if (treeFile == null)
409         {
410           treeFile = applet.getParameter("treeFile");
411         }
412
413         if (treeFile != null)
414         {
415           try
416           {
417             if (inArchive(treeFile))
418             {
419               protocol = AppletFormatAdapter.CLASSLOADER;
420             }
421             else
422             {
423               protocol = AppletFormatAdapter.URL;
424               treeFile = addProtocol(treeFile);
425             }
426
427             jalview.io.NewickFile fin = new jalview.io.NewickFile(treeFile,
428                 protocol);
429
430             fin.parse();
431
432             if (fin.getTree() != null)
433             {
434               currentAlignFrame.loadTree(fin, treeFile);
435             }
436           }
437           catch (Exception ex)
438           {
439             ex.printStackTrace();
440           }
441         }
442
443         String param = getParameter("features");
444         if (param != null)
445         {
446           if (!inArchive(param))
447           {
448             param = addProtocol(param);
449           }
450
451           currentAlignFrame.parseFeaturesFile(param, protocol);
452         }
453
454         param = getParameter("showFeatureSettings");
455         if (param != null && param.equalsIgnoreCase("true"))
456         {
457           currentAlignFrame.viewport.showSequenceFeatures(true);
458           new FeatureSettings(currentAlignFrame.alignPanel);
459         }
460
461         param = getParameter("annotations");
462         if (param != null)
463         {
464           if (!inArchive(param))
465           {
466             param = addProtocol(param);
467           }
468
469           new AnnotationFile().readAnnotationFile(
470               currentAlignFrame.viewport.getAlignment(),
471               param,
472               protocol);
473
474           currentAlignFrame.alignPanel.fontChanged();
475           currentAlignFrame.alignPanel.setScrollValues(0, 0);
476
477         }
478
479         param = getParameter("jnetfile");
480         if (param != null)
481         {
482           try
483           {
484             if (inArchive(param))
485             {
486               protocol = AppletFormatAdapter.CLASSLOADER;
487             }
488             else
489             {
490               protocol = AppletFormatAdapter.URL;
491               param = addProtocol(param);
492             }
493
494             jalview.io.JPredFile predictions = new jalview.io.JPredFile(
495                 param, protocol);
496             new JnetAnnotationMaker().add_annotation(predictions,
497                 currentAlignFrame.viewport.getAlignment(),
498                 0, false); // do not add sequence profile from concise output
499             currentAlignFrame.alignPanel.fontChanged();
500             currentAlignFrame.alignPanel.setScrollValues(0, 0);
501           }
502           catch (Exception ex)
503           {
504             ex.printStackTrace();
505           }
506         }
507
508
509         param = getParameter("PDBFILE");
510         if (param != null)
511         {
512
513           PDBEntry pdb = new PDBEntry();
514
515           String seqstring;
516           SequenceI [] seqs = null;
517
518           if(param.indexOf(" ")>-1)
519           {
520             seqstring = param.substring(param.indexOf(" ")+1);
521             param = param.substring(0, param.indexOf(" "));
522             StringTokenizer st = new StringTokenizer(seqstring);
523             Vector tmp = new Vector();
524             while(st.hasMoreTokens())
525             {
526               tmp.addElement((Sequence) currentAlignFrame.
527                 getAlignViewport().getAlignment().
528                 findName(st.nextToken()));
529             }
530
531             seqs = new SequenceI[tmp.size()];
532             tmp.copyInto(seqs);
533           }
534           else
535           {
536             String sequence = applet.getParameter("PDBSEQ");
537             if (sequence != null)
538               seqs = new SequenceI[]
539                   {
540                   (Sequence) currentAlignFrame.
541                   getAlignViewport().getAlignment().
542                   findName(sequence)};
543           }
544
545           if (!inArchive(param) || jmolAvailable)
546           {
547             param = addProtocol(param);
548           }
549
550           pdb.setFile(param);
551
552
553           if (jmolAvailable)
554             new jalview.appletgui.AppletJmol(pdb,
555                                              seqs,
556                                              currentAlignFrame.alignPanel,
557                                              protocol);
558           else
559
560             new MCview.AppletPDBViewer(pdb,
561                                        seqs,
562                                        currentAlignFrame.alignPanel,
563                                        protocol);
564         }
565       }
566       else
567       {
568         fileFound = false;
569         remove(launcher);
570         repaint();
571       }
572     }
573
574     /**
575      * Discovers whether the given file is in the Applet Archive
576      * @param file String
577      * @return boolean
578      */
579     boolean inArchive(String file)
580     {
581       //This might throw a security exception in certain browsers
582       //Netscape Communicator for instance.
583       try
584       {
585         return (getClass().getResourceAsStream("/" + file) != null);
586       }
587       catch (Exception ex)
588       {
589         System.out.println("Exception checking resources: " + file + " " + ex);
590         return false;
591       }
592     }
593
594     String addProtocol(String file)
595     {
596       if (file.indexOf("://") == -1)
597       {
598         file = getCodeBase() + file;
599       }
600
601       return file;
602     }
603   }
604 }