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.applet.Applet;
24 import java.awt.Button;
25 import java.awt.Color;
26 import java.awt.Component;
27 import java.awt.EventQueue;
29 import java.awt.Frame;
30 import java.awt.Graphics;
31 import java.awt.event.ActionEvent;
32 import java.awt.event.WindowAdapter;
33 import java.awt.event.WindowEvent;
34 import java.io.BufferedReader;
35 import java.io.IOException;
36 import java.io.InputStreamReader;
38 import java.util.ArrayList;
39 import java.util.Hashtable;
40 import java.util.List;
41 import java.util.Locale;
42 import java.util.StringTokenizer;
43 import java.util.Vector;
45 import jalview.analysis.AlignmentUtils;
46 import jalview.api.StructureSelectionManagerProvider;
47 import jalview.appletgui.AlignFrame;
48 import jalview.appletgui.AlignViewport;
49 import jalview.appletgui.EmbmenuFrame;
50 import jalview.appletgui.FeatureSettings;
51 import jalview.appletgui.SplitFrame;
52 import jalview.datamodel.Alignment;
53 import jalview.datamodel.AlignmentI;
54 import jalview.datamodel.AlignmentOrder;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.PDBEntry;
57 import jalview.datamodel.Sequence;
58 import jalview.datamodel.SequenceGroup;
59 import jalview.datamodel.SequenceI;
60 import jalview.io.AnnotationFile;
61 import jalview.io.AppletFormatAdapter;
62 import jalview.io.DataSourceType;
63 import jalview.io.FileFormatI;
64 import jalview.io.FileFormats;
65 import jalview.io.FileParse;
66 import jalview.io.IdentifyFile;
67 import jalview.io.JPredFile;
68 import jalview.io.JnetAnnotationMaker;
69 import jalview.io.NewickFile;
70 import jalview.javascript.JSFunctionExec;
71 import jalview.javascript.JalviewLiteJsApi;
72 import jalview.javascript.JsCallBack;
73 import jalview.javascript.MouseOverStructureListener;
74 import jalview.structure.SelectionListener;
75 import jalview.structure.StructureSelectionManager;
76 import jalview.util.ColorUtils;
77 import jalview.util.HttpUtils;
78 import jalview.util.MessageManager;
79 import netscape.javascript.JSObject;
82 * Jalview Applet. Runs in Java 1.18 runtime
85 * @version $Revision: 1.92 $
87 public class JalviewLite extends Applet
88 implements StructureSelectionManagerProvider, JalviewLiteJsApi
91 private static final String TRUE = "true";
93 private static final String FALSE = "false";
95 public StructureSelectionManager getStructureSelectionManager()
97 return StructureSelectionManager.getStructureSelectionManager(this);
100 // /////////////////////////////////////////
101 // The following public methods may be called
102 // externally, eg via javascript in HTML page
106 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences()
109 public String getSelectedSequences()
111 return getSelectedSequencesFrom(getDefaultTargetFrame());
117 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences(java.lang.String)
120 public String getSelectedSequences(String sep)
122 return getSelectedSequencesFrom(getDefaultTargetFrame(), sep);
129 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
133 public String getSelectedSequencesFrom(AlignFrame alf)
135 return getSelectedSequencesFrom(alf, separator); // ""+0x00AC);
142 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
143 * .AlignFrame, java.lang.String)
146 public String getSelectedSequencesFrom(AlignFrame alf, String sep)
148 StringBuffer result = new StringBuffer("");
149 if (sep == null || sep.length() == 0)
151 sep = separator; // "+0x00AC;
153 if (alf.viewport.getSelectionGroup() != null)
155 SequenceI[] seqs = alf.viewport.getSelectionGroup()
156 .getSequencesInOrder(alf.viewport.getAlignment());
158 for (int i = 0; i < seqs.length; i++)
160 result.append(seqs[i].getName());
165 return result.toString();
171 * @see jalview.bin.JalviewLiteJsApi#highlight(java.lang.String,
172 * java.lang.String, java.lang.String)
175 public void highlight(String sequenceId, String position,
176 String alignedPosition)
178 highlightIn(getDefaultTargetFrame(), sequenceId, position,
185 * @see jalview.bin.JalviewLiteJsApi#highlightIn(jalview.appletgui.AlignFrame,
186 * java.lang.String, java.lang.String, java.lang.String)
189 public void highlightIn(final AlignFrame alf, final String sequenceId,
190 final String position, final String alignedPosition)
192 // TODO: could try to highlight in all alignments if alf==null
193 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
194 alf.viewport.getAlignment().getSequencesArray());
195 final SequenceI sq = matcher.findIdMatch(sequenceId);
201 apos = Integer.valueOf(position).intValue();
203 } catch (NumberFormatException ex)
207 final StructureSelectionManagerProvider me = this;
208 final int pos = apos;
209 // use vamsas listener to broadcast to all listeners in scope
210 if (alignedPosition != null
211 && (alignedPosition.trim().length() == 0 || alignedPosition
212 .toLowerCase(Locale.ROOT).indexOf("false") > -1))
214 java.awt.EventQueue.invokeLater(new Runnable()
219 StructureSelectionManager.getStructureSelectionManager(me)
220 .mouseOverVamsasSequence(sq, sq.findIndex(pos), null);
226 java.awt.EventQueue.invokeLater(new Runnable()
231 StructureSelectionManager.getStructureSelectionManager(me)
232 .mouseOverVamsasSequence(sq, pos, null);
242 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
246 public void select(String sequenceIds, String columns)
248 selectIn(getDefaultTargetFrame(), sequenceIds, columns, separator);
254 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
255 * java.lang.String, java.lang.String)
258 public void select(String sequenceIds, String columns, String sep)
260 selectIn(getDefaultTargetFrame(), sequenceIds, columns, sep);
266 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
267 * java.lang.String, java.lang.String)
270 public void selectIn(AlignFrame alf, String sequenceIds, String columns)
272 selectIn(alf, sequenceIds, columns, separator);
278 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
279 * java.lang.String, java.lang.String, java.lang.String)
282 public void selectIn(final AlignFrame alf, String sequenceIds,
283 String columns, String sep)
285 if (sep == null || sep.length() == 0)
294 .errPrintln("Selecting region using separator string '"
299 String[] ids = separatorListToArray(sequenceIds, sep);
300 String[] cols = separatorListToArray(columns, sep);
301 final SequenceGroup sel = new SequenceGroup();
302 final ColumnSelection csel = new ColumnSelection();
303 AlignmentI al = alf.viewport.getAlignment();
304 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
305 alf.viewport.getAlignment().getSequencesArray());
306 int start = 0, end = al.getWidth(), alw = al.getWidth();
307 boolean seqsfound = true;
308 if (ids != null && ids.length > 0)
311 for (int i = 0; i < ids.length; i++)
313 if (ids[i].trim().length() == 0)
317 SequenceI sq = matcher.findIdMatch(ids[i]);
321 sel.addSequence(sq, false);
325 boolean inseqpos = false;
326 if (cols != null && cols.length > 0)
328 boolean seset = false;
329 for (int i = 0; i < cols.length; i++)
331 String cl = cols[i].trim();
332 if (cl.length() == 0)
337 if ((p = cl.indexOf("-")) > -1)
339 int from = -1, to = -1;
342 from = Integer.valueOf(cl.substring(0, p)).intValue();
344 } catch (NumberFormatException ex)
346 jalview.bin.Console.errPrintln(
347 "ERROR: Couldn't parse first integer in range element column selection string '"
348 + cl + "' - format is 'from-to'");
353 to = Integer.valueOf(cl.substring(p + 1)).intValue();
355 } catch (NumberFormatException ex)
357 jalview.bin.Console.errPrintln(
358 "ERROR: Couldn't parse second integer in range element column selection string '"
359 + cl + "' - format is 'from-to'");
362 if (from >= 0 && to >= 0)
379 // comment to prevent range extension
389 for (int r = from; r <= to; r++)
391 if (r >= 0 && r < alw)
398 jalview.bin.Console.errPrintln("Range '" + cl
399 + "' deparsed as [" + from + "," + to + "]");
404 jalview.bin.Console.errPrintln("ERROR: Invalid Range '" + cl
405 + "' deparsed as [" + from + "," + to + "]");
413 r = Integer.valueOf(cl).intValue();
415 } catch (NumberFormatException ex)
417 if (cl.toLowerCase(Locale.ROOT).equals("sequence"))
419 // we are in the dataset sequence's coordinate frame.
424 jalview.bin.Console.errPrintln(
425 "ERROR: Couldn't parse integer from point selection element of column selection string '"
430 if (r >= 0 && r <= alw)
440 // comment to prevent range extension
453 jalview.bin.Console.errPrintln("Point selection '" + cl
454 + "' deparsed as [" + r + "]");
460 .errPrintln("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)
943 jalview.bin.Console.errPrintln(
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 jalview.bin.Console.errPrintln("Added a mouseover listener for "
956 + ((af == null) ? "All frames"
958 + af.getAlignViewport().getSequenceSetId()));
959 jalview.bin.Console.errPrintln("There are now "
960 + javascriptListeners.size() + " 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)
990 jalview.bin.Console.errPrintln(
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 jalview.bin.Console.errPrintln("Added a selection listener for "
1003 + ((af == null) ? "All frames"
1005 + af.getAlignViewport().getSequenceSetId()));
1006 jalview.bin.Console.errPrintln("There are now "
1007 + javascriptListeners.size() + " 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)
1030 jalview.bin.Console.errPrintln(
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);
1043 .errPrintln("Added a javascript structure viewer listener '"
1045 jalview.bin.Console.errPrintln("There are now "
1046 + javascriptListeners.size() + " 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);
1092 .errPrintln("Removed listener '" + listener + "'");
1102 jalview.bin.Console.errPrintln("There are now "
1103 + javascriptListeners.size() + " listeners in total.");
1110 jalview.bin.Console.errPrintln("Applet " + getName() + " stop().");
1115 public void destroy()
1117 jalview.bin.Console.errPrintln("Applet " + getName() + " destroy().");
1121 private void tidyUp()
1124 if (currentAlignFrame != null && currentAlignFrame.viewport != null
1125 && currentAlignFrame.viewport.applet != null)
1127 AlignViewport av = currentAlignFrame.viewport;
1128 currentAlignFrame.closeMenuItem_actionPerformed();
1130 currentAlignFrame = null;
1132 if (javascriptListeners != null)
1134 while (javascriptListeners.size() > 0)
1136 jalview.javascript.JSFunctionExec mol = javascriptListeners
1138 javascriptListeners.removeElement(mol);
1139 if (mol instanceof SelectionListener)
1141 StructureSelectionManager.getStructureSelectionManager(this)
1142 .removeSelectionListener((SelectionListener) mol);
1146 StructureSelectionManager.getStructureSelectionManager(this)
1147 .removeStructureViewerListener(mol, null);
1152 if (jsFunctionExec != null)
1154 jsFunctionExec.stopQueue();
1155 jsFunctionExec.jvlite = null;
1157 initialAlignFrame = null;
1158 jsFunctionExec = null;
1159 javascriptListeners = null;
1160 StructureSelectionManager.release(this);
1163 private jalview.javascript.JSFunctionExec jsFunctionExec;
1168 * @see jalview.bin.JalviewLiteJsApi#mouseOverStructure(java.lang.String,
1169 * java.lang.String, java.lang.String)
1172 public void mouseOverStructure(final String pdbResNum, final String chain,
1173 final String pdbfile)
1175 final StructureSelectionManagerProvider me = this;
1176 java.awt.EventQueue.invokeLater(new Runnable()
1183 StructureSelectionManager.getStructureSelectionManager(me)
1184 .mouseOverStructure(Integer.valueOf(pdbResNum).intValue(),
1189 .println("mouseOver for '" + pdbResNum + "' in chain '"
1190 + chain + "' in structure '" + pdbfile + "'");
1192 } catch (NumberFormatException e)
1195 .errPrintln("Ignoring invalid residue number string '"
1207 * jalview.bin.JalviewLiteJsApi#scrollViewToIn(jalview.appletgui.AlignFrame,
1208 * java.lang.String, java.lang.String)
1211 public void scrollViewToIn(final AlignFrame alf, final String topRow,
1212 final String leftHandColumn)
1214 java.awt.EventQueue.invokeLater(new Runnable()
1221 alf.scrollTo(Integer.valueOf(topRow).intValue(),
1222 Integer.valueOf(leftHandColumn).intValue());
1224 } catch (Exception ex)
1227 .errPrintln("Couldn't parse integer arguments (topRow='"
1228 + topRow + "' and leftHandColumn='"
1229 + leftHandColumn + "')");
1230 ex.printStackTrace();
1240 * jalview.javascript.JalviewLiteJsApi#scrollViewToRowIn(jalview.appletgui
1241 * .AlignFrame, java.lang.String)
1244 public void scrollViewToRowIn(final AlignFrame alf, final String topRow)
1247 java.awt.EventQueue.invokeLater(new Runnable()
1254 alf.scrollToRow(Integer.valueOf(topRow).intValue());
1256 } catch (Exception ex)
1259 .errPrintln("Couldn't parse integer arguments (topRow='"
1261 ex.printStackTrace();
1272 * jalview.javascript.JalviewLiteJsApi#scrollViewToColumnIn(jalview.appletgui
1273 * .AlignFrame, java.lang.String)
1276 public void scrollViewToColumnIn(final AlignFrame alf,
1277 final String leftHandColumn)
1279 java.awt.EventQueue.invokeLater(new Runnable()
1287 alf.scrollToColumn(Integer.valueOf(leftHandColumn).intValue());
1289 } catch (Exception ex)
1291 jalview.bin.Console.errPrintln(
1292 "Couldn't parse integer arguments (leftHandColumn='"
1293 + leftHandColumn + "')");
1294 ex.printStackTrace();
1301 // //////////////////////////////////////////////
1302 // //////////////////////////////////////////////
1304 public static int lastFrameX = 200;
1306 public static int lastFrameY = 200;
1308 boolean fileFound = true;
1310 String file = "No file";
1312 String file2 = null;
1314 Button launcher = new Button(
1315 MessageManager.getString("label.start_jalview"));
1318 * The currentAlignFrame is static, it will change if and when the user
1319 * selects a new window. Note that it will *never* point back to the embedded
1320 * AlignFrame if the applet is started as embedded on the page and then
1321 * afterwards a new view is created.
1323 public AlignFrame currentAlignFrame = null;
1326 * This is the first frame to be displayed, and does not change. API calls
1327 * will default to this instance if currentAlignFrame is null.
1329 AlignFrame initialAlignFrame = null;
1331 boolean embedded = false;
1333 private boolean checkForJmol = true;
1335 private boolean checkedForJmol = false; // ensure we don't check for jmol
1337 // every time the app is re-inited
1339 public boolean jmolAvailable = false;
1341 private boolean alignPdbStructures = false;
1344 * use an external structure viewer exclusively (no jmols or mc_views will be
1345 * opened by JalviewLite itself)
1347 public boolean useXtrnalSviewer = false;
1349 public static boolean debug = false;
1351 static String builddate = null, version = null, installation = null;
1353 private static void initBuildDetails()
1355 if (builddate == null)
1357 builddate = "unknown";
1359 installation = "applet";
1360 java.net.URL url = JalviewLite.class
1361 .getResource("/.build_properties");
1366 BufferedReader reader = new BufferedReader(
1367 new InputStreamReader(HttpUtils.openStream(url)));
1369 while ((line = reader.readLine()) != null)
1371 if (line.indexOf("VERSION") > -1)
1373 version = line.substring(line.indexOf("=") + 1);
1375 if (line.indexOf("BUILD_DATE") > -1)
1377 builddate = line.substring(line.indexOf("=") + 1);
1379 if (line.indexOf("INSTALLATION") > -1)
1381 installation = line.substring(line.indexOf("=") + 1);
1384 } catch (Exception ex)
1386 ex.printStackTrace();
1392 public static String getBuildDate()
1398 public static String getInstallation()
1401 return installation;
1404 public static String getVersion()
1410 // public JSObject scriptObject = null;
1413 * init method for Jalview Applet
1418 debug = TRUE.equalsIgnoreCase(getParameter("debug"));
1423 jalview.bin.Console.errPrintln("Applet context is '"
1424 + getAppletContext().getClass().toString() + "'");
1426 JSObject scriptObject = JSObject.getWindow(this);
1427 if (debug && scriptObject != null)
1430 .errPrintln("Applet has Javascript callback support.");
1433 } catch (Exception ex)
1435 jalview.bin.Console.errPrintln(
1436 "Warning: No JalviewLite javascript callbacks available.");
1439 ex.printStackTrace();
1445 jalview.bin.Console.errPrintln("JalviewLite Version " + getVersion());
1446 jalview.bin.Console.errPrintln("Build Date : " + getBuildDate());
1447 jalview.bin.Console.errPrintln("Installation : " + getInstallation());
1449 String externalsviewer = getParameter("externalstructureviewer");
1450 if (externalsviewer != null)
1452 useXtrnalSviewer = externalsviewer.trim().toLowerCase(Locale.ROOT)
1456 * if true disable the check for jmol
1458 String chkforJmol = getParameter("nojmol");
1459 if (chkforJmol != null)
1461 checkForJmol = !chkforJmol.equals(TRUE);
1464 * get the separator parameter if present
1466 String sep = getParameter("separator");
1469 if (sep.length() > 0)
1475 .errPrintln("Separator set to '" + separator + "'");
1480 throw new Error(MessageManager
1481 .getString("error.invalid_separator_parameter"));
1487 String param = getParameter("RGB");
1493 r = Integer.parseInt(param.substring(0, 2), 16);
1494 g = Integer.parseInt(param.substring(2, 4), 16);
1495 b = Integer.parseInt(param.substring(4, 6), 16);
1496 } catch (Exception ex)
1503 param = getParameter("label");
1506 launcher.setLabel(param);
1509 setBackground(new Color(r, g, b));
1511 file = getParameter("file");
1515 // Maybe the sequences are added as parameters
1516 StringBuffer data = new StringBuffer("PASTE");
1518 while ((file = getParameter("sequence" + i)) != null)
1520 data.append(file.toString() + "\n");
1523 if (data.length() > 5)
1525 file = data.toString();
1528 if (getDefaultParameter("enableSplitFrame", true))
1530 file2 = getParameter("file2");
1533 embedded = TRUE.equalsIgnoreCase(getParameter("embedded"));
1536 LoadingThread loader = new LoadingThread(file, file2, this);
1539 else if (file != null)
1542 * Start the applet immediately or show a button to start it
1544 if (FALSE.equalsIgnoreCase(getParameter("showbutton")))
1546 LoadingThread loader = new LoadingThread(file, file2, this);
1552 launcher.addActionListener(new java.awt.event.ActionListener()
1555 public void actionPerformed(ActionEvent e)
1557 LoadingThread loader = new LoadingThread(file, file2,
1566 // jalview initialisation with no alignment. loadAlignment() method can
1567 // still be called to open new alignments.
1574 private void initLiveConnect()
1576 // try really hard to get the liveConnect thing working
1577 boolean notFailed = false;
1579 while (!notFailed && tries < 10)
1584 .errPrintln("LiveConnect request thread going to sleep.");
1588 Thread.sleep(700 * (1 + tries));
1589 } catch (InterruptedException q)
1596 .errPrintln("LiveConnect request thread woken up.");
1600 JSObject scriptObject = JSObject.getWindow(this);
1601 if (scriptObject.eval("navigator") != null)
1605 } catch (Exception jsex)
1607 jalview.bin.Console.errPrintln("Attempt " + tries
1608 + " to access LiveConnect javascript failed.");
1613 private void callInitCallback()
1615 String initjscallback = getParameter("oninit");
1616 if (initjscallback == null)
1620 initjscallback = initjscallback.trim();
1621 if (initjscallback.length() > 0)
1623 JSObject scriptObject = null;
1626 scriptObject = JSObject.getWindow(this);
1627 } catch (Exception ex)
1631 // try really hard to let the browser plugin know we want liveconnect
1634 if (scriptObject != null)
1638 // do onInit with the JS executor thread
1639 new JSFunctionExec(this).executeJavascriptFunction(true,
1640 initjscallback, null,
1641 "Calling oninit callback '" + initjscallback + "'.");
1642 } catch (Exception e)
1645 .errPrintln("Exception when executing _oninit callback '"
1646 + initjscallback + "'.");
1647 e.printStackTrace();
1652 jalview.bin.Console.errPrintln("Not executing _oninit callback '"
1653 + initjscallback + "' - no scripting allowed.");
1659 * Initialises and displays a new java.awt.Frame
1662 * java.awt.Frame to be displayed
1664 * title of new frame
1666 * width if new frame
1668 * height of new frame
1670 public static void addFrame(final Frame frame, String title, int width,
1673 frame.setLocation(lastFrameX, lastFrameY);
1676 frame.setSize(width, height);
1677 frame.setTitle(title);
1678 frame.addWindowListener(new WindowAdapter()
1681 public void windowClosing(WindowEvent e)
1683 if (frame instanceof AlignFrame)
1685 AlignViewport vp = ((AlignFrame) frame).viewport;
1686 ((AlignFrame) frame).closeMenuItem_actionPerformed();
1687 if (vp.applet.currentAlignFrame == frame)
1689 vp.applet.currentAlignFrame = null;
1697 if (frame instanceof EmbmenuFrame)
1699 ((EmbmenuFrame) frame).destroyMenus();
1701 frame.setMenuBar(null);
1706 public void windowActivated(WindowEvent e)
1708 if (frame instanceof AlignFrame)
1710 ((AlignFrame) frame).viewport.applet.currentAlignFrame = (AlignFrame) frame;
1713 jalview.bin.Console.errPrintln("Activated window " + frame);
1717 super.windowActivated(e);
1720 * Probably not necessary to do this - see TODO above. (non-Javadoc)
1723 * java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent
1726 * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
1727 * frame) { currentAlignFrame = null; if (debug) {
1728 * jalview.bin.Console.errPrintln("Deactivated window "+frame); } }
1729 * super.windowDeactivated(e); }
1732 frame.setVisible(true);
1736 * This paints the background surrounding the "Launch Jalview button" <br>
1738 * If file given in parameter not found, displays error message
1744 public void paint(Graphics g)
1748 g.setColor(new Color(200, 200, 200));
1749 g.setColor(Color.cyan);
1750 g.fillRect(0, 0, getSize().width, getSize().height);
1751 g.setColor(Color.red);
1753 MessageManager.getString("label.jalview_cannot_open_file"), 5,
1755 g.drawString("\"" + file + "\"", 5, 30);
1759 g.setColor(Color.black);
1760 g.setFont(new Font("Arial", Font.BOLD, 24));
1761 g.drawString(MessageManager.getString("label.jalview_applet"), 50,
1762 getSize().height / 2 - 30);
1763 g.drawString(MessageManager.getString("label.loading_data") + "...",
1764 50, getSize().height / 2);
1769 * get all components associated with the applet of the given type
1774 public Vector getAppletWindow(Class class1)
1776 Vector wnds = new Vector();
1777 Component[] cmp = getComponents();
1780 for (int i = 0; i < cmp.length; i++)
1782 if (class1.isAssignableFrom(cmp[i].getClass()))
1784 wnds.addElement(cmp);
1791 class LoadJmolThread extends Thread
1793 private boolean running = false;
1798 if (running || checkedForJmol)
1807 if (!System.getProperty("java.version").startsWith("1.1"))
1809 Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
1810 jmolAvailable = true;
1814 jalview.bin.Console.outPrintln(
1815 "Jmol not available - Using mc_view for structures");
1817 } catch (java.lang.ClassNotFoundException ex)
1823 jmolAvailable = false;
1826 jalview.bin.Console.errPrintln(
1827 "Skipping Jmol check. Will use mc_view (probably)");
1830 checkedForJmol = true;
1834 public boolean notFinished()
1836 return running || !checkedForJmol;
1840 class LoadingThread extends Thread
1843 * State variable: protocol for access to file source
1845 DataSourceType protocol;
1847 String _file; // alignment file or URL spec
1849 String _file2; // second alignment file or URL spec
1853 private void dbgMsg(String msg)
1855 if (JalviewLite.debug)
1857 jalview.bin.Console.errPrintln(msg);
1862 * update the protocol state variable for accessing the datasource located
1866 * @return possibly updated datasource string
1868 public String resolveFileProtocol(String path)
1873 if (path.startsWith("PASTE"))
1875 protocol = DataSourceType.PASTE;
1876 return path.substring(5);
1882 if (path.indexOf("://") != -1)
1884 protocol = DataSourceType.URL;
1889 * try relative to document root
1891 URL documentBase = getDocumentBase();
1892 String withDocBase = resolveUrlForLocalOrAbsolute(path, documentBase);
1893 if (HttpUtils.isValidUrl(withDocBase))
1897 jalview.bin.Console.errPrintln("Prepended document base '"
1898 + documentBase + "' to make: '" + withDocBase + "'");
1900 protocol = DataSourceType.URL;
1905 * try relative to codebase (if different to document base)
1907 URL codeBase = getCodeBase();
1908 String withCodeBase = applet.resolveUrlForLocalOrAbsolute(path,
1910 if (!withCodeBase.equals(withDocBase)
1911 && HttpUtils.isValidUrl(withCodeBase))
1913 protocol = DataSourceType.URL;
1916 jalview.bin.Console.errPrintln("Prepended codebase '" + codeBase
1917 + "' to make: '" + withCodeBase + "'");
1919 return withCodeBase;
1923 * try locating by classloader; try this last so files in the directory
1924 * are resolved using document base
1926 if (inArchive(path))
1928 protocol = DataSourceType.CLASSLOADER;
1933 public LoadingThread(String file, String file2, JalviewLite _applet)
1936 this._file2 = file2;
1943 LoadJmolThread jmolchecker = new LoadJmolThread();
1944 jmolchecker.start();
1945 while (jmolchecker.notFinished())
1947 // wait around until the Jmol check is complete.
1951 } catch (Exception e)
1956 // applet.callInitCallback();
1960 * Load the alignment and any related files as specified by applet
1963 private void startLoading()
1965 dbgMsg("Loading thread started with:\n>>file\n" + _file
1968 dbgMsg("Loading started.");
1970 AlignFrame newAlignFrame = readAlignment(_file);
1971 AlignFrame newAlignFrame2 = readAlignment(_file2);
1972 if (newAlignFrame != null)
1974 addToDisplay(newAlignFrame, newAlignFrame2);
1975 loadTree(newAlignFrame);
1977 loadScoreFile(newAlignFrame);
1979 loadFeatures(newAlignFrame);
1981 loadAnnotations(newAlignFrame);
1983 loadJnetFile(newAlignFrame);
1985 loadPdbFiles(newAlignFrame);
1990 applet.remove(launcher);
1997 * Add an AlignFrame to the display; or if two are provided, a SplitFrame.
2002 public void addToDisplay(AlignFrame af, AlignFrame af2)
2006 AlignmentI al1 = af.viewport.getAlignment();
2007 AlignmentI al2 = af2.viewport.getAlignment();
2008 AlignmentI cdna = al1.isNucleotide() ? al1 : al2;
2009 AlignmentI prot = al1.isNucleotide() ? al2 : al1;
2010 if (AlignmentUtils.mapProteinAlignmentToCdna(prot, cdna))
2013 SplitFrame sf = new SplitFrame(af, af2);
2014 sf.addToDisplay(embedded, JalviewLite.this);
2019 String msg = "Could not map any sequence in " + af2.getTitle()
2021 + (al1.isNucleotide() ? "protein product" : "cDNA")
2022 + " for " + af.getTitle();
2023 jalview.bin.Console.errPrintln(msg);
2027 af.addToDisplay(embedded);
2031 * Read the alignment file (from URL, text 'paste', or archive by
2036 protected AlignFrame readAlignment(String fileParam)
2038 if (fileParam == null)
2042 String resolvedFile = resolveFileProtocol(fileParam);
2043 AlignmentI al = null;
2046 FileFormatI format = new IdentifyFile().identify(resolvedFile,
2048 dbgMsg("File identified as '" + format + "'");
2049 al = new AppletFormatAdapter().readFile(resolvedFile, protocol,
2051 if ((al != null) && (al.getHeight() > 0))
2053 dbgMsg("Successfully loaded file.");
2054 al.setDataset(null);
2055 AlignFrame newAlignFrame = new AlignFrame(al, applet,
2056 resolvedFile, embedded, false);
2057 newAlignFrame.setTitle(resolvedFile);
2058 if (initialAlignFrame == null)
2060 initialAlignFrame = newAlignFrame;
2062 // update the focus.
2063 currentAlignFrame = newAlignFrame;
2065 if (protocol == DataSourceType.PASTE)
2067 newAlignFrame.setTitle(MessageManager
2068 .formatMessage("label.sequences_from", new Object[]
2069 { applet.getDocumentBase().toString() }));
2072 newAlignFrame.statusBar.setText(MessageManager.formatMessage(
2073 "label.successfully_loaded_file", new Object[]
2076 return newAlignFrame;
2078 } catch (java.io.IOException ex)
2080 dbgMsg("File load exception.");
2081 ex.printStackTrace();
2086 FileParse fp = new FileParse(resolvedFile, protocol);
2088 dbgMsg(">>>Dumping contents of '" + resolvedFile + "' " + "("
2090 while ((ln = fp.nextLine()) != null)
2094 dbgMsg(">>>Dump finished.");
2095 } catch (Exception e)
2097 jalview.bin.Console.errPrintln(
2098 "Exception when trying to dump the content of the file parameter.");
2099 e.printStackTrace();
2107 * Load PDBFiles if any specified by parameter(s). Returns true if loaded,
2113 protected boolean loadPdbFiles(AlignFrame alignFrame)
2115 boolean result = false;
2117 * <param name="alignpdbfiles" value="false/true"/> Undocumented for 2.6 -
2118 * related to JAL-434
2121 applet.setAlignPdbStructures(
2122 getDefaultParameter("alignpdbfiles", false));
2124 * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
2127 * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
2129 * <param name="PDBfile3" value="1q0o Q45135_9MICO">
2132 int pdbFileCount = 0;
2133 // Accumulate pdbs here if they are heading for the same view (if
2134 // alignPdbStructures is true)
2135 Vector pdbs = new Vector();
2136 // create a lazy matcher if we're asked to
2137 jalview.analysis.SequenceIdMatcher matcher = (applet
2138 .getDefaultParameter("relaxedidmatch", false))
2139 ? new jalview.analysis.SequenceIdMatcher(
2140 alignFrame.getAlignViewport().getAlignment()
2141 .getSequencesArray())
2147 if (pdbFileCount > 0)
2149 param = applet.getParameter("PDBFILE" + pdbFileCount);
2153 param = applet.getParameter("PDBFILE");
2158 PDBEntry pdb = new PDBEntry();
2161 SequenceI[] seqs = null;
2162 String[] chains = null;
2164 StringTokenizer st = new StringTokenizer(param, " ");
2166 if (st.countTokens() < 2)
2168 String sequence = applet.getParameter("PDBSEQ");
2169 if (sequence != null)
2171 seqs = new SequenceI[] { matcher == null
2172 ? (Sequence) alignFrame.getAlignViewport()
2173 .getAlignment().findName(sequence)
2174 : matcher.findIdMatch(sequence) };
2180 param = st.nextToken();
2181 List<SequenceI> tmp = new ArrayList<>();
2182 List<String> tmp2 = new ArrayList<>();
2184 while (st.hasMoreTokens())
2186 seqstring = st.nextToken();
2187 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
2188 if (st2.countTokens() > 1)
2190 // This is the chain
2191 tmp2.add(st2.nextToken());
2192 seqstring = st2.nextToken();
2194 tmp.add(matcher == null
2195 ? (Sequence) alignFrame.getAlignViewport()
2196 .getAlignment().findName(seqstring)
2197 : matcher.findIdMatch(seqstring));
2200 seqs = tmp.toArray(new SequenceI[tmp.size()]);
2201 if (tmp2.size() == tmp.size())
2203 chains = tmp2.toArray(new String[tmp2.size()]);
2206 param = resolveFileProtocol(param);
2207 // TODO check JAL-357 for files in a jar (CLASSLOADER)
2212 for (int i = 0; i < seqs.length; i++)
2214 if (seqs[i] != null)
2216 ((Sequence) seqs[i]).addPDBId(pdb);
2217 StructureSelectionManager
2218 .getStructureSelectionManager(applet)
2219 .registerPDBEntry(pdb);
2223 if (JalviewLite.debug)
2225 // this may not really be a problem but we give a warning
2227 jalview.bin.Console.errPrintln(
2228 "Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
2234 if (!alignPdbStructures)
2236 alignFrame.newStructureView(applet, pdb, seqs, chains,
2241 pdbs.addElement(new Object[] { pdb, seqs, chains, protocol });
2247 } while (param != null || pdbFileCount < 10);
2248 if (pdbs.size() > 0)
2250 SequenceI[][] seqs = new SequenceI[pdbs.size()][];
2251 PDBEntry[] pdb = new PDBEntry[pdbs.size()];
2252 String[][] chains = new String[pdbs.size()][];
2253 String[] protocols = new String[pdbs.size()];
2255 pdbsiSize = pdbs.size(); pdbsi < pdbsiSize; pdbsi++)
2257 Object[] o = (Object[]) pdbs.elementAt(pdbsi);
2258 pdb[pdbsi] = (PDBEntry) o[0];
2259 seqs[pdbsi] = (SequenceI[]) o[1];
2260 chains[pdbsi] = (String[]) o[2];
2261 protocols[pdbsi] = (String) o[3];
2263 alignFrame.alignedStructureView(applet, pdb, seqs, chains,
2271 * Load in a Jnetfile if specified by parameter. Returns true if loaded,
2277 protected boolean loadJnetFile(AlignFrame alignFrame)
2279 boolean result = false;
2280 String param = applet.getParameter("jnetfile");
2283 // jnet became jpred around 2016
2284 param = applet.getParameter("jpredfile");
2290 param = resolveFileProtocol(param);
2291 JPredFile predictions = new JPredFile(param, protocol);
2292 JnetAnnotationMaker.add_annotation(predictions,
2293 alignFrame.viewport.getAlignment(), 0, false);
2294 // false == do not add sequence profile from concise output
2296 alignFrame.viewport.getAlignment().setupJPredAlignment();
2298 alignFrame.alignPanel.fontChanged();
2299 alignFrame.alignPanel.setScrollValues(0, 0);
2301 } catch (Exception ex)
2303 ex.printStackTrace();
2310 * Load annotations if specified by parameter. Returns true if loaded, else
2316 protected boolean loadAnnotations(AlignFrame alignFrame)
2318 boolean result = false;
2319 String param = applet.getParameter("annotations");
2322 param = resolveFileProtocol(param);
2324 if (new AnnotationFile().annotateAlignmentView(alignFrame.viewport,
2327 alignFrame.alignPanel.fontChanged();
2328 alignFrame.alignPanel.setScrollValues(0, 0);
2333 jalview.bin.Console.errPrintln(
2334 "Annotations were not added from annotation file '"
2342 * Load features file and view settings as specified by parameters. Returns
2343 * true if features were loaded, else false.
2348 protected boolean loadFeatures(AlignFrame alignFrame)
2350 boolean result = false;
2351 // ///////////////////////////
2352 // modify display of features
2353 // we do this before any features have been loaded, ensuring any hidden
2354 // groups are hidden when features first displayed
2356 // hide specific groups
2358 String param = applet.getParameter("hidefeaturegroups");
2361 alignFrame.setFeatureGroupState(separatorListToArray(param), false);
2362 // applet.setFeatureGroupStateOn(newAlignFrame, param, false);
2364 // show specific groups
2365 param = applet.getParameter("showfeaturegroups");
2368 alignFrame.setFeatureGroupState(separatorListToArray(param), true);
2369 // applet.setFeatureGroupStateOn(newAlignFrame, param, true);
2371 // and now load features
2372 param = applet.getParameter("features");
2375 param = resolveFileProtocol(param);
2377 result = alignFrame.parseFeaturesFile(param, protocol);
2380 param = applet.getParameter("showFeatureSettings");
2381 if (param != null && param.equalsIgnoreCase(TRUE))
2383 alignFrame.viewport.setShowSequenceFeatures(true);
2384 new FeatureSettings(alignFrame.alignPanel);
2390 * Load a score file if specified by parameter. Returns true if file was
2391 * loaded, else false.
2395 protected boolean loadScoreFile(AlignFrame alignFrame)
2397 boolean result = false;
2398 String sScoreFile = applet.getParameter("scoreFile");
2399 if (sScoreFile != null && !"".equals(sScoreFile))
2405 jalview.bin.Console.errPrintln(
2406 "Attempting to load T-COFFEE score file from the scoreFile parameter");
2408 result = alignFrame.loadScoreFile(sScoreFile);
2411 jalview.bin.Console.errPrintln(
2412 "Failed to parse T-COFFEE parameter as a valid score file ('"
2413 + sScoreFile + "')");
2415 } catch (Exception e)
2417 System.err.printf("Cannot read score file: '%s'. Cause: %s \n",
2418 sScoreFile, e.getMessage());
2425 * Load a tree for the alignment if specified by parameter. Returns true if
2426 * a tree was loaded, else false.
2431 protected boolean loadTree(AlignFrame alignFrame)
2433 boolean result = false;
2434 String treeFile = applet.getParameter("tree");
2435 if (treeFile == null)
2437 treeFile = applet.getParameter("treeFile");
2440 if (treeFile != null)
2444 treeFile = resolveFileProtocol(treeFile);
2445 NewickFile fin = new NewickFile(treeFile, protocol);
2448 if (fin.getTree() != null)
2450 alignFrame.loadTree(fin, treeFile);
2452 dbgMsg("Successfully imported tree.");
2456 dbgMsg("Tree parameter did not resolve to a valid tree.");
2458 } catch (Exception ex)
2460 ex.printStackTrace();
2467 * Discovers whether the given file is in the Applet Archive
2473 boolean inArchive(String f)
2475 // This might throw a security exception in certain browsers
2476 // Netscape Communicator for instance.
2479 boolean rtn = (getClass().getResourceAsStream("/" + f) != null);
2482 jalview.bin.Console.errPrintln("Resource '" + f + "' was "
2483 + (rtn ? "" : "not ") + "located by classloader.");
2486 } catch (Exception ex)
2488 jalview.bin.Console.outPrintln(
2489 "Exception checking resources: " + f + " " + ex);
2496 * @return the default alignFrame acted on by the public applet methods. May
2497 * return null with an error message on System.err indicating the
2500 public AlignFrame getDefaultTargetFrame()
2502 if (currentAlignFrame != null)
2504 return currentAlignFrame;
2506 if (initialAlignFrame != null)
2508 return initialAlignFrame;
2510 jalview.bin.Console.errPrintln(
2511 "Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
2516 * separator used for separatorList
2518 protected String separator = "" + ((char) 0x00AC); // the default used to be
2519 // '|' but many sequence
2520 // IDS include pipes.
2523 * set to enable the URL based javascript execution mechanism
2525 public boolean jsfallbackEnabled = false;
2528 * parse the string into a list
2531 * @return elements separated by separator
2533 public String[] separatorListToArray(String list)
2535 return separatorListToArray(list, separator);
2539 * parse the string into a list
2543 * @return elements separated by separator
2545 public static String[] separatorListToArray(String list, String separator)
2547 // TODO use StringUtils version (slightly different...)
2548 int seplen = separator.length();
2549 if (list == null || list.equals("") || list.equals(separator))
2553 java.util.Vector jv = new Vector();
2555 while ((pos = list.indexOf(separator, cp)) > cp)
2557 jv.addElement(list.substring(cp, pos));
2560 if (cp < list.length())
2562 String c = list.substring(cp);
2563 if (!c.equals(separator))
2570 String[] v = new String[jv.size()];
2571 for (int i = 0; i < v.length; i++)
2573 v[i] = (String) jv.elementAt(i);
2575 jv.removeAllElements();
2578 jalview.bin.Console.errPrintln("Array from '" + separator
2579 + "' separated List:\n" + v.length);
2580 for (int i = 0; i < v.length; i++)
2582 jalview.bin.Console.errPrintln("item " + i + " '" + v[i] + "'");
2589 jalview.bin.Console.errPrintln(
2590 "Empty Array from '" + separator + "' separated List");
2596 * concatenate the list with separator
2599 * @return concatenated string
2601 public String arrayToSeparatorList(String[] list)
2603 return arrayToSeparatorList(list, separator);
2607 * concatenate the list with separator
2611 * @return concatenated string
2613 public static String arrayToSeparatorList(String[] list, String separator)
2615 // TODO use StringUtils version
2616 StringBuffer v = new StringBuffer();
2617 if (list != null && list.length > 0)
2619 for (int i = 0, iSize = list.length; i < iSize; i++)
2621 if (list[i] != null)
2625 v.append(separator);
2633 .println("Returning '" + separator + "' separated List:\n");
2634 jalview.bin.Console.errPrintln(v);
2636 return v.toString();
2640 jalview.bin.Console.errPrintln(
2641 "Returning empty '" + separator + "' separated List\n");
2643 return "" + separator;
2649 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroups()
2652 public String getFeatureGroups()
2654 String lst = arrayToSeparatorList(
2655 getDefaultTargetFrame().getFeatureGroups());
2663 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOn(jalview.appletgui.AlignFrame
2667 public String getFeatureGroupsOn(AlignFrame alf)
2669 String lst = arrayToSeparatorList(alf.getFeatureGroups());
2676 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfState(boolean)
2679 public String getFeatureGroupsOfState(boolean visible)
2681 return arrayToSeparatorList(
2682 getDefaultTargetFrame().getFeatureGroupsOfState(visible));
2689 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfStateOn(jalview.appletgui
2690 * .AlignFrame, boolean)
2693 public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
2695 return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
2701 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupStateOn(jalview.appletgui.
2702 * AlignFrame, java.lang.String, boolean)
2705 public void setFeatureGroupStateOn(final AlignFrame alf,
2706 final String groups, boolean state)
2708 final boolean st = state;// !(state==null || state.equals("") ||
2709 // state.toLowerCase(Locale.ROOT).equals("false"));
2710 java.awt.EventQueue.invokeLater(new Runnable()
2715 alf.setFeatureGroupState(separatorListToArray(groups), st);
2723 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupState(java.lang.String,
2727 public void setFeatureGroupState(String groups, boolean state)
2729 setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
2735 * @see jalview.bin.JalviewLiteJsApi#getSeparator()
2738 public String getSeparator()
2746 * @see jalview.bin.JalviewLiteJsApi#setSeparator(java.lang.String)
2749 public void setSeparator(String separator)
2751 if (separator == null || separator.length() < 1)
2754 separator = "" + ((char) 0x00AC);
2756 this.separator = separator;
2760 .errPrintln("Default Separator now: '" + separator + "'");
2765 * get boolean value of applet parameter 'name' and return default if
2766 * parameter is not set
2771 * the value to return otherwise
2772 * @return true or false
2774 public boolean getDefaultParameter(String name, boolean def)
2777 if ((stn = getParameter(name)) == null)
2781 if (TRUE.equalsIgnoreCase(stn))
2791 * @see jalview.bin.JalviewLiteJsApi#addPdbFile(jalview.appletgui.AlignFrame,
2792 * java.lang.String, java.lang.String, java.lang.String)
2795 public boolean addPdbFile(AlignFrame alFrame, String sequenceId,
2796 String pdbEntryString, String pdbFile)
2798 return alFrame.addPdbFile(sequenceId, pdbEntryString, pdbFile);
2801 protected void setAlignPdbStructures(boolean alignPdbStructures)
2803 this.alignPdbStructures = alignPdbStructures;
2806 public boolean isAlignPdbStructures()
2808 return alignPdbStructures;
2814 // callInitCallback();
2817 private Hashtable<String, long[]> jshashes = new Hashtable<>();
2819 private Hashtable<String, Hashtable<String, String[]>> jsmessages = new Hashtable<>();
2821 public void setJsMessageSet(String messageclass, String viewId,
2822 String[] colcommands)
2824 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2827 msgset = new Hashtable<>();
2828 jsmessages.put(messageclass, msgset);
2830 msgset.put(viewId, colcommands);
2831 long[] l = new long[colcommands.length];
2832 for (int i = 0; i < colcommands.length; i++)
2834 l[i] = colcommands[i].hashCode();
2836 jshashes.put(messageclass + "|" + viewId, l);
2842 * @see jalview.bin.JalviewLiteJsApi#getJsMessage(java.lang.String,
2846 public String getJsMessage(String messageclass, String viewId)
2848 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2851 String[] msgs = msgset.get(viewId);
2854 for (int i = 0; i < msgs.length; i++)
2856 if (msgs[i] != null)
2868 public boolean isJsMessageSetChanged(String string, String string2,
2869 String[] colcommands)
2871 long[] l = jshashes.get(string + "|" + string2);
2872 if (l == null && colcommands != null)
2876 for (int i = 0; i < colcommands.length; i++)
2878 if (l[i] != colcommands[i].hashCode())
2886 private Vector jsExecQueue = new Vector();
2888 public Vector getJsExecQueue()
2893 public void setExecutor(JSFunctionExec jsFunctionExec2)
2895 jsFunctionExec = jsFunctionExec2;
2899 * return the given colour value parameter or the given default if parameter
2906 public Color getDefaultColourParameter(String colparam, Color defcolour)
2908 String colprop = getParameter(colparam);
2909 if (colprop == null || colprop.trim().length() == 0)
2913 Color col = ColorUtils.parseColourString(colprop);
2916 jalview.bin.Console.errPrintln("Couldn't parse '" + colprop
2917 + "' as a colour for " + colparam);
2919 return (col == null) ? defcolour : col;
2922 public void openJalviewHelpUrl()
2924 String helpUrl = getParameter("jalviewhelpurl");
2925 if (helpUrl == null || helpUrl.trim().length() < 5)
2927 helpUrl = "http://www.jalview.org/help.html";
2929 showURL(helpUrl, "HELP");
2933 * form a complete URL given a path to a resource and a reference location on
2937 * - an absolute path on the same server as localref or a document
2938 * located relative to localref
2940 * - a URL on the same server as url
2941 * @return a complete URL for the resource located by url
2943 private String resolveUrlForLocalOrAbsolute(String targetPath,
2946 String resolvedPath = "";
2947 if (targetPath.startsWith("/"))
2949 String codebase = localref.toString();
2950 String localfile = localref.getFile();
2951 resolvedPath = codebase.substring(0,
2952 codebase.length() - localfile.length()) + targetPath;
2953 return resolvedPath;
2957 * get URL path and strip off any trailing file e.g.
2958 * www.jalview.org/examples/index.html#applets?a=b is trimmed to
2959 * www.jalview.org/examples/
2961 String urlPath = localref.toString();
2962 String directoryPath = urlPath;
2963 int lastSeparator = directoryPath.lastIndexOf("/");
2964 if (lastSeparator > 0)
2966 directoryPath = directoryPath.substring(0, lastSeparator + 1);
2969 if (targetPath.startsWith("/"))
2972 * construct absolute URL to a file on the server - this is not allowed?
2974 // String localfile = localref.getFile();
2975 // resolvedPath = urlPath.substring(0,
2976 // urlPath.length() - localfile.length())
2978 resolvedPath = directoryPath + targetPath.substring(1);
2982 resolvedPath = directoryPath + targetPath;
2986 jalview.bin.Console.errPrintln(
2987 "resolveUrlForLocalOrAbsolute returning " + resolvedPath);
2989 return resolvedPath;
2993 * open a URL in the browser - resolving it according to relative refs and
2994 * coping with javascript: protocol if necessary.
2999 public void showURL(String url, String target)
3003 if (url.indexOf(":") == -1)
3005 // TODO: verify (Bas Vroling bug) prepend codebase or server URL to
3007 // Should really use docbase, not codebase.
3009 url = resolveUrlForLocalOrAbsolute(url,
3010 prepend = getDefaultParameter("resolvetocodebase", false)
3012 : getDocumentBase());
3015 jalview.bin.Console.errPrintln("Show url (prepended " + prepend
3016 + " - toggle resolvetocodebase if code/docbase resolution is wrong): "
3024 jalview.bin.Console.errPrintln("Show url: " + url);
3027 if (url.indexOf("javascript:") == 0)
3029 // no target for the javascript context
3030 getAppletContext().showDocument(new java.net.URL(url));
3034 getAppletContext().showDocument(new java.net.URL(url), target);
3036 } catch (Exception ex)
3038 ex.printStackTrace();
3043 * bind structures in a viewer to any matching sequences in an alignFrame (use
3044 * sequenceIds to limit scope of search to specific sequences)
3048 * @param sequenceIds
3049 * @return TODO: consider making an exception structure for indicating when
3050 * binding fails public SequenceStructureBinding
3051 * addStructureViewInstance( AlignFrame alFrame, Object viewer, String
3054 * if (sequenceIds != null && sequenceIds.length() > 0) { return
3055 * alFrame.addStructureViewInstance(viewer,
3056 * separatorListToArray(sequenceIds)); } else { return
3057 * alFrame.addStructureViewInstance(viewer, null); } // return null; }