2 * Jalview - A Sequence Alignment Editor and Viewer (Development Version 2.4.1)
3 * Copyright (C) 2009 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
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.
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.
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
24 import java.awt.event.*;
27 import jalview.appletgui.*;
28 import jalview.datamodel.*;
32 * Jalview Applet. Runs in Java 1.18 runtime
37 public class JalviewLite extends Applet
40 // /////////////////////////////////////////
41 // The following public methods maybe called
42 // externally, eg via javascript in HTML page
44 * @return String list of selected sequence IDs, each terminated by "¬"
47 public String getSelectedSequences()
49 return getSelectedSequencesFrom(getDefaultTargetFrame());
54 * separator string or null for default
55 * @return String list of selected sequence IDs, each terminated by sep or
58 public String getSelectedSequences(String sep)
60 return getSelectedSequencesFrom(getDefaultTargetFrame(), sep);
65 * alignframe containing selection
66 * @return String list of selected sequence IDs, each terminated by "¬"
69 public String getSelectedSequencesFrom(AlignFrame alf)
71 return getSelectedSequencesFrom(alf, "¬");
75 * get list of selected sequence IDs separated by given separator
78 * window containing selection
80 * separator string to use - default is "¬"
81 * @return String list of selected sequence IDs, each terminated by the given
84 public String getSelectedSequencesFrom(AlignFrame alf, String sep)
86 StringBuffer result = new StringBuffer("");
87 if (sep == null || sep.length() == 0)
91 if (alf.viewport.getSelectionGroup() != null)
93 SequenceI[] seqs = alf.viewport.getSelectionGroup()
94 .getSequencesInOrder(alf.viewport.getAlignment());
96 for (int i = 0; i < seqs.length; i++)
98 result.append(seqs[i].getName());
103 return result.toString();
107 * get sequences selected in current alignFrame and return their alignment in
108 * format 'format' either with or without suffix
113 * format of alignment file
115 * "true" to append /start-end string to each sequence ID
116 * @return selected sequences as flat file or empty string if there was no
119 public String getSelectedSequencesAsAlignment(String format, String suffix)
121 return getSelectedSequencesAsAlignmentFrom(currentAlignFrame, format,
126 * get sequences selected in alf and return their alignment in format 'format'
127 * either with or without suffix
132 * format of alignment file
134 * "true" to append /start-end string to each sequence ID
135 * @return selected sequences as flat file or empty string if there was no
138 public String getSelectedSequencesAsAlignmentFrom(AlignFrame alf,
139 String format, String suffix)
143 boolean seqlimits = suffix.equalsIgnoreCase("true");
144 if (alf.viewport.getSelectionGroup() != null)
146 String reply = new AppletFormatAdapter().formatSequences(format,
147 new Alignment(alf.viewport.getSelectionAsNewSequence()),
151 } catch (Exception ex)
153 ex.printStackTrace();
154 return "Error retrieving alignment in " + format + " format. ";
159 public String getAlignment(String format)
161 return getAlignmentFrom(getDefaultTargetFrame(), format, "true");
164 public String getAlignmentFrom(AlignFrame alf, String format)
166 return getAlignmentFrom(alf, format, "true");
169 public String getAlignment(String format, String suffix)
171 return getAlignmentFrom(getDefaultTargetFrame(), format, suffix);
174 public String getAlignmentFrom(AlignFrame alf, String format,
179 boolean seqlimits = suffix.equalsIgnoreCase("true");
181 String reply = new AppletFormatAdapter().formatSequences(format,
182 alf.viewport.getAlignment(), seqlimits);
184 } catch (Exception ex)
186 ex.printStackTrace();
187 return "Error retrieving alignment in " + format + " format. ";
191 public void loadAnnotation(String annotation)
193 loadAnnotationFrom(getDefaultTargetFrame(), annotation);
196 public void loadAnnotationFrom(AlignFrame alf, String annotation)
198 if (new AnnotationFile().readAnnotationFile(alf.getAlignViewport()
199 .getAlignment(), annotation, AppletFormatAdapter.PASTE))
201 alf.alignPanel.fontChanged();
202 alf.alignPanel.setScrollValues(0, 0);
206 alf.parseFeaturesFile(annotation, AppletFormatAdapter.PASTE);
210 public String getFeatures(String format)
212 return getFeaturesFrom(getDefaultTargetFrame(), format);
215 public String getFeaturesFrom(AlignFrame alf, String format)
217 return alf.outputFeatures(false, format);
220 public String getAnnotation()
222 return getAnnotationFrom(getDefaultTargetFrame());
225 public String getAnnotationFrom(AlignFrame alf)
227 return alf.outputAnnotations(false);
230 public AlignFrame newView()
232 return newViewFrom(getDefaultTargetFrame());
235 public AlignFrame newView(String name)
237 return newViewFrom(getDefaultTargetFrame(), name);
240 public AlignFrame newViewFrom(AlignFrame alf)
242 return alf.newView(null);
245 public AlignFrame newViewFrom(AlignFrame alf, String name)
247 return alf.newView(name);
253 * alignment file as a string
256 * @return null or new alignment frame
258 public AlignFrame loadAlignment(String text, String title)
262 String format = new IdentifyFile().Identify(text,
263 AppletFormatAdapter.PASTE);
266 al = new AppletFormatAdapter().readFile(text,
267 AppletFormatAdapter.PASTE, format);
268 if (al.getHeight() > 0)
270 return new AlignFrame(al, this, title, false);
272 } catch (java.io.IOException ex)
274 ex.printStackTrace();
279 // //////////////////////////////////////////////
280 // //////////////////////////////////////////////
282 static int lastFrameX = 200;
284 static int lastFrameY = 200;
286 boolean fileFound = true;
288 String file = "No file";
290 Button launcher = new Button("Start Jalview");
293 * The currentAlignFrame is static, it will change if and when the user
294 * selects a new window. Note that it will *never* point back to the embedded
295 * AlignFrame if the applet is started as embedded on the page and then
296 * afterwards a new view is created.
298 public static AlignFrame currentAlignFrame;
301 * This is the first frame to be displayed, and does not change. API calls
302 * will default to this instance if currentAlignFrame is null.
304 AlignFrame initialAlignFrame;
306 boolean embedded = false;
308 private boolean checkForJmol = true;
309 private boolean checkedForJmol = false; // ensure we don't check for jmol every time the app is re-inited
311 public boolean jmolAvailable = false;
313 public static boolean debug;
316 * init method for Jalview Applet
321 * turn on extra applet debugging
323 String dbg = getParameter("debug");
326 debug = dbg.toLowerCase().equals("true");
329 * if true disable the check for jmol
331 String chkforJmol = getParameter("nojmol");
332 if (chkforJmol != null)
334 checkForJmol = !chkforJmol.equals("true");
337 * get the separator parameter if present
339 String sep = getParameter("separator");
342 if (sep.length() > 0)
347 System.err.println("Separator set to '" + separator + "'");
353 "Invalid separator parameter - must be non-zero length");
359 String param = getParameter("RGB");
365 r = Integer.parseInt(param.substring(0, 2), 16);
366 g = Integer.parseInt(param.substring(2, 4), 16);
367 b = Integer.parseInt(param.substring(4, 6), 16);
368 } catch (Exception ex)
376 param = getParameter("label");
379 launcher.setLabel(param);
382 this.setBackground(new Color(r, g, b));
384 file = getParameter("file");
388 // Maybe the sequences are added as parameters
389 StringBuffer data = new StringBuffer("PASTE");
391 while ((file = getParameter("sequence" + i)) != null)
393 data.append(file.toString() + "\n");
396 if (data.length() > 5)
398 file = data.toString();
402 final JalviewLite applet = this;
403 if (getParameter("embedded") != null
404 && getParameter("embedded").equalsIgnoreCase("true"))
406 // Launch as embedded applet in page
408 LoadingThread loader = new LoadingThread(file, applet);
411 else if (file != null)
413 if (getParameter("showbutton") == null
414 || !getParameter("showbutton").equalsIgnoreCase("false"))
416 // Add the JalviewLite 'Button' to the page
418 launcher.addActionListener(new java.awt.event.ActionListener()
420 public void actionPerformed(ActionEvent e)
422 LoadingThread loader = new LoadingThread(file, applet);
429 // Open jalviewLite immediately.
430 LoadingThread loader = new LoadingThread(file, applet);
436 // jalview initialisation with no alignment. loadAlignment() method can
437 // still be called to open new alignments.
444 * Initialises and displays a new java.awt.Frame
447 * java.awt.Frame to be displayed
453 * height of new frame
455 public static void addFrame(final Frame frame, String title, int width,
458 frame.setLocation(lastFrameX, lastFrameY);
461 frame.setSize(width, height);
462 frame.setTitle(title);
463 frame.addWindowListener(new WindowAdapter()
465 public void windowClosing(WindowEvent e)
467 if (frame instanceof AlignFrame)
469 ((AlignFrame) frame).closeMenuItem_actionPerformed();
471 if (currentAlignFrame == frame)
473 currentAlignFrame = null;
477 if (frame instanceof EmbmenuFrame)
479 ((EmbmenuFrame) frame).destroyMenus();
481 frame.setMenuBar(null);
485 public void windowActivated(WindowEvent e)
487 if (frame instanceof AlignFrame)
489 currentAlignFrame = (AlignFrame) frame;
492 System.err.println("Activated window " + frame);
496 super.windowActivated(e);
499 * Probably not necessary to do this - see TODO above. (non-Javadoc)
501 * @see java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent)
503 * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
504 * frame) { currentAlignFrame = null; if (debug) {
505 * System.err.println("Deactivated window "+frame); } }
506 * super.windowDeactivated(e); }
509 frame.setVisible(true);
513 * This paints the background surrounding the "Launch Jalview button" <br>
515 * If file given in parameter not found, displays error message
520 public void paint(Graphics g)
524 g.setColor(new Color(200, 200, 200));
525 g.setColor(Color.cyan);
526 g.fillRect(0, 0, getSize().width, getSize().height);
527 g.setColor(Color.red);
528 g.drawString("Jalview can't open file", 5, 15);
529 g.drawString("\"" + file + "\"", 5, 30);
533 g.setColor(Color.black);
534 g.setFont(new Font("Arial", Font.BOLD, 24));
535 g.drawString("Jalview Applet", 50, this.getSize().height / 2 - 30);
536 g.drawString("Loading Data...", 50, this.getSize().height / 2);
540 class LoadJmolThread extends Thread
542 private boolean running=false;
546 if (running || checkedForJmol) {
554 if (!System.getProperty("java.version").startsWith("1.1"))
556 Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
557 jmolAvailable = true;
562 .println("Jmol not available - Using MCview for structures");
564 } catch (java.lang.ClassNotFoundException ex)
570 jmolAvailable = false;
574 .println("Skipping Jmol check. Will use MCView (probably)");
581 public boolean notFinished()
583 return running || !checkedForJmol;
587 class LoadingThread extends Thread
590 * State variable: File source
595 * State variable: protocol for access to file source
600 * State variable: format of file source
605 private void dbgMsg(String msg)
609 System.err.println(msg);
614 * update the protocol state variable for accessing the datasource located
618 * @return possibly updated datasource string
620 public String setProtocolState(String file)
622 if (file.startsWith("PASTE"))
624 file = file.substring(5);
625 protocol = AppletFormatAdapter.PASTE;
627 else if (inArchive(file))
629 protocol = AppletFormatAdapter.CLASSLOADER;
633 file = addProtocol(file);
634 protocol = AppletFormatAdapter.URL;
636 dbgMsg("Protocol identified as '" + protocol + "'");
640 public LoadingThread(String _file, JalviewLite _applet)
648 LoadJmolThread jmolchecker = new LoadJmolThread();
650 while (jmolchecker.notFinished())
652 // wait around until the Jmol check is complete.
653 try { Thread.sleep(2); } catch (Exception e) {};
658 private void startLoading()
660 AlignFrame newAlignFrame;
661 dbgMsg("Loading thread started with:\n>>file\n" + _file + ">>endfile");
662 file = setProtocolState(_file);
664 format = new jalview.io.IdentifyFile().Identify(file, protocol);
665 dbgMsg("File identified as '" + format + "'");
666 dbgMsg("Loading started.");
670 al = new AppletFormatAdapter().readFile(file, protocol, format);
671 } catch (java.io.IOException ex)
673 dbgMsg("File load exception.");
674 ex.printStackTrace();
677 FileParse fp = new FileParse(file, protocol);
679 dbgMsg(">>>Dumping contents of '"+file+"' "+"("+protocol+")");
680 while ((ln=fp.nextLine())!=null) {
683 dbgMsg(">>>Dump finished.");
684 } catch (Exception e)
686 System.err.println("Exception when trying to dump the content of the file parameter.");
691 if ((al != null) && (al.getHeight() > 0))
693 dbgMsg("Successfully loaded file.");
694 newAlignFrame = new AlignFrame(al, applet, file, embedded);
695 if (initialAlignFrame==null)
697 initialAlignFrame = newAlignFrame;
700 currentAlignFrame = newAlignFrame;
702 if (protocol == jalview.io.AppletFormatAdapter.PASTE)
704 newAlignFrame.setTitle("Sequences from " + getDocumentBase());
707 newAlignFrame.statusBar.setText("Successfully loaded file "
710 String treeFile = applet.getParameter("tree");
711 if (treeFile == null)
713 treeFile = applet.getParameter("treeFile");
716 if (treeFile != null)
720 treeFile = setProtocolState(treeFile);
722 * if (inArchive(treeFile)) { protocol =
723 * AppletFormatAdapter.CLASSLOADER; } else { protocol =
724 * AppletFormatAdapter.URL; treeFile = addProtocol(treeFile); }
726 jalview.io.NewickFile fin = new jalview.io.NewickFile(treeFile,
731 if (fin.getTree() != null)
733 newAlignFrame.loadTree(fin, treeFile);
734 dbgMsg("Successfuly imported tree.");
738 dbgMsg("Tree parameter did not resolve to a valid tree.");
740 } catch (Exception ex)
742 ex.printStackTrace();
746 String param = getParameter("features");
749 param = setProtocolState(param);
751 newAlignFrame.parseFeaturesFile(param, protocol);
754 param = getParameter("showFeatureSettings");
755 if (param != null && param.equalsIgnoreCase("true"))
757 newAlignFrame.viewport.showSequenceFeatures(true);
758 new FeatureSettings(newAlignFrame.alignPanel);
761 param = getParameter("annotations");
764 param = setProtocolState(param);
766 if (new AnnotationFile().readAnnotationFile(
767 newAlignFrame.viewport.getAlignment(), param,
770 newAlignFrame.alignPanel.fontChanged();
771 newAlignFrame.alignPanel.setScrollValues(0, 0);
776 .println("Annotations were not added from annotation file '"
782 param = getParameter("jnetfile");
787 param = setProtocolState(param);
788 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
790 JnetAnnotationMaker.add_annotation(predictions,
791 newAlignFrame.viewport.getAlignment(), 0, false); // false==do
799 newAlignFrame.alignPanel.fontChanged();
800 newAlignFrame.alignPanel.setScrollValues(0, 0);
801 } catch (Exception ex)
803 ex.printStackTrace();
808 * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
811 * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
813 * <param name="PDBfile3" value="1q0o Q45135_9MICO">
816 int pdbFileCount = 0;
819 if (pdbFileCount > 0)
820 param = getParameter("PDBFILE" + pdbFileCount);
822 param = getParameter("PDBFILE");
826 PDBEntry pdb = new PDBEntry();
829 SequenceI[] seqs = null;
830 String[] chains = null;
832 StringTokenizer st = new StringTokenizer(param, " ");
834 if (st.countTokens() < 2)
836 String sequence = applet.getParameter("PDBSEQ");
837 if (sequence != null)
838 seqs = new SequenceI[]
839 { (Sequence) newAlignFrame.getAlignViewport()
840 .getAlignment().findName(sequence) };
845 param = st.nextToken();
846 Vector tmp = new Vector();
847 Vector tmp2 = new Vector();
849 while (st.hasMoreTokens())
851 seqstring = st.nextToken();
852 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
853 if (st2.countTokens() > 1)
856 tmp2.addElement(st2.nextToken());
857 seqstring = st2.nextToken();
859 tmp.addElement((Sequence) newAlignFrame
860 .getAlignViewport().getAlignment().findName(
864 seqs = new SequenceI[tmp.size()];
866 if (tmp2.size() == tmp.size())
868 chains = new String[tmp2.size()];
869 tmp2.copyInto(chains);
872 param = setProtocolState(param);
874 if (// !jmolAvailable
876 protocol == AppletFormatAdapter.CLASSLOADER)
878 // TODO: verify this Re:
879 // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
880 // This exception preserves the current behaviour where, even if
881 // the local pdb file was identified in the class loader
882 protocol = AppletFormatAdapter.URL; // this is probably NOT
884 param = addProtocol(param); //
891 for (int i = 0; i < seqs.length; i++)
895 ((Sequence) seqs[i]).addPDBId(pdb);
899 if (JalviewLite.debug)
901 // this may not really be a problem but we give a warning
904 .println("Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
912 new jalview.appletgui.AppletJmol(pdb, seqs, chains,
913 newAlignFrame.alignPanel, protocol);
918 new MCview.AppletPDBViewer(pdb, seqs, chains,
919 newAlignFrame.alignPanel, protocol);
924 } while (pdbFileCount < 10);
926 // ///////////////////////////
927 // modify display of features
929 // hide specific groups
930 param = getParameter("hidefeaturegroups");
933 applet.setFeatureGroupStateOn(newAlignFrame,param, false);
935 // show specific groups
936 param = getParameter("showfeaturegroups");
939 applet.setFeatureGroupStateOn(newAlignFrame,param, true);
951 * Discovers whether the given file is in the Applet Archive
957 boolean inArchive(String file)
959 // This might throw a security exception in certain browsers
960 // Netscape Communicator for instance.
963 boolean rtn = (getClass().getResourceAsStream("/" + file) != null);
966 System.err.println("Resource '" + file + "' was "
967 + (rtn ? "" : "not") + " located by classloader.");
970 } catch (Exception ex)
972 System.out.println("Exception checking resources: " + file + " "
978 String addProtocol(String file)
980 if (file.indexOf("://") == -1)
982 file = getCodeBase() + file;
985 System.err.println("Prepended codebase for resource: '" + file
995 * @return the default alignFrame acted on by the public applet methods. May
996 * return null with an error message on System.err indicating the
999 protected AlignFrame getDefaultTargetFrame()
1001 if (currentAlignFrame != null)
1003 return currentAlignFrame;
1005 if (initialAlignFrame != null)
1007 return initialAlignFrame;
1010 .println("Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
1015 * separator used for separatorList
1017 protected String separator = "|"; // this is a safe(ish) separator - tabs
1019 // don't work for firefox
1022 * parse the string into a list
1025 * @return elements separated by separator
1027 public String[] separatorListToArray(String list)
1029 int seplen = separator.length();
1030 if (list == null || list.equals(""))
1032 java.util.Vector jv = new Vector();
1034 while ((pos = list.indexOf(separator, cp)) > cp)
1036 jv.addElement(list.substring(cp, pos));
1039 if (cp < list.length())
1041 jv.addElement(list.substring(cp));
1045 String[] v = new String[jv.size()];
1046 for (int i = 0; i < v.length; i++)
1048 v[i] = (String) jv.elementAt(i);
1050 jv.removeAllElements();
1053 System.err.println("Array from '" + separator
1054 + "' separated List:\n" + v.length);
1055 for (int i = 0; i < v.length; i++)
1057 System.err.println("item " + i + " '" + v[i] + "'");
1064 System.err.println("Empty Array from '" + separator
1065 + "' separated List");
1071 * concatenate the list with separator
1074 * @return concatenated string
1076 public String arrayToSeparatorList(String[] list)
1078 StringBuffer v = new StringBuffer();
1081 for (int i = 0, iSize = list.length - 1; i < iSize; i++)
1083 if (list[i] != null)
1087 v.append(separator);
1089 if (list[list.length - 1] != null)
1091 v.append(list[list.length - 1]);
1095 System.err.println("Returning '" + separator
1096 + "' separated List:\n");
1097 System.err.println(v);
1099 return v.toString();
1103 System.err.println("Returning empty '" + separator
1104 + "' separated List\n");
1111 * @see jalview.appletgui.AlignFrame#getFeatureGroups()
1113 public String getFeatureGroups()
1115 String lst = arrayToSeparatorList(getDefaultTargetFrame()
1116 .getFeatureGroups());
1122 * alignframe to get feature groups on
1124 * @see jalview.appletgui.AlignFrame#getFeatureGroups()
1126 public String getFeatureGroupsOn(AlignFrame alf)
1128 String lst = arrayToSeparatorList(alf.getFeatureGroups());
1135 * @see jalview.appletgui.AlignFrame#getFeatureGroupsOfState(boolean)
1137 public String getFeatureGroupsOfState(boolean visible)
1139 return arrayToSeparatorList(getDefaultTargetFrame()
1140 .getFeatureGroupsOfState(visible));
1145 * align frame to get groups of state visible
1148 * @see jalview.appletgui.AlignFrame#getFeatureGroupsOfState(boolean)
1150 public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
1152 return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
1157 * tab separated list of group names
1160 * @see jalview.appletgui.AlignFrame#setFeatureGroupState(java.lang.String[],
1163 public void setFeatureGroupStateOn(AlignFrame alf, String groups,
1166 boolean st = state;// !(state==null || state.equals("") ||
1167 // state.toLowerCase().equals("false"));
1168 alf.setFeatureGroupState(separatorListToArray(groups), st);
1171 public void setFeatureGroupState(String groups, boolean state)
1173 setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
1177 * List separator string
1179 * @return the separator
1181 public String getSeparator()
1187 * List separator string
1190 * the separator to set
1192 public void setSeparator(String separator)
1194 this.separator = separator;