2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
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
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentUtils;
24 import jalview.api.StructureSelectionManagerProvider;
25 import jalview.appletgui.AlignFrame;
26 import jalview.appletgui.AlignViewport;
27 import jalview.appletgui.EmbmenuFrame;
28 import jalview.appletgui.FeatureSettings;
29 import jalview.appletgui.SplitFrame;
30 import jalview.datamodel.Alignment;
31 import jalview.datamodel.AlignmentI;
32 import jalview.datamodel.AlignmentOrder;
33 import jalview.datamodel.ColumnSelection;
34 import jalview.datamodel.PDBEntry;
35 import jalview.datamodel.Sequence;
36 import jalview.datamodel.SequenceGroup;
37 import jalview.datamodel.SequenceI;
38 import jalview.io.AnnotationFile;
39 import jalview.io.AppletFormatAdapter;
40 import jalview.io.DataSourceType;
41 import jalview.io.FileFormatI;
42 import jalview.io.FileFormats;
43 import jalview.io.FileParse;
44 import jalview.io.IdentifyFile;
45 import jalview.io.JPredFile;
46 import jalview.io.JnetAnnotationMaker;
47 import jalview.io.NewickFile;
48 import jalview.javascript.JSFunctionExec;
49 import jalview.javascript.JalviewLiteJsApi;
50 import jalview.javascript.JsCallBack;
51 import jalview.javascript.MouseOverStructureListener;
52 import jalview.structure.SelectionListener;
53 import jalview.structure.StructureSelectionManager;
54 import jalview.util.ColorUtils;
55 import jalview.util.HttpUtils;
56 import jalview.util.MessageManager;
58 import java.applet.Applet;
59 import java.awt.Button;
60 import java.awt.Color;
61 import java.awt.Component;
62 import java.awt.EventQueue;
64 import java.awt.Frame;
65 import java.awt.Graphics;
66 import java.awt.event.ActionEvent;
67 import java.awt.event.WindowAdapter;
68 import java.awt.event.WindowEvent;
69 import java.io.BufferedReader;
70 import java.io.IOException;
71 import java.io.InputStreamReader;
73 import java.util.ArrayList;
74 import java.util.Hashtable;
75 import java.util.List;
76 import java.util.StringTokenizer;
77 import java.util.Vector;
79 import netscape.javascript.JSObject;
82 * Jalview Applet. Runs in Java 1.18 runtime
85 * @version $Revision: 1.92 $
87 public class JalviewLite extends Applet implements
88 StructureSelectionManagerProvider, JalviewLiteJsApi
91 private static final String TRUE = "true";
93 private static final String FALSE = "false";
95 public StructureSelectionManager getStructureSelectionManager()
97 return StructureSelectionManager.getStructureSelectionManager(this);
100 // /////////////////////////////////////////
101 // The following public methods may be called
102 // externally, eg via javascript in HTML page
106 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences()
109 public String getSelectedSequences()
111 return getSelectedSequencesFrom(getDefaultTargetFrame());
117 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences(java.lang.String)
120 public String getSelectedSequences(String sep)
122 return getSelectedSequencesFrom(getDefaultTargetFrame(), sep);
129 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
133 public String getSelectedSequencesFrom(AlignFrame alf)
135 return getSelectedSequencesFrom(alf, separator); // ""+0x00AC);
142 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
143 * .AlignFrame, java.lang.String)
146 public String getSelectedSequencesFrom(AlignFrame alf, String sep)
148 StringBuffer result = new StringBuffer("");
149 if (sep == null || sep.length() == 0)
151 sep = separator; // "+0x00AC;
153 if (alf.viewport.getSelectionGroup() != null)
155 SequenceI[] seqs = alf.viewport.getSelectionGroup()
156 .getSequencesInOrder(alf.viewport.getAlignment());
158 for (int i = 0; i < seqs.length; i++)
160 result.append(seqs[i].getName());
165 return result.toString();
171 * @see jalview.bin.JalviewLiteJsApi#highlight(java.lang.String,
172 * java.lang.String, java.lang.String)
175 public void highlight(String sequenceId, String position,
176 String alignedPosition)
178 highlightIn(getDefaultTargetFrame(), sequenceId, position,
185 * @see jalview.bin.JalviewLiteJsApi#highlightIn(jalview.appletgui.AlignFrame,
186 * java.lang.String, java.lang.String, java.lang.String)
189 public void highlightIn(final AlignFrame alf, final String sequenceId,
190 final String position, final String alignedPosition)
192 // TODO: could try to highlight in all alignments if alf==null
193 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
194 alf.viewport.getAlignment().getSequencesArray());
195 final SequenceI sq = matcher.findIdMatch(sequenceId);
201 apos = new Integer(position).intValue();
203 } catch (NumberFormatException ex)
207 final StructureSelectionManagerProvider me = this;
208 final int pos = apos;
209 // use vamsas listener to broadcast to all listeners in scope
210 if (alignedPosition != null
211 && (alignedPosition.trim().length() == 0 || alignedPosition
212 .toLowerCase().indexOf("false") > -1))
214 java.awt.EventQueue.invokeLater(new Runnable()
219 StructureSelectionManager.getStructureSelectionManager(me)
220 .mouseOverVamsasSequence(sq, sq.findIndex(pos), null);
226 java.awt.EventQueue.invokeLater(new Runnable()
231 StructureSelectionManager.getStructureSelectionManager(me)
232 .mouseOverVamsasSequence(sq, pos, null);
242 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
246 public void select(String sequenceIds, String columns)
248 selectIn(getDefaultTargetFrame(), sequenceIds, columns, separator);
254 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
255 * java.lang.String, java.lang.String)
258 public void select(String sequenceIds, String columns, String sep)
260 selectIn(getDefaultTargetFrame(), sequenceIds, columns, sep);
266 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
267 * java.lang.String, java.lang.String)
270 public void selectIn(AlignFrame alf, String sequenceIds, String columns)
272 selectIn(alf, sequenceIds, columns, separator);
278 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
279 * java.lang.String, java.lang.String, java.lang.String)
282 public void selectIn(final AlignFrame alf, String sequenceIds,
283 String columns, String sep)
285 if (sep == null || sep.length() == 0)
293 System.err.println("Selecting region using separator string '"
298 String[] ids = separatorListToArray(sequenceIds, sep);
299 String[] cols = separatorListToArray(columns, sep);
300 final SequenceGroup sel = new SequenceGroup();
301 final ColumnSelection csel = new ColumnSelection();
302 AlignmentI al = alf.viewport.getAlignment();
303 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
304 alf.viewport.getAlignment().getSequencesArray());
305 int start = 0, end = al.getWidth(), alw = al.getWidth();
306 boolean seqsfound = true;
307 if (ids != null && ids.length > 0)
310 for (int i = 0; i < ids.length; i++)
312 if (ids[i].trim().length() == 0)
316 SequenceI sq = matcher.findIdMatch(ids[i]);
320 sel.addSequence(sq, false);
324 boolean inseqpos = false;
325 if (cols != null && cols.length > 0)
327 boolean seset = false;
328 for (int i = 0; i < cols.length; i++)
330 String cl = cols[i].trim();
331 if (cl.length() == 0)
336 if ((p = cl.indexOf("-")) > -1)
338 int from = -1, to = -1;
341 from = new Integer(cl.substring(0, p)).intValue();
343 } catch (NumberFormatException ex)
346 .println("ERROR: Couldn't parse first integer in range element column selection string '"
347 + cl + "' - format is 'from-to'");
352 to = new Integer(cl.substring(p + 1)).intValue();
354 } catch (NumberFormatException ex)
357 .println("ERROR: Couldn't parse second integer in range element column selection string '"
358 + cl + "' - format is 'from-to'");
361 if (from >= 0 && to >= 0)
378 // comment to prevent range extension
388 for (int r = from; r <= to; r++)
390 if (r >= 0 && r < alw)
397 System.err.println("Range '" + cl + "' deparsed as [" + from
403 System.err.println("ERROR: Invalid Range '" + cl
404 + "' deparsed as [" + from + "," + to + "]");
412 r = new Integer(cl).intValue();
414 } catch (NumberFormatException ex)
416 if (cl.toLowerCase().equals("sequence"))
418 // we are in the dataset sequence's coordinate frame.
424 .println("ERROR: Couldn't parse integer from point selection element of column selection string '"
429 if (r >= 0 && r <= alw)
439 // comment to prevent range extension
452 System.err.println("Point selection '" + cl
453 + "' deparsed as [" + r + "]");
458 System.err.println("ERROR: Invalid Point selection '" + cl
459 + "' deparsed as [" + r + "]");
466 // we only propagate the selection when it was the null selection, or the
467 // given sequences were found in the alignment.
468 if (inseqpos && sel.getSize() > 0)
470 // assume first sequence provides reference frame ?
471 SequenceI rs = sel.getSequenceAt(0);
472 start = rs.findIndex(start);
473 end = rs.findIndex(end);
474 List<Integer> cs = new ArrayList<Integer>(csel.getSelected());
476 for (Integer selectedCol : cs)
478 csel.addElement(rs.findIndex(selectedCol));
481 sel.setStartRes(start);
483 EventQueue.invokeLater(new Runnable()
488 alf.select(sel, csel);
498 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignment(java.lang.
499 * String, java.lang.String)
502 public String getSelectedSequencesAsAlignment(String format, String suffix)
504 return getSelectedSequencesAsAlignmentFrom(getDefaultTargetFrame(),
512 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignmentFrom(jalview
513 * .appletgui.AlignFrame, java.lang.String, java.lang.String)
516 public String getSelectedSequencesAsAlignmentFrom(AlignFrame alf,
517 String format, String suffix)
521 FileFormatI theFormat = FileFormats.getInstance().forName(format);
522 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
523 if (alf.viewport.getSelectionGroup() != null)
525 // JBPNote: getSelectionAsNewSequence behaviour has changed - this
526 // method now returns a full copy of sequence data
527 // TODO consider using getSequenceSelection instead here
528 String reply = new AppletFormatAdapter().formatSequences(theFormat,
529 new Alignment(alf.viewport.getSelectionAsNewSequence()),
533 } catch (IllegalArgumentException ex)
535 ex.printStackTrace();
536 return "Error retrieving alignment, possibly invalid format specifier: "
545 * @see jalview.bin.JalviewLiteJsApi#getAlignmentOrder()
548 public String getAlignmentOrder()
550 return getAlignmentOrderFrom(getDefaultTargetFrame());
557 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
561 public String getAlignmentOrderFrom(AlignFrame alf)
563 return getAlignmentOrderFrom(alf, separator);
570 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
571 * , java.lang.String)
574 public String getAlignmentOrderFrom(AlignFrame alf, String sep)
576 AlignmentI alorder = alf.getAlignViewport().getAlignment();
577 String[] order = new String[alorder.getHeight()];
578 for (int i = 0; i < order.length; i++)
580 order[i] = alorder.getSequenceAt(i).getName();
582 return arrayToSeparatorList(order);
588 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
592 public String orderBy(String order, String undoName)
594 return orderBy(order, undoName, separator);
600 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
601 * java.lang.String, java.lang.String)
604 public String orderBy(String order, String undoName, String sep)
606 return orderAlignmentBy(getDefaultTargetFrame(), order, undoName, sep);
613 * jalview.bin.JalviewLiteJsApi#orderAlignmentBy(jalview.appletgui.AlignFrame,
614 * java.lang.String, java.lang.String, java.lang.String)
617 public String orderAlignmentBy(AlignFrame alf, String order,
618 String undoName, String sep)
620 String[] ids = separatorListToArray(order, sep);
621 SequenceI[] sqs = null;
622 if (ids != null && ids.length > 0)
624 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
625 alf.viewport.getAlignment().getSequencesArray());
627 sqs = new SequenceI[ids.length];
628 for (int i = 0; i < ids.length; i++)
630 if (ids[i].trim().length() == 0)
634 SequenceI sq = matcher.findIdMatch(ids[i]);
642 SequenceI[] sqq = new SequenceI[s];
643 System.arraycopy(sqs, 0, sqq, 0, s);
656 final AlignmentOrder aorder = new AlignmentOrder(sqs);
658 if (undoName != null && undoName.trim().length() == 0)
662 final String _undoName = undoName;
663 // TODO: deal with synchronization here: cannot raise any events until after
664 // this has returned.
665 return alf.sortBy(aorder, _undoName) ? TRUE : "";
671 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String)
674 public String getAlignment(String format)
676 return getAlignmentFrom(getDefaultTargetFrame(), format, TRUE);
683 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
687 public String getAlignmentFrom(AlignFrame alf, String format)
689 return getAlignmentFrom(alf, format, TRUE);
695 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String,
699 public String getAlignment(String format, String suffix)
701 return getAlignmentFrom(getDefaultTargetFrame(), format, suffix);
708 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
709 * java.lang.String, java.lang.String)
712 public String getAlignmentFrom(AlignFrame alf, String format,
717 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
719 FileFormatI theFormat = FileFormats.getInstance().forName(format);
720 String reply = new AppletFormatAdapter().formatSequences(theFormat,
721 alf.viewport.getAlignment(), seqlimits);
723 } catch (IllegalArgumentException ex)
725 ex.printStackTrace();
726 return "Error retrieving alignment, possibly invalid format specifier: "
734 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
737 public void loadAnnotation(String annotation)
739 loadAnnotationFrom(getDefaultTargetFrame(), annotation);
746 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
747 * , java.lang.String)
750 public void loadAnnotationFrom(AlignFrame alf, String annotation)
752 if (new AnnotationFile().annotateAlignmentView(alf.getAlignViewport(),
753 annotation, DataSourceType.PASTE))
755 alf.alignPanel.fontChanged();
756 alf.alignPanel.setScrollValues(0, 0);
760 alf.parseFeaturesFile(annotation, DataSourceType.PASTE);
767 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
770 public void loadFeatures(String features, boolean autoenabledisplay)
772 loadFeaturesFrom(getDefaultTargetFrame(), features, autoenabledisplay);
779 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
780 * , java.lang.String)
783 public boolean loadFeaturesFrom(AlignFrame alf, String features,
784 boolean autoenabledisplay)
786 return alf.parseFeaturesFile(features, DataSourceType.PASTE,
793 * @see jalview.bin.JalviewLiteJsApi#getFeatures(java.lang.String)
796 public String getFeatures(String format)
798 return getFeaturesFrom(getDefaultTargetFrame(), format);
805 * jalview.bin.JalviewLiteJsApi#getFeaturesFrom(jalview.appletgui.AlignFrame,
809 public String getFeaturesFrom(AlignFrame alf, String format)
811 return alf.outputFeatures(false, format);
817 * @see jalview.bin.JalviewLiteJsApi#getAnnotation()
820 public String getAnnotation()
822 return getAnnotationFrom(getDefaultTargetFrame());
829 * jalview.bin.JalviewLiteJsApi#getAnnotationFrom(jalview.appletgui.AlignFrame
833 public String getAnnotationFrom(AlignFrame alf)
835 return alf.outputAnnotations(false);
841 * @see jalview.bin.JalviewLiteJsApi#newView()
844 public AlignFrame newView()
846 return newViewFrom(getDefaultTargetFrame());
852 * @see jalview.bin.JalviewLiteJsApi#newView(java.lang.String)
855 public AlignFrame newView(String name)
857 return newViewFrom(getDefaultTargetFrame(), name);
863 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame)
866 public AlignFrame newViewFrom(AlignFrame alf)
868 return alf.newView(null);
874 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame,
878 public AlignFrame newViewFrom(AlignFrame alf, String name)
880 return alf.newView(name);
886 * @see jalview.bin.JalviewLiteJsApi#loadAlignment(java.lang.String,
890 public AlignFrame loadAlignment(String text, String title)
892 AlignmentI al = null;
896 FileFormatI format = new IdentifyFile().identify(text,
897 DataSourceType.PASTE);
898 al = new AppletFormatAdapter().readFile(text, DataSourceType.PASTE,
900 if (al.getHeight() > 0)
902 return new AlignFrame(al, this, title, false);
904 } catch (IOException ex)
906 ex.printStackTrace();
914 * @see jalview.bin.JalviewLiteJsApi#setMouseoverListener(java.lang.String)
917 public void setMouseoverListener(String listener)
919 setMouseoverListener(currentAlignFrame, listener);
922 private Vector<jalview.javascript.JSFunctionExec> javascriptListeners = new Vector<jalview.javascript.JSFunctionExec>();
928 * jalview.bin.JalviewLiteJsApi#setMouseoverListener(jalview.appletgui.AlignFrame
929 * , java.lang.String)
932 public void setMouseoverListener(AlignFrame af, String listener)
934 if (listener != null)
936 listener = listener.trim();
937 if (listener.length() == 0)
940 .println("jalview Javascript error: Ignoring empty function for mouseover listener.");
944 jalview.javascript.MouseOverListener mol = new jalview.javascript.MouseOverListener(
946 javascriptListeners.addElement(mol);
947 StructureSelectionManager.getStructureSelectionManager(this)
948 .addStructureViewerListener(mol);
951 System.err.println("Added a mouseover listener for "
952 + ((af == null) ? "All frames" : "Just views for "
953 + af.getAlignViewport().getSequenceSetId()));
954 System.err.println("There are now " + javascriptListeners.size()
955 + " listeners in total.");
962 * @see jalview.bin.JalviewLiteJsApi#setSelectionListener(java.lang.String)
965 public void setSelectionListener(String listener)
967 setSelectionListener(null, listener);
974 * jalview.bin.JalviewLiteJsApi#setSelectionListener(jalview.appletgui.AlignFrame
975 * , java.lang.String)
978 public void setSelectionListener(AlignFrame af, String listener)
980 if (listener != null)
982 listener = listener.trim();
983 if (listener.length() == 0)
986 .println("jalview Javascript error: Ignoring empty function for selection listener.");
990 jalview.javascript.JsSelectionSender mol = new jalview.javascript.JsSelectionSender(
992 javascriptListeners.addElement(mol);
993 StructureSelectionManager.getStructureSelectionManager(this)
994 .addSelectionListener(mol);
997 System.err.println("Added a selection listener for "
998 + ((af == null) ? "All frames" : "Just views for "
999 + af.getAlignViewport().getSequenceSetId()));
1000 System.err.println("There are now " + javascriptListeners.size()
1001 + " listeners in total.");
1006 * Callable from javascript to register a javascript function to pass events
1007 * to a structure viewer.
1010 * the name of a javascript function
1012 * a token separated list of PDB file names listened for
1013 * @see jalview.bin.JalviewLiteJsApi#setStructureListener(java.lang.String,
1017 public void setStructureListener(String listener, String modelSet)
1019 if (listener != null)
1021 listener = listener.trim();
1022 if (listener.length() == 0)
1025 .println("jalview Javascript error: Ignoring empty function for selection listener.");
1029 MouseOverStructureListener mol = new MouseOverStructureListener(this,
1030 listener, separatorListToArray(modelSet));
1031 javascriptListeners.addElement(mol);
1032 StructureSelectionManager.getStructureSelectionManager(this)
1033 .addStructureViewerListener(mol);
1036 System.err.println("Added a javascript structure viewer listener '"
1038 System.err.println("There are now " + javascriptListeners.size()
1039 + " listeners in total.");
1047 * jalview.bin.JalviewLiteJsApi#removeJavascriptListener(jalview.appletgui
1048 * .AlignFrame, java.lang.String)
1051 public void removeJavascriptListener(AlignFrame af, String listener)
1053 if (listener != null)
1055 listener = listener.trim();
1056 if (listener.length() == 0)
1061 boolean rprt = false;
1062 for (int ms = 0, msSize = javascriptListeners.size(); ms < msSize;)
1064 Object lstn = javascriptListeners.elementAt(ms);
1065 JsCallBack lstner = (JsCallBack) lstn;
1066 if ((af == null || lstner.getAlignFrame() == af)
1067 && (listener == null || lstner.getListenerFunction().equals(
1070 javascriptListeners.removeElement(lstner);
1072 if (lstner instanceof SelectionListener)
1074 StructureSelectionManager.getStructureSelectionManager(this)
1075 .removeSelectionListener((SelectionListener) lstner);
1079 StructureSelectionManager.getStructureSelectionManager(this)
1080 .removeStructureViewerListener(lstner, null);
1085 System.err.println("Removed listener '" + listener + "'");
1095 System.err.println("There are now " + javascriptListeners.size()
1096 + " listeners in total.");
1103 System.err.println("Applet " + getName() + " stop().");
1108 public void destroy()
1110 System.err.println("Applet " + getName() + " destroy().");
1114 private void tidyUp()
1117 if (currentAlignFrame != null && currentAlignFrame.viewport != null
1118 && currentAlignFrame.viewport.applet != null)
1120 AlignViewport av = currentAlignFrame.viewport;
1121 currentAlignFrame.closeMenuItem_actionPerformed();
1123 currentAlignFrame = null;
1125 if (javascriptListeners != null)
1127 while (javascriptListeners.size() > 0)
1129 jalview.javascript.JSFunctionExec mol = javascriptListeners
1131 javascriptListeners.removeElement(mol);
1132 if (mol instanceof SelectionListener)
1134 StructureSelectionManager.getStructureSelectionManager(this)
1135 .removeSelectionListener((SelectionListener) mol);
1139 StructureSelectionManager.getStructureSelectionManager(this)
1140 .removeStructureViewerListener(mol, null);
1145 if (jsFunctionExec != null)
1147 jsFunctionExec.stopQueue();
1148 jsFunctionExec.jvlite = null;
1150 initialAlignFrame = null;
1151 jsFunctionExec = null;
1152 javascriptListeners = null;
1153 StructureSelectionManager.release(this);
1156 private jalview.javascript.JSFunctionExec jsFunctionExec;
1161 * @see jalview.bin.JalviewLiteJsApi#mouseOverStructure(java.lang.String,
1162 * java.lang.String, java.lang.String)
1165 public void mouseOverStructure(final String pdbResNum,
1166 final String chain, final String pdbfile)
1168 final StructureSelectionManagerProvider me = this;
1169 java.awt.EventQueue.invokeLater(new Runnable()
1176 StructureSelectionManager.getStructureSelectionManager(me)
1177 .mouseOverStructure(new Integer(pdbResNum).intValue(),
1181 System.err.println("mouseOver for '" + pdbResNum
1182 + "' in chain '" + chain + "' in structure '" + pdbfile
1185 } catch (NumberFormatException e)
1187 System.err.println("Ignoring invalid residue number string '"
1199 * jalview.bin.JalviewLiteJsApi#scrollViewToIn(jalview.appletgui.AlignFrame,
1200 * java.lang.String, java.lang.String)
1203 public void scrollViewToIn(final AlignFrame alf, final String topRow,
1204 final String leftHandColumn)
1206 java.awt.EventQueue.invokeLater(new Runnable()
1213 alf.scrollTo(new Integer(topRow).intValue(), new Integer(
1214 leftHandColumn).intValue());
1216 } catch (Exception ex)
1218 System.err.println("Couldn't parse integer arguments (topRow='"
1219 + topRow + "' and leftHandColumn='" + leftHandColumn
1221 ex.printStackTrace();
1231 * jalview.javascript.JalviewLiteJsApi#scrollViewToRowIn(jalview.appletgui
1232 * .AlignFrame, java.lang.String)
1235 public void scrollViewToRowIn(final AlignFrame alf, final String topRow)
1238 java.awt.EventQueue.invokeLater(new Runnable()
1245 alf.scrollToRow(new Integer(topRow).intValue());
1247 } catch (Exception ex)
1249 System.err.println("Couldn't parse integer arguments (topRow='"
1251 ex.printStackTrace();
1262 * jalview.javascript.JalviewLiteJsApi#scrollViewToColumnIn(jalview.appletgui
1263 * .AlignFrame, java.lang.String)
1266 public void scrollViewToColumnIn(final AlignFrame alf,
1267 final String leftHandColumn)
1269 java.awt.EventQueue.invokeLater(new Runnable()
1277 alf.scrollToColumn(new Integer(leftHandColumn).intValue());
1279 } catch (Exception ex)
1282 .println("Couldn't parse integer arguments (leftHandColumn='"
1283 + leftHandColumn + "')");
1284 ex.printStackTrace();
1291 // //////////////////////////////////////////////
1292 // //////////////////////////////////////////////
1294 public static int lastFrameX = 200;
1296 public static int lastFrameY = 200;
1298 boolean fileFound = true;
1300 String file = "No file";
1302 String file2 = null;
1304 Button launcher = new Button(
1305 MessageManager.getString("label.start_jalview"));
1308 * The currentAlignFrame is static, it will change if and when the user
1309 * selects a new window. Note that it will *never* point back to the embedded
1310 * AlignFrame if the applet is started as embedded on the page and then
1311 * afterwards a new view is created.
1313 public AlignFrame currentAlignFrame = null;
1316 * This is the first frame to be displayed, and does not change. API calls
1317 * will default to this instance if currentAlignFrame is null.
1319 AlignFrame initialAlignFrame = null;
1321 boolean embedded = false;
1323 private boolean checkForJmol = true;
1325 private boolean checkedForJmol = false; // ensure we don't check for jmol
1327 // every time the app is re-inited
1329 public boolean jmolAvailable = false;
1331 private boolean alignPdbStructures = false;
1334 * use an external structure viewer exclusively (no jmols or MCViews will be
1335 * opened by JalviewLite itself)
1337 public boolean useXtrnalSviewer = false;
1339 public static boolean debug = false;
1341 static String builddate = null, version = null, installation = null;
1343 private static void initBuildDetails()
1345 if (builddate == null)
1347 builddate = "unknown";
1349 installation = "applet";
1350 java.net.URL url = JalviewLite.class
1351 .getResource("/.build_properties");
1356 BufferedReader reader = new BufferedReader(new InputStreamReader(
1359 while ((line = reader.readLine()) != null)
1361 if (line.indexOf("VERSION") > -1)
1363 version = line.substring(line.indexOf("=") + 1);
1365 if (line.indexOf("BUILD_DATE") > -1)
1367 builddate = line.substring(line.indexOf("=") + 1);
1369 if (line.indexOf("INSTALLATION") > -1)
1371 installation = line.substring(line.indexOf("=") + 1);
1374 } catch (Exception ex)
1376 ex.printStackTrace();
1382 public static String getBuildDate()
1388 public static String getInstallation()
1391 return installation;
1394 public static String getVersion()
1400 // public JSObject scriptObject = null;
1403 * init method for Jalview Applet
1408 debug = TRUE.equalsIgnoreCase(getParameter("debug"));
1413 System.err.println("Applet context is '"
1414 + getAppletContext().getClass().toString() + "'");
1416 JSObject scriptObject = JSObject.getWindow(this);
1417 if (debug && scriptObject != null)
1419 System.err.println("Applet has Javascript callback support.");
1422 } catch (Exception ex)
1425 .println("Warning: No JalviewLite javascript callbacks available.");
1428 ex.printStackTrace();
1434 System.err.println("JalviewLite Version " + getVersion());
1435 System.err.println("Build Date : " + getBuildDate());
1436 System.err.println("Installation : " + getInstallation());
1438 String externalsviewer = getParameter("externalstructureviewer");
1439 if (externalsviewer != null)
1441 useXtrnalSviewer = externalsviewer.trim().toLowerCase().equals(TRUE);
1444 * if true disable the check for jmol
1446 String chkforJmol = getParameter("nojmol");
1447 if (chkforJmol != null)
1449 checkForJmol = !chkforJmol.equals(TRUE);
1452 * get the separator parameter if present
1454 String sep = getParameter("separator");
1457 if (sep.length() > 0)
1462 System.err.println("Separator set to '" + separator + "'");
1469 .getString("error.invalid_separator_parameter"));
1475 String param = getParameter("RGB");
1481 r = Integer.parseInt(param.substring(0, 2), 16);
1482 g = Integer.parseInt(param.substring(2, 4), 16);
1483 b = Integer.parseInt(param.substring(4, 6), 16);
1484 } catch (Exception ex)
1491 param = getParameter("label");
1494 launcher.setLabel(param);
1497 setBackground(new Color(r, g, b));
1499 file = getParameter("file");
1503 // Maybe the sequences are added as parameters
1504 StringBuffer data = new StringBuffer("PASTE");
1506 while ((file = getParameter("sequence" + i)) != null)
1508 data.append(file.toString() + "\n");
1511 if (data.length() > 5)
1513 file = data.toString();
1516 if (getDefaultParameter("enableSplitFrame", true))
1518 file2 = getParameter("file2");
1521 embedded = TRUE.equalsIgnoreCase(getParameter("embedded"));
1524 LoadingThread loader = new LoadingThread(file, file2, this);
1527 else if (file != null)
1530 * Start the applet immediately or show a button to start it
1532 if (FALSE.equalsIgnoreCase(getParameter("showbutton")))
1534 LoadingThread loader = new LoadingThread(file, file2, this);
1540 launcher.addActionListener(new java.awt.event.ActionListener()
1543 public void actionPerformed(ActionEvent e)
1545 LoadingThread loader = new LoadingThread(file, file2,
1554 // jalview initialisation with no alignment. loadAlignment() method can
1555 // still be called to open new alignments.
1562 private void initLiveConnect()
1564 // try really hard to get the liveConnect thing working
1565 boolean notFailed = false;
1567 while (!notFailed && tries < 10)
1571 System.err.println("LiveConnect request thread going to sleep.");
1575 Thread.sleep(700 * (1 + tries));
1576 } catch (InterruptedException q)
1582 System.err.println("LiveConnect request thread woken up.");
1586 JSObject scriptObject = JSObject.getWindow(this);
1587 if (scriptObject.eval("navigator") != null)
1591 } catch (Exception jsex)
1593 System.err.println("Attempt " + tries
1594 + " to access LiveConnect javascript failed.");
1599 private void callInitCallback()
1601 String initjscallback = getParameter("oninit");
1602 if (initjscallback == null)
1606 initjscallback = initjscallback.trim();
1607 if (initjscallback.length() > 0)
1609 JSObject scriptObject = null;
1612 scriptObject = JSObject.getWindow(this);
1613 } catch (Exception ex)
1617 // try really hard to let the browser plugin know we want liveconnect
1620 if (scriptObject != null)
1624 // do onInit with the JS executor thread
1625 new JSFunctionExec(this).executeJavascriptFunction(true,
1626 initjscallback, null, "Calling oninit callback '"
1627 + initjscallback + "'.");
1628 } catch (Exception e)
1630 System.err.println("Exception when executing _oninit callback '"
1631 + initjscallback + "'.");
1632 e.printStackTrace();
1637 System.err.println("Not executing _oninit callback '"
1638 + initjscallback + "' - no scripting allowed.");
1644 * Initialises and displays a new java.awt.Frame
1647 * java.awt.Frame to be displayed
1649 * title of new frame
1651 * width if new frame
1653 * height of new frame
1655 public static void addFrame(final Frame frame, String title, int width,
1658 frame.setLocation(lastFrameX, lastFrameY);
1661 frame.setSize(width, height);
1662 frame.setTitle(title);
1663 frame.addWindowListener(new WindowAdapter()
1666 public void windowClosing(WindowEvent e)
1668 if (frame instanceof AlignFrame)
1670 AlignViewport vp = ((AlignFrame) frame).viewport;
1671 ((AlignFrame) frame).closeMenuItem_actionPerformed();
1672 if (vp.applet.currentAlignFrame == frame)
1674 vp.applet.currentAlignFrame = null;
1682 if (frame instanceof EmbmenuFrame)
1684 ((EmbmenuFrame) frame).destroyMenus();
1686 frame.setMenuBar(null);
1691 public void windowActivated(WindowEvent e)
1693 if (frame instanceof AlignFrame)
1695 ((AlignFrame) frame).viewport.applet.currentAlignFrame = (AlignFrame) frame;
1698 System.err.println("Activated window " + frame);
1702 super.windowActivated(e);
1705 * Probably not necessary to do this - see TODO above. (non-Javadoc)
1708 * java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent
1711 * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
1712 * frame) { currentAlignFrame = null; if (debug) {
1713 * System.err.println("Deactivated window "+frame); } }
1714 * super.windowDeactivated(e); }
1717 frame.setVisible(true);
1721 * This paints the background surrounding the "Launch Jalview button" <br>
1723 * If file given in parameter not found, displays error message
1729 public void paint(Graphics g)
1733 g.setColor(new Color(200, 200, 200));
1734 g.setColor(Color.cyan);
1735 g.fillRect(0, 0, getSize().width, getSize().height);
1736 g.setColor(Color.red);
1738 MessageManager.getString("label.jalview_cannot_open_file"),
1740 g.drawString("\"" + file + "\"", 5, 30);
1744 g.setColor(Color.black);
1745 g.setFont(new Font("Arial", Font.BOLD, 24));
1746 g.drawString(MessageManager.getString("label.jalview_applet"), 50,
1747 getSize().height / 2 - 30);
1748 g.drawString(MessageManager.getString("label.loading_data") + "...",
1749 50, getSize().height / 2);
1754 * get all components associated with the applet of the given type
1759 public Vector getAppletWindow(Class class1)
1761 Vector wnds = new Vector();
1762 Component[] cmp = getComponents();
1765 for (int i = 0; i < cmp.length; i++)
1767 if (class1.isAssignableFrom(cmp[i].getClass()))
1769 wnds.addElement(cmp);
1776 class LoadJmolThread extends Thread
1778 private boolean running = false;
1783 if (running || checkedForJmol)
1792 if (!System.getProperty("java.version").startsWith("1.1"))
1794 Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
1795 jmolAvailable = true;
1800 .println("Jmol not available - Using MCview for structures");
1802 } catch (java.lang.ClassNotFoundException ex)
1808 jmolAvailable = false;
1812 .println("Skipping Jmol check. Will use MCView (probably)");
1815 checkedForJmol = true;
1819 public boolean notFinished()
1821 return running || !checkedForJmol;
1825 class LoadingThread extends Thread
1828 * State variable: protocol for access to file source
1830 DataSourceType protocol;
1832 String _file; // alignment file or URL spec
1834 String _file2; // second alignment file or URL spec
1838 private void dbgMsg(String msg)
1840 if (JalviewLite.debug)
1842 System.err.println(msg);
1847 * update the protocol state variable for accessing the datasource located
1851 * @return possibly updated datasource string
1853 public String resolveFileProtocol(String path)
1858 if (path.startsWith("PASTE"))
1860 protocol = DataSourceType.PASTE;
1861 return path.substring(5);
1867 if (path.indexOf("://") != -1)
1869 protocol = DataSourceType.URL;
1874 * try relative to document root
1876 URL documentBase = getDocumentBase();
1877 String withDocBase = resolveUrlForLocalOrAbsolute(path, documentBase);
1878 if (HttpUtils.isValidUrl(withDocBase))
1882 System.err.println("Prepended document base '" + documentBase
1883 + "' to make: '" + withDocBase + "'");
1885 protocol = DataSourceType.URL;
1890 * try relative to codebase (if different to document base)
1892 URL codeBase = getCodeBase();
1893 String withCodeBase = applet.resolveUrlForLocalOrAbsolute(path,
1895 if (!withCodeBase.equals(withDocBase)
1896 && HttpUtils.isValidUrl(withCodeBase))
1898 protocol = DataSourceType.URL;
1901 System.err.println("Prepended codebase '" + codeBase
1902 + "' to make: '" + withCodeBase + "'");
1904 return withCodeBase;
1908 * try locating by classloader; try this last so files in the directory
1909 * are resolved using document base
1911 if (inArchive(path))
1913 protocol = DataSourceType.CLASSLOADER;
1918 public LoadingThread(String file, String file2, JalviewLite _applet)
1921 this._file2 = file2;
1928 LoadJmolThread jmolchecker = new LoadJmolThread();
1929 jmolchecker.start();
1930 while (jmolchecker.notFinished())
1932 // wait around until the Jmol check is complete.
1936 } catch (Exception e)
1941 // applet.callInitCallback();
1945 * Load the alignment and any related files as specified by applet
1948 private void startLoading()
1950 dbgMsg("Loading thread started with:\n>>file\n" + _file + ">>endfile");
1952 dbgMsg("Loading started.");
1954 AlignFrame newAlignFrame = readAlignment(_file);
1955 AlignFrame newAlignFrame2 = readAlignment(_file2);
1956 if (newAlignFrame != null)
1958 addToDisplay(newAlignFrame, newAlignFrame2);
1959 loadTree(newAlignFrame);
1961 loadScoreFile(newAlignFrame);
1963 loadFeatures(newAlignFrame);
1965 loadAnnotations(newAlignFrame);
1967 loadJnetFile(newAlignFrame);
1969 loadPdbFiles(newAlignFrame);
1974 applet.remove(launcher);
1981 * Add an AlignFrame to the display; or if two are provided, a SplitFrame.
1986 public void addToDisplay(AlignFrame af, AlignFrame af2)
1990 AlignmentI al1 = af.viewport.getAlignment();
1991 AlignmentI al2 = af2.viewport.getAlignment();
1992 AlignmentI cdna = al1.isNucleotide() ? al1 : al2;
1993 AlignmentI prot = al1.isNucleotide() ? al2 : al1;
1994 if (AlignmentUtils.mapProteinAlignmentToCdna(prot, cdna))
1997 SplitFrame sf = new SplitFrame(af, af2);
1998 sf.addToDisplay(embedded, JalviewLite.this);
2003 String msg = "Could not map any sequence in " + af2.getTitle()
2005 + (al1.isNucleotide() ? "protein product" : "cDNA")
2006 + " for " + af.getTitle();
2007 System.err.println(msg);
2011 af.addToDisplay(embedded);
2015 * Read the alignment file (from URL, text 'paste', or archive by
2020 protected AlignFrame readAlignment(String fileParam)
2022 if (fileParam == null)
2026 String resolvedFile = resolveFileProtocol(fileParam);
2027 AlignmentI al = null;
2030 FileFormatI format = new IdentifyFile().identify(resolvedFile,
2032 dbgMsg("File identified as '" + format + "'");
2033 al = new AppletFormatAdapter().readFile(resolvedFile, protocol,
2035 if ((al != null) && (al.getHeight() > 0))
2037 dbgMsg("Successfully loaded file.");
2038 al.setDataset(null);
2039 AlignFrame newAlignFrame = new AlignFrame(al, applet,
2040 resolvedFile, embedded, false);
2041 newAlignFrame.setTitle(resolvedFile);
2042 if (initialAlignFrame == null)
2044 initialAlignFrame = newAlignFrame;
2046 // update the focus.
2047 currentAlignFrame = newAlignFrame;
2049 if (protocol == DataSourceType.PASTE)
2051 newAlignFrame.setTitle(MessageManager.formatMessage(
2052 "label.sequences_from", new Object[] { applet
2053 .getDocumentBase().toString() }));
2056 newAlignFrame.statusBar.setText(MessageManager.formatMessage(
2057 "label.successfully_loaded_file",
2058 new Object[] { resolvedFile }));
2060 return newAlignFrame;
2062 } catch (java.io.IOException ex)
2064 dbgMsg("File load exception.");
2065 ex.printStackTrace();
2070 FileParse fp = new FileParse(resolvedFile, protocol);
2072 dbgMsg(">>>Dumping contents of '" + resolvedFile + "' " + "("
2074 while ((ln = fp.nextLine()) != null)
2078 dbgMsg(">>>Dump finished.");
2079 } catch (Exception e)
2082 .println("Exception when trying to dump the content of the file parameter.");
2083 e.printStackTrace();
2091 * Load PDBFiles if any specified by parameter(s). Returns true if loaded,
2097 protected boolean loadPdbFiles(AlignFrame alignFrame)
2099 boolean result = false;
2101 * <param name="alignpdbfiles" value="false/true"/> Undocumented for 2.6 -
2102 * related to JAL-434
2105 applet.setAlignPdbStructures(getDefaultParameter("alignpdbfiles",
2108 * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
2111 * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
2113 * <param name="PDBfile3" value="1q0o Q45135_9MICO">
2116 int pdbFileCount = 0;
2117 // Accumulate pdbs here if they are heading for the same view (if
2118 // alignPdbStructures is true)
2119 Vector pdbs = new Vector();
2120 // create a lazy matcher if we're asked to
2121 jalview.analysis.SequenceIdMatcher matcher = (applet
2122 .getDefaultParameter("relaxedidmatch", false)) ? new jalview.analysis.SequenceIdMatcher(
2123 alignFrame.getAlignViewport().getAlignment()
2124 .getSequencesArray()) : null;
2129 if (pdbFileCount > 0)
2131 param = applet.getParameter("PDBFILE" + pdbFileCount);
2135 param = applet.getParameter("PDBFILE");
2140 PDBEntry pdb = new PDBEntry();
2143 SequenceI[] seqs = null;
2144 String[] chains = null;
2146 StringTokenizer st = new StringTokenizer(param, " ");
2148 if (st.countTokens() < 2)
2150 String sequence = applet.getParameter("PDBSEQ");
2151 if (sequence != null)
2153 seqs = new SequenceI[] { matcher == null ? (Sequence) alignFrame
2154 .getAlignViewport().getAlignment().findName(sequence)
2155 : matcher.findIdMatch(sequence) };
2161 param = st.nextToken();
2162 List<SequenceI> tmp = new ArrayList<SequenceI>();
2163 List<String> tmp2 = new ArrayList<String>();
2165 while (st.hasMoreTokens())
2167 seqstring = st.nextToken();
2168 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
2169 if (st2.countTokens() > 1)
2171 // This is the chain
2172 tmp2.add(st2.nextToken());
2173 seqstring = st2.nextToken();
2175 tmp.add(matcher == null ? (Sequence) alignFrame
2176 .getAlignViewport().getAlignment()
2177 .findName(seqstring) : matcher.findIdMatch(seqstring));
2180 seqs = tmp.toArray(new SequenceI[tmp.size()]);
2181 if (tmp2.size() == tmp.size())
2183 chains = tmp2.toArray(new String[tmp2.size()]);
2186 param = resolveFileProtocol(param);
2187 // TODO check JAL-357 for files in a jar (CLASSLOADER)
2192 for (int i = 0; i < seqs.length; i++)
2194 if (seqs[i] != null)
2196 ((Sequence) seqs[i]).addPDBId(pdb);
2197 StructureSelectionManager.getStructureSelectionManager(
2198 applet).registerPDBEntry(pdb);
2202 if (JalviewLite.debug)
2204 // this may not really be a problem but we give a warning
2207 .println("Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
2213 if (!alignPdbStructures)
2215 alignFrame.newStructureView(applet, pdb, seqs, chains,
2220 pdbs.addElement(new Object[] { pdb, seqs, chains, protocol });
2226 } while (param != null || pdbFileCount < 10);
2227 if (pdbs.size() > 0)
2229 SequenceI[][] seqs = new SequenceI[pdbs.size()][];
2230 PDBEntry[] pdb = new PDBEntry[pdbs.size()];
2231 String[][] chains = new String[pdbs.size()][];
2232 String[] protocols = new String[pdbs.size()];
2233 for (int pdbsi = 0, pdbsiSize = pdbs.size(); pdbsi < pdbsiSize; pdbsi++)
2235 Object[] o = (Object[]) pdbs.elementAt(pdbsi);
2236 pdb[pdbsi] = (PDBEntry) o[0];
2237 seqs[pdbsi] = (SequenceI[]) o[1];
2238 chains[pdbsi] = (String[]) o[2];
2239 protocols[pdbsi] = (String) o[3];
2241 alignFrame.alignedStructureView(applet, pdb, seqs, chains,
2249 * Load in a Jnetfile if specified by parameter. Returns true if loaded,
2255 protected boolean loadJnetFile(AlignFrame alignFrame)
2257 boolean result = false;
2258 String param = applet.getParameter("jnetfile");
2261 // jnet became jpred around 2016
2262 param = applet.getParameter("jpredfile");
2268 param = resolveFileProtocol(param);
2269 JPredFile predictions = new JPredFile(param, protocol);
2270 JnetAnnotationMaker.add_annotation(predictions,
2271 alignFrame.viewport.getAlignment(), 0, false);
2272 // false == do not add sequence profile from concise output
2273 SequenceI repseq = alignFrame.viewport.getAlignment()
2275 alignFrame.viewport.getAlignment().setSeqrep(repseq);
2276 ColumnSelection cs = new ColumnSelection();
2277 cs.hideInsertionsFor(repseq);
2278 alignFrame.viewport.setColumnSelection(cs);
2279 alignFrame.alignPanel.fontChanged();
2280 alignFrame.alignPanel.setScrollValues(0, 0);
2282 } catch (Exception ex)
2284 ex.printStackTrace();
2291 * Load annotations if specified by parameter. Returns true if loaded, else
2297 protected boolean loadAnnotations(AlignFrame alignFrame)
2299 boolean result = false;
2300 String param = applet.getParameter("annotations");
2303 param = resolveFileProtocol(param);
2305 if (new AnnotationFile().annotateAlignmentView(alignFrame.viewport,
2308 alignFrame.alignPanel.fontChanged();
2309 alignFrame.alignPanel.setScrollValues(0, 0);
2315 .println("Annotations were not added from annotation file '"
2323 * Load features file and view settings as specified by parameters. Returns
2324 * true if features were loaded, else false.
2329 protected boolean loadFeatures(AlignFrame alignFrame)
2331 boolean result = false;
2332 // ///////////////////////////
2333 // modify display of features
2334 // we do this before any features have been loaded, ensuring any hidden
2335 // groups are hidden when features first displayed
2337 // hide specific groups
2339 String param = applet.getParameter("hidefeaturegroups");
2342 alignFrame.setFeatureGroupState(separatorListToArray(param), false);
2343 // applet.setFeatureGroupStateOn(newAlignFrame, param, false);
2345 // show specific groups
2346 param = applet.getParameter("showfeaturegroups");
2349 alignFrame.setFeatureGroupState(separatorListToArray(param), true);
2350 // applet.setFeatureGroupStateOn(newAlignFrame, param, true);
2352 // and now load features
2353 param = applet.getParameter("features");
2356 param = resolveFileProtocol(param);
2358 result = alignFrame.parseFeaturesFile(param, protocol);
2361 param = applet.getParameter("showFeatureSettings");
2362 if (param != null && param.equalsIgnoreCase(TRUE))
2364 alignFrame.viewport.setShowSequenceFeatures(true);
2365 new FeatureSettings(alignFrame.alignPanel);
2371 * Load a score file if specified by parameter. Returns true if file was
2372 * loaded, else false.
2376 protected boolean loadScoreFile(AlignFrame alignFrame)
2378 boolean result = false;
2379 String sScoreFile = applet.getParameter("scoreFile");
2380 if (sScoreFile != null && !"".equals(sScoreFile))
2387 .println("Attempting to load T-COFFEE score file from the scoreFile parameter");
2389 result = alignFrame.loadScoreFile(sScoreFile);
2393 .println("Failed to parse T-COFFEE parameter as a valid score file ('"
2394 + sScoreFile + "')");
2396 } catch (Exception e)
2398 System.err.printf("Cannot read score file: '%s'. Cause: %s \n",
2399 sScoreFile, e.getMessage());
2406 * Load a tree for the alignment if specified by parameter. Returns true if
2407 * a tree was loaded, else false.
2412 protected boolean loadTree(AlignFrame alignFrame)
2414 boolean result = false;
2415 String treeFile = applet.getParameter("tree");
2416 if (treeFile == null)
2418 treeFile = applet.getParameter("treeFile");
2421 if (treeFile != null)
2425 treeFile = resolveFileProtocol(treeFile);
2426 NewickFile fin = new NewickFile(treeFile, protocol);
2429 if (fin.getTree() != null)
2431 alignFrame.loadTree(fin, treeFile);
2433 dbgMsg("Successfully imported tree.");
2437 dbgMsg("Tree parameter did not resolve to a valid tree.");
2439 } catch (Exception ex)
2441 ex.printStackTrace();
2448 * Discovers whether the given file is in the Applet Archive
2454 boolean inArchive(String f)
2456 // This might throw a security exception in certain browsers
2457 // Netscape Communicator for instance.
2460 boolean rtn = (getClass().getResourceAsStream("/" + f) != null);
2463 System.err.println("Resource '" + f + "' was "
2464 + (rtn ? "" : "not ") + "located by classloader.");
2467 } catch (Exception ex)
2469 System.out.println("Exception checking resources: " + f + " " + ex);
2476 * @return the default alignFrame acted on by the public applet methods. May
2477 * return null with an error message on System.err indicating the
2480 public AlignFrame getDefaultTargetFrame()
2482 if (currentAlignFrame != null)
2484 return currentAlignFrame;
2486 if (initialAlignFrame != null)
2488 return initialAlignFrame;
2491 .println("Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
2496 * separator used for separatorList
2498 protected String separator = "" + ((char) 0x00AC); // the default used to be
2499 // '|' but many sequence
2500 // IDS include pipes.
2503 * set to enable the URL based javascript execution mechanism
2505 public boolean jsfallbackEnabled = false;
2508 * parse the string into a list
2511 * @return elements separated by separator
2513 public String[] separatorListToArray(String list)
2515 return separatorListToArray(list, separator);
2519 * parse the string into a list
2523 * @return elements separated by separator
2525 public static String[] separatorListToArray(String list, String separator)
2527 // TODO use StringUtils version (slightly different...)
2528 int seplen = separator.length();
2529 if (list == null || list.equals("") || list.equals(separator))
2533 java.util.Vector jv = new Vector();
2535 while ((pos = list.indexOf(separator, cp)) > cp)
2537 jv.addElement(list.substring(cp, pos));
2540 if (cp < list.length())
2542 String c = list.substring(cp);
2543 if (!c.equals(separator))
2550 String[] v = new String[jv.size()];
2551 for (int i = 0; i < v.length; i++)
2553 v[i] = (String) jv.elementAt(i);
2555 jv.removeAllElements();
2558 System.err.println("Array from '" + separator
2559 + "' separated List:\n" + v.length);
2560 for (int i = 0; i < v.length; i++)
2562 System.err.println("item " + i + " '" + v[i] + "'");
2569 System.err.println("Empty Array from '" + separator
2570 + "' separated List");
2576 * concatenate the list with separator
2579 * @return concatenated string
2581 public String arrayToSeparatorList(String[] list)
2583 return arrayToSeparatorList(list, separator);
2587 * concatenate the list with separator
2591 * @return concatenated string
2593 public static String arrayToSeparatorList(String[] list, String separator)
2595 // TODO use StringUtils version
2596 StringBuffer v = new StringBuffer();
2597 if (list != null && list.length > 0)
2599 for (int i = 0, iSize = list.length; i < iSize; i++)
2601 if (list[i] != null)
2605 v.append(separator);
2612 System.err.println("Returning '" + separator
2613 + "' separated List:\n");
2614 System.err.println(v);
2616 return v.toString();
2620 System.err.println("Returning empty '" + separator
2621 + "' separated List\n");
2623 return "" + separator;
2629 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroups()
2632 public String getFeatureGroups()
2634 String lst = arrayToSeparatorList(getDefaultTargetFrame()
2635 .getFeatureGroups());
2643 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOn(jalview.appletgui.AlignFrame
2647 public String getFeatureGroupsOn(AlignFrame alf)
2649 String lst = arrayToSeparatorList(alf.getFeatureGroups());
2656 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfState(boolean)
2659 public String getFeatureGroupsOfState(boolean visible)
2661 return arrayToSeparatorList(getDefaultTargetFrame()
2662 .getFeatureGroupsOfState(visible));
2669 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfStateOn(jalview.appletgui
2670 * .AlignFrame, boolean)
2673 public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
2675 return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
2681 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupStateOn(jalview.appletgui.
2682 * AlignFrame, java.lang.String, boolean)
2685 public void setFeatureGroupStateOn(final AlignFrame alf,
2686 final String groups, boolean state)
2688 final boolean st = state;// !(state==null || state.equals("") ||
2689 // state.toLowerCase().equals("false"));
2690 java.awt.EventQueue.invokeLater(new Runnable()
2695 alf.setFeatureGroupState(separatorListToArray(groups), st);
2703 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupState(java.lang.String,
2707 public void setFeatureGroupState(String groups, boolean state)
2709 setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
2715 * @see jalview.bin.JalviewLiteJsApi#getSeparator()
2718 public String getSeparator()
2726 * @see jalview.bin.JalviewLiteJsApi#setSeparator(java.lang.String)
2729 public void setSeparator(String separator)
2731 if (separator == null || separator.length() < 1)
2734 separator = "" + ((char) 0x00AC);
2736 this.separator = separator;
2739 System.err.println("Default Separator now: '" + separator + "'");
2744 * get boolean value of applet parameter 'name' and return default if
2745 * parameter is not set
2750 * the value to return otherwise
2751 * @return true or false
2753 public boolean getDefaultParameter(String name, boolean def)
2756 if ((stn = getParameter(name)) == null)
2760 if (TRUE.equalsIgnoreCase(stn))
2770 * @see jalview.bin.JalviewLiteJsApi#addPdbFile(jalview.appletgui.AlignFrame,
2771 * java.lang.String, java.lang.String, java.lang.String)
2774 public boolean addPdbFile(AlignFrame alFrame, String sequenceId,
2775 String pdbEntryString, String pdbFile)
2777 return alFrame.addPdbFile(sequenceId, pdbEntryString, pdbFile);
2780 protected void setAlignPdbStructures(boolean alignPdbStructures)
2782 this.alignPdbStructures = alignPdbStructures;
2785 public boolean isAlignPdbStructures()
2787 return alignPdbStructures;
2793 // callInitCallback();
2796 private Hashtable<String, long[]> jshashes = new Hashtable<String, long[]>();
2798 private Hashtable<String, Hashtable<String, String[]>> jsmessages = new Hashtable<String, Hashtable<String, String[]>>();
2800 public void setJsMessageSet(String messageclass, String viewId,
2801 String[] colcommands)
2803 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2806 msgset = new Hashtable<String, String[]>();
2807 jsmessages.put(messageclass, msgset);
2809 msgset.put(viewId, colcommands);
2810 long[] l = new long[colcommands.length];
2811 for (int i = 0; i < colcommands.length; i++)
2813 l[i] = colcommands[i].hashCode();
2815 jshashes.put(messageclass + "|" + viewId, l);
2821 * @see jalview.bin.JalviewLiteJsApi#getJsMessage(java.lang.String,
2825 public String getJsMessage(String messageclass, String viewId)
2827 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2830 String[] msgs = msgset.get(viewId);
2833 for (int i = 0; i < msgs.length; i++)
2835 if (msgs[i] != null)
2847 public boolean isJsMessageSetChanged(String string, String string2,
2848 String[] colcommands)
2850 long[] l = jshashes.get(string + "|" + string2);
2851 if (l == null && colcommands != null)
2855 for (int i = 0; i < colcommands.length; i++)
2857 if (l[i] != colcommands[i].hashCode())
2865 private Vector jsExecQueue = new Vector();
2867 public Vector getJsExecQueue()
2872 public void setExecutor(JSFunctionExec jsFunctionExec2)
2874 jsFunctionExec = jsFunctionExec2;
2878 * return the given colour value parameter or the given default if parameter
2885 public Color getDefaultColourParameter(String colparam, Color defcolour)
2887 String colprop = getParameter(colparam);
2888 if (colprop == null || colprop.trim().length() == 0)
2892 Color col = ColorUtils.parseColourString(colprop);
2895 System.err.println("Couldn't parse '" + colprop
2896 + "' as a colour for " + colparam);
2898 return (col == null) ? defcolour : col;
2901 public void openJalviewHelpUrl()
2903 String helpUrl = getParameter("jalviewhelpurl");
2904 if (helpUrl == null || helpUrl.trim().length() < 5)
2906 helpUrl = "http://www.jalview.org/help.html";
2908 showURL(helpUrl, "HELP");
2912 * form a complete URL given a path to a resource and a reference location on
2916 * - an absolute path on the same server as localref or a document
2917 * located relative to localref
2919 * - a URL on the same server as url
2920 * @return a complete URL for the resource located by url
2922 private String resolveUrlForLocalOrAbsolute(String targetPath,
2925 String resolvedPath = "";
2926 if (targetPath.startsWith("/"))
2928 String codebase = localref.toString();
2929 String localfile = localref.getFile();
2930 resolvedPath = codebase.substring(0,
2931 codebase.length() - localfile.length())
2933 return resolvedPath;
2937 * get URL path and strip off any trailing file e.g.
2938 * www.jalview.org/examples/index.html#applets?a=b is trimmed to
2939 * www.jalview.org/examples/
2941 String urlPath = localref.toString();
2942 String directoryPath = urlPath;
2943 int lastSeparator = directoryPath.lastIndexOf("/");
2944 if (lastSeparator > 0)
2946 directoryPath = directoryPath.substring(0, lastSeparator + 1);
2949 if (targetPath.startsWith("/"))
2952 * construct absolute URL to a file on the server - this is not allowed?
2954 // String localfile = localref.getFile();
2955 // resolvedPath = urlPath.substring(0,
2956 // urlPath.length() - localfile.length())
2958 resolvedPath = directoryPath + targetPath.substring(1);
2962 resolvedPath = directoryPath + targetPath;
2966 System.err.println("resolveUrlForLocalOrAbsolute returning "
2969 return resolvedPath;
2973 * open a URL in the browser - resolving it according to relative refs and
2974 * coping with javascript: protocol if necessary.
2979 public void showURL(String url, String target)
2983 if (url.indexOf(":") == -1)
2985 // TODO: verify (Bas Vroling bug) prepend codebase or server URL to
2987 // Should really use docbase, not codebase.
2989 url = resolveUrlForLocalOrAbsolute(
2991 prepend = getDefaultParameter("resolvetocodebase", false) ? getCodeBase()
2992 : getDocumentBase());
2996 .println("Show url (prepended "
2998 + " - toggle resolvetocodebase if code/docbase resolution is wrong): "
3006 System.err.println("Show url: " + url);
3009 if (url.indexOf("javascript:") == 0)
3011 // no target for the javascript context
3012 getAppletContext().showDocument(new java.net.URL(url));
3016 getAppletContext().showDocument(new java.net.URL(url), target);
3018 } catch (Exception ex)
3020 ex.printStackTrace();
3025 * bind structures in a viewer to any matching sequences in an alignFrame (use
3026 * sequenceIds to limit scope of search to specific sequences)
3030 * @param sequenceIds
3031 * @return TODO: consider making an exception structure for indicating when
3032 * binding fails public SequenceStructureBinding
3033 * addStructureViewInstance( AlignFrame alFrame, Object viewer, String
3036 * if (sequenceIds != null && sequenceIds.length() > 0) { return
3037 * alFrame.addStructureViewInstance(viewer,
3038 * separatorListToArray(sequenceIds)); } else { return
3039 * alFrame.addStructureViewInstance(viewer, null); } // return null; }