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 java.util.Locale;
25 import jalview.analysis.AlignmentUtils;
26 import jalview.api.StructureSelectionManagerProvider;
27 import jalview.appletgui.AlignFrame;
28 import jalview.appletgui.AlignViewport;
29 import jalview.appletgui.EmbmenuFrame;
30 import jalview.appletgui.FeatureSettings;
31 import jalview.appletgui.SplitFrame;
32 import jalview.datamodel.Alignment;
33 import jalview.datamodel.AlignmentI;
34 import jalview.datamodel.AlignmentOrder;
35 import jalview.datamodel.ColumnSelection;
36 import jalview.datamodel.PDBEntry;
37 import jalview.datamodel.Sequence;
38 import jalview.datamodel.SequenceGroup;
39 import jalview.datamodel.SequenceI;
40 import jalview.io.AnnotationFile;
41 import jalview.io.AppletFormatAdapter;
42 import jalview.io.DataSourceType;
43 import jalview.io.FileFormatI;
44 import jalview.io.FileFormats;
45 import jalview.io.FileParse;
46 import jalview.io.IdentifyFile;
47 import jalview.io.JPredFile;
48 import jalview.io.JnetAnnotationMaker;
49 import jalview.io.NewickFile;
50 import jalview.javascript.JSFunctionExec;
51 import jalview.javascript.JalviewLiteJsApi;
52 import jalview.javascript.JsCallBack;
53 import jalview.javascript.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
213 && (alignedPosition.trim().length() == 0 || alignedPosition
214 .toLowerCase(Locale.ROOT).indexOf("false") > -1))
216 java.awt.EventQueue.invokeLater(new Runnable()
221 StructureSelectionManager.getStructureSelectionManager(me)
222 .mouseOverVamsasSequence(sq, sq.findIndex(pos), null);
228 java.awt.EventQueue.invokeLater(new Runnable()
233 StructureSelectionManager.getStructureSelectionManager(me)
234 .mouseOverVamsasSequence(sq, pos, null);
244 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
248 public void select(String sequenceIds, String columns)
250 selectIn(getDefaultTargetFrame(), sequenceIds, columns, separator);
256 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
257 * java.lang.String, java.lang.String)
260 public void select(String sequenceIds, String columns, String sep)
262 selectIn(getDefaultTargetFrame(), sequenceIds, columns, sep);
268 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
269 * java.lang.String, java.lang.String)
272 public void selectIn(AlignFrame alf, String sequenceIds, String columns)
274 selectIn(alf, sequenceIds, columns, separator);
280 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
281 * java.lang.String, java.lang.String, java.lang.String)
284 public void selectIn(final AlignFrame alf, String sequenceIds,
285 String columns, String sep)
287 if (sep == null || sep.length() == 0)
296 .errPrintln("Selecting region using separator string '"
301 String[] ids = separatorListToArray(sequenceIds, sep);
302 String[] cols = separatorListToArray(columns, sep);
303 final SequenceGroup sel = new SequenceGroup();
304 final ColumnSelection csel = new ColumnSelection();
305 AlignmentI al = alf.viewport.getAlignment();
306 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
307 alf.viewport.getAlignment().getSequencesArray());
308 int start = 0, end = al.getWidth(), alw = al.getWidth();
309 boolean seqsfound = true;
310 if (ids != null && ids.length > 0)
313 for (int i = 0; i < ids.length; i++)
315 if (ids[i].trim().length() == 0)
319 SequenceI sq = matcher.findIdMatch(ids[i]);
323 sel.addSequence(sq, false);
327 boolean inseqpos = false;
328 if (cols != null && cols.length > 0)
330 boolean seset = false;
331 for (int i = 0; i < cols.length; i++)
333 String cl = cols[i].trim();
334 if (cl.length() == 0)
339 if ((p = cl.indexOf("-")) > -1)
341 int from = -1, to = -1;
344 from = Integer.valueOf(cl.substring(0, p)).intValue();
346 } catch (NumberFormatException ex)
348 jalview.bin.Console.errPrintln(
349 "ERROR: Couldn't parse first integer in range element column selection string '"
350 + cl + "' - format is 'from-to'");
355 to = Integer.valueOf(cl.substring(p + 1)).intValue();
357 } catch (NumberFormatException ex)
359 jalview.bin.Console.errPrintln(
360 "ERROR: Couldn't parse second integer in range element column selection string '"
361 + cl + "' - format is 'from-to'");
364 if (from >= 0 && to >= 0)
381 // comment to prevent range extension
391 for (int r = from; r <= to; r++)
393 if (r >= 0 && r < alw)
400 jalview.bin.Console.errPrintln("Range '" + cl
401 + "' deparsed as [" + from + "," + to + "]");
406 jalview.bin.Console.errPrintln("ERROR: Invalid Range '" + cl
407 + "' deparsed as [" + from + "," + to + "]");
415 r = Integer.valueOf(cl).intValue();
417 } catch (NumberFormatException ex)
419 if (cl.toLowerCase(Locale.ROOT).equals("sequence"))
421 // we are in the dataset sequence's coordinate frame.
426 jalview.bin.Console.errPrintln(
427 "ERROR: Couldn't parse integer from point selection element of column selection string '"
432 if (r >= 0 && r <= alw)
442 // comment to prevent range extension
455 jalview.bin.Console.errPrintln("Point selection '" + cl
456 + "' deparsed as [" + r + "]");
462 .errPrintln("ERROR: Invalid Point selection '" + cl
463 + "' deparsed as [" + r + "]");
470 // we only propagate the selection when it was the null selection, or the
471 // given sequences were found in the alignment.
472 if (inseqpos && sel.getSize() > 0)
474 // assume first sequence provides reference frame ?
475 SequenceI rs = sel.getSequenceAt(0);
476 start = rs.findIndex(start);
477 end = rs.findIndex(end);
478 List<Integer> cs = new ArrayList<>(csel.getSelected());
480 for (Integer selectedCol : cs)
482 csel.addElement(rs.findIndex(selectedCol));
485 sel.setStartRes(start);
487 EventQueue.invokeLater(new Runnable()
492 alf.select(sel, csel,
493 alf.getAlignViewport().getAlignment().getHiddenColumns());
503 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignment(java.lang.
504 * String, java.lang.String)
507 public String getSelectedSequencesAsAlignment(String format,
510 return getSelectedSequencesAsAlignmentFrom(getDefaultTargetFrame(),
518 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignmentFrom(jalview
519 * .appletgui.AlignFrame, java.lang.String, java.lang.String)
522 public String getSelectedSequencesAsAlignmentFrom(AlignFrame alf,
523 String format, String suffix)
527 FileFormatI theFormat = FileFormats.getInstance().forName(format);
528 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
529 if (alf.viewport.getSelectionGroup() != null)
531 // JBPNote: getSelectionAsNewSequence behaviour has changed - this
532 // method now returns a full copy of sequence data
533 // TODO consider using getSequenceSelection instead here
534 String reply = new AppletFormatAdapter().formatSequences(theFormat,
535 new Alignment(alf.viewport.getSelectionAsNewSequence()),
539 } catch (IllegalArgumentException ex)
541 ex.printStackTrace();
542 return "Error retrieving alignment, possibly invalid format specifier: "
551 * @see jalview.bin.JalviewLiteJsApi#getAlignmentOrder()
554 public String getAlignmentOrder()
556 return getAlignmentOrderFrom(getDefaultTargetFrame());
563 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
567 public String getAlignmentOrderFrom(AlignFrame alf)
569 return getAlignmentOrderFrom(alf, separator);
576 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
577 * , java.lang.String)
580 public String getAlignmentOrderFrom(AlignFrame alf, String sep)
582 AlignmentI alorder = alf.getAlignViewport().getAlignment();
583 String[] order = new String[alorder.getHeight()];
584 for (int i = 0; i < order.length; i++)
586 order[i] = alorder.getSequenceAt(i).getName();
588 return arrayToSeparatorList(order);
594 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
598 public String orderBy(String order, String undoName)
600 return orderBy(order, undoName, separator);
606 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
607 * java.lang.String, java.lang.String)
610 public String orderBy(String order, String undoName, String sep)
612 return orderAlignmentBy(getDefaultTargetFrame(), order, undoName, sep);
619 * jalview.bin.JalviewLiteJsApi#orderAlignmentBy(jalview.appletgui.AlignFrame,
620 * java.lang.String, java.lang.String, java.lang.String)
623 public String orderAlignmentBy(AlignFrame alf, String order,
624 String undoName, String sep)
626 String[] ids = separatorListToArray(order, sep);
627 SequenceI[] sqs = null;
628 if (ids != null && ids.length > 0)
630 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
631 alf.viewport.getAlignment().getSequencesArray());
633 sqs = new SequenceI[ids.length];
634 for (int i = 0; i < ids.length; i++)
636 if (ids[i].trim().length() == 0)
640 SequenceI sq = matcher.findIdMatch(ids[i]);
648 SequenceI[] sqq = new SequenceI[s];
649 System.arraycopy(sqs, 0, sqq, 0, s);
662 final AlignmentOrder aorder = new AlignmentOrder(sqs);
664 if (undoName != null && undoName.trim().length() == 0)
668 final String _undoName = undoName;
669 // TODO: deal with synchronization here: cannot raise any events until after
670 // this has returned.
671 return alf.sortBy(aorder, _undoName) ? TRUE : "";
677 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String)
680 public String getAlignment(String format)
682 return getAlignmentFrom(getDefaultTargetFrame(), format, TRUE);
689 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
693 public String getAlignmentFrom(AlignFrame alf, String format)
695 return getAlignmentFrom(alf, format, TRUE);
701 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String,
705 public String getAlignment(String format, String suffix)
707 return getAlignmentFrom(getDefaultTargetFrame(), format, suffix);
714 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
715 * java.lang.String, java.lang.String)
718 public String getAlignmentFrom(AlignFrame alf, String format,
723 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
725 FileFormatI theFormat = FileFormats.getInstance().forName(format);
726 String reply = new AppletFormatAdapter().formatSequences(theFormat,
727 alf.viewport.getAlignment(), seqlimits);
729 } catch (IllegalArgumentException ex)
731 ex.printStackTrace();
732 return "Error retrieving alignment, possibly invalid format specifier: "
740 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
743 public void loadAnnotation(String annotation)
745 loadAnnotationFrom(getDefaultTargetFrame(), annotation);
752 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
753 * , java.lang.String)
756 public void loadAnnotationFrom(AlignFrame alf, String annotation)
758 if (new AnnotationFile().annotateAlignmentView(alf.getAlignViewport(),
759 annotation, DataSourceType.PASTE))
761 alf.alignPanel.fontChanged();
762 alf.alignPanel.setScrollValues(0, 0);
766 alf.parseFeaturesFile(annotation, DataSourceType.PASTE);
773 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
776 public void loadFeatures(String features, boolean autoenabledisplay)
778 loadFeaturesFrom(getDefaultTargetFrame(), features, autoenabledisplay);
785 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
786 * , java.lang.String)
789 public boolean loadFeaturesFrom(AlignFrame alf, String features,
790 boolean autoenabledisplay)
792 return alf.parseFeaturesFile(features, DataSourceType.PASTE,
799 * @see jalview.bin.JalviewLiteJsApi#getFeatures(java.lang.String)
802 public String getFeatures(String format)
804 return getFeaturesFrom(getDefaultTargetFrame(), format);
811 * jalview.bin.JalviewLiteJsApi#getFeaturesFrom(jalview.appletgui.AlignFrame,
815 public String getFeaturesFrom(AlignFrame alf, String format)
817 return alf.outputFeatures(false, format);
823 * @see jalview.bin.JalviewLiteJsApi#getAnnotation()
826 public String getAnnotation()
828 return getAnnotationFrom(getDefaultTargetFrame());
835 * jalview.bin.JalviewLiteJsApi#getAnnotationFrom(jalview.appletgui.AlignFrame
839 public String getAnnotationFrom(AlignFrame alf)
841 return alf.outputAnnotations(false);
847 * @see jalview.bin.JalviewLiteJsApi#newView()
850 public AlignFrame newView()
852 return newViewFrom(getDefaultTargetFrame());
858 * @see jalview.bin.JalviewLiteJsApi#newView(java.lang.String)
861 public AlignFrame newView(String name)
863 return newViewFrom(getDefaultTargetFrame(), name);
869 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame)
872 public AlignFrame newViewFrom(AlignFrame alf)
874 return alf.newView(null);
880 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame,
884 public AlignFrame newViewFrom(AlignFrame alf, String name)
886 return alf.newView(name);
892 * @see jalview.bin.JalviewLiteJsApi#loadAlignment(java.lang.String,
896 public AlignFrame loadAlignment(String text, String title)
898 AlignmentI al = null;
902 FileFormatI format = new IdentifyFile().identify(text,
903 DataSourceType.PASTE);
904 al = new AppletFormatAdapter().readFile(text, DataSourceType.PASTE,
906 if (al.getHeight() > 0)
908 return new AlignFrame(al, this, title, false);
910 } catch (IOException ex)
912 ex.printStackTrace();
920 * @see jalview.bin.JalviewLiteJsApi#setMouseoverListener(java.lang.String)
923 public void setMouseoverListener(String listener)
925 setMouseoverListener(currentAlignFrame, listener);
928 private Vector<jalview.javascript.JSFunctionExec> javascriptListeners = new Vector<>();
934 * jalview.bin.JalviewLiteJsApi#setMouseoverListener(jalview.appletgui.AlignFrame
935 * , java.lang.String)
938 public void setMouseoverListener(AlignFrame af, String listener)
940 if (listener != null)
942 listener = listener.trim();
943 if (listener.length() == 0)
945 jalview.bin.Console.errPrintln(
946 "jalview Javascript error: Ignoring empty function for mouseover listener.");
950 jalview.javascript.MouseOverListener mol = new jalview.javascript.MouseOverListener(
952 javascriptListeners.addElement(mol);
953 StructureSelectionManager.getStructureSelectionManager(this)
954 .addStructureViewerListener(mol);
957 jalview.bin.Console.errPrintln("Added a mouseover listener for "
958 + ((af == null) ? "All frames"
960 + af.getAlignViewport().getSequenceSetId()));
961 jalview.bin.Console.errPrintln("There are now "
962 + javascriptListeners.size() + " listeners in total.");
969 * @see jalview.bin.JalviewLiteJsApi#setSelectionListener(java.lang.String)
972 public void setSelectionListener(String listener)
974 setSelectionListener(null, listener);
981 * jalview.bin.JalviewLiteJsApi#setSelectionListener(jalview.appletgui.AlignFrame
982 * , java.lang.String)
985 public void setSelectionListener(AlignFrame af, String listener)
987 if (listener != null)
989 listener = listener.trim();
990 if (listener.length() == 0)
992 jalview.bin.Console.errPrintln(
993 "jalview Javascript error: Ignoring empty function for selection listener.");
997 jalview.javascript.JsSelectionSender mol = new jalview.javascript.JsSelectionSender(
999 javascriptListeners.addElement(mol);
1000 StructureSelectionManager.getStructureSelectionManager(this)
1001 .addSelectionListener(mol);
1004 jalview.bin.Console.errPrintln("Added a selection listener for "
1005 + ((af == null) ? "All frames"
1007 + af.getAlignViewport().getSequenceSetId()));
1008 jalview.bin.Console.errPrintln("There are now "
1009 + javascriptListeners.size() + " listeners in total.");
1014 * Callable from javascript to register a javascript function to pass events
1015 * to a structure viewer.
1018 * the name of a javascript function
1020 * a token separated list of PDB file names listened for
1021 * @see jalview.bin.JalviewLiteJsApi#setStructureListener(java.lang.String,
1025 public void setStructureListener(String listener, String modelSet)
1027 if (listener != null)
1029 listener = listener.trim();
1030 if (listener.length() == 0)
1032 jalview.bin.Console.errPrintln(
1033 "jalview Javascript error: Ignoring empty function for selection listener.");
1037 MouseOverStructureListener mol = new MouseOverStructureListener(this,
1038 listener, separatorListToArray(modelSet));
1039 javascriptListeners.addElement(mol);
1040 StructureSelectionManager.getStructureSelectionManager(this)
1041 .addStructureViewerListener(mol);
1045 .errPrintln("Added a javascript structure viewer listener '"
1047 jalview.bin.Console.errPrintln("There are now "
1048 + javascriptListeners.size() + " listeners in total.");
1056 * jalview.bin.JalviewLiteJsApi#removeJavascriptListener(jalview.appletgui
1057 * .AlignFrame, java.lang.String)
1060 public void removeJavascriptListener(AlignFrame af, String listener)
1062 if (listener != null)
1064 listener = listener.trim();
1065 if (listener.length() == 0)
1070 boolean rprt = false;
1071 for (int ms = 0, msSize = javascriptListeners.size(); ms < msSize;)
1073 Object lstn = javascriptListeners.elementAt(ms);
1074 JsCallBack lstner = (JsCallBack) lstn;
1075 if ((af == null || lstner.getAlignFrame() == af) && (listener == null
1076 || lstner.getListenerFunction().equals(listener)))
1078 javascriptListeners.removeElement(lstner);
1080 if (lstner instanceof SelectionListener)
1082 StructureSelectionManager.getStructureSelectionManager(this)
1083 .removeSelectionListener((SelectionListener) lstner);
1087 StructureSelectionManager.getStructureSelectionManager(this)
1088 .removeStructureViewerListener(lstner, null);
1094 .errPrintln("Removed listener '" + listener + "'");
1104 jalview.bin.Console.errPrintln("There are now "
1105 + javascriptListeners.size() + " listeners in total.");
1112 jalview.bin.Console.errPrintln("Applet " + getName() + " stop().");
1117 public void destroy()
1119 jalview.bin.Console.errPrintln("Applet " + getName() + " destroy().");
1123 private void tidyUp()
1126 if (currentAlignFrame != null && currentAlignFrame.viewport != null
1127 && currentAlignFrame.viewport.applet != null)
1129 AlignViewport av = currentAlignFrame.viewport;
1130 currentAlignFrame.closeMenuItem_actionPerformed();
1132 currentAlignFrame = null;
1134 if (javascriptListeners != null)
1136 while (javascriptListeners.size() > 0)
1138 jalview.javascript.JSFunctionExec mol = javascriptListeners
1140 javascriptListeners.removeElement(mol);
1141 if (mol instanceof SelectionListener)
1143 StructureSelectionManager.getStructureSelectionManager(this)
1144 .removeSelectionListener((SelectionListener) mol);
1148 StructureSelectionManager.getStructureSelectionManager(this)
1149 .removeStructureViewerListener(mol, null);
1154 if (jsFunctionExec != null)
1156 jsFunctionExec.stopQueue();
1157 jsFunctionExec.jvlite = null;
1159 initialAlignFrame = null;
1160 jsFunctionExec = null;
1161 javascriptListeners = null;
1162 StructureSelectionManager.release(this);
1165 private jalview.javascript.JSFunctionExec jsFunctionExec;
1170 * @see jalview.bin.JalviewLiteJsApi#mouseOverStructure(java.lang.String,
1171 * java.lang.String, java.lang.String)
1174 public void mouseOverStructure(final String pdbResNum, final String chain,
1175 final String pdbfile)
1177 final StructureSelectionManagerProvider me = this;
1178 java.awt.EventQueue.invokeLater(new Runnable()
1185 StructureSelectionManager.getStructureSelectionManager(me)
1186 .mouseOverStructure(Integer.valueOf(pdbResNum).intValue(),
1191 .println("mouseOver for '" + pdbResNum + "' in chain '"
1192 + chain + "' in structure '" + pdbfile + "'");
1194 } catch (NumberFormatException e)
1197 .errPrintln("Ignoring invalid residue number string '"
1209 * jalview.bin.JalviewLiteJsApi#scrollViewToIn(jalview.appletgui.AlignFrame,
1210 * java.lang.String, java.lang.String)
1213 public void scrollViewToIn(final AlignFrame alf, final String topRow,
1214 final String leftHandColumn)
1216 java.awt.EventQueue.invokeLater(new Runnable()
1223 alf.scrollTo(Integer.valueOf(topRow).intValue(),
1224 Integer.valueOf(leftHandColumn).intValue());
1226 } catch (Exception ex)
1229 .errPrintln("Couldn't parse integer arguments (topRow='"
1230 + topRow + "' and leftHandColumn='"
1231 + leftHandColumn + "')");
1232 ex.printStackTrace();
1242 * jalview.javascript.JalviewLiteJsApi#scrollViewToRowIn(jalview.appletgui
1243 * .AlignFrame, java.lang.String)
1246 public void scrollViewToRowIn(final AlignFrame alf, final String topRow)
1249 java.awt.EventQueue.invokeLater(new Runnable()
1256 alf.scrollToRow(Integer.valueOf(topRow).intValue());
1258 } catch (Exception ex)
1261 .errPrintln("Couldn't parse integer arguments (topRow='"
1263 ex.printStackTrace();
1274 * jalview.javascript.JalviewLiteJsApi#scrollViewToColumnIn(jalview.appletgui
1275 * .AlignFrame, java.lang.String)
1278 public void scrollViewToColumnIn(final AlignFrame alf,
1279 final String leftHandColumn)
1281 java.awt.EventQueue.invokeLater(new Runnable()
1289 alf.scrollToColumn(Integer.valueOf(leftHandColumn).intValue());
1291 } catch (Exception ex)
1293 jalview.bin.Console.errPrintln(
1294 "Couldn't parse integer arguments (leftHandColumn='"
1295 + leftHandColumn + "')");
1296 ex.printStackTrace();
1303 // //////////////////////////////////////////////
1304 // //////////////////////////////////////////////
1306 public static int lastFrameX = 200;
1308 public static int lastFrameY = 200;
1310 boolean fileFound = true;
1312 String file = "No file";
1314 String file2 = null;
1316 Button launcher = new Button(
1317 MessageManager.getString("label.start_jalview"));
1320 * The currentAlignFrame is static, it will change if and when the user
1321 * selects a new window. Note that it will *never* point back to the embedded
1322 * AlignFrame if the applet is started as embedded on the page and then
1323 * afterwards a new view is created.
1325 public AlignFrame currentAlignFrame = null;
1328 * This is the first frame to be displayed, and does not change. API calls
1329 * will default to this instance if currentAlignFrame is null.
1331 AlignFrame initialAlignFrame = null;
1333 boolean embedded = false;
1335 private boolean checkForJmol = true;
1337 private boolean checkedForJmol = false; // ensure we don't check for jmol
1339 // every time the app is re-inited
1341 public boolean jmolAvailable = false;
1343 private boolean alignPdbStructures = false;
1346 * use an external structure viewer exclusively (no jmols or mc_views will be
1347 * opened by JalviewLite itself)
1349 public boolean useXtrnalSviewer = false;
1351 public static boolean debug = false;
1353 static String builddate = null, version = null, installation = null;
1355 private static void initBuildDetails()
1357 if (builddate == null)
1359 builddate = "unknown";
1361 installation = "applet";
1362 java.net.URL url = JalviewLite.class
1363 .getResource("/.build_properties");
1368 BufferedReader reader = new BufferedReader(
1369 new InputStreamReader(url.openStream()));
1371 while ((line = reader.readLine()) != null)
1373 if (line.indexOf("VERSION") > -1)
1375 version = line.substring(line.indexOf("=") + 1);
1377 if (line.indexOf("BUILD_DATE") > -1)
1379 builddate = line.substring(line.indexOf("=") + 1);
1381 if (line.indexOf("INSTALLATION") > -1)
1383 installation = line.substring(line.indexOf("=") + 1);
1386 } catch (Exception ex)
1388 ex.printStackTrace();
1394 public static String getBuildDate()
1400 public static String getInstallation()
1403 return installation;
1406 public static String getVersion()
1412 // public JSObject scriptObject = null;
1415 * init method for Jalview Applet
1420 debug = TRUE.equalsIgnoreCase(getParameter("debug"));
1425 jalview.bin.Console.errPrintln("Applet context is '"
1426 + getAppletContext().getClass().toString() + "'");
1428 JSObject scriptObject = JSObject.getWindow(this);
1429 if (debug && scriptObject != null)
1432 .errPrintln("Applet has Javascript callback support.");
1435 } catch (Exception ex)
1437 jalview.bin.Console.errPrintln(
1438 "Warning: No JalviewLite javascript callbacks available.");
1441 ex.printStackTrace();
1447 jalview.bin.Console.errPrintln("JalviewLite Version " + getVersion());
1448 jalview.bin.Console.errPrintln("Build Date : " + getBuildDate());
1449 jalview.bin.Console.errPrintln("Installation : " + getInstallation());
1451 String externalsviewer = getParameter("externalstructureviewer");
1452 if (externalsviewer != null)
1454 useXtrnalSviewer = externalsviewer.trim().toLowerCase(Locale.ROOT)
1458 * if true disable the check for jmol
1460 String chkforJmol = getParameter("nojmol");
1461 if (chkforJmol != null)
1463 checkForJmol = !chkforJmol.equals(TRUE);
1466 * get the separator parameter if present
1468 String sep = getParameter("separator");
1471 if (sep.length() > 0)
1477 .errPrintln("Separator set to '" + separator + "'");
1482 throw new Error(MessageManager
1483 .getString("error.invalid_separator_parameter"));
1489 String param = getParameter("RGB");
1495 r = Integer.parseInt(param.substring(0, 2), 16);
1496 g = Integer.parseInt(param.substring(2, 4), 16);
1497 b = Integer.parseInt(param.substring(4, 6), 16);
1498 } catch (Exception ex)
1505 param = getParameter("label");
1508 launcher.setLabel(param);
1511 setBackground(new Color(r, g, b));
1513 file = getParameter("file");
1517 // Maybe the sequences are added as parameters
1518 StringBuffer data = new StringBuffer("PASTE");
1520 while ((file = getParameter("sequence" + i)) != null)
1522 data.append(file.toString() + "\n");
1525 if (data.length() > 5)
1527 file = data.toString();
1530 if (getDefaultParameter("enableSplitFrame", true))
1532 file2 = getParameter("file2");
1535 embedded = TRUE.equalsIgnoreCase(getParameter("embedded"));
1538 LoadingThread loader = new LoadingThread(file, file2, this);
1541 else if (file != null)
1544 * Start the applet immediately or show a button to start it
1546 if (FALSE.equalsIgnoreCase(getParameter("showbutton")))
1548 LoadingThread loader = new LoadingThread(file, file2, this);
1554 launcher.addActionListener(new java.awt.event.ActionListener()
1557 public void actionPerformed(ActionEvent e)
1559 LoadingThread loader = new LoadingThread(file, file2,
1568 // jalview initialisation with no alignment. loadAlignment() method can
1569 // still be called to open new alignments.
1576 private void initLiveConnect()
1578 // try really hard to get the liveConnect thing working
1579 boolean notFailed = false;
1581 while (!notFailed && tries < 10)
1586 .errPrintln("LiveConnect request thread going to sleep.");
1590 Thread.sleep(700 * (1 + tries));
1591 } catch (InterruptedException q)
1598 .errPrintln("LiveConnect request thread woken up.");
1602 JSObject scriptObject = JSObject.getWindow(this);
1603 if (scriptObject.eval("navigator") != null)
1607 } catch (Exception jsex)
1609 jalview.bin.Console.errPrintln("Attempt " + tries
1610 + " to access LiveConnect javascript failed.");
1615 private void callInitCallback()
1617 String initjscallback = getParameter("oninit");
1618 if (initjscallback == null)
1622 initjscallback = initjscallback.trim();
1623 if (initjscallback.length() > 0)
1625 JSObject scriptObject = null;
1628 scriptObject = JSObject.getWindow(this);
1629 } catch (Exception ex)
1633 // try really hard to let the browser plugin know we want liveconnect
1636 if (scriptObject != null)
1640 // do onInit with the JS executor thread
1641 new JSFunctionExec(this).executeJavascriptFunction(true,
1642 initjscallback, null,
1643 "Calling oninit callback '" + initjscallback + "'.");
1644 } catch (Exception e)
1647 .errPrintln("Exception when executing _oninit callback '"
1648 + initjscallback + "'.");
1649 e.printStackTrace();
1654 jalview.bin.Console.errPrintln("Not executing _oninit callback '"
1655 + initjscallback + "' - no scripting allowed.");
1661 * Initialises and displays a new java.awt.Frame
1664 * java.awt.Frame to be displayed
1666 * title of new frame
1668 * width if new frame
1670 * height of new frame
1672 public static void addFrame(final Frame frame, String title, int width,
1675 frame.setLocation(lastFrameX, lastFrameY);
1678 frame.setSize(width, height);
1679 frame.setTitle(title);
1680 frame.addWindowListener(new WindowAdapter()
1683 public void windowClosing(WindowEvent e)
1685 if (frame instanceof AlignFrame)
1687 AlignViewport vp = ((AlignFrame) frame).viewport;
1688 ((AlignFrame) frame).closeMenuItem_actionPerformed();
1689 if (vp.applet.currentAlignFrame == frame)
1691 vp.applet.currentAlignFrame = null;
1699 if (frame instanceof EmbmenuFrame)
1701 ((EmbmenuFrame) frame).destroyMenus();
1703 frame.setMenuBar(null);
1708 public void windowActivated(WindowEvent e)
1710 if (frame instanceof AlignFrame)
1712 ((AlignFrame) frame).viewport.applet.currentAlignFrame = (AlignFrame) frame;
1715 jalview.bin.Console.errPrintln("Activated window " + frame);
1719 super.windowActivated(e);
1722 * Probably not necessary to do this - see TODO above. (non-Javadoc)
1725 * java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent
1728 * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
1729 * frame) { currentAlignFrame = null; if (debug) {
1730 * jalview.bin.Console.errPrintln("Deactivated window "+frame); } }
1731 * super.windowDeactivated(e); }
1734 frame.setVisible(true);
1738 * This paints the background surrounding the "Launch Jalview button" <br>
1740 * If file given in parameter not found, displays error message
1746 public void paint(Graphics g)
1750 g.setColor(new Color(200, 200, 200));
1751 g.setColor(Color.cyan);
1752 g.fillRect(0, 0, getSize().width, getSize().height);
1753 g.setColor(Color.red);
1755 MessageManager.getString("label.jalview_cannot_open_file"), 5,
1757 g.drawString("\"" + file + "\"", 5, 30);
1761 g.setColor(Color.black);
1762 g.setFont(new Font("Arial", Font.BOLD, 24));
1763 g.drawString(MessageManager.getString("label.jalview_applet"), 50,
1764 getSize().height / 2 - 30);
1765 g.drawString(MessageManager.getString("label.loading_data") + "...",
1766 50, getSize().height / 2);
1771 * get all components associated with the applet of the given type
1776 public Vector getAppletWindow(Class class1)
1778 Vector wnds = new Vector();
1779 Component[] cmp = getComponents();
1782 for (int i = 0; i < cmp.length; i++)
1784 if (class1.isAssignableFrom(cmp[i].getClass()))
1786 wnds.addElement(cmp);
1793 class LoadJmolThread extends Thread
1795 private boolean running = false;
1800 if (running || checkedForJmol)
1809 if (!System.getProperty("java.version").startsWith("1.1"))
1811 Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
1812 jmolAvailable = true;
1816 jalview.bin.Console.outPrintln(
1817 "Jmol not available - Using mc_view for structures");
1819 } catch (java.lang.ClassNotFoundException ex)
1825 jmolAvailable = false;
1828 jalview.bin.Console.errPrintln(
1829 "Skipping Jmol check. Will use mc_view (probably)");
1832 checkedForJmol = true;
1836 public boolean notFinished()
1838 return running || !checkedForJmol;
1842 class LoadingThread extends Thread
1845 * State variable: protocol for access to file source
1847 DataSourceType protocol;
1849 String _file; // alignment file or URL spec
1851 String _file2; // second alignment file or URL spec
1855 private void dbgMsg(String msg)
1857 if (JalviewLite.debug)
1859 jalview.bin.Console.errPrintln(msg);
1864 * update the protocol state variable for accessing the datasource located
1868 * @return possibly updated datasource string
1870 public String resolveFileProtocol(String path)
1875 if (path.startsWith("PASTE"))
1877 protocol = DataSourceType.PASTE;
1878 return path.substring(5);
1884 if (path.indexOf("://") != -1)
1886 protocol = DataSourceType.URL;
1891 * try relative to document root
1893 URL documentBase = getDocumentBase();
1894 String withDocBase = resolveUrlForLocalOrAbsolute(path, documentBase);
1895 if (HttpUtils.isValidUrl(withDocBase))
1899 jalview.bin.Console.errPrintln("Prepended document base '"
1900 + documentBase + "' to make: '" + withDocBase + "'");
1902 protocol = DataSourceType.URL;
1907 * try relative to codebase (if different to document base)
1909 URL codeBase = getCodeBase();
1910 String withCodeBase = applet.resolveUrlForLocalOrAbsolute(path,
1912 if (!withCodeBase.equals(withDocBase)
1913 && HttpUtils.isValidUrl(withCodeBase))
1915 protocol = DataSourceType.URL;
1918 jalview.bin.Console.errPrintln("Prepended codebase '" + codeBase
1919 + "' to make: '" + withCodeBase + "'");
1921 return withCodeBase;
1925 * try locating by classloader; try this last so files in the directory
1926 * are resolved using document base
1928 if (inArchive(path))
1930 protocol = DataSourceType.CLASSLOADER;
1935 public LoadingThread(String file, String file2, JalviewLite _applet)
1938 this._file2 = file2;
1945 LoadJmolThread jmolchecker = new LoadJmolThread();
1946 jmolchecker.start();
1947 while (jmolchecker.notFinished())
1949 // wait around until the Jmol check is complete.
1953 } catch (Exception e)
1958 // applet.callInitCallback();
1962 * Load the alignment and any related files as specified by applet
1965 private void startLoading()
1967 dbgMsg("Loading thread started with:\n>>file\n" + _file
1970 dbgMsg("Loading started.");
1972 AlignFrame newAlignFrame = readAlignment(_file);
1973 AlignFrame newAlignFrame2 = readAlignment(_file2);
1974 if (newAlignFrame != null)
1976 addToDisplay(newAlignFrame, newAlignFrame2);
1977 loadTree(newAlignFrame);
1979 loadScoreFile(newAlignFrame);
1981 loadFeatures(newAlignFrame);
1983 loadAnnotations(newAlignFrame);
1985 loadJnetFile(newAlignFrame);
1987 loadPdbFiles(newAlignFrame);
1992 applet.remove(launcher);
1999 * Add an AlignFrame to the display; or if two are provided, a SplitFrame.
2004 public void addToDisplay(AlignFrame af, AlignFrame af2)
2008 AlignmentI al1 = af.viewport.getAlignment();
2009 AlignmentI al2 = af2.viewport.getAlignment();
2010 AlignmentI cdna = al1.isNucleotide() ? al1 : al2;
2011 AlignmentI prot = al1.isNucleotide() ? al2 : al1;
2012 if (AlignmentUtils.mapProteinAlignmentToCdna(prot, cdna))
2015 SplitFrame sf = new SplitFrame(af, af2);
2016 sf.addToDisplay(embedded, JalviewLite.this);
2021 String msg = "Could not map any sequence in " + af2.getTitle()
2023 + (al1.isNucleotide() ? "protein product" : "cDNA")
2024 + " for " + af.getTitle();
2025 jalview.bin.Console.errPrintln(msg);
2029 af.addToDisplay(embedded);
2033 * Read the alignment file (from URL, text 'paste', or archive by
2038 protected AlignFrame readAlignment(String fileParam)
2040 if (fileParam == null)
2044 String resolvedFile = resolveFileProtocol(fileParam);
2045 AlignmentI al = null;
2048 FileFormatI format = new IdentifyFile().identify(resolvedFile,
2050 dbgMsg("File identified as '" + format + "'");
2051 al = new AppletFormatAdapter().readFile(resolvedFile, protocol,
2053 if ((al != null) && (al.getHeight() > 0))
2055 dbgMsg("Successfully loaded file.");
2056 al.setDataset(null);
2057 AlignFrame newAlignFrame = new AlignFrame(al, applet,
2058 resolvedFile, embedded, false);
2059 newAlignFrame.setTitle(resolvedFile);
2060 if (initialAlignFrame == null)
2062 initialAlignFrame = newAlignFrame;
2064 // update the focus.
2065 currentAlignFrame = newAlignFrame;
2067 if (protocol == DataSourceType.PASTE)
2069 newAlignFrame.setTitle(MessageManager
2070 .formatMessage("label.sequences_from", new Object[]
2071 { applet.getDocumentBase().toString() }));
2074 newAlignFrame.statusBar.setText(MessageManager.formatMessage(
2075 "label.successfully_loaded_file", new Object[]
2078 return newAlignFrame;
2080 } catch (java.io.IOException ex)
2082 dbgMsg("File load exception.");
2083 ex.printStackTrace();
2088 FileParse fp = new FileParse(resolvedFile, protocol);
2090 dbgMsg(">>>Dumping contents of '" + resolvedFile + "' " + "("
2092 while ((ln = fp.nextLine()) != null)
2096 dbgMsg(">>>Dump finished.");
2097 } catch (Exception e)
2099 jalview.bin.Console.errPrintln(
2100 "Exception when trying to dump the content of the file parameter.");
2101 e.printStackTrace();
2109 * Load PDBFiles if any specified by parameter(s). Returns true if loaded,
2115 protected boolean loadPdbFiles(AlignFrame alignFrame)
2117 boolean result = false;
2119 * <param name="alignpdbfiles" value="false/true"/> Undocumented for 2.6 -
2120 * related to JAL-434
2123 applet.setAlignPdbStructures(
2124 getDefaultParameter("alignpdbfiles", false));
2126 * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
2129 * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
2131 * <param name="PDBfile3" value="1q0o Q45135_9MICO">
2134 int pdbFileCount = 0;
2135 // Accumulate pdbs here if they are heading for the same view (if
2136 // alignPdbStructures is true)
2137 Vector pdbs = new Vector();
2138 // create a lazy matcher if we're asked to
2139 jalview.analysis.SequenceIdMatcher matcher = (applet
2140 .getDefaultParameter("relaxedidmatch", false))
2141 ? new jalview.analysis.SequenceIdMatcher(
2142 alignFrame.getAlignViewport().getAlignment()
2143 .getSequencesArray())
2149 if (pdbFileCount > 0)
2151 param = applet.getParameter("PDBFILE" + pdbFileCount);
2155 param = applet.getParameter("PDBFILE");
2160 PDBEntry pdb = new PDBEntry();
2163 SequenceI[] seqs = null;
2164 String[] chains = null;
2166 StringTokenizer st = new StringTokenizer(param, " ");
2168 if (st.countTokens() < 2)
2170 String sequence = applet.getParameter("PDBSEQ");
2171 if (sequence != null)
2173 seqs = new SequenceI[] { matcher == null
2174 ? (Sequence) alignFrame.getAlignViewport()
2175 .getAlignment().findName(sequence)
2176 : matcher.findIdMatch(sequence) };
2182 param = st.nextToken();
2183 List<SequenceI> tmp = new ArrayList<>();
2184 List<String> tmp2 = new ArrayList<>();
2186 while (st.hasMoreTokens())
2188 seqstring = st.nextToken();
2189 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
2190 if (st2.countTokens() > 1)
2192 // This is the chain
2193 tmp2.add(st2.nextToken());
2194 seqstring = st2.nextToken();
2196 tmp.add(matcher == null
2197 ? (Sequence) alignFrame.getAlignViewport()
2198 .getAlignment().findName(seqstring)
2199 : matcher.findIdMatch(seqstring));
2202 seqs = tmp.toArray(new SequenceI[tmp.size()]);
2203 if (tmp2.size() == tmp.size())
2205 chains = tmp2.toArray(new String[tmp2.size()]);
2208 param = resolveFileProtocol(param);
2209 // TODO check JAL-357 for files in a jar (CLASSLOADER)
2214 for (int i = 0; i < seqs.length; i++)
2216 if (seqs[i] != null)
2218 ((Sequence) seqs[i]).addPDBId(pdb);
2219 StructureSelectionManager
2220 .getStructureSelectionManager(applet)
2221 .registerPDBEntry(pdb);
2225 if (JalviewLite.debug)
2227 // this may not really be a problem but we give a warning
2229 jalview.bin.Console.errPrintln(
2230 "Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
2236 if (!alignPdbStructures)
2238 alignFrame.newStructureView(applet, pdb, seqs, chains,
2243 pdbs.addElement(new Object[] { pdb, seqs, chains, protocol });
2249 } while (param != null || pdbFileCount < 10);
2250 if (pdbs.size() > 0)
2252 SequenceI[][] seqs = new SequenceI[pdbs.size()][];
2253 PDBEntry[] pdb = new PDBEntry[pdbs.size()];
2254 String[][] chains = new String[pdbs.size()][];
2255 String[] protocols = new String[pdbs.size()];
2256 for (int pdbsi = 0, pdbsiSize = pdbs
2257 .size(); pdbsi < pdbsiSize; pdbsi++)
2259 Object[] o = (Object[]) pdbs.elementAt(pdbsi);
2260 pdb[pdbsi] = (PDBEntry) o[0];
2261 seqs[pdbsi] = (SequenceI[]) o[1];
2262 chains[pdbsi] = (String[]) o[2];
2263 protocols[pdbsi] = (String) o[3];
2265 alignFrame.alignedStructureView(applet, pdb, seqs, chains,
2273 * Load in a Jnetfile if specified by parameter. Returns true if loaded,
2279 protected boolean loadJnetFile(AlignFrame alignFrame)
2281 boolean result = false;
2282 String param = applet.getParameter("jnetfile");
2285 // jnet became jpred around 2016
2286 param = applet.getParameter("jpredfile");
2292 param = resolveFileProtocol(param);
2293 JPredFile predictions = new JPredFile(param, protocol);
2294 JnetAnnotationMaker.add_annotation(predictions,
2295 alignFrame.viewport.getAlignment(), 0, false);
2296 // false == do not add sequence profile from concise output
2298 alignFrame.viewport.getAlignment().setupJPredAlignment();
2300 alignFrame.alignPanel.fontChanged();
2301 alignFrame.alignPanel.setScrollValues(0, 0);
2303 } catch (Exception ex)
2305 ex.printStackTrace();
2312 * Load annotations if specified by parameter. Returns true if loaded, else
2318 protected boolean loadAnnotations(AlignFrame alignFrame)
2320 boolean result = false;
2321 String param = applet.getParameter("annotations");
2324 param = resolveFileProtocol(param);
2326 if (new AnnotationFile().annotateAlignmentView(alignFrame.viewport,
2329 alignFrame.alignPanel.fontChanged();
2330 alignFrame.alignPanel.setScrollValues(0, 0);
2335 jalview.bin.Console.errPrintln(
2336 "Annotations were not added from annotation file '"
2344 * Load features file and view settings as specified by parameters. Returns
2345 * true if features were loaded, else false.
2350 protected boolean loadFeatures(AlignFrame alignFrame)
2352 boolean result = false;
2353 // ///////////////////////////
2354 // modify display of features
2355 // we do this before any features have been loaded, ensuring any hidden
2356 // groups are hidden when features first displayed
2358 // hide specific groups
2360 String param = applet.getParameter("hidefeaturegroups");
2363 alignFrame.setFeatureGroupState(separatorListToArray(param), false);
2364 // applet.setFeatureGroupStateOn(newAlignFrame, param, false);
2366 // show specific groups
2367 param = applet.getParameter("showfeaturegroups");
2370 alignFrame.setFeatureGroupState(separatorListToArray(param), true);
2371 // applet.setFeatureGroupStateOn(newAlignFrame, param, true);
2373 // and now load features
2374 param = applet.getParameter("features");
2377 param = resolveFileProtocol(param);
2379 result = alignFrame.parseFeaturesFile(param, protocol);
2382 param = applet.getParameter("showFeatureSettings");
2383 if (param != null && param.equalsIgnoreCase(TRUE))
2385 alignFrame.viewport.setShowSequenceFeatures(true);
2386 new FeatureSettings(alignFrame.alignPanel);
2392 * Load a score file if specified by parameter. Returns true if file was
2393 * loaded, else false.
2397 protected boolean loadScoreFile(AlignFrame alignFrame)
2399 boolean result = false;
2400 String sScoreFile = applet.getParameter("scoreFile");
2401 if (sScoreFile != null && !"".equals(sScoreFile))
2407 jalview.bin.Console.errPrintln(
2408 "Attempting to load T-COFFEE score file from the scoreFile parameter");
2410 result = alignFrame.loadScoreFile(sScoreFile);
2413 jalview.bin.Console.errPrintln(
2414 "Failed to parse T-COFFEE parameter as a valid score file ('"
2415 + sScoreFile + "')");
2417 } catch (Exception e)
2419 System.err.printf("Cannot read score file: '%s'. Cause: %s \n",
2420 sScoreFile, e.getMessage());
2427 * Load a tree for the alignment if specified by parameter. Returns true if
2428 * a tree was loaded, else false.
2433 protected boolean loadTree(AlignFrame alignFrame)
2435 boolean result = false;
2436 String treeFile = applet.getParameter("tree");
2437 if (treeFile == null)
2439 treeFile = applet.getParameter("treeFile");
2442 if (treeFile != null)
2446 treeFile = resolveFileProtocol(treeFile);
2447 NewickFile fin = new NewickFile(treeFile, protocol);
2450 if (fin.getTree() != null)
2452 alignFrame.loadTree(fin, treeFile);
2454 dbgMsg("Successfully imported tree.");
2458 dbgMsg("Tree parameter did not resolve to a valid tree.");
2460 } catch (Exception ex)
2462 ex.printStackTrace();
2469 * Discovers whether the given file is in the Applet Archive
2475 boolean inArchive(String f)
2477 // This might throw a security exception in certain browsers
2478 // Netscape Communicator for instance.
2481 boolean rtn = (getClass().getResourceAsStream("/" + f) != null);
2484 jalview.bin.Console.errPrintln("Resource '" + f + "' was "
2485 + (rtn ? "" : "not ") + "located by classloader.");
2488 } catch (Exception ex)
2490 jalview.bin.Console.outPrintln(
2491 "Exception checking resources: " + f + " " + ex);
2498 * @return the default alignFrame acted on by the public applet methods. May
2499 * return null with an error message on System.err indicating the
2502 public AlignFrame getDefaultTargetFrame()
2504 if (currentAlignFrame != null)
2506 return currentAlignFrame;
2508 if (initialAlignFrame != null)
2510 return initialAlignFrame;
2512 jalview.bin.Console.errPrintln(
2513 "Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
2518 * separator used for separatorList
2520 protected String separator = "" + ((char) 0x00AC); // the default used to be
2521 // '|' but many sequence
2522 // IDS include pipes.
2525 * set to enable the URL based javascript execution mechanism
2527 public boolean jsfallbackEnabled = false;
2530 * parse the string into a list
2533 * @return elements separated by separator
2535 public String[] separatorListToArray(String list)
2537 return separatorListToArray(list, separator);
2541 * parse the string into a list
2545 * @return elements separated by separator
2547 public static String[] separatorListToArray(String list, String separator)
2549 // TODO use StringUtils version (slightly different...)
2550 int seplen = separator.length();
2551 if (list == null || list.equals("") || list.equals(separator))
2555 java.util.Vector jv = new Vector();
2557 while ((pos = list.indexOf(separator, cp)) > cp)
2559 jv.addElement(list.substring(cp, pos));
2562 if (cp < list.length())
2564 String c = list.substring(cp);
2565 if (!c.equals(separator))
2572 String[] v = new String[jv.size()];
2573 for (int i = 0; i < v.length; i++)
2575 v[i] = (String) jv.elementAt(i);
2577 jv.removeAllElements();
2580 jalview.bin.Console.errPrintln("Array from '" + separator
2581 + "' separated List:\n" + v.length);
2582 for (int i = 0; i < v.length; i++)
2584 jalview.bin.Console.errPrintln("item " + i + " '" + v[i] + "'");
2591 jalview.bin.Console.errPrintln(
2592 "Empty Array from '" + separator + "' separated List");
2598 * concatenate the list with separator
2601 * @return concatenated string
2603 public String arrayToSeparatorList(String[] list)
2605 return arrayToSeparatorList(list, separator);
2609 * concatenate the list with separator
2613 * @return concatenated string
2615 public static String arrayToSeparatorList(String[] list, String separator)
2617 // TODO use StringUtils version
2618 StringBuffer v = new StringBuffer();
2619 if (list != null && list.length > 0)
2621 for (int i = 0, iSize = list.length; i < iSize; i++)
2623 if (list[i] != null)
2627 v.append(separator);
2635 .println("Returning '" + separator + "' separated List:\n");
2636 jalview.bin.Console.errPrintln(v);
2638 return v.toString();
2642 jalview.bin.Console.errPrintln(
2643 "Returning empty '" + separator + "' separated List\n");
2645 return "" + separator;
2651 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroups()
2654 public String getFeatureGroups()
2656 String lst = arrayToSeparatorList(
2657 getDefaultTargetFrame().getFeatureGroups());
2665 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOn(jalview.appletgui.AlignFrame
2669 public String getFeatureGroupsOn(AlignFrame alf)
2671 String lst = arrayToSeparatorList(alf.getFeatureGroups());
2678 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfState(boolean)
2681 public String getFeatureGroupsOfState(boolean visible)
2683 return arrayToSeparatorList(
2684 getDefaultTargetFrame().getFeatureGroupsOfState(visible));
2691 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfStateOn(jalview.appletgui
2692 * .AlignFrame, boolean)
2695 public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
2697 return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
2703 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupStateOn(jalview.appletgui.
2704 * AlignFrame, java.lang.String, boolean)
2707 public void setFeatureGroupStateOn(final AlignFrame alf,
2708 final String groups, boolean state)
2710 final boolean st = state;// !(state==null || state.equals("") ||
2711 // state.toLowerCase(Locale.ROOT).equals("false"));
2712 java.awt.EventQueue.invokeLater(new Runnable()
2717 alf.setFeatureGroupState(separatorListToArray(groups), st);
2725 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupState(java.lang.String,
2729 public void setFeatureGroupState(String groups, boolean state)
2731 setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
2737 * @see jalview.bin.JalviewLiteJsApi#getSeparator()
2740 public String getSeparator()
2748 * @see jalview.bin.JalviewLiteJsApi#setSeparator(java.lang.String)
2751 public void setSeparator(String separator)
2753 if (separator == null || separator.length() < 1)
2756 separator = "" + ((char) 0x00AC);
2758 this.separator = separator;
2762 .errPrintln("Default Separator now: '" + separator + "'");
2767 * get boolean value of applet parameter 'name' and return default if
2768 * parameter is not set
2773 * the value to return otherwise
2774 * @return true or false
2776 public boolean getDefaultParameter(String name, boolean def)
2779 if ((stn = getParameter(name)) == null)
2783 if (TRUE.equalsIgnoreCase(stn))
2793 * @see jalview.bin.JalviewLiteJsApi#addPdbFile(jalview.appletgui.AlignFrame,
2794 * java.lang.String, java.lang.String, java.lang.String)
2797 public boolean addPdbFile(AlignFrame alFrame, String sequenceId,
2798 String pdbEntryString, String pdbFile)
2800 return alFrame.addPdbFile(sequenceId, pdbEntryString, pdbFile);
2803 protected void setAlignPdbStructures(boolean alignPdbStructures)
2805 this.alignPdbStructures = alignPdbStructures;
2808 public boolean isAlignPdbStructures()
2810 return alignPdbStructures;
2816 // callInitCallback();
2819 private Hashtable<String, long[]> jshashes = new Hashtable<>();
2821 private Hashtable<String, Hashtable<String, String[]>> jsmessages = new Hashtable<>();
2823 public void setJsMessageSet(String messageclass, String viewId,
2824 String[] colcommands)
2826 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2829 msgset = new Hashtable<>();
2830 jsmessages.put(messageclass, msgset);
2832 msgset.put(viewId, colcommands);
2833 long[] l = new long[colcommands.length];
2834 for (int i = 0; i < colcommands.length; i++)
2836 l[i] = colcommands[i].hashCode();
2838 jshashes.put(messageclass + "|" + viewId, l);
2844 * @see jalview.bin.JalviewLiteJsApi#getJsMessage(java.lang.String,
2848 public String getJsMessage(String messageclass, String viewId)
2850 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2853 String[] msgs = msgset.get(viewId);
2856 for (int i = 0; i < msgs.length; i++)
2858 if (msgs[i] != null)
2870 public boolean isJsMessageSetChanged(String string, String string2,
2871 String[] colcommands)
2873 long[] l = jshashes.get(string + "|" + string2);
2874 if (l == null && colcommands != null)
2878 for (int i = 0; i < colcommands.length; i++)
2880 if (l[i] != colcommands[i].hashCode())
2888 private Vector jsExecQueue = new Vector();
2890 public Vector getJsExecQueue()
2895 public void setExecutor(JSFunctionExec jsFunctionExec2)
2897 jsFunctionExec = jsFunctionExec2;
2901 * return the given colour value parameter or the given default if parameter
2908 public Color getDefaultColourParameter(String colparam, Color defcolour)
2910 String colprop = getParameter(colparam);
2911 if (colprop == null || colprop.trim().length() == 0)
2915 Color col = ColorUtils.parseColourString(colprop);
2918 jalview.bin.Console.errPrintln("Couldn't parse '" + colprop
2919 + "' as a colour for " + colparam);
2921 return (col == null) ? defcolour : col;
2924 public void openJalviewHelpUrl()
2926 String helpUrl = getParameter("jalviewhelpurl");
2927 if (helpUrl == null || helpUrl.trim().length() < 5)
2929 helpUrl = "http://www.jalview.org/help.html";
2931 showURL(helpUrl, "HELP");
2935 * form a complete URL given a path to a resource and a reference location on
2939 * - an absolute path on the same server as localref or a document
2940 * located relative to localref
2942 * - a URL on the same server as url
2943 * @return a complete URL for the resource located by url
2945 private String resolveUrlForLocalOrAbsolute(String targetPath,
2948 String resolvedPath = "";
2949 if (targetPath.startsWith("/"))
2951 String codebase = localref.toString();
2952 String localfile = localref.getFile();
2953 resolvedPath = codebase.substring(0,
2954 codebase.length() - localfile.length()) + targetPath;
2955 return resolvedPath;
2959 * get URL path and strip off any trailing file e.g.
2960 * www.jalview.org/examples/index.html#applets?a=b is trimmed to
2961 * www.jalview.org/examples/
2963 String urlPath = localref.toString();
2964 String directoryPath = urlPath;
2965 int lastSeparator = directoryPath.lastIndexOf("/");
2966 if (lastSeparator > 0)
2968 directoryPath = directoryPath.substring(0, lastSeparator + 1);
2971 if (targetPath.startsWith("/"))
2974 * construct absolute URL to a file on the server - this is not allowed?
2976 // String localfile = localref.getFile();
2977 // resolvedPath = urlPath.substring(0,
2978 // urlPath.length() - localfile.length())
2980 resolvedPath = directoryPath + targetPath.substring(1);
2984 resolvedPath = directoryPath + targetPath;
2988 jalview.bin.Console.errPrintln(
2989 "resolveUrlForLocalOrAbsolute returning " + resolvedPath);
2991 return resolvedPath;
2995 * open a URL in the browser - resolving it according to relative refs and
2996 * coping with javascript: protocol if necessary.
3001 public void showURL(String url, String target)
3005 if (url.indexOf(":") == -1)
3007 // TODO: verify (Bas Vroling bug) prepend codebase or server URL to
3009 // Should really use docbase, not codebase.
3011 url = resolveUrlForLocalOrAbsolute(url,
3012 prepend = getDefaultParameter("resolvetocodebase", false)
3014 : getDocumentBase());
3017 jalview.bin.Console.errPrintln("Show url (prepended " + prepend
3018 + " - toggle resolvetocodebase if code/docbase resolution is wrong): "
3026 jalview.bin.Console.errPrintln("Show url: " + url);
3029 if (url.indexOf("javascript:") == 0)
3031 // no target for the javascript context
3032 getAppletContext().showDocument(new java.net.URL(url));
3036 getAppletContext().showDocument(new java.net.URL(url), target);
3038 } catch (Exception ex)
3040 ex.printStackTrace();
3045 * bind structures in a viewer to any matching sequences in an alignFrame (use
3046 * sequenceIds to limit scope of search to specific sequences)
3050 * @param sequenceIds
3051 * @return TODO: consider making an exception structure for indicating when
3052 * binding fails public SequenceStructureBinding
3053 * addStructureViewInstance( AlignFrame alFrame, Object viewer, String
3056 * if (sequenceIds != null && sequenceIds.length() > 0) { return
3057 * alFrame.addStructureViewInstance(viewer,
3058 * separatorListToArray(sequenceIds)); } else { return
3059 * alFrame.addStructureViewInstance(viewer, null); } // return null; }