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=null;
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=null;
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=false;
316 * init method for Jalview Applet
322 * turn on extra applet debugging
324 String dbg = getParameter("debug");
327 debug = dbg.toLowerCase().equals("true");
330 * if true disable the check for jmol
332 String chkforJmol = getParameter("nojmol");
333 if (chkforJmol != null)
335 checkForJmol = !chkforJmol.equals("true");
338 * get the separator parameter if present
340 String sep = getParameter("separator");
343 if (sep.length() > 0)
348 System.err.println("Separator set to '" + separator + "'");
354 "Invalid separator parameter - must be non-zero length");
360 String param = getParameter("RGB");
366 r = Integer.parseInt(param.substring(0, 2), 16);
367 g = Integer.parseInt(param.substring(2, 4), 16);
368 b = Integer.parseInt(param.substring(4, 6), 16);
369 } catch (Exception ex)
377 param = getParameter("label");
380 launcher.setLabel(param);
383 this.setBackground(new Color(r, g, b));
385 file = getParameter("file");
389 // Maybe the sequences are added as parameters
390 StringBuffer data = new StringBuffer("PASTE");
392 while ((file = getParameter("sequence" + i)) != null)
394 data.append(file.toString() + "\n");
397 if (data.length() > 5)
399 file = data.toString();
403 final JalviewLite applet = this;
404 if (getParameter("embedded") != null
405 && getParameter("embedded").equalsIgnoreCase("true"))
407 // Launch as embedded applet in page
409 LoadingThread loader = new LoadingThread(file, applet);
412 else if (file != null)
414 if (getParameter("showbutton") == null
415 || !getParameter("showbutton").equalsIgnoreCase("false"))
417 // Add the JalviewLite 'Button' to the page
419 launcher.addActionListener(new java.awt.event.ActionListener()
421 public void actionPerformed(ActionEvent e)
423 LoadingThread loader = new LoadingThread(file, applet);
430 // Open jalviewLite immediately.
431 LoadingThread loader = new LoadingThread(file, applet);
437 // jalview initialisation with no alignment. loadAlignment() method can
438 // still be called to open new alignments.
445 * Initialises and displays a new java.awt.Frame
448 * java.awt.Frame to be displayed
454 * height of new frame
456 public static void addFrame(final Frame frame, String title, int width,
459 frame.setLocation(lastFrameX, lastFrameY);
462 frame.setSize(width, height);
463 frame.setTitle(title);
464 frame.addWindowListener(new WindowAdapter()
466 public void windowClosing(WindowEvent e)
468 if (frame instanceof AlignFrame)
470 ((AlignFrame) frame).closeMenuItem_actionPerformed();
472 if (currentAlignFrame == frame)
474 currentAlignFrame = null;
478 if (frame instanceof EmbmenuFrame)
480 ((EmbmenuFrame) frame).destroyMenus();
482 frame.setMenuBar(null);
486 public void windowActivated(WindowEvent e)
488 if (frame instanceof AlignFrame)
490 currentAlignFrame = (AlignFrame) frame;
493 System.err.println("Activated window " + frame);
497 super.windowActivated(e);
500 * Probably not necessary to do this - see TODO above. (non-Javadoc)
502 * @see java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent)
504 * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
505 * frame) { currentAlignFrame = null; if (debug) {
506 * System.err.println("Deactivated window "+frame); } }
507 * super.windowDeactivated(e); }
510 frame.setVisible(true);
514 * This paints the background surrounding the "Launch Jalview button" <br>
516 * If file given in parameter not found, displays error message
521 public void paint(Graphics g)
525 g.setColor(new Color(200, 200, 200));
526 g.setColor(Color.cyan);
527 g.fillRect(0, 0, getSize().width, getSize().height);
528 g.setColor(Color.red);
529 g.drawString("Jalview can't open file", 5, 15);
530 g.drawString("\"" + file + "\"", 5, 30);
534 g.setColor(Color.black);
535 g.setFont(new Font("Arial", Font.BOLD, 24));
536 g.drawString("Jalview Applet", 50, this.getSize().height / 2 - 30);
537 g.drawString("Loading Data...", 50, this.getSize().height / 2);
541 class LoadJmolThread extends Thread
543 private boolean running=false;
547 if (running || checkedForJmol) {
555 if (!System.getProperty("java.version").startsWith("1.1"))
557 Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
558 jmolAvailable = true;
563 .println("Jmol not available - Using MCview for structures");
565 } catch (java.lang.ClassNotFoundException ex)
571 jmolAvailable = false;
575 .println("Skipping Jmol check. Will use MCView (probably)");
582 public boolean notFinished()
584 return running || !checkedForJmol;
588 class LoadingThread extends Thread
591 * State variable: File source
596 * State variable: protocol for access to file source
601 * State variable: format of file source
606 private void dbgMsg(String msg)
610 System.err.println(msg);
615 * update the protocol state variable for accessing the datasource located
619 * @return possibly updated datasource string
621 public String setProtocolState(String file)
623 if (file.startsWith("PASTE"))
625 file = file.substring(5);
626 protocol = AppletFormatAdapter.PASTE;
628 else if (inArchive(file))
630 protocol = AppletFormatAdapter.CLASSLOADER;
634 file = addProtocol(file);
635 protocol = AppletFormatAdapter.URL;
637 dbgMsg("Protocol identified as '" + protocol + "'");
641 public LoadingThread(String _file, JalviewLite _applet)
649 LoadJmolThread jmolchecker = new LoadJmolThread();
651 while (jmolchecker.notFinished())
653 // wait around until the Jmol check is complete.
654 try { Thread.sleep(2); } catch (Exception e) {};
659 private void startLoading()
661 AlignFrame newAlignFrame;
662 dbgMsg("Loading thread started with:\n>>file\n" + _file + ">>endfile");
663 file = setProtocolState(_file);
665 format = new jalview.io.IdentifyFile().Identify(file, protocol);
666 dbgMsg("File identified as '" + format + "'");
667 dbgMsg("Loading started.");
671 al = new AppletFormatAdapter().readFile(file, protocol, format);
672 } catch (java.io.IOException ex)
674 dbgMsg("File load exception.");
675 ex.printStackTrace();
678 FileParse fp = new FileParse(file, protocol);
680 dbgMsg(">>>Dumping contents of '"+file+"' "+"("+protocol+")");
681 while ((ln=fp.nextLine())!=null) {
684 dbgMsg(">>>Dump finished.");
685 } catch (Exception e)
687 System.err.println("Exception when trying to dump the content of the file parameter.");
692 if ((al != null) && (al.getHeight() > 0))
694 dbgMsg("Successfully loaded file.");
695 newAlignFrame = new AlignFrame(al, applet, file, embedded);
696 if (initialAlignFrame==null)
698 initialAlignFrame = newAlignFrame;
701 currentAlignFrame = newAlignFrame;
703 if (protocol == jalview.io.AppletFormatAdapter.PASTE)
705 newAlignFrame.setTitle("Sequences from " + getDocumentBase());
708 newAlignFrame.statusBar.setText("Successfully loaded file "
711 String treeFile = applet.getParameter("tree");
712 if (treeFile == null)
714 treeFile = applet.getParameter("treeFile");
717 if (treeFile != null)
721 treeFile = setProtocolState(treeFile);
723 * if (inArchive(treeFile)) { protocol =
724 * AppletFormatAdapter.CLASSLOADER; } else { protocol =
725 * AppletFormatAdapter.URL; treeFile = addProtocol(treeFile); }
727 jalview.io.NewickFile fin = new jalview.io.NewickFile(treeFile,
732 if (fin.getTree() != null)
734 newAlignFrame.loadTree(fin, treeFile);
735 dbgMsg("Successfuly imported tree.");
739 dbgMsg("Tree parameter did not resolve to a valid tree.");
741 } catch (Exception ex)
743 ex.printStackTrace();
747 String param = getParameter("features");
750 param = setProtocolState(param);
752 newAlignFrame.parseFeaturesFile(param, protocol);
755 param = getParameter("showFeatureSettings");
756 if (param != null && param.equalsIgnoreCase("true"))
758 newAlignFrame.viewport.showSequenceFeatures(true);
759 new FeatureSettings(newAlignFrame.alignPanel);
762 param = getParameter("annotations");
765 param = setProtocolState(param);
767 if (new AnnotationFile().readAnnotationFile(
768 newAlignFrame.viewport.getAlignment(), param,
771 newAlignFrame.alignPanel.fontChanged();
772 newAlignFrame.alignPanel.setScrollValues(0, 0);
777 .println("Annotations were not added from annotation file '"
783 param = getParameter("jnetfile");
788 param = setProtocolState(param);
789 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
791 JnetAnnotationMaker.add_annotation(predictions,
792 newAlignFrame.viewport.getAlignment(), 0, false); // false==do
800 newAlignFrame.alignPanel.fontChanged();
801 newAlignFrame.alignPanel.setScrollValues(0, 0);
802 } catch (Exception ex)
804 ex.printStackTrace();
809 * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
812 * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
814 * <param name="PDBfile3" value="1q0o Q45135_9MICO">
817 int pdbFileCount = 0;
820 if (pdbFileCount > 0)
821 param = getParameter("PDBFILE" + pdbFileCount);
823 param = getParameter("PDBFILE");
827 PDBEntry pdb = new PDBEntry();
830 SequenceI[] seqs = null;
831 String[] chains = null;
833 StringTokenizer st = new StringTokenizer(param, " ");
835 if (st.countTokens() < 2)
837 String sequence = applet.getParameter("PDBSEQ");
838 if (sequence != null)
839 seqs = new SequenceI[]
840 { (Sequence) newAlignFrame.getAlignViewport()
841 .getAlignment().findName(sequence) };
846 param = st.nextToken();
847 Vector tmp = new Vector();
848 Vector tmp2 = new Vector();
850 while (st.hasMoreTokens())
852 seqstring = st.nextToken();
853 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
854 if (st2.countTokens() > 1)
857 tmp2.addElement(st2.nextToken());
858 seqstring = st2.nextToken();
860 tmp.addElement((Sequence) newAlignFrame
861 .getAlignViewport().getAlignment().findName(
865 seqs = new SequenceI[tmp.size()];
867 if (tmp2.size() == tmp.size())
869 chains = new String[tmp2.size()];
870 tmp2.copyInto(chains);
873 param = setProtocolState(param);
875 if (// !jmolAvailable
877 protocol == AppletFormatAdapter.CLASSLOADER)
879 // TODO: verify this Re:
880 // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
881 // This exception preserves the current behaviour where, even if
882 // the local pdb file was identified in the class loader
883 protocol = AppletFormatAdapter.URL; // this is probably NOT
885 param = addProtocol(param); //
892 for (int i = 0; i < seqs.length; i++)
896 ((Sequence) seqs[i]).addPDBId(pdb);
900 if (JalviewLite.debug)
902 // this may not really be a problem but we give a warning
905 .println("Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
913 new jalview.appletgui.AppletJmol(pdb, seqs, chains,
914 newAlignFrame.alignPanel, protocol);
919 new MCview.AppletPDBViewer(pdb, seqs, chains,
920 newAlignFrame.alignPanel, protocol);
925 } while (pdbFileCount < 10);
927 // ///////////////////////////
928 // modify display of features
930 // hide specific groups
931 param = getParameter("hidefeaturegroups");
934 applet.setFeatureGroupStateOn(newAlignFrame,param, false);
936 // show specific groups
937 param = getParameter("showfeaturegroups");
940 applet.setFeatureGroupStateOn(newAlignFrame,param, true);
952 * Discovers whether the given file is in the Applet Archive
958 boolean inArchive(String file)
960 // This might throw a security exception in certain browsers
961 // Netscape Communicator for instance.
964 boolean rtn = (getClass().getResourceAsStream("/" + file) != null);
967 System.err.println("Resource '" + file + "' was "
968 + (rtn ? "" : "not") + " located by classloader.");
971 } catch (Exception ex)
973 System.out.println("Exception checking resources: " + file + " "
979 String addProtocol(String file)
981 if (file.indexOf("://") == -1)
983 file = getCodeBase() + file;
986 System.err.println("Prepended codebase for resource: '" + file
996 * @return the default alignFrame acted on by the public applet methods. May
997 * return null with an error message on System.err indicating the
1000 protected AlignFrame getDefaultTargetFrame()
1002 if (currentAlignFrame != null)
1004 return currentAlignFrame;
1006 if (initialAlignFrame != null)
1008 return initialAlignFrame;
1011 .println("Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
1016 * separator used for separatorList
1018 protected String separator = "|"; // this is a safe(ish) separator - tabs
1020 // don't work for firefox
1023 * parse the string into a list
1026 * @return elements separated by separator
1028 public String[] separatorListToArray(String list)
1030 int seplen = separator.length();
1031 if (list == null || list.equals(""))
1033 java.util.Vector jv = new Vector();
1035 while ((pos = list.indexOf(separator, cp)) > cp)
1037 jv.addElement(list.substring(cp, pos));
1040 if (cp < list.length())
1042 jv.addElement(list.substring(cp));
1046 String[] v = new String[jv.size()];
1047 for (int i = 0; i < v.length; i++)
1049 v[i] = (String) jv.elementAt(i);
1051 jv.removeAllElements();
1054 System.err.println("Array from '" + separator
1055 + "' separated List:\n" + v.length);
1056 for (int i = 0; i < v.length; i++)
1058 System.err.println("item " + i + " '" + v[i] + "'");
1065 System.err.println("Empty Array from '" + separator
1066 + "' separated List");
1072 * concatenate the list with separator
1075 * @return concatenated string
1077 public String arrayToSeparatorList(String[] list)
1079 StringBuffer v = new StringBuffer();
1082 for (int i = 0, iSize = list.length - 1; i < iSize; i++)
1084 if (list[i] != null)
1088 v.append(separator);
1090 if (list[list.length - 1] != null)
1092 v.append(list[list.length - 1]);
1096 System.err.println("Returning '" + separator
1097 + "' separated List:\n");
1098 System.err.println(v);
1100 return v.toString();
1104 System.err.println("Returning empty '" + separator
1105 + "' separated List\n");
1112 * @see jalview.appletgui.AlignFrame#getFeatureGroups()
1114 public String getFeatureGroups()
1116 String lst = arrayToSeparatorList(getDefaultTargetFrame()
1117 .getFeatureGroups());
1123 * alignframe to get feature groups on
1125 * @see jalview.appletgui.AlignFrame#getFeatureGroups()
1127 public String getFeatureGroupsOn(AlignFrame alf)
1129 String lst = arrayToSeparatorList(alf.getFeatureGroups());
1136 * @see jalview.appletgui.AlignFrame#getFeatureGroupsOfState(boolean)
1138 public String getFeatureGroupsOfState(boolean visible)
1140 return arrayToSeparatorList(getDefaultTargetFrame()
1141 .getFeatureGroupsOfState(visible));
1146 * align frame to get groups of state visible
1149 * @see jalview.appletgui.AlignFrame#getFeatureGroupsOfState(boolean)
1151 public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
1153 return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
1158 * tab separated list of group names
1161 * @see jalview.appletgui.AlignFrame#setFeatureGroupState(java.lang.String[],
1164 public void setFeatureGroupStateOn(AlignFrame alf, String groups,
1167 boolean st = state;// !(state==null || state.equals("") ||
1168 // state.toLowerCase().equals("false"));
1169 alf.setFeatureGroupState(separatorListToArray(groups), st);
1172 public void setFeatureGroupState(String groups, boolean state)
1174 setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
1178 * List separator string
1180 * @return the separator
1182 public String getSeparator()
1188 * List separator string
1191 * the separator to set
1193 public void setSeparator(String separator)
1195 this.separator = separator;