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.FileParse;
41 import jalview.io.IdentifyFile;
42 import jalview.io.JPredFile;
43 import jalview.io.JnetAnnotationMaker;
44 import jalview.io.NewickFile;
45 import jalview.javascript.JSFunctionExec;
46 import jalview.javascript.JalviewLiteJsApi;
47 import jalview.javascript.JsCallBack;
48 import jalview.javascript.MouseOverStructureListener;
49 import jalview.structure.SelectionListener;
50 import jalview.structure.StructureSelectionManager;
51 import jalview.util.HttpUtils;
52 import jalview.util.MessageManager;
54 import java.applet.Applet;
55 import java.awt.Button;
56 import java.awt.Color;
57 import java.awt.Component;
58 import java.awt.EventQueue;
60 import java.awt.Frame;
61 import java.awt.Graphics;
62 import java.awt.event.ActionEvent;
63 import java.awt.event.WindowAdapter;
64 import java.awt.event.WindowEvent;
65 import java.io.BufferedReader;
66 import java.io.InputStreamReader;
68 import java.util.ArrayList;
69 import java.util.Hashtable;
70 import java.util.List;
71 import java.util.StringTokenizer;
72 import java.util.Vector;
74 import netscape.javascript.JSObject;
77 * Jalview Applet. Runs in Java 1.18 runtime
80 * @version $Revision: 1.92 $
82 public class JalviewLite extends Applet implements
83 StructureSelectionManagerProvider, JalviewLiteJsApi
86 private static final String TRUE = "true";
88 private static final String FALSE = "false";
90 public StructureSelectionManager getStructureSelectionManager()
92 return StructureSelectionManager.getStructureSelectionManager(this);
95 // /////////////////////////////////////////
96 // The following public methods may be called
97 // externally, eg via javascript in HTML page
101 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences()
103 public String getSelectedSequences()
105 return getSelectedSequencesFrom(getDefaultTargetFrame());
111 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences(java.lang.String)
113 public String getSelectedSequences(String sep)
115 return getSelectedSequencesFrom(getDefaultTargetFrame(), sep);
122 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
125 public String getSelectedSequencesFrom(AlignFrame alf)
127 return getSelectedSequencesFrom(alf, separator); // ""+0x00AC);
134 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
135 * .AlignFrame, java.lang.String)
137 public String getSelectedSequencesFrom(AlignFrame alf, String sep)
139 StringBuffer result = new StringBuffer("");
140 if (sep == null || sep.length() == 0)
142 sep = separator; // "+0x00AC;
144 if (alf.viewport.getSelectionGroup() != null)
146 SequenceI[] seqs = alf.viewport.getSelectionGroup()
147 .getSequencesInOrder(alf.viewport.getAlignment());
149 for (int i = 0; i < seqs.length; i++)
151 result.append(seqs[i].getName());
156 return result.toString();
162 * @see jalview.bin.JalviewLiteJsApi#highlight(java.lang.String,
163 * java.lang.String, java.lang.String)
165 public void highlight(String sequenceId, String position,
166 String alignedPosition)
168 highlightIn(getDefaultTargetFrame(), sequenceId, position,
175 * @see jalview.bin.JalviewLiteJsApi#highlightIn(jalview.appletgui.AlignFrame,
176 * java.lang.String, java.lang.String, java.lang.String)
178 public void highlightIn(final AlignFrame alf, final String sequenceId,
179 final String position, final String alignedPosition)
181 // TODO: could try to highlight in all alignments if alf==null
182 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
183 alf.viewport.getAlignment().getSequencesArray());
184 final SequenceI sq = matcher.findIdMatch(sequenceId);
190 apos = new Integer(position).intValue();
192 } catch (NumberFormatException ex)
196 final StructureSelectionManagerProvider me = this;
197 final int pos = apos;
198 // use vamsas listener to broadcast to all listeners in scope
199 if (alignedPosition != null
200 && (alignedPosition.trim().length() == 0 || alignedPosition
201 .toLowerCase().indexOf("false") > -1))
203 java.awt.EventQueue.invokeLater(new Runnable()
208 StructureSelectionManager.getStructureSelectionManager(me)
209 .mouseOverVamsasSequence(sq, sq.findIndex(pos), null);
215 java.awt.EventQueue.invokeLater(new Runnable()
220 StructureSelectionManager.getStructureSelectionManager(me)
221 .mouseOverVamsasSequence(sq, pos, null);
231 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
234 public void select(String sequenceIds, String columns)
236 selectIn(getDefaultTargetFrame(), sequenceIds, columns, separator);
242 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
243 * java.lang.String, java.lang.String)
245 public void select(String sequenceIds, String columns, String sep)
247 selectIn(getDefaultTargetFrame(), sequenceIds, columns, sep);
253 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
254 * java.lang.String, java.lang.String)
256 public void selectIn(AlignFrame alf, String sequenceIds, String columns)
258 selectIn(alf, sequenceIds, columns, separator);
264 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
265 * java.lang.String, java.lang.String, java.lang.String)
267 public void selectIn(final AlignFrame alf, String sequenceIds,
268 String columns, String sep)
270 if (sep == null || sep.length() == 0)
278 System.err.println("Selecting region using separator string '"
283 String[] ids = separatorListToArray(sequenceIds, sep);
284 String[] cols = separatorListToArray(columns, sep);
285 final SequenceGroup sel = new SequenceGroup();
286 final ColumnSelection csel = new ColumnSelection();
287 AlignmentI al = alf.viewport.getAlignment();
288 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
289 alf.viewport.getAlignment().getSequencesArray());
290 int start = 0, end = al.getWidth(), alw = al.getWidth();
291 boolean seqsfound = true;
292 if (ids != null && ids.length > 0)
295 for (int i = 0; i < ids.length; i++)
297 if (ids[i].trim().length() == 0)
301 SequenceI sq = matcher.findIdMatch(ids[i]);
305 sel.addSequence(sq, false);
309 boolean inseqpos = false;
310 if (cols != null && cols.length > 0)
312 boolean seset = false;
313 for (int i = 0; i < cols.length; i++)
315 String cl = cols[i].trim();
316 if (cl.length() == 0)
321 if ((p = cl.indexOf("-")) > -1)
323 int from = -1, to = -1;
326 from = new Integer(cl.substring(0, p)).intValue();
328 } catch (NumberFormatException ex)
331 .println("ERROR: Couldn't parse first integer in range element column selection string '"
332 + cl + "' - format is 'from-to'");
337 to = new Integer(cl.substring(p + 1)).intValue();
339 } catch (NumberFormatException ex)
342 .println("ERROR: Couldn't parse second integer in range element column selection string '"
343 + cl + "' - format is 'from-to'");
346 if (from >= 0 && to >= 0)
363 // comment to prevent range extension
373 for (int r = from; r <= to; r++)
375 if (r >= 0 && r < alw)
382 System.err.println("Range '" + cl + "' deparsed as [" + from
388 System.err.println("ERROR: Invalid Range '" + cl
389 + "' deparsed as [" + from + "," + to + "]");
397 r = new Integer(cl).intValue();
399 } catch (NumberFormatException ex)
401 if (cl.toLowerCase().equals("sequence"))
403 // we are in the dataset sequence's coordinate frame.
409 .println("ERROR: Couldn't parse integer from point selection element of column selection string '"
414 if (r >= 0 && r <= alw)
424 // comment to prevent range extension
437 System.err.println("Point selection '" + cl
438 + "' deparsed as [" + r + "]");
443 System.err.println("ERROR: Invalid Point selection '" + cl
444 + "' deparsed as [" + r + "]");
451 // we only propagate the selection when it was the null selection, or the
452 // given sequences were found in the alignment.
453 if (inseqpos && sel.getSize() > 0)
455 // assume first sequence provides reference frame ?
456 SequenceI rs = sel.getSequenceAt(0);
457 start = rs.findIndex(start);
458 end = rs.findIndex(end);
461 List<Integer> cs = csel.getSelected();
462 // note - the following actually clears cs as well, since
463 // csel.getSelected returns a reference. Need to check if we need to
464 // have a concurrentModification exception thrown here
466 for (Integer selectedCol : cs)
468 csel.addElement(rs.findIndex(selectedCol));
472 sel.setStartRes(start);
474 EventQueue.invokeLater(new Runnable()
479 alf.select(sel, csel);
489 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignment(java.lang.
490 * String, java.lang.String)
492 public String getSelectedSequencesAsAlignment(String format, String suffix)
494 return getSelectedSequencesAsAlignmentFrom(getDefaultTargetFrame(),
502 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignmentFrom(jalview
503 * .appletgui.AlignFrame, java.lang.String, java.lang.String)
505 public String getSelectedSequencesAsAlignmentFrom(AlignFrame alf,
506 String format, String suffix)
510 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
511 if (alf.viewport.getSelectionGroup() != null)
513 // JBPNote: getSelectionAsNewSequence behaviour has changed - this
514 // method now returns a full copy of sequence data
515 // TODO consider using getSequenceSelection instead here
516 String reply = new AppletFormatAdapter().formatSequences(format,
517 new Alignment(alf.viewport.getSelectionAsNewSequence()),
521 } catch (Exception ex)
523 ex.printStackTrace();
524 return "Error retrieving alignment in " + format + " format. ";
532 * @see jalview.bin.JalviewLiteJsApi#getAlignmentOrder()
534 public String getAlignmentOrder()
536 return getAlignmentOrderFrom(getDefaultTargetFrame());
543 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
546 public String getAlignmentOrderFrom(AlignFrame alf)
548 return getAlignmentOrderFrom(alf, separator);
555 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
556 * , java.lang.String)
558 public String getAlignmentOrderFrom(AlignFrame alf, String sep)
560 AlignmentI alorder = alf.getAlignViewport().getAlignment();
561 String[] order = new String[alorder.getHeight()];
562 for (int i = 0; i < order.length; i++)
564 order[i] = alorder.getSequenceAt(i).getName();
566 return arrayToSeparatorList(order);
572 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
575 public String orderBy(String order, String undoName)
577 return orderBy(order, undoName, separator);
583 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
584 * java.lang.String, java.lang.String)
586 public String orderBy(String order, String undoName, String sep)
588 return orderAlignmentBy(getDefaultTargetFrame(), order, undoName, sep);
595 * jalview.bin.JalviewLiteJsApi#orderAlignmentBy(jalview.appletgui.AlignFrame,
596 * java.lang.String, java.lang.String, java.lang.String)
598 public String orderAlignmentBy(AlignFrame alf, String order,
599 String undoName, String sep)
601 String[] ids = separatorListToArray(order, sep);
602 SequenceI[] sqs = null;
603 if (ids != null && ids.length > 0)
605 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
606 alf.viewport.getAlignment().getSequencesArray());
608 sqs = new SequenceI[ids.length];
609 for (int i = 0; i < ids.length; i++)
611 if (ids[i].trim().length() == 0)
615 SequenceI sq = matcher.findIdMatch(ids[i]);
623 SequenceI[] sqq = new SequenceI[s];
624 System.arraycopy(sqs, 0, sqq, 0, s);
637 final AlignmentOrder aorder = new AlignmentOrder(sqs);
639 if (undoName != null && undoName.trim().length() == 0)
643 final String _undoName = undoName;
644 // TODO: deal with synchronization here: cannot raise any events until after
645 // this has returned.
646 return alf.sortBy(aorder, _undoName) ? TRUE : "";
652 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String)
654 public String getAlignment(String format)
656 return getAlignmentFrom(getDefaultTargetFrame(), format, TRUE);
663 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
666 public String getAlignmentFrom(AlignFrame alf, String format)
668 return getAlignmentFrom(alf, format, TRUE);
674 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String,
677 public String getAlignment(String format, String suffix)
679 return getAlignmentFrom(getDefaultTargetFrame(), format, suffix);
686 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
687 * java.lang.String, java.lang.String)
689 public String getAlignmentFrom(AlignFrame alf, String format,
694 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
696 String reply = new AppletFormatAdapter().formatSequences(format,
697 alf.viewport.getAlignment(), seqlimits);
699 } catch (Exception ex)
701 ex.printStackTrace();
702 return "Error retrieving alignment in " + format + " format. ";
709 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
711 public void loadAnnotation(String annotation)
713 loadAnnotationFrom(getDefaultTargetFrame(), annotation);
720 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
721 * , java.lang.String)
723 public void loadAnnotationFrom(AlignFrame alf, String annotation)
725 if (new AnnotationFile().annotateAlignmentView(alf.getAlignViewport(),
726 annotation, AppletFormatAdapter.PASTE))
728 alf.alignPanel.fontChanged();
729 alf.alignPanel.setScrollValues(0, 0);
733 alf.parseFeaturesFile(annotation, AppletFormatAdapter.PASTE);
740 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
742 public void loadFeatures(String features, boolean autoenabledisplay)
744 loadFeaturesFrom(getDefaultTargetFrame(), features, autoenabledisplay);
751 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
752 * , java.lang.String)
754 public boolean loadFeaturesFrom(AlignFrame alf, String features,
755 boolean autoenabledisplay)
757 return alf.parseFeaturesFile(features, AppletFormatAdapter.PASTE,
764 * @see jalview.bin.JalviewLiteJsApi#getFeatures(java.lang.String)
766 public String getFeatures(String format)
768 return getFeaturesFrom(getDefaultTargetFrame(), format);
775 * jalview.bin.JalviewLiteJsApi#getFeaturesFrom(jalview.appletgui.AlignFrame,
778 public String getFeaturesFrom(AlignFrame alf, String format)
780 return alf.outputFeatures(false, format);
786 * @see jalview.bin.JalviewLiteJsApi#getAnnotation()
788 public String getAnnotation()
790 return getAnnotationFrom(getDefaultTargetFrame());
797 * jalview.bin.JalviewLiteJsApi#getAnnotationFrom(jalview.appletgui.AlignFrame
800 public String getAnnotationFrom(AlignFrame alf)
802 return alf.outputAnnotations(false);
808 * @see jalview.bin.JalviewLiteJsApi#newView()
810 public AlignFrame newView()
812 return newViewFrom(getDefaultTargetFrame());
818 * @see jalview.bin.JalviewLiteJsApi#newView(java.lang.String)
820 public AlignFrame newView(String name)
822 return newViewFrom(getDefaultTargetFrame(), name);
828 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame)
830 public AlignFrame newViewFrom(AlignFrame alf)
832 return alf.newView(null);
838 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame,
841 public AlignFrame newViewFrom(AlignFrame alf, String name)
843 return alf.newView(name);
849 * @see jalview.bin.JalviewLiteJsApi#loadAlignment(java.lang.String,
852 public AlignFrame loadAlignment(String text, String title)
854 AlignmentI al = null;
856 String format = new IdentifyFile().identify(text,
857 AppletFormatAdapter.PASTE);
860 al = new AppletFormatAdapter().readFile(text,
861 AppletFormatAdapter.PASTE, format);
862 if (al.getHeight() > 0)
864 return new AlignFrame(al, this, title, false);
866 } catch (java.io.IOException ex)
868 ex.printStackTrace();
876 * @see jalview.bin.JalviewLiteJsApi#setMouseoverListener(java.lang.String)
878 public void setMouseoverListener(String listener)
880 setMouseoverListener(currentAlignFrame, listener);
883 private Vector<jalview.javascript.JSFunctionExec> javascriptListeners = new Vector<jalview.javascript.JSFunctionExec>();
889 * jalview.bin.JalviewLiteJsApi#setMouseoverListener(jalview.appletgui.AlignFrame
890 * , java.lang.String)
892 public void setMouseoverListener(AlignFrame af, String listener)
894 if (listener != null)
896 listener = listener.trim();
897 if (listener.length() == 0)
900 .println("jalview Javascript error: Ignoring empty function for mouseover listener.");
904 jalview.javascript.MouseOverListener mol = new jalview.javascript.MouseOverListener(
906 javascriptListeners.addElement(mol);
907 StructureSelectionManager.getStructureSelectionManager(this)
908 .addStructureViewerListener(mol);
911 System.err.println("Added a mouseover listener for "
912 + ((af == null) ? "All frames" : "Just views for "
913 + af.getAlignViewport().getSequenceSetId()));
914 System.err.println("There are now " + javascriptListeners.size()
915 + " listeners in total.");
922 * @see jalview.bin.JalviewLiteJsApi#setSelectionListener(java.lang.String)
924 public void setSelectionListener(String listener)
926 setSelectionListener(null, listener);
933 * jalview.bin.JalviewLiteJsApi#setSelectionListener(jalview.appletgui.AlignFrame
934 * , java.lang.String)
936 public void setSelectionListener(AlignFrame af, String listener)
938 if (listener != null)
940 listener = listener.trim();
941 if (listener.length() == 0)
944 .println("jalview Javascript error: Ignoring empty function for selection listener.");
948 jalview.javascript.JsSelectionSender mol = new jalview.javascript.JsSelectionSender(
950 javascriptListeners.addElement(mol);
951 StructureSelectionManager.getStructureSelectionManager(this)
952 .addSelectionListener(mol);
955 System.err.println("Added a selection listener for "
956 + ((af == null) ? "All frames" : "Just views for "
957 + af.getAlignViewport().getSequenceSetId()));
958 System.err.println("There are now " + javascriptListeners.size()
959 + " listeners in total.");
964 * Callable from javascript to register a javascript function to pass events
965 * to a structure viewer.
968 * the name of a javascript function
970 * a token separated list of PDB file names listened for
971 * @see jalview.bin.JalviewLiteJsApi#setStructureListener(java.lang.String,
974 public void setStructureListener(String listener, String modelSet)
976 if (listener != null)
978 listener = listener.trim();
979 if (listener.length() == 0)
982 .println("jalview Javascript error: Ignoring empty function for selection listener.");
986 MouseOverStructureListener mol = new MouseOverStructureListener(this,
987 listener, separatorListToArray(modelSet));
988 javascriptListeners.addElement(mol);
989 StructureSelectionManager.getStructureSelectionManager(this)
990 .addStructureViewerListener(mol);
993 System.err.println("Added a javascript structure viewer listener '"
995 System.err.println("There are now " + javascriptListeners.size()
996 + " listeners in total.");
1004 * jalview.bin.JalviewLiteJsApi#removeJavascriptListener(jalview.appletgui
1005 * .AlignFrame, java.lang.String)
1007 public void removeJavascriptListener(AlignFrame af, String listener)
1009 if (listener != null)
1011 listener = listener.trim();
1012 if (listener.length() == 0)
1017 boolean rprt = false;
1018 for (int ms = 0, msSize = javascriptListeners.size(); ms < msSize;)
1020 Object lstn = javascriptListeners.elementAt(ms);
1021 JsCallBack lstner = (JsCallBack) lstn;
1022 if ((af == null || lstner.getAlignFrame() == af)
1023 && (listener == null || lstner.getListenerFunction().equals(
1026 javascriptListeners.removeElement(lstner);
1028 if (lstner instanceof SelectionListener)
1030 StructureSelectionManager.getStructureSelectionManager(this)
1031 .removeSelectionListener((SelectionListener) lstner);
1035 StructureSelectionManager.getStructureSelectionManager(this)
1036 .removeStructureViewerListener(lstner, null);
1041 System.err.println("Removed listener '" + listener + "'");
1051 System.err.println("There are now " + javascriptListeners.size()
1052 + " listeners in total.");
1058 System.err.println("Applet " + getName() + " stop().");
1062 public void destroy()
1064 System.err.println("Applet " + getName() + " destroy().");
1068 private void tidyUp()
1071 if (currentAlignFrame != null && currentAlignFrame.viewport != null
1072 && currentAlignFrame.viewport.applet != null)
1074 AlignViewport av = currentAlignFrame.viewport;
1075 currentAlignFrame.closeMenuItem_actionPerformed();
1077 currentAlignFrame = null;
1079 if (javascriptListeners != null)
1081 while (javascriptListeners.size() > 0)
1083 jalview.javascript.JSFunctionExec mol = javascriptListeners
1085 javascriptListeners.removeElement(mol);
1086 if (mol instanceof SelectionListener)
1088 StructureSelectionManager.getStructureSelectionManager(this)
1089 .removeSelectionListener((SelectionListener) mol);
1093 StructureSelectionManager.getStructureSelectionManager(this)
1094 .removeStructureViewerListener(mol, null);
1099 if (jsFunctionExec != null)
1101 jsFunctionExec.stopQueue();
1102 jsFunctionExec.jvlite = null;
1104 initialAlignFrame = null;
1105 jsFunctionExec = null;
1106 javascriptListeners = null;
1107 StructureSelectionManager.release(this);
1110 private jalview.javascript.JSFunctionExec jsFunctionExec;
1115 * @see jalview.bin.JalviewLiteJsApi#mouseOverStructure(java.lang.String,
1116 * java.lang.String, java.lang.String)
1118 public void mouseOverStructure(final String pdbResNum,
1119 final String chain, final String pdbfile)
1121 final StructureSelectionManagerProvider me = this;
1122 java.awt.EventQueue.invokeLater(new Runnable()
1129 StructureSelectionManager.getStructureSelectionManager(me)
1130 .mouseOverStructure(new Integer(pdbResNum).intValue(),
1134 System.err.println("mouseOver for '" + pdbResNum
1135 + "' in chain '" + chain + "' in structure '" + pdbfile
1138 } catch (NumberFormatException e)
1140 System.err.println("Ignoring invalid residue number string '"
1152 * jalview.bin.JalviewLiteJsApi#scrollViewToIn(jalview.appletgui.AlignFrame,
1153 * java.lang.String, java.lang.String)
1155 public void scrollViewToIn(final AlignFrame alf, final String topRow,
1156 final String leftHandColumn)
1158 java.awt.EventQueue.invokeLater(new Runnable()
1165 alf.scrollTo(new Integer(topRow).intValue(), new Integer(
1166 leftHandColumn).intValue());
1168 } catch (Exception ex)
1170 System.err.println("Couldn't parse integer arguments (topRow='"
1171 + topRow + "' and leftHandColumn='" + leftHandColumn
1173 ex.printStackTrace();
1183 * jalview.javascript.JalviewLiteJsApi#scrollViewToRowIn(jalview.appletgui
1184 * .AlignFrame, java.lang.String)
1187 public void scrollViewToRowIn(final AlignFrame alf, final String topRow)
1190 java.awt.EventQueue.invokeLater(new Runnable()
1197 alf.scrollToRow(new Integer(topRow).intValue());
1199 } catch (Exception ex)
1201 System.err.println("Couldn't parse integer arguments (topRow='"
1203 ex.printStackTrace();
1214 * jalview.javascript.JalviewLiteJsApi#scrollViewToColumnIn(jalview.appletgui
1215 * .AlignFrame, java.lang.String)
1218 public void scrollViewToColumnIn(final AlignFrame alf,
1219 final String leftHandColumn)
1221 java.awt.EventQueue.invokeLater(new Runnable()
1229 alf.scrollToColumn(new Integer(leftHandColumn).intValue());
1231 } catch (Exception ex)
1234 .println("Couldn't parse integer arguments (leftHandColumn='"
1235 + leftHandColumn + "')");
1236 ex.printStackTrace();
1243 // //////////////////////////////////////////////
1244 // //////////////////////////////////////////////
1246 public static int lastFrameX = 200;
1248 public static int lastFrameY = 200;
1250 boolean fileFound = true;
1252 String file = "No file";
1254 String file2 = null;
1256 Button launcher = new Button(
1257 MessageManager.getString("label.start_jalview"));
1260 * The currentAlignFrame is static, it will change if and when the user
1261 * selects a new window. Note that it will *never* point back to the embedded
1262 * AlignFrame if the applet is started as embedded on the page and then
1263 * afterwards a new view is created.
1265 public AlignFrame currentAlignFrame = null;
1268 * This is the first frame to be displayed, and does not change. API calls
1269 * will default to this instance if currentAlignFrame is null.
1271 AlignFrame initialAlignFrame = null;
1273 boolean embedded = false;
1275 private boolean checkForJmol = true;
1277 private boolean checkedForJmol = false; // ensure we don't check for jmol
1279 // every time the app is re-inited
1281 public boolean jmolAvailable = false;
1283 private boolean alignPdbStructures = false;
1286 * use an external structure viewer exclusively (no jmols or MCViews will be
1287 * opened by JalviewLite itself)
1289 public boolean useXtrnalSviewer = false;
1291 public static boolean debug = false;
1293 static String builddate = null, version = null, installation = null;
1295 private static void initBuildDetails()
1297 if (builddate == null)
1299 builddate = "unknown";
1301 installation = "applet";
1302 java.net.URL url = JalviewLite.class
1303 .getResource("/.build_properties");
1308 BufferedReader reader = new BufferedReader(new InputStreamReader(
1311 while ((line = reader.readLine()) != null)
1313 if (line.indexOf("VERSION") > -1)
1315 version = line.substring(line.indexOf("=") + 1);
1317 if (line.indexOf("BUILD_DATE") > -1)
1319 builddate = line.substring(line.indexOf("=") + 1);
1321 if (line.indexOf("INSTALLATION") > -1)
1323 installation = line.substring(line.indexOf("=") + 1);
1326 } catch (Exception ex)
1328 ex.printStackTrace();
1334 public static String getBuildDate()
1340 public static String getInstallation()
1343 return installation;
1346 public static String getVersion()
1352 // public JSObject scriptObject = null;
1355 * init method for Jalview Applet
1360 debug = TRUE.equalsIgnoreCase(getParameter("debug"));
1365 System.err.println("Applet context is '"
1366 + getAppletContext().getClass().toString() + "'");
1368 JSObject scriptObject = JSObject.getWindow(this);
1369 if (debug && scriptObject != null)
1371 System.err.println("Applet has Javascript callback support.");
1374 } catch (Exception ex)
1377 .println("Warning: No JalviewLite javascript callbacks available.");
1380 ex.printStackTrace();
1386 System.err.println("JalviewLite Version " + getVersion());
1387 System.err.println("Build Date : " + getBuildDate());
1388 System.err.println("Installation : " + getInstallation());
1390 String externalsviewer = getParameter("externalstructureviewer");
1391 if (externalsviewer != null)
1393 useXtrnalSviewer = externalsviewer.trim().toLowerCase().equals(TRUE);
1396 * if true disable the check for jmol
1398 String chkforJmol = getParameter("nojmol");
1399 if (chkforJmol != null)
1401 checkForJmol = !chkforJmol.equals(TRUE);
1404 * get the separator parameter if present
1406 String sep = getParameter("separator");
1409 if (sep.length() > 0)
1414 System.err.println("Separator set to '" + separator + "'");
1421 .getString("error.invalid_separator_parameter"));
1427 String param = getParameter("RGB");
1433 r = Integer.parseInt(param.substring(0, 2), 16);
1434 g = Integer.parseInt(param.substring(2, 4), 16);
1435 b = Integer.parseInt(param.substring(4, 6), 16);
1436 } catch (Exception ex)
1443 param = getParameter("label");
1446 launcher.setLabel(param);
1449 setBackground(new Color(r, g, b));
1451 file = getParameter("file");
1455 // Maybe the sequences are added as parameters
1456 StringBuffer data = new StringBuffer("PASTE");
1458 while ((file = getParameter("sequence" + i)) != null)
1460 data.append(file.toString() + "\n");
1463 if (data.length() > 5)
1465 file = data.toString();
1468 if (getDefaultParameter("enableSplitFrame", true))
1470 file2 = getParameter("file2");
1473 embedded = TRUE.equalsIgnoreCase(getParameter("embedded"));
1476 LoadingThread loader = new LoadingThread(file, file2, this);
1479 else if (file != null)
1482 * Start the applet immediately or show a button to start it
1484 if (FALSE.equalsIgnoreCase(getParameter("showbutton")))
1486 LoadingThread loader = new LoadingThread(file, file2, this);
1492 launcher.addActionListener(new java.awt.event.ActionListener()
1494 public void actionPerformed(ActionEvent e)
1496 LoadingThread loader = new LoadingThread(file, file2,
1505 // jalview initialisation with no alignment. loadAlignment() method can
1506 // still be called to open new alignments.
1513 private void initLiveConnect()
1515 // try really hard to get the liveConnect thing working
1516 boolean notFailed = false;
1518 while (!notFailed && tries < 10)
1522 System.err.println("LiveConnect request thread going to sleep.");
1526 Thread.sleep(700 * (1 + tries));
1527 } catch (InterruptedException q)
1533 System.err.println("LiveConnect request thread woken up.");
1537 JSObject scriptObject = JSObject.getWindow(this);
1538 if (scriptObject.eval("navigator") != null)
1542 } catch (Exception jsex)
1544 System.err.println("Attempt " + tries
1545 + " to access LiveConnect javascript failed.");
1550 private void callInitCallback()
1552 String initjscallback = getParameter("oninit");
1553 if (initjscallback == null)
1557 initjscallback = initjscallback.trim();
1558 if (initjscallback.length() > 0)
1560 JSObject scriptObject = null;
1563 scriptObject = JSObject.getWindow(this);
1564 } catch (Exception ex)
1568 // try really hard to let the browser plugin know we want liveconnect
1571 if (scriptObject != null)
1575 // do onInit with the JS executor thread
1576 new JSFunctionExec(this).executeJavascriptFunction(true,
1577 initjscallback, null, "Calling oninit callback '"
1578 + initjscallback + "'.");
1579 } catch (Exception e)
1581 System.err.println("Exception when executing _oninit callback '"
1582 + initjscallback + "'.");
1583 e.printStackTrace();
1588 System.err.println("Not executing _oninit callback '"
1589 + initjscallback + "' - no scripting allowed.");
1595 * Initialises and displays a new java.awt.Frame
1598 * java.awt.Frame to be displayed
1600 * title of new frame
1602 * width if new frame
1604 * height of new frame
1606 public static void addFrame(final Frame frame, String title, int width,
1609 frame.setLocation(lastFrameX, lastFrameY);
1612 frame.setSize(width, height);
1613 frame.setTitle(title);
1614 frame.addWindowListener(new WindowAdapter()
1616 public void windowClosing(WindowEvent e)
1618 if (frame instanceof AlignFrame)
1620 AlignViewport vp = ((AlignFrame) frame).viewport;
1621 ((AlignFrame) frame).closeMenuItem_actionPerformed();
1622 if (vp.applet.currentAlignFrame == frame)
1624 vp.applet.currentAlignFrame = null;
1632 if (frame instanceof EmbmenuFrame)
1634 ((EmbmenuFrame) frame).destroyMenus();
1636 frame.setMenuBar(null);
1640 public void windowActivated(WindowEvent e)
1642 if (frame instanceof AlignFrame)
1644 ((AlignFrame) frame).viewport.applet.currentAlignFrame = (AlignFrame) frame;
1647 System.err.println("Activated window " + frame);
1651 super.windowActivated(e);
1654 * Probably not necessary to do this - see TODO above. (non-Javadoc)
1657 * java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent
1660 * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
1661 * frame) { currentAlignFrame = null; if (debug) {
1662 * System.err.println("Deactivated window "+frame); } }
1663 * super.windowDeactivated(e); }
1666 frame.setVisible(true);
1670 * This paints the background surrounding the "Launch Jalview button" <br>
1672 * If file given in parameter not found, displays error message
1677 public void paint(Graphics g)
1681 g.setColor(new Color(200, 200, 200));
1682 g.setColor(Color.cyan);
1683 g.fillRect(0, 0, getSize().width, getSize().height);
1684 g.setColor(Color.red);
1686 MessageManager.getString("label.jalview_cannot_open_file"),
1688 g.drawString("\"" + file + "\"", 5, 30);
1692 g.setColor(Color.black);
1693 g.setFont(new Font("Arial", Font.BOLD, 24));
1694 g.drawString(MessageManager.getString("label.jalview_applet"), 50,
1695 getSize().height / 2 - 30);
1696 g.drawString(MessageManager.getString("label.loading_data") + "...",
1697 50, getSize().height / 2);
1702 * get all components associated with the applet of the given type
1707 public Vector getAppletWindow(Class class1)
1709 Vector wnds = new Vector();
1710 Component[] cmp = getComponents();
1713 for (int i = 0; i < cmp.length; i++)
1715 if (class1.isAssignableFrom(cmp[i].getClass()))
1717 wnds.addElement(cmp);
1724 class LoadJmolThread extends Thread
1726 private boolean running = false;
1730 if (running || checkedForJmol)
1739 if (!System.getProperty("java.version").startsWith("1.1"))
1741 Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
1742 jmolAvailable = true;
1747 .println("Jmol not available - Using MCview for structures");
1749 } catch (java.lang.ClassNotFoundException ex)
1755 jmolAvailable = false;
1759 .println("Skipping Jmol check. Will use MCView (probably)");
1762 checkedForJmol = true;
1766 public boolean notFinished()
1768 return running || !checkedForJmol;
1772 class LoadingThread extends Thread
1775 * State variable: protocol for access to file source
1779 String _file; // alignment file or URL spec
1781 String _file2; // second alignment file or URL spec
1785 private void dbgMsg(String msg)
1787 if (JalviewLite.debug)
1789 System.err.println(msg);
1794 * update the protocol state variable for accessing the datasource located
1798 * @return possibly updated datasource string
1800 public String resolveFileProtocol(String path)
1805 if (path.startsWith("PASTE"))
1807 protocol = AppletFormatAdapter.PASTE;
1808 return path.substring(5);
1814 if (path.indexOf("://") != -1)
1816 protocol = AppletFormatAdapter.URL;
1821 * try relative to document root
1823 URL documentBase = getDocumentBase();
1824 String withDocBase = resolveUrlForLocalOrAbsolute(path, documentBase);
1825 if (HttpUtils.isValidUrl(withDocBase))
1829 System.err.println("Prepended document base '" + documentBase
1830 + "' to make: '" + withDocBase + "'");
1832 protocol = AppletFormatAdapter.URL;
1837 * try relative to codebase (if different to document base)
1839 URL codeBase = getCodeBase();
1840 String withCodeBase = applet.resolveUrlForLocalOrAbsolute(path,
1842 if (!withCodeBase.equals(withDocBase)
1843 && HttpUtils.isValidUrl(withCodeBase))
1845 protocol = AppletFormatAdapter.URL;
1848 System.err.println("Prepended codebase '" + codeBase
1849 + "' to make: '" + withCodeBase + "'");
1851 return withCodeBase;
1855 * try locating by classloader; try this last so files in the directory
1856 * are resolved using document base
1858 if (inArchive(path))
1860 protocol = AppletFormatAdapter.CLASSLOADER;
1865 public LoadingThread(String file, String file2, JalviewLite _applet)
1868 this._file2 = file2;
1874 LoadJmolThread jmolchecker = new LoadJmolThread();
1875 jmolchecker.start();
1876 while (jmolchecker.notFinished())
1878 // wait around until the Jmol check is complete.
1882 } catch (Exception e)
1887 // applet.callInitCallback();
1891 * Load the alignment and any related files as specified by applet
1894 private void startLoading()
1896 dbgMsg("Loading thread started with:\n>>file\n" + _file + ">>endfile");
1898 dbgMsg("Loading started.");
1900 AlignFrame newAlignFrame = readAlignment(_file);
1901 AlignFrame newAlignFrame2 = readAlignment(_file2);
1902 if (newAlignFrame != null)
1904 addToDisplay(newAlignFrame, newAlignFrame2);
1905 loadTree(newAlignFrame);
1907 loadScoreFile(newAlignFrame);
1909 loadFeatures(newAlignFrame);
1911 loadAnnotations(newAlignFrame);
1913 loadJnetFile(newAlignFrame);
1915 loadPdbFiles(newAlignFrame);
1920 applet.remove(launcher);
1927 * Add an AlignFrame to the display; or if two are provided, a SplitFrame.
1932 public void addToDisplay(AlignFrame af, AlignFrame af2)
1936 AlignmentI al1 = af.viewport.getAlignment();
1937 AlignmentI al2 = af2.viewport.getAlignment();
1938 AlignmentI cdna = al1.isNucleotide() ? al1 : al2;
1939 AlignmentI prot = al1.isNucleotide() ? al2 : al1;
1940 if (AlignmentUtils.mapProteinAlignmentToCdna(prot, cdna))
1943 SplitFrame sf = new SplitFrame(af, af2);
1944 sf.addToDisplay(embedded, JalviewLite.this);
1949 String msg = "Could not map any sequence in " + af2.getTitle()
1951 + (al1.isNucleotide() ? "protein product" : "cDNA")
1952 + " for " + af.getTitle();
1953 System.err.println(msg);
1957 af.addToDisplay(embedded);
1961 * Read the alignment file (from URL, text 'paste', or archive by
1966 protected AlignFrame readAlignment(String fileParam)
1968 if (fileParam == null)
1972 String resolvedFile = resolveFileProtocol(fileParam);
1973 String format = new IdentifyFile().identify(resolvedFile, protocol);
1974 dbgMsg("File identified as '" + format + "'");
1975 AlignmentI al = null;
1978 al = new AppletFormatAdapter().readFile(resolvedFile, protocol,
1980 if ((al != null) && (al.getHeight() > 0))
1982 dbgMsg("Successfully loaded file.");
1983 al.setDataset(null);
1984 AlignFrame newAlignFrame = new AlignFrame(al, applet,
1985 resolvedFile, embedded, false);
1986 newAlignFrame.setTitle(resolvedFile);
1987 if (initialAlignFrame == null)
1989 initialAlignFrame = newAlignFrame;
1991 // update the focus.
1992 currentAlignFrame = newAlignFrame;
1994 if (protocol == AppletFormatAdapter.PASTE)
1996 newAlignFrame.setTitle(MessageManager.formatMessage(
1997 "label.sequences_from", new Object[] { applet
1998 .getDocumentBase().toString() }));
2001 newAlignFrame.statusBar.setText(MessageManager.formatMessage(
2002 "label.successfully_loaded_file",
2003 new Object[] { resolvedFile }));
2005 return newAlignFrame;
2007 } catch (java.io.IOException ex)
2009 dbgMsg("File load exception.");
2010 ex.printStackTrace();
2015 FileParse fp = new FileParse(resolvedFile, protocol);
2017 dbgMsg(">>>Dumping contents of '" + resolvedFile + "' " + "("
2019 while ((ln = fp.nextLine()) != null)
2023 dbgMsg(">>>Dump finished.");
2024 } catch (Exception e)
2027 .println("Exception when trying to dump the content of the file parameter.");
2028 e.printStackTrace();
2036 * Load PDBFiles if any specified by parameter(s). Returns true if loaded,
2042 protected boolean loadPdbFiles(AlignFrame alignFrame)
2044 boolean result = false;
2046 * <param name="alignpdbfiles" value="false/true"/> Undocumented for 2.6 -
2047 * related to JAL-434
2050 applet.setAlignPdbStructures(getDefaultParameter("alignpdbfiles",
2053 * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
2056 * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
2058 * <param name="PDBfile3" value="1q0o Q45135_9MICO">
2061 int pdbFileCount = 0;
2062 // Accumulate pdbs here if they are heading for the same view (if
2063 // alignPdbStructures is true)
2064 Vector pdbs = new Vector();
2065 // create a lazy matcher if we're asked to
2066 jalview.analysis.SequenceIdMatcher matcher = (applet
2067 .getDefaultParameter("relaxedidmatch", false)) ? new jalview.analysis.SequenceIdMatcher(
2068 alignFrame.getAlignViewport().getAlignment()
2069 .getSequencesArray()) : null;
2074 if (pdbFileCount > 0)
2076 param = applet.getParameter("PDBFILE" + pdbFileCount);
2080 param = applet.getParameter("PDBFILE");
2085 PDBEntry pdb = new PDBEntry();
2088 SequenceI[] seqs = null;
2089 String[] chains = null;
2091 StringTokenizer st = new StringTokenizer(param, " ");
2093 if (st.countTokens() < 2)
2095 String sequence = applet.getParameter("PDBSEQ");
2096 if (sequence != null)
2098 seqs = new SequenceI[] { matcher == null ? (Sequence) alignFrame
2099 .getAlignViewport().getAlignment().findName(sequence)
2100 : matcher.findIdMatch(sequence) };
2106 param = st.nextToken();
2107 List<SequenceI> tmp = new ArrayList<SequenceI>();
2108 List<String> tmp2 = new ArrayList<String>();
2110 while (st.hasMoreTokens())
2112 seqstring = st.nextToken();
2113 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
2114 if (st2.countTokens() > 1)
2116 // This is the chain
2117 tmp2.add(st2.nextToken());
2118 seqstring = st2.nextToken();
2120 tmp.add(matcher == null ? (Sequence) alignFrame
2121 .getAlignViewport().getAlignment()
2122 .findName(seqstring) : matcher.findIdMatch(seqstring));
2125 seqs = tmp.toArray(new SequenceI[tmp.size()]);
2126 if (tmp2.size() == tmp.size())
2128 chains = tmp2.toArray(new String[tmp2.size()]);
2131 param = resolveFileProtocol(param);
2132 // TODO check JAL-357 for files in a jar (CLASSLOADER)
2137 for (int i = 0; i < seqs.length; i++)
2139 if (seqs[i] != null)
2141 ((Sequence) seqs[i]).addPDBId(pdb);
2142 StructureSelectionManager.getStructureSelectionManager(
2143 applet).registerPDBEntry(pdb);
2147 if (JalviewLite.debug)
2149 // this may not really be a problem but we give a warning
2152 .println("Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
2158 if (!alignPdbStructures)
2160 alignFrame.newStructureView(applet, pdb, seqs, chains,
2165 pdbs.addElement(new Object[] { pdb, seqs, chains,
2166 new String(protocol) });
2172 } while (param != null || pdbFileCount < 10);
2173 if (pdbs.size() > 0)
2175 SequenceI[][] seqs = new SequenceI[pdbs.size()][];
2176 PDBEntry[] pdb = new PDBEntry[pdbs.size()];
2177 String[][] chains = new String[pdbs.size()][];
2178 String[] protocols = new String[pdbs.size()];
2179 for (int pdbsi = 0, pdbsiSize = pdbs.size(); pdbsi < pdbsiSize; pdbsi++)
2181 Object[] o = (Object[]) pdbs.elementAt(pdbsi);
2182 pdb[pdbsi] = (PDBEntry) o[0];
2183 seqs[pdbsi] = (SequenceI[]) o[1];
2184 chains[pdbsi] = (String[]) o[2];
2185 protocols[pdbsi] = (String) o[3];
2187 alignFrame.alignedStructureView(applet, pdb, seqs, chains,
2195 * Load in a Jnetfile if specified by parameter. Returns true if loaded,
2201 protected boolean loadJnetFile(AlignFrame alignFrame)
2203 boolean result = false;
2204 String param = applet.getParameter("jnetfile");
2209 param = resolveFileProtocol(param);
2210 JPredFile predictions = new JPredFile(param, protocol);
2211 JnetAnnotationMaker.add_annotation(predictions,
2212 alignFrame.viewport.getAlignment(), 0, false);
2213 // false == do not add sequence profile from concise output
2214 SequenceI repseq = alignFrame.viewport.getAlignment()
2216 alignFrame.viewport.getAlignment().setSeqrep(repseq);
2217 ColumnSelection cs = new ColumnSelection();
2218 cs.hideInsertionsFor(repseq);
2219 alignFrame.viewport.setColumnSelection(cs);
2220 alignFrame.alignPanel.fontChanged();
2221 alignFrame.alignPanel.setScrollValues(0, 0);
2223 } catch (Exception ex)
2225 ex.printStackTrace();
2232 * Load annotations if specified by parameter. Returns true if loaded, else
2238 protected boolean loadAnnotations(AlignFrame alignFrame)
2240 boolean result = false;
2241 String param = applet.getParameter("annotations");
2244 param = resolveFileProtocol(param);
2246 if (new AnnotationFile().annotateAlignmentView(alignFrame.viewport,
2249 alignFrame.alignPanel.fontChanged();
2250 alignFrame.alignPanel.setScrollValues(0, 0);
2256 .println("Annotations were not added from annotation file '"
2264 * Load features file and view settings as specified by parameters. Returns
2265 * true if features were loaded, else false.
2270 protected boolean loadFeatures(AlignFrame alignFrame)
2272 boolean result = false;
2273 // ///////////////////////////
2274 // modify display of features
2275 // we do this before any features have been loaded, ensuring any hidden
2276 // groups are hidden when features first displayed
2278 // hide specific groups
2280 String param = applet.getParameter("hidefeaturegroups");
2283 alignFrame.setFeatureGroupState(separatorListToArray(param), false);
2284 // applet.setFeatureGroupStateOn(newAlignFrame, param, false);
2286 // show specific groups
2287 param = applet.getParameter("showfeaturegroups");
2290 alignFrame.setFeatureGroupState(separatorListToArray(param), true);
2291 // applet.setFeatureGroupStateOn(newAlignFrame, param, true);
2293 // and now load features
2294 param = applet.getParameter("features");
2297 param = resolveFileProtocol(param);
2299 result = alignFrame.parseFeaturesFile(param, protocol);
2302 param = applet.getParameter("showFeatureSettings");
2303 if (param != null && param.equalsIgnoreCase(TRUE))
2305 alignFrame.viewport.setShowSequenceFeatures(true);
2306 new FeatureSettings(alignFrame.alignPanel);
2312 * Load a score file if specified by parameter. Returns true if file was
2313 * loaded, else false.
2317 protected boolean loadScoreFile(AlignFrame alignFrame)
2319 boolean result = false;
2320 String sScoreFile = applet.getParameter("scoreFile");
2321 if (sScoreFile != null && !"".equals(sScoreFile))
2328 .println("Attempting to load T-COFFEE score file from the scoreFile parameter");
2330 result = alignFrame.loadScoreFile(sScoreFile);
2334 .println("Failed to parse T-COFFEE parameter as a valid score file ('"
2335 + sScoreFile + "')");
2337 } catch (Exception e)
2339 System.err.printf("Cannot read score file: '%s'. Cause: %s \n",
2340 sScoreFile, e.getMessage());
2347 * Load a tree for the alignment if specified by parameter. Returns true if
2348 * a tree was loaded, else false.
2353 protected boolean loadTree(AlignFrame alignFrame)
2355 boolean result = false;
2356 String treeFile = applet.getParameter("tree");
2357 if (treeFile == null)
2359 treeFile = applet.getParameter("treeFile");
2362 if (treeFile != null)
2366 treeFile = resolveFileProtocol(treeFile);
2367 NewickFile fin = new NewickFile(treeFile, protocol);
2370 if (fin.getTree() != null)
2372 alignFrame.loadTree(fin, treeFile);
2374 dbgMsg("Successfully imported tree.");
2378 dbgMsg("Tree parameter did not resolve to a valid tree.");
2380 } catch (Exception ex)
2382 ex.printStackTrace();
2389 * Discovers whether the given file is in the Applet Archive
2395 boolean inArchive(String f)
2397 // This might throw a security exception in certain browsers
2398 // Netscape Communicator for instance.
2401 boolean rtn = (getClass().getResourceAsStream("/" + f) != null);
2404 System.err.println("Resource '" + f + "' was "
2405 + (rtn ? "" : "not ") + "located by classloader.");
2408 } catch (Exception ex)
2410 System.out.println("Exception checking resources: " + f + " " + ex);
2417 * @return the default alignFrame acted on by the public applet methods. May
2418 * return null with an error message on System.err indicating the
2421 public AlignFrame getDefaultTargetFrame()
2423 if (currentAlignFrame != null)
2425 return currentAlignFrame;
2427 if (initialAlignFrame != null)
2429 return initialAlignFrame;
2432 .println("Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
2437 * separator used for separatorList
2439 protected String separator = "" + ((char) 0x00AC); // the default used to be
2440 // '|' but many sequence
2441 // IDS include pipes.
2444 * set to enable the URL based javascript execution mechanism
2446 public boolean jsfallbackEnabled = false;
2449 * parse the string into a list
2452 * @return elements separated by separator
2454 public String[] separatorListToArray(String list)
2456 return separatorListToArray(list, separator);
2460 * parse the string into a list
2464 * @return elements separated by separator
2466 public static String[] separatorListToArray(String list, String separator)
2468 // TODO use StringUtils version (slightly different...)
2469 int seplen = separator.length();
2470 if (list == null || list.equals("") || list.equals(separator))
2474 java.util.Vector jv = new Vector();
2476 while ((pos = list.indexOf(separator, cp)) > cp)
2478 jv.addElement(list.substring(cp, pos));
2481 if (cp < list.length())
2483 String c = list.substring(cp);
2484 if (!c.equals(separator))
2491 String[] v = new String[jv.size()];
2492 for (int i = 0; i < v.length; i++)
2494 v[i] = (String) jv.elementAt(i);
2496 jv.removeAllElements();
2499 System.err.println("Array from '" + separator
2500 + "' separated List:\n" + v.length);
2501 for (int i = 0; i < v.length; i++)
2503 System.err.println("item " + i + " '" + v[i] + "'");
2510 System.err.println("Empty Array from '" + separator
2511 + "' separated List");
2517 * concatenate the list with separator
2520 * @return concatenated string
2522 public String arrayToSeparatorList(String[] list)
2524 return arrayToSeparatorList(list, separator);
2528 * concatenate the list with separator
2532 * @return concatenated string
2534 public static String arrayToSeparatorList(String[] list, String separator)
2536 // TODO use StringUtils version
2537 StringBuffer v = new StringBuffer();
2538 if (list != null && list.length > 0)
2540 for (int i = 0, iSize = list.length; i < iSize; i++)
2542 if (list[i] != null)
2546 v.append(separator);
2553 System.err.println("Returning '" + separator
2554 + "' separated List:\n");
2555 System.err.println(v);
2557 return v.toString();
2561 System.err.println("Returning empty '" + separator
2562 + "' separated List\n");
2564 return "" + separator;
2570 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroups()
2572 public String getFeatureGroups()
2574 String lst = arrayToSeparatorList(getDefaultTargetFrame()
2575 .getFeatureGroups());
2583 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOn(jalview.appletgui.AlignFrame
2586 public String getFeatureGroupsOn(AlignFrame alf)
2588 String lst = arrayToSeparatorList(alf.getFeatureGroups());
2595 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfState(boolean)
2597 public String getFeatureGroupsOfState(boolean visible)
2599 return arrayToSeparatorList(getDefaultTargetFrame()
2600 .getFeatureGroupsOfState(visible));
2607 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfStateOn(jalview.appletgui
2608 * .AlignFrame, boolean)
2610 public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
2612 return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
2618 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupStateOn(jalview.appletgui.
2619 * AlignFrame, java.lang.String, boolean)
2621 public void setFeatureGroupStateOn(final AlignFrame alf,
2622 final String groups, boolean state)
2624 final boolean st = state;// !(state==null || state.equals("") ||
2625 // state.toLowerCase().equals("false"));
2626 java.awt.EventQueue.invokeLater(new Runnable()
2631 alf.setFeatureGroupState(separatorListToArray(groups), st);
2639 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupState(java.lang.String,
2642 public void setFeatureGroupState(String groups, boolean state)
2644 setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
2650 * @see jalview.bin.JalviewLiteJsApi#getSeparator()
2652 public String getSeparator()
2660 * @see jalview.bin.JalviewLiteJsApi#setSeparator(java.lang.String)
2662 public void setSeparator(String separator)
2664 if (separator == null || separator.length() < 1)
2667 separator = "" + ((char) 0x00AC);
2669 this.separator = separator;
2672 System.err.println("Default Separator now: '" + separator + "'");
2677 * get boolean value of applet parameter 'name' and return default if
2678 * parameter is not set
2683 * the value to return otherwise
2684 * @return true or false
2686 public boolean getDefaultParameter(String name, boolean def)
2689 if ((stn = getParameter(name)) == null)
2693 if (TRUE.equalsIgnoreCase(stn))
2703 * @see jalview.bin.JalviewLiteJsApi#addPdbFile(jalview.appletgui.AlignFrame,
2704 * java.lang.String, java.lang.String, java.lang.String)
2706 public boolean addPdbFile(AlignFrame alFrame, String sequenceId,
2707 String pdbEntryString, String pdbFile)
2709 return alFrame.addPdbFile(sequenceId, pdbEntryString, pdbFile);
2712 protected void setAlignPdbStructures(boolean alignPdbStructures)
2714 this.alignPdbStructures = alignPdbStructures;
2717 public boolean isAlignPdbStructures()
2719 return alignPdbStructures;
2724 // callInitCallback();
2727 private Hashtable<String, long[]> jshashes = new Hashtable<String, long[]>();
2729 private Hashtable<String, Hashtable<String, String[]>> jsmessages = new Hashtable<String, Hashtable<String, String[]>>();
2731 public void setJsMessageSet(String messageclass, String viewId,
2732 String[] colcommands)
2734 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2737 msgset = new Hashtable<String, String[]>();
2738 jsmessages.put(messageclass, msgset);
2740 msgset.put(viewId, colcommands);
2741 long[] l = new long[colcommands.length];
2742 for (int i = 0; i < colcommands.length; i++)
2744 l[i] = colcommands[i].hashCode();
2746 jshashes.put(messageclass + "|" + viewId, l);
2752 * @see jalview.bin.JalviewLiteJsApi#getJsMessage(java.lang.String,
2755 public String getJsMessage(String messageclass, String viewId)
2757 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2760 String[] msgs = msgset.get(viewId);
2763 for (int i = 0; i < msgs.length; i++)
2765 if (msgs[i] != null)
2777 public boolean isJsMessageSetChanged(String string, String string2,
2778 String[] colcommands)
2780 long[] l = jshashes.get(string + "|" + string2);
2781 if (l == null && colcommands != null)
2785 for (int i = 0; i < colcommands.length; i++)
2787 if (l[i] != colcommands[i].hashCode())
2795 private Vector jsExecQueue = new Vector();
2797 public Vector getJsExecQueue()
2802 public void setExecutor(JSFunctionExec jsFunctionExec2)
2804 jsFunctionExec = jsFunctionExec2;
2808 * return the given colour value parameter or the given default if parameter
2815 public Color getDefaultColourParameter(String colparam, Color defcolour)
2817 String colprop = getParameter(colparam);
2818 if (colprop == null || colprop.trim().length() == 0)
2822 Color col = jalview.schemes.ColourSchemeProperty
2823 .getAWTColorFromName(colprop);
2828 col = new jalview.schemes.UserColourScheme(colprop).findColour('A');
2829 } catch (Exception ex)
2831 System.err.println("Couldn't parse '" + colprop
2832 + "' as a colour for " + colparam);
2836 return (col == null) ? defcolour : col;
2840 public void openJalviewHelpUrl()
2842 String helpUrl = getParameter("jalviewhelpurl");
2843 if (helpUrl == null || helpUrl.trim().length() < 5)
2845 helpUrl = "http://www.jalview.org/help.html";
2847 showURL(helpUrl, "HELP");
2851 * form a complete URL given a path to a resource and a reference location on
2855 * - an absolute path on the same server as localref or a document
2856 * located relative to localref
2858 * - a URL on the same server as url
2859 * @return a complete URL for the resource located by url
2861 private String resolveUrlForLocalOrAbsolute(String targetPath,
2864 String resolvedPath = "";
2865 if (targetPath.startsWith("/"))
2867 String codebase = localref.toString();
2868 String localfile = localref.getFile();
2869 resolvedPath = codebase.substring(0,
2870 codebase.length() - localfile.length())
2872 return resolvedPath;
2876 * get URL path and strip off any trailing file e.g.
2877 * www.jalview.org/examples/index.html#applets?a=b is trimmed to
2878 * www.jalview.org/examples/
2880 String urlPath = localref.toString();
2881 String directoryPath = urlPath;
2882 int lastSeparator = directoryPath.lastIndexOf("/");
2883 if (lastSeparator > 0)
2885 directoryPath = directoryPath.substring(0, lastSeparator + 1);
2888 if (targetPath.startsWith("/"))
2891 * construct absolute URL to a file on the server - this is not allowed?
2893 // String localfile = localref.getFile();
2894 // resolvedPath = urlPath.substring(0,
2895 // urlPath.length() - localfile.length())
2897 resolvedPath = directoryPath + targetPath.substring(1);
2901 resolvedPath = directoryPath + targetPath;
2905 System.err.println("resolveUrlForLocalOrAbsolute returning "
2908 return resolvedPath;
2912 * open a URL in the browser - resolving it according to relative refs and
2913 * coping with javascript: protocol if necessary.
2918 public void showURL(String url, String target)
2922 if (url.indexOf(":") == -1)
2924 // TODO: verify (Bas Vroling bug) prepend codebase or server URL to
2926 // Should really use docbase, not codebase.
2928 url = resolveUrlForLocalOrAbsolute(
2930 prepend = getDefaultParameter("resolvetocodebase", false) ? getCodeBase()
2931 : getDocumentBase());
2935 .println("Show url (prepended "
2937 + " - toggle resolvetocodebase if code/docbase resolution is wrong): "
2945 System.err.println("Show url: " + url);
2948 if (url.indexOf("javascript:") == 0)
2950 // no target for the javascript context
2951 getAppletContext().showDocument(new java.net.URL(url));
2955 getAppletContext().showDocument(new java.net.URL(url), target);
2957 } catch (Exception ex)
2959 ex.printStackTrace();
2964 * bind structures in a viewer to any matching sequences in an alignFrame (use
2965 * sequenceIds to limit scope of search to specific sequences)
2969 * @param sequenceIds
2970 * @return TODO: consider making an exception structure for indicating when
2971 * binding fails public SequenceStructureBinding
2972 * addStructureViewInstance( AlignFrame alFrame, Object viewer, String
2975 * if (sequenceIds != null && sequenceIds.length() > 0) { return
2976 * alFrame.addStructureViewInstance(viewer,
2977 * separatorListToArray(sequenceIds)); } else { return
2978 * alFrame.addStructureViewInstance(viewer, null); } // return null; }