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 && (alignedPosition.trim().length() == 0
215 || alignedPosition.toLowerCase(Locale.ROOT).indexOf("false") > -1))
217 java.awt.EventQueue.invokeLater(new Runnable()
222 StructureSelectionManager.getStructureSelectionManager(me)
223 .mouseOverVamsasSequence(sq, sq.findIndex(pos), null);
229 java.awt.EventQueue.invokeLater(new Runnable()
234 StructureSelectionManager.getStructureSelectionManager(me)
235 .mouseOverVamsasSequence(sq, pos, null);
245 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
249 public void select(String sequenceIds, String columns)
251 selectIn(getDefaultTargetFrame(), sequenceIds, columns, separator);
257 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
258 * java.lang.String, java.lang.String)
261 public void select(String sequenceIds, String columns, String sep)
263 selectIn(getDefaultTargetFrame(), sequenceIds, columns, sep);
269 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
270 * java.lang.String, java.lang.String)
273 public void selectIn(AlignFrame alf, String sequenceIds, String columns)
275 selectIn(alf, sequenceIds, columns, separator);
281 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
282 * java.lang.String, java.lang.String, java.lang.String)
285 public void selectIn(final AlignFrame alf, String sequenceIds,
286 String columns, String sep)
288 if (sep == null || sep.length() == 0)
296 System.err.println("Selecting region using separator string '"
301 String[] ids = separatorListToArray(sequenceIds, sep);
302 String[] cols = separatorListToArray(columns, sep);
303 final SequenceGroup sel = new SequenceGroup();
304 final ColumnSelection csel = new ColumnSelection();
305 AlignmentI al = alf.viewport.getAlignment();
306 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
307 alf.viewport.getAlignment().getSequencesArray());
308 int start = 0, end = al.getWidth(), alw = al.getWidth();
309 boolean seqsfound = true;
310 if (ids != null && ids.length > 0)
313 for (int i = 0; i < ids.length; i++)
315 if (ids[i].trim().length() == 0)
319 SequenceI sq = matcher.findIdMatch(ids[i]);
323 sel.addSequence(sq, false);
327 boolean inseqpos = false;
328 if (cols != null && cols.length > 0)
330 boolean seset = false;
331 for (int i = 0; i < cols.length; i++)
333 String cl = cols[i].trim();
334 if (cl.length() == 0)
339 if ((p = cl.indexOf("-")) > -1)
341 int from = -1, to = -1;
344 from = Integer.valueOf(cl.substring(0, p)).intValue();
346 } catch (NumberFormatException ex)
349 "ERROR: Couldn't parse first integer in range element column selection string '"
350 + cl + "' - format is 'from-to'");
355 to = Integer.valueOf(cl.substring(p + 1)).intValue();
357 } catch (NumberFormatException ex)
360 "ERROR: Couldn't parse second integer in range element column selection string '"
361 + cl + "' - format is 'from-to'");
364 if (from >= 0 && to >= 0)
381 // comment to prevent range extension
391 for (int r = from; r <= to; r++)
393 if (r >= 0 && r < alw)
400 System.err.println("Range '" + cl + "' deparsed as [" + from
406 System.err.println("ERROR: Invalid Range '" + cl
407 + "' deparsed as [" + from + "," + to + "]");
415 r = Integer.valueOf(cl).intValue();
417 } catch (NumberFormatException ex)
419 if (cl.toLowerCase(Locale.ROOT).equals("sequence"))
421 // we are in the dataset sequence's coordinate frame.
427 "ERROR: Couldn't parse integer from point selection element of column selection string '"
432 if (r >= 0 && r <= alw)
442 // comment to prevent range extension
455 System.err.println("Point selection '" + cl
456 + "' deparsed as [" + r + "]");
461 System.err.println("ERROR: Invalid Point selection '" + cl
462 + "' deparsed as [" + r + "]");
469 // we only propagate the selection when it was the null selection, or the
470 // given sequences were found in the alignment.
471 if (inseqpos && sel.getSize() > 0)
473 // assume first sequence provides reference frame ?
474 SequenceI rs = sel.getSequenceAt(0);
475 start = rs.findIndex(start);
476 end = rs.findIndex(end);
477 List<Integer> cs = new ArrayList<>(csel.getSelected());
479 for (Integer selectedCol : cs)
481 csel.addElement(rs.findIndex(selectedCol));
484 sel.setStartRes(start);
486 EventQueue.invokeLater(new Runnable()
491 alf.select(sel, csel,
492 alf.getAlignViewport().getAlignment().getHiddenColumns());
502 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignment(java.lang.
503 * String, java.lang.String)
506 public String getSelectedSequencesAsAlignment(String format,
509 return getSelectedSequencesAsAlignmentFrom(getDefaultTargetFrame(),
517 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignmentFrom(jalview
518 * .appletgui.AlignFrame, java.lang.String, java.lang.String)
521 public String getSelectedSequencesAsAlignmentFrom(AlignFrame alf,
522 String format, String suffix)
526 FileFormatI theFormat = FileFormats.getInstance().forName(format);
527 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
528 if (alf.viewport.getSelectionGroup() != null)
530 // JBPNote: getSelectionAsNewSequence behaviour has changed - this
531 // method now returns a full copy of sequence data
532 // TODO consider using getSequenceSelection instead here
533 String reply = new AppletFormatAdapter().formatSequences(theFormat,
534 new Alignment(alf.viewport.getSelectionAsNewSequence()),
538 } catch (IllegalArgumentException ex)
540 ex.printStackTrace();
541 return "Error retrieving alignment, possibly invalid format specifier: "
550 * @see jalview.bin.JalviewLiteJsApi#getAlignmentOrder()
553 public String getAlignmentOrder()
555 return getAlignmentOrderFrom(getDefaultTargetFrame());
562 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
566 public String getAlignmentOrderFrom(AlignFrame alf)
568 return getAlignmentOrderFrom(alf, separator);
575 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
576 * , java.lang.String)
579 public String getAlignmentOrderFrom(AlignFrame alf, String sep)
581 AlignmentI alorder = alf.getAlignViewport().getAlignment();
582 String[] order = new String[alorder.getHeight()];
583 for (int i = 0; i < order.length; i++)
585 order[i] = alorder.getSequenceAt(i).getName();
587 return arrayToSeparatorList(order);
593 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
597 public String orderBy(String order, String undoName)
599 return orderBy(order, undoName, separator);
605 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
606 * java.lang.String, java.lang.String)
609 public String orderBy(String order, String undoName, String sep)
611 return orderAlignmentBy(getDefaultTargetFrame(), order, undoName, sep);
618 * jalview.bin.JalviewLiteJsApi#orderAlignmentBy(jalview.appletgui.AlignFrame,
619 * java.lang.String, java.lang.String, java.lang.String)
622 public String orderAlignmentBy(AlignFrame alf, String order,
623 String undoName, String sep)
625 String[] ids = separatorListToArray(order, sep);
626 SequenceI[] sqs = null;
627 if (ids != null && ids.length > 0)
629 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
630 alf.viewport.getAlignment().getSequencesArray());
632 sqs = new SequenceI[ids.length];
633 for (int i = 0; i < ids.length; i++)
635 if (ids[i].trim().length() == 0)
639 SequenceI sq = matcher.findIdMatch(ids[i]);
647 SequenceI[] sqq = new SequenceI[s];
648 System.arraycopy(sqs, 0, sqq, 0, s);
661 final AlignmentOrder aorder = new AlignmentOrder(sqs);
663 if (undoName != null && undoName.trim().length() == 0)
667 final String _undoName = undoName;
668 // TODO: deal with synchronization here: cannot raise any events until after
669 // this has returned.
670 return alf.sortBy(aorder, _undoName) ? TRUE : "";
676 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String)
679 public String getAlignment(String format)
681 return getAlignmentFrom(getDefaultTargetFrame(), format, TRUE);
688 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
692 public String getAlignmentFrom(AlignFrame alf, String format)
694 return getAlignmentFrom(alf, format, TRUE);
700 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String,
704 public String getAlignment(String format, String suffix)
706 return getAlignmentFrom(getDefaultTargetFrame(), format, suffix);
713 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
714 * java.lang.String, java.lang.String)
717 public String getAlignmentFrom(AlignFrame alf, String format,
722 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
724 FileFormatI theFormat = FileFormats.getInstance().forName(format);
725 String reply = new AppletFormatAdapter().formatSequences(theFormat,
726 alf.viewport.getAlignment(), seqlimits);
728 } catch (IllegalArgumentException ex)
730 ex.printStackTrace();
731 return "Error retrieving alignment, possibly invalid format specifier: "
739 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
742 public void loadAnnotation(String annotation)
744 loadAnnotationFrom(getDefaultTargetFrame(), annotation);
751 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
752 * , java.lang.String)
755 public void loadAnnotationFrom(AlignFrame alf, String annotation)
757 if (new AnnotationFile().annotateAlignmentView(alf.getAlignViewport(),
758 annotation, DataSourceType.PASTE))
760 alf.alignPanel.fontChanged();
761 alf.alignPanel.setScrollValues(0, 0);
765 alf.parseFeaturesFile(annotation, DataSourceType.PASTE);
772 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
775 public void loadFeatures(String features, boolean autoenabledisplay)
777 loadFeaturesFrom(getDefaultTargetFrame(), features, autoenabledisplay);
784 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
785 * , java.lang.String)
788 public boolean loadFeaturesFrom(AlignFrame alf, String features,
789 boolean autoenabledisplay)
791 return alf.parseFeaturesFile(features, DataSourceType.PASTE,
798 * @see jalview.bin.JalviewLiteJsApi#getFeatures(java.lang.String)
801 public String getFeatures(String format)
803 return getFeaturesFrom(getDefaultTargetFrame(), format);
810 * jalview.bin.JalviewLiteJsApi#getFeaturesFrom(jalview.appletgui.AlignFrame,
814 public String getFeaturesFrom(AlignFrame alf, String format)
816 return alf.outputFeatures(false, format);
822 * @see jalview.bin.JalviewLiteJsApi#getAnnotation()
825 public String getAnnotation()
827 return getAnnotationFrom(getDefaultTargetFrame());
834 * jalview.bin.JalviewLiteJsApi#getAnnotationFrom(jalview.appletgui.AlignFrame
838 public String getAnnotationFrom(AlignFrame alf)
840 return alf.outputAnnotations(false);
846 * @see jalview.bin.JalviewLiteJsApi#newView()
849 public AlignFrame newView()
851 return newViewFrom(getDefaultTargetFrame());
857 * @see jalview.bin.JalviewLiteJsApi#newView(java.lang.String)
860 public AlignFrame newView(String name)
862 return newViewFrom(getDefaultTargetFrame(), name);
868 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame)
871 public AlignFrame newViewFrom(AlignFrame alf)
873 return alf.newView(null);
879 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame,
883 public AlignFrame newViewFrom(AlignFrame alf, String name)
885 return alf.newView(name);
891 * @see jalview.bin.JalviewLiteJsApi#loadAlignment(java.lang.String,
895 public AlignFrame loadAlignment(String text, String title)
897 AlignmentI al = null;
901 FileFormatI format = new IdentifyFile().identify(text,
902 DataSourceType.PASTE);
903 al = new AppletFormatAdapter().readFile(text, DataSourceType.PASTE,
905 if (al.getHeight() > 0)
907 return new AlignFrame(al, this, title, false);
909 } catch (IOException ex)
911 ex.printStackTrace();
919 * @see jalview.bin.JalviewLiteJsApi#setMouseoverListener(java.lang.String)
922 public void setMouseoverListener(String listener)
924 setMouseoverListener(currentAlignFrame, listener);
927 private Vector<JSFunctionExec> javascriptListeners = new Vector<>();
933 * jalview.bin.JalviewLiteJsApi#setMouseoverListener(jalview.appletgui.AlignFrame
934 * , java.lang.String)
937 public void setMouseoverListener(AlignFrame af, String listener)
939 if (listener != null)
941 listener = listener.trim();
942 if (listener.length() == 0)
945 "jalview Javascript error: Ignoring empty function for mouseover listener.");
949 MouseOverListener mol = new MouseOverListener(
951 javascriptListeners.addElement(mol);
952 StructureSelectionManager.getStructureSelectionManager(this)
953 .addStructureViewerListener(mol);
956 System.err.println("Added a mouseover listener for "
957 + ((af == null) ? "All frames"
959 + af.getAlignViewport().getSequenceSetId()));
960 System.err.println("There are now " + javascriptListeners.size()
961 + " listeners in total.");
968 * @see jalview.bin.JalviewLiteJsApi#setSelectionListener(java.lang.String)
971 public void setSelectionListener(String listener)
973 setSelectionListener(null, listener);
980 * jalview.bin.JalviewLiteJsApi#setSelectionListener(jalview.appletgui.AlignFrame
981 * , java.lang.String)
984 public void setSelectionListener(AlignFrame af, String listener)
986 if (listener != null)
988 listener = listener.trim();
989 if (listener.length() == 0)
992 "jalview Javascript error: Ignoring empty function for selection listener.");
996 JsSelectionSender mol = new JsSelectionSender(
998 javascriptListeners.addElement(mol);
999 StructureSelectionManager.getStructureSelectionManager(this)
1000 .addSelectionListener(mol);
1003 System.err.println("Added a selection listener for "
1004 + ((af == null) ? "All frames"
1006 + af.getAlignViewport().getSequenceSetId()));
1007 System.err.println("There are now " + javascriptListeners.size()
1008 + " listeners in total.");
1013 * Callable from javascript to register a javascript function to pass events
1014 * to a structure viewer.
1017 * the name of a javascript function
1019 * a token separated list of PDB file names listened for
1020 * @see jalview.bin.JalviewLiteJsApi#setStructureListener(java.lang.String,
1024 public void setStructureListener(String listener, String modelSet)
1026 if (listener != null)
1028 listener = listener.trim();
1029 if (listener.length() == 0)
1032 "jalview Javascript error: Ignoring empty function for selection listener.");
1036 MouseOverStructureListener mol = new MouseOverStructureListener(this,
1037 listener, separatorListToArray(modelSet));
1038 javascriptListeners.addElement(mol);
1039 StructureSelectionManager.getStructureSelectionManager(this)
1040 .addStructureViewerListener(mol);
1043 System.err.println("Added a javascript structure viewer listener '"
1045 System.err.println("There are now " + javascriptListeners.size()
1046 + " listeners in total.");
1054 * jalview.bin.JalviewLiteJsApi#removeJavascriptListener(jalview.appletgui
1055 * .AlignFrame, java.lang.String)
1058 public void removeJavascriptListener(AlignFrame af, String listener)
1060 if (listener != null)
1062 listener = listener.trim();
1063 if (listener.length() == 0)
1068 boolean rprt = false;
1069 for (int ms = 0, msSize = javascriptListeners.size(); ms < msSize;)
1071 Object lstn = javascriptListeners.elementAt(ms);
1072 JsCallBack lstner = (JsCallBack) lstn;
1073 if ((af == null || lstner.getAlignFrame() == af) && (listener == null
1074 || lstner.getListenerFunction().equals(listener)))
1076 javascriptListeners.removeElement(lstner);
1078 if (lstner instanceof SelectionListener)
1080 StructureSelectionManager.getStructureSelectionManager(this)
1081 .removeSelectionListener((SelectionListener) lstner);
1085 StructureSelectionManager.getStructureSelectionManager(this)
1086 .removeStructureViewerListener(lstner, null);
1091 System.err.println("Removed listener '" + listener + "'");
1101 System.err.println("There are now " + javascriptListeners.size()
1102 + " listeners in total.");
1109 System.err.println("Applet " + getName() + " stop().");
1114 public void destroy()
1116 System.err.println("Applet " + getName() + " destroy().");
1120 private void tidyUp()
1123 if (currentAlignFrame != null && currentAlignFrame.viewport != null
1124 && currentAlignFrame.viewport.applet != null)
1126 AlignViewport av = currentAlignFrame.viewport;
1127 currentAlignFrame.closeMenuItem_actionPerformed();
1129 currentAlignFrame = null;
1131 if (javascriptListeners != null)
1133 while (javascriptListeners.size() > 0)
1135 JSFunctionExec mol = javascriptListeners
1137 javascriptListeners.removeElement(mol);
1138 if (mol instanceof SelectionListener)
1140 StructureSelectionManager.getStructureSelectionManager(this)
1141 .removeSelectionListener((SelectionListener) mol);
1145 StructureSelectionManager.getStructureSelectionManager(this)
1146 .removeStructureViewerListener(mol, null);
1151 if (jsFunctionExec != null)
1153 jsFunctionExec.stopQueue();
1154 jsFunctionExec.jvlite = null;
1156 initialAlignFrame = null;
1157 jsFunctionExec = null;
1158 javascriptListeners = null;
1159 StructureSelectionManager.release(this);
1162 private JSFunctionExec jsFunctionExec;
1167 * @see jalview.bin.JalviewLiteJsApi#mouseOverStructure(java.lang.String,
1168 * java.lang.String, java.lang.String)
1171 public void mouseOverStructure(final String pdbResNum, final String chain,
1172 final String pdbfile)
1174 final StructureSelectionManagerProvider me = this;
1175 java.awt.EventQueue.invokeLater(new Runnable()
1182 StructureSelectionManager.getStructureSelectionManager(me)
1183 .mouseOverStructure(Integer.valueOf(pdbResNum).intValue(),
1188 .println("mouseOver for '" + pdbResNum + "' in chain '"
1189 + chain + "' in structure '" + pdbfile + "'");
1191 } catch (NumberFormatException e)
1193 System.err.println("Ignoring invalid residue number string '"
1205 * jalview.bin.JalviewLiteJsApi#scrollViewToIn(jalview.appletgui.AlignFrame,
1206 * java.lang.String, java.lang.String)
1209 public void scrollViewToIn(final AlignFrame alf, final String topRow,
1210 final String leftHandColumn)
1212 java.awt.EventQueue.invokeLater(new Runnable()
1219 alf.scrollTo(Integer.valueOf(topRow).intValue(),
1220 Integer.valueOf(leftHandColumn).intValue());
1222 } catch (Exception ex)
1224 System.err.println("Couldn't parse integer arguments (topRow='"
1225 + topRow + "' and leftHandColumn='" + leftHandColumn
1227 ex.printStackTrace();
1237 * JalviewLiteJsApi#scrollViewToRowIn(jalview.appletgui
1238 * .AlignFrame, java.lang.String)
1241 public void scrollViewToRowIn(final AlignFrame alf, final String topRow)
1244 java.awt.EventQueue.invokeLater(new Runnable()
1251 alf.scrollToRow(Integer.valueOf(topRow).intValue());
1253 } catch (Exception ex)
1255 System.err.println("Couldn't parse integer arguments (topRow='"
1257 ex.printStackTrace();
1268 * JalviewLiteJsApi#scrollViewToColumnIn(jalview.appletgui
1269 * .AlignFrame, java.lang.String)
1272 public void scrollViewToColumnIn(final AlignFrame alf,
1273 final String leftHandColumn)
1275 java.awt.EventQueue.invokeLater(new Runnable()
1283 alf.scrollToColumn(Integer.valueOf(leftHandColumn).intValue());
1285 } catch (Exception ex)
1288 "Couldn't parse integer arguments (leftHandColumn='"
1289 + leftHandColumn + "')");
1290 ex.printStackTrace();
1297 // //////////////////////////////////////////////
1298 // //////////////////////////////////////////////
1300 public static int lastFrameX = 200;
1302 public static int lastFrameY = 200;
1304 boolean fileFound = true;
1306 String file = "No file";
1308 String file2 = null;
1310 Button launcher = new Button(
1311 MessageManager.getString("label.start_jalview"));
1314 * The currentAlignFrame is static, it will change if and when the user
1315 * selects a new window. Note that it will *never* point back to the embedded
1316 * AlignFrame if the applet is started as embedded on the page and then
1317 * afterwards a new view is created.
1319 public AlignFrame currentAlignFrame = null;
1322 * This is the first frame to be displayed, and does not change. API calls
1323 * will default to this instance if currentAlignFrame is null.
1325 AlignFrame initialAlignFrame = null;
1327 boolean embedded = false;
1329 private boolean checkForJmol = true;
1331 private boolean checkedForJmol = false; // ensure we don't check for jmol
1333 // every time the app is re-inited
1335 public boolean jmolAvailable = false;
1337 private boolean alignPdbStructures = false;
1340 * use an external structure viewer exclusively (no jmols or mc_views will be
1341 * opened by JalviewLite itself)
1343 public boolean useXtrnalSviewer = false;
1345 public static boolean debug = false;
1347 static String builddate = null, version = null, installation = null;
1349 private static void initBuildDetails()
1351 if (builddate == null)
1353 builddate = "unknown";
1355 installation = "applet";
1356 java.net.URL url = JalviewLite.class
1357 .getResource("/.build_properties");
1362 BufferedReader reader = new BufferedReader(
1363 new InputStreamReader(url.openStream()));
1365 while ((line = reader.readLine()) != null)
1367 if (line.indexOf("VERSION") > -1)
1369 version = line.substring(line.indexOf("=") + 1);
1371 if (line.indexOf("BUILD_DATE") > -1)
1373 builddate = line.substring(line.indexOf("=") + 1);
1375 if (line.indexOf("INSTALLATION") > -1)
1377 installation = line.substring(line.indexOf("=") + 1);
1380 } catch (Exception ex)
1382 ex.printStackTrace();
1388 public static String getBuildDate()
1394 public static String getInstallation()
1397 return installation;
1400 public static String getVersion()
1406 // public JSObject scriptObject = null;
1409 * init method for Jalview Applet
1414 debug = TRUE.equalsIgnoreCase(getParameter("debug"));
1419 System.err.println("Applet context is '"
1420 + getAppletContext().getClass().toString() + "'");
1422 JSObject scriptObject = JSObject.getWindow(this);
1423 if (debug && scriptObject != null)
1425 System.err.println("Applet has Javascript callback support.");
1428 } catch (Exception ex)
1431 "Warning: No JalviewLite javascript callbacks available.");
1434 ex.printStackTrace();
1440 System.err.println("JalviewLite Version " + getVersion());
1441 System.err.println("Build Date : " + getBuildDate());
1442 System.err.println("Installation : " + getInstallation());
1444 String externalsviewer = getParameter("externalstructureviewer");
1445 if (externalsviewer != null)
1447 useXtrnalSviewer = externalsviewer.trim().toLowerCase(Locale.ROOT).equals(TRUE);
1450 * if true disable the check for jmol
1452 String chkforJmol = getParameter("nojmol");
1453 if (chkforJmol != null)
1455 checkForJmol = !chkforJmol.equals(TRUE);
1458 * get the separator parameter if present
1460 String sep = getParameter("separator");
1463 if (sep.length() > 0)
1468 System.err.println("Separator set to '" + separator + "'");
1473 throw new Error(MessageManager
1474 .getString("error.invalid_separator_parameter"));
1480 String param = getParameter("RGB");
1486 r = Integer.parseInt(param.substring(0, 2), 16);
1487 g = Integer.parseInt(param.substring(2, 4), 16);
1488 b = Integer.parseInt(param.substring(4, 6), 16);
1489 } catch (Exception ex)
1496 param = getParameter("label");
1499 launcher.setLabel(param);
1502 setBackground(new Color(r, g, b));
1504 file = getParameter("file");
1508 // Maybe the sequences are added as parameters
1509 StringBuffer data = new StringBuffer("PASTE");
1511 while ((file = getParameter("sequence" + i)) != null)
1513 data.append(file.toString() + "\n");
1516 if (data.length() > 5)
1518 file = data.toString();
1521 if (getDefaultParameter("enableSplitFrame", true))
1523 file2 = getParameter("file2");
1526 embedded = TRUE.equalsIgnoreCase(getParameter("embedded"));
1529 LoadingThread loader = new LoadingThread(file, file2, this);
1532 else if (file != null)
1535 * Start the applet immediately or show a button to start it
1537 if (FALSE.equalsIgnoreCase(getParameter("showbutton")))
1539 LoadingThread loader = new LoadingThread(file, file2, this);
1545 launcher.addActionListener(new java.awt.event.ActionListener()
1548 public void actionPerformed(ActionEvent e)
1550 LoadingThread loader = new LoadingThread(file, file2,
1559 // jalview initialisation with no alignment. loadAlignment() method can
1560 // still be called to open new alignments.
1567 private void initLiveConnect()
1569 // try really hard to get the liveConnect thing working
1570 boolean notFailed = false;
1572 while (!notFailed && tries < 10)
1576 System.err.println("LiveConnect request thread going to sleep.");
1580 Thread.sleep(700 * (1 + tries));
1581 } catch (InterruptedException q)
1587 System.err.println("LiveConnect request thread woken up.");
1591 JSObject scriptObject = JSObject.getWindow(this);
1592 if (scriptObject.eval("navigator") != null)
1596 } catch (Exception jsex)
1598 System.err.println("Attempt " + tries
1599 + " to access LiveConnect javascript failed.");
1604 private void callInitCallback()
1606 String initjscallback = getParameter("oninit");
1607 if (initjscallback == null)
1611 initjscallback = initjscallback.trim();
1612 if (initjscallback.length() > 0)
1614 JSObject scriptObject = null;
1617 scriptObject = JSObject.getWindow(this);
1618 } catch (Exception ex)
1622 // try really hard to let the browser plugin know we want liveconnect
1625 if (scriptObject != null)
1629 // do onInit with the JS executor thread
1630 new JSFunctionExec(this).executeJavascriptFunction(true,
1631 initjscallback, null,
1632 "Calling oninit callback '" + initjscallback + "'.");
1633 } catch (Exception e)
1635 System.err.println("Exception when executing _oninit callback '"
1636 + initjscallback + "'.");
1637 e.printStackTrace();
1642 System.err.println("Not executing _oninit callback '"
1643 + initjscallback + "' - no scripting allowed.");
1649 * Initialises and displays a new java.awt.Frame
1652 * java.awt.Frame to be displayed
1654 * title of new frame
1656 * width if new frame
1658 * height of new frame
1660 public static void addFrame(final Frame frame, String title, int width,
1663 frame.setLocation(lastFrameX, lastFrameY);
1666 frame.setSize(width, height);
1667 frame.setTitle(title);
1668 frame.addWindowListener(new WindowAdapter()
1671 public void windowClosing(WindowEvent e)
1673 if (frame instanceof AlignFrame)
1675 AlignViewport vp = ((AlignFrame) frame).viewport;
1676 ((AlignFrame) frame).closeMenuItem_actionPerformed();
1677 if (vp.applet.currentAlignFrame == frame)
1679 vp.applet.currentAlignFrame = null;
1687 if (frame instanceof EmbmenuFrame)
1689 ((EmbmenuFrame) frame).destroyMenus();
1691 frame.setMenuBar(null);
1696 public void windowActivated(WindowEvent e)
1698 if (frame instanceof AlignFrame)
1700 ((AlignFrame) frame).viewport.applet.currentAlignFrame = (AlignFrame) frame;
1703 System.err.println("Activated window " + frame);
1707 super.windowActivated(e);
1710 * Probably not necessary to do this - see TODO above. (non-Javadoc)
1713 * java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent
1716 * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
1717 * frame) { currentAlignFrame = null; if (debug) {
1718 * System.err.println("Deactivated window "+frame); } }
1719 * super.windowDeactivated(e); }
1722 frame.setVisible(true);
1726 * This paints the background surrounding the "Launch Jalview button" <br>
1728 * If file given in parameter not found, displays error message
1734 public void paint(Graphics g)
1738 g.setColor(new Color(200, 200, 200));
1739 g.setColor(Color.cyan);
1740 g.fillRect(0, 0, getSize().width, getSize().height);
1741 g.setColor(Color.red);
1743 MessageManager.getString("label.jalview_cannot_open_file"), 5,
1745 g.drawString("\"" + file + "\"", 5, 30);
1749 g.setColor(Color.black);
1750 g.setFont(new Font("Arial", Font.BOLD, 24));
1751 g.drawString(MessageManager.getString("label.jalview_applet"), 50,
1752 getSize().height / 2 - 30);
1753 g.drawString(MessageManager.getString("label.loading_data") + "...",
1754 50, getSize().height / 2);
1759 * get all components associated with the applet of the given type
1764 public Vector getAppletWindow(Class class1)
1766 Vector wnds = new Vector();
1767 Component[] cmp = getComponents();
1770 for (int i = 0; i < cmp.length; i++)
1772 if (class1.isAssignableFrom(cmp[i].getClass()))
1774 wnds.addElement(cmp);
1781 class LoadJmolThread extends Thread
1783 private boolean running = false;
1788 if (running || checkedForJmol)
1797 if (!System.getProperty("java.version").startsWith("1.1"))
1799 Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
1800 jmolAvailable = true;
1805 "Jmol not available - Using mc_view for structures");
1807 } catch (java.lang.ClassNotFoundException ex)
1813 jmolAvailable = false;
1817 "Skipping Jmol check. Will use mc_view (probably)");
1820 checkedForJmol = true;
1824 public boolean notFinished()
1826 return running || !checkedForJmol;
1830 class LoadingThread extends Thread
1833 * State variable: protocol for access to file source
1835 DataSourceType protocol;
1837 String _file; // alignment file or URL spec
1839 String _file2; // second alignment file or URL spec
1843 private void dbgMsg(String msg)
1845 if (JalviewLite.debug)
1847 System.err.println(msg);
1852 * update the protocol state variable for accessing the datasource located
1856 * @return possibly updated datasource string
1858 public String resolveFileProtocol(String path)
1863 if (path.startsWith("PASTE"))
1865 protocol = DataSourceType.PASTE;
1866 return path.substring(5);
1872 if (path.indexOf("://") != -1)
1874 protocol = DataSourceType.URL;
1879 * try relative to document root
1881 URL documentBase = getDocumentBase();
1882 String withDocBase = resolveUrlForLocalOrAbsolute(path, documentBase);
1883 if (HttpUtils.isValidUrl(withDocBase))
1887 System.err.println("Prepended document base '" + documentBase
1888 + "' to make: '" + withDocBase + "'");
1890 protocol = DataSourceType.URL;
1895 * try relative to codebase (if different to document base)
1897 URL codeBase = getCodeBase();
1898 String withCodeBase = applet.resolveUrlForLocalOrAbsolute(path,
1900 if (!withCodeBase.equals(withDocBase)
1901 && HttpUtils.isValidUrl(withCodeBase))
1903 protocol = DataSourceType.URL;
1906 System.err.println("Prepended codebase '" + codeBase
1907 + "' to make: '" + withCodeBase + "'");
1909 return withCodeBase;
1913 * try locating by classloader; try this last so files in the directory
1914 * are resolved using document base
1916 if (inArchive(path))
1918 protocol = DataSourceType.CLASSLOADER;
1923 public LoadingThread(String file, String file2, JalviewLite _applet)
1926 this._file2 = file2;
1933 LoadJmolThread jmolchecker = new LoadJmolThread();
1934 jmolchecker.start();
1935 while (jmolchecker.notFinished())
1937 // wait around until the Jmol check is complete.
1941 } catch (Exception e)
1946 // applet.callInitCallback();
1950 * Load the alignment and any related files as specified by applet
1953 private void startLoading()
1955 dbgMsg("Loading thread started with:\n>>file\n" + _file
1958 dbgMsg("Loading started.");
1960 AlignFrame newAlignFrame = readAlignment(_file);
1961 AlignFrame newAlignFrame2 = readAlignment(_file2);
1962 if (newAlignFrame != null)
1964 addToDisplay(newAlignFrame, newAlignFrame2);
1965 loadTree(newAlignFrame);
1967 loadScoreFile(newAlignFrame);
1969 loadFeatures(newAlignFrame);
1971 loadAnnotations(newAlignFrame);
1973 loadJnetFile(newAlignFrame);
1975 loadPdbFiles(newAlignFrame);
1980 applet.remove(launcher);
1987 * Add an AlignFrame to the display; or if two are provided, a SplitFrame.
1992 public void addToDisplay(AlignFrame af, AlignFrame af2)
1996 AlignmentI al1 = af.viewport.getAlignment();
1997 AlignmentI al2 = af2.viewport.getAlignment();
1998 AlignmentI cdna = al1.isNucleotide() ? al1 : al2;
1999 AlignmentI prot = al1.isNucleotide() ? al2 : al1;
2000 if (AlignmentUtils.mapProteinAlignmentToCdna(prot, cdna))
2003 SplitFrame sf = new SplitFrame(af, af2);
2004 sf.addToDisplay(embedded, JalviewLite.this);
2009 String msg = "Could not map any sequence in " + af2.getTitle()
2011 + (al1.isNucleotide() ? "protein product" : "cDNA")
2012 + " for " + af.getTitle();
2013 System.err.println(msg);
2017 af.addToDisplay(embedded);
2021 * Read the alignment file (from URL, text 'paste', or archive by
2026 protected AlignFrame readAlignment(String fileParam)
2028 if (fileParam == null)
2032 String resolvedFile = resolveFileProtocol(fileParam);
2033 AlignmentI al = null;
2036 FileFormatI format = new IdentifyFile().identify(resolvedFile,
2038 dbgMsg("File identified as '" + format + "'");
2039 al = new AppletFormatAdapter().readFile(resolvedFile, protocol,
2041 if ((al != null) && (al.getHeight() > 0))
2043 dbgMsg("Successfully loaded file.");
2044 al.setDataset(null);
2045 AlignFrame newAlignFrame = new AlignFrame(al, applet,
2046 resolvedFile, embedded, false);
2047 newAlignFrame.setTitle(resolvedFile);
2048 if (initialAlignFrame == null)
2050 initialAlignFrame = newAlignFrame;
2052 // update the focus.
2053 currentAlignFrame = newAlignFrame;
2055 if (protocol == DataSourceType.PASTE)
2057 newAlignFrame.setTitle(MessageManager
2058 .formatMessage("label.sequences_from", new Object[]
2059 { applet.getDocumentBase().toString() }));
2062 newAlignFrame.statusBar.setText(MessageManager.formatMessage(
2063 "label.successfully_loaded_file", new Object[]
2066 return newAlignFrame;
2068 } catch (java.io.IOException ex)
2070 dbgMsg("File load exception.");
2071 ex.printStackTrace();
2076 FileParse fp = new FileParse(resolvedFile, protocol);
2078 dbgMsg(">>>Dumping contents of '" + resolvedFile + "' " + "("
2080 while ((ln = fp.nextLine()) != null)
2084 dbgMsg(">>>Dump finished.");
2085 } catch (Exception e)
2088 "Exception when trying to dump the content of the file parameter.");
2089 e.printStackTrace();
2097 * Load PDBFiles if any specified by parameter(s). Returns true if loaded,
2103 protected boolean loadPdbFiles(AlignFrame alignFrame)
2105 boolean result = false;
2107 * <param name="alignpdbfiles" value="false/true"/> Undocumented for 2.6 -
2108 * related to JAL-434
2111 applet.setAlignPdbStructures(
2112 getDefaultParameter("alignpdbfiles", false));
2114 * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
2117 * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
2119 * <param name="PDBfile3" value="1q0o Q45135_9MICO">
2122 int pdbFileCount = 0;
2123 // Accumulate pdbs here if they are heading for the same view (if
2124 // alignPdbStructures is true)
2125 Vector pdbs = new Vector();
2126 // create a lazy matcher if we're asked to
2127 jalview.analysis.SequenceIdMatcher matcher = (applet
2128 .getDefaultParameter("relaxedidmatch", false))
2129 ? new jalview.analysis.SequenceIdMatcher(
2130 alignFrame.getAlignViewport().getAlignment()
2131 .getSequencesArray())
2137 if (pdbFileCount > 0)
2139 param = applet.getParameter("PDBFILE" + pdbFileCount);
2143 param = applet.getParameter("PDBFILE");
2148 PDBEntry pdb = new PDBEntry();
2151 SequenceI[] seqs = null;
2152 String[] chains = null;
2154 StringTokenizer st = new StringTokenizer(param, " ");
2156 if (st.countTokens() < 2)
2158 String sequence = applet.getParameter("PDBSEQ");
2159 if (sequence != null)
2161 seqs = new SequenceI[] { matcher == null
2162 ? (Sequence) alignFrame.getAlignViewport()
2163 .getAlignment().findName(sequence)
2164 : matcher.findIdMatch(sequence) };
2170 param = st.nextToken();
2171 List<SequenceI> tmp = new ArrayList<>();
2172 List<String> tmp2 = new ArrayList<>();
2174 while (st.hasMoreTokens())
2176 seqstring = st.nextToken();
2177 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
2178 if (st2.countTokens() > 1)
2180 // This is the chain
2181 tmp2.add(st2.nextToken());
2182 seqstring = st2.nextToken();
2184 tmp.add(matcher == null
2185 ? (Sequence) alignFrame.getAlignViewport()
2186 .getAlignment().findName(seqstring)
2187 : matcher.findIdMatch(seqstring));
2190 seqs = tmp.toArray(new SequenceI[tmp.size()]);
2191 if (tmp2.size() == tmp.size())
2193 chains = tmp2.toArray(new String[tmp2.size()]);
2196 param = resolveFileProtocol(param);
2197 // TODO check JAL-357 for files in a jar (CLASSLOADER)
2202 for (int i = 0; i < seqs.length; i++)
2204 if (seqs[i] != null)
2206 ((Sequence) seqs[i]).addPDBId(pdb);
2207 StructureSelectionManager
2208 .getStructureSelectionManager(applet)
2209 .registerPDBEntry(pdb);
2213 if (JalviewLite.debug)
2215 // this may not really be a problem but we give a warning
2218 "Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
2224 if (!alignPdbStructures)
2226 alignFrame.newStructureView(applet, pdb, seqs, chains,
2231 pdbs.addElement(new Object[] { pdb, seqs, chains, protocol });
2237 } while (param != null || pdbFileCount < 10);
2238 if (pdbs.size() > 0)
2240 SequenceI[][] seqs = new SequenceI[pdbs.size()][];
2241 PDBEntry[] pdb = new PDBEntry[pdbs.size()];
2242 String[][] chains = new String[pdbs.size()][];
2243 String[] protocols = new String[pdbs.size()];
2244 for (int pdbsi = 0, pdbsiSize = pdbs
2245 .size(); pdbsi < pdbsiSize; pdbsi++)
2247 Object[] o = (Object[]) pdbs.elementAt(pdbsi);
2248 pdb[pdbsi] = (PDBEntry) o[0];
2249 seqs[pdbsi] = (SequenceI[]) o[1];
2250 chains[pdbsi] = (String[]) o[2];
2251 protocols[pdbsi] = (String) o[3];
2253 alignFrame.alignedStructureView(applet, pdb, seqs, chains,
2261 * Load in a Jnetfile if specified by parameter. Returns true if loaded,
2267 protected boolean loadJnetFile(AlignFrame alignFrame)
2269 boolean result = false;
2270 String param = applet.getParameter("jnetfile");
2273 // jnet became jpred around 2016
2274 param = applet.getParameter("jpredfile");
2280 param = resolveFileProtocol(param);
2281 JPredFile predictions = new JPredFile(param, protocol);
2282 JnetAnnotationMaker.add_annotation(predictions,
2283 alignFrame.viewport.getAlignment(), 0, false);
2284 // false == do not add sequence profile from concise output
2286 alignFrame.viewport.getAlignment().setupJPredAlignment();
2288 alignFrame.alignPanel.fontChanged();
2289 alignFrame.alignPanel.setScrollValues(0, 0);
2291 } catch (Exception ex)
2293 ex.printStackTrace();
2300 * Load annotations if specified by parameter. Returns true if loaded, else
2306 protected boolean loadAnnotations(AlignFrame alignFrame)
2308 boolean result = false;
2309 String param = applet.getParameter("annotations");
2312 param = resolveFileProtocol(param);
2314 if (new AnnotationFile().annotateAlignmentView(alignFrame.viewport,
2317 alignFrame.alignPanel.fontChanged();
2318 alignFrame.alignPanel.setScrollValues(0, 0);
2324 "Annotations were not added from annotation file '"
2332 * Load features file and view settings as specified by parameters. Returns
2333 * true if features were loaded, else false.
2338 protected boolean loadFeatures(AlignFrame alignFrame)
2340 boolean result = false;
2341 // ///////////////////////////
2342 // modify display of features
2343 // we do this before any features have been loaded, ensuring any hidden
2344 // groups are hidden when features first displayed
2346 // hide specific groups
2348 String param = applet.getParameter("hidefeaturegroups");
2351 alignFrame.setFeatureGroupState(separatorListToArray(param), false);
2352 // applet.setFeatureGroupStateOn(newAlignFrame, param, false);
2354 // show specific groups
2355 param = applet.getParameter("showfeaturegroups");
2358 alignFrame.setFeatureGroupState(separatorListToArray(param), true);
2359 // applet.setFeatureGroupStateOn(newAlignFrame, param, true);
2361 // and now load features
2362 param = applet.getParameter("features");
2365 param = resolveFileProtocol(param);
2367 result = alignFrame.parseFeaturesFile(param, protocol);
2370 param = applet.getParameter("showFeatureSettings");
2371 if (param != null && param.equalsIgnoreCase(TRUE))
2373 alignFrame.viewport.setShowSequenceFeatures(true);
2374 new FeatureSettings(alignFrame.alignPanel);
2380 * Load a score file if specified by parameter. Returns true if file was
2381 * loaded, else false.
2385 protected boolean loadScoreFile(AlignFrame alignFrame)
2387 boolean result = false;
2388 String sScoreFile = applet.getParameter("scoreFile");
2389 if (sScoreFile != null && !"".equals(sScoreFile))
2396 "Attempting to load T-COFFEE score file from the scoreFile parameter");
2398 result = alignFrame.loadScoreFile(sScoreFile);
2402 "Failed to parse T-COFFEE parameter as a valid score file ('"
2403 + sScoreFile + "')");
2405 } catch (Exception e)
2407 System.err.printf("Cannot read score file: '%s'. Cause: %s \n",
2408 sScoreFile, e.getMessage());
2415 * Load a tree for the alignment if specified by parameter. Returns true if
2416 * a tree was loaded, else false.
2421 protected boolean loadTree(AlignFrame alignFrame)
2423 boolean result = false;
2424 String treeFile = applet.getParameter("tree");
2425 if (treeFile == null)
2427 treeFile = applet.getParameter("treeFile");
2430 if (treeFile != null)
2434 treeFile = resolveFileProtocol(treeFile);
2435 NewickFile fin = new NewickFile(treeFile, protocol);
2438 if (fin.getTree() != null)
2440 alignFrame.loadTree(fin, treeFile);
2442 dbgMsg("Successfully imported tree.");
2446 dbgMsg("Tree parameter did not resolve to a valid tree.");
2448 } catch (Exception ex)
2450 ex.printStackTrace();
2457 * Discovers whether the given file is in the Applet Archive
2463 boolean inArchive(String f)
2465 // This might throw a security exception in certain browsers
2466 // Netscape Communicator for instance.
2469 boolean rtn = (getClass().getResourceAsStream("/" + f) != null);
2472 System.err.println("Resource '" + f + "' was "
2473 + (rtn ? "" : "not ") + "located by classloader.");
2476 } catch (Exception ex)
2478 System.out.println("Exception checking resources: " + f + " " + ex);
2485 * @return the default alignFrame acted on by the public applet methods. May
2486 * return null with an error message on System.err indicating the
2489 public AlignFrame getDefaultTargetFrame()
2491 if (currentAlignFrame != null)
2493 return currentAlignFrame;
2495 if (initialAlignFrame != null)
2497 return initialAlignFrame;
2500 "Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
2505 * separator used for separatorList
2507 protected String separator = "" + ((char) 0x00AC); // the default used to be
2508 // '|' but many sequence
2509 // IDS include pipes.
2512 * set to enable the URL based javascript execution mechanism
2514 public boolean jsfallbackEnabled = false;
2517 * parse the string into a list
2520 * @return elements separated by separator
2522 public String[] separatorListToArray(String list)
2524 return separatorListToArray(list, separator);
2528 * parse the string into a list
2532 * @return elements separated by separator
2534 public static String[] separatorListToArray(String list, String separator)
2536 // TODO use StringUtils version (slightly different...)
2537 int seplen = separator.length();
2538 if (list == null || list.equals("") || list.equals(separator))
2542 java.util.Vector jv = new Vector();
2544 while ((pos = list.indexOf(separator, cp)) > cp)
2546 jv.addElement(list.substring(cp, pos));
2549 if (cp < list.length())
2551 String c = list.substring(cp);
2552 if (!c.equals(separator))
2559 String[] v = new String[jv.size()];
2560 for (int i = 0; i < v.length; i++)
2562 v[i] = (String) jv.elementAt(i);
2564 jv.removeAllElements();
2567 System.err.println("Array from '" + separator
2568 + "' separated List:\n" + v.length);
2569 for (int i = 0; i < v.length; i++)
2571 System.err.println("item " + i + " '" + v[i] + "'");
2579 "Empty Array from '" + separator + "' separated List");
2585 * concatenate the list with separator
2588 * @return concatenated string
2590 public String arrayToSeparatorList(String[] list)
2592 return arrayToSeparatorList(list, separator);
2596 * concatenate the list with separator
2600 * @return concatenated string
2602 public static String arrayToSeparatorList(String[] list, String separator)
2604 // TODO use StringUtils version
2605 StringBuffer v = new StringBuffer();
2606 if (list != null && list.length > 0)
2608 for (int i = 0, iSize = list.length; i < iSize; i++)
2610 if (list[i] != null)
2614 v.append(separator);
2622 .println("Returning '" + separator + "' separated List:\n");
2623 System.err.println(v);
2625 return v.toString();
2630 "Returning empty '" + separator + "' separated List\n");
2632 return "" + separator;
2638 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroups()
2641 public String getFeatureGroups()
2643 String lst = arrayToSeparatorList(
2644 getDefaultTargetFrame().getFeatureGroups());
2652 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOn(jalview.appletgui.AlignFrame
2656 public String getFeatureGroupsOn(AlignFrame alf)
2658 String lst = arrayToSeparatorList(alf.getFeatureGroups());
2665 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfState(boolean)
2668 public String getFeatureGroupsOfState(boolean visible)
2670 return arrayToSeparatorList(
2671 getDefaultTargetFrame().getFeatureGroupsOfState(visible));
2678 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfStateOn(jalview.appletgui
2679 * .AlignFrame, boolean)
2682 public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
2684 return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
2690 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupStateOn(jalview.appletgui.
2691 * AlignFrame, java.lang.String, boolean)
2694 public void setFeatureGroupStateOn(final AlignFrame alf,
2695 final String groups, boolean state)
2697 final boolean st = state;// !(state==null || state.equals("") ||
2698 // state.toLowerCase(Locale.ROOT).equals("false"));
2699 java.awt.EventQueue.invokeLater(new Runnable()
2704 alf.setFeatureGroupState(separatorListToArray(groups), st);
2712 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupState(java.lang.String,
2716 public void setFeatureGroupState(String groups, boolean state)
2718 setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
2724 * @see jalview.bin.JalviewLiteJsApi#getSeparator()
2727 public String getSeparator()
2735 * @see jalview.bin.JalviewLiteJsApi#setSeparator(java.lang.String)
2738 public void setSeparator(String separator)
2740 if (separator == null || separator.length() < 1)
2743 separator = "" + ((char) 0x00AC);
2745 this.separator = separator;
2748 System.err.println("Default Separator now: '" + separator + "'");
2753 * get boolean value of applet parameter 'name' and return default if
2754 * parameter is not set
2759 * the value to return otherwise
2760 * @return true or false
2762 public boolean getDefaultParameter(String name, boolean def)
2765 if ((stn = getParameter(name)) == null)
2769 if (TRUE.equalsIgnoreCase(stn))
2779 * @see jalview.bin.JalviewLiteJsApi#addPdbFile(jalview.appletgui.AlignFrame,
2780 * java.lang.String, java.lang.String, java.lang.String)
2783 public boolean addPdbFile(AlignFrame alFrame, String sequenceId,
2784 String pdbEntryString, String pdbFile)
2786 return alFrame.addPdbFile(sequenceId, pdbEntryString, pdbFile);
2789 protected void setAlignPdbStructures(boolean alignPdbStructures)
2791 this.alignPdbStructures = alignPdbStructures;
2794 public boolean isAlignPdbStructures()
2796 return alignPdbStructures;
2802 // callInitCallback();
2805 private Hashtable<String, long[]> jshashes = new Hashtable<>();
2807 private Hashtable<String, Hashtable<String, String[]>> jsmessages = new Hashtable<>();
2809 public void setJsMessageSet(String messageclass, String viewId,
2810 String[] colcommands)
2812 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2815 msgset = new Hashtable<>();
2816 jsmessages.put(messageclass, msgset);
2818 msgset.put(viewId, colcommands);
2819 long[] l = new long[colcommands.length];
2820 for (int i = 0; i < colcommands.length; i++)
2822 l[i] = colcommands[i].hashCode();
2824 jshashes.put(messageclass + "|" + viewId, l);
2830 * @see jalview.bin.JalviewLiteJsApi#getJsMessage(java.lang.String,
2834 public String getJsMessage(String messageclass, String viewId)
2836 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2839 String[] msgs = msgset.get(viewId);
2842 for (int i = 0; i < msgs.length; i++)
2844 if (msgs[i] != null)
2856 public boolean isJsMessageSetChanged(String string, String string2,
2857 String[] colcommands)
2859 long[] l = jshashes.get(string + "|" + string2);
2860 if (l == null && colcommands != null)
2864 for (int i = 0; i < colcommands.length; i++)
2866 if (l[i] != colcommands[i].hashCode())
2874 private Vector jsExecQueue = new Vector();
2876 public Vector getJsExecQueue()
2881 public void setExecutor(JSFunctionExec jsFunctionExec2)
2883 jsFunctionExec = jsFunctionExec2;
2887 * return the given colour value parameter or the given default if parameter
2894 public Color getDefaultColourParameter(String colparam, Color defcolour)
2896 String colprop = getParameter(colparam);
2897 if (colprop == null || colprop.trim().length() == 0)
2901 Color col = ColorUtils.parseColourString(colprop);
2904 System.err.println("Couldn't parse '" + colprop + "' as a colour for "
2907 return (col == null) ? defcolour : col;
2910 public void openJalviewHelpUrl()
2912 String helpUrl = getParameter("jalviewhelpurl");
2913 if (helpUrl == null || helpUrl.trim().length() < 5)
2915 helpUrl = "http://www.jalview.org/help.html";
2917 showURL(helpUrl, "HELP");
2921 * form a complete URL given a path to a resource and a reference location on
2925 * - an absolute path on the same server as localref or a document
2926 * located relative to localref
2928 * - a URL on the same server as url
2929 * @return a complete URL for the resource located by url
2931 private String resolveUrlForLocalOrAbsolute(String targetPath,
2934 String resolvedPath = "";
2935 if (targetPath.startsWith("/"))
2937 String codebase = localref.toString();
2938 String localfile = localref.getFile();
2939 resolvedPath = codebase.substring(0,
2940 codebase.length() - localfile.length()) + targetPath;
2941 return resolvedPath;
2945 * get URL path and strip off any trailing file e.g.
2946 * www.jalview.org/examples/index.html#applets?a=b is trimmed to
2947 * www.jalview.org/examples/
2949 String urlPath = localref.toString();
2950 String directoryPath = urlPath;
2951 int lastSeparator = directoryPath.lastIndexOf("/");
2952 if (lastSeparator > 0)
2954 directoryPath = directoryPath.substring(0, lastSeparator + 1);
2957 if (targetPath.startsWith("/"))
2960 * construct absolute URL to a file on the server - this is not allowed?
2962 // String localfile = localref.getFile();
2963 // resolvedPath = urlPath.substring(0,
2964 // urlPath.length() - localfile.length())
2966 resolvedPath = directoryPath + targetPath.substring(1);
2970 resolvedPath = directoryPath + targetPath;
2975 "resolveUrlForLocalOrAbsolute returning " + resolvedPath);
2977 return resolvedPath;
2981 * open a URL in the browser - resolving it according to relative refs and
2982 * coping with javascript: protocol if necessary.
2987 public void showURL(String url, String target)
2991 if (url.indexOf(":") == -1)
2993 // TODO: verify (Bas Vroling bug) prepend codebase or server URL to
2995 // Should really use docbase, not codebase.
2997 url = resolveUrlForLocalOrAbsolute(url,
2998 prepend = getDefaultParameter("resolvetocodebase", false)
3000 : getDocumentBase());
3003 System.err.println("Show url (prepended " + prepend
3004 + " - toggle resolvetocodebase if code/docbase resolution is wrong): "
3012 System.err.println("Show url: " + url);
3015 if (url.indexOf("javascript:") == 0)
3017 // no target for the javascript context
3018 getAppletContext().showDocument(new java.net.URL(url));
3022 getAppletContext().showDocument(new java.net.URL(url), target);
3024 } catch (Exception ex)
3026 ex.printStackTrace();
3031 * bind structures in a viewer to any matching sequences in an alignFrame (use
3032 * sequenceIds to limit scope of search to specific sequences)
3036 * @param sequenceIds
3037 * @return TODO: consider making an exception structure for indicating when
3038 * binding fails public SequenceStructureBinding
3039 * addStructureViewInstance( AlignFrame alFrame, Object viewer, String
3042 * if (sequenceIds != null && sequenceIds.length() > 0) { return
3043 * alFrame.addStructureViewInstance(viewer,
3044 * separatorListToArray(sequenceIds)); } else { return
3045 * alFrame.addStructureViewInstance(viewer, null); } // return null; }