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.HiddenColumns;
35 import jalview.datamodel.PDBEntry;
36 import jalview.datamodel.Sequence;
37 import jalview.datamodel.SequenceGroup;
38 import jalview.datamodel.SequenceI;
39 import jalview.io.AnnotationFile;
40 import jalview.io.AppletFormatAdapter;
41 import jalview.io.DataSourceType;
42 import jalview.io.FileFormatI;
43 import jalview.io.FileFormats;
44 import jalview.io.FileParse;
45 import jalview.io.IdentifyFile;
46 import jalview.io.JPredFile;
47 import jalview.io.JnetAnnotationMaker;
48 import jalview.io.NewickFile;
49 import jalview.javascript.JSFunctionExec;
50 import jalview.javascript.JalviewLiteJsApi;
51 import jalview.javascript.JsCallBack;
52 import jalview.javascript.MouseOverStructureListener;
53 import jalview.structure.SelectionListener;
54 import jalview.structure.StructureSelectionManager;
55 import jalview.util.ColorUtils;
56 import jalview.util.HttpUtils;
57 import jalview.util.MessageManager;
59 import java.applet.Applet;
60 import java.awt.Button;
61 import java.awt.Color;
62 import java.awt.Component;
63 import java.awt.EventQueue;
65 import java.awt.Frame;
66 import java.awt.Graphics;
67 import java.awt.event.ActionEvent;
68 import java.awt.event.WindowAdapter;
69 import java.awt.event.WindowEvent;
70 import java.io.BufferedReader;
71 import java.io.IOException;
72 import java.io.InputStreamReader;
74 import java.util.ArrayList;
75 import java.util.Hashtable;
76 import java.util.List;
77 import java.util.StringTokenizer;
78 import java.util.Vector;
80 import netscape.javascript.JSObject;
83 * Jalview Applet. Runs in Java 1.18 runtime
86 * @version $Revision: 1.92 $
88 public class JalviewLite extends Applet implements
89 StructureSelectionManagerProvider, JalviewLiteJsApi
92 private static final String TRUE = "true";
94 private static final String FALSE = "false";
96 public StructureSelectionManager getStructureSelectionManager()
98 return StructureSelectionManager.getStructureSelectionManager(this);
101 // /////////////////////////////////////////
102 // The following public methods may be called
103 // externally, eg via javascript in HTML page
107 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences()
110 public String getSelectedSequences()
112 return getSelectedSequencesFrom(getDefaultTargetFrame());
118 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences(java.lang.String)
121 public String getSelectedSequences(String sep)
123 return getSelectedSequencesFrom(getDefaultTargetFrame(), sep);
130 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
134 public String getSelectedSequencesFrom(AlignFrame alf)
136 return getSelectedSequencesFrom(alf, separator); // ""+0x00AC);
143 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
144 * .AlignFrame, java.lang.String)
147 public String getSelectedSequencesFrom(AlignFrame alf, String sep)
149 StringBuffer result = new StringBuffer("");
150 if (sep == null || sep.length() == 0)
152 sep = separator; // "+0x00AC;
154 if (alf.viewport.getSelectionGroup() != null)
156 SequenceI[] seqs = alf.viewport.getSelectionGroup()
157 .getSequencesInOrder(alf.viewport.getAlignment());
159 for (int i = 0; i < seqs.length; i++)
161 result.append(seqs[i].getName());
166 return result.toString();
172 * @see jalview.bin.JalviewLiteJsApi#highlight(java.lang.String,
173 * java.lang.String, java.lang.String)
176 public void highlight(String sequenceId, String position,
177 String alignedPosition)
179 highlightIn(getDefaultTargetFrame(), sequenceId, position,
186 * @see jalview.bin.JalviewLiteJsApi#highlightIn(jalview.appletgui.AlignFrame,
187 * java.lang.String, java.lang.String, java.lang.String)
190 public void highlightIn(final AlignFrame alf, final String sequenceId,
191 final String position, final String alignedPosition)
193 // TODO: could try to highlight in all alignments if alf==null
194 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
195 alf.viewport.getAlignment().getSequencesArray());
196 final SequenceI sq = matcher.findIdMatch(sequenceId);
202 apos = new Integer(position).intValue();
204 } catch (NumberFormatException ex)
208 final StructureSelectionManagerProvider me = this;
209 final int pos = apos;
210 // use vamsas listener to broadcast to all listeners in scope
211 if (alignedPosition != null
212 && (alignedPosition.trim().length() == 0 || alignedPosition
213 .toLowerCase().indexOf("false") > -1))
215 java.awt.EventQueue.invokeLater(new Runnable()
220 StructureSelectionManager.getStructureSelectionManager(me)
221 .mouseOverVamsasSequence(sq, sq.findIndex(pos), null);
227 java.awt.EventQueue.invokeLater(new Runnable()
232 StructureSelectionManager.getStructureSelectionManager(me)
233 .mouseOverVamsasSequence(sq, pos, null);
243 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
247 public void select(String sequenceIds, String columns)
249 selectIn(getDefaultTargetFrame(), sequenceIds, columns, separator);
255 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
256 * java.lang.String, java.lang.String)
259 public void select(String sequenceIds, String columns, String sep)
261 selectIn(getDefaultTargetFrame(), sequenceIds, columns, sep);
267 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
268 * java.lang.String, java.lang.String)
271 public void selectIn(AlignFrame alf, String sequenceIds, String columns)
273 selectIn(alf, sequenceIds, columns, separator);
279 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
280 * java.lang.String, java.lang.String, java.lang.String)
283 public void selectIn(final AlignFrame alf, String sequenceIds,
284 String columns, String sep)
286 if (sep == null || sep.length() == 0)
294 System.err.println("Selecting region using separator string '"
299 String[] ids = separatorListToArray(sequenceIds, sep);
300 String[] cols = separatorListToArray(columns, sep);
301 final SequenceGroup sel = new SequenceGroup();
302 final ColumnSelection csel = new ColumnSelection();
303 AlignmentI al = alf.viewport.getAlignment();
304 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
305 alf.viewport.getAlignment().getSequencesArray());
306 int start = 0, end = al.getWidth(), alw = al.getWidth();
307 boolean seqsfound = true;
308 if (ids != null && ids.length > 0)
311 for (int i = 0; i < ids.length; i++)
313 if (ids[i].trim().length() == 0)
317 SequenceI sq = matcher.findIdMatch(ids[i]);
321 sel.addSequence(sq, false);
325 boolean inseqpos = false;
326 if (cols != null && cols.length > 0)
328 boolean seset = false;
329 for (int i = 0; i < cols.length; i++)
331 String cl = cols[i].trim();
332 if (cl.length() == 0)
337 if ((p = cl.indexOf("-")) > -1)
339 int from = -1, to = -1;
342 from = new Integer(cl.substring(0, p)).intValue();
344 } catch (NumberFormatException ex)
347 .println("ERROR: Couldn't parse first integer in range element column selection string '"
348 + cl + "' - format is 'from-to'");
353 to = new Integer(cl.substring(p + 1)).intValue();
355 } catch (NumberFormatException ex)
358 .println("ERROR: Couldn't parse second integer in range element column selection string '"
359 + cl + "' - format is 'from-to'");
362 if (from >= 0 && to >= 0)
379 // comment to prevent range extension
389 for (int r = from; r <= to; r++)
391 if (r >= 0 && r < alw)
398 System.err.println("Range '" + cl + "' deparsed as [" + from
404 System.err.println("ERROR: Invalid Range '" + cl
405 + "' deparsed as [" + from + "," + to + "]");
413 r = new Integer(cl).intValue();
415 } catch (NumberFormatException ex)
417 if (cl.toLowerCase().equals("sequence"))
419 // we are in the dataset sequence's coordinate frame.
425 .println("ERROR: Couldn't parse integer from point selection element of column selection string '"
430 if (r >= 0 && r <= alw)
440 // comment to prevent range extension
453 System.err.println("Point selection '" + cl
454 + "' deparsed as [" + r + "]");
459 System.err.println("ERROR: Invalid Point selection '" + cl
460 + "' deparsed as [" + r + "]");
467 // we only propagate the selection when it was the null selection, or the
468 // given sequences were found in the alignment.
469 if (inseqpos && sel.getSize() > 0)
471 // assume first sequence provides reference frame ?
472 SequenceI rs = sel.getSequenceAt(0);
473 start = rs.findIndex(start);
474 end = rs.findIndex(end);
475 List<Integer> cs = new ArrayList<Integer>(csel.getSelected());
477 for (Integer selectedCol : cs)
479 csel.addElement(rs.findIndex(selectedCol));
482 sel.setStartRes(start);
484 EventQueue.invokeLater(new Runnable()
489 alf.select(sel, csel, alf.getAlignViewport().getAlignment()
490 .getHiddenColumns());
500 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignment(java.lang.
501 * String, java.lang.String)
504 public String getSelectedSequencesAsAlignment(String format, String suffix)
506 return getSelectedSequencesAsAlignmentFrom(getDefaultTargetFrame(),
514 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignmentFrom(jalview
515 * .appletgui.AlignFrame, java.lang.String, java.lang.String)
518 public String getSelectedSequencesAsAlignmentFrom(AlignFrame alf,
519 String format, String suffix)
523 FileFormatI theFormat = FileFormats.getInstance().forName(format);
524 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
525 if (alf.viewport.getSelectionGroup() != null)
527 // JBPNote: getSelectionAsNewSequence behaviour has changed - this
528 // method now returns a full copy of sequence data
529 // TODO consider using getSequenceSelection instead here
530 String reply = new AppletFormatAdapter().formatSequences(theFormat,
531 new Alignment(alf.viewport.getSelectionAsNewSequence()),
535 } catch (IllegalArgumentException ex)
537 ex.printStackTrace();
538 return "Error retrieving alignment, possibly invalid format specifier: "
547 * @see jalview.bin.JalviewLiteJsApi#getAlignmentOrder()
550 public String getAlignmentOrder()
552 return getAlignmentOrderFrom(getDefaultTargetFrame());
559 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
563 public String getAlignmentOrderFrom(AlignFrame alf)
565 return getAlignmentOrderFrom(alf, separator);
572 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
573 * , java.lang.String)
576 public String getAlignmentOrderFrom(AlignFrame alf, String sep)
578 AlignmentI alorder = alf.getAlignViewport().getAlignment();
579 String[] order = new String[alorder.getHeight()];
580 for (int i = 0; i < order.length; i++)
582 order[i] = alorder.getSequenceAt(i).getName();
584 return arrayToSeparatorList(order);
590 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
594 public String orderBy(String order, String undoName)
596 return orderBy(order, undoName, separator);
602 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
603 * java.lang.String, java.lang.String)
606 public String orderBy(String order, String undoName, String sep)
608 return orderAlignmentBy(getDefaultTargetFrame(), order, undoName, sep);
615 * jalview.bin.JalviewLiteJsApi#orderAlignmentBy(jalview.appletgui.AlignFrame,
616 * java.lang.String, java.lang.String, java.lang.String)
619 public String orderAlignmentBy(AlignFrame alf, String order,
620 String undoName, String sep)
622 String[] ids = separatorListToArray(order, sep);
623 SequenceI[] sqs = null;
624 if (ids != null && ids.length > 0)
626 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
627 alf.viewport.getAlignment().getSequencesArray());
629 sqs = new SequenceI[ids.length];
630 for (int i = 0; i < ids.length; i++)
632 if (ids[i].trim().length() == 0)
636 SequenceI sq = matcher.findIdMatch(ids[i]);
644 SequenceI[] sqq = new SequenceI[s];
645 System.arraycopy(sqs, 0, sqq, 0, s);
658 final AlignmentOrder aorder = new AlignmentOrder(sqs);
660 if (undoName != null && undoName.trim().length() == 0)
664 final String _undoName = undoName;
665 // TODO: deal with synchronization here: cannot raise any events until after
666 // this has returned.
667 return alf.sortBy(aorder, _undoName) ? TRUE : "";
673 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String)
676 public String getAlignment(String format)
678 return getAlignmentFrom(getDefaultTargetFrame(), format, TRUE);
685 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
689 public String getAlignmentFrom(AlignFrame alf, String format)
691 return getAlignmentFrom(alf, format, TRUE);
697 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String,
701 public String getAlignment(String format, String suffix)
703 return getAlignmentFrom(getDefaultTargetFrame(), format, suffix);
710 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
711 * java.lang.String, java.lang.String)
714 public String getAlignmentFrom(AlignFrame alf, String format,
719 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
721 FileFormatI theFormat = FileFormats.getInstance().forName(format);
722 String reply = new AppletFormatAdapter().formatSequences(theFormat,
723 alf.viewport.getAlignment(), seqlimits);
725 } catch (IllegalArgumentException ex)
727 ex.printStackTrace();
728 return "Error retrieving alignment, possibly invalid format specifier: "
736 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
739 public void loadAnnotation(String annotation)
741 loadAnnotationFrom(getDefaultTargetFrame(), annotation);
748 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
749 * , java.lang.String)
752 public void loadAnnotationFrom(AlignFrame alf, String annotation)
754 if (new AnnotationFile().annotateAlignmentView(alf.getAlignViewport(),
755 annotation, DataSourceType.PASTE))
757 alf.alignPanel.fontChanged();
758 alf.alignPanel.setScrollValues(0, 0);
762 alf.parseFeaturesFile(annotation, DataSourceType.PASTE);
769 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
772 public void loadFeatures(String features, boolean autoenabledisplay)
774 loadFeaturesFrom(getDefaultTargetFrame(), features, autoenabledisplay);
781 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
782 * , java.lang.String)
785 public boolean loadFeaturesFrom(AlignFrame alf, String features,
786 boolean autoenabledisplay)
788 return alf.parseFeaturesFile(features, DataSourceType.PASTE,
795 * @see jalview.bin.JalviewLiteJsApi#getFeatures(java.lang.String)
798 public String getFeatures(String format)
800 return getFeaturesFrom(getDefaultTargetFrame(), format);
807 * jalview.bin.JalviewLiteJsApi#getFeaturesFrom(jalview.appletgui.AlignFrame,
811 public String getFeaturesFrom(AlignFrame alf, String format)
813 return alf.outputFeatures(false, format);
819 * @see jalview.bin.JalviewLiteJsApi#getAnnotation()
822 public String getAnnotation()
824 return getAnnotationFrom(getDefaultTargetFrame());
831 * jalview.bin.JalviewLiteJsApi#getAnnotationFrom(jalview.appletgui.AlignFrame
835 public String getAnnotationFrom(AlignFrame alf)
837 return alf.outputAnnotations(false);
843 * @see jalview.bin.JalviewLiteJsApi#newView()
846 public AlignFrame newView()
848 return newViewFrom(getDefaultTargetFrame());
854 * @see jalview.bin.JalviewLiteJsApi#newView(java.lang.String)
857 public AlignFrame newView(String name)
859 return newViewFrom(getDefaultTargetFrame(), name);
865 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame)
868 public AlignFrame newViewFrom(AlignFrame alf)
870 return alf.newView(null);
876 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame,
880 public AlignFrame newViewFrom(AlignFrame alf, String name)
882 return alf.newView(name);
888 * @see jalview.bin.JalviewLiteJsApi#loadAlignment(java.lang.String,
892 public AlignFrame loadAlignment(String text, String title)
894 AlignmentI al = null;
898 FileFormatI format = new IdentifyFile().identify(text,
899 DataSourceType.PASTE);
900 al = new AppletFormatAdapter().readFile(text, DataSourceType.PASTE,
902 if (al.getHeight() > 0)
904 return new AlignFrame(al, this, title, false);
906 } catch (IOException ex)
908 ex.printStackTrace();
916 * @see jalview.bin.JalviewLiteJsApi#setMouseoverListener(java.lang.String)
919 public void setMouseoverListener(String listener)
921 setMouseoverListener(currentAlignFrame, listener);
924 private Vector<jalview.javascript.JSFunctionExec> javascriptListeners = new Vector<jalview.javascript.JSFunctionExec>();
930 * jalview.bin.JalviewLiteJsApi#setMouseoverListener(jalview.appletgui.AlignFrame
931 * , java.lang.String)
934 public void setMouseoverListener(AlignFrame af, String listener)
936 if (listener != null)
938 listener = listener.trim();
939 if (listener.length() == 0)
942 .println("jalview Javascript error: Ignoring empty function for mouseover listener.");
946 jalview.javascript.MouseOverListener mol = new jalview.javascript.MouseOverListener(
948 javascriptListeners.addElement(mol);
949 StructureSelectionManager.getStructureSelectionManager(this)
950 .addStructureViewerListener(mol);
953 System.err.println("Added a mouseover listener for "
954 + ((af == null) ? "All frames" : "Just views for "
955 + af.getAlignViewport().getSequenceSetId()));
956 System.err.println("There are now " + javascriptListeners.size()
957 + " listeners in total.");
964 * @see jalview.bin.JalviewLiteJsApi#setSelectionListener(java.lang.String)
967 public void setSelectionListener(String listener)
969 setSelectionListener(null, listener);
976 * jalview.bin.JalviewLiteJsApi#setSelectionListener(jalview.appletgui.AlignFrame
977 * , java.lang.String)
980 public void setSelectionListener(AlignFrame af, String listener)
982 if (listener != null)
984 listener = listener.trim();
985 if (listener.length() == 0)
988 .println("jalview Javascript error: Ignoring empty function for selection listener.");
992 jalview.javascript.JsSelectionSender mol = new jalview.javascript.JsSelectionSender(
994 javascriptListeners.addElement(mol);
995 StructureSelectionManager.getStructureSelectionManager(this)
996 .addSelectionListener(mol);
999 System.err.println("Added a selection listener for "
1000 + ((af == null) ? "All frames" : "Just views for "
1001 + af.getAlignViewport().getSequenceSetId()));
1002 System.err.println("There are now " + javascriptListeners.size()
1003 + " listeners in total.");
1008 * Callable from javascript to register a javascript function to pass events
1009 * to a structure viewer.
1012 * the name of a javascript function
1014 * a token separated list of PDB file names listened for
1015 * @see jalview.bin.JalviewLiteJsApi#setStructureListener(java.lang.String,
1019 public void setStructureListener(String listener, String modelSet)
1021 if (listener != null)
1023 listener = listener.trim();
1024 if (listener.length() == 0)
1027 .println("jalview Javascript error: Ignoring empty function for selection listener.");
1031 MouseOverStructureListener mol = new MouseOverStructureListener(this,
1032 listener, separatorListToArray(modelSet));
1033 javascriptListeners.addElement(mol);
1034 StructureSelectionManager.getStructureSelectionManager(this)
1035 .addStructureViewerListener(mol);
1038 System.err.println("Added a javascript structure viewer listener '"
1040 System.err.println("There are now " + javascriptListeners.size()
1041 + " listeners in total.");
1049 * jalview.bin.JalviewLiteJsApi#removeJavascriptListener(jalview.appletgui
1050 * .AlignFrame, java.lang.String)
1053 public void removeJavascriptListener(AlignFrame af, String listener)
1055 if (listener != null)
1057 listener = listener.trim();
1058 if (listener.length() == 0)
1063 boolean rprt = false;
1064 for (int ms = 0, msSize = javascriptListeners.size(); ms < msSize;)
1066 Object lstn = javascriptListeners.elementAt(ms);
1067 JsCallBack lstner = (JsCallBack) lstn;
1068 if ((af == null || lstner.getAlignFrame() == af)
1069 && (listener == null || lstner.getListenerFunction().equals(
1072 javascriptListeners.removeElement(lstner);
1074 if (lstner instanceof SelectionListener)
1076 StructureSelectionManager.getStructureSelectionManager(this)
1077 .removeSelectionListener((SelectionListener) lstner);
1081 StructureSelectionManager.getStructureSelectionManager(this)
1082 .removeStructureViewerListener(lstner, null);
1087 System.err.println("Removed listener '" + listener + "'");
1097 System.err.println("There are now " + javascriptListeners.size()
1098 + " listeners in total.");
1105 System.err.println("Applet " + getName() + " stop().");
1110 public void destroy()
1112 System.err.println("Applet " + getName() + " destroy().");
1116 private void tidyUp()
1119 if (currentAlignFrame != null && currentAlignFrame.viewport != null
1120 && currentAlignFrame.viewport.applet != null)
1122 AlignViewport av = currentAlignFrame.viewport;
1123 currentAlignFrame.closeMenuItem_actionPerformed();
1125 currentAlignFrame = null;
1127 if (javascriptListeners != null)
1129 while (javascriptListeners.size() > 0)
1131 jalview.javascript.JSFunctionExec mol = javascriptListeners
1133 javascriptListeners.removeElement(mol);
1134 if (mol instanceof SelectionListener)
1136 StructureSelectionManager.getStructureSelectionManager(this)
1137 .removeSelectionListener((SelectionListener) mol);
1141 StructureSelectionManager.getStructureSelectionManager(this)
1142 .removeStructureViewerListener(mol, null);
1147 if (jsFunctionExec != null)
1149 jsFunctionExec.stopQueue();
1150 jsFunctionExec.jvlite = null;
1152 initialAlignFrame = null;
1153 jsFunctionExec = null;
1154 javascriptListeners = null;
1155 StructureSelectionManager.release(this);
1158 private jalview.javascript.JSFunctionExec jsFunctionExec;
1163 * @see jalview.bin.JalviewLiteJsApi#mouseOverStructure(java.lang.String,
1164 * java.lang.String, java.lang.String)
1167 public void mouseOverStructure(final String pdbResNum,
1168 final String chain, final String pdbfile)
1170 final StructureSelectionManagerProvider me = this;
1171 java.awt.EventQueue.invokeLater(new Runnable()
1178 StructureSelectionManager.getStructureSelectionManager(me)
1179 .mouseOverStructure(new Integer(pdbResNum).intValue(),
1183 System.err.println("mouseOver for '" + pdbResNum
1184 + "' in chain '" + chain + "' in structure '" + pdbfile
1187 } catch (NumberFormatException e)
1189 System.err.println("Ignoring invalid residue number string '"
1201 * jalview.bin.JalviewLiteJsApi#scrollViewToIn(jalview.appletgui.AlignFrame,
1202 * java.lang.String, java.lang.String)
1205 public void scrollViewToIn(final AlignFrame alf, final String topRow,
1206 final String leftHandColumn)
1208 java.awt.EventQueue.invokeLater(new Runnable()
1215 alf.scrollTo(new Integer(topRow).intValue(), new Integer(
1216 leftHandColumn).intValue());
1218 } catch (Exception ex)
1220 System.err.println("Couldn't parse integer arguments (topRow='"
1221 + topRow + "' and leftHandColumn='" + leftHandColumn
1223 ex.printStackTrace();
1233 * jalview.javascript.JalviewLiteJsApi#scrollViewToRowIn(jalview.appletgui
1234 * .AlignFrame, java.lang.String)
1237 public void scrollViewToRowIn(final AlignFrame alf, final String topRow)
1240 java.awt.EventQueue.invokeLater(new Runnable()
1247 alf.scrollToRow(new Integer(topRow).intValue());
1249 } catch (Exception ex)
1251 System.err.println("Couldn't parse integer arguments (topRow='"
1253 ex.printStackTrace();
1264 * jalview.javascript.JalviewLiteJsApi#scrollViewToColumnIn(jalview.appletgui
1265 * .AlignFrame, java.lang.String)
1268 public void scrollViewToColumnIn(final AlignFrame alf,
1269 final String leftHandColumn)
1271 java.awt.EventQueue.invokeLater(new Runnable()
1279 alf.scrollToColumn(new Integer(leftHandColumn).intValue());
1281 } catch (Exception ex)
1284 .println("Couldn't parse integer arguments (leftHandColumn='"
1285 + leftHandColumn + "')");
1286 ex.printStackTrace();
1293 // //////////////////////////////////////////////
1294 // //////////////////////////////////////////////
1296 public static int lastFrameX = 200;
1298 public static int lastFrameY = 200;
1300 boolean fileFound = true;
1302 String file = "No file";
1304 String file2 = null;
1306 Button launcher = new Button(
1307 MessageManager.getString("label.start_jalview"));
1310 * The currentAlignFrame is static, it will change if and when the user
1311 * selects a new window. Note that it will *never* point back to the embedded
1312 * AlignFrame if the applet is started as embedded on the page and then
1313 * afterwards a new view is created.
1315 public AlignFrame currentAlignFrame = null;
1318 * This is the first frame to be displayed, and does not change. API calls
1319 * will default to this instance if currentAlignFrame is null.
1321 AlignFrame initialAlignFrame = null;
1323 boolean embedded = false;
1325 private boolean checkForJmol = true;
1327 private boolean checkedForJmol = false; // ensure we don't check for jmol
1329 // every time the app is re-inited
1331 public boolean jmolAvailable = false;
1333 private boolean alignPdbStructures = false;
1336 * use an external structure viewer exclusively (no jmols or MCViews will be
1337 * opened by JalviewLite itself)
1339 public boolean useXtrnalSviewer = false;
1341 public static boolean debug = false;
1343 static String builddate = null, version = null, installation = null;
1345 private static void initBuildDetails()
1347 if (builddate == null)
1349 builddate = "unknown";
1351 installation = "applet";
1352 java.net.URL url = JalviewLite.class
1353 .getResource("/.build_properties");
1358 BufferedReader reader = new BufferedReader(new InputStreamReader(
1361 while ((line = reader.readLine()) != null)
1363 if (line.indexOf("VERSION") > -1)
1365 version = line.substring(line.indexOf("=") + 1);
1367 if (line.indexOf("BUILD_DATE") > -1)
1369 builddate = line.substring(line.indexOf("=") + 1);
1371 if (line.indexOf("INSTALLATION") > -1)
1373 installation = line.substring(line.indexOf("=") + 1);
1376 } catch (Exception ex)
1378 ex.printStackTrace();
1384 public static String getBuildDate()
1390 public static String getInstallation()
1393 return installation;
1396 public static String getVersion()
1402 // public JSObject scriptObject = null;
1405 * init method for Jalview Applet
1410 debug = TRUE.equalsIgnoreCase(getParameter("debug"));
1415 System.err.println("Applet context is '"
1416 + getAppletContext().getClass().toString() + "'");
1418 JSObject scriptObject = JSObject.getWindow(this);
1419 if (debug && scriptObject != null)
1421 System.err.println("Applet has Javascript callback support.");
1424 } catch (Exception ex)
1427 .println("Warning: No JalviewLite javascript callbacks available.");
1430 ex.printStackTrace();
1436 System.err.println("JalviewLite Version " + getVersion());
1437 System.err.println("Build Date : " + getBuildDate());
1438 System.err.println("Installation : " + getInstallation());
1440 String externalsviewer = getParameter("externalstructureviewer");
1441 if (externalsviewer != null)
1443 useXtrnalSviewer = externalsviewer.trim().toLowerCase().equals(TRUE);
1446 * if true disable the check for jmol
1448 String chkforJmol = getParameter("nojmol");
1449 if (chkforJmol != null)
1451 checkForJmol = !chkforJmol.equals(TRUE);
1454 * get the separator parameter if present
1456 String sep = getParameter("separator");
1459 if (sep.length() > 0)
1464 System.err.println("Separator set to '" + separator + "'");
1471 .getString("error.invalid_separator_parameter"));
1477 String param = getParameter("RGB");
1483 r = Integer.parseInt(param.substring(0, 2), 16);
1484 g = Integer.parseInt(param.substring(2, 4), 16);
1485 b = Integer.parseInt(param.substring(4, 6), 16);
1486 } catch (Exception ex)
1493 param = getParameter("label");
1496 launcher.setLabel(param);
1499 setBackground(new Color(r, g, b));
1501 file = getParameter("file");
1505 // Maybe the sequences are added as parameters
1506 StringBuffer data = new StringBuffer("PASTE");
1508 while ((file = getParameter("sequence" + i)) != null)
1510 data.append(file.toString() + "\n");
1513 if (data.length() > 5)
1515 file = data.toString();
1518 if (getDefaultParameter("enableSplitFrame", true))
1520 file2 = getParameter("file2");
1523 embedded = TRUE.equalsIgnoreCase(getParameter("embedded"));
1526 LoadingThread loader = new LoadingThread(file, file2, this);
1529 else if (file != null)
1532 * Start the applet immediately or show a button to start it
1534 if (FALSE.equalsIgnoreCase(getParameter("showbutton")))
1536 LoadingThread loader = new LoadingThread(file, file2, this);
1542 launcher.addActionListener(new java.awt.event.ActionListener()
1545 public void actionPerformed(ActionEvent e)
1547 LoadingThread loader = new LoadingThread(file, file2,
1556 // jalview initialisation with no alignment. loadAlignment() method can
1557 // still be called to open new alignments.
1564 private void initLiveConnect()
1566 // try really hard to get the liveConnect thing working
1567 boolean notFailed = false;
1569 while (!notFailed && tries < 10)
1573 System.err.println("LiveConnect request thread going to sleep.");
1577 Thread.sleep(700 * (1 + tries));
1578 } catch (InterruptedException q)
1584 System.err.println("LiveConnect request thread woken up.");
1588 JSObject scriptObject = JSObject.getWindow(this);
1589 if (scriptObject.eval("navigator") != null)
1593 } catch (Exception jsex)
1595 System.err.println("Attempt " + tries
1596 + " to access LiveConnect javascript failed.");
1601 private void callInitCallback()
1603 String initjscallback = getParameter("oninit");
1604 if (initjscallback == null)
1608 initjscallback = initjscallback.trim();
1609 if (initjscallback.length() > 0)
1611 JSObject scriptObject = null;
1614 scriptObject = JSObject.getWindow(this);
1615 } catch (Exception ex)
1619 // try really hard to let the browser plugin know we want liveconnect
1622 if (scriptObject != null)
1626 // do onInit with the JS executor thread
1627 new JSFunctionExec(this).executeJavascriptFunction(true,
1628 initjscallback, null, "Calling oninit callback '"
1629 + initjscallback + "'.");
1630 } catch (Exception e)
1632 System.err.println("Exception when executing _oninit callback '"
1633 + initjscallback + "'.");
1634 e.printStackTrace();
1639 System.err.println("Not executing _oninit callback '"
1640 + initjscallback + "' - no scripting allowed.");
1646 * Initialises and displays a new java.awt.Frame
1649 * java.awt.Frame to be displayed
1651 * title of new frame
1653 * width if new frame
1655 * height of new frame
1657 public static void addFrame(final Frame frame, String title, int width,
1660 frame.setLocation(lastFrameX, lastFrameY);
1663 frame.setSize(width, height);
1664 frame.setTitle(title);
1665 frame.addWindowListener(new WindowAdapter()
1668 public void windowClosing(WindowEvent e)
1670 if (frame instanceof AlignFrame)
1672 AlignViewport vp = ((AlignFrame) frame).viewport;
1673 ((AlignFrame) frame).closeMenuItem_actionPerformed();
1674 if (vp.applet.currentAlignFrame == frame)
1676 vp.applet.currentAlignFrame = null;
1684 if (frame instanceof EmbmenuFrame)
1686 ((EmbmenuFrame) frame).destroyMenus();
1688 frame.setMenuBar(null);
1693 public void windowActivated(WindowEvent e)
1695 if (frame instanceof AlignFrame)
1697 ((AlignFrame) frame).viewport.applet.currentAlignFrame = (AlignFrame) frame;
1700 System.err.println("Activated window " + frame);
1704 super.windowActivated(e);
1707 * Probably not necessary to do this - see TODO above. (non-Javadoc)
1710 * java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent
1713 * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
1714 * frame) { currentAlignFrame = null; if (debug) {
1715 * System.err.println("Deactivated window "+frame); } }
1716 * super.windowDeactivated(e); }
1719 frame.setVisible(true);
1723 * This paints the background surrounding the "Launch Jalview button" <br>
1725 * If file given in parameter not found, displays error message
1731 public void paint(Graphics g)
1735 g.setColor(new Color(200, 200, 200));
1736 g.setColor(Color.cyan);
1737 g.fillRect(0, 0, getSize().width, getSize().height);
1738 g.setColor(Color.red);
1740 MessageManager.getString("label.jalview_cannot_open_file"),
1742 g.drawString("\"" + file + "\"", 5, 30);
1746 g.setColor(Color.black);
1747 g.setFont(new Font("Arial", Font.BOLD, 24));
1748 g.drawString(MessageManager.getString("label.jalview_applet"), 50,
1749 getSize().height / 2 - 30);
1750 g.drawString(MessageManager.getString("label.loading_data") + "...",
1751 50, getSize().height / 2);
1756 * get all components associated with the applet of the given type
1761 public Vector getAppletWindow(Class class1)
1763 Vector wnds = new Vector();
1764 Component[] cmp = getComponents();
1767 for (int i = 0; i < cmp.length; i++)
1769 if (class1.isAssignableFrom(cmp[i].getClass()))
1771 wnds.addElement(cmp);
1778 class LoadJmolThread extends Thread
1780 private boolean running = false;
1785 if (running || checkedForJmol)
1794 if (!System.getProperty("java.version").startsWith("1.1"))
1796 Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
1797 jmolAvailable = true;
1802 .println("Jmol not available - Using MCview for structures");
1804 } catch (java.lang.ClassNotFoundException ex)
1810 jmolAvailable = false;
1814 .println("Skipping Jmol check. Will use MCView (probably)");
1817 checkedForJmol = true;
1821 public boolean notFinished()
1823 return running || !checkedForJmol;
1827 class LoadingThread extends Thread
1830 * State variable: protocol for access to file source
1832 DataSourceType protocol;
1834 String _file; // alignment file or URL spec
1836 String _file2; // second alignment file or URL spec
1840 private void dbgMsg(String msg)
1842 if (JalviewLite.debug)
1844 System.err.println(msg);
1849 * update the protocol state variable for accessing the datasource located
1853 * @return possibly updated datasource string
1855 public String resolveFileProtocol(String path)
1860 if (path.startsWith("PASTE"))
1862 protocol = DataSourceType.PASTE;
1863 return path.substring(5);
1869 if (path.indexOf("://") != -1)
1871 protocol = DataSourceType.URL;
1876 * try relative to document root
1878 URL documentBase = getDocumentBase();
1879 String withDocBase = resolveUrlForLocalOrAbsolute(path, documentBase);
1880 if (HttpUtils.isValidUrl(withDocBase))
1884 System.err.println("Prepended document base '" + documentBase
1885 + "' to make: '" + withDocBase + "'");
1887 protocol = DataSourceType.URL;
1892 * try relative to codebase (if different to document base)
1894 URL codeBase = getCodeBase();
1895 String withCodeBase = applet.resolveUrlForLocalOrAbsolute(path,
1897 if (!withCodeBase.equals(withDocBase)
1898 && HttpUtils.isValidUrl(withCodeBase))
1900 protocol = DataSourceType.URL;
1903 System.err.println("Prepended codebase '" + codeBase
1904 + "' to make: '" + withCodeBase + "'");
1906 return withCodeBase;
1910 * try locating by classloader; try this last so files in the directory
1911 * are resolved using document base
1913 if (inArchive(path))
1915 protocol = DataSourceType.CLASSLOADER;
1920 public LoadingThread(String file, String file2, JalviewLite _applet)
1923 this._file2 = file2;
1930 LoadJmolThread jmolchecker = new LoadJmolThread();
1931 jmolchecker.start();
1932 while (jmolchecker.notFinished())
1934 // wait around until the Jmol check is complete.
1938 } catch (Exception e)
1943 // applet.callInitCallback();
1947 * Load the alignment and any related files as specified by applet
1950 private void startLoading()
1952 dbgMsg("Loading thread started with:\n>>file\n" + _file + ">>endfile");
1954 dbgMsg("Loading started.");
1956 AlignFrame newAlignFrame = readAlignment(_file);
1957 AlignFrame newAlignFrame2 = readAlignment(_file2);
1958 if (newAlignFrame != null)
1960 addToDisplay(newAlignFrame, newAlignFrame2);
1961 loadTree(newAlignFrame);
1963 loadScoreFile(newAlignFrame);
1965 loadFeatures(newAlignFrame);
1967 loadAnnotations(newAlignFrame);
1969 loadJnetFile(newAlignFrame);
1971 loadPdbFiles(newAlignFrame);
1976 applet.remove(launcher);
1983 * Add an AlignFrame to the display; or if two are provided, a SplitFrame.
1988 public void addToDisplay(AlignFrame af, AlignFrame af2)
1992 AlignmentI al1 = af.viewport.getAlignment();
1993 AlignmentI al2 = af2.viewport.getAlignment();
1994 AlignmentI cdna = al1.isNucleotide() ? al1 : al2;
1995 AlignmentI prot = al1.isNucleotide() ? al2 : al1;
1996 if (AlignmentUtils.mapProteinAlignmentToCdna(prot, cdna))
1999 SplitFrame sf = new SplitFrame(af, af2);
2000 sf.addToDisplay(embedded, JalviewLite.this);
2005 String msg = "Could not map any sequence in " + af2.getTitle()
2007 + (al1.isNucleotide() ? "protein product" : "cDNA")
2008 + " for " + af.getTitle();
2009 System.err.println(msg);
2013 af.addToDisplay(embedded);
2017 * Read the alignment file (from URL, text 'paste', or archive by
2022 protected AlignFrame readAlignment(String fileParam)
2024 if (fileParam == null)
2028 String resolvedFile = resolveFileProtocol(fileParam);
2029 AlignmentI al = null;
2032 FileFormatI format = new IdentifyFile().identify(resolvedFile,
2034 dbgMsg("File identified as '" + format + "'");
2035 al = new AppletFormatAdapter().readFile(resolvedFile, protocol,
2037 if ((al != null) && (al.getHeight() > 0))
2039 dbgMsg("Successfully loaded file.");
2040 al.setDataset(null);
2041 AlignFrame newAlignFrame = new AlignFrame(al, applet,
2042 resolvedFile, embedded, false);
2043 newAlignFrame.setTitle(resolvedFile);
2044 if (initialAlignFrame == null)
2046 initialAlignFrame = newAlignFrame;
2048 // update the focus.
2049 currentAlignFrame = newAlignFrame;
2051 if (protocol == DataSourceType.PASTE)
2053 newAlignFrame.setTitle(MessageManager.formatMessage(
2054 "label.sequences_from", new Object[] { applet
2055 .getDocumentBase().toString() }));
2058 newAlignFrame.statusBar.setText(MessageManager.formatMessage(
2059 "label.successfully_loaded_file",
2060 new Object[] { resolvedFile }));
2062 return newAlignFrame;
2064 } catch (java.io.IOException ex)
2066 dbgMsg("File load exception.");
2067 ex.printStackTrace();
2072 FileParse fp = new FileParse(resolvedFile, protocol);
2074 dbgMsg(">>>Dumping contents of '" + resolvedFile + "' " + "("
2076 while ((ln = fp.nextLine()) != null)
2080 dbgMsg(">>>Dump finished.");
2081 } catch (Exception e)
2084 .println("Exception when trying to dump the content of the file parameter.");
2085 e.printStackTrace();
2093 * Load PDBFiles if any specified by parameter(s). Returns true if loaded,
2099 protected boolean loadPdbFiles(AlignFrame alignFrame)
2101 boolean result = false;
2103 * <param name="alignpdbfiles" value="false/true"/> Undocumented for 2.6 -
2104 * related to JAL-434
2107 applet.setAlignPdbStructures(getDefaultParameter("alignpdbfiles",
2110 * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
2113 * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
2115 * <param name="PDBfile3" value="1q0o Q45135_9MICO">
2118 int pdbFileCount = 0;
2119 // Accumulate pdbs here if they are heading for the same view (if
2120 // alignPdbStructures is true)
2121 Vector pdbs = new Vector();
2122 // create a lazy matcher if we're asked to
2123 jalview.analysis.SequenceIdMatcher matcher = (applet
2124 .getDefaultParameter("relaxedidmatch", false)) ? new jalview.analysis.SequenceIdMatcher(
2125 alignFrame.getAlignViewport().getAlignment()
2126 .getSequencesArray()) : null;
2131 if (pdbFileCount > 0)
2133 param = applet.getParameter("PDBFILE" + pdbFileCount);
2137 param = applet.getParameter("PDBFILE");
2142 PDBEntry pdb = new PDBEntry();
2145 SequenceI[] seqs = null;
2146 String[] chains = null;
2148 StringTokenizer st = new StringTokenizer(param, " ");
2150 if (st.countTokens() < 2)
2152 String sequence = applet.getParameter("PDBSEQ");
2153 if (sequence != null)
2155 seqs = new SequenceI[] { matcher == null ? (Sequence) alignFrame
2156 .getAlignViewport().getAlignment().findName(sequence)
2157 : matcher.findIdMatch(sequence) };
2163 param = st.nextToken();
2164 List<SequenceI> tmp = new ArrayList<SequenceI>();
2165 List<String> tmp2 = new ArrayList<String>();
2167 while (st.hasMoreTokens())
2169 seqstring = st.nextToken();
2170 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
2171 if (st2.countTokens() > 1)
2173 // This is the chain
2174 tmp2.add(st2.nextToken());
2175 seqstring = st2.nextToken();
2177 tmp.add(matcher == null ? (Sequence) alignFrame
2178 .getAlignViewport().getAlignment()
2179 .findName(seqstring) : matcher.findIdMatch(seqstring));
2182 seqs = tmp.toArray(new SequenceI[tmp.size()]);
2183 if (tmp2.size() == tmp.size())
2185 chains = tmp2.toArray(new String[tmp2.size()]);
2188 param = resolveFileProtocol(param);
2189 // TODO check JAL-357 for files in a jar (CLASSLOADER)
2194 for (int i = 0; i < seqs.length; i++)
2196 if (seqs[i] != null)
2198 ((Sequence) seqs[i]).addPDBId(pdb);
2199 StructureSelectionManager.getStructureSelectionManager(
2200 applet).registerPDBEntry(pdb);
2204 if (JalviewLite.debug)
2206 // this may not really be a problem but we give a warning
2209 .println("Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
2215 if (!alignPdbStructures)
2217 alignFrame.newStructureView(applet, pdb, seqs, chains,
2222 pdbs.addElement(new Object[] { pdb, seqs, chains, protocol });
2228 } while (param != null || pdbFileCount < 10);
2229 if (pdbs.size() > 0)
2231 SequenceI[][] seqs = new SequenceI[pdbs.size()][];
2232 PDBEntry[] pdb = new PDBEntry[pdbs.size()];
2233 String[][] chains = new String[pdbs.size()][];
2234 String[] protocols = new String[pdbs.size()];
2235 for (int pdbsi = 0, pdbsiSize = pdbs.size(); pdbsi < pdbsiSize; pdbsi++)
2237 Object[] o = (Object[]) pdbs.elementAt(pdbsi);
2238 pdb[pdbsi] = (PDBEntry) o[0];
2239 seqs[pdbsi] = (SequenceI[]) o[1];
2240 chains[pdbsi] = (String[]) o[2];
2241 protocols[pdbsi] = (String) o[3];
2243 alignFrame.alignedStructureView(applet, pdb, seqs, chains,
2251 * Load in a Jnetfile if specified by parameter. Returns true if loaded,
2257 protected boolean loadJnetFile(AlignFrame alignFrame)
2259 boolean result = false;
2260 String param = applet.getParameter("jnetfile");
2263 // jnet became jpred around 2016
2264 param = applet.getParameter("jpredfile");
2270 param = resolveFileProtocol(param);
2271 JPredFile predictions = new JPredFile(param, protocol);
2272 JnetAnnotationMaker.add_annotation(predictions,
2273 alignFrame.viewport.getAlignment(), 0, false);
2274 // false == do not add sequence profile from concise output
2275 SequenceI repseq = alignFrame.viewport.getAlignment()
2277 alignFrame.viewport.getAlignment().setSeqrep(repseq);
2278 HiddenColumns cs = new HiddenColumns();
2279 cs.hideInsertionsFor(repseq);
2280 alignFrame.viewport.getAlignment().setHiddenColumns(cs);
2281 alignFrame.alignPanel.fontChanged();
2282 alignFrame.alignPanel.setScrollValues(0, 0);
2284 } catch (Exception ex)
2286 ex.printStackTrace();
2293 * Load annotations if specified by parameter. Returns true if loaded, else
2299 protected boolean loadAnnotations(AlignFrame alignFrame)
2301 boolean result = false;
2302 String param = applet.getParameter("annotations");
2305 param = resolveFileProtocol(param);
2307 if (new AnnotationFile().annotateAlignmentView(alignFrame.viewport,
2310 alignFrame.alignPanel.fontChanged();
2311 alignFrame.alignPanel.setScrollValues(0, 0);
2317 .println("Annotations were not added from annotation file '"
2325 * Load features file and view settings as specified by parameters. Returns
2326 * true if features were loaded, else false.
2331 protected boolean loadFeatures(AlignFrame alignFrame)
2333 boolean result = false;
2334 // ///////////////////////////
2335 // modify display of features
2336 // we do this before any features have been loaded, ensuring any hidden
2337 // groups are hidden when features first displayed
2339 // hide specific groups
2341 String param = applet.getParameter("hidefeaturegroups");
2344 alignFrame.setFeatureGroupState(separatorListToArray(param), false);
2345 // applet.setFeatureGroupStateOn(newAlignFrame, param, false);
2347 // show specific groups
2348 param = applet.getParameter("showfeaturegroups");
2351 alignFrame.setFeatureGroupState(separatorListToArray(param), true);
2352 // applet.setFeatureGroupStateOn(newAlignFrame, param, true);
2354 // and now load features
2355 param = applet.getParameter("features");
2358 param = resolveFileProtocol(param);
2360 result = alignFrame.parseFeaturesFile(param, protocol);
2363 param = applet.getParameter("showFeatureSettings");
2364 if (param != null && param.equalsIgnoreCase(TRUE))
2366 alignFrame.viewport.setShowSequenceFeatures(true);
2367 new FeatureSettings(alignFrame.alignPanel);
2373 * Load a score file if specified by parameter. Returns true if file was
2374 * loaded, else false.
2378 protected boolean loadScoreFile(AlignFrame alignFrame)
2380 boolean result = false;
2381 String sScoreFile = applet.getParameter("scoreFile");
2382 if (sScoreFile != null && !"".equals(sScoreFile))
2389 .println("Attempting to load T-COFFEE score file from the scoreFile parameter");
2391 result = alignFrame.loadScoreFile(sScoreFile);
2395 .println("Failed to parse T-COFFEE parameter as a valid score file ('"
2396 + sScoreFile + "')");
2398 } catch (Exception e)
2400 System.err.printf("Cannot read score file: '%s'. Cause: %s \n",
2401 sScoreFile, e.getMessage());
2408 * Load a tree for the alignment if specified by parameter. Returns true if
2409 * a tree was loaded, else false.
2414 protected boolean loadTree(AlignFrame alignFrame)
2416 boolean result = false;
2417 String treeFile = applet.getParameter("tree");
2418 if (treeFile == null)
2420 treeFile = applet.getParameter("treeFile");
2423 if (treeFile != null)
2427 treeFile = resolveFileProtocol(treeFile);
2428 NewickFile fin = new NewickFile(treeFile, protocol);
2431 if (fin.getTree() != null)
2433 alignFrame.loadTree(fin, treeFile);
2435 dbgMsg("Successfully imported tree.");
2439 dbgMsg("Tree parameter did not resolve to a valid tree.");
2441 } catch (Exception ex)
2443 ex.printStackTrace();
2450 * Discovers whether the given file is in the Applet Archive
2456 boolean inArchive(String f)
2458 // This might throw a security exception in certain browsers
2459 // Netscape Communicator for instance.
2462 boolean rtn = (getClass().getResourceAsStream("/" + f) != null);
2465 System.err.println("Resource '" + f + "' was "
2466 + (rtn ? "" : "not ") + "located by classloader.");
2469 } catch (Exception ex)
2471 System.out.println("Exception checking resources: " + f + " " + ex);
2478 * @return the default alignFrame acted on by the public applet methods. May
2479 * return null with an error message on System.err indicating the
2482 public AlignFrame getDefaultTargetFrame()
2484 if (currentAlignFrame != null)
2486 return currentAlignFrame;
2488 if (initialAlignFrame != null)
2490 return initialAlignFrame;
2493 .println("Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
2498 * separator used for separatorList
2500 protected String separator = "" + ((char) 0x00AC); // the default used to be
2501 // '|' but many sequence
2502 // IDS include pipes.
2505 * set to enable the URL based javascript execution mechanism
2507 public boolean jsfallbackEnabled = false;
2510 * parse the string into a list
2513 * @return elements separated by separator
2515 public String[] separatorListToArray(String list)
2517 return separatorListToArray(list, separator);
2521 * parse the string into a list
2525 * @return elements separated by separator
2527 public static String[] separatorListToArray(String list, String separator)
2529 // TODO use StringUtils version (slightly different...)
2530 int seplen = separator.length();
2531 if (list == null || list.equals("") || list.equals(separator))
2535 java.util.Vector jv = new Vector();
2537 while ((pos = list.indexOf(separator, cp)) > cp)
2539 jv.addElement(list.substring(cp, pos));
2542 if (cp < list.length())
2544 String c = list.substring(cp);
2545 if (!c.equals(separator))
2552 String[] v = new String[jv.size()];
2553 for (int i = 0; i < v.length; i++)
2555 v[i] = (String) jv.elementAt(i);
2557 jv.removeAllElements();
2560 System.err.println("Array from '" + separator
2561 + "' separated List:\n" + v.length);
2562 for (int i = 0; i < v.length; i++)
2564 System.err.println("item " + i + " '" + v[i] + "'");
2571 System.err.println("Empty Array from '" + separator
2572 + "' separated List");
2578 * concatenate the list with separator
2581 * @return concatenated string
2583 public String arrayToSeparatorList(String[] list)
2585 return arrayToSeparatorList(list, separator);
2589 * concatenate the list with separator
2593 * @return concatenated string
2595 public static String arrayToSeparatorList(String[] list, String separator)
2597 // TODO use StringUtils version
2598 StringBuffer v = new StringBuffer();
2599 if (list != null && list.length > 0)
2601 for (int i = 0, iSize = list.length; i < iSize; i++)
2603 if (list[i] != null)
2607 v.append(separator);
2614 System.err.println("Returning '" + separator
2615 + "' separated List:\n");
2616 System.err.println(v);
2618 return v.toString();
2622 System.err.println("Returning empty '" + separator
2623 + "' separated List\n");
2625 return "" + separator;
2631 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroups()
2634 public String getFeatureGroups()
2636 String lst = arrayToSeparatorList(getDefaultTargetFrame()
2637 .getFeatureGroups());
2645 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOn(jalview.appletgui.AlignFrame
2649 public String getFeatureGroupsOn(AlignFrame alf)
2651 String lst = arrayToSeparatorList(alf.getFeatureGroups());
2658 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfState(boolean)
2661 public String getFeatureGroupsOfState(boolean visible)
2663 return arrayToSeparatorList(getDefaultTargetFrame()
2664 .getFeatureGroupsOfState(visible));
2671 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfStateOn(jalview.appletgui
2672 * .AlignFrame, boolean)
2675 public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
2677 return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
2683 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupStateOn(jalview.appletgui.
2684 * AlignFrame, java.lang.String, boolean)
2687 public void setFeatureGroupStateOn(final AlignFrame alf,
2688 final String groups, boolean state)
2690 final boolean st = state;// !(state==null || state.equals("") ||
2691 // state.toLowerCase().equals("false"));
2692 java.awt.EventQueue.invokeLater(new Runnable()
2697 alf.setFeatureGroupState(separatorListToArray(groups), st);
2705 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupState(java.lang.String,
2709 public void setFeatureGroupState(String groups, boolean state)
2711 setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
2717 * @see jalview.bin.JalviewLiteJsApi#getSeparator()
2720 public String getSeparator()
2728 * @see jalview.bin.JalviewLiteJsApi#setSeparator(java.lang.String)
2731 public void setSeparator(String separator)
2733 if (separator == null || separator.length() < 1)
2736 separator = "" + ((char) 0x00AC);
2738 this.separator = separator;
2741 System.err.println("Default Separator now: '" + separator + "'");
2746 * get boolean value of applet parameter 'name' and return default if
2747 * parameter is not set
2752 * the value to return otherwise
2753 * @return true or false
2755 public boolean getDefaultParameter(String name, boolean def)
2758 if ((stn = getParameter(name)) == null)
2762 if (TRUE.equalsIgnoreCase(stn))
2772 * @see jalview.bin.JalviewLiteJsApi#addPdbFile(jalview.appletgui.AlignFrame,
2773 * java.lang.String, java.lang.String, java.lang.String)
2776 public boolean addPdbFile(AlignFrame alFrame, String sequenceId,
2777 String pdbEntryString, String pdbFile)
2779 return alFrame.addPdbFile(sequenceId, pdbEntryString, pdbFile);
2782 protected void setAlignPdbStructures(boolean alignPdbStructures)
2784 this.alignPdbStructures = alignPdbStructures;
2787 public boolean isAlignPdbStructures()
2789 return alignPdbStructures;
2795 // callInitCallback();
2798 private Hashtable<String, long[]> jshashes = new Hashtable<String, long[]>();
2800 private Hashtable<String, Hashtable<String, String[]>> jsmessages = new Hashtable<String, Hashtable<String, String[]>>();
2802 public void setJsMessageSet(String messageclass, String viewId,
2803 String[] colcommands)
2805 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2808 msgset = new Hashtable<String, String[]>();
2809 jsmessages.put(messageclass, msgset);
2811 msgset.put(viewId, colcommands);
2812 long[] l = new long[colcommands.length];
2813 for (int i = 0; i < colcommands.length; i++)
2815 l[i] = colcommands[i].hashCode();
2817 jshashes.put(messageclass + "|" + viewId, l);
2823 * @see jalview.bin.JalviewLiteJsApi#getJsMessage(java.lang.String,
2827 public String getJsMessage(String messageclass, String viewId)
2829 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2832 String[] msgs = msgset.get(viewId);
2835 for (int i = 0; i < msgs.length; i++)
2837 if (msgs[i] != null)
2849 public boolean isJsMessageSetChanged(String string, String string2,
2850 String[] colcommands)
2852 long[] l = jshashes.get(string + "|" + string2);
2853 if (l == null && colcommands != null)
2857 for (int i = 0; i < colcommands.length; i++)
2859 if (l[i] != colcommands[i].hashCode())
2867 private Vector jsExecQueue = new Vector();
2869 public Vector getJsExecQueue()
2874 public void setExecutor(JSFunctionExec jsFunctionExec2)
2876 jsFunctionExec = jsFunctionExec2;
2880 * return the given colour value parameter or the given default if parameter
2887 public Color getDefaultColourParameter(String colparam, Color defcolour)
2889 String colprop = getParameter(colparam);
2890 if (colprop == null || colprop.trim().length() == 0)
2894 Color col = ColorUtils.parseColourString(colprop);
2897 System.err.println("Couldn't parse '" + colprop
2898 + "' as a colour for " + colparam);
2900 return (col == null) ? defcolour : col;
2903 public void openJalviewHelpUrl()
2905 String helpUrl = getParameter("jalviewhelpurl");
2906 if (helpUrl == null || helpUrl.trim().length() < 5)
2908 helpUrl = "http://www.jalview.org/help.html";
2910 showURL(helpUrl, "HELP");
2914 * form a complete URL given a path to a resource and a reference location on
2918 * - an absolute path on the same server as localref or a document
2919 * located relative to localref
2921 * - a URL on the same server as url
2922 * @return a complete URL for the resource located by url
2924 private String resolveUrlForLocalOrAbsolute(String targetPath,
2927 String resolvedPath = "";
2928 if (targetPath.startsWith("/"))
2930 String codebase = localref.toString();
2931 String localfile = localref.getFile();
2932 resolvedPath = codebase.substring(0,
2933 codebase.length() - localfile.length())
2935 return resolvedPath;
2939 * get URL path and strip off any trailing file e.g.
2940 * www.jalview.org/examples/index.html#applets?a=b is trimmed to
2941 * www.jalview.org/examples/
2943 String urlPath = localref.toString();
2944 String directoryPath = urlPath;
2945 int lastSeparator = directoryPath.lastIndexOf("/");
2946 if (lastSeparator > 0)
2948 directoryPath = directoryPath.substring(0, lastSeparator + 1);
2951 if (targetPath.startsWith("/"))
2954 * construct absolute URL to a file on the server - this is not allowed?
2956 // String localfile = localref.getFile();
2957 // resolvedPath = urlPath.substring(0,
2958 // urlPath.length() - localfile.length())
2960 resolvedPath = directoryPath + targetPath.substring(1);
2964 resolvedPath = directoryPath + targetPath;
2968 System.err.println("resolveUrlForLocalOrAbsolute returning "
2971 return resolvedPath;
2975 * open a URL in the browser - resolving it according to relative refs and
2976 * coping with javascript: protocol if necessary.
2981 public void showURL(String url, String target)
2985 if (url.indexOf(":") == -1)
2987 // TODO: verify (Bas Vroling bug) prepend codebase or server URL to
2989 // Should really use docbase, not codebase.
2991 url = resolveUrlForLocalOrAbsolute(
2993 prepend = getDefaultParameter("resolvetocodebase", false) ? getCodeBase()
2994 : getDocumentBase());
2998 .println("Show url (prepended "
3000 + " - toggle resolvetocodebase if code/docbase resolution is wrong): "
3008 System.err.println("Show url: " + url);
3011 if (url.indexOf("javascript:") == 0)
3013 // no target for the javascript context
3014 getAppletContext().showDocument(new java.net.URL(url));
3018 getAppletContext().showDocument(new java.net.URL(url), target);
3020 } catch (Exception ex)
3022 ex.printStackTrace();
3027 * bind structures in a viewer to any matching sequences in an alignFrame (use
3028 * sequenceIds to limit scope of search to specific sequences)
3032 * @param sequenceIds
3033 * @return TODO: consider making an exception structure for indicating when
3034 * binding fails public SequenceStructureBinding
3035 * addStructureViewInstance( AlignFrame alFrame, Object viewer, String
3038 * if (sequenceIds != null && sequenceIds.length() > 0) { return
3039 * alFrame.addStructureViewInstance(viewer,
3040 * separatorListToArray(sequenceIds)); } else { return
3041 * alFrame.addStructureViewInstance(viewer, null); } // return null; }