Add param to Jmol path
[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       if (!System.getProperty("java.version").startsWith("1.1"))
163       {
164         Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
165         jmolAvailable = true;
166       }
167     }
168     catch (java.lang.ClassNotFoundException ex)
169     {
170       System.out.println("Jmol not available - Using MCview for structures");
171     }
172
173     int r = 255;
174     int g = 255;
175     int b = 255;
176     String param = getParameter("RGB");
177
178     if (param != null)
179     {
180       try
181       {
182         r = Integer.parseInt(param.substring(0, 2), 16);
183         g = Integer.parseInt(param.substring(2, 4), 16);
184         b = Integer.parseInt(param.substring(4, 6), 16);
185       }
186       catch (Exception ex)
187       {
188         r = 255;
189         g = 255;
190         b = 255;
191       }
192     }
193
194     param = getParameter("label");
195     if (param != null)
196     {
197       launcher.setLabel(param);
198     }
199
200     this.setBackground(new Color(r, g, b));
201
202     file = getParameter("file");
203
204     if (file == null)
205     {
206       //Maybe the sequences are added as parameters
207       StringBuffer data = new StringBuffer("PASTE");
208       int i = 1;
209       while ( (file = getParameter("sequence" + i)) != null)
210       {
211         data.append(file.toString() + "\n");
212         i++;
213       }
214       if (data.length() > 5)
215       {
216         file = data.toString();
217       }
218     }
219
220     final JalviewLite applet = this;
221     if (getParameter("embedded") != null
222         && getParameter("embedded").equalsIgnoreCase("true"))
223     {
224       embedded = true;
225       LoadingThread loader = new LoadingThread(file, applet);
226       loader.start();
227     }
228     else if (file != null)
229     {
230       add(launcher);
231
232       launcher.addActionListener(new java.awt.event.ActionListener()
233       {
234         public void actionPerformed(ActionEvent e)
235         {
236           LoadingThread loader = new LoadingThread(file,
237               applet);
238           loader.start();
239         }
240       });
241     }
242     else
243     {
244       file = "NO FILE";
245       fileFound = false;
246     }
247   }
248
249   public static void main(String[] args)
250   {
251     if (args.length != 1)
252     {
253       System.out.println("\nUsage: java -jar jalviewApplet.jar fileName\n");
254       System.exit(1);
255     }
256
257     String format = new jalview.io.IdentifyFile().Identify(args[0],
258         AppletFormatAdapter.FILE);
259
260     Alignment al = null;
261     try
262     {
263       al = new AppletFormatAdapter().readFile(args[0], AppletFormatAdapter.FILE,
264                                               format);
265     }
266     catch (java.io.IOException ex)
267     {
268       ex.printStackTrace();
269     }
270     if ( (al != null) && (al.getHeight() > 0))
271     {
272       AlignFrame af = new AlignFrame(al, null, args[0], false);
273       af.statusBar.setText("Successfully loaded file " + args[0]);
274     }
275   }
276
277   /**
278    * Initialises and displays a new java.awt.Frame
279    *
280    * @param frame java.awt.Frame to be displayed
281    * @param title title of new frame
282    * @param width width if new frame
283    * @param height height of new frame
284    */
285   public static void addFrame(final Frame frame, String title, int width,
286                               int height)
287   {
288     frame.setLocation(lastFrameX, lastFrameY);
289     lastFrameX += 40;
290     lastFrameY += 40;
291     frame.setSize(width, height);
292     frame.setTitle(title);
293     frame.addWindowListener(new WindowAdapter()
294     {
295       public void windowClosing(WindowEvent e)
296       {
297         if (frame instanceof AlignFrame)
298         {
299           ( (AlignFrame) frame).closeMenuItem_actionPerformed();
300         }
301         if (currentAlignFrame == frame)
302         {
303           currentAlignFrame = null;
304         }
305         lastFrameX -= 40;
306         lastFrameY -= 40;
307         frame.setMenuBar(null);
308         frame.dispose();
309       }
310
311       public void windowActivated(WindowEvent e)
312       {
313         if (frame instanceof AlignFrame)
314         {
315           currentAlignFrame = (AlignFrame) frame;
316         }
317       }
318
319     });
320     frame.setVisible(true);
321   }
322
323   /**
324    * This paints the background surrounding the "Launch Jalview button"
325    * <br>
326    * <br>If file given in parameter not found, displays error message
327    *
328    * @param g graphics context
329    */
330   public void paint(Graphics g)
331   {
332     if (!fileFound)
333     {
334       g.setColor(new Color(200, 200, 200));
335       g.setColor(Color.cyan);
336       g.fillRect(0, 0, getSize().width, getSize().height);
337       g.setColor(Color.red);
338       g.drawString("Jalview can't open file", 5, 15);
339       g.drawString("\"" + file + "\"", 5, 30);
340     }
341     else if (embedded)
342     {
343       g.setColor(Color.black);
344       g.setFont(new Font("Arial", Font.BOLD, 24));
345       g.drawString("Jalview Applet", 50, this.getSize().height / 2 - 30);
346       g.drawString("Loading Data...", 50, this.getSize().height / 2);
347     }
348
349   }
350
351   class LoadingThread
352       extends Thread
353   {
354     String file;
355     String protocol;
356     String format;
357     JalviewLite applet;
358
359     public LoadingThread(String _file,
360                          JalviewLite _applet)
361     {
362       file = _file;
363       if (file.startsWith("PASTE"))
364       {
365         file = file.substring(5);
366         protocol = AppletFormatAdapter.PASTE;
367       }
368       else if (inArchive(file))
369       {
370         protocol = AppletFormatAdapter.CLASSLOADER;
371       }
372       else
373       {
374         file = addProtocol(file);
375         protocol = AppletFormatAdapter.URL;
376       }
377       format = new jalview.io.IdentifyFile().Identify(file, protocol);
378       applet = _applet;
379     }
380
381     public void run()
382     {
383       Alignment al = null;
384       try
385       {
386         al = new AppletFormatAdapter().readFile(file, protocol,
387                                                 format);
388       }
389       catch (java.io.IOException ex)
390       {
391         ex.printStackTrace();
392       }
393       if ( (al != null) && (al.getHeight() > 0))
394       {
395         currentAlignFrame = new AlignFrame(al,
396                                            applet,
397                                            file,
398                                            embedded);
399
400         if (protocol == jalview.io.AppletFormatAdapter.PASTE)
401         {
402           currentAlignFrame.setTitle("Sequences from " + getDocumentBase());
403         }
404
405         initialAlignFrame = currentAlignFrame;
406
407         currentAlignFrame.statusBar.setText("Successfully loaded file " + file);
408
409         String treeFile = applet.getParameter("tree");
410         if (treeFile == null)
411         {
412           treeFile = applet.getParameter("treeFile");
413         }
414
415         if (treeFile != null)
416         {
417           try
418           {
419             if (inArchive(treeFile))
420             {
421               protocol = AppletFormatAdapter.CLASSLOADER;
422             }
423             else
424             {
425               protocol = AppletFormatAdapter.URL;
426               treeFile = addProtocol(treeFile);
427             }
428
429             jalview.io.NewickFile fin = new jalview.io.NewickFile(treeFile,
430                 protocol);
431
432             fin.parse();
433
434             if (fin.getTree() != null)
435             {
436               currentAlignFrame.loadTree(fin, treeFile);
437             }
438           }
439           catch (Exception ex)
440           {
441             ex.printStackTrace();
442           }
443         }
444
445         String param = getParameter("features");
446         if (param != null)
447         {
448           if (!inArchive(param))
449           {
450             param = addProtocol(param);
451           }
452
453           currentAlignFrame.parseFeaturesFile(param, protocol);
454         }
455
456         param = getParameter("showFeatureSettings");
457         if (param != null && param.equalsIgnoreCase("true"))
458         {
459           currentAlignFrame.viewport.showSequenceFeatures(true);
460           new FeatureSettings(currentAlignFrame.alignPanel);
461         }
462
463         param = getParameter("annotations");
464         if (param != null)
465         {
466           if (!inArchive(param))
467           {
468             param = addProtocol(param);
469           }
470
471           new AnnotationFile().readAnnotationFile(
472               currentAlignFrame.viewport.getAlignment(),
473               param,
474               protocol);
475
476           currentAlignFrame.alignPanel.fontChanged();
477           currentAlignFrame.alignPanel.setScrollValues(0, 0);
478
479         }
480
481         param = getParameter("jnetfile");
482         if (param != null)
483         {
484           try
485           {
486             if (inArchive(param))
487             {
488               protocol = AppletFormatAdapter.CLASSLOADER;
489             }
490             else
491             {
492               protocol = AppletFormatAdapter.URL;
493               param = addProtocol(param);
494             }
495
496             jalview.io.JPredFile predictions = new jalview.io.JPredFile(
497                 param, protocol);
498             new JnetAnnotationMaker().add_annotation(predictions,
499                 currentAlignFrame.viewport.getAlignment(),
500                 0, false); // do not add sequence profile from concise output
501             currentAlignFrame.alignPanel.fontChanged();
502             currentAlignFrame.alignPanel.setScrollValues(0, 0);
503           }
504           catch (Exception ex)
505           {
506             ex.printStackTrace();
507           }
508         }
509
510
511         param = getParameter("PDBFILE");
512         if (param != null)
513         {
514
515           PDBEntry pdb = new PDBEntry();
516
517           String seqstring;
518           SequenceI [] seqs = null;
519
520           if(param.indexOf(" ")>-1)
521           {
522             seqstring = param.substring(param.indexOf(" ")+1);
523             param = param.substring(0, param.indexOf(" "));
524             StringTokenizer st = new StringTokenizer(seqstring);
525             Vector tmp = new Vector();
526             while(st.hasMoreTokens())
527             {
528               tmp.addElement((Sequence) currentAlignFrame.
529                 getAlignViewport().getAlignment().
530                 findName(st.nextToken()));
531             }
532
533             seqs = new SequenceI[tmp.size()];
534             tmp.copyInto(seqs);
535           }
536           else
537           {
538             String sequence = applet.getParameter("PDBSEQ");
539             if (sequence != null)
540               seqs = new SequenceI[]
541                   {
542                   (Sequence) currentAlignFrame.
543                   getAlignViewport().getAlignment().
544                   findName(sequence)};
545           }
546
547          // if (!inArchive(param) || jmolAvailable)
548           {
549             param = addProtocol(param);
550           }
551
552           pdb.setFile(param);
553
554           for(int i=0; i<seqs.length; i++)
555           {
556             ((Sequence)seqs[i]).addPDBId(pdb);
557           }
558
559           if (jmolAvailable)
560             new jalview.appletgui.AppletJmol(pdb,
561                                              seqs,
562                                              currentAlignFrame.alignPanel,
563                                              protocol);
564           else
565
566             new MCview.AppletPDBViewer(pdb,
567                                        seqs,
568                                        currentAlignFrame.alignPanel,
569                                        protocol);
570         }
571       }
572       else
573       {
574         fileFound = false;
575         remove(launcher);
576         repaint();
577       }
578     }
579
580     /**
581      * Discovers whether the given file is in the Applet Archive
582      * @param file String
583      * @return boolean
584      */
585     boolean inArchive(String file)
586     {
587       //This might throw a security exception in certain browsers
588       //Netscape Communicator for instance.
589       try
590       {
591         return (getClass().getResourceAsStream("/" + file) != null);
592       }
593       catch (Exception ex)
594       {
595         System.out.println("Exception checking resources: " + file + " " + ex);
596         return false;
597       }
598     }
599
600     String addProtocol(String file)
601     {
602       if (file.indexOf("://") == -1)
603       {
604         file = getCodeBase() + file;
605       }
606
607       return file;
608     }
609   }
610 }