2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentUtils;
24 import jalview.api.StructureSelectionManagerProvider;
25 import jalview.appletgui.AlignFrame;
26 import jalview.appletgui.AlignViewport;
27 import jalview.appletgui.EmbmenuFrame;
28 import jalview.appletgui.FeatureSettings;
29 import jalview.appletgui.SplitFrame;
30 import jalview.datamodel.Alignment;
31 import jalview.datamodel.AlignmentI;
32 import jalview.datamodel.AlignmentOrder;
33 import jalview.datamodel.ColumnSelection;
34 import jalview.datamodel.PDBEntry;
35 import jalview.datamodel.Sequence;
36 import jalview.datamodel.SequenceGroup;
37 import jalview.datamodel.SequenceI;
38 import jalview.io.AnnotationFile;
39 import jalview.io.AppletFormatAdapter;
40 import jalview.io.DataSourceType;
41 import jalview.io.FileFormatI;
42 import jalview.io.FileFormats;
43 import jalview.io.FileParse;
44 import jalview.io.IdentifyFile;
45 import jalview.io.JPredFile;
46 import jalview.io.JnetAnnotationMaker;
47 import jalview.io.NewickFile;
48 import jalview.appletgui.js.JSFunctionExec;
49 import jalview.appletgui.js.JalviewLiteJsApi;
50 import jalview.appletgui.js.JsCallBack;
51 import jalview.appletgui.js.JsSelectionSender;
52 import jalview.appletgui.js.MouseOverListener;
53 import jalview.appletgui.js.MouseOverStructureListener;
54 import jalview.structure.SelectionListener;
55 import jalview.structure.StructureSelectionManager;
56 import jalview.util.ColorUtils;
57 import jalview.util.HttpUtils;
58 import jalview.util.MessageManager;
60 import java.applet.Applet;
61 import java.awt.Button;
62 import java.awt.Color;
63 import java.awt.Component;
64 import java.awt.EventQueue;
66 import java.awt.Frame;
67 import java.awt.Graphics;
68 import java.awt.event.ActionEvent;
69 import java.awt.event.WindowAdapter;
70 import java.awt.event.WindowEvent;
71 import java.io.BufferedReader;
72 import java.io.IOException;
73 import java.io.InputStreamReader;
75 import java.util.ArrayList;
76 import java.util.Hashtable;
77 import java.util.List;
78 import java.util.StringTokenizer;
79 import java.util.Vector;
81 import netscape.javascript.JSObject;
84 * Jalview Applet. Runs in Java 1.18 runtime
87 * @version $Revision: 1.92 $
89 public class JalviewLite extends Applet
90 implements StructureSelectionManagerProvider, JalviewLiteJsApi
93 private static final String TRUE = "true";
95 private static final String FALSE = "false";
97 public StructureSelectionManager getStructureSelectionManager()
99 return StructureSelectionManager.getStructureSelectionManager(this);
102 // /////////////////////////////////////////
103 // The following public methods may be called
104 // externally, eg via javascript in HTML page
108 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences()
111 public String getSelectedSequences()
113 return getSelectedSequencesFrom(getDefaultTargetFrame());
119 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences(java.lang.String)
122 public String getSelectedSequences(String sep)
124 return getSelectedSequencesFrom(getDefaultTargetFrame(), sep);
131 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
135 public String getSelectedSequencesFrom(AlignFrame alf)
137 return getSelectedSequencesFrom(alf, separator); // ""+0x00AC);
144 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
145 * .AlignFrame, java.lang.String)
148 public String getSelectedSequencesFrom(AlignFrame alf, String sep)
150 StringBuffer result = new StringBuffer("");
151 if (sep == null || sep.length() == 0)
153 sep = separator; // "+0x00AC;
155 if (alf.viewport.getSelectionGroup() != null)
157 SequenceI[] seqs = alf.viewport.getSelectionGroup()
158 .getSequencesInOrder(alf.viewport.getAlignment());
160 for (int i = 0; i < seqs.length; i++)
162 result.append(seqs[i].getName());
167 return result.toString();
173 * @see jalview.bin.JalviewLiteJsApi#highlight(java.lang.String,
174 * java.lang.String, java.lang.String)
177 public void highlight(String sequenceId, String position,
178 String alignedPosition)
180 highlightIn(getDefaultTargetFrame(), sequenceId, position,
187 * @see jalview.bin.JalviewLiteJsApi#highlightIn(jalview.appletgui.AlignFrame,
188 * java.lang.String, java.lang.String, java.lang.String)
191 public void highlightIn(final AlignFrame alf, final String sequenceId,
192 final String position, final String alignedPosition)
194 // TODO: could try to highlight in all alignments if alf==null
195 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
196 alf.viewport.getAlignment().getSequencesArray());
197 final SequenceI sq = matcher.findIdMatch(sequenceId);
203 apos = Integer.valueOf(position).intValue();
205 } catch (NumberFormatException ex)
209 final StructureSelectionManagerProvider me = this;
210 final int pos = apos;
211 // use vamsas listener to broadcast to all listeners in scope
212 if (alignedPosition != null && (alignedPosition.trim().length() == 0
213 || alignedPosition.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 = Integer.valueOf(cl.substring(0, p)).intValue();
344 } catch (NumberFormatException ex)
347 "ERROR: Couldn't parse first integer in range element column selection string '"
348 + cl + "' - format is 'from-to'");
353 to = Integer.valueOf(cl.substring(p + 1)).intValue();
355 } catch (NumberFormatException ex)
358 "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 = Integer.valueOf(cl).intValue();
415 } catch (NumberFormatException ex)
417 if (cl.toLowerCase().equals("sequence"))
419 // we are in the dataset sequence's coordinate frame.
425 "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<>(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,
490 alf.getAlignViewport().getAlignment().getHiddenColumns());
500 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignment(java.lang.
501 * String, java.lang.String)
504 public String getSelectedSequencesAsAlignment(String format,
507 return getSelectedSequencesAsAlignmentFrom(getDefaultTargetFrame(),
515 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignmentFrom(jalview
516 * .appletgui.AlignFrame, java.lang.String, java.lang.String)
519 public String getSelectedSequencesAsAlignmentFrom(AlignFrame alf,
520 String format, String suffix)
524 FileFormatI theFormat = FileFormats.getInstance().forName(format);
525 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
526 if (alf.viewport.getSelectionGroup() != null)
528 // JBPNote: getSelectionAsNewSequence behaviour has changed - this
529 // method now returns a full copy of sequence data
530 // TODO consider using getSequenceSelection instead here
531 String reply = new AppletFormatAdapter().formatSequences(theFormat,
532 new Alignment(alf.viewport.getSelectionAsNewSequence()),
536 } catch (IllegalArgumentException ex)
538 ex.printStackTrace();
539 return "Error retrieving alignment, possibly invalid format specifier: "
548 * @see jalview.bin.JalviewLiteJsApi#getAlignmentOrder()
551 public String getAlignmentOrder()
553 return getAlignmentOrderFrom(getDefaultTargetFrame());
560 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
564 public String getAlignmentOrderFrom(AlignFrame alf)
566 return getAlignmentOrderFrom(alf, separator);
573 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
574 * , java.lang.String)
577 public String getAlignmentOrderFrom(AlignFrame alf, String sep)
579 AlignmentI alorder = alf.getAlignViewport().getAlignment();
580 String[] order = new String[alorder.getHeight()];
581 for (int i = 0; i < order.length; i++)
583 order[i] = alorder.getSequenceAt(i).getName();
585 return arrayToSeparatorList(order);
591 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
595 public String orderBy(String order, String undoName)
597 return orderBy(order, undoName, separator);
603 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
604 * java.lang.String, java.lang.String)
607 public String orderBy(String order, String undoName, String sep)
609 return orderAlignmentBy(getDefaultTargetFrame(), order, undoName, sep);
616 * jalview.bin.JalviewLiteJsApi#orderAlignmentBy(jalview.appletgui.AlignFrame,
617 * java.lang.String, java.lang.String, java.lang.String)
620 public String orderAlignmentBy(AlignFrame alf, String order,
621 String undoName, String sep)
623 String[] ids = separatorListToArray(order, sep);
624 SequenceI[] sqs = null;
625 if (ids != null && ids.length > 0)
627 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
628 alf.viewport.getAlignment().getSequencesArray());
630 sqs = new SequenceI[ids.length];
631 for (int i = 0; i < ids.length; i++)
633 if (ids[i].trim().length() == 0)
637 SequenceI sq = matcher.findIdMatch(ids[i]);
645 SequenceI[] sqq = new SequenceI[s];
646 System.arraycopy(sqs, 0, sqq, 0, s);
659 final AlignmentOrder aorder = new AlignmentOrder(sqs);
661 if (undoName != null && undoName.trim().length() == 0)
665 final String _undoName = undoName;
666 // TODO: deal with synchronization here: cannot raise any events until after
667 // this has returned.
668 return alf.sortBy(aorder, _undoName) ? TRUE : "";
674 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String)
677 public String getAlignment(String format)
679 return getAlignmentFrom(getDefaultTargetFrame(), format, TRUE);
686 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
690 public String getAlignmentFrom(AlignFrame alf, String format)
692 return getAlignmentFrom(alf, format, TRUE);
698 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String,
702 public String getAlignment(String format, String suffix)
704 return getAlignmentFrom(getDefaultTargetFrame(), format, suffix);
711 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
712 * java.lang.String, java.lang.String)
715 public String getAlignmentFrom(AlignFrame alf, String format,
720 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
722 FileFormatI theFormat = FileFormats.getInstance().forName(format);
723 String reply = new AppletFormatAdapter().formatSequences(theFormat,
724 alf.viewport.getAlignment(), seqlimits);
726 } catch (IllegalArgumentException ex)
728 ex.printStackTrace();
729 return "Error retrieving alignment, possibly invalid format specifier: "
737 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
740 public void loadAnnotation(String annotation)
742 loadAnnotationFrom(getDefaultTargetFrame(), annotation);
749 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
750 * , java.lang.String)
753 public void loadAnnotationFrom(AlignFrame alf, String annotation)
755 if (new AnnotationFile().annotateAlignmentView(alf.getAlignViewport(),
756 annotation, DataSourceType.PASTE))
758 alf.alignPanel.fontChanged();
759 alf.alignPanel.setScrollValues(0, 0);
763 alf.parseFeaturesFile(annotation, DataSourceType.PASTE);
770 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
773 public void loadFeatures(String features, boolean autoenabledisplay)
775 loadFeaturesFrom(getDefaultTargetFrame(), features, autoenabledisplay);
782 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
783 * , java.lang.String)
786 public boolean loadFeaturesFrom(AlignFrame alf, String features,
787 boolean autoenabledisplay)
789 return alf.parseFeaturesFile(features, DataSourceType.PASTE,
796 * @see jalview.bin.JalviewLiteJsApi#getFeatures(java.lang.String)
799 public String getFeatures(String format)
801 return getFeaturesFrom(getDefaultTargetFrame(), format);
808 * jalview.bin.JalviewLiteJsApi#getFeaturesFrom(jalview.appletgui.AlignFrame,
812 public String getFeaturesFrom(AlignFrame alf, String format)
814 return alf.outputFeatures(false, format);
820 * @see jalview.bin.JalviewLiteJsApi#getAnnotation()
823 public String getAnnotation()
825 return getAnnotationFrom(getDefaultTargetFrame());
832 * jalview.bin.JalviewLiteJsApi#getAnnotationFrom(jalview.appletgui.AlignFrame
836 public String getAnnotationFrom(AlignFrame alf)
838 return alf.outputAnnotations(false);
844 * @see jalview.bin.JalviewLiteJsApi#newView()
847 public AlignFrame newView()
849 return newViewFrom(getDefaultTargetFrame());
855 * @see jalview.bin.JalviewLiteJsApi#newView(java.lang.String)
858 public AlignFrame newView(String name)
860 return newViewFrom(getDefaultTargetFrame(), name);
866 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame)
869 public AlignFrame newViewFrom(AlignFrame alf)
871 return alf.newView(null);
877 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame,
881 public AlignFrame newViewFrom(AlignFrame alf, String name)
883 return alf.newView(name);
889 * @see jalview.bin.JalviewLiteJsApi#loadAlignment(java.lang.String,
893 public AlignFrame loadAlignment(String text, String title)
895 AlignmentI al = null;
899 FileFormatI format = new IdentifyFile().identify(text,
900 DataSourceType.PASTE);
901 al = new AppletFormatAdapter().readFile(text, DataSourceType.PASTE,
903 if (al.getHeight() > 0)
905 return new AlignFrame(al, this, title, false);
907 } catch (IOException ex)
909 ex.printStackTrace();
917 * @see jalview.bin.JalviewLiteJsApi#setMouseoverListener(java.lang.String)
920 public void setMouseoverListener(String listener)
922 setMouseoverListener(currentAlignFrame, listener);
925 private Vector<JSFunctionExec> javascriptListeners = new Vector<>();
931 * jalview.bin.JalviewLiteJsApi#setMouseoverListener(jalview.appletgui.AlignFrame
932 * , java.lang.String)
935 public void setMouseoverListener(AlignFrame af, String listener)
937 if (listener != null)
939 listener = listener.trim();
940 if (listener.length() == 0)
943 "jalview Javascript error: Ignoring empty function for mouseover listener.");
947 MouseOverListener mol = new MouseOverListener(
949 javascriptListeners.addElement(mol);
950 StructureSelectionManager.getStructureSelectionManager(this)
951 .addStructureViewerListener(mol);
954 System.err.println("Added a mouseover listener for "
955 + ((af == null) ? "All frames"
957 + af.getAlignViewport().getSequenceSetId()));
958 System.err.println("There are now " + javascriptListeners.size()
959 + " listeners in total.");
966 * @see jalview.bin.JalviewLiteJsApi#setSelectionListener(java.lang.String)
969 public void setSelectionListener(String listener)
971 setSelectionListener(null, listener);
978 * jalview.bin.JalviewLiteJsApi#setSelectionListener(jalview.appletgui.AlignFrame
979 * , java.lang.String)
982 public void setSelectionListener(AlignFrame af, String listener)
984 if (listener != null)
986 listener = listener.trim();
987 if (listener.length() == 0)
990 "jalview Javascript error: Ignoring empty function for selection listener.");
994 JsSelectionSender mol = new JsSelectionSender(
996 javascriptListeners.addElement(mol);
997 StructureSelectionManager.getStructureSelectionManager(this)
998 .addSelectionListener(mol);
1001 System.err.println("Added a selection listener for "
1002 + ((af == null) ? "All frames"
1004 + af.getAlignViewport().getSequenceSetId()));
1005 System.err.println("There are now " + javascriptListeners.size()
1006 + " listeners in total.");
1011 * Callable from javascript to register a javascript function to pass events
1012 * to a structure viewer.
1015 * the name of a javascript function
1017 * a token separated list of PDB file names listened for
1018 * @see jalview.bin.JalviewLiteJsApi#setStructureListener(java.lang.String,
1022 public void setStructureListener(String listener, String modelSet)
1024 if (listener != null)
1026 listener = listener.trim();
1027 if (listener.length() == 0)
1030 "jalview Javascript error: Ignoring empty function for selection listener.");
1034 MouseOverStructureListener mol = new MouseOverStructureListener(this,
1035 listener, separatorListToArray(modelSet));
1036 javascriptListeners.addElement(mol);
1037 StructureSelectionManager.getStructureSelectionManager(this)
1038 .addStructureViewerListener(mol);
1041 System.err.println("Added a javascript structure viewer listener '"
1043 System.err.println("There are now " + javascriptListeners.size()
1044 + " listeners in total.");
1052 * jalview.bin.JalviewLiteJsApi#removeJavascriptListener(jalview.appletgui
1053 * .AlignFrame, java.lang.String)
1056 public void removeJavascriptListener(AlignFrame af, String listener)
1058 if (listener != null)
1060 listener = listener.trim();
1061 if (listener.length() == 0)
1066 boolean rprt = false;
1067 for (int ms = 0, msSize = javascriptListeners.size(); ms < msSize;)
1069 Object lstn = javascriptListeners.elementAt(ms);
1070 JsCallBack lstner = (JsCallBack) lstn;
1071 if ((af == null || lstner.getAlignFrame() == af) && (listener == null
1072 || lstner.getListenerFunction().equals(listener)))
1074 javascriptListeners.removeElement(lstner);
1076 if (lstner instanceof SelectionListener)
1078 StructureSelectionManager.getStructureSelectionManager(this)
1079 .removeSelectionListener((SelectionListener) lstner);
1083 StructureSelectionManager.getStructureSelectionManager(this)
1084 .removeStructureViewerListener(lstner, null);
1089 System.err.println("Removed listener '" + listener + "'");
1099 System.err.println("There are now " + javascriptListeners.size()
1100 + " listeners in total.");
1107 System.err.println("Applet " + getName() + " stop().");
1112 public void destroy()
1114 System.err.println("Applet " + getName() + " destroy().");
1118 private void tidyUp()
1121 if (currentAlignFrame != null && currentAlignFrame.viewport != null
1122 && currentAlignFrame.viewport.applet != null)
1124 AlignViewport av = currentAlignFrame.viewport;
1125 currentAlignFrame.closeMenuItem_actionPerformed();
1127 currentAlignFrame = null;
1129 if (javascriptListeners != null)
1131 while (javascriptListeners.size() > 0)
1133 JSFunctionExec mol = javascriptListeners
1135 javascriptListeners.removeElement(mol);
1136 if (mol instanceof SelectionListener)
1138 StructureSelectionManager.getStructureSelectionManager(this)
1139 .removeSelectionListener((SelectionListener) mol);
1143 StructureSelectionManager.getStructureSelectionManager(this)
1144 .removeStructureViewerListener(mol, null);
1149 if (jsFunctionExec != null)
1151 jsFunctionExec.stopQueue();
1152 jsFunctionExec.jvlite = null;
1154 initialAlignFrame = null;
1155 jsFunctionExec = null;
1156 javascriptListeners = null;
1157 StructureSelectionManager.release(this);
1160 private JSFunctionExec jsFunctionExec;
1165 * @see jalview.bin.JalviewLiteJsApi#mouseOverStructure(java.lang.String,
1166 * java.lang.String, java.lang.String)
1169 public void mouseOverStructure(final String pdbResNum, final String chain,
1170 final String pdbfile)
1172 final StructureSelectionManagerProvider me = this;
1173 java.awt.EventQueue.invokeLater(new Runnable()
1180 StructureSelectionManager.getStructureSelectionManager(me)
1181 .mouseOverStructure(Integer.valueOf(pdbResNum).intValue(),
1186 .println("mouseOver for '" + pdbResNum + "' in chain '"
1187 + chain + "' in structure '" + pdbfile + "'");
1189 } catch (NumberFormatException e)
1191 System.err.println("Ignoring invalid residue number string '"
1203 * jalview.bin.JalviewLiteJsApi#scrollViewToIn(jalview.appletgui.AlignFrame,
1204 * java.lang.String, java.lang.String)
1207 public void scrollViewToIn(final AlignFrame alf, final String topRow,
1208 final String leftHandColumn)
1210 java.awt.EventQueue.invokeLater(new Runnable()
1217 alf.scrollTo(Integer.valueOf(topRow).intValue(),
1218 Integer.valueOf(leftHandColumn).intValue());
1220 } catch (Exception ex)
1222 System.err.println("Couldn't parse integer arguments (topRow='"
1223 + topRow + "' and leftHandColumn='" + leftHandColumn
1225 ex.printStackTrace();
1235 * JalviewLiteJsApi#scrollViewToRowIn(jalview.appletgui
1236 * .AlignFrame, java.lang.String)
1239 public void scrollViewToRowIn(final AlignFrame alf, final String topRow)
1242 java.awt.EventQueue.invokeLater(new Runnable()
1249 alf.scrollToRow(Integer.valueOf(topRow).intValue());
1251 } catch (Exception ex)
1253 System.err.println("Couldn't parse integer arguments (topRow='"
1255 ex.printStackTrace();
1266 * JalviewLiteJsApi#scrollViewToColumnIn(jalview.appletgui
1267 * .AlignFrame, java.lang.String)
1270 public void scrollViewToColumnIn(final AlignFrame alf,
1271 final String leftHandColumn)
1273 java.awt.EventQueue.invokeLater(new Runnable()
1281 alf.scrollToColumn(Integer.valueOf(leftHandColumn).intValue());
1283 } catch (Exception ex)
1286 "Couldn't parse integer arguments (leftHandColumn='"
1287 + leftHandColumn + "')");
1288 ex.printStackTrace();
1295 // //////////////////////////////////////////////
1296 // //////////////////////////////////////////////
1298 public static int lastFrameX = 200;
1300 public static int lastFrameY = 200;
1302 boolean fileFound = true;
1304 String file = "No file";
1306 String file2 = null;
1308 Button launcher = new Button(
1309 MessageManager.getString("label.start_jalview"));
1312 * The currentAlignFrame is static, it will change if and when the user
1313 * selects a new window. Note that it will *never* point back to the embedded
1314 * AlignFrame if the applet is started as embedded on the page and then
1315 * afterwards a new view is created.
1317 public AlignFrame currentAlignFrame = null;
1320 * This is the first frame to be displayed, and does not change. API calls
1321 * will default to this instance if currentAlignFrame is null.
1323 AlignFrame initialAlignFrame = null;
1325 boolean embedded = false;
1327 private boolean checkForJmol = true;
1329 private boolean checkedForJmol = false; // ensure we don't check for jmol
1331 // every time the app is re-inited
1333 public boolean jmolAvailable = false;
1335 private boolean alignPdbStructures = false;
1338 * use an external structure viewer exclusively (no jmols or mc_views will be
1339 * opened by JalviewLite itself)
1341 public boolean useXtrnalSviewer = false;
1343 public static boolean debug = false;
1345 static String builddate = null, version = null, installation = null;
1347 private static void initBuildDetails()
1349 if (builddate == null)
1351 builddate = "unknown";
1353 installation = "applet";
1354 java.net.URL url = JalviewLite.class
1355 .getResource("/.build_properties");
1360 BufferedReader reader = new BufferedReader(
1361 new InputStreamReader(url.openStream()));
1363 while ((line = reader.readLine()) != null)
1365 if (line.indexOf("VERSION") > -1)
1367 version = line.substring(line.indexOf("=") + 1);
1369 if (line.indexOf("BUILD_DATE") > -1)
1371 builddate = line.substring(line.indexOf("=") + 1);
1373 if (line.indexOf("INSTALLATION") > -1)
1375 installation = line.substring(line.indexOf("=") + 1);
1378 } catch (Exception ex)
1380 ex.printStackTrace();
1386 public static String getBuildDate()
1392 public static String getInstallation()
1395 return installation;
1398 public static String getVersion()
1404 // public JSObject scriptObject = null;
1407 * init method for Jalview Applet
1412 debug = TRUE.equalsIgnoreCase(getParameter("debug"));
1417 System.err.println("Applet context is '"
1418 + getAppletContext().getClass().toString() + "'");
1420 JSObject scriptObject = JSObject.getWindow(this);
1421 if (debug && scriptObject != null)
1423 System.err.println("Applet has Javascript callback support.");
1426 } catch (Exception ex)
1429 "Warning: No JalviewLite javascript callbacks available.");
1432 ex.printStackTrace();
1438 System.err.println("JalviewLite Version " + getVersion());
1439 System.err.println("Build Date : " + getBuildDate());
1440 System.err.println("Installation : " + getInstallation());
1442 String externalsviewer = getParameter("externalstructureviewer");
1443 if (externalsviewer != null)
1445 useXtrnalSviewer = externalsviewer.trim().toLowerCase().equals(TRUE);
1448 * if true disable the check for jmol
1450 String chkforJmol = getParameter("nojmol");
1451 if (chkforJmol != null)
1453 checkForJmol = !chkforJmol.equals(TRUE);
1456 * get the separator parameter if present
1458 String sep = getParameter("separator");
1461 if (sep.length() > 0)
1466 System.err.println("Separator set to '" + separator + "'");
1471 throw new Error(MessageManager
1472 .getString("error.invalid_separator_parameter"));
1478 String param = getParameter("RGB");
1484 r = Integer.parseInt(param.substring(0, 2), 16);
1485 g = Integer.parseInt(param.substring(2, 4), 16);
1486 b = Integer.parseInt(param.substring(4, 6), 16);
1487 } catch (Exception ex)
1494 param = getParameter("label");
1497 launcher.setLabel(param);
1500 setBackground(new Color(r, g, b));
1502 file = getParameter("file");
1506 // Maybe the sequences are added as parameters
1507 StringBuffer data = new StringBuffer("PASTE");
1509 while ((file = getParameter("sequence" + i)) != null)
1511 data.append(file.toString() + "\n");
1514 if (data.length() > 5)
1516 file = data.toString();
1519 if (getDefaultParameter("enableSplitFrame", true))
1521 file2 = getParameter("file2");
1524 embedded = TRUE.equalsIgnoreCase(getParameter("embedded"));
1527 LoadingThread loader = new LoadingThread(file, file2, this);
1530 else if (file != null)
1533 * Start the applet immediately or show a button to start it
1535 if (FALSE.equalsIgnoreCase(getParameter("showbutton")))
1537 LoadingThread loader = new LoadingThread(file, file2, this);
1543 launcher.addActionListener(new java.awt.event.ActionListener()
1546 public void actionPerformed(ActionEvent e)
1548 LoadingThread loader = new LoadingThread(file, file2,
1557 // jalview initialisation with no alignment. loadAlignment() method can
1558 // still be called to open new alignments.
1565 private void initLiveConnect()
1567 // try really hard to get the liveConnect thing working
1568 boolean notFailed = false;
1570 while (!notFailed && tries < 10)
1574 System.err.println("LiveConnect request thread going to sleep.");
1578 Thread.sleep(700 * (1 + tries));
1579 } catch (InterruptedException q)
1585 System.err.println("LiveConnect request thread woken up.");
1589 JSObject scriptObject = JSObject.getWindow(this);
1590 if (scriptObject.eval("navigator") != null)
1594 } catch (Exception jsex)
1596 System.err.println("Attempt " + tries
1597 + " to access LiveConnect javascript failed.");
1602 private void callInitCallback()
1604 String initjscallback = getParameter("oninit");
1605 if (initjscallback == null)
1609 initjscallback = initjscallback.trim();
1610 if (initjscallback.length() > 0)
1612 JSObject scriptObject = null;
1615 scriptObject = JSObject.getWindow(this);
1616 } catch (Exception ex)
1620 // try really hard to let the browser plugin know we want liveconnect
1623 if (scriptObject != null)
1627 // do onInit with the JS executor thread
1628 new JSFunctionExec(this).executeJavascriptFunction(true,
1629 initjscallback, null,
1630 "Calling oninit callback '" + initjscallback + "'.");
1631 } catch (Exception e)
1633 System.err.println("Exception when executing _oninit callback '"
1634 + initjscallback + "'.");
1635 e.printStackTrace();
1640 System.err.println("Not executing _oninit callback '"
1641 + initjscallback + "' - no scripting allowed.");
1647 * Initialises and displays a new java.awt.Frame
1650 * java.awt.Frame to be displayed
1652 * title of new frame
1654 * width if new frame
1656 * height of new frame
1658 public static void addFrame(final Frame frame, String title, int width,
1661 frame.setLocation(lastFrameX, lastFrameY);
1664 frame.setSize(width, height);
1665 frame.setTitle(title);
1666 frame.addWindowListener(new WindowAdapter()
1669 public void windowClosing(WindowEvent e)
1671 if (frame instanceof AlignFrame)
1673 AlignViewport vp = ((AlignFrame) frame).viewport;
1674 ((AlignFrame) frame).closeMenuItem_actionPerformed();
1675 if (vp.applet.currentAlignFrame == frame)
1677 vp.applet.currentAlignFrame = null;
1685 if (frame instanceof EmbmenuFrame)
1687 ((EmbmenuFrame) frame).destroyMenus();
1689 frame.setMenuBar(null);
1694 public void windowActivated(WindowEvent e)
1696 if (frame instanceof AlignFrame)
1698 ((AlignFrame) frame).viewport.applet.currentAlignFrame = (AlignFrame) frame;
1701 System.err.println("Activated window " + frame);
1705 super.windowActivated(e);
1708 * Probably not necessary to do this - see TODO above. (non-Javadoc)
1711 * java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent
1714 * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
1715 * frame) { currentAlignFrame = null; if (debug) {
1716 * System.err.println("Deactivated window "+frame); } }
1717 * super.windowDeactivated(e); }
1720 frame.setVisible(true);
1724 * This paints the background surrounding the "Launch Jalview button" <br>
1726 * If file given in parameter not found, displays error message
1732 public void paint(Graphics g)
1736 g.setColor(new Color(200, 200, 200));
1737 g.setColor(Color.cyan);
1738 g.fillRect(0, 0, getSize().width, getSize().height);
1739 g.setColor(Color.red);
1741 MessageManager.getString("label.jalview_cannot_open_file"), 5,
1743 g.drawString("\"" + file + "\"", 5, 30);
1747 g.setColor(Color.black);
1748 g.setFont(new Font("Arial", Font.BOLD, 24));
1749 g.drawString(MessageManager.getString("label.jalview_applet"), 50,
1750 getSize().height / 2 - 30);
1751 g.drawString(MessageManager.getString("label.loading_data") + "...",
1752 50, getSize().height / 2);
1757 * get all components associated with the applet of the given type
1762 public Vector getAppletWindow(Class class1)
1764 Vector wnds = new Vector();
1765 Component[] cmp = getComponents();
1768 for (int i = 0; i < cmp.length; i++)
1770 if (class1.isAssignableFrom(cmp[i].getClass()))
1772 wnds.addElement(cmp);
1779 class LoadJmolThread extends Thread
1781 private boolean running = false;
1786 if (running || checkedForJmol)
1795 if (!System.getProperty("java.version").startsWith("1.1"))
1797 Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
1798 jmolAvailable = true;
1803 "Jmol not available - Using mc_view for structures");
1805 } catch (java.lang.ClassNotFoundException ex)
1811 jmolAvailable = false;
1815 "Skipping Jmol check. Will use mc_view (probably)");
1818 checkedForJmol = true;
1822 public boolean notFinished()
1824 return running || !checkedForJmol;
1828 class LoadingThread extends Thread
1831 * State variable: protocol for access to file source
1833 DataSourceType protocol;
1835 String _file; // alignment file or URL spec
1837 String _file2; // second alignment file or URL spec
1841 private void dbgMsg(String msg)
1843 if (JalviewLite.debug)
1845 System.err.println(msg);
1850 * update the protocol state variable for accessing the datasource located
1854 * @return possibly updated datasource string
1856 public String resolveFileProtocol(String path)
1861 if (path.startsWith("PASTE"))
1863 protocol = DataSourceType.PASTE;
1864 return path.substring(5);
1870 if (path.indexOf("://") != -1)
1872 protocol = DataSourceType.URL;
1877 * try relative to document root
1879 URL documentBase = getDocumentBase();
1880 String withDocBase = resolveUrlForLocalOrAbsolute(path, documentBase);
1881 if (HttpUtils.isValidUrl(withDocBase))
1885 System.err.println("Prepended document base '" + documentBase
1886 + "' to make: '" + withDocBase + "'");
1888 protocol = DataSourceType.URL;
1893 * try relative to codebase (if different to document base)
1895 URL codeBase = getCodeBase();
1896 String withCodeBase = applet.resolveUrlForLocalOrAbsolute(path,
1898 if (!withCodeBase.equals(withDocBase)
1899 && HttpUtils.isValidUrl(withCodeBase))
1901 protocol = DataSourceType.URL;
1904 System.err.println("Prepended codebase '" + codeBase
1905 + "' to make: '" + withCodeBase + "'");
1907 return withCodeBase;
1911 * try locating by classloader; try this last so files in the directory
1912 * are resolved using document base
1914 if (inArchive(path))
1916 protocol = DataSourceType.CLASSLOADER;
1921 public LoadingThread(String file, String file2, JalviewLite _applet)
1924 this._file2 = file2;
1931 LoadJmolThread jmolchecker = new LoadJmolThread();
1932 jmolchecker.start();
1933 while (jmolchecker.notFinished())
1935 // wait around until the Jmol check is complete.
1939 } catch (Exception e)
1944 // applet.callInitCallback();
1948 * Load the alignment and any related files as specified by applet
1951 private void startLoading()
1953 dbgMsg("Loading thread started with:\n>>file\n" + _file
1956 dbgMsg("Loading started.");
1958 AlignFrame newAlignFrame = readAlignment(_file);
1959 AlignFrame newAlignFrame2 = readAlignment(_file2);
1960 if (newAlignFrame != null)
1962 addToDisplay(newAlignFrame, newAlignFrame2);
1963 loadTree(newAlignFrame);
1965 loadScoreFile(newAlignFrame);
1967 loadFeatures(newAlignFrame);
1969 loadAnnotations(newAlignFrame);
1971 loadJnetFile(newAlignFrame);
1973 loadPdbFiles(newAlignFrame);
1978 applet.remove(launcher);
1985 * Add an AlignFrame to the display; or if two are provided, a SplitFrame.
1990 public void addToDisplay(AlignFrame af, AlignFrame af2)
1994 AlignmentI al1 = af.viewport.getAlignment();
1995 AlignmentI al2 = af2.viewport.getAlignment();
1996 AlignmentI cdna = al1.isNucleotide() ? al1 : al2;
1997 AlignmentI prot = al1.isNucleotide() ? al2 : al1;
1998 if (AlignmentUtils.mapProteinAlignmentToCdna(prot, cdna))
2001 SplitFrame sf = new SplitFrame(af, af2);
2002 sf.addToDisplay(embedded, JalviewLite.this);
2007 String msg = "Could not map any sequence in " + af2.getTitle()
2009 + (al1.isNucleotide() ? "protein product" : "cDNA")
2010 + " for " + af.getTitle();
2011 System.err.println(msg);
2015 af.addToDisplay(embedded);
2019 * Read the alignment file (from URL, text 'paste', or archive by
2024 protected AlignFrame readAlignment(String fileParam)
2026 if (fileParam == null)
2030 String resolvedFile = resolveFileProtocol(fileParam);
2031 AlignmentI al = null;
2034 FileFormatI format = new IdentifyFile().identify(resolvedFile,
2036 dbgMsg("File identified as '" + format + "'");
2037 al = new AppletFormatAdapter().readFile(resolvedFile, protocol,
2039 if ((al != null) && (al.getHeight() > 0))
2041 dbgMsg("Successfully loaded file.");
2042 al.setDataset(null);
2043 AlignFrame newAlignFrame = new AlignFrame(al, applet,
2044 resolvedFile, embedded, false);
2045 newAlignFrame.setTitle(resolvedFile);
2046 if (initialAlignFrame == null)
2048 initialAlignFrame = newAlignFrame;
2050 // update the focus.
2051 currentAlignFrame = newAlignFrame;
2053 if (protocol == DataSourceType.PASTE)
2055 newAlignFrame.setTitle(MessageManager
2056 .formatMessage("label.sequences_from", new Object[]
2057 { applet.getDocumentBase().toString() }));
2060 newAlignFrame.statusBar.setText(MessageManager.formatMessage(
2061 "label.successfully_loaded_file", new Object[]
2064 return newAlignFrame;
2066 } catch (java.io.IOException ex)
2068 dbgMsg("File load exception.");
2069 ex.printStackTrace();
2074 FileParse fp = new FileParse(resolvedFile, protocol);
2076 dbgMsg(">>>Dumping contents of '" + resolvedFile + "' " + "("
2078 while ((ln = fp.nextLine()) != null)
2082 dbgMsg(">>>Dump finished.");
2083 } catch (Exception e)
2086 "Exception when trying to dump the content of the file parameter.");
2087 e.printStackTrace();
2095 * Load PDBFiles if any specified by parameter(s). Returns true if loaded,
2101 protected boolean loadPdbFiles(AlignFrame alignFrame)
2103 boolean result = false;
2105 * <param name="alignpdbfiles" value="false/true"/> Undocumented for 2.6 -
2106 * related to JAL-434
2109 applet.setAlignPdbStructures(
2110 getDefaultParameter("alignpdbfiles", false));
2112 * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
2115 * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
2117 * <param name="PDBfile3" value="1q0o Q45135_9MICO">
2120 int pdbFileCount = 0;
2121 // Accumulate pdbs here if they are heading for the same view (if
2122 // alignPdbStructures is true)
2123 Vector pdbs = new Vector();
2124 // create a lazy matcher if we're asked to
2125 jalview.analysis.SequenceIdMatcher matcher = (applet
2126 .getDefaultParameter("relaxedidmatch", false))
2127 ? new jalview.analysis.SequenceIdMatcher(
2128 alignFrame.getAlignViewport().getAlignment()
2129 .getSequencesArray())
2135 if (pdbFileCount > 0)
2137 param = applet.getParameter("PDBFILE" + pdbFileCount);
2141 param = applet.getParameter("PDBFILE");
2146 PDBEntry pdb = new PDBEntry();
2149 SequenceI[] seqs = null;
2150 String[] chains = null;
2152 StringTokenizer st = new StringTokenizer(param, " ");
2154 if (st.countTokens() < 2)
2156 String sequence = applet.getParameter("PDBSEQ");
2157 if (sequence != null)
2159 seqs = new SequenceI[] { matcher == null
2160 ? (Sequence) alignFrame.getAlignViewport()
2161 .getAlignment().findName(sequence)
2162 : matcher.findIdMatch(sequence) };
2168 param = st.nextToken();
2169 List<SequenceI> tmp = new ArrayList<>();
2170 List<String> tmp2 = new ArrayList<>();
2172 while (st.hasMoreTokens())
2174 seqstring = st.nextToken();
2175 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
2176 if (st2.countTokens() > 1)
2178 // This is the chain
2179 tmp2.add(st2.nextToken());
2180 seqstring = st2.nextToken();
2182 tmp.add(matcher == null
2183 ? (Sequence) alignFrame.getAlignViewport()
2184 .getAlignment().findName(seqstring)
2185 : matcher.findIdMatch(seqstring));
2188 seqs = tmp.toArray(new SequenceI[tmp.size()]);
2189 if (tmp2.size() == tmp.size())
2191 chains = tmp2.toArray(new String[tmp2.size()]);
2194 param = resolveFileProtocol(param);
2195 // TODO check JAL-357 for files in a jar (CLASSLOADER)
2200 for (int i = 0; i < seqs.length; i++)
2202 if (seqs[i] != null)
2204 ((Sequence) seqs[i]).addPDBId(pdb);
2205 StructureSelectionManager
2206 .getStructureSelectionManager(applet)
2207 .registerPDBEntry(pdb);
2211 if (JalviewLite.debug)
2213 // this may not really be a problem but we give a warning
2216 "Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
2222 if (!alignPdbStructures)
2224 alignFrame.newStructureView(applet, pdb, seqs, chains,
2229 pdbs.addElement(new Object[] { pdb, seqs, chains, protocol });
2235 } while (param != null || pdbFileCount < 10);
2236 if (pdbs.size() > 0)
2238 SequenceI[][] seqs = new SequenceI[pdbs.size()][];
2239 PDBEntry[] pdb = new PDBEntry[pdbs.size()];
2240 String[][] chains = new String[pdbs.size()][];
2241 String[] protocols = new String[pdbs.size()];
2242 for (int pdbsi = 0, pdbsiSize = pdbs
2243 .size(); pdbsi < pdbsiSize; pdbsi++)
2245 Object[] o = (Object[]) pdbs.elementAt(pdbsi);
2246 pdb[pdbsi] = (PDBEntry) o[0];
2247 seqs[pdbsi] = (SequenceI[]) o[1];
2248 chains[pdbsi] = (String[]) o[2];
2249 protocols[pdbsi] = (String) o[3];
2251 alignFrame.alignedStructureView(applet, pdb, seqs, chains,
2259 * Load in a Jnetfile if specified by parameter. Returns true if loaded,
2265 protected boolean loadJnetFile(AlignFrame alignFrame)
2267 boolean result = false;
2268 String param = applet.getParameter("jnetfile");
2271 // jnet became jpred around 2016
2272 param = applet.getParameter("jpredfile");
2278 param = resolveFileProtocol(param);
2279 JPredFile predictions = new JPredFile(param, protocol);
2280 JnetAnnotationMaker.add_annotation(predictions,
2281 alignFrame.viewport.getAlignment(), 0, false);
2282 // false == do not add sequence profile from concise output
2284 alignFrame.viewport.getAlignment().setupJPredAlignment();
2286 alignFrame.alignPanel.fontChanged();
2287 alignFrame.alignPanel.setScrollValues(0, 0);
2289 } catch (Exception ex)
2291 ex.printStackTrace();
2298 * Load annotations if specified by parameter. Returns true if loaded, else
2304 protected boolean loadAnnotations(AlignFrame alignFrame)
2306 boolean result = false;
2307 String param = applet.getParameter("annotations");
2310 param = resolveFileProtocol(param);
2312 if (new AnnotationFile().annotateAlignmentView(alignFrame.viewport,
2315 alignFrame.alignPanel.fontChanged();
2316 alignFrame.alignPanel.setScrollValues(0, 0);
2322 "Annotations were not added from annotation file '"
2330 * Load features file and view settings as specified by parameters. Returns
2331 * true if features were loaded, else false.
2336 protected boolean loadFeatures(AlignFrame alignFrame)
2338 boolean result = false;
2339 // ///////////////////////////
2340 // modify display of features
2341 // we do this before any features have been loaded, ensuring any hidden
2342 // groups are hidden when features first displayed
2344 // hide specific groups
2346 String param = applet.getParameter("hidefeaturegroups");
2349 alignFrame.setFeatureGroupState(separatorListToArray(param), false);
2350 // applet.setFeatureGroupStateOn(newAlignFrame, param, false);
2352 // show specific groups
2353 param = applet.getParameter("showfeaturegroups");
2356 alignFrame.setFeatureGroupState(separatorListToArray(param), true);
2357 // applet.setFeatureGroupStateOn(newAlignFrame, param, true);
2359 // and now load features
2360 param = applet.getParameter("features");
2363 param = resolveFileProtocol(param);
2365 result = alignFrame.parseFeaturesFile(param, protocol);
2368 param = applet.getParameter("showFeatureSettings");
2369 if (param != null && param.equalsIgnoreCase(TRUE))
2371 alignFrame.viewport.setShowSequenceFeatures(true);
2372 new FeatureSettings(alignFrame.alignPanel);
2378 * Load a score file if specified by parameter. Returns true if file was
2379 * loaded, else false.
2383 protected boolean loadScoreFile(AlignFrame alignFrame)
2385 boolean result = false;
2386 String sScoreFile = applet.getParameter("scoreFile");
2387 if (sScoreFile != null && !"".equals(sScoreFile))
2394 "Attempting to load T-COFFEE score file from the scoreFile parameter");
2396 result = alignFrame.loadScoreFile(sScoreFile);
2400 "Failed to parse T-COFFEE parameter as a valid score file ('"
2401 + sScoreFile + "')");
2403 } catch (Exception e)
2405 System.err.printf("Cannot read score file: '%s'. Cause: %s \n",
2406 sScoreFile, e.getMessage());
2413 * Load a tree for the alignment if specified by parameter. Returns true if
2414 * a tree was loaded, else false.
2419 protected boolean loadTree(AlignFrame alignFrame)
2421 boolean result = false;
2422 String treeFile = applet.getParameter("tree");
2423 if (treeFile == null)
2425 treeFile = applet.getParameter("treeFile");
2428 if (treeFile != null)
2432 treeFile = resolveFileProtocol(treeFile);
2433 NewickFile fin = new NewickFile(treeFile, protocol);
2436 if (fin.getTree() != null)
2438 alignFrame.loadTree(fin, treeFile);
2440 dbgMsg("Successfully imported tree.");
2444 dbgMsg("Tree parameter did not resolve to a valid tree.");
2446 } catch (Exception ex)
2448 ex.printStackTrace();
2455 * Discovers whether the given file is in the Applet Archive
2461 boolean inArchive(String f)
2463 // This might throw a security exception in certain browsers
2464 // Netscape Communicator for instance.
2467 boolean rtn = (getClass().getResourceAsStream("/" + f) != null);
2470 System.err.println("Resource '" + f + "' was "
2471 + (rtn ? "" : "not ") + "located by classloader.");
2474 } catch (Exception ex)
2476 System.out.println("Exception checking resources: " + f + " " + ex);
2483 * @return the default alignFrame acted on by the public applet methods. May
2484 * return null with an error message on System.err indicating the
2487 public AlignFrame getDefaultTargetFrame()
2489 if (currentAlignFrame != null)
2491 return currentAlignFrame;
2493 if (initialAlignFrame != null)
2495 return initialAlignFrame;
2498 "Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
2503 * separator used for separatorList
2505 protected String separator = "" + ((char) 0x00AC); // the default used to be
2506 // '|' but many sequence
2507 // IDS include pipes.
2510 * set to enable the URL based javascript execution mechanism
2512 public boolean jsfallbackEnabled = false;
2515 * parse the string into a list
2518 * @return elements separated by separator
2520 public String[] separatorListToArray(String list)
2522 return separatorListToArray(list, separator);
2526 * parse the string into a list
2530 * @return elements separated by separator
2532 public static String[] separatorListToArray(String list, String separator)
2534 // TODO use StringUtils version (slightly different...)
2535 int seplen = separator.length();
2536 if (list == null || list.equals("") || list.equals(separator))
2540 java.util.Vector jv = new Vector();
2542 while ((pos = list.indexOf(separator, cp)) > cp)
2544 jv.addElement(list.substring(cp, pos));
2547 if (cp < list.length())
2549 String c = list.substring(cp);
2550 if (!c.equals(separator))
2557 String[] v = new String[jv.size()];
2558 for (int i = 0; i < v.length; i++)
2560 v[i] = (String) jv.elementAt(i);
2562 jv.removeAllElements();
2565 System.err.println("Array from '" + separator
2566 + "' separated List:\n" + v.length);
2567 for (int i = 0; i < v.length; i++)
2569 System.err.println("item " + i + " '" + v[i] + "'");
2577 "Empty Array from '" + separator + "' separated List");
2583 * concatenate the list with separator
2586 * @return concatenated string
2588 public String arrayToSeparatorList(String[] list)
2590 return arrayToSeparatorList(list, separator);
2594 * concatenate the list with separator
2598 * @return concatenated string
2600 public static String arrayToSeparatorList(String[] list, String separator)
2602 // TODO use StringUtils version
2603 StringBuffer v = new StringBuffer();
2604 if (list != null && list.length > 0)
2606 for (int i = 0, iSize = list.length; i < iSize; i++)
2608 if (list[i] != null)
2612 v.append(separator);
2620 .println("Returning '" + separator + "' separated List:\n");
2621 System.err.println(v);
2623 return v.toString();
2628 "Returning empty '" + separator + "' separated List\n");
2630 return "" + separator;
2636 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroups()
2639 public String getFeatureGroups()
2641 String lst = arrayToSeparatorList(
2642 getDefaultTargetFrame().getFeatureGroups());
2650 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOn(jalview.appletgui.AlignFrame
2654 public String getFeatureGroupsOn(AlignFrame alf)
2656 String lst = arrayToSeparatorList(alf.getFeatureGroups());
2663 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfState(boolean)
2666 public String getFeatureGroupsOfState(boolean visible)
2668 return arrayToSeparatorList(
2669 getDefaultTargetFrame().getFeatureGroupsOfState(visible));
2676 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfStateOn(jalview.appletgui
2677 * .AlignFrame, boolean)
2680 public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
2682 return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
2688 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupStateOn(jalview.appletgui.
2689 * AlignFrame, java.lang.String, boolean)
2692 public void setFeatureGroupStateOn(final AlignFrame alf,
2693 final String groups, boolean state)
2695 final boolean st = state;// !(state==null || state.equals("") ||
2696 // state.toLowerCase().equals("false"));
2697 java.awt.EventQueue.invokeLater(new Runnable()
2702 alf.setFeatureGroupState(separatorListToArray(groups), st);
2710 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupState(java.lang.String,
2714 public void setFeatureGroupState(String groups, boolean state)
2716 setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
2722 * @see jalview.bin.JalviewLiteJsApi#getSeparator()
2725 public String getSeparator()
2733 * @see jalview.bin.JalviewLiteJsApi#setSeparator(java.lang.String)
2736 public void setSeparator(String separator)
2738 if (separator == null || separator.length() < 1)
2741 separator = "" + ((char) 0x00AC);
2743 this.separator = separator;
2746 System.err.println("Default Separator now: '" + separator + "'");
2751 * get boolean value of applet parameter 'name' and return default if
2752 * parameter is not set
2757 * the value to return otherwise
2758 * @return true or false
2760 public boolean getDefaultParameter(String name, boolean def)
2763 if ((stn = getParameter(name)) == null)
2767 if (TRUE.equalsIgnoreCase(stn))
2777 * @see jalview.bin.JalviewLiteJsApi#addPdbFile(jalview.appletgui.AlignFrame,
2778 * java.lang.String, java.lang.String, java.lang.String)
2781 public boolean addPdbFile(AlignFrame alFrame, String sequenceId,
2782 String pdbEntryString, String pdbFile)
2784 return alFrame.addPdbFile(sequenceId, pdbEntryString, pdbFile);
2787 protected void setAlignPdbStructures(boolean alignPdbStructures)
2789 this.alignPdbStructures = alignPdbStructures;
2792 public boolean isAlignPdbStructures()
2794 return alignPdbStructures;
2800 // callInitCallback();
2803 private Hashtable<String, long[]> jshashes = new Hashtable<>();
2805 private Hashtable<String, Hashtable<String, String[]>> jsmessages = new Hashtable<>();
2807 public void setJsMessageSet(String messageclass, String viewId,
2808 String[] colcommands)
2810 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2813 msgset = new Hashtable<>();
2814 jsmessages.put(messageclass, msgset);
2816 msgset.put(viewId, colcommands);
2817 long[] l = new long[colcommands.length];
2818 for (int i = 0; i < colcommands.length; i++)
2820 l[i] = colcommands[i].hashCode();
2822 jshashes.put(messageclass + "|" + viewId, l);
2828 * @see jalview.bin.JalviewLiteJsApi#getJsMessage(java.lang.String,
2832 public String getJsMessage(String messageclass, String viewId)
2834 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2837 String[] msgs = msgset.get(viewId);
2840 for (int i = 0; i < msgs.length; i++)
2842 if (msgs[i] != null)
2854 public boolean isJsMessageSetChanged(String string, String string2,
2855 String[] colcommands)
2857 long[] l = jshashes.get(string + "|" + string2);
2858 if (l == null && colcommands != null)
2862 for (int i = 0; i < colcommands.length; i++)
2864 if (l[i] != colcommands[i].hashCode())
2872 private Vector jsExecQueue = new Vector();
2874 public Vector getJsExecQueue()
2879 public void setExecutor(JSFunctionExec jsFunctionExec2)
2881 jsFunctionExec = jsFunctionExec2;
2885 * return the given colour value parameter or the given default if parameter
2892 public Color getDefaultColourParameter(String colparam, Color defcolour)
2894 String colprop = getParameter(colparam);
2895 if (colprop == null || colprop.trim().length() == 0)
2899 Color col = ColorUtils.parseColourString(colprop);
2902 System.err.println("Couldn't parse '" + colprop + "' as a colour for "
2905 return (col == null) ? defcolour : col;
2908 public void openJalviewHelpUrl()
2910 String helpUrl = getParameter("jalviewhelpurl");
2911 if (helpUrl == null || helpUrl.trim().length() < 5)
2913 helpUrl = "http://www.jalview.org/help.html";
2915 showURL(helpUrl, "HELP");
2919 * form a complete URL given a path to a resource and a reference location on
2923 * - an absolute path on the same server as localref or a document
2924 * located relative to localref
2926 * - a URL on the same server as url
2927 * @return a complete URL for the resource located by url
2929 private String resolveUrlForLocalOrAbsolute(String targetPath,
2932 String resolvedPath = "";
2933 if (targetPath.startsWith("/"))
2935 String codebase = localref.toString();
2936 String localfile = localref.getFile();
2937 resolvedPath = codebase.substring(0,
2938 codebase.length() - localfile.length()) + targetPath;
2939 return resolvedPath;
2943 * get URL path and strip off any trailing file e.g.
2944 * www.jalview.org/examples/index.html#applets?a=b is trimmed to
2945 * www.jalview.org/examples/
2947 String urlPath = localref.toString();
2948 String directoryPath = urlPath;
2949 int lastSeparator = directoryPath.lastIndexOf("/");
2950 if (lastSeparator > 0)
2952 directoryPath = directoryPath.substring(0, lastSeparator + 1);
2955 if (targetPath.startsWith("/"))
2958 * construct absolute URL to a file on the server - this is not allowed?
2960 // String localfile = localref.getFile();
2961 // resolvedPath = urlPath.substring(0,
2962 // urlPath.length() - localfile.length())
2964 resolvedPath = directoryPath + targetPath.substring(1);
2968 resolvedPath = directoryPath + targetPath;
2973 "resolveUrlForLocalOrAbsolute returning " + resolvedPath);
2975 return resolvedPath;
2979 * open a URL in the browser - resolving it according to relative refs and
2980 * coping with javascript: protocol if necessary.
2985 public void showURL(String url, String target)
2989 if (url.indexOf(":") == -1)
2991 // TODO: verify (Bas Vroling bug) prepend codebase or server URL to
2993 // Should really use docbase, not codebase.
2995 url = resolveUrlForLocalOrAbsolute(url,
2996 prepend = getDefaultParameter("resolvetocodebase", false)
2998 : getDocumentBase());
3001 System.err.println("Show url (prepended " + prepend
3002 + " - toggle resolvetocodebase if code/docbase resolution is wrong): "
3010 System.err.println("Show url: " + url);
3013 if (url.indexOf("javascript:") == 0)
3015 // no target for the javascript context
3016 getAppletContext().showDocument(new java.net.URL(url));
3020 getAppletContext().showDocument(new java.net.URL(url), target);
3022 } catch (Exception ex)
3024 ex.printStackTrace();
3029 * bind structures in a viewer to any matching sequences in an alignFrame (use
3030 * sequenceIds to limit scope of search to specific sequences)
3034 * @param sequenceIds
3035 * @return TODO: consider making an exception structure for indicating when
3036 * binding fails public SequenceStructureBinding
3037 * addStructureViewInstance( AlignFrame alFrame, Object viewer, String
3040 * if (sequenceIds != null && sequenceIds.length() > 0) { return
3041 * alFrame.addStructureViewInstance(viewer,
3042 * separatorListToArray(sequenceIds)); } else { return
3043 * alFrame.addStructureViewInstance(viewer, null); } // return null; }