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.appletgui.js.JSFunctionExec;
51 import jalview.appletgui.js.JalviewLiteJsApi;
52 import jalview.appletgui.js.JsCallBack;
53 import jalview.appletgui.js.JsSelectionSender;
54 import jalview.appletgui.js.MouseOverListener;
55 import jalview.appletgui.js.MouseOverStructureListener;
56 import jalview.structure.SelectionListener;
57 import jalview.structure.StructureSelectionManager;
58 import jalview.util.ColorUtils;
59 import jalview.util.HttpUtils;
60 import jalview.util.MessageManager;
62 import java.applet.Applet;
63 import java.awt.Button;
64 import java.awt.Color;
65 import java.awt.Component;
66 import java.awt.EventQueue;
68 import java.awt.Frame;
69 import java.awt.Graphics;
70 import java.awt.event.ActionEvent;
71 import java.awt.event.WindowAdapter;
72 import java.awt.event.WindowEvent;
73 import java.io.BufferedReader;
74 import java.io.IOException;
75 import java.io.InputStreamReader;
77 import java.util.ArrayList;
78 import java.util.Hashtable;
79 import java.util.List;
80 import java.util.StringTokenizer;
81 import java.util.Vector;
83 import netscape.javascript.JSObject;
86 * Jalview Applet. Runs in Java 1.18 runtime
89 * @version $Revision: 1.92 $
91 public class JalviewLite extends Applet
92 implements StructureSelectionManagerProvider, JalviewLiteJsApi
95 private static final String TRUE = "true";
97 private static final String FALSE = "false";
99 public StructureSelectionManager getStructureSelectionManager()
101 return StructureSelectionManager.getStructureSelectionManager(this);
104 // /////////////////////////////////////////
105 // The following public methods may be called
106 // externally, eg via javascript in HTML page
110 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences()
113 public String getSelectedSequences()
115 return getSelectedSequencesFrom(getDefaultTargetFrame());
121 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences(java.lang.String)
124 public String getSelectedSequences(String sep)
126 return getSelectedSequencesFrom(getDefaultTargetFrame(), sep);
133 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
137 public String getSelectedSequencesFrom(AlignFrame alf)
139 return getSelectedSequencesFrom(alf, separator); // ""+0x00AC);
146 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
147 * .AlignFrame, java.lang.String)
150 public String getSelectedSequencesFrom(AlignFrame alf, String sep)
152 StringBuffer result = new StringBuffer("");
153 if (sep == null || sep.length() == 0)
155 sep = separator; // "+0x00AC;
157 if (alf.viewport.getSelectionGroup() != null)
159 SequenceI[] seqs = alf.viewport.getSelectionGroup()
160 .getSequencesInOrder(alf.viewport.getAlignment());
162 for (int i = 0; i < seqs.length; i++)
164 result.append(seqs[i].getName());
169 return result.toString();
175 * @see jalview.bin.JalviewLiteJsApi#highlight(java.lang.String,
176 * java.lang.String, java.lang.String)
179 public void highlight(String sequenceId, String position,
180 String alignedPosition)
182 highlightIn(getDefaultTargetFrame(), sequenceId, position,
189 * @see jalview.bin.JalviewLiteJsApi#highlightIn(jalview.appletgui.AlignFrame,
190 * java.lang.String, java.lang.String, java.lang.String)
193 public void highlightIn(final AlignFrame alf, final String sequenceId,
194 final String position, final String alignedPosition)
196 // TODO: could try to highlight in all alignments if alf==null
197 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
198 alf.viewport.getAlignment().getSequencesArray());
199 final SequenceI sq = matcher.findIdMatch(sequenceId);
205 apos = Integer.valueOf(position).intValue();
207 } catch (NumberFormatException ex)
211 final StructureSelectionManagerProvider me = this;
212 final int pos = apos;
213 // use vamsas listener to broadcast to all listeners in scope
214 if (alignedPosition != null
215 && (alignedPosition.trim().length() == 0 || alignedPosition
216 .toLowerCase(Locale.ROOT).indexOf("false") > -1))
218 java.awt.EventQueue.invokeLater(new Runnable()
223 StructureSelectionManager.getStructureSelectionManager(me)
224 .mouseOverVamsasSequence(sq, sq.findIndex(pos), null);
230 java.awt.EventQueue.invokeLater(new Runnable()
235 StructureSelectionManager.getStructureSelectionManager(me)
236 .mouseOverVamsasSequence(sq, pos, null);
246 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
250 public void select(String sequenceIds, String columns)
252 selectIn(getDefaultTargetFrame(), sequenceIds, columns, separator);
258 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
259 * java.lang.String, java.lang.String)
262 public void select(String sequenceIds, String columns, String sep)
264 selectIn(getDefaultTargetFrame(), sequenceIds, columns, sep);
270 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
271 * java.lang.String, java.lang.String)
274 public void selectIn(AlignFrame alf, String sequenceIds, String columns)
276 selectIn(alf, sequenceIds, columns, separator);
282 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
283 * java.lang.String, java.lang.String, java.lang.String)
286 public void selectIn(final AlignFrame alf, String sequenceIds,
287 String columns, String sep)
289 if (sep == null || sep.length() == 0)
297 System.err.println("Selecting region using separator string '"
302 String[] ids = separatorListToArray(sequenceIds, sep);
303 String[] cols = separatorListToArray(columns, sep);
304 final SequenceGroup sel = new SequenceGroup();
305 final ColumnSelection csel = new ColumnSelection();
306 AlignmentI al = alf.viewport.getAlignment();
307 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
308 alf.viewport.getAlignment().getSequencesArray());
309 int start = 0, end = al.getWidth(), alw = al.getWidth();
310 boolean seqsfound = true;
311 if (ids != null && ids.length > 0)
314 for (int i = 0; i < ids.length; i++)
316 if (ids[i].trim().length() == 0)
320 SequenceI sq = matcher.findIdMatch(ids[i]);
324 sel.addSequence(sq, false);
328 boolean inseqpos = false;
329 if (cols != null && cols.length > 0)
331 boolean seset = false;
332 for (int i = 0; i < cols.length; i++)
334 String cl = cols[i].trim();
335 if (cl.length() == 0)
340 if ((p = cl.indexOf("-")) > -1)
342 int from = -1, to = -1;
345 from = Integer.valueOf(cl.substring(0, p)).intValue();
347 } catch (NumberFormatException ex)
350 "ERROR: Couldn't parse first integer in range element column selection string '"
351 + cl + "' - format is 'from-to'");
356 to = Integer.valueOf(cl.substring(p + 1)).intValue();
358 } catch (NumberFormatException ex)
361 "ERROR: Couldn't parse second integer in range element column selection string '"
362 + cl + "' - format is 'from-to'");
365 if (from >= 0 && to >= 0)
382 // comment to prevent range extension
392 for (int r = from; r <= to; r++)
394 if (r >= 0 && r < alw)
401 System.err.println("Range '" + cl + "' deparsed as [" + from
407 System.err.println("ERROR: Invalid Range '" + cl
408 + "' deparsed as [" + from + "," + to + "]");
416 r = Integer.valueOf(cl).intValue();
418 } catch (NumberFormatException ex)
420 if (cl.toLowerCase(Locale.ROOT).equals("sequence"))
422 // we are in the dataset sequence's coordinate frame.
428 "ERROR: Couldn't parse integer from point selection element of column selection string '"
433 if (r >= 0 && r <= alw)
443 // comment to prevent range extension
456 System.err.println("Point selection '" + cl
457 + "' deparsed as [" + r + "]");
462 System.err.println("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<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)
946 "jalview Javascript error: Ignoring empty function for mouseover listener.");
950 MouseOverListener mol = new MouseOverListener(
952 javascriptListeners.addElement(mol);
953 StructureSelectionManager.getStructureSelectionManager(this)
954 .addStructureViewerListener(mol);
957 System.err.println("Added a mouseover listener for "
958 + ((af == null) ? "All frames"
960 + af.getAlignViewport().getSequenceSetId()));
961 System.err.println("There are now " + javascriptListeners.size()
962 + " 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)
993 "jalview Javascript error: Ignoring empty function for selection listener.");
997 JsSelectionSender mol = new JsSelectionSender(
999 javascriptListeners.addElement(mol);
1000 StructureSelectionManager.getStructureSelectionManager(this)
1001 .addSelectionListener(mol);
1004 System.err.println("Added a selection listener for "
1005 + ((af == null) ? "All frames"
1007 + af.getAlignViewport().getSequenceSetId()));
1008 System.err.println("There are now " + javascriptListeners.size()
1009 + " 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)
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);
1044 System.err.println("Added a javascript structure viewer listener '"
1046 System.err.println("There are now " + javascriptListeners.size()
1047 + " listeners in total.");
1055 * jalview.bin.JalviewLiteJsApi#removeJavascriptListener(jalview.appletgui
1056 * .AlignFrame, java.lang.String)
1059 public void removeJavascriptListener(AlignFrame af, String listener)
1061 if (listener != null)
1063 listener = listener.trim();
1064 if (listener.length() == 0)
1069 boolean rprt = false;
1070 for (int ms = 0, msSize = javascriptListeners.size(); ms < msSize;)
1072 Object lstn = javascriptListeners.elementAt(ms);
1073 JsCallBack lstner = (JsCallBack) lstn;
1074 if ((af == null || lstner.getAlignFrame() == af) && (listener == null
1075 || lstner.getListenerFunction().equals(listener)))
1077 javascriptListeners.removeElement(lstner);
1079 if (lstner instanceof SelectionListener)
1081 StructureSelectionManager.getStructureSelectionManager(this)
1082 .removeSelectionListener((SelectionListener) lstner);
1086 StructureSelectionManager.getStructureSelectionManager(this)
1087 .removeStructureViewerListener(lstner, null);
1092 System.err.println("Removed listener '" + listener + "'");
1102 System.err.println("There are now " + javascriptListeners.size()
1103 + " listeners in total.");
1110 System.err.println("Applet " + getName() + " stop().");
1115 public void destroy()
1117 System.err.println("Applet " + getName() + " destroy().");
1121 private void tidyUp()
1124 if (currentAlignFrame != null && currentAlignFrame.viewport != null
1125 && currentAlignFrame.viewport.applet != null)
1127 AlignViewport av = currentAlignFrame.viewport;
1128 currentAlignFrame.closeMenuItem_actionPerformed();
1130 currentAlignFrame = null;
1132 if (javascriptListeners != null)
1134 while (javascriptListeners.size() > 0)
1136 JSFunctionExec mol = javascriptListeners
1138 javascriptListeners.removeElement(mol);
1139 if (mol instanceof SelectionListener)
1141 StructureSelectionManager.getStructureSelectionManager(this)
1142 .removeSelectionListener((SelectionListener) mol);
1146 StructureSelectionManager.getStructureSelectionManager(this)
1147 .removeStructureViewerListener(mol, null);
1152 if (jsFunctionExec != null)
1154 jsFunctionExec.stopQueue();
1155 jsFunctionExec.jvlite = null;
1157 initialAlignFrame = null;
1158 jsFunctionExec = null;
1159 javascriptListeners = null;
1160 StructureSelectionManager.release(this);
1163 private JSFunctionExec jsFunctionExec;
1168 * @see jalview.bin.JalviewLiteJsApi#mouseOverStructure(java.lang.String,
1169 * java.lang.String, java.lang.String)
1172 public void mouseOverStructure(final String pdbResNum, final String chain,
1173 final String pdbfile)
1175 final StructureSelectionManagerProvider me = this;
1176 java.awt.EventQueue.invokeLater(new Runnable()
1183 StructureSelectionManager.getStructureSelectionManager(me)
1184 .mouseOverStructure(Integer.valueOf(pdbResNum).intValue(),
1189 .println("mouseOver for '" + pdbResNum + "' in chain '"
1190 + chain + "' in structure '" + pdbfile + "'");
1192 } catch (NumberFormatException e)
1194 System.err.println("Ignoring invalid residue number string '"
1206 * jalview.bin.JalviewLiteJsApi#scrollViewToIn(jalview.appletgui.AlignFrame,
1207 * java.lang.String, java.lang.String)
1210 public void scrollViewToIn(final AlignFrame alf, final String topRow,
1211 final String leftHandColumn)
1213 java.awt.EventQueue.invokeLater(new Runnable()
1220 alf.scrollTo(Integer.valueOf(topRow).intValue(),
1221 Integer.valueOf(leftHandColumn).intValue());
1223 } catch (Exception ex)
1225 System.err.println("Couldn't parse integer arguments (topRow='"
1226 + topRow + "' and leftHandColumn='" + leftHandColumn
1228 ex.printStackTrace();
1238 * JalviewLiteJsApi#scrollViewToRowIn(jalview.appletgui
1239 * .AlignFrame, java.lang.String)
1242 public void scrollViewToRowIn(final AlignFrame alf, final String topRow)
1245 java.awt.EventQueue.invokeLater(new Runnable()
1252 alf.scrollToRow(Integer.valueOf(topRow).intValue());
1254 } catch (Exception ex)
1256 System.err.println("Couldn't parse integer arguments (topRow='"
1258 ex.printStackTrace();
1269 * JalviewLiteJsApi#scrollViewToColumnIn(jalview.appletgui
1270 * .AlignFrame, java.lang.String)
1273 public void scrollViewToColumnIn(final AlignFrame alf,
1274 final String leftHandColumn)
1276 java.awt.EventQueue.invokeLater(new Runnable()
1284 alf.scrollToColumn(Integer.valueOf(leftHandColumn).intValue());
1286 } catch (Exception ex)
1289 "Couldn't parse integer arguments (leftHandColumn='"
1290 + leftHandColumn + "')");
1291 ex.printStackTrace();
1298 // //////////////////////////////////////////////
1299 // //////////////////////////////////////////////
1301 public static int lastFrameX = 200;
1303 public static int lastFrameY = 200;
1305 boolean fileFound = true;
1307 String file = "No file";
1309 String file2 = null;
1311 Button launcher = new Button(
1312 MessageManager.getString("label.start_jalview"));
1315 * The currentAlignFrame is static, it will change if and when the user
1316 * selects a new window. Note that it will *never* point back to the embedded
1317 * AlignFrame if the applet is started as embedded on the page and then
1318 * afterwards a new view is created.
1320 public AlignFrame currentAlignFrame = null;
1323 * This is the first frame to be displayed, and does not change. API calls
1324 * will default to this instance if currentAlignFrame is null.
1326 AlignFrame initialAlignFrame = null;
1328 boolean embedded = false;
1330 private boolean checkForJmol = true;
1332 private boolean checkedForJmol = false; // ensure we don't check for jmol
1334 // every time the app is re-inited
1336 public boolean jmolAvailable = false;
1338 private boolean alignPdbStructures = false;
1341 * use an external structure viewer exclusively (no jmols or mc_views will be
1342 * opened by JalviewLite itself)
1344 public boolean useXtrnalSviewer = false;
1346 public static boolean debug = false;
1348 static String builddate = null, version = null, installation = null;
1350 private static void initBuildDetails()
1352 if (builddate == null)
1354 builddate = "unknown";
1356 installation = "applet";
1357 java.net.URL url = JalviewLite.class
1358 .getResource("/.build_properties");
1363 BufferedReader reader = new BufferedReader(
1364 new InputStreamReader(url.openStream()));
1366 while ((line = reader.readLine()) != null)
1368 if (line.indexOf("VERSION") > -1)
1370 version = line.substring(line.indexOf("=") + 1);
1372 if (line.indexOf("BUILD_DATE") > -1)
1374 builddate = line.substring(line.indexOf("=") + 1);
1376 if (line.indexOf("INSTALLATION") > -1)
1378 installation = line.substring(line.indexOf("=") + 1);
1381 } catch (Exception ex)
1383 ex.printStackTrace();
1389 public static String getBuildDate()
1395 public static String getInstallation()
1398 return installation;
1401 public static String getVersion()
1407 // public JSObject scriptObject = null;
1410 * init method for Jalview Applet
1415 debug = TRUE.equalsIgnoreCase(getParameter("debug"));
1420 System.err.println("Applet context is '"
1421 + getAppletContext().getClass().toString() + "'");
1423 JSObject scriptObject = JSObject.getWindow(this);
1424 if (debug && scriptObject != null)
1426 System.err.println("Applet has Javascript callback support.");
1429 } catch (Exception ex)
1432 "Warning: No JalviewLite javascript callbacks available.");
1435 ex.printStackTrace();
1441 System.err.println("JalviewLite Version " + getVersion());
1442 System.err.println("Build Date : " + getBuildDate());
1443 System.err.println("Installation : " + getInstallation());
1445 String externalsviewer = getParameter("externalstructureviewer");
1446 if (externalsviewer != null)
1448 useXtrnalSviewer = externalsviewer.trim().toLowerCase(Locale.ROOT)
1452 * if true disable the check for jmol
1454 String chkforJmol = getParameter("nojmol");
1455 if (chkforJmol != null)
1457 checkForJmol = !chkforJmol.equals(TRUE);
1460 * get the separator parameter if present
1462 String sep = getParameter("separator");
1465 if (sep.length() > 0)
1470 System.err.println("Separator set to '" + separator + "'");
1475 throw new Error(MessageManager
1476 .getString("error.invalid_separator_parameter"));
1482 String param = getParameter("RGB");
1488 r = Integer.parseInt(param.substring(0, 2), 16);
1489 g = Integer.parseInt(param.substring(2, 4), 16);
1490 b = Integer.parseInt(param.substring(4, 6), 16);
1491 } catch (Exception ex)
1498 param = getParameter("label");
1501 launcher.setLabel(param);
1504 setBackground(new Color(r, g, b));
1506 file = getParameter("file");
1510 // Maybe the sequences are added as parameters
1511 StringBuffer data = new StringBuffer("PASTE");
1513 while ((file = getParameter("sequence" + i)) != null)
1515 data.append(file.toString() + "\n");
1518 if (data.length() > 5)
1520 file = data.toString();
1523 if (getDefaultParameter("enableSplitFrame", true))
1525 file2 = getParameter("file2");
1528 embedded = TRUE.equalsIgnoreCase(getParameter("embedded"));
1531 LoadingThread loader = new LoadingThread(file, file2, this);
1534 else if (file != null)
1537 * Start the applet immediately or show a button to start it
1539 if (FALSE.equalsIgnoreCase(getParameter("showbutton")))
1541 LoadingThread loader = new LoadingThread(file, file2, this);
1547 launcher.addActionListener(new java.awt.event.ActionListener()
1550 public void actionPerformed(ActionEvent e)
1552 LoadingThread loader = new LoadingThread(file, file2,
1561 // jalview initialisation with no alignment. loadAlignment() method can
1562 // still be called to open new alignments.
1569 private void initLiveConnect()
1571 // try really hard to get the liveConnect thing working
1572 boolean notFailed = false;
1574 while (!notFailed && tries < 10)
1578 System.err.println("LiveConnect request thread going to sleep.");
1582 Thread.sleep(700 * (1 + tries));
1583 } catch (InterruptedException q)
1589 System.err.println("LiveConnect request thread woken up.");
1593 JSObject scriptObject = JSObject.getWindow(this);
1594 if (scriptObject.eval("navigator") != null)
1598 } catch (Exception jsex)
1600 System.err.println("Attempt " + tries
1601 + " to access LiveConnect javascript failed.");
1606 private void callInitCallback()
1608 String initjscallback = getParameter("oninit");
1609 if (initjscallback == null)
1613 initjscallback = initjscallback.trim();
1614 if (initjscallback.length() > 0)
1616 JSObject scriptObject = null;
1619 scriptObject = JSObject.getWindow(this);
1620 } catch (Exception ex)
1624 // try really hard to let the browser plugin know we want liveconnect
1627 if (scriptObject != null)
1631 // do onInit with the JS executor thread
1632 new JSFunctionExec(this).executeJavascriptFunction(true,
1633 initjscallback, null,
1634 "Calling oninit callback '" + initjscallback + "'.");
1635 } catch (Exception e)
1637 System.err.println("Exception when executing _oninit callback '"
1638 + initjscallback + "'.");
1639 e.printStackTrace();
1644 System.err.println("Not executing _oninit callback '"
1645 + initjscallback + "' - no scripting allowed.");
1651 * Initialises and displays a new java.awt.Frame
1654 * java.awt.Frame to be displayed
1656 * title of new frame
1658 * width if new frame
1660 * height of new frame
1662 public static void addFrame(final Frame frame, String title, int width,
1665 frame.setLocation(lastFrameX, lastFrameY);
1668 frame.setSize(width, height);
1669 frame.setTitle(title);
1670 frame.addWindowListener(new WindowAdapter()
1673 public void windowClosing(WindowEvent e)
1675 if (frame instanceof AlignFrame)
1677 AlignViewport vp = ((AlignFrame) frame).viewport;
1678 ((AlignFrame) frame).closeMenuItem_actionPerformed();
1679 if (vp.applet.currentAlignFrame == frame)
1681 vp.applet.currentAlignFrame = null;
1689 if (frame instanceof EmbmenuFrame)
1691 ((EmbmenuFrame) frame).destroyMenus();
1693 frame.setMenuBar(null);
1698 public void windowActivated(WindowEvent e)
1700 if (frame instanceof AlignFrame)
1702 ((AlignFrame) frame).viewport.applet.currentAlignFrame = (AlignFrame) frame;
1705 System.err.println("Activated window " + frame);
1709 super.windowActivated(e);
1712 * Probably not necessary to do this - see TODO above. (non-Javadoc)
1715 * java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent
1718 * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
1719 * frame) { currentAlignFrame = null; if (debug) {
1720 * System.err.println("Deactivated window "+frame); } }
1721 * super.windowDeactivated(e); }
1724 frame.setVisible(true);
1728 * This paints the background surrounding the "Launch Jalview button" <br>
1730 * If file given in parameter not found, displays error message
1736 public void paint(Graphics g)
1740 g.setColor(new Color(200, 200, 200));
1741 g.setColor(Color.cyan);
1742 g.fillRect(0, 0, getSize().width, getSize().height);
1743 g.setColor(Color.red);
1745 MessageManager.getString("label.jalview_cannot_open_file"), 5,
1747 g.drawString("\"" + file + "\"", 5, 30);
1751 g.setColor(Color.black);
1752 g.setFont(new Font("Arial", Font.BOLD, 24));
1753 g.drawString(MessageManager.getString("label.jalview_applet"), 50,
1754 getSize().height / 2 - 30);
1755 g.drawString(MessageManager.getString("label.loading_data") + "...",
1756 50, getSize().height / 2);
1761 * get all components associated with the applet of the given type
1766 public Vector getAppletWindow(Class class1)
1768 Vector wnds = new Vector();
1769 Component[] cmp = getComponents();
1772 for (int i = 0; i < cmp.length; i++)
1774 if (class1.isAssignableFrom(cmp[i].getClass()))
1776 wnds.addElement(cmp);
1783 class LoadJmolThread extends Thread
1785 private boolean running = false;
1790 if (running || checkedForJmol)
1799 if (!System.getProperty("java.version").startsWith("1.1"))
1801 Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
1802 jmolAvailable = true;
1807 "Jmol not available - Using mc_view for structures");
1809 } catch (java.lang.ClassNotFoundException ex)
1815 jmolAvailable = false;
1819 "Skipping Jmol check. Will use mc_view (probably)");
1822 checkedForJmol = true;
1826 public boolean notFinished()
1828 return running || !checkedForJmol;
1832 class LoadingThread extends Thread
1835 * State variable: protocol for access to file source
1837 DataSourceType protocol;
1839 String _file; // alignment file or URL spec
1841 String _file2; // second alignment file or URL spec
1845 private void dbgMsg(String msg)
1847 if (JalviewLite.debug)
1849 System.err.println(msg);
1854 * update the protocol state variable for accessing the datasource located
1858 * @return possibly updated datasource string
1860 public String resolveFileProtocol(String path)
1865 if (path.startsWith("PASTE"))
1867 protocol = DataSourceType.PASTE;
1868 return path.substring(5);
1874 if (path.indexOf("://") != -1)
1876 protocol = DataSourceType.URL;
1881 * try relative to document root
1883 URL documentBase = getDocumentBase();
1884 String withDocBase = resolveUrlForLocalOrAbsolute(path, documentBase);
1885 if (HttpUtils.isValidUrl(withDocBase))
1889 System.err.println("Prepended document base '" + documentBase
1890 + "' to make: '" + withDocBase + "'");
1892 protocol = DataSourceType.URL;
1897 * try relative to codebase (if different to document base)
1899 URL codeBase = getCodeBase();
1900 String withCodeBase = applet.resolveUrlForLocalOrAbsolute(path,
1902 if (!withCodeBase.equals(withDocBase)
1903 && HttpUtils.isValidUrl(withCodeBase))
1905 protocol = DataSourceType.URL;
1908 System.err.println("Prepended codebase '" + codeBase
1909 + "' to make: '" + withCodeBase + "'");
1911 return withCodeBase;
1915 * try locating by classloader; try this last so files in the directory
1916 * are resolved using document base
1918 if (inArchive(path))
1920 protocol = DataSourceType.CLASSLOADER;
1925 public LoadingThread(String file, String file2, JalviewLite _applet)
1928 this._file2 = file2;
1935 LoadJmolThread jmolchecker = new LoadJmolThread();
1936 jmolchecker.start();
1937 while (jmolchecker.notFinished())
1939 // wait around until the Jmol check is complete.
1943 } catch (Exception e)
1948 // applet.callInitCallback();
1952 * Load the alignment and any related files as specified by applet
1955 private void startLoading()
1957 dbgMsg("Loading thread started with:\n>>file\n" + _file
1960 dbgMsg("Loading started.");
1962 AlignFrame newAlignFrame = readAlignment(_file);
1963 AlignFrame newAlignFrame2 = readAlignment(_file2);
1964 if (newAlignFrame != null)
1966 addToDisplay(newAlignFrame, newAlignFrame2);
1967 loadTree(newAlignFrame);
1969 loadScoreFile(newAlignFrame);
1971 loadFeatures(newAlignFrame);
1973 loadAnnotations(newAlignFrame);
1975 loadJnetFile(newAlignFrame);
1977 loadPdbFiles(newAlignFrame);
1982 applet.remove(launcher);
1989 * Add an AlignFrame to the display; or if two are provided, a SplitFrame.
1994 public void addToDisplay(AlignFrame af, AlignFrame af2)
1998 AlignmentI al1 = af.viewport.getAlignment();
1999 AlignmentI al2 = af2.viewport.getAlignment();
2000 AlignmentI cdna = al1.isNucleotide() ? al1 : al2;
2001 AlignmentI prot = al1.isNucleotide() ? al2 : al1;
2002 if (AlignmentUtils.mapProteinAlignmentToCdna(prot, cdna))
2005 SplitFrame sf = new SplitFrame(af, af2);
2006 sf.addToDisplay(embedded, JalviewLite.this);
2011 String msg = "Could not map any sequence in " + af2.getTitle()
2013 + (al1.isNucleotide() ? "protein product" : "cDNA")
2014 + " for " + af.getTitle();
2015 System.err.println(msg);
2019 af.addToDisplay(embedded);
2023 * Read the alignment file (from URL, text 'paste', or archive by
2028 protected AlignFrame readAlignment(String fileParam)
2030 if (fileParam == null)
2034 String resolvedFile = resolveFileProtocol(fileParam);
2035 AlignmentI al = null;
2038 FileFormatI format = new IdentifyFile().identify(resolvedFile,
2040 dbgMsg("File identified as '" + format + "'");
2041 al = new AppletFormatAdapter().readFile(resolvedFile, protocol,
2043 if ((al != null) && (al.getHeight() > 0))
2045 dbgMsg("Successfully loaded file.");
2046 al.setDataset(null);
2047 AlignFrame newAlignFrame = new AlignFrame(al, applet,
2048 resolvedFile, embedded, false);
2049 newAlignFrame.setTitle(resolvedFile);
2050 if (initialAlignFrame == null)
2052 initialAlignFrame = newAlignFrame;
2054 // update the focus.
2055 currentAlignFrame = newAlignFrame;
2057 if (protocol == DataSourceType.PASTE)
2059 newAlignFrame.setTitle(MessageManager
2060 .formatMessage("label.sequences_from", new Object[]
2061 { applet.getDocumentBase().toString() }));
2064 newAlignFrame.statusBar.setText(MessageManager.formatMessage(
2065 "label.successfully_loaded_file", new Object[]
2068 return newAlignFrame;
2070 } catch (java.io.IOException ex)
2072 dbgMsg("File load exception.");
2073 ex.printStackTrace();
2078 FileParse fp = new FileParse(resolvedFile, protocol);
2080 dbgMsg(">>>Dumping contents of '" + resolvedFile + "' " + "("
2082 while ((ln = fp.nextLine()) != null)
2086 dbgMsg(">>>Dump finished.");
2087 } catch (Exception e)
2090 "Exception when trying to dump the content of the file parameter.");
2091 e.printStackTrace();
2099 * Load PDBFiles if any specified by parameter(s). Returns true if loaded,
2105 protected boolean loadPdbFiles(AlignFrame alignFrame)
2107 boolean result = false;
2109 * <param name="alignpdbfiles" value="false/true"/> Undocumented for 2.6 -
2110 * related to JAL-434
2113 applet.setAlignPdbStructures(
2114 getDefaultParameter("alignpdbfiles", false));
2116 * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
2119 * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
2121 * <param name="PDBfile3" value="1q0o Q45135_9MICO">
2124 int pdbFileCount = 0;
2125 // Accumulate pdbs here if they are heading for the same view (if
2126 // alignPdbStructures is true)
2127 Vector pdbs = new Vector();
2128 // create a lazy matcher if we're asked to
2129 jalview.analysis.SequenceIdMatcher matcher = (applet
2130 .getDefaultParameter("relaxedidmatch", false))
2131 ? new jalview.analysis.SequenceIdMatcher(
2132 alignFrame.getAlignViewport().getAlignment()
2133 .getSequencesArray())
2139 if (pdbFileCount > 0)
2141 param = applet.getParameter("PDBFILE" + pdbFileCount);
2145 param = applet.getParameter("PDBFILE");
2150 PDBEntry pdb = new PDBEntry();
2153 SequenceI[] seqs = null;
2154 String[] chains = null;
2156 StringTokenizer st = new StringTokenizer(param, " ");
2158 if (st.countTokens() < 2)
2160 String sequence = applet.getParameter("PDBSEQ");
2161 if (sequence != null)
2163 seqs = new SequenceI[] { matcher == null
2164 ? (Sequence) alignFrame.getAlignViewport()
2165 .getAlignment().findName(sequence)
2166 : matcher.findIdMatch(sequence) };
2172 param = st.nextToken();
2173 List<SequenceI> tmp = new ArrayList<>();
2174 List<String> tmp2 = new ArrayList<>();
2176 while (st.hasMoreTokens())
2178 seqstring = st.nextToken();
2179 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
2180 if (st2.countTokens() > 1)
2182 // This is the chain
2183 tmp2.add(st2.nextToken());
2184 seqstring = st2.nextToken();
2186 tmp.add(matcher == null
2187 ? (Sequence) alignFrame.getAlignViewport()
2188 .getAlignment().findName(seqstring)
2189 : matcher.findIdMatch(seqstring));
2192 seqs = tmp.toArray(new SequenceI[tmp.size()]);
2193 if (tmp2.size() == tmp.size())
2195 chains = tmp2.toArray(new String[tmp2.size()]);
2198 param = resolveFileProtocol(param);
2199 // TODO check JAL-357 for files in a jar (CLASSLOADER)
2204 for (int i = 0; i < seqs.length; i++)
2206 if (seqs[i] != null)
2208 ((Sequence) seqs[i]).addPDBId(pdb);
2209 StructureSelectionManager
2210 .getStructureSelectionManager(applet)
2211 .registerPDBEntry(pdb);
2215 if (JalviewLite.debug)
2217 // this may not really be a problem but we give a warning
2220 "Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
2226 if (!alignPdbStructures)
2228 alignFrame.newStructureView(applet, pdb, seqs, chains,
2233 pdbs.addElement(new Object[] { pdb, seqs, chains, protocol });
2239 } while (param != null || pdbFileCount < 10);
2240 if (pdbs.size() > 0)
2242 SequenceI[][] seqs = new SequenceI[pdbs.size()][];
2243 PDBEntry[] pdb = new PDBEntry[pdbs.size()];
2244 String[][] chains = new String[pdbs.size()][];
2245 String[] protocols = new String[pdbs.size()];
2246 for (int pdbsi = 0, pdbsiSize = pdbs
2247 .size(); pdbsi < pdbsiSize; pdbsi++)
2249 Object[] o = (Object[]) pdbs.elementAt(pdbsi);
2250 pdb[pdbsi] = (PDBEntry) o[0];
2251 seqs[pdbsi] = (SequenceI[]) o[1];
2252 chains[pdbsi] = (String[]) o[2];
2253 protocols[pdbsi] = (String) o[3];
2255 alignFrame.alignedStructureView(applet, pdb, seqs, chains,
2263 * Load in a Jnetfile if specified by parameter. Returns true if loaded,
2269 protected boolean loadJnetFile(AlignFrame alignFrame)
2271 boolean result = false;
2272 String param = applet.getParameter("jnetfile");
2275 // jnet became jpred around 2016
2276 param = applet.getParameter("jpredfile");
2282 param = resolveFileProtocol(param);
2283 JPredFile predictions = new JPredFile(param, protocol);
2284 JnetAnnotationMaker.add_annotation(predictions,
2285 alignFrame.viewport.getAlignment(), 0, false);
2286 // false == do not add sequence profile from concise output
2288 alignFrame.viewport.getAlignment().setupJPredAlignment();
2290 alignFrame.alignPanel.fontChanged();
2291 alignFrame.alignPanel.setScrollValues(0, 0);
2293 } catch (Exception ex)
2295 ex.printStackTrace();
2302 * Load annotations if specified by parameter. Returns true if loaded, else
2308 protected boolean loadAnnotations(AlignFrame alignFrame)
2310 boolean result = false;
2311 String param = applet.getParameter("annotations");
2314 param = resolveFileProtocol(param);
2316 if (new AnnotationFile().annotateAlignmentView(alignFrame.viewport,
2319 alignFrame.alignPanel.fontChanged();
2320 alignFrame.alignPanel.setScrollValues(0, 0);
2326 "Annotations were not added from annotation file '"
2334 * Load features file and view settings as specified by parameters. Returns
2335 * true if features were loaded, else false.
2340 protected boolean loadFeatures(AlignFrame alignFrame)
2342 boolean result = false;
2343 // ///////////////////////////
2344 // modify display of features
2345 // we do this before any features have been loaded, ensuring any hidden
2346 // groups are hidden when features first displayed
2348 // hide specific groups
2350 String param = applet.getParameter("hidefeaturegroups");
2353 alignFrame.setFeatureGroupState(separatorListToArray(param), false);
2354 // applet.setFeatureGroupStateOn(newAlignFrame, param, false);
2356 // show specific groups
2357 param = applet.getParameter("showfeaturegroups");
2360 alignFrame.setFeatureGroupState(separatorListToArray(param), true);
2361 // applet.setFeatureGroupStateOn(newAlignFrame, param, true);
2363 // and now load features
2364 param = applet.getParameter("features");
2367 param = resolveFileProtocol(param);
2369 result = alignFrame.parseFeaturesFile(param, protocol);
2372 param = applet.getParameter("showFeatureSettings");
2373 if (param != null && param.equalsIgnoreCase(TRUE))
2375 alignFrame.viewport.setShowSequenceFeatures(true);
2376 new FeatureSettings(alignFrame.alignPanel);
2382 * Load a score file if specified by parameter. Returns true if file was
2383 * loaded, else false.
2387 protected boolean loadScoreFile(AlignFrame alignFrame)
2389 boolean result = false;
2390 String sScoreFile = applet.getParameter("scoreFile");
2391 if (sScoreFile != null && !"".equals(sScoreFile))
2398 "Attempting to load T-COFFEE score file from the scoreFile parameter");
2400 result = alignFrame.loadScoreFile(sScoreFile);
2404 "Failed to parse T-COFFEE parameter as a valid score file ('"
2405 + sScoreFile + "')");
2407 } catch (Exception e)
2409 System.err.printf("Cannot read score file: '%s'. Cause: %s \n",
2410 sScoreFile, e.getMessage());
2417 * Load a tree for the alignment if specified by parameter. Returns true if
2418 * a tree was loaded, else false.
2423 protected boolean loadTree(AlignFrame alignFrame)
2425 boolean result = false;
2426 String treeFile = applet.getParameter("tree");
2427 if (treeFile == null)
2429 treeFile = applet.getParameter("treeFile");
2432 if (treeFile != null)
2436 treeFile = resolveFileProtocol(treeFile);
2437 NewickFile fin = new NewickFile(treeFile, protocol);
2440 if (fin.getTree() != null)
2442 alignFrame.loadTree(fin, treeFile);
2444 dbgMsg("Successfully imported tree.");
2448 dbgMsg("Tree parameter did not resolve to a valid tree.");
2450 } catch (Exception ex)
2452 ex.printStackTrace();
2459 * Discovers whether the given file is in the Applet Archive
2465 boolean inArchive(String f)
2467 // This might throw a security exception in certain browsers
2468 // Netscape Communicator for instance.
2471 boolean rtn = (getClass().getResourceAsStream("/" + f) != null);
2474 System.err.println("Resource '" + f + "' was "
2475 + (rtn ? "" : "not ") + "located by classloader.");
2478 } catch (Exception ex)
2480 System.out.println("Exception checking resources: " + f + " " + ex);
2487 * @return the default alignFrame acted on by the public applet methods. May
2488 * return null with an error message on System.err indicating the
2491 public AlignFrame getDefaultTargetFrame()
2493 if (currentAlignFrame != null)
2495 return currentAlignFrame;
2497 if (initialAlignFrame != null)
2499 return initialAlignFrame;
2502 "Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
2507 * separator used for separatorList
2509 protected String separator = "" + ((char) 0x00AC); // the default used to be
2510 // '|' but many sequence
2511 // IDS include pipes.
2514 * set to enable the URL based javascript execution mechanism
2516 public boolean jsfallbackEnabled = false;
2519 * parse the string into a list
2522 * @return elements separated by separator
2524 public String[] separatorListToArray(String list)
2526 return separatorListToArray(list, separator);
2530 * parse the string into a list
2534 * @return elements separated by separator
2536 public static String[] separatorListToArray(String list, String separator)
2538 // TODO use StringUtils version (slightly different...)
2539 int seplen = separator.length();
2540 if (list == null || list.equals("") || list.equals(separator))
2544 java.util.Vector jv = new Vector();
2546 while ((pos = list.indexOf(separator, cp)) > cp)
2548 jv.addElement(list.substring(cp, pos));
2551 if (cp < list.length())
2553 String c = list.substring(cp);
2554 if (!c.equals(separator))
2561 String[] v = new String[jv.size()];
2562 for (int i = 0; i < v.length; i++)
2564 v[i] = (String) jv.elementAt(i);
2566 jv.removeAllElements();
2569 System.err.println("Array from '" + separator
2570 + "' separated List:\n" + v.length);
2571 for (int i = 0; i < v.length; i++)
2573 System.err.println("item " + i + " '" + v[i] + "'");
2581 "Empty Array from '" + separator + "' separated List");
2587 * concatenate the list with separator
2590 * @return concatenated string
2592 public String arrayToSeparatorList(String[] list)
2594 return arrayToSeparatorList(list, separator);
2598 * concatenate the list with separator
2602 * @return concatenated string
2604 public static String arrayToSeparatorList(String[] list, String separator)
2606 // TODO use StringUtils version
2607 StringBuffer v = new StringBuffer();
2608 if (list != null && list.length > 0)
2610 for (int i = 0, iSize = list.length; i < iSize; i++)
2612 if (list[i] != null)
2616 v.append(separator);
2624 .println("Returning '" + separator + "' separated List:\n");
2625 System.err.println(v);
2627 return v.toString();
2632 "Returning empty '" + separator + "' separated List\n");
2634 return "" + separator;
2640 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroups()
2643 public String getFeatureGroups()
2645 String lst = arrayToSeparatorList(
2646 getDefaultTargetFrame().getFeatureGroups());
2654 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOn(jalview.appletgui.AlignFrame
2658 public String getFeatureGroupsOn(AlignFrame alf)
2660 String lst = arrayToSeparatorList(alf.getFeatureGroups());
2667 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfState(boolean)
2670 public String getFeatureGroupsOfState(boolean visible)
2672 return arrayToSeparatorList(
2673 getDefaultTargetFrame().getFeatureGroupsOfState(visible));
2680 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfStateOn(jalview.appletgui
2681 * .AlignFrame, boolean)
2684 public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
2686 return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
2692 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupStateOn(jalview.appletgui.
2693 * AlignFrame, java.lang.String, boolean)
2696 public void setFeatureGroupStateOn(final AlignFrame alf,
2697 final String groups, boolean state)
2699 final boolean st = state;// !(state==null || state.equals("") ||
2700 // state.toLowerCase(Locale.ROOT).equals("false"));
2701 java.awt.EventQueue.invokeLater(new Runnable()
2706 alf.setFeatureGroupState(separatorListToArray(groups), st);
2714 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupState(java.lang.String,
2718 public void setFeatureGroupState(String groups, boolean state)
2720 setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
2726 * @see jalview.bin.JalviewLiteJsApi#getSeparator()
2729 public String getSeparator()
2737 * @see jalview.bin.JalviewLiteJsApi#setSeparator(java.lang.String)
2740 public void setSeparator(String separator)
2742 if (separator == null || separator.length() < 1)
2745 separator = "" + ((char) 0x00AC);
2747 this.separator = separator;
2750 System.err.println("Default Separator now: '" + separator + "'");
2755 * get boolean value of applet parameter 'name' and return default if
2756 * parameter is not set
2761 * the value to return otherwise
2762 * @return true or false
2764 public boolean getDefaultParameter(String name, boolean def)
2767 if ((stn = getParameter(name)) == null)
2771 if (TRUE.equalsIgnoreCase(stn))
2781 * @see jalview.bin.JalviewLiteJsApi#addPdbFile(jalview.appletgui.AlignFrame,
2782 * java.lang.String, java.lang.String, java.lang.String)
2785 public boolean addPdbFile(AlignFrame alFrame, String sequenceId,
2786 String pdbEntryString, String pdbFile)
2788 return alFrame.addPdbFile(sequenceId, pdbEntryString, pdbFile);
2791 protected void setAlignPdbStructures(boolean alignPdbStructures)
2793 this.alignPdbStructures = alignPdbStructures;
2796 public boolean isAlignPdbStructures()
2798 return alignPdbStructures;
2804 // callInitCallback();
2807 private Hashtable<String, long[]> jshashes = new Hashtable<>();
2809 private Hashtable<String, Hashtable<String, String[]>> jsmessages = new Hashtable<>();
2811 public void setJsMessageSet(String messageclass, String viewId,
2812 String[] colcommands)
2814 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2817 msgset = new Hashtable<>();
2818 jsmessages.put(messageclass, msgset);
2820 msgset.put(viewId, colcommands);
2821 long[] l = new long[colcommands.length];
2822 for (int i = 0; i < colcommands.length; i++)
2824 l[i] = colcommands[i].hashCode();
2826 jshashes.put(messageclass + "|" + viewId, l);
2832 * @see jalview.bin.JalviewLiteJsApi#getJsMessage(java.lang.String,
2836 public String getJsMessage(String messageclass, String viewId)
2838 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2841 String[] msgs = msgset.get(viewId);
2844 for (int i = 0; i < msgs.length; i++)
2846 if (msgs[i] != null)
2858 public boolean isJsMessageSetChanged(String string, String string2,
2859 String[] colcommands)
2861 long[] l = jshashes.get(string + "|" + string2);
2862 if (l == null && colcommands != null)
2866 for (int i = 0; i < colcommands.length; i++)
2868 if (l[i] != colcommands[i].hashCode())
2876 private Vector jsExecQueue = new Vector();
2878 public Vector getJsExecQueue()
2883 public void setExecutor(JSFunctionExec jsFunctionExec2)
2885 jsFunctionExec = jsFunctionExec2;
2889 * return the given colour value parameter or the given default if parameter
2896 public Color getDefaultColourParameter(String colparam, Color defcolour)
2898 String colprop = getParameter(colparam);
2899 if (colprop == null || colprop.trim().length() == 0)
2903 Color col = ColorUtils.parseColourString(colprop);
2906 System.err.println("Couldn't parse '" + colprop + "' as a colour for "
2909 return (col == null) ? defcolour : col;
2912 public void openJalviewHelpUrl()
2914 String helpUrl = getParameter("jalviewhelpurl");
2915 if (helpUrl == null || helpUrl.trim().length() < 5)
2917 helpUrl = "http://www.jalview.org/help.html";
2919 showURL(helpUrl, "HELP");
2923 * form a complete URL given a path to a resource and a reference location on
2927 * - an absolute path on the same server as localref or a document
2928 * located relative to localref
2930 * - a URL on the same server as url
2931 * @return a complete URL for the resource located by url
2933 private String resolveUrlForLocalOrAbsolute(String targetPath,
2936 String resolvedPath = "";
2937 if (targetPath.startsWith("/"))
2939 String codebase = localref.toString();
2940 String localfile = localref.getFile();
2941 resolvedPath = codebase.substring(0,
2942 codebase.length() - localfile.length()) + targetPath;
2943 return resolvedPath;
2947 * get URL path and strip off any trailing file e.g.
2948 * www.jalview.org/examples/index.html#applets?a=b is trimmed to
2949 * www.jalview.org/examples/
2951 String urlPath = localref.toString();
2952 String directoryPath = urlPath;
2953 int lastSeparator = directoryPath.lastIndexOf("/");
2954 if (lastSeparator > 0)
2956 directoryPath = directoryPath.substring(0, lastSeparator + 1);
2959 if (targetPath.startsWith("/"))
2962 * construct absolute URL to a file on the server - this is not allowed?
2964 // String localfile = localref.getFile();
2965 // resolvedPath = urlPath.substring(0,
2966 // urlPath.length() - localfile.length())
2968 resolvedPath = directoryPath + targetPath.substring(1);
2972 resolvedPath = directoryPath + targetPath;
2977 "resolveUrlForLocalOrAbsolute returning " + resolvedPath);
2979 return resolvedPath;
2983 * open a URL in the browser - resolving it according to relative refs and
2984 * coping with javascript: protocol if necessary.
2989 public void showURL(String url, String target)
2993 if (url.indexOf(":") == -1)
2995 // TODO: verify (Bas Vroling bug) prepend codebase or server URL to
2997 // Should really use docbase, not codebase.
2999 url = resolveUrlForLocalOrAbsolute(url,
3000 prepend = getDefaultParameter("resolvetocodebase", false)
3002 : getDocumentBase());
3005 System.err.println("Show url (prepended " + prepend
3006 + " - toggle resolvetocodebase if code/docbase resolution is wrong): "
3014 System.err.println("Show url: " + url);
3017 if (url.indexOf("javascript:") == 0)
3019 // no target for the javascript context
3020 getAppletContext().showDocument(new java.net.URL(url));
3024 getAppletContext().showDocument(new java.net.URL(url), target);
3026 } catch (Exception ex)
3028 ex.printStackTrace();
3033 * bind structures in a viewer to any matching sequences in an alignFrame (use
3034 * sequenceIds to limit scope of search to specific sequences)
3038 * @param sequenceIds
3039 * @return TODO: consider making an exception structure for indicating when
3040 * binding fails public SequenceStructureBinding
3041 * addStructureViewInstance( AlignFrame alFrame, Object viewer, String
3044 * if (sequenceIds != null && sequenceIds.length() > 0) { return
3045 * alFrame.addStructureViewInstance(viewer,
3046 * separatorListToArray(sequenceIds)); } else { return
3047 * alFrame.addStructureViewInstance(viewer, null); } // return null; }