2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.5)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
5 * This file is part of Jalview.
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.
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.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
23 import java.awt.event.*;
24 import java.io.BufferedReader;
25 import java.io.InputStreamReader;
28 import jalview.appletgui.*;
29 import jalview.datamodel.*;
33 * Jalview Applet. Runs in Java 1.18 runtime
38 public class JalviewLite extends Applet
41 // /////////////////////////////////////////
42 // The following public methods maybe called
43 // externally, eg via javascript in HTML page
45 * @return String list of selected sequence IDs, each terminated by "¬"
48 public String getSelectedSequences()
50 return getSelectedSequencesFrom(getDefaultTargetFrame());
55 * separator string or null for default
56 * @return String list of selected sequence IDs, each terminated by sep or
59 public String getSelectedSequences(String sep)
61 return getSelectedSequencesFrom(getDefaultTargetFrame(), sep);
66 * alignframe containing selection
67 * @return String list of selected sequence IDs, each terminated by "¬"
70 public String getSelectedSequencesFrom(AlignFrame alf)
72 return getSelectedSequencesFrom(alf, "¬");
76 * get list of selected sequence IDs separated by given separator
79 * window containing selection
81 * separator string to use - default is "¬"
82 * @return String list of selected sequence IDs, each terminated by the given
85 public String getSelectedSequencesFrom(AlignFrame alf, String sep)
87 StringBuffer result = new StringBuffer("");
88 if (sep == null || sep.length() == 0)
92 if (alf.viewport.getSelectionGroup() != null)
94 SequenceI[] seqs = alf.viewport.getSelectionGroup()
95 .getSequencesInOrder(alf.viewport.getAlignment());
97 for (int i = 0; i < seqs.length; i++)
99 result.append(seqs[i].getName());
104 return result.toString();
108 * get sequences selected in current alignFrame and return their alignment in
109 * format 'format' either with or without suffix
112 * - where selection is
114 * - format of alignment file
116 * - "true" to append /start-end string to each sequence ID
117 * @return selected sequences as flat file or empty string if there was no
120 public String getSelectedSequencesAsAlignment(String format, String suffix)
122 return getSelectedSequencesAsAlignmentFrom(currentAlignFrame, format,
127 * get sequences selected in alf and return their alignment in format 'format'
128 * either with or without suffix
131 * - where selection is
133 * - format of alignment file
135 * - "true" to append /start-end string to each sequence ID
136 * @return selected sequences as flat file or empty string if there was no
139 public String getSelectedSequencesAsAlignmentFrom(AlignFrame alf,
140 String format, String suffix)
144 boolean seqlimits = suffix.equalsIgnoreCase("true");
145 if (alf.viewport.getSelectionGroup() != null)
147 String reply = new AppletFormatAdapter().formatSequences(format,
148 new Alignment(alf.viewport.getSelectionAsNewSequence()),
152 } catch (Exception ex)
154 ex.printStackTrace();
155 return "Error retrieving alignment in " + format + " format. ";
160 public String getAlignment(String format)
162 return getAlignmentFrom(getDefaultTargetFrame(), format, "true");
165 public String getAlignmentFrom(AlignFrame alf, String format)
167 return getAlignmentFrom(alf, format, "true");
170 public String getAlignment(String format, String suffix)
172 return getAlignmentFrom(getDefaultTargetFrame(), format, suffix);
175 public String getAlignmentFrom(AlignFrame alf, String format,
180 boolean seqlimits = suffix.equalsIgnoreCase("true");
182 String reply = new AppletFormatAdapter().formatSequences(format,
183 alf.viewport.getAlignment(), seqlimits);
185 } catch (Exception ex)
187 ex.printStackTrace();
188 return "Error retrieving alignment in " + format + " format. ";
192 public void loadAnnotation(String annotation)
194 loadAnnotationFrom(getDefaultTargetFrame(), annotation);
197 public void loadAnnotationFrom(AlignFrame alf, String annotation)
199 if (new AnnotationFile().readAnnotationFile(alf.getAlignViewport()
200 .getAlignment(), annotation, AppletFormatAdapter.PASTE))
202 alf.alignPanel.fontChanged();
203 alf.alignPanel.setScrollValues(0, 0);
207 alf.parseFeaturesFile(annotation, AppletFormatAdapter.PASTE);
211 public String getFeatures(String format)
213 return getFeaturesFrom(getDefaultTargetFrame(), format);
216 public String getFeaturesFrom(AlignFrame alf, String format)
218 return alf.outputFeatures(false, format);
221 public String getAnnotation()
223 return getAnnotationFrom(getDefaultTargetFrame());
226 public String getAnnotationFrom(AlignFrame alf)
228 return alf.outputAnnotations(false);
231 public AlignFrame newView()
233 return newViewFrom(getDefaultTargetFrame());
236 public AlignFrame newView(String name)
238 return newViewFrom(getDefaultTargetFrame(), name);
241 public AlignFrame newViewFrom(AlignFrame alf)
243 return alf.newView(null);
246 public AlignFrame newViewFrom(AlignFrame alf, String name)
248 return alf.newView(name);
254 * alignment file as a string
257 * @return null or new alignment frame
259 public AlignFrame loadAlignment(String text, String title)
263 String format = new IdentifyFile().Identify(text,
264 AppletFormatAdapter.PASTE);
267 al = new AppletFormatAdapter().readFile(text,
268 AppletFormatAdapter.PASTE, format);
269 if (al.getHeight() > 0)
271 return new AlignFrame(al, this, title, false);
273 } catch (java.io.IOException ex)
275 ex.printStackTrace();
280 // //////////////////////////////////////////////
281 // //////////////////////////////////////////////
283 static int lastFrameX = 200;
285 static int lastFrameY = 200;
287 boolean fileFound = true;
289 String file = "No file";
291 Button launcher = new Button("Start Jalview");
294 * The currentAlignFrame is static, it will change if and when the user
295 * selects a new window. Note that it will *never* point back to the embedded
296 * AlignFrame if the applet is started as embedded on the page and then
297 * afterwards a new view is created.
299 public static AlignFrame currentAlignFrame = null;
302 * This is the first frame to be displayed, and does not change. API calls
303 * will default to this instance if currentAlignFrame is null.
305 AlignFrame initialAlignFrame = null;
307 boolean embedded = false;
309 private boolean checkForJmol = true;
311 private boolean checkedForJmol = false; // ensure we don't check for jmol
313 // every time the app is re-inited
315 public boolean jmolAvailable = false;
317 public static boolean debug = false;
319 static String builddate = null, version = null;
321 private static void initBuildDetails()
323 if (builddate == null)
325 builddate = "unknown";
327 java.net.URL url = JalviewLite.class
328 .getResource("/.build_properties");
333 BufferedReader reader = new BufferedReader(new InputStreamReader(
336 while ((line = reader.readLine()) != null)
338 if (line.indexOf("VERSION") > -1)
340 version = line.substring(line.indexOf("=") + 1);
342 if (line.indexOf("BUILD_DATE") > -1)
344 builddate = line.substring(line.indexOf("=") + 1);
347 } catch (Exception ex)
349 ex.printStackTrace();
355 public static String getBuildDate()
361 public static String getVersion()
368 * init method for Jalview Applet
374 * turn on extra applet debugging
376 String dbg = getParameter("debug");
379 debug = dbg.toLowerCase().equals("true");
384 System.err.println("JalviewLite Version " + getVersion());
385 System.err.println("Build Date : " + getBuildDate());
389 * if true disable the check for jmol
391 String chkforJmol = getParameter("nojmol");
392 if (chkforJmol != null)
394 checkForJmol = !chkforJmol.equals("true");
397 * get the separator parameter if present
399 String sep = getParameter("separator");
402 if (sep.length() > 0)
407 System.err.println("Separator set to '" + separator + "'");
413 "Invalid separator parameter - must be non-zero length");
419 String param = getParameter("RGB");
425 r = Integer.parseInt(param.substring(0, 2), 16);
426 g = Integer.parseInt(param.substring(2, 4), 16);
427 b = Integer.parseInt(param.substring(4, 6), 16);
428 } catch (Exception ex)
436 param = getParameter("label");
439 launcher.setLabel(param);
442 this.setBackground(new Color(r, g, b));
444 file = getParameter("file");
448 // Maybe the sequences are added as parameters
449 StringBuffer data = new StringBuffer("PASTE");
451 while ((file = getParameter("sequence" + i)) != null)
453 data.append(file.toString() + "\n");
456 if (data.length() > 5)
458 file = data.toString();
462 final JalviewLite applet = this;
463 if (getParameter("embedded") != null
464 && getParameter("embedded").equalsIgnoreCase("true"))
466 // Launch as embedded applet in page
468 LoadingThread loader = new LoadingThread(file, applet);
471 else if (file != null)
473 if (getParameter("showbutton") == null
474 || !getParameter("showbutton").equalsIgnoreCase("false"))
476 // Add the JalviewLite 'Button' to the page
478 launcher.addActionListener(new java.awt.event.ActionListener()
480 public void actionPerformed(ActionEvent e)
482 LoadingThread loader = new LoadingThread(file, applet);
489 // Open jalviewLite immediately.
490 LoadingThread loader = new LoadingThread(file, applet);
496 // jalview initialisation with no alignment. loadAlignment() method can
497 // still be called to open new alignments.
504 * Initialises and displays a new java.awt.Frame
507 * java.awt.Frame to be displayed
513 * height of new frame
515 public static void addFrame(final Frame frame, String title, int width,
518 frame.setLocation(lastFrameX, lastFrameY);
521 frame.setSize(width, height);
522 frame.setTitle(title);
523 frame.addWindowListener(new WindowAdapter()
525 public void windowClosing(WindowEvent e)
527 if (frame instanceof AlignFrame)
529 ((AlignFrame) frame).closeMenuItem_actionPerformed();
531 if (currentAlignFrame == frame)
533 currentAlignFrame = null;
537 if (frame instanceof EmbmenuFrame)
539 ((EmbmenuFrame) frame).destroyMenus();
541 frame.setMenuBar(null);
545 public void windowActivated(WindowEvent e)
547 if (frame instanceof AlignFrame)
549 currentAlignFrame = (AlignFrame) frame;
552 System.err.println("Activated window " + frame);
556 super.windowActivated(e);
559 * Probably not necessary to do this - see TODO above. (non-Javadoc)
562 * java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent
565 * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
566 * frame) { currentAlignFrame = null; if (debug) {
567 * System.err.println("Deactivated window "+frame); } }
568 * super.windowDeactivated(e); }
571 frame.setVisible(true);
575 * This paints the background surrounding the "Launch Jalview button" <br>
577 * If file given in parameter not found, displays error message
582 public void paint(Graphics g)
586 g.setColor(new Color(200, 200, 200));
587 g.setColor(Color.cyan);
588 g.fillRect(0, 0, getSize().width, getSize().height);
589 g.setColor(Color.red);
590 g.drawString("Jalview can't open file", 5, 15);
591 g.drawString("\"" + file + "\"", 5, 30);
595 g.setColor(Color.black);
596 g.setFont(new Font("Arial", Font.BOLD, 24));
597 g.drawString("Jalview Applet", 50, this.getSize().height / 2 - 30);
598 g.drawString("Loading Data...", 50, this.getSize().height / 2);
602 class LoadJmolThread extends Thread
604 private boolean running = false;
608 if (running || checkedForJmol)
617 if (!System.getProperty("java.version").startsWith("1.1"))
619 Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
620 jmolAvailable = true;
625 .println("Jmol not available - Using MCview for structures");
627 } catch (java.lang.ClassNotFoundException ex)
633 jmolAvailable = false;
637 .println("Skipping Jmol check. Will use MCView (probably)");
640 checkedForJmol = true;
644 public boolean notFinished()
646 return running || !checkedForJmol;
650 class LoadingThread extends Thread
653 * State variable: File source
658 * State variable: protocol for access to file source
663 * State variable: format of file source
671 private void dbgMsg(String msg)
675 System.err.println(msg);
680 * update the protocol state variable for accessing the datasource located
684 * @return possibly updated datasource string
686 public String setProtocolState(String file)
688 if (file.startsWith("PASTE"))
690 file = file.substring(5);
691 protocol = AppletFormatAdapter.PASTE;
693 else if (inArchive(file))
695 protocol = AppletFormatAdapter.CLASSLOADER;
699 file = addProtocol(file);
700 protocol = AppletFormatAdapter.URL;
702 dbgMsg("Protocol identified as '" + protocol + "'");
706 public LoadingThread(String _file, JalviewLite _applet)
714 LoadJmolThread jmolchecker = new LoadJmolThread();
716 while (jmolchecker.notFinished())
718 // wait around until the Jmol check is complete.
722 } catch (Exception e)
730 private void startLoading()
732 AlignFrame newAlignFrame;
733 dbgMsg("Loading thread started with:\n>>file\n" + _file + ">>endfile");
734 file = setProtocolState(_file);
736 format = new jalview.io.IdentifyFile().Identify(file, protocol);
737 dbgMsg("File identified as '" + format + "'");
738 dbgMsg("Loading started.");
742 al = new AppletFormatAdapter().readFile(file, protocol, format);
743 } catch (java.io.IOException ex)
745 dbgMsg("File load exception.");
746 ex.printStackTrace();
751 FileParse fp = new FileParse(file, protocol);
753 dbgMsg(">>>Dumping contents of '" + file + "' " + "("
755 while ((ln = fp.nextLine()) != null)
759 dbgMsg(">>>Dump finished.");
760 } catch (Exception e)
763 .println("Exception when trying to dump the content of the file parameter.");
768 if ((al != null) && (al.getHeight() > 0))
770 dbgMsg("Successfully loaded file.");
771 newAlignFrame = new AlignFrame(al, applet, file, embedded);
772 if (initialAlignFrame == null)
774 initialAlignFrame = newAlignFrame;
777 currentAlignFrame = newAlignFrame;
779 if (protocol == jalview.io.AppletFormatAdapter.PASTE)
781 newAlignFrame.setTitle("Sequences from " + getDocumentBase());
784 newAlignFrame.statusBar.setText("Successfully loaded file " + file);
786 String treeFile = applet.getParameter("tree");
787 if (treeFile == null)
789 treeFile = applet.getParameter("treeFile");
792 if (treeFile != null)
796 treeFile = setProtocolState(treeFile);
798 * if (inArchive(treeFile)) { protocol =
799 * AppletFormatAdapter.CLASSLOADER; } else { protocol =
800 * AppletFormatAdapter.URL; treeFile = addProtocol(treeFile); }
802 jalview.io.NewickFile fin = new jalview.io.NewickFile(treeFile,
807 if (fin.getTree() != null)
809 newAlignFrame.loadTree(fin, treeFile);
810 dbgMsg("Successfuly imported tree.");
814 dbgMsg("Tree parameter did not resolve to a valid tree.");
816 } catch (Exception ex)
818 ex.printStackTrace();
822 String param = getParameter("features");
825 param = setProtocolState(param);
827 newAlignFrame.parseFeaturesFile(param, protocol);
830 param = getParameter("showFeatureSettings");
831 if (param != null && param.equalsIgnoreCase("true"))
833 newAlignFrame.viewport.showSequenceFeatures(true);
834 new FeatureSettings(newAlignFrame.alignPanel);
837 param = getParameter("annotations");
840 param = setProtocolState(param);
842 if (new AnnotationFile().readAnnotationFile(
843 newAlignFrame.viewport.getAlignment(), param, protocol))
845 newAlignFrame.alignPanel.fontChanged();
846 newAlignFrame.alignPanel.setScrollValues(0, 0);
851 .println("Annotations were not added from annotation file '"
857 param = getParameter("jnetfile");
862 param = setProtocolState(param);
863 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
865 JnetAnnotationMaker.add_annotation(predictions,
866 newAlignFrame.viewport.getAlignment(), 0, false); // false==do
874 newAlignFrame.alignPanel.fontChanged();
875 newAlignFrame.alignPanel.setScrollValues(0, 0);
876 } catch (Exception ex)
878 ex.printStackTrace();
883 * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
886 * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
888 * <param name="PDBfile3" value="1q0o Q45135_9MICO">
891 int pdbFileCount = 0;
894 if (pdbFileCount > 0)
895 param = getParameter("PDBFILE" + pdbFileCount);
897 param = getParameter("PDBFILE");
901 PDBEntry pdb = new PDBEntry();
904 SequenceI[] seqs = null;
905 String[] chains = null;
907 StringTokenizer st = new StringTokenizer(param, " ");
909 if (st.countTokens() < 2)
911 String sequence = applet.getParameter("PDBSEQ");
912 if (sequence != null)
913 seqs = new SequenceI[]
914 { (Sequence) newAlignFrame.getAlignViewport()
915 .getAlignment().findName(sequence) };
920 param = st.nextToken();
921 Vector tmp = new Vector();
922 Vector tmp2 = new Vector();
924 while (st.hasMoreTokens())
926 seqstring = st.nextToken();
927 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
928 if (st2.countTokens() > 1)
931 tmp2.addElement(st2.nextToken());
932 seqstring = st2.nextToken();
934 tmp.addElement((Sequence) newAlignFrame.getAlignViewport()
935 .getAlignment().findName(seqstring));
938 seqs = new SequenceI[tmp.size()];
940 if (tmp2.size() == tmp.size())
942 chains = new String[tmp2.size()];
943 tmp2.copyInto(chains);
946 param = setProtocolState(param);
948 if (// !jmolAvailable
950 protocol == AppletFormatAdapter.CLASSLOADER)
952 // TODO: verify this Re:
953 // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
954 // This exception preserves the current behaviour where, even if
955 // the local pdb file was identified in the class loader
956 protocol = AppletFormatAdapter.URL; // this is probably NOT
958 param = addProtocol(param); //
965 for (int i = 0; i < seqs.length; i++)
969 ((Sequence) seqs[i]).addPDBId(pdb);
973 if (JalviewLite.debug)
975 // this may not really be a problem but we give a warning
978 .println("Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
986 new jalview.appletgui.AppletJmol(pdb, seqs, chains,
987 newAlignFrame.alignPanel, protocol);
992 new MCview.AppletPDBViewer(pdb, seqs, chains,
993 newAlignFrame.alignPanel, protocol);
998 } while (pdbFileCount < 10);
1000 // ///////////////////////////
1001 // modify display of features
1003 // hide specific groups
1004 param = getParameter("hidefeaturegroups");
1007 applet.setFeatureGroupStateOn(newAlignFrame, param, false);
1009 // show specific groups
1010 param = getParameter("showfeaturegroups");
1013 applet.setFeatureGroupStateOn(newAlignFrame, param, true);
1025 * Discovers whether the given file is in the Applet Archive
1031 boolean inArchive(String file)
1033 // This might throw a security exception in certain browsers
1034 // Netscape Communicator for instance.
1037 boolean rtn = (getClass().getResourceAsStream("/" + file) != null);
1040 System.err.println("Resource '" + file + "' was "
1041 + (rtn ? "" : "not") + " located by classloader.");
1044 } catch (Exception ex)
1046 System.out.println("Exception checking resources: " + file + " "
1052 String addProtocol(String file)
1054 if (file.indexOf("://") == -1)
1056 file = getCodeBase() + file;
1059 System.err.println("Prepended codebase for resource: '" + file
1069 * @return the default alignFrame acted on by the public applet methods. May
1070 * return null with an error message on System.err indicating the
1073 protected AlignFrame getDefaultTargetFrame()
1075 if (currentAlignFrame != null)
1077 return currentAlignFrame;
1079 if (initialAlignFrame != null)
1081 return initialAlignFrame;
1084 .println("Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
1089 * separator used for separatorList
1091 protected String separator = "|"; // this is a safe(ish) separator - tabs
1093 // don't work for firefox
1096 * parse the string into a list
1099 * @return elements separated by separator
1101 public String[] separatorListToArray(String list)
1103 int seplen = separator.length();
1104 if (list == null || list.equals(""))
1106 java.util.Vector jv = new Vector();
1108 while ((pos = list.indexOf(separator, cp)) > cp)
1110 jv.addElement(list.substring(cp, pos));
1113 if (cp < list.length())
1115 jv.addElement(list.substring(cp));
1119 String[] v = new String[jv.size()];
1120 for (int i = 0; i < v.length; i++)
1122 v[i] = (String) jv.elementAt(i);
1124 jv.removeAllElements();
1127 System.err.println("Array from '" + separator
1128 + "' separated List:\n" + v.length);
1129 for (int i = 0; i < v.length; i++)
1131 System.err.println("item " + i + " '" + v[i] + "'");
1138 System.err.println("Empty Array from '" + separator
1139 + "' separated List");
1145 * concatenate the list with separator
1148 * @return concatenated string
1150 public String arrayToSeparatorList(String[] list)
1152 StringBuffer v = new StringBuffer();
1155 for (int i = 0, iSize = list.length - 1; i < iSize; i++)
1157 if (list[i] != null)
1161 v.append(separator);
1163 if (list[list.length - 1] != null)
1165 v.append(list[list.length - 1]);
1169 System.err.println("Returning '" + separator
1170 + "' separated List:\n");
1171 System.err.println(v);
1173 return v.toString();
1177 System.err.println("Returning empty '" + separator
1178 + "' separated List\n");
1185 * @see jalview.appletgui.AlignFrame#getFeatureGroups()
1187 public String getFeatureGroups()
1189 String lst = arrayToSeparatorList(getDefaultTargetFrame()
1190 .getFeatureGroups());
1196 * alignframe to get feature groups on
1198 * @see jalview.appletgui.AlignFrame#getFeatureGroups()
1200 public String getFeatureGroupsOn(AlignFrame alf)
1202 String lst = arrayToSeparatorList(alf.getFeatureGroups());
1209 * @see jalview.appletgui.AlignFrame#getFeatureGroupsOfState(boolean)
1211 public String getFeatureGroupsOfState(boolean visible)
1213 return arrayToSeparatorList(getDefaultTargetFrame()
1214 .getFeatureGroupsOfState(visible));
1219 * align frame to get groups of state visible
1222 * @see jalview.appletgui.AlignFrame#getFeatureGroupsOfState(boolean)
1224 public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
1226 return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
1231 * tab separated list of group names
1234 * @see jalview.appletgui.AlignFrame#setFeatureGroupState(java.lang.String[],
1237 public void setFeatureGroupStateOn(AlignFrame alf, String groups,
1240 boolean st = state;// !(state==null || state.equals("") ||
1241 // state.toLowerCase().equals("false"));
1242 alf.setFeatureGroupState(separatorListToArray(groups), st);
1245 public void setFeatureGroupState(String groups, boolean state)
1247 setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
1251 * List separator string
1253 * @return the separator
1255 public String getSeparator()
1261 * List separator string
1264 * the separator to set
1266 public void setSeparator(String separator)
1268 this.separator = separator;
1272 * get boolean value of applet parameter 'name' and return default if
1273 * parameter is not set
1278 * the value to return otherwise
1279 * @return true or false
1281 public boolean getDefaultParameter(String name, boolean def)
1284 if ((stn = getParameter(name)) == null)
1288 if (stn.toLowerCase().equals("true"))