X-Git-Url: http://source.jalview.org/gitweb/?a=blobdiff_plain;f=src%2Fjalview%2Fbin%2FJalviewAppLoader.java;fp=src%2Fjalview%2Fbin%2FJalviewAppLoader.java;h=51a03306e46382c3ac1221666481852f98dacdf0;hb=a83adb45bdf9554e270921b4baad94defd314b36;hp=0000000000000000000000000000000000000000;hpb=d4ec118f86b5c9dee801e743c46aaacc7bb521d1;p=jalview.git diff --git a/src/jalview/bin/JalviewAppLoader.java b/src/jalview/bin/JalviewAppLoader.java new file mode 100644 index 0000000..51a0330 --- /dev/null +++ b/src/jalview/bin/JalviewAppLoader.java @@ -0,0 +1,1483 @@ +package jalview.bin; + +import jalview.api.AlignFrameI; +import jalview.api.JalviewApp; +import jalview.api.StructureSelectionManagerProvider; +import jalview.datamodel.Alignment; +import jalview.datamodel.AlignmentI; +import jalview.datamodel.AlignmentOrder; +import jalview.datamodel.ColumnSelection; +import jalview.datamodel.HiddenColumns; +import jalview.datamodel.PDBEntry; +import jalview.datamodel.Sequence; +import jalview.datamodel.SequenceGroup; +import jalview.datamodel.SequenceI; +import jalview.gui.AlignFrame; +import jalview.gui.AlignViewport; +import jalview.gui.Desktop; +import jalview.io.AnnotationFile; +import jalview.io.AppletFormatAdapter; +import jalview.io.DataSourceType; +import jalview.io.FeaturesFile; +import jalview.io.FileFormat; +import jalview.io.FileFormatI; +import jalview.io.FileFormats; +import jalview.io.IdentifyFile; +import jalview.io.JPredFile; +import jalview.io.JnetAnnotationMaker; +import jalview.io.NewickFile; +import jalview.structure.SelectionSource; +import jalview.structure.StructureSelectionManager; +import jalview.util.HttpUtils; +import jalview.util.MessageManager; + +import java.awt.EventQueue; +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; +import java.util.Vector; + +/** + * A class to load parameters for either JalviewLite or Jalview + * + * @author hansonr + * + */ +public class JalviewAppLoader +{ + + private JalviewApp app; // Jalview or JalviewJS or JalviewLite + + private boolean debug; + + String separator = "\u00AC"; // JalviewLite note: the default used to + // be '|', but many sequence IDS include + // pipes. + + public String getSeparator() + { + return separator; + } + + public void setSeparator(String separator) + { + this.separator = separator; + } + + public JalviewAppLoader(boolean debug) + { + this.debug = debug; + } + + public void load(JalviewApp app) + { + + this.app = app; + + String sep = app.getParameter("separator"); + if (sep != null) + { + if (sep.length() > 0) + { + separator = sep; + } + else + { + throw new Error(MessageManager + .getString("error.invalid_separator_parameter")); + } + } + + loadTree(); + loadScoreFile(); + loadFeatures(); + loadAnnotations(); + loadJnetFile(); + loadPdbFiles(); + callInitCallback(); + } + + /** + * Load PDBFiles if any specified by parameter(s). Returns true if loaded, + * else false. + * + * @param loaderFrame + * @return + */ + protected boolean loadPdbFiles() + { + boolean result = false; + /* + * Undocumented for 2.6 - + * related to JAL-434 + */ + + boolean doAlign = app.getDefaultParameter("alignpdbfiles", false); + app.setAlignPdbStructures(doAlign); + /* + * + * + * + * + * + */ + + // Accumulate pdbs here if they are heading for the same view (if + // alignPdbStructures is true) + Vector pdbs = new Vector<>(); + // create a lazy matcher if we're asked to + jalview.analysis.SequenceIdMatcher matcher = (app + .getDefaultParameter("relaxedidmatch", false)) + ? new jalview.analysis.SequenceIdMatcher( + app.getViewport().getAlignment() + .getSequencesArray()) + : null; + + int pdbFileCount = 0; + String param; + do + { + if (pdbFileCount > 0) + { + param = app.getParameter("PDBFILE" + pdbFileCount); + } + else + { + param = app.getParameter("PDBFILE"); + } + + if (param != null) + { + PDBEntry pdb = new PDBEntry(); + + String seqstring; + SequenceI[] seqs = null; + String[] chains = null; + + StringTokenizer st = new StringTokenizer(param, " "); + + if (st.countTokens() < 2) + { + String sequence = app.getParameter("PDBSEQ"); + if (sequence != null) + { + seqs = new SequenceI[] { matcher == null + ? (Sequence) app.getViewport().getAlignment() + .findName(sequence) + : matcher.findIdMatch(sequence) }; + } + + } + else + { + param = st.nextToken(); + List tmp = new ArrayList<>(); + List tmp2 = new ArrayList<>(); + + while (st.hasMoreTokens()) + { + seqstring = st.nextToken(); + StringTokenizer st2 = new StringTokenizer(seqstring, "="); + if (st2.countTokens() > 1) + { + // This is the chain + tmp2.add(st2.nextToken()); + seqstring = st2.nextToken(); + } + tmp.add(matcher == null + ? (Sequence) app.getViewport().getAlignment() + .findName(seqstring) + : matcher.findIdMatch(seqstring)); + } + + seqs = tmp.toArray(new SequenceI[tmp.size()]); + if (tmp2.size() == tmp.size()) + { + chains = tmp2.toArray(new String[tmp2.size()]); + } + } + pdb.setId(param); + ret[0] = param; + DataSourceType protocol = resolveFileProtocol(app, ret); + // TODO check JAL-357 for files in a jar (CLASSLOADER) + pdb.setFile(ret[0]); + + if (seqs != null) + { + for (int i = 0; i < seqs.length; i++) + { + if (seqs[i] != null) + { + ((Sequence) seqs[i]).addPDBId(pdb); + StructureSelectionManager + .getStructureSelectionManager( + (StructureSelectionManagerProvider) app) + .registerPDBEntry(pdb); + } + else + { + if (debug) + { + // this may not really be a problem but we give a warning + // anyway + System.err.println( + "Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence " + + i + ")"); + } + } + } + + if (doAlign) + { + pdbs.addElement(new Object[] { pdb, seqs, chains, protocol }); + } + else + { + app.newStructureView(pdb, seqs, chains, protocol); + } + } + } + + pdbFileCount++; + } while (param != null || pdbFileCount < 10); + if (pdbs.size() > 0) + { + SequenceI[][] seqs = new SequenceI[pdbs.size()][]; + PDBEntry[] pdb = new PDBEntry[pdbs.size()]; + String[][] chains = new String[pdbs.size()][]; + String[] protocols = new String[pdbs.size()]; + for (int pdbsi = 0, pdbsiSize = pdbs + .size(); pdbsi < pdbsiSize; pdbsi++) + { + Object[] o = pdbs.elementAt(pdbsi); + pdb[pdbsi] = (PDBEntry) o[0]; + seqs[pdbsi] = (SequenceI[]) o[1]; + chains[pdbsi] = (String[]) o[2]; + protocols[pdbsi] = (String) o[3]; + } + app.alignedStructureView(pdb, seqs, chains, protocols); + result = true; + } + return result; + } + + /** + * Load in a Jnetfile if specified by parameter. Returns true if loaded, else + * false. + * + * @param alignFrame + * @return + */ + protected boolean loadJnetFile() + { + boolean result = false; + String param = app.getParameter("jnetfile"); + if (param == null) + { + // jnet became jpred around 2016 + param = app.getParameter("jpredfile"); + } + if (param != null) + { + try + { + ret[0] = param; + DataSourceType protocol = resolveFileProtocol(app, ret); + JPredFile predictions = new JPredFile(ret[0], protocol); + JnetAnnotationMaker.add_annotation(predictions, + app.getViewport().getAlignment(), 0, false); + // false == do not add sequence profile from concise output + app.getViewport().getAlignment().setupJPredAlignment(); + app.updateForAnnotations(); + result = true; + } catch (Exception ex) + { + ex.printStackTrace(); + } + } + return result; + } + + /** + * Load annotations if specified by parameter. Returns true if loaded, else + * false. + * + * @param alignFrame + * @return + */ + protected boolean loadAnnotations() + { + boolean result = false; + String param = app.getParameter("annotations"); + if (param != null) + { + ret[0] = param; + DataSourceType protocol = resolveFileProtocol(app, ret); + param = ret[0]; + if (new AnnotationFile().annotateAlignmentView(app.getViewport(), + param, protocol)) + { + app.updateForAnnotations(); + result = true; + } + else + { + System.err + .println("Annotations were not added from annotation file '" + + param + "'"); + } + } + return result; + } + + /** + * Load features file and view settings as specified by parameters. Returns + * true if features were loaded, else false. + * + * @param alignFrame + * @return + */ + protected boolean loadFeatures() + { + boolean result = false; + // /////////////////////////// + // modify display of features + // we do this before any features have been loaded, ensuring any hidden + // groups are hidden when features first displayed + // + // hide specific groups + // + String param = app.getParameter("hidefeaturegroups"); + if (param != null) + { + app.setFeatureGroupState(separatorListToArray(param, separator), + false); + // app.setFeatureGroupStateOn(newAlignFrame, param, false); + } + // show specific groups + param = app.getParameter("showfeaturegroups"); + if (param != null) + { + app.setFeatureGroupState(separatorListToArray(param, separator), + true); + // app.setFeatureGroupStateOn(newAlignFrame, param, true); + } + // and now load features + param = app.getParameter("features"); + if (param != null) + { + ret[0] = param; + DataSourceType protocol = resolveFileProtocol(app, ret); + + result = app.parseFeaturesFile(ret[0], protocol); + } + + param = app.getParameter("showFeatureSettings"); + if (param != null && param.equalsIgnoreCase("true")) + { + app.newFeatureSettings(); + } + return result; + } + + /** + * Load a score file if specified by parameter. Returns true if file was + * loaded, else false. + * + * @param loaderFrame + */ + protected boolean loadScoreFile() + { + boolean result = false; + String sScoreFile = app.getParameter("scoreFile"); + if (sScoreFile != null && !"".equals(sScoreFile)) + { + try + { + if (debug) + { + System.err.println( + "Attempting to load T-COFFEE score file from the scoreFile parameter"); + } + result = app.loadScoreFile(sScoreFile); + if (!result) + { + System.err.println( + "Failed to parse T-COFFEE parameter as a valid score file ('" + + sScoreFile + "')"); + } + } catch (Exception e) + { + System.err.printf("Cannot read score file: '%s'. Cause: %s \n", + sScoreFile, e.getMessage()); + } + } + return result; + } + + String[] ret = new String[1]; + + /** + * Load a tree for the alignment if specified by parameter. Returns true if a + * tree was loaded, else false. + * + * @param loaderFrame + * @return + */ + protected boolean loadTree() + { + boolean result = false; + String treeFile = app.getParameter("tree"); + if (treeFile == null) + { + treeFile = app.getParameter("treeFile"); + } + + if (treeFile != null) + { + try + { + ret[0] = treeFile; + NewickFile fin = new NewickFile(treeFile, + resolveFileProtocol(app, ret)); + fin.parse(); + + if (fin.getTree() != null) + { + app.loadTree(fin, ret[0]); + result = true; + if (debug) + { + System.out.println("Successfully imported tree."); + } + } + else + { + if (debug) + { + System.out.println( + "Tree parameter did not resolve to a valid tree."); + } + } + } catch (Exception ex) + { + ex.printStackTrace(); + } + } + return result; + } + + /** + * form a complete URL given a path to a resource and a reference location on + * the same server + * + * @param targetPath + * - an absolute path on the same server as localref or a document + * located relative to localref + * @param localref + * - a URL on the same server as url + * @return a complete URL for the resource located by url + */ + public static String resolveUrlForLocalOrAbsolute(String targetPath, + URL localref) + { + String resolvedPath = ""; + if (targetPath.startsWith("/")) + { + String codebase = localref.toString(); + String localfile = localref.getFile(); + resolvedPath = codebase.substring(0, + codebase.length() - localfile.length()) + targetPath; + return resolvedPath; + } + + /* + * get URL path and strip off any trailing file e.g. + * www.jalview.org/examples/index.html#applets?a=b is trimmed to + * www.jalview.org/examples/ + */ + String urlPath = localref.toString(); + String directoryPath = urlPath; + int lastSeparator = directoryPath.lastIndexOf("/"); + if (lastSeparator > 0) + { + directoryPath = directoryPath.substring(0, lastSeparator + 1); + } + + if (targetPath.startsWith("/")) + { + /* + * construct absolute URL to a file on the server - this is not allowed? + */ + // String localfile = localref.getFile(); + // resolvedPath = urlPath.substring(0, + // urlPath.length() - localfile.length()) + // + targetPath; + resolvedPath = directoryPath + targetPath.substring(1); + } + else + { + resolvedPath = directoryPath + targetPath; + } + // if (debug) + // { + // System.err.println( + // "resolveUrlForLocalOrAbsolute returning " + resolvedPath); + // } + return resolvedPath; + } + + /** + * parse the string into a list + * + * @param list + * @param separator + * @return elements separated by separator + */ + public static String[] separatorListToArray(String list, String separator) + { + // TODO use StringUtils version (slightly different...) + int seplen = separator.length(); + if (list == null || list.equals("") || list.equals(separator)) + { + return null; + } + Vector jv = new Vector<>(); + int cp = 0, pos; + while ((pos = list.indexOf(separator, cp)) > cp) + { + jv.addElement(list.substring(cp, pos)); + cp = pos + seplen; + } + if (cp < list.length()) + { + String c = list.substring(cp); + if (!c.equals(separator)) + { + jv.addElement(c); + } + } + if (jv.size() > 0) + { + String[] v = new String[jv.size()]; + for (int i = 0; i < v.length; i++) + { + v[i] = jv.elementAt(i); + } + jv.removeAllElements(); + // if (debug) + // { + // System.err.println("Array from '" + separator + // + "' separated List:\n" + v.length); + // for (int i = 0; i < v.length; i++) + // { + // System.err.println("item " + i + " '" + v[i] + "'"); + // } + // } + return v; + } + // if (debug) + // { + // System.err.println( + // "Empty Array from '" + separator + "' separated List"); + // } + return null; + } + + public static DataSourceType resolveFileProtocol(JalviewApp app, + String[] retPath) + { + String path = retPath[0]; + /* + * is it paste data? + */ + if (path.startsWith("PASTE")) + { + retPath[0] = path.substring(5); + return DataSourceType.PASTE; + } + + /* + * is it a URL? + */ + if (path.indexOf("://") >= 0) + { + return DataSourceType.URL; + } + + /* + * try relative to document root + */ + URL documentBase = app.getDocumentBase(); + String withDocBase = resolveUrlForLocalOrAbsolute(path, documentBase); + if (HttpUtils.isValidUrl(withDocBase)) + { + // if (debug) + // { + // System.err.println("Prepended document base '" + documentBase + // + "' to make: '" + withDocBase + "'"); + // } + retPath[0] = withDocBase; + return DataSourceType.URL; + } + + /* + * try relative to codebase (if different to document base) + */ + URL codeBase = app.getCodeBase(); + String withCodeBase = resolveUrlForLocalOrAbsolute(path, codeBase); + if (!withCodeBase.equals(withDocBase) + && HttpUtils.isValidUrl(withCodeBase)) + { + // if (debug) + // { + // System.err.println("Prepended codebase '" + codeBase + // + "' to make: '" + withCodeBase + "'"); + // } + retPath[0] = withCodeBase; + return DataSourceType.URL; + } + + /* + * try locating by classloader; try this last so files in the directory + * are resolved using document base + */ + if (inArchive(app.getClass(), path)) + { + return DataSourceType.CLASSLOADER; + } + return null; + } + + /** + * Discovers whether the given file is in the Applet Archive + * + * @param f + * String + * @return boolean + */ + private static boolean inArchive(Class c, String f) + { + // This might throw a security exception in certain browsers + // Netscape Communicator for instance. + try + { + boolean rtn = (c.getResourceAsStream("/" + f) != null); + // if (debug) + // { + // System.err.println("Resource '" + f + "' was " + // + (rtn ? "" : "not ") + "located by classloader."); + // } + return rtn; + } catch (Exception ex) + { + System.out.println("Exception checking resources: " + f + " " + ex); + return false; + } + } + + public void callInitCallback() + { + String initjscallback = app.getParameter("oninit"); + if (initjscallback == null) + { + return; + } + initjscallback = initjscallback.trim(); + if (initjscallback.length() > 0) + { + // TODO + } + } + + /** + * read sequence1...sequenceN as a raw alignment + * + * @param jalviewApp + * @return + */ + public String getPastedSequence(JalviewApp jalviewApp) + { + StringBuffer data = new StringBuffer("PASTE"); + int i = 1; + String file = null; + while ((file = app.getParameter("sequence" + i)) != null) + { + data.append(file.toString() + "\n"); + i++; + } + if (data.length() > 5) + { + file = data.toString(); + } + return file; + } + + /** + * concatenate the list with separator + * + * @param list + * @param separator + * @return concatenated string + */ + public static String arrayToSeparatorList(String[] list, String separator) + { + // TODO use StringUtils version + StringBuffer v = new StringBuffer(); + if (list != null && list.length > 0) + { + for (int i = 0, iSize = list.length; i < iSize; i++) + { + if (list[i] != null) + { + if (i > 0) + { + v.append(separator); + } + v.append(list[i]); + } + } + // if (debug) + // { + // System.err + // .println("Returning '" + separator + "' separated List:\n"); + // System.err.println(v); + // } + return v.toString(); + } + // if (debug) + // { + // System.err.println( + // "Returning empty '" + separator + "' separated List\n"); + // } + return "" + separator; + } + + public String arrayToSeparatorList(String[] array) + { + return arrayToSeparatorList(array, separator); + } + + public String getSelectedSequencesFrom(AlignFrameI alf, String sep) + { + StringBuffer result = new StringBuffer(""); + if (sep == null || sep.length() == 0) + { + sep = separator; // "+0x00AC; + } + AlignViewport v = ((AlignFrame) alf).getViewport(); + if (v.getSelectionGroup() != null) + { + SequenceI[] seqs = v.getSelectionGroup() + .getSequencesInOrder(v.getAlignment()); + + for (int i = 0; i < seqs.length; i++) + { + result.append(seqs[i].getName()); + result.append(sep); + } + } + + return result.toString(); + } + + public void setFeatureGroupStateOn(final AlignFrameI alf, + final String groups, boolean state) + { + java.awt.EventQueue.invokeLater(new Runnable() + { + @Override + public void run() + { + ((AlignFrame) alf).setFeatureGroupState( + separatorListToArray(groups, separator), state); + } + }); + } + + public String getFeatureGroupsOfStateOn(AlignFrameI alf, boolean visible) + { + return arrayToSeparatorList( + ((AlignFrame) alf).getFeatureGroupsOfState(visible)); + } + + public void scrollViewToIn(final AlignFrameI alf, final String topRow, + final String leftHandColumn) + { + java.awt.EventQueue.invokeLater(new Runnable() + { + @Override + public void run() + { + try + { + ((AlignFrame) alf).scrollTo(new Integer(topRow).intValue(), + new Integer(leftHandColumn).intValue()); + + } catch (Exception ex) + { + System.err.println("Couldn't parse integer arguments (topRow='" + + topRow + "' and leftHandColumn='" + leftHandColumn + + "')"); + ex.printStackTrace(); + } + } + }); + } + + public void scrollViewToRowIn(final AlignFrameI alf, final String topRow) + { + + java.awt.EventQueue.invokeLater(new Runnable() + { + @Override + public void run() + { + try + { + ((AlignFrame) alf).scrollToRow(new Integer(topRow).intValue()); + + } catch (Exception ex) + { + System.err.println("Couldn't parse integer arguments (topRow='" + + topRow + "')"); + ex.printStackTrace(); + } + + } + }); + } + + public void scrollViewToColumnIn(final AlignFrameI alf, + final String leftHandColumn) + { + java.awt.EventQueue.invokeLater(new Runnable() + { + + @Override + public void run() + { + try + { + ((AlignFrame) alf) + .scrollToColumn(new Integer(leftHandColumn).intValue()); + + } catch (Exception ex) + { + System.err.println( + "Couldn't parse integer arguments (leftHandColumn='" + + leftHandColumn + "')"); + ex.printStackTrace(); + } + } + }); + + } + + public boolean addPdbFile(AlignFrameI alf, String sequenceId, + String pdbEntryString, String pdbFile) + { + AlignFrame alFrame = (AlignFrame) alf; + SequenceI toaddpdb = alFrame.getViewport().getAlignment() + .findName(sequenceId); + boolean needtoadd = false; + if (toaddpdb != null) + { + Vector pdbe = toaddpdb.getAllPDBEntries(); + PDBEntry pdbentry = null; + if (pdbe != null && pdbe.size() > 0) + { + for (int pe = 0, peSize = pdbe.size(); pe < peSize; pe++) + { + pdbentry = pdbe.elementAt(pe); + if (!pdbentry.getId().equals(pdbEntryString) + && !pdbentry.getFile().equals(pdbFile)) + { + pdbentry = null; + } + else + { + continue; + } + } + } + if (pdbentry == null) + { + pdbentry = new PDBEntry(); + pdbentry.setId(pdbEntryString); + pdbentry.setFile(pdbFile); + needtoadd = true; // add this new entry to sequence. + } + // resolve data source + // TODO: this code should be a refactored to an io package + DataSourceType protocol = AppletFormatAdapter.resolveProtocol(pdbFile, + FileFormat.PDB); + if (protocol == null) + { + return false; + } + if (needtoadd) + { + pdbentry.setProperty("protocol", protocol); + toaddpdb.addPDBId(pdbentry); + alFrame.alignPanel.getStructureSelectionManager() + .registerPDBEntry(pdbentry); + } + } + return true; + } + + public AlignFrameI loadAlignment(String text, int width, int height, + String title) + { + AlignmentI al = null; + + try + { + FileFormatI format = new IdentifyFile().identify(text, + DataSourceType.PASTE); + al = new AppletFormatAdapter().readFile(text, DataSourceType.PASTE, + format); + if (al.getHeight() > 0) + { + return new AlignFrame(al, width, height, title); + } + } catch (IOException ex) + { + ex.printStackTrace(); + } + return null; + } + + public String getFeatureGroupsOn(AlignFrameI alf) + { + return arrayToSeparatorList( + ((AlignFrame) alf).getFeatureGroups()); + } + + public void highlightIn(final AlignFrameI alf, final String sequenceId, + final String position, final String alignedPosition) + { + // TODO: could try to highlight in all alignments if alf==null + jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher( + ((AlignFrame) alf).getViewport().getAlignment() + .getSequencesArray()); + final SequenceI sq = matcher.findIdMatch(sequenceId); + if (sq != null) + { + int apos = -1; + try + { + apos = new Integer(position).intValue(); + apos--; + } catch (NumberFormatException ex) + { + return; + } + final int pos = apos; + // use vamsas listener to broadcast to all listeners in scope + if (alignedPosition != null && (alignedPosition.trim().length() == 0 + || alignedPosition.toLowerCase().indexOf("false") > -1)) + { + java.awt.EventQueue.invokeLater(new Runnable() + { + @Override + public void run() + { + StructureSelectionManager + .getStructureSelectionManager(Desktop.getInstance()) + .mouseOverVamsasSequence(sq, sq.findIndex(pos), null); + } + }); + } + else + { + java.awt.EventQueue.invokeLater(new Runnable() + { + @Override + public void run() + { + StructureSelectionManager + .getStructureSelectionManager(Desktop.getInstance()) + .mouseOverVamsasSequence(sq, pos, null); + } + }); + } + } + } + + public void selectIn(final AlignFrameI alf, String sequenceIds, + String columns, String sep) + { + if (sep == null || sep.length() == 0) + { + sep = separator; + } + else + { + if (debug) + { + System.err.println("Selecting region using separator string '" + + separator + "'"); + } + } + // deparse fields + String[] ids = JalviewAppLoader.separatorListToArray(sequenceIds, sep); + String[] cols = JalviewAppLoader.separatorListToArray(columns, sep); + final SequenceGroup sel = new SequenceGroup(); + final ColumnSelection csel = new ColumnSelection(); + AlignmentI al = ((AlignFrame) alf).getViewport().getAlignment(); + jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher( + ((AlignFrame) alf).getViewport().getAlignment() + .getSequencesArray()); + int start = 0, end = al.getWidth(), alw = al.getWidth(); + boolean seqsfound = true; + if (ids != null && ids.length > 0) + { + seqsfound = false; + for (int i = 0; i < ids.length; i++) + { + if (ids[i].trim().length() == 0) + { + continue; + } + SequenceI sq = matcher.findIdMatch(ids[i]); + if (sq != null) + { + seqsfound = true; + sel.addSequence(sq, false); + } + } + } + boolean inseqpos = false; + if (cols != null && cols.length > 0) + { + boolean seset = false; + for (int i = 0; i < cols.length; i++) + { + String cl = cols[i].trim(); + if (cl.length() == 0) + { + continue; + } + int p; + if ((p = cl.indexOf("-")) > -1) + { + int from = -1, to = -1; + try + { + from = new Integer(cl.substring(0, p)).intValue(); + from--; + } catch (NumberFormatException ex) + { + System.err.println( + "ERROR: Couldn't parse first integer in range element column selection string '" + + cl + "' - format is 'from-to'"); + return; + } + try + { + to = new Integer(cl.substring(p + 1)).intValue(); + to--; + } catch (NumberFormatException ex) + { + System.err.println( + "ERROR: Couldn't parse second integer in range element column selection string '" + + cl + "' - format is 'from-to'"); + return; + } + if (from >= 0 && to >= 0) + { + // valid range + if (from < to) + { + int t = to; + to = from; + to = t; + } + if (!seset) + { + start = from; + end = to; + seset = true; + } + else + { + // comment to prevent range extension + if (start > from) + { + start = from; + } + if (end < to) + { + end = to; + } + } + for (int r = from; r <= to; r++) + { + if (r >= 0 && r < alw) + { + csel.addElement(r); + } + } + if (debug) + { + System.err.println("Range '" + cl + "' deparsed as [" + from + + "," + to + "]"); + } + } + else + { + System.err.println("ERROR: Invalid Range '" + cl + + "' deparsed as [" + from + "," + to + "]"); + } + } + else + { + int r = -1; + try + { + r = new Integer(cl).intValue(); + r--; + } catch (NumberFormatException ex) + { + if (cl.toLowerCase().equals("sequence")) + { + // we are in the dataset sequence's coordinate frame. + inseqpos = true; + } + else + { + System.err.println( + "ERROR: Couldn't parse integer from point selection element of column selection string '" + + cl + "'"); + return; + } + } + if (r >= 0 && r <= alw) + { + if (!seset) + { + start = r; + end = r; + seset = true; + } + else + { + // comment to prevent range extension + if (start > r) + { + start = r; + } + if (end < r) + { + end = r; + } + } + csel.addElement(r); + if (debug) + { + System.err.println("Point selection '" + cl + + "' deparsed as [" + r + "]"); + } + } + else + { + System.err.println("ERROR: Invalid Point selection '" + cl + + "' deparsed as [" + r + "]"); + } + } + } + } + if (seqsfound) + { + // we only propagate the selection when it was the null selection, or the + // given sequences were found in the alignment. + if (inseqpos && sel.getSize() > 0) + { + // assume first sequence provides reference frame ? + SequenceI rs = sel.getSequenceAt(0); + start = rs.findIndex(start); + end = rs.findIndex(end); + List cs = new ArrayList<>(csel.getSelected()); + csel.clear(); + for (Integer selectedCol : cs) + { + csel.addElement(rs.findIndex(selectedCol)); + } + } + sel.setStartRes(start); + sel.setEndRes(end); + EventQueue.invokeLater(new Runnable() + { + @Override + public void run() + { + ((AlignFrame) alf).select(sel, csel, ((AlignFrame) alf) + .getCurrentView().getAlignment().getHiddenColumns()); + } + }); + } + } + + public String getAlignmentOrderFrom(AlignFrameI alf, String sep) + { + AlignmentI alorder = ((AlignFrame) alf).getViewport().getAlignment(); + String[] order = new String[alorder.getHeight()]; + for (int i = 0; i < order.length; i++) + { + order[i] = alorder.getSequenceAt(i).getName(); + } + return arrayToSeparatorList(order, sep); + } + + public String getSelectedSequencesAsAlignmentFrom(AlignFrameI alf, + String format, String suffix) + { + try + { + AlignViewport vp = ((AlignFrame) alf).getViewport(); + FileFormatI theFormat = FileFormats.getInstance().forName(format); + boolean seqlimits = (suffix == null + || suffix.equalsIgnoreCase("true")); + if (vp.getSelectionGroup() != null) + { + // JBPNote: getSelectionAsNewSequence behaviour has changed - this + // method now returns a full copy of sequence data + // TODO consider using getSequenceSelection instead here + String reply = new AppletFormatAdapter().formatSequences(theFormat, + new Alignment(vp.getSelectionAsNewSequence()), + seqlimits); + return reply; + } + } catch (IllegalArgumentException ex) + { + ex.printStackTrace(); + return "Error retrieving alignment, possibly invalid format specifier: " + + format; + } + return ""; + } + + public String orderAlignmentBy(AlignFrameI alf, String order, + String undoName, String sep) + { + if (sep == null || sep.length() == 0) + { + sep = separator; + } + String[] ids = JalviewAppLoader.separatorListToArray(order, sep); + SequenceI[] sqs = null; + if (ids != null && ids.length > 0) + { + jalview.analysis.SequenceIdMatcher matcher = new jalview.analysis.SequenceIdMatcher( + ((AlignFrame) alf).getViewport().getAlignment() + .getSequencesArray()); + int s = 0; + sqs = new SequenceI[ids.length]; + for (int i = 0; i < ids.length; i++) + { + if (ids[i].trim().length() == 0) + { + continue; + } + SequenceI sq = matcher.findIdMatch(ids[i]); + if (sq != null) + { + sqs[s++] = sq; + } + } + if (s > 0) + { + SequenceI[] sqq = new SequenceI[s]; + System.arraycopy(sqs, 0, sqq, 0, s); + sqs = sqq; + } + else + { + sqs = null; + } + } + if (sqs == null) + { + return ""; + } + ; + final AlignmentOrder aorder = new AlignmentOrder(sqs); + + if (undoName != null && undoName.trim().length() == 0) + { + undoName = null; + } + final String _undoName = undoName; + // TODO: deal with synchronization here: cannot raise any events until after + // this has returned. + return ((AlignFrame) alf).sortBy(aorder, _undoName) ? "true" : ""; + } + + public String getAlignmentFrom(AlignFrameI alf, String format, + String suffix) + { + try + { + boolean seqlimits = (suffix == null + || suffix.equalsIgnoreCase("true")); + + FileFormatI theFormat = FileFormats.getInstance().forName(format); + String reply = new AppletFormatAdapter().formatSequences(theFormat, + ((AlignFrame) alf).getViewport().getAlignment(), seqlimits); + return reply; + } catch (IllegalArgumentException ex) + { + ex.printStackTrace(); + return "Error retrieving alignment, possibly invalid format specifier: " + + format; + } + } + + public void loadAnnotationFrom(AlignFrameI alf, String annotation) + { + if (new AnnotationFile().annotateAlignmentView( + ((AlignFrame) alf).getViewport(), annotation, + DataSourceType.PASTE)) + { + ((AlignFrame) alf).alignPanel.fontChanged(); + ((AlignFrame) alf).alignPanel.setScrollValues(0, 0); + } + else + { + ((AlignFrame) alf).parseFeaturesFile(annotation, + DataSourceType.PASTE); + } + } + + public boolean loadFeaturesFrom(AlignFrameI alf, String features, + boolean autoenabledisplay) + { + boolean ret = ((AlignFrame) alf).parseFeaturesFile(features, + DataSourceType.PASTE); + if (!ret) + { + return false; + } + if (autoenabledisplay) + { + ((AlignFrame) alf).getViewport().setShowSequenceFeatures(true); + // this next was for a checkbox in JalviewLite + // ((AlignFrame) alf).getViewport().sequenceFeatures.setState(true); + } + return true; + } + + public String getFeaturesFrom(AlignFrameI alf, String format) + { + AlignFrame f = ((AlignFrame) alf); + + String features; + FeaturesFile formatter = new FeaturesFile(); + if (format.equalsIgnoreCase("Jalview")) + { + features = formatter.printJalviewFormat( + f.getViewport().getAlignment().getSequencesArray(), + f.alignPanel.getFeatureRenderer(), true); + } + else + { + features = formatter.printGffFormat( + f.getViewport().getAlignment().getSequencesArray(), + f.alignPanel.getFeatureRenderer(), true); + } + + if (features == null) + { + features = ""; + } + return features; + + } + + public String getAnnotationFrom(AlignFrameI alf) + { + AlignFrame f = (AlignFrame) alf; + String annotation = new AnnotationFile() + .printAnnotationsForView(f.getViewport()); + return annotation; + } + + public AlignFrameI newViewFrom(AlignFrameI alf, String name) + { + return (AlignFrameI) ((AlignFrame) alf).newView(name, true); + } + + public String[] separatorListToArray(String list) + { + return separatorListToArray(list, separator); + } + + public Object[] getSelectionForListener(AlignFrameI currentFrame, + SequenceGroup seqsel, ColumnSelection colsel, + HiddenColumns hidden, SelectionSource source, Object alignFrame) + { + // System.err.println("Testing selection event relay to + // jsfunction:"+_listener); + String setid = ""; + AlignFrame src = (AlignFrame) alignFrame; + if (source != null) + { + if (source instanceof AlignViewport + && ((AlignFrame) currentFrame).getViewport() == source) + { + // should be valid if it just generated an event! + src = (AlignFrame) currentFrame; + + } + } + String[] seqs = new String[] {}; + String[] cols = new String[] {}; + int strt = 0, end = (src == null) ? -1 + : src.alignPanel.av.getAlignment().getWidth(); + if (seqsel != null && seqsel.getSize() > 0) + { + seqs = new String[seqsel.getSize()]; + for (int i = 0; i < seqs.length; i++) + { + seqs[i] = seqsel.getSequenceAt(i).getName(); + } + if (strt < seqsel.getStartRes()) + { + strt = seqsel.getStartRes(); + } + if (end == -1 || end > seqsel.getEndRes()) + { + end = seqsel.getEndRes(); + } + } + if (colsel != null && !colsel.isEmpty()) + { + if (end == -1) + { + end = colsel.getMax() + 1; + } + cols = new String[colsel.getSelected().size()]; + for (int i = 0; i < cols.length; i++) + { + cols[i] = "" + (1 + colsel.getSelected().get(i).intValue()); + } + } + else + { + if (seqsel != null && seqsel.getSize() > 0) + { + // send a valid range, otherwise we send the empty selection + cols = new String[2]; + cols[0] = "" + (1 + strt) + "-" + (1 + end); + } + } + return new Object[] { src, setid, arrayToSeparatorList(seqs), + arrayToSeparatorList(cols) }; + } + +} \ No newline at end of file