2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentUtils;
24 import jalview.api.StructureSelectionManagerProvider;
25 import jalview.appletgui.AlignFrame;
26 import jalview.appletgui.AlignViewport;
27 import jalview.appletgui.EmbmenuFrame;
28 import jalview.appletgui.FeatureSettings;
29 import jalview.appletgui.SplitFrame;
30 import jalview.datamodel.Alignment;
31 import jalview.datamodel.AlignmentI;
32 import jalview.datamodel.AlignmentOrder;
33 import jalview.datamodel.ColumnSelection;
34 import jalview.datamodel.PDBEntry;
35 import jalview.datamodel.Sequence;
36 import jalview.datamodel.SequenceGroup;
37 import jalview.datamodel.SequenceI;
38 import jalview.io.AnnotationFile;
39 import jalview.io.AppletFormatAdapter;
40 import jalview.io.DataSourceType;
41 import jalview.io.FileFormatI;
42 import jalview.io.FileFormats;
43 import jalview.io.FileParse;
44 import jalview.io.IdentifyFile;
45 import jalview.io.JPredFile;
46 import jalview.io.JnetAnnotationMaker;
47 import jalview.io.NewickFile;
48 import jalview.javascript.JSFunctionExec;
49 import jalview.javascript.JalviewLiteJsApi;
50 import jalview.javascript.JsCallBack;
51 import jalview.javascript.MouseOverStructureListener;
52 import jalview.structure.SelectionListener;
53 import jalview.structure.StructureSelectionManager;
54 import jalview.util.ColorUtils;
55 import jalview.util.HttpUtils;
56 import jalview.util.MessageManager;
58 import java.applet.Applet;
59 import java.awt.Button;
60 import java.awt.Color;
61 import java.awt.Component;
62 import java.awt.EventQueue;
64 import java.awt.Frame;
65 import java.awt.Graphics;
66 import java.awt.event.ActionEvent;
67 import java.awt.event.WindowAdapter;
68 import java.awt.event.WindowEvent;
69 import java.io.BufferedReader;
70 import java.io.IOException;
71 import java.io.InputStreamReader;
73 import java.util.ArrayList;
74 import java.util.Hashtable;
75 import java.util.List;
76 import java.util.StringTokenizer;
77 import java.util.Vector;
79 import netscape.javascript.JSObject;
82 * Jalview Applet. Runs in Java 1.18 runtime
85 * @version $Revision: 1.92 $
87 public class JalviewLite extends Applet
88 implements StructureSelectionManagerProvider, JalviewLiteJsApi
91 private static final String TRUE = "true";
93 private static final String FALSE = "false";
95 public StructureSelectionManager getStructureSelectionManager()
97 return StructureSelectionManager.getStructureSelectionManager(this);
100 // /////////////////////////////////////////
101 // The following public methods may be called
102 // externally, eg via javascript in HTML page
106 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences()
109 public String getSelectedSequences()
111 return getSelectedSequencesFrom(getDefaultTargetFrame());
117 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences(java.lang.String)
120 public String getSelectedSequences(String sep)
122 return getSelectedSequencesFrom(getDefaultTargetFrame(), sep);
129 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
133 public String getSelectedSequencesFrom(AlignFrame alf)
135 return getSelectedSequencesFrom(alf, separator); // ""+0x00AC);
142 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
143 * .AlignFrame, java.lang.String)
146 public String getSelectedSequencesFrom(AlignFrame alf, String sep)
148 StringBuffer result = new StringBuffer("");
149 if (sep == null || sep.length() == 0)
151 sep = separator; // "+0x00AC;
153 if (alf.viewport.getSelectionGroup() != null)
155 SequenceI[] seqs = alf.viewport.getSelectionGroup()
156 .getSequencesInOrder(alf.viewport.getAlignment());
158 for (int i = 0; i < seqs.length; i++)
160 result.append(seqs[i].getName());
165 return result.toString();
171 * @see jalview.bin.JalviewLiteJsApi#highlight(java.lang.String,
172 * java.lang.String, java.lang.String)
175 public void highlight(String sequenceId, String position,
176 String alignedPosition)
178 highlightIn(getDefaultTargetFrame(), sequenceId, position,
185 * @see jalview.bin.JalviewLiteJsApi#highlightIn(jalview.appletgui.AlignFrame,
186 * java.lang.String, java.lang.String, java.lang.String)
189 public void highlightIn(final AlignFrame alf, final String sequenceId,
190 final String position, final String alignedPosition)
192 // TODO: could try to highlight in all alignments if alf==null
193 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
194 alf.viewport.getAlignment().getSequencesArray());
195 final SequenceI sq = matcher.findIdMatch(sequenceId);
201 apos = new Integer(position).intValue();
203 } catch (NumberFormatException ex)
207 final StructureSelectionManagerProvider me = this;
208 final int pos = apos;
209 // use vamsas listener to broadcast to all listeners in scope
210 if (alignedPosition != null && (alignedPosition.trim().length() == 0
211 || alignedPosition.toLowerCase().indexOf("false") > -1))
213 java.awt.EventQueue.invokeLater(new Runnable()
218 StructureSelectionManager.getStructureSelectionManager(me)
219 .mouseOverVamsasSequence(sq, sq.findIndex(pos), null);
225 java.awt.EventQueue.invokeLater(new Runnable()
230 StructureSelectionManager.getStructureSelectionManager(me)
231 .mouseOverVamsasSequence(sq, pos, null);
241 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
245 public void select(String sequenceIds, String columns)
247 selectIn(getDefaultTargetFrame(), sequenceIds, columns, separator);
253 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
254 * java.lang.String, java.lang.String)
257 public void select(String sequenceIds, String columns, String sep)
259 selectIn(getDefaultTargetFrame(), sequenceIds, columns, sep);
265 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
266 * java.lang.String, java.lang.String)
269 public void selectIn(AlignFrame alf, String sequenceIds, String columns)
271 selectIn(alf, sequenceIds, columns, separator);
277 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
278 * java.lang.String, java.lang.String, java.lang.String)
281 public void selectIn(final AlignFrame alf, String sequenceIds,
282 String columns, String sep)
284 if (sep == null || sep.length() == 0)
292 System.err.println("Selecting region using separator string '"
297 String[] ids = separatorListToArray(sequenceIds, sep);
298 String[] cols = separatorListToArray(columns, sep);
299 final SequenceGroup sel = new SequenceGroup();
300 final ColumnSelection csel = new ColumnSelection();
301 AlignmentI al = alf.viewport.getAlignment();
302 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
303 alf.viewport.getAlignment().getSequencesArray());
304 int start = 0, end = al.getWidth(), alw = al.getWidth();
305 boolean seqsfound = true;
306 if (ids != null && ids.length > 0)
309 for (int i = 0; i < ids.length; i++)
311 if (ids[i].trim().length() == 0)
315 SequenceI sq = matcher.findIdMatch(ids[i]);
319 sel.addSequence(sq, false);
323 boolean inseqpos = false;
324 if (cols != null && cols.length > 0)
326 boolean seset = false;
327 for (int i = 0; i < cols.length; i++)
329 String cl = cols[i].trim();
330 if (cl.length() == 0)
335 if ((p = cl.indexOf("-")) > -1)
337 int from = -1, to = -1;
340 from = new Integer(cl.substring(0, p)).intValue();
342 } catch (NumberFormatException ex)
345 "ERROR: Couldn't parse first integer in range element column selection string '"
346 + cl + "' - format is 'from-to'");
351 to = new Integer(cl.substring(p + 1)).intValue();
353 } catch (NumberFormatException ex)
356 "ERROR: Couldn't parse second integer in range element column selection string '"
357 + cl + "' - format is 'from-to'");
360 if (from >= 0 && to >= 0)
377 // comment to prevent range extension
387 for (int r = from; r <= to; r++)
389 if (r >= 0 && r < alw)
396 System.err.println("Range '" + cl + "' deparsed as [" + from
402 System.err.println("ERROR: Invalid Range '" + cl
403 + "' deparsed as [" + from + "," + to + "]");
411 r = new Integer(cl).intValue();
413 } catch (NumberFormatException ex)
415 if (cl.toLowerCase().equals("sequence"))
417 // we are in the dataset sequence's coordinate frame.
423 "ERROR: Couldn't parse integer from point selection element of column selection string '"
428 if (r >= 0 && r <= alw)
438 // comment to prevent range extension
451 System.err.println("Point selection '" + cl
452 + "' deparsed as [" + r + "]");
457 System.err.println("ERROR: Invalid Point selection '" + cl
458 + "' deparsed as [" + r + "]");
465 // we only propagate the selection when it was the null selection, or the
466 // given sequences were found in the alignment.
467 if (inseqpos && sel.getSize() > 0)
469 // assume first sequence provides reference frame ?
470 SequenceI rs = sel.getSequenceAt(0);
471 start = rs.findIndex(start);
472 end = rs.findIndex(end);
473 List<Integer> cs = new ArrayList<>(csel.getSelected());
475 for (Integer selectedCol : cs)
477 csel.addElement(rs.findIndex(selectedCol));
480 sel.setStartRes(start);
482 EventQueue.invokeLater(new Runnable()
487 alf.select(sel, csel,
488 alf.getAlignViewport().getAlignment().getHiddenColumns());
498 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignment(java.lang.
499 * String, java.lang.String)
502 public String getSelectedSequencesAsAlignment(String format,
505 return getSelectedSequencesAsAlignmentFrom(getDefaultTargetFrame(),
513 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignmentFrom(jalview
514 * .appletgui.AlignFrame, java.lang.String, java.lang.String)
517 public String getSelectedSequencesAsAlignmentFrom(AlignFrame alf,
518 String format, String suffix)
522 FileFormatI theFormat = FileFormats.getInstance().forName(format);
523 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
524 if (alf.viewport.getSelectionGroup() != null)
526 // JBPNote: getSelectionAsNewSequence behaviour has changed - this
527 // method now returns a full copy of sequence data
528 // TODO consider using getSequenceSelection instead here
529 String reply = new AppletFormatAdapter().formatSequences(theFormat,
530 new Alignment(alf.viewport.getSelectionAsNewSequence()),
534 } catch (IllegalArgumentException ex)
536 ex.printStackTrace();
537 return "Error retrieving alignment, possibly invalid format specifier: "
546 * @see jalview.bin.JalviewLiteJsApi#getAlignmentOrder()
549 public String getAlignmentOrder()
551 return getAlignmentOrderFrom(getDefaultTargetFrame());
558 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
562 public String getAlignmentOrderFrom(AlignFrame alf)
564 return getAlignmentOrderFrom(alf, separator);
571 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
572 * , java.lang.String)
575 public String getAlignmentOrderFrom(AlignFrame alf, String sep)
577 AlignmentI alorder = alf.getAlignViewport().getAlignment();
578 String[] order = new String[alorder.getHeight()];
579 for (int i = 0; i < order.length; i++)
581 order[i] = alorder.getSequenceAt(i).getName();
583 return arrayToSeparatorList(order);
589 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
593 public String orderBy(String order, String undoName)
595 return orderBy(order, undoName, separator);
601 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
602 * java.lang.String, java.lang.String)
605 public String orderBy(String order, String undoName, String sep)
607 return orderAlignmentBy(getDefaultTargetFrame(), order, undoName, sep);
614 * jalview.bin.JalviewLiteJsApi#orderAlignmentBy(jalview.appletgui.AlignFrame,
615 * java.lang.String, java.lang.String, java.lang.String)
618 public String orderAlignmentBy(AlignFrame alf, String order,
619 String undoName, String sep)
621 String[] ids = separatorListToArray(order, sep);
622 SequenceI[] sqs = null;
623 if (ids != null && ids.length > 0)
625 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
626 alf.viewport.getAlignment().getSequencesArray());
628 sqs = new SequenceI[ids.length];
629 for (int i = 0; i < ids.length; i++)
631 if (ids[i].trim().length() == 0)
635 SequenceI sq = matcher.findIdMatch(ids[i]);
643 SequenceI[] sqq = new SequenceI[s];
644 System.arraycopy(sqs, 0, sqq, 0, s);
657 final AlignmentOrder aorder = new AlignmentOrder(sqs);
659 if (undoName != null && undoName.trim().length() == 0)
663 final String _undoName = undoName;
664 // TODO: deal with synchronization here: cannot raise any events until after
665 // this has returned.
666 return alf.sortBy(aorder, _undoName) ? TRUE : "";
672 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String)
675 public String getAlignment(String format)
677 return getAlignmentFrom(getDefaultTargetFrame(), format, TRUE);
684 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
688 public String getAlignmentFrom(AlignFrame alf, String format)
690 return getAlignmentFrom(alf, format, TRUE);
696 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String,
700 public String getAlignment(String format, String suffix)
702 return getAlignmentFrom(getDefaultTargetFrame(), format, suffix);
709 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
710 * java.lang.String, java.lang.String)
713 public String getAlignmentFrom(AlignFrame alf, String format,
718 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
720 FileFormatI theFormat = FileFormats.getInstance().forName(format);
721 String reply = new AppletFormatAdapter().formatSequences(theFormat,
722 alf.viewport.getAlignment(), seqlimits);
724 } catch (IllegalArgumentException ex)
726 ex.printStackTrace();
727 return "Error retrieving alignment, possibly invalid format specifier: "
735 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
738 public void loadAnnotation(String annotation)
740 loadAnnotationFrom(getDefaultTargetFrame(), annotation);
747 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
748 * , java.lang.String)
751 public void loadAnnotationFrom(AlignFrame alf, String annotation)
753 if (new AnnotationFile().annotateAlignmentView(alf.getAlignViewport(),
754 annotation, DataSourceType.PASTE))
756 alf.alignPanel.fontChanged();
757 alf.alignPanel.setScrollValues(0, 0);
761 alf.parseFeaturesFile(annotation, DataSourceType.PASTE);
768 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
771 public void loadFeatures(String features, boolean autoenabledisplay)
773 loadFeaturesFrom(getDefaultTargetFrame(), features, autoenabledisplay);
780 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
781 * , java.lang.String)
784 public boolean loadFeaturesFrom(AlignFrame alf, String features,
785 boolean autoenabledisplay)
787 return alf.parseFeaturesFile(features, DataSourceType.PASTE,
794 * @see jalview.bin.JalviewLiteJsApi#getFeatures(java.lang.String)
797 public String getFeatures(String format)
799 return getFeaturesFrom(getDefaultTargetFrame(), format);
806 * jalview.bin.JalviewLiteJsApi#getFeaturesFrom(jalview.appletgui.AlignFrame,
810 public String getFeaturesFrom(AlignFrame alf, String format)
812 return alf.outputFeatures(false, format);
818 * @see jalview.bin.JalviewLiteJsApi#getAnnotation()
821 public String getAnnotation()
823 return getAnnotationFrom(getDefaultTargetFrame());
830 * jalview.bin.JalviewLiteJsApi#getAnnotationFrom(jalview.appletgui.AlignFrame
834 public String getAnnotationFrom(AlignFrame alf)
836 return alf.outputAnnotations(false);
842 * @see jalview.bin.JalviewLiteJsApi#newView()
845 public AlignFrame newView()
847 return newViewFrom(getDefaultTargetFrame());
853 * @see jalview.bin.JalviewLiteJsApi#newView(java.lang.String)
856 public AlignFrame newView(String name)
858 return newViewFrom(getDefaultTargetFrame(), name);
864 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame)
867 public AlignFrame newViewFrom(AlignFrame alf)
869 return alf.newView(null);
875 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame,
879 public AlignFrame newViewFrom(AlignFrame alf, String name)
881 return alf.newView(name);
887 * @see jalview.bin.JalviewLiteJsApi#loadAlignment(java.lang.String,
891 public AlignFrame loadAlignment(String text, String title)
893 AlignmentI al = null;
897 FileFormatI format = new IdentifyFile().identify(text,
898 DataSourceType.PASTE);
899 al = new AppletFormatAdapter().readFile(text, DataSourceType.PASTE,
901 if (al.getHeight() > 0)
903 return new AlignFrame(al, this, title, false);
905 } catch (IOException ex)
907 ex.printStackTrace();
915 * @see jalview.bin.JalviewLiteJsApi#setMouseoverListener(java.lang.String)
918 public void setMouseoverListener(String listener)
920 setMouseoverListener(currentAlignFrame, listener);
923 private Vector<jalview.javascript.JSFunctionExec> javascriptListeners = new Vector<>();
929 * jalview.bin.JalviewLiteJsApi#setMouseoverListener(jalview.appletgui.AlignFrame
930 * , java.lang.String)
933 public void setMouseoverListener(AlignFrame af, String listener)
935 if (listener != null)
937 listener = listener.trim();
938 if (listener.length() == 0)
941 "jalview Javascript error: Ignoring empty function for mouseover listener.");
945 jalview.javascript.MouseOverListener mol = new jalview.javascript.MouseOverListener(
947 javascriptListeners.addElement(mol);
948 StructureSelectionManager.getStructureSelectionManager(this)
949 .addStructureViewerListener(mol);
952 System.err.println("Added a mouseover listener for "
953 + ((af == null) ? "All frames"
955 + af.getAlignViewport().getSequenceSetId()));
956 System.err.println("There are now " + javascriptListeners.size()
957 + " listeners in total.");
964 * @see jalview.bin.JalviewLiteJsApi#setSelectionListener(java.lang.String)
967 public void setSelectionListener(String listener)
969 setSelectionListener(null, listener);
976 * jalview.bin.JalviewLiteJsApi#setSelectionListener(jalview.appletgui.AlignFrame
977 * , java.lang.String)
980 public void setSelectionListener(AlignFrame af, String listener)
982 if (listener != null)
984 listener = listener.trim();
985 if (listener.length() == 0)
988 "jalview Javascript error: Ignoring empty function for selection listener.");
992 jalview.javascript.JsSelectionSender mol = new jalview.javascript.JsSelectionSender(
994 javascriptListeners.addElement(mol);
995 StructureSelectionManager.getStructureSelectionManager(this)
996 .addSelectionListener(mol);
999 System.err.println("Added a selection listener for "
1000 + ((af == null) ? "All frames"
1002 + af.getAlignViewport().getSequenceSetId()));
1003 System.err.println("There are now " + javascriptListeners.size()
1004 + " listeners in total.");
1009 * Callable from javascript to register a javascript function to pass events
1010 * to a structure viewer.
1013 * the name of a javascript function
1015 * a token separated list of PDB file names listened for
1016 * @see jalview.bin.JalviewLiteJsApi#setStructureListener(java.lang.String,
1020 public void setStructureListener(String listener, String modelSet)
1022 if (listener != null)
1024 listener = listener.trim();
1025 if (listener.length() == 0)
1028 "jalview Javascript error: Ignoring empty function for selection listener.");
1032 MouseOverStructureListener mol = new MouseOverStructureListener(this,
1033 listener, separatorListToArray(modelSet));
1034 javascriptListeners.addElement(mol);
1035 StructureSelectionManager.getStructureSelectionManager(this)
1036 .addStructureViewerListener(mol);
1039 System.err.println("Added a javascript structure viewer listener '"
1041 System.err.println("There are now " + javascriptListeners.size()
1042 + " listeners in total.");
1050 * jalview.bin.JalviewLiteJsApi#removeJavascriptListener(jalview.appletgui
1051 * .AlignFrame, java.lang.String)
1054 public void removeJavascriptListener(AlignFrame af, String listener)
1056 if (listener != null)
1058 listener = listener.trim();
1059 if (listener.length() == 0)
1064 boolean rprt = false;
1065 for (int ms = 0, msSize = javascriptListeners.size(); ms < msSize;)
1067 Object lstn = javascriptListeners.elementAt(ms);
1068 JsCallBack lstner = (JsCallBack) lstn;
1069 if ((af == null || lstner.getAlignFrame() == af) && (listener == null
1070 || lstner.getListenerFunction().equals(listener)))
1072 javascriptListeners.removeElement(lstner);
1074 if (lstner instanceof SelectionListener)
1076 StructureSelectionManager.getStructureSelectionManager(this)
1077 .removeSelectionListener((SelectionListener) lstner);
1081 StructureSelectionManager.getStructureSelectionManager(this)
1082 .removeStructureViewerListener(lstner, null);
1087 System.err.println("Removed listener '" + listener + "'");
1097 System.err.println("There are now " + javascriptListeners.size()
1098 + " listeners in total.");
1105 System.err.println("Applet " + getName() + " stop().");
1110 public void destroy()
1112 System.err.println("Applet " + getName() + " destroy().");
1116 private void tidyUp()
1119 if (currentAlignFrame != null && currentAlignFrame.viewport != null
1120 && currentAlignFrame.viewport.applet != null)
1122 AlignViewport av = currentAlignFrame.viewport;
1123 currentAlignFrame.closeMenuItem_actionPerformed();
1125 currentAlignFrame = null;
1127 if (javascriptListeners != null)
1129 while (javascriptListeners.size() > 0)
1131 jalview.javascript.JSFunctionExec mol = javascriptListeners
1133 javascriptListeners.removeElement(mol);
1134 if (mol instanceof SelectionListener)
1136 StructureSelectionManager.getStructureSelectionManager(this)
1137 .removeSelectionListener((SelectionListener) mol);
1141 StructureSelectionManager.getStructureSelectionManager(this)
1142 .removeStructureViewerListener(mol, null);
1147 if (jsFunctionExec != null)
1149 jsFunctionExec.stopQueue();
1150 jsFunctionExec.jvlite = null;
1152 initialAlignFrame = null;
1153 jsFunctionExec = null;
1154 javascriptListeners = null;
1155 StructureSelectionManager.release(this);
1158 private jalview.javascript.JSFunctionExec jsFunctionExec;
1163 * @see jalview.bin.JalviewLiteJsApi#mouseOverStructure(java.lang.String,
1164 * java.lang.String, java.lang.String)
1167 public void mouseOverStructure(final String pdbResNum, final String chain,
1168 final String pdbfile)
1170 final StructureSelectionManagerProvider me = this;
1171 java.awt.EventQueue.invokeLater(new Runnable()
1178 StructureSelectionManager.getStructureSelectionManager(me)
1179 .mouseOverStructure(new Integer(pdbResNum).intValue(),
1184 .println("mouseOver for '" + pdbResNum + "' in chain '"
1185 + chain + "' in structure '" + pdbfile + "'");
1187 } catch (NumberFormatException e)
1189 System.err.println("Ignoring invalid residue number string '"
1201 * jalview.bin.JalviewLiteJsApi#scrollViewToIn(jalview.appletgui.AlignFrame,
1202 * java.lang.String, java.lang.String)
1205 public void scrollViewToIn(final AlignFrame alf, final String topRow,
1206 final String leftHandColumn)
1208 java.awt.EventQueue.invokeLater(new Runnable()
1215 alf.scrollTo(new Integer(topRow).intValue(),
1216 new Integer(leftHandColumn).intValue());
1218 } catch (Exception ex)
1220 System.err.println("Couldn't parse integer arguments (topRow='"
1221 + topRow + "' and leftHandColumn='" + leftHandColumn
1223 ex.printStackTrace();
1233 * jalview.javascript.JalviewLiteJsApi#scrollViewToRowIn(jalview.appletgui
1234 * .AlignFrame, java.lang.String)
1237 public void scrollViewToRowIn(final AlignFrame alf, final String topRow)
1240 java.awt.EventQueue.invokeLater(new Runnable()
1247 alf.scrollToRow(new Integer(topRow).intValue());
1249 } catch (Exception ex)
1251 System.err.println("Couldn't parse integer arguments (topRow='"
1253 ex.printStackTrace();
1264 * jalview.javascript.JalviewLiteJsApi#scrollViewToColumnIn(jalview.appletgui
1265 * .AlignFrame, java.lang.String)
1268 public void scrollViewToColumnIn(final AlignFrame alf,
1269 final String leftHandColumn)
1271 java.awt.EventQueue.invokeLater(new Runnable()
1279 alf.scrollToColumn(new Integer(leftHandColumn).intValue());
1281 } catch (Exception ex)
1284 "Couldn't parse integer arguments (leftHandColumn='"
1285 + leftHandColumn + "')");
1286 ex.printStackTrace();
1293 // //////////////////////////////////////////////
1294 // //////////////////////////////////////////////
1296 public static int lastFrameX = 200;
1298 public static int lastFrameY = 200;
1300 boolean fileFound = true;
1302 String file = "No file";
1304 String file2 = null;
1306 Button launcher = new Button(
1307 MessageManager.getString("label.start_jalview"));
1310 * The currentAlignFrame is static, it will change if and when the user
1311 * selects a new window. Note that it will *never* point back to the embedded
1312 * AlignFrame if the applet is started as embedded on the page and then
1313 * afterwards a new view is created.
1315 public AlignFrame currentAlignFrame = null;
1318 * This is the first frame to be displayed, and does not change. API calls
1319 * will default to this instance if currentAlignFrame is null.
1321 AlignFrame initialAlignFrame = null;
1323 boolean embedded = false;
1325 private boolean checkForJmol = true;
1327 private boolean checkedForJmol = false; // ensure we don't check for jmol
1329 // every time the app is re-inited
1331 public boolean jmolAvailable = false;
1333 private boolean alignPdbStructures = false;
1336 * use an external structure viewer exclusively (no jmols or MCViews will be
1337 * opened by JalviewLite itself)
1339 public boolean useXtrnalSviewer = false;
1341 public static boolean debug = false;
1343 static String builddate = null, version = null, installation = null;
1345 private static void initBuildDetails()
1347 if (builddate == null)
1349 builddate = "unknown";
1351 installation = "applet";
1352 java.net.URL url = JalviewLite.class
1353 .getResource("/.build_properties");
1358 BufferedReader reader = new BufferedReader(
1359 new InputStreamReader(url.openStream()));
1361 while ((line = reader.readLine()) != null)
1363 if (line.indexOf("VERSION") > -1)
1365 version = line.substring(line.indexOf("=") + 1);
1367 if (line.indexOf("BUILD_DATE") > -1)
1369 builddate = line.substring(line.indexOf("=") + 1);
1371 if (line.indexOf("INSTALLATION") > -1)
1373 installation = line.substring(line.indexOf("=") + 1);
1376 } catch (Exception ex)
1378 ex.printStackTrace();
1384 public static String getBuildDate()
1390 public static String getInstallation()
1393 return installation;
1396 public static String getVersion()
1402 // public JSObject scriptObject = null;
1405 * init method for Jalview Applet
1410 debug = TRUE.equalsIgnoreCase(getParameter("debug"));
1415 System.err.println("Applet context is '"
1416 + getAppletContext().getClass().toString() + "'");
1418 JSObject scriptObject = JSObject.getWindow(this);
1419 if (debug && scriptObject != null)
1421 System.err.println("Applet has Javascript callback support.");
1424 } catch (Exception ex)
1427 "Warning: No JalviewLite javascript callbacks available.");
1430 ex.printStackTrace();
1436 System.err.println("JalviewLite Version " + getVersion());
1437 System.err.println("Build Date : " + getBuildDate());
1438 System.err.println("Installation : " + getInstallation());
1440 String externalsviewer = getParameter("externalstructureviewer");
1441 if (externalsviewer != null)
1443 useXtrnalSviewer = externalsviewer.trim().toLowerCase().equals(TRUE);
1446 * if true disable the check for jmol
1448 String chkforJmol = getParameter("nojmol");
1449 if (chkforJmol != null)
1451 checkForJmol = !chkforJmol.equals(TRUE);
1454 * get the separator parameter if present
1456 String sep = getParameter("separator");
1459 if (sep.length() > 0)
1464 System.err.println("Separator set to '" + separator + "'");
1469 throw new Error(MessageManager
1470 .getString("error.invalid_separator_parameter"));
1476 String param = getParameter("RGB");
1482 r = Integer.parseInt(param.substring(0, 2), 16);
1483 g = Integer.parseInt(param.substring(2, 4), 16);
1484 b = Integer.parseInt(param.substring(4, 6), 16);
1485 } catch (Exception ex)
1492 param = getParameter("label");
1495 launcher.setLabel(param);
1498 setBackground(new Color(r, g, b));
1500 file = getParameter("file");
1504 // Maybe the sequences are added as parameters
1505 StringBuffer data = new StringBuffer("PASTE");
1507 while ((file = getParameter("sequence" + i)) != null)
1509 data.append(file.toString() + "\n");
1512 if (data.length() > 5)
1514 file = data.toString();
1517 if (getDefaultParameter("enableSplitFrame", true))
1519 file2 = getParameter("file2");
1522 embedded = TRUE.equalsIgnoreCase(getParameter("embedded"));
1525 LoadingThread loader = new LoadingThread(file, file2, this);
1528 else if (file != null)
1531 * Start the applet immediately or show a button to start it
1533 if (FALSE.equalsIgnoreCase(getParameter("showbutton")))
1535 LoadingThread loader = new LoadingThread(file, file2, this);
1541 launcher.addActionListener(new java.awt.event.ActionListener()
1544 public void actionPerformed(ActionEvent e)
1546 LoadingThread loader = new LoadingThread(file, file2,
1555 // jalview initialisation with no alignment. loadAlignment() method can
1556 // still be called to open new alignments.
1563 private void initLiveConnect()
1565 // try really hard to get the liveConnect thing working
1566 boolean notFailed = false;
1568 while (!notFailed && tries < 10)
1572 System.err.println("LiveConnect request thread going to sleep.");
1576 Thread.sleep(700 * (1 + tries));
1577 } catch (InterruptedException q)
1583 System.err.println("LiveConnect request thread woken up.");
1587 JSObject scriptObject = JSObject.getWindow(this);
1588 if (scriptObject.eval("navigator") != null)
1592 } catch (Exception jsex)
1594 System.err.println("Attempt " + tries
1595 + " to access LiveConnect javascript failed.");
1600 private void callInitCallback()
1602 String initjscallback = getParameter("oninit");
1603 if (initjscallback == null)
1607 initjscallback = initjscallback.trim();
1608 if (initjscallback.length() > 0)
1610 JSObject scriptObject = null;
1613 scriptObject = JSObject.getWindow(this);
1614 } catch (Exception ex)
1618 // try really hard to let the browser plugin know we want liveconnect
1621 if (scriptObject != null)
1625 // do onInit with the JS executor thread
1626 new JSFunctionExec(this).executeJavascriptFunction(true,
1627 initjscallback, null,
1628 "Calling oninit callback '" + initjscallback + "'.");
1629 } catch (Exception e)
1631 System.err.println("Exception when executing _oninit callback '"
1632 + initjscallback + "'.");
1633 e.printStackTrace();
1638 System.err.println("Not executing _oninit callback '"
1639 + initjscallback + "' - no scripting allowed.");
1645 * Initialises and displays a new java.awt.Frame
1648 * java.awt.Frame to be displayed
1650 * title of new frame
1652 * width if new frame
1654 * height of new frame
1656 public static void addFrame(final Frame frame, String title, int width,
1659 frame.setLocation(lastFrameX, lastFrameY);
1662 frame.setSize(width, height);
1663 frame.setTitle(title);
1664 frame.addWindowListener(new WindowAdapter()
1667 public void windowClosing(WindowEvent e)
1669 if (frame instanceof AlignFrame)
1671 AlignViewport vp = ((AlignFrame) frame).viewport;
1672 ((AlignFrame) frame).closeMenuItem_actionPerformed();
1673 if (vp.applet.currentAlignFrame == frame)
1675 vp.applet.currentAlignFrame = null;
1683 if (frame instanceof EmbmenuFrame)
1685 ((EmbmenuFrame) frame).destroyMenus();
1687 frame.setMenuBar(null);
1692 public void windowActivated(WindowEvent e)
1694 if (frame instanceof AlignFrame)
1696 ((AlignFrame) frame).viewport.applet.currentAlignFrame = (AlignFrame) frame;
1699 System.err.println("Activated window " + frame);
1703 super.windowActivated(e);
1706 * Probably not necessary to do this - see TODO above. (non-Javadoc)
1709 * java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent
1712 * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
1713 * frame) { currentAlignFrame = null; if (debug) {
1714 * System.err.println("Deactivated window "+frame); } }
1715 * super.windowDeactivated(e); }
1718 frame.setVisible(true);
1722 * This paints the background surrounding the "Launch Jalview button" <br>
1724 * If file given in parameter not found, displays error message
1730 public void paint(Graphics g)
1734 g.setColor(new Color(200, 200, 200));
1735 g.setColor(Color.cyan);
1736 g.fillRect(0, 0, getSize().width, getSize().height);
1737 g.setColor(Color.red);
1739 MessageManager.getString("label.jalview_cannot_open_file"), 5,
1741 g.drawString("\"" + file + "\"", 5, 30);
1745 g.setColor(Color.black);
1746 g.setFont(new Font("Arial", Font.BOLD, 24));
1747 g.drawString(MessageManager.getString("label.jalview_applet"), 50,
1748 getSize().height / 2 - 30);
1749 g.drawString(MessageManager.getString("label.loading_data") + "...",
1750 50, getSize().height / 2);
1755 * get all components associated with the applet of the given type
1760 public Vector getAppletWindow(Class class1)
1762 Vector wnds = new Vector();
1763 Component[] cmp = getComponents();
1766 for (int i = 0; i < cmp.length; i++)
1768 if (class1.isAssignableFrom(cmp[i].getClass()))
1770 wnds.addElement(cmp);
1777 class LoadJmolThread extends Thread
1779 private boolean running = false;
1784 if (running || checkedForJmol)
1793 if (!System.getProperty("java.version").startsWith("1.1"))
1795 Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
1796 jmolAvailable = true;
1801 "Jmol not available - Using MCview for structures");
1803 } catch (java.lang.ClassNotFoundException ex)
1809 jmolAvailable = false;
1813 "Skipping Jmol check. Will use MCView (probably)");
1816 checkedForJmol = true;
1820 public boolean notFinished()
1822 return running || !checkedForJmol;
1826 class LoadingThread extends Thread
1829 * State variable: protocol for access to file source
1831 DataSourceType protocol;
1833 String _file; // alignment file or URL spec
1835 String _file2; // second alignment file or URL spec
1839 private void dbgMsg(String msg)
1841 if (JalviewLite.debug)
1843 System.err.println(msg);
1848 * update the protocol state variable for accessing the datasource located
1852 * @return possibly updated datasource string
1854 public String resolveFileProtocol(String path)
1859 if (path.startsWith("PASTE"))
1861 protocol = DataSourceType.PASTE;
1862 return path.substring(5);
1868 if (path.indexOf("://") != -1)
1870 protocol = DataSourceType.URL;
1875 * try relative to document root
1877 URL documentBase = getDocumentBase();
1878 String withDocBase = resolveUrlForLocalOrAbsolute(path, documentBase);
1879 if (HttpUtils.isValidUrl(withDocBase))
1883 System.err.println("Prepended document base '" + documentBase
1884 + "' to make: '" + withDocBase + "'");
1886 protocol = DataSourceType.URL;
1891 * try relative to codebase (if different to document base)
1893 URL codeBase = getCodeBase();
1894 String withCodeBase = applet.resolveUrlForLocalOrAbsolute(path,
1896 if (!withCodeBase.equals(withDocBase)
1897 && HttpUtils.isValidUrl(withCodeBase))
1899 protocol = DataSourceType.URL;
1902 System.err.println("Prepended codebase '" + codeBase
1903 + "' to make: '" + withCodeBase + "'");
1905 return withCodeBase;
1909 * try locating by classloader; try this last so files in the directory
1910 * are resolved using document base
1912 if (inArchive(path))
1914 protocol = DataSourceType.CLASSLOADER;
1919 public LoadingThread(String file, String file2, JalviewLite _applet)
1922 this._file2 = file2;
1929 LoadJmolThread jmolchecker = new LoadJmolThread();
1930 jmolchecker.start();
1931 while (jmolchecker.notFinished())
1933 // wait around until the Jmol check is complete.
1937 } catch (Exception e)
1942 // applet.callInitCallback();
1946 * Load the alignment and any related files as specified by applet
1949 private void startLoading()
1951 dbgMsg("Loading thread started with:\n>>file\n" + _file
1954 dbgMsg("Loading started.");
1956 AlignFrame newAlignFrame = readAlignment(_file);
1957 AlignFrame newAlignFrame2 = readAlignment(_file2);
1958 if (newAlignFrame != null)
1960 addToDisplay(newAlignFrame, newAlignFrame2);
1961 loadTree(newAlignFrame);
1963 loadScoreFile(newAlignFrame);
1965 loadFeatures(newAlignFrame);
1967 loadAnnotations(newAlignFrame);
1969 loadJnetFile(newAlignFrame);
1971 loadPdbFiles(newAlignFrame);
1976 applet.remove(launcher);
1983 * Add an AlignFrame to the display; or if two are provided, a SplitFrame.
1988 public void addToDisplay(AlignFrame af, AlignFrame af2)
1992 AlignmentI al1 = af.viewport.getAlignment();
1993 AlignmentI al2 = af2.viewport.getAlignment();
1994 AlignmentI cdna = al1.isNucleotide() ? al1 : al2;
1995 AlignmentI prot = al1.isNucleotide() ? al2 : al1;
1996 if (AlignmentUtils.mapProteinAlignmentToCdna(prot, cdna))
1999 SplitFrame sf = new SplitFrame(af, af2);
2000 sf.addToDisplay(embedded, JalviewLite.this);
2005 String msg = "Could not map any sequence in " + af2.getTitle()
2007 + (al1.isNucleotide() ? "protein product" : "cDNA")
2008 + " for " + af.getTitle();
2009 System.err.println(msg);
2013 af.addToDisplay(embedded);
2017 * Read the alignment file (from URL, text 'paste', or archive by
2022 protected AlignFrame readAlignment(String fileParam)
2024 if (fileParam == null)
2028 String resolvedFile = resolveFileProtocol(fileParam);
2029 AlignmentI al = null;
2032 FileFormatI format = new IdentifyFile().identify(resolvedFile,
2034 dbgMsg("File identified as '" + format + "'");
2035 al = new AppletFormatAdapter().readFile(resolvedFile, protocol,
2037 if ((al != null) && (al.getHeight() > 0))
2039 dbgMsg("Successfully loaded file.");
2040 al.setDataset(null);
2041 AlignFrame newAlignFrame = new AlignFrame(al, applet,
2042 resolvedFile, embedded, false);
2043 newAlignFrame.setTitle(resolvedFile);
2044 if (initialAlignFrame == null)
2046 initialAlignFrame = newAlignFrame;
2048 // update the focus.
2049 currentAlignFrame = newAlignFrame;
2051 if (protocol == DataSourceType.PASTE)
2053 newAlignFrame.setTitle(MessageManager
2054 .formatMessage("label.sequences_from", new Object[]
2055 { applet.getDocumentBase().toString() }));
2058 newAlignFrame.statusBar.setText(MessageManager.formatMessage(
2059 "label.successfully_loaded_file", new Object[]
2062 return newAlignFrame;
2064 } catch (java.io.IOException ex)
2066 dbgMsg("File load exception.");
2067 ex.printStackTrace();
2072 FileParse fp = new FileParse(resolvedFile, protocol);
2074 dbgMsg(">>>Dumping contents of '" + resolvedFile + "' " + "("
2076 while ((ln = fp.nextLine()) != null)
2080 dbgMsg(">>>Dump finished.");
2081 } catch (Exception e)
2084 "Exception when trying to dump the content of the file parameter.");
2085 e.printStackTrace();
2093 * Load PDBFiles if any specified by parameter(s). Returns true if loaded,
2099 protected boolean loadPdbFiles(AlignFrame alignFrame)
2101 boolean result = false;
2103 * <param name="alignpdbfiles" value="false/true"/> Undocumented for 2.6 -
2104 * related to JAL-434
2107 applet.setAlignPdbStructures(
2108 getDefaultParameter("alignpdbfiles", false));
2110 * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
2113 * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
2115 * <param name="PDBfile3" value="1q0o Q45135_9MICO">
2118 int pdbFileCount = 0;
2119 // Accumulate pdbs here if they are heading for the same view (if
2120 // alignPdbStructures is true)
2121 Vector pdbs = new Vector();
2122 // create a lazy matcher if we're asked to
2123 jalview.analysis.SequenceIdMatcher matcher = (applet
2124 .getDefaultParameter("relaxedidmatch", false))
2125 ? new jalview.analysis.SequenceIdMatcher(
2126 alignFrame.getAlignViewport().getAlignment()
2127 .getSequencesArray())
2133 if (pdbFileCount > 0)
2135 param = applet.getParameter("PDBFILE" + pdbFileCount);
2139 param = applet.getParameter("PDBFILE");
2144 PDBEntry pdb = new PDBEntry();
2147 SequenceI[] seqs = null;
2148 String[] chains = null;
2150 StringTokenizer st = new StringTokenizer(param, " ");
2152 if (st.countTokens() < 2)
2154 String sequence = applet.getParameter("PDBSEQ");
2155 if (sequence != null)
2157 seqs = new SequenceI[] { matcher == null
2158 ? (Sequence) alignFrame.getAlignViewport()
2159 .getAlignment().findName(sequence)
2160 : matcher.findIdMatch(sequence) };
2166 param = st.nextToken();
2167 List<SequenceI> tmp = new ArrayList<>();
2168 List<String> tmp2 = new ArrayList<>();
2170 while (st.hasMoreTokens())
2172 seqstring = st.nextToken();
2173 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
2174 if (st2.countTokens() > 1)
2176 // This is the chain
2177 tmp2.add(st2.nextToken());
2178 seqstring = st2.nextToken();
2180 tmp.add(matcher == null
2181 ? (Sequence) alignFrame.getAlignViewport()
2182 .getAlignment().findName(seqstring)
2183 : matcher.findIdMatch(seqstring));
2186 seqs = tmp.toArray(new SequenceI[tmp.size()]);
2187 if (tmp2.size() == tmp.size())
2189 chains = tmp2.toArray(new String[tmp2.size()]);
2192 param = resolveFileProtocol(param);
2193 // TODO check JAL-357 for files in a jar (CLASSLOADER)
2198 for (int i = 0; i < seqs.length; i++)
2200 if (seqs[i] != null)
2202 ((Sequence) seqs[i]).addPDBId(pdb);
2203 StructureSelectionManager
2204 .getStructureSelectionManager(applet)
2205 .registerPDBEntry(pdb);
2209 if (JalviewLite.debug)
2211 // this may not really be a problem but we give a warning
2214 "Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
2220 if (!alignPdbStructures)
2222 alignFrame.newStructureView(applet, pdb, seqs, chains,
2227 pdbs.addElement(new Object[] { pdb, seqs, chains, protocol });
2233 } while (param != null || pdbFileCount < 10);
2234 if (pdbs.size() > 0)
2236 SequenceI[][] seqs = new SequenceI[pdbs.size()][];
2237 PDBEntry[] pdb = new PDBEntry[pdbs.size()];
2238 String[][] chains = new String[pdbs.size()][];
2239 String[] protocols = new String[pdbs.size()];
2240 for (int pdbsi = 0, pdbsiSize = pdbs
2241 .size(); pdbsi < pdbsiSize; pdbsi++)
2243 Object[] o = (Object[]) pdbs.elementAt(pdbsi);
2244 pdb[pdbsi] = (PDBEntry) o[0];
2245 seqs[pdbsi] = (SequenceI[]) o[1];
2246 chains[pdbsi] = (String[]) o[2];
2247 protocols[pdbsi] = (String) o[3];
2249 alignFrame.alignedStructureView(applet, pdb, seqs, chains,
2257 * Load in a Jnetfile if specified by parameter. Returns true if loaded,
2263 protected boolean loadJnetFile(AlignFrame alignFrame)
2265 boolean result = false;
2266 String param = applet.getParameter("jnetfile");
2269 // jnet became jpred around 2016
2270 param = applet.getParameter("jpredfile");
2276 param = resolveFileProtocol(param);
2277 JPredFile predictions = new JPredFile(param, protocol);
2278 JnetAnnotationMaker.add_annotation(predictions,
2279 alignFrame.viewport.getAlignment(), 0, false);
2280 // false == do not add sequence profile from concise output
2282 alignFrame.viewport.getAlignment().setupJPredAlignment();
2284 alignFrame.alignPanel.fontChanged();
2285 alignFrame.alignPanel.setScrollValues(0, 0);
2287 } catch (Exception ex)
2289 ex.printStackTrace();
2296 * Load annotations if specified by parameter. Returns true if loaded, else
2302 protected boolean loadAnnotations(AlignFrame alignFrame)
2304 boolean result = false;
2305 String param = applet.getParameter("annotations");
2308 param = resolveFileProtocol(param);
2310 if (new AnnotationFile().annotateAlignmentView(alignFrame.viewport,
2313 alignFrame.alignPanel.fontChanged();
2314 alignFrame.alignPanel.setScrollValues(0, 0);
2320 "Annotations were not added from annotation file '"
2328 * Load features file and view settings as specified by parameters. Returns
2329 * true if features were loaded, else false.
2334 protected boolean loadFeatures(AlignFrame alignFrame)
2336 boolean result = false;
2337 // ///////////////////////////
2338 // modify display of features
2339 // we do this before any features have been loaded, ensuring any hidden
2340 // groups are hidden when features first displayed
2342 // hide specific groups
2344 String param = applet.getParameter("hidefeaturegroups");
2347 alignFrame.setFeatureGroupState(separatorListToArray(param), false);
2348 // applet.setFeatureGroupStateOn(newAlignFrame, param, false);
2350 // show specific groups
2351 param = applet.getParameter("showfeaturegroups");
2354 alignFrame.setFeatureGroupState(separatorListToArray(param), true);
2355 // applet.setFeatureGroupStateOn(newAlignFrame, param, true);
2357 // and now load features
2358 param = applet.getParameter("features");
2361 param = resolveFileProtocol(param);
2363 result = alignFrame.parseFeaturesFile(param, protocol);
2366 param = applet.getParameter("showFeatureSettings");
2367 if (param != null && param.equalsIgnoreCase(TRUE))
2369 alignFrame.viewport.setShowSequenceFeatures(true);
2370 new FeatureSettings(alignFrame.alignPanel);
2376 * Load a score file if specified by parameter. Returns true if file was
2377 * loaded, else false.
2381 protected boolean loadScoreFile(AlignFrame alignFrame)
2383 boolean result = false;
2384 String sScoreFile = applet.getParameter("scoreFile");
2385 if (sScoreFile != null && !"".equals(sScoreFile))
2392 "Attempting to load T-COFFEE score file from the scoreFile parameter");
2394 result = alignFrame.loadScoreFile(sScoreFile);
2398 "Failed to parse T-COFFEE parameter as a valid score file ('"
2399 + sScoreFile + "')");
2401 } catch (Exception e)
2403 System.err.printf("Cannot read score file: '%s'. Cause: %s \n",
2404 sScoreFile, e.getMessage());
2411 * Load a tree for the alignment if specified by parameter. Returns true if
2412 * a tree was loaded, else false.
2417 protected boolean loadTree(AlignFrame alignFrame)
2419 boolean result = false;
2420 String treeFile = applet.getParameter("tree");
2421 if (treeFile == null)
2423 treeFile = applet.getParameter("treeFile");
2426 if (treeFile != null)
2430 treeFile = resolveFileProtocol(treeFile);
2431 NewickFile fin = new NewickFile(treeFile, protocol);
2434 if (fin.getTree() != null)
2436 alignFrame.loadTree(fin, treeFile);
2438 dbgMsg("Successfully imported tree.");
2442 dbgMsg("Tree parameter did not resolve to a valid tree.");
2444 } catch (Exception ex)
2446 ex.printStackTrace();
2453 * Discovers whether the given file is in the Applet Archive
2459 boolean inArchive(String f)
2461 // This might throw a security exception in certain browsers
2462 // Netscape Communicator for instance.
2465 boolean rtn = (getClass().getResourceAsStream("/" + f) != null);
2468 System.err.println("Resource '" + f + "' was "
2469 + (rtn ? "" : "not ") + "located by classloader.");
2472 } catch (Exception ex)
2474 System.out.println("Exception checking resources: " + f + " " + ex);
2481 * @return the default alignFrame acted on by the public applet methods. May
2482 * return null with an error message on System.err indicating the
2485 public AlignFrame getDefaultTargetFrame()
2487 if (currentAlignFrame != null)
2489 return currentAlignFrame;
2491 if (initialAlignFrame != null)
2493 return initialAlignFrame;
2496 "Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
2501 * separator used for separatorList
2503 protected String separator = "" + ((char) 0x00AC); // the default used to be
2504 // '|' but many sequence
2505 // IDS include pipes.
2508 * set to enable the URL based javascript execution mechanism
2510 public boolean jsfallbackEnabled = false;
2513 * parse the string into a list
2516 * @return elements separated by separator
2518 public String[] separatorListToArray(String list)
2520 return separatorListToArray(list, separator);
2524 * parse the string into a list
2528 * @return elements separated by separator
2530 public static String[] separatorListToArray(String list, String separator)
2532 // TODO use StringUtils version (slightly different...)
2533 int seplen = separator.length();
2534 if (list == null || list.equals("") || list.equals(separator))
2538 java.util.Vector jv = new Vector();
2540 while ((pos = list.indexOf(separator, cp)) > cp)
2542 jv.addElement(list.substring(cp, pos));
2545 if (cp < list.length())
2547 String c = list.substring(cp);
2548 if (!c.equals(separator))
2555 String[] v = new String[jv.size()];
2556 for (int i = 0; i < v.length; i++)
2558 v[i] = (String) jv.elementAt(i);
2560 jv.removeAllElements();
2563 System.err.println("Array from '" + separator
2564 + "' separated List:\n" + v.length);
2565 for (int i = 0; i < v.length; i++)
2567 System.err.println("item " + i + " '" + v[i] + "'");
2575 "Empty Array from '" + separator + "' separated List");
2581 * concatenate the list with separator
2584 * @return concatenated string
2586 public String arrayToSeparatorList(String[] list)
2588 return arrayToSeparatorList(list, separator);
2592 * concatenate the list with separator
2596 * @return concatenated string
2598 public static String arrayToSeparatorList(String[] list, String separator)
2600 // TODO use StringUtils version
2601 StringBuffer v = new StringBuffer();
2602 if (list != null && list.length > 0)
2604 for (int i = 0, iSize = list.length; i < iSize; i++)
2606 if (list[i] != null)
2610 v.append(separator);
2618 .println("Returning '" + separator + "' separated List:\n");
2619 System.err.println(v);
2621 return v.toString();
2626 "Returning empty '" + separator + "' separated List\n");
2628 return "" + separator;
2634 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroups()
2637 public String getFeatureGroups()
2639 String lst = arrayToSeparatorList(
2640 getDefaultTargetFrame().getFeatureGroups());
2648 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOn(jalview.appletgui.AlignFrame
2652 public String getFeatureGroupsOn(AlignFrame alf)
2654 String lst = arrayToSeparatorList(alf.getFeatureGroups());
2661 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfState(boolean)
2664 public String getFeatureGroupsOfState(boolean visible)
2666 return arrayToSeparatorList(
2667 getDefaultTargetFrame().getFeatureGroupsOfState(visible));
2674 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfStateOn(jalview.appletgui
2675 * .AlignFrame, boolean)
2678 public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
2680 return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
2686 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupStateOn(jalview.appletgui.
2687 * AlignFrame, java.lang.String, boolean)
2690 public void setFeatureGroupStateOn(final AlignFrame alf,
2691 final String groups, boolean state)
2693 final boolean st = state;// !(state==null || state.equals("") ||
2694 // state.toLowerCase().equals("false"));
2695 java.awt.EventQueue.invokeLater(new Runnable()
2700 alf.setFeatureGroupState(separatorListToArray(groups), st);
2708 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupState(java.lang.String,
2712 public void setFeatureGroupState(String groups, boolean state)
2714 setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
2720 * @see jalview.bin.JalviewLiteJsApi#getSeparator()
2723 public String getSeparator()
2731 * @see jalview.bin.JalviewLiteJsApi#setSeparator(java.lang.String)
2734 public void setSeparator(String separator)
2736 if (separator == null || separator.length() < 1)
2739 separator = "" + ((char) 0x00AC);
2741 this.separator = separator;
2744 System.err.println("Default Separator now: '" + separator + "'");
2749 * get boolean value of applet parameter 'name' and return default if
2750 * parameter is not set
2755 * the value to return otherwise
2756 * @return true or false
2758 public boolean getDefaultParameter(String name, boolean def)
2761 if ((stn = getParameter(name)) == null)
2765 if (TRUE.equalsIgnoreCase(stn))
2775 * @see jalview.bin.JalviewLiteJsApi#addPdbFile(jalview.appletgui.AlignFrame,
2776 * java.lang.String, java.lang.String, java.lang.String)
2779 public boolean addPdbFile(AlignFrame alFrame, String sequenceId,
2780 String pdbEntryString, String pdbFile)
2782 return alFrame.addPdbFile(sequenceId, pdbEntryString, pdbFile);
2785 protected void setAlignPdbStructures(boolean alignPdbStructures)
2787 this.alignPdbStructures = alignPdbStructures;
2790 public boolean isAlignPdbStructures()
2792 return alignPdbStructures;
2798 // callInitCallback();
2801 private Hashtable<String, long[]> jshashes = new Hashtable<>();
2803 private Hashtable<String, Hashtable<String, String[]>> jsmessages = new Hashtable<>();
2805 public void setJsMessageSet(String messageclass, String viewId,
2806 String[] colcommands)
2808 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2811 msgset = new Hashtable<>();
2812 jsmessages.put(messageclass, msgset);
2814 msgset.put(viewId, colcommands);
2815 long[] l = new long[colcommands.length];
2816 for (int i = 0; i < colcommands.length; i++)
2818 l[i] = colcommands[i].hashCode();
2820 jshashes.put(messageclass + "|" + viewId, l);
2826 * @see jalview.bin.JalviewLiteJsApi#getJsMessage(java.lang.String,
2830 public String getJsMessage(String messageclass, String viewId)
2832 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2835 String[] msgs = msgset.get(viewId);
2838 for (int i = 0; i < msgs.length; i++)
2840 if (msgs[i] != null)
2852 public boolean isJsMessageSetChanged(String string, String string2,
2853 String[] colcommands)
2855 long[] l = jshashes.get(string + "|" + string2);
2856 if (l == null && colcommands != null)
2860 for (int i = 0; i < colcommands.length; i++)
2862 if (l[i] != colcommands[i].hashCode())
2870 private Vector jsExecQueue = new Vector();
2872 public Vector getJsExecQueue()
2877 public void setExecutor(JSFunctionExec jsFunctionExec2)
2879 jsFunctionExec = jsFunctionExec2;
2883 * return the given colour value parameter or the given default if parameter
2890 public Color getDefaultColourParameter(String colparam, Color defcolour)
2892 String colprop = getParameter(colparam);
2893 if (colprop == null || colprop.trim().length() == 0)
2897 Color col = ColorUtils.parseColourString(colprop);
2900 System.err.println("Couldn't parse '" + colprop + "' as a colour for "
2903 return (col == null) ? defcolour : col;
2906 public void openJalviewHelpUrl()
2908 String helpUrl = getParameter("jalviewhelpurl");
2909 if (helpUrl == null || helpUrl.trim().length() < 5)
2911 helpUrl = "http://www.jalview.org/help.html";
2913 showURL(helpUrl, "HELP");
2917 * form a complete URL given a path to a resource and a reference location on
2921 * - an absolute path on the same server as localref or a document
2922 * located relative to localref
2924 * - a URL on the same server as url
2925 * @return a complete URL for the resource located by url
2927 private String resolveUrlForLocalOrAbsolute(String targetPath,
2930 String resolvedPath = "";
2931 if (targetPath.startsWith("/"))
2933 String codebase = localref.toString();
2934 String localfile = localref.getFile();
2935 resolvedPath = codebase.substring(0,
2936 codebase.length() - localfile.length()) + targetPath;
2937 return resolvedPath;
2941 * get URL path and strip off any trailing file e.g.
2942 * www.jalview.org/examples/index.html#applets?a=b is trimmed to
2943 * www.jalview.org/examples/
2945 String urlPath = localref.toString();
2946 String directoryPath = urlPath;
2947 int lastSeparator = directoryPath.lastIndexOf("/");
2948 if (lastSeparator > 0)
2950 directoryPath = directoryPath.substring(0, lastSeparator + 1);
2953 if (targetPath.startsWith("/"))
2956 * construct absolute URL to a file on the server - this is not allowed?
2958 // String localfile = localref.getFile();
2959 // resolvedPath = urlPath.substring(0,
2960 // urlPath.length() - localfile.length())
2962 resolvedPath = directoryPath + targetPath.substring(1);
2966 resolvedPath = directoryPath + targetPath;
2971 "resolveUrlForLocalOrAbsolute returning " + resolvedPath);
2973 return resolvedPath;
2977 * open a URL in the browser - resolving it according to relative refs and
2978 * coping with javascript: protocol if necessary.
2983 public void showURL(String url, String target)
2987 if (url.indexOf(":") == -1)
2989 // TODO: verify (Bas Vroling bug) prepend codebase or server URL to
2991 // Should really use docbase, not codebase.
2993 url = resolveUrlForLocalOrAbsolute(url,
2994 prepend = getDefaultParameter("resolvetocodebase", false)
2996 : getDocumentBase());
2999 System.err.println("Show url (prepended " + prepend
3000 + " - toggle resolvetocodebase if code/docbase resolution is wrong): "
3008 System.err.println("Show url: " + url);
3011 if (url.indexOf("javascript:") == 0)
3013 // no target for the javascript context
3014 getAppletContext().showDocument(new java.net.URL(url));
3018 getAppletContext().showDocument(new java.net.URL(url), target);
3020 } catch (Exception ex)
3022 ex.printStackTrace();
3027 * bind structures in a viewer to any matching sequences in an alignFrame (use
3028 * sequenceIds to limit scope of search to specific sequences)
3032 * @param sequenceIds
3033 * @return TODO: consider making an exception structure for indicating when
3034 * binding fails public SequenceStructureBinding
3035 * addStructureViewInstance( AlignFrame alFrame, Object viewer, String
3038 * if (sequenceIds != null && sequenceIds.length() > 0) { return
3039 * alFrame.addStructureViewInstance(viewer,
3040 * separatorListToArray(sequenceIds)); } else { return
3041 * alFrame.addStructureViewInstance(viewer, null); } // return null; }