2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import java.util.Locale;
25 import jalview.analysis.AlignmentUtils;
26 import jalview.api.StructureSelectionManagerProvider;
27 import jalview.appletgui.AlignFrame;
28 import jalview.appletgui.AlignViewport;
29 import jalview.appletgui.EmbmenuFrame;
30 import jalview.appletgui.FeatureSettings;
31 import jalview.appletgui.SplitFrame;
32 import jalview.datamodel.Alignment;
33 import jalview.datamodel.AlignmentI;
34 import jalview.datamodel.AlignmentOrder;
35 import jalview.datamodel.ColumnSelection;
36 import jalview.datamodel.PDBEntry;
37 import jalview.datamodel.Sequence;
38 import jalview.datamodel.SequenceGroup;
39 import jalview.datamodel.SequenceI;
40 import jalview.io.AnnotationFile;
41 import jalview.io.AppletFormatAdapter;
42 import jalview.io.DataSourceType;
43 import jalview.io.FileFormatI;
44 import jalview.io.FileFormats;
45 import jalview.io.FileParse;
46 import jalview.io.IdentifyFile;
47 import jalview.io.JPredFile;
48 import jalview.io.JnetAnnotationMaker;
49 import jalview.io.NewickFile;
50 import jalview.javascript.JSFunctionExec;
51 import jalview.javascript.JalviewLiteJsApi;
52 import jalview.javascript.JsCallBack;
53 import jalview.javascript.MouseOverStructureListener;
54 import jalview.structure.SelectionListener;
55 import jalview.structure.StructureSelectionManager;
56 import jalview.util.ColorUtils;
57 import jalview.util.HttpUtils;
58 import jalview.util.MessageManager;
60 import java.applet.Applet;
61 import java.awt.Button;
62 import java.awt.Color;
63 import java.awt.Component;
64 import java.awt.EventQueue;
66 import java.awt.Frame;
67 import java.awt.Graphics;
68 import java.awt.event.ActionEvent;
69 import java.awt.event.WindowAdapter;
70 import java.awt.event.WindowEvent;
71 import java.io.BufferedReader;
72 import java.io.IOException;
73 import java.io.InputStreamReader;
75 import java.util.ArrayList;
76 import java.util.Hashtable;
77 import java.util.List;
78 import java.util.StringTokenizer;
79 import java.util.Vector;
81 import netscape.javascript.JSObject;
84 * Jalview Applet. Runs in Java 1.18 runtime
87 * @version $Revision: 1.92 $
89 public class JalviewLite extends Applet
90 implements StructureSelectionManagerProvider, JalviewLiteJsApi
93 private static final String TRUE = "true";
95 private static final String FALSE = "false";
97 public StructureSelectionManager getStructureSelectionManager()
99 return StructureSelectionManager.getStructureSelectionManager(this);
102 // /////////////////////////////////////////
103 // The following public methods may be called
104 // externally, eg via javascript in HTML page
108 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences()
111 public String getSelectedSequences()
113 return getSelectedSequencesFrom(getDefaultTargetFrame());
119 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences(java.lang.String)
122 public String getSelectedSequences(String sep)
124 return getSelectedSequencesFrom(getDefaultTargetFrame(), sep);
131 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
135 public String getSelectedSequencesFrom(AlignFrame alf)
137 return getSelectedSequencesFrom(alf, separator); // ""+0x00AC);
144 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
145 * .AlignFrame, java.lang.String)
148 public String getSelectedSequencesFrom(AlignFrame alf, String sep)
150 StringBuffer result = new StringBuffer("");
151 if (sep == null || sep.length() == 0)
153 sep = separator; // "+0x00AC;
155 if (alf.viewport.getSelectionGroup() != null)
157 SequenceI[] seqs = alf.viewport.getSelectionGroup()
158 .getSequencesInOrder(alf.viewport.getAlignment());
160 for (int i = 0; i < seqs.length; i++)
162 result.append(seqs[i].getName());
167 return result.toString();
173 * @see jalview.bin.JalviewLiteJsApi#highlight(java.lang.String,
174 * java.lang.String, java.lang.String)
177 public void highlight(String sequenceId, String position,
178 String alignedPosition)
180 highlightIn(getDefaultTargetFrame(), sequenceId, position,
187 * @see jalview.bin.JalviewLiteJsApi#highlightIn(jalview.appletgui.AlignFrame,
188 * java.lang.String, java.lang.String, java.lang.String)
191 public void highlightIn(final AlignFrame alf, final String sequenceId,
192 final String position, final String alignedPosition)
194 // TODO: could try to highlight in all alignments if alf==null
195 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
196 alf.viewport.getAlignment().getSequencesArray());
197 final SequenceI sq = matcher.findIdMatch(sequenceId);
203 apos = Integer.valueOf(position).intValue();
205 } catch (NumberFormatException ex)
209 final StructureSelectionManagerProvider me = this;
210 final int pos = apos;
211 // use vamsas listener to broadcast to all listeners in scope
212 if (alignedPosition != null
213 && (alignedPosition.trim().length() == 0 || alignedPosition
214 .toLowerCase(Locale.ROOT).indexOf("false") > -1))
216 java.awt.EventQueue.invokeLater(new Runnable()
221 StructureSelectionManager.getStructureSelectionManager(me)
222 .mouseOverVamsasSequence(sq, sq.findIndex(pos), null);
228 java.awt.EventQueue.invokeLater(new Runnable()
233 StructureSelectionManager.getStructureSelectionManager(me)
234 .mouseOverVamsasSequence(sq, pos, null);
244 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
248 public void select(String sequenceIds, String columns)
250 selectIn(getDefaultTargetFrame(), sequenceIds, columns, separator);
256 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
257 * java.lang.String, java.lang.String)
260 public void select(String sequenceIds, String columns, String sep)
262 selectIn(getDefaultTargetFrame(), sequenceIds, columns, sep);
268 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
269 * java.lang.String, java.lang.String)
272 public void selectIn(AlignFrame alf, String sequenceIds, String columns)
274 selectIn(alf, sequenceIds, columns, separator);
280 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
281 * java.lang.String, java.lang.String, java.lang.String)
284 public void selectIn(final AlignFrame alf, String sequenceIds,
285 String columns, String sep)
287 if (sep == null || sep.length() == 0)
295 System.err.println("Selecting region using separator string '"
300 String[] ids = separatorListToArray(sequenceIds, sep);
301 String[] cols = separatorListToArray(columns, sep);
302 final SequenceGroup sel = new SequenceGroup();
303 final ColumnSelection csel = new ColumnSelection();
304 AlignmentI al = alf.viewport.getAlignment();
305 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
306 alf.viewport.getAlignment().getSequencesArray());
307 int start = 0, end = al.getWidth(), alw = al.getWidth();
308 boolean seqsfound = true;
309 if (ids != null && ids.length > 0)
312 for (int i = 0; i < ids.length; i++)
314 if (ids[i].trim().length() == 0)
318 SequenceI sq = matcher.findIdMatch(ids[i]);
322 sel.addSequence(sq, false);
326 boolean inseqpos = false;
327 if (cols != null && cols.length > 0)
329 boolean seset = false;
330 for (int i = 0; i < cols.length; i++)
332 String cl = cols[i].trim();
333 if (cl.length() == 0)
338 if ((p = cl.indexOf("-")) > -1)
340 int from = -1, to = -1;
343 from = Integer.valueOf(cl.substring(0, p)).intValue();
345 } catch (NumberFormatException ex)
348 "ERROR: Couldn't parse first integer in range element column selection string '"
349 + cl + "' - format is 'from-to'");
354 to = Integer.valueOf(cl.substring(p + 1)).intValue();
356 } catch (NumberFormatException ex)
359 "ERROR: Couldn't parse second integer in range element column selection string '"
360 + cl + "' - format is 'from-to'");
363 if (from >= 0 && to >= 0)
380 // comment to prevent range extension
390 for (int r = from; r <= to; r++)
392 if (r >= 0 && r < alw)
399 System.err.println("Range '" + cl + "' deparsed as [" + from
405 System.err.println("ERROR: Invalid Range '" + cl
406 + "' deparsed as [" + from + "," + to + "]");
414 r = Integer.valueOf(cl).intValue();
416 } catch (NumberFormatException ex)
418 if (cl.toLowerCase(Locale.ROOT).equals("sequence"))
420 // we are in the dataset sequence's coordinate frame.
426 "ERROR: Couldn't parse integer from point selection element of column selection string '"
431 if (r >= 0 && r <= alw)
441 // comment to prevent range extension
454 System.err.println("Point selection '" + cl
455 + "' deparsed as [" + r + "]");
460 System.err.println("ERROR: Invalid Point selection '" + cl
461 + "' deparsed as [" + r + "]");
468 // we only propagate the selection when it was the null selection, or the
469 // given sequences were found in the alignment.
470 if (inseqpos && sel.getSize() > 0)
472 // assume first sequence provides reference frame ?
473 SequenceI rs = sel.getSequenceAt(0);
474 start = rs.findIndex(start);
475 end = rs.findIndex(end);
476 List<Integer> cs = new ArrayList<>(csel.getSelected());
478 for (Integer selectedCol : cs)
480 csel.addElement(rs.findIndex(selectedCol));
483 sel.setStartRes(start);
485 EventQueue.invokeLater(new Runnable()
490 alf.select(sel, csel,
491 alf.getAlignViewport().getAlignment().getHiddenColumns());
501 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignment(java.lang.
502 * String, java.lang.String)
505 public String getSelectedSequencesAsAlignment(String format,
508 return getSelectedSequencesAsAlignmentFrom(getDefaultTargetFrame(),
516 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignmentFrom(jalview
517 * .appletgui.AlignFrame, java.lang.String, java.lang.String)
520 public String getSelectedSequencesAsAlignmentFrom(AlignFrame alf,
521 String format, String suffix)
525 FileFormatI theFormat = FileFormats.getInstance().forName(format);
526 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
527 if (alf.viewport.getSelectionGroup() != null)
529 // JBPNote: getSelectionAsNewSequence behaviour has changed - this
530 // method now returns a full copy of sequence data
531 // TODO consider using getSequenceSelection instead here
532 String reply = new AppletFormatAdapter().formatSequences(theFormat,
533 new Alignment(alf.viewport.getSelectionAsNewSequence()),
537 } catch (IllegalArgumentException ex)
539 ex.printStackTrace();
540 return "Error retrieving alignment, possibly invalid format specifier: "
549 * @see jalview.bin.JalviewLiteJsApi#getAlignmentOrder()
552 public String getAlignmentOrder()
554 return getAlignmentOrderFrom(getDefaultTargetFrame());
561 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
565 public String getAlignmentOrderFrom(AlignFrame alf)
567 return getAlignmentOrderFrom(alf, separator);
574 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
575 * , java.lang.String)
578 public String getAlignmentOrderFrom(AlignFrame alf, String sep)
580 AlignmentI alorder = alf.getAlignViewport().getAlignment();
581 String[] order = new String[alorder.getHeight()];
582 for (int i = 0; i < order.length; i++)
584 order[i] = alorder.getSequenceAt(i).getName();
586 return arrayToSeparatorList(order);
592 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
596 public String orderBy(String order, String undoName)
598 return orderBy(order, undoName, separator);
604 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
605 * java.lang.String, java.lang.String)
608 public String orderBy(String order, String undoName, String sep)
610 return orderAlignmentBy(getDefaultTargetFrame(), order, undoName, sep);
617 * jalview.bin.JalviewLiteJsApi#orderAlignmentBy(jalview.appletgui.AlignFrame,
618 * java.lang.String, java.lang.String, java.lang.String)
621 public String orderAlignmentBy(AlignFrame alf, String order,
622 String undoName, String sep)
624 String[] ids = separatorListToArray(order, sep);
625 SequenceI[] sqs = null;
626 if (ids != null && ids.length > 0)
628 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
629 alf.viewport.getAlignment().getSequencesArray());
631 sqs = new SequenceI[ids.length];
632 for (int i = 0; i < ids.length; i++)
634 if (ids[i].trim().length() == 0)
638 SequenceI sq = matcher.findIdMatch(ids[i]);
646 SequenceI[] sqq = new SequenceI[s];
647 System.arraycopy(sqs, 0, sqq, 0, s);
660 final AlignmentOrder aorder = new AlignmentOrder(sqs);
662 if (undoName != null && undoName.trim().length() == 0)
666 final String _undoName = undoName;
667 // TODO: deal with synchronization here: cannot raise any events until after
668 // this has returned.
669 return alf.sortBy(aorder, _undoName) ? TRUE : "";
675 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String)
678 public String getAlignment(String format)
680 return getAlignmentFrom(getDefaultTargetFrame(), format, TRUE);
687 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
691 public String getAlignmentFrom(AlignFrame alf, String format)
693 return getAlignmentFrom(alf, format, TRUE);
699 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String,
703 public String getAlignment(String format, String suffix)
705 return getAlignmentFrom(getDefaultTargetFrame(), format, suffix);
712 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
713 * java.lang.String, java.lang.String)
716 public String getAlignmentFrom(AlignFrame alf, String format,
721 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
723 FileFormatI theFormat = FileFormats.getInstance().forName(format);
724 String reply = new AppletFormatAdapter().formatSequences(theFormat,
725 alf.viewport.getAlignment(), seqlimits);
727 } catch (IllegalArgumentException ex)
729 ex.printStackTrace();
730 return "Error retrieving alignment, possibly invalid format specifier: "
738 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
741 public void loadAnnotation(String annotation)
743 loadAnnotationFrom(getDefaultTargetFrame(), annotation);
750 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
751 * , java.lang.String)
754 public void loadAnnotationFrom(AlignFrame alf, String annotation)
756 if (new AnnotationFile().annotateAlignmentView(alf.getAlignViewport(),
757 annotation, DataSourceType.PASTE))
759 alf.alignPanel.fontChanged();
760 alf.alignPanel.setScrollValues(0, 0);
764 alf.parseFeaturesFile(annotation, DataSourceType.PASTE);
771 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
774 public void loadFeatures(String features, boolean autoenabledisplay)
776 loadFeaturesFrom(getDefaultTargetFrame(), features, autoenabledisplay);
783 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
784 * , java.lang.String)
787 public boolean loadFeaturesFrom(AlignFrame alf, String features,
788 boolean autoenabledisplay)
790 return alf.parseFeaturesFile(features, DataSourceType.PASTE,
797 * @see jalview.bin.JalviewLiteJsApi#getFeatures(java.lang.String)
800 public String getFeatures(String format)
802 return getFeaturesFrom(getDefaultTargetFrame(), format);
809 * jalview.bin.JalviewLiteJsApi#getFeaturesFrom(jalview.appletgui.AlignFrame,
813 public String getFeaturesFrom(AlignFrame alf, String format)
815 return alf.outputFeatures(false, format);
821 * @see jalview.bin.JalviewLiteJsApi#getAnnotation()
824 public String getAnnotation()
826 return getAnnotationFrom(getDefaultTargetFrame());
833 * jalview.bin.JalviewLiteJsApi#getAnnotationFrom(jalview.appletgui.AlignFrame
837 public String getAnnotationFrom(AlignFrame alf)
839 return alf.outputAnnotations(false);
845 * @see jalview.bin.JalviewLiteJsApi#newView()
848 public AlignFrame newView()
850 return newViewFrom(getDefaultTargetFrame());
856 * @see jalview.bin.JalviewLiteJsApi#newView(java.lang.String)
859 public AlignFrame newView(String name)
861 return newViewFrom(getDefaultTargetFrame(), name);
867 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame)
870 public AlignFrame newViewFrom(AlignFrame alf)
872 return alf.newView(null);
878 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame,
882 public AlignFrame newViewFrom(AlignFrame alf, String name)
884 return alf.newView(name);
890 * @see jalview.bin.JalviewLiteJsApi#loadAlignment(java.lang.String,
894 public AlignFrame loadAlignment(String text, String title)
896 AlignmentI al = null;
900 FileFormatI format = new IdentifyFile().identify(text,
901 DataSourceType.PASTE);
902 al = new AppletFormatAdapter().readFile(text, DataSourceType.PASTE,
904 if (al.getHeight() > 0)
906 return new AlignFrame(al, this, title, false);
908 } catch (IOException ex)
910 ex.printStackTrace();
918 * @see jalview.bin.JalviewLiteJsApi#setMouseoverListener(java.lang.String)
921 public void setMouseoverListener(String listener)
923 setMouseoverListener(currentAlignFrame, listener);
926 private Vector<jalview.javascript.JSFunctionExec> javascriptListeners = new Vector<>();
932 * jalview.bin.JalviewLiteJsApi#setMouseoverListener(jalview.appletgui.AlignFrame
933 * , java.lang.String)
936 public void setMouseoverListener(AlignFrame af, String listener)
938 if (listener != null)
940 listener = listener.trim();
941 if (listener.length() == 0)
944 "jalview Javascript error: Ignoring empty function for mouseover listener.");
948 jalview.javascript.MouseOverListener mol = new jalview.javascript.MouseOverListener(
950 javascriptListeners.addElement(mol);
951 StructureSelectionManager.getStructureSelectionManager(this)
952 .addStructureViewerListener(mol);
955 System.err.println("Added a mouseover listener for "
956 + ((af == null) ? "All frames"
958 + af.getAlignViewport().getSequenceSetId()));
959 System.err.println("There are now " + javascriptListeners.size()
960 + " listeners in total.");
967 * @see jalview.bin.JalviewLiteJsApi#setSelectionListener(java.lang.String)
970 public void setSelectionListener(String listener)
972 setSelectionListener(null, listener);
979 * jalview.bin.JalviewLiteJsApi#setSelectionListener(jalview.appletgui.AlignFrame
980 * , java.lang.String)
983 public void setSelectionListener(AlignFrame af, String listener)
985 if (listener != null)
987 listener = listener.trim();
988 if (listener.length() == 0)
991 "jalview Javascript error: Ignoring empty function for selection listener.");
995 jalview.javascript.JsSelectionSender mol = new jalview.javascript.JsSelectionSender(
997 javascriptListeners.addElement(mol);
998 StructureSelectionManager.getStructureSelectionManager(this)
999 .addSelectionListener(mol);
1002 System.err.println("Added a selection listener for "
1003 + ((af == null) ? "All frames"
1005 + af.getAlignViewport().getSequenceSetId()));
1006 System.err.println("There are now " + javascriptListeners.size()
1007 + " listeners in total.");
1012 * Callable from javascript to register a javascript function to pass events
1013 * to a structure viewer.
1016 * the name of a javascript function
1018 * a token separated list of PDB file names listened for
1019 * @see jalview.bin.JalviewLiteJsApi#setStructureListener(java.lang.String,
1023 public void setStructureListener(String listener, String modelSet)
1025 if (listener != null)
1027 listener = listener.trim();
1028 if (listener.length() == 0)
1031 "jalview Javascript error: Ignoring empty function for selection listener.");
1035 MouseOverStructureListener mol = new MouseOverStructureListener(this,
1036 listener, separatorListToArray(modelSet));
1037 javascriptListeners.addElement(mol);
1038 StructureSelectionManager.getStructureSelectionManager(this)
1039 .addStructureViewerListener(mol);
1042 System.err.println("Added a javascript structure viewer listener '"
1044 System.err.println("There are now " + javascriptListeners.size()
1045 + " listeners in total.");
1053 * jalview.bin.JalviewLiteJsApi#removeJavascriptListener(jalview.appletgui
1054 * .AlignFrame, java.lang.String)
1057 public void removeJavascriptListener(AlignFrame af, String listener)
1059 if (listener != null)
1061 listener = listener.trim();
1062 if (listener.length() == 0)
1067 boolean rprt = false;
1068 for (int ms = 0, msSize = javascriptListeners.size(); ms < msSize;)
1070 Object lstn = javascriptListeners.elementAt(ms);
1071 JsCallBack lstner = (JsCallBack) lstn;
1072 if ((af == null || lstner.getAlignFrame() == af) && (listener == null
1073 || lstner.getListenerFunction().equals(listener)))
1075 javascriptListeners.removeElement(lstner);
1077 if (lstner instanceof SelectionListener)
1079 StructureSelectionManager.getStructureSelectionManager(this)
1080 .removeSelectionListener((SelectionListener) lstner);
1084 StructureSelectionManager.getStructureSelectionManager(this)
1085 .removeStructureViewerListener(lstner, null);
1090 System.err.println("Removed listener '" + listener + "'");
1100 System.err.println("There are now " + javascriptListeners.size()
1101 + " listeners in total.");
1108 System.err.println("Applet " + getName() + " stop().");
1113 public void destroy()
1115 System.err.println("Applet " + getName() + " destroy().");
1119 private void tidyUp()
1122 if (currentAlignFrame != null && currentAlignFrame.viewport != null
1123 && currentAlignFrame.viewport.applet != null)
1125 AlignViewport av = currentAlignFrame.viewport;
1126 currentAlignFrame.closeMenuItem_actionPerformed();
1128 currentAlignFrame = null;
1130 if (javascriptListeners != null)
1132 while (javascriptListeners.size() > 0)
1134 jalview.javascript.JSFunctionExec mol = javascriptListeners
1136 javascriptListeners.removeElement(mol);
1137 if (mol instanceof SelectionListener)
1139 StructureSelectionManager.getStructureSelectionManager(this)
1140 .removeSelectionListener((SelectionListener) mol);
1144 StructureSelectionManager.getStructureSelectionManager(this)
1145 .removeStructureViewerListener(mol, null);
1150 if (jsFunctionExec != null)
1152 jsFunctionExec.stopQueue();
1153 jsFunctionExec.jvlite = null;
1155 initialAlignFrame = null;
1156 jsFunctionExec = null;
1157 javascriptListeners = null;
1158 StructureSelectionManager.release(this);
1161 private jalview.javascript.JSFunctionExec jsFunctionExec;
1166 * @see jalview.bin.JalviewLiteJsApi#mouseOverStructure(java.lang.String,
1167 * java.lang.String, java.lang.String)
1170 public void mouseOverStructure(final String pdbResNum, final String chain,
1171 final String pdbfile)
1173 final StructureSelectionManagerProvider me = this;
1174 java.awt.EventQueue.invokeLater(new Runnable()
1181 StructureSelectionManager.getStructureSelectionManager(me)
1182 .mouseOverStructure(Integer.valueOf(pdbResNum).intValue(),
1187 .println("mouseOver for '" + pdbResNum + "' in chain '"
1188 + chain + "' in structure '" + pdbfile + "'");
1190 } catch (NumberFormatException e)
1192 System.err.println("Ignoring invalid residue number string '"
1204 * jalview.bin.JalviewLiteJsApi#scrollViewToIn(jalview.appletgui.AlignFrame,
1205 * java.lang.String, java.lang.String)
1208 public void scrollViewToIn(final AlignFrame alf, final String topRow,
1209 final String leftHandColumn)
1211 java.awt.EventQueue.invokeLater(new Runnable()
1218 alf.scrollTo(Integer.valueOf(topRow).intValue(),
1219 Integer.valueOf(leftHandColumn).intValue());
1221 } catch (Exception ex)
1223 System.err.println("Couldn't parse integer arguments (topRow='"
1224 + topRow + "' and leftHandColumn='" + leftHandColumn
1226 ex.printStackTrace();
1236 * jalview.javascript.JalviewLiteJsApi#scrollViewToRowIn(jalview.appletgui
1237 * .AlignFrame, java.lang.String)
1240 public void scrollViewToRowIn(final AlignFrame alf, final String topRow)
1243 java.awt.EventQueue.invokeLater(new Runnable()
1250 alf.scrollToRow(Integer.valueOf(topRow).intValue());
1252 } catch (Exception ex)
1254 System.err.println("Couldn't parse integer arguments (topRow='"
1256 ex.printStackTrace();
1267 * jalview.javascript.JalviewLiteJsApi#scrollViewToColumnIn(jalview.appletgui
1268 * .AlignFrame, java.lang.String)
1271 public void scrollViewToColumnIn(final AlignFrame alf,
1272 final String leftHandColumn)
1274 java.awt.EventQueue.invokeLater(new Runnable()
1282 alf.scrollToColumn(Integer.valueOf(leftHandColumn).intValue());
1284 } catch (Exception ex)
1287 "Couldn't parse integer arguments (leftHandColumn='"
1288 + leftHandColumn + "')");
1289 ex.printStackTrace();
1296 // //////////////////////////////////////////////
1297 // //////////////////////////////////////////////
1299 public static int lastFrameX = 200;
1301 public static int lastFrameY = 200;
1303 boolean fileFound = true;
1305 String file = "No file";
1307 String file2 = null;
1309 Button launcher = new Button(
1310 MessageManager.getString("label.start_jalview"));
1313 * The currentAlignFrame is static, it will change if and when the user
1314 * selects a new window. Note that it will *never* point back to the embedded
1315 * AlignFrame if the applet is started as embedded on the page and then
1316 * afterwards a new view is created.
1318 public AlignFrame currentAlignFrame = null;
1321 * This is the first frame to be displayed, and does not change. API calls
1322 * will default to this instance if currentAlignFrame is null.
1324 AlignFrame initialAlignFrame = null;
1326 boolean embedded = false;
1328 private boolean checkForJmol = true;
1330 private boolean checkedForJmol = false; // ensure we don't check for jmol
1332 // every time the app is re-inited
1334 public boolean jmolAvailable = false;
1336 private boolean alignPdbStructures = false;
1339 * use an external structure viewer exclusively (no jmols or mc_views will be
1340 * opened by JalviewLite itself)
1342 public boolean useXtrnalSviewer = false;
1344 public static boolean debug = false;
1346 static String builddate = null, version = null, installation = null;
1348 private static void initBuildDetails()
1350 if (builddate == null)
1352 builddate = "unknown";
1354 installation = "applet";
1355 java.net.URL url = JalviewLite.class
1356 .getResource("/.build_properties");
1361 BufferedReader reader = new BufferedReader(
1362 new InputStreamReader(url.openStream()));
1364 while ((line = reader.readLine()) != null)
1366 if (line.indexOf("VERSION") > -1)
1368 version = line.substring(line.indexOf("=") + 1);
1370 if (line.indexOf("BUILD_DATE") > -1)
1372 builddate = line.substring(line.indexOf("=") + 1);
1374 if (line.indexOf("INSTALLATION") > -1)
1376 installation = line.substring(line.indexOf("=") + 1);
1379 } catch (Exception ex)
1381 ex.printStackTrace();
1387 public static String getBuildDate()
1393 public static String getInstallation()
1396 return installation;
1399 public static String getVersion()
1405 // public JSObject scriptObject = null;
1408 * init method for Jalview Applet
1413 debug = TRUE.equalsIgnoreCase(getParameter("debug"));
1418 System.err.println("Applet context is '"
1419 + getAppletContext().getClass().toString() + "'");
1421 JSObject scriptObject = JSObject.getWindow(this);
1422 if (debug && scriptObject != null)
1424 System.err.println("Applet has Javascript callback support.");
1427 } catch (Exception ex)
1430 "Warning: No JalviewLite javascript callbacks available.");
1433 ex.printStackTrace();
1439 System.err.println("JalviewLite Version " + getVersion());
1440 System.err.println("Build Date : " + getBuildDate());
1441 System.err.println("Installation : " + getInstallation());
1443 String externalsviewer = getParameter("externalstructureviewer");
1444 if (externalsviewer != null)
1446 useXtrnalSviewer = externalsviewer.trim().toLowerCase(Locale.ROOT)
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; }