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.MessageManager;
53 import java.applet.Applet;
54 import java.awt.Button;
55 import java.awt.Color;
56 import java.awt.Component;
57 import java.awt.EventQueue;
59 import java.awt.Frame;
60 import java.awt.Graphics;
61 import java.awt.event.ActionEvent;
62 import java.awt.event.WindowAdapter;
63 import java.awt.event.WindowEvent;
64 import java.io.BufferedReader;
65 import java.io.IOException;
66 import java.io.InputStream;
67 import java.io.InputStreamReader;
69 import java.util.ArrayList;
70 import java.util.Hashtable;
71 import java.util.List;
72 import java.util.StringTokenizer;
73 import java.util.Vector;
75 import netscape.javascript.JSObject;
78 * Jalview Applet. Runs in Java 1.18 runtime
81 * @version $Revision: 1.92 $
83 public class JalviewLite extends Applet implements
84 StructureSelectionManagerProvider, JalviewLiteJsApi
87 private static final String TRUE = "true";
89 private static final String FALSE = "false";
91 public StructureSelectionManager getStructureSelectionManager()
93 return StructureSelectionManager.getStructureSelectionManager(this);
96 // /////////////////////////////////////////
97 // The following public methods may be called
98 // externally, eg via javascript in HTML page
102 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences()
104 public String getSelectedSequences()
106 return getSelectedSequencesFrom(getDefaultTargetFrame());
112 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences(java.lang.String)
114 public String getSelectedSequences(String sep)
116 return getSelectedSequencesFrom(getDefaultTargetFrame(), sep);
123 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
126 public String getSelectedSequencesFrom(AlignFrame alf)
128 return getSelectedSequencesFrom(alf, separator); // ""+0x00AC);
135 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
136 * .AlignFrame, java.lang.String)
138 public String getSelectedSequencesFrom(AlignFrame alf, String sep)
140 StringBuffer result = new StringBuffer("");
141 if (sep == null || sep.length() == 0)
143 sep = separator; // "+0x00AC;
145 if (alf.viewport.getSelectionGroup() != null)
147 SequenceI[] seqs = alf.viewport.getSelectionGroup()
148 .getSequencesInOrder(alf.viewport.getAlignment());
150 for (int i = 0; i < seqs.length; i++)
152 result.append(seqs[i].getName());
157 return result.toString();
163 * @see jalview.bin.JalviewLiteJsApi#highlight(java.lang.String,
164 * java.lang.String, java.lang.String)
166 public void highlight(String sequenceId, String position,
167 String alignedPosition)
169 highlightIn(getDefaultTargetFrame(), sequenceId, position,
176 * @see jalview.bin.JalviewLiteJsApi#highlightIn(jalview.appletgui.AlignFrame,
177 * java.lang.String, java.lang.String, java.lang.String)
179 public void highlightIn(final AlignFrame alf, final String sequenceId,
180 final String position, final String alignedPosition)
182 // TODO: could try to highlight in all alignments if alf==null
183 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
184 alf.viewport.getAlignment().getSequencesArray());
185 final SequenceI sq = matcher.findIdMatch(sequenceId);
191 apos = new Integer(position).intValue();
193 } catch (NumberFormatException ex)
197 final StructureSelectionManagerProvider me = this;
198 final int pos = apos;
199 // use vamsas listener to broadcast to all listeners in scope
200 if (alignedPosition != null
201 && (alignedPosition.trim().length() == 0 || alignedPosition
202 .toLowerCase().indexOf("false") > -1))
204 java.awt.EventQueue.invokeLater(new Runnable()
209 StructureSelectionManager.getStructureSelectionManager(me)
210 .mouseOverVamsasSequence(sq, sq.findIndex(pos), null);
216 java.awt.EventQueue.invokeLater(new Runnable()
221 StructureSelectionManager.getStructureSelectionManager(me)
222 .mouseOverVamsasSequence(sq, pos, null);
232 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
235 public void select(String sequenceIds, String columns)
237 selectIn(getDefaultTargetFrame(), sequenceIds, columns, separator);
243 * @see jalview.bin.JalviewLiteJsApi#select(java.lang.String,
244 * java.lang.String, java.lang.String)
246 public void select(String sequenceIds, String columns, String sep)
248 selectIn(getDefaultTargetFrame(), sequenceIds, columns, sep);
254 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
255 * java.lang.String, java.lang.String)
257 public void selectIn(AlignFrame alf, String sequenceIds, String columns)
259 selectIn(alf, sequenceIds, columns, separator);
265 * @see jalview.bin.JalviewLiteJsApi#selectIn(jalview.appletgui.AlignFrame,
266 * java.lang.String, java.lang.String, java.lang.String)
268 public void selectIn(final AlignFrame alf, String sequenceIds,
269 String columns, String sep)
271 if (sep == null || sep.length() == 0)
279 System.err.println("Selecting region using separator string '"
284 String[] ids = separatorListToArray(sequenceIds, sep);
285 String[] cols = separatorListToArray(columns, sep);
286 final SequenceGroup sel = new SequenceGroup();
287 final ColumnSelection csel = new ColumnSelection();
288 AlignmentI al = alf.viewport.getAlignment();
289 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
290 alf.viewport.getAlignment().getSequencesArray());
291 int start = 0, end = al.getWidth(), alw = al.getWidth();
292 boolean seqsfound = true;
293 if (ids != null && ids.length > 0)
296 for (int i = 0; i < ids.length; i++)
298 if (ids[i].trim().length() == 0)
302 SequenceI sq = matcher.findIdMatch(ids[i]);
306 sel.addSequence(sq, false);
310 boolean inseqpos = false;
311 if (cols != null && cols.length > 0)
313 boolean seset = false;
314 for (int i = 0; i < cols.length; i++)
316 String cl = cols[i].trim();
317 if (cl.length() == 0)
322 if ((p = cl.indexOf("-")) > -1)
324 int from = -1, to = -1;
327 from = new Integer(cl.substring(0, p)).intValue();
329 } catch (NumberFormatException ex)
332 .println("ERROR: Couldn't parse first integer in range element column selection string '"
333 + cl + "' - format is 'from-to'");
338 to = new Integer(cl.substring(p + 1)).intValue();
340 } catch (NumberFormatException ex)
343 .println("ERROR: Couldn't parse second integer in range element column selection string '"
344 + cl + "' - format is 'from-to'");
347 if (from >= 0 && to >= 0)
364 // comment to prevent range extension
374 for (int r = from; r <= to; r++)
376 if (r >= 0 && r < alw)
383 System.err.println("Range '" + cl + "' deparsed as [" + from
389 System.err.println("ERROR: Invalid Range '" + cl
390 + "' deparsed as [" + from + "," + to + "]");
398 r = new Integer(cl).intValue();
400 } catch (NumberFormatException ex)
402 if (cl.toLowerCase().equals("sequence"))
404 // we are in the dataset sequence's coordinate frame.
410 .println("ERROR: Couldn't parse integer from point selection element of column selection string '"
415 if (r >= 0 && r <= alw)
425 // comment to prevent range extension
438 System.err.println("Point selection '" + cl
439 + "' deparsed as [" + r + "]");
444 System.err.println("ERROR: Invalid Point selection '" + cl
445 + "' deparsed as [" + r + "]");
452 // we only propagate the selection when it was the null selection, or the
453 // given sequences were found in the alignment.
454 if (inseqpos && sel.getSize() > 0)
456 // assume first sequence provides reference frame ?
457 SequenceI rs = sel.getSequenceAt(0);
458 start = rs.findIndex(start);
459 end = rs.findIndex(end);
462 List<Integer> cs = csel.getSelected();
464 for (Integer selectedCol : cs)
466 csel.addElement(rs.findIndex(selectedCol));
470 sel.setStartRes(start);
472 EventQueue.invokeLater(new Runnable()
477 alf.select(sel, csel);
487 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignment(java.lang.
488 * String, java.lang.String)
490 public String getSelectedSequencesAsAlignment(String format, String suffix)
492 return getSelectedSequencesAsAlignmentFrom(getDefaultTargetFrame(),
500 * jalview.bin.JalviewLiteJsApi#getSelectedSequencesAsAlignmentFrom(jalview
501 * .appletgui.AlignFrame, java.lang.String, java.lang.String)
503 public String getSelectedSequencesAsAlignmentFrom(AlignFrame alf,
504 String format, String suffix)
508 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
509 if (alf.viewport.getSelectionGroup() != null)
511 // JBPNote: getSelectionAsNewSequence behaviour has changed - this
512 // method now returns a full copy of sequence data
513 // TODO consider using getSequenceSelection instead here
514 String reply = new AppletFormatAdapter().formatSequences(format,
515 new Alignment(alf.viewport.getSelectionAsNewSequence()),
519 } catch (Exception ex)
521 ex.printStackTrace();
522 return "Error retrieving alignment in " + format + " format. ";
530 * @see jalview.bin.JalviewLiteJsApi#getAlignmentOrder()
532 public String getAlignmentOrder()
534 return getAlignmentOrderFrom(getDefaultTargetFrame());
541 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
544 public String getAlignmentOrderFrom(AlignFrame alf)
546 return getAlignmentOrderFrom(alf, separator);
553 * jalview.bin.JalviewLiteJsApi#getAlignmentOrderFrom(jalview.appletgui.AlignFrame
554 * , java.lang.String)
556 public String getAlignmentOrderFrom(AlignFrame alf, String sep)
558 AlignmentI alorder = alf.getAlignViewport().getAlignment();
559 String[] order = new String[alorder.getHeight()];
560 for (int i = 0; i < order.length; i++)
562 order[i] = alorder.getSequenceAt(i).getName();
564 return arrayToSeparatorList(order);
570 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
573 public String orderBy(String order, String undoName)
575 return orderBy(order, undoName, separator);
581 * @see jalview.bin.JalviewLiteJsApi#orderBy(java.lang.String,
582 * java.lang.String, java.lang.String)
584 public String orderBy(String order, String undoName, String sep)
586 return orderAlignmentBy(getDefaultTargetFrame(), order, undoName, sep);
593 * jalview.bin.JalviewLiteJsApi#orderAlignmentBy(jalview.appletgui.AlignFrame,
594 * java.lang.String, java.lang.String, java.lang.String)
596 public String orderAlignmentBy(AlignFrame alf, String order,
597 String undoName, String sep)
599 String[] ids = separatorListToArray(order, sep);
600 SequenceI[] sqs = null;
601 if (ids != null && ids.length > 0)
603 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
604 alf.viewport.getAlignment().getSequencesArray());
606 sqs = new SequenceI[ids.length];
607 for (int i = 0; i < ids.length; i++)
609 if (ids[i].trim().length() == 0)
613 SequenceI sq = matcher.findIdMatch(ids[i]);
621 SequenceI[] sqq = new SequenceI[s];
622 System.arraycopy(sqs, 0, sqq, 0, s);
635 final AlignmentOrder aorder = new AlignmentOrder(sqs);
637 if (undoName != null && undoName.trim().length() == 0)
641 final String _undoName = undoName;
642 // TODO: deal with synchronization here: cannot raise any events until after
643 // this has returned.
644 return alf.sortBy(aorder, _undoName) ? TRUE : "";
650 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String)
652 public String getAlignment(String format)
654 return getAlignmentFrom(getDefaultTargetFrame(), format, TRUE);
661 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
664 public String getAlignmentFrom(AlignFrame alf, String format)
666 return getAlignmentFrom(alf, format, TRUE);
672 * @see jalview.bin.JalviewLiteJsApi#getAlignment(java.lang.String,
675 public String getAlignment(String format, String suffix)
677 return getAlignmentFrom(getDefaultTargetFrame(), format, suffix);
684 * jalview.bin.JalviewLiteJsApi#getAlignmentFrom(jalview.appletgui.AlignFrame,
685 * java.lang.String, java.lang.String)
687 public String getAlignmentFrom(AlignFrame alf, String format,
692 boolean seqlimits = suffix.equalsIgnoreCase(TRUE);
694 String reply = new AppletFormatAdapter().formatSequences(format,
695 alf.viewport.getAlignment(), seqlimits);
697 } catch (Exception ex)
699 ex.printStackTrace();
700 return "Error retrieving alignment in " + format + " format. ";
707 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
709 public void loadAnnotation(String annotation)
711 loadAnnotationFrom(getDefaultTargetFrame(), annotation);
718 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
719 * , java.lang.String)
721 public void loadAnnotationFrom(AlignFrame alf, String annotation)
723 if (new AnnotationFile().annotateAlignmentView(alf.getAlignViewport(),
724 annotation, AppletFormatAdapter.PASTE))
726 alf.alignPanel.fontChanged();
727 alf.alignPanel.setScrollValues(0, 0);
731 alf.parseFeaturesFile(annotation, AppletFormatAdapter.PASTE);
738 * @see jalview.bin.JalviewLiteJsApi#loadAnnotation(java.lang.String)
740 public void loadFeatures(String features, boolean autoenabledisplay)
742 loadFeaturesFrom(getDefaultTargetFrame(), features, autoenabledisplay);
749 * jalview.bin.JalviewLiteJsApi#loadAnnotationFrom(jalview.appletgui.AlignFrame
750 * , java.lang.String)
752 public boolean loadFeaturesFrom(AlignFrame alf, String features,
753 boolean autoenabledisplay)
755 return alf.parseFeaturesFile(features, AppletFormatAdapter.PASTE,
762 * @see jalview.bin.JalviewLiteJsApi#getFeatures(java.lang.String)
764 public String getFeatures(String format)
766 return getFeaturesFrom(getDefaultTargetFrame(), format);
773 * jalview.bin.JalviewLiteJsApi#getFeaturesFrom(jalview.appletgui.AlignFrame,
776 public String getFeaturesFrom(AlignFrame alf, String format)
778 return alf.outputFeatures(false, format);
784 * @see jalview.bin.JalviewLiteJsApi#getAnnotation()
786 public String getAnnotation()
788 return getAnnotationFrom(getDefaultTargetFrame());
795 * jalview.bin.JalviewLiteJsApi#getAnnotationFrom(jalview.appletgui.AlignFrame
798 public String getAnnotationFrom(AlignFrame alf)
800 return alf.outputAnnotations(false);
806 * @see jalview.bin.JalviewLiteJsApi#newView()
808 public AlignFrame newView()
810 return newViewFrom(getDefaultTargetFrame());
816 * @see jalview.bin.JalviewLiteJsApi#newView(java.lang.String)
818 public AlignFrame newView(String name)
820 return newViewFrom(getDefaultTargetFrame(), name);
826 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame)
828 public AlignFrame newViewFrom(AlignFrame alf)
830 return alf.newView(null);
836 * @see jalview.bin.JalviewLiteJsApi#newViewFrom(jalview.appletgui.AlignFrame,
839 public AlignFrame newViewFrom(AlignFrame alf, String name)
841 return alf.newView(name);
847 * @see jalview.bin.JalviewLiteJsApi#loadAlignment(java.lang.String,
850 public AlignFrame loadAlignment(String text, String title)
852 AlignmentI al = null;
854 String format = new IdentifyFile().Identify(text,
855 AppletFormatAdapter.PASTE);
858 al = new AppletFormatAdapter().readFile(text,
859 AppletFormatAdapter.PASTE, format);
860 if (al.getHeight() > 0)
862 return new AlignFrame(al, this, title, false);
864 } catch (java.io.IOException ex)
866 ex.printStackTrace();
874 * @see jalview.bin.JalviewLiteJsApi#setMouseoverListener(java.lang.String)
876 public void setMouseoverListener(String listener)
878 setMouseoverListener(currentAlignFrame, listener);
881 private Vector<jalview.javascript.JSFunctionExec> javascriptListeners = new Vector<jalview.javascript.JSFunctionExec>();
887 * jalview.bin.JalviewLiteJsApi#setMouseoverListener(jalview.appletgui.AlignFrame
888 * , java.lang.String)
890 public void setMouseoverListener(AlignFrame af, String listener)
892 if (listener != null)
894 listener = listener.trim();
895 if (listener.length() == 0)
898 .println("jalview Javascript error: Ignoring empty function for mouseover listener.");
902 jalview.javascript.MouseOverListener mol = new jalview.javascript.MouseOverListener(
904 javascriptListeners.addElement(mol);
905 StructureSelectionManager.getStructureSelectionManager(this)
906 .addStructureViewerListener(mol);
909 System.err.println("Added a mouseover listener for "
910 + ((af == null) ? "All frames" : "Just views for "
911 + af.getAlignViewport().getSequenceSetId()));
912 System.err.println("There are now " + javascriptListeners.size()
913 + " listeners in total.");
920 * @see jalview.bin.JalviewLiteJsApi#setSelectionListener(java.lang.String)
922 public void setSelectionListener(String listener)
924 setSelectionListener(null, listener);
931 * jalview.bin.JalviewLiteJsApi#setSelectionListener(jalview.appletgui.AlignFrame
932 * , java.lang.String)
934 public void setSelectionListener(AlignFrame af, String listener)
936 if (listener != null)
938 listener = listener.trim();
939 if (listener.length() == 0)
942 .println("jalview Javascript error: Ignoring empty function for selection listener.");
946 jalview.javascript.JsSelectionSender mol = new jalview.javascript.JsSelectionSender(
948 javascriptListeners.addElement(mol);
949 StructureSelectionManager.getStructureSelectionManager(this)
950 .addSelectionListener(mol);
953 System.err.println("Added a selection listener for "
954 + ((af == null) ? "All frames" : "Just views for "
955 + af.getAlignViewport().getSequenceSetId()));
956 System.err.println("There are now " + javascriptListeners.size()
957 + " listeners in total.");
962 * Callable from javascript to register a javascript function to pass events
963 * to a structure viewer.
966 * the name of a javascript function
968 * a token separated list of PDB file names listened for
969 * @see jalview.bin.JalviewLiteJsApi#setStructureListener(java.lang.String,
972 public void setStructureListener(String listener, String modelSet)
974 if (listener != null)
976 listener = listener.trim();
977 if (listener.length() == 0)
980 .println("jalview Javascript error: Ignoring empty function for selection listener.");
984 MouseOverStructureListener mol = new MouseOverStructureListener(this,
985 listener, separatorListToArray(modelSet));
986 javascriptListeners.addElement(mol);
987 StructureSelectionManager.getStructureSelectionManager(this)
988 .addStructureViewerListener(mol);
991 System.err.println("Added a javascript structure viewer listener '"
993 System.err.println("There are now " + javascriptListeners.size()
994 + " listeners in total.");
1002 * jalview.bin.JalviewLiteJsApi#removeJavascriptListener(jalview.appletgui
1003 * .AlignFrame, java.lang.String)
1005 public void removeJavascriptListener(AlignFrame af, String listener)
1007 if (listener != null)
1009 listener = listener.trim();
1010 if (listener.length() == 0)
1015 boolean rprt = false;
1016 for (int ms = 0, msSize = javascriptListeners.size(); ms < msSize;)
1018 Object lstn = javascriptListeners.elementAt(ms);
1019 JsCallBack lstner = (JsCallBack) lstn;
1020 if ((af == null || lstner.getAlignFrame() == af)
1021 && (listener == null || lstner.getListenerFunction().equals(
1024 javascriptListeners.removeElement(lstner);
1026 if (lstner instanceof SelectionListener)
1028 StructureSelectionManager.getStructureSelectionManager(this)
1029 .removeSelectionListener((SelectionListener) lstner);
1033 StructureSelectionManager.getStructureSelectionManager(this)
1034 .removeStructureViewerListener(lstner, null);
1039 System.err.println("Removed listener '" + listener + "'");
1049 System.err.println("There are now " + javascriptListeners.size()
1050 + " listeners in total.");
1056 System.err.println("Applet " + getName() + " stop().");
1060 public void destroy()
1062 System.err.println("Applet " + getName() + " destroy().");
1066 private void tidyUp()
1069 if (currentAlignFrame != null && currentAlignFrame.viewport != null
1070 && currentAlignFrame.viewport.applet != null)
1072 AlignViewport av = currentAlignFrame.viewport;
1073 currentAlignFrame.closeMenuItem_actionPerformed();
1075 currentAlignFrame = null;
1077 if (javascriptListeners != null)
1079 while (javascriptListeners.size() > 0)
1081 jalview.javascript.JSFunctionExec mol = javascriptListeners
1083 javascriptListeners.removeElement(mol);
1084 if (mol instanceof SelectionListener)
1086 StructureSelectionManager.getStructureSelectionManager(this)
1087 .removeSelectionListener((SelectionListener) mol);
1091 StructureSelectionManager.getStructureSelectionManager(this)
1092 .removeStructureViewerListener(mol, null);
1097 if (jsFunctionExec != null)
1099 jsFunctionExec.stopQueue();
1100 jsFunctionExec.jvlite = null;
1102 initialAlignFrame = null;
1103 jsFunctionExec = null;
1104 javascriptListeners = null;
1105 StructureSelectionManager.release(this);
1108 private jalview.javascript.JSFunctionExec jsFunctionExec;
1113 * @see jalview.bin.JalviewLiteJsApi#mouseOverStructure(java.lang.String,
1114 * java.lang.String, java.lang.String)
1116 public void mouseOverStructure(final String pdbResNum,
1117 final String chain, final String pdbfile)
1119 final StructureSelectionManagerProvider me = this;
1120 java.awt.EventQueue.invokeLater(new Runnable()
1127 StructureSelectionManager.getStructureSelectionManager(me)
1128 .mouseOverStructure(new Integer(pdbResNum).intValue(),
1132 System.err.println("mouseOver for '" + pdbResNum
1133 + "' in chain '" + chain + "' in structure '" + pdbfile
1136 } catch (NumberFormatException e)
1138 System.err.println("Ignoring invalid residue number string '"
1150 * jalview.bin.JalviewLiteJsApi#scrollViewToIn(jalview.appletgui.AlignFrame,
1151 * java.lang.String, java.lang.String)
1153 public void scrollViewToIn(final AlignFrame alf, final String topRow,
1154 final String leftHandColumn)
1156 java.awt.EventQueue.invokeLater(new Runnable()
1163 alf.scrollTo(new Integer(topRow).intValue(), new Integer(
1164 leftHandColumn).intValue());
1166 } catch (Exception ex)
1168 System.err.println("Couldn't parse integer arguments (topRow='"
1169 + topRow + "' and leftHandColumn='" + leftHandColumn
1171 ex.printStackTrace();
1181 * jalview.javascript.JalviewLiteJsApi#scrollViewToRowIn(jalview.appletgui
1182 * .AlignFrame, java.lang.String)
1185 public void scrollViewToRowIn(final AlignFrame alf, final String topRow)
1188 java.awt.EventQueue.invokeLater(new Runnable()
1195 alf.scrollToRow(new Integer(topRow).intValue());
1197 } catch (Exception ex)
1199 System.err.println("Couldn't parse integer arguments (topRow='"
1201 ex.printStackTrace();
1212 * jalview.javascript.JalviewLiteJsApi#scrollViewToColumnIn(jalview.appletgui
1213 * .AlignFrame, java.lang.String)
1216 public void scrollViewToColumnIn(final AlignFrame alf,
1217 final String leftHandColumn)
1219 java.awt.EventQueue.invokeLater(new Runnable()
1227 alf.scrollToColumn(new Integer(leftHandColumn).intValue());
1229 } catch (Exception ex)
1232 .println("Couldn't parse integer arguments (leftHandColumn='"
1233 + leftHandColumn + "')");
1234 ex.printStackTrace();
1241 // //////////////////////////////////////////////
1242 // //////////////////////////////////////////////
1244 public static int lastFrameX = 200;
1246 public static int lastFrameY = 200;
1248 boolean fileFound = true;
1250 String file = "No file";
1252 String file2 = null;
1254 Button launcher = new Button(
1255 MessageManager.getString("label.start_jalview"));
1258 * The currentAlignFrame is static, it will change if and when the user
1259 * selects a new window. Note that it will *never* point back to the embedded
1260 * AlignFrame if the applet is started as embedded on the page and then
1261 * afterwards a new view is created.
1263 public AlignFrame currentAlignFrame = null;
1266 * This is the first frame to be displayed, and does not change. API calls
1267 * will default to this instance if currentAlignFrame is null.
1269 AlignFrame initialAlignFrame = null;
1271 boolean embedded = false;
1273 private boolean checkForJmol = true;
1275 private boolean checkedForJmol = false; // ensure we don't check for jmol
1277 // every time the app is re-inited
1279 public boolean jmolAvailable = false;
1281 private boolean alignPdbStructures = false;
1284 * use an external structure viewer exclusively (no jmols or MCViews will be
1285 * opened by JalviewLite itself)
1287 public boolean useXtrnalSviewer = false;
1289 public static boolean debug = false;
1291 static String builddate = null, version = null, installation = null;
1293 private static void initBuildDetails()
1295 if (builddate == null)
1297 builddate = "unknown";
1299 installation = "applet";
1300 java.net.URL url = JalviewLite.class
1301 .getResource("/.build_properties");
1306 BufferedReader reader = new BufferedReader(new InputStreamReader(
1309 while ((line = reader.readLine()) != null)
1311 if (line.indexOf("VERSION") > -1)
1313 version = line.substring(line.indexOf("=") + 1);
1315 if (line.indexOf("BUILD_DATE") > -1)
1317 builddate = line.substring(line.indexOf("=") + 1);
1319 if (line.indexOf("INSTALLATION") > -1)
1321 installation = line.substring(line.indexOf("=") + 1);
1324 } catch (Exception ex)
1326 ex.printStackTrace();
1332 public static String getBuildDate()
1338 public static String getInstallation()
1341 return installation;
1344 public static String getVersion()
1350 // public JSObject scriptObject = null;
1353 * init method for Jalview Applet
1358 debug = TRUE.equalsIgnoreCase(getParameter("debug"));
1363 System.err.println("Applet context is '"
1364 + getAppletContext().getClass().toString() + "'");
1366 JSObject scriptObject = JSObject.getWindow(this);
1367 if (debug && scriptObject != null)
1369 System.err.println("Applet has Javascript callback support.");
1372 } catch (Exception ex)
1375 .println("Warning: No JalviewLite javascript callbacks available.");
1378 ex.printStackTrace();
1384 System.err.println("JalviewLite Version " + getVersion());
1385 System.err.println("Build Date : " + getBuildDate());
1386 System.err.println("Installation : " + getInstallation());
1388 String externalsviewer = getParameter("externalstructureviewer");
1389 if (externalsviewer != null)
1391 useXtrnalSviewer = externalsviewer.trim().toLowerCase().equals(TRUE);
1394 * if true disable the check for jmol
1396 String chkforJmol = getParameter("nojmol");
1397 if (chkforJmol != null)
1399 checkForJmol = !chkforJmol.equals(TRUE);
1402 * get the separator parameter if present
1404 String sep = getParameter("separator");
1407 if (sep.length() > 0)
1412 System.err.println("Separator set to '" + separator + "'");
1419 .getString("error.invalid_separator_parameter"));
1425 String param = getParameter("RGB");
1431 r = Integer.parseInt(param.substring(0, 2), 16);
1432 g = Integer.parseInt(param.substring(2, 4), 16);
1433 b = Integer.parseInt(param.substring(4, 6), 16);
1434 } catch (Exception ex)
1441 param = getParameter("label");
1444 launcher.setLabel(param);
1447 setBackground(new Color(r, g, b));
1449 file = getParameter("file");
1453 // Maybe the sequences are added as parameters
1454 StringBuffer data = new StringBuffer("PASTE");
1456 while ((file = getParameter("sequence" + i)) != null)
1458 data.append(file.toString() + "\n");
1461 if (data.length() > 5)
1463 file = data.toString();
1466 if (getDefaultParameter("enableSplitFrame", true))
1468 file2 = getParameter("file2");
1471 embedded = TRUE.equalsIgnoreCase(getParameter("embedded"));
1474 LoadingThread loader = new LoadingThread(file, file2, this);
1477 else if (file != null)
1480 * Start the applet immediately or show a button to start it
1482 if (FALSE.equalsIgnoreCase(getParameter("showbutton")))
1484 LoadingThread loader = new LoadingThread(file, file2, this);
1490 launcher.addActionListener(new java.awt.event.ActionListener()
1492 public void actionPerformed(ActionEvent e)
1494 LoadingThread loader = new LoadingThread(file, file2,
1503 // jalview initialisation with no alignment. loadAlignment() method can
1504 // still be called to open new alignments.
1511 private void initLiveConnect()
1513 // try really hard to get the liveConnect thing working
1514 boolean notFailed = false;
1516 while (!notFailed && tries < 10)
1520 System.err.println("LiveConnect request thread going to sleep.");
1524 Thread.sleep(700 * (1 + tries));
1525 } catch (InterruptedException q)
1531 System.err.println("LiveConnect request thread woken up.");
1535 JSObject scriptObject = JSObject.getWindow(this);
1536 if (scriptObject.eval("navigator") != null)
1540 } catch (Exception jsex)
1542 System.err.println("Attempt " + tries
1543 + " to access LiveConnect javascript failed.");
1548 private void callInitCallback()
1550 String initjscallback = getParameter("oninit");
1551 if (initjscallback == null)
1555 initjscallback = initjscallback.trim();
1556 if (initjscallback.length() > 0)
1558 JSObject scriptObject = null;
1561 scriptObject = JSObject.getWindow(this);
1562 } catch (Exception ex)
1566 // try really hard to let the browser plugin know we want liveconnect
1569 if (scriptObject != null)
1573 // do onInit with the JS executor thread
1574 new JSFunctionExec(this).executeJavascriptFunction(true,
1575 initjscallback, null, "Calling oninit callback '"
1576 + initjscallback + "'.");
1577 } catch (Exception e)
1579 System.err.println("Exception when executing _oninit callback '"
1580 + initjscallback + "'.");
1581 e.printStackTrace();
1586 System.err.println("Not executing _oninit callback '"
1587 + initjscallback + "' - no scripting allowed.");
1593 * Initialises and displays a new java.awt.Frame
1596 * java.awt.Frame to be displayed
1598 * title of new frame
1600 * width if new frame
1602 * height of new frame
1604 public static void addFrame(final Frame frame, String title, int width,
1607 frame.setLocation(lastFrameX, lastFrameY);
1610 frame.setSize(width, height);
1611 frame.setTitle(title);
1612 frame.addWindowListener(new WindowAdapter()
1614 public void windowClosing(WindowEvent e)
1616 if (frame instanceof AlignFrame)
1618 AlignViewport vp = ((AlignFrame) frame).viewport;
1619 ((AlignFrame) frame).closeMenuItem_actionPerformed();
1620 if (vp.applet.currentAlignFrame == frame)
1622 vp.applet.currentAlignFrame = null;
1630 if (frame instanceof EmbmenuFrame)
1632 ((EmbmenuFrame) frame).destroyMenus();
1634 frame.setMenuBar(null);
1638 public void windowActivated(WindowEvent e)
1640 if (frame instanceof AlignFrame)
1642 ((AlignFrame) frame).viewport.applet.currentAlignFrame = (AlignFrame) frame;
1645 System.err.println("Activated window " + frame);
1649 super.windowActivated(e);
1652 * Probably not necessary to do this - see TODO above. (non-Javadoc)
1655 * java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent
1658 * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
1659 * frame) { currentAlignFrame = null; if (debug) {
1660 * System.err.println("Deactivated window "+frame); } }
1661 * super.windowDeactivated(e); }
1664 frame.setVisible(true);
1668 * This paints the background surrounding the "Launch Jalview button" <br>
1670 * If file given in parameter not found, displays error message
1675 public void paint(Graphics g)
1679 g.setColor(new Color(200, 200, 200));
1680 g.setColor(Color.cyan);
1681 g.fillRect(0, 0, getSize().width, getSize().height);
1682 g.setColor(Color.red);
1684 MessageManager.getString("label.jalview_cannot_open_file"),
1686 g.drawString("\"" + file + "\"", 5, 30);
1690 g.setColor(Color.black);
1691 g.setFont(new Font("Arial", Font.BOLD, 24));
1692 g.drawString(MessageManager.getString("label.jalview_applet"), 50,
1693 getSize().height / 2 - 30);
1694 g.drawString(MessageManager.getString("label.loading_data") + "...",
1695 50, getSize().height / 2);
1700 * get all components associated with the applet of the given type
1705 public Vector getAppletWindow(Class class1)
1707 Vector wnds = new Vector();
1708 Component[] cmp = getComponents();
1711 for (int i = 0; i < cmp.length; i++)
1713 if (class1.isAssignableFrom(cmp[i].getClass()))
1715 wnds.addElement(cmp);
1722 class LoadJmolThread extends Thread
1724 private boolean running = false;
1728 if (running || checkedForJmol)
1737 if (!System.getProperty("java.version").startsWith("1.1"))
1739 Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
1740 jmolAvailable = true;
1745 .println("Jmol not available - Using MCview for structures");
1747 } catch (java.lang.ClassNotFoundException ex)
1753 jmolAvailable = false;
1757 .println("Skipping Jmol check. Will use MCView (probably)");
1760 checkedForJmol = true;
1764 public boolean notFinished()
1766 return running || !checkedForJmol;
1770 class LoadingThread extends Thread
1773 * State variable: protocol for access to file source
1777 String _file; // alignment file or URL spec
1779 String _file2; // second alignment file or URL spec
1783 private void dbgMsg(String msg)
1785 if (JalviewLite.debug)
1787 System.err.println(msg);
1792 * update the protocol state variable for accessing the datasource located
1796 * @return possibly updated datasource string
1798 public String resolveFileProtocol(String path)
1803 if (path.startsWith("PASTE"))
1805 protocol = AppletFormatAdapter.PASTE;
1806 return path.substring(5);
1812 if (path.indexOf("://") != -1)
1814 protocol = AppletFormatAdapter.URL;
1819 * try relative to document root
1821 URL documentBase = getDocumentBase();
1822 String withDocBase = resolveUrlForLocalOrAbsolute(path, documentBase);
1823 if (urlExists(withDocBase))
1827 System.err.println("Prepended document base '" + documentBase
1828 + "' to make: '" + withDocBase + "'");
1830 protocol = AppletFormatAdapter.URL;
1835 * try relative to codebase (if different to document base)
1837 URL codeBase = getCodeBase();
1838 String withCodeBase = applet.resolveUrlForLocalOrAbsolute(path,
1840 if (!withCodeBase.equals(withDocBase) && urlExists(withCodeBase))
1842 protocol = AppletFormatAdapter.URL;
1845 System.err.println("Prepended codebase '" + codeBase
1846 + "' to make: '" + withCodeBase + "'");
1848 return withCodeBase;
1852 * try locating by classloader; try this last so files in the directory
1853 * are resolved using document base
1855 if (inArchive(path))
1857 protocol = AppletFormatAdapter.CLASSLOADER;
1862 public LoadingThread(String file, String file2, JalviewLite _applet)
1865 this._file2 = file2;
1871 LoadJmolThread jmolchecker = new LoadJmolThread();
1872 jmolchecker.start();
1873 while (jmolchecker.notFinished())
1875 // wait around until the Jmol check is complete.
1879 } catch (Exception e)
1884 // applet.callInitCallback();
1888 * Load the alignment and any related files as specified by applet
1891 private void startLoading()
1893 dbgMsg("Loading thread started with:\n>>file\n" + _file + ">>endfile");
1895 dbgMsg("Loading started.");
1897 AlignFrame newAlignFrame = readAlignment(_file);
1898 AlignFrame newAlignFrame2 = readAlignment(_file2);
1899 if (newAlignFrame != null)
1901 addToDisplay(newAlignFrame, newAlignFrame2);
1902 loadTree(newAlignFrame);
1904 loadScoreFile(newAlignFrame);
1906 loadFeatures(newAlignFrame);
1908 loadAnnotations(newAlignFrame);
1910 loadJnetFile(newAlignFrame);
1912 loadPdbFiles(newAlignFrame);
1917 applet.remove(launcher);
1924 * Add an AlignFrame to the display; or if two are provided, a SplitFrame.
1929 public void addToDisplay(AlignFrame af, AlignFrame af2)
1933 AlignmentI al1 = af.viewport.getAlignment();
1934 AlignmentI al2 = af2.viewport.getAlignment();
1935 AlignmentI cdna = al1.isNucleotide() ? al1 : al2;
1936 AlignmentI prot = al1.isNucleotide() ? al2 : al1;
1937 if (AlignmentUtils.mapProteinAlignmentToCdna(prot, cdna))
1940 SplitFrame sf = new SplitFrame(af, af2);
1941 sf.addToDisplay(embedded, JalviewLite.this);
1946 String msg = "Could not map any sequence in " + af2.getTitle()
1948 + (al1.isNucleotide() ? "protein product" : "cDNA")
1949 + " for " + af.getTitle();
1950 System.err.println(msg);
1954 af.addToDisplay(embedded);
1958 * Read the alignment file (from URL, text 'paste', or archive by
1963 protected AlignFrame readAlignment(String fileParam)
1965 if (fileParam == null)
1969 String resolvedFile = resolveFileProtocol(fileParam);
1970 String format = new IdentifyFile().Identify(resolvedFile, protocol);
1971 dbgMsg("File identified as '" + format + "'");
1972 AlignmentI al = null;
1975 al = new AppletFormatAdapter().readFile(resolvedFile, protocol,
1977 if ((al != null) && (al.getHeight() > 0))
1979 dbgMsg("Successfully loaded file.");
1980 al.setDataset(null);
1981 AlignFrame newAlignFrame = new AlignFrame(al, applet,
1982 resolvedFile, embedded, false);
1983 newAlignFrame.setTitle(resolvedFile);
1984 if (initialAlignFrame == null)
1986 initialAlignFrame = newAlignFrame;
1988 // update the focus.
1989 currentAlignFrame = newAlignFrame;
1991 if (protocol == AppletFormatAdapter.PASTE)
1993 newAlignFrame.setTitle(MessageManager.formatMessage(
1994 "label.sequences_from", new Object[] { applet
1995 .getDocumentBase().toString() }));
1998 newAlignFrame.statusBar.setText(MessageManager.formatMessage(
1999 "label.successfully_loaded_file",
2000 new Object[] { resolvedFile }));
2002 return newAlignFrame;
2004 } catch (java.io.IOException ex)
2006 dbgMsg("File load exception.");
2007 ex.printStackTrace();
2012 FileParse fp = new FileParse(resolvedFile, protocol);
2014 dbgMsg(">>>Dumping contents of '" + resolvedFile + "' " + "("
2016 while ((ln = fp.nextLine()) != null)
2020 dbgMsg(">>>Dump finished.");
2021 } catch (Exception e)
2024 .println("Exception when trying to dump the content of the file parameter.");
2025 e.printStackTrace();
2033 * Load PDBFiles if any specified by parameter(s). Returns true if loaded,
2039 protected boolean loadPdbFiles(AlignFrame alignFrame)
2041 boolean result = false;
2043 * <param name="alignpdbfiles" value="false/true"/> Undocumented for 2.6 -
2044 * related to JAL-434
2047 applet.setAlignPdbStructures(getDefaultParameter("alignpdbfiles",
2050 * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
2053 * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
2055 * <param name="PDBfile3" value="1q0o Q45135_9MICO">
2058 int pdbFileCount = 0;
2059 // Accumulate pdbs here if they are heading for the same view (if
2060 // alignPdbStructures is true)
2061 Vector pdbs = new Vector();
2062 // create a lazy matcher if we're asked to
2063 jalview.analysis.SequenceIdMatcher matcher = (applet
2064 .getDefaultParameter("relaxedidmatch", false)) ? new jalview.analysis.SequenceIdMatcher(
2065 alignFrame.getAlignViewport().getAlignment()
2066 .getSequencesArray()) : null;
2071 if (pdbFileCount > 0)
2073 param = applet.getParameter("PDBFILE" + pdbFileCount);
2077 param = applet.getParameter("PDBFILE");
2082 PDBEntry pdb = new PDBEntry();
2085 SequenceI[] seqs = null;
2086 String[] chains = null;
2088 StringTokenizer st = new StringTokenizer(param, " ");
2090 if (st.countTokens() < 2)
2092 String sequence = applet.getParameter("PDBSEQ");
2093 if (sequence != null)
2095 seqs = new SequenceI[] { matcher == null ? (Sequence) alignFrame
2096 .getAlignViewport().getAlignment().findName(sequence)
2097 : matcher.findIdMatch(sequence) };
2103 param = st.nextToken();
2104 List<SequenceI> tmp = new ArrayList<SequenceI>();
2105 List<String> tmp2 = new ArrayList<String>();
2107 while (st.hasMoreTokens())
2109 seqstring = st.nextToken();
2110 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
2111 if (st2.countTokens() > 1)
2113 // This is the chain
2114 tmp2.add(st2.nextToken());
2115 seqstring = st2.nextToken();
2117 tmp.add(matcher == null ? (Sequence) alignFrame
2118 .getAlignViewport().getAlignment()
2119 .findName(seqstring) : matcher.findIdMatch(seqstring));
2122 seqs = tmp.toArray(new SequenceI[tmp.size()]);
2123 if (tmp2.size() == tmp.size())
2125 chains = tmp2.toArray(new String[tmp2.size()]);
2128 param = resolveFileProtocol(param);
2129 // TODO check JAL-357 for files in a jar (CLASSLOADER)
2134 for (int i = 0; i < seqs.length; i++)
2136 if (seqs[i] != null)
2138 ((Sequence) seqs[i]).addPDBId(pdb);
2139 StructureSelectionManager.getStructureSelectionManager(
2140 applet).registerPDBEntry(pdb);
2144 if (JalviewLite.debug)
2146 // this may not really be a problem but we give a warning
2149 .println("Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
2155 if (!alignPdbStructures)
2157 alignFrame.newStructureView(applet, pdb, seqs, chains,
2162 pdbs.addElement(new Object[] { pdb, seqs, chains,
2163 new String(protocol) });
2169 } while (param != null || pdbFileCount < 10);
2170 if (pdbs.size() > 0)
2172 SequenceI[][] seqs = new SequenceI[pdbs.size()][];
2173 PDBEntry[] pdb = new PDBEntry[pdbs.size()];
2174 String[][] chains = new String[pdbs.size()][];
2175 String[] protocols = new String[pdbs.size()];
2176 for (int pdbsi = 0, pdbsiSize = pdbs.size(); pdbsi < pdbsiSize; pdbsi++)
2178 Object[] o = (Object[]) pdbs.elementAt(pdbsi);
2179 pdb[pdbsi] = (PDBEntry) o[0];
2180 seqs[pdbsi] = (SequenceI[]) o[1];
2181 chains[pdbsi] = (String[]) o[2];
2182 protocols[pdbsi] = (String) o[3];
2184 alignFrame.alignedStructureView(applet, pdb, seqs, chains,
2192 * Load in a Jnetfile if specified by parameter. Returns true if loaded,
2198 protected boolean loadJnetFile(AlignFrame alignFrame)
2200 boolean result = false;
2201 String param = applet.getParameter("jnetfile");
2206 param = resolveFileProtocol(param);
2207 JPredFile predictions = new JPredFile(param, protocol);
2208 JnetAnnotationMaker.add_annotation(predictions,
2209 alignFrame.viewport.getAlignment(), 0, false);
2210 // false == do not add sequence profile from concise output
2211 SequenceI repseq = alignFrame.viewport.getAlignment()
2213 alignFrame.viewport.getAlignment().setSeqrep(repseq);
2214 ColumnSelection cs = new ColumnSelection();
2215 cs.hideInsertionsFor(repseq);
2216 alignFrame.viewport.setColumnSelection(cs);
2217 alignFrame.alignPanel.fontChanged();
2218 alignFrame.alignPanel.setScrollValues(0, 0);
2220 } catch (Exception ex)
2222 ex.printStackTrace();
2229 * Load annotations if specified by parameter. Returns true if loaded, else
2235 protected boolean loadAnnotations(AlignFrame alignFrame)
2237 boolean result = false;
2238 String param = applet.getParameter("annotations");
2241 param = resolveFileProtocol(param);
2243 if (new AnnotationFile().annotateAlignmentView(alignFrame.viewport,
2246 alignFrame.alignPanel.fontChanged();
2247 alignFrame.alignPanel.setScrollValues(0, 0);
2253 .println("Annotations were not added from annotation file '"
2261 * Load features file and view settings as specified by parameters. Returns
2262 * true if features were loaded, else false.
2267 protected boolean loadFeatures(AlignFrame alignFrame)
2269 boolean result = false;
2270 // ///////////////////////////
2271 // modify display of features
2272 // we do this before any features have been loaded, ensuring any hidden
2273 // groups are hidden when features first displayed
2275 // hide specific groups
2277 String param = applet.getParameter("hidefeaturegroups");
2280 alignFrame.setFeatureGroupState(separatorListToArray(param), false);
2281 // applet.setFeatureGroupStateOn(newAlignFrame, param, false);
2283 // show specific groups
2284 param = applet.getParameter("showfeaturegroups");
2287 alignFrame.setFeatureGroupState(separatorListToArray(param), true);
2288 // applet.setFeatureGroupStateOn(newAlignFrame, param, true);
2290 // and now load features
2291 param = applet.getParameter("features");
2294 param = resolveFileProtocol(param);
2296 result = alignFrame.parseFeaturesFile(param, protocol);
2299 param = applet.getParameter("showFeatureSettings");
2300 if (param != null && param.equalsIgnoreCase(TRUE))
2302 alignFrame.viewport.setShowSequenceFeatures(true);
2303 new FeatureSettings(alignFrame.alignPanel);
2309 * Load a score file if specified by parameter. Returns true if file was
2310 * loaded, else false.
2314 protected boolean loadScoreFile(AlignFrame alignFrame)
2316 boolean result = false;
2317 String sScoreFile = applet.getParameter("scoreFile");
2318 if (sScoreFile != null && !"".equals(sScoreFile))
2325 .println("Attempting to load T-COFFEE score file from the scoreFile parameter");
2327 result = alignFrame.loadScoreFile(sScoreFile);
2331 .println("Failed to parse T-COFFEE parameter as a valid score file ('"
2332 + sScoreFile + "')");
2334 } catch (Exception e)
2336 System.err.printf("Cannot read score file: '%s'. Cause: %s \n",
2337 sScoreFile, e.getMessage());
2344 * Load a tree for the alignment if specified by parameter. Returns true if
2345 * a tree was loaded, else false.
2350 protected boolean loadTree(AlignFrame alignFrame)
2352 boolean result = false;
2353 String treeFile = applet.getParameter("tree");
2354 if (treeFile == null)
2356 treeFile = applet.getParameter("treeFile");
2359 if (treeFile != null)
2363 treeFile = resolveFileProtocol(treeFile);
2364 NewickFile fin = new NewickFile(treeFile, protocol);
2367 if (fin.getTree() != null)
2369 alignFrame.loadTree(fin, treeFile);
2371 dbgMsg("Successfully imported tree.");
2375 dbgMsg("Tree parameter did not resolve to a valid tree.");
2377 } catch (Exception ex)
2379 ex.printStackTrace();
2386 * Discovers whether the given file is in the Applet Archive
2392 boolean inArchive(String f)
2394 // This might throw a security exception in certain browsers
2395 // Netscape Communicator for instance.
2398 boolean rtn = (getClass().getResourceAsStream("/" + f) != null);
2401 System.err.println("Resource '" + f + "' was "
2402 + (rtn ? "" : "not ") + "located by classloader.");
2405 } catch (Exception ex)
2407 System.out.println("Exception checking resources: " + f + " "
2414 * If the file is not already in URL format, tries to locate it by resolving
2420 String addProtocol(final String f)
2422 if (f.indexOf("://") != -1)
2424 // already has URL format
2429 * Try relative to document base
2431 URL documentBase = getDocumentBase();
2432 System.err.println("Trying documentbase: " + documentBase);
2433 String url = applet.resolveUrlForLocalOrAbsolute(f, documentBase);
2436 if (true/* debug */)
2438 System.err.println("Prepended document base '" + documentBase
2439 + "' to make: '" + url + "'");
2445 * Try relative to codebase
2447 URL codeBase = getCodeBase();
2448 System.err.println("Trying codebase: " + codeBase);
2449 url = applet.resolveUrlForLocalOrAbsolute(f, codeBase);
2452 if (true/* debug */)
2454 System.err.println("Prepended codebase '" + codeBase
2455 + "' to make: '" + url + "'");
2464 * Returns true if an input stream can be opened on the specified URL, else
2470 private boolean urlExists(String url)
2472 InputStream is = null;
2475 is = new URL(url).openStream();
2480 } catch (Exception x)
2490 } catch (IOException e)
2501 * @return the default alignFrame acted on by the public applet methods. May
2502 * return null with an error message on System.err indicating the
2505 public AlignFrame getDefaultTargetFrame()
2507 if (currentAlignFrame != null)
2509 return currentAlignFrame;
2511 if (initialAlignFrame != null)
2513 return initialAlignFrame;
2516 .println("Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
2521 * separator used for separatorList
2523 protected String separator = "" + ((char) 0x00AC); // the default used to be
2524 // '|' but many sequence
2525 // IDS include pipes.
2528 * set to enable the URL based javascript execution mechanism
2530 public boolean jsfallbackEnabled = false;
2533 * parse the string into a list
2536 * @return elements separated by separator
2538 public String[] separatorListToArray(String list)
2540 return separatorListToArray(list, separator);
2544 * parse the string into a list
2548 * @return elements separated by separator
2550 public static String[] separatorListToArray(String list, String separator)
2552 // TODO use StringUtils version (slightly different...)
2553 int seplen = separator.length();
2554 if (list == null || list.equals("") || list.equals(separator))
2558 java.util.Vector jv = new Vector();
2560 while ((pos = list.indexOf(separator, cp)) > cp)
2562 jv.addElement(list.substring(cp, pos));
2565 if (cp < list.length())
2567 String c = list.substring(cp);
2568 if (!c.equals(separator))
2575 String[] v = new String[jv.size()];
2576 for (int i = 0; i < v.length; i++)
2578 v[i] = (String) jv.elementAt(i);
2580 jv.removeAllElements();
2583 System.err.println("Array from '" + separator
2584 + "' separated List:\n" + v.length);
2585 for (int i = 0; i < v.length; i++)
2587 System.err.println("item " + i + " '" + v[i] + "'");
2594 System.err.println("Empty Array from '" + separator
2595 + "' separated List");
2601 * concatenate the list with separator
2604 * @return concatenated string
2606 public String arrayToSeparatorList(String[] list)
2608 return arrayToSeparatorList(list, separator);
2612 * concatenate the list with separator
2616 * @return concatenated string
2618 public static String arrayToSeparatorList(String[] list, String separator)
2620 // TODO use StringUtils version
2621 StringBuffer v = new StringBuffer();
2622 if (list != null && list.length > 0)
2624 for (int i = 0, iSize = list.length; i < iSize; i++)
2626 if (list[i] != null)
2630 v.append(separator);
2637 System.err.println("Returning '" + separator
2638 + "' separated List:\n");
2639 System.err.println(v);
2641 return v.toString();
2645 System.err.println("Returning empty '" + separator
2646 + "' separated List\n");
2648 return "" + separator;
2654 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroups()
2656 public String getFeatureGroups()
2658 String lst = arrayToSeparatorList(getDefaultTargetFrame()
2659 .getFeatureGroups());
2667 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOn(jalview.appletgui.AlignFrame
2670 public String getFeatureGroupsOn(AlignFrame alf)
2672 String lst = arrayToSeparatorList(alf.getFeatureGroups());
2679 * @see jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfState(boolean)
2681 public String getFeatureGroupsOfState(boolean visible)
2683 return arrayToSeparatorList(getDefaultTargetFrame()
2684 .getFeatureGroupsOfState(visible));
2691 * jalview.bin.JalviewLiteJsApi#getFeatureGroupsOfStateOn(jalview.appletgui
2692 * .AlignFrame, boolean)
2694 public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
2696 return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
2702 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupStateOn(jalview.appletgui.
2703 * 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().equals("false"));
2710 java.awt.EventQueue.invokeLater(new Runnable()
2715 alf.setFeatureGroupState(separatorListToArray(groups), st);
2723 * @see jalview.bin.JalviewLiteJsApi#setFeatureGroupState(java.lang.String,
2726 public void setFeatureGroupState(String groups, boolean state)
2728 setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
2734 * @see jalview.bin.JalviewLiteJsApi#getSeparator()
2736 public String getSeparator()
2744 * @see jalview.bin.JalviewLiteJsApi#setSeparator(java.lang.String)
2746 public void setSeparator(String separator)
2748 if (separator == null || separator.length() < 1)
2751 separator = "" + ((char) 0x00AC);
2753 this.separator = separator;
2756 System.err.println("Default Separator now: '" + separator + "'");
2761 * get boolean value of applet parameter 'name' and return default if
2762 * parameter is not set
2767 * the value to return otherwise
2768 * @return true or false
2770 public boolean getDefaultParameter(String name, boolean def)
2773 if ((stn = getParameter(name)) == null)
2777 if (TRUE.equalsIgnoreCase(stn))
2787 * @see jalview.bin.JalviewLiteJsApi#addPdbFile(jalview.appletgui.AlignFrame,
2788 * java.lang.String, java.lang.String, java.lang.String)
2790 public boolean addPdbFile(AlignFrame alFrame, String sequenceId,
2791 String pdbEntryString, String pdbFile)
2793 return alFrame.addPdbFile(sequenceId, pdbEntryString, pdbFile);
2796 protected void setAlignPdbStructures(boolean alignPdbStructures)
2798 this.alignPdbStructures = alignPdbStructures;
2801 public boolean isAlignPdbStructures()
2803 return alignPdbStructures;
2808 // callInitCallback();
2811 private Hashtable<String, long[]> jshashes = new Hashtable<String, long[]>();
2813 private Hashtable<String, Hashtable<String, String[]>> jsmessages = new Hashtable<String, Hashtable<String, String[]>>();
2815 public void setJsMessageSet(String messageclass, String viewId,
2816 String[] colcommands)
2818 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2821 msgset = new Hashtable<String, String[]>();
2822 jsmessages.put(messageclass, msgset);
2824 msgset.put(viewId, colcommands);
2825 long[] l = new long[colcommands.length];
2826 for (int i = 0; i < colcommands.length; i++)
2828 l[i] = colcommands[i].hashCode();
2830 jshashes.put(messageclass + "|" + viewId, l);
2836 * @see jalview.bin.JalviewLiteJsApi#getJsMessage(java.lang.String,
2839 public String getJsMessage(String messageclass, String viewId)
2841 Hashtable<String, String[]> msgset = jsmessages.get(messageclass);
2844 String[] msgs = msgset.get(viewId);
2847 for (int i = 0; i < msgs.length; i++)
2849 if (msgs[i] != null)
2861 public boolean isJsMessageSetChanged(String string, String string2,
2862 String[] colcommands)
2864 long[] l = jshashes.get(string + "|" + string2);
2865 if (l == null && colcommands != null)
2869 for (int i = 0; i < colcommands.length; i++)
2871 if (l[i] != colcommands[i].hashCode())
2879 private Vector jsExecQueue = new Vector();
2881 public Vector getJsExecQueue()
2886 public void setExecutor(JSFunctionExec jsFunctionExec2)
2888 jsFunctionExec = jsFunctionExec2;
2892 * return the given colour value parameter or the given default if parameter
2899 public Color getDefaultColourParameter(String colparam, Color defcolour)
2901 String colprop = getParameter(colparam);
2902 if (colprop == null || colprop.trim().length() == 0)
2906 Color col = jalview.schemes.ColourSchemeProperty
2907 .getAWTColorFromName(colprop);
2912 col = new jalview.schemes.UserColourScheme(colprop).findColour('A');
2913 } catch (Exception ex)
2915 System.err.println("Couldn't parse '" + colprop
2916 + "' as a colour for " + colparam);
2920 return (col == null) ? defcolour : col;
2924 public void openJalviewHelpUrl()
2926 String helpUrl = getParameter("jalviewhelpurl");
2927 if (helpUrl == null || helpUrl.trim().length() < 5)
2929 helpUrl = "http://www.jalview.org/help.html";
2931 showURL(helpUrl, "HELP");
2935 * form a complete URL given a path to a resource and a reference location on
2939 * - an absolute path on the same server as localref or a document
2940 * located relative to localref
2942 * - a URL on the same server as url
2943 * @return a complete URL for the resource located by url
2945 private String resolveUrlForLocalOrAbsolute(String targetPath,
2948 String resolvedPath = "";
2951 * get URL path and strip off any trailing file e.g.
2952 * www.jalview.org/examples/index.html#applets?a=b is trimmed to
2953 * www.jalview.org/examples/
2955 String urlPath = localref.toString();
2956 String directoryPath = urlPath;
2957 int lastSeparator = directoryPath.lastIndexOf("/");
2958 if (lastSeparator > 0)
2960 directoryPath = directoryPath.substring(0, lastSeparator + 1);
2963 if (targetPath.startsWith("/"))
2966 * construct absolute URL to a file on the server - this is not allowed?
2968 // String localfile = localref.getFile();
2969 // resolvedPath = urlPath.substring(0,
2970 // urlPath.length() - localfile.length())
2972 resolvedPath = directoryPath + targetPath.substring(1);
2976 resolvedPath = directoryPath + targetPath;
2980 System.err.println("resolveUrlForLocalOrAbsolute returning "
2983 return resolvedPath;
2987 * open a URL in the browser - resolving it according to relative refs and
2988 * coping with javascript: protocol if necessary.
2993 public void showURL(String url, String target)
2997 if (url.indexOf(":") == -1)
2999 // TODO: verify (Bas Vroling bug) prepend codebase or server URL to
3001 // Should really use docbase, not codebase.
3003 url = resolveUrlForLocalOrAbsolute(
3005 prepend = getDefaultParameter("resolvetocodebase", false) ? getCodeBase()
3006 : getDocumentBase());
3010 .println("Show url (prepended "
3012 + " - toggle resolvetocodebase if code/docbase resolution is wrong): "
3020 System.err.println("Show url: " + url);
3023 if (url.indexOf("javascript:") == 0)
3025 // no target for the javascript context
3026 getAppletContext().showDocument(new java.net.URL(url));
3030 getAppletContext().showDocument(new java.net.URL(url), target);
3032 } catch (Exception ex)
3034 ex.printStackTrace();
3039 * bind structures in a viewer to any matching sequences in an alignFrame (use
3040 * sequenceIds to limit scope of search to specific sequences)
3044 * @param sequenceIds
3045 * @return TODO: consider making an exception structure for indicating when
3046 * binding fails public SequenceStructureBinding
3047 * addStructureViewInstance( AlignFrame alFrame, Object viewer, String
3050 * if (sequenceIds != null && sequenceIds.length() > 0) { return
3051 * alFrame.addStructureViewInstance(viewer,
3052 * separatorListToArray(sequenceIds)); } else { return
3053 * alFrame.addStructureViewInstance(viewer, null); } // return null; }