2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentUtils;
24 import jalview.api.StructureSelectionManagerProvider;
25 import jalview.appletgui.AlignFrame;
26 import jalview.appletgui.AlignViewport;
27 import jalview.appletgui.EmbmenuFrame;
28 import jalview.appletgui.FeatureSettings;
29 import jalview.appletgui.SplitFrame;
30 import jalview.datamodel.Alignment;
31 import jalview.datamodel.AlignmentI;
32 import jalview.datamodel.AlignmentOrder;
33 import jalview.datamodel.ColumnSelection;
34 import jalview.datamodel.PDBEntry;
35 import jalview.datamodel.Sequence;
36 import jalview.datamodel.SequenceGroup;
37 import jalview.datamodel.SequenceI;
38 import jalview.io.AnnotationFile;
39 import jalview.io.AppletFormatAdapter;
40 import jalview.io.FileParse;
41 import jalview.io.IdentifyFile;
42 import jalview.io.JPredFile;
43 import jalview.io.JnetAnnotationMaker;
44 import jalview.io.NewickFile;
45 import jalview.javascript.JSFunctionExec;
46 import jalview.javascript.JalviewLiteJsApi;
47 import jalview.javascript.JsCallBack;
48 import jalview.javascript.MouseOverStructureListener;
49 import jalview.structure.SelectionListener;
50 import jalview.structure.StructureSelectionManager;
51 import jalview.util.HttpUtils;
52 import jalview.util.MessageManager;
54 import java.applet.Applet;
55 import java.awt.Button;
56 import java.awt.Color;
57 import java.awt.Component;
58 import java.awt.EventQueue;
60 import java.awt.Frame;
61 import java.awt.Graphics;
62 import java.awt.event.ActionEvent;
63 import java.awt.event.WindowAdapter;
64 import java.awt.event.WindowEvent;
65 import java.io.BufferedReader;
66 import java.io.InputStreamReader;
68 import java.util.ArrayList;
69 import java.util.Hashtable;
70 import java.util.List;
71 import java.util.StringTokenizer;
72 import java.util.Vector;
74 import netscape.javascript.JSObject;
77 * Jalview Applet. Runs in Java 1.18 runtime
80 * @version $Revision: 1.92 $
82 public class JalviewLite extends Applet implements
83 StructureSelectionManagerProvider, JalviewLiteJsApi
86 private static final String TRUE = "true";
88 private static final String FALSE = "false";
90 public StructureSelectionManager getStructureSelectionManager()
92 return StructureSelectionManager.getStructureSelectionManager(this);
95 // /////////////////////////////////////////
96 // The following public methods may be called
97 // externally, eg via javascript in HTML page
101 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences()
104 public String getSelectedSequences()
106 return getSelectedSequencesFrom(getDefaultTargetFrame());
112 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences(java.lang.String)
115 public String getSelectedSequences(String sep)
117 return getSelectedSequencesFrom(getDefaultTargetFrame(), sep);
124 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
128 public String getSelectedSequencesFrom(AlignFrame alf)
130 return getSelectedSequencesFrom(alf, separator); // ""+0x00AC);
137 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
138 * .AlignFrame, java.lang.String)
141 public String getSelectedSequencesFrom(AlignFrame alf, String sep)
143 StringBuffer result = new StringBuffer("");
144 if (sep == null || sep.length() == 0)
146 sep = separator; // "+0x00AC;
148 if (alf.viewport.getSelectionGroup() != null)
150 SequenceI[] seqs = alf.viewport.getSelectionGroup()
151 .getSequencesInOrder(alf.viewport.getAlignment());
153 for (int i = 0; i < seqs.length; i++)
155 result.append(seqs[i].getName());
160 return result.toString();
166 * @see jalview.bin.JalviewLiteJsApi#highlight(java.lang.String,
167 * java.lang.String, java.lang.String)
170 public void highlight(String sequenceId, String position,
171 String alignedPosition)
173 highlightIn(getDefaultTargetFrame(), sequenceId, position,
180 * @see jalview.bin.JalviewLiteJsApi#highlightIn(jalview.appletgui.AlignFrame,
181 * java.lang.String, java.lang.String, java.lang.String)
184 public void highlightIn(final AlignFrame alf, final String sequenceId,
185 final String position, final String alignedPosition)
187 // TODO: could try to highlight in all alignments if alf==null
188 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
189 alf.viewport.getAlignment().getSequencesArray());
190 final SequenceI sq = matcher.findIdMatch(sequenceId);
196 apos = new Integer(position).intValue();
198 } catch (NumberFormatException ex)
202 final StructureSelectionManagerProvider me = this;
203 final int pos = apos;
204 // use vamsas listener to broadcast to all listeners in scope
205 if (alignedPosition != null
206 && (alignedPosition.trim().length() == 0 || alignedPosition
207 .toLowerCase().indexOf("false") > -1))
209 java.awt.EventQueue.invokeLater(new Runnable()
214 StructureSelectionManager.getStructureSelectionManager(me)
215 .mouseOverVamsasSequence(sq, sq.findIndex(pos), null);
221 java.awt.EventQueue.invokeLater(new Runnable()
226 StructureSelectionManager.getStructureSelectionManager(me)
227 .mouseOverVamsasSequence(sq, pos, null);
237 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
241 public void select(String sequenceIds, String columns)
243 selectIn(getDefaultTargetFrame(), sequenceIds, columns, separator);
249 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
250 * java.lang.String, java.lang.String)
253 public void select(String sequenceIds, String columns, String sep)
255 selectIn(getDefaultTargetFrame(), sequenceIds, columns, sep);
261 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
262 * java.lang.String, java.lang.String)
265 public void selectIn(AlignFrame alf, String sequenceIds, String columns)
267 selectIn(alf, sequenceIds, columns, separator);
273 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
274 * java.lang.String, java.lang.String, java.lang.String)
277 public void selectIn(final AlignFrame alf, String sequenceIds,
278 String columns, String sep)
280 if (sep == null || sep.length() == 0)
288 System.err.println("Selecting region using separator string '"
293 String[] ids = separatorListToArray(sequenceIds, sep);
294 String[] cols = separatorListToArray(columns, sep);
295 final SequenceGroup sel = new SequenceGroup();
296 final ColumnSelection csel = new ColumnSelection();
297 AlignmentI al = alf.viewport.getAlignment();
298 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
299 alf.viewport.getAlignment().getSequencesArray());
300 int start = 0, end = al.getWidth(), alw = al.getWidth();
301 boolean seqsfound = true;
302 if (ids != null && ids.length > 0)
305 for (int i = 0; i < ids.length; i++)
307 if (ids[i].trim().length() == 0)
311 SequenceI sq = matcher.findIdMatch(ids[i]);
315 sel.addSequence(sq, false);
319 boolean inseqpos = false;
320 if (cols != null && cols.length > 0)
322 boolean seset = false;
323 for (int i = 0; i < cols.length; i++)
325 String cl = cols[i].trim();
326 if (cl.length() == 0)
331 if ((p = cl.indexOf("-")) > -1)
333 int from = -1, to = -1;
336 from = new Integer(cl.substring(0, p)).intValue();
338 } catch (NumberFormatException ex)
341 .println("ERROR: Couldn't parse first integer in range element column selection string '"
342 + cl + "' - format is 'from-to'");
347 to = new Integer(cl.substring(p + 1)).intValue();
349 } catch (NumberFormatException ex)
352 .println("ERROR: Couldn't parse second integer in range element column selection string '"
353 + cl + "' - format is 'from-to'");
356 if (from >= 0 && to >= 0)
373 // comment to prevent range extension
383 for (int r = from; r <= to; r++)
385 if (r >= 0 && r < alw)
392 System.err.println("Range '" + cl + "' deparsed as [" + from
398 System.err.println("ERROR: Invalid Range '" + cl
399 + "' deparsed as [" + from + "," + to + "]");
407 r = new Integer(cl).intValue();
409 } catch (NumberFormatException ex)
411 if (cl.toLowerCase().equals("sequence"))
413 // we are in the dataset sequence's coordinate frame.
419 .println("ERROR: Couldn't parse integer from point selection element of column selection string '"
424 if (r >= 0 && r <= alw)
434 // comment to prevent range extension
447 System.err.println("Point selection '" + cl
448 + "' deparsed as [" + r + "]");
453 System.err.println("ERROR: Invalid Point selection '" + cl
454 + "' deparsed as [" + r + "]");
461 // we only propagate the selection when it was the null selection, or the
462 // given sequences were found in the alignment.
463 if (inseqpos && sel.getSize() > 0)
465 // assume first sequence provides reference frame ?
466 SequenceI rs = sel.getSequenceAt(0);
467 start = rs.findIndex(start);
468 end = rs.findIndex(end);
471 List<Integer> cs = csel.getSelected();
472 // note - the following actually clears cs as well, since
473 // csel.getSelected returns a reference. Need to check if we need to
474 // have a concurrentModification exception thrown here
476 for (Integer selectedCol : cs)
478 csel.addElement(rs.findIndex(selectedCol));
482 sel.setStartRes(start);
484 EventQueue.invokeLater(new Runnable()
489 alf.select(sel, csel);
499 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignment(java.lang.
500 * String, java.lang.String)
503 public String getSelectedSequencesAsAlignment(String format, String suffix)
505 return getSelectedSequencesAsAlignmentFrom(getDefaultTargetFrame(),
513 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignmentFrom(jalview
514 * .appletgui.AlignFrame, java.lang.String, java.lang.String)
517 public String getSelectedSequencesAsAlignmentFrom(AlignFrame alf,
518 String format, String suffix)
522 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
523 if (alf.viewport.getSelectionGroup() != null)
525 // JBPNote: getSelectionAsNewSequence behaviour has changed - this
526 // method now returns a full copy of sequence data
527 // TODO consider using getSequenceSelection instead here
528 String reply = new AppletFormatAdapter().formatSequences(format,
529 new Alignment(alf.viewport.getSelectionAsNewSequence()),
533 } catch (Exception ex)
535 ex.printStackTrace();
536 return "Error retrieving alignment in " + format + " format. ";
544 * @see jalview.bin.JalviewLiteJsApi#getAlignmentOrder()
547 public String getAlignmentOrder()
549 return getAlignmentOrderFrom(getDefaultTargetFrame());
556 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
560 public String getAlignmentOrderFrom(AlignFrame alf)
562 return getAlignmentOrderFrom(alf, separator);
569 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
570 * , java.lang.String)
573 public String getAlignmentOrderFrom(AlignFrame alf, String sep)
575 AlignmentI alorder = alf.getAlignViewport().getAlignment();
576 String[] order = new String[alorder.getHeight()];
577 for (int i = 0; i < order.length; i++)
579 order[i] = alorder.getSequenceAt(i).getName();
581 return arrayToSeparatorList(order);
587 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
591 public String orderBy(String order, String undoName)
593 return orderBy(order, undoName, separator);
599 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
600 * java.lang.String, java.lang.String)
603 public String orderBy(String order, String undoName, String sep)
605 return orderAlignmentBy(getDefaultTargetFrame(), order, undoName, sep);
612 * jalview.bin.JalviewLiteJsApi#orderAlignmentBy(jalview.appletgui.AlignFrame,
613 * java.lang.String, java.lang.String, java.lang.String)
616 public String orderAlignmentBy(AlignFrame alf, String order,
617 String undoName, String sep)
619 String[] ids = separatorListToArray(order, sep);
620 SequenceI[] sqs = null;
621 if (ids != null && ids.length > 0)
623 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
624 alf.viewport.getAlignment().getSequencesArray());
626 sqs = new SequenceI[ids.length];
627 for (int i = 0; i < ids.length; i++)
629 if (ids[i].trim().length() == 0)
633 SequenceI sq = matcher.findIdMatch(ids[i]);
641 SequenceI[] sqq = new SequenceI[s];
642 System.arraycopy(sqs, 0, sqq, 0, s);
655 final AlignmentOrder aorder = new AlignmentOrder(sqs);
657 if (undoName != null && undoName.trim().length() == 0)
661 final String _undoName = undoName;
662 // TODO: deal with synchronization here: cannot raise any events until after
663 // this has returned.
664 return alf.sortBy(aorder, _undoName) ? TRUE : "";
670 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String)
673 public String getAlignment(String format)
675 return getAlignmentFrom(getDefaultTargetFrame(), format, TRUE);
682 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
686 public String getAlignmentFrom(AlignFrame alf, String format)
688 return getAlignmentFrom(alf, format, TRUE);
694 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String,
698 public String getAlignment(String format, String suffix)
700 return getAlignmentFrom(getDefaultTargetFrame(), format, suffix);
707 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
708 * java.lang.String, java.lang.String)
711 public String getAlignmentFrom(AlignFrame alf, String format,
716 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
718 String reply = new AppletFormatAdapter().formatSequences(format,
719 alf.viewport.getAlignment(), seqlimits);
721 } catch (Exception ex)
723 ex.printStackTrace();
724 return "Error retrieving alignment in " + format + " format. ";
731 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
734 public void loadAnnotation(String annotation)
736 loadAnnotationFrom(getDefaultTargetFrame(), annotation);
743 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
744 * , java.lang.String)
747 public void loadAnnotationFrom(AlignFrame alf, String annotation)
749 if (new AnnotationFile().annotateAlignmentView(alf.getAlignViewport(),
750 annotation, AppletFormatAdapter.PASTE))
752 alf.alignPanel.fontChanged();
753 alf.alignPanel.setScrollValues(0, 0);
757 alf.parseFeaturesFile(annotation, AppletFormatAdapter.PASTE);
764 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
767 public void loadFeatures(String features, boolean autoenabledisplay)
769 loadFeaturesFrom(getDefaultTargetFrame(), features, autoenabledisplay);
776 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
777 * , java.lang.String)
780 public boolean loadFeaturesFrom(AlignFrame alf, String features,
781 boolean autoenabledisplay)
783 return alf.parseFeaturesFile(features, AppletFormatAdapter.PASTE,
790 * @see jalview.bin.JalviewLiteJsApi#getFeatures(java.lang.String)
793 public String getFeatures(String format)
795 return getFeaturesFrom(getDefaultTargetFrame(), format);
802 * jalview.bin.JalviewLiteJsApi#getFeaturesFrom(jalview.appletgui.AlignFrame,
806 public String getFeaturesFrom(AlignFrame alf, String format)
808 return alf.outputFeatures(false, format);
814 * @see jalview.bin.JalviewLiteJsApi#getAnnotation()
817 public String getAnnotation()
819 return getAnnotationFrom(getDefaultTargetFrame());
826 * jalview.bin.JalviewLiteJsApi#getAnnotationFrom(jalview.appletgui.AlignFrame
830 public String getAnnotationFrom(AlignFrame alf)
832 return alf.outputAnnotations(false);
838 * @see jalview.bin.JalviewLiteJsApi#newView()
841 public AlignFrame newView()
843 return newViewFrom(getDefaultTargetFrame());
849 * @see jalview.bin.JalviewLiteJsApi#newView(java.lang.String)
852 public AlignFrame newView(String name)
854 return newViewFrom(getDefaultTargetFrame(), name);
860 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame)
863 public AlignFrame newViewFrom(AlignFrame alf)
865 return alf.newView(null);
871 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame,
875 public AlignFrame newViewFrom(AlignFrame alf, String name)
877 return alf.newView(name);
883 * @see jalview.bin.JalviewLiteJsApi#loadAlignment(java.lang.String,
887 public AlignFrame loadAlignment(String text, String title)
889 AlignmentI al = null;
891 String format = new IdentifyFile().identify(text,
892 AppletFormatAdapter.PASTE);
895 al = new AppletFormatAdapter().readFile(text,
896 AppletFormatAdapter.PASTE, format);
897 if (al.getHeight() > 0)
899 return new AlignFrame(al, this, title, false);
901 } catch (java.io.IOException ex)
903 ex.printStackTrace();
911 * @see jalview.bin.JalviewLiteJsApi#setMouseoverListener(java.lang.String)
914 public void setMouseoverListener(String listener)
916 setMouseoverListener(currentAlignFrame, listener);
919 private Vector<jalview.javascript.JSFunctionExec> javascriptListeners = new Vector<jalview.javascript.JSFunctionExec>();
925 * jalview.bin.JalviewLiteJsApi#setMouseoverListener(jalview.appletgui.AlignFrame
926 * , java.lang.String)
929 public void setMouseoverListener(AlignFrame af, String listener)
931 if (listener != null)
933 listener = listener.trim();
934 if (listener.length() == 0)
937 .println("jalview Javascript error: Ignoring empty function for mouseover listener.");
941 jalview.javascript.MouseOverListener mol = new jalview.javascript.MouseOverListener(
943 javascriptListeners.addElement(mol);
944 StructureSelectionManager.getStructureSelectionManager(this)
945 .addStructureViewerListener(mol);
948 System.err.println("Added a mouseover listener for "
949 + ((af == null) ? "All frames" : "Just views for "
950 + af.getAlignViewport().getSequenceSetId()));
951 System.err.println("There are now " + javascriptListeners.size()
952 + " listeners in total.");
959 * @see jalview.bin.JalviewLiteJsApi#setSelectionListener(java.lang.String)
962 public void setSelectionListener(String listener)
964 setSelectionListener(null, listener);
971 * jalview.bin.JalviewLiteJsApi#setSelectionListener(jalview.appletgui.AlignFrame
972 * , java.lang.String)
975 public void setSelectionListener(AlignFrame af, String listener)
977 if (listener != null)
979 listener = listener.trim();
980 if (listener.length() == 0)
983 .println("jalview Javascript error: Ignoring empty function for selection listener.");
987 jalview.javascript.JsSelectionSender mol = new jalview.javascript.JsSelectionSender(
989 javascriptListeners.addElement(mol);
990 StructureSelectionManager.getStructureSelectionManager(this)
991 .addSelectionListener(mol);
994 System.err.println("Added a selection listener for "
995 + ((af == null) ? "All frames" : "Just views for "
996 + af.getAlignViewport().getSequenceSetId()));
997 System.err.println("There are now " + javascriptListeners.size()
998 + " listeners in total.");
1003 * Callable from javascript to register a javascript function to pass events
1004 * to a structure viewer.
1007 * the name of a javascript function
1009 * a token separated list of PDB file names listened for
1010 * @see jalview.bin.JalviewLiteJsApi#setStructureListener(java.lang.String,
1014 public void setStructureListener(String listener, String modelSet)
1016 if (listener != null)
1018 listener = listener.trim();
1019 if (listener.length() == 0)
1022 .println("jalview Javascript error: Ignoring empty function for selection listener.");
1026 MouseOverStructureListener mol = new MouseOverStructureListener(this,
1027 listener, separatorListToArray(modelSet));
1028 javascriptListeners.addElement(mol);
1029 StructureSelectionManager.getStructureSelectionManager(this)
1030 .addStructureViewerListener(mol);
1033 System.err.println("Added a javascript structure viewer listener '"
1035 System.err.println("There are now " + javascriptListeners.size()
1036 + " listeners in total.");
1044 * jalview.bin.JalviewLiteJsApi#removeJavascriptListener(jalview.appletgui
1045 * .AlignFrame, java.lang.String)
1048 public void removeJavascriptListener(AlignFrame af, String listener)
1050 if (listener != null)
1052 listener = listener.trim();
1053 if (listener.length() == 0)
1058 boolean rprt = false;
1059 for (int ms = 0, msSize = javascriptListeners.size(); ms < msSize;)
1061 Object lstn = javascriptListeners.elementAt(ms);
1062 JsCallBack lstner = (JsCallBack) lstn;
1063 if ((af == null || lstner.getAlignFrame() == af)
1064 && (listener == null || lstner.getListenerFunction().equals(
1067 javascriptListeners.removeElement(lstner);
1069 if (lstner instanceof SelectionListener)
1071 StructureSelectionManager.getStructureSelectionManager(this)
1072 .removeSelectionListener((SelectionListener) lstner);
1076 StructureSelectionManager.getStructureSelectionManager(this)
1077 .removeStructureViewerListener(lstner, null);
1082 System.err.println("Removed listener '" + listener + "'");
1092 System.err.println("There are now " + javascriptListeners.size()
1093 + " listeners in total.");
1100 System.err.println("Applet " + getName() + " stop().");
1105 public void destroy()
1107 System.err.println("Applet " + getName() + " destroy().");
1111 private void tidyUp()
1114 if (currentAlignFrame != null && currentAlignFrame.viewport != null
1115 && currentAlignFrame.viewport.applet != null)
1117 AlignViewport av = currentAlignFrame.viewport;
1118 currentAlignFrame.closeMenuItem_actionPerformed();
1120 currentAlignFrame = null;
1122 if (javascriptListeners != null)
1124 while (javascriptListeners.size() > 0)
1126 jalview.javascript.JSFunctionExec mol = javascriptListeners
1128 javascriptListeners.removeElement(mol);
1129 if (mol instanceof SelectionListener)
1131 StructureSelectionManager.getStructureSelectionManager(this)
1132 .removeSelectionListener((SelectionListener) mol);
1136 StructureSelectionManager.getStructureSelectionManager(this)
1137 .removeStructureViewerListener(mol, null);
1142 if (jsFunctionExec != null)
1144 jsFunctionExec.stopQueue();
1145 jsFunctionExec.jvlite = null;
1147 initialAlignFrame = null;
1148 jsFunctionExec = null;
1149 javascriptListeners = null;
1150 StructureSelectionManager.release(this);
1153 private jalview.javascript.JSFunctionExec jsFunctionExec;
1158 * @see jalview.bin.JalviewLiteJsApi#mouseOverStructure(java.lang.String,
1159 * java.lang.String, java.lang.String)
1162 public void mouseOverStructure(final String pdbResNum,
1163 final String chain, final String pdbfile)
1165 final StructureSelectionManagerProvider me = this;
1166 java.awt.EventQueue.invokeLater(new Runnable()
1173 StructureSelectionManager.getStructureSelectionManager(me)
1174 .mouseOverStructure(new Integer(pdbResNum).intValue(),
1178 System.err.println("mouseOver for '" + pdbResNum
1179 + "' in chain '" + chain + "' in structure '" + pdbfile
1182 } catch (NumberFormatException e)
1184 System.err.println("Ignoring invalid residue number string '"
1196 * jalview.bin.JalviewLiteJsApi#scrollViewToIn(jalview.appletgui.AlignFrame,
1197 * java.lang.String, java.lang.String)
1200 public void scrollViewToIn(final AlignFrame alf, final String topRow,
1201 final String leftHandColumn)
1203 java.awt.EventQueue.invokeLater(new Runnable()
1210 alf.scrollTo(new Integer(topRow).intValue(), new Integer(
1211 leftHandColumn).intValue());
1213 } catch (Exception ex)
1215 System.err.println("Couldn't parse integer arguments (topRow='"
1216 + topRow + "' and leftHandColumn='" + leftHandColumn
1218 ex.printStackTrace();
1228 * jalview.javascript.JalviewLiteJsApi#scrollViewToRowIn(jalview.appletgui
1229 * .AlignFrame, java.lang.String)
1232 public void scrollViewToRowIn(final AlignFrame alf, final String topRow)
1235 java.awt.EventQueue.invokeLater(new Runnable()
1242 alf.scrollToRow(new Integer(topRow).intValue());
1244 } catch (Exception ex)
1246 System.err.println("Couldn't parse integer arguments (topRow='"
1248 ex.printStackTrace();
1259 * jalview.javascript.JalviewLiteJsApi#scrollViewToColumnIn(jalview.appletgui
1260 * .AlignFrame, java.lang.String)
1263 public void scrollViewToColumnIn(final AlignFrame alf,
1264 final String leftHandColumn)
1266 java.awt.EventQueue.invokeLater(new Runnable()
1274 alf.scrollToColumn(new Integer(leftHandColumn).intValue());
1276 } catch (Exception ex)
1279 .println("Couldn't parse integer arguments (leftHandColumn='"
1280 + leftHandColumn + "')");
1281 ex.printStackTrace();
1288 // //////////////////////////////////////////////
1289 // //////////////////////////////////////////////
1291 public static int lastFrameX = 200;
1293 public static int lastFrameY = 200;
1295 boolean fileFound = true;
1297 String file = "No file";
1299 String file2 = null;
1301 Button launcher = new Button(
1302 MessageManager.getString("label.start_jalview"));
1305 * The currentAlignFrame is static, it will change if and when the user
1306 * selects a new window. Note that it will *never* point back to the embedded
1307 * AlignFrame if the applet is started as embedded on the page and then
1308 * afterwards a new view is created.
1310 public AlignFrame currentAlignFrame = null;
1313 * This is the first frame to be displayed, and does not change. API calls
1314 * will default to this instance if currentAlignFrame is null.
1316 AlignFrame initialAlignFrame = null;
1318 boolean embedded = false;
1320 private boolean checkForJmol = true;
1322 private boolean checkedForJmol = false; // ensure we don't check for jmol
1324 // every time the app is re-inited
1326 public boolean jmolAvailable = false;
1328 private boolean alignPdbStructures = false;
1331 * use an external structure viewer exclusively (no jmols or MCViews will be
1332 * opened by JalviewLite itself)
1334 public boolean useXtrnalSviewer = false;
1336 public static boolean debug = false;
1338 static String builddate = null, version = null, installation = null;
1340 private static void initBuildDetails()
1342 if (builddate == null)
1344 builddate = "unknown";
1346 installation = "applet";
1347 java.net.URL url = JalviewLite.class
1348 .getResource("/.build_properties");
1353 BufferedReader reader = new BufferedReader(new InputStreamReader(
1356 while ((line = reader.readLine()) != null)
1358 if (line.indexOf("VERSION") > -1)
1360 version = line.substring(line.indexOf("=") + 1);
1362 if (line.indexOf("BUILD_DATE") > -1)
1364 builddate = line.substring(line.indexOf("=") + 1);
1366 if (line.indexOf("INSTALLATION") > -1)
1368 installation = line.substring(line.indexOf("=") + 1);
1371 } catch (Exception ex)
1373 ex.printStackTrace();
1379 public static String getBuildDate()
1385 public static String getInstallation()
1388 return installation;
1391 public static String getVersion()
1397 // public JSObject scriptObject = null;
1400 * init method for Jalview Applet
1405 debug = TRUE.equalsIgnoreCase(getParameter("debug"));
1410 System.err.println("Applet context is '"
1411 + getAppletContext().getClass().toString() + "'");
1413 JSObject scriptObject = JSObject.getWindow(this);
1414 if (debug && scriptObject != null)
1416 System.err.println("Applet has Javascript callback support.");
1419 } catch (Exception ex)
1422 .println("Warning: No JalviewLite javascript callbacks available.");
1425 ex.printStackTrace();
1431 System.err.println("JalviewLite Version " + getVersion());
1432 System.err.println("Build Date : " + getBuildDate());
1433 System.err.println("Installation : " + getInstallation());
1435 String externalsviewer = getParameter("externalstructureviewer");
1436 if (externalsviewer != null)
1438 useXtrnalSviewer = externalsviewer.trim().toLowerCase().equals(TRUE);
1441 * if true disable the check for jmol
1443 String chkforJmol = getParameter("nojmol");
1444 if (chkforJmol != null)
1446 checkForJmol = !chkforJmol.equals(TRUE);
1449 * get the separator parameter if present
1451 String sep = getParameter("separator");
1454 if (sep.length() > 0)
1459 System.err.println("Separator set to '" + separator + "'");
1466 .getString("error.invalid_separator_parameter"));
1472 String param = getParameter("RGB");
1478 r = Integer.parseInt(param.substring(0, 2), 16);
1479 g = Integer.parseInt(param.substring(2, 4), 16);
1480 b = Integer.parseInt(param.substring(4, 6), 16);
1481 } catch (Exception ex)
1488 param = getParameter("label");
1491 launcher.setLabel(param);
1494 setBackground(new Color(r, g, b));
1496 file = getParameter("file");
1500 // Maybe the sequences are added as parameters
1501 StringBuffer data = new StringBuffer("PASTE");
1503 while ((file = getParameter("sequence" + i)) != null)
1505 data.append(file.toString() + "\n");
1508 if (data.length() > 5)
1510 file = data.toString();
1513 if (getDefaultParameter("enableSplitFrame", true))
1515 file2 = getParameter("file2");
1518 embedded = TRUE.equalsIgnoreCase(getParameter("embedded"));
1521 LoadingThread loader = new LoadingThread(file, file2, this);
1524 else if (file != null)
1527 * Start the applet immediately or show a button to start it
1529 if (FALSE.equalsIgnoreCase(getParameter("showbutton")))
1531 LoadingThread loader = new LoadingThread(file, file2, this);
1537 launcher.addActionListener(new java.awt.event.ActionListener()
1540 public void actionPerformed(ActionEvent e)
1542 LoadingThread loader = new LoadingThread(file, file2,
1551 // jalview initialisation with no alignment. loadAlignment() method can
1552 // still be called to open new alignments.
1559 private void initLiveConnect()
1561 // try really hard to get the liveConnect thing working
1562 boolean notFailed = false;
1564 while (!notFailed && tries < 10)
1568 System.err.println("LiveConnect request thread going to sleep.");
1572 Thread.sleep(700 * (1 + tries));
1573 } catch (InterruptedException q)
1579 System.err.println("LiveConnect request thread woken up.");
1583 JSObject scriptObject = JSObject.getWindow(this);
1584 if (scriptObject.eval("navigator") != null)
1588 } catch (Exception jsex)
1590 System.err.println("Attempt " + tries
1591 + " to access LiveConnect javascript failed.");
1596 private void callInitCallback()
1598 String initjscallback = getParameter("oninit");
1599 if (initjscallback == null)
1603 initjscallback = initjscallback.trim();
1604 if (initjscallback.length() > 0)
1606 JSObject scriptObject = null;
1609 scriptObject = JSObject.getWindow(this);
1610 } catch (Exception ex)
1614 // try really hard to let the browser plugin know we want liveconnect
1617 if (scriptObject != null)
1621 // do onInit with the JS executor thread
1622 new JSFunctionExec(this).executeJavascriptFunction(true,
1623 initjscallback, null, "Calling oninit callback '"
1624 + initjscallback + "'.");
1625 } catch (Exception e)
1627 System.err.println("Exception when executing _oninit callback '"
1628 + initjscallback + "'.");
1629 e.printStackTrace();
1634 System.err.println("Not executing _oninit callback '"
1635 + initjscallback + "' - no scripting allowed.");
1641 * Initialises and displays a new java.awt.Frame
1644 * java.awt.Frame to be displayed
1646 * title of new frame
1648 * width if new frame
1650 * height of new frame
1652 public static void addFrame(final Frame frame, String title, int width,
1655 frame.setLocation(lastFrameX, lastFrameY);
1658 frame.setSize(width, height);
1659 frame.setTitle(title);
1660 frame.addWindowListener(new WindowAdapter()
1663 public void windowClosing(WindowEvent e)
1665 if (frame instanceof AlignFrame)
1667 AlignViewport vp = ((AlignFrame) frame).viewport;
1668 ((AlignFrame) frame).closeMenuItem_actionPerformed();
1669 if (vp.applet.currentAlignFrame == frame)
1671 vp.applet.currentAlignFrame = null;
1679 if (frame instanceof EmbmenuFrame)
1681 ((EmbmenuFrame) frame).destroyMenus();
1683 frame.setMenuBar(null);
1688 public void windowActivated(WindowEvent e)
1690 if (frame instanceof AlignFrame)
1692 ((AlignFrame) frame).viewport.applet.currentAlignFrame = (AlignFrame) frame;
1695 System.err.println("Activated window " + frame);
1699 super.windowActivated(e);
1702 * Probably not necessary to do this - see TODO above. (non-Javadoc)
1705 * java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent
1708 * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
1709 * frame) { currentAlignFrame = null; if (debug) {
1710 * System.err.println("Deactivated window "+frame); } }
1711 * super.windowDeactivated(e); }
1714 frame.setVisible(true);
1718 * This paints the background surrounding the "Launch Jalview button" <br>
1720 * If file given in parameter not found, displays error message
1726 public void paint(Graphics g)
1730 g.setColor(new Color(200, 200, 200));
1731 g.setColor(Color.cyan);
1732 g.fillRect(0, 0, getSize().width, getSize().height);
1733 g.setColor(Color.red);
1735 MessageManager.getString("label.jalview_cannot_open_file"),
1737 g.drawString("\"" + file + "\"", 5, 30);
1741 g.setColor(Color.black);
1742 g.setFont(new Font("Arial", Font.BOLD, 24));
1743 g.drawString(MessageManager.getString("label.jalview_applet"), 50,
1744 getSize().height / 2 - 30);
1745 g.drawString(MessageManager.getString("label.loading_data") + "...",
1746 50, getSize().height / 2);
1751 * get all components associated with the applet of the given type
1756 public Vector getAppletWindow(Class class1)
1758 Vector wnds = new Vector();
1759 Component[] cmp = getComponents();
1762 for (int i = 0; i < cmp.length; i++)
1764 if (class1.isAssignableFrom(cmp[i].getClass()))
1766 wnds.addElement(cmp);
1773 class LoadJmolThread extends Thread
1775 private boolean running = false;
1780 if (running || checkedForJmol)
1789 if (!System.getProperty("java.version").startsWith("1.1"))
1791 Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
1792 jmolAvailable = true;
1797 .println("Jmol not available - Using MCview for structures");
1799 } catch (java.lang.ClassNotFoundException ex)
1805 jmolAvailable = false;
1809 .println("Skipping Jmol check. Will use MCView (probably)");
1812 checkedForJmol = true;
1816 public boolean notFinished()
1818 return running || !checkedForJmol;
1822 class LoadingThread extends Thread
1825 * State variable: protocol for access to file source
1829 String _file; // alignment file or URL spec
1831 String _file2; // second alignment file or URL spec
1835 private void dbgMsg(String msg)
1837 if (JalviewLite.debug)
1839 System.err.println(msg);
1844 * update the protocol state variable for accessing the datasource located
1848 * @return possibly updated datasource string
1850 public String resolveFileProtocol(String path)
1855 if (path.startsWith("PASTE"))
1857 protocol = AppletFormatAdapter.PASTE;
1858 return path.substring(5);
1864 if (path.indexOf("://") != -1)
1866 protocol = AppletFormatAdapter.URL;
1871 * try relative to document root
1873 URL documentBase = getDocumentBase();
1874 String withDocBase = resolveUrlForLocalOrAbsolute(path, documentBase);
1875 if (HttpUtils.isValidUrl(withDocBase))
1879 System.err.println("Prepended document base '" + documentBase
1880 + "' to make: '" + withDocBase + "'");
1882 protocol = AppletFormatAdapter.URL;
1887 * try relative to codebase (if different to document base)
1889 URL codeBase = getCodeBase();
1890 String withCodeBase = applet.resolveUrlForLocalOrAbsolute(path,
1892 if (!withCodeBase.equals(withDocBase)
1893 && HttpUtils.isValidUrl(withCodeBase))
1895 protocol = AppletFormatAdapter.URL;
1898 System.err.println("Prepended codebase '" + codeBase
1899 + "' to make: '" + withCodeBase + "'");
1901 return withCodeBase;
1905 * try locating by classloader; try this last so files in the directory
1906 * are resolved using document base
1908 if (inArchive(path))
1910 protocol = AppletFormatAdapter.CLASSLOADER;
1915 public LoadingThread(String file, String file2, JalviewLite _applet)
1918 this._file2 = file2;
1925 LoadJmolThread jmolchecker = new LoadJmolThread();
1926 jmolchecker.start();
1927 while (jmolchecker.notFinished())
1929 // wait around until the Jmol check is complete.
1933 } catch (Exception e)
1938 // applet.callInitCallback();
1942 * Load the alignment and any related files as specified by applet
1945 private void startLoading()
1947 dbgMsg("Loading thread started with:\n>>file\n" + _file + ">>endfile");
1949 dbgMsg("Loading started.");
1951 AlignFrame newAlignFrame = readAlignment(_file);
1952 AlignFrame newAlignFrame2 = readAlignment(_file2);
1953 if (newAlignFrame != null)
1955 addToDisplay(newAlignFrame, newAlignFrame2);
1956 loadTree(newAlignFrame);
1958 loadScoreFile(newAlignFrame);
1960 loadFeatures(newAlignFrame);
1962 loadAnnotations(newAlignFrame);
1964 loadJnetFile(newAlignFrame);
1966 loadPdbFiles(newAlignFrame);
1971 applet.remove(launcher);
1978 * Add an AlignFrame to the display; or if two are provided, a SplitFrame.
1983 public void addToDisplay(AlignFrame af, AlignFrame af2)
1987 AlignmentI al1 = af.viewport.getAlignment();
1988 AlignmentI al2 = af2.viewport.getAlignment();
1989 AlignmentI cdna = al1.isNucleotide() ? al1 : al2;
1990 AlignmentI prot = al1.isNucleotide() ? al2 : al1;
1991 if (AlignmentUtils.mapProteinAlignmentToCdna(prot, cdna))
1994 SplitFrame sf = new SplitFrame(af, af2);
1995 sf.addToDisplay(embedded, JalviewLite.this);
2000 String msg = "Could not map any sequence in " + af2.getTitle()
2002 + (al1.isNucleotide() ? "protein product" : "cDNA")
2003 + " for " + af.getTitle();
2004 System.err.println(msg);
2008 af.addToDisplay(embedded);
2012 * Read the alignment file (from URL, text 'paste', or archive by
2017 protected AlignFrame readAlignment(String fileParam)
2019 if (fileParam == null)
2023 String resolvedFile = resolveFileProtocol(fileParam);
2024 String format = new IdentifyFile().identify(resolvedFile, protocol);
2025 dbgMsg("File identified as '" + format + "'");
2026 AlignmentI al = null;
2029 al = new AppletFormatAdapter().readFile(resolvedFile, protocol,
2031 if ((al != null) && (al.getHeight() > 0))
2033 dbgMsg("Successfully loaded file.");
2034 al.setDataset(null);
2035 AlignFrame newAlignFrame = new AlignFrame(al, applet,
2036 resolvedFile, embedded, false);
2037 newAlignFrame.setTitle(resolvedFile);
2038 if (initialAlignFrame == null)
2040 initialAlignFrame = newAlignFrame;
2042 // update the focus.
2043 currentAlignFrame = newAlignFrame;
2045 if (protocol == AppletFormatAdapter.PASTE)
2047 newAlignFrame.setTitle(MessageManager.formatMessage(
2048 "label.sequences_from", new Object[] { applet
2049 .getDocumentBase().toString() }));
2052 newAlignFrame.statusBar.setText(MessageManager.formatMessage(
2053 "label.successfully_loaded_file",
2054 new Object[] { resolvedFile }));
2056 return newAlignFrame;
2058 } catch (java.io.IOException ex)
2060 dbgMsg("File load exception.");
2061 ex.printStackTrace();
2066 FileParse fp = new FileParse(resolvedFile, protocol);
2068 dbgMsg(">>>Dumping contents of '" + resolvedFile + "' " + "("
2070 while ((ln = fp.nextLine()) != null)
2074 dbgMsg(">>>Dump finished.");
2075 } catch (Exception e)
2078 .println("Exception when trying to dump the content of the file parameter.");
2079 e.printStackTrace();
2087 * Load PDBFiles if any specified by parameter(s). Returns true if loaded,
2093 protected boolean loadPdbFiles(AlignFrame alignFrame)
2095 boolean result = false;
2097 * <param name="alignpdbfiles" value="false/true"/> Undocumented for 2.6 -
2098 * related to JAL-434
2101 applet.setAlignPdbStructures(getDefaultParameter("alignpdbfiles",
2104 * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
2107 * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
2109 * <param name="PDBfile3" value="1q0o Q45135_9MICO">
2112 int pdbFileCount = 0;
2113 // Accumulate pdbs here if they are heading for the same view (if
2114 // alignPdbStructures is true)
2115 Vector pdbs = new Vector();
2116 // create a lazy matcher if we're asked to
2117 jalview.analysis.SequenceIdMatcher matcher = (applet
2118 .getDefaultParameter("relaxedidmatch", false)) ? new jalview.analysis.SequenceIdMatcher(
2119 alignFrame.getAlignViewport().getAlignment()
2120 .getSequencesArray()) : null;
2125 if (pdbFileCount > 0)
2127 param = applet.getParameter("PDBFILE" + pdbFileCount);
2131 param = applet.getParameter("PDBFILE");
2136 PDBEntry pdb = new PDBEntry();
2139 SequenceI[] seqs = null;
2140 String[] chains = null;
2142 StringTokenizer st = new StringTokenizer(param, " ");
2144 if (st.countTokens() < 2)
2146 String sequence = applet.getParameter("PDBSEQ");
2147 if (sequence != null)
2149 seqs = new SequenceI[] { matcher == null ? (Sequence) alignFrame
2150 .getAlignViewport().getAlignment().findName(sequence)
2151 : matcher.findIdMatch(sequence) };
2157 param = st.nextToken();
2158 List<SequenceI> tmp = new ArrayList<SequenceI>();
2159 List<String> tmp2 = new ArrayList<String>();
2161 while (st.hasMoreTokens())
2163 seqstring = st.nextToken();
2164 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
2165 if (st2.countTokens() > 1)
2167 // This is the chain
2168 tmp2.add(st2.nextToken());
2169 seqstring = st2.nextToken();
2171 tmp.add(matcher == null ? (Sequence) alignFrame
2172 .getAlignViewport().getAlignment()
2173 .findName(seqstring) : matcher.findIdMatch(seqstring));
2176 seqs = tmp.toArray(new SequenceI[tmp.size()]);
2177 if (tmp2.size() == tmp.size())
2179 chains = tmp2.toArray(new String[tmp2.size()]);
2182 param = resolveFileProtocol(param);
2183 // TODO check JAL-357 for files in a jar (CLASSLOADER)
2188 for (int i = 0; i < seqs.length; i++)
2190 if (seqs[i] != null)
2192 ((Sequence) seqs[i]).addPDBId(pdb);
2193 StructureSelectionManager.getStructureSelectionManager(
2194 applet).registerPDBEntry(pdb);
2198 if (JalviewLite.debug)
2200 // this may not really be a problem but we give a warning
2203 .println("Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
2209 if (!alignPdbStructures)
2211 alignFrame.newStructureView(applet, pdb, seqs, chains,
2216 pdbs.addElement(new Object[] { pdb, seqs, chains,
2217 new String(protocol) });
2223 } while (param != null || pdbFileCount < 10);
2224 if (pdbs.size() > 0)
2226 SequenceI[][] seqs = new SequenceI[pdbs.size()][];
2227 PDBEntry[] pdb = new PDBEntry[pdbs.size()];
2228 String[][] chains = new String[pdbs.size()][];
2229 String[] protocols = new String[pdbs.size()];
2230 for (int pdbsi = 0, pdbsiSize = pdbs.size(); pdbsi < pdbsiSize; pdbsi++)
2232 Object[] o = (Object[]) pdbs.elementAt(pdbsi);
2233 pdb[pdbsi] = (PDBEntry) o[0];
2234 seqs[pdbsi] = (SequenceI[]) o[1];
2235 chains[pdbsi] = (String[]) o[2];
2236 protocols[pdbsi] = (String) o[3];
2238 alignFrame.alignedStructureView(applet, pdb, seqs, chains,
2246 * Load in a Jnetfile if specified by parameter. Returns true if loaded,
2252 protected boolean loadJnetFile(AlignFrame alignFrame)
2254 boolean result = false;
2255 String param = applet.getParameter("jnetfile");
2260 param = resolveFileProtocol(param);
2261 JPredFile predictions = new JPredFile(param, protocol);
2262 JnetAnnotationMaker.add_annotation(predictions,
2263 alignFrame.viewport.getAlignment(), 0, false);
2264 // false == do not add sequence profile from concise output
2265 SequenceI repseq = alignFrame.viewport.getAlignment()
2267 alignFrame.viewport.getAlignment().setSeqrep(repseq);
2268 ColumnSelection cs = new ColumnSelection();
2269 cs.hideInsertionsFor(repseq);
2270 alignFrame.viewport.setColumnSelection(cs);
2271 alignFrame.alignPanel.fontChanged();
2272 alignFrame.alignPanel.setScrollValues(0, 0);
2274 } catch (Exception ex)
2276 ex.printStackTrace();
2283 * Load annotations if specified by parameter. Returns true if loaded, else
2289 protected boolean loadAnnotations(AlignFrame alignFrame)
2291 boolean result = false;
2292 String param = applet.getParameter("annotations");
2295 param = resolveFileProtocol(param);
2297 if (new AnnotationFile().annotateAlignmentView(alignFrame.viewport,
2300 alignFrame.alignPanel.fontChanged();
2301 alignFrame.alignPanel.setScrollValues(0, 0);
2307 .println("Annotations were not added from annotation file '"
2315 * Load features file and view settings as specified by parameters. Returns
2316 * true if features were loaded, else false.
2321 protected boolean loadFeatures(AlignFrame alignFrame)
2323 boolean result = false;
2324 // ///////////////////////////
2325 // modify display of features
2326 // we do this before any features have been loaded, ensuring any hidden
2327 // groups are hidden when features first displayed
2329 // hide specific groups
2331 String param = applet.getParameter("hidefeaturegroups");
2334 alignFrame.setFeatureGroupState(separatorListToArray(param), false);
2335 // applet.setFeatureGroupStateOn(newAlignFrame, param, false);
2337 // show specific groups
2338 param = applet.getParameter("showfeaturegroups");
2341 alignFrame.setFeatureGroupState(separatorListToArray(param), true);
2342 // applet.setFeatureGroupStateOn(newAlignFrame, param, true);
2344 // and now load features
2345 param = applet.getParameter("features");
2348 param = resolveFileProtocol(param);
2350 result = alignFrame.parseFeaturesFile(param, protocol);
2353 param = applet.getParameter("showFeatureSettings");
2354 if (param != null && param.equalsIgnoreCase(TRUE))
2356 alignFrame.viewport.setShowSequenceFeatures(true);
2357 new FeatureSettings(alignFrame.alignPanel);
2363 * Load a score file if specified by parameter. Returns true if file was
2364 * loaded, else false.
2368 protected boolean loadScoreFile(AlignFrame alignFrame)
2370 boolean result = false;
2371 String sScoreFile = applet.getParameter("scoreFile");
2372 if (sScoreFile != null && !"".equals(sScoreFile))
2379 .println("Attempting to load T-COFFEE score file from the scoreFile parameter");
2381 result = alignFrame.loadScoreFile(sScoreFile);
2385 .println("Failed to parse T-COFFEE parameter as a valid score file ('"
2386 + sScoreFile + "')");
2388 } catch (Exception e)
2390 System.err.printf("Cannot read score file: '%s'. Cause: %s \n",
2391 sScoreFile, e.getMessage());
2398 * Load a tree for the alignment if specified by parameter. Returns true if
2399 * a tree was loaded, else false.
2404 protected boolean loadTree(AlignFrame alignFrame)
2406 boolean result = false;
2407 String treeFile = applet.getParameter("tree");
2408 if (treeFile == null)
2410 treeFile = applet.getParameter("treeFile");
2413 if (treeFile != null)
2417 treeFile = resolveFileProtocol(treeFile);
2418 NewickFile fin = new NewickFile(treeFile, protocol);
2421 if (fin.getTree() != null)
2423 alignFrame.loadTree(fin, treeFile);
2425 dbgMsg("Successfully imported tree.");
2429 dbgMsg("Tree parameter did not resolve to a valid tree.");
2431 } catch (Exception ex)
2433 ex.printStackTrace();
2440 * Discovers whether the given file is in the Applet Archive
2446 boolean inArchive(String f)
2448 // This might throw a security exception in certain browsers
2449 // Netscape Communicator for instance.
2452 boolean rtn = (getClass().getResourceAsStream("/" + f) != null);
2455 System.err.println("Resource '" + f + "' was "
2456 + (rtn ? "" : "not ") + "located by classloader.");
2459 } catch (Exception ex)
2461 System.out.println("Exception checking resources: " + f + " " + ex);
2468 * @return the default alignFrame acted on by the public applet methods. May
2469 * return null with an error message on System.err indicating the
2472 public AlignFrame getDefaultTargetFrame()
2474 if (currentAlignFrame != null)
2476 return currentAlignFrame;
2478 if (initialAlignFrame != null)
2480 return initialAlignFrame;
2483 .println("Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
2488 * separator used for separatorList
2490 protected String separator = "" + ((char) 0x00AC); // the default used to be
2491 // '|' but many sequence
2492 // IDS include pipes.
2495 * set to enable the URL based javascript execution mechanism
2497 public boolean jsfallbackEnabled = false;
2500 * parse the string into a list
2503 * @return elements separated by separator
2505 public String[] separatorListToArray(String list)
2507 return separatorListToArray(list, separator);
2511 * parse the string into a list
2515 * @return elements separated by separator
2517 public static String[] separatorListToArray(String list, String separator)
2519 // TODO use StringUtils version (slightly different...)
2520 int seplen = separator.length();
2521 if (list == null || list.equals("") || list.equals(separator))
2525 java.util.Vector jv = new Vector();
2527 while ((pos = list.indexOf(separator, cp)) > cp)
2529 jv.addElement(list.substring(cp, pos));
2532 if (cp < list.length())
2534 String c = list.substring(cp);
2535 if (!c.equals(separator))
2542 String[] v = new String[jv.size()];
2543 for (int i = 0; i < v.length; i++)
2545 v[i] = (String) jv.elementAt(i);
2547 jv.removeAllElements();
2550 System.err.println("Array from '" + separator
2551 + "' separated List:\n" + v.length);
2552 for (int i = 0; i < v.length; i++)
2554 System.err.println("item " + i + " '" + v[i] + "'");
2561 System.err.println("Empty Array from '" + separator
2562 + "' separated List");
2568 * concatenate the list with separator
2571 * @return concatenated string
2573 public String arrayToSeparatorList(String[] list)
2575 return arrayToSeparatorList(list, separator);
2579 * concatenate the list with separator
2583 * @return concatenated string
2585 public static String arrayToSeparatorList(String[] list, String separator)
2587 // TODO use StringUtils version
2588 StringBuffer v = new StringBuffer();
2589 if (list != null && list.length > 0)
2591 for (int i = 0, iSize = list.length; i < iSize; i++)
2593 if (list[i] != null)
2597 v.append(separator);
2604 System.err.println("Returning '" + separator
2605 + "' separated List:\n");
2606 System.err.println(v);
2608 return v.toString();
2612 System.err.println("Returning empty '" + separator
2613 + "' separated List\n");
2615 return "" + separator;
2621 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroups()
2624 public String getFeatureGroups()
2626 String lst = arrayToSeparatorList(getDefaultTargetFrame()
2627 .getFeatureGroups());
2635 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOn(jalview.appletgui.AlignFrame
2639 public String getFeatureGroupsOn(AlignFrame alf)
2641 String lst = arrayToSeparatorList(alf.getFeatureGroups());
2648 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfState(boolean)
2651 public String getFeatureGroupsOfState(boolean visible)
2653 return arrayToSeparatorList(getDefaultTargetFrame()
2654 .getFeatureGroupsOfState(visible));
2661 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfStateOn(jalview.appletgui
2662 * .AlignFrame, boolean)
2665 public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
2667 return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
2673 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupStateOn(jalview.appletgui.
2674 * AlignFrame, java.lang.String, boolean)
2677 public void setFeatureGroupStateOn(final AlignFrame alf,
2678 final String groups, boolean state)
2680 final boolean st = state;// !(state==null || state.equals("") ||
2681 // state.toLowerCase().equals("false"));
2682 java.awt.EventQueue.invokeLater(new Runnable()
2687 alf.setFeatureGroupState(separatorListToArray(groups), st);
2695 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupState(java.lang.String,
2699 public void setFeatureGroupState(String groups, boolean state)
2701 setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
2707 * @see jalview.bin.JalviewLiteJsApi#getSeparator()
2710 public String getSeparator()
2718 * @see jalview.bin.JalviewLiteJsApi#setSeparator(java.lang.String)
2721 public void setSeparator(String separator)
2723 if (separator == null || separator.length() < 1)
2726 separator = "" + ((char) 0x00AC);
2728 this.separator = separator;
2731 System.err.println("Default Separator now: '" + separator + "'");
2736 * get boolean value of applet parameter 'name' and return default if
2737 * parameter is not set
2742 * the value to return otherwise
2743 * @return true or false
2745 public boolean getDefaultParameter(String name, boolean def)
2748 if ((stn = getParameter(name)) == null)
2752 if (TRUE.equalsIgnoreCase(stn))
2762 * @see jalview.bin.JalviewLiteJsApi#addPdbFile(jalview.appletgui.AlignFrame,
2763 * java.lang.String, java.lang.String, java.lang.String)
2766 public boolean addPdbFile(AlignFrame alFrame, String sequenceId,
2767 String pdbEntryString, String pdbFile)
2769 return alFrame.addPdbFile(sequenceId, pdbEntryString, pdbFile);
2772 protected void setAlignPdbStructures(boolean alignPdbStructures)
2774 this.alignPdbStructures = alignPdbStructures;
2777 public boolean isAlignPdbStructures()
2779 return alignPdbStructures;
2785 // callInitCallback();
2788 private Hashtable<String, long[]> jshashes = new Hashtable<String, long[]>();
2790 private Hashtable<String, Hashtable<String, String[]>> jsmessages = new Hashtable<String, Hashtable<String, String[]>>();
2792 public void setJsMessageSet(String messageclass, String viewId,
2793 String[] colcommands)
2795 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2798 msgset = new Hashtable<String, String[]>();
2799 jsmessages.put(messageclass, msgset);
2801 msgset.put(viewId, colcommands);
2802 long[] l = new long[colcommands.length];
2803 for (int i = 0; i < colcommands.length; i++)
2805 l[i] = colcommands[i].hashCode();
2807 jshashes.put(messageclass + "|" + viewId, l);
2813 * @see jalview.bin.JalviewLiteJsApi#getJsMessage(java.lang.String,
2817 public String getJsMessage(String messageclass, String viewId)
2819 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2822 String[] msgs = msgset.get(viewId);
2825 for (int i = 0; i < msgs.length; i++)
2827 if (msgs[i] != null)
2839 public boolean isJsMessageSetChanged(String string, String string2,
2840 String[] colcommands)
2842 long[] l = jshashes.get(string + "|" + string2);
2843 if (l == null && colcommands != null)
2847 for (int i = 0; i < colcommands.length; i++)
2849 if (l[i] != colcommands[i].hashCode())
2857 private Vector jsExecQueue = new Vector();
2859 public Vector getJsExecQueue()
2864 public void setExecutor(JSFunctionExec jsFunctionExec2)
2866 jsFunctionExec = jsFunctionExec2;
2870 * return the given colour value parameter or the given default if parameter
2877 public Color getDefaultColourParameter(String colparam, Color defcolour)
2879 String colprop = getParameter(colparam);
2880 if (colprop == null || colprop.trim().length() == 0)
2884 Color col = jalview.schemes.ColourSchemeProperty
2885 .getAWTColorFromName(colprop);
2890 col = new jalview.schemes.UserColourScheme(colprop).findColour('A');
2891 } catch (Exception ex)
2893 System.err.println("Couldn't parse '" + colprop
2894 + "' as a colour for " + colparam);
2898 return (col == null) ? defcolour : col;
2902 public void openJalviewHelpUrl()
2904 String helpUrl = getParameter("jalviewhelpurl");
2905 if (helpUrl == null || helpUrl.trim().length() < 5)
2907 helpUrl = "http://www.jalview.org/help.html";
2909 showURL(helpUrl, "HELP");
2913 * form a complete URL given a path to a resource and a reference location on
2917 * - an absolute path on the same server as localref or a document
2918 * located relative to localref
2920 * - a URL on the same server as url
2921 * @return a complete URL for the resource located by url
2923 private String resolveUrlForLocalOrAbsolute(String targetPath,
2926 String resolvedPath = "";
2927 if (targetPath.startsWith("/"))
2929 String codebase = localref.toString();
2930 String localfile = localref.getFile();
2931 resolvedPath = codebase.substring(0,
2932 codebase.length() - localfile.length())
2934 return resolvedPath;
2938 * get URL path and strip off any trailing file e.g.
2939 * www.jalview.org/examples/index.html#applets?a=b is trimmed to
2940 * www.jalview.org/examples/
2942 String urlPath = localref.toString();
2943 String directoryPath = urlPath;
2944 int lastSeparator = directoryPath.lastIndexOf("/");
2945 if (lastSeparator > 0)
2947 directoryPath = directoryPath.substring(0, lastSeparator + 1);
2950 if (targetPath.startsWith("/"))
2953 * construct absolute URL to a file on the server - this is not allowed?
2955 // String localfile = localref.getFile();
2956 // resolvedPath = urlPath.substring(0,
2957 // urlPath.length() - localfile.length())
2959 resolvedPath = directoryPath + targetPath.substring(1);
2963 resolvedPath = directoryPath + targetPath;
2967 System.err.println("resolveUrlForLocalOrAbsolute returning "
2970 return resolvedPath;
2974 * open a URL in the browser - resolving it according to relative refs and
2975 * coping with javascript: protocol if necessary.
2980 public void showURL(String url, String target)
2984 if (url.indexOf(":") == -1)
2986 // TODO: verify (Bas Vroling bug) prepend codebase or server URL to
2988 // Should really use docbase, not codebase.
2990 url = resolveUrlForLocalOrAbsolute(
2992 prepend = getDefaultParameter("resolvetocodebase", false) ? getCodeBase()
2993 : getDocumentBase());
2997 .println("Show url (prepended "
2999 + " - toggle resolvetocodebase if code/docbase resolution is wrong): "
3007 System.err.println("Show url: " + url);
3010 if (url.indexOf("javascript:") == 0)
3012 // no target for the javascript context
3013 getAppletContext().showDocument(new java.net.URL(url));
3017 getAppletContext().showDocument(new java.net.URL(url), target);
3019 } catch (Exception ex)
3021 ex.printStackTrace();
3026 * bind structures in a viewer to any matching sequences in an alignFrame (use
3027 * sequenceIds to limit scope of search to specific sequences)
3031 * @param sequenceIds
3032 * @return TODO: consider making an exception structure for indicating when
3033 * binding fails public SequenceStructureBinding
3034 * addStructureViewInstance( AlignFrame alFrame, Object viewer, String
3037 * if (sequenceIds != null && sequenceIds.length() > 0) { return
3038 * alFrame.addStructureViewInstance(viewer,
3039 * separatorListToArray(sequenceIds)); } else { return
3040 * alFrame.addStructureViewInstance(viewer, null); } // return null; }