2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
20 import jalview.appletgui.AlignFrame;
21 import jalview.appletgui.EmbmenuFrame;
22 import jalview.appletgui.FeatureSettings;
23 import jalview.datamodel.Alignment;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.AlignmentOrder;
26 import jalview.datamodel.ColumnSelection;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.Sequence;
29 import jalview.datamodel.SequenceGroup;
30 import jalview.datamodel.SequenceI;
31 import jalview.io.AnnotationFile;
32 import jalview.io.AppletFormatAdapter;
33 import jalview.io.FileParse;
34 import jalview.io.IdentifyFile;
35 import jalview.io.JnetAnnotationMaker;
36 import jalview.javascript.JSFunctionExec;
37 import jalview.javascript.JsCallBack;
38 import jalview.structure.SelectionListener;
39 import jalview.structure.StructureSelectionManager;
41 import java.applet.Applet;
42 import java.awt.Button;
43 import java.awt.Color;
44 import java.awt.Component;
46 import java.awt.Frame;
47 import java.awt.Graphics;
48 import java.awt.event.ActionEvent;
49 import java.awt.event.WindowAdapter;
50 import java.awt.event.WindowEvent;
51 import java.io.BufferedReader;
52 import java.io.InputStreamReader;
53 import java.util.StringTokenizer;
54 import java.util.Vector;
56 import netscape.javascript.JSObject;
59 * Jalview Applet. Runs in Java 1.18 runtime
64 public class JalviewLite extends Applet
67 // /////////////////////////////////////////
68 // The following public methods maybe called
69 // externally, eg via javascript in HTML page
71 * @return String list of selected sequence IDs, each terminated by the
72 * 'boolean not' character (""+0x00AC) or (¬)
74 public String getSelectedSequences()
76 return getSelectedSequencesFrom(getDefaultTargetFrame());
81 * separator string or null for default
82 * @return String list of selected sequence IDs, each terminated by given
85 public String getSelectedSequences(String sep)
87 return getSelectedSequencesFrom(getDefaultTargetFrame(), sep);
92 * alignframe containing selection
93 * @return String list of selected sequence IDs, each terminated by current
94 * default separator sequence
97 public String getSelectedSequencesFrom(AlignFrame alf)
99 return getSelectedSequencesFrom(alf, separator); // ""+0x00AC);
103 * get list of selected sequence IDs separated by given separator
106 * window containing selection
108 * separator string to use - default is 'boolean not'
109 * @return String list of selected sequence IDs, each terminated by the given
112 public String getSelectedSequencesFrom(AlignFrame alf, String sep)
114 StringBuffer result = new StringBuffer("");
115 if (sep == null || sep.length() == 0)
117 sep = separator; // "+0x00AC;
119 if (alf.viewport.getSelectionGroup() != null)
121 SequenceI[] seqs = alf.viewport.getSelectionGroup()
122 .getSequencesInOrder(alf.viewport.getAlignment());
124 for (int i = 0; i < seqs.length; i++)
126 result.append(seqs[i].getName());
131 return result.toString();
137 * id of sequence to highlight
139 * integer position [ tobe implemented or range ] on sequence
140 * @param alignedPosition
141 * true/false/empty string - indicate if position is an alignment
142 * column or unaligned sequence position
144 public void highlight(String sequenceId, String position,
145 String alignedPosition)
147 highlightIn(getDefaultTargetFrame(), sequenceId, position,
154 * id of sequence to highlight
156 * integer position [ tobe implemented or range ] on sequence
157 * @param alignedPosition
158 * false, blank or something else - indicate if position is an
159 * alignment column or unaligned sequence position
161 public void highlightIn(AlignFrame alf, String sequenceId,
162 String position, String alignedPosition)
164 // TODO: could try to highlight in all alignments if alf==null
165 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
166 alf.viewport.getAlignment().getSequencesArray());
167 SequenceI sq = matcher.findIdMatch(sequenceId);
173 apos = new Integer(position).intValue();
175 } catch (NumberFormatException ex)
179 // use vamsas listener to broadcast to all listeners in scope
180 if (alignedPosition != null
181 && (alignedPosition.trim().length() == 0 || alignedPosition
182 .toLowerCase().indexOf("false") > -1))
184 StructureSelectionManager.getStructureSelectionManager()
185 .mouseOverVamsasSequence(sq, sq.findIndex(apos), null);
189 StructureSelectionManager.getStructureSelectionManager()
190 .mouseOverVamsasSequence(sq, apos, null);
197 * select regions of the currrent alignment frame
200 * String separated list of sequence ids or empty string
202 * String separated list { column range or column, ..} or empty
205 public void select(String sequenceIds, String columns)
207 selectIn(getDefaultTargetFrame(), sequenceIds, columns, separator);
211 * select regions of the currrent alignment frame
214 * String separated list { column range, seq1...seqn sequence ids }
216 * separator between toselect fields
218 public void select(String sequenceIds, String columns, String sep)
220 selectIn(getDefaultTargetFrame(), sequenceIds, columns, sep);
224 * select regions of the given alignment frame
228 * String separated list { column range, seq1...seqn sequence ids }
230 * separator between toselect fields
232 public void selectIn(AlignFrame alf, String sequenceIds, String columns)
234 selectIn(alf, sequenceIds, columns, separator);
238 * select regions of the given alignment frame
242 * String separated list { column range, seq1...seqn sequence ids }
244 * separator between toselect fields
246 public void selectIn(AlignFrame alf, String sequenceIds, String columns,
249 if (sep == null || sep.length() == 0)
257 System.err.println("Selecting region using separator string '"
262 String[] ids = separatorListToArray(sequenceIds, sep);
263 String[] cols = separatorListToArray(columns, sep);
264 SequenceGroup sel = new SequenceGroup();
265 ColumnSelection csel = new ColumnSelection();
266 AlignmentI al = alf.viewport.getAlignment();
267 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
268 alf.viewport.getAlignment().getSequencesArray());
269 int start = 0, end = al.getWidth(), alw = al.getWidth();
270 boolean seqsfound = true;
271 if (ids != null && ids.length > 0)
274 for (int i = 0; i < ids.length; i++)
276 if (ids[i].trim().length() == 0)
280 SequenceI sq = matcher.findIdMatch(ids[i]);
284 sel.addSequence(sq, false);
288 boolean inseqpos = false;
289 if (cols != null && cols.length > 0)
291 boolean seset = false;
292 for (int i = 0; i < cols.length; i++)
294 String cl = cols[i].trim();
295 if (cl.length() == 0)
300 if ((p = cl.indexOf("-")) > -1)
302 int from = -1, to = -1;
305 from = new Integer(cl.substring(0, p)).intValue();
307 } catch (NumberFormatException ex)
310 .println("ERROR: Couldn't parse first integer in range element column selection string '"
311 + cl + "' - format is 'from-to'");
316 to = new Integer(cl.substring(p + 1)).intValue();
318 } catch (NumberFormatException ex)
321 .println("ERROR: Couldn't parse second integer in range element column selection string '"
322 + cl + "' - format is 'from-to'");
325 if (from >= 0 && to >= 0)
342 // comment to prevent range extension
352 for (int r = from; r <= to; r++)
354 if (r >= 0 && r < alw)
361 System.err.println("Range '" + cl + "' deparsed as [" + from
367 System.err.println("ERROR: Invalid Range '" + cl
368 + "' deparsed as [" + from + "," + to + "]");
376 r = new Integer(cl).intValue();
378 } catch (NumberFormatException ex)
380 if (cl.toLowerCase().equals("sequence"))
382 // we are in the dataset sequence's coordinate frame.
388 .println("ERROR: Couldn't parse integer from point selection element of column selection string '"
393 if (r >= 0 && r <= alw)
403 // comment to prevent range extension
416 System.err.println("Point selection '" + cl
417 + "' deparsed as [" + r + "]");
422 System.err.println("ERROR: Invalid Point selection '" + cl
423 + "' deparsed as [" + r + "]");
430 // we only propagate the selection when it was the null selection, or the
431 // given sequences were found in the alignment.
432 if (inseqpos && sel.getSize() > 0)
434 // assume first sequence provides reference frame ?
435 SequenceI rs = sel.getSequenceAt(0);
436 start = rs.findIndex(start);
437 end = rs.findIndex(end);
440 Vector cs = csel.getSelected();
442 for (int csi = 0, csiS = cs.size(); csi < csiS; csi++)
444 csel.addElement(rs.findIndex(((Integer) cs.elementAt(csi))
449 sel.setStartRes(start);
451 alf.select(sel, csel);
456 * get sequences selected in current alignFrame and return their alignment in
457 * format 'format' either with or without suffix
460 * - where selection is
462 * - format of alignment file
464 * - "true" to append /start-end string to each sequence ID
465 * @return selected sequences as flat file or empty string if there was no
468 public String getSelectedSequencesAsAlignment(String format, String suffix)
470 return getSelectedSequencesAsAlignmentFrom(getDefaultTargetFrame(),
475 * get sequences selected in alf and return their alignment in format 'format'
476 * either with or without suffix
479 * - where selection is
481 * - format of alignment file
483 * - "true" to append /start-end string to each sequence ID
484 * @return selected sequences as flat file or empty string if there was no
487 public String getSelectedSequencesAsAlignmentFrom(AlignFrame alf,
488 String format, String suffix)
492 boolean seqlimits = suffix.equalsIgnoreCase("true");
493 if (alf.viewport.getSelectionGroup() != null)
495 String reply = new AppletFormatAdapter().formatSequences(format,
496 new Alignment(alf.viewport.getSelectionAsNewSequence()),
500 } catch (Exception ex)
502 ex.printStackTrace();
503 return "Error retrieving alignment in " + format + " format. ";
508 public String getAlignmentOrder()
510 return getAlignmentOrderFrom(getDefaultTargetFrame());
513 public String getAlignmentOrderFrom(AlignFrame alf)
515 return getAlignmentOrderFrom(alf, separator);
518 public String getAlignmentOrderFrom(AlignFrame alf, String sep)
520 AlignmentI alorder = alf.getAlignViewport().getAlignment();
521 String[] order = new String[alorder.getHeight()];
522 for (int i = 0; i < order.length; i++)
524 order[i] = alorder.getSequenceAt(i).getName();
526 return arrayToSeparatorList(order);
529 public String orderBy(String order, String undoName)
531 return orderBy(order, undoName, separator);
534 public String orderBy(String order, String undoName, String sep)
536 return orderAlignmentBy(getDefaultTargetFrame(), order, undoName, sep);
539 public String orderAlignmentBy(AlignFrame alf, String order,
540 String undoName, String sep)
542 String[] ids = separatorListToArray(order, sep);
543 SequenceI[] sqs = null;
544 if (ids != null && ids.length > 0)
546 jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher(
547 alf.viewport.getAlignment().getSequencesArray());
549 sqs = new SequenceI[ids.length];
550 for (int i = 0; i < ids.length; i++)
552 if (ids[i].trim().length() == 0)
556 SequenceI sq = matcher.findIdMatch(ids[i]);
564 SequenceI[] sqq = new SequenceI[s];
565 System.arraycopy(sqs, 0, sqq, 0, s);
578 AlignmentOrder aorder = new AlignmentOrder(sqs);
580 if (undoName != null && undoName.trim().length() == 0)
585 return alf.sortBy(aorder, undoName) ? "true" : "";
588 public String getAlignment(String format)
590 return getAlignmentFrom(getDefaultTargetFrame(), format, "true");
593 public String getAlignmentFrom(AlignFrame alf, String format)
595 return getAlignmentFrom(alf, format, "true");
598 public String getAlignment(String format, String suffix)
600 return getAlignmentFrom(getDefaultTargetFrame(), format, suffix);
603 public String getAlignmentFrom(AlignFrame alf, String format,
608 boolean seqlimits = suffix.equalsIgnoreCase("true");
610 String reply = new AppletFormatAdapter().formatSequences(format,
611 alf.viewport.getAlignment(), seqlimits);
613 } catch (Exception ex)
615 ex.printStackTrace();
616 return "Error retrieving alignment in " + format + " format. ";
620 public void loadAnnotation(String annotation)
622 loadAnnotationFrom(getDefaultTargetFrame(), annotation);
625 public void loadAnnotationFrom(AlignFrame alf, String annotation)
627 if (new AnnotationFile().readAnnotationFile(alf.getAlignViewport()
628 .getAlignment(), annotation, AppletFormatAdapter.PASTE))
630 alf.alignPanel.fontChanged();
631 alf.alignPanel.setScrollValues(0, 0);
635 alf.parseFeaturesFile(annotation, AppletFormatAdapter.PASTE);
639 public String getFeatures(String format)
641 return getFeaturesFrom(getDefaultTargetFrame(), format);
644 public String getFeaturesFrom(AlignFrame alf, String format)
646 return alf.outputFeatures(false, format);
649 public String getAnnotation()
651 return getAnnotationFrom(getDefaultTargetFrame());
654 public String getAnnotationFrom(AlignFrame alf)
656 return alf.outputAnnotations(false);
659 public AlignFrame newView()
661 return newViewFrom(getDefaultTargetFrame());
664 public AlignFrame newView(String name)
666 return newViewFrom(getDefaultTargetFrame(), name);
669 public AlignFrame newViewFrom(AlignFrame alf)
671 return alf.newView(null);
674 public AlignFrame newViewFrom(AlignFrame alf, String name)
676 return alf.newView(name);
682 * alignment file as a string
685 * @return null or new alignment frame
687 public AlignFrame loadAlignment(String text, String title)
691 String format = new IdentifyFile().Identify(text,
692 AppletFormatAdapter.PASTE);
695 al = new AppletFormatAdapter().readFile(text,
696 AppletFormatAdapter.PASTE, format);
697 if (al.getHeight() > 0)
699 return new AlignFrame(al, this, title, false);
701 } catch (java.io.IOException ex)
703 ex.printStackTrace();
708 public void setMouseoverListener(String listener)
710 setMouseoverListener(currentAlignFrame, listener);
713 private Vector javascriptListeners = new Vector();
715 public void setMouseoverListener(AlignFrame af, String listener)
717 if (listener != null)
719 listener = listener.trim();
720 if (listener.length() == 0)
723 .println("jalview Javascript error: Ignoring empty function for mouseover listener.");
727 jalview.javascript.MouseOverListener mol = new jalview.javascript.MouseOverListener(
729 javascriptListeners.addElement(mol);
730 StructureSelectionManager.getStructureSelectionManager()
731 .addStructureViewerListener(mol);
734 System.err.println("Added a mouseover listener for "
735 + ((af == null) ? "All frames" : "Just views for "
736 + af.getAlignViewport().getSequenceSetId()));
737 System.err.println("There are now " + javascriptListeners.size()
738 + " listeners in total.");
742 public void setSelectionListener(String listener)
744 setSelectionListener(null, listener);
747 public void setSelectionListener(AlignFrame af, String listener)
749 if (listener != null)
751 listener = listener.trim();
752 if (listener.length() == 0)
755 .println("jalview Javascript error: Ignoring empty function for selection listener.");
759 jalview.javascript.JsSelectionSender mol = new jalview.javascript.JsSelectionSender(
761 javascriptListeners.addElement(mol);
762 StructureSelectionManager.getStructureSelectionManager()
763 .addSelectionListener(mol);
766 System.err.println("Added a selection listener for "
767 + ((af == null) ? "All frames" : "Just views for "
768 + af.getAlignViewport().getSequenceSetId()));
769 System.err.println("There are now " + javascriptListeners.size()
770 + " listeners in total.");
774 public void setStructureListener(String listener)
776 if (listener != null)
778 listener = listener.trim();
779 if (listener.length() == 0)
782 .println("jalview Javascript error: Ignoring empty function for selection listener.");
786 jalview.javascript.MouseOverStructureListener mol = new jalview.javascript.MouseOverStructureListener(this, listener);
787 javascriptListeners.addElement(mol);
788 StructureSelectionManager.getStructureSelectionManager()
789 .addStructureViewerListener(mol);
792 System.err.println("Added a javascript structure viewer listener '"+listener+"'");
793 System.err.println("There are now " + javascriptListeners.size()
794 + " listeners in total.");
798 * remove any callback using the given listener function and associated with
799 * the given alignFrame (or null for all callbacks)
806 public void removeJavascriptListener(AlignFrame af, String listener)
808 if (listener != null)
810 listener = listener.trim();
811 if (listener.length() == 0)
816 boolean rprt = false;
817 for (int ms = 0, msSize = javascriptListeners.size(); ms < msSize;)
819 Object lstn = javascriptListeners.elementAt(ms);
820 JsCallBack lstner = (JsCallBack) lstn;
821 if ((af == null || lstner.getAlignFrame() == af)
822 && (listener == null || lstner.getListenerFunction().equals(
825 javascriptListeners.removeElement(lstner);
827 if (lstner instanceof SelectionListener)
829 StructureSelectionManager.getStructureSelectionManager()
830 .removeSelectionListener((SelectionListener) lstner);
834 StructureSelectionManager.getStructureSelectionManager()
835 .removeStructureViewerListener(lstner, null);
840 System.err.println("Removed listener '" + listener + "'");
850 System.err.println("There are now " + javascriptListeners.size()
851 + " listeners in total.");
857 if (javascriptListeners != null)
859 while (javascriptListeners.size() > 0)
861 Object mol = javascriptListeners.elementAt(0);
862 javascriptListeners.removeElement(mol);
863 if (mol instanceof SelectionListener)
865 StructureSelectionManager.getStructureSelectionManager()
866 .removeSelectionListener((SelectionListener) mol);
870 StructureSelectionManager.getStructureSelectionManager()
871 .removeStructureViewerListener(mol, null);
875 jalview.javascript.JSFunctionExec.stopQueue();
879 * send a mouseover message to all the alignment windows associated with the
880 * given residue in the pdbfile
886 public void mouseOverStructure(String pdbResNum, String chain, String pdbfile)
889 StructureSelectionManager.getStructureSelectionManager()
890 .mouseOverStructure(new Integer(pdbResNum).intValue(), chain, pdbfile);
893 System.err.println("mouseOver for '"+pdbResNum+"' in chain '"+chain+"' in structure '"+pdbfile+"'");
895 } catch (NumberFormatException e)
897 System.err.println("Ignoring invalid residue number string '"+pdbResNum+"'");
901 // //////////////////////////////////////////////
902 // //////////////////////////////////////////////
904 public static int lastFrameX = 200;
906 public static int lastFrameY = 200;
908 boolean fileFound = true;
910 String file = "No file";
912 Button launcher = new Button("Start Jalview");
915 * The currentAlignFrame is static, it will change if and when the user
916 * selects a new window. Note that it will *never* point back to the embedded
917 * AlignFrame if the applet is started as embedded on the page and then
918 * afterwards a new view is created.
920 public AlignFrame currentAlignFrame = null;
923 * This is the first frame to be displayed, and does not change. API calls
924 * will default to this instance if currentAlignFrame is null.
926 AlignFrame initialAlignFrame = null;
928 boolean embedded = false;
930 private boolean checkForJmol = true;
932 private boolean checkedForJmol = false; // ensure we don't check for jmol
934 // every time the app is re-inited
936 public boolean jmolAvailable = false;
938 private boolean alignPdbStructures = false;
941 * use an external structure viewer exclusively (no jmols or MCViews will be opened by JalviewLite itself)
943 public boolean useXtrnalSviewer=false;
945 public static boolean debug = false;
947 static String builddate = null, version = null;
949 private static void initBuildDetails()
951 if (builddate == null)
953 builddate = "unknown";
955 java.net.URL url = JalviewLite.class
956 .getResource("/.build_properties");
961 BufferedReader reader = new BufferedReader(new InputStreamReader(
964 while ((line = reader.readLine()) != null)
966 if (line.indexOf("VERSION") > -1)
968 version = line.substring(line.indexOf("=") + 1);
970 if (line.indexOf("BUILD_DATE") > -1)
972 builddate = line.substring(line.indexOf("=") + 1);
975 } catch (Exception ex)
977 ex.printStackTrace();
983 public static String getBuildDate()
989 public static String getVersion()
995 // public JSObject scriptObject = null;
998 * init method for Jalview Applet
1002 // remove any handlers that might be hanging around from an earlier instance
1007 System.err.println("Applet context is '"
1008 + getAppletContext().getClass().toString() + "'");
1010 JSObject scriptObject = JSObject.getWindow(this);
1011 if (debug && scriptObject != null)
1013 System.err.println("Applet has Javascript callback support.");
1016 } catch (Exception ex)
1019 .println("Warning: No JalviewLite javascript callbacks available.");
1022 ex.printStackTrace();
1026 * turn on extra applet debugging
1028 String dbg = getParameter("debug");
1031 debug = dbg.toLowerCase().equals("true");
1036 System.err.println("JalviewLite Version " + getVersion());
1037 System.err.println("Build Date : " + getBuildDate());
1040 String externalsviewer = getParameter("externalstructureviewer");
1041 if (externalsviewer!=null)
1043 useXtrnalSviewer=externalsviewer.trim().toLowerCase().equals("true");
1046 * if true disable the check for jmol
1048 String chkforJmol = getParameter("nojmol");
1049 if (chkforJmol != null)
1051 checkForJmol = !chkforJmol.equals("true");
1054 * get the separator parameter if present
1056 String sep = getParameter("separator");
1059 if (sep.length() > 0)
1064 System.err.println("Separator set to '" + separator + "'");
1070 "Invalid separator parameter - must be non-zero length");
1076 String param = getParameter("RGB");
1082 r = Integer.parseInt(param.substring(0, 2), 16);
1083 g = Integer.parseInt(param.substring(2, 4), 16);
1084 b = Integer.parseInt(param.substring(4, 6), 16);
1085 } catch (Exception ex)
1092 param = getParameter("label");
1095 launcher.setLabel(param);
1098 setBackground(new Color(r, g, b));
1100 file = getParameter("file");
1104 // Maybe the sequences are added as parameters
1105 StringBuffer data = new StringBuffer("PASTE");
1107 while ((file = getParameter("sequence" + i)) != null)
1109 data.append(file.toString() + "\n");
1112 if (data.length() > 5)
1114 file = data.toString();
1118 final JalviewLite jvapplet = this;
1119 if (getParameter("embedded") != null
1120 && getParameter("embedded").equalsIgnoreCase("true"))
1122 // Launch as embedded applet in page
1124 LoadingThread loader = new LoadingThread(file, jvapplet);
1127 else if (file != null)
1129 if (getParameter("showbutton") == null
1130 || !getParameter("showbutton").equalsIgnoreCase("false"))
1132 // Add the JalviewLite 'Button' to the page
1134 launcher.addActionListener(new java.awt.event.ActionListener()
1136 public void actionPerformed(ActionEvent e)
1138 LoadingThread loader = new LoadingThread(file, jvapplet);
1145 // Open jalviewLite immediately.
1146 LoadingThread loader = new LoadingThread(file, jvapplet);
1152 // jalview initialisation with no alignment. loadAlignment() method can
1153 // still be called to open new alignments.
1156 // callInitCallback();
1160 private void callInitCallback()
1162 String initjscallback = getParameter("oninit");
1163 if (initjscallback == null)
1167 initjscallback = initjscallback.trim();
1168 if (initjscallback.length() > 0)
1170 JSObject scriptObject = null;
1173 scriptObject = JSObject.getWindow(this);
1174 } catch (Exception ex)
1178 if (scriptObject != null)
1182 // do onInit with the JS executor thread
1183 new JSFunctionExec(this).executeJavascriptFunction(true,
1184 initjscallback, null, "Calling oninit callback '"
1185 + initjscallback + "'.");
1186 } catch (Exception e)
1188 System.err.println("Exception when executing _oninit callback '"
1189 + initjscallback + "'.");
1190 e.printStackTrace();
1195 System.err.println("Not executing _oninit callback '"
1196 + initjscallback + "' - no scripting allowed.");
1202 * Initialises and displays a new java.awt.Frame
1205 * java.awt.Frame to be displayed
1207 * title of new frame
1209 * width if new frame
1211 * height of new frame
1213 public static void addFrame(final Frame frame, String title, int width,
1216 frame.setLocation(lastFrameX, lastFrameY);
1219 frame.setSize(width, height);
1220 frame.setTitle(title);
1221 frame.addWindowListener(new WindowAdapter()
1223 public void windowClosing(WindowEvent e)
1225 if (frame instanceof AlignFrame)
1227 ((AlignFrame) frame).closeMenuItem_actionPerformed();
1228 if (((AlignFrame) frame).viewport.applet.currentAlignFrame == frame)
1230 ((AlignFrame) frame).viewport.applet.currentAlignFrame = null;
1235 if (frame instanceof EmbmenuFrame)
1237 ((EmbmenuFrame) frame).destroyMenus();
1239 frame.setMenuBar(null);
1243 public void windowActivated(WindowEvent e)
1245 if (frame instanceof AlignFrame)
1247 ((AlignFrame) frame).viewport.applet.currentAlignFrame = (AlignFrame) frame;
1250 System.err.println("Activated window " + frame);
1254 super.windowActivated(e);
1257 * Probably not necessary to do this - see TODO above. (non-Javadoc)
1260 * java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent
1263 * public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
1264 * frame) { currentAlignFrame = null; if (debug) {
1265 * System.err.println("Deactivated window "+frame); } }
1266 * super.windowDeactivated(e); }
1269 frame.setVisible(true);
1273 * This paints the background surrounding the "Launch Jalview button" <br>
1275 * If file given in parameter not found, displays error message
1280 public void paint(Graphics g)
1284 g.setColor(new Color(200, 200, 200));
1285 g.setColor(Color.cyan);
1286 g.fillRect(0, 0, getSize().width, getSize().height);
1287 g.setColor(Color.red);
1288 g.drawString("Jalview can't open file", 5, 15);
1289 g.drawString("\"" + file + "\"", 5, 30);
1293 g.setColor(Color.black);
1294 g.setFont(new Font("Arial", Font.BOLD, 24));
1295 g.drawString("Jalview Applet", 50, getSize().height / 2 - 30);
1296 g.drawString("Loading Data...", 50, getSize().height / 2);
1301 * get all components associated with the applet of the given type
1306 public Vector getAppletWindow(Class class1)
1308 Vector wnds = new Vector();
1309 Component[] cmp = getComponents();
1312 for (int i = 0; i < cmp.length; i++)
1314 if (class1.isAssignableFrom(cmp[i].getClass()))
1316 wnds.addElement(cmp);
1323 class LoadJmolThread extends Thread
1325 private boolean running = false;
1329 if (running || checkedForJmol)
1338 if (!System.getProperty("java.version").startsWith("1.1"))
1340 Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
1341 jmolAvailable = true;
1346 .println("Jmol not available - Using MCview for structures");
1348 } catch (java.lang.ClassNotFoundException ex)
1354 jmolAvailable = false;
1358 .println("Skipping Jmol check. Will use MCView (probably)");
1361 checkedForJmol = true;
1365 public boolean notFinished()
1367 return running || !checkedForJmol;
1371 class LoadingThread extends Thread
1374 * State variable: File source
1379 * State variable: protocol for access to file source
1384 * State variable: format of file source
1392 private void dbgMsg(String msg)
1396 System.err.println(msg);
1401 * update the protocol state variable for accessing the datasource located
1405 * @return possibly updated datasource string
1407 public String setProtocolState(String file)
1409 if (file.startsWith("PASTE"))
1411 file = file.substring(5);
1412 protocol = AppletFormatAdapter.PASTE;
1414 else if (inArchive(file))
1416 protocol = AppletFormatAdapter.CLASSLOADER;
1420 file = addProtocol(file);
1421 protocol = AppletFormatAdapter.URL;
1423 dbgMsg("Protocol identified as '" + protocol + "'");
1427 public LoadingThread(String _file, JalviewLite _applet)
1435 LoadJmolThread jmolchecker = new LoadJmolThread();
1436 jmolchecker.start();
1437 while (jmolchecker.notFinished())
1439 // wait around until the Jmol check is complete.
1443 } catch (Exception e)
1449 // applet.callInitCallback();
1452 private void startLoading()
1454 AlignFrame newAlignFrame;
1455 dbgMsg("Loading thread started with:\n>>file\n" + _file + ">>endfile");
1456 file = setProtocolState(_file);
1458 format = new jalview.io.IdentifyFile().Identify(file, protocol);
1459 dbgMsg("File identified as '" + format + "'");
1460 dbgMsg("Loading started.");
1461 Alignment al = null;
1464 al = new AppletFormatAdapter().readFile(file, protocol, format);
1465 } catch (java.io.IOException ex)
1467 dbgMsg("File load exception.");
1468 ex.printStackTrace();
1473 FileParse fp = new FileParse(file, protocol);
1475 dbgMsg(">>>Dumping contents of '" + file + "' " + "("
1477 while ((ln = fp.nextLine()) != null)
1481 dbgMsg(">>>Dump finished.");
1482 } catch (Exception e)
1485 .println("Exception when trying to dump the content of the file parameter.");
1486 e.printStackTrace();
1490 if ((al != null) && (al.getHeight() > 0))
1492 dbgMsg("Successfully loaded file.");
1493 newAlignFrame = new AlignFrame(al, applet, file, embedded);
1494 if (initialAlignFrame == null)
1496 initialAlignFrame = newAlignFrame;
1498 // update the focus.
1499 currentAlignFrame = newAlignFrame;
1501 if (protocol == jalview.io.AppletFormatAdapter.PASTE)
1503 newAlignFrame.setTitle("Sequences from "
1504 + applet.getDocumentBase());
1507 newAlignFrame.statusBar.setText("Successfully loaded file " + file);
1509 String treeFile = applet.getParameter("tree");
1510 if (treeFile == null)
1512 treeFile = applet.getParameter("treeFile");
1515 if (treeFile != null)
1519 treeFile = setProtocolState(treeFile);
1521 * if (inArchive(treeFile)) { protocol =
1522 * AppletFormatAdapter.CLASSLOADER; } else { protocol =
1523 * AppletFormatAdapter.URL; treeFile = addProtocol(treeFile); }
1525 jalview.io.NewickFile fin = new jalview.io.NewickFile(treeFile,
1530 if (fin.getTree() != null)
1532 newAlignFrame.loadTree(fin, treeFile);
1533 dbgMsg("Successfuly imported tree.");
1537 dbgMsg("Tree parameter did not resolve to a valid tree.");
1539 } catch (Exception ex)
1541 ex.printStackTrace();
1545 String param = applet.getParameter("features");
1548 param = setProtocolState(param);
1550 newAlignFrame.parseFeaturesFile(param, protocol);
1553 param = applet.getParameter("showFeatureSettings");
1554 if (param != null && param.equalsIgnoreCase("true"))
1556 newAlignFrame.viewport.showSequenceFeatures(true);
1557 new FeatureSettings(newAlignFrame.alignPanel);
1560 param = applet.getParameter("annotations");
1563 param = setProtocolState(param);
1565 if (new AnnotationFile().readAnnotationFile(
1566 newAlignFrame.viewport.getAlignment(), param, protocol))
1568 newAlignFrame.alignPanel.fontChanged();
1569 newAlignFrame.alignPanel.setScrollValues(0, 0);
1574 .println("Annotations were not added from annotation file '"
1580 param = applet.getParameter("jnetfile");
1585 param = setProtocolState(param);
1586 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
1588 JnetAnnotationMaker.add_annotation(predictions,
1589 newAlignFrame.viewport.getAlignment(), 0, false); // false==do
1597 newAlignFrame.alignPanel.fontChanged();
1598 newAlignFrame.alignPanel.setScrollValues(0, 0);
1599 } catch (Exception ex)
1601 ex.printStackTrace();
1605 * <param name="alignpdbfiles" value="false/true"/> Undocumented for 2.6
1606 * - related to JAL-434
1608 applet.setAlignPdbStructures(getDefaultParameter("alignpdbfiles",
1611 * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
1614 * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
1616 * <param name="PDBfile3" value="1q0o Q45135_9MICO">
1619 int pdbFileCount = 0;
1620 // Accumulate pdbs here if they are heading for the same view (if
1621 // alignPdbStructures is true)
1622 Vector pdbs = new Vector();
1623 // create a lazy matcher if we're asked to
1624 jalview.analysis.SequenceIdMatcher matcher = (applet.getDefaultParameter("relaxedidmatch", false)) ? new jalview.analysis.SequenceIdMatcher(
1625 newAlignFrame.getAlignViewport().getAlignment().getSequencesArray()) : null;
1629 if (pdbFileCount > 0)
1630 param = applet.getParameter("PDBFILE" + pdbFileCount);
1632 param = applet.getParameter("PDBFILE");
1636 PDBEntry pdb = new PDBEntry();
1639 SequenceI[] seqs = null;
1640 String[] chains = null;
1642 StringTokenizer st = new StringTokenizer(param, " ");
1644 if (st.countTokens() < 2)
1646 String sequence = applet.getParameter("PDBSEQ");
1647 if (sequence != null)
1648 seqs = new SequenceI[]
1649 { matcher==null ? (Sequence) newAlignFrame.getAlignViewport()
1650 .getAlignment().findName(sequence) : matcher.findIdMatch(sequence) };
1655 param = st.nextToken();
1656 Vector tmp = new Vector();
1657 Vector tmp2 = new Vector();
1659 while (st.hasMoreTokens())
1661 seqstring = st.nextToken();
1662 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
1663 if (st2.countTokens() > 1)
1665 // This is the chain
1666 tmp2.addElement(st2.nextToken());
1667 seqstring = st2.nextToken();
1669 tmp.addElement(matcher==null ? (Sequence) newAlignFrame.getAlignViewport()
1670 .getAlignment().findName(seqstring) : matcher.findIdMatch(seqstring));
1673 seqs = new SequenceI[tmp.size()];
1675 if (tmp2.size() == tmp.size())
1677 chains = new String[tmp2.size()];
1678 tmp2.copyInto(chains);
1681 param = setProtocolState(param);
1683 if (// !jmolAvailable
1685 protocol == AppletFormatAdapter.CLASSLOADER)
1687 // TODO: verify this Re:
1688 // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
1689 // This exception preserves the current behaviour where, even if
1690 // the local pdb file was identified in the class loader
1691 protocol = AppletFormatAdapter.URL; // this is probably NOT
1693 param = addProtocol(param); //
1700 for (int i = 0; i < seqs.length; i++)
1702 if (seqs[i] != null)
1704 ((Sequence) seqs[i]).addPDBId(pdb);
1708 if (JalviewLite.debug)
1710 // this may not really be a problem but we give a warning
1713 .println("Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
1719 if (!alignPdbStructures)
1721 newAlignFrame.newStructureView(applet, pdb, seqs, chains,
1726 pdbs.addElement(new Object[]
1727 { pdb, seqs, chains, new String(protocol) });
1733 } while (pdbFileCount < 10);
1734 if (pdbs.size() > 0)
1736 SequenceI[][] seqs = new SequenceI[pdbs.size()][];
1737 PDBEntry[] pdb = new PDBEntry[pdbs.size()];
1738 String[][] chains = new String[pdbs.size()][];
1739 String[] protocols = new String[pdbs.size()];
1740 for (int pdbsi = 0, pdbsiSize = pdbs.size(); pdbsi < pdbsiSize; pdbsi++)
1742 Object[] o = (Object[]) pdbs.elementAt(pdbsi);
1743 pdb[pdbsi] = (PDBEntry) o[0];
1744 seqs[pdbsi] = (SequenceI[]) o[1];
1745 chains[pdbsi] = (String[]) o[2];
1746 protocols[pdbsi] = (String) o[3];
1748 newAlignFrame.alignedStructureView(applet, pdb, seqs, chains,
1752 // ///////////////////////////
1753 // modify display of features
1755 // hide specific groups
1756 param = applet.getParameter("hidefeaturegroups");
1759 applet.setFeatureGroupStateOn(newAlignFrame, param, false);
1761 // show specific groups
1762 param = applet.getParameter("showfeaturegroups");
1765 applet.setFeatureGroupStateOn(newAlignFrame, param, true);
1771 applet.remove(launcher);
1777 * Discovers whether the given file is in the Applet Archive
1783 boolean inArchive(String file)
1785 // This might throw a security exception in certain browsers
1786 // Netscape Communicator for instance.
1789 boolean rtn = (getClass().getResourceAsStream("/" + file) != null);
1792 System.err.println("Resource '" + file + "' was "
1793 + (rtn ? "" : "not") + " located by classloader.");
1796 } catch (Exception ex)
1798 System.out.println("Exception checking resources: " + file + " "
1804 String addProtocol(String file)
1806 if (file.indexOf("://") == -1)
1808 file = applet.getCodeBase() + file;
1811 System.err.println("Prepended codebase for resource: '" + file
1821 * @return the default alignFrame acted on by the public applet methods. May
1822 * return null with an error message on System.err indicating the
1825 public AlignFrame getDefaultTargetFrame()
1827 if (currentAlignFrame != null)
1829 return currentAlignFrame;
1831 if (initialAlignFrame != null)
1833 return initialAlignFrame;
1836 .println("Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
1841 * separator used for separatorList
1843 protected String separator = "" + ((char) 0x00AC); // the default used to be
1844 // '|' but many sequence
1845 // IDS include pipes.
1848 * parse the string into a list
1851 * @return elements separated by separator
1853 public String[] separatorListToArray(String list)
1855 return separatorListToArray(list, separator);
1859 * parse the string into a list
1863 * @return elements separated by separator
1865 public String[] separatorListToArray(String list, String separator)
1867 // note separator local variable intentionally masks object field
1868 int seplen = separator.length();
1869 if (list == null || list.equals("") || list.equals(separator))
1871 java.util.Vector jv = new Vector();
1873 while ((pos = list.indexOf(separator, cp)) > cp)
1875 jv.addElement(list.substring(cp, pos));
1878 if (cp < list.length())
1880 String c = list.substring(cp);
1881 if (!c.equals(separator))
1888 String[] v = new String[jv.size()];
1889 for (int i = 0; i < v.length; i++)
1891 v[i] = (String) jv.elementAt(i);
1893 jv.removeAllElements();
1896 System.err.println("Array from '" + separator
1897 + "' separated List:\n" + v.length);
1898 for (int i = 0; i < v.length; i++)
1900 System.err.println("item " + i + " '" + v[i] + "'");
1907 System.err.println("Empty Array from '" + separator
1908 + "' separated List");
1914 * concatenate the list with separator
1917 * @return concatenated string
1919 public String arrayToSeparatorList(String[] list)
1921 return arrayToSeparatorList(list, separator);
1925 * concatenate the list with separator
1929 * @return concatenated string
1931 public String arrayToSeparatorList(String[] list, String separator)
1933 StringBuffer v = new StringBuffer();
1934 if (list != null && list.length > 0)
1936 for (int i = 0, iSize = list.length; i < iSize; i++)
1938 if (list[i] != null)
1942 v.append(separator);
1949 System.err.println("Returning '" + separator
1950 + "' separated List:\n");
1951 System.err.println(v);
1953 return v.toString();
1957 System.err.println("Returning empty '" + separator
1958 + "' separated List\n");
1960 return "" + separator;
1965 * @see jalview.appletgui.AlignFrame#getFeatureGroups()
1967 public String getFeatureGroups()
1969 String lst = arrayToSeparatorList(getDefaultTargetFrame()
1970 .getFeatureGroups());
1976 * alignframe to get feature groups on
1978 * @see jalview.appletgui.AlignFrame#getFeatureGroups()
1980 public String getFeatureGroupsOn(AlignFrame alf)
1982 String lst = arrayToSeparatorList(alf.getFeatureGroups());
1989 * @see jalview.appletgui.AlignFrame#getFeatureGroupsOfState(boolean)
1991 public String getFeatureGroupsOfState(boolean visible)
1993 return arrayToSeparatorList(getDefaultTargetFrame()
1994 .getFeatureGroupsOfState(visible));
1999 * align frame to get groups of state visible
2002 * @see jalview.appletgui.AlignFrame#getFeatureGroupsOfState(boolean)
2004 public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
2006 return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
2011 * tab separated list of group names
2014 * @see jalview.appletgui.AlignFrame#setFeatureGroupState(java.lang.String[],
2017 public void setFeatureGroupStateOn(AlignFrame alf, String groups,
2020 boolean st = state;// !(state==null || state.equals("") ||
2021 // state.toLowerCase().equals("false"));
2022 alf.setFeatureGroupState(separatorListToArray(groups), st);
2025 public void setFeatureGroupState(String groups, boolean state)
2027 setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
2031 * List separator string
2033 * @return the separator
2035 public String getSeparator()
2041 * List separator string
2044 * the separator to set. empty string will reset separator to default
2046 public void setSeparator(String separator)
2048 if (separator == null || separator.length() < 1)
2051 separator = "" + ((char) 0x00AC);
2053 this.separator = separator;
2056 System.err.println("Default Separator now: '" + separator + "'");
2061 * get boolean value of applet parameter 'name' and return default if
2062 * parameter is not set
2067 * the value to return otherwise
2068 * @return true or false
2070 public boolean getDefaultParameter(String name, boolean def)
2073 if ((stn = getParameter(name)) == null)
2077 if (stn.toLowerCase().equals("true"))
2085 * bind a pdb file to a sequence in the given alignFrame.
2088 * - null or specific alignFrame. This specifies the dataset that
2089 * will be searched for a seuqence called sequenceId
2091 * - sequenceId within the dataset.
2092 * @param pdbEntryString
2093 * - the short name for the PDB file
2095 * - pdb file - either a URL or a valid PDB file.
2096 * @return true if binding was as success TODO: consider making an exception
2097 * structure for indicating when PDB parsing or seqeunceId location
2100 public boolean addPdbFile(AlignFrame alFrame, String sequenceId,
2101 String pdbEntryString, String pdbFile)
2103 return alFrame.addPdbFile(sequenceId, pdbEntryString, pdbFile);
2106 protected void setAlignPdbStructures(boolean alignPdbStructures)
2108 this.alignPdbStructures = alignPdbStructures;
2111 public boolean isAlignPdbStructures()
2113 return alignPdbStructures;
2122 * bind structures in a viewer to any matching sequences in an alignFrame (use
2123 * sequenceIds to limit scope of search to specific sequences)
2127 * @param sequenceIds
2128 * @return TODO: consider making an exception structure for indicating when
2129 * binding fails public SequenceStructureBinding
2130 * addStructureViewInstance( AlignFrame alFrame, Object viewer, String
2133 * if (sequenceIds != null && sequenceIds.length() > 0) { return
2134 * alFrame.addStructureViewInstance(viewer,
2135 * separatorListToArray(sequenceIds)); } else { return
2136 * alFrame.addStructureViewInstance(viewer, null); } // return null; }