httpclient-4.0.3.jar
httpcore-4.0.1.jar
httpmime-4.0.3.jar
-intervalstore-v1.0.jar
+intervalstore-v1.1.jar
- jabaws-min-client-2.2.0.jar
+ jabaws-min-client-NO_LOG4J-2.2.1.jar Apache license - pre-release of JABAWS 2.2.1 client built from https://source.jalview.org/crucible/changelog/jabaws?cs=586260b9f877e0954513fcffb0aa27eaddc5d0ff
java-json.jar
jaxrpc.jar
jersey-client-1.19.4.jar CDDL 1.1 + GPL2 w/ CPE - http://glassfish.java.net/public/CDDL+GPL_1_1.html
jswingreader-0.3.jar Apache license - built from http://jswingreader.sourceforge.net/ svn/trunk v12
libquaqua64-8.0.jnilib.jar quaqua: v.8.0 (latest stable) by Randel S Hofer. LGPL and BSD Modified license: downloaded from http://www.randelshofer.ch/quaqua/
libquaqua-8.0.jnilib.jar quaqua: v.8.0 (latest stable) by Randel S Hofer. LGPL and BSD Modified license: downloaded from http://www.randelshofer.ch/quaqua/
- log4j-1.2.8.jar
+ log4j-1.2-api-2.16.0.jar Apache license version 2.0
+ log4j-api-2.16.0.jar Apache license version 2.0
+ log4j-core-2.16.0.jar Apache license version 2.0
+ log4j-slf4j18-impl-2.16.0.jar Apache license version 2.0
mail.jar
miglayout-4.0-swing.jar BSD - http://www.migcalendar.com/miglayout/versions/4.0/license.txt
quaqua-filechooser-only-8.0.jar quaqua: v.8.0 (latest stable) by Randel S Hofer. LGPL and BSD Modified license: downloaded from http://www.randelshofer.ch/quaqua/
regex.jar
saaj.jar
servlet-api-3.1.jar
- slf4j-api-1.7.7.jar
- slf4j-log4j12-1.7.7.jar
+ slf4j-api-1.7.32.jar MIT license - https://opensource.org/licenses/mit-license.php
+ slf4j-log4j12-1.7.32.jar MIT license - https://opensource.org/licenses/mit-license.php
vamsas-client.jar
VAqua5-patch.jar This is a patched version of VAqua v5 (latest stable) by Alan Snyder et al. GPLv3 with Classpath exception, also includes contributions from Quaqua: http://violetlib.org/vaqua/overview.html - see doc/patching-vaqua.txt for patch details, and http://issues.jalview.org/browse/JAL-2988 for details of the bug that the patch addresses.
VARNAv3-93.jar GPL licenced software by K�vin Darty, Alain Denise and Yann Ponty - http://varna.lri.fr
jaxb-api-2.3.1.jar CDDL 1.1 + GPL2 w/ CPE - https://oss.oracle.com/licenses/CDDL+GPL-1.1
jaxb-runtime-2.3.2.jar Eclipse Distribution License - v 1.0 - http://www.eclipse.org/org/documents/edl-v10.php
jaxws-api-2.3.1.jar CDDL + GPLv2 with classpath exception - https://github.com/javaee/jax-ws-spec/blob/master/LICENSE.md
jsr311-api-1.1.1.jar CDDL License - http://www.opensource.org/licenses/cddl1.php
mimepull-1.9.11.jar Eclipse Distribution License - v 1.0 - http://www.eclipse.org/org/documents/edl-v10.php
policy-2.7.6.jar Eclipse Distribution License - v 1.0 - http://www.eclipse.org/org/documents/edl-v10.php
- slf4j-api-1.7.26.jar MIT License - https://opensource.org/licenses/mit-license.php
- slf4j-log4j12-1.7.26.jar MIT License - https://opensource.org/licenses/mit-license.php
stax-ex-1.8.1.jar Eclipse Distribution License - v 1.0 - http://www.eclipse.org/org/documents/edl-v10.php
stax2-api-4.2.jar The BSD License - http://www.opensource.org/licenses/bsd-license.php
streambuffer-1.5.7.jar Eclipse Distribution License - v 1.0 - http://www.eclipse.org/org/documents/edl-v10.php
import groovy.transform.ExternalizeMethods
import groovy.util.XmlParser
import groovy.xml.XmlUtil
-
+ import groovy.json.JsonBuilder
import com.vladsch.flexmark.util.ast.Node
import com.vladsch.flexmark.html.HtmlRenderer
import com.vladsch.flexmark.parser.Parser
import com.vladsch.flexmark.ext.autolink.AutolinkExtension
import com.vladsch.flexmark.ext.anchorlink.AnchorLinkExtension
import com.vladsch.flexmark.ext.toc.TocExtension
+ import com.google.common.hash.HashCode
+ import com.google.common.hash.Hashing
+ import com.google.common.io.Files
+ import org.jsoup.Jsoup
+ import org.jsoup.nodes.Element
buildscript {
repositories {
}
dependencies {
classpath "com.vladsch.flexmark:flexmark-all:0.62.0"
+ classpath "org.jsoup:jsoup:1.14.3"
}
}
id 'eclipse'
id "com.diffplug.gradle.spotless" version "3.28.0"
id 'com.github.johnrengelman.shadow' version '4.0.3'
- id 'com.install4j.gradle' version '8.0.10'
- id 'com.dorongold.task-tree' version '1.5' // only needed to display task dependency tree with gradle task1 [task2 ...] taskTree
- id 'com.palantir.git-version' version '0.12.3'
+ id 'com.install4j.gradle' version '9.0.6'
+ id 'com.dorongold.task-tree' version '2.1.0' // only needed to display task dependency tree with gradle task1 [task2 ...] taskTree
+ id 'com.palantir.git-version' version '0.13.0' apply false
}
repositories {
}
+
// in ext the values are cast to Object. Ensure string values are cast as String (and not GStringImpl) for later use
def string(Object o) {
return o == null ? "" : o.toString()
}
-
def overrideProperties(String propsFileName, boolean output = false) {
if (propsFileName == null) {
return
ext {
jalviewDirAbsolutePath = file(jalviewDir).getAbsolutePath()
jalviewDirRelativePath = jalviewDir
+ date = new Date()
getdownChannelName = CHANNEL.toLowerCase()
// default to "default". Currently only has different cosmetics for "develop", "release", "default"
// Import channel_properties
channelDir = string("${jalviewDir}/${channel_properties_dir}/${propertiesChannelName}")
channelGradleProperties = string("${channelDir}/channel_gradle.properties")
+ channelPropsFile = string("${channelDir}/${resource_dir}/${channel_props}")
overrideProperties(channelGradleProperties, false)
// local build environment properties
// can be "projectDir/local.properties"
// Import releaseProps from the RELEASE file
// or a file specified via JALVIEW_RELEASE_FILE if defined
// Expect jalview.version and target release branch in jalview.release
- def releaseProps = new Properties();
+ releaseProps = new Properties();
def releasePropFile = findProperty("JALVIEW_RELEASE_FILE");
def defaultReleasePropFile = "${jalviewDirAbsolutePath}/RELEASE";
try {
if (findProperty("JALVIEW_VERSION")==null || "".equals(JALVIEW_VERSION)) {
JALVIEW_VERSION = releaseProps.get("jalview.version")
}
+ println("JALVIEW_VERSION is set to '${JALVIEW_VERSION}'")
// this property set when running Eclipse headlessly
j2sHeadlessBuildProperty = string("net.sf.j2s.core.headlessbuild")
// datestamp
buildDate = new Date().format("yyyyMMdd")
+
// essentials
bareSourceDir = string(source_dir)
sourceDir = string("${jalviewDir}/${bareSourceDir}")
//cloverTestClassesDir = cloverClassesDir
cloverDb = string("${cloverBuildDir}/clover.db")
testSourceDir = useClover ? cloverTestInstrDir : testDir
testClassesDir = useClover ? cloverTestClassesDir : "${jalviewDir}/${test_output_dir}"
- getdownWebsiteDir = string("${jalviewDir}/${getdown_website_dir}/${JAVA_VERSION}")
+ getdownChannelDir = string("${getdown_website_dir}/${propertiesChannelName}")
+ getdownAppBaseDir = string("${jalviewDir}/${getdownChannelDir}/${JAVA_VERSION}")
+ getdownArchiveDir = string("${jalviewDir}/${getdown_archive_dir}")
+ getdownFullArchiveDir = null
+ getdownTextLines = []
+ getdownLaunchJvl = null
+ getdownVersionLaunchJvl = null
buildDist = true
buildProperties = null
// the following values might be overridden by the CHANNEL switch
getdownDir = string("${getdownChannelName}/${JAVA_VERSION}")
getdownAppBase = string("${getdown_channel_base}/${getdownDir}")
+ getdownArchiveAppBase = getdown_archive_base
getdownLauncher = string("${jalviewDir}/${getdown_lib_dir}/${getdown_launcher}")
getdownAppDistDir = getdown_app_dir_alt
getdownImagesDir = string("${jalviewDir}/${getdown_images_dir}")
install4jWindowsIconsFile = string("${install4j_images_dir}/${install4j_windows_icons_file}")
install4jPngIconFile = string("${install4j_images_dir}/${install4j_png_icon_file}")
install4jBackground = string("${install4j_images_dir}/${install4j_background}")
+ install4jBuildDir = "${install4j_build_dir}/${JAVA_VERSION}"
+ install4jCheckSums = true
+
+ applicationName = "${jalview_name}"
switch (CHANNEL) {
case "BUILD":
case [ "RELEASE", "JALVIEWJS-RELEASE" ]:
getdownAppDistDir = getdown_app_dir_release
+ getdownSetAppBaseProperty = true
reportRsyncCommand = true
install4jSuffix = ""
install4jInstallerName = "${jalview_name} Installer"
case "ARCHIVELOCAL":
getdownChannelName = string("archive/${JALVIEW_VERSION}")
getdownDir = string("${getdownChannelName}/${JAVA_VERSION}")
- getdownAppBase = file(getdownWebsiteDir).toURI().toString()
+ getdownAppBase = file(getdownAppBaseDir).toURI().toString()
if (!file("${ARCHIVEDIR}/${package_dir}").exists()) {
throw new GradleException("Must provide an ARCHIVEDIR value to produce an archive distribution")
} else {
case "TEST-RELEASE":
reportRsyncCommand = true
+ getdownSetAppBaseProperty = true
// Don't ignore transpile errors for release build
if (jalviewjs_ignore_transpile_errors.equals("true")) {
jalviewjs_ignore_transpile_errors = "false"
case [ "LOCAL", "JALVIEWJS" ]:
JALVIEW_VERSION = "TEST"
- getdownAppBase = file(getdownWebsiteDir).toURI().toString()
+ getdownAppBase = file(getdownAppBaseDir).toURI().toString()
+ getdownArchiveAppBase = file("${jalviewDir}/${getdown_archive_dir}").toURI().toString()
getdownLauncher = string("${jalviewDir}/${getdown_lib_dir}/${getdown_launcher_local}")
install4jExtraScheme = "jalviewl"
+ install4jCheckSums = false
break
default: // something wrong specified
break
}
+ JALVIEW_VERSION_UNDERSCORES = JALVIEW_VERSION.replaceAll("\\.", "_")
+ hugoDataJsonFile = file("${jalviewDir}/${hugo_build_dir}/${hugo_data_installers_dir}/installers-${JALVIEW_VERSION_UNDERSCORES}.json")
+ hugoArchiveMdFile = file("${jalviewDir}/${hugo_build_dir}/${hugo_version_archive_dir}/Version-${JALVIEW_VERSION_UNDERSCORES}/_index.md")
// override getdownAppBase if requested
if (findProperty("getdown_appbase_override") != null) {
// revert to LOCAL if empty string
if (string(getdown_appbase_override) == "") {
- getdownAppBase = file(getdownWebsiteDir).toURI().toString()
+ getdownAppBase = file(getdownAppBaseDir).toURI().toString()
getdownLauncher = string("${jalviewDir}/${getdown_lib_dir}/${getdown_launcher_local}")
} else if (string(getdown_appbase_override).startsWith("file://")) {
getdownAppBase = string(getdown_appbase_override)
jvlChannelName = jvlChannelName.replaceAll("[^\\w\\-]+", "_")
// install4j application and folder names
if (install4jSuffix == "") {
install4jBundleId = "${install4j_bundle_id}"
install4jWinApplicationId = install4j_release_win_application_id
} else {
- install4jApplicationName = "${jalview_name} ${install4jSuffix}"
+ applicationName = "${jalview_name} ${install4jSuffix}"
install4jBundleId = "${install4j_bundle_id}-" + install4jSuffix.toLowerCase()
// add int hash of install4jSuffix to the last part of the application_id
def id = install4j_release_win_application_id
}
// sanitise folder and id names
// install4jApplicationFolder = e.g. "Jalview Build"
- install4jApplicationFolder = install4jApplicationName
+ install4jApplicationFolder = applicationName
.replaceAll("[\"'~:/\\\\\\s]", "_") // replace all awkward filename chars " ' ~ : / \
.replaceAll("_+", "_") // collapse __
- install4jInternalId = install4jApplicationName
+ install4jInternalId = applicationName
.replaceAll(" ","_")
.replaceAll("[^\\w\\-\\.]", "_") // replace other non [alphanumeric,_,-,.]
.replaceAll("_+", "") // collapse __
//.replaceAll("_*-_*", "-") // collapse _-_
- install4jUnixApplicationFolder = install4jApplicationName
+ install4jUnixApplicationFolder = applicationName
.replaceAll(" ","_")
.replaceAll("[^\\w\\-\\.]", "_") // replace other non [alphanumeric,_,-,.]
.replaceAll("_+", "_") // collapse __
.toLowerCase()
getdownWrapperLink = install4jUnixApplicationFolder // e.g. "jalview_local"
- getdownAppDir = string("${getdownWebsiteDir}/${getdownAppDistDir}")
- //getdownJ11libDir = "${getdownWebsiteDir}/${getdown_j11lib_dir}"
- getdownResourceDir = string("${getdownWebsiteDir}/${getdown_resource_dir}")
- getdownInstallDir = string("${getdownWebsiteDir}/${getdown_install_dir}")
+ getdownAppDir = string("${getdownAppBaseDir}/${getdownAppDistDir}")
+ //getdownJ11libDir = "${getdownAppBaseDir}/${getdown_j11lib_dir}"
+ getdownResourceDir = string("${getdownAppBaseDir}/${getdown_resource_dir}")
+ getdownInstallDir = string("${getdownAppBaseDir}/${getdown_install_dir}")
getdownFilesDir = string("${jalviewDir}/${getdown_files_dir}/${JAVA_VERSION}/")
getdownFilesInstallDir = string("${getdownFilesDir}/${getdown_install_dir}")
/* compile without modules -- using classpath libraries
modules_compileClasspath = fileTree(dir: "${jalviewDir}/${j11modDir}", include: ["*.jar"])
modules_runtimeClasspath = modules_compileClasspath
*/
- def details = versionDetails()
- gitHash = details.gitHash
- gitBranch = details.branchName
-
+ gitHash = "SOURCE"
+ gitBranch = "Source"
+ try {
+ apply plugin: "com.palantir.git-version"
+ def details = versionDetails()
+ gitHash = details.gitHash
+ gitBranch = details.branchName
+ } catch(org.gradle.api.internal.plugins.PluginApplicationException e) {
+ println("Not in a git repository. Using git values from RELEASE properties file.")
+ gitHash = releaseProps.getProperty("git.hash")
+ gitBranch = releaseProps.getProperty("git.branch")
+ } catch(java.lang.RuntimeException e1) {
+ throw new GradleException("Error with git-version plugin. Directory '.git' exists but versionDetails() cannot be found.")
+ }
println("Using a ${CHANNEL} profile.")
jreInstallsDir = System.getProperty("user.home") + jreInstallsDir.substring(1)
}
macosJavaVMDir = string("${jreInstallsDir}/jre-${JAVA_INTEGER_VERSION}-mac-x64/jre")
- macosJavaVMTgz = string("${jreInstallsDir}/tgz/jre-${JAVA_INTEGER_VERSION}-mac-x64.tar.gz")
windowsJavaVMDir = string("${jreInstallsDir}/jre-${JAVA_INTEGER_VERSION}-windows-x64/jre")
- windowsJavaVMTgz = string("${jreInstallsDir}/tgz/jre-${JAVA_INTEGER_VERSION}-windows-x64.tar.gz")
linuxJavaVMDir = string("${jreInstallsDir}/jre-${JAVA_INTEGER_VERSION}-linux-x64/jre")
- linuxJavaVMTgz = string("${jreInstallsDir}/tgz/jre-${JAVA_INTEGER_VERSION}-linux-x64.tar.gz")
+ macosJavaVMTgz = string("${jreInstallsDir}/tgz/jre_${JAVA_INTEGER_VERSION}_mac_x64.tar.gz")
+ windowsJavaVMTgz = string("${jreInstallsDir}/tgz/jre_${JAVA_INTEGER_VERSION}_windows_x64.tar.gz")
+ linuxJavaVMTgz = string("${jreInstallsDir}/tgz/jre_${JAVA_INTEGER_VERSION}_linux_x64.tar.gz")
install4jDir = string("${jalviewDir}/${install4j_utils_dir}")
install4jConfFileName = string("jalview-install4j-conf.install4j")
install4jConfFile = file("${install4jDir}/${install4jConfFileName}")
helpBuildDir = string("${resourceBuildDir}/help_build")
docBuildDir = string("${resourceBuildDir}/doc_build")
-
if (buildProperties == null) {
buildProperties = string("${resourcesBuildDir}/${build_properties_file}")
}
srcDirs = [ resourcesBuildDir, docBuildDir, helpBuildDir ]
}
-
compileClasspath = files(sourceSets.main.java.outputDir)
compileClasspath += fileTree(dir: "${jalviewDir}/${libDir}", include: ["*.jar"])
// format is a string like date.format("dd MMMM yyyy")
def getDate(format) {
- def date = new Date()
return date.format(format)
}
def htmlFilePath = mdFile.getPath().replaceAll(/\..*?$/, ".html")
htmlFiles.add(file(htmlFilePath))
}
-
outputs.files(htmlFiles)
}
+ def hugoTemplateSubstitutions(String input, Map extras=null) {
+ def replacements = [
+ DATE: getDate("yyyy-MM-dd"),
+ CHANNEL: propertiesChannelName,
+ APPLICATION_NAME: applicationName,
+ GIT_HASH: gitHash,
+ GIT_BRANCH: gitBranch,
+ VERSION: JALVIEW_VERSION,
+ JAVA_VERSION: JAVA_VERSION,
+ VERSION_UNDERSCORES: JALVIEW_VERSION_UNDERSCORES,
+ DRAFT: "false",
+ JVL_HEADER: ""
+ ]
+ def output = input
+ if (extras != null) {
+ extras.each{ k, v ->
+ output = output.replaceAll("__${k}__", ((v == null)?"":v))
+ }
+ }
+ replacements.each{ k, v ->
+ output = output.replaceAll("__${k}__", ((v == null)?"":v))
+ }
+ return output
+ }
+
+ def mdFileComponents(File mdFile, def dateOnly=false) {
+ def map = [:]
+ def content = ""
+ if (mdFile.exists()) {
+ def inFrontMatter = false
+ def firstLine = true
+ mdFile.eachLine { line ->
+ if (line.matches("---")) {
+ def prev = inFrontMatter
+ inFrontMatter = firstLine
+ if (inFrontMatter != prev)
+ return false
+ }
+ if (inFrontMatter) {
+ def m = null
+ if (m = line =~ /^date:\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/) {
+ map["date"] = new Date().parse("yyyy-MM-dd HH:mm:ss", m[0][1])
+ } else if (m = line =~ /^date:\s*(\d{4}-\d{2}-\d{2})/) {
+ map["date"] = new Date().parse("yyyy-MM-dd", m[0][1])
+ } else if (m = line =~ /^channel:\s*(\S+)/) {
+ map["channel"] = m[0][1]
+ } else if (m = line =~ /^version:\s*(\S+)/) {
+ map["version"] = m[0][1]
+ } else if (m = line =~ /^\s*([^:]+)\s*:\s*(\S.*)/) {
+ map[ m[0][1] ] = m[0][2]
+ }
+ if (dateOnly && map["date"] != null) {
+ return false
+ }
+ } else {
+ if (dateOnly)
+ return false
+ content += line+"\n"
+ }
+ firstLine = false
+ }
+ }
+ return dateOnly ? map["date"] : [map, content]
+ }
+
+ task hugoTemplates {
+ group "website"
+ description "Create partially populated md pages for hugo website build"
+
+ def hugoTemplatesDir = file("${jalviewDir}/${hugo_templates_dir}")
+ def hugoBuildDir = "${jalviewDir}/${hugo_build_dir}"
+ def templateFiles = fileTree(dir: hugoTemplatesDir)
+ def releaseMdFile = file("${jalviewDir}/${releases_dir}/release-${JALVIEW_VERSION_UNDERSCORES}.md")
+ def whatsnewMdFile = file("${jalviewDir}/${whatsnew_dir}/whatsnew-${JALVIEW_VERSION_UNDERSCORES}.md")
+ def oldJvlFile = file("${jalviewDir}/${hugo_old_jvl}")
+ def jalviewjsFile = file("${jalviewDir}/${hugo_jalviewjs}")
+
+ doFirst {
+ // specific release template for version archive
+ def changes = ""
+ def whatsnew = null
+ def givenDate = null
+ def givenChannel = null
+ def givenVersion = null
+ if (CHANNEL == "RELEASE") {
+ def (map, content) = mdFileComponents(releaseMdFile)
+ givenDate = map.date
+ givenChannel = map.channel
+ givenVersion = map.version
+ changes = content
+ if (givenVersion != null && givenVersion != JALVIEW_VERSION) {
+ throw new GradleException("'version' header (${givenVersion}) found in ${releaseMdFile} does not match JALVIEW_VERSION (${JALVIEW_VERSION})")
+ }
+
+ if (whatsnewMdFile.exists())
+ whatsnew = whatsnewMdFile.text
+ }
+
+ def oldJvl = oldJvlFile.exists() ? oldJvlFile.collect{it} : []
+ def jalviewjsLink = jalviewjsFile.exists() ? jalviewjsFile.collect{it} : []
+
+ def changesHugo = null
+ if (changes != null) {
+ changesHugo = '<div class="release_notes">\n\n'
+ def inSection = false
+ changes.eachLine { line ->
+ def m = null
+ if (m = line =~ /^##([^#].*)$/) {
+ if (inSection) {
+ changesHugo += "</div>\n\n"
+ }
+ def section = m[0][1].trim()
+ section = section.toLowerCase()
+ section = section.replaceAll(/ +/, "_")
+ section = section.replaceAll(/[^a-z0-9_\-]/, "")
+ changesHugo += "<div class=\"${section}\">\n\n"
+ inSection = true
+ } else if (m = line =~ /^(\s*-\s*)<!--([^>]+)-->(.*?)(<br\/?>)?\s*$/) {
+ def comment = m[0][2].trim()
+ if (comment != "") {
+ comment = comment.replaceAll('"', """)
+ def issuekeys = []
+ comment.eachMatch(/JAL-\d+/) { jal -> issuekeys += jal }
+ def newline = m[0][1]
+ if (comment.trim() != "")
+ newline += "{{<comment>}}${comment}{{</comment>}} "
+ newline += m[0][3].trim()
+ if (issuekeys.size() > 0)
+ newline += " {{< jal issue=\"${issuekeys.join(",")}\" alt=\"${comment}\" >}}"
+ if (m[0][4] != null)
+ newline += m[0][4]
+ line = newline
+ }
+ }
+ changesHugo += line+"\n"
+ }
+ if (inSection) {
+ changesHugo += "\n</div>\n\n"
+ }
+ changesHugo += '</div>'
+ }
+
+ templateFiles.each{ templateFile ->
+ def newFileName = string(hugoTemplateSubstitutions(templateFile.getName()))
+ def relPath = hugoTemplatesDir.toPath().relativize(templateFile.toPath()).getParent()
+ def newRelPathName = hugoTemplateSubstitutions( relPath.toString() )
+
+ def outPathName = string("${hugoBuildDir}/$newRelPathName")
+
+ copy {
+ from templateFile
+ rename(templateFile.getName(), newFileName)
+ into outPathName
+ }
+
+ def newFile = file("${outPathName}/${newFileName}".toString())
+ def content = newFile.text
+ newFile.text = hugoTemplateSubstitutions(content,
+ [
+ WHATSNEW: whatsnew,
+ CHANGES: changesHugo,
+ DATE: givenDate == null ? "" : givenDate.format("yyyy-MM-dd"),
+ DRAFT: givenDate == null ? "true" : "false",
+ JALVIEWJSLINK: jalviewjsLink.contains(JALVIEW_VERSION) ? "true" : "false",
+ JVL_HEADER: oldJvl.contains(JALVIEW_VERSION) ? "jvl: true" : ""
+ ]
+ )
+ }
+
+ }
+
+ inputs.file(oldJvlFile)
+ inputs.dir(hugoTemplatesDir)
+ inputs.property("JALVIEW_VERSION", { JALVIEW_VERSION })
+ inputs.property("CHANNEL", { CHANNEL })
+ }
+
+ def getMdDate(File mdFile) {
+ return mdFileComponents(mdFile, true)
+ }
+
+ def getMdSections(String content) {
+ def sections = [:]
+ def sectionContent = ""
+ def sectionName = null
+ content.eachLine { line ->
+ def m = null
+ if (m = line =~ /^##([^#].*)$/) {
+ if (sectionName != null) {
+ sections[sectionName] = sectionContent
+ sectionName = null
+ sectionContent = ""
+ }
+ sectionName = m[0][1].trim()
+ sectionName = sectionName.toLowerCase()
+ sectionName = sectionName.replaceAll(/ +/, "_")
+ sectionName = sectionName.replaceAll(/[^a-z0-9_\-]/, "")
+ } else if (sectionName != null) {
+ sectionContent += line+"\n"
+ }
+ }
+ if (sectionContent != null) {
+ sections[sectionName] = sectionContent
+ }
+ return sections
+ }
-
-
task copyHelp(type: Copy) {
def inputDir = helpSourceDir
def outputDir = "${helpBuildDir}/${help_dir}"
}
+ task releasesTemplates {
+ group "help"
+ description "Recreate whatsNew.html and releases.html from markdown files and templates in help"
+
+ dependsOn copyHelp
+
+ def releasesTemplateFile = file("${jalviewDir}/${releases_template}")
+ def whatsnewTemplateFile = file("${jalviewDir}/${whatsnew_template}")
+ def releasesHtmlFile = file("${helpBuildDir}/${help_dir}/${releases_html}")
+ def whatsnewHtmlFile = file("${helpBuildDir}/${help_dir}/${whatsnew_html}")
+ def releasesMdDir = "${jalviewDir}/${releases_dir}"
+ def whatsnewMdDir = "${jalviewDir}/${whatsnew_dir}"
+
+ doFirst {
+ def releaseMdFile = file("${releasesMdDir}/release-${JALVIEW_VERSION_UNDERSCORES}.md")
+ def whatsnewMdFile = file("${whatsnewMdDir}/whatsnew-${JALVIEW_VERSION_UNDERSCORES}.md")
+
+ if (CHANNEL == "RELEASE") {
+ if (!releaseMdFile.exists()) {
+ throw new GradleException("File ${releaseMdFile} must be created for RELEASE")
+ }
+ if (!whatsnewMdFile.exists()) {
+ throw new GradleException("File ${whatsnewMdFile} must be created for RELEASE")
+ }
+ }
+
+ def releaseFiles = fileTree(dir: releasesMdDir, include: "release-*.md")
+ def releaseFilesDates = releaseFiles.collectEntries {
+ [(it): getMdDate(it)]
+ }
+ releaseFiles = releaseFiles.sort { a,b -> releaseFilesDates[a].compareTo(releaseFilesDates[b]) }
+
+ def releasesTemplate = releasesTemplateFile.text
+ def m = releasesTemplate =~ /(?s)__VERSION_LOOP_START__(.*)__VERSION_LOOP_END__/
+ def versionTemplate = m[0][1]
+
+ MutableDataSet options = new MutableDataSet()
+
+ def extensions = new ArrayList<>()
+ options.set(Parser.EXTENSIONS, extensions)
+ options.set(Parser.HTML_BLOCK_COMMENT_ONLY_FULL_LINE, true)
+
+ Parser parser = Parser.builder(options).build()
+ HtmlRenderer renderer = HtmlRenderer.builder(options).build()
+
+ def actualVersions = releaseFiles.collect { rf ->
+ def (rfMap, rfContent) = mdFileComponents(rf)
+ return rfMap.version
+ }
+ def versionsHtml = ""
+ def linkedVersions = []
+ releaseFiles.reverse().each { rFile ->
+ def (rMap, rContent) = mdFileComponents(rFile)
+
+ def versionLink = ""
+ def partialVersion = ""
+ def firstPart = true
+ rMap.version.split("\\.").each { part ->
+ def displayPart = ( firstPart ? "" : "." ) + part
+ partialVersion += displayPart
+ if (
+ linkedVersions.contains(partialVersion)
+ || ( actualVersions.contains(partialVersion) && partialVersion != rMap.version )
+ ) {
+ versionLink += displayPart
+ } else {
+ versionLink += "<a id=\"Jalview.${partialVersion}\">${displayPart}</a>"
+ linkedVersions += partialVersion
+ }
+ firstPart = false
+ }
+ def displayDate = releaseFilesDates[rFile].format("dd/MM/yyyy")
+
+ def lm = null
+ def rContentProcessed = ""
+ rContent.eachLine { line ->
+ if (lm = line =~ /^(\s*-)(\s*<!--[^>]*?-->)(.*)$/) {
+ line = "${lm[0][1]}${lm[0][3]}${lm[0][2]}"
+ } else if (lm = line =~ /^###([^#]+.*)$/) {
+ line = "_${lm[0][1].trim()}_"
+ }
+ rContentProcessed += line + "\n"
+ }
+
+ def rContentSections = getMdSections(rContentProcessed)
+ def rVersion = versionTemplate
+ if (rVersion != "") {
+ def rNewFeatures = rContentSections["new_features"]
+ def rIssuesResolved = rContentSections["issues_resolved"]
+ Node newFeaturesNode = parser.parse(rNewFeatures)
+ String newFeaturesHtml = renderer.render(newFeaturesNode)
+ Node issuesResolvedNode = parser.parse(rIssuesResolved)
+ String issuesResolvedHtml = renderer.render(issuesResolvedNode)
+ rVersion = hugoTemplateSubstitutions(rVersion,
+ [
+ VERSION: rMap.version,
+ VERSION_LINK: versionLink,
+ DISPLAY_DATE: displayDate,
+ NEW_FEATURES: newFeaturesHtml,
+ ISSUES_RESOLVED: issuesResolvedHtml
+ ]
+ )
+ versionsHtml += rVersion
+ }
+ }
+
+ releasesTemplate = releasesTemplate.replaceAll("(?s)__VERSION_LOOP_START__.*__VERSION_LOOP_END__", versionsHtml)
+ releasesTemplate = hugoTemplateSubstitutions(releasesTemplate)
+ releasesHtmlFile.text = releasesTemplate
+
+ if (whatsnewMdFile.exists()) {
+ def wnDisplayDate = releaseFilesDates[releaseMdFile] != null ? releaseFilesDates[releaseMdFile].format("dd MMMM yyyy") : ""
+ def whatsnewMd = hugoTemplateSubstitutions(whatsnewMdFile.text)
+ Node whatsnewNode = parser.parse(whatsnewMd)
+ String whatsnewHtml = renderer.render(whatsnewNode)
+ whatsnewHtml = whatsnewTemplateFile.text.replaceAll("__WHATS_NEW__", whatsnewHtml)
+ whatsnewHtmlFile.text = hugoTemplateSubstitutions(whatsnewHtml,
+ [
+ VERSION: JALVIEW_VERSION,
+ DISPLAY_DATE: wnDisplayDate
+ ]
+ )
+ } else if (gradle.taskGraph.hasTask(":linkCheck")) {
+ whatsnewHtmlFile.text = "Development build " + getDate("yyyy-MM-dd HH:mm:ss")
+ }
+
+ }
+
+ inputs.file(releasesTemplateFile)
+ inputs.file(whatsnewTemplateFile)
+ inputs.dir(releasesMdDir)
+ inputs.dir(whatsnewMdDir)
+ outputs.file(releasesHtmlFile)
+ outputs.file(whatsnewHtmlFile)
+ }
-
-
task copyResources(type: Copy) {
group = "build"
description = "Copy (and make text substitutions in) the resources dir to the build area"
property "BUILD_DATE", getDate("HH:mm:ss dd MMMM yyyy")
property "VERSION", JALVIEW_VERSION
property "INSTALLATION", INSTALLATION+" git-commit:"+gitHash+" ["+gitBranch+"]"
+ property "JAVA_COMPILE_VERSION", JAVA_INTEGER_VERSION
if (getdownSetAppBaseProperty) {
property "GETDOWNAPPBASE", getdownAppBase
property "GETDOWNAPPDISTDIR", getdownAppDistDir
outputs.file(outputFile)
}
+
task buildIndices(type: JavaExec) {
dependsOn copyHelp
classpath = sourceSets.main.compileClasspath
dependsOn createBuildProperties
}
-
task prepare {
dependsOn buildResources
dependsOn copyDocs
dependsOn copyHelp
+ dependsOn releasesTemplates
dependsOn convertMdFiles
dependsOn buildIndices
}
compileJava.dependsOn prepare
run.dependsOn compileJava
//run.dependsOn prepare
+
+
//testReportDirName = "test-reports" // note that test workingDir will be $jalviewDir
test {
dependsOn prepare
}
-
-
task compileLinkCheck(type: JavaCompile) {
options.fork = true
classpath = files("${jalviewDir}/${utils_dir}")
def helpLinksCheckerOutFile = file("${jalviewDir}/${utils_dir}/HelpLinksChecker.out")
classpath = files("${jalviewDir}/${utils_dir}")
main = "HelpLinksChecker"
- workingDir = jalviewDir
+ workingDir = "${helpBuildDir}"
args = [ "${helpBuildDir}/${help_dir}", "-nointernet" ]
def outFOS = new FileOutputStream(helpLinksCheckerOutFile, false) // false == don't append
outputs.file(helpLinksCheckerOutFile)
}
+
// import the pubhtmlhelp target
ant.properties.basedir = "${jalviewDir}"
ant.properties.helpBuildDir = "${helpBuildDir}/${help_dir}"
manifest {
attributes "Main-Class": main_class,
"Permissions": "all-permissions",
- "Application-Name": install4jApplicationName,
+ "Application-Name": applicationName,
"Codebase": application_codebase,
"Implementation-Version": JALVIEW_VERSION
}
archiveFileName = rootProject.name+".jar"
duplicatesStrategy "EXCLUDE"
+
exclude "cache*/**"
exclude "*.jar"
exclude "*.jar.*"
dependsOn clean
}
+
shadowJar {
group = "distribution"
description = "Create a single jar file with all dependency libraries merged. Can be run with java -jar"
}
manifest {
attributes "Implementation-Version": JALVIEW_VERSION,
- "Application-Name": install4jApplicationName
+ "Application-Name": applicationName
}
+
duplicatesStrategy "INCLUDE"
+
mainClassName = shadow_jar_main_class
mergeServiceFiles()
classifier = "all-"+JALVIEW_VERSION+"-j"+JAVA_VERSION
}
def getdownWebsiteResourceFilenames = []
- def getdownTextString = ""
def getdownResourceDir = getdownResourceDir
def getdownResourceFilenames = []
doFirst {
// clean the getdown website and files dir before creating getdown folders
- delete getdownWebsiteDir
+ delete getdownAppBaseDir
delete getdownFilesDir
copy {
}
getdownWebsiteResourceFilenames += "${getdownAppDistDir}/${getdown_build_properties}"
- // set some getdown_txt_ properties then go through all properties looking for getdown_txt_...
+ copy {
+ from channelPropsFile
+ into getdownAppBaseDir
+ }
+ getdownWebsiteResourceFilenames += file(channelPropsFile).getName()
+
+ // set some getdownTxt_ properties then go through all properties looking for getdownTxt_...
def props = project.properties.sort { it.key }
if (getdownAltJavaMinVersion != null && getdownAltJavaMinVersion.length() > 0) {
props.put("getdown_txt_java_min_version", getdownAltJavaMinVersion)
}
props.put("getdown_txt_title", jalview_name)
- props.put("getdown_txt_ui.name", install4jApplicationName)
+ props.put("getdown_txt_ui.name", applicationName)
// start with appbase
- getdownTextString += "appbase = ${getdownAppBase}\n"
+ getdownTextLines += "appbase = ${getdownAppBase}"
props.each{ prop, val ->
if (prop.startsWith("getdown_txt_") && val != null) {
if (prop.startsWith("getdown_txt_multi_")) {
def key = prop.substring(18)
val.split(",").each{ v ->
- def line = "${key} = ${v}\n"
- getdownTextString += line
+ def line = "${key} = ${v}"
+ getdownTextLines += line
}
} else {
// file values rationalised
}
}
if (! prop.startsWith("getdown_txt_resource")) {
- def line = prop.substring(12) + " = ${val}\n"
- getdownTextString += line
+ def line = prop.substring(12) + " = ${val}"
+ getdownTextLines += line
}
}
}
}
getdownWebsiteResourceFilenames.each{ filename ->
- getdownTextString += "resource = ${filename}\n"
+ getdownTextLines += "resource = ${filename}"
}
getdownResourceFilenames.each{ filename ->
copy {
if (s.exists()) {
copy {
from s
- into "${getdownWebsiteDir}/${getdown_wrapper_script_dir}"
+ into "${getdownAppBaseDir}/${getdown_wrapper_script_dir}"
}
- getdownTextString += "resource = ${getdown_wrapper_script_dir}/${script}\n"
+ getdownTextLines += "resource = ${getdown_wrapper_script_dir}/${script}"
}
}
codeFiles += f
}
}
- codeFiles.sort().each{f ->
+ def jalviewJar = jar.archiveFileName.getOrNull()
+ // put jalview.jar first for CLASSPATH and .properties files reasons
+ codeFiles.sort{a, b -> ( a.getName() == jalviewJar ? -1 : ( b.getName() == jalviewJar ? 1 : a <=> b ) ) }.each{f ->
def name = f.getName()
- def line = "code = ${getdownAppDistDir}/${name}\n"
- getdownTextString += line
+ def line = "code = ${getdownAppDistDir}/${name}"
+ getdownTextLines += line
copy {
from f.getPath()
into getdownAppDir
def j11libFiles = fileTree(dir: "${jalviewDir}/${j11libDir}", include: ["*.jar"]).getFiles()
j11libFiles.sort().each{f ->
def name = f.getName()
- def line = "code = ${getdown_j11lib_dir}/${name}\n"
- getdownTextString += line
+ def line = "code = ${getdown_j11lib_dir}/${name}"
+ getdownTextLines += line
copy {
from f.getPath()
into getdownJ11libDir
*/
// getdown-launcher.jar should not be in main application class path so the main application can move it when updated. Listed as a resource so it gets updated.
- //getdownTextString += "class = " + file(getdownLauncher).getName() + "\n"
- getdownTextString += "resource = ${getdown_launcher_new}\n"
- getdownTextString += "class = ${main_class}\n"
+ //getdownTextLines += "class = " + file(getdownLauncher).getName()
+ getdownTextLines += "resource = ${getdown_launcher_new}"
+ getdownTextLines += "class = ${main_class}"
// Not setting these properties in general so that getdownappbase and getdowndistdir will default to release version in jalview.bin.Cache
if (getdownSetAppBaseProperty) {
- getdownTextString += "jvmarg = -Dgetdowndistdir=${getdownAppDistDir}\n"
- getdownTextString += "jvmarg = -Dgetdownappbase=${getdownAppBase}\n"
+ getdownTextLines += "jvmarg = -Dgetdowndistdir=${getdownAppDistDir}"
+ getdownTextLines += "jvmarg = -Dgetdownappbase=${getdownAppBase}"
}
- def getdown_txt = file("${getdownWebsiteDir}/getdown.txt")
- getdown_txt.write(getdownTextString)
+ def getdownTxt = file("${getdownAppBaseDir}/getdown.txt")
+ getdownTxt.write(getdownTextLines.join("\n"))
- def getdownLaunchJvl = getdown_launch_jvl_name + ( (jvlChannelName != null && jvlChannelName.length() > 0)?"-${jvlChannelName}":"" ) + ".jvl"
- def launchJvl = file("${getdownWebsiteDir}/${getdownLaunchJvl}")
+ getdownLaunchJvl = getdown_launch_jvl_name + ( (jvlChannelName != null && jvlChannelName.length() > 0)?"-${jvlChannelName}":"" ) + ".jvl"
+ def launchJvl = file("${getdownAppBaseDir}/${getdownLaunchJvl}")
launchJvl.write("appbase=${getdownAppBase}")
// files going into the getdown website dir: getdown-launcher.jar
copy {
from getdownLauncher
rename(file(getdownLauncher).getName(), getdown_launcher_new)
- into getdownWebsiteDir
+ into getdownAppBaseDir
}
// files going into the getdown website dir: getdown-launcher(-local).jar
if (file(getdownLauncher).getName() != getdown_launcher) {
rename(file(getdownLauncher).getName(), getdown_launcher)
}
- into getdownWebsiteDir
+ into getdownAppBaseDir
}
// files going into the getdown website dir: ./install dir and files
if (! (CHANNEL.startsWith("ARCHIVE") || CHANNEL.startsWith("DEVELOP"))) {
copy {
- from getdown_txt
+ from getdownTxt
from getdownLauncher
from "${getdownAppDir}/${getdown_build_properties}"
if (file(getdownLauncher).getName() != getdown_launcher) {
// files going into the getdown files dir: getdown.txt, getdown-launcher.jar, channel-launch.jvl, build_properties
copy {
- from getdown_txt
+ from getdownTxt
from launchJvl
from getdownLauncher
- from "${getdownWebsiteDir}/${getdown_build_properties}"
+ from "${getdownAppBaseDir}/${getdown_build_properties}"
+ from "${getdownAppBaseDir}/${channel_props}"
if (file(getdownLauncher).getName() != getdown_launcher) {
rename(file(getdownLauncher).getName(), getdown_launcher)
}
into getdownFilesDir
}
- // and ./resources (not all downloaded by getdown)
+ // and ./resource (not all downloaded by getdown)
copy {
from getdownResourceDir
into "${getdownFilesDir}/${getdown_resource_dir}"
if (buildDist) {
inputs.dir("${jalviewDir}/${package_dir}")
}
- outputs.dir(getdownWebsiteDir)
+ outputs.dir(getdownAppBaseDir)
outputs.dir(getdownFilesDir)
}
classpath = files(getdownLauncher)
}
main = "com.threerings.getdown.tools.Digester"
- args getdownWebsiteDir
- inputs.dir(getdownWebsiteDir)
- outputs.file("${getdownWebsiteDir}/digest2.txt")
+ args getdownAppBaseDir
+ inputs.dir(getdownAppBaseDir)
+ outputs.file("${getdownAppBaseDir}/digest2.txt")
}
dependsOn getdownDigest
doLast {
if (reportRsyncCommand) {
- def fromDir = getdownWebsiteDir + (getdownWebsiteDir.endsWith('/')?'':'/')
+ def fromDir = getdownAppBaseDir + (getdownAppBaseDir.endsWith('/')?'':'/')
def toDir = "${getdown_rsync_dest}/${getdownDir}" + (getdownDir.endsWith('/')?'':'/')
println "LIKELY RSYNC COMMAND:"
println "mkdir -p '$toDir'\nrsync -avh --delete '$fromDir' '$toDir'"
}
+ task getdownArchiveBuild() {
+ group = "distribution"
+ description = "Put files in the archive dir to go on the website"
+
+ dependsOn getdownWebsite
+
+ def v = "v${JALVIEW_VERSION_UNDERSCORES}"
+ def vDir = "${getdownArchiveDir}/${v}"
+ getdownFullArchiveDir = "${vDir}/getdown"
+ getdownVersionLaunchJvl = "${vDir}/jalview-${v}.jvl"
+
+ def vAltDir = "alt_${v}"
+ def archiveImagesDir = "${jalviewDir}/${channel_properties_dir}/old/images"
+
+ doFirst {
+ // cleanup old "old" dir
+ delete getdownArchiveDir
+
+ def getdownArchiveTxt = file("${getdownFullArchiveDir}/getdown.txt")
+ getdownArchiveTxt.getParentFile().mkdirs()
+ def getdownArchiveTextLines = []
+ def getdownFullArchiveAppBase = "${getdownArchiveAppBase}${getdownArchiveAppBase.endsWith("/")?"":"/"}${v}/getdown/"
+
+ // the libdir
+ copy {
+ from "${getdownAppBaseDir}/${getdownAppDistDir}"
+ into "${getdownFullArchiveDir}/${vAltDir}"
+ }
+
+ getdownTextLines.each { line ->
+ line = line.replaceAll("^(?<s>appbase\\s*=\\s*).*", '${s}'+getdownFullArchiveAppBase)
+ line = line.replaceAll("^(?<s>(resource|code)\\s*=\\s*)${getdownAppDistDir}/", '${s}'+vAltDir+"/")
+ line = line.replaceAll("^(?<s>ui.background_image\\s*=\\s*).*\\.png", '${s}'+"${getdown_resource_dir}/jalview_archive_getdown_background.png")
+ line = line.replaceAll("^(?<s>ui.instant_background_image\\s*=\\s*).*\\.png", '${s}'+"${getdown_resource_dir}/jalview_archive_getdown_background_initialising.png")
+ line = line.replaceAll("^(?<s>ui.error_background\\s*=\\s*).*\\.png", '${s}'+"${getdown_resource_dir}/jalview_archive_getdown_background_error.png")
+ line = line.replaceAll("^(?<s>ui.progress_image\\s*=\\s*).*\\.png", '${s}'+"${getdown_resource_dir}/jalview_archive_getdown_progress_bar.png")
+ // remove the existing resource = resource/ or bin/ lines
+ if (! line.matches("resource\\s*=\\s*(resource|bin)/.*")) {
+ getdownArchiveTextLines += line
+ }
+ }
+
+ // the resource dir -- add these files as resource lines in getdown.txt
+ copy {
+ from "${archiveImagesDir}"
+ into "${getdownFullArchiveDir}/${getdown_resource_dir}"
+ eachFile { file ->
+ getdownArchiveTextLines += "resource = ${getdown_resource_dir}/${file.getName()}"
+ }
+ }
+
+ getdownArchiveTxt.write(getdownArchiveTextLines.join("\n"))
+
+ def vLaunchJvl = file(getdownVersionLaunchJvl)
+ vLaunchJvl.getParentFile().mkdirs()
+ vLaunchJvl.write("appbase=${getdownFullArchiveAppBase}\n")
+ def vLaunchJvlPath = vLaunchJvl.toPath().toAbsolutePath()
+ def jvlLinkPath = file("${vDir}/jalview.jvl").toPath().toAbsolutePath()
+ // for some reason filepath.relativize(fileInSameDirPath) gives a path to "../" which is wrong
+ //java.nio.file.Files.createSymbolicLink(jvlLinkPath, jvlLinkPath.relativize(vLaunchJvlPath));
+ java.nio.file.Files.createSymbolicLink(jvlLinkPath, java.nio.file.Paths.get(".",vLaunchJvl.getName()));
+
+ // files going into the getdown files dir: getdown.txt, getdown-launcher.jar, channel-launch.jvl, build_properties
+ copy {
+ from getdownLauncher
+ from "${getdownAppBaseDir}/${getdownLaunchJvl}"
+ from "${getdownAppBaseDir}/${getdown_launcher_new}"
+ from "${getdownAppBaseDir}/${channel_props}"
+ if (file(getdownLauncher).getName() != getdown_launcher) {
+ rename(file(getdownLauncher).getName(), getdown_launcher)
+ }
+ into getdownFullArchiveDir
+ }
+
+ }
+ }
+
+ task getdownArchiveDigest(type: JavaExec) {
+ group = "distribution"
+ description = "Digest the getdown archive folder"
+
+ dependsOn getdownArchiveBuild
+
+ doFirst {
+ classpath = files(getdownLauncher)
+ args getdownFullArchiveDir
+ }
+ main = "com.threerings.getdown.tools.Digester"
+ inputs.dir(getdownFullArchiveDir)
+ outputs.file("${getdownFullArchiveDir}/digest2.txt")
+ }
+
+ task getdownArchive() {
+ group = "distribution"
+ description = "Build the website archive dir with getdown digest"
+
+ dependsOn getdownArchiveBuild
+ dependsOn getdownArchiveDigest
+ }
-
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
clean {
doFirst {
- delete getdownWebsiteDir
+ delete getdownAppBaseDir
delete getdownFilesDir
+ delete getdownArchiveDir
}
}
}
}
+ // disable install screen for OSX dmg (for 2.11.2.0)
+ install4jConfigXml.'**'.macosArchive.each { macosArchive ->
+ macosArchive.attributes().remove('executeSetupApp')
+ macosArchive.attributes().remove('setupAppId')
+ }
-
// turn off checksum creation for LOCAL channel
def e = install4jConfigXml.application[0]
- if (CHANNEL == "LOCAL") {
- e.'@createChecksums' = "false"
- } else {
- e.'@createChecksums' = "true"
- }
+ e.'@createChecksums' = string(install4jCheckSums)
// put file association actions where placeholder action is
def install4jFileAssociationsText = install4jFileAssociationsFile.text
}
}
-
// write install4j file
install4jConfFile.text = XmlUtil.serialize(install4jConfigXml)
}
}
}
+ task cleanInstallersDataFiles {
+ def installersOutputTxt = file("${jalviewDir}/${install4jBuildDir}/output.txt")
+ def installersSha256 = file("${jalviewDir}/${install4jBuildDir}/sha256sums")
+ def hugoDataJsonFile = file("${jalviewDir}/${install4jBuildDir}/installers-${JALVIEW_VERSION_UNDERSCORES}.json")
+ doFirst {
+ delete installersOutputTxt
+ delete installersSha256
+ delete hugoDataJsonFile
+ }
+ }
- task installers(type: com.install4j.gradle.Install4jTask) {
+ task installerFiles(type: com.install4j.gradle.Install4jTask) {
group = "distribution"
description = "Create the install4j installers"
dependsOn getdown
dependsOn copyInstall4jTemplate
+ dependsOn cleanInstallersDataFiles
projectFile = install4jConfFile
filesMd5 = filesMd5.substring(0,8)
}
def install4jTemplateVersion = "${JALVIEW_VERSION}_F${filesMd5}_C${gitHash}"
variables = [
'JALVIEW_NAME': jalview_name,
- 'JALVIEW_APPLICATION_NAME': install4jApplicationName,
+ 'JALVIEW_APPLICATION_NAME': applicationName,
'JALVIEW_DIR': "../..",
'OSX_KEYSTORE': OSX_KEYSTORE,
'OSX_APPLEID': OSX_APPLEID,
'WRAPPER_SCRIPT_BIN_DIR': getdown_wrapper_script_dir,
'INSTALLER_NAME': install4jInstallerName,
'INSTALL4J_UTILS_DIR': install4j_utils_dir,
- 'GETDOWN_WEBSITE_DIR': getdown_website_dir,
+ 'GETDOWN_CHANNEL_DIR': getdownChannelDir,
'GETDOWN_FILES_DIR': getdown_files_dir,
'GETDOWN_RESOURCE_DIR': getdown_resource_dir,
'GETDOWN_DIST_DIR': getdownAppDistDir,
'WINDOWS_ICONS_FILE': install4jWindowsIconsFile,
'PNG_ICON_FILE': install4jPngIconFile,
'BACKGROUND': install4jBackground,
+
]
//println("INSTALL4J VARIABLES:")
}
//verbose=true
- inputs.dir(getdownWebsiteDir)
+ inputs.dir(getdownAppBaseDir)
inputs.file(install4jConfFile)
inputs.file("${install4jDir}/${install4j_info_plist_file_associations}")
inputs.dir(macosJavaVMDir)
outputs.dir("${jalviewDir}/${install4j_build_dir}/${JAVA_VERSION}")
}
+ def getDataHash(File myFile) {
+ HashCode hash = Files.asByteSource(myFile).hash(Hashing.sha256())
+ return myFile.exists()
+ ? [
+ "file" : myFile.getName(),
+ "filesize" : myFile.length(),
+ "sha256" : hash.toString()
+ ]
+ : null
+ }
+
+ def writeDataJsonFile(File installersOutputTxt, File installersSha256, File dataJsonFile) {
+ def hash = [
+ "channel" : getdownChannelName,
+ "date" : getDate("yyyy-MM-dd HH:mm:ss"),
+ "git-commit" : "${gitHash} [${gitBranch}]",
+ "version" : JALVIEW_VERSION
+ ]
+ // install4j installer files
+ if (installersOutputTxt.exists()) {
+ def idHash = [:]
+ installersOutputTxt.readLines().each { def line ->
+ if (line.startsWith("#")) {
+ return;
+ }
+ line.replaceAll("\n","")
+ def vals = line.split("\t")
+ def filename = vals[3]
+ def filesize = file(filename).length()
+ filename = filename.replaceAll(/^.*\//, "")
+ hash[vals[0]] = [ "id" : vals[0], "os" : vals[1], "name" : vals[2], "file" : filename, "filesize" : filesize ]
+ idHash."${filename}" = vals[0]
+ }
+ if (install4jCheckSums && installersSha256.exists()) {
+ installersSha256.readLines().each { def line ->
+ if (line.startsWith("#")) {
+ return;
+ }
+ line.replaceAll("\n","")
+ def vals = line.split(/\s+\*?/)
+ def filename = vals[1]
+ def innerHash = (hash.(idHash."${filename}"))."sha256" = vals[0]
+ }
+ }
+ }
+
+ [
+ "JAR": shadowJar.archiveFile, // executable JAR
+ "JVL": getdownVersionLaunchJvl, // version JVL
+ "SOURCE": sourceDist.archiveFile // source TGZ
+ ].each { key, value ->
+ def file = file(value)
+ if (file.exists()) {
+ def fileHash = getDataHash(file)
+ if (fileHash != null) {
+ hash."${key}" = fileHash;
+ }
+ }
+ }
+ return dataJsonFile.write(new JsonBuilder(hash).toPrettyString())
+ }
+
+ task staticMakeInstallersJsonFile {
+ doFirst {
+ def output = findProperty("i4j_output")
+ def sha256 = findProperty("i4j_sha256")
+ def json = findProperty("i4j_json")
+ if (output == null || sha256 == null || json == null) {
+ throw new GradleException("Must provide paths to all of output.txt, sha256sums, and output.json with '-Pi4j_output=... -Pi4j_sha256=... -Pi4j_json=...")
+ }
+ writeDataJsonFile(file(output), file(sha256), file(json))
+ }
+ }
+
+ task installers {
+ dependsOn installerFiles
+ }
-
spotless {
java {
eclipse().configFile(eclipse_codestyle_file)
}
}
+ task createSourceReleaseProperties(type: WriteProperties) {
+ group = "distribution"
+ description = "Create the source RELEASE properties file"
+
+ def sourceTarBuildDir = "${buildDir}/sourceTar"
+ def sourceReleasePropertiesFile = "${sourceTarBuildDir}/RELEASE"
+ outputFile (sourceReleasePropertiesFile)
+
+ doFirst {
+ releaseProps.each{ key, val -> property key, val }
+ property "git.branch", gitBranch
+ property "git.hash", gitHash
+ }
+
+ outputs.file(outputFile)
+ }
task sourceDist(type: Tar) {
group "distribution"
dependsOn createBuildProperties
dependsOn convertMdFiles
- def VERSION_UNDERSCORES = JALVIEW_VERSION.replaceAll("\\.", "_")
- def outputFileName = "${project.name}_${VERSION_UNDERSCORES}.tar.gz"
+ dependsOn eclipseAllPreferences
+ dependsOn createSourceReleaseProperties
+
+
+ def outputFileName = "${project.name}_${JALVIEW_VERSION_UNDERSCORES}.tar.gz"
archiveFileName = outputFileName
compression Compression.GZIP
"*locales/**",
"utils/InstallAnywhere",
"**/*.log",
+ "RELEASE",
]
def PROCESS_FILES=[
"AUTHORS",
"FEATURETODO",
"LICENSE",
"**/README",
- "RELEASE",
"THIRDPARTYLIBS",
"TESTNG",
"build.gradle",
"**/*.sh",
]
def INCLUDE_FILES=[
- ".settings/org.eclipse.jdt.core.jalview.prefs",
+ ".classpath",
+ ".settings/org.eclipse.buildship.core.prefs",
+ ".settings/org.eclipse.jdt.core.prefs"
]
from(jalviewDir) {
exclude ("utils/InstallAnywhere")
exclude (getdown_files_dir)
- exclude (getdown_website_dir)
+ // getdown_website_dir and getdown_archive_dir moved to build/website/docroot/getdown
+ //exclude (getdown_website_dir)
+ //exclude (getdown_archive_dir)
// exluding these as not using jars as modules yet
exclude ("${j11modDir}/**/*.jar")
// exclude(EXCLUDE_FILES)
// exclude(PROCESS_FILES)
// }
+
from(file(buildProperties).getParent()) {
include(file(buildProperties).getName())
rename(file(buildProperties).getName(), "build_properties")
line.replaceAll("^INSTALLATION=.*\$","INSTALLATION=Source Release"+" git-commit\\\\:"+gitHash+" ["+gitBranch+"]")
})
}
+
+ def sourceTarBuildDir = "${buildDir}/sourceTar"
+ from(sourceTarBuildDir) {
+ // this includes the appended RELEASE properties file
+ }
}
+ task dataInstallersJson {
+ group "website"
+ description "Create the installers-VERSION.json data file for installer files created"
+
+ mustRunAfter installers
+ mustRunAfter shadowJar
+ mustRunAfter sourceDist
+ mustRunAfter getdownArchive
+
+ def installersOutputTxt = file("${jalviewDir}/${install4jBuildDir}/output.txt")
+ def installersSha256 = file("${jalviewDir}/${install4jBuildDir}/sha256sums")
+
+ if (installersOutputTxt.exists()) {
+ inputs.file(installersOutputTxt)
+ }
+ if (install4jCheckSums && installersSha256.exists()) {
+ inputs.file(installersSha256)
+ }
+ [
+ shadowJar.archiveFile, // executable JAR
+ getdownVersionLaunchJvl, // version JVL
+ sourceDist.archiveFile // source TGZ
+ ].each { fileName ->
+ if (file(fileName).exists()) {
+ inputs.file(fileName)
+ }
+ }
+
+ outputs.file(hugoDataJsonFile)
+
+ doFirst {
+ writeDataJsonFile(installersOutputTxt, installersSha256, hugoDataJsonFile)
+ }
+ }
task helppages {
+ group "help"
+ description "Copies all help pages to build dir. Runs ant task 'pubhtmlhelp'."
-
dependsOn copyHelp
dependsOn pubhtmlhelp
property(jalviewjs_j2s_alt_file_property_config, jalviewjs_j2s_alt_file_property)
}
}
+
+
task jalviewjsSetEclipseWorkspace {
def propKey = "jalviewjs_eclipse_workspace"
def propVal = null
preserve {
include "**"
}
+
// should this be exclude really ?
duplicatesStrategy "INCLUDE"
+
outputs.files outputFiles
inputs.files inputFiles
}
jalview_key.pass = alignmentisfun
jalview_tsaurl =
proxyPort = 80
- proxyHost = sqid
+ proxyHost = squid
jalview_keyalg = SHA1withRSA
jalview_keydig = SHA1
jalview_name = Jalview
+ hugo_old_jvl = utils/hugo/old_jvl.txt
+ hugo_jalviewjs = utils/hugo/jalviewjs.txt
+ hugo_build_dir = build/website/hugo
+ hugo_data_installers_dir = data/installers
+ hugo_version_archive_dir = content/development/archive
+ hugo_templates_dir = utils/hugo/templates
+ releases_template = help/templates/releases.html
+ whatsnew_template = help/templates/whatsNew.html
+ releases_html = html/releases.html
+ whatsnew_html = html/whatsNew.html
+ whatsnew_dir = help/markdown/whatsnew
+ releases_dir = help/markdown/releases
+ # these are going to be used in the future to gather website release files together
+ getdown_website_dir = build/website/docroot/getdown
+ getdown_archive_dir = build/website/docroot/old
+ getdown_files_dir = build/getdown/files
-
getdown_local = false
- getdown_website_dir = getdown/website
getdown_resource_dir = resource
- getdown_files_dir = getdown/files
getdown_lib_dir = getdown/lib
getdown_launcher = getdown-launcher.jar
getdown_launcher_local = getdown-launcher-local.jar
# now got better (dynamic) defaults when jvmmem* not set
#getdown_txt_jalview.jvmmempc = 90
#getdown_txt_jalview.jvmmemmax = 32G
- getdown_txt_multi_jvmarg = -Dgetdownappdir=%APPDIR%
+ getdown_txt_multi_jvmarg = -Dgetdowninstanceappdir=%APPDIR%
getdown_txt_strict_comments = true
getdown_txt_ui.progress_sync_before_shown = true
getdown_txt_ui.progress_sync_after_shown = false
flexmark_css = utils/doc/github.css
channel_properties_dir = utils/channels
- install4j_home_dir = ~/buildtools/install4j8
+ channel_props = channel.props
+
+ install4j_home_dir = ~/buildtools/install4j9
install4j_copyright_message = ...
install4j_bundle_id = org.jalview.jalview-desktop
install4j_utils_dir = utils/install4j
install4j_images_dir = utils/install4j
- install4j_template = install4j8_template.install4j
+ install4j_template = install4j9_template.install4j
install4j_info_plist_file_associations = file_associations_auto-Info_plist.xml
install4j_installer_file_associations = file_associations_auto-install4j8.xml
#install4j_DMG_uninstaller_app_files = uninstall_old_jalview_files.xml
OSX_KEYSTORE =
OSX_KEYPASS =
JSIGN_SH = echo
-
OSX_APPLEID =
OSX_ALTOOLPASS =
CHANNEL=LOCAL
getdown_channel_base = https://www.jalview.org/getdown
+ getdown_archive_base = https://www.jalview.org/old
getdown_app_dir_release = release
getdown_app_dir_alt = alt
getdown_app_dir_java = jre
# these are used for actual .j2s file to pass on to alt j2s file
jalviewjs_j2s_settings = .j2s
jalviewjs_j2s_alt_file_property_config = j2s.config.altfileproperty
+
# for developing in Eclipse as IDE, set this to automatically copy current swingjs/net.sf.j2s.core.jar to your dropins dir
jalviewjs_eclipseIDE_auto_copy_j2s_plugin = false
# Override this in a local.properties file
#j2s.compiler.nonqualified.classes = null
#j2s.compiler.mode = debug
#a semicolon-separated list of package (foo.) or class (foo.bar) replacements to be made
- j2s.class.replacements = org.apache.log4j.->jalview.javascript.log4j.
+ #j2s.class.replacements = org.apache.logging.log4j.->jalview.javascript.log4j.
j2s.template.html = utils/jalviewjs/template.html
j2s_coretemplate_html = utils/jalviewjs/coretemplate.html
#output file name for logging methods declared - delete the file to regenerate a listing
<mapID target="pdbmcviewer" url="html/features/pdbviewer.html"/>
<mapID target="pdbjmol" url="html/features/jmol.html"/>
<mapID target="chimera" url="html/features/chimera.html"/>
+ <mapID target="pymol" url="html/features/pymol.html"/>
<mapID target="chimera.annotxfer" url="html/features/chimera.html#annotxfer"/>
<mapID target="varna" url="html/features/varna.html"/>
<mapID target="xsspannotation" url="html/features/xsspannotation.html"/>
<mapID target="preferences" url="html/features/preferences.html"/>
+ <mapID target="startupprefs" url="html/features/preferences.html#startup"/>
<mapID target="strucprefs" url="html/features/preferences.html#structure"/>
<mapID target="commandline" url="html/features/commandline.html"/>
+ <mapID target="jalviewcltool" url="html/features/commandline.html#script"/>
<mapID target="clarguments" url="html/features/clarguments.html"/>
<mapID target="jvlfiles" url="html/features/jvlfiles.html"/>
<mapID target="io" url="html/io/index.html"/>
<mapID target="colours.clustal" url="html/colourSchemes/clustal.html"/>
<mapID target="colours.zappo" url="html/colourSchemes/zappo.html" />
<mapID target="colours.taylor" url="html/colourSchemes/taylor.html" />
+ <mapID target="colours.gecos-flower" url="html/colourSchemes/gecos-flower.html" />
+ <mapID target="colours.gecos-blossom" url="html/colourSchemes/gecos-blossom.html" />
+ <mapID target="colours.gecos-sunset" url="html/colourSchemes/gecos-sunset.html" />
+ <mapID target="colours.gecos-ocean" url="html/colourSchemes/gecos-ocean.html" />
<mapID target="colours.hydro" url="html/colourSchemes/hydrophobic.html" />
<mapID target="colours.helix" url="html/colourSchemes/helix.html" />
<mapID target="colours.strand" url="html/colourSchemes/strand.html" />
<mapID target="alwCalc" url="html/menus/alwcalculate.html"/>
<mapID target="wsMenu" url="html/menus/wsmenu.html"/>
+ <mapID target="alwHmmer" url="html/menus/alwhmmer.html"/>
<mapID target="popMenu" url="html/menus/popupMenu.html"/>
<mapID target="popMenuAddref" url="html/menus/popupMenu.html#addrefannot"/>
<mapID target="annotPanelMenu" url="html/menus/alwannotationpanel.html"/>
<mapID target="pdbfts" url="html/features/pdbsequencefetcher.html#pdbfts" />
<mapID target="siftsmapping" url="html/features/siftsmapping.html" />
<mapID target="pdbchooser" url="html/features/structurechooser.html" />
+ <mapID target="structuresvia3dbeacons" url="html/features/structurechooser.html#3dbeaconssearch" />
<mapID target="selectcolbyannot" url="html/features/columnFilterByAnnotation.html" />
<mapID target="biojsmsa" url="html/features/biojsmsa.html" />
<tocitem text="Jalview Documentation" target="home" expand="true">
<tocitem text="What's new" target="new" expand="true">
<tocitem text="Latest Release Notes" target="release"/>
- <tocitem text="Virtual Features in CDS/Protein Views" target="splitframe.virtualfeats"/>
- <tocitem text="VCF Variant Attributes" target="importvcf.attribs"/>
- <tocitem text="Feature Filters and Attribute Colourschemes" target="features.featureschemes" />
- <tocitem text="The Java Console, Logging and Reporting Bugs" target="logging" />
+ <tocitem text="Support for ChimeraX" target="chimera"/>
+ <tocitem text="Support for Pymol" target="pymol"/>
+ <tocitem text="Structures via 3D Beacons" target="structuresvia3dbeacons" />
+ <tocitem text="Startup Memory Settings" target="startupprefs" />
+ <tocitem text="The Java Console, Logging and Reporting Bugs" target="logging" />
+ <tocitem text="Command line launch scripts" target="jalviewcltool"/>
</tocitem>
<tocitem text="Editing Alignments" target="edit" />
<tocitem text="ClustalX" target="colours.clustal" />
<tocitem text="Zappo" target="colours.zappo" />
<tocitem text="Taylor" target="colours.taylor" />
+ <tocitem text="gecos Flower" target="colours.gecos-flower" />
+ <tocitem text="gecos Blossom" target="colours.gecos-blossom" />
+ <tocitem text="gecos Sunset" target="colours.gecos-sunset" />
+ <tocitem text="gecos Ocean" target="colours.gecos-ocean" />
<tocitem text="Hydrophobicity" target="colours.hydro" />
<tocitem text="Helix propensity" target="colours.helix" />
<tocitem text="Strand propensity" target="colours.strand" />
<tocitem text="PDB Sequence Fetcher" target="pdbfetcher" />
<tocitem text="PDB & 3D-Beacons Structure Chooser" target="pdbchooser" />
<tocitem text="Jmol Viewer" target="pdbjmol" />
- <tocitem text="Chimera Viewer" target="chimera" />
+ <tocitem text="Chimera/X Viewer" target="chimera" />
+ <tocitem text="Pymol Viewer" target="pymol" />
</tocitem>
<tocitem text="Viewing RNA structures" target="varna" expand="false"/>
<tocitem text="Opening URLs from Jalview" target="urllinks" expand="true">
<tocitem text="Colour Menu" target="alwColour" />
<tocitem text="Calculate Menu" target="alwCalc" />
<tocitem text="Web Service Menu" target="wsMenu" />
+ <tocitem text="HMMER Menu" target="alwHmmer" />
<tocitem text="Annotation Panel Menu" target="annotPanelMenu" />
<tocitem text="Popup Menu" target="popMenu" />
</tocitem>
</li>
<li>The <a href="#connections"><strong>"Connections"</strong>
Preferences</a> tab allows you to configure Jalview's internet
- settings and specify your default web browser.
+ settings.
</li>
<li>The <a href="#links"><strong>"Links"</strong>
Preferences</a> tab shows the currently configured <em>URL
<li>The <a href="#editing"><strong>"Editing"</strong>
Preferences</a> tab contains settings affecting behaviour when editing alignments.
</li>
+ <li>The <a href="#startup"><strong>"Startup"</strong>
+ Preferences</a> tab allows you to adjust how much memory is
+ allocated to Jalview when it is launched.
+ </li>
+ <li>The <a href="#hmmer"><strong>"HMMER"</strong>
+ Preferences</a> tab allows you to configure locally installed HMMER tools.
+ </li>
<li>The <a href="../webServices/webServicesPrefs.html"><strong>"Web
Service"</strong> Preferences</a> tab allows you to configure the <a
href="http://www.compbio.dundee.ac.uk/jabaws">JABAWS</a>
structure information read from PDB will be processed and annotation
added to associated sequences.
<p>
- <em>Use RNAView for secondary structure</em> - if selected, the
- pyRNA RNAView service (<a href="https://github.com/fjossinet/PyRNA">https://github.com/fjossinet/PyRNA</a>)
- will be called to derive secondary structure information for RNA
- chains.
- <p>
<em>Add secondary structure annotation to alignment</em> - if
selected, <a href="http://swift.cmbi.ru.nl/gv/dssp/">Jmol's
implementation DSSP</a> will be used to add annotation to polypeptide
the backbone atoms in the PDB file will be extracted as annotation
lines shown on the alignment.<br/><em>Since 2.11.2, scores from the Temperature Column for structures imported via the 3D-Beacons network may be shown instead as model quality or reliability scores.</em>
<p>
- <em>Default structure viewer</em> - choose Jmol, CHIMERA, CHIMERAX or PYMOL for
+ <em><strong>Default structure viewer</strong></em> - choose Jmol, CHIMERA, CHIMERAX or PYMOL for
viewing 3D structures.
<p>
<em>Path to Chimera/X/Pymol program</em> - Optional, as Jalview will search
installed the chosen viewer in a non-standard location, you can specify it
here, by entering the full path to its executable.<br/>For Chimera, locate the path to the chimera program, similarly for ChimeraX and Pymol. Rather than typing in the path, you can also <em>double-click this field</em> to open a file chooser dialog.</p>
<p>
+ <em>Sequence <-> Structure Mapping Method</em> - This setting controls whether
+ Jalview attempts to retrieve mappings between Uniprot protein
+ sequences and 3D structures in the PDBe with SIFTS, or constructs a
+ mapping by conservative alignment between the sequences and chains
+ in the 3D structure data using the Needleman and Wunsch algorithm.
+ SIFTS is enabled by default.
+ <p>
<em>PDB Fields shown in Search and Structure Summaries</em> - ticks
in this table indicate fields shown by default when browsing results
of a free text search via the PDB sequence fetcher, or 3D structures
<em>Sort with New Tree</em> - When selected, any trees calculated or
loaded onto the alignment will automatically sort the alignment.
</p>
- <p>
+ <p> </p>
+ <p>
+ <a name="startup"><strong>Startup</strong></a>
+ </p>
+ <p>
+ When Jalview is launched it by default examines the available memory
+ and requests up to 90% to be allocated to the application, or 32G,
+ which ever is smaller. The <em>Startup</em> tab allows you to adjust
+ the maximum percentage and hard limits for Jalview memory allocation
+ stored in your .jalview_properties file.
+ </p>
+ <p> </p>
++ <p>
+ <a name="hmmer"><strong>"HMMER" Preferences tab</strong></a>
+ </p>
+ <p>If you have installed HMMER tools (available from <a href="http://hmmerorg">hmmer.org</a>),
+ then you should specify on this screen the location of the installation (the path to the folder
+ containing binary executable programs). Double-click in the input field to open a file browser.</p>
+ <p>When this path is configured, the <a href="../menus/alwhmmer.html">HMMER menu</a> will be
+ enabled in the Alignment window.</p>
+ <p> </p>
<em>Web Services Preferences</em> - documentation for this tab is
given in the
<a href="../webServices/webServicesPrefs.html">Web Services
action.show_html_source = Show HTML Source
action.print = Print...
action.web_service = Web Service
+action.hmmer = HMMER
action.cancel_job = Cancel Job
action.start_job = Start Job
action.revert = Revert
action.text = Text
action.by_pairwise_id = By Pairwise Identity
action.by_id = By Id
+action.by_evalue = By E-Value
+action.by_bit_score = By Bit Score
action.by_length = By Length
action.by_group = By Group
action.unmark_as_reference = Unmark as Reference
action.border_colour = Border colour
action.edit_new_group = Edit New Group
action.hide_sequences = Hide Sequences
+action.add_background_frequencies = Add Background Frequencies
action.sequences = Sequences
action.ids = IDS
action.ids_sequences = IDS and sequences
tooltip.select_highlighted_columns = Press B to mark highlighted columns, Ctrl-(or Cmd)-B to toggle, and Alt-B to mark all but highlighted columns
action.deselect_all = Deselect all
action.invert_selection = Invert selection
+action.filter_by_evalue = Filter by E-Value
+action.filter_by_score = Filter by Score
action.using_jmol = Using Jmol
action.undo_changes_to_feature_settings = Undo all unapplied changes to feature settings
action.undo_changes_to_feature_settings_and_close_the_dialog = Undo all pending changes and close the feature settings dialog
# delete Clustal - use FileFormat name instead
label.clustal = Clustal
# label.colourScheme_<schemeName> as in JalviewColourScheme, spaces removed
- label.colourScheme_clustal = Clustalx
+ label.colourScheme_clustal = Clustal
label.colourScheme_blosum62 = BLOSUM62 Score
label.colourScheme_%identity = Percentage Identity
label.colourScheme_zappo = Zappo
label.colourScheme_buriedindex = Buried Index
label.colourScheme_purine/pyrimidine = Purine/Pyrimidine
label.colourScheme_nucleotide = Nucleotide
+label.colourScheme_hmmer-uniprot = HMMER profile v global background
+label.colourScheme_hmmer-alignment = HMMER profile v alignment background
+label.colourScheme_hmm_match_score = HMM Match Score
label.colourScheme_t-coffeescores = T-Coffee Scores
label.colourScheme_rnahelices = By RNA Helices
label.colourScheme_sequenceid = Sequence ID Colour
+ label.colourScheme_gecos\:flower = gecos Flower
+ label.colourScheme_gecos\:blossom = gecos Blossom
+ label.colourScheme_gecos\:sunset = gecos Sunset
+ label.colourScheme_gecos\:ocean = gecos Ocean
label.blc = BLC
label.fasta = Fasta
label.msf = MSF
label.viewer_path_tip = Jalview will first try any path entered here, else standard installation locations.<br>Double-click to browse for file.
label.invalid_viewer_path = Path not found or not executable
label.viewer_missing = Structure viewer not found.<br/>Please enter the path to the executable (if installed),<br/>or download and install the program.
- label.open_viewer_failed = Error opening {0} - is it installed?\nCheck path in Preferences, Structure
+ label.open_viewer_failed = Error opening {0} - is it installed?\nCheck configured path in Structure tab of Jalview''s Preferences
label.min_colour = Minimum Colour
label.max_colour = Maximum Colour
label.no_colour = No Colour
label.couldnt_load_file = Couldn't load file
label.couldnt_find_pdb_id_in_file = Couldn't find a PDB id in the file supplied. Please enter an Id to identify this structure.
label.no_pdb_id_in_file = No PDB Id in File
- label.couldnt_read_pasted_text = Couldn't read the pasted text {0}
+ label.couldnt_read_pasted_text = Couldn''t read the pasted text {0}
label.error_parsing_text = Error parsing text
label.input_alignment_from_url = Input Alignment From URL
label.input_alignment = Input Alignment
label.standard_databases = Standard Databases
label.fetch_embl_uniprot = Fetch from EMBL/EMBLCDS or Uniprot/PDB and any selected DAS sources
label.fetch_uniprot_references = Fetch Uniprot references
- label.search_3dbeacons = 3D-Beacons Search
+ label.search_3dbeacons = Search 3D-Beacons
label.find_models_from_3dbeacons = Search 3D-Beacons for 3D structures and models
label.3dbeacons = 3D-Beacons
label.fetch_references_for = Fetch database references for {0} sequences ?
- label.fetch_references_for_3dbeacons = 3D Beacons needs Uniprot References. Fetch database references for {0} sequences ?
+ label.fetch_references_for_3dbeacons = 3D Beacons needs to fetch Uniprot References for {0} sequences. Do you want to continue ?
label.reset_min_max_colours_to_defaults = Reset min and max colours to defaults from user preferences.
label.align_structures_using_linked_alignment_views = Superpose structures using {0} selected alignment view(s)
label.threshold_feature_display_by_score = Threshold the feature display by score.
label.address = Address
label.host = Host
label.port = Port
- label.default_browser_unix = Default Browser (Unix)
+ label.default_browser_unix_windows = Default Browser (Unix, Windows)
label.send_usage_statistics = Send usage statistics
label.check_for_questionnaires = Check for questionnaires
label.check_for_latest_version = Check for latest version
label.web_services = Web Services
label.right_click_to_edit_currently_selected_parameter = Right click to edit currently selected parameter.
label.let_jmol_manage_structure_colours = Let Jmol manage structure colours
- label.fetch_chimera_attributes = Fetch Chimera attributes
- label.fetch_chimera_attributes_tip = Copy Chimera attribute to Jalview feature
+ label.fetch_viewer_attributes = Fetch {0} attributes
+ label.fetch_viewer_attributes_tip = Copy {0} attribute to Jalview feature
label.marks_leaves_tree_not_associated_with_sequence = Marks leaves of tree not associated with a sequence
label.index_web_services_menu_by_host_site = Index web services in menu by the host site
label.option_want_informed_web_service_URL_cannot_be_accessed_jalview_when_starts_up = Check this option if you want to be informed<br>when a web service URL cannot be accessed by Jalview<br>when it starts up
label.insufficient_residues = Not enough aligned residues ({0}) to perform superposition
label.create_viewer_attributes = Write Jalview features
label.create_viewer_attributes_tip = Set structure residue attributes for Jalview features
- label.attributes_set = {0} attribute values set on Chimera
+ label.attributes_set = {0} attribute values set on {1}
label.sort_alignment_by_tree = Sort Alignment By Tree
label.mark_unlinked_leaves = Mark Unlinked Leaves
label.associate_leaves_with = Associate Leaves With
label.variable_color_for = Variable Feature Colour for {0}
label.select_background_colour = Select Background Colour
label.invalid_font = Invalid Font
+ label.search_db_all = Search all of {0}
+ label.search_db_index = Search {0} index {1}
label.separate_multiple_accession_ids = Enter one or more accession IDs separated by a semi-colon ";"
- label.separate_multiple_query_values = Enter one or more {0}s separated by a semi-colon ";"
+ label.separate_multiple_query_values = Enter one or more {0} separated by a semi-colon ";"
label.search_all = Enter one or more search values separated by a semi-colon ";" (Note: This searches the entire database)
label.replace_commas_semicolons = Replace commas with semi-colons
label.parsing_failed_syntax_errors_shown_below_param = Parsing failed. Syntax errors shown below {0}
label.set_proxy_settings = Please set up your proxy settings in the 'Connections' tab of the Preferences window
label.proxy_authorization_failed = Proxy Authorization Failed
label.internal_jalview_error = Internal Jalview Error
- label.secondary_structure_prediction_service_couldnt_be_located = The Secondary Structure Prediction Service named {0} at {1} couldn't be located.
+ label.secondary_structure_prediction_service_couldnt_be_located = The Secondary Structure Prediction Service named {0} at {1} couldn''t be located.
label.service_called_is_not_msa_service = The Service called \n{0}\nis not a \nMultiple Sequence Alignment Service\!
label.msa_service_is_unknown = The Multiple Sequence Alignment Service named {0} is unknown
label.service_called_is_not_seq_search_service = The Service called \n{0}\nis not a \nSequence Search Service\!
label.save_state = Save State
label.restore_state = Restore State
label.saving_jalview_project = Saving jalview project {0}
+label.loading_jalview_project = Loading jalview project {0}
label.load_feature_colours = Load Feature Colours
label.save_feature_colours = Save Feature Colour Scheme
label.select_startup_file = Select startup file
error.implementation_error_msawbjob_called = Implementation error - StartJob(MsaWSJob) called on a WSJobInstance {0}
error.implementation_error_cannot_attach_ws_menu_entry = IMPLEMENTATION ERROR: cannot attach WS Menu Entry without service handle reference!
error.parameter_migration_not_implemented_yet = Parameter migration not implemented yet
+error.implementation_error_cannot_set_jaba_option = Implementation error: cannot set Jaba Option to a value outside its allowed value range!
error.implementation_error_valuetype_doesnt_support_jabaws_type = IMPLEMENTATION ERROR: jalview.ws.params.ValueConstrainI.ValueType does not support the JABAWS type : {0}
error.cannot_create_jabaws_param_set = Cannot create a JabaWSParamSet from non-JabaWS parameters
error.cannot_set_arguments_to_jabaws_param_set = Cannot set arguments to a JabaWSParamSet that are not JabaWS arguments
error.implementation_error_runner_config_not_available = Implementation Error: Runner Config not available for a JABAWS service of type {0} ({1})
error.implementation_error_cannot_handle_jaba_param = Implementation Error: Cannot handle Jaba parameter object {0}
error.implementation_error_attempt_to_delete_service_preset = Implementation error: Attempt to delete a service preset!
- error.implementation_error_cannot_locate_oldname_presetname = Implementation error: Can't locate either oldname ({0}) or presetName ({1}in the datastore!"
+ error.implementation_error_cannot_locate_oldname_presetname = Implementation error: Can''t locate either oldname ({0}) or presetName ({1}) in the datastore!"
error.implementation_error_jabaws_param_set_only_handled_by = Implementation error: JabaWsParamSets can only be handled by JabaParamStore
error.cannot_set_source_file_for = Cannot set source file for {0}
error.mismatch_service_instance_preset = Probable mismatch between service instance and preset!
error.implementation_error_can_only_instantiate_jaba_param_sets = Implementation error: Can only instantiate Jaba parameter sets
error.no_aacon_service_found = No AACon service found
error.implementation_error_couldnt_copy_value_constraint = Implementation error: could not copy ValueConstrain!
- error.couldnt_encode_as_utf8 = Couldn't encode {0} as UTF-8.
+ error.couldnt_encode_as_utf8 = Couldn''t encode {0} as UTF-8.
error.tree_inputtype_not_yet_implemented = Tree InputType not yet implemented
error.implementation_error_need_to_have_httpresponse = Implementation Error: need to have an HttpResponse to process
error.dbrefsource_implementation_exception =DBRefSource Implementation Exception
exception.number_of_residues_in_query_sequence_differ_from_prediction = Number of residues in {0} supposed query sequence ({1}\n{2})\ndiffer from number of prediction sites in prediction ({3})
label.mapped = mapped
exception.jpredconcide_entry_has_unexpected_number_of_columns = JPredConcise: Entry ({0}) has an unexpected number of columns
- exception.couldnt_parse_concise_annotation_for_prediction = Couldn't parse concise annotation for prediction profile.\n{0}
+ exception.couldnt_parse_concise_annotation_for_prediction = Couldn''t parse concise annotation for prediction profile.\n{0}
exception.newfile = NewickFile\: {0}\n
label.no_tree_read_in = No Tree read in
- exception.rnaml_couldnt_access_datasource = Couldn't access datasource ({0})
- exception.ranml_couldnt_process_data = Couldn't process data as RNAML file ({0})
+ exception.rnaml_couldnt_access_datasource = Couldn''t access datasource ({0})
+ exception.ranml_couldnt_process_data = Couldn''t process data as RNAML file ({0})
exception.ranml_invalid_file = Invalid RNAML file ({0})
exception.ranml_problem_parsing_data = Problem parsing data as RNAML ({0})
exception.pfam_no_sequences_found = No sequences found (PFAM input)
+exception.hmmer_no_valid_sequences_found = No valid sequences found
exception.stockholm_invalid_format = This file is not in valid STOCKHOLM format: First line does not contain '# STOCKHOLM'
exception.couldnt_parse_sequence_line = Could not parse sequence line: {0}
exception.unknown_annotation_detected = Unknown annotation detected: {0} {1}
- exception.couldnt_store_sequence_mappings = Couldn't store sequence mappings for {0}
+ exception.couldnt_store_sequence_mappings = Couldn''t store sequence mappings for {0}
exception.matrix_too_many_iteration = Too many iterations in {0} (max is {1})
exception.browser_not_found = Exception in finding browser: {0}
+ exception.browser_unable_to_launch = Unable to launch browser: {0}
exception.browser_unable_to_locate = Unable to locate browser: {0}
+ exception.browser_os_not_supported = Launching browser on this operating system not supported. Use URL\n{0}
exception.invocation_target_exception_creating_aedesc = InvocationTargetException while creating AEDesc: {0}
exception.illegal_access_building_apple_evt= IllegalAccessException while building AppleEvent: {0}
exception.unable_to_launch_url = Unable to launch URL: {0}
exception.invocation_target_calling_url = InvocationTargetException while calling openURL: {0}
exception.illegal_access_calling_url = IllegalAccessException while calling openURL: {0}
exception.interrupted_launching_browser = InterruptedException while launching browser: {0}
+exception.ebiembl_retrieval_failed_on = EBI EMBL XML retrieval failed on {0}:{1}
exception.no_pdb_records_for_chain = No PDB Records for {0} chain {1}
exception.unexpected_handling_rnaml_translation_for_pdb = Unexpected exception when handling RNAML translation of PDB data
exception.couldnt_recover_sequence_properties_for_alignment = Couldn't recover sequence properties for alignment
warn.input_is_too_big = Input is too big!
warn.invalid_job_param_set = Invalid job parameter set!
warn.oneseq_msainput_selection = The current selection only contains a single sequence. Do you want to submit all sequences for alignment instead ?
- info.job_couldnt_be_run_server_doesnt_support_program = Job could not be run because the server doesn't support this program.\n{0}
+ info.job_couldnt_be_run_server_doesnt_support_program = Job could not be run because the server doesn''t support this program.\n{0}
info.job_couldnt_be_run_exceeded_hard_limit = Job could not be run because it exceeded a hard limit on the server.\n{0}
info.job_couldnt_be_run_incorrect_param_setting = Job could not be run because some of the parameter settings are not supported by the server.\n{0}\nPlease check to make sure you have used the correct parameter set for this service\!\n
info.no_jobs_ran = No jobs ran
status.fetching_pdb = Fetching PDB {0}
status.refreshing_news = Refreshing news
status.opening_params = Opening {0}
+status.waiting_sequence_database_fetchers_init = Waiting for Sequence Database Fetchers to initialise
+status.init_sequence_database_fetchers = Initialising Sequence Database Fetchers
status.fetching_sequence_queries_from = Fetching {0} sequence queries from {1}
status.finshed_querying = Finished querying
status.parsing_results = Parsing results.
status.searching_3d_beacons = Searching 3D Beacons
status.no_structures_discovered_from_3d_beacons = No models discovered from 3D Beacons
status.opening_file_for = opening file for
+status.running_hmmbuild = Building Hidden Markov Model
+status.running_hmmalign = Creating alignment with Hidden Markov Model
+status.running_search = Searching for matching sequences
status.colouring_structures = Colouring structures
label.font_doesnt_have_letters_defined = Font doesn't have letters defined\nso cannot be used\nwith alignment data
label.font_too_small = Font size is too small
+label.error_loading_file_params = Error loading file {0}
+label.error_loading_jalview_file = Error loading Jalview file
warn.out_of_memory_when_action = Out of memory when {0}\!\!\nSee help files for increasing Java Virtual Machine memory.
warn.out_of_memory_loading_file = Out of memory loading file {0}\!\!\nSee help files for increasing Java Virtual Machine memory.
label.out_of_memory = Out of memory
label.invalid_id_column_width = Invalid ID Column width
warn.user_defined_width_requirements = The user defined width for the\nannotation and sequence ID columns\nin exported figures must be\nat least 12 pixels wide.
+label.couldnt_create_sequence_fetcher = Couldn't create SequenceFetcher
+warn.couldnt_create_sequence_fetcher_client = Could not create the sequence fetcher client. Check error logs for details.
warn.server_didnt_pass_validation = Service did not pass validation.\nCheck the Jalview Console for more details.
warn.url_must_contain = Sequence URL must contain $SEQUENCE_ID$, $DB_ACCESSION$, or a regex
warn.urls_not_contacted = URLs that could not be contacted
option.autosearch = Autosearch
label.retrieve_ids = Retrieve IDs
label.display_settings_for = Display settings for {0} features
+label.simple = Simple
label.simple_colour = Simple Colour
label.colour_by_text = Colour by text
label.graduated_colour = Graduated Colour
label.pca = PCA
label.create_image_of = Create {0} image of {1}
label.click_to_edit = Click to edit, right-click for menu
+label.hmmalign = hmmalign
+label.use_hmm = HMM profile to use
+label.use_sequence = Sequence to use
+label.hmmbuild = hmmbuild
+label.hmmsearch = hmmsearch
+label.jackhmmer = jackhmmer
+label.installation = Installation
+label.hmmer_location = HMMER Binaries Installation Location
+label.cygwin_location = Cygwin Binaries Installation Location (Windows)
+label.information_annotation = Information Annotation
+label.ignore_below_background_frequency = Ignore Below Background Frequency
+label.information_description = Information content, measured in bits
+warn.no_hmm = No Hidden Markov model found.\nRun hmmbuild or load an HMM file first.
+label.no_sequences_found = No matching sequences, or an error occurred.
+label.hmmer = HMMER
+label.trim_termini = Trim Non-Matching Termini
+label.trim_termini_desc = If true, non-matching regions on either end of the resulting alignment are removed.
+label.no_of_sequences = Number of sequences returned
+label.reporting_cutoff = Reporting Cut-off
+label.inclusion_threshold = Inlcusion Threshold
+label.freq_alignment = Use alignment background frequencies
+label.freq_uniprot = Use Uniprot background frequencies
+label.hmmalign_options = hmmalign options
+label.hmmsearch_options = hmmsearch options
+label.jackhmmer_options = jackhmmer options
+label.executable_not_found = The ''{0}'' executable file was not found
+warn.command_failed = {0} failed
+label.invalid_folder = Invalid Folder
+label.number_of_results = Number of Results to Return
+label.number_of_iterations = Number of jackhmmer Iterations
+label.auto_align_seqs = Automatically Align Fetched Sequences
+label.new_returned = new sequences returned
+label.use_accessions = Return Accessions
+label.check_for_new_sequences = Return Number of New Sequences
+label.evalue = E-Value
+label.reporting_seq_evalue = Reporting Sequence E-value Cut-off
+label.reporting_seq_score = Reporting Sequence Score Threshold
+label.reporting_dom_evalue = Reporting Domain E-value Cut-off
+label.reporting_dom_score = Reporting Domain Score Threshold
+label.inclusion_seq_evalue = Inclusion Sequence E-value Cut-off
+label.inclusion_seq_score = Inclusion Sequence Score Threshold
+label.inclusion_dom_evalue = Inclusion Domain E-value Cut-off
+label.inclusion_dom_score = Inclusion Domain Score Threshold
+label.number_of_results_desc = The maximum number of hmmsearch results to display
+label.number_of_iterations_desc = The number of iterations jackhmmer will complete when searching for new sequences
+label.auto_align_seqs_desc = If true, all fetched sequences will be aligned to the hidden Markov model with which the search was performed
+label.check_for_new_sequences_desc = Display number of new sequences returned from hmmsearch compared to the previous alignment
+label.use_accessions_desc = If true, the accession number of each sequence is returned, rather than that sequence's name
+label.reporting_seq_e_value_desc = The E-value cutoff for returned sequences
+label.reporting_seq_score_desc = The score threshold for returned sequences
+label.reporting_dom_e_value_desc = The E-value cutoff for returned domains
+label.reporting_dom_score_desc = The score threshold for returned domains
+label.inclusion_seq_e_value_desc = Sequences with an E-value less than this cut-off are classed as significant
+label.inclusion_seq_score_desc = Sequences with a bit score greater than this threshold are classed as significant
+label.inclusion_dom_e_value_desc = Domains with an E-value less than this cut-off are classed as significant
+label.inclusion_dom_score_desc = Domains with a bit score greater than this threshold are classed as significant
+label.add_database = Add Database
+label.this_alignment = This alignment
+warn.invalid_format = This is not a valid database file format. The current supported formats are Fasta, Stockholm and Pfam.
+label.database_for_hmmsearch = The database hmmsearch will search through
+label.use_reference = Use Reference Annotation
+label.use_reference_desc = If true, hmmbuild will keep all columns defined as a reference position by the reference annotation
+label.hmm_name = Alignment HMM Name
+label.hmm_name_desc = The name given to the HMM for the alignment
+warn.no_reference_annotation = No reference annotation found
+label.hmmbuild_for = Build HMM for
+label.hmmbuild_for_desc = Build an HMM for the selected sets of sequences
+label.alignment = Alignment
+label.groups_and_alignment = All groups and alignment
+label.groups = All groups
+label.selected_group = Selected group
+label.use_info_for_height = Use Information Content as Letter Height
+action.search = Search
label.backupfiles_confirm_delete = Confirm delete
label.backupfiles_confirm_delete_old_files = Delete the following older backup files? (see the Backups tab in Preferences for more options)
label.backupfiles_confirm_save_file = Confirm save file
label.backupfiles_confirm_save_new_saved_file_ok = The new saved file seems okay.
label.backupfiles_confirm_save_new_saved_file_not_ok = The new saved file might not be okay.
label.continue_operation = Continue operation?
+ label.continue = Continue
label.backups = Backups
label.backup = Backup
label.backup_files = Backup Files
label.append_to_filename = Append to filename (%n is replaced by the backup number)
label.append_to_filename_tooltip = %n in the text will be replaced by the backup number. The text will appear after the filename. See the summary box above.
label.index_digits = Number of digits to use for the backup number (%n)
+label.summary_of_backups_scheme = Summary of backup scheme
label.scheme_examples = Scheme examples
label.increment_index = Increase appended text numbers - newest file has largest number.
label.reverse_roll = "Roll" appended text numbers - newest backup file is always number 1.
label.keep_all_versions_description = Keep all previous versions of the file
label.rolled_backups_description = Keep the last nine versions of the file from _bak.1 (newest) to _bak.9 (oldest)
label.cancel_changes_description = Cancel changes made to your last saved Custom scheme
+label.previously_saved_scheme = Previously saved scheme
label.no_backup_files = NO BACKUP FILES
label.include_backup_files = Include backup files
label.cancel_changes = Cancel changes
label.warning_confirm_change_reverse = Warning!\nIf you change the increment/decrement of the backup filename number, without changing the suffix or number of digits,\nthis may cause loss of backup files created with the previous backup filename scheme.\nAre you sure you wish to do this?
label.change_increment_decrement = Change increment/decrement?
+label.was_previous = was {0}
label.newerdelete_replacement_line = Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted and replaced by apparently older file\n''{1}''\t(modified {3}, size {5}).
label.confirm_deletion_or_rename = Confirm deletion of ''{0}'' or rename to ''{1}''?
label.newerdelete_line = Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted but is newer than the oldest remaining backup file\n''{1}''\t(modified {3}, size {5}).
label.log_level_tooltip = Temporarily set the log level for this console. The log level will revert to {0} when this Java console is closed.
label.copy_to_clipboard = Copy to clipboard
label.copy_to_clipboard_tooltip = Copy all of the log text in this console to the system clipboard
+ label.startup = Startup
+ label.memory = Memory
+ label.customise_memory_settings = Customise maximum memory settings
+ label.memory_setting_text = New memory settings will only come into effect the next time you start Jalview
+ label.maximum_memory_used = Maximum memory limited to both
+ label.percent_of_physical_memory = Maximum percent of physical memory
+ label.maximum_memory = Maximum absolute memory
+ label.maximum_memory_tooltip = Enter memory as an integer number optionally followed by 'b', 'k', 'm', 'g' or 't'
+ label.adjustments_for_this_computer = Adjustments for this computer
+ label.memory_example_text = Maximum memory that would be used with these settings on this computer
+ label.memory_example_tooltip = The memory allocated to Jalview is the smaller of the percentage of physical memory (default 90%) and the maximum absolute memory (default 32GB). If your computer's memory cannot be ascertained then the maximum absolute memory defaults to 8GB (if not customised).<br>Jalview will always try and reserve 512MB for the OS and at least 512MB for itself.
+ warning.wrong_jvm_version_title = Wrong Java Version
+ warning.wrong_jvm_version_message = The Java version being used (Java {0}) may lead to problems.\nThis installation of Jalview should be used with Java {1}.
label.occupancy = Ocupación
label.clustal = Clustal
# label.colourScheme_<schemeName> as in JalviewColourScheme
- label.colourScheme_clustal = Clustalx
+ label.colourScheme_clustal = Clustal
label.colourScheme_blosum62 = Puntuación del BLOSUM62
label.colourScheme_%identity = Porcentaje de identidad
label.colourScheme_zappo = Zappo
label.colourScheme_t-coffeescores = Puntuación del T-Coffee
label.colourScheme_rnahelices = Por hélices de RNA
label.colourScheme_sequenceid = Color de ID de secuencia
+ label.colourScheme_gecos\:flower = gecos Flower
+ label.colourScheme_gecos\:blossom = gecos Blossom
+ label.colourScheme_gecos\:sunset = gecos Sunset
+ label.colourScheme_gecos\:ocean = gecos Ocean
label.blc = BLC
label.fasta = Fasta
label.msf = MSF
label.overview_window = Ventana resumen
label.none = Ninguno
label.above_identity_threshold = Por encima del umbral de identidad
-label.show_sequence_features = Mostrar las características de secuencia
+label.show_sequence_features = Mostrar las características de las secuencias
label.nucleotide = Nucleótido
label.to_new_alignment = A nuevo alineamiento
label.to_this_alignment = Añadir a este alineamiento
label.couldnt_locate = No se pudo localizar {0}
label.url_not_found = URL no encontrada
label.new_sequence_url_link = Enlace a una nueva secuencia URL
+label.cannot_edit_annotations_in_wrapped_view = No se pueden editar anotaciones en vista envolvente
+label.wrapped_view_no_edit = Vista envolvente - no editar
label.error_retrieving_data = Error en la recuperación de datos
label.user_colour_scheme_must_have_name = El esquema de colores del usuario debe tener un nombre
label.no_name_colour_scheme = No hay nombre para el esquema de colores
label.address = Dirección
label.host = Host
label.port = Puerto
- label.default_browser_unix = Navegador por defecto (Unix)
+ label.default_browser_unix_windows = Navegador por defecto (Unix, Windows)
label.send_usage_statistics = Enviar estadísticas de uso
label.check_for_questionnaires = Comprobar los cuestionarios
label.check_for_latest_version = Comprobar la última versión
label.link_name = Nombre del enalce
label.pdb_file = Fichero PDB
label.colour_with_jmol = Colorear con Jmol
+label.jmol = Jmol
label.sort_alignment_by_tree = Ordenar alineamiento por árbol
label.mark_unlinked_leaves = Marcar las hojas como no enlazadas
label.associate_leaves_with = Asociar hojas con
label.variable_color_for = Color variable para la característica de {0}
label.select_background_colour = Seleccionar color de fondo
label.invalid_font = Fuente no válida
+ label.search_db_all = Buscar en todo {0}
+ label.search_db_index = Buscar índice {0} {1}
label.separate_multiple_accession_ids = Separar los accession id con un punto y coma ";"
label.replace_commas_semicolons = Cambiar comas por puntos y comas
label.parsing_failed_syntax_errors_shown_below_param = Parseo erróneo. A continuación, se muestras los errores de sintaxis {0}
label.save_state = Guardar estado
label.restore_state = Restaurar estado
label.saving_jalview_project = Guardando el proyecto de Jalview {0}
+label.loading_jalview_project = Cargando el proyecto de Jalview {0}
label.load_feature_colours = Cargar colores de características
label.save_feature_colours = Guardar esquema cromático de características
label.select_startup_file = Seleccionar fichero de arranque
error.implementation_error_old_jalview_object_not_bound =Error de implementación: ¡el objeto Jalview antiguo no está enlazado! ({0})
error.implementation_error_vamsas_doc_class_should_bind_to_type = Error de implementación: la clase de documento VAMSAS {0} debe enlazar a {1} (pero se ha encontrado que lo está a {2})
error.invalid_vamsas_rangetype_cannot_resolve_lists = RangeType VAMSAS no válido - ¡no es posible resolver ambas listas de Pos y Seg con los valores elegidos!
+error.implementation_error_maplist_is_null = Error de implementación. MapList es nulo en initMapType.
error.implementation_error_cannot_have_null_alignment = Error de implementación: no es posible tener una clave nula en el alineamiento
error.implementation_error_null_fileparse = Error de implementación. FileParse nulo en el construictor de copia
error.implementation_error_structure_selection_manager_null = Error de implementación. El contexto structure selection manager's es nulo
error.implementation_error_msawbjob_called = Error de implementación - StartJob(MsaWSJob) invocado en un WSJobInstance {0}
error.implementation_error_cannot_attach_ws_menu_entry = Error de implementación: ¡no es posible adjunto una WS Menu Entry sin una referencia a un manejador del servicio!
error.parameter_migration_not_implemented_yet = La migración de parámetros no se ha implementado todavía
+error.implementation_error_cannot_set_jaba_option = Error de implementación: no es posible establecer el valor de Jaba Option a un valor fuera de su rango permitido
error.implementation_error_valuetype_doesnt_support_jabaws_type = Error de implementación: jalview.ws.params.ValueConstrainI.ValueType no soporta el tipo JABAWS: {0}
error.cannot_create_jabaws_param_set = No es posible crear un JabaWSParamSet con parámetros no JabaWS
error.cannot_set_arguments_to_jabaws_param_set = No es posible establecer argumentos en JabaWSParamSet que no sean argumentos JabaWS
exception.couldnt_store_sequence_mappings = No es posible almacenar los mapeos de secuencia para {0}
exception.matrix_too_many_iteration = Demasiadas iteraciones en {0} (el máximo es {1})
exception.browser_not_found = Excepción al buscar el navegador: {0}
+ exception.browser_unable_to_launch = Imposible iniciar el navegador: {0}
exception.browser_unable_to_locate = Imposible encontrar el navegador: {0}
+ exception.browser_os_not_supported = No se admite el inicio del navegador en este sistema operativo. Usar URL\n{0}
exception.invocation_target_exception_creating_aedesc = InvocationTargetException mientras se creaba AEDesc: {0}
exception.illegal_access_building_apple_evt= IllegalAccessException mientras se construía AppleEvent: {0}
exception.unable_to_launch_url = Imposible lanzar la URL: {0}
status.fetching_db_refs = Recuperando db refs
label.font_doesnt_have_letters_defined = La fuente no tiene letras definidas\npor lo que no puede emplease\ncon datos de alineamientos
label.font_too_small = Tamaño de la letra es demasiado pequeña
+label.error_loading_file_params = Error cargando el fichero {0}
+label.error_loading_jalview_file = Error cargando el fichero Jalview
warn.out_of_memory_when_action = Sin memoria al {0}\!\!\nConsulte los ficheros de ayuda para ajustar la memoria de la m\u00E1quina virtual de Java.
warn.out_of_memory_loading_file = Sin memoria al cargar el fichero {0}\!\!\nConsulte los ficheros de ayuda para ajustar la memoria de la m\u00E1quina virtual de Java.
label.out_of_memory = Sin memoria
label.add_reference_annotations=Añadir anotaciones de referencia
label.hide_insertions=Ocultar Inserciones
info.change_threshold_mode_to_enable=Cambiar Modo de Umbral para Habilitar
- label.separate_multiple_query_values=Introducir uno o mas {0}s separados por punto y coma ";"
+ label.separate_multiple_query_values=Introducir uno o mas {0} separados por punto y coma ";"
label.fetch_chimera_attributes = Buscar atributos desde Chimera
label.fetch_chimera_attributes_tip = Copiar atributo de Chimera a característica de Jalview
label.view_rna_structure=Estructura 2D VARNA
exception.outofmemory_loading_mmcif_file=Sin memoria al cargar el fichero mmCIF
label.hide_columns_not_containing=Ocultar las columnas que no contengan
label.pdb_sequence_fetcher=Recuperador de secuencias PDB
+status.waiting_for_user_to_select_output_file=Esperando que el usuario seleccione el fichero {0}
action.prev_page=<<
status.cancelled_image_export_operation=Operación de exportación {0} cancelada
label.couldnt_run_groovy_script=No se ha podido ejecutar el script Groovy
option.autosearch = Auto búsqueda
label.retrieve_ids = Recuperar IDs
label.display_settings_for = Visualización de características {0}
+label.simple = Simple
label.simple_colour = Color simple
label.colour_by_text = Colorear por texto
label.graduated_colour = Color graduado
label.backupfiles_confirm_save_new_saved_file_ok = El nuevo archivo guardado parece estar bien.
label.backupfiles_confirm_save_new_saved_file_not_ok = El nuevo archivo guardado podría no estar bien.
label.continue_operation = ¿Continuar operación?
+ label.continue = Continua
label.backups = Respaldos
label.backup = Respaldo
label.backup_files = Archivos de respaldos
label.log_level_tooltip = Establezca temporalmente el nivel de registro para esta consola. El nivel de registro volverá a {0} cuando se cierre esta consola de Java.
label.copy_to_clipboard = Copiar en el portapapeles
label.copy_to_clipboard_tooltip = Copie todo el texto de registro en esta consola al portapapeles del sistema
+ label.startup = Inicio
+ label.memory = Memoria
+ label.customise_memory_settings = Personalizar la configuración de memoria máxima
+ label.memory_setting_text = La nueva configuración de memoria solo entrará en vigor la próxima vez que inicie Jalview
+ label.maximum_memory_used = Memoria máxima limitada a ambos
+ label.percent_of_physical_memory = Porcentaje máximo de memoria física
+ label.maximum_memory = Memoria absoluta máxima
+ label.maximum_memory_tooltip = Ingrese la memoria como un número entero seguido opcionalmente por 'b', 'k', 'm', 'g' o 't'
+ label.adjustments_for_this_computer = Ajustes para esta computadora
+ label.memory_example_text = Memoria máxima que se usaría con esta configuración en esta computadora
+ label.memory_example_tooltip = La memoria asignada a Jalview es el menor entre el porcentaje de memoria física (predeterminado 90%) y la memoria absoluta máxima (predeterminado 32 GB). Si no se puede determinar la memoria de su computadora, la memoria absoluta máxima predeterminada es de 8 GB (si no está personalizada).<br>Jalview siempre intentará reservar 512 MB para el sistema operativo y al menos 512 MB para sí mismo.
+ warning.wrong_jvm_version_title = Versión incorrecta de Java
+ warning.wrong_jvm_version_message = La versión de Java que se está utilizando (Java {0}) puede generar problemas.\nEsta instalación de Jalview debe usarse con Java {1}.
+
import jalview.datamodel.AlignmentAnnotation;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.Annotation;
+import jalview.datamodel.HiddenMarkovModel;
import jalview.datamodel.Profile;
import jalview.datamodel.ProfileI;
import jalview.datamodel.Profiles;
import jalview.datamodel.ResidueCount.SymbolCounts;
import jalview.datamodel.SequenceI;
import jalview.ext.android.SparseIntArray;
+import jalview.schemes.ResidueProperties;
import jalview.util.Comparison;
import jalview.util.Format;
import jalview.util.MappingUtils;
* This class is used extensively in calculating alignment colourschemes that
* depend on the amount of conservation in each alignment column.
*
*/
public class AAFrequency
{
- public static final String PROFILE = "P";
-
- /*
- * Quick look-up of String value of char 'A' to 'Z'
- */
- private static final String[] CHARS = new String['Z' - 'A' + 1];
+ private static final double LOG2 = Math.log(2);
- static
- {
- for (char c = 'A'; c <= 'Z'; c++)
- {
- CHARS[c - 'A'] = String.valueOf(c);
- }
- }
+ public static final String PROFILE = "P";
public static final ProfilesI calculate(List<SequenceI> list, int start,
int end)
}
/**
+ * Returns the full set of profiles for a hidden Markov model. The underlying
+ * data is the raw probabilities of a residue being emitted at each node,
+ * however the profiles returned by this function contain the percentage
+ * chance of a residue emission.
+ *
+ * @param hmm
+ * @param width
+ * The width of the Profile array (Profiles) to be returned.
+ * @param start
+ * The alignment column on which the first profile is based.
+ * @param end
+ * The alignment column on which the last profile is based.
+ * @param removeBelowBackground
+ * if true, symbols with a match emission probability less than
+ * background frequency are ignored
+ * @return
+ */
+ public static ProfilesI calculateHMMProfiles(final HiddenMarkovModel hmm,
+ int width, int start, int end, boolean removeBelowBackground,
+ boolean infoLetterHeight)
+ {
+ ProfileI[] result = new ProfileI[width];
+ char[] symbols = hmm.getSymbols().toCharArray();
+ int symbolCount = symbols.length;
+ for (int column = start; column < end; column++)
+ {
+ ResidueCount counts = new ResidueCount();
+ for (char symbol : symbols)
+ {
+ int value = getAnalogueCount(hmm, column, symbol,
+ removeBelowBackground, infoLetterHeight);
+ counts.put(symbol, value);
+ }
+ int maxCount = counts.getModalCount();
+ String maxResidue = counts.getResiduesForCount(maxCount);
+ int gapCount = counts.getGapCount();
+ ProfileI profile = new Profile(symbolCount, gapCount, maxCount,
+ maxResidue);
+ profile.setCounts(counts);
+
+ result[column] = profile;
+ }
+ return new Profiles(result);
+ }
+
+ /**
* Make an estimate of the profile size we are going to compute i.e. how many
* different characters may be present in it. Overestimating has a cost of
* using more memory than necessary. Underestimating has a cost of needing to
}
/**
- * Derive the gap count annotation row.
+ * Derive the information annotations to be added to the alignment for
+ * display. This does not recompute the raw data, but may be called on a
+ * change in display options, such as 'ignore below background frequency',
+ * which may in turn result in a change in the derived values.
+ *
+ * @param information
+ * the annotation row to add annotations to
+ * @param profiles
+ * the source information data
+ * @param startCol
+ * start column (inclusive)
+ * @param endCol
+ * end column (exclusive)
+ * @param ignoreGaps
+ * if true, normalise residue percentages
+ * @param showSequenceLogo
+ * if true include all information symbols, else just show modal
+ * residue
+ */
+ public static float completeInformation(AlignmentAnnotation information,
+ ProfilesI profiles, int startCol, int endCol)
+ {
+ // long now = System.currentTimeMillis();
+ if (information == null || information.annotations == null)
+ {
+ /*
+ * called with a bad alignment annotation row
+ * wait for it to be initialised properly
+ */
+ return 0;
+ }
+
+ float max = 0f;
+ SequenceI hmmSeq = information.sequenceRef;
+
+ int seqLength = hmmSeq.getLength();
+ if (information.annotations.length < seqLength)
+ {
+ return 0;
+ }
+
+ HiddenMarkovModel hmm = hmmSeq.getHMM();
+
+ for (int column = startCol; column < endCol; column++)
+ {
+ if (column >= seqLength)
+ {
+ // hmm consensus sequence is shorter than the alignment
+ break;
+ }
+
+ float value = hmm.getInformationContent(column);
+ boolean isNaN = Float.isNaN(value);
+ if (!isNaN)
+ {
+ max = Math.max(max, value);
+ }
+
+ String description = isNaN ? null
+ : String.format("%.4f bits", value);
+ information.annotations[column] = new Annotation(
+ Character.toString(
+ Character.toUpperCase(hmmSeq.getCharAt(column))),
+ description, ' ', value);
+ }
+
+ information.graphMax = max;
+ return max;
+ }
+
+ /**
+ * Derive the occupancy count annotation
*
- * @param gaprow
+ * @param occupancy
* the annotation row to add annotations to
* @param profiles
* the source consensus data
* @param endCol
* end column (exclusive)
*/
- public static void completeGapAnnot(AlignmentAnnotation gaprow,
+ public static void completeGapAnnot(AlignmentAnnotation occupancy,
ProfilesI profiles, int startCol, int endCol, long nseq)
{
- if (gaprow == null || gaprow.annotations == null
- || gaprow.annotations.length < endCol)
+ if (occupancy == null || occupancy.annotations == null
+ || occupancy.annotations.length < endCol)
{
/*
* called with a bad alignment annotation row
return;
}
// always set ranges again
- gaprow.graphMax = nseq;
- gaprow.graphMin = 0;
+ occupancy.graphMax = nseq;
+ occupancy.graphMin = 0;
double scale = 0.8 / nseq;
for (int i = startCol; i < endCol; i++)
{
* happens if sequences calculated over were
* shorter than alignment width
*/
- gaprow.annotations[i] = null;
+ occupancy.annotations[i] = null;
return;
}
String description = "" + gapped;
- gaprow.annotations[i] = new Annotation("", description, '\0', gapped,
+ occupancy.annotations[i] = new Annotation("", description, '\0',
+ gapped,
jalview.util.ColorUtils.bleachColour(Color.DARK_GRAY,
(float) scale * gapped));
}
return result;
}
+
/**
* Extract a sorted extract of cDNA codon profile data. The returned array
* contains
* @return
*/
public static int[] extractCdnaProfile(
- Hashtable<String, Object> hashtable,
- boolean ignoreGaps)
+ Hashtable<String, Object> hashtable, boolean ignoreGaps)
{
// this holds #seqs, #ungapped, and then codon count, indexed by encoded
// codon triplet
*/
public static void completeCdnaConsensus(
AlignmentAnnotation consensusAnnotation,
- Hashtable<String, Object>[] consensusData, boolean showProfileLogo,
- int nseqs)
+ Hashtable<String, Object>[] consensusData,
+ boolean showProfileLogo, int nseqs)
{
if (consensusAnnotation == null
|| consensusAnnotation.annotations == null
}
return scale;
}
+
+ /**
+ * Returns the sorted HMM profile for the given column of the alignment. The
+ * returned array contains
+ *
+ * <pre>
+ * [profileType=0, numberOfValues, 100, charValue1, percentage1, charValue2, percentage2, ...]
+ * in descending order of percentage value
+ * </pre>
+ *
+ * @param hmm
+ * @param column
+ * @param removeBelowBackground
+ * if true, ignores residues with probability less than their
+ * background frequency
+ * @param infoHeight
+ * if true, uses the log ratio 'information' measure to scale the
+ * value
+ * @return
+ */
+ public static int[] extractHMMProfile(HiddenMarkovModel hmm, int column,
+ boolean removeBelowBackground, boolean infoHeight)
+ {
+ if (hmm == null)
+ {
+ return null;
+ }
+ String alphabet = hmm.getSymbols();
+ int size = alphabet.length();
+ char symbols[] = new char[size];
+ int values[] = new int[size];
+ int totalCount = 0;
+
+ for (int i = 0; i < size; i++)
+ {
+ char symbol = alphabet.charAt(i);
+ symbols[i] = symbol;
+ int value = getAnalogueCount(hmm, column, symbol,
+ removeBelowBackground, infoHeight);
+ values[i] = value;
+ totalCount += value;
+ }
+
+ /*
+ * sort symbols by increasing emission probability
+ */
+ QuickSort.sort(values, symbols);
+
+ int[] profile = new int[3 + size * 2];
+
+ profile[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
+ profile[1] = size;
+ profile[2] = 100;
+
+ /*
+ * order symbol/count profile by decreasing emission probability
+ */
+ if (totalCount != 0)
+ {
+ int arrayPos = 3;
+ for (int k = size - 1; k >= 0; k--)
+ {
+ Float percentage;
+ int value = values[k];
+ if (removeBelowBackground)
+ {
+ percentage = ((float) value) / totalCount * 100f;
+ }
+ else
+ {
+ percentage = value / 100f;
+ }
+ int intPercent = Math.round(percentage);
+ profile[arrayPos] = symbols[k];
+ profile[arrayPos + 1] = intPercent;
+ arrayPos += 2;
+ }
+ }
+ return profile;
+ }
+
+ /**
+ * Converts the emission probability of a residue at a column in the alignment
+ * to a 'count', suitable for rendering as an annotation value
+ *
+ * @param hmm
+ * @param column
+ * @param symbol
+ * @param removeBelowBackground
+ * if true, returns 0 for any symbol with a match emission
+ * probability less than the background frequency
+ * @infoHeight if true, uses the log ratio 'information content' to scale the
+ * value
+ * @return
+ */
+ static int getAnalogueCount(HiddenMarkovModel hmm, int column,
+ char symbol, boolean removeBelowBackground, boolean infoHeight)
+ {
+ double value = hmm.getMatchEmissionProbability(column, symbol);
+ double freq = ResidueProperties.backgroundFrequencies
+ .get(hmm.getAlphabetType()).get(symbol);
+ if (value < freq && removeBelowBackground)
+ {
+ return 0;
+ }
+
+ if (infoHeight)
+ {
+ value = value * (Math.log(value / freq) / LOG2);
+ }
+
+ value = value * 10000d;
+ return Math.round((float) value);
+ }
}
import java.util.Locale;
+ import java.util.ArrayList;
+ import java.util.Arrays;
+ import java.util.Collection;
+ import java.util.Collections;
+ import java.util.HashMap;
+ import java.util.HashSet;
+ import java.util.Iterator;
+ import java.util.LinkedHashMap;
+ import java.util.List;
+ import java.util.Map;
+ import java.util.Map.Entry;
+ import java.util.NoSuchElementException;
+ import java.util.Set;
+ import java.util.SortedMap;
+ import java.util.TreeMap;
+
+ import jalview.bin.Console;
import jalview.commands.RemoveGapColCommand;
import jalview.datamodel.AlignedCodon;
import jalview.datamodel.AlignedCodonFrame;
import jalview.util.MapList;
import jalview.util.MappingUtils;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Collection;
- import java.util.Collections;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.Iterator;
- import java.util.LinkedHashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.NoSuchElementException;
- import java.util.Set;
- import java.util.SortedMap;
- import java.util.TreeMap;
-
/**
* grab bag of useful alignment manipulation operations Expect these to be
* refactored elsewhere at some point.
.getSequence(s.getStart() - 1 - ustream_ds, s.getStart() - 1))
.toLowerCase(Locale.ROOT).toCharArray();
char[] downstream = new String(
- ds.getSequence(s_end - 1, s_end + dstream_ds)).toLowerCase(Locale.ROOT)
- .toCharArray();
+ ds.getSequence(s_end - 1, s_end + dstream_ds))
+ .toLowerCase(Locale.ROOT).toCharArray();
char[] coreseq = s.getSequence();
char[] nseq = new char[offset + upstream.length + downstream.length
+ coreseq.length];
if (cdnaLength != mappedLength && cdnaLength > 2)
{
String lastCodon = String.valueOf(cdnaSeqChars,
- cdnaLength - CODON_LENGTH, CODON_LENGTH).toUpperCase(Locale.ROOT);
+ cdnaLength - CODON_LENGTH, CODON_LENGTH)
+ .toUpperCase(Locale.ROOT);
for (String stop : ResidueProperties.STOP_CODONS)
{
if (lastCodon.equals(stop))
*/
int startOffset = 0;
if (cdnaLength != mappedLength && cdnaLength > 2
- && String.valueOf(cdnaSeqChars, 0, CODON_LENGTH).toUpperCase(Locale.ROOT)
+ && String.valueOf(cdnaSeqChars, 0, CODON_LENGTH)
+ .toUpperCase(Locale.ROOT)
.equals(ResidueProperties.START))
{
startOffset += CODON_LENGTH;
mapList = mapList.getInverse();
}
final int cdsLength = cdsDss.getLength();
- int mappedFromLength = MappingUtils.getLength(mapList
- .getFromRanges());
+ int mappedFromLength = MappingUtils
+ .getLength(mapList.getFromRanges());
int mappedToLength = MappingUtils
.getLength(mapList.getToRanges());
boolean addStopCodon = (cdsLength == mappedFromLength
final List<AlignmentAnnotation> result = new ArrayList<>();
for (AlignmentAnnotation dsann : datasetAnnotations)
{
- /*
- * Find matching annotations on the alignment. If none is found, then
- * add this annotation to the list of 'addable' annotations for this
- * sequence.
- */
- final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
- .findAnnotations(seq, dsann.getCalcId(), dsann.label);
- if (!matchedAlignmentAnnotations.iterator().hasNext())
+ if (dsann.annotations != null) // ignore non-positional annotation
{
- result.add(dsann);
- if (labelForCalcId != null)
+ /*
+ * Find matching annotations on the alignment. If none is found, then
+ * add this annotation to the list of 'addable' annotations for this
+ * sequence.
+ */
+ final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
+ .findAnnotations(seq, dsann.getCalcId(), dsann.label);
+ if (!matchedAlignmentAnnotations.iterator().hasNext())
{
- labelForCalcId.put(dsann.getCalcId(), dsann.label);
+ result.add(dsann);
+ if (labelForCalcId != null)
+ {
+ labelForCalcId.put(dsann.getCalcId(), dsann.label);
+ }
}
}
- }
- /*
- * Save any addable annotations for this sequence
- */
- if (!result.isEmpty())
- {
- candidates.put(seq, result);
+ /*
+ * Save any addable annotations for this sequence
+ */
+ if (!result.isEmpty())
+ {
+ candidates.put(seq, result);
+ }
}
}
}
productSeqs = new HashSet<>();
for (SequenceI seq : products)
{
- productSeqs.add(seq.getDatasetSequence() == null ? seq : seq
- .getDatasetSequence());
+ productSeqs.add(seq.getDatasetSequence() == null ? seq
+ : seq.getDatasetSequence());
}
}
dataset.addSequence(cdsSeqDss);
AlignedCodonFrame cdsToProteinMapping = new AlignedCodonFrame();
cdsToProteinMapping.addMap(cdsSeqDss, proteinProduct,
- cdsToProteinMap);
+ cdsToProteinMap);
/*
* guard against duplicating the mapping if repeating this action
List<DBRefEntry> primrefs = dnaDss.getPrimaryDBRefs();
for (int ip = 0, np = primrefs.size(); ip < np; ip++)
{
- DBRefEntry primRef = primrefs.get(ip);
+ DBRefEntry primRef = primrefs.get(ip);
/*
* create a cross-reference from CDS to the source sequence's
* primary reference and vice versa
*/
String source = primRef.getSource();
String version = primRef.getVersion();
- DBRefEntry cdsCrossRef = new DBRefEntry(source, source + ":"
- + version, primRef.getAccessionId());
- cdsCrossRef.setMap(new Mapping(dnaDss, new MapList(cdsToDnaMap)));
+ DBRefEntry cdsCrossRef = new DBRefEntry(source,
+ source + ":" + version, primRef.getAccessionId());
+ cdsCrossRef
+ .setMap(new Mapping(dnaDss, new MapList(cdsToDnaMap)));
cdsSeqDss.addDBRef(cdsCrossRef);
- dnaSeq.addDBRef(new DBRefEntry(source, version, cdsSeq
- .getName(), new Mapping(cdsSeqDss, dnaToCdsMap)));
+ dnaSeq.addDBRef(new DBRefEntry(source, version,
+ cdsSeq.getName(), new Mapping(cdsSeqDss, dnaToCdsMap)));
// problem here is that the cross-reference is synthesized -
// cdsSeq.getName() may be like 'CDS|dnaaccession' or
// 'CDS|emblcdsacc'
DBRefEntry proteinToCdsRef = new DBRefEntry(source, version,
cdsSeq.getName());
//
- proteinToCdsRef.setMap(new Mapping(cdsSeqDss, cdsToProteinMap
- .getInverse()));
+ proteinToCdsRef.setMap(
+ new Mapping(cdsSeqDss, cdsToProteinMap.getInverse()));
proteinProduct.addDBRef(proteinToCdsRef);
}
/*
}
}
- AlignmentI cds = new Alignment(cdsSeqs.toArray(new SequenceI[cdsSeqs
- .size()]));
+ AlignmentI cds = new Alignment(
+ cdsSeqs.toArray(new SequenceI[cdsSeqs.size()]));
cds.setDataset(dataset);
return cds;
SequenceI newSeq = null;
- final MapList maplist = mapping.getMap();
- if (maplist.isContiguous() && maplist.isFromForwardStrand())
- {
- /*
- * just a subsequence, keep same dataset sequence
- */
- int start = maplist.getFromLowest();
- int end = maplist.getFromHighest();
- newSeq = seq.getSubSequence(start - 1, end);
- newSeq.setName(seqId);
- }
- else
- {
- /*
- * construct by splicing mapped from ranges
- */
- char[] seqChars = seq.getSequence();
- List<int[]> fromRanges = maplist.getFromRanges();
- int cdsWidth = MappingUtils.getLength(fromRanges);
- char[] newSeqChars = new char[cdsWidth];
+ /*
+ * construct CDS sequence by splicing mapped from ranges
+ */
+ char[] seqChars = seq.getSequence();
+ List<int[]> fromRanges = mapping.getMap().getFromRanges();
+ int cdsWidth = MappingUtils.getLength(fromRanges);
+ char[] newSeqChars = new char[cdsWidth];
- int newPos = 0;
- for (int[] range : fromRanges)
+ int newPos = 0;
+ for (int[] range : fromRanges)
+ {
+ if (range[0] <= range[1])
{
- if (range[0] <= range[1])
- {
- // forward strand mapping - just copy the range
- int length = range[1] - range[0] + 1;
- System.arraycopy(seqChars, range[0] - 1, newSeqChars, newPos,
- length);
- newPos += length;
- }
- else
+ // forward strand mapping - just copy the range
+ int length = range[1] - range[0] + 1;
+ System.arraycopy(seqChars, range[0] - 1, newSeqChars, newPos,
+ length);
+ newPos += length;
+ }
+ else
+ {
+ // reverse strand mapping - copy and complement one by one
+ for (int i = range[0]; i >= range[1]; i--)
{
- // reverse strand mapping - copy and complement one by one
- for (int i = range[0]; i >= range[1]; i--)
- {
- newSeqChars[newPos++] = Dna.getComplement(seqChars[i - 1]);
- }
+ newSeqChars[newPos++] = Dna.getComplement(seqChars[i - 1]);
}
}
}
else
{
- System.err.println(
- "JAL-2154 regression: warning - found (and ignnored a duplicate CDS sequence):"
+ Console.error(
+ "JAL-2154 regression: warning - found (and ignored) a duplicate CDS sequence:"
+ mtch.toString());
}
}
/*
* get features, optionally restricted by an ontology term
*/
- List<SequenceFeature> sfs = select == null ? fromSeq.getFeatures()
- .getPositionalFeatures() : fromSeq.getFeatures()
- .getFeaturesByOntology(select);
+ List<SequenceFeature> sfs = select == null
+ ? fromSeq.getFeatures().getPositionalFeatures()
+ : fromSeq.getFeatures().getFeaturesByOntology(select);
int count = 0;
for (SequenceFeature sf : sfs)
{
List<int[]> result = new ArrayList<>();
- List<SequenceFeature> sfs = dnaSeq.getFeatures().getFeaturesByOntology(
- SequenceOntologyI.CDS);
+ List<SequenceFeature> sfs = dnaSeq.getFeatures()
+ .getFeaturesByOntology(SequenceOntologyI.CDS);
if (sfs.isEmpty())
{
return result;
int phase = 0;
try
{
- String s = sf.getPhase();
- if (s != null)
- {
- phase = Integer.parseInt(s);
- }
+ String s = sf.getPhase();
+ if (s != null)
+ {
+ phase = Integer.parseInt(s);
+ }
} catch (NumberFormatException e)
{
// leave as zero
SequenceIdMatcher matcher = new SequenceIdMatcher(seqs);
if (xrefs != null)
{
- // BH 2019.01.25 recoded to remove iterators
-
+ // BH 2019.01.25 recoded to remove iterators
+
for (int ix = 0, nx = xrefs.length; ix < nx; ix++)
{
- SequenceI xref = xrefs[ix];
+ SequenceI xref = xrefs[ix];
List<DBRefEntry> dbrefs = xref.getDBRefs();
if (dbrefs != null)
{
* true; else returns false
*
* @param unaligned
- * - sequences to be aligned based on aligned
+ * - sequences to be aligned based on aligned
* @param aligned
- * - 'guide' alignment containing sequences derived from same
- * dataset as unaligned
+ * - 'guide' alignment containing sequences derived from same dataset
+ * as unaligned
* @return
*/
static boolean alignAsSameSequences(AlignmentI unaligned,
{
return false;
}
- SequenceI alignedSeq = alignedDatasets.get(ds)
- .get(0);
+ SequenceI alignedSeq = alignedDatasets.get(ds).get(0);
int startCol = alignedSeq.findIndex(seq.getStart()); // 1..
leftmost = Math.min(leftmost, startCol);
}
*/
package jalview.analysis;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
import jalview.datamodel.AlignedCodonFrame;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.SequenceI;
import jalview.util.DBRefUtils;
import jalview.util.MapList;
-import jalview.ws.SequenceFetcherFactory;
-import jalview.ws.seqfetcher.ASequenceFetcher;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
+import jalview.ws.SequenceFetcher;
/**
* Functions for cross-referencing sequence databases.
/*
* first find seq's xrefs (dna-to-peptide or peptide-to-dna)
*/
- List<DBRefEntry> rfs = DBRefUtils.selectDbRefs(!fromDna, seq.getDBRefs());
+ List<DBRefEntry> rfs = DBRefUtils.selectDbRefs(!fromDna,
+ seq.getDBRefs());
addXrefsToSources(rfs, sources);
if (dataset != null)
{
/*
* find sequence's direct (dna-to-dna, peptide-to-peptide) xrefs
*/
- List<DBRefEntry> lrfs = DBRefUtils.selectDbRefs(fromDna, seq.getDBRefs());
+ List<DBRefEntry> lrfs = DBRefUtils.selectDbRefs(fromDna,
+ seq.getDBRefs());
List<SequenceI> foundSeqs = new ArrayList<>();
/*
{
// do a bit more work - search for sequences with references matching
// xrefs on this sequence.
- found = searchDataset(fromDna, dss, xref, rseqs, cf, false, DBRefUtils.SEARCH_MODE_FULL);
+ found = searchDataset(fromDna, dss, xref, rseqs, cf, false,
+ DBRefUtils.SEARCH_MODE_FULL);
}
if (found)
{
private void retrieveCrossRef(List<DBRefEntry> sourceRefs, SequenceI seq,
List<DBRefEntry> xrfs, boolean fromDna, AlignedCodonFrame cf)
{
- ASequenceFetcher sftch = SequenceFetcherFactory.getSequenceFetcher();
SequenceI[] retrieved = null;
SequenceI dss = seq.getDatasetSequence() == null ? seq
: seq.getDatasetSequence();
}
try
{
- retrieved = sftch.getSequences(sourceRefs, !fromDna);
+ retrieved = SequenceFetcher.getInstance().getSequences(sourceRefs, !fromDna);
} catch (Exception e)
{
System.err.println(
addedXref |= importCrossRefSeq(cf, newDsSeqs, doNotAdd, dss,
retrievedDss);
}
+ // JBPNote: What assumptions are made for dbref structures on
+ // retrieved sequences ?
+ // addedXref will be true means importCrossRefSeq found
+ // sequences with dbrefs with mappings to sequences congruent with dss
+
if (!addedXref)
{
// try again, after looking for matching IDs
// protein
if (sq.isProtein() == fromDna)
{
- List<DBRefEntry> sqdbrefs = sq.getPrimaryDBRefs();
+ List<DBRefEntry> sqdbrefs = sq.getPrimaryDBRefs();
for (int idb = 0, ndb = sqdbrefs.size(); idb < ndb; idb++)
{
- DBRefEntry dbr = sqdbrefs.get(idb);
- List<DBRefEntry> searchrefs = DBRefUtils.searchRefs(dbrSourceSet, dbr, DBRefUtils.SEARCH_MODE_FULL);
+ DBRefEntry dbr = sqdbrefs.get(idb);
+ List<DBRefEntry> searchrefs = DBRefUtils.searchRefs(dbrSourceSet,
+ dbr, DBRefUtils.SEARCH_MODE_FULL);
for (int isr = 0, nsr = searchrefs.size(); isr < nsr; isr++)
{
sourceRefs.remove(searchrefs.get(isr));
/**
* process sequence retrieved via a dbref on source sequence to resolve and
- * transfer data
+ * transfer data JBPNote: as of 2022-02-03 - this assumes retrievedSequence
+ * has dbRefs with Mapping references to a sequence congruent with
+ * sourceSequence
*
* @param cf
* @param sourceSequence
List<DBRefEntry> dbr = retrievedSequence.getDBRefs();
if (dbr != null)
{
- for (int ib = 0, nb = dbr.size(); ib < nb; ib++)
+ for (int ib = 0, nb = dbr.size(); ib < nb; ib++)
{
- DBRefEntry dbref = dbr.get(ib);
+ DBRefEntry dbref = dbr.get(ib);
+ // matched will return null if the dbref has no map
SequenceI matched = findInDataset(dbref);
if (matched == sourceSequence)
{
Mapping map = dbref.getMap();
if (map != null)
{
- SequenceI ms = map.getTo();
+ SequenceI ms = map.getTo();
if (ms != null && map.getMap() != null)
{
if (ms == sourceSequence)
/**
* Returns null or the first sequence in the dataset which is identical to
* xref.mapTo, and has a) a primary dbref matching xref, or if none found, the
- * first one with an ID source|xrefacc
+ * first one with an ID source|xrefacc JBPNote: Could refactor this to
+ * AlignmentI/DatasetI
*
* @param xref
* with map and mapped-to sequence
for (SequenceI seq : dataset.getSequences())
{
// first check primary refs.
- List<DBRefEntry> match = DBRefUtils.searchRefs(
- seq.getPrimaryDBRefs(), template, DBRefUtils.SEARCH_MODE_FULL);
+ List<DBRefEntry> match = DBRefUtils.searchRefs(seq.getPrimaryDBRefs(),
+ template, DBRefUtils.SEARCH_MODE_FULL);
if (match != null && match.size() == 1 && sameSequence(seq, dss))
{
return seq;
/**
* Updates any empty mappings in the cross-references with one to a compatible
* retrieved sequence if found, and adds any new mappings to the
- * AlignedCodonFrame
+ * AlignedCodonFrame JBPNote: TODO: this relies on sequence IDs like
+ * UNIPROT|ACCESSION - which do not always happen.
*
* @param mapFrom
* @param xrefs
}
for (int i = 0, n = lrfs.size(); i < n; i++)
{
- // DBRefEntry xref = new DBRefEntry(lrfs.get(i));
- // // add in wildcards
- // xref.setVersion(null);
- // xref.setMap(null);
+ // DBRefEntry xref = new DBRefEntry(lrfs.get(i));
+ // // add in wildcards
+ // xref.setVersion(null);
+ // xref.setMap(null);
found |= searchDataset(fromDna, sequenceI, lrfs.get(i), foundSeqs, cf,
false, DBRefUtils.SEARCH_MODE_NO_MAP_NO_VERSION);
}
* sequenceI or all the returned sequences (eg a genomic reference
* associated with a locus and one or more transcripts)</li>
* </ul>
- * @param mode SEARCH_MODE_FULL for all; SEARCH_MODE_NO_MAP_NO_VERSION optional
+ * @param mode
+ * SEARCH_MODE_FULL for all; SEARCH_MODE_NO_MAP_NO_VERSION optional
* @return true if relationship found and sequence added.
*/
boolean searchDataset(boolean fromDna, SequenceI fromSeq, DBRefEntry xrf,
*/
package jalview.analysis;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+
import jalview.api.AlignViewportI;
import jalview.datamodel.AlignedCodon;
import jalview.datamodel.AlignedCodonFrame;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.Annotation;
import jalview.datamodel.DBRefEntry;
-import jalview.datamodel.DBRefSource;
import jalview.datamodel.FeatureProperties;
import jalview.datamodel.GraphLine;
import jalview.datamodel.Mapping;
import jalview.util.MapList;
import jalview.util.ShiftList;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.Iterator;
-import java.util.List;
-
public class Dna
{
private static final String STOP_ASTERIX = "*";
* @param ac2
* @return
*/
- public static final int compareCodonPos(AlignedCodon ac1, AlignedCodon ac2)
+ public static final int compareCodonPos(AlignedCodon ac1,
+ AlignedCodon ac2)
{
return comparator.compare(ac1, ac2);
// return jalview_2_8_2compare(ac1, ac2);
mappedrefs.add(ref); // add translated protein maps
}
}
- dnarefs = mappedrefs;//.toArray(new DBRefEntry[mappedrefs.size()]);
+ dnarefs = mappedrefs;// .toArray(new DBRefEntry[mappedrefs.size()]);
for (int d = 0, nd = dnarefs.size(); d < nd; d++)
{
Mapping mp = dnarefs.get(d).getMap();
/*
* Filled up a reading frame...
*/
- AlignedCodon alignedCodon = new AlignedCodon(cdp[0], cdp[1], cdp[2]);
+ AlignedCodon alignedCodon = new AlignedCodon(cdp[0], cdp[1],
+ cdp[2]);
String aa = codeTable.translate(new String(codon));
rf = 0;
final String gapString = String.valueOf(gapChar);
private static void transferCodedFeatures(SequenceI dna, SequenceI pep,
MapList map)
{
- // BH 2019.01.25 nop?
- // List<DBRefEntry> dnarefs = DBRefUtils.selectRefs(dna.getDBRefs(),
- // DBRefSource.DNACODINGDBS);
- // if (dnarefs != null)
- // {
- // // intersect with pep
- // for (int d = 0, nd = dnarefs.size(); d < nd; d++)
- // {
- // Mapping mp = dnarefs.get(d).getMap();
- // if (mp != null)
- // {
- // }
- // }
- // }
+ // BH 2019.01.25 nop?
+ // List<DBRefEntry> dnarefs = DBRefUtils.selectRefs(dna.getDBRefs(),
+ // DBRefSource.DNACODINGDBS);
+ // if (dnarefs != null)
+ // {
+ // // intersect with pep
+ // for (int d = 0, nd = dnarefs.size(); d < nd; d++)
+ // {
+ // Mapping mp = dnarefs.get(d).getMap();
+ // if (mp != null)
+ // {
+ // }
+ // }
+ // }
for (SequenceFeature sf : dna.getFeatures().getAllFeatures())
{
- if (FeatureProperties.isCodingFeature(null, sf.getType()))
+ if (FeatureProperties.isCodingFeature(null, sf.getType()))
+ {
+ // if (map.intersectsFrom(sf[f].begin, sf[f].end))
{
- // if (map.intersectsFrom(sf[f].begin, sf[f].end))
- {
- }
}
+ }
}
}
import jalview.datamodel.SequenceGroup;
import jalview.datamodel.SequenceI;
import jalview.util.Comparison;
+import jalview.util.Platform;
import jalview.util.MapList;
import java.util.ArrayList;
{
doFind(theSearchString, matchCase, searchDescription, false,
ignoreHidden);
-
+
if (searchResults.isEmpty() && idMatches.isEmpty())
{
/*
String searchString = matchCase ? theSearchString
: theSearchString.toUpperCase(Locale.ROOT);
- Regex searchPattern = new Regex(searchString);
+ Regex searchPattern = Platform.newRegex(searchString);
searchPattern.setIgnoreCase(!matchCase);
SequenceGroup selection = viewport.getSelectionGroup();
}
/**
- * Calculates and saves the sequence string to search. The string is restricted
- * to the current selection region if there is one, and is saved with all gaps
- * removed.
+ * Calculates and saves the sequence string to search. The string is
+ * restricted to the current selection region if there is one, and is saved
+ * with all gaps removed.
* <p>
* If there are hidden columns, and option {@ignoreHidden} is selected, then
* only visible positions of the sequence are included, and a mapping is also
}
/**
- * Returns a string consisting of only the visible residues of {@code seq} from
- * alignment column {@ fromColumn}, restricted to the current selection region
- * if there is one.
+ * Returns a string consisting of only the visible residues of {@code seq}
+ * from alignment column {@ fromColumn}, restricted to the current selection
+ * region if there is one.
* <p>
- * As a side-effect, also computes the mapping from the true sequence positions
- * to the positions (1, 2, ...) of the returned sequence. This is to allow
- * search matches in the visible sequence to be converted to sequence positions.
+ * As a side-effect, also computes the mapping from the true sequence
+ * positions to the positions (1, 2, ...) of the returned sequence. This is to
+ * allow search matches in the visible sequence to be converted to sequence
+ * positions.
*
* @param seq
* @return
/**
* Advances the search to the next sequence in the alignment. Sequences not in
- * the current selection group (if there is one) are skipped. The (sub-)sequence
- * to be searched is extracted, gaps removed, and saved, or set to null if there
- * are no more sequences to search.
+ * the current selection group (if there is one) are skipped. The
+ * (sub-)sequence to be searched is extracted, gaps removed, and saved, or set
+ * to null if there are no more sequences to search.
* <p>
* Returns true if a sequence could be found, false if end of alignment was
* reached
* @param ignoreHidden
* @return
*/
- protected boolean findNextMatch(String searchString,
- Regex searchPattern, boolean matchDescription,
- boolean ignoreHidden)
+ protected boolean findNextMatch(String searchString, Regex searchPattern,
+ boolean matchDescription, boolean ignoreHidden)
{
if (residueIndex < 0)
{
* at start of sequence; try find by residue number, in sequence id,
* or (optionally) in sequence description
*/
- if (doNonMotifSearches(searchString, searchPattern,
- matchDescription))
+ if (doNonMotifSearches(searchString, searchPattern, matchDescription))
{
return true;
}
*/
int offset = searchPattern.matchedFrom();
int matchStartPosition = this.searchedSequenceStartPosition + offset;
- int matchEndPosition = matchStartPosition
- + searchPattern.charsMatched() - 1;
+ int matchEndPosition = matchStartPosition + searchPattern.charsMatched()
+ - 1;
/*
* update residueIndex to next position after the start of the match
* (findIndex returns a value base 1, columnIndex is held base 0)
*/
- residueIndex = searchPattern.matchedFrom()+1;
+ residueIndex = searchPattern.matchedFrom() + 1;
/*
* return false if the match is entirely in a hidden region
}
/**
- * Adds one match to the stored list. If hidden residues are being skipped, then
- * the match may need to be split into contiguous positions of the sequence (so
- * it does not include skipped residues).
+ * Adds one match to the stored list. If hidden residues are being skipped,
+ * then the match may need to be split into contiguous positions of the
+ * sequence (so it does not include skipped residues).
*
* @param seq
* @param matchStartPosition
* @param searchPattern
* @return
*/
- protected boolean searchSequenceDescription(SequenceI seq, Regex searchPattern)
+ protected boolean searchSequenceDescription(SequenceI seq,
+ Regex searchPattern)
{
String desc = seq.getDescription();
- if (desc != null && searchPattern.search(desc) && !idMatches.contains(seq))
+ if (desc != null && searchPattern.search(desc)
+ && !idMatches.contains(seq))
{
idMatches.add(seq);
return true;
/**
* If the residue position is valid for the sequence, and in a visible column,
- * adds the position to the search results and returns true, else answers false.
+ * adds the position to the search results and returns true, else answers
+ * false.
*
* @param seq
* @param resNo
return true;
}
int col = seq.findIndex(res); // base 1
- return viewport.getAlignment().getHiddenColumns().isVisible(col - 1); // base 0
+ return viewport.getAlignment().getHiddenColumns().isVisible(col - 1); // base
+ // 0
}
@Override
*/
package jalview.analysis;
+import jalview.bin.Cache;
++import jalview.bin.Console;
+import jalview.datamodel.AlignmentAnnotation;
+import jalview.datamodel.HiddenMarkovModel;
import jalview.datamodel.PDBEntry;
import jalview.datamodel.Sequence;
import jalview.datamodel.SequenceFeature;
import jalview.datamodel.SequenceI;
+import java.util.ArrayList;
import java.util.Enumeration;
+import java.util.HashMap;
import java.util.Hashtable;
+import java.util.Iterator;
import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
import java.util.Vector;
+import static java.lang.String.format;
public class SeqsetUtils
{
+ public static class SequenceInfo {
+ private String name;
+ private int start;
+ private int end;
+ private Optional<String> description = Optional.empty();
+ private Optional<List<SequenceFeature>> features = Optional.empty();
+ private Optional<List<PDBEntry>> pdbId = Optional.empty();
+ private Optional<SequenceI> dataset = Optional.empty();
+ private Optional<HiddenMarkovModel> hmm = Optional.empty();
+ private Optional<AlignmentAnnotation[]> searchScores = Optional.empty();
+
+ private SequenceInfo(String name, int start, int end) {
+ this.name = name;
+ this.start = start;
+ this.end = end;
+ }
+ }
/**
* Store essential properties of a sequence in a hashtable for later recovery
- * Keys are Name, Start, End, SeqFeatures, PdbId
+ * Keys are Name, Start, End, SeqFeatures, PdbId, HMM
*
* @param seq
* SequenceI
* @return Hashtable
*/
- public static Hashtable SeqCharacterHash(SequenceI seq)
+ public static SequenceInfo SeqCharacterHash(SequenceI seq)
{
- Hashtable sqinfo = new Hashtable();
- sqinfo.put("Name", seq.getName());
- sqinfo.put("Start", Integer.valueOf(seq.getStart()));
- sqinfo.put("End", Integer.valueOf(seq.getEnd()));
- if (seq.getDescription() != null)
- {
- sqinfo.put("Description", seq.getDescription());
- }
-
- Vector<SequenceFeature> sfeat = new Vector<SequenceFeature>();
- List<SequenceFeature> sfs = seq.getFeatures().getAllFeatures();
- sfeat.addAll(sfs);
-
- if (seq.getDatasetSequence() == null)
+ SequenceInfo sqinfo = new SequenceInfo(seq.getName(), seq.getStart(), seq.getEnd());
+ sqinfo.description = Optional.ofNullable(seq.getDescription());
+ sqinfo.dataset = Optional.ofNullable(seq.getDatasetSequence());
+ if (!sqinfo.dataset.isPresent())
{
- sqinfo.put("SeqFeatures", sfeat);
- sqinfo.put("PdbId",
- (seq.getAllPDBEntries() != null) ? seq.getAllPDBEntries()
- : new Vector<PDBEntry>());
+ ArrayList<SequenceFeature> feats = new ArrayList<>(
+ seq.getFeatures().getAllFeatures());
+ sqinfo.features = Optional.of(feats);
+ sqinfo.pdbId = Optional.of(Objects.requireNonNullElse(
+ seq.getAllPDBEntries(), new ArrayList<>()));
}
- else
+ if (seq.hasHMMProfile())
{
- sqinfo.put("datasetSequence",
- (seq.getDatasetSequence() != null) ? seq.getDatasetSequence()
- : new Sequence("THISISAPLACEHOLDER", ""));
+ sqinfo.hmm = Optional.of(seq.getHMM());
}
+ sqinfo.searchScores = Optional.ofNullable(seq.getAnnotation("Search Scores"));
return sqinfo;
}
* Hashtable
* @return boolean true if name was not updated from sqinfo Name entry
*/
- public static boolean SeqCharacterUnhash(SequenceI sq, Hashtable sqinfo)
+ public static boolean SeqCharacterUnhash(SequenceI sq, SequenceInfo sqinfo)
{
- boolean namePresent = true;
if (sqinfo == null)
{
return false;
}
- String oldname = (String) sqinfo.get("Name");
- Integer start = (Integer) sqinfo.get("Start");
- Integer end = (Integer) sqinfo.get("End");
- Vector<SequenceFeature> sfeatures = (Vector<SequenceFeature>) sqinfo
- .get("SeqFeatures");
- Vector<PDBEntry> pdbid = (Vector<PDBEntry>) sqinfo.get("PdbId");
- String description = (String) sqinfo.get("Description");
- Sequence seqds = (Sequence) sqinfo.get("datasetSequence");
- if (oldname == null)
- {
- namePresent = false;
- }
- else
+ if (sqinfo.name != null)
{
- sq.setName(oldname);
+ sq.setName(sqinfo.name);
}
- if (pdbid != null && pdbid.size() > 0)
- {
- sq.setPDBId(pdbid);
- }
-
- if ((start != null) && (end != null))
+ sq.setStart(sqinfo.start);
+ sq.setEnd(sqinfo.end);
+ if (sqinfo.pdbId.isPresent() && !sqinfo.pdbId.get().isEmpty())
+ sq.setPDBId(new Vector<>(sqinfo.pdbId.get()));
+ if (sqinfo.features.isPresent() && !sqinfo.features.get().isEmpty())
+ sq.setSequenceFeatures(sqinfo.features.get());
+ if (sqinfo.description.isPresent())
+ sq.setDescription(sqinfo.description.get());
+ if (sqinfo.dataset.isPresent())
{
- sq.setStart(start.intValue());
- sq.setEnd(end.intValue());
- }
-
- if (sfeatures != null && !sfeatures.isEmpty())
- {
- sq.setSequenceFeatures(sfeatures);
- }
- if (description != null)
- {
- sq.setDescription(description);
+ if (sqinfo.features.isPresent())
+ {
- Cache.log.warn("Setting dataset sequence for a sequence which has " +
++ Console.warn("Setting dataset sequence for a sequence which has " +
+ "sequence features. Dataset sequence features will not be visible.");
+ assert false;
+ }
+ sq.setDatasetSequence(sqinfo.dataset.get());
}
- if ((seqds != null) && !(seqds.getName().equals("THISISAPLACEHOLDER")
- && seqds.getLength() == 0))
+ if (sqinfo.hmm.isPresent())
+ sq.setHMM(new HiddenMarkovModel(sqinfo.hmm.get(), sq));
+ if (sqinfo.searchScores.isPresent())
{
- if (sfeatures != null)
+ for (AlignmentAnnotation score : sqinfo.searchScores.get())
{
- System.err.println(
- "Implementation error: setting dataset sequence for a sequence which has sequence features.\n\tDataset sequence features will not be visible.");
+ sq.addAlignmentAnnotation(score);
}
- sq.setDatasetSequence(seqds);
}
-
- return namePresent;
+ return sqinfo.name != null;
}
/**
*/
public static String unique_name(int i)
{
- return new String("Sequence" + i);
+ return String.format("Sequence%d", i);
}
/**
* @see deuniquify to recover original names (and properties) for renamed
* sequences
*/
- public static Hashtable uniquify(SequenceI[] sequences,
+ public static Map<String, SequenceInfo> uniquify(SequenceI[] sequences,
boolean write_names)
{
// Generate a safely named sequence set and a hash to recover the sequence
// names
- Hashtable map = new Hashtable();
+ HashMap<String, SequenceInfo> map = new HashMap<>();
// String[] un_names = new String[sequences.length];
for (int i = 0; i < sequences.length; i++)
* SequenceI[]
* @return boolean
*/
- public static boolean deuniquify(Hashtable map, SequenceI[] sequences)
+ public static boolean deuniquify(Map<String, SequenceInfo> map,
+ SequenceI[] sequences)
{
return deuniquify(map, sequences, true);
}
* map.
* @return boolean
*/
- public static boolean deuniquify(Hashtable map, SequenceI[] sequences,
- boolean quiet)
+ public static boolean deuniquify(Map<String, SequenceInfo> map,
+ SequenceI[] sequences, boolean quiet)
{
jalview.analysis.SequenceIdMatcher matcher = new SequenceIdMatcher(
sequences);
SequenceI msq = null;
- Enumeration keys = map.keys();
- Vector unmatched = new Vector();
+ Iterator<String> keys = map.keySet().iterator();
+ Vector<SequenceI> unmatched = new Vector<>();
for (int i = 0, j = sequences.length; i < j; i++)
{
unmatched.addElement(sequences[i]);
}
- while (keys.hasMoreElements())
+ while (keys.hasNext())
{
- Object key = keys.nextElement();
- if (key instanceof String)
- {
+ String key = keys.next();
+ try {
if ((msq = matcher.findIdMatch((String) key)) != null)
{
- Hashtable sqinfo = (Hashtable) map.get(key);
+ SequenceInfo sqinfo = map.get(key);
unmatched.removeElement(msq);
SeqCharacterUnhash(msq, sqinfo);
}
{
if (!quiet)
{
- Cache.log.warn(format("Can't find '%s' in uniquified alignment",
- System.err.println("Can't find '" + ((String) key)
- + "' in uniquified alignment");
++ Console.warn(format("Can't find '%s' in uniquified alignment",
+ key));
}
}
+ } catch (ClassCastException ccastex) {
+ if (!quiet)
+ {
- Cache.log.error("Unexpected object in SeqSet map : "+ key.getClass());
++ Console.error("Unexpected object in SeqSet map : "+ key.getClass());
+ }
}
}
if (unmatched.size() > 0 && !quiet)
{
- System.err.println("Did not find matches for :");
- for (Enumeration i = unmatched.elements(); i
- .hasMoreElements(); System.out
- .println(((SequenceI) i.nextElement()).getName()))
+ StringBuilder sb = new StringBuilder("Did not find match for sequences: ");
+ Enumeration<SequenceI> i = unmatched.elements();
+ sb.append(i.nextElement().getName());
+ for (; i.hasMoreElements();)
{
- ;
+ sb.append(", " + i.nextElement().getName());
}
- Cache.log.warn(sb.toString());
++ Console.warn(sb.toString());
return false;
}
*
* @return
*/
- public ViewportRanges getRanges();
+ ViewportRanges getRanges();
/**
* calculate the height for visible annotation, revalidating bounds where
*
* @return total height of annotation
*/
- public int calcPanelHeight();
+ int calcPanelHeight();
/**
* Answers true if the viewport has at least one column selected
boolean isNormaliseSequenceLogo();
+ boolean isShowInformationHistogram();
+
+ boolean isShowHMMSequenceLogo();
+
+ boolean isNormaliseHMMSequenceLogo();
+
ColourSchemeI getGlobalColourScheme();
/**
boolean isIgnoreGapsConsensus();
+ boolean isIgnoreBelowBackground();
+
boolean isCalculationInProgress(AlignmentAnnotation alignmentAnnotation);
AlignmentAnnotation getAlignmentQualityAnnot();
*
* @return
*/
- AlignCalcManagerI getCalcManager();
+ AlignCalcManagerI2 getCalcManager();
/**
* get the percentage gaps allowed in a conservation calculation
@Override
void setProteinFontAsCdna(boolean b);
- TreeModel getCurrentTree();
+ void setHmmProfiles(ProfilesI info);
- void setCurrentTree(TreeModel tree);
+ ProfilesI getHmmProfiles();
+
+ /**
+ * Registers and starts a worker thread to calculate Information Content
+ * annotation, if it is not already registered
+ *
+ * @param ap
+ */
+ void initInformationWorker(AlignmentViewPanel ap);
+
+ boolean isInfoLetterHeight();
+
+ public abstract TreeModel getCurrentTree();
/**
* Answers a data bean containing data for export as configured by the
*/
AlignmentExportData getAlignExportData(AlignExportSettingsI options);
+ public abstract void setCurrentTree(TreeModel tree);
+
/**
* @param update
* - set the flag for updating structures on next repaint
* regions of the alignment
*
* @param selectedRegionOnly
- * if true, and the view has a selection region,
- * then only the intersection of visible columns
- * with the selection region is returned
+ * if true, and the view has a selection region, then only the
+ * intersection of visible columns with the selection region is
+ * returned
* @return
*/
Iterator<int[]> getViewAsVisibleContigs(boolean selectedRegionOnly);
ap.alignFrame.addHistoryItem(editCommand);
- ap.av.firePropertyChange("alignment", null,
- ap.av.getAlignment().getSequences());
+ ap.av.notifyAlignment();
}
}
}
ap.alignFrame.addHistoryItem(caseCommand);
- ap.av.firePropertyChange("alignment", null,
- ap.av.getAlignment().getSequences());
+ ap.av.notifyAlignment();
}
}
if (start <= end)
{
seqs.add(sg.getSequenceAt(i));
- features.add(new SequenceFeature(null, null, start, end,
- "Jalview"));
+ features.add(
+ new SequenceFeature(null, null, start, end, "Jalview"));
}
}
}
else
{
- new mc_view.AppletPDBViewer(entry, new SequenceI[] { seq }, null, ap,
- DataSourceType.URL);
+ new mc_view.AppletPDBViewer(entry, new SequenceI[] { seq }, null,
+ ap, DataSourceType.URL);
}
}
hydrophobicityColour
.setName(JalviewColourScheme.Hydrophobic.toString());
hydrophobicityColour.addItemListener(this);
- helixColour.setLabel(MessageManager
- .getString("label.colourScheme_helixpropensity"));
+ helixColour.setLabel(
+ MessageManager.getString("label.colourScheme_helixpropensity"));
helixColour.setName(JalviewColourScheme.Helix.toString());
helixColour.addItemListener(this);
strandColour.setLabel(MessageManager
alignPanel);
viewport.updateConservation(alignPanel);
viewport.updateConsensus(alignPanel);
+ viewport.initInformationWorker(alignPanel);
displayNonconservedMenuItem.setState(viewport.getShowUnconserved());
followMouseOverFlag.setState(viewport.isFollowHighlight());
case KeyEvent.VK_F2:
viewport.cursorMode = !viewport.cursorMode;
- setStatus(MessageManager
- .formatMessage("label.keyboard_editing_mode", new String[]
+ setStatus(MessageManager.formatMessage("label.keyboard_editing_mode",
+ new String[]
{ (viewport.cursorMode ? "on" : "off") }));
if (viewport.cursorMode)
{
}
else if (source == autoCalculate)
{
- viewport.autoCalculateConsensus = autoCalculate.getState();
+ viewport.setAutoCalculateConsensusAndConservation(autoCalculate.getState());
}
else if (source == sortByTree)
{
{
sortGroupMenuItem_actionPerformed();
}
+ else if (source == sortEValueMenuItem)
+ {
+ sortEValueMenuItem_actionPerformed();
+ }
+ else if (source == sortBitScoreMenuItem)
+ {
+ sortBitScoreMenuItem_actionPerformed();
+ }
else if (source == removeRedundancyMenuItem)
{
removeRedundancyMenuItem_actionPerformed();
}
else
{
- features = formatter.printGffFormat(viewport.getAlignment()
- .getSequencesArray(), alignPanel.getFeatureRenderer(), true,
- false);
+ features = formatter.printGffFormat(
+ viewport.getAlignment().getSequencesArray(),
+ alignPanel.getFeatureRenderer(), true, false);
}
if (displayTextbox)
catch (java.net.MalformedURLException ex)
{
url = viewport.applet.getCodeBase() + url;
- }
- catch (UnsupportedEncodingException ex)
+ } catch (UnsupportedEncodingException ex)
{
System.err.println(
"WARNING = IMPLEMENTATION ERROR - UNSUPPORTED ENCODING EXCEPTION FOR "
// viewport.getColumnSelection().getHiddenColumns()
// != null;
updateEditMenuBar();
- originalSource.firePropertyChange("alignment", null,
- originalSource.getAlignment().getSequences());
+ originalSource.notifyAlignment();
}
/**
// != null;
updateEditMenuBar();
- originalSource.firePropertyChange("alignment", null,
- originalSource.getAlignment().getSequences());
+ originalSource.notifyAlignment();
}
AlignmentViewport getOriginatingSource(CommandI command)
viewport.getRanges().setEndSeq(viewport.getAlignment().getHeight() - 1); // BH
// 2019.04.18
viewport.getAlignment().getWidth();
- viewport.firePropertyChange("alignment", null,
- viewport.getAlignment().getSequences());
+ viewport.notifyAlignment();
}
viewport.setSelectionGroup(null);
viewport.getAlignment().deleteGroup(sg);
- viewport.firePropertyChange("alignment", null,
- viewport.getAlignment().getSequences());
+ viewport.notifyAlignment();
if (viewport.getAlignment().getHeight() < 1)
{
column, al);
}
- setStatus(MessageManager
- .formatMessage("label.removed_columns", new String[]
+ setStatus(MessageManager.formatMessage("label.removed_columns",
+ new String[]
{ Integer.valueOf(trimRegion.getSize()).toString() }));
addHistoryItem(trimRegion);
}
}
- viewport.firePropertyChange("alignment", null, al.getSequences());
+ viewport.notifyAlignment();
}
}
addHistoryItem(removeGapCols);
- setStatus(MessageManager
- .formatMessage("label.removed_empty_columns", new String[]
+ setStatus(MessageManager.formatMessage("label.removed_empty_columns",
+ new String[]
{ Integer.valueOf(removeGapCols.getSize()).toString() }));
// This is to maintain viewport position on first residue
// if (viewport.hasHiddenColumns)
// viewport.getColumnSelection().compensateForEdits(shifts);
ranges.setStartRes(seq.findIndex(startRes) - 1);
- viewport.firePropertyChange("alignment", null, al.getSequences());
+ viewport.notifyAlignment();
}
ranges.setStartRes(seq.findIndex(startRes) - 1);
- viewport.firePropertyChange("alignment", null, al.getSequences());
+ viewport.notifyAlignment();
}
}
+ public void sortEValueMenuItem_actionPerformed()
+ {
+ SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
+ AlignmentSorter.sortByEValue(viewport.getAlignment());
+ addHistoryItem(new OrderCommand("Group Sort", oldOrder,
+ viewport.getAlignment()));
+ alignPanel.paintAlignment(true, false);
+
+ }
+
+ public void sortBitScoreMenuItem_actionPerformed()
+ {
+ SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
+ AlignmentSorter.sortByBitScore(viewport.getAlignment());
+ addHistoryItem(new OrderCommand("Group Sort", oldOrder,
+ viewport.getAlignment()));
+ alignPanel.paintAlignment(true, false);
+
+ }
+
public void removeRedundancyMenuItem_actionPerformed()
{
new RedundancyPanel(alignPanel);
MenuItem sortGroupMenuItem = new MenuItem();
+ MenuItem sortEValueMenuItem = new MenuItem();
+
+ MenuItem sortBitScoreMenuItem = new MenuItem();
+
MenuItem removeRedundancyMenuItem = new MenuItem();
MenuItem pairwiseAlignmentMenuItem = new MenuItem();
hydrophobicityColour.setLabel(
MessageManager.getString("label.colourScheme_hydrophobic"));
hydrophobicityColour.addActionListener(this);
- helixColour.setLabel(MessageManager
- .getString("label.colourScheme_helixpropensity"));
+ helixColour.setLabel(
+ MessageManager.getString("label.colourScheme_helixpropensity"));
helixColour.addActionListener(this);
strandColour.setLabel(MessageManager
.getString("label.colourScheme_strandpropensity"));
{
// register the association(s) and quit, don't create any windows.
if (StructureSelectionManager.getStructureSelectionManager(applet)
- .setMapping(seqs, chains, pdb.getFile(), protocol, null) == null)
+ .setMapping(seqs, chains, pdb.getFile(), protocol,
+ null) == null)
{
System.err.println("Failed to map " + pdb.getFile() + " ("
+ protocol + ") to any sequences");
/*
- * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
* Copyright (C) $$Year-Rel$$ The Jalview Authors
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
*
* This file is part of Jalview.
*
private AnnotationColumnChooser annotationColumnSelectionState;
+ java.awt.Frame nullFrame;
+
+ protected FeatureSettings featureSettings = null;
+
+ private float heightScale = 1, widthScale = 1;
+
public AlignViewport(AlignmentI al, JalviewLite applet)
{
super(al);
- calculator = new jalview.workers.AlignCalcManager();
+ calculator = new jalview.workers.AlignCalcManager2();
this.applet = applet;
// we always pad gaps
if (colour != null)
{
- residueShading = new ResidueShader(
- ColourSchemeProperty.getColourScheme(this, alignment,
- colour));
+ residueShading = new ResidueShader(ColourSchemeProperty
+ .getColourScheme(this, alignment, colour));
if (residueShading != null)
{
- residueShading.setConsensus(hconsensus);
+ residueShading.setConsensus(consensusProfiles);
}
}
}
}
initAutoAnnotation();
-
}
- java.awt.Frame nullFrame;
-
- protected FeatureSettings featureSettings = null;
-
- private float heightScale = 1, widthScale = 1;
-
/**
* {@inheritDoc}
*/
.getStructureSelectionManager(applet);
}
- @Override
- public boolean isNormaliseSequenceLogo()
- {
- return normaliseSequenceLogo;
- }
-
- public void setNormaliseSequenceLogo(boolean state)
- {
- normaliseSequenceLogo = state;
- }
-
/**
*
* @return true if alignment characters should be displayed
if (mappedCommand != null)
{
mappedCommand.doCommand(null);
- firePropertyChange("alignment", null, getAlignment().getSequences());
+ notifyAlignment();
// ap.scalePanelHolder.repaint();
// ap.repaint();
}
/**
- * Applies the supplied feature settings descriptor to currently known features.
- * This supports an 'initial configuration' of feature colouring based on a
- * preset or user favourite. This may then be modified in the usual way using
- * the Feature Settings dialogue. NOT IMPLEMENTED FOR APPLET
+ * Applies the supplied feature settings descriptor to currently known
+ * features. This supports an 'initial configuration' of feature colouring
+ * based on a preset or user favourite. This may then be modified in the usual
+ * way using the Feature Settings dialogue. NOT IMPLEMENTED FOR APPLET
*
* @param featureSettings
*/
}
/**
- * Merges the supplied feature settings descriptor with existing feature styles.
- * This supports an 'initial configuration' of feature colouring based on a
- * preset or user favourite. This may then be modified in the usual way using
- * the Feature Settings dialogue. NOT IMPLEMENTED FOR APPLET
+ * Merges the supplied feature settings descriptor with existing feature
+ * styles. This supports an 'initial configuration' of feature colouring based
+ * on a preset or user favourite. This may then be modified in the usual way
+ * using the Feature Settings dialogue. NOT IMPLEMENTED FOR APPLET
*
* @param featureSettings
*/
public boolean scrollTo(int ostart, int end, int seqIndex,
boolean scrollToNearest, boolean redrawOverview)
{
- int startv, endv, starts, ends;//, width;
+ int startv, endv, starts, ends;// , width;
int start = -1;
if (av.hasHiddenColumns())
// this is called after loading new annotation onto alignment
if (alignFrame.getSize().height == 0)
{
- System.out.println(
- "adjustAnnotationHeight frame size zero NEEDS FIXING");
+ // panel not laid out yet?
+ return;
}
fontChanged();
validateAnnotationDimensions(true);
import java.awt.event.MouseMotionListener;
import java.beans.PropertyChangeEvent;
+import jalview.datamodel.AlignmentAnnotation;
+import jalview.datamodel.Annotation;
+import jalview.datamodel.SequenceI;
+import jalview.renderer.AnnotationRenderer;
+import jalview.renderer.AwtRenderPanelI;
+import jalview.schemes.ResidueProperties;
+import jalview.util.Comparison;
+import jalview.util.MessageManager;
+import jalview.viewmodel.ViewportListenerI;
+import jalview.viewmodel.ViewportRanges;
+
public class AnnotationPanel extends Panel
implements AwtRenderPanelI, AdjustmentListener, ActionListener,
MouseListener, MouseMotionListener, ViewportListenerI
public static int GRAPH_HEIGHT = 40;
- // boolean MAC = false;
+ // boolean MAC = false;
public final AnnotationRenderer renderer;
public AnnotationPanel(AlignmentPanel ap)
{
new jalview.util.Platform();
- // MAC = Platform.isAMac();
+ // MAC = Platform.isAMac();
this.ap = ap;
av = ap.av;
setLayout(null);
od = new OverviewDimensionsShowHidden(av.getRanges(),
(av.isShowAnnotation()
- && av.getSequenceConsensusHash() != null));
+ && av.getSequenceConsensusHash() != null));
oviewCanvas = new OverviewCanvas(od, av);
setLayout(new BorderLayout());
}
else
{
- this.getParent()
- .setCursor(
- Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
+ this.getParent().setCursor(
+ Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
}
}
// (wait to see if it's a drag instead)
// otherwise update the viewport
if (!od.isPositionInBox(evt.getX(), evt.getY()))
- {
- draggingBox = false;
+ {
+ draggingBox = false;
// display drag cursor at mouse position
setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
@Override
public void mouseDragged(MouseEvent evt)
{
- if (Platform.isWinRightButton(evt))
+ if (Platform.isWinRightButton(evt))
{
- showPopupMenu(evt);
- return;
+ showPopupMenu(evt);
+ return;
}
if (SwingUtilities.isRightMouseButton(evt))
- {
- return;
+ {
+ return;
+ }
+
+ if (draggingBox)
+ {
+ // set the mouse position as a fixed point in the box
+ // and drag relative to that position
+ od.adjustViewportFromMouse(evt.getX(), evt.getY(),
+ av.getAlignment().getHiddenSequences(),
+ av.getAlignment().getHiddenColumns());
+ }
+ else
+ {
+ od.updateViewportFromMouse(evt.getX(), evt.getY(),
+ av.getAlignment().getHiddenSequences(),
+ av.getAlignment().getHiddenColumns());
}
-
- if (draggingBox)
- {
- // set the mouse position as a fixed point in the box
- // and drag relative to that position
- od.adjustViewportFromMouse(evt.getX(), evt.getY(),
- av.getAlignment().getHiddenSequences(),
- av.getAlignment().getHiddenColumns());
- }
- else
- {
- od.updateViewportFromMouse(evt.getX(), evt.getY(),
- av.getAlignment().getHiddenSequences(),
- av.getAlignment().getHiddenColumns());
- }
- ap.paintAlignment(false, false);
+ ap.paintAlignment(false, false);
}
/**
if (editCommand != null && editCommand.getSize() > 0)
{
ap.alignFrame.addHistoryItem(editCommand);
- av.firePropertyChange("alignment", null,
- av.getAlignment().getSequences());
+ av.notifyAlignment();
}
startseq = -1;
*/
List<SequenceFeature> findFeaturesAtColumn(SequenceI sequence, int column)
{
- return seqCanvas.getFeatureRenderer().findFeaturesAtColumn(sequence, column);
+ return seqCanvas.getFeatureRenderer().findFeaturesAtColumn(sequence,
+ column);
}
Tooltip tooltip;
{
if (sg.getSize() == av.getAlignment().getHeight())
{
- if ((av.hasHiddenColumns() && startres < av.getAlignment()
- .getHiddenColumns()
- .getNextHiddenBoundary(false, startres)))
+ if ((av.hasHiddenColumns()
+ && startres < av.getAlignment().getHiddenColumns()
+ .getNextHiddenBoundary(false, startres)))
{
endEditing();
return;
{
cs = ColourSchemeProperty.getColourScheme(av, sg,
ColourSchemeProperty
- .getColourName(av.getGlobalColourScheme()));
+ .getColourName(av.getGlobalColourScheme()));
}
// cs is null if shading is an annotationColourGradient
// if (cs != null)
ap.updateAnnotation();
if (av.getCodingComplement() != null)
{
- ((AlignmentViewport) av.getCodingComplement()).firePropertyChange(
- "alignment", null, ap.av.getAlignment().getSequences());
+ ((AlignmentViewport) av.getCodingComplement()).notifyAlignment();
+ // Technically, the property change is not the same because av is not necessarily getCodingComplement(),
+ // but this is the appletgui, so I am not going to worry about it. BH
+ //.firePropertyChange("alignment", null, ap.av.getAlignment().getSequences());
}
}
* along with Jalview. If not, see <http://www.gnu.org/licenses/>.
* The Jalview Authors are detailed in the 'AUTHORS' file.
*/
-package jalview.javascript;
+package jalview.appletgui.js;
import jalview.appletgui.AlignFrame;
import jalview.bin.JalviewLite;
if (seq != last || i != index)
{
// this should really be a trace message.
- // Cache.log.debug("Mouse over " + v.getId() + " bound to "
+ // Cache.debug("Mouse over " + v.getId() + " bound to "
// + seq + " at " + index);
last = seq;
i = index;
* along with Jalview. If not, see <http://www.gnu.org/licenses/>.
* The Jalview Authors are detailed in the 'AUTHORS' file.
*/
-package jalview.javascript;
+package jalview.appletgui.js;
import jalview.api.AlignmentViewPanel;
import jalview.api.FeatureRenderer;
import jalview.api.SequenceRenderer;
import jalview.appletgui.AlignFrame;
+import jalview.appletgui.js.JsCallBack;
import jalview.bin.JalviewLite;
import jalview.datamodel.SequenceI;
import jalview.ext.jmol.JmolCommands;
// structure
ArrayList<String[]> ccomands = new ArrayList<>();
ArrayList<String> pdbfn = new ArrayList<>();
- String[] colcommands = new JmolCommands()
- .colourBySequence(ssm, modelSet, sequence, sr,
- (AlignmentViewPanel) source);
+ String[] colcommands = new JmolCommands().colourBySequence(ssm,
+ modelSet, sequence, sr, (AlignmentViewPanel) source);
if (colcommands == null)
{
return;
--- /dev/null
+/*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
+package jalview.bin;
+
+import jalview.util.Platform;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * A class to hold singleton objects, whose scope (context) is
+ * <ul>
+ * <li>the Java runtime (JVM) when running as Java</li>
+ * <li>one 'applet', when running as JalviewJS</li>
+ * </ul>
+ * This allows separation of multiple JS applets running on the same browser
+ * page, each with their own 'singleton' instances.
+ * <p>
+ * Instance objects are held in a separate Map (keyed by Class) for each
+ * context. For Java, this is just a single static Map. For SwingJS, the map is
+ * stored as a field {@code _swingjsSingletons} of
+ * {@code Thread.currentThread.getThreadGroup()}, as a proxy for the applet.
+ * <p>
+ * Note that when an applet is stopped, its ThreadGroup is removed, allowing any
+ * singleton references to be garbage collected.
+ *
+ * @author hansonr
+ */
+public class ApplicationSingletonProvider
+{
+ /**
+ * A tagging interface to mark classes whose singleton instances may be served
+ * by {@code ApplicationSingletonProvider}, giving a distinct instance per JS
+ * 'applet'.
+ * <p>
+ * A class whose singleton should have global scope (be shared across all
+ * applets on a page) should <em>not</em> use this mechanism, but just provide
+ * a single instance (class static member) in the normal way.
+ */
+ public interface ApplicationSingletonI
+ {
+ }
+
+ /*
+ * Map used to hold singletons in JVM context
+ */
+ private static Map<Class<? extends ApplicationSingletonI>, ApplicationSingletonI> singletons = new HashMap<>();
+
+ /**
+ * private constructor for non-instantiable class
+ */
+ private ApplicationSingletonProvider()
+ {
+ }
+
+ /**
+ * Returns the singletons map for the current context (JVM for Java,
+ * ThreadGroup for JS), creating the map on the first request for each JS
+ * ThreadGroup
+ *
+ * @return
+ */
+ private static Map<Class<? extends ApplicationSingletonI>, ApplicationSingletonI> getContextMap()
+ {
+ @SuppressWarnings("unused")
+ ThreadGroup g = (Platform.isJS()
+ ? Thread.currentThread().getThreadGroup()
+ : null);
+ Map<Class<? extends ApplicationSingletonI>, ApplicationSingletonI> map = singletons;
+ /** @j2sNative map = g._swingjsSingletons; */
+ if (map == null)
+ {
+ map = new HashMap<>();
+ /** @j2sNative g._swingjsSingletons = map; */
+ }
+
+ return map;
+ }
+
+ /**
+ * Answers the singleton instance of the given class for the current context
+ * (JVM or SwingJS 'applet'). If no instance yet exists, one is created, by
+ * calling the class's no-argument constructor. Answers null if any error
+ * occurs (or occurred previously for the same class).
+ *
+ * @param c
+ * @return
+ */
+ public static ApplicationSingletonI getInstance(Class<? extends ApplicationSingletonI> c)
+ {
+ Map<Class<? extends ApplicationSingletonI>, ApplicationSingletonI> map = getContextMap();
+ if (map.containsKey(c))
+ {
+ /*
+ * singleton already created _or_ creation failed (null value stored)
+ */
+ return map.get(c);
+ }
+
+ /*
+ * create and save the singleton
+ */
+ ApplicationSingletonI o = map.get(c);
+ try
+ {
+ Constructor<? extends ApplicationSingletonI> con = c
+ .getDeclaredConstructor();
+ con.setAccessible(true);
+ o = con.newInstance();
+ } catch (IllegalAccessException | InstantiationException
+ | IllegalArgumentException | InvocationTargetException
+ | NoSuchMethodException | SecurityException e)
+ {
- Cache.log.error("Failed to create singleton for " + c.toString()
++ Console.error("Failed to create singleton for " + c.toString()
+ + ", error was: " + e.toString());
+ e.printStackTrace();
+ }
+
+ /*
+ * store the new singleton; note that a
+ * null value is saved if construction failed
+ */
+ getContextMap().put(c, o);
+ return o;
+ }
+
+ /**
+ * Removes the current singleton instance of the given class from the current
+ * application context. This has the effect of ensuring that a new instance is
+ * created the next time one is requested.
+ *
+ * @param c
+ */
+ public static void removeInstance(
+ Class<? extends ApplicationSingletonI> c)
+ {
+ Map<Class<? extends ApplicationSingletonI>, ApplicationSingletonI> map = getContextMap();
+ if (map != null)
+ {
+ map.remove(c);
+ }
+ }
+}
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.TreeSet;
+import java.util.regex.Pattern;
import javax.swing.LookAndFeel;
import javax.swing.UIManager;
- import org.apache.log4j.ConsoleAppender;
- import org.apache.log4j.Level;
- import org.apache.log4j.Logger;
- import org.apache.log4j.SimpleLayout;
-
+import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
import jalview.datamodel.PDBEntry;
import jalview.gui.Preferences;
import jalview.gui.UserDefinedColours;
+ import jalview.log.JLoggerLog4j;
import jalview.schemes.ColourSchemeLoader;
import jalview.schemes.ColourSchemes;
import jalview.schemes.UserColourScheme;
* <li>FOLLOW_SELECTIONS (true) Controls whether a new alignment view should
* respond to selections made in other alignments containing the same sequences.
* </li>
+ * <li>SHOW_JWS2_SERVICES (true) when set to false, jalview will not
+ * auto-discover JABAWS services</li>
* <li>JWS2HOSTURLS comma-separated list of URLs to try for JABAWS services</li>
* <li>SHOW_WSDISCOVERY_ERRORS (true) Controls if the web service URL discovery
* warning dialog box is displayed.</li>
* <li>CHIMERA_PATH specify full path to Chimera program (if non-standard)</li>
* <li>ID_ORG_HOSTURL location of jalview service providing identifiers.org urls
* </li>
- *
+ * <li>NONEWS - when set disables Jalview News from automatically appearing</li>
+ * <li>NOHTMLTEMPLATES - when set, the
+ * https://github.com/jalview/exporter-templates/tree/master/biojs repository is
+ * not downloaded automatically</li>
+ * <li>NOIDENTIFIERSSERVICE - when set, jalview won't automatically download
+ * available URL linkouts via www.jalview.org/services/identifiers</li>
+ * <li>
* </ul>
* Deprecated settings:
* <ul>
* @author $author$
* @version $Revision$
*/
-public class Cache
+public class Cache implements ApplicationSingletonI
{
-
+ private Cache()
+ {
+ // private singleton
+ }
+
+ /**
+ * In Java, this will be a static field instance, which will be
+ * application-specific; in JavaScript it will be an applet-specific instance
+ * tied to the applet's ThreadGroup.
+ *
+ * @return
+ */
+ public static Cache getInstance()
+ {
+ return (Cache) ApplicationSingletonProvider.getInstance(Cache.class);
+ }
-
/**
* property giving log4j level for CASTOR loggers
*/
/**
* Sifts settings
*/
- public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = System
- .getProperty("user.home") + File.separatorChar
- + ".sifts_downloads" + File.separatorChar;
+ public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = Platform.getUserPath(".sifts_downloads/");
+
+
private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
/**
* Identifiers.org download settings
*/
- private static final String ID_ORG_FILE = System.getProperty("user.home")
- + File.separatorChar + ".identifiers.org.ids.json";
+ private static final String ID_ORG_FILE = Platform.getUserPath(".identifiers.org.ids.json");
/**
* Allowed values are PDB or mmCIF
/**
* Initialises the Jalview Application Log
*/
- public static Logger log;
-
+ public final static String JALVIEW_LOGGER_NAME = "JalviewLogger";
// save the proxy properties set at startup
public final static String[] startupProxyProperties = {
// in-memory only storage of proxy password, safer to use char array
public static char[] proxyAuthPassword = null;
+
/** Jalview Properties */
- public static Properties applicationProperties = new Properties()
+ private Properties applicationProperties = new Properties()
{
// override results in properties output in alphabetical order
@Override
/* build Properties (not all saved to .jalview_properties) */
public static Properties buildProperties = new Properties();
+
/** Default file is ~/.jalview_properties */
static String propertiesFile;
private final static String JS_PROPERTY_PREFIX = "jalview_";
- public static void initLogger()
- {
- if (log != null)
- {
- return;
- }
- try
- {
- // TODO: redirect stdout and stderr here in order to grab the output of
- // the log
-
- ConsoleAppender ap = new ConsoleAppender(new SimpleLayout(),
- "System.err");
- ap.setName("JalviewLogger");
- org.apache.log4j.Logger.getRootLogger().addAppender(ap); // catch all for
- // log output
- Logger laxis = Logger.getLogger("org.apache.axis");
- Logger lcastor = Logger.getLogger("org.exolab.castor");
- jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
-
- laxis.setLevel(Level.toLevel(
- Cache.getDefault("logs.Axis.Level", Level.INFO.toString())));
- lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
- Level.INFO.toString())));
- lcastor = Logger.getLogger("org.exolab.castor.xml");
- lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
- Level.INFO.toString())));
- // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
- // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
- // Level.INFO.toString())));
- // we shouldn't need to do this
- org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.INFO);
- jalview.bin.Cache.log.setLevel(Level.toLevel(Cache
- .getDefault("logs.Jalview.level", Level.INFO.toString())));
- // laxis.addAppender(ap);
- // lcastor.addAppender(ap);
- // jalview.bin.Cache.log.addAppender(ap);
- // Tell the user that debug is enabled
- jalview.bin.Cache.log.debug(ChannelProperties.getProperty("app_name")
- + " Debugging Output Follows.");
- } catch (Exception ex)
- {
- System.err.println("Problems initializing the log4j system\n");
- ex.printStackTrace(System.err);
- }
- }
+
/**
- * Loads properties from the given properties file. Any existing properties
- * are first cleared.
+ * Loads properties from the given properties file. Any existing properties are
+ * first cleared.
*/
public static void loadProperties(String propsFile)
{
-
+ getInstance().loadPropertiesImpl(propsFile);
+
+ }
+
+ private void loadPropertiesImpl(String propsFile)
+ {
-
propertiesFile = propsFile;
String releasePropertiesFile = null;
boolean defaultProperties = false;
if (propsFile == null && !propsAreReadOnly)
{
+ // TODO: @bsoares - for 2.12 testing: check test,develop,release props are located correctly
String channelPrefsFilename = ChannelProperties
.getProperty("preferences.filename");
String releasePrefsFilename = ".jalview_properties";
- propertiesFile = System.getProperty("user.home") + File.separatorChar
- + channelPrefsFilename;
- releasePropertiesFile = System.getProperty("user.home")
- + File.separatorChar + releasePrefsFilename;
+ propertiesFile = Platform.getUserPath(channelPrefsFilename);
+ releasePropertiesFile = Platform.getUserPath(releasePrefsFilename);
defaultProperties = true;
}
else
System.out.println(
"Disabling Jalview writing to user's local properties file.");
propsAreReadOnly = true;
-
} catch (Exception ex)
{
fis = null;
System.out.println("Error reading properties file: " + ex);
}
}
+
/* TO BE REPLACED WITH PROXY_TYPE SETTINGS
if (getDefault("USE_PROXY", false))
{
default:
String message = "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
+ proxyType;
- Cache.warn(message);
+ Console.warn(message);
}
// LOAD THE AUTHORS FROM THE authors.props file
SiftsSettings
.setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
- SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache
+ SiftsSettings.setSiftDownloadDirectory(Cache
.getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
SiftsSettings.setFailSafePIDThreshold(
- jalview.bin.Cache.getDefault("sifts_fail_safe_pid_threshold",
+ Cache.getDefault("sifts_fail_safe_pid_threshold",
DEFAULT_FAIL_SAFE_PID_THRESHOLD));
SiftsSettings.setCacheThresholdInDays(
- jalview.bin.Cache.getDefault("sifts_cache_threshold_in_days",
+ Cache.getDefault("sifts_cache_threshold_in_days",
DEFAULT_CACHE_THRESHOLD_IN_DAYS));
IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
"https://www.jalview.org/services/identifiers"));
IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
- StructureImportSettings.setDefaultStructureFileFormat(jalview.bin.Cache
- .getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
+ StructureImportSettings.setDefaultStructureFileFormat(
+ Cache.getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
StructureImportSettings
.setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
// StructureImportSettings
- // .setDefaultPDBFileParser(jalview.bin.Cache.getDefault(
+ // .setDefaultPDBFileParser(Cache.getDefault(
// "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
String jnlpVersion = System.getProperty("jalview.version");
&& (System.getProperty("java.awt.headless") == null || System
.getProperty("java.awt.headless").equals("false")))
{
+
class VersionChecker extends Thread
{
+
@Override
public void run()
{
String remoteBuildPropertiesUrl = Cache
.getAppbaseBuildProperties();
+
String orgtimeout = System
.getProperty("sun.net.client.defaultConnectTimeout");
if (orgtimeout == null)
+ orgtimeout + " seconds.");
}
String remoteVersion = null;
- try
- {
- System.setProperty("sun.net.client.defaultConnectTimeout",
- "5000");
- java.net.URL url = new java.net.URL(remoteBuildPropertiesUrl);
- BufferedReader in = new BufferedReader(
- new InputStreamReader(url.openStream()));
-
- Properties remoteBuildProperties = new Properties();
- remoteBuildProperties.load(in);
- remoteVersion = remoteBuildProperties.getProperty("VERSION");
- } catch (Exception ex)
+ if (remoteBuildPropertiesUrl.startsWith("http"))
{
- System.out
- .println("Non-fatal exception when checking version at "
- + remoteBuildPropertiesUrl + ":");
- System.out.println(ex);
- remoteVersion = getProperty("VERSION");
+ try
+ {
+ System.setProperty("sun.net.client.defaultConnectTimeout",
+ "5000");
+
+ URL url = new URL(remoteBuildPropertiesUrl);
+
+ BufferedReader in = new BufferedReader(
+ new InputStreamReader(url.openStream()));
+
+ Properties remoteBuildProperties = new Properties();
+ remoteBuildProperties.load(in);
+ remoteVersion = remoteBuildProperties.getProperty("VERSION");
+ } catch (Exception ex)
+ {
+ System.out.println(
+ "Non-fatal exception when checking version at "
+ + remoteBuildPropertiesUrl + ":");
+ System.out.println(ex);
+ remoteVersion = getProperty("VERSION");
+ }
}
System.setProperty("sun.net.client.defaultConnectTimeout",
orgtimeout);
return url;
}
- public static void loadBuildProperties(boolean reportVersion)
+ public void loadBuildProperties(boolean reportVersion)
{
String codeInstallation = getProperty("INSTALLATION");
boolean printVersion = codeInstallation == null;
applicationProperties.put("VERSION",
buildProperties.getProperty("VERSION"));
}
+ if (buildProperties.getProperty("JAVA_COMPILE_VERSION", null) != null)
+ {
+ applicationProperties.put("JAVA_COMPILE_VERSION",
+ buildProperties.getProperty("JAVA_COMPILE_VERSION"));
+ }
} catch (Exception ex)
{
System.out.println("Error reading build details: " + ex);
}
}
- private static void deleteBuildProperties()
+ private void deleteBuildProperties()
{
applicationProperties.remove("LATEST_VERSION");
applicationProperties.remove("VERSION");
}
/**
- * Gets Jalview application property of given key. Returns null if key not
- * found
+ * Gets Jalview application property of given key. Returns null if key not found
*
* @param key
- * Name of property
+ * Name of property
*
* @return Property value
*/
public static String getProperty(String key)
{
- String prop = applicationProperties.getProperty(key);
- if (prop == null && Platform.isJS())
- {
- prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
- + "_" + JS_PROPERTY_PREFIX + key);
- }
+ String prop = getInstance().applicationProperties.getProperty(key);
+ // if (prop == null && Platform.isJS())
+ // {
+ // prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
+ // + "_" + JS_PROPERTY_PREFIX + key);
+ // }
return prop;
}
/**
- * These methods are used when checking if the saved preference is different
- * to the default setting
+ * These methods are used when checking if the saved preference is different to
+ * the default setting
*/
public static boolean getDefault(String property, boolean def)
}
/**
- * Answers the value of the given property, or the supplied default value if
- * the property is not set
+ * Answers the value of the given property, or the supplied default value if the
+ * property is not set
*/
public static String getDefault(String property, String def)
{
* Stores property in the file "HOME_DIR/.jalview_properties"
*
* @param key
- * Name of object
+ * Name of object
* @param obj
- * String value of property
+ * String value of property
*
* @return previous value of property (or null)
*/
public static Object setProperty(String key, String obj)
{
- Object oldValue = null;
- try
- {
- oldValue = applicationProperties.setProperty(key, obj);
- if (propertiesFile != null && !propsAreReadOnly)
- {
- FileOutputStream out = new FileOutputStream(propertiesFile);
- applicationProperties.store(out, "---JalviewX Properties File---");
- out.close();
- }
- } catch (Exception ex)
- {
- System.out.println(
- "Error setting property: " + key + " " + obj + "\n" + ex);
- }
- return oldValue;
+ return getInstance().setPropertyImpl(key, obj, true);
+ }
+
+ /**
+ * Removes the specified property from the jalview properties file
+ *
+ * @param key
+ */
+ public static void removeProperty(String key)
+ {
+ getInstance().removePropertyImpl(key, true);
+ }
+
+ /**
+ * Removes the named property for the running application, without saving the
+ * properties file
+ *
+ * BH noting that ColourMenuHelper calls this. If the intent is to save, then
+ * simply chanet that call to removeProperty(key).
+ *
+ * @param key
+ */
+ public static void removePropertyNoSave(String key)
+ {
+
+ getInstance().
+
+ removePropertyImpl(key, false);
}
/**
- * remove the specified property from the jalview properties file
+ * Removes the named property, and optionally saves the current properties to
+ * file
*
- * @param string
+ * @param key
+ * @param andSave
*/
- public static void removeProperty(String string)
+ private void removePropertyImpl(String key, boolean andSave)
{
- applicationProperties.remove(string);
- saveProperties();
+ applicationProperties.remove(key);
+ if (andSave)
+ saveProperties();
}
/**
*/
public static void saveProperties()
{
+ getInstance().savePropertiesImpl();
+ }
+
+ /**
+ * save the properties to the jalview properties path
+ */
+ private void savePropertiesImpl()
+
+ {
if (!propsAreReadOnly)
{
try
if (jalview.jbgui.GDesktop.class.getClassLoader()
.loadClass("uk.ac.vamsas.client.VorbaId") != null)
{
- jalview.bin.Cache.log.debug(
+ Console.debug(
"Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
vamsasJarsArePresent = 1;
- Logger lvclient = Logger.getLogger("uk.ac.vamsas");
- lvclient.setLevel(Level.toLevel(Cache
- .getDefault("logs.Vamsas.Level", Level.INFO.toString())));
-
- lvclient.addAppender(log.getAppender("JalviewLogger"));
+ JLoggerLog4j lvclient = JLoggerLog4j.getLogger("uk.ac.vamsas",
+ Console.getCachedLogLevel("logs.Vamsas.Level"));
+ JLoggerLog4j.addAppender(lvclient, Console.log,
+ JALVIEW_LOGGER_NAME);
// Tell the user that debug is enabled
lvclient.debug(ChannelProperties.getProperty("app_name")
+ " Vamsas Client Debugging Output Follows.");
} catch (Exception e)
{
vamsasJarsArePresent = 0;
- jalview.bin.Cache.log.debug("Vamsas Classes are not present");
+ Console.debug("Vamsas Classes are not present");
}
}
return (vamsasJarsArePresent > 0);
if (Cache.class.getClassLoader()
.loadClass("groovy.lang.GroovyObject") != null)
{
- jalview.bin.Cache.log.debug(
+ Console.debug(
"Found Groovy (groovy.lang.GroovyObject can be loaded)");
groovyJarsArePresent = 1;
- Logger lgclient = Logger.getLogger("groovy");
- lgclient.setLevel(Level.toLevel(Cache
- .getDefault("logs.Groovy.Level", Level.INFO.toString())));
-
- lgclient.addAppender(log.getAppender("JalviewLogger"));
+ JLoggerLog4j lgclient = JLoggerLog4j.getLogger("groovy",
+ Console.getCachedLogLevel("logs.Groovy.Level"));
+ JLoggerLog4j.addAppender(lgclient, Console.log,
+ JALVIEW_LOGGER_NAME);
// Tell the user that debug is enabled
lgclient.debug(ChannelProperties.getProperty("app_name")
+ " Groovy Client Debugging Output Follows.");
} catch (Error e)
{
groovyJarsArePresent = 0;
- jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
+ Console.debug("Groovy Classes are not present", e);
} catch (Exception e)
{
groovyJarsArePresent = 0;
- jalview.bin.Cache.log.debug("Groovy Classes are not present");
+ Console.debug("Groovy Classes are not present");
}
}
return (groovyJarsArePresent > 0);
.loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
} catch (Exception e)
{
- log.debug(
+ Console.debug(
"com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
tracker = null;
jgoogleanalyticstracker = null;
{ String.class, String.class, String.class })
.newInstance(new Object[]
{ ChannelProperties.getProperty("app_name") + " Desktop",
- (vrs = jalview.bin.Cache.getProperty("VERSION") + "_"
- + jalview.bin.Cache.getDefault("BUILD_DATE",
- "unknown")),
+ (vrs = Cache.getProperty("VERSION") + "_"
+ + Cache.getDefault("BUILD_DATE", "unknown")),
"UA-9060947-1" });
jgoogleanalyticstracker
.getMethod("trackAsynchronously", new Class[]
}
if (re != null || ex != null || err != null)
{
- if (log != null)
+ if (re != null)
{
- if (re != null)
- {
- log.debug("Caught runtime exception in googletracker init:",
- re);
- }
- if (ex != null)
- {
- log.warn(
- "Failed to initialise GoogleTracker for Jalview Desktop with version "
- + vrs,
- ex);
- }
- if (err != null)
- {
- log.error(
- "Whilst initing GoogleTracker for Jalview Desktop version "
- + vrs,
- err);
- }
+ Console.debug("Caught runtime exception in googletracker init:",
+ re);
}
- else
+ if (ex != null)
{
- if (re != null)
- {
- System.err.println(
- "Debug: Caught runtime exception in googletracker init:"
- + vrs);
- re.printStackTrace();
- }
- if (ex != null)
- {
- System.err.println(
- "Warning: Failed to initialise GoogleTracker for Jalview Desktop with version "
- + vrs);
- ex.printStackTrace();
- }
-
- if (err != null)
- {
- System.err.println(
- "ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
- + vrs);
- err.printStackTrace();
- }
+ Console.warn(
+ "Failed to initialise GoogleTracker for Jalview Desktop with version "
+ + vrs,
+ ex);
+ }
+ if (err != null)
+ {
+ Console.error(
+ "Whilst initing GoogleTracker for Jalview Desktop version "
+ + vrs,
+ err);
}
}
else
{
- log.debug("Successfully initialised tracker.");
+ Console.debug("Successfully initialised tracker.");
}
}
}
Color col = ColorUtils.parseColourString(colprop);
if (col == null)
{
- log.warn("Couldn't parse '" + colprop + "' as a colour for "
+ Console.warn("Couldn't parse '" + colprop + "' as a colour for "
+ property);
}
return (col == null) ? defcolour : col;
* @param property
* @param colour
*/
- public static void setColourProperty(String property, Color colour)
+ public static void setColourPropertyNoSave(String property, Color colour)
{
- setProperty(property, jalview.util.Format.getHexString(colour));
+ setPropertyNoSave(property, jalview.util.Format.getHexString(colour));
}
/**
public static Date getDateProperty(String propertyName)
{
String val = getProperty(propertyName);
+
if (val != null)
{
try
{
- return date_format.parse(val);
+ if ((val = val.trim()).indexOf(",") < 0 && val.indexOf("-") >= 0 && val.indexOf(" ") == val.lastIndexOf(" ")) {
+ val = val.replace(" ",", ").replace('-',' ');
+ }
+ Date date = date_format.parse(val);
+ return date;
} catch (Exception ex)
{
System.err.println("Invalid or corrupt date in property '"
}
if (value == null || value.trim().length() < 1)
{
- Cache.applicationProperties.remove(propName);
+ getInstance().applicationProperties.remove(propName);
}
else
{
- Cache.applicationProperties.setProperty(propName, value);
+ getInstance().applicationProperties.setProperty(propName, value);
}
}
* Loads in user colour schemes from files.
*
* @param files
- * a '|'-delimited list of file paths
+ * a '|'-delimited list of file paths
*/
public static void initUserColourSchemes(String files)
{
}
else
{
- applicationProperties
+ getInstance().applicationProperties
.remove(UserDefinedColours.USER_DEFINED_COLOURS);
}
}
{
return;
}
- String line = prefix + (value != null ? value : defaultValue) + suffix;
- sb.append(line);
+ if (prefix != null)
+ sb.append(prefix);
+ sb.append(value == null ? defaultValue : value);
+ if (suffix != null)
+ sb.append(suffix);
}
/**
StringBuilder sb = new StringBuilder();
sb.append(ChannelProperties.getProperty("app_name"))
.append(" Version: ");
- sb.append(jalview.bin.Cache.getDefault("VERSION", "TEST"));
+ sb.append(Cache.getDefault("VERSION", "TEST"));
sb.append("\n");
sb.append(ChannelProperties.getProperty("app_name"))
.append(" Installation: ");
- sb.append(jalview.bin.Cache.getDefault("INSTALLATION", "unknown"));
+ sb.append(Cache.getDefault("INSTALLATION", "unknown"));
sb.append("\n");
- sb.append("Build Date: "
- + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
+ sb.append("Build Date: ");
+ sb.append(Cache.getDefault("BUILD_DATE", "unknown"));
sb.append("\n");
sb.append("Java version: ");
sb.append(System.getProperty("java.version"));
sb.append(" (");
sb.append(lafClass);
sb.append(")\n");
- // Not displayed in release version ( determined by possible version number
- // regex 9[9.]*9[.-_a9]* )
- if (Pattern.matches("^\\d[\\d\\.]*\\d[\\.\\-\\w]*$",
- jalview.bin.Cache.getDefault("VERSION", "TEST")))
+ if (Console.isDebugEnabled()
+ || !"release".equals(ChannelProperties.getProperty("channel")))
{
+ appendIfNotNull(sb, "Channel: ",
+ ChannelProperties.getProperty("channel"), "\n", null);
appendIfNotNull(sb, "Getdown appdir: ",
- System.getProperty("getdownappdir"), "\n", null);
+ System.getProperty("getdowninstanceappdir"), "\n", null);
appendIfNotNull(sb, "Getdown appbase: ",
- System.getProperty("getdownappbase"), "\n", null);
+ System.getProperty("getdowninstanceappbase"), "\n", null);
appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
"\n", "unknown");
}
{
// consider returning more human friendly info
// eg 'built from Source' or update channel
- return jalview.bin.Cache.getDefault("INSTALLATION", "unknown");
- return Cache.getDefault("INSTALLATION", "unknown");
++ return Cache.getDefault("INSTALLATION", "unknown");
+ }
+
+ /**
+ *
+ * For AppletParams and Preferences ok_actionPerformed and
+ * startupFileTextfield_mouseClicked
+ *
+ * Sets a property value for the running application, without saving it to the
+ * properties file
+ *
+ * @param key
+ * @param obj
+ */
+ public static void setPropertyNoSave(String key, String obj)
+ {
+ getInstance().setPropertyImpl(key, obj, false);
+ }
+
+ /**
+ * Sets a property value, and optionally also saves the current properties to
+ * file
+ *
+ * @param key
+ * @param obj
+ * @param andSave
+ * @return
+ */
+ private Object setPropertyImpl(
+ String key, String obj, boolean andSave)
+ {
+ Object oldValue = null;
+ try
+ {
+ oldValue = applicationProperties.setProperty(key, obj);
+ if (andSave && !propsAreReadOnly && propertiesFile != null)
+ {
+ FileOutputStream out = new FileOutputStream(propertiesFile);
+ applicationProperties.store(out, "---JalviewX Properties File---");
+ out.close();
+ }
+ } catch (Exception ex)
+ {
+ System.out.println(
+ "Error setting property: " + key + " " + obj + "\n" + ex);
+ }
+ return oldValue;
}
public static String getStackTraceString(Throwable t)
? " [" + startupProxyProperties[6] + "]"
: "");
- Cache.debug(sb.toString());
+ Console.debug(sb.toString());
}
public static void setProxyPropertiesFromPreferences()
case Cache.PROXYTYPE_NONE:
if (!previousProxyType.equals(proxyType))
{
- Cache.log.info("Setting no proxy settings");
+ Console.info("Setting no proxy settings");
Cache.setProxyProperties(null, null, null, null, null, null, null,
null, null);
}
case Cache.PROXYTYPE_CUSTOM:
// always re-set a custom proxy -- it might have changed, particularly
// password
- Cache.log.info("Setting custom proxy settings");
+ Console.info("Setting custom proxy settings");
boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
Cache.getDefault("PROXY_PORT", null),
proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
break;
default: // system proxy settings by default
- Cache.log.info("Setting system proxy settings");
+ Console.info("Setting system proxy settings");
Cache.resetProxyProperties();
}
}
char[] displayHttpPw = new char[httpPassword == null ? 0
: httpPassword.length];
Arrays.fill(displayHttpPw, '*');
- Cache.debug("CACHE Proxy: setting new Authenticator with httpUser='"
- + httpUser + "' httpPassword='" + displayHttpPw + "'");
+ Console.debug(
+ "CACHE Proxy: setting new Authenticator with httpUser='"
+ + httpUser + "' httpPassword='" + displayHttpPw
+ + "'");
if (!Platform.isJS())
/* *
* java.net.Authenticator not implemented in SwingJS yet
&& getRequestingPort() == Integer
.valueOf(httpPort))
{
- Cache.debug(
+ Console.debug(
"AUTHENTICATOR returning PasswordAuthentication(\""
+ httpUser + "\", '"
+ new String(displayHttpPw) + "')");
{
char[] displayHttpsPw = new char[httpPassword.length];
Arrays.fill(displayHttpsPw, '*');
- Cache.debug(
+ Console.debug(
"AUTHENTICATOR returning PasswordAuthentication(\""
+ httpsUser + "\", '" + displayHttpsPw
+ "'");
}
} catch (NumberFormatException e)
{
- Cache.error("Problem with proxy port values [http:"
+ Console.error("Problem with proxy port values [http:"
+ httpPort + ", https:" + httpsPort + "]");
}
- Cache.debug(
+ Console.debug(
"AUTHENTICATOR after trying to get PasswordAuthentication");
}
}
// non proxy request
- Cache.debug("AUTHENTICATOR returning null");
+ Console.debug("AUTHENTICATOR returning null");
return null;
}
});
// required to re-enable basic authentication (should be okay for a
// local proxy)
- Cache.debug(
+ Console.debug(
"AUTHENTICATOR setting property 'jdk.http.auth.tunneling.disabledSchemes' to \"\"");
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
} catch (SecurityException e)
{
- Cache.error("Could not set default Authenticator");
- Cache.debug(getStackTraceString(e));
+ Console.error("Could not set default Authenticator");
+ Console.debug(getStackTraceString(e));
}
}
else
*
*/
{
- Cache.debug("AUTHENTICATOR setting default Authenticator to null");
+ Console.debug(
+ "AUTHENTICATOR setting default Authenticator to null");
Authenticator.setDefault(null);
}
}
// nonProxyHosts not currently configurable in Preferences
- Cache.debug("AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
- + nonProxyHosts + "\"");
+ Console.debug(
+ "AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
+ + nonProxyHosts + "\"");
setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
}
}
}
- public final static int TRACE = 10;
-
- public final static int DEBUG = 20;
-
- public final static int INFO = 30;
-
- public final static int WARN = 40;
-
- public final static int ERROR = 50;
-
- public static boolean println(int level, String message)
- {
- if (Cache.log == null)
- {
- if (level >= WARN)
- System.err.println(message);
- else if (level >= INFO)
- System.out.println(message);
- // not printing debug or trace messages
- return false;
- }
- if (level >= ERROR)
- {
- Cache.log.error(message);
- }
- else if (level >= WARN)
- {
- Cache.log.warn(message);
- }
- else if (level >= INFO)
- {
- Cache.log.info(message);
- }
- else if (level >= DEBUG)
- {
- Cache.log.debug(message);
- }
- else
- {
- Cache.log.trace(message);
- }
- return true;
- }
-
- public static void trace(String message)
- {
- println(TRACE, message);
- }
-
- public static void debug(String message)
- {
- println(DEBUG, message);
- }
-
- public static void info(String message)
- {
- println(INFO, message);
- }
-
- public static void warn(String message)
- {
- println(WARN, message);
- }
-
- public static void error(String message)
- {
- println(ERROR, message);
- }
-
/**
* Getdown appbase methods
*/
*/
package jalview.bin;
++import java.util.Locale;
++
+import java.awt.GraphicsEnvironment;
+ import java.awt.Color;
+
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
+ import javax.swing.JOptionPane;
+ import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
+ import com.formdev.flatlaf.FlatLightLaf;
+ import com.formdev.flatlaf.util.SystemInfo;
import com.threerings.getdown.util.LaunchUtil;
+ //import edu.stanford.ejalbert.launching.IBrowserLaunching;
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
+import jalview.api.AlignCalcWorkerI;
+import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
import jalview.ext.so.SequenceOntology;
import jalview.gui.AlignFrame;
+import jalview.gui.AlignViewport;
import jalview.gui.Desktop;
+import jalview.gui.Preferences;
import jalview.gui.PromptUserConfig;
import jalview.io.AppletFormatAdapter;
import jalview.io.BioJsHTMLOutput;
import jalview.schemes.ColourSchemeProperty;
import jalview.util.ChannelProperties;
import jalview.util.HttpUtils;
+ import jalview.util.LaunchUtils;
import jalview.util.MessageManager;
import jalview.util.Platform;
import jalview.ws.jws2.Jws2Discoverer;
* @author $author$
* @version $Revision$
*/
-public class Jalview
+public class Jalview implements ApplicationSingletonI
{
- static
+ // for testing those nasty messages you cannot ever find.
+ // static
+ // {
+ // System.setOut(new PrintStream(new ByteArrayOutputStream())
+ // {
+ // @Override
+ // public void println(Object o)
+ // {
+ // if (o != null)
+ // {
+ // System.err.println(o);
+ // }
+ // }
+ //
+ // });
+ // }
+ public static Jalview getInstance()
+ {
+ return (Jalview) ApplicationSingletonProvider
+ .getInstance(Jalview.class);
+ }
+
+ private Jalview()
{
Platform.getURLCommandArguments();
+ Platform.addJ2SDirectDatabaseCall("https://www.jalview.org");
+ Platform.addJ2SDirectDatabaseCall("http://www.jalview.org");
+ Platform.addJ2SDirectDatabaseCall("http://www.compbio.dundee.ac.uk");
+ Platform.addJ2SDirectDatabaseCall("https://www.compbio.dundee.ac.uk");
}
- /*
- * singleton instance of this class
- */
- private static Jalview instance;
+
++ private boolean headless;
+
private Desktop desktop;
- public static AlignFrame currentAlignFrame;
+ public AlignFrame currentAlignFrame;
+
+ public String appletResourcePath;
+
+ public String j2sAppletID;
+
+ private boolean noCalculation, noMenuBar, noStatus;
+
+ private boolean noAnnotation;
+
+ public boolean getStartCalculations()
+ {
+ return !noCalculation;
+ }
+
+ public boolean getAllowMenuBar()
+ {
+ return !noMenuBar;
+ }
+
+ public boolean getShowStatus()
+ {
+ return !noStatus;
+ }
+
+ public boolean getShowAnnotation()
+ {
+ return !noAnnotation;
+ }
static
{
-- if (!Platform.isJS())
++ if (Platform.isJS())
++ {
++ Platform.getURLCommandArguments();
++ } else
/**
* Java only
*
}
- public static Jalview getInstance()
- {
- return instance;
- }
+ private final static boolean doPlatformLogging = false;
/**
* main class for Jalview application
*/
public static void main(String[] args)
{
- // setLogging(); // BH - for event debugging in JavaScript
- instance = new Jalview();
- instance.doMain(args);
- }
-
- private static void logClass(String name)
- {
- // BH - for event debugging in JavaScript
- ConsoleHandler consoleHandler = new ConsoleHandler();
- consoleHandler.setLevel(Level.ALL);
- Logger logger = Logger.getLogger(name);
- logger.setLevel(Level.ALL);
- logger.addHandler(consoleHandler);
- }
-
- @SuppressWarnings("unused")
- private static void setLogging()
- {
-
- /**
- * @j2sIgnore
- *
- */
+ if (doPlatformLogging)
{
- System.out.println("not in js");
+ Platform.startJavaLogging();
}
- // BH - for event debugging in JavaScript (Java mode only)
- if (!Platform.isJS())
- /**
- * Java only
- *
- * @j2sIgnore
- */
- {
- Logger.getLogger("").setLevel(Level.ALL);
- logClass("java.awt.EventDispatchThread");
- logClass("java.awt.EventQueue");
- logClass("java.awt.Component");
- logClass("java.awt.focus.Component");
- logClass("java.awt.focus.DefaultKeyboardFocusManager");
- }
+ getInstance().doMain(args);
}
+
+
+
/**
* @param args
void doMain(String[] args)
{
- if (!Platform.isJS())
+ boolean isJS = Platform.isJS();
+ if (!isJS)
{
System.setSecurityManager(null);
}
+ /*
+ * @j2sNative J2S.db._DirectDatabaseCalls["compbio.dundee.ac.uk"]=null;
+ * @j2sNative J2S.db._DirectDatabaseCalls["jalview.org"]=null;
+ *
+ */
System.out
.println("Java version: " + System.getProperty("java.version"));
System.out.println("Java Home: " + System.getProperty("java.home"));
}
// report Jalview version
- Cache.loadBuildProperties(true);
+ Cache.getInstance().loadBuildProperties(true);
ArgsParser aparser = new ArgsParser(args);
-- boolean headless = false;
++ headless = false;
String usrPropsFile = aparser.getValue("props");
Cache.loadProperties(usrPropsFile); // must do this before
- if (usrPropsFile != null)
+ boolean allowServices = true;
+
+ if (isJS)
{
- System.out.println(
- "CMD [-props " + usrPropsFile + "] executed successfully!");
+ j2sAppletID = Platform.getAppID(null);
+ Preferences.setAppletDefaults();
+ Cache.loadProperties(usrPropsFile); // again, because we
+ // might be changing defaults here?
+ appletResourcePath = (String) aparser.getAppletValue("resourcepath",
+ null, true);
}
- if (!Platform.isJS())
+ else
/**
* Java only
*
* @j2sIgnore
*/
{
+ if (usrPropsFile != null)
+ {
+ System.out.println(
+ "CMD [-props " + usrPropsFile + "] executed successfully!");
+ }
if (aparser.contains("help") || aparser.contains("h"))
{
showUsage();
System.exit(0);
}
+ // BH note: Only -nodisplay is official; others are deprecated?
if (aparser.contains("nodisplay") || aparser.contains("nogui")
- || aparser.contains("headless"))
+ || aparser.contains("headless")
+ || GraphicsEnvironment.isHeadless())
{
- System.setProperty("java.awt.headless", "true");
+ if (!isJS) {
+ // BH Definitely not a good idea in JavaScript;
+ // probably should not be here for Java, either.
+ System.setProperty("java.awt.headless", "true");
+ }
headless = true;
}
// anything else!
+ // allow https handshakes to download intermediate certs if necessary
+ System.setProperty("com.sun.security.enableAIAcaIssuers", "true");
-
- final String jabawsUrl = aparser.getValue("jabaws");
- if (jabawsUrl != null)
+ final String jabawsUrl = aparser.getValue(ArgsParser.JABAWS);
+ allowServices = !("none".equals(jabawsUrl));
+ if (allowServices && jabawsUrl != null)
{
try
{
- Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
+ Jws2Discoverer.getInstance().setPreferredUrl(jabawsUrl);
System.out.println(
"CMD [-jabaws " + jabawsUrl + "] executed successfully!");
} catch (MalformedURLException e)
"Invalid jabaws parameter: " + jabawsUrl + " ignored");
}
}
-
}
+
- String defs = aparser.getValue("setprop");
+ String defs = aparser.getValue(ArgsParser.SETPROP);
while (defs != null)
{
int p = defs.indexOf('=');
else
{
System.out.println("Executing setprop argument: " + defs);
- if (Platform.isJS())
+ if (isJS)
{
Cache.setProperty(defs.substring(0, p), defs.substring(p + 1));
}
- // DISABLED FOR SECURITY REASONS
- // TODO: add a property to allow properties to be overriden by cli args
- // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
}
defs = aparser.getValue("setprop");
}
}
System.setProperty("http.agent",
"Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
-
try
{
- Cache.initLogger();
+ Console.initLogger();
} catch (NoClassDefFoundError error)
{
error.printStackTrace();
* configure 'full' SO model if preferences say to, else use the default (full SO)
* - as JS currently doesn't have OBO parsing, it must use 'Lite' version
*/
- boolean soDefault = !Platform.isJS();
+ boolean soDefault = !isJS;
if (Cache.getDefault("USE_FULL_SO", soDefault))
{
-- SequenceOntologyFactory.setInstance(new SequenceOntology());
++ SequenceOntologyFactory.setSequenceOntology(new SequenceOntology());
}
if (!headless)
{
Desktop.nosplash = aparser.contains("nosplash");
- desktop = new Desktop();
+ desktop = Desktop.getInstance();
desktop.setInBatchMode(true); // indicate we are starting up
try
JalviewTaskbar.setTaskbar(this);
} catch (Exception e)
{
- Cache.log.info("Cannot set Taskbar");
- Cache.log.error(e.getMessage());
+ Console.info("Cannot set Taskbar");
+ Console.error(e.getMessage());
// e.printStackTrace();
} catch (Throwable t)
{
- Cache.log.info("Cannot set Taskbar");
- Cache.log.error(t.getMessage());
+ Console.info("Cannot set Taskbar");
+ Console.error(t.getMessage());
// t.printStackTrace();
}
+
// set Proxy settings before all the internet calls
Cache.setProxyPropertiesFromPreferences();
desktop.setVisible(true);
- if (!Platform.isJS())
+ if (isJS)
+ {
+ Cache.setProperty("SHOW_JWS2_SERVICES", "false");
+ }
+ if (allowServices && !aparser.contains("nowebservicediscovery"))
+ {
+ desktop.startServiceDiscovery();
+ }
+
+ if (!isJS)
/**
* Java only
*
* @j2sIgnore
*/
{
-
+ /**
+ * Check to see that the JVM version being run is suitable for the Java
+ * version this Jalview was compiled for. Popup a warning if not.
+ */
+ if (!LaunchUtils.checkJavaVersion())
+ {
+ Console.warn("The Java version being used (Java "
+ + LaunchUtils.getJavaVersion()
+ + ") may lead to problems. This installation of Jalview should be used with Java "
+ + LaunchUtils.getJavaCompileVersion() + ".");
+
+ if (!LaunchUtils
+ .getBooleanUserPreference("IGNORE_JVM_WARNING_POPUP"))
+ {
+ Object[] options = {
+ MessageManager.getString("label.continue") };
+ JOptionPane.showOptionDialog(null,
+ MessageManager.formatMessage(
+ "warning.wrong_jvm_version_message",
+ LaunchUtils.getJavaVersion(),
+ LaunchUtils.getJavaCompileVersion()),
+ MessageManager
+ .getString("warning.wrong_jvm_version_title"),
+ JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
+ null, options, options[0]);
+ }
+ }
-
- if (!aparser.contains("nowebservicediscovery"))
- {
- desktop.startServiceDiscovery();
- }
if (!aparser.contains("nousagestats"))
{
startUsageStats(desktop);
{
// Start the desktop questionnaire prompter with the specified
// questionnaire
- Cache.log.debug("Starting questionnaire url at " + url);
+ Console.debug("Starting questionnaire url at " + url);
desktop.checkForQuestionnaire(url);
System.out.println("CMD questionnaire[-" + url
+ "] executed successfully!");
// "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
// //
String defurl = "https://www.jalview.org/cgi-bin/questionnaire.pl";
- Cache.log.debug(
+ Console.debug(
"Starting questionnaire with default url: " + defurl);
desktop.checkForQuestionnaire(defurl);
}
.println("CMD [-noquestionnaire] executed successfully!");
}
- if (!aparser.contains("nonews"))
+ if (!aparser.contains("nonews")
+ || Cache.getProperty("NONEWS") == null)
{
desktop.checkForNews();
}
- BioJsHTMLOutput.updateBioJS();
+ if (!aparser.contains("nohtmltemplates")
+ || Cache.getProperty("NOHTMLTEMPLATES") == null)
+ {
+ BioJsHTMLOutput.updateBioJS();
+ }
}
}
+
+ // Check if JVM and compile version might cause problems and log if it
+ // might.
+ if (headless && !Platform.isJS() && !LaunchUtils.checkJavaVersion())
+ {
+ Console.warn("The Java version being used (Java "
+ + LaunchUtils.getJavaVersion()
+ + ") may lead to problems. This installation of Jalview should be used with Java "
+ + LaunchUtils.getJavaCompileVersion() + ".");
+ }
+ parseArguments(aparser, true);
+ }
- // Move any new getdown-launcher-new.jar into place over old
- // getdown-launcher.jar
- String appdirString = System.getProperty("getdownappdir");
- if (appdirString != null && appdirString.length() > 0)
+ /**
+ * Parse all command-line String[] arguments as well as all JavaScript-derived
+ * parameters from Info.
+ *
+ * We allow for this method to be run from JavaScript. Basically allowing
+ * simple scripting.
+ *
+ * @param aparser
+ * @param isStartup
+ */
+ public void parseArguments(ArgsParser aparser, boolean isStartup)
+ {
+
+ String groovyscript = null; // script to execute after all loading is
+ boolean isJS = Platform.isJS();
+ if (!isJS)
+ /** @j2sIgnore */
{
- final File appdir = new File(appdirString);
- new Thread()
+ // Move any new getdown-launcher-new.jar into place over old
+ // getdown-launcher.jar
+ String appdirString = System.getProperty("getdownappdir");
+ if (appdirString != null && appdirString.length() > 0)
{
- @Override
- public void run()
+ final File appdir = new File(appdirString);
+ new Thread()
{
- LaunchUtil.upgradeGetdown(
- new File(appdir, "getdown-launcher-old.jar"),
- new File(appdir, "getdown-launcher.jar"),
- new File(appdir, "getdown-launcher-new.jar"));
- }
- }.start();
- }
+ @Override
+ public void run()
+ {
+ LaunchUtil.upgradeGetdown(
+ new File(appdir, "getdown-launcher-old.jar"),
+ new File(appdir, "getdown-launcher.jar"),
+ new File(appdir, "getdown-launcher-new.jar"));
+ }
+ }.start();
+ }
- String file = null, data = null;
- FileFormatI format = null;
- DataSourceType protocol = null;
- FileLoader fileLoader = new FileLoader(!headless);
+ // completed one way or another
+ // extract groovy argument and execute if necessary
+ groovyscript = aparser.getValue("groovy", true);
+ }
- String groovyscript = null; // script to execute after all loading is
- // completed one way or another
- // extract groovy argument and execute if necessary
- groovyscript = aparser.getValue("groovy", true);
- file = aparser.getValue("open", true);
+ String file = aparser.getValue("open", true);
- if (file == null && desktop == null)
+ if (!isJS && file == null && desktop == null)
{
System.out.println("No files to open!");
System.exit(1);
}
+ setDisplayParameters(aparser);
+
+ // time to open a file.
long progress = -1;
+ DataSourceType protocol = null;
+ FileLoader fileLoader = new FileLoader(!headless);
+ FileFormatI format = null;
// Finally, deal with the remaining input data.
- if (file != null)
+ AlignFrame af = null;
+
+ JalviewJSApp jsApp = (isJS ? new JalviewJSApp(this, aparser) : null);
+
+ if (file == null)
+ {
+ if (isJS)
+ {
+ // JalviewJS allows sequence1 sequence2 ....
+
+ }
+ else if (!headless && Cache.getDefault("SHOW_STARTUP_FILE", true))
- /**
- * Java only
- *
- * @j2sIgnore
- */
++ /**
++ * Java only
++ *
++ * @j2sIgnore
++ */
++ {
++ file = Cache.getDefault("STARTUP_FILE",
++ Cache.getDefault("www.jalview.org", "https://www.jalview.org")
++ + "/examples/exampleFile_2_7.jvp");
++ if (file.equals("http://www.jalview.org/examples/exampleFile_2_3.jar")
++ || file.equals(
++ "http://www.jalview.org/examples/exampleFile_2_7.jar"))
+ {
++ file.replace("http:", "https:");
++ // hardwire upgrade of the startup file
++ file.replace("_2_3", "_2_7");
++ file.replace("2_7.jar", "2_7.jvp");
++ // and remove the stale setting
++ Cache.removeProperty("STARTUP_FILE");
++ }
+
- // We'll only open the default file if the desktop is visible.
- // And the user
- // ////////////////////
-
- file = Cache.getDefault("STARTUP_FILE",
- Cache.getDefault("www.jalview.org",
- "http://www.jalview.org")
- + "/examples/exampleFile_2_7.jar");
- if (file.equals(
- "http://www.jalview.org/examples/exampleFile_2_3.jar"))
- {
- // hardwire upgrade of the startup file
- file.replace("_2_3.jar", "_2_7.jar");
- // and remove the stale setting
- Cache.removeProperty("STARTUP_FILE");
- }
-
- protocol = DataSourceType.FILE;
-
- if (file.indexOf("http:") > -1)
- {
- protocol = DataSourceType.URL;
- }
++ protocol = AppletFormatAdapter.checkProtocol(file);
+
- if (file.endsWith(".jar"))
++ if (file.endsWith(".jar"))
++ {
++ format = FileFormat.Jalview;
++ }
++ else
++ {
++ try
+ {
- format = FileFormat.Jalview;
- }
- else
++ format = new IdentifyFile().identify(file, protocol);
++ } catch (FileFormatException e)
+ {
- try
- {
- format = new IdentifyFile().identify(file, protocol);
- } catch (FileFormatException e)
- {
- // TODO what?
- }
++ // TODO what?
+ }
- af = fileLoader.LoadFileWaitTillLoaded(file, protocol, format);
+ }
++
++ af = fileLoader.LoadFileWaitTillLoaded(file, protocol, format);
++ }
+ }
+ else
{
if (!headless)
{
}
}
+ // JS Only argument to provide a format parameter to specify what format to use
+ String fileFormat = (isJS
+ ? (String) aparser.getAppletValue("format", null, true)
+ : null);
protocol = AppletFormatAdapter.checkProtocol(file);
try
{
- format = new IdentifyFile().identify(file, protocol);
+ format = (fileFormat != null
+ ? FileFormats.getInstance().forName(fileFormat)
+ : null);
+ if (format == null)
+ {
+ format = new IdentifyFile().identify(file, protocol);
+ }
} catch (FileFormatException e1)
{
// TODO ?
}
- AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
+ af = new FileLoader(!headless).LoadFileWaitTillLoaded(file, protocol,
format);
if (af == null)
{
- System.out.println("error");
+ System.out.println("jalview error - AlignFrame was not created");
}
else
{
- setCurrentAlignFrame(af);
- data = aparser.getValue("colour", true);
- if (data != null)
+
+ // JalviewLite interface for JavaScript allows second file open
+ String file2 = aparser.getValue(ArgsParser.OPEN2, true);
+ if (file2 != null)
{
- data.replaceAll("%20", " ");
-
- ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
- af.getViewport(), af.getViewport().getAlignment(), data);
-
- if (cs != null)
+ protocol = AppletFormatAdapter.checkProtocol(file2);
+ try
{
- System.out.println(
- "CMD [-color " + data + "] executed successfully!");
+ format = new IdentifyFile().identify(file2, protocol);
+ } catch (FileFormatException e1)
+ {
+ // TODO ?
}
- af.changeColour(cs);
- }
-
- // Must maintain ability to use the groups flag
- data = aparser.getValue("groups", true);
- if (data != null)
- {
- af.parseFeaturesFile(data,
- AppletFormatAdapter.checkProtocol(data));
- // System.out.println("Added " + data);
- System.out.println(
- "CMD groups[-" + data + "] executed successfully!");
- }
- data = aparser.getValue("features", true);
- if (data != null)
- {
- af.parseFeaturesFile(data,
- AppletFormatAdapter.checkProtocol(data));
- // System.out.println("Added " + data);
- System.out.println(
- "CMD [-features " + data + "] executed successfully!");
- }
-
- data = aparser.getValue("annotations", true);
- if (data != null)
- {
- af.loadJalviewDataFile(data, null, null, null);
- // System.out.println("Added " + data);
- System.out.println(
- "CMD [-annotations " + data + "] executed successfully!");
- }
- // set or clear the sortbytree flag.
- if (aparser.contains("sortbytree"))
- {
- af.getViewport().setSortByTree(true);
- if (af.getViewport().getSortByTree())
+ AlignFrame af2 = new FileLoader(!headless)
+ .LoadFileWaitTillLoaded(file2, protocol, format);
+ if (af2 == null)
{
- System.out.println("CMD [-sortbytree] executed successfully!");
+ System.out.println("error");
}
- }
- if (aparser.contains("no-annotation"))
- {
- af.getViewport().setShowAnnotation(false);
- if (!af.getViewport().isShowAnnotation())
+ else
{
- System.out.println("CMD no-annotation executed successfully!");
+ AlignViewport.openLinkedAlignmentAs(af,
+ af.getViewport().getAlignment(),
+ af2.getViewport().getAlignment(), "",
+ AlignViewport.SPLIT_FRAME);
+ System.out.println(
+ "CMD [-open2 " + file2 + "] executed successfully!");
}
}
- if (aparser.contains("nosortbytree"))
+ // af is loaded - so set it as current frame
+ setCurrentAlignFrame(af);
+
+ setFrameDependentProperties(aparser, af);
+
+ if (isJS)
{
- af.getViewport().setSortByTree(false);
- if (!af.getViewport().getSortByTree())
- {
- System.out
- .println("CMD [-nosortbytree] executed successfully!");
- }
+ jsApp.initFromParams(af);
}
- data = aparser.getValue("tree", true);
- if (data != null)
+ else
+ /**
+ * Java only
+ *
+ * @j2sIgnore
+ */
{
- try
+ if (groovyscript != null)
{
- System.out.println(
- "CMD [-tree " + data + "] executed successfully!");
- NewickFile nf = new NewickFile(data,
- AppletFormatAdapter.checkProtocol(data));
- af.getViewport()
- .setCurrentTree(af.showNewickTree(nf, data).getTree());
- } catch (IOException ex)
- {
- System.err.println("Couldn't add tree " + data);
- ex.printStackTrace(System.err);
+ // Execute the groovy script after we've done all the rendering
+ // stuff
+ // and before any images or figures are generated.
+ System.out.println("Executing script " + groovyscript);
+ executeGroovyScript(groovyscript, af);
+ System.out.println("CMD groovy[" + groovyscript
+ + "] executed successfully!");
+ groovyscript = null;
}
}
- // TODO - load PDB structure(s) to alignment JAL-629
- // (associate with identical sequence in alignment, or a specified
- // sequence)
- if (groovyscript != null)
- {
- // Execute the groovy script after we've done all the rendering stuff
- // and before any images or figures are generated.
- System.out.println("Executing script " + groovyscript);
- executeGroovyScript(groovyscript, af);
- System.out.println("CMD groovy[" + groovyscript
- + "] executed successfully!");
- groovyscript = null;
+ if (!isJS || !isStartup) {
+ createOutputFiles(aparser, format);
}
- String imageName = "unnamed.png";
- while (aparser.getSize() > 1)
- {
- String outputFormat = aparser.nextValue();
- file = aparser.nextValue();
+ }
+ if (headless)
+ {
+ af.getViewport().getCalcManager().shutdown();
+ }
+ }
+ // extract groovy arguments before anything else.
+ // Once all other stuff is done, execute any groovy scripts (in order)
+ if (!isJS && groovyscript != null)
+ {
+ if (Cache.groovyJarsPresent())
+ {
+ // TODO: DECIDE IF THIS SECOND PASS AT GROOVY EXECUTION IS STILL REQUIRED !!
+ System.out.println("Executing script " + groovyscript);
+ executeGroovyScript(groovyscript, af);
+ System.out.println("CMD groovy[" + groovyscript
+ + "] executed successfully!");
- if (outputFormat.equalsIgnoreCase("png"))
- {
- af.createPNG(new File(file));
- imageName = (new File(file)).getName();
- System.out.println("Creating PNG image: " + file);
- continue;
- }
- else if (outputFormat.equalsIgnoreCase("svg"))
- {
- File imageFile = new File(file);
- imageName = imageFile.getName();
- af.createSVG(imageFile);
- System.out.println("Creating SVG image: " + file);
- continue;
- }
- else if (outputFormat.equalsIgnoreCase("html"))
- {
- File imageFile = new File(file);
- imageName = imageFile.getName();
- HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
- htmlSVG.exportHTML(file);
+ }
+ else
+ {
+ System.err.println(
+ "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
+ + groovyscript);
+ }
+ }
- System.out.println("Creating HTML image: " + file);
- continue;
- }
- else if (outputFormat.equalsIgnoreCase("biojsmsa"))
- {
- if (file == null)
- {
- System.err.println("The output html file must not be null");
- return;
- }
- try
- {
- BioJsHTMLOutput.refreshVersionInfo(
- BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
- } catch (URISyntaxException e)
- {
- e.printStackTrace();
- }
- BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
- bjs.exportHTML(file);
- System.out
- .println("Creating BioJS MSA Viwer HTML file: " + file);
- continue;
- }
- else if (outputFormat.equalsIgnoreCase("imgMap"))
- {
- af.createImageMap(new File(file), imageName);
- System.out.println("Creating image map: " + file);
- continue;
- }
- else if (outputFormat.equalsIgnoreCase("eps"))
- {
- File outputFile = new File(file);
- System.out.println(
- "Creating EPS file: " + outputFile.getAbsolutePath());
- af.createEPS(outputFile);
- continue;
- }
- FileFormatI outFormat = null;
- try
- {
- outFormat = FileFormats.getInstance().forName(outputFormat);
- } catch (Exception formatP)
- {
- System.out.println("Couldn't parse " + outFormat
- + " as a valid Jalview format string.");
- }
- if (outFormat != null)
- {
- if (!outFormat.isWritable())
- {
- System.out.println(
- "This version of Jalview does not support alignment export as "
- + outputFormat);
- }
- else
- {
- af.saveAlignment(file, outFormat);
- if (af.isSaveAlignmentSuccessful())
- {
- System.out.println("Written alignment in "
- + outFormat.getName() + " format to " + file);
- }
- else
- {
- System.out.println("Error writing file " + file + " in "
- + outFormat.getName() + " format!!");
- }
- }
- }
+ // and finally, turn off batch mode indicator - if the desktop still exists
+ if (desktop != null)
+ {
+ if (progress != -1)
+ {
+ desktop.setProgressBar(null, progress);
+ }
+ desktop.setInBatchMode(false);
+ }
+
+ if (jsApp != null) {
+ jsApp.callInitCallback();
+ }
+ }
+
+ /**
+ * Set general display parameters irrespective of file loading or headlessness.
+ *
+ * @param aparser
+ */
+ private void setDisplayParameters(ArgsParser aparser)
+ {
+ if (aparser.contains(ArgsParser.NOMENUBAR))
+ {
+ noMenuBar = true;
+ System.out.println("CMD [nomenu] executed successfully!");
+ }
- }
+ if (aparser.contains(ArgsParser.NOSTATUS))
+ {
+ noStatus = true;
+ System.out.println("CMD [nostatus] executed successfully!");
+ }
- while (aparser.getSize() > 0)
- {
- System.out.println("Unknown arg: " + aparser.nextValue());
- }
- }
+ if (aparser.contains(ArgsParser.NOANNOTATION)
+ || aparser.contains(ArgsParser.NOANNOTATION2))
+ {
+ noAnnotation = true;
+ System.out.println("CMD no-annotation executed successfully!");
}
- AlignFrame startUpAlframe = null;
- // We'll only open the default file if the desktop is visible.
- // And the user
- // ////////////////////
+ if (aparser.contains(ArgsParser.NOCALCULATION))
+ {
+ noCalculation = true;
+ System.out.println("CMD [nocalculation] executed successfully!");
+ }
+ }
-
- if (!Platform.isJS() && !headless && file == null
- && Cache.getDefault("SHOW_STARTUP_FILE", true))
- /**
- * Java only
- *
- * @j2sIgnore
- */
+ private void setFrameDependentProperties(ArgsParser aparser,
+ AlignFrame af)
+ {
+ String data = aparser.getValue(ArgsParser.COLOUR, true);
+ if (data != null)
{
- file = Cache.getDefault("STARTUP_FILE",
- Cache.getDefault("www.jalview.org", "https://www.jalview.org")
- + "/examples/exampleFile_2_7.jvp");
- if (file.equals("http://www.jalview.org/examples/exampleFile_2_3.jar")
- || file.equals(
- "http://www.jalview.org/examples/exampleFile_2_7.jar"))
+ data.replaceAll("%20", " ");
+
+ ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
+ af.getViewport(), af.getViewport().getAlignment(), data);
+
+ if (cs != null)
{
- file.replace("http:", "https:");
- // hardwire upgrade of the startup file
- file.replace("_2_3", "_2_7");
- file.replace("2_7.jar", "2_7.jvp");
- // and remove the stale setting
- Cache.removeProperty("STARTUP_FILE");
+ System.out.println(
+ "CMD [-color " + data + "] executed successfully!");
}
+ af.changeColour(cs);
+ }
- protocol = AppletFormatAdapter.checkProtocol(file);
+ // Must maintain ability to use the groups flag
+ data = aparser.getValue(ArgsParser.GROUPS, true);
+ if (data != null)
+ {
+ af.parseFeaturesFile(data,
+ AppletFormatAdapter.checkProtocol(data));
+ // System.out.println("Added " + data);
+ System.out.println(
+ "CMD groups[-" + data + "] executed successfully!");
+ }
+ data = aparser.getValue(ArgsParser.FEATURES, true);
+ if (data != null)
+ {
+ af.parseFeaturesFile(data,
+ AppletFormatAdapter.checkProtocol(data));
+ // System.out.println("Added " + data);
+ System.out.println(
+ "CMD [-features " + data + "] executed successfully!");
+ }
+ data = aparser.getValue(ArgsParser.ANNOTATIONS, true);
+ if (data != null)
+ {
+ af.loadJalviewDataFile(data, null, null, null);
+ // System.out.println("Added " + data);
+ System.out.println(
+ "CMD [-annotations " + data + "] executed successfully!");
+ }
- if (file.endsWith(".jar"))
+ // JavaScript feature
+
+ if (aparser.contains(ArgsParser.SHOWOVERVIEW))
+ {
+ af.overviewMenuItem_actionPerformed(null);
+ System.out.println("CMD [showoverview] executed successfully!");
+ }
+
+ // set or clear the sortbytree flag.
+ if (aparser.contains(ArgsParser.SORTBYTREE))
+ {
+ af.getViewport().setSortByTree(true);
+ if (af.getViewport().getSortByTree())
{
- format = FileFormat.Jalview;
+ System.out.println("CMD [-sortbytree] executed successfully!");
}
- else
+ }
+
+ boolean doUpdateAnnotation = false;
+ /**
+ * we do this earlier in JalviewJS because of a complication with
+ * SHOWOVERVIEW
+ *
+ * For now, just fixing this in JalviewJS.
+ *
+ *
+ * @j2sIgnore
+ *
+ */
+ {
+ if (noAnnotation)
{
- try
+ af.getViewport().setShowAnnotation(false);
+ if (!af.getViewport().isShowAnnotation())
{
- format = new IdentifyFile().identify(file, protocol);
- } catch (FileFormatException e)
- {
- // TODO what?
+ doUpdateAnnotation = true;
}
}
+
- startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
- format);
- // extract groovy arguments before anything else.
}
- // Once all other stuff is done, execute any groovy scripts (in order)
- if (groovyscript != null)
+ if (aparser.contains(ArgsParser.NOSORTBYTREE))
{
- if (Cache.groovyJarsPresent())
+ af.getViewport().setSortByTree(false);
+ if (!af.getViewport().getSortByTree())
{
- System.out.println("Executing script " + groovyscript);
- executeGroovyScript(groovyscript, startUpAlframe);
+ doUpdateAnnotation = true;
+ System.out
+ .println("CMD [-nosortbytree] executed successfully!");
}
- else
+ }
+ if (doUpdateAnnotation)
+ { // BH 2019.07.24
+ af.setMenusForViewport();
+ af.alignPanel.updateLayout();
+ }
+
+ data = aparser.getValue(ArgsParser.TREE, true);
+ if (data != null)
+ {
+ try
{
- System.err.println(
- "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
- + groovyscript);
+ NewickFile nf = new NewickFile(data,
+ AppletFormatAdapter.checkProtocol(data));
+ af.getViewport()
+ .setCurrentTree(af.showNewickTree(nf, data).getTree());
+ System.out.println(
+ "CMD [-tree " + data + "] executed successfully!");
+ } catch (IOException ex)
+ {
+ System.err.println("Couldn't add tree " + data);
+ ex.printStackTrace(System.err);
}
}
- // and finally, turn off batch mode indicator - if the desktop still exists
- if (desktop != null)
+ // TODO - load PDB structure(s) to alignment JAL-629
+ // (associate with identical sequence in alignment, or a specified
+ // sequence)
+
+ }
+
+ /**
+ * Writes an output file for each format (if any) specified in the
+ * command-line arguments. Supported formats are currently
+ * <ul>
+ * <li>png</li>
+ * <li>svg</li>
+ * <li>html</li>
+ * <li>biojsmsa</li>
+ * <li>imgMap</li>
+ * <li>eps</li>
+ * </ul>
+ * A format parameter should be followed by a parameter specifying the output
+ * file name. {@code imgMap} parameters should follow those for the
+ * corresponding alignment image output.
+ *
+ * @param aparser
+ * @param format
+ */
+ private void createOutputFiles(ArgsParser aparser, FileFormatI format)
+ {
+ // logic essentially the same as 2.11.2/2.11.3 but uses a switch instead
+ AlignFrame af = currentAlignFrame;
+ while (aparser.getSize() >= 2)
{
- if (progress != -1)
+ String outputFormat = aparser.nextValue();
+ File imageFile;
+ String fname;
+ switch (outputFormat.toLowerCase(Locale.ROOT))
{
- desktop.setProgressBar(null, progress);
+ case "png":
+ imageFile = new File(aparser.nextValue());
+ af.createPNG(imageFile);
+ System.out.println(
+ "Creating PNG image: " + imageFile.getAbsolutePath());
+ continue;
+ case "svg":
+ imageFile = new File(aparser.nextValue());
+ af.createSVG(imageFile);
+ System.out.println(
+ "Creating SVG image: " + imageFile.getAbsolutePath());
+ continue;
+ case "eps":
+ imageFile = new File(aparser.nextValue());
+ System.out.println(
+ "Creating EPS file: " + imageFile.getAbsolutePath());
+ af.createEPS(imageFile);
+ continue;
+ case "biojsmsa":
+ fname = new File(aparser.nextValue()).getAbsolutePath();
+ try
+ {
+ BioJsHTMLOutput.refreshVersionInfo(
+ BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
+ } catch (URISyntaxException e)
+ {
+ e.printStackTrace();
+ }
+ BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
+ bjs.exportHTML(fname);
+ System.out.println("Creating BioJS MSA Viwer HTML file: " + fname);
+ continue;
+ case "html":
+ fname = new File(aparser.nextValue()).getAbsolutePath();
+ HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
+ htmlSVG.exportHTML(fname);
+ System.out.println("Creating HTML image: " + fname);
+ continue;
+ case "imgmap":
+ imageFile = new File(aparser.nextValue());
+ af.alignPanel.makePNGImageMap(imageFile, "unnamed.png");
+ System.out.println(
+ "Creating image map: " + imageFile.getAbsolutePath());
+ continue;
+ default:
+ // fall through - try to parse as an alignment data export format
+ FileFormatI outFormat = null;
+ try
+ {
+ outFormat = FileFormats.getInstance().forName(outputFormat);
+ } catch (Exception formatP)
+ {
+ }
+ if (outFormat == null)
+ {
+ System.out.println("Couldn't parse " + outputFormat
+ + " as a valid Jalview format string.");
+ continue;
+ }
+ if (!outFormat.isWritable())
+ {
+ System.out.println(
+ "This version of Jalview does not support alignment export as "
+ + outputFormat);
+ continue;
+ }
+ // record file as it was passed to Jalview so it is recognisable to the CLI
+ // caller
+ String file;
+ fname = new File(file = aparser.nextValue()).getAbsolutePath();
+ // JBPNote - yuck - really wish we did have a bean returned from this which gave
+ // success/fail like before !
+ af.saveAlignment(fname, outFormat);
+ if (!af.isSaveAlignmentSuccessful())
+ {
+ System.out.println("Written alignment in " + outputFormat
+ + " format to " + file);
+ continue;
+ }
+ else
+ {
+ System.out.println("Error writing file " + file + " in "
+ + outputFormat + " format!!");
+ }
}
- desktop.setInBatchMode(false);
+ }
+ // ??? Should report - 'ignoring' extra args here...
+ while (aparser.getSize() > 0)
+ {
+ System.out.println("Ignoring extra argument: " + aparser.nextValue());
}
}
private static void setLookAndFeel()
{
- // property laf = "crossplatform", "system", "gtk", "metal", "nimbus" or
- // "mac"
+ // property laf = "crossplatform", "system", "gtk", "metal", "nimbus",
+ // "mac" or "flat"
// If not set (or chosen laf fails), use the normal SystemLaF and if on Mac,
// try Quaqua/Vaqua.
String lafProp = System.getProperty("laf");
lafSet = setCrossPlatformLookAndFeel();
if (!lafSet)
{
- Cache.log.error("Could not set requested laf=" + laf);
+ Console.error("Could not set requested laf=" + laf);
}
break;
case "system":
lafSet = setSystemLookAndFeel();
if (!lafSet)
{
- Cache.log.error("Could not set requested laf=" + laf);
+ Console.error("Could not set requested laf=" + laf);
}
break;
case "gtk":
lafSet = setGtkLookAndFeel();
if (!lafSet)
{
- Cache.log.error("Could not set requested laf=" + laf);
+ Console.error("Could not set requested laf=" + laf);
}
break;
case "metal":
lafSet = setMetalLookAndFeel();
if (!lafSet)
{
- Cache.log.error("Could not set requested laf=" + laf);
+ Console.error("Could not set requested laf=" + laf);
}
break;
case "nimbus":
lafSet = setNimbusLookAndFeel();
if (!lafSet)
{
- Cache.log.error("Could not set requested laf=" + laf);
+ Console.error("Could not set requested laf=" + laf);
+ }
+ break;
+ case "flat":
+ lafSet = setFlatLookAndFeel();
+ if (!lafSet)
+ {
+ Console.error("Could not set requested laf=" + laf);
}
break;
case "quaqua":
lafSet = setQuaquaLookAndFeel();
if (!lafSet)
{
- Cache.log.error("Could not set requested laf=" + laf);
+ Console.error("Could not set requested laf=" + laf);
}
break;
case "vaqua":
lafSet = setVaquaLookAndFeel();
if (!lafSet)
{
- Cache.log.error("Could not set requested laf=" + laf);
+ Console.error("Could not set requested laf=" + laf);
}
break;
case "mac":
lafSet = setMacLookAndFeel();
if (!lafSet)
{
- Cache.log.error("Could not set requested laf=" + laf);
+ Console.error("Could not set requested laf=" + laf);
}
break;
case "none":
break;
default:
- Cache.log.error("Requested laf=" + laf + " not implemented");
+ Console.error("Requested laf=" + laf + " not implemented");
}
if (!lafSet)
{
set = true;
} catch (Exception ex)
{
- Cache.log.error("Unexpected Look and Feel Exception");
- Cache.log.error(ex.getMessage());
- Cache.log.debug(Cache.getStackTraceString(ex));
+ Console.error("Unexpected Look and Feel Exception");
+ Console.error(ex.getMessage());
+ Console.debug(Cache.getStackTraceString(ex));
}
return set;
}
set = true;
} catch (Exception ex)
{
- Cache.log.error("Unexpected Look and Feel Exception");
- Cache.log.error(ex.getMessage());
- Cache.log.debug(Cache.getStackTraceString(ex));
+ Console.error("Unexpected Look and Feel Exception");
+ Console.error(ex.getMessage());
+ Console.debug(Cache.getStackTraceString(ex));
}
return set;
}
if (info.getName() != null && nameStartsWith
? info.getName().toLowerCase(Locale.ROOT)
.startsWith(name.toLowerCase(Locale.ROOT))
- : info.getName().toLowerCase(Locale.ROOT).equals(name.toLowerCase(Locale.ROOT)))
+ : info.getName().toLowerCase(Locale.ROOT)
+ .equals(name.toLowerCase(Locale.ROOT)))
{
className = info.getClassName();
break;
set = true;
} catch (Exception ex)
{
- Cache.log.error("Unexpected Look and Feel Exception");
- Cache.log.error(ex.getMessage());
- Cache.log.debug(Cache.getStackTraceString(ex));
+ Console.error("Unexpected Look and Feel Exception");
+ Console.error(ex.getMessage());
+ Console.debug(Cache.getStackTraceString(ex));
}
return set;
}
"javax.swing.plaf.nimbus.NimbusLookAndFeel", false);
}
+ private static boolean setFlatLookAndFeel()
+ {
+ boolean set = setSpecificLookAndFeel("flatlaf light",
+ "com.formdev.flatlaf.FlatLightLaf", false);
+ if (set)
+ {
+ if (Platform.isMac())
+ {
+ System.setProperty("apple.laf.useScreenMenuBar", "true");
+ System.setProperty("apple.awt.application.name",
+ ChannelProperties.getProperty("app_name"));
+ System.setProperty("apple.awt.application.appearance", "system");
+ if (SystemInfo.isMacFullWindowContentSupported
- && Desktop.desktop != null)
++ && Desktop.getInstance() != null)
+ {
- Desktop.desktop.getRootPane()
++ Desktop.getInstance().getRootPane()
+ .putClientProperty("apple.awt.fullWindowContent", true);
- Desktop.desktop.getRootPane()
++ Desktop.getInstance().getRootPane()
+ .putClientProperty("apple.awt.transparentTitleBar", true);
+ }
+
+ SwingUtilities.invokeLater(() -> {
+ FlatLightLaf.setup();
+ });
+ }
+
+ UIManager.put("TabbedPane.showTabSeparators", true);
+ UIManager.put("TabbedPane.tabSeparatorsFullHeight", true);
+ UIManager.put("TabbedPane.tabsOverlapBorder", true);
+ // UIManager.put("TabbedPane.hasFullBorder", true);
+ UIManager.put("TabbedPane.tabLayoutPolicy", "scroll");
+ UIManager.put("TabbedPane.scrollButtonsPolicy", "asNeeded");
+ UIManager.put("TabbedPane.smoothScrolling", true);
+ UIManager.put("TabbedPane.tabWidthMode", "compact");
+ UIManager.put("TabbedPane.selectedBackground", Color.white);
+ }
+ return set;
+ }
-
private static boolean setQuaquaLookAndFeel()
{
return setSpecificLookAndFeel("quaqua",
System.setProperty("com.apple.mrj.application.apple.menu.about.name",
ChannelProperties.getProperty("app_name"));
System.setProperty("apple.laf.useScreenMenuBar", "true");
+ /*
+ * broken native LAFs on (ARM?) macbooks
set = setQuaquaLookAndFeel();
if ((!set) || !UIManager.getLookAndFeel().getClass().toString()
.toLowerCase(Locale.ROOT).contains("quaqua"))
{
set = setVaquaLookAndFeel();
}
+ */
+ set = setFlatLookAndFeel();
return set;
}
+
private static void showUsage()
{
System.out.println(
/**
* start a User Config prompt asking if we can log usage statistics.
*/
- PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
+ PromptUserConfig prompter = new PromptUserConfig(Desktop.getDesktopPane(),
"USAGESTATS", "Jalview Usage Statistics",
"Do you want to help make Jalview better by enabling "
+ "the collection of usage statistics with Google Analytics ?"
@Override
public void run()
{
- Cache.log.debug(
+ Console.debug(
"Initialising googletracker for usage stats.");
Cache.initGoogleTracker();
- Cache.log.debug("Tracking enabled.");
+ Console.debug("Tracking enabled.");
}
}, new Runnable()
{
@Override
public void run()
{
- Cache.log.debug("Not enabling Google Tracking.");
+ Console.debug("Not enabling Google Tracking.");
}
}, null, true);
desktop.addDialogThread(prompter);
}
/**
- * Quit method delegates to Desktop.quit - unless running in headless mode
- * when it just ends the JVM
+ * Quit method delegates to Desktop.quit - unless running in headless mode when
+ * it just ends the JVM
*/
public void quit()
{
public static AlignFrame getCurrentAlignFrame()
{
- return Jalview.currentAlignFrame;
+ return Jalview.getInstance().currentAlignFrame;
}
public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
{
- Jalview.currentAlignFrame = currentAlignFrame;
+ Jalview.getInstance().currentAlignFrame = currentAlignFrame;
+ }
+
+ public void notifyWorker(AlignCalcWorkerI worker, String status)
+ {
+ // System.out.println("Jalview worker " + worker.getClass().getSimpleName()
+ // + " " + status);
+ }
+
+
+ private static boolean isInteractive = true;
+
+ public static boolean isInteractive()
+ {
+ return isInteractive;
+ }
+
+ public static void setInteractive(boolean tf)
+ {
+ isInteractive = tf;
}
}
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.bin;
import jalview.util.Platform;
import javax.swing.Timer;
/**
- * Entry point for JalviewJS development.
+ * Entry point for JalviewJS development.
*
*
*
public class JalviewJS2
{
- static {
+ static
+ {
/**
- * @j2sNative
+ * @ could do it this way:
*
- * J2S.thisApplet.__Info.args =
- * ["open","examples/uniref50.fa","features",
- * "examples/exampleFeatures.txt"];
+ * j2sNative
+ *
+ * J2S.thisApplet.__Info.args = [ "open","examples/uniref50.fa",
+ * "features","examples/exampleFeatures.txt", "noannotation" ];
*/
}
public static void main(String[] args) throws Exception
{
+ if (args.length == 0)
+ {
+ args = new String[] {
+ // "headless",
+ "open", "examples/uniref50.fa",
+// "features",
+// "examples/exampleFeatures.txt"
+// , "noannotation"
+ //, "showoverview"
+ //, "png", "test-bh.png"
+ };
+ }
+
+ // String cmds = "nodisplay -open examples/uniref50.fa -sortbytree -props
+ // test/jalview/io/testProps.jvprops -colour zappo "
+ // + "-jabaws http://www.compbio.dundee.ac.uk/jabaws -nosortbytree "
+ // + "-features examples/testdata/plantfdx.features -annotations
+ // examples/testdata/plantfdx.annotations -tree
+ // examples/testdata/uniref50_test_tree";
+ // args = cmds.split(" ");
Jalview.main(args);
- //showFocusTimer();
- }
+ // showFocusTimer();
+ }
- protected static int focusTime = 0;
+ protected static int focusTime = 0;
private static void showFocusTimer()
{
}
}
-
}
import jalview.io.JPredFile;
import jalview.io.JnetAnnotationMaker;
import jalview.io.NewickFile;
-import jalview.javascript.JSFunctionExec;
-import jalview.javascript.JalviewLiteJsApi;
-import jalview.javascript.JsCallBack;
-import jalview.javascript.MouseOverStructureListener;
+import jalview.appletgui.js.JSFunctionExec;
+import jalview.appletgui.js.JalviewLiteJsApi;
+import jalview.appletgui.js.JsCallBack;
+import jalview.appletgui.js.JsSelectionSender;
+import jalview.appletgui.js.MouseOverListener;
+import jalview.appletgui.js.MouseOverStructureListener;
import jalview.structure.SelectionListener;
import jalview.structure.StructureSelectionManager;
import jalview.util.ColorUtils;
final StructureSelectionManagerProvider me = this;
final int pos = apos;
// use vamsas listener to broadcast to all listeners in scope
- if (alignedPosition != null && (alignedPosition.trim().length() == 0
- || alignedPosition.toLowerCase(Locale.ROOT).indexOf("false") > -1))
+ if (alignedPosition != null
+ && (alignedPosition.trim().length() == 0 || alignedPosition
+ .toLowerCase(Locale.ROOT).indexOf("false") > -1))
{
java.awt.EventQueue.invokeLater(new Runnable()
{
setMouseoverListener(currentAlignFrame, listener);
}
- private Vector<jalview.javascript.JSFunctionExec> javascriptListeners = new Vector<>();
+ private Vector<JSFunctionExec> javascriptListeners = new Vector<>();
/*
* (non-Javadoc)
return;
}
}
- jalview.javascript.MouseOverListener mol = new jalview.javascript.MouseOverListener(
+ MouseOverListener mol = new MouseOverListener(
this, af, listener);
javascriptListeners.addElement(mol);
StructureSelectionManager.getStructureSelectionManager(this)
return;
}
}
- jalview.javascript.JsSelectionSender mol = new jalview.javascript.JsSelectionSender(
+ JsSelectionSender mol = new JsSelectionSender(
this, af, listener);
javascriptListeners.addElement(mol);
StructureSelectionManager.getStructureSelectionManager(this)
{
while (javascriptListeners.size() > 0)
{
- jalview.javascript.JSFunctionExec mol = javascriptListeners
+ JSFunctionExec mol = javascriptListeners
.elementAt(0);
javascriptListeners.removeElement(mol);
if (mol instanceof SelectionListener)
StructureSelectionManager.release(this);
}
- private jalview.javascript.JSFunctionExec jsFunctionExec;
+ private JSFunctionExec jsFunctionExec;
/*
* (non-Javadoc)
* (non-Javadoc)
*
* @see
- * jalview.javascript.JalviewLiteJsApi#scrollViewToRowIn(jalview.appletgui
+ * JalviewLiteJsApi#scrollViewToRowIn(jalview.appletgui
* .AlignFrame, java.lang.String)
*/
@Override
* (non-Javadoc)
*
* @see
- * jalview.javascript.JalviewLiteJsApi#scrollViewToColumnIn(jalview.appletgui
+ * JalviewLiteJsApi#scrollViewToColumnIn(jalview.appletgui
* .AlignFrame, java.lang.String)
*/
@Override
String externalsviewer = getParameter("externalstructureviewer");
if (externalsviewer != null)
{
- useXtrnalSviewer = externalsviewer.trim().toLowerCase(Locale.ROOT).equals(TRUE);
+ useXtrnalSviewer = externalsviewer.trim().toLowerCase(Locale.ROOT)
+ .equals(TRUE);
}
/**
* if true disable the check for jmol
{
synchronized (sequences)
{
-
+
if (i > -1 && i < sequences.size())
{
return sequences.get(i);
}
/**
+ * Inserts a sequence at a point in the alignment.
+ *
+ * @param i
+ * the index of the position the sequence is to be inserted in.
+ */
+ @Override
+ public void insertSequenceAt(int i, SequenceI snew)
+ {
+ synchronized (sequences)
+ {
+ if (sequences.size() > i)
+ {
+ sequences.add(i, snew);
+ return;
+
+ }
+ else
+ {
+ sequences.add(snew);
+ hiddenSequences.adjustHeightSequenceAdded();
+ }
+ return;
+ }
+ }
+
+ /**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
@Override
public SequenceI findName(SequenceI startAfter, String token, boolean b)
{
-
+ if (token == null)
+ return null;
int i = 0;
SequenceI sq = null;
String sqname = null;
public int getWidth()
{
int maxLength = -1;
-
+
for (int i = 0; i < sequences.size(); i++)
{
maxLength = Math.max(maxLength, getSequenceAt(i).getLength());
String calcId, boolean autoCalc, SequenceI seqRef,
SequenceGroup groupRef)
{
- if (annotations != null)
+ AlignmentAnnotation annot = annotations == null ? null
+ : AlignmentAnnotation.findFirstAnnotation(
+ Arrays.asList(getAlignmentAnnotation()), name, calcId,
+ autoCalc, seqRef, groupRef);
+
+ if (annot == null)
{
- for (AlignmentAnnotation annot : getAlignmentAnnotation())
+
+ annot = new AlignmentAnnotation(name, name, new Annotation[1], 0f, 0f,
+ AlignmentAnnotation.BAR_GRAPH);
+ annot.hasText = false;
+ if (calcId != null)
{
- if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
- && (calcId == null || annot.getCalcId().equals(calcId))
- && annot.sequenceRef == seqRef
- && annot.groupRef == groupRef)
- {
- return annot;
- }
+ annot.setCalcId(calcId);
+ }
+ annot.autoCalculated = autoCalc;
+ if (seqRef != null)
+ {
+ annot.setSequenceRef(seqRef);
}
+ annot.groupRef = groupRef;
+ addAnnotation(annot);
}
- AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
- new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
- annot.hasText = false;
- if (calcId != null)
+ return annot;
+ }
+
+
+ @Override
+ public AlignmentAnnotation updateFromOrCopyAnnotation(
+ AlignmentAnnotation ala)
+ {
+ AlignmentAnnotation annot = AlignmentAnnotation.findFirstAnnotation(
+ Arrays.asList(getAlignmentAnnotation()), ala.label, ala.calcId,
+ ala.autoCalculated, ala.sequenceRef, ala.groupRef);
+ if (annot == null)
{
- annot.setCalcId(new String(calcId));
+ annot = new AlignmentAnnotation(ala);
+ addAnnotation(annot);
}
- annot.autoCalculated = autoCalc;
- if (seqRef != null)
+ else
{
- annot.setSequenceRef(seqRef);
+ annot.updateAlignmentAnnotationFrom(ala);
}
- annot.groupRef = groupRef;
- addAnnotation(annot);
-
+ validateAnnotation(annot);
return annot;
}
}
}
+ @Override
+ public List<SequenceI> getHmmSequences()
+ {
+ List<SequenceI> result = new ArrayList<>();
+ for (int i = 0; i < sequences.size(); i++)
+ {
+ SequenceI seq = sequences.get(i);
+ if (seq.hasHMMProfile())
+ {
+ result.add(seq);
+ }
+ }
+ return result;
+ }
}
*/
package jalview.datamodel;
- import java.util.Locale;
-
- import jalview.analysis.Rna;
- import jalview.analysis.SecStrConsensus.SimpleBP;
- import jalview.analysis.WUSSParseException;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
+ import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
+ import jalview.analysis.Rna;
+ import jalview.analysis.SecStrConsensus.SimpleBP;
+ import jalview.analysis.WUSSParseException;
+
/**
* DOCUMENT ME!
*
*/
private long invalidrnastruc = -2;
+ private double bitScore;
+
+ private double eValue;
+
/**
* Updates the _rnasecstr field Determines the positions that base pair and
* the positions of helices based on secondary structure from a Stockholm file
return rnaSecondaryStructureEquivalent(that, true);
}
- public boolean rnaSecondaryStructureEquivalent(AlignmentAnnotation that, boolean compareType)
+ public boolean rnaSecondaryStructureEquivalent(AlignmentAnnotation that,
+ boolean compareType)
{
SequenceFeature[] thisSfArray = this.getRnaSecondaryStructure();
SequenceFeature[] thatSfArray = that.getRnaSecondaryStructure();
return false;
}
Arrays.sort(thisSfArray, new SFSortByEnd()); // probably already sorted
- // like this
+ // like this
Arrays.sort(thatSfArray, new SFSortByEnd()); // probably already sorted
- // like this
- for (int i=0; i < thisSfArray.length; i++) {
+ // like this
+ for (int i = 0; i < thisSfArray.length; i++)
+ {
SequenceFeature thisSf = thisSfArray[i];
SequenceFeature thatSf = thatSfArray[i];
- if (compareType) {
- if (thisSf.getType() == null || thatSf.getType() == null) {
- if (thisSf.getType() == null && thatSf.getType() == null) {
+ if (compareType)
+ {
+ if (thisSf.getType() == null || thatSf.getType() == null)
+ {
+ if (thisSf.getType() == null && thatSf.getType() == null)
+ {
continue;
- } else {
+ }
+ else
+ {
return false;
}
}
- if (! thisSf.getType().equals(thatSf.getType())) {
+ if (!thisSf.getType().equals(thatSf.getType()))
+ {
return false;
}
}
// annotations[i].secondaryStructure + "'");
// TODO: 2.8.2 should this ss symbol validation check be a function in
// RNA/ResidueProperties ?
+ // allow for DSSP extended code:
+ // https://www.wikidoc.org/index.php/Secondary_structure#The_DSSP_code
+ // GHITEBS as well as C and X (for missing?)
if (annotations[i].secondaryStructure == '('
|| annotations[i].secondaryStructure == '['
|| annotations[i].secondaryStructure == '<'
|| annotations[i].secondaryStructure == '{'
|| annotations[i].secondaryStructure == 'A'
- || annotations[i].secondaryStructure == 'B'
- || annotations[i].secondaryStructure == 'C'
+ // || annotations[i].secondaryStructure == 'B'
+ // || annotations[i].secondaryStructure == 'C'
|| annotations[i].secondaryStructure == 'D'
// || annotations[i].secondaryStructure == 'E' // ambiguous on
// its own -- already checked above
|| annotations[i].secondaryStructure == 'F'
- || annotations[i].secondaryStructure == 'G'
+ // || annotations[i].secondaryStructure == 'G'
// || annotations[i].secondaryStructure == 'H' // ambiguous on
// its own -- already checked above
- || annotations[i].secondaryStructure == 'I'
+ // || annotations[i].secondaryStructure == 'I'
|| annotations[i].secondaryStructure == 'J'
|| annotations[i].secondaryStructure == 'K'
|| annotations[i].secondaryStructure == 'L'
|| annotations[i].secondaryStructure == 'P'
|| annotations[i].secondaryStructure == 'Q'
|| annotations[i].secondaryStructure == 'R'
- || annotations[i].secondaryStructure == 'S'
- || annotations[i].secondaryStructure == 'T'
+ // || annotations[i].secondaryStructure == 'S'
+ // || annotations[i].secondaryStructure == 'T'
|| annotations[i].secondaryStructure == 'U'
|| annotations[i].secondaryStructure == 'V'
|| annotations[i].secondaryStructure == 'W'
- || annotations[i].secondaryStructure == 'X'
+ // || annotations[i].secondaryStructure == 'X'
|| annotations[i].secondaryStructure == 'Y'
|| annotations[i].secondaryStructure == 'Z')
{
: annotations[index + offset].displayCharacter == null
|| annotations[index
+ offset].displayCharacter
- .length() == 0
- ? annotations[index
- + offset].secondaryStructure
- : annotations[index
- + offset].displayCharacter
- .charAt(0));
+ .length() == 0
+ ? annotations[index
+ + offset].secondaryStructure
+ : annotations[index
+ + offset].displayCharacter
+ .charAt(0));
}
@Override
}
return null;
}
-
+
/**
* Creates a new AlignmentAnnotation object.
*
}
}
}
-
+
/**
* Copy constructor creates a new independent annotation row with the same
* associated sequenceRef
public AlignmentAnnotation(AlignmentAnnotation annotation)
{
setAnnotationId();
+ updateAlignmentAnnotationFrom(annotation);
+ }
+
+ /**
+ * copy attributes and annotation from an existing annotation (used by copy
+ * constructor). This method does not update the unique annotationId
+ *
+ * @param annotation
+ */
+ public void updateAlignmentAnnotationFrom(AlignmentAnnotation annotation)
+ {
this.label = new String(annotation.label);
if (annotation.description != null)
{
this.scaleColLabel = annotation.scaleColLabel;
this.showAllColLabels = annotation.showAllColLabels;
this.calcId = annotation.calcId;
+ this.bitScore = annotation.bitScore;
+ this.eValue = annotation.eValue;
+
if (annotation.properties != null)
{
properties = new HashMap<>();
* @param seqRef
* @param startRes
* @param alreadyMapped
+ * - annotation are at aligned columns
*/
public void createSequenceMapping(SequenceI seqRef, int startRes,
boolean alreadyMapped)
{
return hasScore || !Double.isNaN(score);
}
-
+
/**
* Score only annotation
*
makeVisibleAnnotation(hidden);
}
+
public void setPadGaps(boolean padgaps, char gapchar)
{
this.padGaps = padgaps;
Iterable<AlignmentAnnotation> list, SequenceI seq, String calcId,
String label)
{
-
ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
for (AlignmentAnnotation ann : list)
{
public static Iterable<AlignmentAnnotation> findAnnotation(
List<AlignmentAnnotation> list, String calcId)
{
-
List<AlignmentAnnotation> aa = new ArrayList<>();
if (calcId == null)
{
return aa;
}
+ public double getBitScore()
+ {
+ return bitScore;
+ }
+
+ public void setBitScore(double bitScore)
+ {
+ this.bitScore = bitScore;
+ }
+
+ public double getEValue()
+ {
+ return eValue;
+ }
+
+ public void setEValue(double eValue)
+ {
+ this.eValue = eValue;
+ }
+
+ public static AlignmentAnnotation findFirstAnnotation(
+ Iterable<AlignmentAnnotation> alignmentAnnotation, String name,
+ String calcId, boolean autoCalc, SequenceI seqRef,
+ SequenceGroup groupRef)
+ {
+
+ for (AlignmentAnnotation annot : alignmentAnnotation)
+ {
+ if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
+ && (calcId == null || annot.getCalcId().equals(calcId))
+ && annot.sequenceRef == seqRef && annot.groupRef == groupRef)
+ {
+ return annot;
+ }
+ }
+ return null;
+ }
+
}
*/
package jalview.datamodel;
-import jalview.util.CaseInsensitiveString;
-
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
+import jalview.util.CaseInsensitiveString;
+
public class PDBEntry
{
private static final int PDB_ID_LENGTH = 4;
+ /**
+ * property set when id is a 'manufactured' identifier from the structure
+ * data's filename
+ */
private static final String FAKED_ID = "faked_pdbid";
+ /**
+ * property set when the id is authoritative, and should be used in preference
+ * to any identifiers in the structure data
+ */
+ private static final String AUTHORITATIVE_ID = "authoritative_pdbid";
+
private String file;
private String type;
{
// TODO is FILE needed; if not is this enum needed, or can we
// use FileFormatI for PDB, MMCIF?
- PDB("pdb", "pdb"), MMCIF("mmcif", "cif"), BCIF("bcif","bcif"),FILE("?", "?");
+ PDB("pdb", "pdb"), MMCIF("mmcif", "cif"), BCIF("bcif", "bcif"),
+ FILE("?", "?");
/*
* file extension for cached structure file; must be one that
{
}
+ /**
+ * Entry point when file is not known and fileType may be string
+ * @param pdbId
+ * @param chain may be null
+ * @param fileType "pdb", "mmcif", or "bcif"; null defaults to mmcif
+ */
+ public PDBEntry(String pdbId, String chain, String fileType) {
+ this.id = pdbId.toLowerCase();
+ setChainCode(chain); // I note that PDB Chains ARE case-sensitive now
+ if (fileType == null)
+ fileType = "mmcif";
+ switch (fileType.toLowerCase()) {
+ case "pdb":
+ this.type = Type.PDB.toString();
+ break;
+ case "mmcif":
+ this.type = Type.MMCIF.toString();
+ break;
+ default:
+ case "bcif":
+ System.out.println("format " + fileType + " has not been implemented; using mmCIF");
+ this.type = Type.MMCIF.toString();
+ break;
+ }
+ }
+
public PDBEntry(String pdbId, String chain, PDBEntry.Type type,
String filePath)
{
return id;
}
+ /**
+ * TODO
+ *
+ * @param key "protocol"
+ * @param value
+ */
public void setProperty(String key, Object value)
{
if (this.properties == null)
// this shouldn't happen, but could do if the id from the
// file is not the same as the id from the authority that provided
// the file
- if (!newEntry.fakedPDBId())
+ if (!newEntry.fakedPDBId() && !isAuthoritative())
{
return false;
} // otherwise we can update
*/
String key = newProps.nextElement();
Object value = newEntry.getProperty(key);
- if (FAKED_ID.equals(key))
+ if (FAKED_ID.equals(key) || AUTHORITATIVE_ID.equals(key))
{
// we never update the fake ID property
continue;
}
return true;
}
-
+
+ public void setAuthoritative(boolean isAuthoritative)
+ {
+ setProperty(AUTHORITATIVE_ID, Boolean.valueOf(isAuthoritative));
+ }
+
+ /**
+ *
+ * @return true if the identifier should be preferred over any identifiers
+ * embedded in the structure data
+ */
+ public boolean isAuthoritative()
+ {
+ if (_hasProperty(AUTHORITATIVE_ID))
+ {
+ return ((Boolean) getProperty(AUTHORITATIVE_ID));
+ }
+ return false;
+ }
+
/**
* set when Jalview has manufactured the ID using a local filename
+ *
* @return
*/
public boolean fakedPDBId()
}
return false;
}
+
public void setFakedPDBId(boolean faked)
{
if (faked)
{
setProperty(FAKED_ID, Boolean.TRUE);
}
- else
+ else
{
- if (properties!=null) {
+ if (properties != null)
+ {
properties.remove(FAKED_ID);
}
}
import jalview.util.QuickSort;
import jalview.util.SparseCount;
+import java.util.List;
+
/**
* A class to count occurrences of residues in a profile, optimised for speed
* and memory footprint.
}
/**
+ * A constructor that counts frequency of all symbols (including gaps) in the
+ * sequences (not case-sensitive)
+ *
+ * @param sequences
+ */
+ public ResidueCount(List<SequenceI> sequences)
+ {
+ this();
+ for (SequenceI seq : sequences)
+ {
+ for (int i = 0; i < seq.getLength(); i++)
+ {
+ add(seq.getCharAt(i));
+ }
+ }
+ }
+
+ /**
* Increments the count for the given character. The supplied character may be
* upper or lower case but counts are for the upper case only. Gap characters
* (space, ., -) are all counted together.
}
}
- if (offset!=GAP_COUNT)
+ if (offset != GAP_COUNT)
{
// update modal residue count
maxCount = Math.max(maxCount, newValue);
sb.append("]");
return sb.toString();
}
+
+ /**
+ * Answers the total count for all symbols (excluding gaps)
+ *
+ * @return
+ */
+ public int getTotalResidueCount()
+ {
+ int total = 0;
+ for (char symbol : this.getSymbolCounts().symbols)
+ {
+ total += getCount(symbol);
+ }
+ return total;
+ }
}
import jalview.util.DBRefUtils;
import jalview.util.MapList;
import jalview.util.StringUtils;
+import jalview.workers.InformationThread;
import java.util.ArrayList;
import java.util.Arrays;
private String vamsasId;
+ HiddenMarkovModel hmm;
+
+ boolean isHMMConsensusSequence = false;
private DBModList<DBRefEntry> dbrefs; // controlled access
/**
this.addPDBId(new PDBEntry(pdb));
}
}
+ if (seq.getHMM() != null)
+ {
+ this.hmm = new HiddenMarkovModel(seq.getHMM(), this);
+ }
}
@Override
@Override
public ContiguousI findPositions(int fromColumn, int toColumn)
{
- if (toColumn < fromColumn || fromColumn < 1)
+ fromColumn = Math.max(fromColumn, 1);
+ if (toColumn < fromColumn)
{
return null;
}
@Override
public void addDBRef(DBRefEntry entry)
{
+ // TODO JAL-3980 maintain as sorted list
if (datasetSequence != null)
{
datasetSequence.addDBRef(entry);
{
dbrefs = new DBModList<>();
}
+ // TODO JAL-3979 LOOK UP RATHER THAN SWEEP FOR EFFICIENCY
for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
{
{
for (AlignmentAnnotation ann : annotation)
{
- if ((ann.calcId != null && ann.calcId.equals(calcId))
+ String id = ann.getCalcId();
+ if ((id != null && id.equals(calcId))
&& (ann.label != null && ann.label.equals(label))
&& ((ignoreDescription && description == null)
|| (ann.description != null
&& ann.description.equals(description))))
-
{
result.add(ann);
}
}
}
+ @Override
+ public HiddenMarkovModel getHMM()
+ {
+ return hmm;
+ }
+
+ @Override
+ public void setHMM(HiddenMarkovModel hmm)
+ {
+ this.hmm = hmm;
+ }
+
+ @Override
+ public boolean hasHMMAnnotation()
+ {
+ if (this.annotation == null) {
+ return false;
+ }
+ for (AlignmentAnnotation ann : annotation)
+ {
+ if (InformationThread.HMM_CALC_ID.equals(ann.getCalcId()))
+ {
+ return true;
+ }
+ }
+ return false;
+ }
/**
* {@inheritDoc}
*/
// otherwise, sequence was completely hidden
return 0;
}
+
+ @Override
+ public boolean hasHMMProfile()
+ {
+ return hmm != null;
+ }
}
import jalview.renderer.ResidueShader;
import jalview.renderer.ResidueShaderI;
import jalview.schemes.ColourSchemeI;
+import jalview.util.MessageManager;
+import jalview.workers.InformationThread;
import java.awt.Color;
import java.beans.PropertyChangeListener;
public class SequenceGroup implements AnnotatedCollectionI
{
// TODO ideally this event notification functionality should be separated into
- // a
- // subclass of ViewportProperties similarly to ViewportRanges. Done here as
- // quick fix for JAL-2665
+ // a subclass of ViewportProperties similarly to ViewportRanges.
+ // Done here as a quick fix for JAL-2665
public static final String SEQ_GROUP_CHANGED = "Sequence group changed";
-
+
protected PropertyChangeSupport changeSupport = new PropertyChangeSupport(
this);
String groupName;
String description;
-
+
Conservation conserve;
+ Conservation conservationData;
+
+ ProfilesI consensusProfiles;
+
+ ProfilesI hmmProfiles;
+
boolean displayBoxes = true;
boolean displayText = true;
boolean colourText = false;
- /**
- * True if the group is defined as a group on the alignment, false if it is
- * just a selection.
+ /*
+ * true if the group is defined as a group on the alignment, false if it is
+ * just a selection
*/
boolean isDefined = false;
- /**
+ /*
* after Olivier's non-conserved only character display
*/
boolean showNonconserved = false;
- /**
- * group members
+ /*
+ * sequences in the group
*/
private List<SequenceI> sequences;
- /**
+ /*
* representative sequence for this group (if any)
*/
private SequenceI seqrep = null;
int width = -1;
- /**
- * Colourscheme applied to group if any
+ /*
+ * colour scheme applied to group if any
*/
public ResidueShaderI cs;
private int startRes = 0;
/**
- * end column (base 0)
+ * end column (base 0)
*/
private int endRes = 0;
public Color textColour2 = Color.white;
- /**
- * consensus calculation property
+ /*
+ * properties for consensus annotation
*/
private boolean ignoreGapsInConsensus = true;
- /**
- * consensus calculation property
- */
private boolean showSequenceLogo = false;
private boolean normaliseSequenceLogo;
/*
+ * properties for HMM information annotation
+ */
+ private boolean hmmIgnoreBelowBackground = true;
+
+ private boolean hmmUseInfoLetterHeight;
+
+ private boolean hmmShowSequenceLogo;
+
+ private boolean hmmNormaliseSequenceLogo;
+
+ private boolean hmmShowHistogram;
+
+ /*
* visibility of rows or represented rows covered by group
*/
private boolean hidereps = false;
/*
* visibility of columns intersecting this group
*/
- private boolean hidecols = false;
+ private boolean hidecols;
AlignmentAnnotation consensus = null;
AlignmentAnnotation conservation = null;
+ private AlignmentAnnotation hmmInformation;
+
private boolean showConsensusHistogram;
-
+
private AnnotatedCollectionI context;
+
/**
- * Creates a new SequenceGroup object.
+ * Constructor, assigning a generated default name of "JGroup:" with object
+ * hashcode appended
*/
public SequenceGroup()
{
* copy constructor
*
* @param seqsel
+ * @param keepsequences
+ * if false do not add sequences from seqsel to new instance
*/
public SequenceGroup(SequenceGroup seqsel)
{
this();
+
if (seqsel != null)
{
sequences = new ArrayList<>();
displayBoxes = seqsel.displayBoxes;
displayText = seqsel.displayText;
colourText = seqsel.colourText;
-
+
startRes = seqsel.startRes;
endRes = seqsel.endRes;
cs = new ResidueShader((ResidueShader) seqsel.cs);
showSequenceLogo = seqsel.showSequenceLogo;
normaliseSequenceLogo = seqsel.normaliseSequenceLogo;
showConsensusHistogram = seqsel.showConsensusHistogram;
+ hmmShowSequenceLogo = seqsel.hmmShowSequenceLogo;
+ hmmNormaliseSequenceLogo = seqsel.hmmNormaliseSequenceLogo;
+ hmmShowHistogram = seqsel.hmmShowHistogram;
idColour = seqsel.idColour;
outlineColour = seqsel.outlineColour;
seqrep = seqsel.seqrep;
thresholdTextColour = seqsel.thresholdTextColour;
width = seqsel.width;
ignoreGapsInConsensus = seqsel.ignoreGapsInConsensus;
+ hmmIgnoreBelowBackground = seqsel.hmmIgnoreBelowBackground;
+ hmmUseInfoLetterHeight = seqsel.hmmUseInfoLetterHeight;
if (seqsel.conserve != null)
{
+ // todo avoid doing this if we don't actually want derived calculations
+ // !
recalcConservation(); // safer than
// aaFrequency = (Vector) seqsel.aaFrequency.clone(); // ??
}
for (int i = 0, ipos = 0; i < inorder.length; i++)
{
SequenceI seq = inorder[i];
- SequenceI seqipos = seqs[ipos] = seq.getSubSequence(startRes, endRes + 1);
+ SequenceI seqipos = seqs[ipos] = seq.getSubSequence(startRes,
+ endRes + 1);
if (seqipos != null)
{
seqipos.setDescription(seq.getDescription());
}
/**
- * calculate residue conservation for group - but only if necessary. returns
- * true if the calculation resulted in a visible change to group
+ * Recalculates column consensus, conservation, and HMM annotation for the
+ * group (as applicable). Returns true if the calculation resulted in a
+ * visible change to group.
*
* @param defer
* when set, colourschemes for this group are not refreshed after
*/
public boolean recalcConservation(boolean defer)
{
- if (cs == null && consensus == null && conservation == null)
+ if (cs == null && consensus == null && conservation == null
+ && hmmInformation == null)
{
return false;
}
{
ProfilesI cnsns = AAFrequency.calculate(sequences, startRes,
endRes + 1, showSequenceLogo);
+ if (hmmInformation != null)
+ {
+ HiddenMarkovModel hmm = hmmInformation.sequenceRef.getHMM();
+
+ ProfilesI info = AAFrequency.calculateHMMProfiles(hmm,
+ (endRes + 1) - startRes, startRes, endRes + 1,
+ hmmIgnoreBelowBackground, hmmUseInfoLetterHeight);
+ _updateInformationRow(info);
+ upd = true;
+ }
if (consensus != null)
{
_updateConsensusRow(cnsns, sequences.size());
}
/**
+ * Recalculates the information content on the HMM annotation
+ *
+ * @param cnsns
+ */
+ private void _updateInformationRow(ProfilesI cnsns)
+ {
+ if (hmmInformation == null)
+ {
+ createInformationAnnotation();
+ }
+ hmmInformation.description = MessageManager
+ .getString("label.information_description");
+ setHmmProfiles(cnsns);
+ // preserve width if already set
+ int aWidth = (hmmInformation.annotations != null)
+ ? (endRes < hmmInformation.annotations.length
+ ? hmmInformation.annotations.length : endRes + 1)
+ : endRes + 1;
+ hmmInformation.annotations = null;
+ hmmInformation.annotations = new Annotation[aWidth]; // should be alignment
+ // width
+ hmmInformation.setCalcId(InformationThread.HMM_CALC_ID);
+ AAFrequency.completeInformation(hmmInformation, cnsns, startRes,
+ endRes + 1);
+ }
+
+ /**
* @param s
* sequence to either add or remove from group
* @param recalc
public void setStartRes(int newStart)
{
int before = startRes;
- startRes= Math.max(0,newStart); // sanity check for negative start column positions
- changeSupport.firePropertyChange(SEQ_GROUP_CHANGED, before, startRes);
-
-
+ startRes = Math.max(0, newStart); // sanity check for negative start column
+ // positions
+ changeSupport.firePropertyChange(SEQ_GROUP_CHANGED, before, startRes);
}
}
/**
+ * Creates the Hidden Markov Model annotation for this group
+ */
+ void createInformationAnnotation()
+ {
+ hmmInformation = new AlignmentAnnotation("", "", new Annotation[1], 0f,
+ 6.25f, AlignmentAnnotation.BAR_GRAPH);
+ hmmInformation.hasText = true;
+ hmmInformation.autoCalculated = false;
+ hmmInformation.groupRef = this;
+ hmmInformation.label = getName();
+ hmmInformation.description = MessageManager
+ .getString("label.information_description");
+ hmmInformation.setCalcId(InformationThread.HMM_CALC_ID);
+ }
+
+ /**
* set this alignmentAnnotation object as the one used to render consensus
* annotation
*
return ignoreGapsInConsensus;
}
+ public void setIgnoreBelowBackground(boolean state)
+ {
+ hmmIgnoreBelowBackground = state;
+ }
+
+ public boolean isIgnoreBelowBackground()
+ {
+ return hmmIgnoreBelowBackground;
+ }
+
+ public void setInfoLetterHeight(boolean state)
+ {
+ hmmUseInfoLetterHeight = state;
+ }
+
+ public boolean isUseInfoLetterHeight()
+ {
+ return hmmUseInfoLetterHeight;
+ }
+
/**
* @param showSequenceLogo
* indicates if a sequence logo is shown for consensus annotation
{
return (startRes <= apos && endRes >= apos) && sequences.contains(seq);
}
+
+ public boolean isShowInformationHistogram()
+ {
+ return hmmShowHistogram;
+ }
+
+ public void setShowInformationHistogram(boolean state)
+ {
+ if (hmmShowHistogram != state && hmmInformation != null)
+ {
+ this.hmmShowHistogram = state;
+ // recalcConservation(); TODO don't know what to do here next
+ }
+ this.hmmShowHistogram = state;
+ }
+
+ public boolean isShowHMMSequenceLogo()
+ {
+ return hmmShowSequenceLogo;
+ }
+
+ public void setShowHMMSequenceLogo(boolean state)
+ {
+ hmmShowSequenceLogo = state;
+ }
+
+ public boolean isNormaliseHMMSequenceLogo()
+ {
+ return hmmNormaliseSequenceLogo;
+ }
+
+ public void setNormaliseHMMSequenceLogo(boolean state)
+ {
+ hmmNormaliseSequenceLogo = state;
+ }
+
+ public ProfilesI getConsensusData()
+ {
+ return consensusProfiles;
+ }
+
+ public ProfilesI getHmmProfiles()
+ {
+ return hmmProfiles;
+ }
+
+ public void setHmmProfiles(ProfilesI hmmProfiles)
+ {
+ this.hmmProfiles = hmmProfiles;
+ }
+
+ @Override
+ public List<SequenceI> getHmmSequences()
+ {
+ List<SequenceI> result = new ArrayList<>();
+ for (int i = 0; i < sequences.size(); i++)
+ {
+ SequenceI seq = sequences.get(i);
+ if (seq.hasHMMProfile())
+ {
+ result.add(seq);
+ }
+ }
+ return result;
+ }
+
}
*/
public void setName(String name);
+ public HiddenMarkovModel getHMM();
+
+ public void setHMM(HiddenMarkovModel hmm);
-
/**
* Get the display name
*/
* from 1), or null if no residues are included in the range
*
* @param fromColum
- * - first column base 1
+ * - first column base 1. (0 and negative positions are rounded up)
* @param toColumn
* - last column, base 1
- * @return
+ * @return null if fromColum>toColumn
*/
public ContiguousI findPositions(int fromColum, int toColumn);
/**
* set the array of Database references for the sequence.
*
- * BH 2019.02.04 changes param to DBModlist
+ * BH 2019.02.04 changes param to DBModlist
*
* @param dbs
* @deprecated - use is discouraged since side-effects may occur if DBRefEntry
* set are not normalised.
- * @throws InvalidArgumentException
- * if the is not one created by Sequence itself
+ * @throws InvalidArgumentException if the is not one created by Sequence itself
*/
@Deprecated
public void setDBRefs(DBModList<DBRefEntry> dbs);
/**
* Returns a (possibly empty) list of any annotations that match on given
- * calcId (source), label (type) and description (observation instance). Null
- * values do not match.
+ * calcId (source), label (type) and description (observation instance).
+ * Null values do not match.
*
* @param calcId
* @param label
*/
public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
String label, String description);
-
/**
* create a new dataset sequence (if necessary) for this sequence and sets
* this sequence to refer to it. This call will move any features or
* list
*/
public List<DBRefEntry> getPrimaryDBRefs();
-
+ /**
+ * Answers true if the sequence has annotation for Hidden Markov Model
+ * information content, else false
+ */
+ boolean hasHMMAnnotation();
/**
* Returns a (possibly empty) list of sequence features that overlap the given
* optional feature types to restrict results to
* @return
*/
- List<SequenceFeature> findFeatures(int fromCol, int toCol,
- String... types);
+ List<SequenceFeature> findFeatures(int fromCol, int toCol, String... types);
/**
* Method to call to indicate that the sequence (characters or alignment/gaps)
* positions to be invalidated.
*/
void sequenceChanged();
-
+
/**
*
* @return BitSet corresponding to index [0,length) where Comparison.isGap()
* @param c1
* @param c2
*/
- int replace(char c1, char c2);
+ public int replace(char c1, char c2);
/**
* Answers the GeneLociI, or null if not known
* @param chromosomeId
* @param map
*/
- void setGeneLoci(String speciesId, String assemblyId, String chromosomeId,
- MapList map);
+ void setGeneLoci(String speciesId, String assemblyId,
+ String chromosomeId, MapList map);
+
/**
* Returns the sequence string constructed from the substrings of a sequence
* the iterator to use
* @return a String corresponding to the sequence
*/
- String getSequenceStringFromIterator(Iterator<int[]> it);
+ public String getSequenceStringFromIterator(Iterator<int[]> it);
/**
* Locate the first position in this sequence which is not contained in an
* iterator over regions
* @return first residue not contained in regions
*/
-
public int firstResidueOutsideIterator(Iterator<int[]> it);
+
+ /**
+ * Answers true if this sequence has an associated Hidden Markov Model
+ *
+ * @return
+ */
+ boolean hasHMMProfile();
}
+
return new ArrayList<>();
}
- return getAllFeatures(featureTypes.toArray(new String[featureTypes
- .size()]));
+ return getAllFeatures(
+ featureTypes.toArray(new String[featureTypes.size()]));
}
/**
for (Entry<String, FeatureStore> featureType : featureStore.entrySet())
{
- Set<String> featureGroups = featureType.getValue().getFeatureGroups(
- positionalFeatures);
+ Set<String> featureGroups = featureType.getValue()
+ .getFeatureGroups(positionalFeatures);
for (String group : groups)
{
if (featureGroups.contains(group))
{
return true;
}
- SequenceOntologyI so = SequenceOntologyFactory.getInstance();
+ SequenceOntologyI so = SequenceOntologyFactory.getSequenceOntology();
for (String term : soTerm)
{
if (type.equals(term) || so.isA(type, term))
@Override
public float getMinimumScore(String type, boolean positional)
{
- return featureStore.containsKey(type) ? featureStore.get(type)
- .getMinimumScore(positional) : Float.NaN;
+ return featureStore.containsKey(type)
+ ? featureStore.get(type).getMinimumScore(positional)
+ : Float.NaN;
}
/**
@Override
public float getMaximumScore(String type, boolean positional)
{
- return featureStore.containsKey(type) ? featureStore.get(type)
- .getMaximumScore(positional) : Float.NaN;
+ return featureStore.containsKey(type)
+ ? featureStore.get(type).getMaximumScore(positional)
+ : Float.NaN;
}
/**
final boolean forwardStrand)
{
Collections.sort(features,
- forwardStrand
- ? IntervalI.COMPARE_BEGIN_ASC_END_DESC
+ forwardStrand ? IntervalI.COMPARE_BEGIN_ASC_END_DESC
: IntervalI.COMPARE_END_DESC);
}
@Override
protected boolean retainFeature(SequenceFeature sf, String accessionId)
{
- if (SequenceOntologyFactory.getInstance().isA(sf.getType(),
+ if (SequenceOntologyFactory.getSequenceOntology().isA(sf.getType(),
SequenceOntologyI.CDS))
{
return false;
for (SequenceFeature sf : sfs)
{
String parentFeature = (String) sf.getValue(PARENT);
- if ( accId.equals(parentFeature))
+ if (accId.equals(parentFeature))
{
result.add(sf);
}
*/
package jalview.ext.ensembl;
-import jalview.datamodel.Alignment;
-import jalview.datamodel.AlignmentI;
-import jalview.datamodel.Sequence;
-import jalview.datamodel.SequenceFeature;
-import jalview.datamodel.SequenceI;
-import jalview.io.gff.SequenceOntologyI;
-import jalview.util.JSONUtils;
-import jalview.util.Platform;
-
-import java.io.BufferedReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.simple.parser.ParseException;
+import jalview.datamodel.Alignment;
+import jalview.datamodel.AlignmentI;
+import jalview.datamodel.Sequence;
+import jalview.datamodel.SequenceFeature;
+import jalview.datamodel.SequenceI;
+import jalview.io.gff.SequenceOntologyI;
+import jalview.util.JSONUtils;
+
/**
* A client for fetching and processing Ensembl feature data in GFF format by
* calling the overlap REST service
public AlignmentI getSequenceRecords(String query) throws IOException
{
// TODO: use a vararg String... for getSequenceRecords instead?
-
+
List<String> queries = new ArrayList<>();
queries.add(query);
SequenceI seq = parseFeaturesJson(queries);
if (seq == null)
- return null;
+ return null;
return new Alignment(new SequenceI[] { seq });
}
SequenceI seq = new Sequence("Dummy", "");
try
{
- Iterator<Object> rvals = (Iterator<Object>) getJSON(null, queries, -1, MODE_ITERATOR, null);
+ Iterator<Object> rvals = (Iterator<Object>) getJSON(null, queries, -1,
+ MODE_ITERATOR, null);
if (rvals == null)
{
- return null;
+ return null;
}
while (rvals.hasNext())
- {
+ {
try
{
Map<String, Object> obj = (Map<String, Object>) rvals.next();
Object phase = obj.get("phase");
String alleles = JSONUtils
.arrayToStringList((List<Object>) obj.get("alleles"));
- String clinSig = JSONUtils
- .arrayToStringList(
- (List<Object>) obj.get("clinical_significance"));
+ String clinSig = JSONUtils.arrayToStringList(
+ (List<Object>) obj.get("clinical_significance"));
/*
* convert 'variation' to 'sequence_variant', and 'cds' to 'CDS'
sf.setValue("clinical_significance", clinSig);
seq.addSequenceFeature(sf);
-
+
} catch (Throwable t)
{
// ignore - keep trying other features
}
} catch (ParseException | IOException e)
{
- e.printStackTrace();
+ e.printStackTrace();
// ignore
}
* @param obj
* @param key
*/
- protected void setFeatureAttribute(SequenceFeature sf, Map<String, Object> obj,
- String key)
+ protected void setFeatureAttribute(SequenceFeature sf,
+ Map<String, Object> obj, String key)
{
Object object = obj.get(key);
if (object != null)
* accepts anything as we will attempt lookup of gene or
* transcript id or gene name
*/
- private static final Regex ACCESSION_REGEX = new Regex(".*");
+ private static final Regex ACCESSION_REGEX = Platform.newRegex(".*");
private static final EnsemblFeatureType[] FEATURES_TO_FETCH = {
EnsemblFeatureType.gene, EnsemblFeatureType.transcript,
{
continue;
}
-
+
if (geneAlignment.getHeight() == 1)
{
// ensure id has 'correct' case for the Ensembl identifier
SequenceOntologyI.NMD_TRANSCRIPT_VARIANT,
SequenceOntologyI.TRANSCRIPT, SequenceOntologyI.EXON,
SequenceOntologyI.CDS };
- List<SequenceFeature> sfs = gene.getFeatures().getFeaturesByOntology(
- soTerms);
+ List<SequenceFeature> sfs = gene.getFeatures()
+ .getFeaturesByOntology(soTerms);
for (SequenceFeature sf : sfs)
{
gene.deleteFeature(sf);
transcriptLoci.add(geneMapping.locateInTo(exon[0], exon[1]));
}
- List<int[]> transcriptRange = Arrays.asList(new int[] {
- transcript.getStart(), transcript.getEnd() });
+ List<int[]> transcriptRange = Arrays
+ .asList(new int[]
+ { transcript.getStart(), transcript.getEnd() });
MapList mapList = new MapList(transcriptRange, transcriptLoci, 1, 1);
transcript.setGeneLoci(loci.getSpeciesId(), loci.getAssemblyId(),
@Override
protected boolean retainFeature(SequenceFeature sf, String accessionId)
{
- SequenceOntologyI so = SequenceOntologyFactory.getInstance();
+ SequenceOntologyI so = SequenceOntologyFactory.getSequenceOntology();
String type = sf.getType();
if (so.isA(type, SequenceOntologyI.GENE))
{
{
return new FeatureSettingsAdapter()
{
- SequenceOntologyI so = SequenceOntologyFactory.getInstance();
+ SequenceOntologyI so = SequenceOntologyFactory.getSequenceOntology();
@Override
public boolean isFeatureHidden(String type)
import jalview.analysis.AlignmentUtils;
import jalview.analysis.Dna;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.DBRefEntry;
* fetch and transfer genomic sequence features,
* fetch protein product and add as cross-reference
*/
- for (int i = 0, n = allIds.size(); i < n; i++)
+ for (int i = 0, n = allIds.size(); i < n; i++)
{
addFeaturesAndProduct(allIds.get(i), alignment);
}
*/
SequenceI genomicSequence = null;
EnsemblFeatures gffFetcher = new EnsemblFeatures(getDomain());
- EnsemblFeatureType[] features = getFeaturesToFetch();
-
+ EnsemblFeatureType[] features = getFeaturesToFetch();
+
// Platform.timeCheck("ESP.getsequencerec1", Platform.TIME_MARK);
-
+
AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
features);
if (geneFeatures != null && geneFeatures.getHeight() > 0)
{
genomicSequence = geneFeatures.getSequenceAt(0);
}
-
+
// Platform.timeCheck("ESP.getsequencerec2", Platform.TIME_MARK);
-
+
if (genomicSequence != null)
{
/*
List<DBRefEntry> uprots = DBRefUtils.selectRefs(ds.getDBRefs(),
new String[]
{ DBRefSource.UNIPROT });
- List<DBRefEntry> upxrefs = DBRefUtils.selectRefs(querySeq.getDBRefs(),
- new String[]
+ List<DBRefEntry> upxrefs = DBRefUtils
+ .selectRefs(querySeq.getDBRefs(), new String[]
{ DBRefSource.UNIPROT });
if (uprots != null)
{
if (upx.size() > 1)
{
- Cache.log.warn(
+ Console.warn(
"Implementation issue - multiple uniprot acc on product sequence.");
}
}
*/
protected void getCrossReferences(SequenceI seq)
{
-
+
// Platform.timeCheck("ESP. getdataseq ", Platform.TIME_MARK);
-
while (seq.getDatasetSequence() != null)
{
seq = seq.getDatasetSequence();
EnsemblXref xrefFetcher = new EnsemblXref(getDomain(), getDbSource(),
getEnsemblDataVersion());
List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
-
+
for (int i = 0, n = xrefs.size(); i < n; i++)
{
- // Platform.timeCheck("ESP. getxref + " + (i) + "/" + n, Platform.TIME_MARK);
- // BH 2019.01.25 this next method was taking 174 ms PER addition for a 266-reference example.
- // DBRefUtils.ensurePrimaries(seq)
- // was at the end of seq.addDBRef, so executed after ever addition!
- // This method was moved to seq.getPrimaryDBRefs()
+ // Platform.timeCheck("ESP. getxref + " + (i) + "/" + n,
+ // Platform.TIME_MARK);
+ // BH 2019.01.25 this next method was taking 174 ms PER addition for a
+ // 266-reference example.
+ // DBRefUtils.ensurePrimaries(seq)
+ // was at the end of seq.addDBRef, so executed after ever addition!
+ // This method was moved to seq.getPrimaryDBRefs()
seq.addDBRef(xrefs.get(i));
}
- // System.out.println("primaries are " + seq.getPrimaryDBRefs().toString());
+ // System.out.println("primaries are " + seq.getPrimaryDBRefs().toString());
/*
* and add a reference to itself
*/
-
- // Platform.timeCheck("ESP. getxref self ", Platform.TIME_MARK);
+
+ // Platform.timeCheck("ESP. getxref self ", Platform.TIME_MARK);
DBRefEntry self = new DBRefEntry(getDbSource(), getEnsemblDataVersion(),
- seq.getName());
+ seq.getName());
- // Platform.timeCheck("ESP. getxref self add ", Platform.TIME_MARK);
+ // Platform.timeCheck("ESP. getxref self add ", Platform.TIME_MARK);
seq.addDBRef(self);
-
+
// Platform.timeCheck("ESP. seqprox done ", Platform.TIME_MARK);
}
List<SequenceI> seqs = parseSequenceJson(ids);
if (seqs == null)
- return alignment;
+ return alignment;
if (seqs.isEmpty())
{
* in future to handle a JSONArray with more than one
*/
// Platform.timeCheck("ENS seqproxy", Platform.TIME_MARK);
- Map<String, Object> val = (Map<String, Object>) getJSON(null, ids, -1, MODE_MAP, null);
+ Map<String, Object> val = (Map<String, Object>) getJSON(null, ids, -1,
+ MODE_MAP, null);
if (val == null)
- return null;
+ return null;
Object s = val.get("desc");
String desc = s == null ? null : s.toString();
s = val.get("id");
*/
protected abstract List<SequenceFeature> getIdentifyingFeatures(
SequenceI seq, String accId);
-
+
int bhtest = 0;
-
+
/**
* Transfers the sequence feature to the target sequence, locating its start
* and end range based on the mapping. Features which do not overlap the
if (mappedRange != null)
{
- // Platform.timeCheck(null, Platform.TIME_SET);
+ // Platform.timeCheck(null, Platform.TIME_SET);
String group = sf.getFeatureGroup();
if (".".equals(group))
{
}
int newBegin = Math.min(mappedRange[0], mappedRange[1]);
int newEnd = Math.max(mappedRange[0], mappedRange[1]);
- // Platform.timeCheck(null, Platform.TIME_MARK);
+ // Platform.timeCheck(null, Platform.TIME_MARK);
bhtest++;
// 280 ms/1000 here:
- SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd, group, sf.getScore());
+ SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
+ group, sf.getScore());
// 0.175 ms here:
targetSequence.addSequenceFeature(copy);
* for sequence_variant on reverse strand, have to convert the allele
* values to their complements
*/
- if (!forwardStrand && SequenceOntologyFactory.getInstance()
+ if (!forwardStrand && SequenceOntologyFactory.getSequenceOntology()
.isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
{
reverseComplementAlleles(copy);
return false;
}
- // long start = System.currentTimeMillis();
+ // long start = System.currentTimeMillis();
List<SequenceFeature> sfs = sourceSequence.getFeatures()
.getPositionalFeatures();
MapList mapping = getGenomicRangesFromFeatures(sourceSequence,
accessionId, targetSequence.getStart());
if (mapping == null)
- {
+ {
return false;
}
boolean result = transferFeatures(sfs, targetSequence, mapping,
accessionId);
- // System.out.println("transferFeatures (" + (sfs.size()) + " --> "
- // + targetSequence.getFeatures().getFeatureCount(true) + ") to "
- // + targetSequence.getName() + " took "
- // + (System.currentTimeMillis() - start) + "ms");
+ // System.out.println("transferFeatures (" + (sfs.size()) + " --> "
+ // + targetSequence.getFeatures().getFeatureCount(true) + ") to "
+ // + targetSequence.getName() + " took "
+ // + (System.currentTimeMillis() - start) + "ms");
return result;
}
SequenceFeatures.sortFeatures(sfs, forwardStrand);
boolean transferred = false;
-
+
for (int i = 0, n = sfs.size(); i < n; i++)
{
- // if ((i%1000) == 0) {
- //// Platform.timeCheck("Feature " + bhtest, Platform.TIME_GET);
- // Platform.timeCheck("ESP. xferFeature + " + (i) + "/" + n, Platform.TIME_MARK);
- // }
+ // if ((i%1000) == 0) {
+ //// Platform.timeCheck("Feature " + bhtest, Platform.TIME_GET);
+ // Platform.timeCheck("ESP. xferFeature + " + (i) + "/" + n,
+ // Platform.TIME_MARK);
+ // }
SequenceFeature sf = sfs.get(i);
if (retainFeature(sf, parentId))
protected boolean featureMayBelong(SequenceFeature sf, String identifier)
{
String parent = (String) sf.getValue(PARENT);
- if (parent != null
- && !parent.equalsIgnoreCase(identifier))
+ if (parent != null && !parent.equalsIgnoreCase(identifier))
{
// this genomic feature belongs to a different transcript
return false;
public static boolean isTranscript(String featureType)
{
return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
- || SequenceOntologyFactory.getInstance().isA(featureType,
+ || SequenceOntologyFactory.getSequenceOntology().isA(featureType,
SequenceOntologyI.TRANSCRIPT);
}
}
import jalview.analysis.AlignmentUtils;
import jalview.bin.Cache;
import jalview.datamodel.DBRefSource;
+import jalview.util.Platform;
import jalview.ws.seqfetcher.DbSourceProxyImpl;
import com.stevesoft.pat.Regex;
* or ENSMUSP or similar for other species
* or CCDSnnnnn.nn with at least 3 digits
*/
- private static final Regex ACCESSION_REGEX = new Regex(
+ private static final Regex ACCESSION_REGEX = Platform.newRegex(
"(ENS([A-Z]{3}|)[GTEP]{1}[0-9]{11}$)" + "|"
+ "(CCDS[0-9.]{3,}$)");
* the default domain names may be overridden in .jalview_properties;
* this allows an easy change from http to https in future if needed
*/
- ensemblDomain = Cache.getDefault(ENSEMBL_BASEURL,
- DEFAULT_ENSEMBL_BASEURL).trim();
+ ensemblDomain = Cache
+ .getDefault(ENSEMBL_BASEURL, DEFAULT_ENSEMBL_BASEURL).trim();
ensemblGenomesDomain = Cache.getDefault(ENSEMBL_GENOMES_BASEURL,
DEFAULT_ENSEMBL_GENOMES_BASEURL).trim();
domain = ensemblDomain;
*/
package jalview.ext.ensembl;
-import jalview.datamodel.AlignmentI;
-import jalview.datamodel.DBRefEntry;
-import jalview.util.DBRefUtils;
-import jalview.util.JSONUtils;
-
-import java.io.BufferedReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.simple.parser.ParseException;
+import jalview.datamodel.AlignmentI;
+import jalview.datamodel.DBRefEntry;
+import jalview.util.DBRefUtils;
+
/**
* A class to fetch cross-references from Ensembl by calling the /xrefs REST
* service
try
{
- Iterator<Object> rvals = (Iterator<Object>) getJSON(getUrl(identifier), ids, -1, MODE_ITERATOR, null);
+ Iterator<Object> rvals = (Iterator<Object>) getJSON(
+ getUrl(identifier), ids, -1, MODE_ITERATOR, null);
while (rvals.hasNext())
{
Map<String, Object> val = (Map<String, Object>) rvals.next();
String db = val.get("dbname").toString();
String id = val.get("primary_id").toString();
- if (db != null && id != null
- && !GO_GENE_ONTOLOGY.equals(db))
+ if (db != null && id != null && !GO_GENE_ONTOLOGY.equals(db))
{
db = DBRefUtils.getCanonicalName(db);
DBRefEntry dbref = new DBRefEntry(db, getXRefVersion(), id);
return result;
}
- // /**
- // * Parses "primary_id" and "dbname" values from the JSON response and
- // * constructs a DBRefEntry. Returns a list of the DBRefEntry created. Note we
- // * don't parse "synonyms" as they appear to be either redirected or obsolete
- // * in Uniprot.
- // *
- // * @param br
- // * @return
- // * @throws IOException
- // */
- // @SuppressWarnings("unchecked")
- //protected List<DBRefEntry> parseResponse(BufferedReader br)
- // throws IOException
- // {
- // return result;
- // }
- //
+ // /**
+ // * Parses "primary_id" and "dbname" values from the JSON response and
+ // * constructs a DBRefEntry. Returns a list of the DBRefEntry created. Note
+ // we
+ // * don't parse "synonyms" as they appear to be either redirected or obsolete
+ // * in Uniprot.
+ // *
+ // * @param br
+ // * @return
+ // * @throws IOException
+ // */
+ // @SuppressWarnings("unchecked")
+ // protected List<DBRefEntry> parseResponse(BufferedReader br)
+ // throws IOException
+ // {
+ // return result;
+ // }
+ //
private String xrefVersion = "ENSEMBL:0";
/**
*/
protected URL getUrl(String identifier)
{
- String url = getDomain() + "/xrefs/id/" + identifier
- + CONTENT_TYPE_JSON + "&all_levels=1";
+ String url = getDomain() + "/xrefs/id/" + identifier + CONTENT_TYPE_JSON
+ + "&all_levels=1";
try
{
return new URL(url);
import java.util.Vector;
import javax.swing.SwingUtilities;
-
import org.jmol.adapter.smarter.SmarterJmolAdapter;
import org.jmol.api.JmolAppConsoleInterface;
import org.jmol.api.JmolSelectionListener;
import jalview.api.FeatureRenderer;
import jalview.api.FeatureSettingsModelI;
import jalview.api.SequenceRenderer;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.PDBEntry;
import jalview.datamodel.SequenceI;
import jalview.gui.AppJmol;
import jalview.structures.models.AAStructureBindingModel;
import jalview.ws.dbsources.Pdb;
import javajs.util.BS;
-
public abstract class JalviewJmolBinding extends AAStructureBindingModel
implements JmolStatusListener, JmolSelectionListener,
ComponentListener
{
private String lastMessage;
+
/*
* when true, try to search the associated datamodel for sequences that are
* associated with any unknown structures in the Jmol view.
private String jmolScript(String script)
{
- Cache.log.debug(">>Jmol>> " + script);
+ Console.debug(">>Jmol>> " + script);
String s = jmolViewer.evalStringQuiet(script); // scriptWait(script); BH
- Cache.log.debug("<<Jmol<< " + s);
+ Console.debug("<<Jmol<< " + s);
return s;
}
{
return null;
}
+
String cmd = command.getCommand();
jmolHistory(false);
if (lastCommand == null || !lastCommand.equals(cmd))
return null;
}
+
/**
* map between index of model filename returned from getPdbFile and the first
* index of models from this file in the viewer. Note - this is not trimmed -
jmolScript(cmd.toString());
jmolHistory(true);
+
}
private boolean debug = true;
setLoadingFromArchive(false);
}
+
protected IProgressIndicator getIProgressIndicator()
{
return null;
}
+
public void showHelp()
{
showUrl("http://wiki.jmol.org"
package jalview.fts.service.uniprot;
+import jalview.bin.ApplicationSingletonProvider;
+import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
- import jalview.bin.Cache;
- import jalview.fts.api.FTSData;
- import jalview.fts.api.FTSDataColumnI;
- import jalview.fts.api.FTSRestClientI;
- import jalview.fts.core.FTSRestClient;
- import jalview.fts.core.FTSRestRequest;
- import jalview.fts.core.FTSRestResponse;
- import jalview.util.MessageManager;
- import jalview.util.Platform;
+ import java.lang.invoke.MethodHandles;
+ import java.net.MalformedURLException;
+ import java.net.URL;
+
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.DefaultClientConfig;
+ import jalview.bin.Cache;
+ import jalview.bin.Console;
+ import jalview.fts.api.FTSData;
+ import jalview.fts.api.FTSDataColumnI;
++import jalview.fts.api.FTSRestClientI;
+ import jalview.fts.core.FTSRestClient;
+ import jalview.fts.core.FTSRestRequest;
+ import jalview.fts.core.FTSRestResponse;
+ import jalview.util.ChannelProperties;
+ import jalview.util.MessageManager;
+ import jalview.util.Platform;
+
+ /*
+ * 2022-07-20 bsoares
+ * See https://issues.jalview.org/browse/JAL-4036
+ * The new Uniprot API is not dissimilar to the old one, but has some important changes.
+ * Some group names have changed slightly, some old groups have gone and there are quite a few new groups.
+ *
+ * Most changes are mappings of old column ids to new field ids. There are a handful of old
+ * columns not mapped to new fields, and new fields without an old column.
+ * [aside: not all possible columns were listed in the resources/fts/uniprot_data_columns.txt file.
+ * These were presumably additions after the file was created]
+ * For existing/mapped fields, the same preferences found in the resource file have been migrated to
+ * the new file with the new field name, id and group.
+ *
+ * The new mapped groups and files are stored and read from resources/fts/uniprot_data_columns-2022.txt.
+ *
+ * There is now no "sort" query string parameter.
+ *
+ * See https://www.uniprot.org/help/api_queries
+ *
+ * SIGNIFICANT CHANGE: Pagination is no longer performed using a record offset, but with a "cursor"
+ * query string parameter that is not really a cursor. The value is an opaque string that is passed (or
+ * rather a whole URL is passed) in the "Link" header of the HTTP response of the previous page.
+ * Where such a link is passed it is put into the cursors ArrayList.
+ * There are @Overridden methods in UniprotFTSPanel.
+ */
-
public class UniProtFTSRestClient extends FTSRestClient
- implements ApplicationSingletonI
++ implements ApplicationSingletonI,FTSRestClientI
{
-
- public static FTSRestClientI getInstance()
++public static UniProtFTSRestClient getInstance()
+{
- return (FTSRestClientI) ApplicationSingletonProvider
++return (UniProtFTSRestClient) ApplicationSingletonProvider
+ .getInstance(UniProtFTSRestClient.class);
+}
+ private static final String DEFAULT_UNIPROT_DOMAIN = "https://rest.uniprot.org";
- private static final String DEFAULT_UNIPROT_DOMAIN = "https://www.uniprot.org";
+ private static final String USER_AGENT = ChannelProperties
+ .getProperty("app_name", "Jalview") + " "
+ + Cache.getDefault("VERSION", "Unknown") + " "
+ + MethodHandles.lookup().lookupClass() + " help@jalview.org";
static
{
Platform.addJ2SDirectDatabaseCall(DEFAULT_UNIPROT_DOMAIN);
}
- private static UniProtFTSRestClient instance = null;
+
public final String uniprotSearchEndpoint;
- public UniProtFTSRestClient()
+ private UniProtFTSRestClient()
{
super();
- uniprotSearchEndpoint = Cache.getDefault("UNIPROT_DOMAIN",
- DEFAULT_UNIPROT_DOMAIN) + "/uniprot/";
+ this.clearCursors();
+ uniprotSearchEndpoint = Cache.getDefault("UNIPROT_2022_DOMAIN",
+ DEFAULT_UNIPROT_DOMAIN) + "/uniprotkb/search";
}
@SuppressWarnings("unchecked")
public FTSRestResponse executeRequest(FTSRestRequest uniprotRestRequest)
throws Exception
{
+ return executeRequest(uniprotRestRequest, null);
+ }
+
+ public FTSRestResponse executeRequest(FTSRestRequest uniprotRestRequest,
+ String cursor) throws Exception
+ {
try
{
String wantedFields = getDataColumnsFieldsAsCommaDelimitedString(
}
else
{
- query = uniprotRestRequest.getFieldToSearchBy()
- .equalsIgnoreCase("Search All")
- ? uniprotRestRequest.getSearchTerm()
- + " or mnemonic:"
- + uniprotRestRequest.getSearchTerm()
+ query = uniprotRestRequest.getFieldToSearchBy().equalsIgnoreCase(
+ "Search All") ? uniprotRestRequest.getSearchTerm()
+ // + " or mnemonic:"
+ // + uniprotRestRequest.getSearchTerm()
: uniprotRestRequest.getFieldToSearchBy() + ":"
+ uniprotRestRequest.getSearchTerm();
}
WebResource webResource = null;
webResource = client.resource(uniprotSearchEndpoint)
- .queryParam("format", "tab")
- .queryParam("columns", wantedFields)
- .queryParam("limit", String.valueOf(responseSize))
- .queryParam("offset", String.valueOf(offSet))
- .queryParam("sort", "score").queryParam("query", query);
+ .queryParam("format", "tsv")
+ .queryParam("fields", wantedFields)
+ .queryParam("size", String.valueOf(responseSize))
+ /* 2022 new api has no "sort"
+ * .queryParam("sort", "score")
+ */
+ .queryParam("query", query);
+ if (offSet != 0 && cursor != null && cursor.length() > 0)
+ // 2022 new api does not do pagination with an offset, it requires a
+ // "cursor" parameter with a key (given for the next page).
+ // (see https://www.uniprot.org/help/pagination)
+ {
+ webResource = webResource.queryParam("cursor", cursor);
+ }
+ Console.debug(
+ "Uniprot FTS Request: " + webResource.getURI().toString());
// Execute the REST request
- ClientResponse clientResponse = webResource
- .accept(MediaType.TEXT_PLAIN).get(clientResponseClass);
+ WebResource.Builder wrBuilder = webResource
+ .accept(MediaType.TEXT_PLAIN);
+ if (!Platform.isJS())
+ /**
+ * Java only
+ *
+ * @j2sIgnore
+ */
+ {
+ wrBuilder.header("User-Agent", USER_AGENT);
+ }
+ ClientResponse clientResponse = wrBuilder.get(clientResponseClass);
+
+ if (!Platform.isJS())
+ /**
+ * Java only
+ *
+ * @j2sIgnore
+ */
+ {
+ if (clientResponse.getHeaders().containsKey("Link"))
+ {
+ // extract the URL from the 'Link: <URL>; ref="stuff"' header
+ String linkHeader = clientResponse.getHeaders().get("Link")
+ .get(0);
+ if (linkHeader.indexOf("<") > -1)
+ {
+ String temp = linkHeader.substring(linkHeader.indexOf("<") + 1);
+ if (temp.indexOf(">") > -1)
+ {
+ String nextUrl = temp.substring(0, temp.indexOf(">"));
+ // then get the cursor value from the query string parameters
+ String nextCursor = getQueryParam("cursor", nextUrl);
+ setCursor(cursorPage + 1, nextCursor);
+ }
+ }
+ }
+ }
-
String uniProtTabDelimittedResponseString = clientResponse
.getEntity(String.class);
// Make redundant objects eligible for garbage collection to conserve
throw new Exception(errorMessage);
}
- int xTotalResults = Platform.isJS() ? 1
- : Integer.valueOf(clientResponse.getHeaders()
- .get("X-Total-Results").get(0));
+ // new Uniprot API is not including a "X-Total-Results" header when there
+ // are 0 results
+ List<String> resultsHeaders = clientResponse.getHeaders()
+ .get("X-Total-Results");
+ int xTotalResults = 0;
+ if (Platform.isJS())
+ {
+ xTotalResults = 1;
+ }
+ else if (resultsHeaders != null && resultsHeaders.size() >= 1)
+ {
+ xTotalResults = Integer.valueOf(resultsHeaders.get(0));
+ }
clientResponse = null;
client = null;
return parseUniprotResponse(uniProtTabDelimittedResponseString,
uniprotRestRequest, xTotalResults);
} catch (Exception e)
{
+ Console.warn("Problem with the query: " + e.getMessage());
+ Console.debug("Exception stacktrace:", e);
String exceptionMsg = e.getMessage();
if (exceptionMsg.contains("SocketException"))
{
};
}
- public static UniProtFTSRestClient getInstance()
- {
- if (instance == null)
- {
- instance = new UniProtFTSRestClient();
- }
- return instance;
- }
+
@Override
public String getColumnDataConfigFileName()
{
- return "/fts/uniprot_data_columns.txt";
+ return "/fts/uniprot_data_columns-2022.txt";
+ }
+
+ /* 2022-07-20 bsoares
+ * used for the new API "cursor" pagination. See https://www.uniprot.org/help/pagination
+ */
+ private ArrayList<String> cursors;
+
+ private int cursorPage = 0;
+
+ protected int getCursorPage()
+ {
+ return cursorPage;
+ }
+
+ protected void setCursorPage(int i)
+ {
+ cursorPage = i;
+ }
+
+ protected void setPrevCursorPage()
+ {
+ if (cursorPage > 0)
+ cursorPage--;
+ }
+
+ protected void setNextCursorPage()
+ {
+ cursorPage++;
+ }
+
+ protected void clearCursors()
+ {
+ cursors = new ArrayList(10);
}
+ protected String getCursor(int i)
+ {
+ return cursors.get(i);
+ }
+
+ protected String getNextCursor()
+ {
+ if (cursors.size() < cursorPage + 2)
+ return null;
+ return cursors.get(cursorPage + 1);
+ }
+
+ protected String getPrevCursor()
+ {
+ if (cursorPage == 0)
+ return null;
+ return cursors.get(cursorPage - 1);
+ }
+
+ protected void setCursor(int i, String c)
+ {
+ cursors.ensureCapacity(i + 1);
+ while (cursors.size() <= i)
+ {
+ cursors.add(null);
+ }
+ cursors.set(i, c);
+ Console.debug(
+ "Set UniprotFRSRestClient cursors[" + i + "] to '" + c + "'");
+ // cursors.add(c);
+ }
+
+ public static String getQueryParam(String param, String u)
+ {
+ if (param == null || u == null)
+ return null;
+ try
+ {
+ URL url = new URL(u);
+ String[] kevs = url.getQuery().split("&");
+ for (int j = 0; j < kevs.length; j++)
+ {
+ String[] kev = kevs[j].split("=", 2);
+ if (param.equals(kev[0]))
+ {
+ return kev[1];
+ }
+ }
+ } catch (MalformedURLException e)
+ {
+ Console.warn("Could not obtain next page 'cursor' value from 'u");
+ }
+ return null;
+ }
-}
+}
this.settings = defaults;
this.isComplexAlignFile = format.isComplexAlignFile();
init(viewport.hasHiddenRows(), viewport.hasHiddenColumns());
- dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
+ dialog = JvOptionPane.newOptionDialog(Desktop.getDesktopPane());
}
/**
MessageManager.getString("action.cancel") };
dialog.showInternalDialog(this,
MessageManager.getString("label.export_settings"),
- JvOptionPane.OK_CANCEL_OPTION, JvOptionPane.PLAIN_MESSAGE,
- null, options, MessageManager.getString("action.ok"));
+ JvOptionPane.OK_CANCEL_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
+ options, MessageManager.getString("action.ok"));
}
/**
boolean set = chkHiddenSeqs.isEnabled() && isSelected;
chkHiddenSeqs.setSelected(set);
settings.setExportHiddenSequences(set);
-
+
set = chkHiddenCols.isEnabled() && isSelected;
chkHiddenCols.setSelected(set);
settings.setExportHiddenColumns(set);
-
+
set = isComplexAlignFile && chkExportAnnots.isEnabled() && isSelected;
chkExportAnnots.setSelected(set);
settings.setExportAnnotations(set);
-
+
set = isComplexAlignFile && chkExportFeats.isEnabled() && isSelected;
chkExportFeats.setSelected(set);
settings.setExportFeatures(set);
-
+
set = isComplexAlignFile && chkExportGrps.isEnabled() && isSelected;
chkExportGrps.setSelected(set);
settings.setExportGroups(set);
settings.setExportHiddenSequences(chkHiddenSeqs.isSelected());
}
});
-
+
chkHiddenCols.setText(
MessageManager.getString("action.export_hidden_columns"));
chkHiddenCols.addActionListener(new ActionListener()
settings.setExportHiddenColumns(chkHiddenCols.isSelected());
}
});
-
+
chkExportAnnots
.setText(MessageManager.getString("action.export_annotations"));
chkExportAnnots.addActionListener(new ActionListener()
settings.setExportAnnotations(chkExportAnnots.isSelected());
}
});
-
+
chkExportFeats
.setText(MessageManager.getString("action.export_features"));
chkExportFeats.addActionListener(new ActionListener()
settings.setExportFeatures(chkExportFeats.isSelected());
}
});
-
+
chkExportGrps.setText(MessageManager.getString("action.export_groups"));
chkExportGrps.addActionListener(new ActionListener()
{
settings.setExportGroups(chkExportGrps.isSelected());
}
});
-
+
JCheckBox chkAll = new JCheckBox(
MessageManager.getString("action.select_all"));
-
+
JPanel hiddenRegionConfPanel = new JPanel(new BorderLayout());
JPanel complexExportPanel = new JPanel(new BorderLayout());
this.setLayout(new BorderLayout());
-
+
chkAll.addItemListener(new ItemListener()
{
@Override
checkAllAction(chkAll.isSelected());
}
});
-
+
hiddenRegionConfPanel.add(chkHiddenSeqs, BorderLayout.CENTER);
hiddenRegionConfPanel.add(chkHiddenCols, BorderLayout.SOUTH);
chkHiddenSeqs.setEnabled(hasHiddenSeq);
chkHiddenCols.setEnabled(hasHiddenCols);
-
+
complexExportPanel.add(chkExportAnnots, BorderLayout.NORTH);
complexExportPanel.add(chkExportFeats, BorderLayout.CENTER);
complexExportPanel.add(chkExportGrps, BorderLayout.SOUTH);
-
+
JPanel actionPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
actionPanel.add(chkAll);
-
+
JPanel optionsPanel = new JPanel();
if (this.isComplexAlignFile)
{
optionsPanel.add(complexExportPanel);
}
-
+
if (hasHiddenSeq || hasHiddenCols)
{
optionsPanel.add(hiddenRegionConfPanel);
}
-
+
add(optionsPanel, BorderLayout.NORTH);
add(actionPanel, BorderLayout.SOUTH);
}
import java.util.Locale;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.swing.JFileChooser;
+import javax.swing.JOptionPane;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
+import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.print.PageFormat;
import java.awt.print.PrinterJob;
import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileWriter;
-import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collection;
import java.util.Deque;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
+import javax.swing.event.InternalFrameAdapter;
+import javax.swing.event.InternalFrameEvent;
import ext.vamsas.ServiceHandle;
import jalview.analysis.AlignmentSorter;
import jalview.api.ViewStyleI;
import jalview.api.analysis.SimilarityParamsI;
import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.bin.Jalview;
import jalview.commands.CommandI;
import jalview.commands.EditCommand;
import jalview.datamodel.SequenceI;
import jalview.gui.ColourMenuHelper.ColourChangeListener;
import jalview.gui.ViewSelectionMenu.ViewSetProvider;
+import jalview.hmmer.HMMAlign;
+import jalview.hmmer.HMMBuild;
+import jalview.hmmer.HMMERParamStore;
+import jalview.hmmer.HMMERPreset;
+import jalview.hmmer.HMMSearch;
+import jalview.hmmer.HmmerCommand;
+import jalview.hmmer.JackHMMER;
import jalview.io.AlignmentProperties;
import jalview.io.AnnotationFile;
import jalview.io.BackupFiles;
import jalview.viewmodel.ViewportRanges;
import jalview.ws.DBRefFetcher;
import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
+import jalview.ws.ServiceChangeListener;
+import jalview.ws.WSDiscovererI;
+import jalview.ws.api.ServiceWithParameters;
import jalview.ws.jws1.Discoverer;
import jalview.ws.jws2.Jws2Discoverer;
-import jalview.ws.jws2.jabaws2.Jws2Instance;
+import jalview.ws.jws2.PreferredServiceRegistry;
+import jalview.ws.params.ArgumentI;
+import jalview.ws.params.ParamDatastoreI;
+import jalview.ws.params.WsParamSetI;
import jalview.ws.seqfetcher.DbSourceProxy;
+import jalview.ws.slivkaws.SlivkaWSDiscoverer;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.swing.JFileChooser;
+import javax.swing.JOptionPane;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.Rectangle;
+import java.awt.Toolkit;
+import java.awt.datatransfer.Clipboard;
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.StringSelection;
+import java.awt.datatransfer.Transferable;
+import java.awt.dnd.DnDConstants;
+import java.awt.dnd.DropTargetDragEvent;
+import java.awt.dnd.DropTargetDropEvent;
+import java.awt.dnd.DropTargetEvent;
+import java.awt.dnd.DropTargetListener;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.FocusAdapter;
+import java.awt.event.FocusEvent;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+import java.awt.event.KeyAdapter;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseEvent;
+import java.awt.print.PageFormat;
+import java.awt.print.PrinterJob;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.PrintWriter;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Vector;
+
+import javax.swing.ButtonGroup;
+import javax.swing.JCheckBoxMenuItem;
+import javax.swing.JComponent;
+import javax.swing.JEditorPane;
+import javax.swing.JInternalFrame;
+import javax.swing.JLabel;
+import javax.swing.JLayeredPane;
+import javax.swing.JMenu;
+import javax.swing.JMenuItem;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.SwingUtilities;
+import javax.swing.event.InternalFrameAdapter;
+import javax.swing.event.InternalFrameEvent;
+
+import ext.vamsas.ServiceHandle;
/**
* DOCUMENT ME!
* @version $Revision$
*/
@SuppressWarnings("serial")
-public class AlignFrame extends GAlignFrame implements DropTargetListener,
- IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
+public class AlignFrame extends GAlignFrame
+ implements DropTargetListener, IProgressIndicator,
+ AlignViewControllerGuiI, ColourChangeListener, ServiceChangeListener
{
+ public static int frameCount;
public static final int DEFAULT_WIDTH = 700;
public static final int DEFAULT_HEIGHT = 500;
*/
String fileName = null;
+ /**
+ * TODO: remove reference to 'FileObject' in AlignFrame - not correct mapping
+ */
File fileObject;
+ private int id;
+
+ private DataSourceType protocol ;
/**
* Creates a new AlignFrame object with specific width and height.
*
public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
int height, String sequenceSetId, String viewId)
{
+ id = (++frameCount);
setSize(width, height);
if (al.getDataset() == null)
viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
- alignPanel = new AlignmentPanel(this, viewport);
-
- addAlignmentPanel(alignPanel, true);
+ // JalviewJS needs to distinguish a new panel from an old one in init()
+ // alignPanel = new AlignmentPanel(this, viewport);
+ // addAlignmentPanel(alignPanel, true);
init();
}
{
viewport.hideSequence(hiddenSeqs);
}
- alignPanel = new AlignmentPanel(this, viewport);
- addAlignmentPanel(alignPanel, true);
+ // alignPanel = new AlignmentPanel(this, viewport);
+ // addAlignmentPanel(alignPanel, true);
init();
}
{
viewport = ap.av;
alignPanel = ap;
- addAlignmentPanel(ap, false);
+ // addAlignmentPanel(ap, false);
init();
}
*/
void init()
{
+ boolean newPanel = (alignPanel == null);
+ viewport.setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
+ if (newPanel)
+ {
+ if (Platform.isJS())
+ {
+ // need to set this up front if NOANNOTATION is
+ // used in conjunction with SHOWOVERVIEW.
+
+ // I have not determined if this is appropriate for
+ // Jalview/Java, as it means we are setting this flag
+ // for all subsequent AlignFrames. For now, at least,
+ // I am setting it to be JalviewJS-only.
+
+ boolean showAnnotation = Jalview.getInstance().getShowAnnotation();
+ viewport.setShowAnnotation(showAnnotation);
+ }
+ alignPanel = new AlignmentPanel(this, viewport);
+ }
+ addAlignmentPanel(alignPanel, newPanel);
-
// setBackground(Color.white); // BH 2019
+
if (!Jalview.isHeadlessMode())
{
progressBar = new ProgressBar(this.statusPanel, this.statusBar);
+ // JalviewJS options
+ statusPanel.setVisible(Jalview.getInstance().getShowStatus());
+ alignFrameMenuBar.setVisible(Jalview.getInstance().getAllowMenuBar());
}
avc = new jalview.controller.AlignViewController(this, viewport,
// modifyPID.setEnabled(false);
}
- String sortby = jalview.bin.Cache.getDefault(Preferences.SORT_ALIGNMENT,
- String sortby = Cache.getDefault("SORT_ALIGNMENT", "No sort");
++ String sortby = Cache.getDefault(Preferences.SORT_ALIGNMENT,
+ "No sort");
if (sortby.equals("Id"))
{
sortPairwiseMenuItem_actionPerformed(null);
}
- this.alignPanel.av
- .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
+ // BH see above
+ //
+ // this.alignPanel.av
+ // .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
setMenusFromViewport(viewport);
buildSortByAnnotationScoresMenu();
});
buildColourMenu();
- if (Desktop.desktop != null)
+ if (Desktop.getDesktopPane() != null)
{
this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
+ addServiceListeners();
if (!Platform.isJS())
{
- addServiceListeners();
}
setGUINucleotide();
}
wrapMenuItem_actionPerformed(null);
}
- if (jalview.bin.Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
- if (Cache.getDefault("SHOW_OVERVIEW", false))
++ if (Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
{
this.overviewMenuItem_actionPerformed(null);
}
});
if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase(Locale.ROOT)
.indexOf("devel") > -1
- || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase(Locale.ROOT)
- .indexOf("test") > -1)
+ || Cache.getDefault("VERSION", "DEVELOPMENT")
+ .toLowerCase(Locale.ROOT).indexOf("test") > -1)
{
formatMenu.add(vsel);
}
* @param format
* format of file
*/
+ @Deprecated
public void setFileName(String file, FileFormatI format)
{
fileName = file;
}
/**
+ *
+ * @param fileName
+ * @param file from SwingJS; may contain bytes -- for reload
+ * @param protocol from SwingJS; may be RELATIVE_URL
+ * @param format
+ */
+ public void setFile(String fileName, File file, DataSourceType protocol, FileFormatI format)
+ {
+ this.fileName = fileName;
+ this.fileObject = file;
+ this.protocol = protocol;
+ setFileFormat(format);
+ reload.setEnabled(true);
+ }
+
+ /**
* JavaScript will have this, maybe others. More dependable than a file name
* and maintains a reference to the actual bytes loaded.
*
switch (evt.getKeyCode())
{
- case 27: // escape key
- deselectAllSequenceMenuItem_actionPerformed(null);
+ case KeyEvent.VK_ESCAPE: // escape key
+ // alignPanel.deselectAllSequences();
+ alignPanel.deselectAllSequences();
break;
}
if (viewport.cursorMode)
{
- alignPanel.getSeqPanel().moveCursor(0, -1,evt.isShiftDown());
+ alignPanel.getSeqPanel().moveCursor(0, -1, evt.isShiftDown());
}
break;
case KeyEvent.VK_LEFT:
if (evt.isAltDown() || !viewport.cursorMode)
{
- viewport.firePropertyChange("alignment", null,
- viewport.getAlignment().getSequences());
+ viewport.notifyAlignment();
}
break;
case KeyEvent.VK_RIGHT:
if (evt.isAltDown() || !viewport.cursorMode)
{
- viewport.firePropertyChange("alignment", null,
- viewport.getAlignment().getSequences());
+ viewport.notifyAlignment();
}
break;
}
{
ap.av.getAlignment().padGaps();
}
- ap.av.updateConservation(ap);
- ap.av.updateConsensus(ap);
- ap.av.updateStrucConsensus(ap);
+ if (Jalview.getInstance().getStartCalculations())
+ {
+ ap.av.updateConservation(ap);
+ ap.av.updateConsensus(ap);
+ ap.av.updateStrucConsensus(ap);
+ ap.av.initInformationWorker(ap);
+ }
}
}
return viewport;
}
+ @Override
+ public void servicesChanged(WSDiscovererI discoverer,
+ Collection<? extends ServiceWithParameters> services)
+ {
+ buildWebServicesMenu();
+ }
/* Set up intrinsic listeners for dynamically generated GUI bits. */
private void addServiceListeners()
{
- final java.beans.PropertyChangeListener thisListener;
- Desktop.instance.addJalviewPropertyChangeListener("services",
- thisListener = new java.beans.PropertyChangeListener()
- {
- @Override
- public void propertyChange(PropertyChangeEvent evt)
- {
- // // System.out.println("Discoverer property change.");
- // if (evt.getPropertyName().equals("services"))
- {
- SwingUtilities.invokeLater(new Runnable()
- {
-
- @Override
- public void run()
- {
- System.err.println(
- "Rebuild WS Menu for service change");
- BuildWebServiceMenu();
- }
-
- });
- }
- }
- });
- addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
+ if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
{
+ WSDiscovererI discoverer = SlivkaWSDiscoverer.getInstance();
+ discoverer.addServiceChangeListener(this);
+ }
+ if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
+ {
+ WSDiscovererI discoverer = Jws2Discoverer.getInstance();
+ discoverer.addServiceChangeListener(this);
+ }
+ // legacy event listener for compatibility with jws1
+ PropertyChangeListener legacyListener = (changeEvent) -> {
+ buildWebServicesMenu();
+ };
+ Desktop.getInstance().addJalviewPropertyChangeListener("services",legacyListener);
+
+ addInternalFrameListener(new InternalFrameAdapter() {
@Override
- public void internalFrameClosed(
- javax.swing.event.InternalFrameEvent evt)
- {
- // System.out.println("deregistering discoverer listener");
- Desktop.instance.removeJalviewPropertyChangeListener("services",
- thisListener);
+ public void internalFrameClosed(InternalFrameEvent e) {
+ System.out.println("deregistering discoverer listener");
+ SlivkaWSDiscoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
+ Jws2Discoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
+ Desktop.getInstance().removeJalviewPropertyChangeListener("services", legacyListener);
closeMenuItem_actionPerformed(true);
}
});
- // Finally, build the menu once to get current service state
- new Thread(new Runnable()
- {
- @Override
- public void run()
- {
- BuildWebServiceMenu();
- }
- }).start();
+ buildWebServicesMenu();
}
/**
scaleLeft.setVisible(av.getWrapAlignment());
scaleRight.setVisible(av.getWrapAlignment());
annotationPanelMenuItem.setState(av.isShowAnnotation());
- /*
- * Show/hide annotations only enabled if annotation panel is shown
- */
- showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
- hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
- showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
- hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
+ // Show/hide annotations only enabled if annotation panel is shown
+ syncAnnotationMenuItems(av.isShowAnnotation());
viewBoxesMenuItem.setSelected(av.getShowBoxes());
viewTextMenuItem.setSelected(av.getShowText());
showNonconservedMenuItem.setSelected(av.getShowUnconserved());
showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
showSequenceLogo.setSelected(av.isShowSequenceLogo());
normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
+ showInformationHistogram.setSelected(av.isShowInformationHistogram());
+ showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
+ normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
ColourMenuHelper.setColourSelected(colourMenu,
av.getGlobalColourScheme());
applyToAllGroups.setState(av.getColourAppliesToAllGroups());
showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
showDbRefsMenuitem.setSelected(av.isShowDBRefs());
- autoCalculate.setSelected(av.autoCalculateConsensus);
+ autoCalculate
+ .setSelected(av.getAutoCalculateConsensusAndConservation());
sortByTree.setSelected(av.sortByTree);
listenToViewSelections.setSelected(av.followSelection);
{
progressBar.setProgressBar(message, id);
}
+
+ @Override
+ public void removeProgressBar(long id)
+ {
+ progressBar.removeProgressBar(id);
+ }
@Override
public void registerHandler(final long id,
*/
public String getVersion()
{
- return jalview.bin.Cache.getProperty("VERSION");
+ return Cache.getProperty("VERSION");
}
public FeatureRenderer getFeatureRenderer()
@Override
public void addFromFile_actionPerformed(ActionEvent e)
{
- Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
+ Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
}
@Override
- public void reload_actionPerformed(ActionEvent e)
+ public void hmmBuild_actionPerformed(boolean withDefaults)
{
- if (fileName != null)
+ if (!alignmentIsSufficient(1))
{
- // TODO: JAL-1108 - ensure all associated frames are closed regardless of
- // originating file's format
- // TODO: work out how to recover feature settings for correct view(s) when
- // file is reloaded.
- if (FileFormat.Jalview.equals(currentFileFormat))
- {
- JInternalFrame[] frames = Desktop.desktop.getAllFrames();
- for (int i = 0; i < frames.length; i++)
+ return;
+ }
+
+ /*
+ * get default parameters, and optionally show a dialog
+ * to allow them to be modified
+ */
+ ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
+ List<ArgumentI> args = store.getServiceParameters();
+
+ if (!withDefaults)
+ {
+ WsParamSetI set = new HMMERPreset();
+ WsJobParameters params = new WsJobParameters(store, set, args);
+ params.showRunDialog().thenAccept((startJob) -> {
+ if (startJob)
{
- if (frames[i] instanceof AlignFrame && frames[i] != this
- && ((AlignFrame) frames[i]).fileName != null
- && ((AlignFrame) frames[i]).fileName.equals(fileName))
- {
- try
- {
- frames[i].setSelected(true);
- Desktop.instance.closeAssociatedWindows();
- } catch (java.beans.PropertyVetoException ex)
- {
- }
- }
+ var args2 = params.getJobParams();
+ new Thread(new HMMBuild(this, args2)).start();
+ }
+ });
+ }
+ else
+ {
+ new Thread(new HMMBuild(this, args)).start();
+ }
+ }
+
+ @Override
+ public void hmmAlign_actionPerformed(boolean withDefaults)
+ {
+ if (!(checkForHMM() && alignmentIsSufficient(2)))
+ {
+ return;
+ }
+
+ /*
+ * get default parameters, and optionally show a dialog
+ * to allow them to be modified
+ */
+ ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
+ List<ArgumentI> args = store.getServiceParameters();
+
+ if (!withDefaults)
+ {
+ WsParamSetI set = new HMMERPreset();
+ WsJobParameters params = new WsJobParameters(store, set, args);
+ params.showRunDialog().thenAccept((startJob) -> {
+ if (startJob)
+ {
+ var args2 = params.getJobParams();
+ new Thread(new HMMAlign(this, args2)).start();
+ }
+ });
+ }
+ else
+ {
+ new Thread(new HMMAlign(this, args)).start();
+ }
+ }
+
+ @Override
+ public void hmmSearch_actionPerformed(boolean withDefaults)
+ {
+ if (!checkForHMM())
+ {
+ return;
+ }
+
+ /*
+ * get default parameters, and (if requested) show
+ * dialog to allow modification
+ */
+ ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
+ List<ArgumentI> args = store.getServiceParameters();
+
+ if (!withDefaults)
+ {
+ WsParamSetI set = new HMMERPreset();
+ WsJobParameters params = new WsJobParameters(store, set, args);
+ params.showRunDialog().thenAccept((startJob) -> {
+ if (startJob)
+ {
+ var args2 = params.getJobParams();
+ new Thread(new HMMSearch(this, args2)).start();
+ alignPanel.repaint();
+ }
+ });
+ }
+ else
+ {
+ new Thread(new HMMSearch(this, args)).start();
+ alignPanel.repaint();
+ }
+ }
+ @Override
+ public void jackhmmer_actionPerformed(boolean withDefaults)
+ {
+
+ /*
+ * get default parameters, and (if requested) show
+ * dialog to allow modification
+ */
+
+ ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
+ List<ArgumentI> args = store.getServiceParameters();
+
+ if (!withDefaults)
+ {
+ WsParamSetI set = new HMMERPreset();
+ WsJobParameters params = new WsJobParameters(store, set, args);
+ params.showRunDialog().thenAccept((startJob) -> {
+ if (startJob)
+ {
+ var args2 = params.getJobParams();
+ new Thread(new JackHMMER(this, args2)).start();
+ alignPanel.repaint();
}
- Desktop.instance.closeAssociatedWindows();
+ });
+ }
+ else
+ {
+ new Thread(new JackHMMER(this, args)).start();
+ alignPanel.repaint();
+ }
+ }
+
+ /**
+ * Checks if the alignment has at least one hidden Markov model, if not shows
+ * a dialog advising to run hmmbuild or load an HMM profile
+ *
+ * @return
+ */
+ private boolean checkForHMM()
+ {
+ if (viewport.getAlignment().getHmmSequences().isEmpty())
+ {
+ JOptionPane.showMessageDialog(this,
+ MessageManager.getString("warn.no_hmm"));
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ protected void filterByEValue_actionPerformed()
+ {
+ viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
+ }
+
+ @Override
+ protected void filterByScore_actionPerformed()
+ {
+ viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
+ }
+
+ private double inputDouble(String message)
+ {
+ String str = null;
+ Double d = null;
+ while (d == null || d <= 0)
+ {
+ str = JOptionPane.showInputDialog(this.alignPanel, message);
+ try
+ {
+ d = Double.valueOf(str);
+ } catch (NumberFormatException e)
+ {
+ }
+ }
+ return d;
+ }
+
+ /**
+ * Checks if the alignment contains the required number of sequences.
+ *
+ * @param required
+ * @return
+ */
+ public boolean alignmentIsSufficient(int required)
+ {
+ if (getViewport().getSequenceSelection().length < required)
+ {
+ JOptionPane.showMessageDialog(this,
+ MessageManager.getString("label.not_enough_sequences"));
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
+ * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
+ * comma-separated list)
+ */
+ @Override
+ public void addDatabase_actionPerformed() throws IOException
+ {
+ if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
+ {
+ Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
+ }
- FileLoader loader = new FileLoader();
- DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(fileName)
- ? DataSourceType.URL
- : DataSourceType.FILE;
- loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
+ String path = openFileChooser(false);
+ if (path != null && new File(path).exists())
+ {
+ IdentifyFile identifier = new IdentifyFile();
+ FileFormatI format = identifier.identify(path, DataSourceType.FILE);
+ if (format == FileFormat.Fasta || format == FileFormat.Stockholm
+ || format == FileFormat.Pfam)
+ {
+ String currentDbPaths = Cache
+ .getProperty(Preferences.HMMSEARCH_DBS);
+ currentDbPaths += Preferences.COMMA + path;
+ Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
}
else
{
- Rectangle bounds = this.getBounds();
+ JOptionPane.showMessageDialog(this,
+ MessageManager.getString("warn.invalid_format"));
+ }
+ }
+ }
- FileLoader loader = new FileLoader();
+ /**
+ * Opens a file chooser, optionally restricted to selecting folders
+ * (directories) only. Answers the path to the selected file or folder, or
+ * null if none is chosen.
+ *
+ * @param
+ * @return
+ */
+ protected String openFileChooser(boolean forFolder)
+ {
+ // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
+ String choice = null;
+ JFileChooser chooser = new JFileChooser();
+ if (forFolder)
+ {
+ chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
+ }
+ chooser.setDialogTitle(
+ MessageManager.getString("label.open_local_file"));
+ chooser.setToolTipText(MessageManager.getString("action.open"));
- AlignFrame newframe = null;
+ int value = chooser.showOpenDialog(this);
- if (fileObject == null)
- {
+ if (value == JFileChooser.APPROVE_OPTION)
+ {
+ choice = chooser.getSelectedFile().getPath();
+ }
+ return choice;
+ }
- DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(
- fileName) ? DataSourceType.URL : DataSourceType.FILE;
- newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
- currentFileFormat);
- }
- else
+ @Override
+ public void reload_actionPerformed(ActionEvent e)
+ {
+ if (fileName == null && fileObject == null)
+ {
+ return;
+ }
+ // TODO: JAL-1108 - ensure all associated frames are closed regardless of
+ // originating file's format
+ // TODO: work out how to recover feature settings for correct view(s) when
+ // file is reloaded.
+ if (FileFormat.Jalview.equals(currentFileFormat))
+ {
+ JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
+ for (int i = 0; i < frames.length; i++)
+ {
+ if (frames[i] instanceof AlignFrame && frames[i] != this
+ && ((AlignFrame) frames[i]).fileName != null
+ && ((AlignFrame) frames[i]).fileName.equals(fileName))
{
- newframe = loader.LoadFileWaitTillLoaded(fileObject,
- DataSourceType.FILE, currentFileFormat);
+ try
+ {
+ frames[i].setSelected(true);
+ Desktop.getInstance().closeAssociatedWindows();
+ } catch (java.beans.PropertyVetoException ex)
+ {
+ }
}
- newframe.setBounds(bounds);
- if (featureSettings != null && featureSettings.isShowing())
+ }
+ Desktop.getInstance().closeAssociatedWindows();
+
+ FileLoader loader = new FileLoader();
+ loader.LoadFile(viewport, (fileObject == null ? fileName : fileObject), protocol, currentFileFormat);
+ }
+ else
+ {
+ Rectangle bounds = this.getBounds();
+
+ FileLoader loader = new FileLoader();
+
+ AlignFrame newframe = null;
+
+ if (fileObject == null)
+ {
+ newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
+ currentFileFormat);
+ }
+ else
+ {
+ newframe = loader.LoadFileWaitTillLoaded(fileObject,
+ DataSourceType.FILE, currentFileFormat);
+ }
+
+ newframe.setBounds(bounds);
+ if (featureSettings != null && featureSettings.isShowing())
+ {
+ final Rectangle fspos = featureSettings.frame.getBounds();
+ // TODO: need a 'show feature settings' function that takes bounds -
+ // need to refactor Desktop.addFrame
+ newframe.featureSettings_actionPerformed(null);
+ final FeatureSettings nfs = newframe.featureSettings;
+ SwingUtilities.invokeLater(new Runnable()
{
- final Rectangle fspos = featureSettings.frame.getBounds();
- // TODO: need a 'show feature settings' function that takes bounds -
- // need to refactor Desktop.addFrame
- newframe.featureSettings_actionPerformed(null);
- final FeatureSettings nfs = newframe.featureSettings;
- SwingUtilities.invokeLater(new Runnable()
+ @Override
+ public void run()
{
- @Override
- public void run()
- {
- nfs.frame.setBounds(fspos);
- }
- });
- this.featureSettings.close();
- this.featureSettings = null;
- }
- this.closeMenuItem_actionPerformed(true);
+ nfs.frame.setBounds(fspos);
+ }
+ });
+ this.featureSettings.close();
+ this.featureSettings = null;
}
+ this.closeMenuItem_actionPerformed(true);
}
}
@Override
public void addFromText_actionPerformed(ActionEvent e)
{
- Desktop.instance
+ Desktop.getInstance()
.inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
}
@Override
public void addFromURL_actionPerformed(ActionEvent e)
{
- Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
+ Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
}
@Override
// todo is this (2005) test now obsolete - value is never null?
while (currentFileFormat == null)
{
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
MessageManager
.getString("label.select_file_format_before_saving"),
MessageManager.getString("label.file_format_not_specified"),
}
else
{
- Cache.log.error(MessageManager
+ Console.error(MessageManager
.formatMessage("label.couldnt_save_file", new Object[]
{ lastFilenameSaved }));
}
}
lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
shortName);
+
statusBar.setText(MessageManager.formatMessage(
"label.successfully_saved_to_file_in_format", new Object[]
- { file, format }));
+ { fileName, format }));
+
return;
}
BackupFiles backupfiles = null;
if (doBackup)
{
- Cache.log.trace(
+ Console.trace(
"ALIGNFRAME making backupfiles object for " + file);
backupfiles = new BackupFiles(file);
}
{
String tempFilePath = doBackup ? backupfiles.getTempFilePath()
: file;
- Cache.log.trace("ALIGNFRAME setting PrintWriter");
+ Console.trace("ALIGNFRAME setting PrintWriter");
PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
if (backupfiles != null)
{
- Cache.log.trace("ALIGNFRAME about to write to temp file "
+ Console.trace("ALIGNFRAME about to write to temp file "
+ backupfiles.getTempFilePath());
}
out.print(output);
- Cache.log.trace("ALIGNFRAME about to close file");
+ Console.trace("ALIGNFRAME about to close file");
out.close();
- Cache.log.trace("ALIGNFRAME closed file");
+ Console.trace("ALIGNFRAME closed file");
AlignFrame.this.setTitle(file);
statusBar.setText(MessageManager.formatMessage(
"label.successfully_saved_to_file_in_format",
} catch (IOException e)
{
lastSaveSuccessful = false;
- Cache.log.error(
+ Console.error(
"ALIGNFRAME Something happened writing the temp file");
- Cache.log.error(e.getMessage());
- Cache.log.debug(Cache.getStackTraceString(e));
+ Console.error(e.getMessage());
+ Console.debug(Cache.getStackTraceString(e));
} catch (Exception ex)
{
lastSaveSuccessful = false;
- Cache.log.error(
+ Console.error(
"ALIGNFRAME Something unexpected happened writing the temp file");
- Cache.log.error(ex.getMessage());
- Cache.log.debug(Cache.getStackTraceString(ex));
+ Console.error(ex.getMessage());
+ Console.debug(Cache.getStackTraceString(ex));
}
if (doBackup)
{
backupfiles.setWriteSuccess(lastSaveSuccessful);
- Cache.log.debug("ALIGNFRAME writing temp file was "
+ Console.debug("ALIGNFRAME writing temp file was "
+ (lastSaveSuccessful ? "" : "NOT ") + "successful");
// do the backup file roll and rename the temp file to actual file
- Cache.log.trace(
+ Console.trace(
"ALIGNFRAME about to rollBackupsAndRenameTempFile");
lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
- Cache.log.debug(
+ Console.debug(
"ALIGNFRAME performed rollBackupsAndRenameTempFile "
+ (lastSaveSuccessful ? "" : "un")
+ "successfully");
bjs.exportHTML(null);
}
+ // ??
public void createImageMap(File file, String image)
{
alignPanel.makePNGImageMap(file, image);
@Override
public void associatedData_actionPerformed(ActionEvent e)
+ throws IOException, InterruptedException
{
final JalviewFileChooser chooser = new JalviewFileChooser(
- jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
+ Cache.getProperty("LAST_DIRECTORY"));
chooser.setFileView(new JalviewFileView());
String tooltip = MessageManager
.getString("label.load_jalview_annotations");
public void run()
{
String choice = chooser.getSelectedFile().getPath();
- jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
+ Cache.setProperty("LAST_DIRECTORY", choice);
loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
}
});
{
if (originalSource != viewport)
{
- Cache.log.warn(
+ Console.warn(
"Implementation worry: mismatch of viewport origin for undo");
}
originalSource.updateHiddenColumns();
// && viewport.getColumnSelection().getHiddenColumns() != null &&
// viewport.getColumnSelection()
// .getHiddenColumns().size() > 0);
- originalSource.firePropertyChange("alignment", null,
- originalSource.getAlignment().getSequences());
+ originalSource.notifyAlignment();
}
}
if (originalSource != viewport)
{
- Cache.log.warn(
+ Console.warn(
"Implementation worry: mismatch of viewport origin for redo");
}
originalSource.updateHiddenColumns();
// && viewport.getColumnSelection().getHiddenColumns() != null &&
// viewport.getColumnSelection()
// .getHiddenColumns().size() > 0);
- originalSource.firePropertyChange("alignment", null,
- originalSource.getAlignment().getSequences());
+ originalSource.notifyAlignment();
}
}
{
return;
}
+
// TODO: JAL-3733 - add an event to the undo buffer for this !
+
viewport.getAlignment().moveSelectedSequencesByOne(sg,
viewport.getHiddenRepSequences(), up);
alignPanel.paintAlignment(true, false);
StringSelection ss = new StringSelection(output);
+ Desktop d = Desktop.getInstance();
try
{
- jalview.gui.Desktop.internalCopy = true;
+ d.internalCopy = true;
// Its really worth setting the clipboard contents
// to empty before setting the large StringSelection!!
Toolkit.getDefaultToolkit().getSystemClipboard()
.setContents(new StringSelection(""), null);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
- Desktop.instance);
+ d);
} catch (OutOfMemoryError er)
{
new OOMWarning("copying region", er);
hiddenCutoff, hiddenOffset);
}
- Desktop.jalviewClipboard = new Object[] { seqs,
+ d.jalviewClipboard = new Object[] { seqs,
viewport.getAlignment().getDataset(), hiddenColumns };
setStatus(MessageManager.formatMessage(
"label.copied_sequences_to_clipboard", new Object[]
*
* @param e
* DOCUMENT ME!
+ * @throws InterruptedException
+ * @throws IOException
*/
@Override
protected void pasteNew_actionPerformed(ActionEvent e)
+ throws IOException, InterruptedException
{
paste(true);
}
*
* @param e
* DOCUMENT ME!
+ * @throws InterruptedException
+ * @throws IOException
*/
@Override
protected void pasteThis_actionPerformed(ActionEvent e)
+ throws IOException, InterruptedException
{
paste(false);
}
*
* @param newAlignment
* true to paste to a new alignment, otherwise add to this.
+ * @throws InterruptedException
+ * @throws IOException
*/
- void paste(boolean newAlignment)
+ void paste(boolean newAlignment) throws IOException, InterruptedException
{
boolean externalPaste = true;
try
boolean annotationAdded = false;
AlignmentI alignment = null;
- if (Desktop.jalviewClipboard != null)
+ Desktop d = Desktop.getInstance();
+
+ if (d.jalviewClipboard != null)
{
// The clipboard was filled from within Jalview, we must use the
// sequences
// And dataset from the copied alignment
- SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
+ SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
// be doubly sure that we create *new* sequence objects.
sequences = new SequenceI[newseq.length];
for (int i = 0; i < newseq.length; i++)
if (newAlignment)
{
- if (Desktop.jalviewClipboard != null)
+ if (d.jalviewClipboard != null)
{
// dataset is inherited
- alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
+ alignment.setDataset((Alignment) d.jalviewClipboard[1]);
}
else
{
alignment = viewport.getAlignment();
alwidth = alignment.getWidth() + 1;
// decide if we need to import sequences from an existing dataset
- boolean importDs = Desktop.jalviewClipboard != null
- && Desktop.jalviewClipboard[1] != alignment.getDataset();
+ boolean importDs = d.jalviewClipboard != null
+ && d.jalviewClipboard[1] != alignment.getDataset();
// importDs==true instructs us to copy over new dataset sequences from
// an existing alignment
Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
}
buildSortByAnnotationScoresMenu();
}
- viewport.firePropertyChange("alignment", null,
- alignment.getSequences());
+ viewport.notifyAlignment();
if (alignPanels != null)
{
for (AlignmentPanel ap : alignPanels)
DEFAULT_HEIGHT);
String newtitle = new String("Copied sequences");
- if (Desktop.jalviewClipboard != null
- && Desktop.jalviewClipboard[2] != null)
+ if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
{
- HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
+ HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
af.viewport.setHiddenColumns(hc);
}
DEFAULT_HEIGHT);
String newtitle = new String("Flanking alignment");
- if (Desktop.jalviewClipboard != null
- && Desktop.jalviewClipboard[2] != null)
+ Desktop d = Desktop.getInstance();
+ if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
{
- HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
+ HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
af.viewport.setHiddenColumns(hc);
}
Runnable okAction = new Runnable()
{
-
@Override
public void run()
{
viewport.sendSelection();
viewport.getAlignment().deleteGroup(sg);
- viewport.firePropertyChange("alignment", null,
- viewport.getAlignment().getSequences());
+ viewport.notifyAlignment();
-
if (viewport.getAlignment().getHeight() < 1)
{
try
} catch (Exception ex)
{
}
+ } else {
+ updateAll(null);
}
}
};
+ 1) == viewport.getAlignment().getWidth()) ? true : false;
if (wholeHeight && wholeWidth)
{
- JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
+ JvOptionPane dialog = JvOptionPane
+ .newOptionDialog(Desktop.getDesktopPane());
dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
Object[] options = new Object[] {
MessageManager.getString("action.ok"),
{
if (avc.deleteGroups())
{
- PaintRefresher.Refresh(this, viewport.getSequenceSetId());
- alignPanel.updateAnnotation();
+ updateAll(viewport.getSequenceSetId());
+ }
+ }
+
+ private void updateAll(String id)
+ {
+ if (id == null)
+ {
+ // this will force a non-fast repaint of both the IdPanel and SeqPanel
+ alignPanel.getIdPanel().getIdCanvas().setNoFastPaint();
+ alignPanel.getSeqPanel().seqCanvas.setNoFastPaint();
+ alignPanel.repaint();
+ }
+ else
+ {
+ // original version
+ PaintRefresher.Refresh(this, id);
alignPanel.paintAlignment(true, true);
}
+ alignPanel.updateAnnotation();
}
/**
@Override
public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
{
- SequenceGroup sg = new SequenceGroup(
- viewport.getAlignment().getSequences());
-
- sg.setEndRes(viewport.getAlignment().getWidth() - 1);
- viewport.setSelectionGroup(sg);
- viewport.isSelectionGroupChanged(true);
- viewport.sendSelection();
- // JAL-2034 - should delegate to
- // alignPanel to decide if overview needs
- // updating.
- alignPanel.paintAlignment(false, false);
- PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
+ alignPanel.selectAllSequences();
}
/**
@Override
public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
{
- if (viewport.cursorMode)
- {
- alignPanel.getSeqPanel().keyboardNo1 = null;
- alignPanel.getSeqPanel().keyboardNo2 = null;
- }
- viewport.setSelectionGroup(null);
- viewport.getColumnSelection().clear();
- viewport.setSearchResults(null);
- alignPanel.getIdPanel().getIdCanvas().searchResults = null;
- // JAL-2034 - should delegate to
- // alignPanel to decide if overview needs
- // updating.
- alignPanel.paintAlignment(false, false);
- PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
- viewport.sendSelection();
+ alignPanel.deselectAllSequences();
}
/**
if (sg == null)
{
- selectAllSequenceMenuItem_actionPerformed(null);
+ alignPanel.selectAllSequences();
return;
}
}
}
- viewport.firePropertyChange("alignment", null,
- viewport.getAlignment().getSequences());
+ viewport.notifyAlignment();
}
}
// if (viewport.hasHiddenColumns)
// viewport.getColumnSelection().compensateForEdits(shifts);
ranges.setStartRes(seq.findIndex(startRes) - 1);
- viewport.firePropertyChange("alignment", null,
- viewport.getAlignment().getSequences());
+ viewport.notifyAlignment();
}
viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
- viewport.firePropertyChange("alignment", null,
- viewport.getAlignment().getSequences());
+ viewport.notifyAlignment();
}
public void padGapsMenuitem_actionPerformed(ActionEvent e)
{
viewport.setPadGaps(padGapsMenuitem.isSelected());
- viewport.firePropertyChange("alignment", null,
- viewport.getAlignment().getSequences());
+ viewport.notifyAlignment();
}
/**
@Override
public void gatherViews_actionPerformed(ActionEvent e)
{
- Desktop.instance.gatherViews(this);
+ Desktop.getInstance().gatherViews(this);
}
/**
{
final boolean setVisible = annotationPanelMenuItem.isSelected();
viewport.setShowAnnotation(setVisible);
- this.showAllSeqAnnotations.setEnabled(setVisible);
- this.hideAllSeqAnnotations.setEnabled(setVisible);
- this.showAllAlAnnotations.setEnabled(setVisible);
- this.hideAllAlAnnotations.setEnabled(setVisible);
+ syncAnnotationMenuItems(setVisible);
alignPanel.updateLayout();
+ repaint();
+ SwingUtilities.invokeLater(new Runnable() {
+
+ @Override
+ public void run()
+ {
+ alignPanel.updateScrollBarsFromRanges();
+ }
+
+ });
+ }
+
+ private void syncAnnotationMenuItems(boolean setVisible)
+ {
+ showAllSeqAnnotations.setEnabled(setVisible);
+ hideAllSeqAnnotations.setEnabled(setVisible);
+ showAllAlAnnotations.setEnabled(setVisible);
+ hideAllAlAnnotations.setEnabled(setVisible);
}
@Override
JLabel textLabel = new JLabel();
textLabel.setText(content);
textLabel.setBackground(Color.WHITE);
+
pane = new JPanel(new BorderLayout());
((JPanel) pane).setOpaque(true);
pane.setBackground(Color.WHITE);
}
JInternalFrame frame = new JInternalFrame();
- final OverviewPanel overview = new OverviewPanel(alignPanel);
+ // BH 2019.07.26 we allow for an embedded
+ // undecorated overview with defined size
+ frame.setName(Platform.getAppID("overview"));
+ //
+ Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
+ if (dim != null && dim.width == 0)
+ {
+ dim = null; // hidden, not embedded
+ }
+ OverviewPanel overview = new OverviewPanel(alignPanel, dim);
frame.setContentPane(overview);
+ if (dim == null)
+ {
+ dim = new Dimension();
+ // was frame.getSize(), but that is 0,0 at this point;
+ }
+ else
+ {
+ // we are imbedding, and so we have an undecorated frame
+ // and we can set the the frame dimensions accordingly.
+ }
+ // allowing for unresizable option using, style="resize:none"
+ boolean resizable = (Platform.getEmbeddedAttribute(frame,
+ "resize") != "none");
Desktop.addInternalFrame(frame, MessageManager
.formatMessage("label.overview_params", new Object[]
- { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
- true, true);
+ { this.getTitle() }), Desktop.FRAME_MAKE_VISIBLE, dim.width,
+ dim.height, resizable, Desktop.FRAME_ALLOW_ANY_SIZE);
frame.pack();
frame.setLayer(JLayeredPane.PALETTE_LAYER);
frame.addInternalFrameListener(
alignPanel.paintAlignment(true, false);
}
+ @Override
+ public void sortEValueMenuItem_actionPerformed(ActionEvent e)
+ {
+ SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
+ AlignmentSorter.sortByEValue(viewport.getAlignment());
+ addHistoryItem(new OrderCommand("Group Sort", oldOrder,
+ viewport.getAlignment()));
+ alignPanel.paintAlignment(true, false);
+
+ }
+
+ @Override
+ public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
+ {
+ SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
+ AlignmentSorter.sortByBitScore(viewport.getAlignment());
+ addHistoryItem(new OrderCommand("Group Sort", oldOrder,
+ viewport.getAlignment()));
+ alignPanel.paintAlignment(true, false);
+
+ }
/**
* DOCUMENT ME!
*
@Override
public void autoCalculate_actionPerformed(ActionEvent e)
{
- viewport.autoCalculateConsensus = autoCalculate.isSelected();
- if (viewport.autoCalculateConsensus)
+ viewport.setAutoCalculateConsensusAndConservation(
+ autoCalculate.isSelected());
+ if (viewport.getAutoCalculateConsensusAndConservation())
{
- viewport.firePropertyChange("alignment", null,
- viewport.getAlignment().getSequences());
+ viewport.notifyAlignment();
}
}
{
if (_s.getLength() < sg.getEndRes())
{
- JvOptionPane.showMessageDialog(Desktop.desktop,
+ JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
MessageManager.getString(
"label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
MessageManager.getString(
frameTitle += this.title;
- Desktop.addInternalFrame(tp, frameTitle, 600, 500);
+ Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
+ Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
}
/**
}
if (viewport.getAlignment().getAlignmentAnnotation()
- .hashCode() != _annotationScoreVectorHash)
+ .hashCode() == _annotationScoreVectorHash)
{
- sortByAnnotScore.removeAll();
- // almost certainly a quicker way to do this - but we keep it simple
- Hashtable<String, String> scoreSorts = new Hashtable<>();
- AlignmentAnnotation aann[];
- for (SequenceI sqa : viewport.getAlignment().getSequences())
+ return;
+ }
+
+ sortByAnnotScore.removeAll();
+ Set<String> scoreSorts = new HashSet<>();
+ for (SequenceI sqa : viewport.getAlignment().getSequences())
+ {
+ AlignmentAnnotation[] anns = sqa.getAnnotation();
+ for (int i = 0; anns != null && i < anns.length; i++)
{
- aann = sqa.getAnnotation();
- for (int i = 0; aann != null && i < aann.length; i++)
+ AlignmentAnnotation aa = anns[i];
+ if (aa != null && aa.hasScore() && aa.sequenceRef != null)
{
- if (aann[i].hasScore() && aann[i].sequenceRef != null)
- {
- scoreSorts.put(aann[i].label, aann[i].label);
- }
+ scoreSorts.add(aa.label);
}
}
- Enumeration<String> labels = scoreSorts.keys();
- while (labels.hasMoreElements())
- {
- addSortByAnnotScoreMenuItem(sortByAnnotScore, labels.nextElement());
- }
- sortByAnnotScore.setVisible(scoreSorts.size() > 0);
- scoreSorts.clear();
-
- _annotationScoreVectorHash = viewport.getAlignment()
- .getAlignmentAnnotation().hashCode();
}
+ for (String label : scoreSorts)
+ {
+ addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
+ }
+ sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
+
+ _annotationScoreVectorHash = viewport.getAlignment()
+ .getAlignmentAnnotation().hashCode();
}
/**
+ * Enable (or, if desired, make visible) the By Tree
+ * submenu only if it has at least one element (or will have).
+ *
+ */
+ @Override
+ protected void enableSortMenuOptions()
+ {
+ List<TreePanel> treePanels = getTreePanels();
+ sortByTreeMenu.setEnabled(!treePanels.isEmpty());
+ }
+
+ /**
* Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
* TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
* call. Listeners are added to remove the menu item when the treePanel is
{
sortByTreeMenu.removeAll();
- List<Component> comps = PaintRefresher.components
- .get(viewport.getSequenceSetId());
- List<TreePanel> treePanels = new ArrayList<>();
- for (Component comp : comps)
- {
- if (comp instanceof TreePanel)
- {
- treePanels.add((TreePanel) comp);
- }
- }
-
- if (treePanels.size() < 1)
- {
- sortByTreeMenu.setVisible(false);
- return;
- }
-
- sortByTreeMenu.setVisible(true);
+ List<TreePanel> treePanels = getTreePanels();
for (final TreePanel tp : treePanels)
{
}
}
+ private List<TreePanel> getTreePanels()
+ {
+ List<Component> comps = PaintRefresher.components
+ .get(viewport.getSequenceSetId());
+ List<TreePanel> treePanels = new ArrayList<>();
+ for (Component comp : comps)
+ {
+ if (comp instanceof TreePanel)
+ {
+ treePanels.add((TreePanel) comp);
+ }
+ }
+ return treePanels;
+ }
public boolean sortBy(AlignmentOrder alorder, String undoname)
{
SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
{
// Pick the tree file
JalviewFileChooser chooser = new JalviewFileChooser(
- jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
+ Cache.getProperty("LAST_DIRECTORY"));
chooser.setFileView(new JalviewFileView());
chooser.setDialogTitle(
MessageManager.getString("label.select_newick_like_tree_file"));
viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
} catch (Exception ex)
{
- JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
+ JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
+ ex.getMessage(),
MessageManager
.getString("label.problem_reading_tree_file"),
JvOptionPane.WARNING_MESSAGE);
}
if (fin != null && fin.hasWarningMessage())
{
- JvOptionPane.showMessageDialog(Desktop.desktop,
+ JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
fin.getWarningMessage(),
MessageManager.getString(
"label.possible_problem_with_tree_file"),
{
tp = new TreePanel(alignPanel, nf, treeTitle, input);
- tp.setSize(w, h);
+ Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
+ if (dim == null)
+ {
+ dim = new Dimension(w, h);
+ }
+ else
+ {
+ // no offset, either
+ x = 0;
+ }
+ tp.setSize(dim.width, dim.height);
if (x > 0 && y > 0)
{
tp.setLocation(x, y);
}
- Desktop.addInternalFrame(tp, treeTitle, w, h);
+ Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
}
} catch (Exception ex)
{
return tp;
}
- private boolean buildingMenu = false;
/**
- * Generates menu items and listener event actions for web service clients
- *
+ * Schedule the web services menu rebuild to the event dispatch thread.
*/
- public void BuildWebServiceMenu()
+ public void buildWebServicesMenu()
{
- while (buildingMenu)
- {
- try
+ SwingUtilities.invokeLater(() -> {
- Cache.log.info("Rebuiling WS menu");
++ Console.info("Rebuiling WS menu");
+ webService.removeAll();
+ if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
{
- Cache.log.info("Building web service menu for slivka");
- System.err.println("Waiting for building menu to finish.");
- Thread.sleep(10);
- } catch (Exception e)
++ Console.info("Building web service menu for slivka");
+ SlivkaWSDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
+ JMenu submenu = new JMenu("Slivka");
+ buildWebServicesMenu(discoverer, submenu);
+ webService.add(submenu);
+ }
+ if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
{
+ WSDiscovererI jws2servs = Jws2Discoverer.getInstance();
+ JMenu submenu = new JMenu("JABAWS");
+ buildLegacyWebServicesMenu(submenu);
+ buildWebServicesMenu(jws2servs, submenu);
+ webService.add(submenu);
}
- }
- final AlignFrame me = this;
- buildingMenu = true;
- new Thread(new Runnable()
+ build_fetchdbmenu(webService);
+ });
+ }
+
+ private void buildLegacyWebServicesMenu(JMenu menu)
+ {
+ JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
+ if (Discoverer.getServices() != null && Discoverer.getServices().size() > 0)
{
- @Override
- public void run()
+ var secstrpred = Discoverer.getServices().get("SecStrPred");
+ if (secstrpred != null)
{
- final List<JMenuItem> legacyItems = new ArrayList<>();
- try
- {
- // System.err.println("Building ws menu again "
- // + Thread.currentThread());
- // TODO: add support for context dependent disabling of services based
- // on
- // alignment and current selection
- // TODO: add additional serviceHandle parameter to specify abstract
- // handler
- // class independently of AbstractName
- // TODO: add in rediscovery GUI function to restart discoverer
- // TODO: group services by location as well as function and/or
- // introduce
- // object broker mechanism.
- final Vector<JMenu> wsmenu = new Vector<>();
- final IProgressIndicator af = me;
-
- /*
- * do not i18n these strings - they are hard-coded in class
- * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
- * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
- */
- final JMenu msawsmenu = new JMenu("Alignment");
- final JMenu secstrmenu = new JMenu(
- "Secondary Structure Prediction");
- final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
- final JMenu analymenu = new JMenu("Analysis");
- final JMenu dismenu = new JMenu("Protein Disorder");
- // JAL-940 - only show secondary structure prediction services from
- // the legacy server
- if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
- // &&
- Discoverer.services != null && (Discoverer.services.size() > 0))
- {
- // TODO: refactor to allow list of AbstractName/Handler bindings to
- // be
- // stored or retrieved from elsewhere
- // No MSAWS used any more:
- // Vector msaws = null; // (Vector)
- // Discoverer.services.get("MsaWS");
- Vector<ServiceHandle> secstrpr = Discoverer.services
- .get("SecStrPred");
- if (secstrpr != null)
- {
- // Add any secondary structure prediction services
- for (int i = 0, j = secstrpr.size(); i < j; i++)
- {
- final ext.vamsas.ServiceHandle sh = secstrpr.get(i);
- jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
- .getServiceClient(sh);
- int p = secstrmenu.getItemCount();
- impl.attachWSMenuEntry(secstrmenu, me);
- int q = secstrmenu.getItemCount();
- for (int litm = p; litm < q; litm++)
- {
- legacyItems.add(secstrmenu.getItem(litm));
- }
- }
- }
- }
-
- // Add all submenus in the order they should appear on the web
- // services menu
- wsmenu.add(msawsmenu);
- wsmenu.add(secstrmenu);
- wsmenu.add(dismenu);
- wsmenu.add(analymenu);
- // No search services yet
- // wsmenu.add(seqsrchmenu);
-
- javax.swing.SwingUtilities.invokeLater(new Runnable()
- {
- @Override
- public void run()
- {
- try
- {
- webService.removeAll();
- // first, add discovered services onto the webservices menu
- if (wsmenu.size() > 0)
- {
- for (int i = 0, j = wsmenu.size(); i < j; i++)
- {
- webService.add(wsmenu.get(i));
- }
- }
- else
- {
- webService.add(me.webServiceNoServices);
- }
- // TODO: move into separate menu builder class.
- {
- // logic for 2.11.1.4 is
- // always look to see if there is a discover. if there isn't
- // we can't show any Jws2 services
- // if there are services available, show them - regardless of
- // the 'show JWS2 preference'
- // if the discoverer is running then say so
- // otherwise offer to trigger discovery if 'show JWS2' is not
- // enabled
- Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
- if (jws2servs != null)
- {
- if (jws2servs.hasServices())
- {
- jws2servs.attachWSMenuEntry(webService, me);
- for (Jws2Instance sv : jws2servs.getServices())
- {
- if (sv.description.toLowerCase(Locale.ROOT)
- .contains("jpred"))
- {
- for (JMenuItem jmi : legacyItems)
- {
- jmi.setVisible(false);
- }
- }
- }
- }
-
- if (jws2servs.isRunning())
- {
- JMenuItem tm = new JMenuItem(
- "Still discovering JABA Services");
- tm.setEnabled(false);
- webService.add(tm);
- }
- else if (!Cache.getDefault("SHOW_JWS2_SERVICES", true))
- {
- JMenuItem enableJws2 = new JMenuItem(
- "Discover Web Services");
- enableJws2.setToolTipText(
- "Select to start JABA Web Service discovery (or enable option in Web Service preferences)");
- enableJws2.setEnabled(true);
- enableJws2.addActionListener(new ActionListener()
- {
-
- @Override
- public void actionPerformed(ActionEvent e)
- {
- // start service discoverer, but ignore preference
- Desktop.instance.startServiceDiscovery(false,
- true);
- }
- });
- webService.add(enableJws2);
- }
- }
- }
- build_urlServiceMenu(me.webService);
- build_fetchdbmenu(webService);
- for (JMenu item : wsmenu)
- {
- if (item.getItemCount() == 0)
- {
- item.setEnabled(false);
- }
- else
- {
- item.setEnabled(true);
- }
- }
- } catch (Exception e)
- {
- Console.debug(
- "Exception during web service menu building process.",
- e);
- }
- }
- });
- } catch (Exception e)
+ for (ext.vamsas.ServiceHandle sh : secstrpred)
{
+ var menuProvider = Discoverer.getServiceClient(sh);
+ menuProvider.attachWSMenuEntry(secstrmenu, this);
}
- buildingMenu = false;
}
- }).start();
+ }
+ menu.add(secstrmenu);
+ }
+ /**
+ * Constructs the web services menu for the given discoverer under the
+ * specified menu. This method must be called on the EDT
+ *
+ * @param discoverer
+ * the discoverer used to build the menu
+ * @param menu
+ * parent component which the elements will be attached to
+ */
+ private void buildWebServicesMenu(WSDiscovererI discoverer, JMenu menu)
+ {
+ if (discoverer.hasServices())
+ {
+ PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
+ discoverer.getServices(), sv -> buildWebServicesMenu(), menu,
+ this, null);
+ }
+ if (discoverer.isRunning())
+ {
+ JMenuItem item = new JMenuItem("Service discovery in progress.");
+ item.setEnabled(false);
+ menu.add(item);
+ }
+ else if (!discoverer.hasServices())
+ {
+ JMenuItem item = new JMenuItem("No services available.");
+ item.setEnabled(false);
+ menu.add(item);
+ }
}
/**
* JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
* AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
*
- * @Override public void actionPerformed(ActionEvent e) {
+ * public void actionPerformed(ActionEvent e) {
* jalview.datamodel.AlignmentView
* .testSelectionViews(af.viewport.getAlignment(),
* af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
showProducts.setEnabled(showp);
} catch (Exception e)
{
- Cache.log.warn(
+ Console.warn(
"canShowProducts threw an exception - please report to help@jalview.org",
e);
return false;
al = dna.translateCdna(codeTable);
} catch (Exception ex)
{
- jalview.bin.Cache.log.error(
- "Exception during translation. Please report this !", ex);
+ Console.error("Exception during translation. Please report this !",
+ ex);
final String msg = MessageManager.getString(
"label.error_when_translating_sequences_submit_bug_report");
final String errorTitle = MessageManager
.getString("label.implementation_error")
+ MessageManager.getString("label.translation_failed");
- JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
- JvOptionPane.ERROR_MESSAGE);
+ JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
+ errorTitle, JvOptionPane.ERROR_MESSAGE);
return;
}
if (al == null || al.getHeight() == 0)
"label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
final String errorTitle = MessageManager
.getString("label.translation_failed");
- JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
- JvOptionPane.WARNING_MESSAGE);
+ JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
+ errorTitle, JvOptionPane.WARNING_MESSAGE);
}
else
{
if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
{
final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
- viewport.openSplitFrame(af, new Alignment(seqs));
+ AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
}
else
{
{
// BH 2018
return avc.parseFeaturesFile(file, sourceType,
- Cache.getDefault("RELAXEDSEQIDMATCHING", false));
+ Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
}
evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
Transferable t = evt.getTransferable();
- final AlignFrame thisaf = this;
final List<Object> files = new ArrayList<>();
List<DataSourceType> protocols = new ArrayList<>();
try
{
Desktop.transferFromDropTarget(files, protocols, evt, t);
+ if (files.size() > 0)
+ {
+ new Thread(new Runnable()
+ {
+
+ @Override
+ public void run()
+ {
+ loadDroppedFiles(files, protocols, evt, t);
+ }
+ }).start();
+ }
} catch (Exception e)
{
e.printStackTrace();
}
- if (files != null)
+ }
+
+ protected void loadDroppedFiles(List<Object> files,
+ List<DataSourceType> protocols, DropTargetDropEvent evt,
+ Transferable t)
+ {
+ try
{
- new Thread(new Runnable()
+ // check to see if any of these files have names matching sequences
+ // in
+ // the alignment
+ SequenceIdMatcher idm = new SequenceIdMatcher(
+ viewport.getAlignment().getSequencesArray());
+ /**
+ * Object[] { String,SequenceI}
+ */
+ ArrayList<Object[]> filesmatched = new ArrayList<>();
+ ArrayList<Object> filesnotmatched = new ArrayList<>();
+ for (int i = 0; i < files.size(); i++)
{
- @Override
- public void run()
+ // BH 2018
+ Object fileObj = files.get(i);
+ String fileName = fileObj.toString();
+ String pdbfn = "";
+ DataSourceType protocol = (fileObj instanceof File
+ ? DataSourceType.FILE
+ : FormatAdapter.checkProtocol(fileName));
+ if (protocol == DataSourceType.FILE)
{
- try
+ File file;
+ if (fileObj instanceof File)
+ {
+ file = (File) fileObj;
+ Platform.cacheFileData(file);
+ }
+ else
+ {
+ file = new File(fileName);
+ }
+ pdbfn = file.getName();
+ }
+ else if (protocol == DataSourceType.URL)
+ {
+ URL url = new URL(fileName);
+ pdbfn = url.getFile();
+ }
+ if (pdbfn.length() > 0)
+ {
+ // attempt to find a match in the alignment
+ SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
+ int l = 0, c = pdbfn.indexOf(".");
+ while (mtch == null && c != -1)
{
- // check to see if any of these files have names matching sequences
- // in
- // the alignment
- SequenceIdMatcher idm = new SequenceIdMatcher(
- viewport.getAlignment().getSequencesArray());
- /**
- * Object[] { String,SequenceI}
- */
- ArrayList<Object[]> filesmatched = new ArrayList<>();
- ArrayList<Object> filesnotmatched = new ArrayList<>();
- for (int i = 0; i < files.size(); i++)
+ do
{
- // BH 2018
- Object file = files.get(i);
- String fileName = file.toString();
- String pdbfn = "";
- DataSourceType protocol = (file instanceof File
- ? DataSourceType.FILE
- : FormatAdapter.checkProtocol(fileName));
- if (protocol == DataSourceType.FILE)
- {
- File fl;
- if (file instanceof File)
- {
- fl = (File) file;
- Platform.cacheFileData(fl);
- }
- else
- {
- fl = new File(fileName);
- }
- pdbfn = fl.getName();
- }
- else if (protocol == DataSourceType.URL)
- {
- URL url = new URL(fileName);
- pdbfn = url.getFile();
- }
- if (pdbfn.length() > 0)
- {
- // attempt to find a match in the alignment
- SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
- int l = 0, c = pdbfn.indexOf(".");
- while (mtch == null && c != -1)
- {
- do
- {
- l = c;
- } while ((c = pdbfn.indexOf(".", l)) > l);
- if (l > -1)
- {
- pdbfn = pdbfn.substring(0, l);
- }
- mtch = idm.findAllIdMatches(pdbfn);
- }
- if (mtch != null)
- {
- FileFormatI type;
- try
- {
- type = new IdentifyFile().identify(file, protocol);
- } catch (Exception ex)
- {
- type = null;
- }
- if (type != null && type.isStructureFile())
- {
- filesmatched.add(new Object[] { file, protocol, mtch });
- continue;
- }
- }
- // File wasn't named like one of the sequences or wasn't a PDB
- // file.
- filesnotmatched.add(file);
- }
+ l = c;
+ } while ((c = pdbfn.indexOf(".", l)) > l);
+ if (l > -1)
+ {
+ pdbfn = pdbfn.substring(0, l);
}
- int assocfiles = 0;
- if (filesmatched.size() > 0)
+ mtch = idm.findAllIdMatches(pdbfn);
+ }
+ if (mtch != null)
+ {
+ FileFormatI type;
+ try
{
- boolean autoAssociate = Cache
- .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
- if (!autoAssociate)
- {
- String msg = MessageManager.formatMessage(
- "label.automatically_associate_structure_files_with_sequences_same_name",
- new Object[]
- { Integer.valueOf(filesmatched.size())
- .toString() });
- String ttl = MessageManager.getString(
- "label.automatically_associate_structure_files_by_name");
- int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
- ttl, JvOptionPane.YES_NO_OPTION);
- autoAssociate = choice == JvOptionPane.YES_OPTION;
- }
- if (autoAssociate)
- {
- for (Object[] fm : filesmatched)
- {
- // try and associate
- // TODO: may want to set a standard ID naming formalism for
- // associating PDB files which have no IDs.
- for (SequenceI toassoc : (SequenceI[]) fm[2])
- {
- PDBEntry pe = new AssociatePdbFileWithSeq()
- .associatePdbWithSeq(fm[0].toString(),
- (DataSourceType) fm[1], toassoc, false,
- Desktop.instance);
- if (pe != null)
- {
- System.err.println("Associated file : "
- + (fm[0].toString()) + " with "
- + toassoc.getDisplayId(true));
- assocfiles++;
- }
- }
- // TODO: do we need to update overview ? only if features are
- // shown I guess
- alignPanel.paintAlignment(true, false);
- }
- }
- else
- {
- /*
- * add declined structures as sequences
- */
- for (Object[] o : filesmatched)
- {
- filesnotmatched.add(o[0]);
- }
- }
+ type = new IdentifyFile().identify(fileObj, protocol);
+ } catch (Exception ex)
+ {
+ type = null;
}
- if (filesnotmatched.size() > 0)
+ if (type != null && type.isStructureFile())
{
- if (assocfiles > 0 && (Cache.getDefault(
- "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
- || JvOptionPane.showConfirmDialog(thisaf,
- "<html>" + MessageManager.formatMessage(
- "label.ignore_unmatched_dropped_files_info",
- new Object[]
- { Integer.valueOf(
- filesnotmatched.size())
- .toString() })
- + "</html>",
- MessageManager.getString(
- "label.ignore_unmatched_dropped_files"),
- JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
- {
- return;
- }
- for (Object fn : filesnotmatched)
+ filesmatched.add(new Object[] { fileObj, protocol, mtch });
+ continue;
+ }
+ }
+ // File wasn't named like one of the sequences or wasn't a PDB
+ // file.
+ filesnotmatched.add(fileObj);
+ }
+ }
+ int assocfiles = 0;
+ if (filesmatched.size() > 0)
+ {
+ boolean autoAssociate = Cache
+ .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
+ if (!autoAssociate)
+ {
+ String msg = MessageManager.formatMessage(
+ "label.automatically_associate_structure_files_with_sequences_same_name",
+ new Object[]
+ { Integer.valueOf(filesmatched.size()).toString() });
+ String ttl = MessageManager.getString(
+ "label.automatically_associate_structure_files_by_name");
+ int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
+ JvOptionPane.YES_NO_OPTION);
+ autoAssociate = choice == JvOptionPane.YES_OPTION;
+ }
+ if (autoAssociate)
+ {
+ for (Object[] fm : filesmatched)
+ {
+ // try and associate
+ // TODO: may want to set a standard ID naming formalism for
+ // associating PDB files which have no IDs.
+ for (SequenceI toassoc : (SequenceI[]) fm[2])
+ {
+ PDBEntry pe = AssociatePdbFileWithSeq.associatePdbWithSeq(
+ fm[0].toString(), (DataSourceType) fm[1], toassoc,
+ false);
+ if (pe != null)
{
- loadJalviewDataFile(fn, null, null, null);
+ System.err.println("Associated file : " + (fm[0].toString())
+ + " with " + toassoc.getDisplayId(true));
+ assocfiles++;
}
}
- } catch (Exception ex)
+ // TODO: do we need to update overview ? only if features are
+ // shown I guess
+ alignPanel.paintAlignment(true, false);
+ }
+ }
+ else
+ {
+ /*
+ * add declined structures as sequences
+ */
+ for (Object[] o : filesmatched)
{
- ex.printStackTrace();
+ filesnotmatched.add(o[0]);
}
}
- }).start();
+ }
+ if (filesnotmatched.size() > 0)
+ {
+ if (assocfiles > 0 && (Cache
+ .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
+ || JvOptionPane.showConfirmDialog(this,
+ "<html>" + MessageManager.formatMessage(
+ "label.ignore_unmatched_dropped_files_info",
+ new Object[]
+ { Integer.valueOf(filesnotmatched.size())
+ .toString() })
+ + "</html>",
+ MessageManager.getString(
+ "label.ignore_unmatched_dropped_files"),
+ JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
+ {
+ return;
+ }
+ for (Object fn : filesnotmatched)
+ {
+ loadJalviewDataFile(fn, null, null, null);
+ }
+
+ }
+ } catch (Exception ex)
+ {
+ ex.printStackTrace();
}
}
*
* @param file
* either a filename or a URL string.
+ * @throws InterruptedException
+ * @throws IOException
*/
public void loadJalviewDataFile(Object file, DataSourceType sourceType,
FileFormatI format, SequenceI assocSeq)
{
// some problem - if no warning its probable that the ID matching
// process didn't work
- JvOptionPane.showMessageDialog(Desktop.desktop,
+ JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
tcf.getWarningMessage() == null
? MessageManager.getString(
"label.check_file_matches_sequence_ids_alignment")
}
} catch (Exception x)
{
- Cache.log.debug(
+ Console.debug(
"Exception when processing data source as T-COFFEE score file",
x);
tcf = null;
if (isAnnotation)
{
- alignPanel.adjustAnnotationHeight();
- viewport.updateSequenceIdColours();
- buildSortByAnnotationScoresMenu();
- alignPanel.paintAlignment(true, true);
+ updateForAnnotations();
}
} catch (Exception ex)
{
+ (format != null
? "(parsing as '" + format + "' file)"
: ""),
- oom, Desktop.desktop);
+ oom, Desktop.getDesktopPane());
+ }
+ }
+
+ /**
+ * Do all updates necessary after an annotation file such as jnet. Also called
+ * from Jalview.loadAppletParams for "annotations", "jnetFile"
+ */
+
+ public void updateForAnnotations()
+ {
+ alignPanel.adjustAnnotationHeight();
+ viewport.updateSequenceIdColours();
+ buildSortByAnnotationScoresMenu();
+ alignPanel.paintAlignment(true, true);
+ }
+
+ /**
+ * Change the display state for the given feature groups -- Added by BH from
+ * JalviewLite
+ *
+ * @param groups
+ * list of group strings
+ * @param state
+ * visible or invisible
+ */
+
+ public void setFeatureGroupState(String[] groups, boolean state)
+ {
+ jalview.api.FeatureRenderer fr = null;
+ viewport.setShowSequenceFeatures(true);
+ if (alignPanel != null
+ && (fr = alignPanel.getFeatureRenderer()) != null)
+ {
+
+ fr.setGroupVisibility(Arrays.asList(groups), state);
+ alignPanel.getSeqPanel().seqCanvas.repaint();
+ if (alignPanel.overviewPanel != null)
+ {
+ alignPanel.overviewPanel.updateOverviewImage();
+ }
}
}
@Override
public void run()
{
- final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
- .getSequenceFetcherSingleton();
+ // ??
+ // final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
+ // .getSequenceFetcherSingleton();
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
+ jalview.ws.SequenceFetcher sf = jalview.ws.SequenceFetcher
+ .getInstance();
String[] dbclasses = sf.getNonAlignmentSources();
List<DbSourceProxy> otherdb;
JMenu dfetch = new JMenu();
}
if (otherdb.size() == 1)
{
- final DbSourceProxy[] dassource = otherdb
- .toArray(new DbSourceProxy[0]);
DbSourceProxy src = otherdb.get(0);
+ DbSourceProxy[] dassource = new DbSourceProxy[] { src };
fetchr = new JMenuItem(src.getDbSource());
fetchr.addActionListener(new ActionListener()
{
@Override
protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
{
- AlignmentI al = viewport.getAlignment();
- al.justify(false);
- viewport.firePropertyChange("alignment", null, al);
+ viewport.getAlignment().justify(false);
+ viewport.notifyAlignment();
}
/**
@Override
protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
{
- AlignmentI al = viewport.getAlignment();
- al.justify(true);
- viewport.firePropertyChange("alignment", null, al);
+ viewport.getAlignment().justify(true);
+ viewport.notifyAlignment();
}
@Override
} catch (Exception ex)
{
System.err.println((ex.toString()));
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
MessageManager.getString("label.couldnt_run_groovy_script"),
MessageManager.getString("label.groovy_support_failed"),
JvOptionPane.ERROR_MESSAGE);
}
}
+ /**
+ * Sets the status of the HMMER menu
+ */
+ public void updateHMMERStatus()
+ {
+ hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
+ }
@Override
protected void loadVcf_actionPerformed()
{
}
private Rectangle lastFeatureSettingsBounds = null;
+
@Override
public void setFeatureSettingsGeometry(Rectangle bounds)
{
{
return lastFeatureSettingsBounds;
}
-}
-class PrintThread extends Thread
-{
- AlignmentPanel ap;
+ public void scrollTo(int row, int column)
+ {
+ alignPanel.getSeqPanel().scrollTo(row, column);
+ }
- public PrintThread(AlignmentPanel ap)
+ public void scrollToRow(int row)
{
- this.ap = ap;
+ alignPanel.getSeqPanel().scrollToRow(row);
}
- static PageFormat pf;
+ public void scrollToColumn(int column)
+ {
+ alignPanel.getSeqPanel().scrollToColumn(column);
+ }
- @Override
- public void run()
+ /**
+ * BH 2019 from JalviewLite
+ *
+ * get sequence feature groups that are hidden or shown
+ *
+ * @param visible
+ * true is visible
+ * @return list
+ */
+
+ public String[] getFeatureGroupsOfState(boolean visible)
{
- PrinterJob printJob = PrinterJob.getPrinterJob();
+ jalview.api.FeatureRenderer fr = null;
+ if (alignPanel != null
+ && (fr = alignPanel.getFeatureRenderer()) != null)
+ {
+ List<String> gps = fr.getGroups(visible);
+ String[] _gps = gps.toArray(new String[gps.size()]);
+ return _gps;
+ }
+ return null;
+ }
+
+ /**
+ *
+ * @return list of feature groups on the view
+ */
- if (pf != null)
+ public String[] getFeatureGroups()
+ {
+ jalview.api.FeatureRenderer fr = null;
+ if (alignPanel != null
+ && (fr = alignPanel.getFeatureRenderer()) != null)
{
- printJob.setPrintable(ap, pf);
+ List<String> gps = fr.getFeatureGroups();
+ String[] _gps = gps.toArray(new String[gps.size()]);
+ return _gps;
}
- else
+ return null;
+ }
+
+ public void select(SequenceGroup sel, ColumnSelection csel,
+ HiddenColumns hidden)
+ {
+ alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
+ }
+
+ public int getID()
+ {
+ return id;
+ }
+
+ static class PrintThread extends Thread
+ {
+ AlignmentPanel ap;
+
+ public PrintThread(AlignmentPanel ap)
{
- printJob.setPrintable(ap);
+ this.ap = ap;
}
- if (printJob.printDialog())
+ static PageFormat pf;
+
+ @Override
+ public void run()
{
- try
+ PrinterJob printJob = PrinterJob.getPrinterJob();
+
+ if (pf != null)
+ {
+ printJob.setPrintable(ap, pf);
+ }
+ else
{
- printJob.print();
- } catch (Exception PrintException)
+ printJob.setPrintable(ap);
+ }
+
+ if (printJob.printDialog())
{
- PrintException.printStackTrace();
+ try
+ {
+ printJob.print();
+ } catch (Exception PrintException)
+ {
+ PrintException.printStackTrace();
+ }
}
}
}
import jalview.api.FeaturesDisplayedI;
import jalview.api.ViewStyleI;
import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.commands.CommandI;
import jalview.datamodel.AlignedCodonFrame;
import jalview.datamodel.Alignment;
import jalview.datamodel.SearchResultsI;
import jalview.datamodel.SequenceGroup;
import jalview.datamodel.SequenceI;
+import jalview.datamodel.features.FeatureMatcherSetI;
import jalview.renderer.ResidueShader;
import jalview.schemes.ColourSchemeI;
import jalview.schemes.ColourSchemeProperty;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Hashtable;
+import java.util.Iterator;
import java.util.List;
import javax.swing.JInternalFrame;
public class AlignViewport extends AlignmentViewport
implements SelectionSource
{
+ public final static int NO_SPLIT = 0;
+
+ public final static int SPLIT_FRAME = 1;
+
+ public final static int NEW_WINDOW = 2;
Font font;
boolean cursorMode = false;
sequenceSetID = seqsetid;
viewId = viewid;
// TODO remove these once 2.4.VAMSAS release finished
- if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
+ if (seqsetid != null)
{
- Cache.log.debug(
+ Console.debug(
"Setting viewport's sequence set id : " + sequenceSetID);
}
- if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
+ if (viewId != null)
{
- Cache.log.debug("Setting viewport's view id : " + viewId);
+ Console.debug("Setting viewport's view id : " + viewId);
}
init();
sequenceSetID = seqsetid;
viewId = viewid;
// TODO remove these once 2.4.VAMSAS release finished
- if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
+ if (seqsetid != null)
{
- Cache.log.debug(
+ Console.debug(
"Setting viewport's sequence set id : " + sequenceSetID);
}
- if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
+ if (viewId != null)
{
- Cache.log.debug("Setting viewport's view id : " + viewId);
+ Console.debug("Setting viewport's view id : " + viewId);
}
if (hiddenColumns != null)
setRightAlignIds(Cache.getDefault("RIGHT_ALIGN_IDS", false));
setCentreColumnLabels(Cache.getDefault("CENTRE_COLUMN_LABELS", false));
- autoCalculateConsensus = Cache.getDefault("AUTO_CALC_CONSENSUS", true);
+ autoCalculateConsensusAndConservation = Cache.getDefault("AUTO_CALC_CONSENSUS", true);
setPadGaps(Cache.getDefault("PAD_GAPS", true));
setShowNPFeats(Cache.getDefault("SHOW_NPFEATS_TOOLTIP", true));
setFont(new Font(fontName, style, Integer.parseInt(fontSize)), true);
- alignment
- .setGapCharacter(Cache.getDefault("GAP_SYMBOL", "-").charAt(0));
+ alignment.setGapCharacter(Cache.getDefault("GAP_SYMBOL", "-").charAt(0));
// We must set conservation and consensus before setting colour,
// as Blosum and Clustal require this to be done
- if (hconsensus == null && !isDataset)
+ if (hconsensus == null && !isDataset)
{
- if (!alignment.isNucleotide())
+ if (!alignment.isNucleotide())
{
showConservation = Cache.getDefault("SHOW_CONSERVATION", true);
showQuality = Cache.getDefault("SHOW_QUALITY", true);
showSequenceLogo = Cache.getDefault("SHOW_CONSENSUS_LOGO", false);
normaliseSequenceLogo = Cache.getDefault("NORMALISE_CONSENSUS_LOGO",
false);
+ // for now, use consensus options for Information till it gets its own
+ setShowHMMSequenceLogo(showSequenceLogo);
+ setNormaliseHMMSequenceLogo(normaliseSequenceLogo);
+ setShowInformationHistogram(showConsensusHistogram);
showGroupConsensus = Cache.getDefault("SHOW_GROUP_CONSENSUS", false);
showConsensus = Cache.getDefault("SHOW_IDENTITY", true);
showOccupancy = Cache.getDefault(Preferences.SHOW_OCCUPANCY, true);
}
initAutoAnnotation();
- String colourProperty = alignment.isNucleotide()
+ // initInformation();
+
+ String colourProperty = alignment.isNucleotide()
? Preferences.DEFAULT_COLOUR_NUC
: Preferences.DEFAULT_COLOUR_PROT;
String schemeName = Cache.getProperty(colourProperty);
schemeName = Cache.getDefault(Preferences.DEFAULT_COLOUR,
ResidueColourScheme.NONE);
}
- ColourSchemeI colourScheme = ColourSchemeProperty
- .getColourScheme(this, alignment, schemeName);
+ ColourSchemeI colourScheme = ColourSchemeProperty.getColourScheme(this,
+ alignment, schemeName);
residueShading = new ResidueShader(colourScheme);
if (colourScheme instanceof UserColourScheme)
if (residueShading != null)
{
- residueShading.setConsensus(hconsensus);
+ residueShading.setConsensus(hconsensus);
}
setColourAppliesToAllGroups(true);
}
+
boolean validCharWidth;
/**
if (align != null)
{
StructureSelectionManager ssm = StructureSelectionManager
- .getStructureSelectionManager(Desktop.instance);
+ .getStructureSelectionManager(Desktop.getInstance());
ssm.registerMappings(align.getCodonFrames());
}
/*
* replace mappings on our alignment
*/
- if (alignment != null && align != null)
+ if (alignment != null && align != null)
{
alignment.setCodonFrames(align.getCodonFrames());
}
if (mappings != null)
{
StructureSelectionManager ssm = StructureSelectionManager
- .getStructureSelectionManager(Desktop.instance);
+ .getStructureSelectionManager(Desktop.getInstance());
for (AlignedCodonFrame acf : mappings)
{
if (noReferencesTo(acf))
public void sendSelection()
{
jalview.structure.StructureSelectionManager
- .getStructureSelectionManager(Desktop.instance)
+ .getStructureSelectionManager(Desktop.getInstance())
.sendSelection(new SequenceGroup(getSelectionGroup()),
new ColumnSelection(getColumnSelection()),
new HiddenColumns(getAlignment().getHiddenColumns()),
public StructureSelectionManager getStructureSelectionManager()
{
return StructureSelectionManager
- .getStructureSelectionManager(Desktop.instance);
+ .getStructureSelectionManager(Desktop.getInstance());
}
+
@Override
public boolean isNormaliseSequenceLogo()
{
return normaliseSequenceLogo;
}
- public void setNormaliseSequenceLogo(boolean state)
+ @Override
+public void setNormaliseSequenceLogo(boolean state)
{
normaliseSequenceLogo = state;
}
{
return validCharWidth;
}
+
+
private Hashtable<String, AutoCalcSetting> calcIdParams = new Hashtable<>();
public AutoCalcSetting getCalcIdSettingsFor(String calcId)
// calculator.getRegisteredWorkersOfClass(settings.getWorkerClass())
if (needsUpdate)
{
- Cache.log.debug("trigger update for " + calcId);
+ Console.debug("trigger update for " + calcId);
}
}
}
ranges.setEndSeq(getAlignment().getHeight() - 1); // BH 2019.04.18
- firePropertyChange("alignment", null, getAlignment().getSequences());
+ notifyAlignment();
}
/**
final String question = JvSwingUtils.wrapTooltip(true,
MessageManager.getString("label.open_split_window?"));
final AlignViewport us = this;
-
+
/*
* options No, Split Window, New Window correspond to
* dialog responses 0, 1, 2 (even though JOptionPane shows them
* in reverse order)
*/
- JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop)
- .setResponseHandler(0, new Runnable()
+ JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.getDesktopPane())
+ .setResponseHandler(NO_SPLIT, new Runnable()
{
@Override
public void run()
{
- addDataToAlignment(al);
+ addDataToAlignment(al);
}
- }).setResponseHandler(1, new Runnable()
+ }).setResponseHandler(SPLIT_FRAME, new Runnable()
{
@Override
public void run()
{
- us.openLinkedAlignmentAs(al, title, true);
+ // Make a copy of this one to open it in a splitframe
+ openLinkedAlignmentAs(getAlignPanel().alignFrame,
+ new Alignment(getAlignment()), al, title,
+ SPLIT_FRAME);
}
- }).setResponseHandler(2, new Runnable()
+ }).setResponseHandler(NEW_WINDOW, new Runnable()
{
@Override
public void run()
{
- us.openLinkedAlignmentAs(al, title, false);
+ openLinkedAlignmentAs(null, getAlignment(), al, title,
+ NEW_WINDOW);
}
});
- dialog.showDialog(question,
+ dialog.showDialog(question,
MessageManager.getString("label.open_split_window"),
JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
}
- protected void openLinkedAlignmentAs(AlignmentI al, String title,
- boolean newWindowOrSplitPane)
+ /**
+ * Open a split frame or a new window
+ *
+ * @param al
+ * @param title
+ * @param mode
+ * SPLIT_FRAME or NEW_WINDOW
+ */
+ public static void openLinkedAlignmentAs(AlignFrame thisFrame,
+ AlignmentI thisAlignment, AlignmentI al, String title, int mode)
{
/*
- * Identify protein and dna alignments. Make a copy of this one if opening
- * in a new split pane.
+ * Identify protein and dna alignments.
*/
- AlignmentI thisAlignment = newWindowOrSplitPane
- ? new Alignment(getAlignment())
- : getAlignment();
AlignmentI protein = al.isNucleotide() ? thisAlignment : al;
- final AlignmentI cdna = al.isNucleotide() ? al : thisAlignment;
+ AlignmentI cdna = al.isNucleotide() ? al : thisAlignment;
/*
* Map sequences. At least one should get mapped as we have already passed
// alignFrame.setFileName(file, format);
// }
- if (!newWindowOrSplitPane)
+ if (mode == NEW_WINDOW)
{
Desktop.addInternalFrame(newAlignFrame, title,
AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
try
{
- newAlignFrame.setMaximum(
- jalview.bin.Cache.getDefault("SHOW_FULLSCREEN", false));
+ newAlignFrame.setMaximum(Cache.getDefault("SHOW_FULLSCREEN", false));
} catch (java.beans.PropertyVetoException ex)
{
}
- if (newWindowOrSplitPane)
+ if (mode == SPLIT_FRAME)
{
al.alignAs(thisAlignment);
- protein = openSplitFrame(newAlignFrame, thisAlignment);
+ openSplitFrame(thisFrame, newAlignFrame, thisAlignment);
}
}
* cdna/protein complement alignment to show in the other split half
* @return the protein alignment in the split frame
*/
- protected AlignmentI openSplitFrame(AlignFrame newAlignFrame,
- AlignmentI complement)
+ static protected AlignmentI openSplitFrame(AlignFrame thisFrame,
+ AlignFrame newAlignFrame, AlignmentI complement)
{
/*
* Make a new frame with a copy of the alignment we are adding to. If this
*/
AlignFrame copyMe = new AlignFrame(complement, AlignFrame.DEFAULT_WIDTH,
AlignFrame.DEFAULT_HEIGHT);
- copyMe.setTitle(getAlignPanel().alignFrame.getTitle());
+ copyMe.setTitle(thisFrame.getTitle());
AlignmentI al = newAlignFrame.viewport.getAlignment();
final AlignFrame proteinFrame = al.isNucleotide() ? copyMe
}
/**
- * Applies the supplied feature settings descriptor to currently known features.
- * This supports an 'initial configuration' of feature colouring based on a
- * preset or user favourite. This may then be modified in the usual way using
- * the Feature Settings dialogue.
+ * Applies the supplied feature settings descriptor to currently known
+ * features. This supports an 'initial configuration' of feature colouring
+ * based on a preset or user favourite. This may then be modified in the usual
+ * way using the Feature Settings dialogue.
*
* @param featureSettings
*/
/**
* when mergeOnly is set, then group and feature visibility or feature colours
* are not modified for features and groups already known to the feature
- * renderer. Feature ordering is always adjusted, and transparency is always set
- * regardless.
+ * renderer. Feature ordering is always adjusted, and transparency is always
+ * set regardless.
*
* @param featureSettings
* @param mergeOnly
{
return;
}
-
-
FeatureRenderer fr = getAlignPanel().getSeqPanel().seqCanvas
.getFeatureRenderer();
- List<String> origRenderOrder = new ArrayList<>();
- List<String> origGroups = new ArrayList<>();
+ List<String> origRenderOrder = new ArrayList(),
+ origGroups = new ArrayList();
- // preserve original render order - allows differentiation between user configured colours and autogenerated ones
+ // preserve original render order - allows differentiation between user
+ // configured colours and autogenerated ones
origRenderOrder.addAll(fr.getRenderOrder());
origGroups.addAll(fr.getFeatureGroups());
if (!mergeOnly)
{
// only clear displayed features if we are mergeing
- // displayed.clear();
+ displayed.clear();
}
// TODO this clears displayed.featuresRegistered - do we care?
//
{
FeatureColourI preferredColour = featureSettings
.getFeatureColour(type);
+ FeatureMatcherSetI preferredFilters = featureSettings
+ .getFeatureFilters(type);
FeatureColourI origColour = fr.getFeatureStyle(type);
if (!mergeOnly || (!origRenderOrder.contains(type)
|| origColour == null
&& origColour.getColour().equals(
ColorUtils.createColourFromName(type)))))
{
- // if we are merging, only update if there wasn't already a colour defined for
+ // if we are merging, only update if there wasn't already a colour
+ // defined for
// this type
if (preferredColour != null)
{
fr.setColour(type, preferredColour);
}
+ if (preferredFilters != null
+ && (!mergeOnly || fr.getFeatureFilter(type) != null))
+ {
+ fr.setFeatureFilter(type, preferredFilters);
+ }
if (featureSettings.isFeatureDisplayed(type))
{
displayed.setVisible(type);
{
if (!mergeOnly || !origGroups.contains(group))
{
- // when merging, display groups only if the aren't already marked as not visible
+ // when merging, display groups only if the aren't already marked as not
+ // visible
fr.setGroupVisibility(group,
featureSettings.isGroupDisplayed(group));
}
fr.orderFeatures(featureSettings);
}
fr.setTransparency(featureSettings.getTransparency());
+
fr.notifyFeaturesChanged();
}
*/
package jalview.gui;
- import java.awt.BorderLayout;
- import java.awt.Color;
- import java.awt.Container;
- import java.awt.Dimension;
- import java.awt.Font;
- import java.awt.FontMetrics;
- import java.awt.Graphics;
- import java.awt.Graphics2D;
- import java.awt.event.AdjustmentEvent;
- import java.awt.event.AdjustmentListener;
- import java.awt.event.ComponentAdapter;
- import java.awt.event.ComponentEvent;
- import java.awt.print.PageFormat;
- import java.awt.print.Printable;
- import java.awt.print.PrinterException;
- import java.beans.PropertyChangeEvent;
- import java.beans.PropertyChangeListener;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.PrintWriter;
- import java.util.List;
-
- import javax.swing.SwingUtilities;
-
import jalview.analysis.AnnotationSorter;
import jalview.api.AlignViewportI;
import jalview.api.AlignmentViewPanel;
import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.bin.Jalview;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.HiddenColumns;
import jalview.util.Comparison;
import jalview.util.ImageMaker;
import jalview.util.MessageManager;
+import jalview.viewmodel.AlignmentViewport;
import jalview.viewmodel.ViewportListenerI;
import jalview.viewmodel.ViewportRanges;
+ import java.awt.BorderLayout;
+ import java.awt.Color;
+ import java.awt.Container;
+ import java.awt.Dimension;
+ import java.awt.Font;
+ import java.awt.FontMetrics;
+ import java.awt.Graphics;
+ import java.awt.Graphics2D;
+ import java.awt.event.AdjustmentEvent;
+ import java.awt.event.AdjustmentListener;
+ import java.awt.event.ComponentAdapter;
+ import java.awt.event.ComponentEvent;
+ import java.awt.print.PageFormat;
+ import java.awt.print.Printable;
+ import java.awt.print.PrinterException;
+ import java.beans.PropertyChangeEvent;
+ import java.beans.PropertyChangeListener;
+ import java.io.File;
+ import java.io.FileWriter;
+ import java.io.PrintWriter;
+ import java.util.List;
+
+ import javax.swing.SwingUtilities;
+
/**
* DOCUMENT ME!
*
*/
public AlignmentPanel(AlignFrame af, final AlignViewport av)
{
+ setName("AligmentPanel");
// setBackground(Color.white); // BH 2019
alignFrame = af;
this.av = av;
ranges.setViewportWidth(widthInRes);
ranges.setViewportHeight(heightInSeq);
}
+ repaint();
}
});
@Override
public void propertyChange(PropertyChangeEvent evt)
{
- if (evt.getPropertyName().equals("alignment"))
- {
+ switch (evt.getPropertyName()) {
+ case AlignmentViewport.PROPERTY_SEQUENCE:
+ updateScrollBarsFromRanges();
+ if (annotationPanel != null)
+ annotationPanel.paintImmediately(0, 0, getWidth(), getHeight());
+ break;
+ case AlignmentViewport.PROPERTY_ALIGNMENT:
+ updateScrollBarsFromRanges();
PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
alignmentChanged();
+ break;
}
}
};
int oldWidth = av.getIdWidth();
// calculate sensible default width when no preference is available
- Dimension r = null;
+ Dimension d = null;
if (av.getIdWidth() < 0)
{
- int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
- int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
- int maxwidth = Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
- r = calculateIdWidth(maxwidth);
- av.setIdWidth(r.width);
+ int maxWidth = getMaxWidth();
+ d = calculateIdWidth(maxWidth);
+ av.setIdWidth(d.width);
}
else
{
- r = new Dimension();
- r.width = av.getIdWidth();
- r.height = 0;
+ d = new Dimension();
+ d.width = av.getIdWidth();
+ d.height = 0;
}
/*
* fudge: if desired width has changed, update layout
* (see also paintComponent - updates layout on a repaint)
*/
- if (r.width != oldWidth)
+ if (d.width != oldWidth)
{
- idPanelHolder.setPreferredSize(r);
+ idPanelHolder.setPreferredSize(d);
validate();
}
- return r;
+ return d;
+ }
+
+ public int getMaxWidth()
+ {
+ int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
+ int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
+ return Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
}
/**
* @return Dimension giving the maximum width of the alignment label panel
* that should be used.
*/
- protected Dimension calculateIdWidth(int maxwidth)
+ public Dimension calculateIdWidth(int maxwidth)
{
- Container c = new Container();
+ Container c = this;// new Container();
+
FontMetrics fm = c.getFontMetrics(
new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
int i = 0;
int idWidth = 0;
+ boolean withSuffix = av.getShowJVSuffix();
while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
{
SequenceI s = al.getSequenceAt(i);
- String id = s.getDisplayId(av.getShowJVSuffix());
+ String id = s.getDisplayId(withSuffix);
int stringWidth = fm.stringWidth(id);
idWidth = Math.max(idWidth, stringWidth);
i++;
{
// BH 2018.04.18 comment: addNotify() is not appropriate here. We
// are not changing ancestors, and keyboard action listeners do
- // not need to be reset. addNotify() is a very expensive operation,
+ // not need to be reset, and most importantly, we can't be sure we are actually
+ // connected to resources.
+
+ // addNotify() is a very expensive operation,
// requiring a full re-layout of all parents and children.
+
// Note in JComponent:
+
// This method is called by the toolkit internally and should
// not be called directly by programs.
+
// I note that addNotify() is called in several areas of Jalview.
int annotationHeight = getAnnotationPanel().adjustPanelHeight();
annotationHeight = getAnnotationPanel()
.adjustForAlignFrame(adjustPanelHeight, annotationHeight);
+ // BH no!!
hscroll.addNotify();
annotationScroller.setPreferredSize(
new Dimension(annotationScroller.getWidth(), annotationHeight));
Dimension e = idPanel.getSize();
alabels.setSize(new Dimension(e.width, annotationHeight));
++
annotationSpaceFillerHolder.setPreferredSize(new Dimension(
annotationSpaceFillerHolder.getWidth(), annotationHeight));
annotationScroller.validate();
/**
* update alignment layout for viewport settings
*/
public void updateLayout()
{
+ ViewportRanges ranges = av.getRanges();
fontChanged();
setAnnotationVisible(av.isShowAnnotation());
boolean wrap = av.getWrapAlignment();
- ViewportRanges ranges = av.getRanges();
ranges.setStartSeq(0);
scalePanelHolder.setVisible(!wrap);
hscroll.setVisible(!wrap);
{
annotationScroller.setVisible(true);
annotationSpaceFillerHolder.setVisible(true);
+ }
+
+ idSpaceFillerPanel1.setVisible(!wrap);
+
+ /*
+ * defer dimension calculations if panel not yet added to a Window
+ * BH 2020.06.09
+ */
+ if (getTopLevelAncestor() == null)
+ {
+ repaint();
+ return;
+ }
+
+ if (!wrap && av.isShowAnnotation())
+ {
validateAnnotationDimensions(false);
}
+
int canvasWidth = getSeqPanel().seqCanvas.getWidth();
if (canvasWidth > 0)
{ // may not yet be laid out
}
}
- idSpaceFillerPanel1.setVisible(!wrap);
+ // System.out.println("ap dim = " + getSize());
+ // these values will go negative if getSize() returns (0,0):
+ // System.out.println("seqpan dim = " + getSeqPanel().getSize());
+ // System.out.println("seqcan dim = " + getSeqPanel().seqCanvas.getSize());
repaint();
}
* visible row to scroll to
*
*/
- public void setScrollValues(int xpos, int ypos)
+ public void setScrollValues(int x, int y)
{
- int x = xpos;
- int y = ypos;
if (av == null || av.getAlignment() == null)
{
{
int width = av.getAlignment().getVisibleWidth();
int height = av.getAlignment().getHeight();
+
- hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
- vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
-
- if (hextent > width)
- {
- hextent = width;
- }
-
- if (vextent > height)
- {
- vextent = height;
- }
-
- if ((hextent + x) > width)
- {
- x = width - hextent;
- }
-
- if ((vextent + y) > height)
- {
- y = height - vextent;
- }
-
- if (y < 0)
- {
- y = 0;
- }
-
- if (x < 0)
- {
- x = 0;
- }
-
- // update the scroll values
- hscroll.setValues(x, hextent, 0, width);
- vscroll.setValues(y, vextent, 0, height);
+
+ hextent = Math.min(getSeqPanel().seqCanvas.getWidth() / av.getCharWidth(), width);
+ vextent = Math.min(getSeqPanel().seqCanvas.getHeight() / av.getCharHeight(), height);
+
+ x = Math.max(0, Math.min(x, width - hextent));
+ y = Math.max(0, Math.min(y, height - vextent));
+
+ updateRanges(x, y);
+ updateScrollBars(x, y, width, height);
}
}
+ private void updateScrollBars(int x, int y, int width, int height)
+ {
+ hscroll.setValues(x, hextent, 0, width);
+ vscroll.setValues(y, vextent, 0, height);
+ }
-
/**
* Respond to adjustment event when horizontal or vertical scrollbar is
* changed
return;
}
- ViewportRanges ranges = av.getRanges();
+
if (evt.getSource() == hscroll)
{
+ if (!updateRanges(hscroll.getValue(), Integer.MIN_VALUE))
+ return;
+ }
+ else if (evt.getSource() == vscroll)
+ {
+ if (!updateRanges(Integer.MIN_VALUE, vscroll.getValue()))
+ return;
+ }
+ repaint();
+ }
+
+ private boolean updateRanges(int x, int y)
+ {
+ ViewportRanges ranges = av.getRanges();
+ boolean isChanged = false;
+ if (x != Integer.MIN_VALUE)
+ {
int oldX = ranges.getStartRes();
int oldwidth = ranges.getViewportWidth();
- int x = hscroll.getValue();
int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
// if we're scrolling to the position we're already at, stop
// this prevents infinite recursion of events when the scroll/viewport
// ranges values are the same
- if ((x == oldX) && (width == oldwidth))
+ if (width > 0 && (x != oldX || width != oldwidth))
{
- return;
+ ranges.setViewportStartAndWidth(x, width);
+ isChanged = true;
}
- ranges.setViewportStartAndWidth(x, width);
}
- else if (evt.getSource() == vscroll)
+ if (y != Integer.MIN_VALUE)
{
int oldY = ranges.getStartSeq();
int oldheight = ranges.getViewportHeight();
- int y = vscroll.getValue();
int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
// if we're scrolling to the position we're already at, stop
// this prevents infinite recursion of events when the scroll/viewport
// ranges values are the same
- if ((y == oldY) && (height == oldheight))
+ if (height > 0 && (y != oldY || height != oldheight))
{
- return;
+ ranges.setViewportStartAndHeight(y, height);
+ isChanged = true;
}
- ranges.setViewportStartAndHeight(y, height);
}
- repaint();
+ return isChanged;
}
/**
// could not be validated and it is not clear if it is now being
// called. Log warning here in case it is called and unforeseen
// problems occur
- Cache.log.warn(
+ Console.warn(
"Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
// scroll to start of panel
av.isShowAutocalculatedAbove());
sorter.sort(getAlignment().getAlignmentAnnotation(),
av.getSortAnnotationsBy());
- repaint();
if (updateStructures)
{
}
if (updateOverview)
{
+
+ alignFrame.repaint();
if (overviewPanel != null)
{
overviewPanel.updateOverviewImage();
}
+ } else {
+ invalidate(); // needed so that the id width adjuster works correctly
+ repaint();
}
}
@Override
public void paintComponent(Graphics g)
{
+ // BH OUCH!
invalidate(); // needed so that the id width adjuster works correctly
Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
* though I still think this call should be elsewhere.
*/
ViewportRanges ranges = av.getRanges();
- setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
+ // setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
super.paintComponent(g);
}
public int printWrappedAlignment(int pageWidth, int pageHeight,
int pageNumber, Graphics g) throws PrinterException
{
- getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
- getHeight());
+ getSeqPanel().seqCanvas.calculateWrappedGeometry();
int annotationHeight = 0;
if (av.isShowAnnotation())
{
}
else
{
- if (Cache.log.isDebugEnabled())
+ if (Console.isDebugEnabled())
{
- Cache.log.warn("Closing alignment panel which is already closed.");
+ Console.warn("Closing alignment panel which is already closed.");
}
}
}
} catch (Exception ex)
{
}
+
if (b)
{
- alignFrame.setDisplayedView(this);
+ setAlignFrameView();
}
}
+ public void setAlignFrameView()
+ {
+ alignFrame.setDisplayedView(this);
+ }
+
@Override
public StructureSelectionManager getStructureSelectionManager()
{
public void propertyChange(PropertyChangeEvent evt)
{
// update this panel's scroll values based on the new viewport ranges values
- ViewportRanges ranges = av.getRanges();
- int x = ranges.getStartRes();
- int y = ranges.getStartSeq();
- setScrollValues(x, y);
+ updateScrollBarsFromRanges();
// now update any complementary alignment (its viewport ranges object
// is different so does not get automatically updated)
}
}
+ void updateScrollBarsFromRanges()
+ {
+ ViewportRanges ranges = av.getRanges();
+ setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
+ }
-
/**
* Set the reference to the PCA/Tree chooser dialog for this panel. This
* reference should be nulled when the dialog is closed.
return calculationDialog;
}
+ /**
+ * From appletgui, for JalviewJS JavaScript interface
+ *
+ * preliminary - untested
+ *
+ * @param ostart
+ * @param end
+ * @param seqIndex
+ * @param scrollToNearest
+ * @param redrawOverview
+ * @return
+ */
+ public boolean scrollTo(int ostart, int end, int seqIndex,
+ boolean scrollToNearest, boolean redrawOverview)
+ {
+ int startv, endv, starts, ends;// , width;
+
+ int start = -1;
+ if (av.hasHiddenColumns())
+ {
+ AlignmentI al = av.getAlignment();
+ start = al.getHiddenColumns().absoluteToVisibleColumn(ostart);
+ end = al.getHiddenColumns().absoluteToVisibleColumn(end);
+ if (start == end)
+ {
+ if (!scrollToNearest && !al.getHiddenColumns().isVisible(ostart))
+ {
+ // don't scroll - position isn't visible
+ return false;
+ }
+ }
+ }
+ else
+ {
+ start = ostart;
+ }
+
+ ViewportRanges ranges = av.getRanges();
+ if (!av.getWrapAlignment())
+ {
+ /*
+ * int spos=av.getStartRes(),sqpos=av.getStartSeq(); if ((startv =
+ * av.getStartRes()) >= start) { spos=start-1; // seqIn //
+ * setScrollValues(start - 1, seqIndex); } else if ((endv =
+ * av.getEndRes()) <= end) { // setScrollValues(spos=startv + 1 + end -
+ * endv, seqIndex); spos=startv + 1 + end - endv; } else if ((starts =
+ * av.getStartSeq()) > seqIndex) { setScrollValues(av.getStartRes(),
+ * seqIndex); } else if ((ends = av.getEndSeq()) <= seqIndex) {
+ * setScrollValues(av.getStartRes(), starts + seqIndex - ends + 1); }
+ */
+
+ // below is scrolling logic up to Jalview 2.8.2
+ // if ((av.getStartRes() > end)
+ // || (av.getEndRes() < start)
+ // || ((av.getStartSeq() > seqIndex) || (av.getEndSeq() < seqIndex)))
+ // {
+ // if (start > av.getAlignment().getWidth() - hextent)
+ // {
+ // start = av.getAlignment().getWidth() - hextent;
+ // if (start < 0)
+ // {
+ // start = 0;
+ // }
+ //
+ // }
+ // if (seqIndex > av.getAlignment().getHeight() - vextent)
+ // {
+ // seqIndex = av.getAlignment().getHeight() - vextent;
+ // if (seqIndex < 0)
+ // {
+ // seqIndex = 0;
+ // }
+ // }
+ // setScrollValues(start, seqIndex);
+ // }
+ // logic copied from jalview.gui.AlignmentPanel:
+ if ((startv = ranges.getStartRes()) >= start)
+ {
+ /*
+ * Scroll left to make start of search results visible
+ */
+ setScrollValues(start - 1, seqIndex);
+ }
+ else if ((endv = ranges.getEndRes()) <= end)
+ {
+ /*
+ * Scroll right to make end of search results visible
+ */
+ setScrollValues(startv + 1 + end - endv, seqIndex);
+ }
+ else if ((starts = ranges.getStartSeq()) > seqIndex)
+ {
+ /*
+ * Scroll up to make start of search results visible
+ */
+ setScrollValues(ranges.getStartRes(), seqIndex);
+ }
+ else if ((ends = ranges.getEndSeq()) <= seqIndex)
+ {
+ /*
+ * Scroll down to make end of search results visible
+ */
+ setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
+ }
+ /*
+ * Else results are already visible - no need to scroll
+ */
+ }
+ else
+ {
+ ranges.scrollToWrappedVisible(start);
+ }
+
+ paintAlignment(redrawOverview, false);
+ return true;
+ }
+
+ private boolean holdRepaint = false;
+
+ /**
+ * Called by IdCanvas and SeqPanel to defer painting until after JVP loading.
+ *
+ * @return true if holding
+ */
+ public boolean getHoldRepaint()
+ {
+ return holdRepaint;
+ }
+
+ /**
+ * Called by Jalview2xml while loading
+ *
+ * @param tf
+ */
+ public void setHoldRepaint(boolean tf)
+ {
+ if (holdRepaint == tf)
+ {
+ return;
+ }
+ holdRepaint = tf;
+ if (!tf)
+ {
+ repaint();
+ }
+ }
+
+ @Override
+ public void repaint()
+ {
+ if (holdRepaint)
+ {
+ // System.out.println("AP repaint holding");
+ // Platform.stackTrace();
+ return;
+ }
+ super.repaint();
+ }
+
+ public void selectAllSequences()
+ {
+ selectSequences(av.getAlignment().getSequences());
+ }
+
+ public void deselectAllSequences()
+ {
+ if (av.cursorMode)
+ {
+ getSeqPanel().keyboardNo1 = null;
+ getSeqPanel().keyboardNo2 = null;
+ }
+ av.setSelectionGroup(null);
+ av.getColumnSelection().clear();
+ av.setSearchResults(null);
+ getIdPanel().getIdCanvas().searchResults = null;
+ av.sendSelection();
+ // JAL-2034 - should delegate to
+ // alignPanel to decide if overview needs
+ // updating.
+ paintAlignment(false, false);
+ PaintRefresher.Refresh(this, av.getSequenceSetId());
+ }
+
+ public void selectSequences(List<SequenceI> seqs)
+ {
+ SequenceGroup sg = new SequenceGroup(seqs);
+ sg.setEndRes(av.getAlignment().getWidth() - 1);
+ av.setSelectionGroup(sg);
+ av.isSelectionGroupChanged(true);
+ av.sendSelection();
+ // JAL-2034 - should delegate to
+ // alignPanel to decide if overview needs
+ // updating.
+ paintAlignment(false, false);
+ PaintRefresher.Refresh(this, av.getSequenceSetId());
+ }
+
}
JPanel maxColour = new JPanel();
private JCheckBox thresholdIsMin = new JCheckBox();
+ private JCheckBox transparency = new JCheckBox();
protected static final int MIN_WIDTH = 500;
"error.implementation_error_dont_know_about_threshold_setting"));
}
thresholdIsMin.setSelected(acg.isThresholdIsMinMax());
- thresholdValue
- .setText(String.valueOf(acg.getAnnotationThreshold()));
+ thresholdValue.setText(String.valueOf(acg.getAnnotationThreshold()));
}
jbInit();
}
});
+ transparency.setBackground(Color.white);
+ transparency.setFont(JvSwingUtils.getLabelFont());
+ transparency
+ .setText(MessageManager.getString("Use Transparency"));
+ transparency.addActionListener(new ActionListener()
+ {
+
+ @Override
+ public void actionPerformed(ActionEvent arg0)
+ {
+ transparency_actionPerformed();
+ }
+ });
this.setLayout(new BorderLayout());
JPanel jPanel1 = new JPanel();
JPanel jPanel2 = new JPanel();
jPanel2.add(annotations, "grow, wrap");
jPanel2.add(seqAssociated);
jPanel2.add(useOriginalColours);
+ jPanel2.add(transparency);
JPanel colpanel = new JPanel(new FlowLayout());
colpanel.setBackground(Color.white);
colpanel.add(minColour);
this.validate();
}
+ protected void transparency_actionPerformed()
+ {
+ updateView();
+ }
protected void resetColours_actionPerformed()
{
setDefaultMinMax();
updateView();
}
};
- JalviewColourChooser.showColourChooser(Desktop.getDesktop(), ttl,
+ JalviewColourChooser.showColourChooser(Desktop.getDesktopPane(), ttl,
colourPanel.getBackground(), listener);
}
acg.setThresholdIsMinMax(thresholdIsMin.isSelected());
+ acg.setPositionToTransparency(transparency.isSelected());
+
this.ap.alignFrame.changeColour(acg);
if (av.getAlignment().getGroups() != null)
{
continue;
}
- sg.setColourScheme(
- acg.getInstance(av, sg));
+ sg.setColourScheme(acg.getInstance(av, sg));
}
}
}
frame.setContentPane(this);
frame.setLayer(JLayeredPane.PALETTE_LAYER);
Dimension preferredSize = frame.getPreferredSize();
- Desktop.addInternalFrame(frame, "", true, preferredSize.width,
- preferredSize.height, true, true);
+ Desktop.addInternalFrame(frame, "", Desktop.FRAME_MAKE_VISIBLE, preferredSize.width,
+ preferredSize.height, Desktop.FRAME_ALLOW_RESIZE, Desktop.FRAME_ALLOW_ANY_SIZE);
}
/**
- * Configures the dialog for options to export visible features. If from a split
- * frame panel showing linked features, make the option to include these in the
- * export visible.
+ * Configures the dialog for options to export visible features. If from a
+ * split frame panel showing linked features, make the option to include these
+ * in the export visible.
*/
public void exportFeatures()
{
}
/**
- * Answers the text to output for either Features (in GFF or Jalview format) or
- * Annotations (in CSV or Jalview format)
+ * Answers the text to output for either Features (in GFF or Jalview format)
+ * or Annotations (in CSV or Jalview format)
*
* @return
*/
}
/**
- * Returns the text contents for output of annotations in either CSV or Jalview
- * format
+ * Returns the text contents for output of annotations in either CSV or
+ * Jalview format
*
* @return
*/
}
/**
- * Builds a panel with a checkbox for the option to export linked (CDS/peptide)
- * features. This is hidden by default, and only made visible if exporting
- * features from a split frame panel which is configured to show linked
- * features.
+ * Builds a panel with a checkbox for the option to export linked
+ * (CDS/peptide) features. This is hidden by default, and only made visible if
+ * exporting features from a split frame panel which is configured to show
+ * linked features.
*
* @return
*/
linkedFeaturesPanel.setOpaque(false);
boolean nucleotide = ap.av.isNucleotide();
- String complement = nucleotide
- ? MessageManager.getString("label.protein").toLowerCase(Locale.ROOT)
- : "CDS";
- JLabel label = new JLabel(
- MessageManager.formatMessage("label.include_linked_features",
- complement));
+ String complement = nucleotide ? MessageManager
+ .getString("label.protein").toLowerCase(Locale.ROOT) : "CDS";
+ JLabel label = new JLabel(MessageManager
+ .formatMessage("label.include_linked_features", complement));
label.setHorizontalAlignment(SwingConstants.TRAILING);
String tooltip = MessageManager
.formatMessage("label.include_linked_tooltip", complement);
- label.setToolTipText(
- JvSwingUtils.wrapTooltip(true, tooltip));
+ label.setToolTipText(JvSwingUtils.wrapTooltip(true, tooltip));
includeLinkedFeatures = new JCheckBox();
linkedFeaturesPanel.add(label);
}
/**
- * Builds the panel with options to output in Jalview, GFF or CSV format. GFF is
- * only made visible when exporting features, CSV only when exporting
+ * Builds the panel with options to output in Jalview, GFF or CSV format. GFF
+ * is only made visible when exporting features, CSV only when exporting
* annotation.
*
* @return
import jalview.util.Comparison;
import jalview.util.MessageManager;
import jalview.util.Platform;
+import jalview.workers.InformationThread;
import java.awt.Color;
import java.awt.Cursor;
*/
public AnnotationLabels(AlignmentPanel ap)
{
-
+
this.ap = ap;
av = ap.av;
ToolTipManager.sharedInstance().registerComponent(this);
EditNameDialog dialog = new EditNameDialog(annotation.label,
annotation.description, name, description);
- dialog.showDialog(ap.alignFrame, title,
- new Runnable()
- {
- @Override
- public void run()
- {
- annotation.label = dialog.getName();
- String text = dialog.getDescription();
- if (text != null && text.length() == 0)
- {
- text = null;
- }
- annotation.description = text;
- if (addNew)
- {
- ap.av.getAlignment().addAnnotation(annotation);
- ap.av.getAlignment().setAnnotationIndex(annotation, 0);
- }
- ap.refresh(true);
- }
- });
+ dialog.showDialog(ap.alignFrame, title, new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ annotation.label = dialog.getName();
+ String text = dialog.getDescription();
+ if (text != null && text.length() == 0)
+ {
+ text = null;
+ }
+ annotation.description = text;
+ if (addNew)
+ {
+ ap.av.getAlignment().addAnnotation(annotation);
+ ap.av.getAlignment().setAnnotationIndex(annotation, 0);
+ }
+ ap.refresh(true);
+ }
+ });
}
@Override
pop.show(this, evt.getX(), evt.getY());
return;
}
+ final AlignmentAnnotation ann = aa[selectedRow];
+ final boolean isSequenceAnnotation = ann.sequenceRef != null;
item = new JMenuItem(EDITNAME);
item.addActionListener(this);
pop.add(item);
if (selectedRow < aa.length)
{
final String label = aa[selectedRow].label;
- if (!aa[selectedRow].autoCalculated)
+ if (!(aa[selectedRow].autoCalculated)
+ && !(InformationThread.HMM_CALC_ID.equals(ann.getCalcId())))
{
if (aa[selectedRow].graph == AlignmentAnnotation.NO_GRAPH)
{
pop.addSeparator();
// av and sequencegroup need to implement same interface for
item = new JCheckBoxMenuItem(TOGGLE_LABELSCALE,
- aa[selectedRow].scaleColLabel);
+ aa[selectedRow].scaleColLabel);
item.addActionListener(this);
pop.add(item);
}
consclipbrd.addActionListener(this);
pop.add(consclipbrd);
}
+ else if (InformationThread.HMM_CALC_ID.equals(ann.getCalcId()))
+ {
+ addHmmerMenu(pop, ann);
+ }
}
pop.show(this, evt.getX(), evt.getY());
}
/**
+ * Adds context menu options for (alignment or group) Hmmer annotation
+ *
+ * @param pop
+ * @param ann
+ */
+ protected void addHmmerMenu(JPopupMenu pop, final AlignmentAnnotation ann)
+ {
+ final boolean isGroupAnnotation = ann.groupRef != null;
+ pop.addSeparator();
+ final JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(
+ MessageManager.getString(
+ "label.ignore_below_background_frequency"),
+ isGroupAnnotation
+ ? ann.groupRef
+ .isIgnoreBelowBackground()
+ : ap.av.isIgnoreBelowBackground());
+ cbmi.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ if (isGroupAnnotation)
+ {
+ if (!ann.groupRef.isUseInfoLetterHeight())
+ {
+ ann.groupRef.setIgnoreBelowBackground(cbmi.getState());
+ // todo and recompute group annotation
+ }
+ }
+ else if (!ap.av.isInfoLetterHeight())
+ {
+ ap.av.setIgnoreBelowBackground(cbmi.getState(), ap);
+ // todo and recompute annotation
+ }
+ ap.alignmentChanged(); // todo not like this
+ }
+ });
+ pop.add(cbmi);
+ final JCheckBoxMenuItem letterHeight = new JCheckBoxMenuItem(
+ MessageManager.getString("label.use_info_for_height"),
+ isGroupAnnotation ? ann.groupRef.isUseInfoLetterHeight()
+ : ap.av.isInfoLetterHeight());
+ letterHeight.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ if (isGroupAnnotation)
+ {
+ ann.groupRef.setInfoLetterHeight((letterHeight.getState()));
+ ann.groupRef.setIgnoreBelowBackground(true);
+ // todo and recompute group annotation
+ }
+ else
+ {
+ ap.av.setInfoLetterHeight(letterHeight.getState(), ap);
+ ap.av.setIgnoreBelowBackground(true, ap);
+ // todo and recompute annotation
+ }
+ ap.alignmentChanged();
+ }
+ });
+ pop.add(letterHeight);
+ if (isGroupAnnotation)
+ {
+ final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
+ MessageManager.getString("label.show_group_histogram"),
+ ann.groupRef.isShowInformationHistogram());
+ chist.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ ann.groupRef.setShowInformationHistogram(chist.getState());
+ ap.repaint();
+ }
+ });
+ pop.add(chist);
+ final JCheckBoxMenuItem cprofl = new JCheckBoxMenuItem(
+ MessageManager.getString("label.show_group_logo"),
+ ann.groupRef.isShowHMMSequenceLogo());
+ cprofl.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ ann.groupRef.setShowHMMSequenceLogo(cprofl.getState());
+ ap.repaint();
+ }
+ });
+ pop.add(cprofl);
+ final JCheckBoxMenuItem cproflnorm = new JCheckBoxMenuItem(
+ MessageManager.getString("label.normalise_group_logo"),
+ ann.groupRef.isNormaliseHMMSequenceLogo());
+ cproflnorm.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ ann.groupRef
+ .setNormaliseHMMSequenceLogo(cproflnorm.getState());
+ // automatically enable logo display if we're clicked
+ ann.groupRef.setShowHMMSequenceLogo(true);
+ ap.repaint();
+ }
+ });
+ pop.add(cproflnorm);
+ }
+ else
+ {
+ final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
+ MessageManager.getString("label.show_histogram"),
+ av.isShowInformationHistogram());
+ chist.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ av.setShowInformationHistogram(chist.getState());
+ ap.repaint();
+ }
+ });
+ pop.add(chist);
+ final JCheckBoxMenuItem cprof = new JCheckBoxMenuItem(
+ MessageManager.getString("label.show_logo"),
+ av.isShowHMMSequenceLogo());
+ cprof.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ av.setShowHMMSequenceLogo(cprof.getState());
+ ap.repaint();
+ }
+ });
+ pop.add(cprof);
+ final JCheckBoxMenuItem cprofnorm = new JCheckBoxMenuItem(
+ MessageManager.getString("label.normalise_logo"),
+ av.isNormaliseHMMSequenceLogo());
+ cprofnorm.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ av.setShowHMMSequenceLogo(true);
+ av.setNormaliseHMMSequenceLogo(cprofnorm.getState());
+ ap.repaint();
+ }
+ });
+ pop.add(cprofnorm);
+ }
+ }
+
+ /**
* A helper method that adds menu options for calculation and visualisation of
* group and/or alignment consensus annotation to a popup menu. This is
* designed to be reusable for either unwrapped mode (popup menu is shown on
* @param pop
*/
static void addConsensusMenuOptions(AlignmentPanel ap,
- AlignmentAnnotation ann,
- JPopupMenu pop)
+ AlignmentAnnotation ann, JPopupMenu pop)
{
pop.addSeparator();
seqs, omitHidden, alignmentStartEnd);
Toolkit.getDefaultToolkit().getSystemClipboard()
- .setContents(new StringSelection(output), Desktop.instance);
+ .setContents(new StringSelection(output), Desktop.getInstance());
HiddenColumns hiddenColumns = null;
av.getAlignment().getHiddenColumns());
}
- Desktop.jalviewClipboard = new Object[] { seqs, ds, // what is the dataset
- // of a consensus
- // sequence ? need to
- // flag
- // sequence as special.
+ // what is the dataset of a consensus sequence?
+ // need to flag sequence as special.
+ Desktop.getInstance().jalviewClipboard = new Object[] { seqs, ds,
hiddenColumns };
}
- /**
- * DOCUMENT ME!
- *
- * @param g1
- * DOCUMENT ME!
- */
@Override
public void paintComponent(Graphics g)
{
*/
public AnnotationPanel(AlignmentPanel ap)
{
+ setName("AnnotationPanel");
ToolTipManager.sharedInstance().registerComponent(this);
ToolTipManager.sharedInstance().setInitialDelay(0);
ToolTipManager.sharedInstance().setDismissDelay(10000);
}
if (dragMode == DragMode.Undefined)
- {
+ {
/*
* drag is diagonal - defer deciding whether to
* treat as up/down or left/right
*/
- return;
- }
+ return;
+ }
+
try
{
if (dragMode == DragMode.Resize)
int newHeight = Math.max(0, graphAnnotation.graphHeight + deltaY);
graphAnnotation.graphHeight = newHeight;
adjustPanelHeight();
+ setNoFastPaint();
ap.paintAlignment(false, false);
}
}
&& ann.annotations[column] != null)
{
tooltip = ann.annotations[column].description;
+ if ("".equals(tooltip))
+ {
+ tooltip = null;
+ }
}
return tooltip;
}
private volatile boolean imageFresh = false;
--
private Rectangle visibleRect = new Rectangle(),
clipBounds = new Rectangle();
@Override
public void paintComponent(Graphics g)
{
--
// BH: note that this method is generally recommended to
// call super.paintComponent(g). Otherwise, the children of this
// component will not be rendered. That is not needed here
// just a JPanel contained in a JViewPort.
computeVisibleRect(visibleRect);
g.setColor(Color.white);
g.fillRect(0, 0, visibleRect.width, visibleRect.height);
- if (image != null)
+ ViewportRanges ranges = av.getRanges();
+
+ if (allowFastPaint && image != null)
{
// BH 2018 optimizing generation of new Rectangle().
if (fastPaint
.getClipBounds(clipBounds)).width)
|| (visibleRect.height != clipBounds.height))
{
- g.drawImage(image, 0, 0, this);
+
- g.drawImage(image, 0, 0, this);
++
++ g.drawImage(image, 0, 0, this);
fastPaint = false;
return;
}
}
-
- imgWidth = (av.getRanges().getEndRes() - av.getRanges().getStartRes()
- + 1) * av.getCharWidth();
+ imgWidth = (ranges.getEndRes() - ranges.getStartRes() + 1)
+ * av.getCharWidth();
-
if (imgWidth < 1)
{
+ fastPaint = false;
return;
}
Graphics2D gg;
gg = (Graphics2D) image.getGraphics();
}
--
- drawComponent(gg, ranges.getStartRes(), av.getRanges().getEndRes() + 1);
++
+ drawComponent(gg, av.getRanges().getStartRes(),
+ av.getRanges().getEndRes() + 1);
gg.dispose();
imageFresh = false;
g.drawImage(image, 0, 0, this);
}
/**
- * set true to enable redraw timing debug output on stderr
- */
- private final boolean debugRedraw = false;
-
- /**
* non-Thread safe repaint
*
* @param horizontal
int er = av.getRanges().getEndRes() + 1;
int transX = 0;
+ if (er == sr + 1)
+ {
+ fastPaint = false;
+ return;
+ }
-
Graphics2D gg = (Graphics2D) image.getGraphics();
- gg.copyArea(0, 0, imgWidth, getHeight(),
- -horizontal * av.getCharWidth(), 0);
-
- if (horizontal > 0) // scrollbar pulled right, image to the left
- {
- transX = (er - sr - horizontal) * av.getCharWidth();
- sr = er - horizontal;
- }
- else if (horizontal < 0)
- {
- er = sr - horizontal;
+ if (imgWidth>Math.abs(horizontal*av.getCharWidth())) {
+ //scroll is less than imgWidth away so can re-use buffered graphics
+ gg.copyArea(0, 0, imgWidth, getHeight(),
+ -horizontal * av.getCharWidth(), 0);
+
+ if (horizontal > 0) // scrollbar pulled right, image to the left
+ {
+ transX = (er - sr - horizontal) * av.getCharWidth();
+ sr = er - horizontal;
+ }
+ else if (horizontal < 0)
+ {
+ er = sr - horizontal;
+ }
}
+
gg.translate(transX, 0);
drawComponent(gg, sr, er);
gg.translate(-transX, 0);
gg.dispose();
--
fastPaint = true;
// Call repaint on alignment panel so that repaints from other alignment
private int[] bounds = new int[2];
+ private boolean allowFastPaint;
-
@Override
public int[] getVisibleVRange()
{
}
return annotationHeight;
}
+
+ /**
+ * Clears the flag that allows a 'fast paint' on the next repaint, so
+ * requiring a full repaint
+ */
+ public void setNoFastPaint()
+ {
+ allowFastPaint = false;
+ }
-
}
{
slider.setSliderValue(value);
}
+
/**
- * Answers the value of the slider position as a percentage between minimum and
- * maximum of its range
+ * Answers the value of the slider position as a percentage between minimum
+ * and maximum of its range
*
* @return
*/
updateView();
}
+
protected void propagateSeqAssociatedThreshold(boolean allAnnotation,
AlignmentAnnotation annotation)
import javax.swing.event.InternalFrameEvent;
import jalview.api.AlignmentViewPanel;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.PDBEntry;
import jalview.datamodel.SequenceI;
import jalview.datamodel.StructureViewerModel;
import jalview.util.ImageMaker;
import jalview.util.MessageManager;
import jalview.util.Platform;
-
public class AppJmol extends StructureViewerBase
{
// ms to wait for Jmol to load files
.toArray(new SequenceI[sequencesForPdb.size()]);
i++;
}
-
// TODO: check if protocol is needed to be set, and if chains are
// autodiscovered.
jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
seqColour.setSelected(true);
viewerColour.setSelected(false);
}
-
this.setBounds(viewerModel.getX(), viewerModel.getY(),
viewerModel.getWidth(), viewerModel.getHeight());
setViewId(viewid);
{
super.initMenus();
+
viewerColour
.setText(MessageManager.getString("label.colour_with_jmol"));
viewerColour.setToolTipText(MessageManager
}
private void openNewJmol(AlignmentPanel ap, boolean alignAdded,
- PDBEntry[] pdbentrys,
- SequenceI[][] seqs)
+ PDBEntry[] pdbentrys, SequenceI[][] seqs)
{
setProgressIndicator(ap.alignFrame);
jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
openNewJmol(ap, alignAdded, pe, seqs);
}
-
void initJmol(String command)
{
jmb.setFinishedInit(false);
} catch (OutOfMemoryError oomerror)
{
new OOMWarning("When trying to open the Jmol viewer!", oomerror);
- Cache.log.debug("File locations are " + filesString);
+ Console.debug("File locations are " + filesString);
} catch (Exception ex)
{
- Cache.log.error("Couldn't open Jmol viewer!", ex);
+ Console.error("Couldn't open Jmol viewer!", ex);
ex.printStackTrace();
return;
}
{
new OOMWarning("When trying to add structures to the Jmol viewer!",
oomerror);
- Cache.log.debug("File locations are " + filesString);
+ Console.debug("File locations are " + filesString);
return;
} catch (Exception ex)
{
- Cache.log.error("Couldn't add files to Jmol viewer!", ex);
+ Console.error("Couldn't add files to Jmol viewer!", ex);
ex.printStackTrace();
return;
}
{
try
{
- Cache.log.debug("Waiting around for jmb notify.");
+ Console.debug("Waiting around for jmb notify.");
waitTotal += waitFor;
// Thread.sleep() throws an exception in JS
jmb.jmolViewer.renderScreenImage(g, width, height);
}
};
- String view = MessageManager.getString("action.view").toLowerCase(Locale.ROOT);
+ String view = MessageManager.getString("action.view")
+ .toLowerCase(Locale.ROOT);
ImageExporter exporter = new ImageExporter(writer,
getProgressIndicator(), type, getTitle());
exporter.doExport(null, this, width, height, view);
try
{
BrowserLauncher // BH 2018
- .openURL("http://wiki.jmol.org");//http://jmol.sourceforge.net/docs/JmolUserGuide/");
+ .openURL("http://wiki.jmol.org");// http://jmol.sourceforge.net/docs/JmolUserGuide/");
} catch (Exception ex)
{
System.err.println("Show Jmol help failed with: " + ex.getMessage());
@Override
public void showConsole(boolean showConsole)
{
+
if (showConsole)
{
if (splitPane == null)
}
}
}
- else if (jmb == null || jmb.jmolViewer == null || !jmb.isFinishedInit())
+ else if (jmb == null || jmb.jmolViewer == null
+ || !jmb.isFinishedInit())
{
g.setColor(Color.black);
g.fillRect(0, 0, currentSize.width, currentSize.height);
import jalview.api.AlignmentViewPanel;
import jalview.api.structures.JalviewStructureDisplayI;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.PDBEntry;
import jalview.datamodel.SequenceI;
jalview.util.BrowserLauncher.openURL(url);
} catch (Exception e)
{
- Cache.log.error("Failed to launch Jmol-associated url " + url, e);
+ Console.error("Failed to launch Jmol-associated url " + url, e);
// TODO: 2.6 : warn user if browser was not configured.
}
}
{
// todo - record which pdbids were successfully imported.
StringBuilder errormsgs = new StringBuilder();
-
+
List<String> files = new ArrayList<>();
String pdbid = "";
try
String[] filesInViewer = getStructureFiles();
// TODO: replace with reference fetching/transfer code (validate PDBentry
// as a DBRef?)
-
+
for (int pi = 0; pi < getPdbCount(); pi++)
{
PDBEntry strucEntry = getPdbEntry(pi);
if (file == null)
{
pdbid = strucEntry.getId();
- try{
+ try
+ {
file = structureViewer.fetchPdbFile(strucEntry);
} catch (OutOfMemoryError oomerror)
{
ex.printStackTrace();
errormsgs.append("'").append(pdbid).append("'");
}
- if (file!=null)
+ if (file != null)
{
// success
files.add(file);
}
if (errormsgs.length() > 0)
{
-- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
++ JvOptionPane.showInternalMessageDialog(Desktop.getInstance(),
MessageManager.formatMessage(
"label.pdb_entries_couldnt_be_retrieved", new String[]
{ errormsgs.toString() }),
import jalview.analysis.TreeBuilder;
import jalview.analysis.scoremodels.ScoreModels;
import jalview.analysis.scoremodels.SimilarityParams;
+import jalview.api.AlignViewportI;
import jalview.api.analysis.ScoreModelI;
import jalview.api.analysis.SimilarityParamsI;
import jalview.bin.Cache;
import jalview.datamodel.SequenceGroup;
import jalview.util.MessageManager;
-
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import javax.swing.event.InternalFrameEvent;
/**
- * A dialog where a user can choose and action Tree or PCA calculation options
+ * A dialog where a user can choose and action Tree or PCA calculation options.
+ *
+ * Allows also for dialog-free static methods openPCAPanel(...) and
+ * openTreePanel(...) for scripted use.
+ *
*/
+@SuppressWarnings("serial")
public class CalculationChooser extends JPanel
{
/*
*/
private static boolean treeMatchGaps = true;
- private static final Font VERDANA_11PT = new Font("Verdana", 0, 11);
+ private static Font VERDANA_11PT;
private static final int MIN_TREE_SELECTION = 3;
private JCheckBox shorterSequence;
- final ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
+ private static ComboBoxTooltipRenderer renderer; // BH was not static
List<String> tips = new ArrayList<>();
private PCAPanel pcaPanel;
/**
+ * Open a new Tree panel on the desktop statically. Params are standard (not
+ * set by Groovy). No dialog is opened.
+ *
+ * @param af
+ * @param treeType
+ * @param modelName
+ * @return null if successful; the string
+ * "label.you_need_at_least_n_sequences" if number of sequences
+ * selected is inappropriate
+ */
+ public static Object openTreePanel(AlignFrame af, String treeType,
+ String modelName)
+ {
+ return openTreePanel(af, treeType, modelName, null);
+ }
+
+ /**
+ * public static method for JalviewJS API to open a PCAPanel without
+ * necessarily using a dialog.
+ *
+ * @param af
+ * @param modelName
+ * @return the PCAPanel, or the string "label.you_need_at_least_n_sequences"
+ * if number of sequences selected is inappropriate
+ */
+ public static Object openPcaPanel(AlignFrame af, String modelName)
+ {
+ return openPcaPanel(af, modelName, null);
+ }
+
+ /**
* Constructor
*
* @param af
pca = new JRadioButton(
MessageManager.getString("label.principal_component_analysis"));
pca.setOpaque(false);
-
+
neighbourJoining = new JRadioButton(
MessageManager.getString("label.tree_calc_nj"));
neighbourJoining.setSelected(true);
paramsPanel.add(includeGappedColumns);
paramsPanel.add(shorterSequence);
+ if (VERDANA_11PT == null)
+ {
+ VERDANA_11PT = new Font("Verdana", 0, 11);
+ }
/*
* OK / Cancel buttons
*/
title = title + " (" + af.getViewport().getViewName() + ")";
}
- Desktop.addInternalFrame(frame, title, width, height, false);
+ Desktop.addInternalFrame(frame, title, Desktop.FRAME_MAKE_VISIBLE, width, height, Desktop.FRAME_NOT_RESIZABLE, Desktop.FRAME_SET_MIN_SIZE_300);
calcChoicePanel.doLayout();
revalidate();
/*
*/
protected JComboBox<String> buildModelOptionsList()
{
- final JComboBox<String> scoreModelsCombo = new JComboBox<>();
+ JComboBox<String> scoreModelsCombo = new JComboBox<>();
+ if (renderer == null)
+ {
+ renderer = new ComboBoxTooltipRenderer();
+ }
scoreModelsCombo.setRenderer(renderer);
/*
* for backwards compatibility with Jalview < 2.8 (JAL-2962)
*/
if (nucleotide && forPca
- && Cache.getDefault("BLOSUM62_PCA_FOR_NUCLEOTIDE", false))
+ && Cache.getDefault(Preferences.BLOSUM62_PCA_FOR_NUCLEOTIDE,
+ false))
{
filtered.add(scoreModels.getBlosum62());
}
*/
protected void openTreePanel(String modelName, SimilarityParamsI params)
{
+ Object ret = openTreePanel(af,
+ neighbourJoining.isSelected() ? TreeBuilder.NEIGHBOUR_JOINING
+ : TreeBuilder.AVERAGE_DISTANCE,
+ modelName, params);
+ if (ret instanceof String)
+ {
+ JvOptionPane.showMessageDialog(this, // was opening on Desktop?
+ MessageManager.formatMessage(
+ (String) ret,
+ MIN_TREE_SELECTION),
+ MessageManager.getString("label.not_enough_sequences"),
+ JvOptionPane.WARNING_MESSAGE);
+
+ }
+ }
+
+ /**
+ * Open a new PCA panel on the desktop
+ *
+ * @param modelName
+ * @param params
+ */
+ protected void openPcaPanel(String modelName, SimilarityParamsI params)
+ {
+ Object ret = openPcaPanel(af, modelName, params);
+ if (ret instanceof String)
+ {
+ JvOptionPane.showInternalMessageDialog(this,
+ MessageManager.formatMessage(
+ (String) ret,
+ MIN_PCA_SELECTION),
+ MessageManager
+ .getString("label.sequence_selection_insufficient"),
+ JvOptionPane.WARNING_MESSAGE);
+ }
+ else
+ {
+ // only used for test suite
+ pcaPanel = (PCAPanel) ret;
+ }
+
+ }
+
+ /**
+ * Open a new Tree panel on the desktop statically
+ *
+ * @param af
+ * @param treeType
+ * @param modelName
+ * @param params
+ * @return null, or the string "label.you_need_at_least_n_sequences" if number
+ * of sequences selected is inappropriate
+ */
+ public static Object openTreePanel(AlignFrame af, String treeType,
+ String modelName, SimilarityParamsI params)
+ {
+
/*
* gui validation shouldn't allow insufficient sequences here, but leave
* this check in in case this method gets exposed programmatically in future
*/
- AlignViewport viewport = af.getViewport();
+ AlignViewportI viewport = af.getViewport();
SequenceGroup sg = viewport.getSelectionGroup();
if (sg != null && sg.getSize() < MIN_TREE_SELECTION)
{
- JvOptionPane.showMessageDialog(Desktop.desktop,
- MessageManager.formatMessage(
- "label.you_need_at_least_n_sequences",
- MIN_TREE_SELECTION),
- MessageManager.getString("label.not_enough_sequences"),
- JvOptionPane.WARNING_MESSAGE);
- return;
+ return "label.you_need_at_least_n_sequences";
+ }
+
+ if (params == null)
+ {
+ params = getSimilarityParameters(false);
}
- String treeType = neighbourJoining.isSelected()
- ? TreeBuilder.NEIGHBOUR_JOINING
- : TreeBuilder.AVERAGE_DISTANCE;
af.newTreePanel(treeType, modelName, params);
+ return null;
}
/**
- * Open a new PCA panel on the desktop
+ * public static method for JalviewJS API
*
+ * @param af
* @param modelName
* @param params
+ * @return the PCAPanel, or null if number of sequences selected is
+ * inappropriate
*/
- protected void openPcaPanel(String modelName, SimilarityParamsI params)
+ public static Object openPcaPanel(AlignFrame af, String modelName,
+ SimilarityParamsI params)
{
- AlignViewport viewport = af.getViewport();
+ AlignViewportI viewport = af.getViewport();
/*
* gui validation shouldn't allow insufficient sequences here, but leave
* this check in in case this method gets exposed programmatically in future
+ *
+ *
*/
if (((viewport.getSelectionGroup() != null)
&& (viewport.getSelectionGroup().getSize() < MIN_PCA_SELECTION)
&& (viewport.getSelectionGroup().getSize() > 0))
|| (viewport.getAlignment().getHeight() < MIN_PCA_SELECTION))
{
- JvOptionPane.showInternalMessageDialog(this,
- MessageManager.formatMessage(
- "label.you_need_at_least_n_sequences",
- MIN_PCA_SELECTION),
- MessageManager
- .getString("label.sequence_selection_insufficient"),
- JvOptionPane.WARNING_MESSAGE);
- return;
+ return "label.you_need_at_least_n_sequences";
+ }
+
+ if (params == null)
+ {
+ params = getSimilarityParameters(true);
}
/*
* construct the panel and kick off its calculation thread
*/
- pcaPanel = new PCAPanel(af.alignPanel, modelName, params);
- new Thread(pcaPanel).start();
-
+ PCAPanel pcap = new PCAPanel(af.alignPanel, modelName, params);
+ new Thread(pcap).start();
+ return pcap;
}
/**
}
}
+
/**
* Returns a data bean holding parameters for similarity (or distance) model
* calculation
* @param doPCA
* @return
*/
- protected SimilarityParamsI getSimilarityParameters(boolean doPCA)
+ public static SimilarityParamsI getSimilarityParameters(
+ boolean doPCA)
{
// commented out: parameter choices read from gui widgets
// SimilarityParamsI params = new SimilarityParams(
return new SimilarityParams(includeGapGap, matchGap, includeGapResidue,
matchOnShortestLength);
+
}
/**
*/
package jalview.gui;
+
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import jalview.api.AlignmentViewPanel;
import jalview.api.FeatureRenderer;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.PDBEntry;
import jalview.datamodel.SequenceI;
import jalview.datamodel.StructureViewerModel;
import jalview.util.ImageMaker.TYPE;
import jalview.util.MessageManager;
import jalview.util.Platform;
-
/**
* GUI elements for handling an external chimera display
*
{
private JalviewChimeraBinding jmb;
+
/*
* Path to Chimera session file. This is set when an open Jalview/Chimera
* session is saved, or on restore from a Jalview project (if it holds the
*/
private String chimeraSessionFile = null;
+
private int myWidth = 500;
private int myHeight = 150;
- private JMenuItem writeFeatures=null;
+ private JMenuItem writeFeatures = null;
- private JMenu fetchAttributes=null;
- /**
+ private JMenu fetchAttributes = null;
+
+ /**
* Initialise menu options.
*/
@Override
writeFeatures = new JMenuItem(
MessageManager.getString("label.create_viewer_attributes"));
- writeFeatures.setToolTipText(MessageManager
- .getString("label.create_viewer_attributes_tip"));
+ writeFeatures.setToolTipText(
+ MessageManager.getString("label.create_viewer_attributes_tip"));
writeFeatures.addActionListener(new ActionListener()
{
@Override
});
viewerActionMenu.add(writeFeatures);
- fetchAttributes = new JMenu(
- MessageManager.getString("label.fetch_chimera_attributes"));
- fetchAttributes.setToolTipText(
- MessageManager.getString("label.fetch_chimera_attributes_tip"));
+ fetchAttributes = new JMenu(MessageManager.formatMessage(
+ "label.fetch_viewer_attributes", getViewerName()));
+ fetchAttributes.setToolTipText(MessageManager.formatMessage(
+ "label.fetch_viewer_attributes_tip", getViewerName()));
fetchAttributes.addMouseListener(new MouseAdapter()
{
// add these back in after menu is refreshed
viewerActionMenu.add(writeFeatures);
viewerActionMenu.add(fetchAttributes);
-
+
};
+
/**
* Query the structure viewer for its residue attribute names and add them as
* items off the attributes menu
{
// todo pull up?
int count = jmb.sendFeaturesToViewer(getAlignmentPanel());
- statusBar.setText(
- MessageManager.formatMessage("label.attributes_set", count));
+ statusBar.setText(MessageManager.formatMessage("label.attributes_set",
+ count, getViewerName()));
}
/**
return new JalviewChimeraBindingModel(this,
ap.getStructureSelectionManager(), pdbentrys, seqs, null);
}
-
/**
* Create a new viewer from saved session state data including Chimera session
* file
* @param ap
*/
public ChimeraViewFrame(PDBEntry[] pe, boolean alignAdded,
- SequenceI[][] seqs,
- AlignmentPanel ap)
+ SequenceI[][] seqs, AlignmentPanel ap)
{
this();
setAlignAddedStructures(alignAdded);
if (!jmb.launchChimera())
{
- JvOptionPane.showMessageDialog(Desktop.desktop,
+ JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
MessageManager.formatMessage("label.open_viewer_failed",
getViewerName()),
MessageManager.getString("label.error_loading_file"),
JvOptionPane.ERROR_MESSAGE);
+ jmb.closeViewer(true);
this.dispose();
return;
}
if (errormsgs.length() > 0)
{
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
MessageManager.formatMessage(
"label.pdb_entries_couldnt_be_retrieved", new Object[]
{ errormsgs.toString() }),
initChimera();
} catch (Exception ex)
{
- Cache.log.error("Couldn't open Chimera viewer!", ex);
+ Console.error("Couldn't open Chimera viewer!", ex);
}
}
+ if (!jmb.isViewerRunning())
+ {
+ // nothing to do
+ // TODO: ensure we tidy up JAL-3619
+ return;
+ }
int num = -1;
for (PDBEntry pe : filePDB)
{
oomerror);
} catch (Exception ex)
{
- Cache.log.error(
+ Console.error(
"Couldn't open " + pe.getFile() + " in Chimera viewer!",
ex);
} finally
{
- Cache.log.debug("File locations are " + files);
+ Console.debug("File locations are " + files);
}
}
}
worker = null;
}
+
@Override
public void makePDBImage(TYPE imageType)
{
return jmb;
}
+
@Override
public ViewerType getViewerType()
{
* the colour scheme (inspected in setColourSelected())
*/
final String name = scheme.getSchemeName();
- String label = MessageManager.getStringOrReturn(
- "label.colourScheme_", name);
+ String label = MessageManager.getStringOrReturn("label.colourScheme_",
+ name);
final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
label);
radioItem.setName(name);
ActionListener al = radioItem.getActionListeners()[0];
radioItem.removeActionListener(al);
int option = JvOptionPane.showInternalConfirmDialog(
- Desktop.desktop,
+ Desktop.getDesktopPane(),
MessageManager
.getString("label.remove_from_default_list"),
MessageManager
}
else
{
- Cache.applicationProperties.remove("USER_DEFINED_COLOURS");
+ Cache.removePropertyNoSave("USER_DEFINED_COLOURS");
}
}
}
import jalview.api.AlignmentViewPanel;
import jalview.api.FeatureSettingsModelI;
import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.DBRefEntry;
if (dna && AlignmentUtils.looksLikeEnsembl(alignment))
{
- // override default featureColourScheme so products have Ensembl variant colours
+ // override default featureColourScheme so products have Ensembl variant
+ // colours
featureColourScheme = new SequenceFetcher()
.getFeatureColourScheme(DBRefSource.ENSEMBL);
}
* and for JAL-3330 also to original alignFrame view(s)
* this currently trashes any original settings.
*/
- for (AlignmentViewPanel origpanel: alignFrame.getAlignPanels()) {
+ for (AlignmentViewPanel origpanel : alignFrame.getAlignPanels())
+ {
origpanel.getAlignViewport()
.mergeFeaturesStyle(featureColourScheme);
}
new OOMWarning("whilst fetching crossreferences", e);
} catch (Throwable e)
{
- Cache.log.error("Error when finding crossreferences", e);
+ Console.error("Error when finding crossreferences", e);
} finally
{
alignFrame.setProgressBar(MessageManager.formatMessage(
{
return;
}
-
+
Set<String> ensemblDivisions = new EnsemblInfo().getDivisions();
-
+
/*
* first look for direct dbrefs from sequence to Ensembl
*/
copyAlignment = AlignmentUtils.makeCopyAlignment(sel,
xrefs.getSequencesArray(), dataset);
}
- copyAlignment
- .setGapCharacter(alignFrame.viewport.getGapCharacter());
+ copyAlignment.setGapCharacter(alignFrame.viewport.getGapCharacter());
StructureSelectionManager ssm = StructureSelectionManager
- .getStructureSelectionManager(Desktop.instance);
+ .getStructureSelectionManager(Desktop.getInstance());
/*
* register any new mappings for sequence mouseover etc
if (copyAlignment.getHeight() <= 0)
{
- System.err.println(
- "No Sequences generated for xRef type " + source);
+ System.err.println("No Sequences generated for xRef type " + source);
return null;
}
*/
package jalview.gui;
+ import jalview.bin.Cache;
import jalview.api.AlignViewportI;
import jalview.api.AlignmentViewPanel;
import jalview.api.ComplexAlignFile;
// TODO: JAL-3048 JalviewFileChooser - Save option
JalviewFileChooser chooser = new JalviewFileChooser(
- jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
+ Cache.getProperty("LAST_DIRECTORY"));
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileView(new JalviewFileView());
.println(MessageManager.getString("label.couldnt_read_data"));
if (!Jalview.isHeadlessMode())
{
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
AppletFormatAdapter.getSupportedFormats(),
MessageManager.getString("label.couldnt_read_data"),
JvOptionPane.WARNING_MESSAGE);
} catch (IOException ex)
{
- JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
+ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(), MessageManager
.formatMessage("label.couldnt_read_pasted_text", new String[]
{ ex.toString() }),
MessageManager.getString("label.error_parsing_text"),
af.getViewport().setShowSequenceFeatures(showSeqFeatures);
af.getViewport().setFeaturesDisplayed(fd);
af.setMenusForViewport();
- ColourSchemeI cs = ColourSchemeMapper.getJalviewColourScheme(
- colourSchemeName, al);
+ ColourSchemeI cs = ColourSchemeMapper
+ .getJalviewColourScheme(colourSchemeName, al);
if (cs != null)
{
af.changeColour(cs);
try
{
- af.setMaximum(
- jalview.bin.Cache.getDefault("SHOW_FULLSCREEN", false));
+ af.setMaximum(Cache.getDefault("SHOW_FULLSCREEN", false));
} catch (Exception ex)
{
}
.println(MessageManager.getString("label.couldnt_read_data"));
if (!Jalview.isHeadlessMode())
{
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
AppletFormatAdapter.getSupportedFormats(),
MessageManager.getString("label.couldnt_read_data"),
JvOptionPane.WARNING_MESSAGE);
*/
package jalview.gui;
+import java.util.Locale;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.Hashtable;
import java.util.List;
import java.util.ListIterator;
-import java.util.Locale;
import java.util.Vector;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.FutureTask;
import java.util.concurrent.Semaphore;
import javax.swing.AbstractAction;
import jalview.api.AlignViewportI;
import jalview.api.AlignmentViewPanel;
+import jalview.api.StructureSelectionManagerProvider;
+import jalview.bin.ApplicationSingletonProvider;
+import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
import jalview.bin.Cache;
import jalview.bin.Jalview;
import jalview.gui.ImageExporter.ImageWriterI;
import jalview.io.IdentifyFile;
import jalview.io.JalviewFileChooser;
import jalview.io.JalviewFileView;
++import jalview.jbgui.APQHandlers;
+import jalview.jbgui.GDesktop;
import jalview.jbgui.GSplitFrame;
import jalview.jbgui.GStructureViewer;
import jalview.project.Jalview2XML;
import jalview.util.BrowserLauncher;
import jalview.util.ChannelProperties;
import jalview.util.ImageMaker.TYPE;
+ import jalview.util.LaunchUtils;
import jalview.util.MessageManager;
import jalview.util.Platform;
--import jalview.util.ShortcutKeyMaskExWrapper;
import jalview.util.UrlConstants;
import jalview.viewmodel.AlignmentViewport;
+import jalview.ws.WSDiscovererI;
import jalview.ws.params.ParamManager;
import jalview.ws.utils.UrlDownloadClient;
* @author $author$
* @version $Revision: 1.155 $
*/
-public class Desktop extends jalview.jbgui.GDesktop
+@SuppressWarnings("serial")
+public class Desktop extends GDesktop
implements DropTargetListener, ClipboardOwner, IProgressIndicator,
- jalview.api.StructureSelectionManagerProvider
+ StructureSelectionManagerProvider, ApplicationSingletonI
+
{
private static final String CITATION;
- static
- {
- URL bg_logo_url = ChannelProperties.getImageURL(
- "bg_logo." + String.valueOf(SplashScreen.logoSize));
- URL uod_logo_url = ChannelProperties.getImageURL(
- "uod_banner." + String.valueOf(SplashScreen.logoSize));
+ static {
+ URL bg_logo_url = ChannelProperties.getImageURL("bg_logo." + String.valueOf(SplashScreen.logoSize));
+ URL uod_logo_url = ChannelProperties.getImageURL("uod_banner." + String.valueOf(SplashScreen.logoSize));
boolean logo = (bg_logo_url != null || uod_logo_url != null);
StringBuilder sb = new StringBuilder();
- sb.append("<br><br>Development managed by The Barton Group, University of Dundee, Scotland, UK.");
- if (logo) {
+ sb.append(
+ "<br><br>Jalview is free software released under GPLv3.<br><br>Development is managed by The Barton Group, University of Dundee, Scotland, UK.");
+ if (logo)
+ {
sb.append("<br>");
}
- sb.append(bg_logo_url == null ? ""
- : "<img alt=\"Barton Group logo\" src=\""
- + bg_logo_url.toString() + "\">");
+ sb.append(bg_logo_url == null ? "" : "<img alt=\"Barton Group logo\" src=\"" + bg_logo_url.toString() + "\">");
sb.append(uod_logo_url == null ? ""
- : " <img alt=\"University of Dundee shield\" src=\""
- + uod_logo_url.toString() + "\">");
+ : " <img alt=\"University of Dundee shield\" src=\"" + uod_logo_url.toString() + "\">");
sb.append(
- "<br><br>For help, see the FAQ at <a href=\"https://www.jalview.org/faq\">www.jalview.org/faq</a> and/or join the jalview-discuss@jalview.org mailing list");
+ "<br><br>For help, see <a href=\"https://www.jalview.org/faq\">www.jalview.org/faq</a> and join <a href=\"https://discourse.jalview.org\">discourse.jalview.org</a>");
sb.append("<br><br>If you use Jalview, please cite:"
- + "<br>Waterhouse, A.M., Procter, J.B., Martin, D.M.A, Clamp, M. and Barton, G. J. (2009)"
- + "<br>Jalview Version 2 - a multiple sequence alignment editor and analysis workbench"
- + "<br>Bioinformatics doi: 10.1093/bioinformatics/btp033");
+ + "<br>Waterhouse, A.M., Procter, J.B., Martin, D.M.A, Clamp, M. and Barton, G. J. (2009)"
+ + "<br>Jalview Version 2 - a multiple sequence alignment editor and analysis workbench"
+ + "<br>Bioinformatics <a href=\"https://doi.org/10.1093/bioinformatics/btp033\">doi: 10.1093/bioinformatics/btp033</a>");
CITATION = sb.toString();
}
private static final String EXPERIMENTAL_FEATURES = "EXPERIMENTAL_FEATURES";
- protected static final String CONFIRM_KEYBOARD_QUIT = "CONFIRM_KEYBOARD_QUIT";
+ public static final String CONFIRM_KEYBOARD_QUIT = "CONFIRM_KEYBOARD_QUIT";
public static HashMap<String, FileWriter> savingFiles = new HashMap<String, FileWriter>();
+ @SuppressWarnings("deprecation")
private JalviewChangeSupport changeSupport = new JalviewChangeSupport();
public static boolean nosplash = false;
+
/**
* news reader - null if it was never started.
*/
* @param listener
* @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.beans.PropertyChangeListener)
*/
+ @Deprecated
public void addJalviewPropertyChangeListener(
PropertyChangeListener listener)
{
* @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.lang.String,
* java.beans.PropertyChangeListener)
*/
+ @Deprecated
public void addJalviewPropertyChangeListener(String propertyName,
PropertyChangeListener listener)
{
* @see jalview.gui.JalviewChangeSupport#removeJalviewPropertyChangeListener(java.lang.String,
* java.beans.PropertyChangeListener)
*/
+ @Deprecated
public void removeJalviewPropertyChangeListener(String propertyName,
PropertyChangeListener listener)
{
listener);
}
- /** Singleton Desktop instance */
- public static Desktop instance;
+ private MyDesktopPane desktopPane;
+
+ public static MyDesktopPane getDesktopPane()
+ {
+ Desktop desktop = getInstance();
+ return desktop == null ? null : desktop.desktopPane;
+ }
- public static MyDesktopPane desktop;
+ /**
+ * Answers an 'application scope' singleton instance of this class. Separate
+ * SwingJS 'applets' running in the same browser page will each have a
+ * distinct instance of Desktop.
+ *
+ * @return
+ */
+ public static Desktop getInstance()
+ {
+ return Jalview.isHeadlessMode() ? null
+ : (Desktop) ApplicationSingletonProvider
+ .getInstance(Desktop.class);
+ }
- public static MyDesktopPane getDesktop()
+ public static StructureSelectionManager getStructureSelectionManager()
{
- // BH 2018 could use currentThread() here as a reference to a
- // Hashtable<Thread, MyDesktopPane> in JavaScript
- return desktop;
+ return StructureSelectionManager
+ .getStructureSelectionManager(getInstance());
}
- static int openFrameCount = 0;
+ int openFrameCount = 0;
- static final int xOffset = 30;
+ final int xOffset = 30;
- static final int yOffset = 30;
+ final int yOffset = 30;
- public static jalview.ws.jws1.Discoverer discoverer;
+ public jalview.ws.jws1.Discoverer discoverer;
- public static Object[] jalviewClipboard;
+ public Object[] jalviewClipboard;
- public static boolean internalCopy = false;
+ public boolean internalCopy = false;
- static int fileLoadingCount = 0;
+ int fileLoadingCount = 0;
class MyDesktopManager implements DesktopManager
{
} catch (NullPointerException npe)
{
Point p = getMousePosition();
- instance.showPasteMenu(p.x, p.y);
+ showPasteMenu(p.x, p.y);
}
}
public void endDraggingFrame(JComponent f)
{
delegate.endDraggingFrame(f);
- desktop.repaint();
+ desktopPane.repaint();
}
@Override
public void endResizingFrame(JComponent f)
{
delegate.endResizingFrame(f);
- desktop.repaint();
+ desktopPane.repaint();
}
@Override
}
/**
- * Creates a new Desktop object.
+ * Private constructor enforces singleton pattern. It is called by reflection
+ * from ApplicationSingletonProvider.getInstance().
*/
- public Desktop()
+ private Desktop()
{
super();
- Cache.initLogger();
- /**
- * A note to implementors. It is ESSENTIAL that any activities that might
- * block are spawned off as threads rather than waited for during this
- * constructor.
- */
- instance = this;
+ try
+ {
+ /**
+ * A note to implementors. It is ESSENTIAL that any activities that might
+ * block are spawned off as threads rather than waited for during this
+ * constructor.
+ */
- doConfigureStructurePrefs();
- setTitle(ChannelProperties.getProperty("app_name") + " "
- + Cache.getProperty("VERSION"));
+ doConfigureStructurePrefs();
+ setTitle(ChannelProperties.getProperty("app_name") + " " + Cache.getProperty("VERSION"));
/**
* Set taskbar "grouped windows" name for linux desktops (works in GNOME and
- * KDE). This uses sun.awt.X11.XToolkit.awtAppClassName which is not
- * officially documented or guaranteed to exist, so we access it via
- * reflection. There appear to be unfathomable criteria about what this
- * string can contain, and it if doesn't meet those criteria then "java"
- * (KDE) or "jalview-bin-Jalview" (GNOME) is used. "Jalview", "Jalview
- * Develop" and "Jalview Test" seem okay, but "Jalview non-release" does
- * not. The reflection access may generate a warning: WARNING: An illegal
- * reflective access operation has occurred WARNING: Illegal reflective
- * access by jalview.gui.Desktop () to field
+ * KDE). This uses sun.awt.X11.XToolkit.awtAppClassName which is not officially
+ * documented or guaranteed to exist, so we access it via reflection. There
+ * appear to be unfathomable criteria about what this string can contain, and it
+ * if doesn't meet those criteria then "java" (KDE) or "jalview-bin-Jalview"
+ * (GNOME) is used. "Jalview", "Jalview Develop" and "Jalview Test" seem okay,
+ * but "Jalview non-release" does not. The reflection access may generate a
+ * warning: WARNING: An illegal reflective access operation has occurred
+ * WARNING: Illegal reflective access by jalview.gui.Desktop () to field
* sun.awt.X11.XToolkit.awtAppClassName which I don't think can be avoided.
*/
- if (Platform.isLinux()) {
- try {
+ if (Platform.isLinux())
+ {
+ if (LaunchUtils.getJavaVersion() >= 11)
+ {
+ jalview.bin.Console.info(
+ "Linux platform only! You may have the following warning next: \"WARNING: An illegal reflective access operation has occurred\"\nThis is expected and cannot be avoided, sorry about that.");
+ }
+ try
+ {
Toolkit xToolkit = Toolkit.getDefaultToolkit();
Field[] declaredFields = xToolkit.getClass().getDeclaredFields();
Field awtAppClassNameField = null;
- if (Arrays.stream(declaredFields)
- .anyMatch(f -> f.getName().equals("awtAppClassName")))
- {
- awtAppClassNameField = xToolkit.getClass()
- .getDeclaredField("awtAppClassName");
+ if (Arrays.stream(declaredFields).anyMatch(f -> f.getName().equals("awtAppClassName"))) {
+ awtAppClassNameField = xToolkit.getClass().getDeclaredField("awtAppClassName");
}
String title = ChannelProperties.getProperty("app_name");
- if (awtAppClassNameField != null)
- {
+ if (awtAppClassNameField != null) {
awtAppClassNameField.setAccessible(true);
awtAppClassNameField.set(xToolkit, title);
- } else {
- Cache.log.debug("XToolkit: awtAppClassName not found");
}
- } catch (Exception e) {
- Cache.debug("Error setting awtAppClassName");
- Cache.trace(Cache.getStackTraceString(e));
+ else
+ {
+ jalview.bin.Console.debug("XToolkit: awtAppClassName not found");
+ }
+ } catch (Exception e)
+ {
+ jalview.bin.Console.debug("Error setting awtAppClassName");
+ jalview.bin.Console.trace(Cache.getStackTraceString(e));
}
}
+ /**
+ * APQHandlers sets handlers for About, Preferences and Quit actions peculiar to
+ * macOS's application menu. APQHandlers will check to see if a handler is
+ * supported before setting it.
+ */
+ try {
+ APQHandlers.setAPQHandlers(this);
+ } catch (Exception e) {
+ System.out.println("Cannot set APQHandlers");
+ // e.printStackTrace();
+ } catch (Throwable t) {
- Cache.warn("Error setting APQHandlers: " + t.toString());
- Cache.trace(Cache.getStackTraceString(t));
++ jalview.bin.Console.warn("Error setting APQHandlers: " + t.toString());
++ jalview.bin.Console.trace(Cache.getStackTraceString(t));
+ }
++
setIconImages(ChannelProperties.getIconList());
- addWindowListener(new WindowAdapter()
- {
+ addWindowListener(new WindowAdapter() {
@Override
- public void windowClosing(WindowEvent ev)
- {
+ public void windowClosing(WindowEvent ev) {
quit();
}
});
- boolean selmemusage = Cache.getDefault("SHOW_MEMUSAGE", false);
+ boolean selmemusage = Cache.getDefault("SHOW_MEMUSAGE", false);
- boolean showjconsole = Cache.getDefault("SHOW_JAVA_CONSOLE", false);
- desktop = new MyDesktopPane(selmemusage);
+ boolean showjconsole = Cache.getDefault("SHOW_JAVA_CONSOLE", false);
+ desktopPane = new MyDesktopPane(selmemusage);
- showMemusage.setSelected(selmemusage);
- desktop.setBackground(Color.white);
+ showMemusage.setSelected(selmemusage);
+ desktopPane.setBackground(Color.white);
- getContentPane().setLayout(new BorderLayout());
- // alternate config - have scrollbars - see notes in JAL-153
- // JScrollPane sp = new JScrollPane();
- // sp.getViewport().setView(desktop);
- // getContentPane().add(sp, BorderLayout.CENTER);
+ getContentPane().setLayout(new BorderLayout());
+ // alternate config - have scrollbars - see notes in JAL-153
+ // JScrollPane sp = new JScrollPane();
+ // sp.getViewport().setView(desktop);
+ // getContentPane().add(sp, BorderLayout.CENTER);
- // BH 2018 - just an experiment to try unclipped JInternalFrames.
- if (Platform.isJS())
- {
- getRootPane().putClientProperty("swingjs.overflow.hidden", "false");
- }
+ // BH 2018 - just an experiment to try unclipped JInternalFrames.
+ if (Platform.isJS())
+ {
+ getRootPane().putClientProperty("swingjs.overflow.hidden", "false");
+ }
- getContentPane().add(desktop, BorderLayout.CENTER);
- desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
+ getContentPane().add(desktopPane, BorderLayout.CENTER);
+ desktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
- // This line prevents Windows Look&Feel resizing all new windows to maximum
- // if previous window was maximised
- desktop.setDesktopManager(new MyDesktopManager(
- (Platform.isWindowsAndNotJS() ? new DefaultDesktopManager()
- : Platform.isAMacAndNotJS()
- ? new AquaInternalFrameManager(
- desktop.getDesktopManager())
- : desktop.getDesktopManager())));
- Rectangle dims = getLastKnownDimensions("");
- if (dims != null)
- {
- setBounds(dims);
- }
- else
- {
- Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
- int xPos = Math.max(5, (screenSize.width - 900) / 2);
- int yPos = Math.max(5, (screenSize.height - 650) / 2);
- setBounds(xPos, yPos, 900, 650);
- }
+ // This line prevents Windows Look&Feel resizing all new windows to
+ // maximum
+ // if previous window was maximised
+ desktopPane.setDesktopManager(new MyDesktopManager(
+ (Platform.isWindowsAndNotJS() ? new DefaultDesktopManager()
+ : Platform.isAMacAndNotJS()
+ ? new AquaInternalFrameManager(
+ desktopPane.getDesktopManager())
+ : desktopPane.getDesktopManager())));
- if (!Platform.isJS())
- /**
- * Java only
- *
- * @j2sIgnore
- */
- {
- jconsole = new Console(this, showjconsole);
- jconsole.setHeader(Cache.getVersionDetailsForConsole());
- showConsole(showjconsole);
+ Rectangle dims = getLastKnownDimensions("");
+ if (dims != null)
+ {
+ setBounds(dims);
+ }
+ else
+ {
+ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
+ int xPos = Math.max(5, (screenSize.width - 900) / 2);
+ int yPos = Math.max(5, (screenSize.height - 650) / 2);
+ setBounds(xPos, yPos, 900, 650);
+ }
- showNews.setVisible(false);
+ if (!Platform.isJS())
+ /**
+ * Java only
+ *
+ * @j2sIgnore
+ */
+ {
+ jconsole = new Console(this, showjconsole);
+ jconsole.setHeader(Cache.getVersionDetailsForConsole());
+ showConsole(showjconsole);
- experimentalFeatures.setSelected(showExperimental());
+ showNews.setVisible(false); // not sure if we should only do this for interactive session?
- getIdentifiersOrgData();
+ experimentalFeatures.setSelected(showExperimental());
- checkURLLinks();
+ getIdentifiersOrgData();
- // Spawn a thread that shows the splashscreen
- if (!nosplash)
- {
- SwingUtilities.invokeLater(new Runnable()
+ if (Jalview.isInteractive())
{
- @Override
- public void run()
- {
- new SplashScreen(true);
+ // disabled for SeqCanvasTest
+ checkURLLinks();
+
+ // Spawn a thread that shows the splashscreen
+ if (!nosplash) {
+ SwingUtilities.invokeLater(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ new SplashScreen(true);
+ }
+ });
}
- });
+
+ // Thread off a new instance of the file chooser - this reduces the
+ // time
+ // it
+ // takes to open it later on.
+ new Thread(new Runnable()
+ {
+ @Override
+ public void run()
+ {
- Cache.log.debug("Filechooser init thread started.");
++ jalview.bin.Console.debug("Filechooser init thread started.");
+ String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
+ JalviewFileChooser.forRead(
+ Cache.getProperty("LAST_DIRECTORY"), fileFormat);
- Cache.log.debug("Filechooser init thread finished.");
++ jalview.bin.Console.debug("Filechooser init thread finished.");
+ }
+ }).start();
+ // Add the service change listener
+ changeSupport.addJalviewPropertyChangeListener("services",
+ new PropertyChangeListener()
+ {
+
+ @Override
+ public void propertyChange(PropertyChangeEvent evt)
+ {
- Cache.log.debug("Firing service changed event for "
++ jalview.bin.Console.debug("Firing service changed event for "
+ + evt.getNewValue());
+ JalviewServicesChanged(evt);
+ }
+ });
+ }
}
- // Thread off a new instance of the file chooser - this reduces the time
- // it
- // takes to open it later on.
- new Thread(new Runnable()
+ this.setDropTarget(new java.awt.dnd.DropTarget(desktopPane, this));
+
+ this.addWindowListener(new WindowAdapter()
{
@Override
- public void run()
+ public void windowClosing(WindowEvent evt)
{
- jalview.bin.Console.debug("Filechooser init thread started.");
- String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
- JalviewFileChooser.forRead(Cache.getProperty("LAST_DIRECTORY"),
- fileFormat);
- jalview.bin.Console.debug("Filechooser init thread finished.");
+ quit();
}
- }).start();
- // Add the service change listener
- changeSupport.addJalviewPropertyChangeListener("services",
- new PropertyChangeListener()
- {
-
- @Override
- public void propertyChange(PropertyChangeEvent evt)
- {
- jalview.bin.Console
- .debug("Firing service changed event for "
- + evt.getNewValue());
- JalviewServicesChanged(evt);
- }
- });
- }
-
- this.setDropTarget(new java.awt.dnd.DropTarget(desktop, this));
-
- this.addWindowListener(new WindowAdapter()
- {
- @Override
- public void windowClosing(WindowEvent evt)
- {
- quit();
- }
- });
+ });
- MouseAdapter ma;
- this.addMouseListener(ma = new MouseAdapter()
- {
- @Override
- public void mousePressed(MouseEvent evt)
+ MouseAdapter ma;
+ this.addMouseListener(ma = new MouseAdapter()
{
- if (evt.isPopupTrigger()) // Mac
+ @Override
+ public void mousePressed(MouseEvent evt)
{
- showPasteMenu(evt.getX(), evt.getY());
+ if (evt.isPopupTrigger()) // Mac
+ {
+ showPasteMenu(evt.getX(), evt.getY());
+ }
}
- }
-
- @Override
- public void mouseReleased(MouseEvent evt)
- {
- if (evt.isPopupTrigger()) // Windows
+ @Override
+ public void mouseReleased(MouseEvent evt)
{
- showPasteMenu(evt.getX(), evt.getY());
+ if (evt.isPopupTrigger()) // Windows
+ {
+ showPasteMenu(evt.getX(), evt.getY());
+ }
}
- }
- });
- desktop.addMouseListener(ma);
+ });
+ desktopPane.addMouseListener(ma);
+ } catch (Throwable t)
+ {
+ t.printStackTrace();
+ }
-
}
/**
public void doConfigureStructurePrefs()
{
// configure services
- StructureSelectionManager ssm = StructureSelectionManager
- .getStructureSelectionManager(this);
- if (Cache.getDefault(Preferences.ADD_SS_ANN, true))
- {
- ssm.setAddTempFacAnnot(
- Cache.getDefault(Preferences.ADD_TEMPFACT_ANN, true));
- ssm.setProcessSecondaryStructure(
- Cache.getDefault(Preferences.STRUCT_FROM_PDB, true));
+ StructureSelectionManager ssm = StructureSelectionManager.getStructureSelectionManager(this);
+ if (Cache.getDefault(Preferences.ADD_SS_ANN, true)) {
+ ssm.setAddTempFacAnnot(Cache.getDefault(Preferences.ADD_TEMPFACT_ANN, true));
+ ssm.setProcessSecondaryStructure(Cache.getDefault(Preferences.STRUCT_FROM_PDB, true));
// JAL-3915 - RNAView is no longer an option so this has no effect
- ssm.setSecStructServices(
- Cache.getDefault(Preferences.USE_RNAVIEW, false));
- }
- else
- {
+ ssm.setSecStructServices(Cache.getDefault(Preferences.USE_RNAVIEW, false));
+ } else {
ssm.setAddTempFacAnnot(false);
ssm.setProcessSecondaryStructure(false);
ssm.setSecStructServices(false);
}
}
- public void checkForNews()
- {
+ public void checkForNews() {
final Desktop me = this;
// Thread off the news reader, in case there are connection problems.
- new Thread(new Runnable()
- {
+ new Thread(new Runnable() {
@Override
- public void run() {
- Cache.log.debug("Starting news thread.");
+ public void run()
+ {
+ jalview.bin.Console.debug("Starting news thread.");
jvnews = new BlogReader(me);
showNews.setVisible(true);
- Cache.log.debug("Completed news thread.");
+ jalview.bin.Console.debug("Completed news thread.");
}
}).start();
}
- public void getIdentifiersOrgData()
- {
- if (Cache.getProperty("NOIDENTIFIERSSERVICE") == null)
- {// Thread off the identifiers fetcher
- new Thread(new Runnable()
- {
+ public void getIdentifiersOrgData() {
+ if (Cache.getProperty("NOIDENTIFIERSSERVICE") == null) {
+ // Thread off the identifiers fetcher
+ new Thread(new Runnable() {
@Override
- public void run() {
- Cache.log.debug("Downloading data from identifiers.org");
- try {
- UrlDownloadClient.download(IdOrgSettings.getUrl(), IdOrgSettings.getDownloadLocation());
- } catch (IOException e) {
- Cache.log.debug("Exception downloading identifiers.org data" + e.getMessage());
+ public void run()
+ {
- jalview.bin.Console
- .debug("Downloading data from identifiers.org");
++ jalview.bin.Console.debug("Downloading data from identifiers.org");
+ try
+ {
+ UrlDownloadClient.download(IdOrgSettings.getUrl(),
+ IdOrgSettings.getDownloadLocation());
+ } catch (IOException e)
+ {
- jalview.bin.Console
- .debug("Exception downloading identifiers.org data"
++ jalview.bin.Console.debug("Exception downloading identifiers.org data"
+ + e.getMessage());
}
}
}).start();
- ;
}
}
@Override
- protected void showNews_actionPerformed(ActionEvent e)
- {
+ protected void showNews_actionPerformed(ActionEvent e) {
showNews(showNews.isSelected());
}
void showNews(boolean visible)
{
- Cache.log.debug((visible ? "Showing" : "Hiding") + " news.");
+ jalview.bin.Console.debug((visible ? "Showing" : "Hiding") + " news.");
showNews.setSelected(visible);
if (visible && !jvnews.isVisible())
{
public void run()
{
long now = System.currentTimeMillis();
- Desktop.instance.setProgressBar(
- MessageManager.getString("status.refreshing_news"), now);
+ setProgressBar(MessageManager.getString("status.refreshing_news"),
+ now);
jvnews.refreshNews();
- Desktop.instance.setProgressBar(null, now);
+ setProgressBar(null, now);
jvnews.showNews();
}
}).start();
String y = Cache.getProperty(windowName + "SCREEN_Y");
String width = Cache.getProperty(windowName + "SCREEN_WIDTH");
String height = Cache.getProperty(windowName + "SCREEN_HEIGHT");
- if ((x != null) && (y != null) && (width != null) && (height != null))
- {
- int ix = Integer.parseInt(x), iy = Integer.parseInt(y),
- iw = Integer.parseInt(width), ih = Integer.parseInt(height);
- if (Cache.getProperty("SCREENGEOMETRY_WIDTH") != null)
- {
+ if ((x != null) && (y != null) && (width != null) && (height != null)) {
+ int ix = Integer.parseInt(x), iy = Integer.parseInt(y), iw = Integer.parseInt(width),
+ ih = Integer.parseInt(height);
+ if (Cache.getProperty("SCREENGEOMETRY_WIDTH") != null) {
// attempt #1 - try to cope with change in screen geometry - this
// version doesn't preserve original jv aspect ratio.
// take ratio of current screen size vs original screen size.
- double sw = ((1f * screenSize.width) / (1f * Integer
- .parseInt(Cache.getProperty("SCREENGEOMETRY_WIDTH"))));
- double sh = ((1f * screenSize.height) / (1f * Integer
- .parseInt(Cache.getProperty("SCREENGEOMETRY_HEIGHT"))));
+ double sw = ((1f * screenSize.width) / (1f * Integer.parseInt(Cache.getProperty("SCREENGEOMETRY_WIDTH"))));
+ double sh = ((1f * screenSize.height) / (1f * Integer.parseInt(Cache.getProperty("SCREENGEOMETRY_HEIGHT"))));
// rescale the bounds depending upon the current screen geometry.
ix = (int) (ix * sw);
iw = (int) (iw * sw);
iy = (int) (iy * sh);
ih = (int) (ih * sh);
- while (ix >= screenSize.width) {
- Cache.log.debug("Window geometry location recall error: shifting horizontal to within screenbounds.");
+ while (ix >= screenSize.width)
+ {
+ jalview.bin.Console.debug(
+ "Window geometry location recall error: shifting horizontal to within screenbounds.");
ix -= screenSize.width;
}
- while (iy >= screenSize.height) {
- Cache.log.debug("Window geometry location recall error: shifting vertical to within screenbounds.");
+ while (iy >= screenSize.height)
+ {
+ jalview.bin.Console.debug(
+ "Window geometry location recall error: shifting vertical to within screenbounds.");
iy -= screenSize.height;
}
- Cache.log.debug("Got last known dimensions for " + windowName + ": x:" + ix + " y:" + iy + " width:" + iw
- + " height:" + ih);
+ jalview.bin.Console.debug(
+ "Got last known dimensions for " + windowName + ": x:" + ix
+ + " y:" + iy + " width:" + iw + " height:" + ih);
}
// return dimensions for new instance
return new Rectangle(ix, iy, iw, ih);
}
}
- /**
- * Adds and opens the given frame to the desktop
- *
- * @param frame
- * Frame to show
- * @param title
- * Visible Title
- * @param w
- * width
- * @param h
- * height
- */
- public static synchronized void addInternalFrame(
- final JInternalFrame frame, String title, int w, int h)
- {
- addInternalFrame(frame, title, true, w, h, true, false);
- }
- /**
- * Add an internal frame to the Jalview desktop
- *
- * @param frame
- * Frame to show
- * @param title
- * Visible Title
- * @param makeVisible
- * When true, display frame immediately, otherwise, caller must call
- * setVisible themselves.
- * @param w
- * width
- * @param h
- * height
- */
- public static synchronized void addInternalFrame(
- final JInternalFrame frame, String title, boolean makeVisible,
- int w, int h)
- {
- addInternalFrame(frame, title, makeVisible, w, h, true, false);
- }
/**
- * Add an internal frame to the Jalview desktop and make it visible
+ * Adds and opens the given frame to the desktop that is visible, allowed to
+ * resize, and has a 300px minimum width.
*
* @param frame
* Frame to show
* width
* @param h
* height
- * @param resizable
- * Allow resize
*/
public static synchronized void addInternalFrame(
- final JInternalFrame frame, String title, int w, int h,
- boolean resizable)
+ final JInternalFrame frame, String title, int w, int h)
{
- addInternalFrame(frame, title, true, w, h, resizable, false);
+ // 58 classes
+
+ addInternalFrame(frame, title, Desktop.FRAME_MAKE_VISIBLE, w, h,
+ FRAME_ALLOW_RESIZE, FRAME_SET_MIN_SIZE_300);
}
/**
- * Add an internal frame to the Jalview desktop
+ * Add an internal frame to the Jalview desktop that may optionally be
+ * visible, resizable, and allowed to be any size
*
* @param frame
* Frame to show
final JInternalFrame frame, String title, boolean makeVisible,
int w, int h, boolean resizable, boolean ignoreMinSize)
{
+ // 15 classes call this method directly.
+
// TODO: allow callers to determine X and Y position of frame (eg. via
// bounds object).
{
frame.setSize(w, h);
}
- // THIS IS A PUBLIC STATIC METHOD, SO IT MAY BE CALLED EVEN IN
- // A HEADLESS STATE WHEN NO DESKTOP EXISTS. MUST RETURN
- // IF JALVIEW IS RUNNING HEADLESS
- // ///////////////////////////////////////////////
- if (instance == null || (System.getProperty("java.awt.headless") != null
- && System.getProperty("java.awt.headless").equals("true")))
- {
- return;
- }
+ if (getInstance() != null)
+ getInstance().addFrame(frame, makeVisible, resizable,
+ ignoreMinSize);
+ }
+
+ // These can now by put into a single int flag, if desired:
+
+ public final static boolean FRAME_MAKE_VISIBLE = true;
+
+ public final static boolean FRAME_NOT_VISIBLE = false;
+
+ public final static boolean FRAME_ALLOW_RESIZE = true;
+
+ public final static boolean FRAME_NOT_RESIZABLE = false;
+
+ public final static boolean FRAME_ALLOW_ANY_SIZE = true;
+
+ public final static boolean FRAME_SET_MIN_SIZE_300 = false;
+
+ private void addFrame(JInternalFrame frame,
+ boolean makeVisible, boolean resizable,
+ boolean ignoreMinSize)
+ {
openFrameCount++;
+
+ boolean isEmbedded = (Platform.getEmbeddedAttribute(frame, "id") != null);
+ boolean hasEmbeddedSize = (Platform.getDimIfEmbedded(frame, -1, -1) != null);
+ // Web page embedding allows us to ignore minimum size
+ ignoreMinSize |= hasEmbeddedSize;
+
if (!ignoreMinSize)
{
- frame.setMinimumSize(
- new Dimension(DEFAULT_MIN_WIDTH, DEFAULT_MIN_HEIGHT));
// Set default dimension for Alignment Frame window.
// The Alignment Frame window could be added from a number of places,
{
frame.setMinimumSize(new Dimension(ALIGN_FRAME_DEFAULT_MIN_WIDTH,
ALIGN_FRAME_DEFAULT_MIN_HEIGHT));
+ } else {
+ frame.setMinimumSize(
+ new Dimension(DEFAULT_MIN_WIDTH, DEFAULT_MIN_HEIGHT));
+
}
}
frame.setIconifiable(resizable);
frame.setOpaque(Platform.isJS());
- if (frame.getX() < 1 && frame.getY() < 1)
+ if (!isEmbedded && frame.getX() < 1 && frame.getY() < 1)
{
frame.setLocation(xOffset * openFrameCount,
yOffset * ((openFrameCount - 1) % 10) + yOffset);
}
/*
- * add an entry for the new frame in the Window menu (and remove it when the
- * frame is closed)
+ * add an entry for the new frame in the Window menu
+ * (and remove it when the frame is closed)
*/
- final JMenuItem menuItem = new JMenuItem(title);
+ final JMenuItem menuItem = new JMenuItem(frame.getTitle());
frame.addInternalFrameListener(new InternalFrameAdapter()
{
@Override
public void internalFrameActivated(InternalFrameEvent evt)
{
- JInternalFrame itf = desktop.getSelectedFrame();
+ JInternalFrame itf = getDesktopPane().getSelectedFrame();
if (itf != null)
{
if (itf instanceof AlignFrame)
PaintRefresher.RemoveComponent(frame);
/*
- * defensive check to prevent frames being added half off the window
+ * defensive check to prevent frames being
+ * added half off the window
*/
if (openFrameCount > 0)
{
{
menuItem.removeActionListener(menuItem.getActionListeners()[0]);
}
- windowMenu.remove(menuItem);
+ getInstance().windowMenu.remove(menuItem);
}
});
frame.setIcon(false);
} catch (java.beans.PropertyVetoException ex)
{
+ // System.err.println(ex.toString());
+
}
}
});
setKeyBindings(frame);
- desktop.add(frame);
+ getDesktopPane().add(frame);
- windowMenu.add(menuItem);
+ getInstance().windowMenu.add(menuItem);
frame.toFront();
try
{
} catch (java.lang.ClassCastException cex)
{
- Cache.log.warn(
- "Squashed a possible GUI implementation error. If you can recreate this, please look at http://issues.jalview.org/browse/JAL-869",
+ jalview.bin.Console.warn(
+ "Squashed a possible GUI implementation error. If you can recreate this, please look at https://issues.jalview.org/browse/JAL-869",
cex);
}
}
*/
private static void setKeyBindings(JInternalFrame frame)
{
+ @SuppressWarnings("serial")
final Action closeAction = new AbstractAction()
{
@Override
/*
* set up key bindings for Ctrl-W and Cmd-W, with the same (Close) action
*/
- KeyStroke ctrlWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
- InputEvent.CTRL_DOWN_MASK);
- KeyStroke cmdWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
- ShortcutKeyMaskExWrapper.getMenuShortcutKeyMaskEx());
+ KeyStroke ctrlWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_DOWN_MASK);
- KeyStroke cmdWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortcutKeyMaskExWrapper.getMenuShortcutKeyMaskEx());
++ KeyStroke cmdWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W, Platform.SHORTCUT_KEY_MASK);
InputMap inputMap = frame
.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
{
if (!internalCopy)
{
- Desktop.jalviewClipboard = null;
+ jalviewClipboard = null;
}
internalCopy = false;
try
{
- Desktop.transferFromDropTarget(files, protocols, evt, t);
+ transferFromDropTarget(files, protocols, evt, t);
} catch (Exception e)
{
e.printStackTrace();
/*
* Call IdentifyFile to verify the file contains what its extension implies.
- * Skip this step for dynamically added file formats, because IdentifyFile does
- * not know how to recognise them.
+ * Skip this step for dynamically added file formats, because
+ * IdentifyFile does not know how to recognise them.
*/
if (FileFormats.getInstance().isIdentifiable(format))
{
panel.add(label);
/*
- * the URL to fetch is input in Java: an editable combobox with history JS:
- * (pending JAL-3038) a plain text field
+ * the URL to fetch is
+ * Java: an editable combobox with history
+ * JS: (pending JAL-3038) a plain text field
*/
JComponent history;
- String urlBase = "http://www.";
+ String urlBase = "https://www.";
if (Platform.isJS())
{
history = new JTextField(urlBase, 35);
public void run()
{
@SuppressWarnings("unchecked")
- String url = (history instanceof JTextField
- ? ((JTextField) history).getText()
- : ((JComboBox<String>) history).getEditor().getItem()
- .toString().trim());
-
- if (url.toLowerCase(Locale.ROOT).endsWith(".jar"))
- {
- if (viewport != null)
- {
- new FileLoader().LoadFile(viewport, url, DataSourceType.URL,
- FileFormat.Jalview);
- }
- else
- {
- new FileLoader().LoadFile(url, DataSourceType.URL,
- FileFormat.Jalview);
+ String url = (history instanceof JTextField ? ((JTextField) history).getText()
+ : ((JComboBox<String>) history).getEditor().getItem().toString().trim());
+
+ if (url.toLowerCase(Locale.ROOT).endsWith(".jar")) {
+ if (viewport != null) {
+ new FileLoader().LoadFile(viewport, url, DataSourceType.URL, FileFormat.Jalview);
+ } else {
+ new FileLoader().LoadFile(url, DataSourceType.URL, FileFormat.Jalview);
}
- }
- else
- {
+ } else {
FileFormatI format = null;
try
{
{
String msg = MessageManager
.formatMessage("label.couldnt_locate", url);
- JvOptionPane.showInternalMessageDialog(Desktop.desktop, msg,
+ JvOptionPane.showInternalMessageDialog(getDesktopPane(), msg,
MessageManager.getString("label.url_not_found"),
JvOptionPane.WARNING_MESSAGE);
};
String dialogOption = MessageManager
.getString("label.input_alignment_from_url");
- JvOptionPane.newOptionDialog(desktop).setResponseHandler(0, action)
+ JvOptionPane.newOptionDialog(desktopPane).setResponseHandler(0, action)
.showInternalDialog(panel, dialogOption,
JvOptionPane.YES_NO_CANCEL_OPTION,
JvOptionPane.PLAIN_MESSAGE, null, options,
{
CutAndPasteTransfer cap = new CutAndPasteTransfer();
cap.setForInput(viewPanel);
- Desktop.addInternalFrame(cap,
- MessageManager.getString("label.cut_paste_alignmen_file"), true,
- 600, 500);
+ addInternalFrame(cap,
+ MessageManager.getString("label.cut_paste_alignmen_file"),
+ FRAME_MAKE_VISIBLE, 600, 500, FRAME_ALLOW_RESIZE,
+ FRAME_SET_MIN_SIZE_300);
}
/*
private void storeLastKnownDimensions(String string, Rectangle jc)
{
- Cache.log.debug("Storing last known dimensions for " + string + ": x:"
- + jc.x + " y:" + jc.y + " width:" + jc.width + " height:"
- + jc.height);
+ jalview.bin.Console.debug("Storing last known dimensions for " + string
+ + ": x:" + jc.x + " y:" + jc.y + " width:" + jc.width
+ + " height:" + jc.height);
Cache.setProperty(string + "SCREEN_X", jc.x + "");
Cache.setProperty(string + "SCREEN_Y", jc.y + "");
public String getAboutMessage()
{
StringBuilder message = new StringBuilder(1024);
- message.append("<div style=\"font-family: sans-serif;\">")
- .append("<h1><strong>Version: ")
- .append(Cache.getProperty("VERSION")).append("</strong></h1>")
- .append("<strong>Built: <em>")
- .append(Cache.getDefault("BUILD_DATE", "unknown"))
- .append("</em> from ").append(Cache.getBuildDetailsForSplash())
- .append("</strong>");
+ message.append("<div style=\"font-family: sans-serif;\">").append("<h1><strong>Version: ")
+ .append(Cache.getProperty("VERSION")).append("</strong></h1>").append("<strong>Built: <em>")
+ .append(Cache.getDefault("BUILD_DATE", "unknown")).append("</em> from ")
+ .append(Cache.getBuildDetailsForSplash()).append("</strong>");
String latestVersion = Cache.getDefault("LATEST_VERSION", "Checking");
- if (latestVersion.equals("Checking"))
- {
+ if (latestVersion.equals("Checking")) {
// JBP removed this message for 2.11: May be reinstated in future version
// message.append("<br>...Checking latest version...</br>");
- }
- else if (!latestVersion.equals(Cache.getProperty("VERSION")))
- {
+ } else if (!latestVersion.equals(Cache.getProperty("VERSION"))) {
boolean red = false;
- if (Cache.getProperty("VERSION").toLowerCase(Locale.ROOT)
- .indexOf("automated build") == -1)
- {
+ if (Cache.getProperty("VERSION").toLowerCase(Locale.ROOT).indexOf("automated build") == -1) {
red = true;
// Displayed when code version and jnlp version do not match and code
// version is not a development build
message.append("<div style=\"color: #FF0000;font-style: bold;\">");
}
- message.append("<br>!! Version ")
- .append(Cache.getDefault("LATEST_VERSION", "..Checking.."))
- .append(" is available for download from ")
- .append(Cache.getDefault("www.jalview.org",
- "https://www.jalview.org"))
- .append(" !!");
- if (red)
- {
+ message.append("<br>!! Version ").append(Cache.getDefault("LATEST_VERSION", "..Checking.."))
+ .append(" is available for download from ")
+ .append(Cache.getDefault("www.jalview.org", "https://www.jalview.org")).append(" !!");
+ if (red) {
message.append("</div>");
}
}
message.append(CITATION);
message.append("</div>");
+
return message.toString();
}
* Action on requesting Help documentation
*/
@Override
- public void documentationMenuItem_actionPerformed()
- {
- try
- {
- if (Platform.isJS())
- {
+ public void documentationMenuItem_actionPerformed() {
+ try {
+ if (Platform.isJS()) {
BrowserLauncher.openURL("https://www.jalview.org/help.html");
- }
- else
+ } else
/**
* Java only
*
{
Help.showHelpWindow();
}
- } catch (Exception ex)
- {
+ } catch (Exception ex) {
System.err.println("Error opening help: " + ex.getMessage());
}
}
public void closeAll_actionPerformed(ActionEvent e)
{
// TODO show a progress bar while closing?
- JInternalFrame[] frames = desktop.getAllFrames();
+ JInternalFrame[] frames = desktopPane.getAllFrames();
for (int i = 0; i < frames.length; i++)
{
try
protected void garbageCollect_actionPerformed(ActionEvent e)
{
// We simply collect the garbage
- Cache.log.debug("Collecting garbage...");
+ jalview.bin.Console.debug("Collecting garbage...");
System.gc();
- Cache.log.debug("Finished garbage collection.");
+ jalview.bin.Console.debug("Finished garbage collection.");
}
/*
* (non-Javadoc)
*
- * @see jalview.jbgui.GDesktop#showMemusage_actionPerformed(java.awt.event.
- * ActionEvent )
+ * @see
+ * jalview.jbgui.GDesktop#showMemusage_actionPerformed(java.awt.event.ActionEvent
+ * )
*/
@Override
protected void showMemusage_actionPerformed(ActionEvent e)
{
- desktop.showMemoryUsage(showMemusage.isSelected());
+ desktopPane.showMemoryUsage(showMemusage.isSelected());
}
/*
void reorderAssociatedWindows(boolean minimize, boolean close)
{
- JInternalFrame[] frames = desktop.getAllFrames();
+ JInternalFrame[] frames = desktopPane.getAllFrames();
if (frames == null || frames.length < 1)
{
return;
}
- AlignmentViewport source = null, target = null;
+ AlignViewportI source = null;
+ AlignViewportI target = null;
if (frames[0] instanceof AlignFrame)
{
source = ((AlignFrame) frames[0]).getCurrentView();
* DOCUMENT ME!
*/
@Override
- protected void preferences_actionPerformed(ActionEvent e)
- {
+ protected void preferences_actionPerformed(ActionEvent e) {
Preferences.openPreferences();
}
approveSave = true;
}
}
+
- if (approveSave || autoSave)
- {
+ if (approveSave || autoSave) {
final Desktop me = this;
final java.io.File chosenFile = projectFile;
new Thread(new Runnable()
+ chosenFile.getName(), oom);
} catch (Exception ex)
{
- Cache.log.error("Problems whilst trying to save to "
+ jalview.bin.Console.error("Problems whilst trying to save to "
+ chosenFile.getName(), ex);
JvOptionPane.showMessageDialog(me,
MessageManager.formatMessage(
new OOMWarning("Whilst loading project from " + choice, oom);
} catch (Exception ex)
{
- Cache.log.error(
+ jalview.bin.Console.error(
"Problems whilst loading project from " + choice, ex);
- JvOptionPane.showMessageDialog(Desktop.desktop,
+ JvOptionPane.showMessageDialog(getDesktopPane(),
MessageManager.formatMessage(
"label.error_whilst_loading_project_from",
new Object[]
}, "Project Loader").start();
}
});
+
chooser.showOpenDialog(this);
}
{
progressPanel = new JPanel(new GridLayout(1, 1));
totalProgressCount = 0;
- instance.getContentPane().add(progressPanel, BorderLayout.SOUTH);
+ getContentPane().add(progressPanel, BorderLayout.SOUTH);
}
JPanel thisprogress = new JPanel(new BorderLayout(10, 5));
JProgressBar progressBar = new JProgressBar();
((GridLayout) progressPanel.getLayout()).setRows(
((GridLayout) progressPanel.getLayout()).getRows() + 1);
++totalProgressCount;
- instance.validate();
+ validate();
return thisprogress;
}
*/
public static AlignmentPanel[] getAlignmentPanels(String alignmentId)
{
- if (Desktop.desktop == null)
+ if (getDesktopPane() == null)
{
// no frames created and in headless mode
// TODO: verify that frames are recoverable when in headless mode
public static AlignmentViewport[] getViewports(String sequenceSetId)
{
List<AlignmentViewport> viewp = new ArrayList<>();
- if (desktop != null)
+ if (getDesktopPane() != null)
{
- AlignFrame[] frames = Desktop.getAlignFrames();
+ AlignFrame[] frames = getAlignFrames();
for (AlignFrame afr : frames)
{
}
/*
- * Restore the view's last exploded frame geometry if known. Multiple views from
- * one exploded frame share and restore the same (frame) position and size.
+ * Restore the view's last exploded frame geometry if known. Multiple
+ * views from one exploded frame share and restore the same (frame)
+ * position and size.
*/
Rectangle geometry = ap.av.getExplodedGeometry();
if (geometry != null)
{
source.viewport.setGatherViewsHere(true);
source.viewport.setExplodedGeometry(source.getBounds());
- JInternalFrame[] frames = desktop.getAllFrames();
+ JInternalFrame[] frames = desktopPane.getAllFrames();
String viewId = source.viewport.getSequenceSetId();
for (int t = 0; t < frames.length; t++)
{
{
source.showFeatureSettingsUI();
}
+
}
public JInternalFrame[] getAllFrames()
{
- return desktop.getAllFrames();
+ return desktopPane.getAllFrames();
}
/**
});
msgPanel.add(jcb);
- JvOptionPane.showMessageDialog(Desktop.desktop, msgPanel,
+ JvOptionPane.showMessageDialog(desktopPane, msgPanel,
MessageManager
.getString("label.SEQUENCE_ID_no_longer_used"),
JvOptionPane.WARNING_MESSAGE);
10, getHeight() - fm.getHeight());
}
}
+
// output debug scale message. Important for jalview.bin.HiDPISettingTest2
-- Desktop.debugScaleMessage(Desktop.getDesktop().getGraphics());
++ Desktop.debugScaleMessage(Desktop.getDesktopPane().getGraphics());
}
}
{
if (Jalview.isHeadlessMode())
{
- // Desktop.desktop is null in headless mode
- return new AlignFrame[] { Jalview.currentAlignFrame };
+ return new AlignFrame[] { Jalview.getInstance().currentAlignFrame };
}
- JInternalFrame[] frames = Desktop.desktop.getAllFrames();
+ JInternalFrame[] frames = getDesktopPane().getAllFrames();
if (frames == null)
{
*/
public GStructureViewer[] getJmols()
{
- JInternalFrame[] frames = Desktop.desktop.getAllFrames();
+ JInternalFrame[] frames = desktopPane.getAllFrames();
if (frames == null)
{
openGroovyConsole();
} catch (Exception ex)
{
- Cache.log.error("Groovy Shell Creation failed.", ex);
+ jalview.bin.Console.error("Groovy Shell Creation failed.", ex);
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ JvOptionPane.showInternalMessageDialog(desktopPane,
MessageManager.getString("label.couldnt_create_groovy_shell"),
MessageManager.getString("label.groovy_support_failed"),
/*
* We allow only one console at a time, so that AlignFrame menu option
- * 'Calculate | Run Groovy script' is unambiguous. Disable 'Groovy Console', and
- * enable 'Run script', when the console is opened, and the reverse when it is
- * closed
+ * 'Calculate | Run Groovy script' is unambiguous.
+ * Disable 'Groovy Console', and enable 'Run script', when the console is
+ * opened, and the reverse when it is closed
*/
Window window = (Window) groovyConsole.getFrame();
window.addWindowListener(new WindowAdapter()
((Window) groovyConsole.getFrame()).setVisible(true);
/*
- * if we got this far, enable 'Run Groovy' in AlignFrame menus and disable
- * opening a second console
+ * if we got this far, enable 'Run Groovy' in AlignFrame menus
+ * and disable opening a second console
*/
enableExecuteGroovy(true);
}
*/
protected void addQuitHandler()
{
- getRootPane()
- .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
- KeyStroke
- .getKeyStroke(KeyEvent.VK_Q,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx()),
+
+ getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
+ .put(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
+ Platform.SHORTCUT_KEY_MASK),
"Quit");
getRootPane().getActionMap().put("Quit", new AbstractAction()
{
public void enableExecuteGroovy(boolean enabled)
{
/*
- * disable opening a second Groovy console (or re-enable when the console is
- * closed)
+ * disable opening a second Groovy console
+ * (or re-enable when the console is closed)
*/
groovyShell.setEnabled(!enabled);
@Override
public void setProgressBar(String message, long id)
{
+ // Platform.timeCheck("Desktop " + message, Platform.TIME_MARK);
+
if (progressBars == null)
{
progressBars = new Hashtable<>();
progressBars.put(Long.valueOf(id), addProgressPanel(message));
}
}
+
+ @Override
+ public void removeProgressBar(long id)
+ {
+ //TODO
+ throw new UnsupportedOperationException("not implemented");
+ }
/*
* (non-Javadoc)
*/
public static AlignFrame getAlignFrameFor(AlignViewportI viewport)
{
- if (desktop != null)
+ if (getDesktopPane() != null)
{
AlignmentPanel[] aps = getAlignmentPanels(
viewport.getSequenceSetId());
this.inBatchMode = inBatchMode;
}
+ /**
+ * start service discovery and wait till it is done
+ */
public void startServiceDiscovery()
{
startServiceDiscovery(false);
}
+ /**
+ * start service discovery threads - blocking or non-blocking
+ *
+ * @param blocking
+ */
public void startServiceDiscovery(boolean blocking)
{
- System.out.println("Starting service discovery");
- startServiceDiscovery(blocking, false);
- }
++ jalview.bin.Console.debug("Starting service discovery");
+
- /**
- * start service discovery threads
- *
- * @param blocking
- * - false means call returns immediately
- * @param ignore_SHOW_JWS2_SERVICES_preference
- * - when true JABA services are discovered regardless of user's JWS2
- * discovery preference setting
- */
- public void startServiceDiscovery(boolean blocking,
- boolean ignore_SHOW_JWS2_SERVICES_preference)
- {
- boolean alive = true;
- Thread t0 = null, t1 = null, t2 = null;
+ var tasks = new ArrayList<Future<?>>();
// JAL-940 - JALVIEW 1 services are now being EOLed as of JABA 2.1 release
- if (true)
+
+ System.out.println("loading services");
+
+ /** @j2sIgnore */
{
// todo: changesupport handlers need to be transferred
if (discoverer == null)
{
- discoverer = new jalview.ws.jws1.Discoverer();
+ discoverer = jalview.ws.jws1.Discoverer.getInstance();
// register PCS handler for desktop.
discoverer.addPropertyChangeListener(changeSupport);
}
// JAL-940 - disabled JWS1 service configuration - always start discoverer
// until we phase out completely
- (t0 = new Thread(discoverer)).start();
+ var f = new FutureTask<Void>(discoverer, null);
+ new Thread(f).start();
+ tasks.add(f);
}
- if (ignore_SHOW_JWS2_SERVICES_preference
- || Cache.getDefault("SHOW_JWS2_SERVICES", true))
+ if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
{
- t2 = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
- .startDiscoverer(changeSupport);
+ tasks.add(jalview.ws.jws2.Jws2Discoverer.getInstance().startDiscoverer());
}
- Thread t3 = null;
+ if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
{
- // TODO: do rest service discovery
+ tasks.add(jalview.ws.slivkaws.SlivkaWSDiscoverer.getInstance().startDiscoverer());
}
if (blocking)
{
- while (alive)
- {
+ for (Future<?> task : tasks) {
try
{
- Thread.sleep(15);
+ // block until all discovery tasks are done
+ task.get();
} catch (Exception e)
{
+ e.printStackTrace();
}
- alive = (t1 != null && t1.isAlive()) || (t2 != null && t2.isAlive())
- || (t3 != null && t3.isAlive())
- || (t0 != null && t0.isAlive());
}
}
}
{
if (evt.getNewValue() == null || evt.getNewValue() instanceof Vector)
{
- final String ermsg = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
- .getErrorMessages();
+ final WSDiscovererI discoverer = jalview.ws.jws2.Jws2Discoverer
+ .getInstance();
+ final String ermsg = discoverer.getErrorMessages();
+ // CONFLICT:ALT:? final String ermsg = jalview.ws.jws2.Jws2Discoverer.getInstance()
if (ermsg != null)
{
if (Cache.getDefault("SHOW_WSDISCOVERY_ERRORS", true))
/*
* JalviewDialog jd =new JalviewDialog() {
*
- * @Override protected void cancelPressed() { // TODO Auto-generated method stub
+ * @Override protected void cancelPressed() { // TODO
+ * Auto-generated method stub
*
- * }@Override protected void okPressed() { // TODO Auto-generated method stub
+ * }@Override protected void okPressed() { // TODO
+ * Auto-generated method stub
*
- * }@Override protected void raiseClosed() { // TODO Auto-generated method stub
+ * }@Override protected void raiseClosed() { // TODO
+ * Auto-generated method stub
*
- * } }; jd.initDialogFrame(new JLabel("<html><table width=\"450\"><tr><td>" +
- * ermsg +
+ * } }; jd.initDialogFrame(new
+ * JLabel("<html><table width=\"450\"><tr><td>" + ermsg +
* "<br/>It may be that you have invalid JABA URLs in your web service preferences,"
* + " or mis-configured HTTP proxy settings.<br/>" +
- * "Check the <em>Connections</em> and <em>Web services</em> tab of the" +
- * " Tools->Preferences dialog box to change them.</td></tr></table></html>" ),
- * true, true, "Web Service Configuration Problem", 450, 400);
+ * "Check the <em>Connections</em> and <em>Web services</em> tab of the"
+ * +
+ * " Tools->Preferences dialog box to change them.</td></tr></table></html>"
+ * ), true, true, "Web Service Configuration Problem", 450,
+ * 400);
*
* jd.waitForInput();
*/
- JvOptionPane.showConfirmDialog(Desktop.desktop,
+ JvOptionPane.showConfirmDialog(desktopPane,
new JLabel("<html><table width=\"450\"><tr><td>"
+ ermsg + "</td></tr></table>"
+ "<p>It may be that you have invalid JABA URLs<br/>in your web service preferences,"
}
else
{
- Cache.log.error(
+ jalview.bin.Console.error(
"Errors reported by JABA discovery service. Check web services preferences.\n"
+ ermsg);
}
*/
public static void showUrl(final String url)
{
- showUrl(url, Desktop.instance);
+ showUrl(url, getInstance());
}
/**
jalview.util.BrowserLauncher.openURL(url);
} catch (Exception ex)
{
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ JvOptionPane.showInternalMessageDialog(getDesktopPane(),
MessageManager
.getString("label.web_browser_not_found_unix"),
MessageManager.getString("label.web_browser_not_found"),
try
{
url = e.getURL().toString();
- Desktop.showUrl(url);
+ showUrl(url);
} catch (Exception x)
{
if (url != null)
{
- if (Cache.log != null)
- {
- Cache.log.error("Couldn't handle string " + url + " as a URL.");
- }
- else
- {
- System.err.println(
- "Couldn't handle string " + url + " as a URL.");
- }
- jalview.bin.Console
- .error("Couldn't handle string " + url + " as a URL.");
++ // TODO does error send to stderr if no log exists ?
++ jalview.bin.Console.error("Couldn't handle string " + url + " as a URL.");
}
// ignore any exceptions due to dud links.
}
{
}
}
- if (instance == null)
+ if (Jalview.isHeadlessMode())
{
return;
}
SwingUtilities.invokeAndWait(prompter);
} catch (Exception q)
{
- Cache.log.warn("Unexpected Exception in dialog thread.", q);
- jalview.bin.Console.warn("Unexpected Exception in dialog thread.",
- q);
++ jalview.bin.Console.warn("Unexpected Exception in dialog thread.", q);
}
}
});
public void exportImage(Graphics g) throws Exception
{
paintAll(g);
- Cache.log.info("Successfully written snapshot to file "
+ jalview.bin.Console.info("Successfully written snapshot to file "
+ of.getAbsolutePath());
}
};
}
/*
- * Processing in reverse order works, forwards order leaves the first panels not
- * visible. I don't know why!
+ * Processing in reverse order works, forwards order leaves the first panels
+ * not visible. I don't know why!
*/
for (int i = viewCount - 1; i >= 0; i--)
{
/*
- * Make new top and bottom frames. These take over the respective AlignmentPanel
- * objects, including their AlignmentViewports, so the cdna/protein
- * relationships between the viewports is carried over to the new split frames.
+ * Make new top and bottom frames. These take over the respective
+ * AlignmentPanel objects, including their AlignmentViewports, so the
+ * cdna/protein relationships between the viewports is carried over to the
+ * new split frames.
*
* explodedGeometry holds the (x, y) position of the previously exploded
* SplitFrame, and the (width, height) of the AlignFrame component
{
splitFrame.setLocation(geometry.getLocation());
}
- Desktop.addInternalFrame(splitFrame, sf.getTitle(), -1, -1);
+ addInternalFrame(splitFrame, sf.getTitle(), -1, -1);
}
/*
- * Clear references to the panels (now relocated in the new SplitFrames) before
- * closing the old SplitFrame.
+ * Clear references to the panels (now relocated in the new SplitFrames)
+ * before closing the old SplitFrame.
*/
topPanels.clear();
bottomPanels.clear();
String topViewId = myTopFrame.viewport.getSequenceSetId();
String bottomViewId = myBottomFrame.viewport.getSequenceSetId();
- JInternalFrame[] frames = desktop.getAllFrames();
+ JInternalFrame[] frames = desktopPane.getAllFrames();
for (JInternalFrame frame : frames)
{
if (frame instanceof SplitFrame && frame != source)
* - the payload from the drop event
* @throws Exception
*/
+ @SuppressWarnings("unchecked")
public static void transferFromDropTarget(List<Object> files,
List<DataSourceType> protocols, DropTargetDropEvent evt,
Transferable t) throws Exception
{
+ // BH 2018 changed List<String> to List<Object> to allow for File from
+ // SwingJS
+
+ // DataFlavor[] flavors = t.getTransferDataFlavors();
+ // for (int i = 0; i < flavors.length; i++) {
+ // if (flavors[i].isFlavorJavaFileListType()) {
+ // evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
+ // List<File> list = (List<File>) t.getTransferData(flavors[i]);
+ // for (int j = 0; j < list.size(); j++) {
+ // File file = (File) list.get(j);
+ // byte[] data = getDroppedFileBytes(file);
+ // fileName.setText(file.getName() + " - " + data.length + " " +
+ // evt.getLocation());
+ // JTextArea target = (JTextArea) ((DropTarget)
+ // evt.getSource()).getComponent();
+ // target.setText(new String(data));
+ // }
+ // dtde.dropComplete(true);
+ // return;
+ // }
+ //
+
DataFlavor uriListFlavor = new DataFlavor(
"text/uri-list;class=java.lang.String"), urlFlavour = null;
try
"application/x-java-url; class=java.net.URL");
} catch (ClassNotFoundException cfe)
{
- Cache.log.debug("Couldn't instantiate the URL dataflavor.", cfe);
+ jalview.bin.Console.debug("Couldn't instantiate the URL dataflavor.",
+ cfe);
}
if (urlFlavour != null && t.isDataFlavorSupported(urlFlavour))
{
protocols.add(DataSourceType.URL);
files.add(url.toString());
- Cache.log.debug("Drop handled as URL dataflavor "
+ jalview.bin.Console.debug("Drop handled as URL dataflavor "
+ files.get(files.size() - 1));
return;
}
}
} catch (Throwable ex)
{
- Cache.log.debug("URL drop handler failed.", ex);
+ jalview.bin.Console.debug("URL drop handler failed.", ex);
}
}
if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
{
// Works on Windows and MacOSX
- Cache.log.debug("Drop handled as javaFileListFlavor");
+ jalview.bin.Console.debug("Drop handled as javaFileListFlavor");
- for (Object file : (List) t
+ for (File file : (List<File>) t
.getTransferData(DataFlavor.javaFileListFlavor))
{
files.add(file);
String data = null;
if (t.isDataFlavorSupported(uriListFlavor))
{
- Cache.log.debug("Drop handled as uriListFlavor");
+ jalview.bin.Console.debug("Drop handled as uriListFlavor");
// This is used by Unix drag system
data = (String) t.getTransferData(uriListFlavor);
}
if (data == null)
{
// fallback to text: workaround - on OSX where there's a JVM bug
- Cache.log.debug("standard URIListFlavor failed. Trying text");
+ jalview.bin.Console
+ .debug("standard URIListFlavor failed. Trying text");
// try text fallback
DataFlavor textDf = new DataFlavor(
"text/plain;class=java.lang.String");
data = (String) t.getTransferData(textDf);
}
- Cache.log.debug("Plain text drop content returned "
+ jalview.bin.Console.debug("Plain text drop content returned "
+ (data == null ? "Null - failed" : data));
}
{
while (protocols.size() < files.size())
{
- Cache.log.debug("Adding missing FILE protocol for "
+ jalview.bin.Console.debug("Adding missing FILE protocol for "
+ files.get(protocols.size()));
protocols.add(DataSourceType.FILE);
}
continue;
}
java.net.URI uri = new java.net.URI(s);
- if (uri.getScheme().toLowerCase().startsWith("http"))
+ if (uri.getScheme().toLowerCase(Locale.ROOT).startsWith("http"))
{
protocols.add(DataSourceType.URL);
files.add(uri.toString());
}
}
- if (Cache.log.isDebugEnabled())
+ if (jalview.bin.Console.isDebugEnabled())
{
if (data == null || !added)
{
if (t.getTransferDataFlavors() != null
&& t.getTransferDataFlavors().length > 0)
{
- Cache.log.debug(
+ jalview.bin.Console.debug(
"Couldn't resolve drop data. Here are the supported flavors:");
for (DataFlavor fl : t.getTransferDataFlavors())
{
- Cache.log.debug(
+ jalview.bin.Console.debug(
"Supported transfer dataflavor: " + fl.toString());
Object df = t.getTransferData(fl);
if (df != null)
{
- Cache.log.debug("Retrieves: " + df);
+ jalview.bin.Console.debug("Retrieves: " + df);
}
else
{
- Cache.log.debug("Retrieved nothing");
+ jalview.bin.Console.debug("Retrieved nothing");
}
}
}
else
{
- Cache.log.debug("Couldn't resolve dataflavor for drop: "
- + t.toString());
- jalview.bin.Console
- .debug("Couldn't resolve dataflavor for drop: "
++ jalview.bin.Console.debug("Couldn't resolve dataflavor for drop: "
+ + t.toString());
}
}
}
}
if (Platform.isWindowsAndNotJS())
{
- Cache.log.debug("Scanning dropped content for Windows Link Files");
- jalview.bin.Console
- .debug("Scanning dropped content for Windows Link Files");
++ jalview.bin.Console.debug("Scanning dropped content for Windows Link Files");
// resolve any .lnk files in the file drop
for (int f = 0; f < files.size(); f++)
{
- String source = files.get(f).toString().toLowerCase();
+ String source = files.get(f).toString().toLowerCase(Locale.ROOT);
if (protocols.get(f).equals(DataSourceType.FILE)
&& (source.endsWith(".lnk") || source.endsWith(".url")
|| source.endsWith(".site")))
File lf = (obj instanceof File ? (File) obj
: new File((String) obj));
// process link file to get a URL
- Cache.log.debug("Found potential link file: " + lf);
+ jalview.bin.Console.debug("Found potential link file: " + lf);
WindowsShortcut wscfile = new WindowsShortcut(lf);
String fullname = wscfile.getRealFilename();
protocols.set(f, FormatAdapter.checkProtocol(fullname));
files.set(f, fullname);
- Cache.log.debug("Parsed real filename " + fullname
+ jalview.bin.Console.debug("Parsed real filename " + fullname
+ " to extract protocol: " + protocols.get(f));
} catch (Exception ex)
{
- Cache.log.error(
+ jalview.bin.Console.error(
"Couldn't parse " + files.get(f) + " as a link file.",
ex);
}
Class<? extends StructureViewerBase> structureViewerClass)
{
List<StructureViewerBase> result = new ArrayList<>();
- JInternalFrame[] frames = Desktop.instance.getAllFrames();
+ JInternalFrame[] frames = getAllFrames();
for (JInternalFrame frame : frames)
{
private static boolean debugScaleMessageDone = false;
- public static void debugScaleMessage(Graphics g)
- {
- if (debugScaleMessageDone)
- {
+ public static void debugScaleMessage(Graphics g) {
+ if (debugScaleMessageDone) {
return;
}
// output used by tests to check HiDPI scaling settings in action
- try
- {
+ try {
Graphics2D gg = (Graphics2D) g;
- if (gg != null)
- {
+ if (gg != null) {
AffineTransform t = gg.getTransform();
double scaleX = t.getScaleX();
double scaleY = t.getScaleY();
- Cache.debug(debugScaleMessage + scaleX + " (X)");
- Cache.debug(debugScaleMessage + scaleY + " (Y)");
+ jalview.bin.Console.debug(debugScaleMessage + scaleX + " (X)");
+ jalview.bin.Console.debug(debugScaleMessage + scaleY + " (Y)");
debugScaleMessageDone = true;
- } else {
- Cache.debug("Desktop graphics null");
}
- } catch (Exception e) {
- Cache.debug(Cache.getStackTraceString(e));
+ else
+ {
+ jalview.bin.Console.debug("Desktop graphics null");
+ }
+ } catch (Exception e)
+ {
+ jalview.bin.Console.debug(Cache.getStackTraceString(e));
}
}
}
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.gui;
+import jalview.api.FeatureColourI;
+import jalview.datamodel.SearchResults;
+import jalview.datamodel.SearchResultsI;
+import jalview.datamodel.SequenceFeature;
+import jalview.datamodel.SequenceI;
+import jalview.gui.JalviewColourChooser.ColourChooserListener;
+import jalview.io.FeaturesFile;
+import jalview.schemes.FeatureColour;
+import jalview.util.ColorUtils;
+import jalview.util.MessageManager;
+
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
-import jalview.api.FeatureColourI;
-import jalview.datamodel.SearchResults;
-import jalview.datamodel.SearchResultsI;
-import jalview.datamodel.SequenceFeature;
-import jalview.datamodel.SequenceI;
-import jalview.gui.JalviewColourChooser.ColourChooserListener;
-import jalview.io.FeaturesFile;
-import jalview.schemes.FeatureColour;
-import jalview.util.ColorUtils;
-import jalview.util.MessageManager;
-
/**
* Provides a dialog allowing the user to add new features, or amend or delete
* existing features
});
description = new JTextArea(3, 25);
-
+
start = new JSpinner();
end = new JSpinner();
start.setPreferredSize(new Dimension(80, 20));
end.setPreferredSize(new Dimension(80, 20));
-
+
/*
* ensure that start can never be more than end
*/
- start.addChangeListener(new ChangeListener()
+ start.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e)
{
- Integer startVal = (Integer) start.getValue();
+ Integer startVal = (Integer) start.getValue();
((SpinnerNumberModel) end.getModel()).setMinimum(startVal);
}
});
- end.addChangeListener(new ChangeListener()
+ end.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e)
{
- Integer endVal = (Integer) end.getValue();
+ Integer endVal = (Integer) end.getValue();
((SpinnerNumberModel) start.getModel()).setMaximum(endVal);
}
});
updateColourButton(mainPanel, colour, featureColour);
};
};
- JalviewColourChooser.showColourChooser(Desktop.getDesktop(),
+ JalviewColourChooser.showColourChooser(Desktop.getDesktopPane(),
title, featureColour.getColour(), listener);
}
else
start.setValue(new Integer(firstFeature.getBegin()));
end.setValue(new Integer(firstFeature.getEnd()));
- ((SpinnerNumberModel) start.getModel())
- .setMaximum(firstFeature.getEnd());
- ((SpinnerNumberModel) end.getModel())
- .setMinimum(firstFeature.getBegin());
+ ((SpinnerNumberModel) start.getModel()).setMaximum(firstFeature.getEnd());
+ ((SpinnerNumberModel) end.getModel()).setMinimum(firstFeature.getBegin());
description.setText(firstFeature.getDescription());
featureColour = fr.getFeatureStyle(featureType);
*/
public void showDialog()
{
- Runnable okAction = forCreate ? getCreateAction() : getAmendAction();
- Runnable cancelAction = getCancelAction();
+ Runnable okAction = forCreate ? getCreateAction() : getAmendAction();
+ Runnable cancelAction = getCancelAction();
/*
* set dialog action handlers for OK (create/Amend) and Cancel options
* also for Delete if applicable (when amending features)
*/
- JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.getDesktopPane())
- .setResponseHandler(0, okAction).setResponseHandler(2, cancelAction);
+ JvOptionPane dialog = JvOptionPane.newOptionDialog(ap.alignFrame)
+ .setResponseHandler(0, okAction)
+ .setResponseHandler(2, cancelAction);
if (!forCreate)
{
dialog.setResponseHandler(1, getDeleteAction());
}
dialog.showInternalDialog(mainPanel, title,
- JvOptionPane.YES_NO_CANCEL_OPTION, JvOptionPane.PLAIN_MESSAGE,
- null, options, MessageManager.getString("action.ok"));
+ JvOptionPane.YES_NO_CANCEL_OPTION,
+ JvOptionPane.PLAIN_MESSAGE, null, options,
+ MessageManager.getString("action.ok"));
}
/**
*/
protected Runnable getCancelAction()
{
- Runnable okAction = new Runnable()
+ Runnable okAction = new Runnable()
{
@Override
public void run()
*/
protected Runnable getCreateAction()
{
- Runnable okAction = new Runnable()
+ Runnable okAction = new Runnable()
{
boolean useLastDefaults = features.get(0).getType() == null;
+ @Override
public void run()
{
final String enteredType = name.getText().trim();
*/
protected Runnable getDeleteAction()
{
- Runnable deleteAction = new Runnable()
+ Runnable deleteAction = new Runnable()
{
+ @Override
public void run()
{
SequenceFeature sf = features.get(featureIndex);
*/
protected Runnable getAmendAction()
{
- Runnable okAction = new Runnable()
+ Runnable okAction = new Runnable()
{
boolean useLastDefaults = features.get(0).getType() == null;
-
+
String featureType = name.getText();
-
+
String featureGroup = group.getText();
-
-
+ @Override
public void run()
{
final String enteredType = name.getText().trim();
transparency.setValue(100 - transparencyAsPercent);
inConstruction = incon;
}
+
/**
* Constructor
*
}
else
{
- Desktop.addInternalFrame(frame, title, false, bounds.width,
- bounds.height);
+ Desktop.addInternalFrame(frame, title, Desktop.FRAME_NOT_VISIBLE, bounds.width,
+ bounds.height, Desktop.FRAME_ALLOW_RESIZE, Desktop.FRAME_SET_MIN_SIZE_300);
frame.setBounds(bounds);
frame.setVisible(true);
}
});
frame.setLayer(JLayeredPane.PALETTE_LAYER);
}
- inConstruction = false;
- }
+ inConstruction = false;
+ }
/**
* Sets the state of buttons to show complement features from viewport
change = null;
}
- /**
- * Constructs and shows a popup menu of possible actions on the selected row and
- * feature type
- *
- * @param rowSelected
- * @param type
- * @param typeCol
- * @param pt
- */
- protected void showPopupMenu(final int rowSelected, final String type, final Object typeCol, final Point pt)
+ /**
+ * Constructs and shows a popup menu of possible actions on the selected row
+ * and feature type
+ *
+ * @param rowSelected
+ * @param type
+ * @param typeCol
+ * @param pt
+ */
+ protected void showPopupMenu(final int rowSelected, final String type,
+ final Object typeCol, final Point pt)
{
JPopupMenu men = new JPopupMenu(MessageManager
.formatMessage("label.settings_for_param", new String[]
{ type }));
- final FeatureColourI featureColour = (FeatureColourI) typeCol;
-
- /*
- * menu option to select (or deselect) variable colour
- */
- final JCheckBoxMenuItem variableColourCB = new JCheckBoxMenuItem(
- MessageManager.getString("label.variable_colour"));
- variableColourCB.setSelected(!featureColour.isSimpleColour());
- men.add(variableColourCB);
-
- /*
- * checkbox action listener doubles up as listener to OK
- * from the variable colour / filters dialog
- */
- variableColourCB.addActionListener(new ActionListener()
- {
- @Override
- public void actionPerformed(ActionEvent e)
- {
- if (e.getSource() == variableColourCB)
- {
- // BH 2018 for JavaScript because this is a checkbox
- men.setVisible(true);
- men.setVisible(false);
- if (featureColour.isSimpleColour())
- {
- /*
- * toggle simple colour to variable colour - show dialog
- */
- FeatureTypeSettings fc = new FeatureTypeSettings(fr, type);
- fc.addActionListener(this);
- }
- else
- {
- /*
- * toggle variable to simple colour - show colour chooser
- */
- String title = MessageManager
- .formatMessage("label.select_colour_for", type);
- ColourChooserListener listener = new ColourChooserListener()
- {
- @Override
- public void colourSelected(Color c)
- {
- table.setValueAt(new FeatureColour(c), rowSelected,
- COLOUR_COLUMN);
- table.validate();
- updateFeatureRenderer(
- ((FeatureTableModel) table.getModel()).getData(),
- false);
- }
- };
- JalviewColourChooser.showColourChooser(FeatureSettings.this,
- title, featureColour.getMaxColour(), listener);
- }
- }
- else
- {
- if (e.getSource() instanceof FeatureTypeSettings)
- {
- /*
- * update after OK in feature colour dialog; the updated
- * colour will have already been set in the FeatureRenderer
- */
- FeatureColourI fci = fr.getFeatureColours().get(type);
- table.setValueAt(fci, rowSelected, COLOUR_COLUMN);
- // BH 2018 setting a table value does not invalidate it.
- // System.out.println("FeatureSettings is valied" +
- // table.validate();
- }
- }
- }
- });
-
- men.addSeparator();
JMenuItem scr = new JMenuItem(
MessageManager.getString("label.sort_by_score"));
}
/**
- * close ourselves but leave any existing UI handlers (e.g a CDS/Protein tabbed
- * feature settings dialog) intact
+ * close ourselves but leave any existing UI handlers (e.g a CDS/Protein
+ * tabbed feature settings dialog) intact
*/
public void closeOldSettings()
{
}
});
- final String byScoreLabel = MessageManager.getString("label.seq_sort_by_score");
+ final String byScoreLabel = MessageManager
+ .getString("label.seq_sort_by_score");
JButton sortByScore = new JButton(byScoreLabel);
sortByScore.setFont(JvSwingUtils.getLabelFont());
sortByScore.addActionListener(new ActionListener()
}
}
});
- final String byDensityLabel = MessageManager.getString("label.sequence_sort_by_density");
+ final String byDensityLabel = MessageManager
+ .getString("label.sequence_sort_by_density");
JButton sortByDens = new JButton(byDensityLabel);
sortByDens.setFont(JvSwingUtils.getLabelFont());
sortByDens.addActionListener(new ActionListener()
}
}
});
- // Cancel for a SplitFrame should just revert changes to the currently displayed
+ // Cancel for a SplitFrame should just revert changes to the currently
+ // displayed
// settings. May want to do this for either or both - so need a splitview
// feature settings cancel/OK.
JButton cancel = new JButton(MessageManager
MessageManager.getString("label.transparency_tip"));
boolean nucleotide = af.getViewport().getAlignment().isNucleotide();
- String text = MessageManager.formatMessage("label.show_linked_features",
- nucleotide
- ? MessageManager.getString("label.protein")
- .toLowerCase(Locale.ROOT)
- : "CDS");
+ String text = MessageManager
+ .formatMessage("label.show_linked_features",
+ nucleotide
+ ? MessageManager.getString("label.protein")
+ .toLowerCase(Locale.ROOT)
+ : "CDS");
showComplement = new JCheckBox(text);
showComplement.addActionListener(new ActionListener()
{
*
* @param fcol
* @param withHint
- * if true include 'click to edit' and similar text
+ * if true include 'click to edit' and similar text
* @return
*/
public static String getColorTooltip(FeatureColourI fcol,
{
title += " " + scope;
}
- Desktop.addInternalFrame(frame, title, MY_WIDTH, MY_HEIGHT);
+ Desktop.addInternalFrame(frame, title, Desktop.FRAME_MAKE_VISIBLE, MY_WIDTH, MY_HEIGHT, Desktop.FRAME_ALLOW_RESIZE, Desktop.FRAME_ALLOW_ANY_SIZE);
frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
searchBox.getComponent().requestFocus();
}
*/
boolean getFocusedViewport()
{
- if (focusfixed || Desktop.getDesktopPane() == null)
- if (focusFixed || Desktop.desktop == null)
++ if (focusFixed || Desktop.getDesktopPane() == null)
{
if (ap != null && av != null)
{
}
// now checks further down the window stack to fix bug
// https://mantis.lifesci.dundee.ac.uk/view.php?id=36008
- JInternalFrame[] frames = Desktop.desktop.getAllFrames();
+ JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
for (int f = 0; f < frames.length; f++)
{
JInternalFrame alignFrame = frames[f];
{
if (idMatch.size() > 0 && searchResults.getCount() > 0)
{
- message.append(" ").append(
- MessageManager.getString("label.and").toLowerCase(Locale.ROOT))
- .append(" ");
+ message.append(" ").append(MessageManager.getString("label.and")
+ .toLowerCase(Locale.ROOT)).append(" ");
}
message.append(MessageManager.formatMessage(
"label.subsequence_matches_found",
*/
package jalview.gui;
- import jalview.datamodel.SequenceI;
- import jalview.viewmodel.ViewportListenerI;
- import jalview.viewmodel.ViewportRanges;
-
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JPanel;
+ import jalview.datamodel.SequenceI;
+ import jalview.viewmodel.ViewportListenerI;
+ import jalview.viewmodel.ViewportRanges;
+
/**
* DOCUMENT ME!
*
BufferedImage image;
- // Graphics2D gg;
+// Graphics2D gg;
int imgHeight = 0;
- boolean fastPaint = false;
+ private boolean fastPaint = false;
List<SequenceI> searchResults;
AnnotationPanel ap;
private Font idfont;
-
+ private boolean allowFastPaint;
/**
* Creates a new IdCanvas object.
this.av = av;
PaintRefresher.Register(this, av.getSequenceSetId());
av.getRanges().addPropertyChangeListener(this);
- }
+ }
/**
* DOCUMENT ME!
g.drawString(s.getDisplayId(av.getShowJVSuffix()), xPos,
(((i - starty + 1) * charHeight) + ypos) - (charHeight / 5));
+ // JAL-3253-applet was just hiddenRows here. ccfc48e (gmungoc) added getShowHiddenMarkers test
if (hiddenRows && av.getShowHiddenMarkers())
{
drawMarker(g, av, i, starty, ypos);
gg.translate(0, -transY);
gg.dispose();
-
+
fastPaint = true;
// Call repaint on alignment panel so that repaints from other alignment
@Override
public void paintComponent(Graphics g)
{
+ if (av.getAlignPanel().getHoldRepaint())
+ {
+ return;
+ }
-
g.setColor(Color.white);
g.fillRect(0, 0, getWidth(), getHeight());
-
- if (fastPaint)
+
+ if (allowFastPaint && fastPaint)
{
fastPaint = false;
g.drawImage(image, 0, 0, this);
-
+
return;
}
-
+
int oldHeight = imgHeight;
-
+
imgHeight = getHeight();
imgHeight -= (imgHeight % av.getCharHeight());
-
+
if (imgHeight < 1)
{
return;
}
-
+
if (oldHeight != imgHeight || image.getWidth(this) != getWidth())
{
image = new BufferedImage(getWidth(), imgHeight,
- BufferedImage.TYPE_INT_RGB);
+ BufferedImage.TYPE_INT_RGB);
}
-
+
Graphics2D gg = image.createGraphics();
-
+
// Fill in the background
gg.setColor(Color.white);
gg.fillRect(0, 0, getWidth(), imgHeight);
-
- drawIds(gg, av, av.getRanges().getStartSeq(),
- av.getRanges().getEndSeq(), searchResults);
+
+ drawIds(gg, av, av.getRanges().getStartSeq(), av.getRanges().getEndSeq(), searchResults);
gg.dispose();
-
+
g.drawImage(image, 0, 0, this);
}
* @param endSeq
* @param selection
*/
- void drawIds(Graphics2D g, AlignViewport alignViewport,
- final int startSeq, final int endSeq, List<SequenceI> selection)
+ void drawIds(Graphics2D g, AlignViewport alignViewport, final int startSeq,
+ final int endSeq, List<SequenceI> selection)
{
Font font = alignViewport.getFont();
if (alignViewport.isSeqNameItalics())
{
- setIdfont(new Font(font.getName(), Font.ITALIC, font.getSize()));
+ setIdfont(new Font(font.getName(), Font.ITALIC,
+ font.getSize()));
}
else
{
g.setColor(currentColor);
int charHeight = alignViewport.getCharHeight();
- g.fillRect(0, (i - startSeq) * charHeight, getWidth(), charHeight);
+ g.fillRect(0, (i - startSeq) * charHeight,
+ getWidth(), charHeight);
g.setColor(currentTextColor);
xPos = panelWidth - fm.stringWidth(string) - 4;
}
- g.drawString(string, xPos,
- (((i - startSeq) * charHeight) + charHeight)
- - (charHeight / 5));
+ g.drawString(string, xPos, (((i - startSeq) * charHeight) + charHeight)
+ - (charHeight / 5));
if (hasHiddenRows && av.getShowHiddenMarkers())
{
int alignmentWidth = alignViewport.getAlignment().getWidth();
final int alheight = alignViewport.getAlignment().getHeight();
-
- // int annotationHeight = 0;
- /*
+
+ /* (former)
* assumption: SeqCanvas.calculateWrappedGeometry has been called
+ *
+ * was based on the fact that SeqCanvas was added as a child prior to IdCanvas,
+ * and children are processed in order of addition.
+ *
+ * It's probably fine. But...
+ *
*/
SeqCanvas seqCanvas = alignViewport.getAlignPanel()
.getSeqPanel().seqCanvas;
+ // ...better: let's call it now
+ seqCanvas.calculateWrappedGeometry();
final int charHeight = alignViewport.getCharHeight();
AnnotationLabels labels = null;
if (alignViewport.isShowAnnotation())
{
+ // BH when was ap == null?
+ if (ap == null)
+ {
+ ap = new AnnotationPanel(alignViewport);
+ }
labels = new AnnotationLabels(alignViewport);
}
- // int hgap = charHeight;
- // if (alignViewport.getScaleAboveWrapped())
- // {
- // hgap += charHeight;
- // }
- //
- // /*
- // * height of alignment + gap + annotations (if shown)
- // */
- // int cHeight = alheight * charHeight + hgap
- // + annotationHeight;
- //
ViewportRanges ranges = alignViewport.getRanges();
int rowSize = ranges.getViewportWidth();
* @param starty
* @param yoffset
*/
- void drawMarker(Graphics2D g, AlignViewport alignViewport, int seqIndex,
- int starty, int yoffset)
+ void drawMarker(Graphics2D g, AlignViewport alignViewport, int seqIndex, int starty, int yoffset)
{
SequenceI[] hseqs = alignViewport.getAlignment()
.getHiddenSequences().hiddenSequences;
/*
* vertices of the triangle, below or above hidden seqs
*/
- int[] xPoints = new int[] { getWidth() - charHeight,
+ int[] xPoints = new int[]
+ { getWidth() - charHeight,
getWidth() - charHeight, getWidth() };
int yShift = seqIndex - starty;
public void propertyChange(PropertyChangeEvent evt)
{
String propertyName = evt.getPropertyName();
- if (propertyName.equals(ViewportRanges.STARTSEQ)
- || (av.getWrapAlignment()
- && propertyName.equals(ViewportRanges.STARTRES)))
+ switch (propertyName)
{
+ case ViewportRanges.STARTSEQ:
fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());
- }
- else if (propertyName.equals(ViewportRanges.STARTRESANDSEQ))
- {
+ break;
+ case ViewportRanges.STARTRES:
+ if (av.getWrapAlignment())
+ {
+ fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());
+ }
+ break;
+ case ViewportRanges.STARTRESANDSEQ:
fastPaint(((int[]) evt.getNewValue())[1]
- ((int[]) evt.getOldValue())[1]);
- }
- else if (propertyName.equals(ViewportRanges.MOVE_VIEWPORT))
- {
+ break;
+ case ViewportRanges.MOVE_VIEWPORT:
repaint();
+ break;
+ default:
}
}
+
+ /**
+ * Clears the flag that allows a 'fast paint' on the next repaint, so
+ * requiring a full repaint
+ */
+ public void setNoFastPaint()
+ {
+ allowFastPaint = false;
+ }
}
StringBuilder text = new StringBuilder();
text.append("Sequence ").append(String.valueOf(seq + 1))
- .append(" ID: ")
- .append(sequence.getName());
+ .append(" ID: ").append(sequence.getName());
alignPanel.alignFrame.setStatus(text.toString());
}
}
jalview.util.BrowserLauncher.openURL(url);
} catch (Exception ex)
{
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
MessageManager.getString("label.web_browser_not_found_unix"),
MessageManager.getString("label.web_browser_not_found"),
JvOptionPane.WARNING_MESSAGE);
}
MousePos pos = alignPanel.getSeqPanel().findMousePosition(e);
-
+
if (e.isPopupTrigger()) // Mac reports this in mousePressed
{
showPopupMenu(e, pos);
*/
package jalview.gui;
-import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
+import java.awt.Container;
import java.awt.Font;
-import java.awt.GridLayout;
-import java.awt.Rectangle;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
+ import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
+ import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import jalview.util.MessageManager;
+import jalview.util.Platform;
/**
* useful functions for building Swing GUIs
*/
public final class JvSwingUtils
{
+ static final String HTML_PREFIX = (Platform.isJS() ?
+ "<html><div style=\"max-width:350px;overflow-wrap:break-word;display:inline-block\">"
+ : "<html><div style=\"width:350; text-align: justify; word-wrap: break-word;\">"
+ );
-
/**
* wrap a bare html safe string to around 60 characters per line using a CSS
* style class specifying word-wrap and break-word
*
* @param enclose
- * if true, add <html> wrapper tags
+ * if true, add <html> wrapper tags (currently false for only
+ * two references -- both in Jws2Discoverer --
* @param ttext
*
* @return
{
Objects.requireNonNull(ttext,
"Tootip text to format must not be null!");
- ttext = ttext.trim();
+ ttext = ttext.trim().replaceAll("<br/>", "<br>");
-
boolean maxLengthExceeded = false;
+
- if (ttext.contains("<br>"))
+ boolean isHTML = ttext.startsWith("<html>");
+ if (isHTML)
{
- String[] htmllines = ttext.split("<br>");
- for (String line : htmllines)
- {
- maxLengthExceeded = line.length() > 60;
- if (maxLengthExceeded)
- {
+ ttext = ttext.substring(6);
+ }
+ if (ttext.endsWith("</html>"))
+ {
+ isHTML = true;
+ ttext = ttext.substring(0, ttext.length() - 7);
+ }
+ boolean hasBR = ttext.contains("<br>");
+ enclose |= isHTML || hasBR;
+ if (hasBR)
+ {
+ int pt = -1, ptlast = -4;
+ while ((pt = ttext.indexOf("<br>", pt + 1)) >= 0) {
+ if (pt - ptlast - 4 > 60) {
+ maxLengthExceeded = true;
break;
}
}
}
- else
+ else
{
maxLengthExceeded = ttext.length() > 60;
}
- if (!maxLengthExceeded)
- {
- return enclose ? "<html>" + ttext + "</html>" : ttext;
- }
-
- return (enclose ? "<html>" : "")
- // BH 2018
- + "<style> div.ttip {width:350px;white-space:pre-wrap;padding:2px;overflow-wrap:break-word;}</style><div class=\"ttip\">"
- // + "<style> p.ttip {width:350px;margin:-14px 0px -14px
- // 0px;padding:2px;overflow-wrap:break-word;}"
- // + "</style><p class=\"ttip\">"
- + ttext + " </div>"
- // + "</p>"
- + ((enclose ? "</html>" : ""));
+ String ret = (!enclose ? ttext : maxLengthExceeded ? HTML_PREFIX + ttext + "</div></html>" :
+ "<html>" + ttext + "</html>");
+ //System.out.println("JvSwUtil " + enclose + " " + maxLengthExceeded + " " + ret);
+ return ret;
}
public static JButton makeButton(String label, String tooltip,
}
/**
+ * A convenience method that that adds a component with label to a container,
+ * sets a tooltip on both component and label, and optionally specifies layout
+ * constraints for the added component (but not the label)
*
- * @param panel
+ * @param container
* @param tooltip
* @param label
- * @param valBox
- * @return the GUI element created that was added to the layout so it's
- * attributes can be changed.
+ * @param comp
+ * @param constraints
*/
- public static JPanel addtoLayout(JPanel panel, String tooltip,
- JComponent label, JComponent valBox)
+ public static void addtoLayout(Container container, String tooltip,
+ JComponent label, JComponent comp, String constraints)
{
- JPanel laypanel = new JPanel(new GridLayout(1, 2));
- JPanel labPanel = new JPanel(new BorderLayout());
- JPanel valPanel = new JPanel();
- labPanel.setBounds(new Rectangle(7, 7, 158, 23));
- valPanel.setBounds(new Rectangle(172, 7, 270, 23));
- labPanel.add(label, BorderLayout.WEST);
- valPanel.add(valBox);
- laypanel.add(labPanel);
- laypanel.add(valPanel);
- valPanel.setToolTipText(tooltip);
- labPanel.setToolTipText(tooltip);
- valBox.setToolTipText(tooltip);
- panel.add(laypanel);
- panel.validate();
- return laypanel;
+ container.add(label);
+ container.add(comp, constraints);
+ comp.setToolTipText(tooltip); // this doesn't seem to show?
+ label.setToolTipText(tooltip);
}
++ // From 2.11.2 merge
+ public static void mgAddtoLayout(JPanel cpanel, String tooltip,
+ JLabel jLabel, JComponent name)
+ {
+ mgAddtoLayout(cpanel, tooltip, jLabel, name, null);
+ }
+
+ public static void mgAddtoLayout(JPanel cpanel, String tooltip,
+ JLabel jLabel, JComponent name, String params)
+ {
+ cpanel.add(jLabel);
+ if (params == null)
+ {
+ cpanel.add(name);
+ }
+ else
+ {
+ cpanel.add(name, params);
+ }
+ name.setToolTipText(tooltip);
+ jLabel.setToolTipText(tooltip);
+ }
+
/**
* standard font for labels and check boxes in dialog boxes
*
combo.setToolTipText(tooltips.get(j));
}
}
-
@Override
public void mouseExited(MouseEvent e)
{
/**
* Adds a titled border to the component in the default font and position (top
- * left), optionally witht italic text
+ * left), optionally with italic text
*
* @param comp
* @param title
*/
package jalview.gui;
+ import jalview.bin.Console;
import jalview.util.MessageManager;
import java.awt.Component;
desktop = instance;
if (oomex != null)
{
- if (jalview.bin.Cache.log != null)
- {
- jalview.bin.Cache.log.error("Out of Memory when " + action,
- oomex);
- }
- else
- {
- System.err.println("Out of Memory when " + action);
- oomex.printStackTrace();
- }
+ Console.error("Out of Memory when " + action, oomex);
}
javax.swing.SwingUtilities.invokeLater(this);
System.gc();
public OOMWarning(String string, OutOfMemoryError oomerror)
{
- this(string, oomerror, Desktop.desktop);
+ this(string, oomerror, Desktop.getDesktopPane());
}
@Override
*/
package jalview.gui;
+import jalview.bin.Cache;
+import jalview.io.DataSourceType;
+import jalview.io.FileLoader;
+import jalview.io.JalviewFileChooser;
+import jalview.io.JalviewFileView;
+import jalview.util.MessageManager;
+import jalview.ws.jws2.dm.JabaOption;
+import jalview.ws.params.ArgumentI;
+import jalview.ws.params.OptionI;
+import jalview.ws.params.ParameterI;
+import jalview.ws.params.ValueConstrainI;
+import jalview.ws.params.ValueConstrainI.ValueType;
+import jalview.ws.params.simple.FileParameter;
+import jalview.ws.params.simple.LogarithmicParameter;
+import jalview.ws.params.simple.RadioChoiceParameter;
+import jalview.ws.params.simple.StringParameter;
-
import java.awt.BorderLayout;
+import java.awt.Color;
import java.awt.Component;
+import java.awt.Container;
import java.awt.Dimension;
+import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
+ import java.awt.event.FocusAdapter;
+ import java.awt.event.FocusEvent;
+import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
-import java.awt.event.KeyListener;
+import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
+import java.io.File;
import java.net.URL;
import java.util.ArrayList;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
+import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
+import javax.swing.JSlider;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
-import jalview.util.MessageManager;
-import jalview.ws.params.ArgumentI;
-import jalview.ws.params.OptionI;
-import jalview.ws.params.ParameterI;
-import jalview.ws.params.ValueConstrainI;
-import jalview.ws.params.ValueConstrainI.ValueType;
import net.miginfocom.swing.MigLayout;
/**
*/
public class OptsAndParamsPage
{
- /**
+ public static final int PARAM_WIDTH = 340;
+
+ public static final int PARAM_HEIGHT = 150;
+
+ public static final int PARAM_CLOSEDHEIGHT = 80;
+
+ URL linkImageURL = getClass().getResource("/images/link.gif");
+
+ Map<String, OptionBox> optSet = new LinkedHashMap<>();
+
+ Map<String, ParamBox> paramSet = new LinkedHashMap<>();
+
+ /*
* compact or verbose style parameters
*/
boolean compact = false;
+ OptsParametersContainerI poparent;
+
+ /**
+ * A class that models a panel rendering a single option (checkbox or choice
+ * list)
+ */
public class OptionBox extends JPanel
implements MouseListener, ActionListener
{
- JCheckBox enabled = new JCheckBox();
+ JCheckBox enabled;
final URL finfo;
OptionI option;
- JLabel optlabel = new JLabel();
+ JComboBox<Object> val;
- JComboBox<String> val = new JComboBox<>();
+ /**
+ * Constructs and adds labels and controls to the panel for one Option
+ *
+ * @param opt
+ */
public OptionBox(OptionI opt)
{
option = opt;
- setLayout(new BorderLayout());
- enabled.setSelected(opt.isRequired()); // TODO: lock required options
+ setLayout(new FlowLayout(FlowLayout.LEFT));
+ enabled = new JCheckBox(opt.getLabel());
+ enabled.setSelected(opt.isRequired());
+
+ /*
+ * If option is required, show a label, if optional a checkbox
+ * (but not for Jabaws pending JWS-126 resolution)
+ */
+ if (opt.isRequired() && !(opt instanceof JabaOption))
+ {
+ finfo = null;
+ add(new JLabel(opt.getLabel()));
+ }
+ else
+ {
+ finfo = option.getFurtherDetails();
+ configureCheckbox(opt);
+ add(enabled);
+ }
+
+ /*
+ * construct the choice box with possible values,
+ * or their display names if provided
+ */
+ val = buildComboBox(opt);
+ val.setSelectedItem(opt.getValue());
+
+ /*
+ * only show the choicebox if there is more than one option,
+ * or the option is mandatory
+ */
+ if (opt.getPossibleValues().size() > 1 || opt.isRequired())
+ {
+ val.addActionListener(this);
+ add(val);
+ }
+
+ setInitialValue();
+ }
+
+ /**
+ * Configures the checkbox that controls whether or not the option is
+ * selected
+ *
+ * @param opt
+ */
+ protected void configureCheckbox(OptionI opt)
+ {
enabled.setFont(new Font("Verdana", Font.PLAIN, 11));
- enabled.setText("");
- enabled.setText(opt.getName());
enabled.addActionListener(this);
- finfo = option.getFurtherDetails();
- String desc = opt.getDescription();
+ final String desc = opt.getDescription();
if (finfo != null)
{
hasLink = true;
- enabled.setToolTipText(JvSwingUtils.wrapTooltip(true,
- ((desc == null || desc.trim().length() == 0)
- ? MessageManager.getString(
- "label.opt_and_params_further_details")
- : desc) + "<br><img src=\"" + linkImageURL
- + "\"/>"));
- enabled.addMouseListener(this);
+ String description = desc;
+ if (desc == null || desc.trim().isEmpty())
+ {
+ description = MessageManager
+ .getString("label.opt_and_params_further_details");
+ }
+ description = description + "<br><img src=\"" + linkImageURL
+ + "\"/>";
+ String text = JvSwingUtils.wrapTooltip(true, description);
+ enabled.setToolTipText(text);
+ enabled.addMouseListener(this); // for popup menu to show link
}
else
{
if (desc != null && desc.trim().length() > 0)
{
- enabled.setToolTipText(
- JvSwingUtils.wrapTooltip(true, opt.getDescription()));
+ enabled.setToolTipText(JvSwingUtils.wrapTooltip(true, desc));
}
}
- add(enabled, BorderLayout.NORTH);
- for (String str : opt.getPossibleValues())
- {
- val.addItem(str);
- }
- val.setSelectedItem(opt.getValue());
- if (opt.getPossibleValues().size() > 1)
- {
- setLayout(new GridLayout(1, 2));
- val.addActionListener(this);
- add(val, BorderLayout.SOUTH);
- }
- // TODO: add actionListeners for popup (to open further info),
- // and to update list of parameters if an option is enabled
- // that takes a value. JBPNote: is this TODO still valid ?
- setInitialValue();
}
@Override
poparent.argSetModified(this, !notmod);
}
- public OptionI getOptionIfEnabled()
+ /**
+ * Answers null if the option is not selected, else a new Option holding the
+ * selected value
+ *
+ * @return
+ */
+ public ArgumentI getSelectedOption()
{
if (!enabled.isSelected())
{
return null;
}
+ String value = getSelectedValue(option, val.getSelectedIndex());
OptionI opt = option.copy();
- if (opt.getPossibleValues() != null
- && opt.getPossibleValues().size() == 1)
- {
- // Hack to make sure the default value for an enabled option with only
- // one value is actually returned
- opt.setValue(opt.getPossibleValues().get(0));
- }
- if (val.getSelectedItem() != null)
- {
- opt.setValue((String) val.getSelectedItem());
- }
- else
- {
- if (option.getValue() != null)
- {
- opt.setValue(option.getValue());
- }
- }
+ opt.setValue(value);
return opt;
}
@Override
public void mouseEntered(MouseEvent e)
{
- // TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e)
{
- // TODO Auto-generated method stub
}
}
}
+ /**
+ * toString representation for identification in the debugger only
+ */
+ @Override
+ public String toString()
+ {
+ return option == null ? super.toString() : option.toString();
+ }
}
+ /**
+ * A class that models a panel rendering a single parameter
+ */
public class ParamBox extends JPanel
implements ChangeListener, ActionListener, MouseListener
{
- boolean adjusting = false;
+ /*
+ * parameter values (or their logs) are multiplied by this
+ * scaling factor to ensure an integer range for the slider
+ */
+ private int sliderScaleFactor = 1;
+
+ boolean isLogarithmicParameter;
+
+ boolean isChoiceParameter;
- boolean choice = false;
+ boolean isIntegerParameter;
- JComboBox<String> choicebox;
+ boolean isStringParameter;
- JPanel controlPanel = new JPanel();
+ boolean adjusting;
- boolean descisvisible = false;
+ /*
+ * drop-down list of choice options (if applicable)
+ */
+ JComboBox<Object> choicebox;
+
+ /*
+ * radio buttons as an alternative to combo box
+ */
+ ButtonGroup buttonGroup;
+
+ JPanel controlsPanel = new JPanel();
+
+ boolean descriptionIsVisible = false;
JScrollPane descPanel = new JScrollPane();
final URL finfo;
- boolean integ = false;
-
- String lastVal;
+ Object lastVal;
ParameterI parameter;
JPanel settingPanel = new JPanel();
- JButton showDesc = new JButton();
+ JSlider slider;
- Slider slider = null;
+ JTextArea descriptionText = new JTextArea();
- JTextArea string = new JTextArea();
+ ValueConstrainI validator;
- ValueConstrainI validator = null;
+ JTextField valueField;
- JTextField valueField = null;
+ private String descTooltip;
- public ParamBox(final OptsParametersContainerI pmlayout,
+ public ParamBox(final OptsParametersContainerI paramContainer,
ParameterI parm)
{
- pmdialogbox = pmlayout;
+ pmdialogbox = paramContainer;
finfo = parm.getFurtherDetails();
validator = parm.getValidValue();
parameter = parm;
+ isLogarithmicParameter = parm instanceof LogarithmicParameter;
if (validator != null)
{
- integ = validator.getType() == ValueType.Integer;
- }
- else
- {
- if (parameter.getPossibleValues() != null)
+ ValueType type = validator.getType();
+ isIntegerParameter = type == ValueType.Integer;
+ isStringParameter = type == ValueType.String
+ || type == ValueType.File;
+
+ /*
+ * ensure slider has an integer range corresponding to
+ * the min-max range of the parameter
+ */
+ if (validator.getMin() != null && validator.getMax() != null
+ // && !isIntegerParameter
+ && !isStringParameter)
{
- choice = true;
+ double min = validator.getMin().doubleValue();
+ double max = validator.getMax().doubleValue();
+ if (isLogarithmicParameter)
+ {
+ min = Math.log(min);
+ max = Math.log(max);
+ }
+ sliderScaleFactor = (int) (1000000 / (max - min));
+ // todo scaleMin, scaleMax could also be final fields
}
}
- if (!compact)
+ List<String> possibleValues = parameter.getPossibleValues();
+ isChoiceParameter = possibleValues != null
+ && !possibleValues.isEmpty();
+
+ if (compact)
{
- makeExpanderParam(parm);
+ addCompactParameter(parm);
}
else
{
- makeCompactParam(parm);
+ addExpandableParam(parm);
}
}
- private void makeCompactParam(ParameterI parm)
+ /**
+ * Adds a 'compact' format parameter, with any help text shown as a tooltip
+ *
+ * @param parm
+ */
+ private void addCompactParameter(ParameterI parm)
{
setLayout(new MigLayout("", "[][grow]"));
String ttipText = null;
- controlPanel.setLayout(new BorderLayout());
+ controlsPanel.setLayout(new BorderLayout());
if (parm.getDescription() != null
&& parm.getDescription().trim().length() > 0)
{
- // Only create description boxes if there actually is a description.
ttipText = (JvSwingUtils.wrapTooltip(true,
parm.getDescription() + (finfo != null ? "<br><img src=\""
+ linkImageURL + "\"/>"
: "")));
}
- JvSwingUtils.mgAddtoLayout(this, ttipText, new JLabel(parm.getName()),
- controlPanel, "");
+ JvSwingUtils.addtoLayout(this, ttipText, new JLabel(parm.getName()),
+ controlsPanel, "");
updateControls(parm);
validate();
}
- private void makeExpanderParam(final ParameterI parm)
+ /**
+ * Adds an 'expanded' format parameter, with any help shown in a panel that
+ * may be shown or hidden
+ *
+ * @param parm
+ */
+ private void addExpandableParam(ParameterI parm)
{
setPreferredSize(new Dimension(PARAM_WIDTH, PARAM_CLOSEDHEIGHT));
setBorder(new TitledBorder(parm.getName()));
setLayout(null);
- showDesc.setFont(new Font("Verdana", Font.PLAIN, 6));
- showDesc.setText("+");
- string.setFont(new Font("Verdana", Font.PLAIN, 11));
- string.setBackground(getBackground());
+ descriptionText.setFont(new Font("Verdana", Font.PLAIN, 11));
+ descriptionText.setBackground(getBackground());
- string.setEditable(false);
- descPanel.getViewport().setView(string);
+ descriptionText.setEditable(false);
+ descPanel.getViewport().setView(descriptionText);
descPanel.setVisible(false);
JPanel firstrow = new JPanel();
firstrow.setLayout(null);
- controlPanel.setLayout(new BorderLayout());
- controlPanel.setBounds(new Rectangle(39, 10, PARAM_WIDTH - 70,
+ controlsPanel.setLayout(new BorderLayout());
+ controlsPanel.setBounds(new Rectangle(39, 10, PARAM_WIDTH - 70,
PARAM_CLOSEDHEIGHT - 50));
- firstrow.add(controlPanel);
+ firstrow.add(controlsPanel);
firstrow.setBounds(new Rectangle(10, 20, PARAM_WIDTH - 30,
PARAM_CLOSEDHEIGHT - 30));
- final ParamBox me = this;
if (parm.getDescription() != null
&& parm.getDescription().trim().length() > 0)
{
- // Only create description boxes if there actually is a description.
- if (finfo != null)
- {
- showDesc.setToolTipText(JvSwingUtils.wrapTooltip(true,
- MessageManager.formatMessage(
- "label.opt_and_params_show_brief_desc_image_link",
- new String[]
- { linkImageURL.toExternalForm() })));
- showDesc.addMouseListener(this);
- }
- else
- {
- showDesc.setToolTipText(
- JvSwingUtils.wrapTooltip(true, MessageManager.getString(
- "label.opt_and_params_show_brief_desc")));
- }
- showDesc.addActionListener(new ActionListener()
- {
-
- @Override
- public void actionPerformed(ActionEvent e)
- {
- descisvisible = !descisvisible;
- descPanel.setVisible(descisvisible);
- descPanel.getVerticalScrollBar().setValue(0);
- me.setPreferredSize(new Dimension(PARAM_WIDTH,
- (descisvisible) ? PARAM_HEIGHT : PARAM_CLOSEDHEIGHT));
- me.validate();
- pmdialogbox.refreshParamLayout();
- }
- });
- string.setWrapStyleWord(true);
- string.setLineWrap(true);
- string.setColumns(32);
- string.setText(parm.getDescription());
- showDesc.setBounds(new Rectangle(10, 10, 16, 16));
- firstrow.add(showDesc);
+ addExpandableHelp(firstrow, parm);
}
add(firstrow);
validator = parm.getValidValue();
parameter = parm;
if (validator != null)
{
- integ = validator.getType() == ValueType.Integer;
+ isIntegerParameter = validator.getType() == ValueType.Integer;
}
else
{
if (parameter.getPossibleValues() != null)
{
- choice = true;
+ isChoiceParameter = true;
}
}
updateControls(parm);
}
/**
- * Action on input in text field
+ * Adds a button which can be clicked to show or hide help text
+ *
+ * @param container
+ * @param param
*/
+ protected void addExpandableHelp(JPanel container, ParameterI param)
+ {
+ JButton showDescBtn = new JButton("+");
+ showDescBtn.setFont(new Font("Verdana", Font.PLAIN, 8));
+ if (finfo != null)
+ {
+ descTooltip = JvSwingUtils.wrapTooltip(true,
+ MessageManager.formatMessage(
+ "label.opt_and_params_show_brief_desc_image_link",
+ new String[]
+ { linkImageURL.toExternalForm() }));
+ showDescBtn.addMouseListener(this);
+ }
+ else
+ {
+ descTooltip = JvSwingUtils.wrapTooltip(true, MessageManager
+ .getString("label.opt_and_params_show_brief_desc"));
+ }
+ showDescBtn.setToolTipText(descTooltip);
+ showDescBtn.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ descriptionIsVisible = !descriptionIsVisible;
+ showDescBtn.setText(descriptionIsVisible ? "-" : "+");
+ showDescBtn.setToolTipText(
+ descriptionIsVisible ? null : descTooltip);
+ descPanel.setVisible(descriptionIsVisible);
+ descPanel.getVerticalScrollBar().setValue(0);
+ ParamBox.this.setPreferredSize(new Dimension(PARAM_WIDTH,
+ (descriptionIsVisible) ? PARAM_HEIGHT
+ : PARAM_CLOSEDHEIGHT));
+ ParamBox.this.validate();
+ pmdialogbox.refreshParamLayout();
+ }
+ });
+ descriptionText.setWrapStyleWord(true);
+ descriptionText.setLineWrap(true);
+ descriptionText.setColumns(32);
+ descriptionText.setText(param.getDescription());
+ showDescBtn.setBounds(new Rectangle(10, 10, 16, 16));
+ container.add(showDescBtn);
+ }
@Override
public void actionPerformed(ActionEvent e)
{
{
return;
}
checkIfModified();
}
+ /**
+ * Checks whether the value of this parameter has been changed and notifies
+ * the parent page accordingly
+ */
private void checkIfModified()
{
- Object cstate = getCurrentValue();
- boolean modified = !cstate.equals(lastVal);
+ Object newValue = updateSliderFromValueField();
+ boolean modified = true;
+ if (newValue.getClass() == lastVal.getClass())
+ {
+ modified = !newValue.equals(lastVal);
+ }
pmdialogbox.argSetModified(this, modified);
}
- /**
- * Answers the current value of the parameter, as text
- *
- * @return
- */
- private String getCurrentValue()
- {
- return choice ? (String) choicebox.getSelectedItem()
- : valueField.getText();
- }
+
@Override
public int getBaseline(int width, int height)
{
return Component.BaselineResizeBehavior.CONSTANT_ASCENT;
}
- public int getBoxHeight()
- {
- return (descisvisible ? PARAM_HEIGHT : PARAM_CLOSEDHEIGHT);
- }
-
- public ParameterI getParameter()
+ /**
+ * Answers an argument holding the value entered or selected in the dialog
+ *
+ * @return
+ */
+ public ArgumentI getParameter()
{
ParameterI prm = parameter.copy();
- if (choice)
+ String value = null;
+ if (parameter instanceof RadioChoiceParameter)
{
- prm.setValue((String) choicebox.getSelectedItem());
+ value = buttonGroup.getSelection().getActionCommand();
+ }
+ else if (isChoiceParameter)
+ {
+ value = getSelectedValue(this.parameter,
+ choicebox.getSelectedIndex());
}
else
{
- prm.setValue(valueField.getText());
+ value = valueField.getText();
}
+ prm.setValue(value);
return prm;
}
@Override
public void mouseEntered(MouseEvent e)
{
- // TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e)
{
- // TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e)
{
}
@Override
public void stateChanged(ChangeEvent e)
{
- if (!adjusting)
+ if (adjusting)
{
- float value = slider.getSliderValue();
- valueField.setText(integ ? Integer.toString((int) value)
- : Float.toString(value));
+ return;
+ }
+ try
+ {
+ adjusting = true;
+ if (!isLogarithmicParameter)
+ {
+ /*
+ * set (int or float formatted) text field value
+ */
+ valueField.setText(isIntegerParameter
+ ? String.valueOf(slider.getValue())
+ : formatDouble(
+ slider.getValue() / (float) sliderScaleFactor));
+ }
+ else
+ {
+ double value = Math.pow(Math.E,
+ slider.getValue() / (double) sliderScaleFactor);
+ valueField.setText(formatDouble(value));
+ }
checkIfModified();
+ } finally
+ {
+ adjusting = false;
}
}
- public void updateControls(ParameterI parm)
+ /**
+ * Answers the value formatted as a string to 3 decimal places - in
+ * scientific notation if the value is less than 0.001
+ *
+ * @param value
+ * @return
+ */
+ String formatDouble(double value)
+ {
+ String format = value < 0.001 ? "%3.1E" : "%3.3f";
+ return String.format(format, value);
+ }
+
+ /**
+ * Formats a number as integer or float (3dp) or scientific notation (1dp)
+ *
+ * @param n
+ * @return
+ */
+ String formatNumber(Number n)
+ {
+ return n instanceof Integer ? String.valueOf(n.intValue())
+ : formatDouble(n.doubleValue());
+ }
+
+ void updateControls(ParameterI parm)
{
adjusting = true;
- boolean init = (choicebox == null && valueField == null);
+ boolean init = (choicebox == null && valueField == null
+ && buttonGroup == null);
if (init)
{
- if (choice)
+ if (parm instanceof RadioChoiceParameter)
+ {
+ buttonGroup = addRadioButtons(parameter, controlsPanel);
+ }
+ else if (isChoiceParameter)
{
- choicebox = new JComboBox<>();
+ choicebox = buildComboBox(parm);
choicebox.addActionListener(this);
- controlPanel.add(choicebox, BorderLayout.CENTER);
+ controlsPanel.add(choicebox, BorderLayout.CENTER);
}
else
{
- valueField = new JTextField();
+ slider = new JSlider();
+ slider.addChangeListener(this);
+ int cols = parm instanceof StringParameter ? 20 : 0;
+ valueField = new JTextField(cols);
valueField.addActionListener(this);
- valueField.addKeyListener(new KeyListener()
+ valueField.addKeyListener(new KeyAdapter()
{
- @Override
- public void keyTyped(KeyEvent e)
- {
- }
@Override
public void keyReleased(KeyEvent e)
{
- if (e.isActionKey())
+ int keyCode = e.getKeyCode();
+ if (e.isActionKey() && keyCode != KeyEvent.VK_LEFT
+ && keyCode != KeyEvent.VK_RIGHT)
{
if (valueField.getText().trim().length() > 0)
{
}
}
- @Override
- public void keyPressed(KeyEvent e)
- {
- }
});
- valueField.addFocusListener(new FocusAdapter()
- {
+ valueField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e)
{
actionPerformed(null);
}
-
+
});
- valueField.setPreferredSize(new Dimension(60, 25));
- valueField.setText(parm.getValue());
- slider = makeSlider(parm.getValidValue());
- updateSliderFromValueField();
- slider.addChangeListener(this);
-
- controlPanel.add(slider, BorderLayout.WEST);
- controlPanel.add(valueField, BorderLayout.EAST);
+ valueField.setPreferredSize(new Dimension(65, 25));
+ if (parm instanceof FileParameter)
+ {
+ valueField.setToolTipText(MessageManager
+ .getString("label.double_click_to_browse"));
+ valueField.addMouseListener(new MouseAdapter()
+ {
+ @Override
+ public void mouseClicked(MouseEvent e)
+ {
+ if (e.getClickCount() == 2)
+ {
+ String dir = Cache.getProperty("LAST_DIRECTORY");
+ JalviewFileChooser chooser = new JalviewFileChooser(dir);
+ chooser.setFileView(new JalviewFileView());
+ chooser.setDialogTitle(
+ MessageManager.getString("action.select_ddbb"));
+
+ int val = chooser.showOpenDialog(ParamBox.this);
+ if (val == JalviewFileChooser.APPROVE_OPTION)
+ {
+ File choice = chooser.getSelectedFile();
+ String path = choice.getPath();
+ valueField.setText(path);
+ Cache.setProperty("LAST_DIRECTORY", choice.getParent());
+ FileLoader.updateRecentlyOpened(path,
+ DataSourceType.FILE);
+ }
+ }
+ }
+ });
+ }
+
+ controlsPanel.add(slider, BorderLayout.WEST);
+ controlsPanel.add(valueField, BorderLayout.EAST);
}
}
- if (parm != null)
+ String value = parm.getValue();
+ if (value != null)
{
- if (choice)
+ if (isChoiceParameter)
{
- if (init)
+ if (!(parm instanceof RadioChoiceParameter))
{
- List<String> vals = parm.getPossibleValues();
- for (String val : vals)
- {
- choicebox.addItem(val);
- }
- }
-
- if (parm.getValue() != null)
- {
- choicebox.setSelectedItem(parm.getValue());
+ choicebox.setSelectedItem(value);
}
}
else
{
- valueField.setText(parm.getValue());
+ valueField.setText(value);
}
}
- lastVal = getCurrentValue();
+ lastVal = updateSliderFromValueField();
adjusting = false;
}
- private Slider makeSlider(ValueConstrainI validValue)
+ /**
+ * Adds a panel to comp, containing a label and radio buttons for the choice
+ * of values of the given option. Returns a ButtonGroup whose members are
+ * the added radio buttons.
+ *
+ * @param option
+ * @param comp
+ *
+ * @return
+ */
+ protected ButtonGroup addRadioButtons(OptionI option, Container comp)
{
- if (validValue != null)
+ ButtonGroup bg = new ButtonGroup();
+ JPanel radioPanel = new JPanel();
+ radioPanel.add(new JLabel(option.getDescription()));
+
+ String value = option.getValue();
+
+ for (String opt : option.getPossibleValues())
{
- final Number minValue = validValue.getMin();
- final Number maxValue = validValue.getMax();
- if (minValue != null && maxValue != null)
- {
- return new Slider(minValue.floatValue(), maxValue.floatValue(),
- minValue.floatValue());
- }
+ JRadioButton btn = new JRadioButton(opt);
+ btn.setActionCommand(opt);
+ boolean selected = opt.equals(value);
+ btn.setSelected(selected);
+ btn.addActionListener(this);
+ bg.add(btn);
+ radioPanel.add(btn);
}
+ comp.add(radioPanel);
- /*
- * otherwise, a nominal slider which will not be visible
- */
- return new Slider(0, 100, 50);
+ return bg;
}
- public void updateSliderFromValueField()
+ /**
+ * Action depends on the type of the input parameter:
+ * <ul>
+ * <li>if a text input, returns the trimmed value</li>
+ * <li>if a choice list or radio button, returns the selected value</li>
+ * <li>if a value slider and input field, sets the value of the slider from
+ * the value in the text field, limiting it to any defined min-max
+ * range.</li>
+ * </ul>
+ * Answers the (possibly modified) input value, as a String, Integer, Float
+ * or Double.
+ *
+ * @return
+ */
+ Object updateSliderFromValueField()
{
- if (validator != null)
+ if (validator == null || isStringParameter)
{
- final Number minValue = validator.getMin();
- final Number maxValue = validator.getMax();
- if (integ)
+ if (isChoiceParameter)
{
- int iVal = 0;
- try
+ if (parameter instanceof RadioChoiceParameter)
{
- valueField.setText(valueField.getText().trim());
- iVal = Integer.valueOf(valueField.getText());
- if (minValue != null && minValue.intValue() > iVal)
- {
- iVal = minValue.intValue();
- // TODO: provide visual indication that hard limit was reached for
- // this parameter
- }
- if (maxValue != null && maxValue.intValue() < iVal)
- {
- iVal = maxValue.intValue();
- }
- } catch (NumberFormatException e)
- {
- System.err.println(e.toString());
- }
- if (minValue != null || maxValue != null)
- {
- valueField.setText(String.valueOf(iVal));
- slider.setSliderValue(iVal);
+ return buttonGroup.getSelection().getActionCommand();
}
else
{
- slider.setVisible(false);
+ return getSelectedValue(this.parameter,
+ choicebox.getSelectedIndex());
}
}
+ slider.setVisible(false);
+ return valueField.getText().trim();
+ }
+
+ if (validator.getMin() == null || validator.getMax() == null)
+ {
+ slider.setVisible(false);
+ }
+
+ valueField.setText(valueField.getText().trim());
+
+ /*
+ * ensure not outside min-max range
+ * TODO: provide some visual indicator if limit reached
+ */
+ try
+ {
+ valueField.setBackground(Color.WHITE);
+ double d = Double.parseDouble(valueField.getText());
+ if (validator.getMin() != null
+ && validator.getMin().doubleValue() > d)
+ {
+ valueField.setText(formatNumber(validator.getMin()));
+ }
+ if (validator.getMax() != null
+ && validator.getMax().doubleValue() < d)
+ {
+ valueField.setText(formatNumber(validator.getMax()));
+ }
+ } catch (NumberFormatException e)
+ {
+ valueField.setBackground(Color.yellow);
+ return Float.NaN;
+ }
+ if (isIntegerParameter)
+ {
+ int iVal = 0;
+ try
+ {
+ iVal = Integer.valueOf(valueField.getText());
+ } catch (Exception e)
+ {
+ valueField.setBackground(Color.yellow);
+ return Integer.valueOf(0);
+ }
+
+ if (validator.getMin() != null && validator.getMax() != null)
+ {
+ slider.getModel().setRangeProperties(iVal, 1,
+ validator.getMin().intValue(),
+ validator.getMax().intValue() + 1, true);
+ }
else
{
- float fVal = 0f;
- try
- {
- valueField.setText(valueField.getText().trim());
- fVal = Float.valueOf(valueField.getText());
- if (minValue != null && minValue.floatValue() > fVal)
- {
- fVal = minValue.floatValue();
- // TODO: provide visual indication that hard limit was reached for
- // this parameter
- // update value field to reflect any bound checking we performed.
- valueField.setText("" + fVal);
- }
- if (maxValue != null && maxValue.floatValue() < fVal)
- {
- fVal = maxValue.floatValue();
- // TODO: provide visual indication that hard limit was reached for
- // this parameter
- // update value field to reflect any bound checking we performed.
- valueField.setText("" + fVal);
- }
- } catch (NumberFormatException e)
- {
- System.err.println(e.toString());
- }
- if (minValue != null && maxValue != null)
- {
- slider.setSliderModel(minValue.floatValue(),
- maxValue.floatValue(), fVal);
- }
- else
- {
- slider.setVisible(false);
- }
+ slider.setVisible(false);
}
+ return Integer.valueOf(iVal);
}
-
- else
+ if (isLogarithmicParameter)
{
- if (!choice)
+ double dVal = 0d;
+ try
+ {
+ double eValue = Double.valueOf(valueField.getText());
+ dVal = Math.log(eValue);
+ } catch (Exception e)
+ {
+ // shouldn't be possible here
+ valueField.setBackground(Color.yellow);
+ return Double.NaN;
+ }
+ if (validator.getMin() != null && validator.getMax() != null)
+ {
+ double scaleMin = Math.log(validator.getMin().doubleValue())
+ * sliderScaleFactor;
+ double scaleMax = Math.log(validator.getMax().doubleValue())
+ * sliderScaleFactor;
+ slider.getModel().setRangeProperties(
+ (int) (sliderScaleFactor * dVal), 1,
+ (int) scaleMin, 1 + (int) scaleMax, true);
+ }
+ else
{
slider.setVisible(false);
}
+ return Double.valueOf(dVal);
}
-
+ float fVal = 0f;
+ try
+ {
+ fVal = Float.valueOf(valueField.getText());
+ } catch (Exception e)
+ {
+ return Float.valueOf(0f); // shouldn't happen
+ }
+ if (validator.getMin() != null && validator.getMax() != null)
+ {
+ float scaleMin = validator.getMin().floatValue()
+ * sliderScaleFactor;
+ float scaleMax = validator.getMax().floatValue()
+ * sliderScaleFactor;
+ slider.getModel().setRangeProperties(
+ (int) (fVal * sliderScaleFactor), 1, (int) scaleMin,
+ 1 + (int) scaleMax, true);
+ }
+ else
+ {
+ slider.setVisible(false);
+ }
+ return Float.valueOf(fVal);
}
}
- public static final int PARAM_WIDTH = 340;
-
- public static final int PARAM_HEIGHT = 150;
-
- public static final int PARAM_CLOSEDHEIGHT = 80;
-
- public OptsAndParamsPage(OptsParametersContainerI paramContainer)
- {
- this(paramContainer, false);
- }
+ /**
+ * Constructor with the option to show 'compact' format (parameter description
+ * as tooltip) or 'expanded' format (parameter description in a textbox which
+ * may be opened or closed). Use compact for simple description text, expanded
+ * for more wordy or formatted text.
+ *
+ * @param paramContainer
+ */
public OptsAndParamsPage(OptsParametersContainerI paramContainer,
boolean compact)
mnu.show(invoker, x, y);
}
- URL linkImageURL = getClass().getResource("/images/link.gif");
-
- Map<String, OptionBox> optSet = new java.util.LinkedHashMap<>();
-
- Map<String, ParamBox> paramSet = new java.util.LinkedHashMap<>();
public Map<String, OptionBox> getOptSet()
{
this.paramSet = paramSet;
}
- OptsParametersContainerI poparent;
OptionBox addOption(OptionI opt)
{
}
/**
- * recover options and parameters from GUI
+ * Answers a list of arguments representing all the options and arguments
+ * selected on the dialog, holding their chosen or input values. Optional
+ * parameters which were not selected are not included.
*
* @return
*/
List<ArgumentI> argSet = new ArrayList<>();
for (OptionBox opts : getOptSet().values())
{
- OptionI opt = opts.getOptionIfEnabled();
+ ArgumentI opt = opts.getSelectedOption();
if (opt != null)
{
argSet.add(opt);
}
for (ParamBox parambox : getParamSet().values())
{
- ParameterI parm = parambox.getParameter();
+ ArgumentI parm = parambox.getParameter();
if (parm != null)
{
argSet.add(parm);
return argSet;
}
+ /**
+ * A helper method that constructs and returns a CombBox for choice of the
+ * possible option values. If display names are provided, then these are added
+ * as options, otherwise the actual values are added.
+ *
+ * @param opt
+ * @return
+ */
+ protected static JComboBox<Object> buildComboBox(OptionI opt)
+ {
+ JComboBox<Object> cb = null;
+ List<String> displayNames = opt.getDisplayNames();
+ if (displayNames != null)
+ {
+ List<Object> displayNamesObjects = new ArrayList<>();
+ displayNamesObjects.addAll(displayNames);
+ cb = JvSwingUtils.buildComboWithTooltips(displayNamesObjects,
+ opt.getPossibleValues());
+ }
+ else
+ {
+ cb = new JComboBox<>();
+ for (String v : opt.getPossibleValues())
+ {
+ cb.addItem(v);
+ }
+ }
+ return cb;
+ }
+
+ /**
+ * Answers the value corresponding to the selected item in the choice combo
+ * box. Note that this returns the underlying value even if a different
+ * display name is used in the combo box.
+ *
+ * @return
+ */
+ protected static String getSelectedValue(OptionI opt, int sel)
+ {
+ List<String> possibleValues = opt.getPossibleValues();
+ String value = null;
+ if (possibleValues != null && possibleValues.size() == 1)
+ {
+ // Hack to make sure the default value for an enabled option with only
+ // one value is actually returned even if this.val is not displayed
+ value = possibleValues.get(0);
+ }
+ else if (sel >= 0 && sel < possibleValues.size())
+ {
+ value = possibleValues.get(sel);
+ }
+ return value;
+ }
}
*/
package jalview.gui;
+import jalview.api.AlignViewportI;
import jalview.bin.Cache;
import jalview.renderer.OverviewRenderer;
import jalview.util.MessageManager;
private OverviewCanvas oviewCanvas;
- protected AlignViewport av;
+ private AlignViewportI av;
private AlignmentPanel ap;
protected boolean draggingBox = false;
+ private Dimension dim;
+
+ private boolean showProgress = !Platform.isJS();
-
protected ProgressPanel progressPanel;
+
/**
- * Creates a new OverviewPanel object.
- *
- * @param alPanel
- * The alignment panel which is shown in the overview panel
+ * Creates the appropriate type of OverviewDimensions, with the desired size
*/
- public OverviewPanel(AlignmentPanel alPanel)
+ private void createOverviewDimensions()
{
- this.av = alPanel.av;
- this.ap = alPanel;
-
- showHidden = Cache.getDefault(Preferences.SHOW_OV_HIDDEN_AT_START,
- false);
+ boolean showAnnotation = (av.isShowAnnotation()
+ && av.getAlignmentConservationAnnotation() != null);
if (showHidden)
{
- od = new OverviewDimensionsShowHidden(av.getRanges(),
- (av.isShowAnnotation()
- && av.getAlignmentConservationAnnotation() != null));
+ od = new OverviewDimensionsShowHidden(av.getRanges(), showAnnotation,
+ dim);
}
else
{
- od = new OverviewDimensionsHideHidden(av.getRanges(),
- (av.isShowAnnotation()
- && av.getAlignmentConservationAnnotation() != null));
+ od = new OverviewDimensionsHideHidden(av.getRanges(), showAnnotation,
+ dim);
}
+ }
+
+ public OverviewPanel(AlignmentPanel alPanel, Dimension dim)
+ {
+ this.av = alPanel.av;
+ this.ap = alPanel;
+ this.dim = dim;
+ showHidden = Cache.getDefault(Preferences.SHOW_OV_HIDDEN_AT_START,
+ false);
+ createOverviewDimensions();
setLayout(new BorderLayout());
progressPanel = new ProgressPanel(OverviewRenderer.UPDATE,
MessageManager.getString("label.oview_calc"), getWidth());
// without this the overview window does not size to fit the overview canvas
setPreferredSize(new Dimension(od.getWidth(), od.getHeight()));
-
+
addComponentListener(new ComponentAdapter()
{
@Override
@Override
public void mousePressed(MouseEvent evt)
{
-
- if (Platform.isWinRightButton(evt))
- {
- showPopupMenu(evt);
- return;
- }
- if (SwingUtilities.isRightMouseButton(evt))
- {
- return;
+
+ if (Platform.isWinRightButton(evt)) {
+ showPopupMenu(evt);
+ return;
+ }
+ if (SwingUtilities.isRightMouseButton(evt)) {
+ return;
}
- // don't do anything if the mouse press is in the overview's box
- // (wait to see if it's a drag instead)
- // otherwise update the viewport
- if (!od.isPositionInBox(evt.getX(), evt.getY()))
- {
- draggingBox = false;
+ // don't do anything if the mouse press is in the overview's box
+ // (wait to see if it's a drag instead)
+ // otherwise update the viewport
+ if (!od.isPositionInBox(evt.getX(), evt.getY()))
+ {
+ draggingBox = false;
- // display drag cursor at mouse position
- setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
+ // display drag cursor at mouse position
+ setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
- od.updateViewportFromMouse(evt.getX(), evt.getY(),
- av.getAlignment().getHiddenSequences(),
- av.getAlignment().getHiddenColumns());
- getParent().setCursor(
- Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
- }
- else
- {
- draggingBox = true;
- od.setDragPoint(evt.getX(), evt.getY(),
- av.getAlignment().getHiddenSequences(),
- av.getAlignment().getHiddenColumns());
- }
+ od.updateViewportFromMouse(evt.getX(), evt.getY(),
+ av.getAlignment().getHiddenSequences(),
+ av.getAlignment().getHiddenColumns());
+ getParent().setCursor(
+ Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
+ }
+ else
+ {
+ draggingBox = true;
+ od.setDragPoint(evt.getX(), evt.getY(),
+ av.getAlignment().getHiddenSequences(),
+ av.getAlignment().getHiddenColumns());
+ }
}
@Override
*/
protected void toggleHiddenColumns()
{
- if (showHidden)
- {
- showHidden = false;
- od = new OverviewDimensionsHideHidden(av.getRanges(),
- (av.isShowAnnotation()
- && av.getAlignmentConservationAnnotation() != null));
- }
- else
- {
- showHidden = true;
- od = new OverviewDimensionsShowHidden(av.getRanges(),
- (av.isShowAnnotation()
- && av.getAlignmentConservationAnnotation() != null));
- }
+ showHidden = !showHidden;
+ createOverviewDimensions();
oviewCanvas.resetOviewDims(od);
updateOverviewImage();
setBoxPosition();
od.setWidth(getWidth());
od.setHeight(getHeight() - progressPanel.getHeight());
}
-
+
setPreferredSize(new Dimension(od.getWidth(),
od.getHeight() + progressPanel.getHeight()));
thread.start();
repaint();
+
}
@Override
* close the parent frame (which also removes it from the
* Desktop Windows menu)
*/
- ((JInternalFrame) SwingUtilities
- .getAncestorOfClass(JInternalFrame.class, (this)))
- .setClosed(true);
+ ((JInternalFrame) SwingUtilities.getAncestorOfClass(
+ JInternalFrame.class, (this))).setClosed(true);
} catch (PropertyVetoException e)
{
// ignore
import jalview.api.AlignViewportI;
import jalview.api.analysis.ScoreModelI;
import jalview.api.analysis.SimilarityParamsI;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.AlignmentView;
import jalview.math.RotatableMatrix.Axis;
import jalview.util.ImageMaker;
import jalview.util.MessageManager;
+import jalview.util.Platform;
import jalview.viewmodel.AlignmentViewport;
import jalview.viewmodel.PCAModel;
ScoreModelI scoreModel = ScoreModels.getInstance()
.getScoreModel(modelName, ap);
- setPcaModel(new PCAModel(seqstrings, seqs, nucleotide, scoreModel,
- params));
+ setPcaModel(
+ new PCAModel(seqstrings, seqs, nucleotide, scoreModel, params));
PaintRefresher.Register(this, av.getSequenceSetId());
setRotatableCanvas(new RotatableCanvas(alignPanel));
repaint();
if (getParent() == null)
{
- Desktop.addInternalFrame(this,
- MessageManager.formatMessage("label.calc_title", "PCA",
- getPcaModel().getScoreModelName()),
- 475, 450);
+ addToDesktop(this, getPcaModel().getScoreModelName());
this.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
}
working = false;
// JAL-2647 disabled after load from project (until save to project done)
if (getPcaModel().getInputData() == null)
{
- Cache.log.info(
+ Console.info(
"Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
return;
}
@Override
public void exportImage(Graphics g) throws Exception
{
- RotatableCanvas canvas = getRotatableCanvas();
- canvas.drawBackground(g);
- canvas.drawScene(g);
+ RotatableCanvas canvas = getRotatableCanvas();
+ canvas.drawBackground(g);
+ canvas.drawScene(g);
if (canvas.drawAxes)
{
canvas.drawAxes(g);
// // setMenusForViewport();
// validate();
}
+
+ @Override
+ public void removeProgressBar(long id)
+ {
+ progressBar.removeProgressBar(id);
+ }
@Override
public void registerHandler(final long id,
final IProgressIndicatorHandler handler)
{
progressBar.registerHandler(id, handler);
- // if (progressBarHandlers == null || !progressBars.contains(Long.valueOf(id)))
+ // if (progressBarHandlers == null ||
+ // !progressBars.contains(Long.valueOf(id)))
// {
// throw new
// Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
getRotatableCanvas().ap = panel;
PaintRefresher.Register(PCAPanel.this, panel.av.getSequenceSetId());
}
+
+ public static void addToDesktop(PCAPanel panel, String modelName)
+ {
+ Dimension dim = Platform.getDimIfEmbedded(panel, 475, 450);
+ Desktop.addInternalFrame(panel, MessageManager.formatMessage(
+ "label.calc_title", "PCA", modelName), dim.width,
+ dim.height);
+ }
}
package jalview.gui;
import jalview.analysis.AlignSeq;
+import jalview.api.AlignViewportI;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentView;
import jalview.datamodel.SequenceGroup;
import jalview.datamodel.SequenceI;
import jalview.jbgui.GPairwiseAlignPanel;
import jalview.util.MessageManager;
-import jalview.viewmodel.AlignmentViewport;
import java.awt.event.ActionEvent;
import java.util.Vector;
private static final String DASHES = "---------------------\n";
- AlignmentViewport av;
+ AlignViewportI av;
Vector<SequenceI> sequences;
* Creates a new PairwiseAlignPanel object.
*
* @param viewport
- * DOCUMENT ME!
*/
- public PairwiseAlignPanel(AlignmentViewport viewport)
+ public PairwiseAlignPanel(AlignViewportI viewport)
{
super();
this.av = viewport;
- sequences = new Vector<SequenceI>();
+ sequences = new Vector<>();
SequenceGroup selectionGroup = viewport.getSelectionGroup();
boolean isSelection = selectionGroup != null
&& selectionGroup.getSize() > 0;
AlignmentView view = viewport.getAlignmentView(isSelection);
// String[] seqStrings = viewport.getViewAsString(true);
- String[] seqStrings = view.getSequenceStrings(viewport
- .getGapCharacter());
+ String[] seqStrings = view
+ .getSequenceStrings(viewport.getGapCharacter());
SequenceI[] seqs;
if (isSelection)
{
- seqs = (SequenceI[]) view.getAlignmentAndHiddenColumns(viewport
- .getGapCharacter())[0];
+ seqs = (SequenceI[]) view
+ .getAlignmentAndHiddenColumns(viewport.getGapCharacter())[0];
}
else
{
}
first = false;
as.printAlignment(System.out);
- scores[i][j] = as.getMaxScore()
- / as.getASeq1().length;
+ scores[i][j] = as.getMaxScore() / as.getASeq1().length;
totscore = totscore + scores[i][j];
textarea.append(as.getOutput());
for (int i = 0; i < seqs.length; i++)
{
- System.out.println(String.format("%3d %s", i + 1,
- seqs[i].getDisplayId(true)));
+ System.out.println(
+ String.format("%3d %s", i + 1, seqs[i].getDisplayId(true)));
}
/*
import jalview.analysis.AlignmentUtils;
import jalview.analysis.Conservation;
import jalview.api.AlignViewportI;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.commands.ChangeCaseCommand;
import jalview.commands.EditCommand;
import jalview.commands.EditCommand.Action;
import jalview.datamodel.HiddenColumns;
import jalview.datamodel.MappedFeatures;
import jalview.datamodel.PDBEntry;
+import jalview.datamodel.ResidueCount;
import jalview.datamodel.SequenceFeature;
import jalview.datamodel.SequenceGroup;
import jalview.datamodel.SequenceI;
import jalview.gui.ColourMenuHelper.ColourChangeListener;
import jalview.gui.JalviewColourChooser.ColourChooserListener;
+import jalview.io.CountReader;
import jalview.io.FileFormatI;
import jalview.io.FileFormats;
import jalview.io.FormatAdapter;
import jalview.util.UrlLink;
import jalview.viewmodel.seqfeatures.FeatureRendererModel;
+import java.io.IOException;
+import java.net.MalformedURLException;
-
/**
* The popup menu that is displayed on right-click on a sequence id, or in the
* sequence alignment.
urlLink = new UrlLink(link);
} catch (Exception foo)
{
- Cache.log.error("Exception for URLLink '" + link + "'", foo);
+ Console.error("Exception for URLLink '" + link + "'", foo);
continue;
}
if (!urlLink.isValid())
{
- Cache.log.error(urlLink.getInvalidMessage());
+ Console.error(urlLink.getInvalidMessage());
continue;
}
jalview.util.BrowserLauncher.openURL(url);
} catch (Exception ex)
{
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
MessageManager.getString("label.web_browser_not_found_unix"),
MessageManager.getString("label.web_browser_not_found"),
JvOptionPane.WARNING_MESSAGE);
}
/**
- * Constructor for a PopupMenu for a click in the alignment panel (on a
- * residue)
+ * Constructor for a PopupMenu for a click in the alignment panel (on a residue)
*
* @param ap
- * the panel in which the mouse is clicked
+ * the panel in which the mouse is clicked
* @param seq
- * the sequence under the mouse
+ * the sequence under the mouse
* @throws NullPointerException
- * if seq is null
+ * if seq is null
*/
public PopupMenu(final AlignmentPanel ap, SequenceI seq, int column)
{
* Constructor for a PopupMenu for a click in the sequence id panel
*
* @param alignPanel
- * the panel in which the mouse is clicked
+ * the panel in which the mouse is clicked
* @param seq
- * the sequence under the mouse click
+ * the sequence under the mouse click
* @param groupLinks
- * templates for sequence external links
+ * templates for sequence external links
* @throws NullPointerException
- * if seq is null
+ * if seq is null
*/
public PopupMenu(final AlignmentPanel alignPanel, final SequenceI seq,
List<String> groupLinks)
* @param alignPanel
* @param seq
* @param column
- * aligned column position (0...)
+ * aligned column position (0...)
* @param groupLinks
*/
- private PopupMenu(boolean fromIdPanel, final AlignmentPanel alignPanel,
+ private PopupMenu(boolean fromIdPanel,
+ final AlignmentPanel alignPanel,
final SequenceI seq, final int column, List<String> groupLinks)
{
Objects.requireNonNull(seq);
/*
* And repeat for the current selection group (if there is one):
*/
- final List<SequenceI> selectedGroup = (alignPanel.av
- .getSelectionGroup() == null
- ? Collections.<SequenceI> emptyList()
- : alignPanel.av.getSelectionGroup().getSequences());
+ final List<SequenceI> selectedGroup = (alignPanel.av.getSelectionGroup() == null
+ ? Collections.<SequenceI> emptyList()
+ : alignPanel.av.getSelectionGroup().getSequences());
buildAnnotationTypesMenus(groupShowAnnotationsMenu,
groupHideAnnotationsMenu, selectedGroup);
configureReferenceAnnotationsMenu(groupAddReferenceAnnotations,
}
}
+ if (seq.hasHMMProfile())
+ {
+ menuItem = new JMenuItem(MessageManager
+ .getString("action.add_background_frequencies"));
+ menuItem.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ try
+ {
+ ResidueCount counts = CountReader.getBackgroundFrequencies(ap,
+ seq);
+ if (counts != null)
+ {
+ seq.getHMM().setBackgroundFrequencies(counts);
+ ap.alignFrame.buildColourMenu();
+ }
+ } catch (MalformedURLException e1)
+ {
+ e1.printStackTrace();
+ } catch (IOException e1)
+ {
+ e1.printStackTrace();
+ }
+ }
+ });
+ add(menuItem);
+ }
-
menuItem = new JMenuItem(
MessageManager.getString("action.hide_sequences"));
menuItem.addActionListener(new ActionListener()
{
buildGroupURLMenu(sg, groupLinks);
}
++ // TODO REMOVE FOR 2.12 ?
// Add a 'show all structures' for the current selection
- Hashtable<String, PDBEntry> pdbe = new Hashtable<>(),
- reppdb = new Hashtable<>();
+ Hashtable<String, PDBEntry> pdbe = new Hashtable<>();
+ Hashtable<String, PDBEntry> reppdb = new Hashtable<>();
SequenceI sqass = null;
for (SequenceI sq : alignPanel.av.getSequenceSelection())
{
createGroupMenuItem.setVisible(true);
unGroupMenuItem.setVisible(false);
- editGroupMenu
- .setText(MessageManager.getString("action.edit_new_group"));
+ editGroupMenu.setText(MessageManager.getString("action.edit_new_group"));
}
else
{
* <li>positional feature links (alignment panel popup menu)</li>
* <li>feature details links (alignment panel popup menu)</li>
* </ul>
- * If this panel is also showed complementary (CDS/protein) features, then
- * links to their feature details are also added.
+ * If this panel is also showed complementary (CDS/protein) features, then links
+ * to their feature details are also added.
*
* @param seq
* @param column
/*
* show local rather than linked feature coordinates
*/
- int[] beginRange = mf.getMappedPositions(start, start);
- start = beginRange[0];
- int[] endRange = mf.getMappedPositions(end, end);
- end = endRange[endRange.length - 1];
+ int[] localRange = mf.getMappedPositions(start, end);
+ if (localRange == null)
+ {
+ // e.g. variant extending to stop codon so not mappable
+ return;
+ }
+ start = localRange[0];
+ end = localRange[localRange.length - 1];
}
StringBuilder desc = new StringBuilder();
desc.append(sf.getType()).append(" ").append(String.valueOf(start));
if (((String[]) sarray[1])[sq] == null)
{
- if (!e.hasMap()
- || (e.getMap().locateMappedRange(start, end) != null))
+ if (!e.hasMap() || (e.getMap()
+ .locateMappedRange(start, end) != null))
{
((String[]) sarray[1])[sq] = e.getAccessionId();
((int[]) sarray[0])[0]++;
urlLink = new GroupUrlLink(link);
} catch (Exception foo)
{
- Cache.log.error("Exception for GroupURLLink '" + link + "'", foo);
+ Console.error("Exception for GroupURLLink '" + link + "'", foo);
continue;
}
if (!urlLink.isValid())
{
- Cache.log.error(urlLink.getInvalidMessage());
+ Console.error(urlLink.getInvalidMessage());
continue;
}
final String label = urlLink.getLabel();
menuItem.setEnabled(true);
for (String calcId : tipEntries.keySet())
{
- tooltip.append("<br>" + calcId + "/" + tipEntries.get(calcId));
+ tooltip.append("<br/>" + calcId + "/" + tipEntries.get(calcId));
}
String tooltipText = JvSwingUtils.wrapTooltip(true,
tooltip.toString());
}
inserts.and(sq.getInsertionsAsBits());
}
- hidden.clearAndHideColumns(inserts,
- ap.av.getSelectionGroup().getStartRes(),
+ hidden.clearAndHideColumns(inserts, ap.av.getSelectionGroup().getStartRes(),
ap.av.getSelectionGroup().getEndRes());
}
contents.append("<p><h2>" + MessageManager.formatMessage(
"label.create_sequence_details_report_annotation_for",
new Object[]
- { seq.getDisplayId(true) }) + "</h2></p><p>");
+ { seq.getDisplayId(true) }) + "</h2></p>\n<p>");
new SequenceAnnotationReport(false).createSequenceAnnotationReport(
contents, seq, true, true, ap.getSeqPanel().seqCanvas.fr);
contents.append("</p>");
/**
* Shows a dialog where the sequence name and description may be edited. If a
- * name containing spaces is entered, these are converted to underscores, with
- * a warning message.
+ * name containing spaces is entered, these are converted to underscores, with a
+ * warning message.
*/
void sequenceName_actionPerformed()
{
sequence.getDescription(),
MessageManager.getString("label.sequence_name"),
MessageManager.getString("label.sequence_description"));
- dialog.showDialog(ap.alignFrame, MessageManager.getString(
- "label.edit_sequence_name_description"), new Runnable()
+ dialog.showDialog(ap.alignFrame,
+ MessageManager.getString(
+ "label.edit_sequence_name_description"),
+ new Runnable()
{
@Override
public void run()
ap.paintAlignment(false, false);
}
sequence.setDescription(dialog.getDescription());
- ap.av.firePropertyChange("alignment", null,
- ap.av.getAlignment().getSequences());
+ ap.av.notifyAlignment();
}
});
}
*/
protected void outline_actionPerformed()
{
- String title = MessageManager.getString("label.select_outline_colour");
+ String title = MessageManager
+ .getString("label.select_outline_colour");
ColourChooserListener listener = new ColourChooserListener()
{
@Override
refresh();
}
};
- JalviewColourChooser.showColourChooser(Desktop.getDesktop(), title,
- Color.BLUE, listener);
+ JalviewColourChooser.showColourChooser(Desktop.getDesktopPane(),
+ title, Color.BLUE, listener);
}
/**
startEnd, caseChange);
ap.alignFrame.addHistoryItem(caseCommand);
+ ap.av.notifyAlignment();
- ap.av.firePropertyChange("alignment", null,
- ap.av.getAlignment().getSequences());
}
}
sg.getStartRes(), sg.getEndRes() + 1,
ap.av.getAlignment());
ap.alignFrame.addHistoryItem(editCommand);
- ap.av.firePropertyChange("alignment", null,
- ap.av.getAlignment().getSequences());
+ ap.av.notifyAlignment();
}
});
}
*/
package jalview.gui;
-
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
+import java.awt.event.FocusAdapter;
+import java.awt.event.FocusEvent;
+import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.help.HelpSetException;
import javax.swing.JComboBox;
+import javax.swing.JFileChooser;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
+import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.RowSorter;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
-//import edu.stanford.ejalbert.launching.IBrowserLaunching;
+import jalview.hmmer.HmmerCommand;
+import jalview.util.FileUtils;
import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
import jalview.analysis.AnnotationSorter.SequenceAnnotationOrder;
++import jalview.bin.ApplicationSingletonProvider;
++import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
import jalview.bin.Cache;
+ import jalview.bin.Console;
+ import jalview.bin.MemorySetting;
import jalview.ext.pymol.PymolManager;
import jalview.gui.Help.HelpId;
import jalview.gui.StructureViewer.ViewerType;
* @author $author$
* @version $Revision$
*/
-
-/*
- * for merge with Jalview-JS
- public class Preferences extends GPreferences implements ApplicationSingletonI
- */
-public class Preferences extends GPreferences
+public class Preferences extends GPreferences implements ApplicationSingletonI
{
- public static final String ENABLE_SPLIT_FRAME = "ENABLE_SPLIT_FRAME";
+ // suggested list delimiter character
+ public static final String COMMA = ",";
- public static final String SCALE_PROTEIN_TO_CDNA = "SCALE_PROTEIN_TO_CDNA";
-
- public static final String DEFAULT_COLOUR = "DEFAULT_COLOUR";
+ public static final String HMMSEARCH_SEQCOUNT = "HMMSEARCH_SEQCOUNT";
- public static final String DEFAULT_COLOUR_PROT = "DEFAULT_COLOUR_PROT";
+ public static final String HMMINFO_GLOBAL_BACKGROUND = "HMMINFO_GLOBAL_BACKGROUND";
- public static final String DEFAULT_COLOUR_NUC = "DEFAULT_COLOUR_NUC";
+ public static final String HMMALIGN_TRIM_TERMINI = "HMMALIGN_TRIM_TERMINI";
+
+ public static final String ADD_SS_ANN = "ADD_SS_ANN";
public static final String ADD_TEMPFACT_ANN = "ADD_TEMPFACT_ANN";
- public static final String ADD_SS_ANN = "ADD_SS_ANN";
+ public static final String ALLOW_UNPUBLISHED_PDB_QUERYING = "ALLOW_UNPUBLISHED_PDB_QUERYING";
- public static final String USE_RNAVIEW = "USE_RNAVIEW";
+ public static final String ANNOTATIONCOLOUR_MAX = "ANNOTATIONCOLOUR_MAX";
- public static final String STRUCT_FROM_PDB = "STRUCT_FROM_PDB";
+ public static final String ANNOTATIONCOLOUR_MIN = "ANNOTATIONCOLOUR_MIN";
- public static final String STRUCTURE_DISPLAY = "STRUCTURE_DISPLAY";
+ public static final String ANTI_ALIAS = "ANTI_ALIAS";
+
+ public static final String AUTO_CALC_CONSENSUS = "AUTO_CALC_CONSENSUS";
+
+ public static final String AUTOASSOCIATE_PDBANDSEQS = "AUTOASSOCIATE_PDBANDSEQS";
+
+ public static final String BLOSUM62_PCA_FOR_NUCLEOTIDE = "BLOSUM62_PCA_FOR_NUCLEOTIDE";
+
+ public static final String CENTRE_COLUMN_LABELS = "CENTRE_COLUMN_LABELS";
public static final String CHIMERA_PATH = "CHIMERA_PATH";
public static final String CHIMERAX_PATH = "CHIMERAX_PATH";
+ public static final String DBREFFETCH_USEPICR = "DBREFFETCH_USEPICR";
+
+ public static final String DEFAULT_COLOUR = "DEFAULT_COLOUR";
+
+ public static final String DEFAULT_COLOUR_NUC = "DEFAULT_COLOUR_NUC";
+ public static final String DEFAULT_COLOUR_PROT = "DEFAULT_COLOUR_PROT";
+
+ public static final String ENABLE_SPLIT_FRAME = "ENABLE_SPLIT_FRAME";
+
+ public static final String FIGURE_AUTOIDWIDTH = "FIGURE_AUTOIDWIDTH";
+
+ public static final String FIGURE_FIXEDIDWIDTH = "FIGURE_FIXEDIDWIDTH";
+
+ public static final String FOLLOW_SELECTIONS = "FOLLOW_SELECTIONS";
+
+ public static final String FONT_NAME = "FONT_NAME";
+
+ public static final String FONT_SIZE = "FONT_SIZE";
+
+ public static final String FONT_STYLE = "FONT_STYLE";
+
+ public static final String HMMER_PATH = "HMMER_PATH";
+
+ public static final String CYGWIN_PATH = "CYGWIN_PATH";
+
+ public static final String HMMSEARCH_DBS = "HMMSEARCH_DBS";
+
+ public static final String GAP_COLOUR = "GAP_COLOUR";
+
+ public static final String GAP_SYMBOL = "GAP_SYMBOL";
+
+ public static final String HIDDEN_COLOUR = "HIDDEN_COLOUR";
+
+ public static final String HIDE_INTRONS = "HIDE_INTRONS";
+
+ public static final String ID_ITALICS = "ID_ITALICS";
+
+ public static final String ID_ORG_HOSTURL = "ID_ORG_HOSTURL";
+
+ public static final String MAP_WITH_SIFTS = "MAP_WITH_SIFTS";
+
+ public static final String NOQUESTIONNAIRES = "NOQUESTIONNAIRES";
+
+ public static final String NORMALISE_CONSENSUS_LOGO = "NORMALISE_CONSENSUS_LOGO";
+
+ public static final String NORMALISE_LOGO = "NORMALISE_LOGO";
+
+ public static final String PAD_GAPS = "PAD_GAPS";
+
+ public static final String PDB_DOWNLOAD_FORMAT = "PDB_DOWNLOAD_FORMAT";
-
public static final String PYMOL_PATH = "PYMOL_PATH";
- public static final String SORT_ANNOTATIONS = "SORT_ANNOTATIONS";
+ public static final String QUESTIONNAIRE = "QUESTIONNAIRE";
+
+ public static final String RELAXEDSEQIDMATCHING = "RELAXEDSEQIDMATCHING";
+
+ public static final String RIGHT_ALIGN_IDS = "RIGHT_ALIGN_IDS";
+
+ public static final String SCALE_PROTEIN_TO_CDNA = "SCALE_PROTEIN_TO_CDNA";
+
+ public static final String SHOW_ANNOTATIONS = "SHOW_ANNOTATIONS";
public static final String SHOW_AUTOCALC_ABOVE = "SHOW_AUTOCALC_ABOVE";
+ public static final String SHOW_CONSENSUS = "SHOW_CONSENSUS";
+
+ public static final String SHOW_CONSENSUS_HISTOGRAM = "SHOW_CONSENSUS_HISTOGRAM";
+
+ public static final String SHOW_CONSENSUS_LOGO = "SHOW_CONSENSUS_LOGO";
+
+ public static final String SHOW_CONSERVATION = "SHOW_CONSERVATION";
+
+ public static final String SHOW_DBREFS_TOOLTIP = "SHOW_DBREFS_TOOLTIP";
+
+ public static final String SHOW_GROUP_CONSENSUS = "SHOW_GROUP_CONSENSUS";
+
+ public static final String SHOW_GROUP_CONSERVATION = "SHOW_GROUP_CONSERVATION";
+
+ public static final String SHOW_JVSUFFIX = "SHOW_JVSUFFIX";
+
+ public static final String SHOW_NPFEATS_TOOLTIP = "SHOW_NPFEATS_TOOLTIP";
public static final String SHOW_OCCUPANCY = "SHOW_OCCUPANCY";
public static final String SHOW_OV_HIDDEN_AT_START = "SHOW_OV_HIDDEN_AT_START";
+ public static final String SHOW_OVERVIEW = "SHOW_OVERVIEW";
+
+ public static final String SHOW_QUALITY = "SHOW_QUALITY";
+
+ public static final String SHOW_UNCONSERVED = "SHOW_UNCONSERVED";
+
+ public static final String SORT_ALIGNMENT = "SORT_ALIGNMENT";
+
+ public static final String SORT_ANNOTATIONS = "SORT_ANNOTATIONS";
+
+ public static final String SORT_BY_TREE = "SORT_BY_TREE";
+
+ public static final String STRUCT_FROM_PDB = "STRUCT_FROM_PDB";
+
+ public static final String STRUCTURE_DISPLAY = "STRUCTURE_DISPLAY";
+
+ public static final String STRUCTURE_DIMENSIONS = "STRUCTURE_DIMENSIONS";
+
+ public static final String UNIPROT_DOMAIN = "UNIPROT_DOMAIN";
+
+ public static final String USE_FULL_SO = "USE_FULL_SO";
public static final String USE_LEGACY_GAP = "USE_LEGACY_GAP";
- public static final String GAP_COLOUR = "GAP_COLOUR";
+ public static final String USE_RNAVIEW = "USE_RNAVIEW";
- public static final String HIDDEN_COLOUR = "HIDDEN_COLOUR";
+ public static final String USER_DEFINED_COLOURS = "USER_DEFINED_COLOURS";
+
+ public static final String WRAP_ALIGNMENT = "WRAP_ALIGNMENT";
private static final int MIN_FONT_SIZE = 1;
private String previousProxyType;
private static Preferences INSTANCE = null; // add "final"
+
/**
* Holds name and link separated with | character. Sequence ID must be
* $SEQUENCE_ID$ or $SEQUENCE_ID=/.possible | chars ./=$
/**
* Holds name and link separated with | character. Sequence IDS and Sequences
- * must be $SEQUENCEIDS$ or $SEQUENCEIDS=/.possible | chars ./=$ and
- * $SEQUENCES$ or $SEQUENCES=/.possible | chars ./=$ and separation character
- * for first and second token specified after a pipe character at end |,|.
- * (TODO: proper escape for using | to separate ids or sequences
+ * must be $SEQUENCEIDS$ or $SEQUENCEIDS=/.possible | chars ./=$ and $SEQUENCES$
+ * or $SEQUENCES=/.possible | chars ./=$ and separation character for first and
+ * second token specified after a pipe character at end |,|. (TODO: proper
+ * escape for using | to separate ids or sequences
*/
public static List<String> groupURLLinks;
private WsPreferences wsPrefs;
+ private SlivkaPreferences slivkaPrefs;
private OptionsParam promptEachTimeOpt = new OptionsParam(
MessageManager.getString("label.prompt_each_time"),
"Prompt each time");
this.setMessage(message);
this.frame.show();
}
+
/**
* Creates a new Preferences object.
*/
wsPrefs = new WsPreferences();
wsTab.add(wsPrefs, BorderLayout.CENTER);
}
+
+ slivkaPrefs = new SlivkaPreferences();
+ slivkaTab.add(slivkaPrefs, BorderLayout.CENTER);
+
int width = 500, height = 450;
if (Platform.isAMacAndNotJS())
{
frame.setMinimumSize(new Dimension(width, height));
/*
+ * Set HMMER tab defaults
+ */
+ hmmrTrimTermini.setSelected(Cache.getDefault(HMMALIGN_TRIM_TERMINI, false));
+ if (Cache.getDefault(HMMINFO_GLOBAL_BACKGROUND, false))
+ {
+ hmmerBackgroundUniprot.setSelected(true);
+ }
+ else
+ {
+ hmmerBackgroundAlignment.setSelected(true);
+ }
+ hmmerSequenceCount
+ .setText(Cache.getProperty(HMMSEARCH_SEQCOUNT));
+ hmmerPath.setText(Cache.getProperty(HMMER_PATH));
+ hmmerPath.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ validateHmmerPath();
+ }
+ });
+ hmmerPath.addFocusListener(new FocusAdapter()
+ {
+ @Override
+ public void focusLost(FocusEvent e)
+ {
+ validateHmmerPath();
+ }
+ });
+ if (cygwinPath != null)
+ {
+ String path = Cache.getProperty(CYGWIN_PATH);
+ if (path == null)
+ {
+ path = FileUtils.getPathTo("bash");
+ }
+ cygwinPath.setText(path);
+ cygwinPath.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ validateCygwinPath();
+ }
+ });
+ cygwinPath.addFocusListener(new FocusAdapter()
+ {
+ @Override
+ public void focusLost(FocusEvent e)
+ {
+ validateCygwinPath();
+ }
+ });
+ }
+
+ /*
* Set Visual tab defaults
*/
seqLimit.setSelected(Cache.getDefault("SHOW_JVSUFFIX", true));
Cache.getDefault("SHOW_CONSENSUS_HISTOGRAM", true));
showConsensLogo
.setSelected(Cache.getDefault("SHOW_CONSENSUS_LOGO", false));
+ showInformationHistogram.setSelected(
+ Cache.getDefault("SHOW_INFORMATION_HISTOGRAM", true));
+ showHMMLogo.setSelected(Cache.getDefault("SHOW_HMM_LOGO", false));
showNpTooltip
.setSelected(Cache.getDefault("SHOW_NPFEATS_TOOLTIP", true));
showDbRefTooltip
addSecondaryStructure.setEnabled(structSelected);
addTempFactor.setSelected(Cache.getDefault(ADD_TEMPFACT_ANN, true));
addTempFactor.setEnabled(structSelected);
+
/*
* set choice of structure viewer, and path if saved as a preference;
* default to Jmol (first choice) if an unexpected value is found
*/
- String viewerType = Cache.getDefault(STRUCTURE_DISPLAY,
+ String viewerType = ViewerType.JMOL.name();
+ if (!Platform.isJS())
+ {
+ Cache.getDefault(STRUCTURE_DISPLAY,
ViewerType.JMOL.name());
+ }
+ // TODO - disable external viewers for JS
structViewer.setSelectedItem(viewerType);
String viewerPath = "";
ViewerType type = null;
}
} catch (IllegalArgumentException e)
{
- Cache.log.error("Unknown structure viewer type: " + viewerType
+ Console.error("Unknown structure viewer type: " + viewerType
+ ", defaulting to Jmol");
type = ViewerType.JMOL;
}
if (validateViewerPath())
{
String path = structureViewerPath.getText();
- try {
- ViewerType type = ViewerType.valueOf(viewerType);
- switch (type)
+ try
+ {
+ ViewerType type = ViewerType.valueOf(viewerType);
+ switch (type)
+ {
+ case JMOL:
+ break;
+ case CHIMERA:
+ Cache.setProperty(CHIMERA_PATH, path);
+ break;
+ case CHIMERAX:
+ Cache.setProperty(CHIMERAX_PATH, path);
+ break;
+ case PYMOL:
+ Cache.setProperty(PYMOL_PATH, path);
+ break;
+ }
+ } catch (IllegalArgumentException x)
{
- case JMOL:
- break;
- case CHIMERA:
- Cache.setProperty(CHIMERA_PATH, path);
- break;
- case CHIMERAX:
- Cache.setProperty(CHIMERAX_PATH, path);
- break;
- case PYMOL:
- Cache.setProperty(PYMOL_PATH, path);
- break;
+ Console.error("Failed to set path - unknown viewer type", x);
}
- } catch (IllegalArgumentException x)
- {
- Cache.log.error("Failed to set path - unknown viewer type",x);
- }
}
}
});
proxyType.setSelected(customProxy.getModel(), true);
break;
default:
- Cache.log.warn(
+ Console.warn(
"Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
+ proxyTypeString);
}
setCustomProxyEnabled();
applyProxyButtonEnabled(false);
+ defaultBrowser.setText(Cache.getDefault("DEFAULT_BROWSER", ""));
+
usagestats.setSelected(Cache.getDefault("USAGESTATS", false));
// note antisense here: default is true
questionnaire
annotations_actionPerformed(null); // update the display of the annotation
// settings
+
+
+
/*
* Set Backups tab defaults
*/
loadLastSavedBackupsOptions();
-
- /*
- * Set Startup tab defaults
- */
-
}
/**
comboBox.addItem(promptEachTimeOpt);
comboBox.addItem(lineArtOpt);
comboBox.addItem(textOpt);
+
+
/*
* JalviewJS doesn't support Lineart so force it to Text
*/
* Set proxy settings first (to be before web services refresh)
*/
saveProxySettings();
+
/*
* Save Visual settings
*/
- Cache.applicationProperties.setProperty("SHOW_JVSUFFIX",
+ Cache.setPropertyNoSave("SHOW_JVSUFFIX",
Boolean.toString(seqLimit.isSelected()));
- Cache.applicationProperties.setProperty("RIGHT_ALIGN_IDS",
+ Cache.setPropertyNoSave("RIGHT_ALIGN_IDS",
Boolean.toString(rightAlign.isSelected()));
- Cache.applicationProperties.setProperty("SHOW_FULLSCREEN",
+ Cache.setPropertyNoSave("SHOW_FULLSCREEN",
Boolean.toString(fullScreen.isSelected()));
- Cache.applicationProperties.setProperty("SHOW_OVERVIEW",
+ Cache.setPropertyNoSave("SHOW_OVERVIEW",
Boolean.toString(openoverv.isSelected()));
- Cache.applicationProperties.setProperty("SHOW_ANNOTATIONS",
+ Cache.setPropertyNoSave("SHOW_ANNOTATIONS",
Boolean.toString(annotations.isSelected()));
- Cache.applicationProperties.setProperty("SHOW_CONSERVATION",
+ Cache.setPropertyNoSave("SHOW_CONSERVATION",
Boolean.toString(conservation.isSelected()));
- Cache.applicationProperties.setProperty("SHOW_QUALITY",
+ Cache.setPropertyNoSave("SHOW_QUALITY",
Boolean.toString(quality.isSelected()));
- Cache.applicationProperties.setProperty("SHOW_IDENTITY",
+ Cache.setPropertyNoSave("SHOW_IDENTITY",
Boolean.toString(identity.isSelected()));
- Cache.applicationProperties.setProperty("GAP_SYMBOL",
+ Cache.setPropertyNoSave("GAP_SYMBOL",
gapSymbolCB.getSelectedItem().toString());
- Cache.applicationProperties.setProperty("FONT_NAME",
+ Cache.setPropertyNoSave("FONT_NAME",
fontNameCB.getSelectedItem().toString());
- Cache.applicationProperties.setProperty("FONT_STYLE",
+ Cache.setPropertyNoSave("FONT_STYLE",
fontStyleCB.getSelectedItem().toString());
- Cache.applicationProperties.setProperty("FONT_SIZE",
+ Cache.setPropertyNoSave("FONT_SIZE",
fontSizeCB.getSelectedItem().toString());
- Cache.applicationProperties.setProperty("ID_ITALICS",
+ Cache.setPropertyNoSave("ID_ITALICS",
Boolean.toString(idItalics.isSelected()));
- Cache.applicationProperties.setProperty("SHOW_UNCONSERVED",
+ Cache.setPropertyNoSave("SHOW_UNCONSERVED",
Boolean.toString(showUnconserved.isSelected()));
- Cache.applicationProperties.setProperty(SHOW_OCCUPANCY,
+ Cache.setPropertyNoSave(SHOW_OCCUPANCY,
Boolean.toString(showOccupancy.isSelected()));
- Cache.applicationProperties.setProperty("SHOW_GROUP_CONSENSUS",
+ Cache.setPropertyNoSave("SHOW_GROUP_CONSENSUS",
Boolean.toString(showGroupConsensus.isSelected()));
- Cache.applicationProperties.setProperty("SHOW_GROUP_CONSERVATION",
+ Cache.setPropertyNoSave("SHOW_GROUP_CONSERVATION",
Boolean.toString(showGroupConservation.isSelected()));
- Cache.applicationProperties.setProperty("SHOW_CONSENSUS_HISTOGRAM",
+ Cache.setPropertyNoSave("SHOW_CONSENSUS_HISTOGRAM",
Boolean.toString(showConsensHistogram.isSelected()));
- Cache.applicationProperties.setProperty("SHOW_CONSENSUS_LOGO",
+ Cache.setPropertyNoSave("SHOW_CONSENSUS_LOGO",
Boolean.toString(showConsensLogo.isSelected()));
- Cache.applicationProperties.setProperty("ANTI_ALIAS",
+ Cache.setPropertyNoSave("SHOW_INFORMATION_HISTOGRAM",
+ Boolean.toString(showConsensHistogram.isSelected()));
+ Cache.setPropertyNoSave("SHOW_HMM_LOGO",
+ Boolean.toString(showHMMLogo.isSelected()));
+ Cache.setPropertyNoSave("ANTI_ALIAS",
Boolean.toString(smoothFont.isSelected()));
- Cache.applicationProperties.setProperty(SCALE_PROTEIN_TO_CDNA,
+ Cache.setPropertyNoSave(SCALE_PROTEIN_TO_CDNA,
Boolean.toString(scaleProteinToCdna.isSelected()));
- Cache.applicationProperties.setProperty("SHOW_NPFEATS_TOOLTIP",
+ Cache.setPropertyNoSave("SHOW_NPFEATS_TOOLTIP",
Boolean.toString(showNpTooltip.isSelected()));
- Cache.applicationProperties.setProperty("SHOW_DBREFS_TOOLTIP",
+ Cache.setPropertyNoSave("SHOW_DBREFS_TOOLTIP",
Boolean.toString(showDbRefTooltip.isSelected()));
- Cache.applicationProperties.setProperty("WRAP_ALIGNMENT",
+ Cache.setPropertyNoSave("WRAP_ALIGNMENT",
Boolean.toString(wrap.isSelected()));
- Cache.applicationProperties.setProperty("STARTUP_FILE",
+ Cache.setPropertyNoSave("STARTUP_FILE",
startupFileTextfield.getText());
- Cache.applicationProperties.setProperty("SHOW_STARTUP_FILE",
+ Cache.setPropertyNoSave("SHOW_STARTUP_FILE",
Boolean.toString(startupCheckbox.isSelected()));
- Cache.applicationProperties.setProperty("SORT_ALIGNMENT",
+ Cache.setPropertyNoSave("SORT_ALIGNMENT",
sortby.getSelectedItem().toString());
// convert description of sort order to enum name for save
.forDescription(sortAnnBy.getSelectedItem().toString());
if (annSortOrder != null)
{
- Cache.applicationProperties.setProperty(SORT_ANNOTATIONS,
+ Cache.setPropertyNoSave(SORT_ANNOTATIONS,
annSortOrder.name());
}
final boolean showAutocalcFirst = sortAutocalc.getSelectedIndex() == 0;
- Cache.applicationProperties.setProperty(SHOW_AUTOCALC_ABOVE,
+ Cache.setPropertyNoSave(SHOW_AUTOCALC_ABOVE,
Boolean.valueOf(showAutocalcFirst).toString());
/*
* Save Colours settings
*/
- Cache.applicationProperties.setProperty(DEFAULT_COLOUR_PROT,
+ Cache.setPropertyNoSave(DEFAULT_COLOUR_PROT,
protColour.getSelectedItem().toString());
- Cache.applicationProperties.setProperty(DEFAULT_COLOUR_NUC,
+ Cache.setPropertyNoSave(DEFAULT_COLOUR_NUC,
nucColour.getSelectedItem().toString());
- Cache.setColourProperty("ANNOTATIONCOLOUR_MIN",
+ Cache.setColourPropertyNoSave("ANNOTATIONCOLOUR_MIN",
minColour.getBackground());
- Cache.setColourProperty("ANNOTATIONCOLOUR_MAX",
+ Cache.setColourPropertyNoSave("ANNOTATIONCOLOUR_MAX",
maxColour.getBackground());
/*
+ * Save HMMER settings
+ */
+ Cache.setPropertyNoSave(HMMALIGN_TRIM_TERMINI,
+ Boolean.toString(hmmrTrimTermini.isSelected()));
+ Cache.setPropertyNoSave(HMMINFO_GLOBAL_BACKGROUND,
+ Boolean.toString(hmmerBackgroundUniprot.isSelected()));
+ Cache.setPropertyNoSave(HMMSEARCH_SEQCOUNT,
+ hmmerSequenceCount.getText());
+ Cache.setOrRemove(HMMER_PATH, hmmerPath.getText());
+ if (cygwinPath != null)
+ {
+ Cache.setOrRemove(CYGWIN_PATH, cygwinPath.getText());
+ }
+ AlignFrame[] frames = Desktop.getAlignFrames();
+ if (frames != null && frames.length > 0)
+ {
+ for (AlignFrame f : frames)
+ {
+ f.updateHMMERStatus();
+ }
+ }
+
+ hmmrTrimTermini.setSelected(Cache.getDefault(HMMALIGN_TRIM_TERMINI, false));
+ if (Cache.getDefault(HMMINFO_GLOBAL_BACKGROUND, false))
+ {
+ hmmerBackgroundUniprot.setSelected(true);
+ }
+ else
+ {
+ hmmerBackgroundAlignment.setSelected(true);
+ }
+ hmmerSequenceCount
+ .setText(Cache.getProperty(HMMSEARCH_SEQCOUNT));
+ hmmerPath.setText(Cache.getProperty(HMMER_PATH));
+
+ /*
* Save Overview settings
*/
- Cache.setColourProperty(GAP_COLOUR, gapColour.getBackground());
- Cache.setColourProperty(HIDDEN_COLOUR, hiddenColour.getBackground());
- Cache.applicationProperties.setProperty(USE_LEGACY_GAP,
+ Cache.setColourPropertyNoSave(GAP_COLOUR, gapColour.getBackground());
+ Cache.setColourPropertyNoSave(HIDDEN_COLOUR, hiddenColour.getBackground());
+ Cache.setPropertyNoSave(USE_LEGACY_GAP,
Boolean.toString(useLegacyGap.isSelected()));
- Cache.applicationProperties.setProperty(SHOW_OV_HIDDEN_AT_START,
+ Cache.setPropertyNoSave(SHOW_OV_HIDDEN_AT_START,
Boolean.toString(showHiddenAtStart.isSelected()));
/*
* Save Structure settings
*/
- Cache.applicationProperties.setProperty(ADD_TEMPFACT_ANN,
+ Cache.setPropertyNoSave(ADD_TEMPFACT_ANN,
Boolean.toString(addTempFactor.isSelected()));
- Cache.applicationProperties.setProperty(ADD_SS_ANN,
+ Cache.setPropertyNoSave(ADD_SS_ANN,
Boolean.toString(addSecondaryStructure.isSelected()));
- Cache.applicationProperties.setProperty(STRUCT_FROM_PDB,
+ Cache.setPropertyNoSave(STRUCT_FROM_PDB,
Boolean.toString(structFromPdb.isSelected()));
+ if (!Platform.isJS()) {
String viewer = structViewer.getSelectedItem().toString();
String viewerPath = structureViewerPath.getText();
- Cache.applicationProperties.setProperty(STRUCTURE_DISPLAY, viewer);
+ Cache.setPropertyNoSave(STRUCTURE_DISPLAY, viewer);
if (viewer.equals(ViewerType.CHIMERA.name()))
{
Cache.setOrRemove(CHIMERA_PATH, viewerPath);
{
Cache.setOrRemove(PYMOL_PATH, viewerPath);
}
- Cache.applicationProperties.setProperty("MAP_WITH_SIFTS",
+ } // nojs
+ Cache.setPropertyNoSave("MAP_WITH_SIFTS",
Boolean.toString(siftsMapping.isSelected()));
SiftsSettings.setMapWithSifts(siftsMapping.isSelected());
/*
* Save Output settings
*/
- Cache.applicationProperties.setProperty("EPS_RENDERING",
+ Cache.setPropertyNoSave("EPS_RENDERING",
((OptionsParam) epsRendering.getSelectedItem()).getCode());
- Cache.applicationProperties.setProperty("HTML_RENDERING",
+ Cache.setPropertyNoSave("HTML_RENDERING",
((OptionsParam) htmlRendering.getSelectedItem()).getCode());
- Cache.applicationProperties.setProperty("SVG_RENDERING",
+ Cache.setPropertyNoSave("SVG_RENDERING",
((OptionsParam) svgRendering.getSelectedItem()).getCode());
/*
* Save Connections settings
*/
- // Proxy settings set first (to catch web services)
+ // Proxy settings were already set first (to catch web services)
+ Cache.setOrRemove("DEFAULT_BROWSER", defaultBrowser.getText());
+
+ jalview.util.BrowserLauncher.resetBrowser();
// save user-defined and selected links
String menuLinks = sequenceUrlLinks.writeUrlsAsString(true);
if (menuLinks.isEmpty())
{
- Cache.applicationProperties.remove("SEQUENCE_LINKS");
+ Cache.removePropertyNoSave("SEQUENCE_LINKS");
}
else
{
- Cache.applicationProperties.setProperty("SEQUENCE_LINKS",
+ Cache.setPropertyNoSave("SEQUENCE_LINKS",
menuLinks.toString());
}
String nonMenuLinks = sequenceUrlLinks.writeUrlsAsString(false);
if (nonMenuLinks.isEmpty())
{
- Cache.applicationProperties.remove("STORED_LINKS");
+ Cache.removePropertyNoSave("STORED_LINKS");
}
else
{
- Cache.applicationProperties.setProperty("STORED_LINKS",
+ Cache.setPropertyNoSave("STORED_LINKS",
nonMenuLinks.toString());
}
- Cache.applicationProperties.setProperty("DEFAULT_URL",
+ Cache.setPropertyNoSave("DEFAULT_URL",
sequenceUrlLinks.getPrimaryUrlId());
Cache.setProperty("VERSION_CHECK",
/*
* Save Output settings
*/
- Cache.applicationProperties.setProperty("BLC_JVSUFFIX",
+ Cache.setPropertyNoSave("BLC_JVSUFFIX",
Boolean.toString(blcjv.isSelected()));
- Cache.applicationProperties.setProperty("CLUSTAL_JVSUFFIX",
+ Cache.setPropertyNoSave("CLUSTAL_JVSUFFIX",
Boolean.toString(clustaljv.isSelected()));
- Cache.applicationProperties.setProperty("FASTA_JVSUFFIX",
+ Cache.setPropertyNoSave("FASTA_JVSUFFIX",
Boolean.toString(fastajv.isSelected()));
- Cache.applicationProperties.setProperty("MSF_JVSUFFIX",
+ Cache.setPropertyNoSave("MSF_JVSUFFIX",
Boolean.toString(msfjv.isSelected()));
- Cache.applicationProperties.setProperty("PFAM_JVSUFFIX",
+ Cache.setPropertyNoSave("PFAM_JVSUFFIX",
Boolean.toString(pfamjv.isSelected()));
- Cache.applicationProperties.setProperty("PILEUP_JVSUFFIX",
+ Cache.setPropertyNoSave("PILEUP_JVSUFFIX",
Boolean.toString(pileupjv.isSelected()));
- Cache.applicationProperties.setProperty("PIR_JVSUFFIX",
+ Cache.setPropertyNoSave("PIR_JVSUFFIX",
Boolean.toString(pirjv.isSelected()));
- Cache.applicationProperties.setProperty("PIR_MODELLER",
+ Cache.setPropertyNoSave("PIR_MODELLER",
Boolean.toString(modellerOutput.isSelected()));
- Cache.applicationProperties.setProperty("EXPORT_EMBBED_BIOJSON",
+ Cache.setPropertyNoSave("EXPORT_EMBBED_BIOJSON",
Boolean.toString(embbedBioJSON.isSelected()));
jalview.io.PIRFile.useModellerOutput = modellerOutput.isSelected();
- Cache.applicationProperties.setProperty("FIGURE_AUTOIDWIDTH",
+ Cache.setPropertyNoSave("FIGURE_AUTOIDWIDTH",
Boolean.toString(autoIdWidth.isSelected()));
userIdWidth_actionPerformed();
- Cache.applicationProperties.setProperty("FIGURE_FIXEDIDWIDTH",
+ Cache.setPropertyNoSave("FIGURE_FIXEDIDWIDTH",
userIdWidth.getText());
/*
* Save Editing settings
*/
- Cache.applicationProperties.setProperty("AUTO_CALC_CONSENSUS",
+ Cache.setPropertyNoSave("AUTO_CALC_CONSENSUS",
Boolean.toString(autoCalculateConsCheck.isSelected()));
- Cache.applicationProperties.setProperty("SORT_BY_TREE",
+ Cache.setPropertyNoSave("SORT_BY_TREE",
Boolean.toString(sortByTree.isSelected()));
- Cache.applicationProperties.setProperty("PAD_GAPS",
+ Cache.setPropertyNoSave("PAD_GAPS",
Boolean.toString(padGaps.isSelected()));
if (!Platform.isJS())
/*
* Save Backups settings
*/
- Cache.applicationProperties.setProperty(BackupFiles.ENABLED,
+ Cache.setPropertyNoSave(BackupFiles.ENABLED,
Boolean.toString(enableBackupFiles.isSelected()));
int preset = getComboIntStringKey(backupfilesPresetsCombo);
- Cache.applicationProperties.setProperty(BackupFiles.NS + "_PRESET", Integer.toString(preset));
- Cache.applicationProperties.setProperty(BackupFiles.NS + "_PRESET",
- Integer.toString(preset));
++ Cache.setPropertyNoSave(BackupFiles.NS + "_PRESET", Integer.toString(preset));
if (preset == BackupFilesPresetEntry.BACKUPFILESSCHEMECUSTOM)
{
BackupFilesPresetEntry customBFPE = getBackupfilesCurrentEntry();
BackupFilesPresetEntry.backupfilesPresetEntriesValues.put(
BackupFilesPresetEntry.BACKUPFILESSCHEMECUSTOM, customBFPE);
- Cache.applicationProperties
- .setProperty(BackupFilesPresetEntry.CUSTOMCONFIG,
- Cache.applicationProperties.setProperty(
- BackupFilesPresetEntry.CUSTOMCONFIG, customBFPE.toString());
++ Cache.setPropertyNoSave(BackupFilesPresetEntry.CUSTOMCONFIG,
+ customBFPE.toString());
}
BackupFilesPresetEntry savedBFPE = BackupFilesPresetEntry.backupfilesPresetEntriesValues
.get(preset);
- Cache.applicationProperties.setProperty(
+ Cache.setPropertyNoSave(
BackupFilesPresetEntry.SAVEDCONFIG, savedBFPE.toString());
+ /*
+ * Save Memory Settings
+ */
- Cache.applicationProperties.setProperty(
++ Cache.setPropertyNoSave(
+ MemorySetting.CUSTOMISED_SETTINGS,
+ Boolean.toString(customiseMemorySetting.isSelected()));
- Cache.applicationProperties.setProperty(MemorySetting.MEMORY_JVMMEMPC,
++ Cache.setPropertyNoSave(MemorySetting.MEMORY_JVMMEMPC,
+ Integer.toString(jvmMemoryPercentSlider.getValue()));
- Cache.applicationProperties.setProperty(MemorySetting.MEMORY_JVMMEMMAX,
++ Cache.setPropertyNoSave(MemorySetting.MEMORY_JVMMEMMAX,
+ jvmMemoryMaxTextField.getText());
+
+ /*
+ * save and close Preferences
+ */
-
Cache.saveProperties();
- Desktop.instance.doConfigureStructurePrefs();
+ Desktop.getInstance().doConfigureStructurePrefs();
try
{
frame.setClosed(true);
{
}
}
+
public void saveProxySettings()
{
String newProxyType = customProxy.isSelected() ? Cache.PROXYTYPE_CUSTOM
: noProxy.isSelected() ? Cache.PROXYTYPE_NONE
: Cache.PROXYTYPE_SYSTEM;
- Cache.applicationProperties.setProperty("USE_PROXY", newProxyType);
+ Cache.setPropertyNoSave("USE_PROXY", newProxyType);
Cache.setOrRemove("PROXY_SERVER", proxyServerHttpTB.getText());
Cache.setOrRemove("PROXY_PORT", proxyPortHttpTB.getText());
Cache.setOrRemove("PROXY_SERVER_HTTPS", proxyServerHttpsTB.getText());
|| !newProxyType.equals(previousProxyType))
{
// force a re-lookup of ws if proxytype is custom or has changed
-- wsPrefs.update++;
++ wsPrefs.refreshWs_actionPerformed(null);
}
previousProxyType = newProxyType;
}
- /**
+ public static void setAppletDefaults()
+ {
+
+ // http://www.jalview.org/old/v2_8/examples/appletParameters.html
+
+ // showConservation true or false Default is true.
+ // showQuality true or false Default is true.
+ // showConsensus true or false Default is true.
+ // showFeatureSettings true or false Shows the feature settings window when
+ // startin
+ // showTreeBootstraps true or false (default is true) show or hide branch
+ // bootstraps
+ // showTreeDistances true or false (default is true) show or hide branch
+ // lengths
+ // showUnlinkedTreeNodes true or false (default is false) indicate if
+ // unassociated nodes should be highlighted in the tree view
+ // showUnconserved true of false (default is false) When true, only gaps and
+ // symbols different to the consensus sequence ions of the alignment
+ // showGroupConsensus true of false (default is false) When true, shows
+ // consensus annotation row for any groups on the alignment. (since 2.7)
+ // showGroupConservation true of false (default is false) When true, shows
+ // amino-acid property conservation annotation row for any groups on the
+ // showConsensusHistogram true of false (default is true) When true, shows
+ // the percentage occurence of the consensus symbol for each column as a
+ // showSequenceLogo true of false (default is false) When true, shows a
+ // sequence logo above the consensus sequence (overlaid above the Consensus
+
+ Cache.setPropertyNoSave(SHOW_CONSERVATION, "true");
+ Cache.setPropertyNoSave(SHOW_QUALITY, "false");
+ Cache.setPropertyNoSave(SHOW_CONSENSUS, "true");
+ Cache.setPropertyNoSave(SHOW_UNCONSERVED, "false");
+ Cache.setPropertyNoSave(SHOW_GROUP_CONSERVATION, "false");
+ Cache.setPropertyNoSave(SHOW_GROUP_CONSENSUS, "false");
+
+ // TODO -- just a start here
+ }
+ /**
* Do any necessary validation before saving settings. Return focus to the
* first tab which fails validation.
*
FileFormatI format = chooser.getSelectedFormat();
if (format != null)
{
- Cache.applicationProperties.setProperty("DEFAULT_FILE_FORMAT",
+ Cache.setPropertyNoSave("DEFAULT_FILE_FORMAT",
format.getName());
}
startupFileTextfield
&& (identity.isSelected() || showGroupConsensus.isSelected()));
showConsensLogo.setEnabled(annotations.isSelected()
&& (identity.isSelected() || showGroupConsensus.isSelected()));
+ showInformationHistogram.setEnabled(annotations.isSelected());
+ showHMMLogo.setEnabled(annotations.isSelected());
}
@Override
boolean valid = false;
while (!valid)
{
- if (JvOptionPane.showInternalConfirmDialog(Desktop.desktop, link,
+ if (JvOptionPane.showInternalConfirmDialog(Desktop.getDesktopPane(), link,
MessageManager.getString("label.new_sequence_url_link"),
JvOptionPane.OK_CANCEL_OPTION, -1,
null) == JvOptionPane.OK_OPTION)
if (index == -1)
{
// button no longer enabled if row is not selected
- Cache.log.debug("Edit with no row selected in linkUrlTable");
+ Console.debug("Edit with no row selected in linkUrlTable");
return;
}
boolean valid = false;
while (!valid)
{
- if (JvOptionPane.showInternalConfirmDialog(Desktop.desktop, link,
+ if (JvOptionPane.showInternalConfirmDialog(Desktop.getDesktopPane(), link,
MessageManager.getString("label.edit_sequence_url_link"),
JvOptionPane.OK_CANCEL_OPTION, -1,
null) == JvOptionPane.OK_OPTION)
if (index == -1)
{
// button no longer enabled if row is not selected
- Cache.log.debug("Delete with no row selected in linkUrlTable");
+ Console.debug("Delete with no row selected in linkUrlTable");
return;
}
else
((UrlLinkTableModel) linkUrlTable.getModel()).removeRow(modelIndex);
}
+ @Override
+ public void defaultBrowser_mouseClicked(MouseEvent e)
+ {
+ // TODO: JAL-3048 not needed for j2s
+ if (!Platform.isJS()) // BH 2019
+ /**
+ * Java only
+ *
+ * @j2sIgnore
+ */
+ {
+ JFileChooser chooser = new JFileChooser(".");
+ chooser.setDialogTitle(
+ MessageManager.getString("label.select_default_browser"));
+
+ int value = chooser.showOpenDialog(this);
+
+ if (value == JFileChooser.APPROVE_OPTION)
+ {
+ defaultBrowser.setText(chooser.getSelectedFile().getAbsolutePath());
+ }
+ }
+ }
+
/*
* (non-Javadoc)
*
if (!useLegacyGap.isSelected())
{
JalviewColourChooser.showColourChooser(this,
- MessageManager.getString("label.select_gap_colour"), gap);
+ MessageManager.getString("label.select_gap_colour"),
+ gap);
}
}
public void hiddenColour_actionPerformed(JPanel hidden)
{
JalviewColourChooser.showColourChooser(this,
- MessageManager.getString("label.select_hidden_colour"), hidden);
+ MessageManager.getString("label.select_hidden_colour"),
+ hidden);
}
@Override
} catch (NumberFormatException x)
{
userIdWidth.setText("");
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
MessageManager
.getString("warn.user_defined_width_requirements"),
MessageManager.getString("label.invalid_id_column_width"),
}
/**
- * Returns true if structure viewer path is to a valid executable, else shows
- * an error dialog. Does nothing if the path is empty, as is the case for Jmol
+ * Returns true if structure viewer path is to a valid executable, else shows an
+ * error dialog. Does nothing if the path is empty, as is the case for Jmol
* (built in to Jalview) or when Jalview is left to try default paths.
*/
private boolean validateViewerPath()
File f = new File(structureViewerPath.getText());
if (!f.canExecute())
{
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
MessageManager.getString("label.invalid_viewer_path"),
MessageManager.getString("label.invalid_viewer_path"),
JvOptionPane.ERROR_MESSAGE);
}
return true;
}
+
+ /**
+ * Returns true if the given text field contains a path to a folder that
+ * contains an executable with the given name, else false (after showing a
+ * warning dialog). The executable name will be tried with .exe appended if not
+ * found.
+ *
+ * @param textField
+ * @param executable
+ */
+ protected boolean validateExecutablePath(JTextField textField, String executable)
+ {
+ String folder = textField.getText().trim();
+
+ if (FileUtils.getExecutable(executable, folder) != null)
+ {
+ return true;
+ }
+ if (folder.length() > 0)
+ {
+ JvOptionPane.showInternalMessageDialog(Desktop.getInstance(),
+ MessageManager.formatMessage("label.executable_not_found",
+ executable),
+ MessageManager.getString("label.invalid_folder"),
+ JvOptionPane.ERROR_MESSAGE);
+ }
+ return false;
+ }
/**
- * If Chimera or ChimeraX or Pymol is selected, check it can be found on
- * default or user-specified path, if not show a warning/help dialog
+ * Checks if a file can be executed
+ *
+ * @param path
+ * the path to the file
+ * @return
+ */
+ public boolean canExecute(String path)
+ {
+ File file = new File(path);
+ if (!file.canExecute())
+ {
+ file = new File(path + ".exe");
+ {
+ if (!file.canExecute())
+ {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ /**
+ * If Chimera or ChimeraX or Pymol is selected, check it can be found on default
+ * or user-specified path, if not show a warning/help dialog
*/
@Override
protected void structureViewer_actionPerformed(String selectedItem)
break;
}
}
+
if (!found)
{
String[] options = { "OK", "Help" };
- int showHelp = JvOptionPane.showInternalOptionDialog(Desktop.desktop,
+ int showHelp = JvOptionPane.showInternalOptionDialog(Desktop.getDesktopPane(),
JvSwingUtils.wrapTooltip(true,
MessageManager.getString("label.viewer_missing")),
"", JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
null, options, options[0]);
+
if (showHelp == JvOptionPane.NO_OPTION)
{
this.selectTab(Preferences.TabRef.STRUCTURE_TAB, null);
}
});
}
- }
+ }
+ }
+
+ @Override
+ protected void validateHmmerPath()
+ {
+ validateExecutablePath(hmmerPath, HmmerCommand.HMMBUILD);
+ }
+
+ @Override
+ protected void validateCygwinPath()
+ {
+ validateExecutablePath(cygwinPath, "run");
}
public class OptionsParam
package jalview.gui;
import jalview.bin.Cache;
+ import jalview.bin.Console;
import java.awt.Component;
* @param desktop
* - where the dialog box will be shown
* @param property
- * - boolean property in jalview.bin.Cache
+ * - boolean property in Cache
* @param dialogTitle
* - title of prompt box
* @param dialogText
return;
}
// First - check to see if wee have an old questionnaire/response id pair.
- String lastq = jalview.bin.Cache.getProperty(property);
+ String lastq = Cache.getProperty(property);
if (lastq == null)
{
raiseDialog();
- Cache.log.debug("Got user response.");
+ Console.debug("Got user response.");
}
- lastq = jalview.bin.Cache.getProperty(property);
+ lastq = Cache.getProperty(property);
String extype = "";
Exception e = null;
if (lastq == null)
// report any exceptions
if (e != null)
{
- Cache.log.warn("Unexpected exception when executing the " + extype
+ Console.warn("Unexpected exception when executing the " + extype
+ " runnable for property " + property, e);
}
}
*/
private void raiseDialog()
{
- if (jalview.bin.Cache.log.isDebugEnabled())
+ if (Console.isDebugEnabled())
{
- jalview.bin.Cache.log.debug("Prompting user for " + dialogTitle
+ Console.debug("Prompting user for " + dialogTitle
+ " for Cache property " + property);
}
try
{
- int reply = JvOptionPane.showConfirmDialog(Desktop.desktop, // component,
+ int reply = JvOptionPane.showConfirmDialog(Desktop.getDesktopPane(), // component,
dialogText, dialogTitle,
(allowCancel) ? JvOptionPane.YES_NO_CANCEL_OPTION
: JvOptionPane.YES_NO_OPTION,
JvOptionPane.QUESTION_MESSAGE);
// and finish parsing the result
- jalview.bin.Cache.log.debug("Got response : " + reply);
+ Console.debug("Got response : " + reply);
if (reply == JvOptionPane.YES_OPTION)
{
- jalview.bin.Cache.setProperty(property, "true");
+ Cache.setProperty(property, "true");
}
else if (reply == JvOptionPane.NO_OPTION)
{
if (removeifunset)
{
- jalview.bin.Cache.removeProperty(property);
+ Cache.removeProperty(property);
}
else
{
- jalview.bin.Cache.setProperty(property, "false");
+ Cache.setProperty(property, "false");
}
}
else
{
- jalview.bin.Cache.log.debug("User cancelled setting " + property);
+ Console.debug("User cancelled setting " + property);
return;
}
// verify the property is set for debugging
- if (jalview.bin.Cache.log.isDebugEnabled())
+ if (Console.isDebugEnabled())
{
- jalview.bin.Cache.log.debug("User set property to "
- + jalview.bin.Cache.getProperty(property));
+ Console.debug(
+ "User set property to " + Cache.getProperty(property));
}
} catch (Exception e)
{
- jalview.bin.Cache.log.warn(
+ Console.warn(
"Unexpected exception when prompting user for yes/no setting for property "
+ property,
e);
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.gui;
import java.awt.event.ActionEvent;
import jalview.api.AlignmentViewPanel;
import jalview.api.FeatureRenderer;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.PDBEntry;
import jalview.datamodel.SequenceI;
import jalview.datamodel.StructureViewerModel;
AlignmentPanel ap)
{
this();
- openNewPymol(ap, new PDBEntry[] { pdb },
- new SequenceI[][]
- { seqs });
+ openNewPymol(ap, new PDBEntry[] { pdb }, new SequenceI[][] { seqs });
}
public PymolViewer(PDBEntry[] pe, boolean alignAdded, SequenceI[][] seqs,
public void run()
{
// todo pull up much of this
-
+
StringBuilder errormsgs = new StringBuilder(128);
List<PDBEntry> filePDB = new ArrayList<>();
List<Integer> filePDBpos = new ArrayList<>();
- String[] curfiles = binding.getStructureFiles(); // files currently in viewer
+ String[] curfiles = binding.getStructureFiles(); // files currently in
+ // viewer
for (int pi = 0; pi < binding.getPdbCount(); pi++)
{
String file = null;
/*
* got file already
*/
- file = new File(thePdbEntry.getFile()).getAbsoluteFile()
- .getPath();
+ file = new File(thePdbEntry.getFile()).getAbsoluteFile().getPath();
// todo - skip if already loaded in PyMOL
}
if (file != null)
filePDBpos.add(Integer.valueOf(pi));
}
}
-
+
if (!filePDB.isEmpty())
{
/*
initPymol();
} catch (Exception ex)
{
- Cache.log.error("Couldn't open PyMOL viewer!", ex);
+ Console.error("Couldn't open PyMOL viewer!", ex);
+ // if we couldn't open Pymol, no point continuing
+ return;
}
}
+ if (!binding.isViewerRunning())
+ {
+ // nothing to do
+ // TODO: ensure we tidy up JAL-3619
+
+ return;
+ }
+
int num = -1;
for (PDBEntry pe : filePDB)
{
StructureFile pdb = binding.getSsm().setMapping(
binding.getSequence()[pos], binding.getChains()[pos],
- pe.getFile(), protocol,
- getProgressIndicator());
+ pe.getFile(), protocol, getProgressIndicator());
binding.stashFoundChains(pdb, pe.getFile());
} catch (Exception ex)
{
- Cache.log.error(
- "Couldn't open " + pe.getFile() + " in Chimera viewer!",
- ex);
+ Console.error("Couldn't open " + pe.getFile() + " in "
+ + getViewerName() + "!", ex);
} finally
{
- // Cache.log.debug("File locations are " + files);
+ // Cache.debug("File locations are " + files);
}
}
}
if (!binding.launchPymol())
{
-- JvOptionPane.showMessageDialog(Desktop.desktop,
++ JvOptionPane.showMessageDialog(Desktop.getInstance(),
MessageManager.formatMessage("label.open_viewer_failed",
getViewerName()),
MessageManager.getString("label.error_loading_file"),
JvOptionPane.ERROR_MESSAGE);
+ binding.closeViewer(true);
this.dispose();
return;
}
boolean opened = binding.openSession(pymolSessionFile);
if (!opened)
{
- Cache.log.error(
- "An error occurred opening PyMOL session file "
+ Console.error("An error occurred opening PyMOL session file "
+ pymolSessionFile);
}
}
{
return "PyMOL";
}
+
JMenuItem writeFeatures = null;
+
@Override
protected void initMenus()
{
writeFeatures = new JMenuItem(
MessageManager.getString("label.create_viewer_attributes"));
- writeFeatures.setToolTipText(MessageManager
- .getString("label.create_viewer_attributes_tip"));
+ writeFeatures.setToolTipText(
+ MessageManager.getString("label.create_viewer_attributes_tip"));
writeFeatures.addActionListener(new ActionListener()
{
@Override
});
viewerActionMenu.add(writeFeatures);
}
-
+
@Override
protected void buildActionMenu()
{
protected void sendFeaturesToPymol()
{
int count = binding.sendFeaturesToViewer(getAlignmentPanel());
- statusBar.setText(
- MessageManager.formatMessage("label.attributes_set", count));
+ statusBar.setText(MessageManager.formatMessage("label.attributes_set",
+ count, getViewerName()));
}
}
{
av.showColumn(hiddenRange[0]);
reveal = null;
- ap.updateLayout();
- ap.paintAlignment(true, true);
- av.sendSelection();
+ updatePanel();
}
});
pop.add(item);
- if (av.getAlignment().getHiddenColumns().hasMultiHiddenColumnRegions())
+ if (av.getAlignment().getHiddenColumns()
+ .hasMultiHiddenColumnRegions())
{
item = new JMenuItem(MessageManager.getString("action.reveal_all"));
item.addActionListener(new ActionListener()
{
av.showAllHiddenColumns();
reveal = null;
- ap.updateLayout();
- ap.paintAlignment(true, true);
- av.sendSelection();
+ updatePanel();
}
});
pop.add(item);
{
av.setSelectionGroup(null);
}
-
- ap.updateLayout();
- ap.paintAlignment(true, true);
- av.sendSelection();
+ updatePanel();
}
});
pop.add(item);
return pop;
}
+ protected void updatePanel()
+ {
+ ap.updateLayout();
+ ap.paintAlignment(true, true);
+ ap.updateScrollBarsFromRanges();
+ av.sendSelection();
+ }
+
/**
* Handles left mouse button press
*
// todo res calculation should be a method on AlignViewport
int xCords = Math.max(0, evt.getX()); // prevent negative X coordinates
ViewportRanges ranges = av.getRanges();
- int res = (xCords / av.getCharWidth())
- + ranges.getStartRes();
+ int res = (xCords / av.getCharWidth()) + ranges.getStartRes();
res = Math.min(res, ranges.getEndRes());
if (av.hasHiddenColumns())
{
@Override
public void paintComponent(Graphics g)
{
- //super.paintComponent(g); // BH 2019
+ // super.paintComponent(g); // BH 2019
/*
* shouldn't get called in wrapped mode as the scale above is
gg.fillPolygon(
new int[]
- { -1 + res * avCharWidth - avCharHeight / 4,
- -1 + res * avCharWidth + avCharHeight / 4,
- -1 + res * avCharWidth }, new int[]
- { y, y, y + 2 * yOf }, 3);
+ { -1 + res * avCharWidth - avCharHeight / 4,
+ -1 + res * avCharWidth + avCharHeight / 4,
+ -1 + res * avCharWidth },
+ new int[]
+ { y, y, y + 2 * yOf }, 3);
}
}
}
|| evt.getPropertyName().equals(ViewportRanges.MOVE_VIEWPORT))
{
// scroll event, repaint panel
-
- // Call repaint on alignment panel so that repaints from other alignment
- // panel components can be aggregated. Otherwise performance of the overview
- // window and others may be adversely affected.
+
+ // Call repaint on alignment panel so that repaints from other alignment
+ // panel components can be aggregated. Otherwise performance of the
+ // overview
+ // window and others may be adversely affected.
av.getAlignPanel().repaint();
}
}
*/
package jalview.gui;
+import jalview.datamodel.AlignmentI;
+import jalview.datamodel.HiddenColumns;
+import jalview.datamodel.SearchResultsI;
+import jalview.datamodel.SequenceGroup;
+import jalview.datamodel.SequenceI;
+import jalview.datamodel.VisibleContigsIterator;
+import jalview.renderer.ScaleRenderer;
+import jalview.renderer.ScaleRenderer.ScaleMark;
+import jalview.util.Comparison;
+import jalview.viewmodel.ViewportListenerI;
+import jalview.viewmodel.ViewportRanges;
+
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JPanel;
-import jalview.datamodel.AlignmentI;
-import jalview.datamodel.HiddenColumns;
-import jalview.datamodel.SearchResultsI;
-import jalview.datamodel.SequenceGroup;
-import jalview.datamodel.SequenceI;
-import jalview.datamodel.VisibleContigsIterator;
-import jalview.renderer.ScaleRenderer;
-import jalview.renderer.ScaleRenderer.ScaleMark;
-import jalview.util.Comparison;
-import jalview.viewmodel.ViewportListenerI;
-import jalview.viewmodel.ViewportRanges;
-
/**
* The Swing component on which the alignment sequences, and annotations (if
* shown), are drawn. This includes scales above, left and right (if shown) in
private final SequenceRenderer seqRdr;
- boolean fastPaint = false;
+ private boolean fastPaint = false;
private boolean fastpainting = false;
private int wrappedVisibleWidths; // number of wrapped widths displayed
+ private int availWidth;
+
+ private int availHeight;
+
+ private boolean allowFastPaint;
// Don't do this! Graphics handles are supposed to be transient
// private Graphics2D gg;
int yPos = ypos + charHeight;
int startX = startx;
int endX = endx;
-
++
if (av.hasHiddenColumns())
{
HiddenColumns hiddenColumns = av.getAlignment().getHiddenColumns();
}
}
+
// System.err.println(">>> FastPaint to " + transX + " " + transY + " "
// + horizontal + " " + vertical + " " + startRes + " " + endRes
// + " " + startSeq + " " + endSeq);
img.getWidth(), img.getHeight(), -horizontal * charWidth,
-vertical * charHeight);
- /** @j2sNative xxi = this.img */
gg.translate(transX, transY);
drawPanel(gg, startRes, endRes, startSeq, endSeq, 0);
// Call repaint on alignment panel so that repaints from other alignment
// panel components can be aggregated. Otherwise performance of the
// overview window and others may be adversely affected.
- // System.out.println("SeqCanvas fastPaint() repaint() request...");
av.getAlignPanel().repaint();
} finally
{
@Override
public void paintComponent(Graphics g)
{
+ if (av.getAlignPanel().getHoldRepaint())
+ {
+ return;
+ }
- int charHeight = av.getCharHeight();
- int charWidth = av.getCharWidth();
-
- int width = getWidth();
- int height = getHeight();
-
- width -= (width % charWidth);
- height -= (height % charHeight);
-
- // BH 2019 can't possibly fastPaint if either width or height is 0
+ getAvailSizes();
- if (width == 0 || height == 0)
+ if (availWidth == 0 || availHeight == 0)
{
return;
}
// }
Rectangle vis, clip;
- if (img != null
- && (fastPaint
- || (vis = getVisibleRect()).width != (clip = g
- .getClipBounds()).width
- || vis.height != clip.height))
+ if (allowFastPaint && img != null
+ && (fastPaint || (vis = getVisibleRect()).width != (clip = g.getClipBounds()).width
+ || vis.height != clip.height))
{
g.drawImage(img, 0, 0, this);
drawSelectionGroup((Graphics2D) g, startRes, endRes, startSeq,
}
else
{
+ allowFastPaint = true;
// img is a cached version of the last view we drew.
// If we have no img or the size has changed, make a new one.
//
- if (img == null || width != img.getWidth()
- || height != img.getHeight())
+ if (img == null || availWidth != img.getWidth()
+ || availHeight != img.getHeight())
{
- img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
+ img = new BufferedImage(availWidth, availHeight,
+ BufferedImage.TYPE_INT_RGB);
}
Graphics2D gg = (Graphics2D) img.getGraphics();
}
gg.setColor(Color.white);
- gg.fillRect(0, 0, img.getWidth(), img.getHeight());
+ gg.fillRect(0, 0, availWidth, availHeight);
if (av.getWrapAlignment())
{
- drawWrappedPanel(gg, width, height, ranges.getStartRes());
- drawWrappedPanel(gg, getWidth(), getHeight(), ranges.getStartRes());
++ drawWrappedPanel(gg, availWidth, availHeight, ranges.getStartRes());
}
else
{
drawCursor(g, startRes, endRes, startSeq, endSeq);
}
}
-
/**
* Draw an alignment panel for printing
*
FontMetrics fm = getFontMetrics(av.getFont());
int labelWidth = 0;
-
+
if (av.getScaleRightWrapped() || av.getScaleLeftWrapped())
{
labelWidth = getLabelWidth(fm);
maxWidth = Math.max(maxWidth, alignment.getSequenceAt(i).getEnd());
}
+ // quick int log10
int length = 0;
for (int i = maxWidth; i > 0; i /= 10)
{
* window
*
* @param g
- * @param canvasWidth
+ * @param availWidth
* available width in pixels
- * @param canvasHeight
+ * @param availHeight
* available height in pixels
* @param startColumn
* the first column (0...) of the alignment to draw
*/
- public void drawWrappedPanel(Graphics g, int canvasWidth,
- int canvasHeight, final int startColumn)
+ public void drawWrappedPanel(Graphics g, int availWidth, int availHeight,
+ final int startColumn)
{
- int wrappedWidthInResidues = calculateWrappedGeometry(canvasWidth,
- canvasHeight);
+ int wrappedWidthInResidues = calculateWrappedGeometry();
av.setWrappedWidth(wrappedWidthInResidues);
// we need to call this again to make sure the startColumn +
// wrappedWidthInResidues values are used to calculate wrappedVisibleWidths
// correctly.
- calculateWrappedGeometry(canvasWidth, canvasHeight);
+ calculateWrappedGeometry();
/*
* draw one width at a time (excluding any scales shown),
{
int endColumn = Math.min(maxWidth,
start + wrappedWidthInResidues - 1);
- drawWrappedWidth(g, ypos, start, endColumn, canvasHeight);
+ drawWrappedWidth(g, ypos, start, endColumn, availHeight);
ypos += wrappedRepeatHeightPx;
start += wrappedWidthInResidues;
currentWidth++;
drawWrappedDecorators(g, startColumn);
}
+ private void getAvailSizes()
+ {
+ int charHeight = av.getCharHeight();
+ int charWidth = av.getCharWidth();
+ availWidth = getWidth();
+ availHeight = getHeight();
+ availWidth -= (availWidth % charWidth);
+ availHeight -= (availHeight % charHeight);
+ }
/**
* Calculates and saves values needed when rendering a wrapped alignment.
* These depend on many factors, including
* <li>whether scales are shown left, right or above the alignment</li>
* </ul>
*
+ * @param availWidth
+ * @param availHeight
+ * @return the number of residue columns in each width
+ */
+ protected int calculateWrappedGeometry()
+ {
+ getAvailSizes();
+ return calculateWrappedGeometry(availWidth, availHeight);
+
+ }
+
+ /**
+ * for test only
* @param canvasWidth
* @param canvasHeight
- * @return the number of residue columns in each width
+ * @return
*/
- protected int calculateWrappedGeometry(int canvasWidth, int canvasHeight)
+ public int calculateWrappedGeometry(int canvasWidth, int canvasHeight)
{
int charHeight = av.getCharHeight();
* compute height in pixels of the wrapped widths
* - start with space above plus sequences
*/
- wrappedRepeatHeightPx = wrappedSpaceAboveAlignment;
- wrappedRepeatHeightPx += av.getAlignment().getHeight() * charHeight;
+ wrappedRepeatHeightPx = wrappedSpaceAboveAlignment
+ + av.getAlignment().getHeight() * charHeight;
/*
* add annotations panel height if shown
* compute width in residues; this also sets East and West label widths
*/
int wrappedWidthInResidues = getWrappedCanvasWidth(canvasWidth);
- av.setWrappedWidth(wrappedWidthInResidues); // update model accordingly
+
/*
* limit visibleWidths to not exceed width of alignment
*/
if (av.getScaleRightWrapped())
{
int x = labelWidthWest + viewportWidth * charWidth;
-
g.translate(x, 0);
drawVerticalScale(g, startCol, endColumn, ypos, false);
g.translate(-x, 0);
}
}
+ private final static BasicStroke dottedStroke = new BasicStroke(1,
+ BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 3f, new float[]
+ { 5f, 3f }, 0f);
+
+ private final static BasicStroke basicStroke = new BasicStroke();
/*
* Draw a selection group over a wrapped alignment
*/
{
// chop the wrapped alignment extent up into panel-sized blocks and treat
// each block as if it were a block from an unwrapped alignment
- g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
- BasicStroke.JOIN_ROUND, 3f, new float[]
- { 5f, 3f }, 0f));
+ g.setStroke(dottedStroke);
g.setColor(Color.RED);
int charWidth = av.getCharWidth();
/ charWidth;
int startx = startRes;
int maxwidth = av.getAlignment().getVisibleWidth();
+ // JAL-3253-applet had this:
+ // // height gap above each panel
+ // int charHeight = av.getCharHeight();
+ // int hgap = charHeight;
+ // if (av.getScaleAboveWrapped())
+ // {
+ // hgap += charHeight;
+ // }
+ // int dy = getAnnotationHeight() + hgap
+ // + av.getAlignment().getHeight() * charHeight;
+ // int ypos = hgap; // vertical offset
+
+ // this is from 0b573ed (gmungoc)
+ int dy = wrappedRepeatHeightPx;
int ypos = wrappedSpaceAboveAlignment;
while ((ypos <= canvasHeight) && (startx < maxwidth))
av.getAlignment().getHeight() - 1, ypos);
g.translate(-labelWidthWest, 0);
- ypos += wrappedRepeatHeightPx;
+ // update vertical offset
+ ypos += dy;
+ // update horizontal offset
startx += cWidth;
}
- g.setStroke(new BasicStroke());
+ g.setStroke(basicStroke);
}
/**
}
}
+
/**
* Draw a selection group over an unwrapped alignment
*
int startRes, int endRes, int startSeq, int endSeq, int offset)
{
int charWidth = av.getCharWidth();
-
if (!av.hasHiddenColumns())
{
drawPartialGroupOutline(g, group, startRes, endRes, startSeq, endSeq,
g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
}
}
-
/**
* Highlights search results in the visible region by rendering as white text
* on a black background. Any previous highlighting is removed. Answers true
return highlightSearchResults(results, false);
}
-
/**
* Highlights search results in the visible region by rendering as white text
* on a black background. Any previous highlighting is removed. Answers true
public void propertyChange(PropertyChangeEvent evt)
{
String eventName = evt.getPropertyName();
- // System.err.println(">>SeqCanvas propertyChange " + eventName);
- if (eventName.equals(SequenceGroup.SEQ_GROUP_CHANGED))
+ // BH 2019.07.27 removes dead code introduced in aad3650 and simplifies
+ // logic, emphasizing no check for ENDRES or ENDSEQ
+
+ // Both scrolling and resizing change viewport ranges: scrolling changes
+ // both start and end points, but resize only changes end values.
+ // Here we only want to fastpaint on a scroll, with resize using a normal
+ // paint, so scroll events are identified as changes to the horizontal or
+ // vertical start value.
+
+ // Make sure we're not trying to draw a panel
+ // larger than the visible window
+ int scrollX = 0;
+ int scrollY = 0;
+ switch (eventName)
{
+ case SequenceGroup.SEQ_GROUP_CHANGED:
fastPaint = true;
repaint();
return;
- }
- else if (eventName.equals(ViewportRanges.MOVE_VIEWPORT))
- {
+ case ViewportRanges.MOVE_VIEWPORT:
fastPaint = false;
- // System.err.println("!!!! fastPaint false from MOVE_VIEWPORT");
repaint();
return;
- }
-
- int scrollX = 0;
- if (eventName.equals(ViewportRanges.STARTRES)
- || eventName.equals(ViewportRanges.STARTRESANDSEQ))
- {
- // Make sure we're not trying to draw a panel
- // larger than the visible window
- if (eventName.equals(ViewportRanges.STARTRES))
- {
- scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
- }
- else
+ case ViewportRanges.STARTSEQ:
+ // meaning STARTOREND
+ // typically scroll, but possibly just the end changed
+ fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
+ return;
+ case ViewportRanges.STARTRES:
+ // meaning STARTOREND
+ scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
+ break;
+ case ViewportRanges.STARTRESANDSEQ:
+ scrollX = ((int[]) evt.getNewValue())[0]
+ - ((int[]) evt.getOldValue())[0];
+ scrollY = ((int[]) evt.getNewValue())[1]
+ - ((int[]) evt.getOldValue())[1];
+ if (scrollX != 0 && scrollY != 0)
{
- scrollX = ((int[]) evt.getNewValue())[0]
- - ((int[]) evt.getOldValue())[0];
- }
- ViewportRanges vpRanges = av.getRanges();
+ // all sorts of problems in JavaScript if this is commented out.
+ repaint();
+ return;
- int range = vpRanges.getEndRes() - vpRanges.getStartRes() + 1;
- if (scrollX > range)
- {
- scrollX = range;
- }
- else if (scrollX < -range)
- {
- scrollX = -range;
}
+ break;
+ default:
+ return;
+ }
+
+ ViewportRanges vpRanges = av.getRanges();
+ int range = vpRanges.getEndRes() - vpRanges.getStartRes() + 1;
+ scrollX = Math.max(Math.min(scrollX, range), -range);
+ // only STARTRES or STARTRESANDSEQ:
+ if (av.getWrapAlignment())
+ {
+ fastPaintWrapped(scrollX);
+ }
+ else
+ {
+ fastPaint(scrollX, scrollY);
}
+
+ // BH 2019.07.27 was:
+ // if (eventName.equals(SequenceGroup.SEQ_GROUP_CHANGED))
+ // {
+ // fastPaint = true;
+ // repaint();
+ // return;
+ // }
+ // else if (eventName.equals(ViewportRanges.MOVE_VIEWPORT))
+ // {
+ // fastPaint = false;
+ // // System.err.println("!!!! fastPaint false from MOVE_VIEWPORT");
+ // repaint();
+ // return;
+ // }
+ //
+ // if (eventName.equals(ViewportRanges.STARTRES)
+ // || eventName.equals(ViewportRanges.STARTRESANDSEQ))
+ // {
+ // // Make sure we're not trying to draw a panel
+ // // larger than the visible window
+ // if (eventName.equals(ViewportRanges.STARTRES))
+ // {
+ // scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
+ // }
+ // else
+ // {
+ // scrollX = ((int[]) evt.getNewValue())[0]
+ // - ((int[]) evt.getOldValue())[0];
+ // }
+ // ViewportRanges vpRanges = av.getRanges();
+ //
+ // int range = vpRanges.getEndRes() - vpRanges.getStartRes() + 1;
+ // if (scrollX > range)
+ // {
+ // scrollX = range;
+ // }
+ // else if (scrollX < -range)
+ // {
+ // scrollX = -range;
+ // }
+ // }
// Both scrolling and resizing change viewport ranges: scrolling changes
// both start and end points, but resize only changes end values.
// Here we only want to fastpaint on a scroll, with resize using a normal
// paint, so scroll events are identified as changes to the horizontal or
// vertical start value.
- if (eventName.equals(ViewportRanges.STARTRES))
- {
- if (av.getWrapAlignment())
- {
- fastPaintWrapped(scrollX);
- }
- else
- {
- fastPaint(scrollX, 0);
- }
- }
- else if (eventName.equals(ViewportRanges.STARTSEQ))
- {
- // scroll
- fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
- }
- else if (eventName.equals(ViewportRanges.STARTRESANDSEQ))
- {
- if (av.getWrapAlignment())
- {
- fastPaintWrapped(scrollX);
- }
- else
- {
- fastPaint(scrollX, 0);
- }
- }
- else if (eventName.equals(ViewportRanges.STARTSEQ))
- {
- // scroll
- fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
- }
- else if (eventName.equals(ViewportRanges.STARTRESANDSEQ))
- {
- if (av.getWrapAlignment())
- {
- fastPaintWrapped(scrollX);
- }
- }
+ // BH 2019.07.27 was:
+ // if (eventName.equals(ViewportRanges.STARTRES))
+ // {
+ // if (av.getWrapAlignment())
+ // {
+ // fastPaintWrapped(scrollX);
+ // }
+ // else
+ // {
+ // fastPaint(scrollX, 0);
+ // }
+ // }
+ // else if (eventName.equals(ViewportRanges.STARTSEQ))
+ // {
+ // // scroll
+ // fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
+ // }
+ // else if (eventName.equals(ViewportRanges.STARTRESANDSEQ))
+ // {
+ // if (av.getWrapAlignment())
+ // {
+ // fastPaintWrapped(scrollX);
+ // }
+ // else
+ // {
+ // fastPaint(scrollX, 0);
+ // }
+ // }
+ //
+ // BH oops!
+ //
+ // else if (eventName.equals(ViewportRanges.STARTSEQ))
+ // {
+ // // scroll
+ // fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
+ // }
+ // else if (eventName.equals(ViewportRanges.STARTRESANDSEQ))
+ // {
+ // if (av.getWrapAlignment())
+ // {
+ // fastPaintWrapped(scrollX);
+ // }
+ // }
}
/**
try
{
-
Graphics gg = img.getGraphics();
-
- calculateWrappedGeometry(getWidth(), getHeight());
+ calculateWrappedGeometry();
/*
* relocate the regions of the alignment that are still visible
drawWrappedDecorators(gg, ranges.getStartRes());
gg.dispose();
-
repaint();
} finally
{
}
Graphics gg = img.getGraphics();
-
ViewportRanges ranges = av.getRanges();
int viewportWidth = ranges.getViewportWidth();
int charWidth = av.getCharWidth();
/*
* white fill first to erase annotations
*/
-
gg.translate(xOffset, 0);
gg.setColor(Color.white);
gg.fillRect(labelWidthWest, ypos, (endRes - startRes + 1) * charWidth,
gg.translate(-xOffset, 0);
drawWrappedWidth(gg, ypos, startRes, endRes, canvasHeight);
-
}
/*
boolean matchFound = false;
- calculateWrappedGeometry(getWidth(), getHeight());
+ calculateWrappedGeometry();
int wrappedWidth = av.getWrappedWidth();
int wrappedHeight = wrappedRepeatHeightPx;
}
}
}
-
gg.dispose();
return matchFound;
return labelWidthWest;
}
+ /**
+ * Clears the flag that allows a 'fast paint' on the next repaint, so
+ * requiring a full repaint
+ */
+ public void setNoFastPaint()
+ {
+ allowFastPaint = false;
+ }
+
}
import javax.swing.ToolTipManager;
import jalview.api.AlignViewportI;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.commands.EditCommand;
import jalview.commands.EditCommand.Action;
import jalview.commands.EditCommand.Edit;
SequenceListener, SelectionListener
{
/*
+ *
* a class that holds computed mouse position
* - column of the alignment (0...)
* - sequence offset (0...)
*/
public SeqPanel(AlignViewport viewport, AlignmentPanel alignPanel)
{
+ setName("SeqPanel");
seqARep = new SequenceAnnotationReport(true);
ToolTipManager.sharedInstance().registerComponent(this);
ToolTipManager.sharedInstance().setInitialDelay(0);
ToolTipManager.sharedInstance().setDismissDelay(10000);
-
+
+
this.av = viewport;
setBackground(Color.white);
int alignmentHeight = av.getAlignment().getHeight();
if (av.getWrapAlignment())
{
- seqCanvas.calculateWrappedGeometry(seqCanvas.getWidth(),
- seqCanvas.getHeight());
+ seqCanvas.calculateWrappedGeometry();
/*
* yPos modulo height of repeating width
return new MousePos(col, seqIndex, annIndex);
}
-
/**
* Returns the aligned sequence position (base 0) at the mouse position, or
* the closest visible one
if (editCommand != null && editCommand.getSize() > 0)
{
ap.alignFrame.addHistoryItem(editCommand);
- av.firePropertyChange("alignment", null,
- av.getAlignment().getSequences());
+ ap.av.notifyAlignment();
}
} finally
{
void moveCursor(int dx, int dy)
{
- moveCursor(dx, dy, false);
+ moveCursor(dx, dy,false);
}
-
void moveCursor(int dx, int dy, boolean nextWord)
{
HiddenColumns hidden = av.getAlignment().getHiddenColumns();
if (nextWord)
{
int maxWidth = av.getAlignment().getWidth();
- int maxHeight = av.getAlignment().getHeight();
- SequenceI seqAtRow = av.getAlignment()
- .getSequenceAt(seqCanvas.cursorY);
+ int maxHeight=av.getAlignment().getHeight();
+ SequenceI seqAtRow = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
// look for next gap or residue
- boolean isGap = Comparison
- .isGap(seqAtRow.getCharAt(seqCanvas.cursorX));
- int p = seqCanvas.cursorX, lastP, r = seqCanvas.cursorY, lastR;
+ boolean isGap = Comparison.isGap(seqAtRow.getCharAt(seqCanvas.cursorX));
+ int p = seqCanvas.cursorX,lastP,r=seqCanvas.cursorY,lastR;
do
{
lastP = p;
p = nextVisible(hidden, maxWidth, p, dx);
} while ((dx != 0 ? p != lastP : r != lastR)
&& isGap == Comparison.isGap(seqAtRow.getCharAt(p)));
- seqCanvas.cursorX = p;
- seqCanvas.cursorY = r;
- }
- else
- {
+ seqCanvas.cursorX=p;
+ seqCanvas.cursorY=r;
+ } else {
int maxWidth = av.getAlignment().getWidth();
- seqCanvas.cursorX = nextVisible(hidden, maxWidth, seqCanvas.cursorX,
- dx);
+ seqCanvas.cursorX = nextVisible(hidden, maxWidth, seqCanvas.cursorX, dx);
seqCanvas.cursorY += dy;
}
scrollToVisible(false);
}
- private int nextVisible(HiddenColumns hidden, int maxWidth, int original,
- int dx)
+ private int nextVisible(HiddenColumns hidden,int maxWidth, int original, int dx)
{
- int newCursorX = original + dx;
+ int newCursorX=original+dx;
if (av.hasHiddenColumns() && !hidden.isVisible(newCursorX))
{
int visx = hidden.absoluteToVisibleColumn(newCursorX - dx);
}
}
newCursorX = (newCursorX < 0) ? 0 : newCursorX;
- if (newCursorX >= maxWidth || !hidden.isVisible(newCursorX))
+ if (newCursorX >= maxWidth
+ || !hidden.isVisible(newCursorX))
{
newCursorX = original;
}
return newCursorX;
}
-
/**
* Scroll to make the cursor visible in the viewport.
*
if (av.getAlignment().getHiddenColumns().isVisible(seqCanvas.cursorX))
{
setStatusMessage(av.getAlignment().getSequenceAt(seqCanvas.cursorY),
- seqCanvas.cursorX, seqCanvas.cursorY);
+ seqCanvas.cursorX, seqCanvas.cursorY);
}
if (repaintNeeded)
}
}
+
void setSelectionAreaAtCursor(boolean topLeft)
{
SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
SequenceI seq = match.getSequence();
SequenceI ds = seq.getDatasetSequence() == null ? seq
: seq.getDatasetSequence();
- MappedFeatures mf = fr2.findComplementFeaturesAtResidue(ds, pos);
+ MappedFeatures mf = fr2
+ .findComplementFeaturesAtResidue(ds, pos);
if (mf != null)
{
for (SequenceFeature sf : mf.features)
{
List<SequenceFeature> features = ap.getFeatureRenderer()
.findFeaturesAtColumn(sequence, column + 1);
- unshownFeatures = seqARep.appendFeatures(tooltipText, pos, features,
- this.ap.getSeqPanel().seqCanvas.fr, MAX_TOOLTIP_LENGTH);
+ unshownFeatures = seqARep.appendFeatures(tooltipText, pos,
+ features, this.ap.getSeqPanel().seqCanvas.fr,
+ MAX_TOOLTIP_LENGTH);
/*
* add features in CDS/protein complement at the corresponding
pos);
if (mf != null)
{
- unshownFeatures += seqARep.appendFeatures(tooltipText, pos, mf,
- fr2, MAX_TOOLTIP_LENGTH);
+ unshownFeatures += seqARep.appendFeatures(tooltipText,
+ pos, mf, fr2, MAX_TOOLTIP_LENGTH);
}
}
}
if (!textString.equals(lastTooltip))
{
lastTooltip = textString;
- lastFormattedTooltip = JvSwingUtils.wrapTooltip(true, textString);
+ lastFormattedTooltip = JvSwingUtils.wrapTooltip(true,
+ textString);
setToolTipText(lastFormattedTooltip);
}
}
String tooltip = AnnotationPanel.buildToolTip(anns[rowIndex], column,
anns);
- if (tooltip == null ? tooltip != lastTooltip
- : !tooltip.equals(lastTooltip))
+ boolean tooltipChanged = tooltip == null ? lastTooltip != null : !tooltip.equals(lastTooltip);
+ if (tooltipChanged)
{
lastTooltip = tooltip;
lastFormattedTooltip = tooltip == null ? null
tempTip.setTipText(lastFormattedTooltip);
int tipWidth = (int) tempTip.getPreferredSize().getWidth();
-
- // was x += (w - x < 200) ? -(w / 2) : 5;
+
+ // was x += (w - x < 200) ? -(w / 2) : 5;
x = (x + tipWidth < w ? x + 10 : w - tipWidth);
Point p = new Point(x, y + av.getCharHeight()); // BH 2018 was - 20?
* changed, so selective redraws can be applied (ie. only structures, only
* overview, etc)
*/
- private boolean updateOverviewAndStructs = false; // TODO: refactor to
- // avcontroller
+ private boolean updateOverviewAndStructs = false; // TODO: refactor to avcontroller
/**
* set if av.getSelectionGroup() refers to a group that is defined on the
* Sequence number (if known), and sequence name.
*/
String seqno = seqIndex == -1 ? "" : " " + (seqIndex + 1);
- text.append("Sequence").append(seqno).append(" ID: ").append(seqName);
+ text.append("Sequence").append(seqno).append(" ID: ")
+ .append(seqName);
String residue = null;
String label = null;
if (groupEditing)
{
- message.append("Edit group:");
+ message.append("Edit group:");
label = MessageManager.getString("action.edit_group");
}
else
{
- message.append("Edit sequence: " + seq.getName());
+ message.append("Edit sequence: " + seq.getName());
label = seq.getName();
if (label.length() > 10)
{
{
for (int j = 0; j < startres - editLastRes; j++)
{
- if (!Comparison.isGap(groupSeqs[g].getCharAt(fixedRight - j)))
+ if (!Comparison
+ .isGap(groupSeqs[g].getCharAt(fixedRight - j)))
{
blank = false;
break;
* highlight the first feature at the position on the alignment
*/
SearchResultsI highlight = new SearchResults();
- highlight.addResult(sequence, features.get(0).getBegin(),
- features.get(0).getEnd());
+ highlight.addResult(sequence, features.get(0).getBegin(), features
+ .get(0).getEnd());
seqCanvas.highlightSearchResults(highlight, true);
/*
return;
}
- res = Math.min(res, av.getAlignment().getWidth() - 1);
+ res = Math.min(res, av.getAlignment().getWidth()-1);
if (stretchGroup.getEndRes() == res)
{
{
if (av.getAlignment() == null)
{
- Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
+ Console.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
+ " ViewId=" + av.getViewId()
+ " 's alignment is NULL! returning immediately.");
return;
{
return lastSearchResults;
}
+
+ /**
+ * scroll to the given row/column - or nearest visible location
+ *
+ * @param row
+ * @param column
+ */
+ public void scrollTo(int row, int column)
+ {
+
+ row = row < 0 ? ap.av.getRanges().getStartSeq() : row;
+ column = column < 0 ? ap.av.getRanges().getStartRes() : column;
+ ap.scrollTo(column, column, row, true, true);
+ }
+
+ /**
+ * scroll to the given row - or nearest visible location
+ *
+ * @param row
+ */
+ public void scrollToRow(int row)
+ {
+
+ row = row < 0 ? ap.av.getRanges().getStartSeq() : row;
+ ap.scrollTo(ap.av.getRanges().getStartRes(),
+ ap.av.getRanges().getStartRes(), row, true, true);
+ }
+
+ /**
+ * scroll to the given column - or nearest visible location
+ *
+ * @param column
+ */
+ public void scrollToColumn(int column)
+ {
+
+ column = column < 0 ? ap.av.getRanges().getStartRes() : column;
+ ap.scrollTo(column, column, ap.av.getRanges().getStartSeq(), true,
+ true);
+ }
-
}
*/
package jalview.gui;
- import jalview.api.FeatureSettingsModelI;
- import jalview.bin.Cache;
- import jalview.datamodel.AlignmentI;
- import jalview.datamodel.DBRefEntry;
- import jalview.datamodel.SequenceI;
- import jalview.fts.core.GFTSPanel;
- import jalview.fts.service.pdb.PDBFTSPanel;
- import jalview.fts.service.uniprot.UniprotFTSPanel;
- import jalview.io.FileFormatI;
- import jalview.io.gff.SequenceOntologyI;
- import jalview.util.DBRefUtils;
- import jalview.util.MessageManager;
- import jalview.util.Platform;
- import jalview.ws.seqfetcher.DbSourceProxy;
-
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
+ import jalview.api.FeatureSettingsModelI;
+ import jalview.bin.Cache;
+ import jalview.bin.Console;
+ import jalview.datamodel.AlignmentI;
+ import jalview.datamodel.DBRefEntry;
+ import jalview.datamodel.SequenceI;
+ import jalview.fts.core.GFTSPanel;
+ import jalview.fts.service.pdb.PDBFTSPanel;
+ import jalview.fts.service.threedbeacons.TDBeaconsFTSPanel;
+ import jalview.fts.service.uniprot.UniprotFTSPanel;
+ import jalview.io.FileFormatI;
+ import jalview.io.gff.SequenceOntologyI;
+ import jalview.util.DBRefUtils;
+ import jalview.util.MessageManager;
+ import jalview.util.Platform;
+ import jalview.ws.seqfetcher.DbSourceProxy;
+
/**
* A panel where the use may choose a database source, and enter one or more
* accessions, to retrieve entries from the database.
return other.key == this.key;
}
}
+
private static jalview.ws.SequenceFetcher sfetch = null;
JLabel exampleAccession;
frame = new JInternalFrame();
frame.setContentPane(this);
- Desktop.addInternalFrame(frame, getFrameTitle(), true, 400,
- Platform.isAMacAndNotJS() ? 240 : 180);
+ Desktop.addInternalFrame(frame, getFrameTitle(), Desktop.FRAME_MAKE_VISIBLE, 400,
+ Platform.isAMacAndNotJS() ? 240 : 180, Desktop.FRAME_ALLOW_RESIZE, Desktop.FRAME_SET_MIN_SIZE_300);
}
private String getFrameTitle()
}
}
}
+
/**
* Answers a semi-colon-delimited string with the example query or queries for
* the selected database
text = text.replace(",", ";");
}
text = text.replaceAll("(\\s|[; ])+", ";");
- if (!t0.equals(text))
+ if (!t0.equals(text))
{
- textArea.setText(text);
+ textArea.setText(text);
}
if (text.isEmpty())
{
}
} catch (Exception e)
{
- Cache.log.info("Error retrieving " + accession + " from "
+ Console.info("Error retrieving " + accession + " from "
+ proxy.getDbName(), e);
}
return success;
for (String q : queries)
{
- // BH 2019.01.25 dbr is never used.
- // DBRefEntry dbr = new DBRefEntry();
- // dbr.setSource(proxy.getDbSource());
- // dbr.setVersion(null);
+ // BH 2019.01.25 dbr is never used.
+ // DBRefEntry dbr = new DBRefEntry();
+ // dbr.setSource(proxy.getDbSource());
+ // dbr.setVersion(null);
String accId = proxy.getAccessionIdFromQuery(q);
- // dbr.setAccessionId(accId);
+ // dbr.setAccessionId(accId);
boolean rfound = false;
for (int r = 0, nr = rs.length; r < nr; r++)
{
}
}
- af.getViewport().applyFeaturesStyle(preferredFeatureColours);
+ if (preferredFeatureColours != null)
+ {
+ af.getViewport().applyFeaturesStyle(preferredFeatureColours);
+ }
if (Cache.getDefault("HIDE_INTRONS", true))
{
af.hideFeatureColumns(SequenceOntologyI.EXON, false);
@Override
public void run()
{
- JvOptionPane.showInternalMessageDialog(Desktop.desktop, error,
+ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(), error,
MessageManager.getString("label.error_retrieving_data"),
JvOptionPane.WARNING_MESSAGE);
}
if (groups != null && !groups.isEmpty())
{
sliderPanel.setAllGroupsCheckEnabled(true);
+ sliderPanel.allGroupsCheck
+ .setSelected(ap.av.getColourAppliesToAllGroups());
}
else
{
if (!conservationSlider.isVisible())
{
Desktop.addInternalFrame(conservationSlider,
- conservationSlider.getTitle(), true, FRAME_WIDTH,
- FRAME_HEIGHT, false, true);
+ conservationSlider.getTitle(), Desktop.FRAME_MAKE_VISIBLE, FRAME_WIDTH,
+ FRAME_HEIGHT, Desktop.FRAME_NOT_RESIZABLE, Desktop.FRAME_ALLOW_ANY_SIZE);
conservationSlider.addInternalFrameListener(new InternalFrameAdapter()
{
@Override
if (!PIDSlider.isVisible())
{
- Desktop.addInternalFrame(PIDSlider, PIDSlider.getTitle(), true,
- FRAME_WIDTH, FRAME_HEIGHT, false, true);
+ Desktop.addInternalFrame(PIDSlider, PIDSlider.getTitle(), Desktop.FRAME_MAKE_VISIBLE,
+ FRAME_WIDTH, FRAME_HEIGHT, Desktop.FRAME_NOT_RESIZABLE, Desktop.FRAME_ALLOW_ANY_SIZE);
PIDSlider.setLayer(JLayeredPane.PALETTE_LAYER);
PIDSlider.addInternalFrameListener(new InternalFrameAdapter()
{
--- /dev/null
+package jalview.gui;
+
+import jalview.bin.Cache;
++import jalview.bin.Console;
+import jalview.util.MessageManager;
+import jalview.ws.WSDiscovererI;
+import jalview.ws.slivkaws.SlivkaWSDiscoverer;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.concurrent.CompletableFuture;
+
+import javax.swing.BorderFactory;
+import javax.swing.Box;
+import javax.swing.BoxLayout;
+import javax.swing.JButton;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JProgressBar;
+import javax.swing.JScrollPane;
+import javax.swing.JTable;
+import javax.swing.SwingUtilities;
+import javax.swing.UIManager;
+import javax.swing.table.AbstractTableModel;
+import javax.swing.table.DefaultTableCellRenderer;
+
+@SuppressWarnings("serial")
+public class SlivkaPreferences extends JPanel
+{
+ {
+ setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
+ setPreferredSize(new Dimension(500, 450));
+ }
+
+ WSDiscovererI discoverer;
+
+ private final ArrayList<String> urls = new ArrayList<>();
+
+ private final Map<String, Integer> statuses = new HashMap<>();
+
+ private final AbstractTableModel urlTableModel = new AbstractTableModel()
+ {
+ final String[] columnNames = { "Service URL", "Status" };
+
+ @Override
+ public String getColumnName(int col)
+ {
+ return columnNames[col];
+ }
+
+ @Override
+ public Object getValueAt(int rowIndex, int columnIndex)
+ {
+ switch (columnIndex)
+ {
+ case 0:
+ return urls.get(rowIndex);
+ case 1:
+ return statuses.getOrDefault(urls.get(rowIndex), WSDiscovererI.STATUS_UNKNOWN);
+ default:
+ throw new NoSuchElementException();
+ }
+ }
+
+ @Override
+ public int getRowCount()
+ {
+ return urls.size();
+ }
+
+ @Override
+ public int getColumnCount()
+ {
+ return 2;
+ }
+ };
+
+ private class WSStatusCellRenderer extends DefaultTableCellRenderer
+ {
+ @Override
+ public Component getTableCellRendererComponent(JTable table,
+ Object value, boolean isSelected, boolean hasFocus, int row,
+ int column)
+ {
+ setHorizontalAlignment(CENTER);
+ super.getTableCellRendererComponent(table, "\u25CF", isSelected,
+ hasFocus, row, column);
+ switch ((Integer) value)
+ {
+ case WSDiscovererI.STATUS_NO_SERVICES:
+ setForeground(Color.ORANGE);
+ break;
+ case WSDiscovererI.STATUS_OK:
+ setForeground(Color.GREEN);
+ break;
+ case WSDiscovererI.STATUS_INVALID:
+ setForeground(Color.RED);
+ break;
+ case WSDiscovererI.STATUS_UNKNOWN:
+ default:
+ setForeground(Color.LIGHT_GRAY);
+ }
+ return this;
+ }
+ }
+
+ private JTable urlListTable = new JTable(urlTableModel);
+ {
+ urlListTable.getColumnModel().getColumn(1).setMaxWidth(60);
+ urlListTable.getColumnModel().getColumn(1)
+ .setCellRenderer(new WSStatusCellRenderer());
+ }
+
+ // URL control panel buttons
+ JButton newWsUrl = new JButton(
+ MessageManager.getString("label.new_service_url"));
+
+ JButton editWsUrl = new JButton(
+ MessageManager.getString("label.edit_service_url"));
+
+ JButton deleteWsUrl = new JButton(
+ MessageManager.getString("label.delete_service_url"));
+
+ JButton moveUrlUp = new JButton(
+ MessageManager.getString("action.move_up"));
+
+ JButton moveUrlDown = new JButton(
+ MessageManager.getString("action.move_down"));
+
+ private String showEditUrlDialog(String oldUrl)
+ {
+ String input = (String) JvOptionPane
+ .showInternalInputDialog(
+ this,
+ MessageManager.getString("label.url:"),
+ UIManager.getString("OptionPane.inputDialogTitle", MessageManager.getLocale()),
+ JOptionPane.QUESTION_MESSAGE,
+ null,
+ null,
+ oldUrl);
+ if (input == null)
+ {
+ return null;
+ }
+ try
+ {
+ new URL(input);
+ } catch (MalformedURLException ex)
+ {
+ JvOptionPane.showInternalMessageDialog(this,
+ MessageManager.getString("label.invalid_url"),
+ UIManager.getString("OptionPane.messageDialogTitle",
+ MessageManager.getLocale()),
+ JOptionPane.WARNING_MESSAGE);
+ return null;
+ }
+ return input;
+ }
+
+ // Button Action Listeners
+ private ActionListener newUrlAction = (ActionEvent e) -> {
+ final String input = showEditUrlDialog("");
+ if (input != null)
+ {
+ urls.add(input);
+ reloadStatusForUrl(input);
+ urlTableModel.fireTableRowsInserted(urls.size(), urls.size());
+ discoverer.setServiceUrls(urls);
+ }
+ };
+
+ private ActionListener editUrlAction = (ActionEvent e) -> {
+ final int i = urlListTable.getSelectedRow();
+ if (i >= 0)
+ {
+ final String input = showEditUrlDialog(urls.get(i));
+ if (input != null)
+ {
+ urls.set(i, input);
+ statuses.remove(input);
+ reloadStatusForUrl(input);
+ urlTableModel.fireTableRowsUpdated(i, i);
+ discoverer.setServiceUrls(urls);
+ }
+ }
+ };
+
+ private ActionListener deleteUrlAction = (ActionEvent e) -> {
+ final int i = urlListTable.getSelectedRow();
+ if (i >= 0)
+ {
+ urls.remove(i);
+ statuses.remove(i);
+ urlTableModel.fireTableRowsDeleted(i, i);
+ discoverer.setServiceUrls(urls);
+ }
+ };
+
+ private ActionListener moveUrlUpAction = (ActionEvent e) -> {
+ final int i = urlListTable.getSelectedRow();
+ if (i > 0)
+ {
+ moveTableRow(i, i - 1);
+ discoverer.setServiceUrls(urls);
+ }
+ };
+
+ private ActionListener moveUrlDownAction = (ActionEvent e) -> {
+ final int i = urlListTable.getSelectedRow();
+ if (i >= 0 && i < urls.size() - 1)
+ {
+ moveTableRow(i, i + 1);
+ discoverer.setServiceUrls(urls);
+ }
+ };
+
+ private MouseListener tableClickListener = new MouseAdapter()
+ {
+ final ActionEvent actionEvent = new ActionEvent(urlListTable,
+ ActionEvent.ACTION_PERFORMED, "edit");
+
+ @Override
+ public void mouseClicked(MouseEvent e)
+ {
+ if (e.getClickCount() > 1)
+ {
+ editUrlAction.actionPerformed(actionEvent);
+ }
+ }
+ };
+
+ // Setting up URL list Pane
+ {
+ Font font = new Font("Verdana", Font.PLAIN, 10);
+ JPanel urlPaneContainer = new JPanel(new BorderLayout(5, 5));
+ urlPaneContainer.setBorder(BorderFactory.createCompoundBorder(
+ BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
+ "Slivka Web Services"),
+ BorderFactory.createEmptyBorder(10, 5, 5, 5)));
+
+ newWsUrl.setFont(font);
+ editWsUrl.setFont(font);
+ deleteWsUrl.setFont(font);
+ moveUrlUp.setFont(font);
+ moveUrlDown.setFont(font);
+ JPanel editContainer = new JPanel();
+ editContainer.add(newWsUrl);
+ editContainer.add(editWsUrl);
+ editContainer.add(deleteWsUrl);
+ urlPaneContainer.add(editContainer, BorderLayout.PAGE_END);
+
+ JPanel moveContainer = new JPanel();
+ moveContainer
+ .setLayout(new BoxLayout(moveContainer, BoxLayout.PAGE_AXIS));
+ moveContainer.add(moveUrlUp);
+ moveContainer.add(Box.createRigidArea(new Dimension(0, 5)));
+ moveContainer.add(moveUrlDown);
+ urlPaneContainer.add(moveContainer, BorderLayout.LINE_START);
+
+ urlPaneContainer.add(new JScrollPane(urlListTable),
+ BorderLayout.CENTER);
+ this.add(urlPaneContainer);
+
+ // Connecting action listeners
+ urlListTable.addMouseListener(tableClickListener);
+ newWsUrl.addActionListener(newUrlAction);
+ editWsUrl.addActionListener(editUrlAction);
+ deleteWsUrl.addActionListener(deleteUrlAction);
+ moveUrlUp.addActionListener(moveUrlUpAction);
+ moveUrlDown.addActionListener(moveUrlDownAction);
+ }
+
+ private void moveTableRow(int fromIndex, int toIndex)
+ {
+ String url = urls.get(fromIndex);
+ int status = statuses.get(fromIndex);
+ urls.set(fromIndex, urls.get(toIndex));
+ urls.set(toIndex, url);
+ if (urlListTable.getSelectedRow() == fromIndex)
+ {
+ urlListTable.setRowSelectionInterval(toIndex, toIndex);
+ }
+ int firstRow = Math.min(toIndex, fromIndex);
+ int lastRow = Math.max(fromIndex, toIndex);
+ urlTableModel.fireTableRowsUpdated(firstRow, lastRow);
+ }
+
+ // Discoverer reloading buttons
+ JButton refreshServices = new JButton(
+ MessageManager.getString("action.refresh_services"));
+
+ JButton resetServices = new JButton(
+ MessageManager.getString("action.reset_services"));
+
+ JProgressBar progressBar = new JProgressBar();
+
+ // Discoverer buttons action listeners
+ private ActionListener refreshServicesAction = (ActionEvent e) -> {
+ progressBar.setVisible(true);
- Cache.log.info("Requesting service reload");
++ Console.info("Requesting service reload");
+ discoverer.startDiscoverer().handle((_discoverer, exception) -> {
+ if (exception == null)
+ {
- Cache.log.info("Reloading done");
++ Console.info("Reloading done");
+ }
+ else
+ {
- Cache.log.error("Reloading failed", exception);
++ Console.error("Reloading failed", exception);
+ }
+ SwingUtilities.invokeLater(() -> progressBar.setVisible(false));
+ return null;
+ });
+ };
+
+ private ActionListener resetServicesAction = (ActionEvent e) -> {
+ discoverer.setServiceUrls(null);
+ urls.clear();
+ statuses.clear();
+ urls.addAll(discoverer.getServiceUrls());
+ for (String url : urls)
+ {
+ reloadStatusForUrl(url);
+ }
+ urlTableModel.fireTableDataChanged();
+ };
+
+ {
+ Font font = new Font("Verdana", Font.PLAIN, 11);
+ refreshServices.setFont(font);
+ resetServices.setFont(font);
+ JPanel container = new JPanel();
+ container.add(refreshServices);
+ container.add(resetServices);
+ this.add(container);
+
+ // Connecting action listeners
+ refreshServices.addActionListener(refreshServicesAction);
+ resetServices.addActionListener(resetServicesAction);
+ }
+
+ {
+ progressBar.setVisible(false);
+ progressBar.setIndeterminate(true);
+ add(progressBar);
+ }
+
+ SlivkaPreferences()
+ {
+ // Initial URLs loading
+ discoverer = SlivkaWSDiscoverer.getInstance();
+ urls.addAll(discoverer.getServiceUrls());
+ for (String url : urls)
+ {
+ reloadStatusForUrl(url);
+ }
+ }
+
+ private void reloadStatusForUrl(String url)
+ {
+ CompletableFuture.supplyAsync(() -> discoverer.getServerStatusFor(url))
+ .thenAccept((status) -> {
+ statuses.put(url, status);
+ int row = urls.indexOf(url);
+ if (row >= 0)
+ urlTableModel.fireTableCellUpdated(row, 1);
+ });
+ }
+}
*/
package jalview.gui;
-
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import jalview.util.ChannelProperties;
import jalview.util.Platform;
+
++import javajs.async.SwingJSUtils.StateHelper;
++import javajs.async.SwingJSUtils.StateMachine;
++
/**
* DOCUMENT ME!
*
* @author $author$
* @version $Revision$
*/
+@SuppressWarnings("serial")
public class SplashScreen extends JPanel
- implements Runnable, HyperlinkListener
+ implements HyperlinkListener, StateMachine
{
+
+ private static final int STATE_INIT = 0;
+
+ private static final int STATE_LOOP = 1;
+
+ private static final int STATE_DONE = 2;
-
private static final int SHOW_FOR_SECS = 5;
- private static final int FONT_SIZE = 11;
+ private static final int FONT_SIZE = (Platform.isJS() ? 14 : 11);
private boolean visible = true;
private static Color fg = Color.BLACK;
+ private static Font font = new Font("SansSerif", Font.PLAIN, FONT_SIZE);
+
++ private JPanel imgPanel = new JPanel(new BorderLayout());
++
/*
* as JTextPane in Java, JLabel in javascript
*/
private JInternalFrame iframe;
-- private Image image;
++ private Image image, logo;
private boolean transientDialog = false;
private long oldTextLength = -1;
++ private StateHelper helper;
+ public static int logoSize = 32;
+
/*
* allow click in the initial splash screen to dismiss it
* immediately (not if opened from About menu)
{
try
{
- visible = false;
closeSplash();
} catch (Exception ex)
{
/**
* Constructor that displays the splash screen
*
- * @param isTransient
+ * @param isStartup
* if true the panel removes itself on click or after a few seconds;
- * if false it stays up until closed by the user
+ * if false it stays up until closed by the user (from Help..About menu)
*/
- public SplashScreen(boolean isTransient)
+ public SplashScreen(boolean isStartup)
{
- this.transientDialog = isTransient;
+ this.transientDialog = isStartup;
+ // we must get the image in JavaScript BEFORE starting the helper,
+ // as it will take a 1 ms clock tick to obtain width and height information.
+ image = ChannelProperties.getImage("banner");
+ logo = ChannelProperties.getImage("logo.48");
+ font = new Font("SansSerif", Font.PLAIN, FONT_SIZE);
+ helper = new StateHelper(this);
+ helper.next(STATE_INIT);
+ }
- if (Platform.isJS()) // BH 2019
- {
- splashText = new JLabel("");
- run();
- }
- else
- {
- /**
- * Java only
- *
- * @j2sIgnore
- */
- {
- splashText = new JTextPane();
- splashText.setBackground(bg);
- splashText.setForeground(fg);
- splashText.setFont(font);
- Thread t = new Thread(this);
- t.start();
- }
- }
+ protected void initSplashScreenWindow()
+ {
+ addMouseListener(closer);
+ waitForImages();
+ setLayout(new BorderLayout());
+ iframe = new JInternalFrame();
+ iframe.setFrameIcon(null);
+ iframe.setClosable(true);
+ iframe.setContentPane(this);
+ iframe.setLayer(JLayeredPane.PALETTE_LAYER);
+ SplashImage splashimg = new SplashImage(image);
+ imgPanel.add(splashimg, BorderLayout.CENTER);
+ add(imgPanel, BorderLayout.NORTH);
+ Desktop.getDesktopPane().add(iframe);
+ refreshText();
}
/**
- * ping the jalview version page then create and display the jalview
- * splashscreen window.
+ * Both Java and JavaScript have to wait for images, but this method will
+ * accomplish nothing for JavaScript. We have already taken care of image
+ * loading with our state loop in JavaScript.
+ *
*/
- void initSplashScreenWindow()
+ private void waitForImages()
{
- addMouseListener(closer);
-
- try
+ if (Platform.isJS())
+ return;
+ MediaTracker mt = new MediaTracker(this);
+ mt.addImage(image, 0);
+ mt.addImage(logo, 1);
+ do
{
- if (!Platform.isJS())
+ try
+ {
+ mt.waitForAll();
+ } catch (InterruptedException x)
{
- image = ChannelProperties.getImage("banner");
- Image logo = ChannelProperties.getImage("logo.48");
- MediaTracker mt = new MediaTracker(this);
- if (image != null)
- {
- mt.addImage(image, 0);
- }
- if (logo != null)
- {
- mt.addImage(logo, 1);
- }
- do
- {
- try
- {
- mt.waitForAll();
- } catch (InterruptedException x)
- {
- }
- if (mt.isErrorAny())
- {
- System.err.println("Error when loading images!");
- }
- } while (!mt.checkAll());
- Desktop.instance.setIconImages(ChannelProperties.getIconList());
}
- } catch (Exception ex)
+ if (mt.isErrorAny())
+ {
+ System.err.println("Error when loading images!");
+ break;
+ }
+ } while (!mt.checkAll());
+ if (logo != null)
{
+ Desktop.getInstance().setIconImage(logo);
}
+
this.setBackground(bg);
this.setForeground(fg);
this.setFont(font);
+ }
- iframe = new JInternalFrame();
- iframe.setFrameIcon(null);
- iframe.setClosable(true);
- this.setLayout(new BorderLayout());
- iframe.setContentPane(this);
- iframe.setLayer(JLayeredPane.PALETTE_LAYER);
- iframe.setBackground(bg);
- iframe.setForeground(fg);
- iframe.setFont(font);
-
- if (Platform.isJS())
+ /**
+ * update text in author text panel reflecting current version information
+ */
+ protected boolean refreshText()
+ {
+ String newtext = Desktop.getInstance().getAboutMessage();
+ // System.err.println("Text found: \n"+newtext+"\nEnd of newtext.");
+ if (oldTextLength == newtext.length())
{
- // ignore in JavaScript
+ return false;
+ }
+
+ iframe.setVisible(false);
+ oldTextLength = newtext.length();
+ if (Platform.isJS()) // BH 2019
+ {
+ /*
+ * SwingJS doesn't have HTMLEditorKit, required for a JTextPane
+ * to display formatted html, so we use a simple alternative
+ */
+ String text = "<html><br><img src=\""
+ + ChannelProperties.getImageURL("banner") + "\"/>" + newtext
+ + "<br></html>";
+ JLabel ta = new JLabel(text);
+ ta.setOpaque(true);
+ ta.setBackground(Color.white);
+ splashText = ta;
}
else
/**
* Java only
- *
+ *
* @j2sIgnore
*/
{
- ((JTextPane) splashText).setEditable(false);
- splashText.setBackground(bg);
- splashText.setForeground(fg);
- splashText.setFont(font);
-
- SplashImage splashimg = new SplashImage(image);
- iconimg.add(splashimg, BorderLayout.LINE_START);
- iconimg.setBackground(bg);
- add(iconimg, BorderLayout.NORTH);
+ JTextPane jtp = new JTextPane();
+ jtp.setEditable(false);
+ jtp.setBackground(bg);
+ jtp.setForeground(fg);
+ jtp.setFont(font);
+ jtp.setContentType("text/html");
+ jtp.setText("<html>" + newtext + "</html>");
+ jtp.addHyperlinkListener(this);
+ splashText = jtp;
}
- add(splashText, BorderLayout.CENTER);
splashText.addMouseListener(closer);
- Desktop.desktop.add(iframe);
- refreshText();
+
+ splashText.setVisible(true);
+ splashText.setSize(new Dimension(750,
+ 375 + logoSize + (Platform.isJS() ? 40 : 0)));
+ splashText.setBackground(bg);
+ splashText.setForeground(fg);
+ splashText.setFont(font);
+ add(splashText, BorderLayout.CENTER);
+ revalidate();
+ int width = Math.max(splashText.getWidth(), iconimg.getWidth());
+ int height = splashText.getHeight() + iconimg.getHeight();
+ iframe.setBounds((iframe.getParent().getWidth() - width) / 2,
- (iframe.getParent().getHeight() - height) / 2, 750,
++ (iframe.getParent().getHeight() - height) / 2,
+ width,height);
+ iframe.validate();
+ iframe.setVisible(true);
+ return true;
}
- /**
- * update text in author text panel reflecting current version information
- */
- protected boolean refreshText()
+ protected void closeSplash()
{
- String newtext = Desktop.instance.getAboutMessage();
- // System.err.println("Text found: \n"+newtext+"\nEnd of newtext.");
- if (oldTextLength != newtext.length())
+ try
+ {
+
+ iframe.setClosed(true);
+ } catch (Exception ex)
{
- iframe.setVisible(false);
- oldTextLength = newtext.length();
- if (Platform.isJS()) // BH 2019
- {
- /*
- * SwingJS doesn't have HTMLEditorKit, required for a JTextPane
- * to display formatted html, so we use a simple alternative
- */
- String text = "<html><br><img src=\""
- + ChannelProperties.getImageURL("banner") + "\"/>" + newtext
- + "<br></html>";
- JLabel ta = new JLabel(text);
- ta.setOpaque(true);
- ta.setBackground(Color.white);
- splashText = ta;
- }
- else
- /**
- * Java only
- *
- * @j2sIgnore
- */
- {
- JTextPane jtp = new JTextPane();
- jtp.setEditable(false);
- jtp.setBackground(bg);
- jtp.setForeground(fg);
- jtp.setFont(font);
- jtp.setContentType("text/html");
- jtp.setText("<html>" + newtext + "</html>");
- jtp.addHyperlinkListener(this);
- splashText = jtp;
- }
- splashText.addMouseListener(closer);
-
- splashText.setVisible(true);
- splashText.setSize(new Dimension(750,
- 425 + logoSize + (Platform.isJS() ? 40 : 0)));
- splashText.setBackground(bg);
- splashText.setForeground(fg);
- splashText.setFont(font);
- add(splashText, BorderLayout.CENTER);
- revalidate();
- int width = Math.max(splashText.getWidth(), iconimg.getWidth());
- int height = splashText.getHeight() + iconimg.getHeight();
- iframe.setBounds(
- Math.max(0, (Desktop.instance.getWidth() - width) / 2),
- Math.max(0, (Desktop.instance.getHeight() - height) / 2),
- width, height);
- iframe.validate();
- iframe.setVisible(true);
- return true;
}
}
/**
- * Create splash screen, display it and clear it off again.
+ * A simple state machine with just three states: init, loop, and done. Ideal
+ * for a simple while/sleep loop that works in Java and JavaScript
+ * identically.
+ *
*/
@Override
- public void run()
+ public boolean stateLoop()
{
- initSplashScreenWindow();
-
- long startTime = System.currentTimeMillis() / 1000;
-
- while (visible)
+ while (true)
{
- iframe.repaint();
- try
+ switch (helper.getState())
{
- Thread.sleep(500);
- } catch (Exception ex)
- {
- }
-
- if (transientDialog && ((System.currentTimeMillis() / 1000)
- - startTime) > SHOW_FOR_SECS)
- {
- visible = false;
- }
-
- if (visible && refreshText())
- {
- iframe.repaint();
- }
- if (!transientDialog)
- {
- return;
+ case STATE_INIT:
+ initSplashScreenWindow();
+ helper.setState(STATE_LOOP);
+ continue;
+ case STATE_LOOP:
+ if (!isVisible())
+ {
+ helper.setState(STATE_DONE);
+ continue;
+ }
+ if (refreshText())
+ {
+ iframe.repaint();
+ }
- if (isStartup)
++ if (transientDialog)
+ helper.delayedState(SHOW_FOR_SECS * 1000, STATE_DONE);
+ return true;
+ default:
+ case STATE_DONE:
+ setVisible(false);
+ closeSplash();
+ Desktop.getInstance().startDialogQueue();
+ return true;
}
}
+
- closeSplash();
- Desktop.instance.startDialogQueue();
- }
-
- /**
- * DOCUMENT ME!
- */
- public void closeSplash()
- {
- try
- {
-
- iframe.setClosed(true);
- } catch (Exception ex)
- {
- }
}
- public class SplashImage extends JPanel
+ private class SplashImage extends JPanel
{
Image image;
*/
package jalview.gui;
+import jalview.api.AlignViewportI;
+import jalview.api.AlignViewControllerGuiI;
+import jalview.api.FeatureSettingsControllerI;
+import jalview.api.SplitContainerI;
+import jalview.controller.FeatureSettingsControllerGuiI;
+import jalview.datamodel.AlignmentI;
+import jalview.jbgui.GAlignFrame;
+import jalview.jbgui.GSplitFrame;
+import jalview.structure.StructureSelectionManager;
+import jalview.util.MessageManager;
+import jalview.util.Platform;
+import jalview.viewmodel.AlignmentViewport;
-
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
-import jalview.api.AlignViewControllerGuiI;
-import jalview.api.FeatureSettingsControllerI;
-import jalview.api.SplitContainerI;
-import jalview.controller.FeatureSettingsControllerGuiI;
-import jalview.datamodel.AlignmentI;
-import jalview.jbgui.GAlignFrame;
-import jalview.jbgui.GSplitFrame;
-import jalview.structure.StructureSelectionManager;
-import jalview.util.MessageManager;
-import jalview.util.Platform;
-import jalview.viewmodel.AlignmentViewport;
+
/**
* An internal frame on the desktop that hosts a horizontally split view of
* linked DNA and Protein alignments. Additional views can be created in linked
// allow about 65 pixels for Desktop decorators on Windows
int newHeight = Math.min(height,
- Desktop.instance.getHeight() - DESKTOP_DECORATORS_HEIGHT);
+ Desktop.getInstance().getHeight() - DESKTOP_DECORATORS_HEIGHT);
if (newHeight != height)
{
int oldDividerLocation = getDividerLocation();
// TODO if CommandListener is only ever 1:1 for complementary views,
// may change broadcast pattern to direct messaging (more efficient)
final StructureSelectionManager ssm = StructureSelectionManager
- .getStructureSelectionManager(Desktop.instance);
+ .getStructureSelectionManager(Desktop.getInstance());
ssm.addCommandListener(((AlignFrame) getTopFrame()).getViewport());
ssm.addCommandListener(((AlignFrame) getBottomFrame()).getViewport());
}
topFrame.alignPanel.adjustAnnotationHeight();
bottomFrame.alignPanel.adjustAnnotationHeight();
- final AlignViewport topViewport = topFrame.viewport;
- final AlignViewport bottomViewport = bottomFrame.viewport;
+ final AlignViewportI topViewport = topFrame.viewport;
+ final AlignViewportI bottomViewport = bottomFrame.viewport;
final AlignmentI topAlignment = topViewport.getAlignment();
final AlignmentI bottomAlignment = bottomViewport.getAlignment();
boolean topAnnotations = topViewport.isShowAnnotation();
* calculate the maximum ratio that leaves at least the height
* of two sequences (after rounding) visible in the bottom panel
*/
- int bottomSequencesHeight = bottomFrame.alignPanel
- .getSeqPanel().seqCanvas.getHeight();
+ int bottomSequencesHeight = bottomFrame.alignPanel.getSeqPanel().seqCanvas
+ .getHeight();
int bottomPanelMinHeight = bottomPanelHeight
- Math.max(0, bottomSequencesHeight - 3 * bottomCharHeight);
double maxRatio = (totalHeight - bottomPanelMinHeight) / totalHeight;
* Ctrl-W / Cmd-W - close view or window
*/
KeyStroke key_cmdW = KeyStroke.getKeyStroke(KeyEvent.VK_W,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
action = new AbstractAction()
{
@Override
* Ctrl-T / Cmd-T open new view
*/
KeyStroke key_cmdT = KeyStroke.getKeyStroke(KeyEvent.VK_T,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
AbstractAction action = new AbstractAction()
{
@Override
adjustLayout();
final StructureSelectionManager ssm = StructureSelectionManager
- .getStructureSelectionManager(Desktop.instance);
+ .getStructureSelectionManager(Desktop.getInstance());
ssm.addCommandListener(newTopPanel.av);
ssm.addCommandListener(newBottomPanel.av);
}
*/
protected void expandViews_actionPerformed()
{
- Desktop.instance.explodeViews(this);
+ Desktop.getInstance().explodeViews(this);
}
/**
*/
protected void gatherViews_actionPerformed()
{
- Desktop.instance.gatherViews(this);
+ Desktop.getInstance().gatherViews(this);
}
/**
* Ctrl-F / Cmd-F open Finder dialog, 'focused' on the right alignment
*/
KeyStroke key_cmdF = KeyStroke.getKeyStroke(KeyEvent.VK_F,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
AbstractAction action = new AbstractAction()
{
@Override
}
/**
- * holds the frame for feature settings, so Protein and DNA tabs can be
- * managed
+ * holds the frame for feature settings, so Protein and DNA tabs can be managed
*/
JInternalFrame featureSettingsUI;
{
return featureSettingsUI != null && !featureSettingsUI.isClosed();
}
-}
+}
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
+import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
+
import jalview.api.structures.JalviewStructureDisplayI;
import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.bin.Jalview;
import jalview.datamodel.PDBEntry;
import jalview.datamodel.SequenceI;
public class StructureChooser extends GStructureChooser
implements IProgressIndicator
{
-- private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
++ protected static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
+ /**
+ * warn user if need to fetch more than this many uniprot records at once
+ */
+ private static final int THRESHOLD_WARN_UNIPROT_FETCH_NEEDED = 20;
-
private SequenceI selectedSequence;
private SequenceI[] selectedSequences;
List<SequenceI> seqsWithoutSourceDBRef = null;
-- private static StructureViewer lastTargetedView = null;
++ protected static StructureViewer lastTargetedView = null;
public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
AlignmentPanel ap)
// which FTS engine to use
data = StructureChooserQuerySource.getQuerySourceFor(selectedSeqs);
initDialog();
+
this.ap = ap;
this.selectedSequence = selectedSeq;
this.selectedSequences = selectedSeqs;
this.progressIndicator = (ap == null) ? null : ap.alignFrame;
init();
+
}
/**
Executors.defaultThreadFactory().newThread(new Runnable()
{
+ @Override
public void run()
{
populateSeqsWithoutSourceDBRef();
// ensure a filter option is in force for search
populateFilterComboBox(true, cachedPDBExists);
+
// looks for any existing structures already loaded
// for the sequences (the cached ones)
// then queries the StructureChooserQuerySource to
/**
* raises dialog for Uniprot fetch followed by 3D beacons search
- * @param ignoreGui - when true, don't ask, just fetch
+ *
+ * @param ignoreGui
+ * - when true, don't ask, just fetch
*/
public void promptForTDBFetch(boolean ignoreGui)
{
{
mainFrame.setEnabled(false);
cmb_filterOption.setEnabled(false);
- progressBar.setProgressBar(MessageManager.getString("status.searching_3d_beacons"), progressId);
+ progressBar.setProgressBar(
+ MessageManager.getString("status.searching_3d_beacons"),
+ progressId);
+ btn_queryTDB.setEnabled(false);
// TODO: warn if no accessions discovered
populateSeqsWithoutSourceDBRef();
// redo initial discovery - this time with 3d beacons
// Executors.
- previousWantedFields=null;
- lastSelected=(FilterOption) cmb_filterOption.getSelectedItem();
+ previousWantedFields = null;
+ lastSelected = (FilterOption) cmb_filterOption.getSelectedItem();
cmb_filterOption.setSelectedItem(null);
- cachedPDBExists = false; // reset to initial
+ cachedPDBExists=false; // reset to initial
initialStructureDiscovery();
if (!isStructuresDiscovered())
{
- progressBar.setProgressBar(MessageManager.getString("status.no_structures_discovered_from_3d_beacons"), progressId);
- btn_queryTDB.setToolTipText(MessageManager.getString("status.no_structures_discovered_from_3d_beacons"));
+ progressBar.setProgressBar(MessageManager.getString(
+ "status.no_structures_discovered_from_3d_beacons"),
+ progressId);
+ btn_queryTDB.setToolTipText(MessageManager.getString(
+ "status.no_structures_discovered_from_3d_beacons"));
btn_queryTDB.setEnabled(false);
- } else {
+ pnl_queryTDB.setVisible(false);
+ }
+ else
+ {
cmb_filterOption.setSelectedIndex(0); // select 'best'
btn_queryTDB.setVisible(false);
+ pnl_queryTDB.setVisible(false);
progressBar.setProgressBar(null, progressId);
}
mainFrame.setEnabled(true);
final FetchFinishedListenerI afterDbRefFetch = new FetchFinishedListenerI()
{
-
+
@Override
public void finished()
{
notQueriedTDBYet = false;
// new thread to discover structures - via 3d beacons
Executors.defaultThreadFactory().newThread(strucDiscovery).start();
-
+
}
};
-
+
// fetch db refs if OK pressed
- final Runnable discoverCanonicalDBrefs = new Runnable()
+ final Runnable discoverCanonicalDBrefs = new Runnable()
{
@Override
public void run()
{
+ btn_queryTDB.setEnabled(false);
populateSeqsWithoutSourceDBRef();
final int y = seqsWithoutSourceDBRef.size();
{ new jalview.ws.dbsources.Uniprot() }, null, false);
dbRefFetcher.addListener(afterDbRefFetch);
// ideally this would also gracefully run with callbacks
-
dbRefFetcher.fetchDBRefs(true);
- } else {
+ }
+ else
+ {
// call finished action directly
afterDbRefFetch.finished();
}
}
};
- final Runnable revertview = new Runnable() {
- public void run() {
- if (lastSelected!=null) {
+ final Runnable revertview = new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ if (lastSelected != null)
+ {
cmb_filterOption.setSelectedItem(lastSelected);
}
};
};
- if (ignoreGui)
+ int threshold = Cache.getDefault("UNIPROT_AUTOFETCH_THRESHOLD",
+ THRESHOLD_WARN_UNIPROT_FETCH_NEEDED);
+ Console.debug("Using Uniprot fetch threshold of " + threshold);
+ if (ignoreGui || seqsWithoutSourceDBRef.size() < threshold)
{
- Executors.defaultThreadFactory().newThread(discoverCanonicalDBrefs)
- .start();
+ Executors.defaultThreadFactory().newThread(discoverCanonicalDBrefs).start();
return;
}
// need cancel and no to result in the discoverPDB action - mocked is
// 'cancel' TODO: mock should be OK
- JvOptionPane.newOptionDialog(this)
-
+ StructureChooser thisSC = this;
+ JvOptionPane.newOptionDialog(thisSC.getFrame())
.setResponseHandler(JvOptionPane.OK_OPTION,
discoverCanonicalDBrefs)
.setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
MessageManager.formatMessage(
"label.fetch_references_for_3dbeacons",
seqsWithoutSourceDBRef.size()),
- MessageManager.getString("label.3dbeacons"),
+ MessageManager
+ .getString("label.3dbeacons"),
JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
null, new Object[]
{ MessageManager.getString("action.ok"),
MessageManager.getString("action.cancel") },
- MessageManager.getString("action.ok"));
+ MessageManager.getString("action.ok"), false);
}
/**
*/
private void discoverStructureViews()
{
- if (Desktop.instance != null)
+ if (Desktop.getInstance() != null)
{
targetView.removeAllItems();
if (lastTargetedView != null && !lastTargetedView.isVisible())
lastTargetedView = null;
}
int linkedViewsAt = 0;
- for (StructureViewerBase view : Desktop.instance
+ for (StructureViewerBase view : Desktop.getInstance()
.getStructureViewers(null, null))
{
StructureViewer viewHandler = (lastTargetedView != null
discoveredStructuresSet = new LinkedHashSet<>();
HashSet<String> errors = new HashSet<>();
+
FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
.getSelectedItem());
+
for (SequenceI seq : selectedSequences)
{
+
FTSRestResponse resultList;
try
{
{
getResultTable()
.setModel(data.getTableModel(discoveredStructuresSet));
+
noOfStructuresFound = discoveredStructuresSet.size();
lastDiscoveredStructuresSet = discoveredStructuresSet;
mainFrame.setTitle(MessageManager.formatMessage(
{
Thread filterThread = new Thread(new Runnable()
{
+
@Override
public void run()
{
for (SequenceI seq : selectedSequences)
{
+
FTSRestResponse resultList;
try
{
resultList = data.selectFirstRankedQuery(seq,
discoveredStructuresSet, wantedFields, fieldToFilterBy,
!chk_invertFilter.isSelected());
+
} catch (Exception e)
{
e.printStackTrace();
// StructureChooser
// works
jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
- jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
+ Cache.getProperty("LAST_DIRECTORY"));
chooser.setFileView(new jalview.io.JalviewFileView());
chooser.setDialogTitle(
MessageManager.formatMessage("label.select_pdb_file_for",
if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
{
selectedPdbFileName = chooser.getSelectedFile().getPath();
- jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
+ Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
validateSelections();
}
}
protected void populateFilterComboBox(boolean haveData,
boolean cachedPDBExist, FilterOption lastSel)
{
+
/*
* temporarily suspend the change listener behaviour
*/
cmb_filterOption.removeItemListener(this);
-
int selSet = -1;
cmb_filterOption.removeAllItems();
if (haveData)
cmb_filterOption.addItem(filter);
}
}
+
cmb_filterOption.addItem(
new FilterOption(MessageManager.getString("label.enter_pdb_id"),
"-", VIEWS_ENTER_ID, false, null));
if (canQueryTDB && notQueriedTDBYet)
{
btn_queryTDB.setVisible(true);
+ pnl_queryTDB.setVisible(true);
}
if (cachedPDBExist)
cmb_filterOption.setSelectedItem(cachedOption);
}
}
-
if (selSet > -1)
{
cmb_filterOption.setSelectedIndex(selSet);
{
FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
.getSelectedItem());
-
+
if (lastSelected == selectedFilterOpt)
{
// don't need to do anything, probably
// otherwise, record selection
// and update the layout and dialog accordingly
lastSelected = selectedFilterOpt;
+
layout_switchableViews.show(pnl_switchableViews,
selectedFilterOpt.getView());
String filterTitle = mainFrame.getTitle();
mainFrame.setTitle(frameTitle);
chk_invertFilter.setVisible(false);
-
+
if (selectedFilterOpt.getView() == VIEWS_FILTER)
{
mainFrame.setTitle(filterTitle);
FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
.getSelectedItem());
String currentView = selectedFilterOpt.getView();
-
- if (currentView == VIEWS_FILTER && data instanceof ThreeDBStructureChooserQuerySource)
-
+ if (currentView == VIEWS_FILTER
+ && data instanceof ThreeDBStructureChooserQuerySource)
{
-
- TDB_FTSData row=((ThreeDBStructureChooserQuerySource)data).getFTSDataFor(getResultTable(), selectedRow, discoveredStructuresSet);
- String pageUrl = row.getModelViewUrl();
-
+ TDB_FTSData row = ((ThreeDBStructureChooserQuerySource) data)
+ .getFTSDataFor(getResultTable(), selectedRow,
+ discoveredStructuresSet);
+ String pageUrl = row.getModelViewUrl();
JPopupMenu popup = new JPopupMenu("3D Beacons");
JMenuItem viewUrl = new JMenuItem("View model web page");
- viewUrl.addActionListener(
- new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e)
- {
- Desktop.showUrl(pageUrl);
- }
- }
- );
+ viewUrl.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ Desktop.showUrl(pageUrl);
+ }
+ });
popup.add(viewUrl);
- SwingUtilities.invokeLater(new Runnable() {
- public void run() { popup.show(getResultTable(), x, y); }
+ SwingUtilities.invokeLater(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ popup.show(getResultTable(), x, y);
+ }
});
return true;
}
// event not handled by us
return false;
}
-
/**
* Validates inputs from the Manual PDB entry panel
*/
{
validateSelections();
}
--
- private FilterOption lastSelected = null;
-
+ private FilterOption lastSelected=null;
/**
* Handles the state change event for the 'filter' combo-box and 'invert'
* check-box
}
return found;
}
+
/**
* Handles the 'New View' action
*/
{
final StructureSelectionManager ssm = ap.getStructureSelectionManager();
--
++ final StructureViewer theViewer = getTargetedStructureViewer(ssm);
++ boolean superimpose = chk_superpose.isSelected();
final int preferredHeight = pnl_filter.getHeight();
Runnable viewStruc = new Runnable()
SequenceI[] selectedSeqs = selectedSeqsToView
.toArray(new SequenceI[selectedSeqsToView.size()]);
-- sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
-- selectedSeqs);
++ sViewer = StructureViewer.launchStructureViewer(ap, pdbEntriesToView,
++ selectedSeqs, superimpose, theViewer, progressBar);
}
else if (currentView == VIEWS_LOCAL_PDB)
{
{
PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
.getModel()).getPDBEntryAt(row).getPdbEntry();
+
pdbEntriesToView[count++] = pdbEntry;
SequenceI selectedSeq = (SequenceI) tbl_local_pdb
.getValueAt(row, refSeqColIndex);
}
SequenceI[] selectedSeqs = selectedSeqsToView
.toArray(new SequenceI[selectedSeqsToView.size()]);
-- sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
-- selectedSeqs);
++ sViewer = StructureViewer.launchStructureViewer(ap, pdbEntriesToView,
++ selectedSeqs, superimpose, theViewer, progressBar);
}
else if (currentView == VIEWS_ENTER_ID)
{
if (pdbIdStr.split(":").length > 1)
{
pdbEntry.setId(pdbIdStr.split(":")[0]);
- pdbEntry.setChainCode(
- pdbIdStr.split(":")[1].toUpperCase(Locale.ROOT));
+ pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase(Locale.ROOT));
}
else
{
}
PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
-- sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
-- new SequenceI[]
-- { selectedSequence });
++ sViewer = StructureViewer.launchStructureViewer(ap, pdbEntriesToView,
++ new SequenceI[]
++ { selectedSequence }, superimpose, theViewer,
++ progressBar);
}
else if (currentView == VIEWS_FROM_FILE)
{
{
selectedSequence = userSelectedSeq;
}
-- PDBEntry fileEntry = new AssociatePdbFileWithSeq()
-- .associatePdbWithSeq(selectedPdbFileName,
-- DataSourceType.FILE, selectedSequence, true,
- Desktop.getInstance());
-
- sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
- ap, new SequenceI[]
- { selectedSequence });
- Desktop.instance);
-
- sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
- ap, new SequenceI[]
- { selectedSequence });
++ PDBEntry fileEntry = AssociatePdbFileWithSeq.associatePdbWithSeq(selectedPdbFileName,
++ DataSourceType.FILE, selectedSequence, true);
++
++ sViewer = StructureViewer.launchStructureViewer(ap, new PDBEntry[] { fileEntry },
++ new SequenceI[] { selectedSequence }, superimpose, theViewer,
++ progressBar);
}
SwingUtilities.invokeLater(new Runnable()
{
}
/**
-- * Adds PDB structures to a new or existing structure viewer
-- *
-- * @param ssm
-- * @param pdbEntriesToView
-- * @param alignPanel
-- * @param sequences
-- * @return
-- */
-- private StructureViewer launchStructureViewer(
-- StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
-- final AlignmentPanel alignPanel, SequenceI[] sequences)
-- {
-- long progressId = sequences.hashCode();
-- setProgressBar(MessageManager
-- .getString("status.launching_3d_structure_viewer"), progressId);
-- final StructureViewer theViewer = getTargetedStructureViewer(ssm);
-- boolean superimpose = chk_superpose.isSelected();
-- theViewer.setSuperpose(superimpose);
--
-- /*
-- * remember user's choice of superimpose or not
-- */
-- Cache.setProperty(AUTOSUPERIMPOSE,
-- Boolean.valueOf(superimpose).toString());
--
-- setProgressBar(null, progressId);
-- if (SiftsSettings.isMapWithSifts())
-- {
-- List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
-- int p = 0;
-- // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
-- // real PDB ID. For moment, we can also safely do this if there is already
-- // a known mapping between the PDBEntry and the sequence.
-- for (SequenceI seq : sequences)
-- {
-- PDBEntry pdbe = pdbEntriesToView[p++];
-- if (pdbe != null && pdbe.getFile() != null)
-- {
-- StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
-- if (smm != null && smm.length > 0)
-- {
-- for (StructureMapping sm : smm)
-- {
-- if (sm.getSequence() == seq)
-- {
-- continue;
-- }
-- }
-- }
-- }
-- if (seq.getPrimaryDBRefs().isEmpty())
-- {
-- seqsWithoutSourceDBRef.add(seq);
-- continue;
-- }
-- }
-- if (!seqsWithoutSourceDBRef.isEmpty())
-- {
-- int y = seqsWithoutSourceDBRef.size();
-- setProgressBar(MessageManager.formatMessage(
-- "status.fetching_dbrefs_for_sequences_without_valid_refs",
-- y), progressId);
-- SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
-- .toArray(new SequenceI[y]);
-- DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
-- dbRefFetcher.fetchDBRefs(true);
--
-- setProgressBar("Fetch complete.", progressId); // todo i18n
-- }
-- }
-- if (pdbEntriesToView.length > 1)
-- {
-- setProgressBar(
-- MessageManager.getString(
-- "status.fetching_3d_structures_for_selected_entries"),
-- progressId);
-- theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
-- }
-- else
-- {
-- setProgressBar(MessageManager.formatMessage(
-- "status.fetching_3d_structures_for",
-- pdbEntriesToView[0].getId()), progressId);
-- theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
-- }
-- setProgressBar(null, progressId);
-- // remember the last viewer we used...
-- lastTargetedView = theViewer;
-- return theViewer;
-- }
--
-- /**
* Populates the combo-box used in associating manually fetched structures to
* a unique sequence when more than one sequence selection is made.
*/
{
if (selectedSequences != null)
{
+ lbl_loading.setVisible(true);
Thread refreshThread = new Thread(new Runnable()
{
@Override
{
fetchStructuresMetaData();
// populateFilterComboBox(true, cachedPDBExists);
+
filterResultSet(
((FilterOption) cmb_filterOption.getSelectedItem())
.getValue());
+ lbl_loading.setVisible(false);
}
});
refreshThread.start();
{
progressBar.setProgressBar(message, id);
}
+
+ @Override
+ public void removeProgressBar(long id)
+ {
+ progressBar.removeProgressBar(id);
+ }
@Override
public void registerHandler(long id, IProgressIndicatorHandler handler)
&& mainFrame.isVisible()
&& cmb_filterOption.getSelectedItem() != null;
}
-
/**
*
* @return true if the 3D-Beacons query button will/has been displayed
*/
- public boolean isCanQueryTDB() {
- return canQueryTDB;
+ public boolean isCanQueryTDB()
+ {
+ return canQueryTDB;
}
public boolean isNotQueriedTDBYet()
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-
import jalview.api.structures.JalviewStructureDisplayI;
import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.PDBEntry;
import jalview.datamodel.SequenceI;
import jalview.datamodel.StructureViewerModel;
++import jalview.structure.StructureMapping;
import jalview.structure.StructureSelectionManager;
++import jalview.util.MessageManager;
++import jalview.util.Platform;
++import jalview.ws.DBRefFetcher;
++import jalview.ws.seqfetcher.DbSourceProxy;
++import jalview.ws.sifts.SiftsSettings;
++
+
/**
* A proxy for handling structure viewers, that orchestrates adding selected
*/
public class StructureViewer
{
+
+ static
+ {
+ Platform.loadStaticResource("core/core_jvjmol.z.js",
+ "org.jmol.viewer.Viewer");
+ }
+
+
+
+
private static final String UNKNOWN_VIEWER_TYPE = "Unknown structure viewer type ";
StructureSelectionManager ssm;
*
* @param structureSelectionManager
*/
- public StructureViewer(StructureSelectionManager structureSelectionManager)
+ public StructureViewer(
+ StructureSelectionManager structureSelectionManager)
{
ssm = structureSelectionManager;
}
return sv;
}
-
@Override
public String toString()
{
}
return "New View";
}
+
/**
*
- * @return ViewerType for currently configured structure viewer
+ * @return ViewerType for currently configured structure viewer
*/
public static ViewerType getViewerType()
{
Map<PDBEntry, SequenceI[]> seqsForPdbs = getSequencesForPdbs(pdbs,
seqs);
- PDBEntry[] pdbsForFile = seqsForPdbs.keySet().toArray(
- new PDBEntry[seqsForPdbs.size()]);
- SequenceI[][] theSeqs = seqsForPdbs.values().toArray(
- new SequenceI[seqsForPdbs.size()][]);
+ PDBEntry[] pdbsForFile = seqsForPdbs.keySet()
+ .toArray(new PDBEntry[seqsForPdbs.size()]);
+ SequenceI[][] theSeqs = seqsForPdbs.values()
+ .toArray(new SequenceI[seqsForPdbs.size()][]);
if (sview != null)
{
sview.setAlignAddedStructures(superposeAdded);
}
else
{
- Cache.log.error(UNKNOWN_VIEWER_TYPE + getViewerType().toString());
+ Console.error(UNKNOWN_VIEWER_TYPE + getViewerType().toString());
}
return sview;
}
}
else
{
- Cache.log.error(UNKNOWN_VIEWER_TYPE + getViewerType().toString());
+ Console.error(UNKNOWN_VIEWER_TYPE + getViewerType().toString());
}
return sview;
}
* Creates a new panel controlling a structure viewer
*
* @param type
+ * @param pdbf
+ * @param id
+ * @param sq
* @param alignPanel
* @param viewerData
* @param sessionFile
String sessionFile, String vid)
{
JalviewStructureDisplayI viewer = null;
+
switch (type)
{
case JMOL:
viewer = new PymolViewer(viewerData, alignPanel, sessionFile, vid);
break;
default:
- Cache.log.error(UNKNOWN_VIEWER_TYPE + type.toString());
+ Console.error(UNKNOWN_VIEWER_TYPE + type.toString());
}
return viewer;
}
superposeAdded = alignAddedStructures;
}
++ /**
++ * Launch a minimal implementation of a StructureViewer.
++ *
++ * @param alignPanel
++ * @param pdb
++ * @param seqs
++ * @return
++ */
++ public static StructureViewer launchStructureViewer(
++ AlignmentPanel alignPanel, PDBEntry pdb, SequenceI[] seqs)
++ {
++ return launchStructureViewer(alignPanel, new PDBEntry[] { pdb }, seqs,
++ false, null, null);
++ }
++
++ /**
++ * Adds PDB structures to a new or existing structure viewer
++ *
++ * @param ssm
++ * @param pdbEntriesToView
++ * @param alignPanel
++ * @param sequences
++ * @return
++ */
++ protected static StructureViewer launchStructureViewer(
++ final AlignmentPanel ap, final PDBEntry[] pdbEntriesToView,
++ SequenceI[] sequences, boolean superimpose,
++ StructureViewer theViewer, IProgressIndicator pb)
++ {
++ final StructureSelectionManager ssm = ap.getStructureSelectionManager();
++ if (theViewer == null)
++ theViewer = new StructureViewer(ssm);
++ long progressId = sequences.hashCode();
++ if (pb != null)
++ pb.setProgressBar(MessageManager.getString(
++ "status.launching_3d_structure_viewer"), progressId);
++ theViewer.setSuperpose(superimpose);
++
++ /*
++ * remember user's choice of superimpose or not
++ */
++ Cache.setProperty(StructureChooser.AUTOSUPERIMPOSE,
++ Boolean.valueOf(superimpose).toString());
++
++ if (pb != null)
++ pb.setProgressBar(null, progressId);
++ if (SiftsSettings.isMapWithSifts())
++ {
++ List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
++ int p = 0;
++ // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
++ // real PDB ID. For moment, we can also safely do this if there is already
++ // a known mapping between the PDBEntry and the sequence.
++ for (SequenceI seq : sequences)
++ {
++ PDBEntry pdbe = pdbEntriesToView[p++];
++ if (pdbe != null && pdbe.getFile() != null)
++ {
++ StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
++ if (smm != null && smm.length > 0)
++ {
++ for (StructureMapping sm : smm)
++ {
++ if (sm.getSequence() == seq)
++ {
++ continue;
++ }
++ }
++ }
++ }
++ if (seq.getPrimaryDBRefs().isEmpty())
++ {
++ seqsWithoutSourceDBRef.add(seq);
++ continue;
++ }
++ }
++ if (!seqsWithoutSourceDBRef.isEmpty())
++ {
++ int y = seqsWithoutSourceDBRef.size();
++ if (pb != null)
++ pb.setProgressBar(MessageManager.formatMessage(
++ "status.fetching_dbrefs_for_sequences_without_valid_refs",
++ y), progressId);
++ SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
++ .toArray(new SequenceI[y]);
++ DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
++ dbRefFetcher.fetchDBRefs(true);
++
++ if (pb != null)
++ pb.setProgressBar("Fetch complete.", progressId); // todo i18n
++ }
++ }
++ if (pdbEntriesToView.length > 1)
++ {
++ if (pb != null)
++ pb.setProgressBar(MessageManager.getString(
++ "status.fetching_3d_structures_for_selected_entries"),
++ progressId);
++ theViewer.viewStructures(pdbEntriesToView, sequences, ap);
++ }
++ else
++ {
++ if (pb != null)
++ pb.setProgressBar(MessageManager.formatMessage(
++ "status.fetching_3d_structures_for",
++ pdbEntriesToView[0].getId()), progressId);
++ theViewer.viewStructures(pdbEntriesToView[0], sequences, ap);
++ }
++ if (pb != null)
++ pb.setProgressBar(null, progressId);
++ // remember the last viewer we used...
++ StructureChooser.lastTargetedView = theViewer;
++ return theViewer;
++ }
++
}
import jalview.api.AlignmentViewPanel;
import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.PDBEntry;
import jalview.datamodel.SequenceI;
{
alignAddedStructures = alignAdded;
}
-
+
/**
- * called by the binding model to indicate when adding structures is happening or has been completed
+ * called by the binding model to indicate when adding structures is happening
+ * or has been completed
+ *
* @param addingStructures
*/
public synchronized void setAddingStructures(boolean addingStructures)
*/
protected List<StructureViewerBase> getViewersFor(AlignmentPanel alp)
{
- return Desktop.instance.getStructureViewers(alp, this.getClass());
+ return Desktop.getInstance().getStructureViewers(alp, this.getClass());
}
@Override
{
return;
}
- AlignmentPanel alignPanel = (AlignmentPanel) apanel; // Implementation error if this
- // cast fails
+ AlignmentPanel alignPanel = (AlignmentPanel) apanel; // Implementation error
+ // if this
+ // cast fails
useAlignmentPanelForSuperposition(alignPanel);
addStructure(pdbentry, seq, chains, alignPanel.alignFrame);
}
public void changeColour_actionPerformed(String colourSchemeName)
{
AlignmentI al = getAlignmentPanel().av.getAlignment();
- ColourSchemeI cs = ColourSchemes.getInstance()
- .getColourScheme(colourSchemeName, getAlignmentPanel().av, al,
- null);
+ ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(
+ colourSchemeName, getAlignmentPanel().av, al, null);
getBinding().colourByJalviewColourScheme(cs);
}
{
sp.append("'" + alignPanel.getViewName() + "' ");
}
- Cache.log.info("Couldn't align structures with the " + sp.toString()
+ Console.info("Couldn't align structures with the " + sp.toString()
+ "associated alignment panels.", e);
}
return reply;
{
return false;
}
- int p=0;
- for (String pdbid:pdbids) {
+ int p = 0;
+ for (String pdbid : pdbids)
+ {
StructureMapping sm[] = getBinding().getSsm().getMapping(pdbid);
- if (sm!=null && sm.length>0 && sm[0]!=null) {
+ if (sm != null && sm.length > 0 && sm[0] != null)
+ {
p++;
}
}
- // only return true if there is a mapping for every structure file we have loaded
+ // only return true if there is a mapping for every structure file we have
+ // loaded
if (p == 0 || p != pdbids.length)
{
return false;
{
String filePath = null;
Pdb pdbclient = new Pdb();
- EBIAlfaFold afclient = new EBIAlfaFold();
+ EBIAlfaFold afclient = new EBIAlfaFold();
AlignmentI pdbseq = null;
String pdbid = processingEntry.getId();
long handle = System.currentTimeMillis()
+ Thread.currentThread().hashCode();
-
+
/*
* Write 'fetching PDB' progress on AlignFrame as we are not yet visible
*/
{
if (afclient.isValidReference(pdbid))
{
- pdbseq = afclient.getSequenceRecords(pdbid);
- } else {
- if (processingEntry.hasRetrievalUrl())
+ pdbseq = afclient.getSequenceRecords(pdbid,
+ processingEntry.getRetrievalUrl());
+ }
+ else
+ {
+ if (processingEntry.hasRetrievalUrl())
+ {
+ String safePDBId = java.net.URLEncoder.encode(pdbid, "UTF-8")
+ .replace("%", "__");
+
+ // retrieve from URL to new local tmpfile
+ File tmpFile = File.createTempFile(safePDBId,
+ "." + (PDBEntry.Type.MMCIF.toString().equals(
+ processingEntry.getType().toString()) ? "cif"
+ : "pdb"));
+ String fromUrl = processingEntry.getRetrievalUrl();
+ UrlDownloadClient.download(fromUrl, tmpFile);
+
+ // may not need this check ?
+ String file = tmpFile.getAbsolutePath();
+ if (file != null)
{
- // retrieve from URL to new local tmpfile
- File tmpFile = File.createTempFile(pdbid,
- "." + (PDBEntry.Type.MMCIF.toString().equals(
- processingEntry.getType().toString()) ? "cif"
- : "pdb"));
- String fromUrl = processingEntry.getRetrievalUrl();
- UrlDownloadClient.download(fromUrl, tmpFile);
-
- // may not need this check ?
- String file = tmpFile.getAbsolutePath();
- if (file != null)
- {
- pdbseq = EBIAlfaFold.importDownloadedStructureFromUrl(fromUrl,tmpFile,pdbid,null,null,null);
- }
- } else {
- pdbseq = pdbclient.getSequenceRecords(pdbid);
+ pdbseq = EBIAlfaFold.importDownloadedStructureFromUrl(fromUrl,
+ tmpFile, pdbid, null, null, null);
}
+ }
+ else
+ {
+ pdbseq = pdbclient.getSequenceRecords(pdbid);
+ }
}
} catch (Exception e)
{
*/
public File saveSession()
{
- if (getBinding() == null) { return null;}
+ if (getBinding() == null)
+ {
+ return null;
+ }
File session = getBinding().saveSession();
long l = session.length();
- int wait=50;
- do {
- try {
+ int wait = 50;
+ do
+ {
+ try
+ {
Thread.sleep(5);
- } catch (InterruptedException e) {
- }
+ } catch (InterruptedException e)
+ {
+ }
long nextl = session.length();
- if (nextl!=l)
+ if (nextl != l)
{
wait = 50;
- l=nextl;
+ l = nextl;
}
- } while (--wait>0);
+ } while (--wait > 0);
return session;
}
@Override
public void showHelp_actionPerformed()
{
+ /*
try
{
- String url = getBinding().getHelpURL();
- if (url != null)
- {
- BrowserLauncher.openURL(url);
- }
- } catch (IOException ex)
+ */
+ String url = getBinding().getHelpURL();
+ if (url != null)
+ {
+ BrowserLauncher.openURL(url);
+ }
+ /*
+ }
+ catch (IOException ex)
{
System.err
.println("Show " + getViewerName() + " failed with: "
+ ex.getMessage());
}
+ */
}
+
@Override
public boolean hasViewerActionsMenu()
{
if (showDistances && (node.dist > 0))
{
- nodeLabel = new Format("%-.2f").form(node.dist);
+ nodeLabel = new Format("%g").form(node.dist);
}
if (showBootstrap && node.bootstrap > -1)
if (showDistances && (node.dist > 0))
{
- nodeLabel = new Format("%-.2f").form(node.dist);
+ nodeLabel = new Format("%g").form(node.dist);
}
if (showBootstrap && node.bootstrap > -1)
if ((node.left() == null) && (node.right() == null))
{
double height = node.height;
- // double dist = node.dist;
- // int xstart = (int) ((height - dist) * wscale) + offx;
+ // double dist = node.dist;
+ // int xstart = (int) ((height - dist) * wscale) + offx;
int xend = (int) (height * wscale) + offx;
int ypos = (int) (node.ycount * chunk) + offy;
*/
if (e.isPopupTrigger())
{
- chooseSubtreeColour();
+ if (highlightNode != null) {
+ chooseSubtreeColour();
+ }
e.consume(); // prevent mouseClicked happening
}
}
void chooseSubtreeColour()
{
String ttl = MessageManager.getString("label.select_subtree_colour");
- ColourChooserListener listener = new ColourChooserListener() {
+ ColourChooserListener listener = new ColourChooserListener()
+ {
@Override
public void colourSelected(Color c)
{
repaint();
}
};
- JalviewColourChooser.showColourChooser(this, ttl, highlightNode.color, listener);
+ JalviewColourChooser.showColourChooser(this, ttl, highlightNode.color,
+ listener);
}
@Override
if (ob instanceof SequenceI)
{
treeSelectionChanged((Sequence) ob);
- PaintRefresher.Refresh(tp, getAssociatedPanel().av.getSequenceSetId());
+ PaintRefresher.Refresh(tp,
+ getAssociatedPanel().av.getSequenceSetId());
repaint();
av.sendSelection();
return;
}
}
- PaintRefresher.Refresh(tp, getAssociatedPanel().av.getSequenceSetId());
+ PaintRefresher.Refresh(tp,
+ getAssociatedPanel().av.getSequenceSetId());
repaint();
}
import jalview.analysis.scoremodels.ScoreModels;
import jalview.api.analysis.ScoreModelI;
import jalview.api.analysis.SimilarityParamsI;
+ import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.commands.CommandI;
import jalview.commands.OrderCommand;
import jalview.datamodel.Alignment;
{
final PropertyChangeListener listener = new PropertyChangeListener()
{
+ @SuppressWarnings("unchecked")
@Override
public void propertyChange(PropertyChangeEvent evt)
{
- if (evt.getPropertyName().equals("alignment"))
- {
+ switch (evt.getPropertyName()) {
+ case AlignmentViewport.PROPERTY_ALIGNMENT:
if (tree == null)
{
System.out.println("tree is null");
{
System.out.println(
"new alignment sequences vector value is null");
+ return;
}
tree.updatePlaceHolders((List<SequenceI>) evt.getNewValue());
treeCanvas.nameHash.clear(); // reset the mapping between canvas
// rectangles and leafnodes
repaint();
+ break;
}
}
};
}
else
{
- ScoreModelI sm = ScoreModels.getInstance()
- .getScoreModel(scoreModelName,
- treeCanvas.getAssociatedPanel());
+ ScoreModelI sm = ScoreModels.getInstance().getScoreModel(
+ scoreModelName, treeCanvas.getAssociatedPanel());
TreeBuilder njtree = treeType.equals(TreeBuilder.NEIGHBOUR_JOINING)
? new NJTree(av, sm, similarityParams)
: new AverageDistanceTree(av, sm, similarityParams);
{
// TODO: JAL-3048 save newick file for Jalview-JS
JalviewFileChooser chooser = new JalviewFileChooser(
- jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
+ Cache.getProperty("LAST_DIRECTORY"));
chooser.setFileView(new JalviewFileView());
chooser.setDialogTitle(
MessageManager.getString("label.save_tree_as_newick"));
if (value == JalviewFileChooser.APPROVE_OPTION)
{
String choice = chooser.getSelectedFile().getPath();
- jalview.bin.Cache.setProperty("LAST_DIRECTORY",
+ Cache.setProperty("LAST_DIRECTORY",
chooser.getSelectedFile().getParent());
try
AlignmentView originalData = tree.getOriginalData();
if (originalData == null)
{
- jalview.bin.Cache.log.info(
+ Console.info(
"Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
return;
}
}
else
{
- treeCanvas.getAssociatedPanel().alignFrame
- .addHistoryItem(
- sortAlignmentIn(treeCanvas.getAssociatedPanel()));
+ treeCanvas.getAssociatedPanel().alignFrame.addHistoryItem(
+ sortAlignmentIn(treeCanvas.getAssociatedPanel()));
}
}
String tree = MessageManager.getString("label.tree");
ImageExporter exporter = new ImageExporter(writer, null, imageFormat,
tree);
- exporter.doExport(null, this, width, height, tree.toLowerCase(Locale.ROOT));
+ exporter.doExport(null, this, width, height,
+ tree.toLowerCase(Locale.ROOT));
}
/**
/*
* i18n description of Neighbour Joining or Average Distance method
*/
- String treecalcnm = MessageManager
- .getString("label.tree_calc_" + treeType.toLowerCase(Locale.ROOT));
+ String treecalcnm = MessageManager.getString(
+ "label.tree_calc_" + treeType.toLowerCase(Locale.ROOT));
/*
* short score model name (long description can be too long)
int width = treeCanvas.getWidth();
int height = treeCanvas.getHeight();
- FileOutputStream out = new FileOutputStream(
- outFile);
+ FileOutputStream out = new FileOutputStream(outFile);
EpsGraphics2D pg = new EpsGraphics2D("Tree", out, 0, 0, width,
height);
pg.setAccurateTextMode(!textOption);
ex.printStackTrace();
}
}
-
+
public AlignViewport getViewport()
{
return av;
frame = new JInternalFrame();
frame.setContentPane(this);
Desktop.addInternalFrame(frame,
- MessageManager.getString("label.user_defined_colours"),
- MY_FRAME_WIDTH, MY_FRAME_HEIGHT, true);
+ MessageManager.getString("label.user_defined_colours"), Desktop.FRAME_MAKE_VISIBLE,
+ MY_FRAME_WIDTH, MY_FRAME_HEIGHT, Desktop.FRAME_ALLOW_RESIZE, Desktop.FRAME_SET_MIN_SIZE_300);
}
/**
{
int row = i / cols + 1;
int index = (row * cols) + i;
- JButton button = makeButton(ResidueProperties.aa[i].toLowerCase(Locale.ROOT),
- ResidueProperties.aa[i].toLowerCase(Locale.ROOT), lowerCaseButtons, i);
+ JButton button = makeButton(
+ ResidueProperties.aa[i].toLowerCase(Locale.ROOT),
+ ResidueProperties.aa[i].toLowerCase(Locale.ROOT),
+ lowerCaseButtons, i);
buttonPanel.add(button, index);
}
{
if (isNoSelectionMade())
{
- JvOptionPane.showMessageDialog(Desktop.desktop,
+ JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
MessageManager
.getString("label.no_colour_selection_in_scheme"),
MessageManager.getString("label.no_colour_selection_warn"),
String[] options = new String[] { title,
MessageManager.getString("label.dont_save_changes"), };
final String question = JvSwingUtils.wrapTooltip(true, message);
- int response = JvOptionPane.showOptionDialog(Desktop.desktop,
+ int response = JvOptionPane.showOptionDialog(Desktop.getDesktopPane(),
question, title, JvOptionPane.DEFAULT_OPTION,
JvOptionPane.PLAIN_MESSAGE, null, options, options[0]);
{
if (isNoSelectionMade())
{
- JvOptionPane.showMessageDialog(Desktop.desktop,
+ JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
MessageManager
.getString("label.no_colour_selection_in_scheme"),
MessageManager.getString("label.no_colour_selection_warn"),
chooser.setDialogTitle(
MessageManager.getString("label.load_colour_scheme"));
chooser.setToolTipText(MessageManager.getString("action.load"));
- chooser.setResponseHandler(0, new Runnable()
+ chooser.setResponseHandler(0, new Runnable()
{
- @Override
- public void run()
- {
- File choice = chooser.getSelectedFile();
- Cache.setProperty(LAST_DIRECTORY, choice.getParent());
-
- UserColourScheme ucs = ColourSchemeLoader
- .loadColourScheme(choice.getAbsolutePath());
- Color[] colors = ucs.getColours();
- schemeName.setText(ucs.getSchemeName());
-
- if (ucs.getLowerCaseColours() != null)
- {
- caseSensitive.setSelected(true);
- lcaseColour.setEnabled(true);
- resetButtonPanel(true);
- for (int i = 0; i < lowerCaseButtons.size(); i++)
- {
- JButton button = lowerCaseButtons.get(i);
- button.setBackground(ucs.getLowerCaseColours()[i]);
- }
- }
- else
- {
- caseSensitive.setSelected(false);
- lcaseColour.setEnabled(false);
- resetButtonPanel(false);
- }
-
- for (int i = 0; i < upperCaseButtons.size(); i++)
- {
- JButton button = upperCaseButtons.get(i);
- button.setBackground(colors[i]);
- }
-
- addNewColourScheme(choice.getPath());
- }
- });
-
+ @Override
+ public void run()
+ {
+ File choice = chooser.getSelectedFile();
+ Cache.setProperty(LAST_DIRECTORY, choice.getParent());
+
+ UserColourScheme ucs = ColourSchemeLoader
+ .loadColourScheme(choice.getAbsolutePath());
+ Color[] colors = ucs.getColours();
+ schemeName.setText(ucs.getSchemeName());
+
+ if (ucs.getLowerCaseColours() != null)
+ {
+ caseSensitive.setSelected(true);
+ lcaseColour.setEnabled(true);
+ resetButtonPanel(true);
+ for (int i = 0; i < lowerCaseButtons.size(); i++)
+ {
+ JButton button = lowerCaseButtons.get(i);
+ button.setBackground(ucs.getLowerCaseColours()[i]);
+ }
+ }
+ else
+ {
+ caseSensitive.setSelected(false);
+ lcaseColour.setEnabled(false);
+ resetButtonPanel(false);
+ }
+
+ for (int i = 0; i < upperCaseButtons.size(); i++)
+ {
+ JButton button = upperCaseButtons.get(i);
+ button.setBackground(colors[i]);
+ }
+
+ addNewColourScheme(choice.getPath());
+ }
+ });
+
chooser.showOpenDialog(this);
}
String name = schemeName.getText().trim();
if (name.length() < 1)
{
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
MessageManager
.getString("label.user_colour_scheme_must_have_name"),
MessageManager.getString("label.no_name_colour_scheme"),
* @j2sIgnore
*/
{
- int reply = JvOptionPane.showInternalConfirmDialog(Desktop.desktop,
+ int reply = JvOptionPane.showInternalConfirmDialog(Desktop.getDesktopPane(),
MessageManager.formatMessage(
"label.colour_scheme_exists_overwrite", new Object[]
{ name, name }),
*/
package jalview.gui;
-import jalview.bin.Cache;
-import jalview.bin.Console;
-import jalview.util.MessageManager;
+
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
+ import javax.swing.JOptionPane;
+
++import jalview.bin.Cache;
++import jalview.bin.Console;
+import jalview.util.MessageManager;
+
public class UserQuestionnaireCheck implements Runnable
{
/**
{
if (url.indexOf("questionnaire.pl") == -1)
{
- jalview.bin.Cache.log.error("'" + url
+ Console.error("'" + url
+ "' is an Invalid URL for the checkForQuestionnaire() method.\n"
+ "This argument is only for questionnaires derived from jalview's questionnaire.pl cgi interface.");
}
private boolean checkresponse(URL qurl) throws Exception
{
- jalview.bin.Cache.log.debug("Checking Response for : " + qurl);
+ Console.debug("Checking Response for : " + qurl);
boolean prompt = false;
// see if we have already responsed to this questionnaire or get a new
// qid/rid pair
try
{
// First - check to see if wee have an old questionnaire/response id pair.
- String lastq = jalview.bin.Cache.getProperty("QUESTIONNAIRE");
+ String lastq = Cache.getProperty("QUESTIONNAIRE");
if (lastq == null)
{
prompt = checkresponse(new URL(url
if (qid != null && rid != null)
{
// Update our local property cache with latest qid and rid
- jalview.bin.Cache.setProperty("QUESTIONNAIRE", qid + ":" + rid);
+ Cache.setProperty("QUESTIONNAIRE", qid + ":" + rid);
}
if (prompt)
{
String qurl = url + (url.indexOf('?') > -1 ? "&" : "?") + "qid="
+ qid + "&rid=" + rid;
- jalview.bin.Cache.log
- .info("Prompting user for questionnaire at " + qurl);
+ Console.info("Prompting user for questionnaire at " + qurl);
- int reply = JvOptionPane.showInternalConfirmDialog(Desktop.desktop,
+ int reply = JvOptionPane.showInternalConfirmDialog(Desktop.getDesktopPane(),
MessageManager.getString("label.jalview_new_questionnaire"),
MessageManager.getString("label.jalview_user_survey"),
JvOptionPane.YES_NO_OPTION, JvOptionPane.QUESTION_MESSAGE);
if (reply == JvOptionPane.YES_OPTION)
{
- jalview.bin.Cache.log.debug("Opening " + qurl);
+ Console.debug("Opening " + qurl);
jalview.util.BrowserLauncher.openURL(qurl);
}
}
} catch (Exception e)
{
- jalview.bin.Cache.log
- .warn("When trying to access questionnaire URL " + url, e);
+ Console.warn("When trying to access questionnaire URL " + url, e);
}
}
package jalview.gui;
import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.ColumnSelection;
import jalview.datamodel.HiddenColumns;
}
} catch (InvalidSessionDocumentException e)
{
- JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
++ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
MessageManager.getString(
"label.vamsas_doc_couldnt_be_opened_as_new_session"),
} catch (Exception e)
{
- jalview.bin.Cache.log.error("Couldn't instantiate vamsas client !",
- e);
+ Console.error("Couldn't instantiate vamsas client !", e);
return false;
}
return true;
}
} catch (Error e)
{
- Cache.log.warn(
+ Console.warn(
"Probable SERIOUS VAMSAS client incompatibility - carrying on regardless",
e);
} catch (Exception e)
{
- Cache.log.warn(
+ Console.warn(
"Probable VAMSAS client incompatibility - carrying on regardless",
e);
}
private ClientHandle getJalviewHandle()
{
return new ClientHandle("jalview.bin.Jalview",
- jalview.bin.Cache.getProperty("VERSION"));
+ Cache.getProperty("VERSION"));
}
/**
addStoreDocumentHandler();
startSession();
inInitialUpdate = true;
- Cache.log.debug(
- "Jalview loading the Vamsas Session for the first time.");
+ Console.debug("Jalview loading the Vamsas Session for the first time.");
dealWithDocumentUpdate(false); // we don't push an update out to the
inInitialUpdate = false;
// document yet.
- Cache.log.debug("... finished update for the first time.");
+ Console.debug("... finished update for the first time.");
}
/**
}
} catch (Exception e)
{
- Cache.log.warn(
+ Console.warn(
"Exception whilst refreshing jalview windows after a vamsas document update.",
e);
}
@Override
public void run()
{
- Cache.log.info("Jalview updating to the Vamsas Session.");
+ Console.info("Jalview updating to the Vamsas Session.");
dealWithDocumentUpdate(true);
- Cache.log.info("Jalview finished updating to the Vamsas Session.");
+ Console.info("Jalview finished updating to the Vamsas Session.");
}
});
{
throw new Error("Jalview not connected to Vamsas session");
}
- Cache.log.info("Jalview disconnecting from the Vamsas Session.");
+ Console.info("Jalview disconnecting from the Vamsas Session.");
try
{
if (joinedSession)
boolean ourprompt = this.promptUser;
this.promptUser = promptUser;
vclient.finalizeClient();
- Cache.log.info("Jalview has left the session.");
+ Console.info("Jalview has left the session.");
this.promptUser = ourprompt; // restore default value
}
else
{
- Cache.log.warn(
+ Console.warn(
"JV Client leaving a session that's its not joined yet.");
}
joinedSession = false;
vobj2jv = null;
} catch (Exception e)
{
- Cache.log.error("Vamsas Session finalization threw exceptions!", e);
+ Console.error("Vamsas Session finalization threw exceptions!", e);
}
}
public void updateJalview(IClientDocument cdoc)
{
- Cache.log.debug("Jalview updating from sesion document ..");
+ Console.debug("Jalview updating from sesion document ..");
ensureJvVamsas();
VamsasAppDatastore vds = new VamsasAppDatastore(cdoc, vobj2jv, jv2vobj,
baseProvEntry(), alRedoState);
vds.updateToJalview();
} catch (Exception e)
{
- Cache.log.error("Failed to update Jalview from vamsas document.", e);
+ Console.error("Failed to update Jalview from vamsas document.", e);
}
try
{
}
} catch (Exception e)
{
- Cache.log.error(
+ Console.error(
"Exception when updating Jalview settings from Appdata.", e);
}
- Cache.log.debug(".. finished updating from sesion document.");
+ Console.debug(".. finished updating from sesion document.");
}
VamsasAppDatastore vds = new VamsasAppDatastore(doc, vobj2jv, jv2vobj,
baseProvEntry(), alRedoState);
// wander through frames
- JInternalFrame[] frames = Desktop.desktop.getAllFrames();
+ JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
if (frames == null)
{
} catch (Exception e)
{
errorsDuringUpdate = true;
- Cache.log.error("Exception synchronizing " + af.getTitle()
- + " "
+ Console.error("Exception synchronizing " + af.getTitle() + " "
+ (af.getViewport().getViewName() == null ? ""
: " view " + af.getViewport().getViewName())
+ " to document.", e);
}
} catch (Exception e)
{
- Cache.log.error("Exception synchronizing Views to Document :", e);
+ Console.error("Exception synchronizing Views to Document :", e);
errorsDuringUpdate = true;
}
}
} catch (Exception e)
{
- Cache.log.error("Client Appdata Write exception", e);
+ Console.error("Client Appdata Write exception", e);
errorsDuringAppUpdate = true;
}
vds.clearSkipList();
{
int storedviews = 0;
// called by update handler for document update.
- Cache.log.debug("Updating jalview from changed vamsas document.");
+ Console.debug("Updating jalview from changed vamsas document.");
disableGui(true);
try
{
long time = System.currentTimeMillis();
IClientDocument cdoc = vclient.getClientDocument();
- if (Cache.log.isDebugEnabled())
+ if (Console.isDebugEnabled())
{
- Cache.log.debug("Time taken to get ClientDocument = "
+ Console.debug("Time taken to get ClientDocument = "
+ (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
}
if (fromJalview)
{
storedviews += updateVamsasDocument(cdoc);
- if (Cache.log.isDebugEnabled())
+ if (Console.isDebugEnabled())
{
- Cache.log.debug(
+ Console.debug(
"Time taken to update Vamsas Document from jalview\t= "
+ (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
}
cdoc.setVamsasRoots(cdoc.getVamsasRoots());
- if (Cache.log.isDebugEnabled())
+ if (Console.isDebugEnabled())
{
- Cache.log.debug("Time taken to set Document Roots\t\t= "
+ Console.debug("Time taken to set Document Roots\t\t= "
+ (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
}
else
{
updateJalview(cdoc);
- if (Cache.log.isDebugEnabled())
+ if (Console.isDebugEnabled())
{
- Cache.log.debug(
+ Console.debug(
"Time taken to update Jalview from vamsas document Roots\t= "
+ (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
}
vclient.updateDocument(cdoc);
- if (Cache.log.isDebugEnabled())
+ if (Console.isDebugEnabled())
{
- Cache.log.debug("Time taken to update Session Document\t= "
+ Console.debug("Time taken to update Session Document\t= "
+ (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
}
recover_objectMappingBackup();
storedviews = 0;
}
- Cache.log.debug("Finished updating from document change.");
+ Console.debug("Finished updating from document change.");
disableGui(false);
return storedviews;
}
@Override
public void propertyChange(PropertyChangeEvent evt)
{
- Cache.log.debug("Dealing with document update event.");
+ Console.debug("Dealing with document update event.");
client.dealWithDocumentUpdate(false);
- Cache.log.debug("finished dealing with event.");
+ Console.debug("finished dealing with event.");
}
});
- Cache.log.debug("Added Jalview handler for vamsas document updates.");
+ Console.debug("Added Jalview handler for vamsas document updates.");
}
private void addStoreDocumentHandler()
{
if (client.promptUser)
{
- Cache.log.debug(
+ Console.debug(
"Asking user if the vamsas session should be stored.");
-- int reply = JvOptionPane.showInternalConfirmDialog(
- Desktop.getDesktopPane(),
- Desktop.desktop,
++ int reply = JvOptionPane.showInternalConfirmDialog(Desktop.getDesktopPane(),
"The current VAMSAS session has unsaved data - do you want to save it ?",
"VAMSAS Session Shutdown",
JvOptionPane.YES_NO_OPTION,
if (reply == JvOptionPane.YES_OPTION)
{
- Cache.log.debug("Prompting for vamsas store filename.");
+ Console.debug("Prompting for vamsas store filename.");
- Desktop.instance.vamsasSave_actionPerformed(null);
+ Desktop.getInstance().vamsasSave_actionPerformed(null);
- Cache.log
- .debug("Finished attempt at storing document.");
+ Console.debug("Finished attempt at storing document.");
}
- Cache.log.debug(
+ Console.debug(
"finished dealing with REQUESTTOCLOSE event.");
}
else
{
- Cache.log.debug(
+ Console.debug(
"Ignoring store document request (promptUser==false)");
}
}
});
- Cache.log.debug("Added Jalview handler for vamsas document updates.");
+ Console.debug("Added Jalview handler for vamsas document updates.");
}
public void disableGui(boolean b)
{
// JAL-3311 TODO: remove this class!
- // Desktop.getInstance().setVamsasUpdate(b);
+ // Desktop.instance.setVamsasUpdate(b);
}
Hashtable _backup_vobj2jv;
} catch (Exception e)
{
// Complain to GUI
- Cache.log.error("Failed to join vamsas session.", e);
+ Console.error("Failed to join vamsas session.", e);
vclient = null;
}
try
{
final IPickManager pm = vclient.getPickManager();
final StructureSelectionManager ssm = StructureSelectionManager
- .getStructureSelectionManager(Desktop.getInstance());
- .getStructureSelectionManager(Desktop.instance);
++ .getStructureSelectionManager(Desktop.getInstance());
final VamsasApplication me = this;
pm.registerMessageHandler(new IMessageHandler()
{
{
return;
}
- // if (Cache.log.isDebugEnabled())
+ // if (Cache.isDebugEnabled())
// {
- // Cache.log.debug("Received MouseOverMessage "+mm.getVorbaID()+"
+ // Cache.debug("Received MouseOverMessage "+mm.getVorbaID()+"
// "+mm.getPosition());
// }
Object jvobj = vobj2jv.get(mm.getVorbaID());
if (jvobj != null && jvobj instanceof SequenceI)
{
last = mstring;
- // Cache.log.debug("Handling Mouse over "+mm.getVorbaID()+"
+ // Cache.debug("Handling Mouse over "+mm.getVorbaID()+"
// bound to "+jvobj+" at "+mm.getPosition());
// position is character position in aligned sequence
ssm.mouseOverVamsasSequence((SequenceI) jvobj,
if (v != null)
{
// this should really be a trace message.
- // Cache.log.debug("Mouse over " + v.getId() + " bound to "
+ // Cache.debug("Mouse over " + v.getId() + " bound to "
// + seq + " at " + index);
last = seq;
i = index;
{
if (vobj2jv == null)
{
- Cache.log.warn(
+ Console.warn(
"Selection listener still active for dead session.");
// not in a session.
return;
if (sm != null)
{
sm.validate(); // debug
- Cache.log.debug("Selection Message\n" + sm.getRawMessage());
+ Console.debug("Selection Message\n" + sm.getRawMessage());
pm.sendMessage(sm);
}
}
ssm.addSelectionListener(selecter);
} catch (Exception e)
{
- Cache.log.error("Failed to init Vamsas Picking", e);
+ Console.error("Failed to init Vamsas Picking", e);
}
}
}
*/
package jalview.gui;
-import java.util.Locale;
+import jalview.jbgui.GWebserviceInfo;
+import jalview.util.MessageManager;
+import jalview.util.Platform;
++import jalview.util.ChannelProperties;
+import jalview.ws.WSClientI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
+import java.util.Locale;
import java.util.Vector;
import javax.swing.JComponent;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
-import jalview.jbgui.GWebserviceInfo;
-import jalview.util.ChannelProperties;
-import jalview.util.MessageManager;
-import jalview.ws.WSClientI;
-
/**
* Base class for web service client thread and gui TODO: create StAX parser to
* extract html body content reliably when preparing html formatted job statuses
public WebserviceInfo(String title, String info, int width, int height,
boolean makeVisible)
{
+ // no references
init(title, info, width, height, makeVisible);
}
{
frame = new JInternalFrame();
frame.setContentPane(this);
- Desktop.addInternalFrame(frame, title, makeVisible, width, height);
+ Desktop.addInternalFrame(frame, title, makeVisible, width, height, Desktop.FRAME_ALLOW_RESIZE, Desktop.FRAME_SET_MIN_SIZE_300);
frame.setClosable(false);
progressBar = new ProgressBar(statusPanel, statusBar);
titlePanel.add(titleText, BorderLayout.CENTER);
setStatus(currentStatus);
- Thread thread = new Thread(ap);
- thread.start();
- final WebserviceInfo thisinfo = this;
- frame.addInternalFrameListener(new InternalFrameAdapter()
+ if (!Platform.isJS())
{
- @Override
- public void internalFrameClosed(InternalFrameEvent evt)
- {
- // System.out.println("Shutting down webservice client");
- WSClientI service = thisinfo.getthisService();
- if (service != null && service.isCancellable())
- {
- service.cancelJob();
- }
- }
- });
+ // No animation for the moment//
+ Thread thread = new Thread(ap);
+ thread.start();
+ }
+ final WebserviceInfo thisinfo = this;
+ frame.addInternalFrameListener(
+ new InternalFrameAdapter()
+ {
+ @Override
+ public void internalFrameClosed(InternalFrameEvent evt)
+ {
+ // System.out.println("Shutting down webservice client");
+ WSClientI service = thisinfo.getthisService();
+ if (service != null && service.isCancellable())
+ {
+ service.cancelJob();
+ }
+ }
+ });
frame.validate();
}
@Override
public void run()
{
- JvOptionPane.showInternalMessageDialog(Desktop.desktop, message,
+ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(), message,
title, JvOptionPane.WARNING_MESSAGE);
}
{
progressBar.setProgressBar(message, id);
}
+
+ @Override
+ public void removeProgressBar(long id)
+ {
+ progressBar.removeProgressBar(id);
+ }
@Override
public void registerHandler(final long id,
*/
package jalview.gui;
++import jalview.bin.Console;
+import jalview.gui.OptsAndParamsPage.OptionBox;
+import jalview.gui.OptsAndParamsPage.ParamBox;
+import jalview.util.MessageManager;
+import jalview.ws.api.UIinfo;
+import jalview.ws.params.ArgumentI;
+import jalview.ws.params.OptionI;
+import jalview.ws.params.ParamDatastoreI;
+import jalview.ws.params.ParameterI;
+import jalview.ws.params.WsParamSetI;
-
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.HierarchyEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
-import java.awt.event.WindowEvent;
-import java.awt.event.WindowListener;
-import java.net.URL;
import java.util.Hashtable;
-import java.util.Iterator;
import java.util.List;
import java.util.Vector;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionStage;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
-import javax.swing.JSplitPane;
import javax.swing.JTextArea;
+import javax.swing.WindowConstants;
import javax.swing.border.TitledBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
-import compbio.metadata.Argument;
-import compbio.metadata.Option;
-import compbio.metadata.Parameter;
-import compbio.metadata.Preset;
-import compbio.metadata.PresetManager;
-import compbio.metadata.RunnerConfig;
-import jalview.bin.Console;
-import jalview.gui.OptsAndParamsPage.OptionBox;
-import jalview.gui.OptsAndParamsPage.ParamBox;
-import jalview.util.MessageManager;
-import jalview.ws.jws2.JabaParamStore;
-import jalview.ws.jws2.JabaPreset;
-import jalview.ws.jws2.Jws2Discoverer;
-import jalview.ws.jws2.jabaws2.Jws2Instance;
-import jalview.ws.params.ArgumentI;
-import jalview.ws.params.OptionI;
-import jalview.ws.params.ParamDatastoreI;
-import jalview.ws.params.ParameterI;
-import jalview.ws.params.WsParamSetI;
import net.miginfocom.swing.MigLayout;
/**
public class WsJobParameters extends JPanel implements ItemListener,
ActionListener, DocumentListener, OptsParametersContainerI
{
- URL linkImageURL = getClass().getResource("/images/link.gif");
+ private static final int PREFERRED_WIDTH = 540;
+
+ private static final int DEFAULT_HEIGHT = 640;
+
+ // the default parameter set shown to the user
+ private static final String SVC_DEF = "Defaults";
+
+ private int maxOptWidth = 200;
- private static final String SVC_DEF = "Defaults"; // this is the null
- // parameter set as shown to
- // user
+ // URL linkImageURL = getClass().getResource("/images/link.gif");
+ // TODO ABSRACT FROM JABAWS CLASSES
+
+ // completion stage representing whether start was clicked
+ private final CompletableFuture<Boolean> completionStage = new CompletableFuture<>();
+
/**
* manager for options and parameters.
*/
- OptsAndParamsPage opanp = new OptsAndParamsPage(this);
+ OptsAndParamsPage opanp;
- /**
+ /*
* panel containing job options
*/
- JPanel jobOptions = new JPanel();
+ JPanel optionsPanel = new JPanel();
- /**
+ /*
* panel containing job parameters
*/
- JPanel paramList = new JPanel();
-
- JPanel SetNamePanel = new JPanel();
+ JPanel paramsPanel = new JPanel();
- JPanel setDetails = new JPanel();
-
- JSplitPane settingsPanel = new JSplitPane();
-
- JPanel jobPanel = new JPanel();
-
- JScrollPane jobOptionsPane = new JScrollPane();
+ JPanel setNamePanel = new JPanel();
JButton createpref = new JButton();
JButton updatepref = new JButton();
- JButton startjob = new JButton();
-
- JButton canceljob = new JButton();
-
- JComboBox setName = new JComboBox();
+ JComboBox<String> setName = new JComboBox<>();
JTextArea setDescr = new JTextArea();
JScrollPane paramPane = new JScrollPane();
-
- // ScrollablePanel optsAndparams = new ScrollablePanel();
- JPanel optsAndparams = new JPanel();
-
- RunnerConfig serviceOptions;
+
+ JButton startjob = JvSwingUtils.makeButton(
+ MessageManager.getString("action.start_job"),
+ MessageManager.getString("label.start_job_current_settings"),
+ this::startjob_actionPerformed);
+ JButton canceljob = JvSwingUtils.makeButton(
+ MessageManager.getString("action.cancel_job"),
+ MessageManager.getString("label.cancel_job_close_dialog"),
+ this::canceljob_actionPerformed);
ParamDatastoreI paramStore;
- private int MAX_OPTWIDTH = 200;
+ // set true when 'Start Job' is clicked
+ boolean startJob = false;
- WsJobParameters(Jws2Instance service)
- {
- this(service, null);
- }
+ JFrame frame = null;
- public WsJobParameters(Jws2Instance service, WsParamSetI preset)
- {
- this(null, service, preset, null);
- }
+ UIinfo service;
- /**
- *
- * @param desktop
- * - if null, create new JFrame outside of desktop
- * @param service
- * @param preset
+ /*
+ * list of service presets in the gui
+ */
+ Hashtable<String, String> servicePresets = null;
+
+ /*
+ * set if dialog is being set - so handlers will avoid spurious events
*/
- public WsJobParameters(JFrame parent, Jws2Instance service,
- WsParamSetI preset, List<Argument> jobArgset)
+ boolean settingDialog = false;
+
+ private Hashtable<Object, Object> modifiedElements = new Hashtable<>();
+
+ String lastParmSet = null;
+
+ public WsJobParameters(ParamDatastoreI store, WsParamSetI preset,
+ List<ArgumentI> args)
{
- this(parent, null, service, preset, jobArgset);
+ super();
+
+ // parameters dialog in 'compact' format (help as tooltips)
+ opanp = new OptsAndParamsPage(this, true);
+ jbInit();
+ this.paramStore = store;
+ this.service = null;
+ init(preset, args);
+ validate();
}
/**
+ * Constructor given a set of parameters and presets, a service to be invoked,
+ * and a list of (Jabaws client) arguments
*
- * @param parent
* @param paramStorei
* @param service
* @param preset
* @param jobArgset
*/
- public WsJobParameters(JFrame parent, ParamDatastoreI paramStorei,
- Jws2Instance service, WsParamSetI preset,
- List<Argument> jobArgset)
+ public WsJobParameters(ParamDatastoreI paramStorei, UIinfo service,
+ WsParamSetI preset, List<ArgumentI> jobArgset)
{
super();
+ // parameters dialog in 'expanded' format (help text boxes)
+ opanp = new OptsAndParamsPage(this, false);
jbInit();
this.paramStore = paramStorei;
- if (paramStore == null)
+ if (paramStore == null && service != null)
{
paramStore = service.getParamStore();
}
this.service = service;
- // argSetModified(false);
- // populate parameter table
- initForService(service, preset, jobArgset);
- // display in new JFrame attached to parent.
+ initForService(preset, jobArgset);
validate();
}
- int response = -1;
-
- JDialog frame = null;
/**
- * shows a modal dialog containing the parameters.
+ * Shows a modal dialog containing the parameters and Start or Cancel options.
+ * Answers true if the job is started, false if cancelled.
*
* @return
*/
- public boolean showRunDialog()
+ public CompletionStage<Boolean> showRunDialog()
{
+
- frame = new JDialog(Desktop.instance, true);
-
- frame.setTitle(MessageManager.formatMessage("label.edit_params_for",
- new String[]
- { service.getActionText() }));
- Rectangle deskr = Desktop.instance.getBounds();
+ // Should JFrame hahve a parent of getDesktop ?
+ frame = new JFrame();
+ frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
+ if (service != null)
+ {
+ frame.setTitle(MessageManager.formatMessage("label.edit_params_for",
+ new String[] { service.getActionText() }));
+ }
+ Rectangle deskr = Desktop.getInstance().getBounds();
Dimension pref = this.getPreferredSize();
frame.setBounds(
new Rectangle((int) (deskr.getCenterX() - pref.width / 2),
}
});
+
frame.setVisible(true);
- if (response > 0)
- {
- return true;
- }
- return false;
+ return completionStage;
}
private void jbInit()
updatepref = JvSwingUtils.makeButton(
MessageManager.getString("action.update"),
MessageManager.getString("label.update_user_parameter_set"),
- new ActionListener()
- {
-
- @Override
- public void actionPerformed(ActionEvent e)
- {
- update_actionPerformed(e);
- }
- });
+ this::update_actionPerformed);
deletepref = JvSwingUtils.makeButton(
MessageManager.getString("action.delete"),
MessageManager.getString("label.delete_user_parameter_set"),
- new ActionListener()
- {
-
- @Override
- public void actionPerformed(ActionEvent e)
- {
- delete_actionPerformed(e);
- }
- });
+ this::delete_actionPerformed);
createpref = JvSwingUtils.makeButton(
MessageManager.getString("action.create"),
MessageManager.getString("label.create_user_parameter_set"),
- new ActionListener()
- {
-
- @Override
- public void actionPerformed(ActionEvent e)
- {
- create_actionPerformed(e);
- }
- });
+ this::create_actionPerformed);
revertpref = JvSwingUtils.makeButton(
MessageManager.getString("action.revert"),
MessageManager
.getString("label.revert_changes_user_parameter_set"),
- new ActionListener()
- {
+ this::revert_actionPerformed);
- @Override
- public void actionPerformed(ActionEvent e)
- {
- revert_actionPerformed(e);
- }
- });
- startjob = JvSwingUtils.makeButton(
- MessageManager.getString("action.start_job"),
- MessageManager.getString("label.start_job_current_settings"),
- new ActionListener()
- {
- @Override
- public void actionPerformed(ActionEvent e)
- {
- startjob_actionPerformed(e);
- }
- });
- canceljob = JvSwingUtils.makeButton(
- MessageManager.getString("action.cancel_job"),
- MessageManager.getString("label.cancel_job_close_dialog"),
- new ActionListener()
- {
- @Override
- public void actionPerformed(ActionEvent e)
- {
- canceljob_actionPerformed(e);
- }
- });
+ JPanel setDetails = new JPanel();
setDetails.setBorder(
new TitledBorder(MessageManager.getString("label.details")));
setDetails.setLayout(new BorderLayout());
setName.getEditor().addActionListener(this);
JPanel setNameInfo = new JPanel(new FlowLayout(FlowLayout.LEFT));
GridBagLayout gbl = new GridBagLayout();
- SetNamePanel.setLayout(gbl);
+ setNamePanel.setLayout(gbl);
JLabel setNameLabel = new JLabel(
MessageManager.getString("label.current_parameter_set_name"));
revertpref.setVisible(false);
createpref.setVisible(false);
JPanel setsavebuts = new JPanel();
- setsavebuts.setLayout(new FlowLayout(FlowLayout.LEFT)); // GridLayout(1,2));
- ((FlowLayout) setsavebuts.getLayout()).setHgap(10);
- ((FlowLayout) setsavebuts.getLayout()).setVgap(0);
+ setsavebuts.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 0)); // GridLayout(1,2));
JPanel spacer = new JPanel();
spacer.setPreferredSize(new Dimension(2, 30));
setsavebuts.add(spacer);
// setsavebuts.setSize(new Dimension(150, 30));
JPanel buttonArea = new JPanel(new GridLayout(1, 1));
buttonArea.add(setsavebuts);
- SetNamePanel.add(setNameInfo);
+ setNamePanel.add(setNameInfo);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridheight = 2;
gbl.setConstraints(setNameInfo, gbc);
- SetNamePanel.add(buttonArea);
+ setNamePanel.add(buttonArea);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
// paramPane.setPreferredSize(new Dimension(360, 400));
// paramPane.setPreferredSize(null);
- jobOptions.setBorder(
+ optionsPanel.setBorder(
new TitledBorder(MessageManager.getString("label.options")));
- jobOptions.setOpaque(true);
- paramList.setBorder(
+ optionsPanel.setOpaque(true);
+ paramsPanel.setBorder(
new TitledBorder(MessageManager.getString("label.parameters")));
- paramList.setOpaque(true);
- JPanel bjo = new JPanel(new BorderLayout()),
- bjp = new JPanel(new BorderLayout());
- bjo.add(jobOptions, BorderLayout.CENTER);
- bjp.add(paramList, BorderLayout.CENTER);
- bjp.setOpaque(true);
- bjo.setOpaque(true);
+ paramsPanel.setOpaque(true);
// optsAndparams.setScrollableWidth(ScrollableSizeHint.FIT);
// optsAndparams.setScrollableHeight(ScrollableSizeHint.NONE);
// optsAndparams.setLayout(new BorderLayout());
+ JPanel optsAndparams = new JPanel();
optsAndparams.setLayout(new BorderLayout());
- optsAndparams.add(jobOptions, BorderLayout.NORTH);
- optsAndparams.add(paramList, BorderLayout.CENTER);
+ optsAndparams.add(optionsPanel, BorderLayout.NORTH);
+ optsAndparams.add(paramsPanel, BorderLayout.CENTER);
JPanel jp = new JPanel(new BorderLayout());
jp.add(optsAndparams, BorderLayout.CENTER);
paramPane.getViewport().setView(jp);
paramPane.setBorder(null);
setLayout(new BorderLayout());
+ JPanel jobPanel = new JPanel();
jobPanel.setPreferredSize(null);
jobPanel.setLayout(new BorderLayout());
jobPanel.add(setDetails, BorderLayout.NORTH);
jobPanel.add(paramPane, BorderLayout.CENTER);
// jobPanel.setOrientation(JSplitPane.VERTICAL_SPLIT);
- add(SetNamePanel, BorderLayout.NORTH);
+ add(setNamePanel, BorderLayout.NORTH);
add(jobPanel, BorderLayout.CENTER);
JPanel dialogpanel = new JPanel();
dialogpanel.add(canceljob);
// JAL-1580: setMaximumSize() doesn't work, so just size for the worst case:
// check for null is for JUnit usage
- final int windowHeight = Desktop.instance == null ? 540
- : Desktop.instance.getHeight();
+ final int windowHeight = Desktop.getInstance() == null ? DEFAULT_HEIGHT
+ : Desktop.getInstance().getHeight();
setPreferredSize(new Dimension(540, windowHeight));
add(dialogpanel, BorderLayout.SOUTH);
validate();
protected void canceljob_actionPerformed(ActionEvent e)
{
- response = 0;
+ startJob = false;
if (frame != null)
{
frame.setVisible(false);
}
+ completionStage.complete(false);
}
protected void startjob_actionPerformed(ActionEvent e)
{
- response = 1;
+ startJob = true;
if (frame != null)
{
frame.setVisible(false);
}
+ completionStage.complete(true);
}
- Jws2Instance service;
+ void initForService(WsParamSetI paramSet, List<ArgumentI> jobArgset)
+ {
+ settingDialog = true;
- /**
- * list of service presets in the gui
- */
- Hashtable servicePresets = null;
+ init(paramSet, jobArgset);
- /**
- * set if dialog is being set - so handlers will avoid spurious events
- */
- boolean settingDialog = false;
+ }
- void initForService(Jws2Instance service, WsParamSetI jabap,
- List<Argument> jabajobArgset)
+ void init(WsParamSetI p, List<ArgumentI> jobArgset)
{
- WsParamSetI p = null;
- List<ArgumentI> jobArgset = null;
- settingDialog = true;
- { // instantiate the abstract proxy for Jaba objects
- jobArgset = jabajobArgset == null ? null
- : JabaParamStore.getJwsArgsfromJaba(jabajobArgset);
- p = jabap; // (jabap != null) ? paramStore.getPreset(jabap.getName()) :
- // null;
- }
-
- Hashtable exnames = new Hashtable();
+ Hashtable<String, String> exnames = new Hashtable<>();
for (int i = 0, iSize = setName.getItemCount(); i < iSize; i++)
{
exnames.put(setName.getItemAt(i), setName.getItemAt(i));
}
- servicePresets = new Hashtable();
+ servicePresets = new Hashtable<>();
// Add the default entry - if not present already.
if (!exnames.contains(SVC_DEF))
{
exnames.put(SVC_DEF, SVC_DEF);
servicePresets.put(SVC_DEF, SVC_DEF);
}
- String curname = (p == null ? "" : p.getName());
+ // String curname = (p == null ? "" : p.getName());
for (WsParamSetI pr : paramStore.getPresets())
{
if (!pr.isModifiable())
}
- @SuppressWarnings("unchecked")
private void updateTable(WsParamSetI p, List<ArgumentI> jobArgset)
{
boolean setDefaultParams = false;
OptionI opt = (OptionI) myarg;
OptionBox ob = opanp.addOption(opt);
ob.resetToDefault(setDefaultParams);
- if (MAX_OPTWIDTH < ob.getPreferredSize().width)
+ if (maxOptWidth < ob.getPreferredSize().width)
{
- MAX_OPTWIDTH = ob.getPreferredSize().width;
+ maxOptWidth = ob.getPreferredSize().width;
}
ob.validate();
cw += ob.getPreferredSize().width + 5;
return modifiedElements.size() > 0;
}
- private Hashtable modifiedElements = new Hashtable();
/**
* reset gui and modification state settings
if (b && modifiedElements.size() > 0)
{
makeSetNameValid(!isUserPreset);
- SetNamePanel.revalidate();
+ setNamePanel.revalidate();
}
updateButtonDisplay();
}
// sync the gui with the preset database
for (int i = 0, iS = setName.getItemCount(); i < iS; i++)
{
- String snm = (String) setName.getItemAt(i);
+ String snm = setName.getItemAt(i);
if (snm.equals(nm))
{
makeupdate = true;
settingDialog = stn;
}
+ /**
+ * Rebuilds the Options and Parameters panels
+ */
@Override
public void refreshParamLayout()
{
- // optsAndparams.setPreferredSize(null);
- FlowLayout fl = new FlowLayout(FlowLayout.LEFT);
- int sep = fl.getVgap();
- boolean fh = true;
- int os = 0,
- s = jobOptions.getBorder().getBorderInsets(jobOptions).bottom
- + jobOptions.getBorder().getBorderInsets(jobOptions).top
- + 2 * sep;
- /**
- * final height for viewport
- */
- int finalh = s;
- int panewidth = paramPane.getViewport().getSize().width - 120
- - jobOptions.getBorder().getBorderInsets(jobOptions).left
- + jobOptions.getBorder().getBorderInsets(jobOptions).right;
-
- int w = 2 * fl.getHgap()
- + (MAX_OPTWIDTH > OptsAndParamsPage.PARAM_WIDTH ? MAX_OPTWIDTH
- : OptsAndParamsPage.PARAM_WIDTH);
- int hgap = fl.getHgap(), cw = hgap;
+ final int rightMargin = 40;
+ final int availableWidth = paramPane.getViewport().getSize().width
+ - rightMargin
+ - optionsPanel.getBorder().getBorderInsets(optionsPanel).left
+ + optionsPanel.getBorder().getBorderInsets(optionsPanel).right;
if (opanp.getOptSet().size() > 0)
{
+ int hgap = 5;
+ int currentWidth = hgap;
- jobOptions.setLayout(new MigLayout("", "", ""));
- jobOptions.removeAll();
+ /*
+ * layout constraint 'nogrid' prevents vertical column alignment,
+ * allowing controls to flow without extra space inserted to align
+ */
+ optionsPanel.setLayout(new MigLayout("nogrid", "", ""));
+ optionsPanel.removeAll();
+ JPanel lastAdded = null;
+ /*
+ * add each control in turn; if adding would overflow the right margin,
+ * remove and re-add the previous parameter with "wrap" (after)
+ * in order to start a new row
+ */
for (OptionBox pbox : opanp.getOptSet().values())
{
pbox.validate();
- cw += pbox.getSize().width + hgap;
- if (cw + 120 > panewidth)
+ int boxWidth = pbox.getSize().width;
+ currentWidth += boxWidth + hgap;
+ boolean wrapAfterLast = currentWidth > availableWidth
+ && lastAdded != null;
+ // System.out.println(String.format(
+ // "%s width=%d, paneWidth=%d, currentWidth=%d, wrapAfterLast=%s",
+ // pbox.toString(), boxWidth, panewidth, currentWidth,
+ // wrapAfterLast));
+ if (wrapAfterLast)
{
- jobOptions.add(pbox, "wrap");
- // System.out.println("Wrap on "+pbox.option.getName());
- cw = hgap + pbox.getSize().width;
- fh = true;
- }
- else
- {
- jobOptions.add(pbox);
- }
- if (fh)
- {
- finalh += pbox.getSize().height + fl.getVgap();
- fh = false;
+ optionsPanel.remove(lastAdded);
+ optionsPanel.add(lastAdded, "wrap");
+ currentWidth = hgap + boxWidth;
}
+ optionsPanel.add(pbox);
+ lastAdded = pbox;
}
- jobOptions.revalidate();
+ optionsPanel.revalidate();
}
else
{
- jobOptions.setVisible(false);
+ optionsPanel.setVisible(false);
}
- // Now layout the parameters assuming they occupy one column - to calculate
- // total height of options+parameters
- fl = new FlowLayout(FlowLayout.LEFT);
- // helpful hint from
- // http://stackoverflow.com/questions/2743177/top-alignment-for-flowlayout
- fl.setAlignOnBaseline(true);
if (opanp.getParamSet().size() > 0)
{
- paramList.removeAll();
- paramList.setLayout(new MigLayout("", "", ""));
- fh = true;
+ paramsPanel.removeAll();
+ paramsPanel.setLayout(new MigLayout("", "", ""));
+ int hgap = 5;
+ int currentWidth = hgap;
+
+ JPanel lastAdded = null;
for (ParamBox pbox : opanp.getParamSet().values())
{
pbox.validate();
- cw += pbox.getSize().width + hgap;
- if (cw + 160 > panewidth)
- {
- paramList.add(pbox, "wrap");
- cw = pbox.getSize().width + hgap;
- fh = true;
- }
- else
+ int boxWidth = pbox.getSize().width;
+ currentWidth += boxWidth + hgap;
+ boolean wrapAfterLast = currentWidth > availableWidth
+ && lastAdded != null;
+ if (wrapAfterLast)
{
- paramList.add(pbox);
+ paramsPanel.remove(lastAdded);
+ paramsPanel.add(lastAdded, "wrap");
+ currentWidth = pbox.getSize().width + hgap;
}
- if (fh)
- {
- finalh += pbox.getSize().height + fl.getVgap();
- fh = false;
- }
-
+ paramsPanel.add(pbox);
+ lastAdded = pbox;
}
+
/*
* s = 2 * sep; for (ParamBox pbox : opanp.getParamSet().values()) {
* pbox.validate(); s += sep +
* .getBorder().getBorderInsets(paramList).bottom+paramList
* .getBorder().getBorderInsets(paramList).top;
*/
- paramList.revalidate();
+ paramsPanel.revalidate();
}
else
{
- paramList.setVisible(false);
+ paramsPanel.setVisible(false);
}
// TODO: waste some time trying to eliminate any unnecessary .validate calls
// here
revalidate();
}
- /**
- * testing method - grab a service and parameter set and show the window
- *
- * @param args
- * @j2sIgnore
- */
- public static void main(String[] args)
- {
- jalview.ws.jws2.Jws2Discoverer disc = jalview.ws.jws2.Jws2Discoverer
- .getDiscoverer();
- int p = 0;
- if (args.length > 0)
- {
- Vector<String> services = new Vector<>();
- services.addElement(args[p++]);
- Jws2Discoverer.getDiscoverer().setServiceUrls(services);
- }
- try
- {
- disc.run();
- } catch (Exception e)
- {
- System.err.println("Aborting. Problem discovering services.");
- e.printStackTrace();
- return;
- }
- Jws2Instance lastserv = null;
- for (Jws2Instance service : disc.getServices())
- {
- lastserv = service;
- if (p >= args.length || service.serviceType.equalsIgnoreCase(args[p]))
- {
- if (lastserv != null)
- {
- List<Preset> prl = null;
- Preset pr = null;
- if (++p < args.length)
- {
- PresetManager prman = lastserv.getPresets();
- if (prman != null)
- {
- pr = prman.getPresetByName(args[p]);
- if (pr == null)
- {
- // just grab the last preset.
- prl = prman.getPresets();
- }
- }
- }
- else
- {
- PresetManager prman = lastserv.getPresets();
- if (prman != null)
- {
- prl = prman.getPresets();
- }
- }
- Iterator<Preset> en = (prl == null) ? null : prl.iterator();
- while (en != null && en.hasNext())
- {
- if (en != null)
- {
- if (!en.hasNext())
- {
- en = prl.iterator();
- }
- pr = en.next();
- }
- {
- System.out.println("Testing opts dupes for "
- + lastserv.getUri() + " : " + lastserv.getActionText()
- + ":" + pr.getName());
- List<Option> rg = lastserv.getRunnerConfig().getOptions();
- for (Option o : rg)
- {
- try
- {
- Option cpy = jalview.ws.jws2.ParameterUtils.copyOption(o);
- } catch (Exception e)
- {
- System.err.println("Failed to copy " + o.getName());
- e.printStackTrace();
- } catch (Error e)
- {
- System.err.println("Failed to copy " + o.getName());
- e.printStackTrace();
- }
- }
- }
- {
- System.out.println("Testing param dupes:");
- List<Parameter> rg = lastserv.getRunnerConfig()
- .getParameters();
- for (Parameter o : rg)
- {
- try
- {
- Parameter cpy = jalview.ws.jws2.ParameterUtils
- .copyParameter(o);
- } catch (Exception e)
- {
- System.err.println("Failed to copy " + o.getName());
- e.printStackTrace();
- } catch (Error e)
- {
- System.err.println("Failed to copy " + o.getName());
- e.printStackTrace();
- }
- }
- }
- {
- System.out.println("Testing param write:");
- List<String> writeparam = null, readparam = null;
- try
- {
- writeparam = jalview.ws.jws2.ParameterUtils
- .writeParameterSet(
- pr.getArguments(lastserv.getRunnerConfig()),
- " ");
- System.out.println("Testing param read :");
- List<Option> pset = jalview.ws.jws2.ParameterUtils
- .processParameters(writeparam,
- lastserv.getRunnerConfig(), " ");
- readparam = jalview.ws.jws2.ParameterUtils
- .writeParameterSet(pset, " ");
- Iterator<String> o = pr.getOptions().iterator(),
- s = writeparam.iterator(), t = readparam.iterator();
- boolean failed = false;
- while (s.hasNext() && t.hasNext())
- {
- String on = o.next(), sn = s.next(), st = t.next();
- if (!sn.equals(st))
- {
- System.out.println(
- "Original was " + on + " Phase 1 wrote " + sn
- + "\tPhase 2 wrote " + st);
- failed = true;
- }
- }
- if (failed)
- {
- System.out.println(
- "Original parameters:\n" + pr.getOptions());
- System.out.println(
- "Wrote parameters in first set:\n" + writeparam);
- System.out.println(
- "Wrote parameters in second set:\n" + readparam);
-
- }
- } catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- WsJobParameters pgui = new WsJobParameters(lastserv,
- new JabaPreset(lastserv, pr));
- JFrame jf = new JFrame(MessageManager
- .formatMessage("label.ws_parameters_for", new String[]
- { lastserv.getActionText() }));
- JPanel cont = new JPanel(new BorderLayout());
- pgui.validate();
- cont.setPreferredSize(pgui.getPreferredSize());
- cont.add(pgui, BorderLayout.CENTER);
- jf.setLayout(new BorderLayout());
- jf.add(cont, BorderLayout.CENTER);
- jf.validate();
- final Thread thr = Thread.currentThread();
- jf.addWindowListener(new WindowListener()
- {
-
- @Override
- public void windowActivated(WindowEvent e)
- {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void windowClosed(WindowEvent e)
- {
- }
-
- @Override
- public void windowClosing(WindowEvent e)
- {
- thr.interrupt();
-
- }
-
- @Override
- public void windowDeactivated(WindowEvent e)
- {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void windowDeiconified(WindowEvent e)
- {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void windowIconified(WindowEvent e)
- {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void windowOpened(WindowEvent e)
- {
- // TODO Auto-generated method stub
-
- }
-
- });
- jf.setVisible(true);
- boolean inter = false;
- while (!inter)
- {
- try
- {
- Thread.sleep(10000);
- } catch (Exception e)
- {
- inter = true;
- }
- }
- jf.dispose();
- }
- }
- }
- }
- }
public boolean isServiceDefaults()
{
return opanp.getCurrentSettings();
}
- String lastParmSet = null;
/*
* Hashtable<String, Object[]> editedParams = new Hashtable<String,
int n = 0;
// remove any set names in the drop down menu that aren't either a reserved
// setting, or a user defined or service preset.
- Vector items = new Vector();
+ Vector<String> items = new Vector<>();
while (n < setName.getItemCount())
{
- String item = (String) setName.getItemAt(n);
+ String item = setName.getItemAt(n);
if (!item.equals(SVC_DEF) && !paramStore.presetExists(item))
{
setName.removeItemAt(n);
initArgSetModified();
syncSetNamesWithStore();
setName.setSelectedItem(lastParmSet);
- SetNamePanel.validate();
+ setNamePanel.validate();
validate();
settingDialog = false;
}
*/
protected void updateWebServiceMenus()
{
+ if (Desktop.getInstance() == null)
+ {
+ return;
+ }
for (AlignFrame alignFrame : Desktop.getAlignFrames())
{
- alignFrame.BuildWebServiceMenu();
+ alignFrame.buildWebServicesMenu();
}
}
@Override
public void itemStateChanged(ItemEvent e)
{
- if (e.getSource() == setName && e.getStateChange() == e.SELECTED)
+ if (e.getSource() == setName
+ && e.getStateChange() == ItemEvent.SELECTED)
{
final String setname = (String) setName.getSelectedItem();
- System.out.println("Item state changed for " + setname
- + " (handling ? " + !settingDialog + ")");
+ if (Console.isDebugEnabled())
+ {
+ Console.debug("Item state changed for " + setname + " (handling ? "
+ + !settingDialog + ")");
+ }
if (settingDialog)
{
// ignore event
}
- private void _renameExistingPreset(String oldName, String curSetName2)
- {
- paramStore.updatePreset(oldName, curSetName2, setDescr.getText(),
- getJobParams());
- }
-
/**
* store current settings as given name. You should then reset gui.
*
package jalview.gui;
import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.io.JalviewFileChooser;
import jalview.io.JalviewFileView;
import jalview.util.MessageManager;
*/
public class WsParamSetManager implements ParamManager
{
+ private static final String WS_PARAM_FILES = "WS_PARAM_FILES";
Hashtable<String, ParamDatastoreI> paramparsers = new Hashtable<>();
@Override
public WsParamSetI[] getParameterSet(String name, String serviceUrl,
boolean modifiable, boolean unmodifiable)
{
- String files = Cache.getProperty("WS_PARAM_FILES");
+ String files = Cache.getProperty(WS_PARAM_FILES);
if (files == null)
{
return null;
}
} catch (IOException e)
{
- Cache.log.info("Failed to parse parameter file " + pfile
- + " (Check that all " + WS_PARAM_FILES
- + " entries are valid!)",
+ Console.info("Failed to parse parameter file " + pfile
+ + " (Check that all JALVIEW_WSPARAMFILES entries are valid!)",
e);
}
}
if (parser != null)
{
WsParamSetI pset = parser.parseServiceParameterFile(
- wspset.getName(), wspset.getDescription(), urlArray,
- wspset.getParameters());
+ wspset.getName(), wspset.getDescription(),
+ urlArray, wspset.getParameters());
if (pset != null)
{
pset.setSourceFile(filename);
{
if (filename != null && !((outfile = new File(filename)).canWrite()))
{
- Cache.log.warn("Can't write to " + filename
+ Console.warn("Can't write to " + filename
+ " - Prompting for new file to write to.");
filename = null;
}
chooser.setDialogTitle(MessageManager
.getString("label.choose_filename_for_param_file"));
chooser.setToolTipText(MessageManager.getString("action.save"));
- int value = chooser.showSaveDialog(Desktop.instance);
+ int value = chooser.showSaveDialog(Desktop.getInstance());
if (value == JalviewFileChooser.APPROVE_OPTION)
{
outfile = chooser.getSelectedFile();
}
if (outfile != null)
{
- String paramFiles = jalview.bin.Cache.getDefault(WS_PARAM_FILES,
- filename);
+ String paramFiles = Cache.getDefault("WS_PARAM_FILES", filename);
if (paramFiles.indexOf(filename) == -1)
{
if (paramFiles.length() > 0)
}
paramFiles = paramFiles.concat(filename);
}
-
- Cache.setProperty("WS_PARAM_FILES", paramFiles);
+ Cache.setProperty(WS_PARAM_FILES, paramFiles);
WebServiceParameterSet paramxml = new WebServiceParameterSet();
parameterSet.setSourceFile(filename);
} catch (Exception e)
{
- Cache.log.error("Couldn't write parameter file to " + outfile, e);
+ Console.error("Couldn't write parameter file to " + outfile, e);
}
}
}
/*
*
- * JalviewFileChooser chooser = new JalviewFileChooser(Cache
+ * JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
* .getProperty("LAST_DIRECTORY"), new String[] { "jc" }, new String[] {
* "Jalview User Colours" }, "Jalview User Colours"); chooser.setFileView(new
* jalview.io.JalviewFileView());
* int value = chooser.showOpenDialog(this);
*
* if (value == JalviewFileChooser.APPROVE_OPTION) { File choice =
- * chooser.getSelectedFile(); Cache.setProperty("LAST_DIRECTORY",
- * choice.getParent()); String defaultColours = Cache.getDefault(
+ * chooser.getSelectedFile(); jalview.bin.Cache.setProperty("LAST_DIRECTORY",
+ * choice.getParent()); String defaultColours = jalview.bin.Cache.getDefault(
* "USER_DEFINED_COLOURS", choice.getPath()); if
* (defaultColours.indexOf(choice.getPath()) == -1) { defaultColours =
* defaultColours.concat("|") .concat(choice.getPath()); } (non-Javadoc)
{
return;
}
- String paramFiles = jalview.bin.Cache.getDefault(WS_PARAM_FILES, "");
- String paramFiles = Cache.getDefault("WS_PARAM_FILES", "");
++ String paramFiles = Cache.getDefault(WS_PARAM_FILES, "");
if (paramFiles.indexOf(filename) > -1)
{
String nparamFiles = new String();
nparamFiles = nparamFiles.concat("|").concat(fl);
}
}
- jalview.bin.Cache.setProperty(WS_PARAM_FILES, nparamFiles);
- Cache.setProperty("WS_PARAM_FILES", nparamFiles);
++ Cache.setProperty(WS_PARAM_FILES, nparamFiles);
}
try
File pfile = new File(filename);
if (pfile.exists() && pfile.canWrite())
{
- if (JvOptionPane.showConfirmDialog(Desktop.instance,
+ if (JvOptionPane.showConfirmDialog(Desktop.getInstance(),
"Delete the preset's file, too ?", "Delete User Preset ?",
JvOptionPane.OK_CANCEL_OPTION) == JvOptionPane.OK_OPTION)
{
}
} catch (Exception e)
{
- Cache.log.error(
+ Console.error(
"Exception when trying to delete webservice user preset: ",
e);
}
--- /dev/null
+package jalview.hmmer;
+
+import jalview.analysis.SeqsetUtils.SequenceInfo;
+import jalview.api.AlignViewportI;
+import jalview.bin.Cache;
++import jalview.bin.Console;
+import jalview.datamodel.Alignment;
+import jalview.datamodel.AlignmentI;
+import jalview.datamodel.AnnotatedCollectionI;
+import jalview.datamodel.ResidueCount;
+import jalview.datamodel.SequenceGroup;
+import jalview.datamodel.SequenceI;
+import jalview.gui.AlignFrame;
+import jalview.gui.JvOptionPane;
+import jalview.io.DataSourceType;
+import jalview.io.FileParse;
+import jalview.io.HMMFile;
+import jalview.util.FileUtils;
+import jalview.util.MessageManager;
+import jalview.ws.params.ArgumentI;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A class that runs the hmmbuild command as a separate process.
+ *
+ * @author gmcarstairs
+ *
+ */
+public class HMMBuild extends HmmerCommand
+{
+ static final String ARG_AMINO = "--amino";
+
+ static final String ARG_DNA = "--dna";
+
+ static final String ARG_RNA = "--rna";
+
+ /**
+ * Constructor
+ *
+ * @param alignFrame
+ * @param args
+ */
+ public HMMBuild(AlignFrame alignFrame, List<ArgumentI> args)
+ {
+ super(alignFrame, args);
+ }
+
+ /**
+ * Builds a HMM from an alignment (and/or groups), then imports and adds it to
+ * the alignment (and/or groups). Call this method directly to execute
+ * synchronously, or via start() in a new Thread for asynchronously.
+ */
+ @Override
+ public void run()
+ {
+ if (params == null || params.isEmpty())
+ {
- Cache.log.error("No parameters to HMMBuild!|");
++ Console.error("No parameters to HMMBuild!|");
+ return;
+ }
+
+ long msgID = System.currentTimeMillis();
+ af.setProgressBar(MessageManager.getString("status.running_hmmbuild"),
+ msgID);
+
+ AlignViewportI viewport = af.getViewport();
+ try
+ {
+ /*
+ * run hmmbuild for alignment and/or groups as selected
+ */
+ List<AnnotatedCollectionI> runBuildFor = parseParameters(viewport);
+
+ for (AnnotatedCollectionI grp : runBuildFor)
+ {
+ runHMMBuild(grp);
+ }
+ } finally
+ {
+ af.setProgressBar("", msgID);
+ viewport.alignmentChanged(af.alignPanel);
+ af.buildColourMenu(); // to enable HMMER colour schemes
+ }
+ }
+
+ /**
+ * Scans the parameters to determine whether to run hmmmbuild for the whole
+ * alignment or specified subgroup(s) or both
+ *
+ * @param viewport
+ * @return
+ */
+ protected List<AnnotatedCollectionI> parseParameters(
+ AlignViewportI viewport)
+ {
+ List<AnnotatedCollectionI> runBuildFor = new ArrayList<>();
+ boolean foundArg = false;
+
+ for (ArgumentI arg : params)
+ {
+ String name = arg.getName();
+ if (MessageManager.getString("label.hmmbuild_for").equals(name))
+ {
+ foundArg = true;
+ String value = arg.getValue();
+
+ if (MessageManager.getString("label.alignment").equals(value))
+ {
+ runBuildFor.add(viewport.getAlignmentView(false)
+ .getVisibleAlignment('-'));
+ }
+ else if (MessageManager.getString("label.groups_and_alignment")
+ .equals(value))
+ {
+ runBuildFor.add(viewport.getAlignmentView(false)
+ .getVisibleAlignment('-'));
+ runBuildFor.addAll(viewport.getAlignment().getGroups());
+ }
+ else if (MessageManager.getString("label.groups").equals(value))
+ {
+ runBuildFor.addAll(viewport.getAlignment().getGroups());
+ }
+ else if (MessageManager.getString("label.selected_group")
+ .equals(value))
+ {
+ runBuildFor.add(viewport.getSelectionGroup());
+ }
+ }
+ else if (MessageManager.getString("label.use_reference")
+ .equals(name))
+ {
+ // todo disable this option if no RF annotation on alignment
+ if (!af.getViewport().hasReferenceAnnotation())
+ {
+ JvOptionPane.showInternalMessageDialog(af, MessageManager
+ .getString("warn.no_reference_annotation"));
+ // return;
+ }
+ }
+ }
+
+ /*
+ * default is to build for the whole alignment
+ */
+ if (!foundArg)
+ {
+ runBuildFor.add(alignment);
+ }
+
+ return runBuildFor;
+ }
+
+ /**
+ * Runs hmmbuild on the given sequences (alignment or group)
+ *
+ * @param grp
+ */
+ private void runHMMBuild(AnnotatedCollectionI ac)
+ {
+ File hmmFile = null;
+ File alignmentFile = null;
+ try
+ {
+ hmmFile = FileUtils.createTempFile("hmm", ".hmm");
+ alignmentFile = FileUtils.createTempFile("output", ".sto");
+
+ if (ac instanceof Alignment)
+ {
+ AlignmentI al = (Alignment) ac;
+ // todo pad gaps in an unaligned SequenceGroup as well?
+ if (!al.isAligned())
+ {
+ al.padGaps();
+ }
+ }
+
+ deleteHmmSequences(ac);
+
+ List<SequenceI> copy = new ArrayList<>();
+ if (ac instanceof Alignment)
+ {
+ copy.addAll(ac.getSequences());
+ }
+ else
+ {
+ SequenceI[] sel = ((SequenceGroup) ac)
+ .getSelectionAsNewSequences((AlignmentI) ac.getContext());
+ for (SequenceI seq : sel)
+ {
+ if (seq != null)
+ {
+ copy.add(seq);
+ }
+ }
+ }
+ // TODO rather than copy alignment data we should anonymize in situ -
+ // export/File import could use anonymization hash to reinstate references
+ // at import level ?
+
+ SequenceI[] copyArray = copy.toArray(new SequenceI[copy.size()]);
+ Map<String, SequenceInfo> sequencesHash = stashSequences(copyArray);
+
+ exportStockholm(copyArray, alignmentFile, ac);
+
+ recoverSequences(sequencesHash, copy.toArray(new SequenceI[] {}));
+
+ boolean ran = runCommand(alignmentFile, hmmFile, ac);
+ if (!ran)
+ {
+ JvOptionPane.showInternalMessageDialog(af, MessageManager
+ .formatMessage("warn.command_failed", "hmmbuild"));
+ return;
+ }
+ importData(hmmFile, ac);
+ } catch (Exception e)
+ {
+ e.printStackTrace();
+ } finally
+ {
+ if (hmmFile != null)
+ {
+ hmmFile.delete();
+ }
+ if (alignmentFile != null)
+ {
+ alignmentFile.delete();
+ }
+ }
+ }
+
+ /**
+ * Constructs and executes the hmmbuild command as a separate process
+ *
+ * @param sequencesFile
+ * the alignment from which the HMM is built
+ * @param hmmFile
+ * the output file to which the HMM is written
+ * @param group
+ * alignment or group for which the hmm is generated
+ *
+ * @return
+ * @throws IOException
+ */
+ private boolean runCommand(File sequencesFile, File hmmFile,
+ AnnotatedCollectionI group) throws IOException
+ {
+ String cmd = getCommandPath(HMMBUILD);
+ if (cmd == null)
+ {
+ return false; // executable not found
+ }
+ List<String> args = new ArrayList<>();
+ args.add(cmd);
+
+ /*
+ * HMM name (will be given to consensus sequence) is
+ * - as specified by an input parameter if set
+ * - else group name with _HMM appended (if for a group)
+ * - else align frame title with _HMM appended (if title is not too long)
+ * - else "Alignment_HMM"
+ */
+ String name = "";
+
+ if (params != null)
+ {
+ for (ArgumentI arg : params)
+ {
+ String argName = arg.getName();
+ switch (argName)
+ {
+ case "HMM Name":
+ name = arg.getValue().trim();
+ break;
+ case "Use Reference Annotation":
+ args.add("--hand");
+ break;
+ }
+ }
+ }
+
+ if (group instanceof SequenceGroup)
+ {
+ name = ((SequenceGroup) group).getName() + "_HMM";
+ }
+
+ if ("".equals(name))
+ {
+ if (af != null && af.getTitle().length() < 15)
+ {
+ name = af.getTitle();
+ }
+ else
+ {
+ name = "Alignment_HMM";
+ }
+ }
+
+ args.add("-n");
+ args.add(name.replace(' ', '_'));
+ if (!alignment.isNucleotide())
+ {
+ args.add(ARG_AMINO); // TODO check for rna
+ }
+ else
+ {
+ args.add(ARG_DNA);
+ }
+
+ args.add(getFilePath(hmmFile, true));
+ args.add(getFilePath(sequencesFile, true));
+
+ return runCommand(args);
+ }
+
+ /**
+ * Imports the .hmm file produced by hmmbuild, and inserts the HMM consensus
+ * sequence (with attached HMM profile) as the first sequence in the alignment
+ * or group for which it was generated
+ *
+ * @param hmmFile
+ * @param ac
+ * (optional) the group for which the hmm was generated
+ * @throws IOException
+ */
+ private void importData(File hmmFile, AnnotatedCollectionI ac)
+ throws IOException
+ {
+ if (hmmFile.length() == 0L)
+ {
- Cache.log.error("Error: hmmbuild produced empty hmm file");
++ Console.error("Error: hmmbuild produced empty hmm file");
+ return;
+ }
+
+ HMMFile file = new HMMFile(
+ new FileParse(hmmFile.getAbsolutePath(), DataSourceType.FILE));
+ SequenceI hmmSeq = file.getHMM().getConsensusSequence();
+
+
+
+ ResidueCount counts = new ResidueCount(alignment.getSequences());
+ hmmSeq.getHMM().setBackgroundFrequencies(counts);
+
+ if (hmmSeq == null)
+ {
+ // hmmbuild failure not detected earlier
+ return;
+ }
+
+ if (ac instanceof SequenceGroup)
+ {
+ SequenceGroup grp = (SequenceGroup) ac;
+ char gapChar = alignment.getGapCharacter();
+ hmmSeq.insertCharAt(0, ac.getStartRes(), gapChar);
+ hmmSeq.insertCharAt(ac.getEndRes() + 1,
+ alignment.getWidth() - ac.getEndRes() - 1, gapChar);
+ SequenceI topSeq = grp.getSequencesInOrder(alignment)[0];
+ int topIndex = alignment.findIndex(topSeq);
+ alignment.insertSequenceAt(topIndex, hmmSeq);
+ ac.setSeqrep(hmmSeq);
+ grp.addSequence(hmmSeq, false);
+ }
+ else
+ {
+ alignment.insertSequenceAt(0, hmmSeq);
+ }
+ }
+}
--- /dev/null
+package jalview.hmmer;
+
+import jalview.bin.Cache;
++import jalview.bin.Console;
+import jalview.datamodel.Alignment;
+import jalview.datamodel.AlignmentAnnotation;
+import jalview.datamodel.AlignmentI;
+import jalview.datamodel.Annotation;
+import jalview.datamodel.HiddenMarkovModel;
+import jalview.datamodel.SequenceI;
+import jalview.gui.AlignFrame;
+import jalview.gui.Desktop;
+import jalview.gui.JvOptionPane;
+import jalview.io.DataSourceType;
+import jalview.io.FileParse;
+import jalview.io.StockholmFile;
+import jalview.util.FileUtils;
+import jalview.util.MessageManager;
+import jalview.ws.params.ArgumentI;
+import jalview.ws.params.simple.BooleanOption;
+import jalview.ws.params.simple.Option;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import javax.swing.JOptionPane;
+
+public class HMMSearch extends Search
+{
+
+ boolean realign = false;
+
+ boolean trim = false;
+
+ boolean returnNoOfNewSeqs = false;
+
+ int seqsToReturn = Integer.MAX_VALUE;
+
+
+ /**
+ * Constructor for the HMMSearchThread
+ *
+ * @param af
+ */
+ public HMMSearch(AlignFrame af, List<ArgumentI> args)
+ {
+ super(af, args);
+ }
+
+ /**
+ * Runs the HMMSearchThread: the data on the alignment or group is exported,
+ * then the command is executed in the command line and then the data is
+ * imported and displayed in a new frame. Call this method directly to execute
+ * synchronously, or via start() in a new Thread for asynchronously.
+ */
+ @Override
+ public void run()
+ {
+ HiddenMarkovModel hmm = getHmmProfile();
+ if (hmm == null)
+ {
+ // shouldn't happen if we got this far
- Cache.log.error("Error: no hmm for hmmsearch");
++ Console.error("Error: no hmm for hmmsearch");
+ return;
+ }
+
+ SequenceI hmmSeq = hmm.getConsensusSequence();
+ long msgId = System.currentTimeMillis();
+ af.setProgressBar(MessageManager.getString("status.running_search"),
+ msgId);
+
+ try
+ {
+ File hmmFile = FileUtils.createTempFile("hmm", ".hmm");
+ File hitsAlignmentFile = FileUtils.createTempFile("hitAlignment",
+ ".sto");
+ File searchOutputFile = FileUtils.createTempFile("searchOutput",
+ ".sto");
+
+ exportHmm(hmm, hmmFile.getAbsoluteFile());
+
+ boolean ran = runCommand(searchOutputFile, hitsAlignmentFile, hmmFile);
+ if (!ran)
+ {
+ JvOptionPane.showInternalMessageDialog(af, MessageManager
+ .formatMessage("warn.command_failed", "hmmsearch"));
+ return;
+ }
+
+ importData(hmmSeq, hitsAlignmentFile, hmmFile, searchOutputFile);
+ // TODO make realignment of search results a step at this level
+ // and make it conditional on this.realign
+ } catch (IOException | InterruptedException e)
+ {
+ e.printStackTrace();
+ }
+ finally
+ {
+ af.setProgressBar("", msgId);
+ }
+ }
+
+ /**
+ * Executes an hmmsearch with the given hmm as input. The database to be
+ * searched is a local file as specified by the 'Database' parameter, or the
+ * current alignment (written to file) if none is specified.
+ *
+ * @param searchOutputFile
+ * @param hitsAlignmentFile
+ * @param hmmFile
+ *
+ * @return
+ * @throws IOException
+ */
+ private boolean runCommand(File searchOutputFile, File hitsAlignmentFile,
+ File hmmFile) throws IOException
+ {
+ String command = getCommandPath(HMMSEARCH);
+ if (command == null)
+ {
+ return false;
+ }
+
+ List<String> args = new ArrayList<>();
+ args.add(command);
+ buildArguments(args, searchOutputFile, hitsAlignmentFile, hmmFile);
+
+ return runCommand(args);
+ }
+
+
+ /**
+ * Imports the data from the temporary file to which the output of hmmsearch
+ * was directed. The results are optionally realigned using hmmalign.
+ *
+ * @param hmmSeq
+ */
+ private void importData(SequenceI hmmSeq, File inputAlignmentTemp,
+ File hmmTemp, File searchOutputFile)
+ throws IOException, InterruptedException
+ {
+ BufferedReader br = new BufferedReader(
+ new FileReader(inputAlignmentTemp));
+ try
+ {
+ if (br.readLine() == null)
+ {
+ JOptionPane.showMessageDialog(af,
+ MessageManager.getString("label.no_sequences_found"));
+ return;
+ }
+ StockholmFile file = new StockholmFile(new FileParse(
+ inputAlignmentTemp.getAbsolutePath(), DataSourceType.FILE));
+ seqs = file.getSeqsAsArray();
+
+ readDomainTable(searchOutputFile, false);
+
+ if (searchAlignment)
+ {
+ recoverSequences(sequencesHash, seqs);
+ }
+
+ // look for PP cons and ref seq in alignment only annotation
+ AlignmentAnnotation modelpos = null, ppcons = null;
+ for (AlignmentAnnotation aa : file.getAnnotations())
+ {
+ if (aa.sequenceRef == null)
+ {
+ if (aa.label.equals("Reference Positions")) // RF feature type in
+ // stockholm parser
+ {
+ modelpos = aa;
+ }
+ if (aa.label.equals("Posterior Probability"))
+ {
+ ppcons = aa;
+ }
+ }
+ }
+
+
+ int seqCount = Math.min(seqs.length, seqsToReturn);
+ SequenceI[] hmmAndSeqs = new SequenceI[seqCount + 1];
+ hmmSeq = hmmSeq.deriveSequence(); // otherwise all bad things happen
+ hmmAndSeqs[0] = hmmSeq;
+ System.arraycopy(seqs, 0, hmmAndSeqs, 1, seqCount);
+ if (modelpos != null)
+ {
+ // TODO need - get ungapped sequence method
+ hmmSeq.setSequence(
+ hmmSeq.getDatasetSequence().getSequenceAsString());
+ Annotation[] refpos = modelpos.annotations;
+ // insert gaps to match with refseq positions
+ int gc = 0, lcol = 0;
+ for (int c = 0; c < refpos.length; c++)
+ {
+ if (refpos[c] != null && ("x".equals(refpos[c].displayCharacter)))
+ {
+ if (gc > 0)
+ {
+ hmmSeq.insertCharAt(lcol + 1, gc, '-');
+ }
+ gc = 0;
+ lcol = c;
+ }
+ else
+ {
+ gc++;
+ }
+ }
+ }
+
+ if (realign)
+ {
+ realignResults(hmmAndSeqs);
+ }
+ else
+ {
+ AlignmentI al = new Alignment(hmmAndSeqs);
+ if (ppcons != null)
+ {
+ al.addAnnotation(ppcons);
+ }
+ if (modelpos != null)
+ {
+ al.addAnnotation(modelpos);
+ }
+ AlignFrame alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
+ AlignFrame.DEFAULT_HEIGHT);
+ String ttl = "hmmSearch of " + databaseName + " using "
+ + hmmSeq.getName();
+ Desktop.addInternalFrame(alignFrame, ttl, AlignFrame.DEFAULT_WIDTH,
+ AlignFrame.DEFAULT_HEIGHT);
+
+ if (returnNoOfNewSeqs)
+ {
+ int nNew = checkForNewSequences();
+ JvOptionPane.showMessageDialog(af.alignPanel, nNew + " "
+ + MessageManager.getString("label.new_returned"));
+ }
+
+ }
+
+
+ hmmTemp.delete();
+ inputAlignmentTemp.delete();
+ searchOutputFile.delete();
+ } finally
+ {
+ if (br != null)
+ {
+ br.close();
+ }
+ }
+ }
+
+ private int checkForNewSequences()
+ {
+ int nNew = seqs.length;
+
+ for (SequenceI resultSeq : seqs)
+ {
+ for (SequenceI aliSeq : alignment.getSequencesArray())
+ {
+ if (resultSeq.getName().equals(aliSeq.getName()))
+ {
+ nNew--;
+ break;
+ }
+ }
+ }
+
+ return nNew;
+
+ }
+
+ /**
+ * Realigns the given sequences using hmmalign, to the HMM profile sequence
+ * which is the first in the array, and opens the results in a new frame
+ *
+ * @param hmmAndSeqs
+ */
+ protected void realignResults(SequenceI[] hmmAndSeqs)
+ {
+ /*
+ * and align the search results to the HMM profile
+ */
+ AlignmentI al = new Alignment(hmmAndSeqs);
+ AlignFrame frame = new AlignFrame(al, 1, 1);
+ List<ArgumentI> alignArgs = new ArrayList<>();
+ String alignTo = hmmAndSeqs[0].getName();
+ List<String> options = Collections.singletonList(alignTo);
+ Option option = new Option(MessageManager.getString("label.use_hmm"),
+ "", true, alignTo, alignTo, options, null);
+ alignArgs.add(option);
+ if (trim)
+ {
+ alignArgs.add(new BooleanOption(
+ MessageManager.getString(TRIM_TERMINI_KEY),
+ MessageManager.getString("label.trim_termini_desc"), true,
+ true, true, null));
+ }
+ HmmerCommand hmmalign = new HMMAlign(frame, alignArgs);
+ hmmalign.run();
+
+ if (returnNoOfNewSeqs)
+ {
+ int nNew = checkForNewSequences();
+ JvOptionPane.showMessageDialog(frame.alignPanel,
+ nNew + " " + MessageManager.getString("label.new_returned"));
+ }
+ }
+
+}
--- /dev/null
+package jalview.hmmer;
+
+import jalview.analysis.SeqsetUtils;
+import jalview.analysis.SeqsetUtils.SequenceInfo;
+import jalview.bin.Cache;
++import jalview.bin.Console;
+import jalview.datamodel.Alignment;
+import jalview.datamodel.AlignmentAnnotation;
+import jalview.datamodel.AlignmentI;
+import jalview.datamodel.AnnotatedCollectionI;
+import jalview.datamodel.Annotation;
+import jalview.datamodel.HiddenMarkovModel;
+import jalview.datamodel.SequenceGroup;
+import jalview.datamodel.SequenceI;
+import jalview.gui.AlignFrame;
+import jalview.gui.JvOptionPane;
+import jalview.gui.Preferences;
+import jalview.io.FastaFile;
+import jalview.io.HMMFile;
+import jalview.io.StockholmFile;
+import jalview.util.FileUtils;
+import jalview.util.MessageManager;
+import jalview.util.Platform;
+import jalview.ws.params.ArgumentI;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Base class for hmmbuild, hmmalign and hmmsearch
+ *
+ * @author TZVanaalten
+ *
+ */
+public abstract class HmmerCommand implements Runnable
+{
+ public static final String HMMBUILD = "hmmbuild";
+
+ protected final AlignFrame af;
+
+ protected final AlignmentI alignment;
+
+ protected final List<ArgumentI> params;
+
+ /*
+ * constants for i18n lookup of passed parameter names
+ */
+ static final String DATABASE_KEY = "label.database";
+
+ static final String THIS_ALIGNMENT_KEY = "label.this_alignment";
+
+ static final String USE_ACCESSIONS_KEY = "label.use_accessions";
+
+ static final String AUTO_ALIGN_SEQS_KEY = "label.auto_align_seqs";
+
+ static final String NUMBER_OF_RESULTS_KEY = "label.number_of_results";
+
+ static final String NUMBER_OF_ITERATIONS = "label.number_of_iterations";
+
+ static final String TRIM_TERMINI_KEY = "label.trim_termini";
+
+ static final String RETURN_N_NEW_SEQ = "label.check_for_new_sequences";
+
+ static final String REPORTING_CUTOFF_KEY = "label.reporting_cutoff";
+
+ static final String CUTOFF_NONE = "label.default";
+
+ static final String CUTOFF_SCORE = "label.score";
+
+ static final String CUTOFF_EVALUE = "label.evalue";
+
+ static final String REPORTING_SEQ_EVALUE_KEY = "label.reporting_seq_evalue";
+
+ static final String REPORTING_DOM_EVALUE_KEY = "label.reporting_dom_evalue";
+
+ static final String REPORTING_SEQ_SCORE_KEY = "label.reporting_seq_score";
+
+ static final String REPORTING_DOM_SCORE_KEY = "label.reporting_dom_score";
+
+ static final String INCLUSION_SEQ_EVALUE_KEY = "label.inclusion_seq_evalue";
+
+ static final String INCLUSION_DOM_EVALUE_KEY = "label.inclusion_dom_evalue";
+
+ static final String INCLUSION_SEQ_SCORE_KEY = "label.inclusion_seq_score";
+
+ static final String INCLUSION_DOM_SCORE_KEY = "label.inclusion_dom_score";
+
+ static final String ARG_TRIM = "--trim";
+
+ static final String INCLUSION_THRESHOLD_KEY = "label.inclusion_threshold";
+
+ /**
+ * Constructor
+ *
+ * @param alignFrame
+ * @param args
+ */
+ public HmmerCommand(AlignFrame alignFrame, List<ArgumentI> args)
+ {
+ af = alignFrame;
+ alignment = af.getViewport().getAlignment();
+ params = args;
+ }
+
+ /**
+ * Answers true if preference HMMER_PATH is set, and its value is the path to
+ * a directory that contains an executable <code>hmmbuild</code> or
+ * <code>hmmbuild.exe</code>, else false
+ *
+ * @return
+ */
+ public static boolean isHmmerAvailable()
+ {
+ File exec = FileUtils.getExecutable(HMMBUILD,
+ Cache.getProperty(Preferences.HMMER_PATH));
+ return exec != null;
+ }
+
+ /**
+ * Uniquifies the sequences when exporting and stores their details in a
+ * hashtable
+ *
+ * @param seqs
+ */
+ protected Map<String, SequenceInfo> stashSequences(SequenceI[] seqs)
+ {
+ return SeqsetUtils.uniquify(seqs, true);
+ }
+
+ /**
+ * Restores the sequence data lost by uniquifying
+ *
+ * @param sequencesHash
+ * @param seqs
+ */
+ protected void recoverSequences(Map<String, SequenceInfo> sequencesHash, SequenceI[] seqs)
+ {
+ SeqsetUtils.deuniquify(sequencesHash, seqs);
+ }
+
+ /**
+ * Runs a command as a separate process and waits for it to complete. Answers
+ * true if the process return status is zero, else false.
+ *
+ * @param commands
+ * the executable command and any arguments to it
+ * @throws IOException
+ */
+ public boolean runCommand(List<String> commands)
+ throws IOException
+ {
+ List<String> args = Platform.isWindowsAndNotJS() ? wrapWithCygwin(commands)
+ : commands;
+
+ try
+ {
+ ProcessBuilder pb = new ProcessBuilder(args);
+ pb.redirectErrorStream(true); // merge syserr to sysout
+ if (Platform.isWindowsAndNotJS())
+ {
+ String path = pb.environment().get("Path");
+ path = jalview.bin.Cache.getProperty("CYGWIN_PATH") + ";" + path;
+ pb.environment().put("Path", path);
+ }
+ final Process p = pb.start();
+ new Thread(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ BufferedReader input = new BufferedReader(
+ new InputStreamReader(p.getInputStream()));
+ try
+ {
+ String line = input.readLine();
+ while (line != null)
+ {
+ System.out.println(line);
+ line = input.readLine();
+ }
+ } catch (IOException e)
+ {
+ e.printStackTrace();
+ }
+ }
+ }).start();
+
+ p.waitFor();
+ int exitValue = p.exitValue();
+ if (exitValue != 0)
+ {
- Cache.log.error("Command failed, return code = " + exitValue);
- Cache.log.error("Command/args were: " + args.toString());
++ Console.error("Command failed, return code = " + exitValue);
++ Console.error("Command/args were: " + args.toString());
+ }
+ return exitValue == 0; // 0 is success, by convention
+ } catch (Exception e)
+ {
+ e.printStackTrace();
+ return false;
+ }
+ }
+
+ /**
+ * Converts the given command to a Cygwin "bash" command wrapper. The hmmer
+ * command and any arguments to it are converted into a single parameter to the
+ * bash command.
+ *
+ * @param commands
+ */
+ protected List<String> wrapWithCygwin(List<String> commands)
+ {
+ File bash = FileUtils.getExecutable("bash",
+ Cache.getProperty(Preferences.CYGWIN_PATH));
+ if (bash == null)
+ {
- Cache.log.error("Cygwin shell not found");
++ Console.error("Cygwin shell not found");
+ return commands;
+ }
+
+ List<String> wrapped = new ArrayList<>();
+ // wrapped.add("C:\Users\tva\run");
+ wrapped.add(bash.getAbsolutePath());
+ wrapped.add("-c");
+
+ /*
+ * combine hmmbuild/search/align and arguments to a single string
+ */
+ StringBuilder sb = new StringBuilder();
+ for (String cmd : commands)
+ {
+ sb.append(" ").append(cmd);
+ }
+ wrapped.add(sb.toString());
+
+ return wrapped;
+ }
+
+ /**
+ * Exports an alignment, and reference (RF) annotation if present, to the
+ * specified file, in Stockholm format, removing all HMM sequences
+ *
+ * @param seqs
+ * @param toFile
+ * @param annotated
+ * @throws IOException
+ */
+ public void exportStockholm(SequenceI[] seqs, File toFile,
+ AnnotatedCollectionI annotated)
+ throws IOException
+ {
+ if (seqs == null)
+ {
+ return;
+ }
+ AlignmentI newAl = new Alignment(seqs);
+
+ if (!newAl.isAligned())
+ {
+ newAl.padGaps();
+ }
+
+ if (toFile != null && annotated != null)
+ {
+ AlignmentAnnotation[] annots = annotated.getAlignmentAnnotation();
+ if (annots != null)
+ {
+ for (AlignmentAnnotation annot : annots)
+ {
+ if (annot.label.contains("Reference") || "RF".equals(annot.label))
+ {
+ AlignmentAnnotation newRF;
+ if (annot.annotations.length > newAl.getWidth())
+ {
+ Annotation[] rfAnnots = new Annotation[newAl.getWidth()];
+ System.arraycopy(annot.annotations, 0, rfAnnots, 0,
+ rfAnnots.length);
+ newRF = new AlignmentAnnotation("RF", "Reference Positions",
+ rfAnnots);
+ }
+ else
+ {
+ newRF = new AlignmentAnnotation(annot);
+ }
+ newAl.addAnnotation(newRF);
+ }
+ }
+ }
+ }
+
+ for (SequenceI seq : newAl.getSequencesArray())
+ {
+ if (seq.getAnnotation() != null)
+ {
+ for (AlignmentAnnotation ann : seq.getAnnotation())
+ {
+ seq.removeAlignmentAnnotation(ann);
+ }
+ }
+ }
+
+ StockholmFile file = new StockholmFile(newAl);
+ String output = file.print(seqs, false);
+ PrintWriter writer = new PrintWriter(toFile);
+ writer.println(output);
+ writer.close();
+ }
+
+ /**
+ * Answers the full path to the given hmmer executable, or null if file cannot
+ * be found or is not executable
+ *
+ * @param cmd
+ * command short name e.g. hmmalign
+ * @return
+ * @throws IOException
+ */
+ protected String getCommandPath(String cmd)
+ throws IOException
+ {
+ String binariesFolder = Cache.getProperty(Preferences.HMMER_PATH);
+ // ensure any symlink to the directory is resolved:
+ binariesFolder = Paths.get(binariesFolder).toRealPath().toString();
+ File file = FileUtils.getExecutable(cmd, binariesFolder);
+ if (file == null && af != null)
+ {
+ JvOptionPane.showInternalMessageDialog(af, MessageManager
+ .formatMessage("label.executable_not_found", cmd));
+ }
+
+ return file == null ? null : getFilePath(file, true);
+ }
+
+ /**
+ * Exports an HMM to the specified file
+ *
+ * @param hmm
+ * @param hmmFile
+ * @throws IOException
+ */
+ public void exportHmm(HiddenMarkovModel hmm, File hmmFile)
+ throws IOException
+ {
+ if (hmm != null)
+ {
+ HMMFile file = new HMMFile(hmm);
+ PrintWriter writer = new PrintWriter(hmmFile);
+ writer.print(file.print());
+ writer.close();
+ }
+ }
+
+ // TODO is needed?
+ /**
+ * Exports a sequence to the specified file
+ *
+ * @param hmm
+ * @param hmmFile
+ * @throws IOException
+ */
+ public void exportSequence(SequenceI seq, File seqFile) throws IOException
+ {
+ if (seq != null)
+ {
+ FastaFile file = new FastaFile();
+ PrintWriter writer = new PrintWriter(seqFile);
+ writer.print(file.print(new SequenceI[] { seq }, false));
+ writer.close();
+ }
+ }
+
+ /**
+ * Answers the HMM profile for the profile sequence the user selected (default
+ * is just the first HMM sequence in the alignment)
+ *
+ * @return
+ */
+ protected HiddenMarkovModel getHmmProfile()
+ {
+ String alignToParamName = MessageManager.getString("label.use_hmm");
+ for (ArgumentI arg : params)
+ {
+ String name = arg.getName();
+ if (name.equals(alignToParamName))
+ {
+ String seqName = arg.getValue();
+ SequenceI hmmSeq = alignment.findName(seqName);
+ if (hmmSeq.hasHMMProfile())
+ {
+ return hmmSeq.getHMM();
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Answers the query sequence the user selected (default is just the first
+ * sequence in the alignment)
+ *
+ * @return
+ */
+ protected SequenceI getSequence()
+ {
+ String alignToParamName = MessageManager
+ .getString("label.use_sequence");
+ for (ArgumentI arg : params)
+ {
+ String name = arg.getName();
+ if (name.equals(alignToParamName))
+ {
+ String seqName = arg.getValue();
+ SequenceI seq = alignment.findName(seqName);
+ return seq;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Answers an absolute path to the given file, in a format suitable for
+ * processing by a hmmer command. On a Windows platform, the native Windows file
+ * path is converted to Cygwin format, by replacing '\'with '/' and drive letter
+ * X with /cygdrive/x.
+ *
+ * @param resultFile
+ * @param isInCygwin
+ * True if file is to be read/written from within the Cygwin
+ * shell. Should be false for any imports.
+ * @return
+ */
+ protected String getFilePath(File resultFile, boolean isInCygwin)
+ {
+ String path = resultFile.getAbsolutePath();
+ if (Platform.isWindowsAndNotJS() && isInCygwin)
+ {
+ // the first backslash escapes '\' for the regular expression argument
+ path = path.replaceAll("\\" + File.separator, "/");
+ int colon = path.indexOf(':');
+ if (colon > 0)
+ {
+ String drive = path.substring(0, colon);
+ path = path.replaceAll(drive + ":", "/cygdrive/" + drive);
+ }
+ }
+
+ return path;
+ }
+
+ /**
+ * A helper method that deletes any HMM consensus sequence from the given
+ * collection, and from the parent alignment if <code>ac</code> is a subgroup
+ *
+ * @param ac
+ */
+ void deleteHmmSequences(AnnotatedCollectionI ac)
+ {
+ List<SequenceI> hmmSeqs = ac.getHmmSequences();
+ for (SequenceI hmmSeq : hmmSeqs)
+ {
+ if (ac instanceof SequenceGroup)
+ {
+ ((SequenceGroup) ac).deleteSequence(hmmSeq, false);
+ AnnotatedCollectionI context = ac.getContext();
+ if (context != null && context instanceof AlignmentI)
+ {
+ ((AlignmentI) context).deleteSequence(hmmSeq);
+ }
+ }
+ else
+ {
+ ((AlignmentI) ac).deleteSequence(hmmSeq);
+ }
+ }
+ }
+
+ /**
+ * Sets the names of any duplicates within the given sequences to include their
+ * respective lengths. Deletes any duplicates that have the same name after this
+ * step
+ *
+ * @param seqs
+ */
+ void renameDuplicates(AlignmentI al)
+ {
+
+ SequenceI[] seqs = al.getSequencesArray();
+ List<Boolean> wasRenamed = new ArrayList<>();
+
+ for (SequenceI seq : seqs)
+ {
+ wasRenamed.add(false);
+ }
+
+ for (int i = 0; i < seqs.length; i++)
+ {
+ for (int j = 0; j < seqs.length; j++)
+ {
+ if (seqs[i].getName().equals(seqs[j].getName()) && i != j
+ && !wasRenamed.get(j))
+ {
+
+ wasRenamed.set(i, true);
+ String range = "/" + seqs[j].getStart() + "-" + seqs[j].getEnd();
+ // setting sequence name to include range - to differentiate between
+ // sequences of the same name. Currently have to include the range twice
+ // because the range is removed (once) when setting the name
+ // TODO come up with a better way of doing this
+ seqs[j].setName(seqs[j].getName() + range + range);
+ }
+
+ }
+ if (wasRenamed.get(i))
+ {
+ String range = "/" + seqs[i].getStart() + "-" + seqs[i].getEnd();
+ seqs[i].setName(seqs[i].getName() + range + range);
+ }
+ }
+
+ for (int i = 0; i < seqs.length; i++)
+ {
+ for (int j = 0; j < seqs.length; j++)
+ {
+ if (seqs[i].getName().equals(seqs[j].getName()) && i != j)
+ {
+ al.deleteSequence(j);
+ }
+ }
+ }
+ }
+
+}
--- /dev/null
+package jalview.hmmer;
+
+import jalview.bin.Cache;
++import jalview.bin.Console;
+import jalview.datamodel.Alignment;
+import jalview.datamodel.AlignmentI;
+import jalview.datamodel.SequenceI;
+import jalview.gui.AlignFrame;
+import jalview.gui.Desktop;
+import jalview.gui.JvOptionPane;
+import jalview.io.DataSourceType;
+import jalview.io.FileParse;
+import jalview.io.StockholmFile;
+import jalview.util.FileUtils;
+import jalview.util.MessageManager;
+import jalview.ws.params.ArgumentI;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.swing.JOptionPane;
+
+public class JackHMMER extends Search
+{
+
+ SequenceI seq = null;
+
+ /**
+ * Constructor for the JackhmmerThread
+ *
+ * @param af
+ */
+ public JackHMMER(AlignFrame af, List<ArgumentI> args)
+ {
+ super(af, args);
+ }
+
+ /**
+ * Runs the JackhmmerThread: the data on the alignment or group is exported,
+ * then the command is executed in the command line and then the data is
+ * imported and displayed in a new frame. Call this method directly to execute
+ * synchronously, or via start() in a new Thread for asynchronously.
+ */
+ @Override
+ public void run()
+ {
+ seq = getSequence();
+ if (seq == null)
+ {
+ // shouldn't happen if we got this far
- Cache.log.error("Error: no sequence for jackhmmer");
++ Console.error("Error: no sequence for jackhmmer");
+ return;
+ }
+
+ long msgId = System.currentTimeMillis();
+ af.setProgressBar(MessageManager.getString("status.running_search"),
+ msgId);
+
+ try
+ {
+ File seqFile = FileUtils.createTempFile("seq", ".sto");
+ File hitsAlignmentFile = FileUtils.createTempFile("hitAlignment",
+ ".sto");
+ File searchOutputFile = FileUtils.createTempFile("searchOutput",
+ ".txt");
+
+ exportStockholm(new SequenceI[] { seq }, seqFile.getAbsoluteFile(),
+ null);
+
+ boolean ran = runCommand(searchOutputFile, hitsAlignmentFile,
+ seqFile);
+ if (!ran)
+ {
+ JvOptionPane.showInternalMessageDialog(af, MessageManager
+ .formatMessage("warn.command_failed", "jackhmmer"));
+ return;
+ }
+
+ importData(hitsAlignmentFile, seqFile, searchOutputFile);
+ // TODO make realignment of search results a step at this level
+ // and make it conditional on this.realign
+ } catch (IOException | InterruptedException e)
+ {
+ e.printStackTrace();
+ } finally
+ {
+ af.setProgressBar("", msgId);
+ }
+ }
+
+ /**
+ * Executes an jackhmmer search with the given sequence as input. The database
+ * to be searched is a local file as specified by the 'Database' parameter, or
+ * the current alignment (written to file) if none is specified.
+ *
+ * @param searchOutputFile
+ * @param hitsAlignmentFile
+ * @param seqFile
+ *
+ * @return
+ * @throws IOException
+ */
+ private boolean runCommand(File searchOutputFile, File hitsAlignmentFile,
+ File seqFile) throws IOException
+ {
+ String command = getCommandPath(JACKHMMER);
+ if (command == null)
+ {
+ return false;
+ }
+
+ List<String> args = new ArrayList<>();
+ args.add(command);
+ buildArguments(args, searchOutputFile, hitsAlignmentFile, seqFile);
+
+ return runCommand(args);
+ }
+
+ /**
+ * Imports the data from the temporary file to which the output of jackhmmer was
+ * directed.
+ */
+ private void importData(File inputAlignmentTemp, File seqTemp,
+ File searchOutputFile) throws IOException, InterruptedException
+ {
+ BufferedReader br = new BufferedReader(
+ new FileReader(inputAlignmentTemp));
+ try
+ {
+ if (br.readLine() == null)
+ {
+ JOptionPane.showMessageDialog(af,
+ MessageManager.getString("label.no_sequences_found"));
+ return;
+ }
+ StockholmFile file = new StockholmFile(new FileParse(
+ inputAlignmentTemp.getAbsolutePath(), DataSourceType.FILE));
+ seqs = file.getSeqsAsArray();
+
+ readDomainTable(searchOutputFile, true);
+
+ if (searchAlignment)
+ {
+ recoverSequences(sequencesHash, seqs);
+ }
+
+
+
+ int seqCount = seqs.length;
+
+
+ AlignmentI al = new Alignment(seqs);
+
+ AlignFrame alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
+ AlignFrame.DEFAULT_HEIGHT);
+ String ttl = "jackhmmer search of " + databaseName + " using "
+ + seqs[0].getName();
+ Desktop.addInternalFrame(alignFrame, ttl, AlignFrame.DEFAULT_WIDTH,
+ AlignFrame.DEFAULT_HEIGHT);
+
+ seqTemp.delete();
+ inputAlignmentTemp.delete();
+ searchOutputFile.delete();
+ } finally
+ {
+ if (br != null)
+ {
+ br.close();
+ }
+ }
+ }
+
+
+
+
+}
*/
package jalview.io;
- import jalview.datamodel.AlignmentAnnotation;
- import jalview.datamodel.AlignmentI;
- import jalview.datamodel.Sequence;
- import jalview.datamodel.SequenceGroup;
- import jalview.datamodel.SequenceI;
- import jalview.util.MessageManager;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;
+ import jalview.datamodel.AlignmentAnnotation;
+ import jalview.datamodel.AlignmentI;
+ import jalview.datamodel.Sequence;
+ import jalview.datamodel.SequenceGroup;
+ import jalview.datamodel.SequenceI;
+ import jalview.util.MessageManager;
+
/**
* DOCUMENT ME!
*
private boolean parseImmediately = true;
+ private boolean dataClosed = false;
+
/**
* @return if doParse() was called at construction time
*/
public AlignFile(boolean parseImmediately, FileParse source)
throws IOException
{
+ this(parseImmediately, source, true);
+ }
+
+ public AlignFile(boolean parseImmediately, FileParse source,
+ boolean closeData) throws IOException
+ {
super(source);
initData();
if (parseImmediately)
{
- doParse();
+ doParse(closeData);
}
}
*/
public void doParse() throws IOException
{
+ doParse(true);
+ }
+
+ public void doParse(boolean closeData) throws IOException
+ {
if (parseCalled)
{
throw new IOException(
}
parseCalled = true;
parse();
+ if (closeData && !dataClosed)
+ {
+ dataIn.close();
+ dataClosed = true;
+ }
}
/**
*/
protected void initData()
{
- seqs = new Vector<SequenceI>();
- annotations = new Vector<AlignmentAnnotation>();
- seqGroups = new ArrayList<SequenceGroup>();
+ seqs = new Vector<>();
+ annotations = new Vector<>();
+ seqGroups = new ArrayList<>();
parseCalled = false;
}
@Override
public void setSeqs(SequenceI[] s)
{
- seqs = new Vector<SequenceI>();
+ seqs = new Vector<>();
for (int i = 0; i < s.length; i++)
{
{
if (newickStrings == null)
{
- newickStrings = new Vector<String[]>();
+ newickStrings = new Vector<>();
}
newickStrings.addElement(new String[] { treeName, newickString });
}
{
seqs.add(seq);
}
+
+ /**
+ * Used only for hmmer statistics, so should probably be removed at some
+ * point. TODO remove this
+ *
+ * @return
+ */
+ public Vector<AlignmentAnnotation> getAnnotations()
+ {
+ return annotations;
+ }
+
}
import jalview.analysis.Conservation;
import jalview.api.AlignViewportI;
+import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentAnnotation;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.Annotation;
private String lastread = "";
/**
+ * default calcId string for new annotation
+ */
+ private String defaultCalcId = null;
+
+ /**
* Constructor
*/
public AnnotationFile()
return readAnnotationFile(al, null, file, sourceType);
}
+ /**
+ * read an annotation file onto the alignment, but apply the given calcId
+ * @param aln
+ * @param calcId
+ * @param file
+ * @param url
+ * @return
+ */
+ public boolean readAnnotationFileWithCalcId(Alignment aln, String calcId, String file,
+ DataSourceType url)
+ {
+ defaultCalcId=calcId;
+ return readAnnotationFile(aln, null, file, url);
+ }
+
public boolean readAnnotationFile(AlignmentI al, HiddenColumns hidden,
Object file, DataSourceType sourceType)
{
annotation = new AlignmentAnnotation(label, description,
(index == 0) ? null : annotations, 0, 0, graphStyle);
-
+ annotation.setCalcId(defaultCalcId);
annotation.score = score;
if (!overrideAutoAnnot && autoAnnots
.containsKey(autoAnnotsKey(annotation, refSeq, groupRef)))
if (rowset != null && rowset.size() > 0)
{
AlignmentAnnotation alan = null;
- for (int elm = 0,
- elmSize = rowset.size(); elm < elmSize; elm++)
+ for (int elm = 0, elmSize = rowset
+ .size(); elm < elmSize; elm++)
{
alan = (AlignmentAnnotation) rowset.elementAt(elm);
alan.groupRef = theGroup;
{
return readFile(null, file, sourceType, fileFormat);
}
-
- public AlignmentI readFile(File selectedFile, String file, DataSourceType sourceType,
- FileFormatI fileFormat) throws IOException
+
+ public AlignmentI readFile(File selectedFile, String file,
+ DataSourceType sourceType, FileFormatI fileFormat)
+ throws IOException
{
this.selectedFile = selectedFile;
- if (selectedFile != null)
- {
- this.inFile = selectedFile.getPath();
- }
- this.inFile = file;
+ inFile = (selectedFile == null ? file : selectedFile.getPath());
try
{
if (fileFormat.isStructureFile())
if (isParseWithJMOL)
{
// needs a File option
- alignFile = new JmolParser(selectedFile == null ? inFile : selectedFile, sourceType);
+ alignFile = new JmolParser(
+ selectedFile == null ? inFile : selectedFile, sourceType);
}
else
{
((StructureFile) alignFile).setDbRefType(
FileFormat.PDB.equals(fileFormat) ? Type.PDB : Type.MMCIF);
}
- else if (selectedFile != null) {
- alignFile = fileFormat.getReader(new FileParse(selectedFile, sourceType));
- } else
+ else if (selectedFile != null)
+ {
+ alignFile = fileFormat
+ .getReader(new FileParse(selectedFile, sourceType));
+ }
+ else
{
// alignFile = fileFormat.getAlignmentFile(inFile, sourceType);
alignFile = fileFormat.getReader(new FileParse(inFile, sourceType));
return null;
}
-
/**
* Determines the protocol (i.e DataSourceType.{FILE|PASTE|URL}) for the input
* data
*
* BH 2018 allows File or String, and can return RELATIVE_URL
*
- * @param dataObject File or String
+ * @param dataObject
+ * File or String
* @return the protocol for the input data
*/
public static DataSourceType checkProtocol(Object dataObject)
{
- if(dataObject instanceof File)
+ if (dataObject instanceof File)
{
return DataSourceType.FILE;
}
-
+
String data = dataObject.toString();
DataSourceType protocol = DataSourceType.PASTE;
String ft = data.toLowerCase(Locale.ROOT).trim();
*/
package jalview.io;
-
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.TreeMap;
import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.gui.Desktop;
import jalview.gui.JvOptionPane;
import jalview.util.MessageManager;
import jalview.util.Platform;
+
/*
* BackupFiles used for manipulating (naming rolling/deleting) backup/version files when an alignment or project file is saved.
* User configurable options are:
private static final String newTempFileSuffix = "_newfile";
private static final String oldTempFileSuffix = "_oldfile_tobedeleted";
+
public BackupFiles(String filename)
{
this(new File(filename));
{
String tempfilename = file.getName();
File tempdir = file.getParentFile();
- Cache.trace(
+ Console.trace(
"BACKUPFILES [file!=null] attempting to create temp file for "
+ tempfilename + " in dir " + tempdir);
temp = File.createTempFile(tempfilename,
TEMP_FILE_EXT + newTempFileSuffix, tempdir);
- Cache.debug(
+ Console.debug(
"BACKUPFILES using temp file " + temp.getAbsolutePath());
}
else
{
- Cache.trace(
+ Console.trace(
"BACKUPFILES [file==null] attempting to create default temp file "
+ DEFAULT_TEMP_FILE + " with extension "
+ TEMP_FILE_EXT);
}
} catch (IOException e)
{
- Cache.error("Could not create temp file to save to (IOException)");
- Cache.error(e.getMessage());
- Cache.debug(Cache.getStackTraceString(e));
+ Console.error("Could not create temp file to save to (IOException)");
+ Console.error(e.getMessage());
+ Console.debug(Cache.getStackTraceString(e));
} catch (Exception e)
{
- Cache.error("Exception creating temp file for saving");
- Cache.debug(Cache.getStackTraceString(e));
+ Console.error("Exception creating temp file for saving");
+ Console.debug(Cache.getStackTraceString(e));
}
this.setTempFile(temp);
}
public static void classInit()
{
- Cache.initLogger();
- Cache.trace("BACKUPFILES classInit");
+ Console.initLogger();
+ Console.trace("BACKUPFILES classInit");
boolean e = Cache.getDefault(ENABLED, !Platform.isJS());
setEnabled(e);
- Cache.trace("BACKUPFILES " + (e ? "enabled" : "disabled"));
+ Console.trace("BACKUPFILES " + (e ? "enabled" : "disabled"));
BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
.getSavedBackupEntry();
- Cache.trace("BACKUPFILES preset scheme " + bfpe.toString());
+ Console.trace("BACKUPFILES preset scheme " + bfpe.toString());
setConfirmDelete(bfpe.confirmDelete);
- Cache.trace("BACKUPFILES confirm delete " + bfpe.confirmDelete);
+ Console.trace("BACKUPFILES confirm delete " + bfpe.confirmDelete);
}
public static void setEnabled(boolean flag)
path = this.getTempFile().getCanonicalPath();
} catch (IOException e)
{
- Cache.error("IOException when getting Canonical Path of temp file '"
+ Console.error("IOException when getting Canonical Path of temp file '"
+ this.getTempFile().getName() + "'");
- Cache.debug(Cache.getStackTraceString(e));
+ Console.debug(Cache.getStackTraceString(e));
}
return path;
}
|| suffix.length() == 0)
{
// nothing to do
- Cache.debug("BACKUPFILES rollBackupFiles nothing to do." + ", "
+ Console.debug("BACKUPFILES rollBackupFiles nothing to do." + ", "
+ "filename: " + (file != null ? file.getName() : "null")
+ ", " + "file exists: " + file.exists() + ", " + "enabled: "
+ enabled + ", " + "max: " + max + ", " + "suffix: '" + suffix
return true;
}
- Cache.trace("BACKUPFILES rollBackupFiles starting");
+ Console.trace("BACKUPFILES rollBackupFiles starting");
+
String dir = "";
File dirFile;
try
{
dirFile = file.getParentFile();
dir = dirFile.getCanonicalPath();
- Cache.trace("BACKUPFILES dir: " + dir);
+ Console.trace("BACKUPFILES dir: " + dir);
} catch (Exception e)
{
- Cache.error("Could not get canonical path for file '" + file + "'");
- Cache.error(e.getMessage());
- Cache.debug(Cache.getStackTraceString(e));
+ Console.error("Could not get canonical path for file '" + file + "'");
+ Console.error(e.getMessage());
+ Console.debug(Cache.getStackTraceString(e));
return false;
}
String filename = file.getName();
String basename = filename;
- Cache.trace("BACKUPFILES filename is " + filename);
+ Console.trace("BACKUPFILES filename is " + filename);
boolean ret = true;
// Create/move backups up one
File[] backupFiles = dirFile.listFiles(bff);
int nextIndexNum = 0;
- Cache.trace("BACKUPFILES backupFiles.length: " + backupFiles.length);
+ Console.trace("BACKUPFILES backupFiles.length: " + backupFiles.length);
if (backupFiles.length == 0)
{
// No other backup files. Just need to move existing file to backupfile_1
- Cache.trace(
+ Console.trace(
"BACKUPFILES no existing backup files, setting index to 1");
nextIndexNum = 1;
}
if (reverseOrder)
{
// backup style numbering
-
- Cache.trace("BACKUPFILES rolling files in reverse order");
+ Console.trace("BACKUPFILES rolling files in reverse order");
int tempMax = noMax ? -1 : max;
// noMax == true means no limits
tempMax = i;
}
}
+
File previousFile = null;
File fileToBeDeleted = null;
for (int n = tempMax; n > 0; n--)
// no "oldest" file to delete
previousFile = backupfile_n;
fileToBeDeleted = null;
- Cache.trace("BACKUPFILES No oldest file to delete");
+ Console.trace("BACKUPFILES No oldest file to delete");
continue;
}
File replacementFile = backupfile_n;
long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
long replacementFileLMT = replacementFile.lastModified();
- Cache.trace("BACKUPFILES fileToBeDeleted is "
+ Console.trace("BACKUPFILES fileToBeDeleted is "
+ fileToBeDeleted.getAbsolutePath());
- Cache.trace("BACKUPFILES replacementFile is "
+ Console.trace("BACKUPFILES replacementFile is "
+ backupfile_n.getAbsolutePath());
try
{
File oldestTempFile = nextTempFile(fileToBeDeleted.getName(),
dirFile);
+
if (fileToBeDeletedLMT > replacementFileLMT)
{
String fileToBeDeletedLMTString = sdf
.format(fileToBeDeletedLMT);
String replacementFileLMTString = sdf
.format(replacementFileLMT);
- Cache.warn("WARNING! I am set to delete backupfile "
+ Console.warn("WARNING! I am set to delete backupfile "
+ fileToBeDeleted.getName()
+ " has modification time "
+ fileToBeDeletedLMTString
boolean delete = confirmNewerDeleteFile(fileToBeDeleted,
replacementFile, true);
- Cache.trace("BACKUPFILES " + (delete ? "confirmed" : "not")
- + " deleting file "
+ Console.trace("BACKUPFILES "
+ + (delete ? "confirmed" : "not") + " deleting file "
+ fileToBeDeleted.getAbsolutePath()
+ " which is newer than "
+ replacementFile.getAbsolutePath());
}
else
{
- Cache.debug("BACKUPFILES moving "
+ Console.debug("BACKUPFILES moving "
+ fileToBeDeleted.getAbsolutePath() + " to "
+ oldestTempFile.getAbsolutePath());
moveFileToFile(fileToBeDeleted, oldestTempFile);
}
else
{
- Cache.debug("BACKUPFILES going to move "
+ Console.debug("BACKUPFILES going to move "
+ fileToBeDeleted.getAbsolutePath() + " to "
+ oldestTempFile.getAbsolutePath());
moveFileToFile(fileToBeDeleted, oldestTempFile);
} catch (Exception e)
{
- Cache.error(
+ Console.error(
"Error occurred, probably making new temp file for '"
+ fileToBeDeleted.getName() + "'");
- Cache.error(Cache.getStackTraceString(e));
+ Console.error(Cache.getStackTraceString(e));
}
// reset
}
bfsb.append(backupFiles[i].getName());
}
- Cache.trace("BACKUPFILES backupFiles: " + bfsb.toString());
+ Console.trace("BACKUPFILES backupFiles: " + bfsb.toString());
// noMax == true means keep all backup files
if ((!noMax) && bfTreeMap.size() >= max)
{
- Cache.trace("BACKUPFILES noMax: " + noMax + ", " + "max: " + max
+ Console.trace("BACKUPFILES noMax: " + noMax + ", " + "max: " + max
+ ", " + "bfTreeMap.size(): " + bfTreeMap.size());
// need to delete some files to keep number of backups to designated
// max.
int numToDelete = suffix.indexOf(NUM_PLACEHOLDER) > -1
? bfTreeMap.size() - max + 1
: 0;
- Cache.trace("BACKUPFILES numToDelete: " + numToDelete);
+ Console.trace("BACKUPFILES numToDelete: " + numToDelete);
// the "replacement" file is the latest backup file being kept (it's
// not replacing though)
File replacementFile = numToDelete < backupFiles.length
File fileToBeDeleted = backupFiles[i];
boolean delete = true;
- Cache.trace("BACKUPFILES fileToBeDeleted: " + fileToBeDeleted);
+ Console.trace(
+ "BACKUPFILES fileToBeDeleted: " + fileToBeDeleted);
+
boolean newer = false;
if (replacementFile != null)
{
String replacementFileLMTString = sdf
.format(replacementFileLMT);
- Cache.warn("WARNING! I am set to delete backupfile '"
+ Console.warn("WARNING! I am set to delete backupfile '"
+ fileToBeDeleted.getName()
+ "' has modification time "
+ fileToBeDeletedLMTString
{
// User has confirmed delete -- no need to add it to the list
fileToBeDeleted.delete();
- Cache.debug("BACKUPFILES deleting fileToBeDeleted: "
+ Console.debug("BACKUPFILES deleting fileToBeDeleted: "
+ fileToBeDeleted);
delete = false;
}
else
{
// keeping file, nothing to do!
- Cache.debug("BACKUPFILES keeping fileToBeDeleted: "
+ Console.debug("BACKUPFILES keeping fileToBeDeleted: "
+ fileToBeDeleted);
}
}
if (delete)
{
addDeleteFile(fileToBeDeleted);
- Cache.debug("BACKUPFILES addDeleteFile(fileToBeDeleted): "
+ Console.debug("BACKUPFILES addDeleteFile(fileToBeDeleted): "
+ fileToBeDeleted);
}
String latestBackupFilename = dir + File.separatorChar
+ BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
suffix, digits);
- Cache.trace("BACKUPFILES Moving old file [" + file
+ Console.trace("BACKUPFILES Moving old file [" + file
+ "] to latestBackupFilename [" + latestBackupFilename + "]");
// using boolean '&' instead of '&&' as don't want moveFileToFile attempt to
// be conditional (short-circuit)
ret = ret & moveFileToFile(file, new File(latestBackupFilename));
- Cache.debug("BACKUPFILES moving " + file + " to " + latestBackupFilename
- + " was " + (ret ? "" : "NOT ") + "successful");
-
+ Console.debug(
+ "BACKUPFILES moving " + file + " to " + latestBackupFilename
+ + " was " + (ret ? "" : "NOT ") + "successful");
if (tidyUp)
{
- Cache.debug("BACKUPFILES tidying up files");
+ Console.debug("BACKUPFILES tidying up files");
tidyUpFiles();
}
saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
} catch (Exception e)
{
- Cache.error(
+ Console.error(
"Error when confirming to keep backup file newer than other backup files.");
e.printStackTrace();
}
MessageManager.getString("label.delete"),
MessageManager.getString("label.rename") };
+ // TODO enable JvOptionPane to behave appropriately when batch/headless
confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
- : JvOptionPane.showOptionDialog(Desktop.desktop,
+ : JvOptionPane.showOptionDialog(Desktop.getDesktopPane(),
messageSB.toString(),
MessageManager.getString(
"label.backupfiles_confirm_delete"),
- // "Confirm delete"
JvOptionPane.YES_NO_OPTION,
JvOptionPane.WARNING_MESSAGE, null, options,
options[0]);
MessageManager.getString("label.keep") };
confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
- : JvOptionPane.showOptionDialog(Desktop.desktop,
- messageSB.toString(),
- MessageManager.getString(
- "label.backupfiles_confirm_delete"),
- // "Confirm delete"
- JvOptionPane.YES_NO_OPTION,
- JvOptionPane.WARNING_MESSAGE, null, options,
- options[0]);
+ : JvOptionPane.showOptionDialog(Desktop.getDesktopPane(),
+ messageSB.toString(),
+ MessageManager.getString("label.backupfiles_confirm_delete"),
+ JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
+ null, options, options[0]);
}
-
// return should be TRUE if file is to be deleted
return (confirmButton == JvOptionPane.YES_OPTION);
}
}
int confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
- : JvOptionPane.showConfirmDialog(Desktop.getDesktopPane(),
- : JvOptionPane.showConfirmDialog(Desktop.desktop,
++ : JvOptionPane.showConfirmDialog(Desktop.getDesktopPane(),
messageSB.toString(),
MessageManager.getString(
"label.backupfiles_confirm_delete"),
for (int i = 0; i < deleteFiles.size(); i++)
{
File fileToDelete = deleteFiles.get(i);
- Cache.trace("BACKUPFILES about to delete fileToDelete:"
+ Console.trace("BACKUPFILES about to delete fileToDelete:"
+ fileToDelete);
fileToDelete.delete();
- Cache.warn("deleted '" + fileToDelete.getName() + "'");
+ Console.warn("deleted '" + fileToDelete.getName() + "'");
}
}
.append(MessageManager.getString("label.continue_operation"));
int confirmButton = Platform.isHeadless() ? JvOptionPane.OK_OPTION
- : JvOptionPane.showConfirmDialog(Desktop.desktop,
+ : JvOptionPane.showConfirmDialog(Desktop.getDesktopPane(),
messageSB.toString(),
MessageManager.getString(
"label.backupfiles_confirm_save_file"),
dirFile = file.getParentFile();
} catch (Exception e)
{
- Cache.error("Could not get canonical path for file '" + file + "'");
+ Console.error("Could not get canonical path for file '" + file + "'");
return new TreeMap<>();
}
int pos = deleteFiles.indexOf(fileToBeDeleted);
if (pos > -1)
{
- Cache.debug("BACKUPFILES not adding file "
+ Console.debug("BACKUPFILES not adding file "
+ fileToBeDeleted.getAbsolutePath()
+ " to the delete list (already at index" + pos + ")");
return true;
}
else
{
- Cache.debug("BACKUPFILES adding file "
+ Console.debug("BACKUPFILES adding file "
+ fileToBeDeleted.getAbsolutePath() + " to the delete list");
deleteFiles.add(fileToBeDeleted);
}
public static boolean moveFileToFile(File oldFile, File newFile)
{
- Cache.initLogger();
+ Console.initLogger();
boolean ret = false;
Path oldPath = Paths.get(oldFile.getAbsolutePath());
Path newPath = Paths.get(newFile.getAbsolutePath());
try
{
// delete destination file - not usually necessary but Just In Case...
- Cache.trace("BACKUPFILES deleting " + newFile.getAbsolutePath());
+ Console.trace("BACKUPFILES deleting " + newFile.getAbsolutePath());
newFile.delete();
- Cache.trace("BACKUPFILES moving " + oldFile.getAbsolutePath() + " to "
- + newFile.getAbsolutePath());
+ Console.trace("BACKUPFILES moving " + oldFile.getAbsolutePath()
+ + " to " + newFile.getAbsolutePath());
Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
ret = true;
- Cache.trace("BACKUPFILES move seems to have succeeded");
+ Console.trace("BACKUPFILES move seems to have succeeded");
} catch (IOException e)
{
- Cache.warn("Could not move file '" + oldPath.toString() + "' to '"
+ Console.warn("Could not move file '" + oldPath.toString() + "' to '"
+ newPath.toString() + "'");
- Cache.error(e.getMessage());
- Cache.debug(Cache.getStackTraceString(e));
+ Console.error(e.getMessage());
+ Console.debug(Cache.getStackTraceString(e));
ret = false;
} catch (Exception e)
{
- Cache.error(e.getMessage());
- Cache.debug(Cache.getStackTraceString(e));
+ Console.error(e.getMessage());
+ Console.debug(Cache.getStackTraceString(e));
ret = false;
}
return ret;
*/
package jalview.io;
+ import jalview.bin.Cache;
import jalview.gui.AlignmentPanel;
import jalview.gui.OOMWarning;
import jalview.json.binding.biojs.BioJSReleasePojo;
import jalview.json.binding.biojs.BioJSRepositoryPojo;
import jalview.util.MessageManager;
+import jalview.util.Platform;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
private static TreeMap<String, File> bioJsMSAVersions;
- public static final String DEFAULT_DIR = System.getProperty("user.home")
- + File.separatorChar + ".biojs_templates" + File.separatorChar;
+ public static final String DEFAULT_DIR = Platform.getUserPath(".biojs_templates/");
- public static final String BJS_TEMPLATES_LOCAL_DIRECTORY = jalview.bin.Cache
+ public static final String BJS_TEMPLATES_LOCAL_DIRECTORY = Cache
.getDefault("biojs_template_directory", DEFAULT_DIR);
- public static final String BJS_TEMPLATE_GIT_REPO = jalview.bin.Cache
- .getDefault("biojs_template_git_repo",
- "https://raw.githubusercontent.com/jalview/exporter-templates/master/biojs/package.json");
+ public static final String BJS_TEMPLATE_GIT_REPO = Cache.getDefault(
+ "biojs_template_git_repo",
+ "https://raw.githubusercontent.com/jalview/exporter-templates/master/biojs/package.json");
public BioJsHTMLOutput(AlignmentPanel ap)
{
{
return true;
}
+ },
+ HMMER3("HMMER3", "hmm", true, true)
+ {
+ @Override
+ public AlignmentFileReaderI getReader(FileParse source)
+ throws IOException
+ {
+ return new HMMFile(source);
+ }
+
+ @Override
+ public AlignmentFileWriterI getWriter(AlignmentI al)
+ {
+ return new HMMFile();
+ }
+ }, BSML("BSML", "bbb", true, false)
+ {
+ @Override
+ public AlignmentFileReaderI getReader(FileParse source)
+ throws IOException
+ {
+ return new BSMLFile(source);
+ }
+
+ @Override
+ public AlignmentFileWriterI getWriter(AlignmentI al)
+ {
+ return null;
+ }
};
+
private boolean writable;
private boolean readable;
* @param shortName
* @param extensions
* comma-separated list of file extensions associated with the format
- * @param isReadable - can be recognised by IdentifyFile and imported with the given reader
- * @param isWritable - can be exported with the returned writer
+ * @param isReadable
+ * - can be recognised by IdentifyFile and imported with the given
+ * reader
+ * @param isWritable
+ * - can be exported with the returned writer
*/
private FileFormat(String shortName, String extensions,
boolean isReadable, boolean isWritable)
import java.util.Map;
import java.util.Set;
+import jalview.bin.ApplicationSingletonProvider;
+import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
+
/**
* A singleton registry of alignment file formats known to Jalview. On startup,
* the 'built-in' formats are added (from the FileFormat enum). Additional
* @author gmcarstairs
*
*/
-public class FileFormats
+public class FileFormats implements ApplicationSingletonI
{
- private static FileFormats instance = new FileFormats();
-
- /*
- * A lookup map of file formats by upper-cased name
- */
- private static Map<String, FileFormatI> formats;
-
- /*
- * Formats in this set are capable of being identified by IdentifyFile
- */
- private static Set<FileFormatI> identifiable;
-
public static FileFormats getInstance()
{
- return instance;
+ return (FileFormats) ApplicationSingletonProvider.getInstance(FileFormats.class);
}
/**
reset();
}
+ /*
+ * A lookup map of file formats by upper-cased name
+ */
+ private Map<String, FileFormatI> formats;
+
+ /*
+ * Formats in this set are capable of being identified by IdentifyFile
+ */
+ private Set<FileFormatI> identifiable;
+
+
/**
* Reset to just the built-in file formats packaged with Jalview. These are
* added (and will be shown in menus) in the order of their declaration in the
*/
public FileFormatI forName(String format)
{
- return format == null ? null : formats.get(format.toUpperCase(Locale.ROOT));
+ return format == null ? null
+ : formats.get(format.toUpperCase(Locale.ROOT));
}
/**
*/
package jalview.io;
+import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import java.util.StringTokenizer;
import jalview.schemes.ColourSchemeI;
import jalview.structure.StructureSelectionManager;
import jalview.util.MessageManager;
+import jalview.util.Platform;
import jalview.ws.utils.UrlDownloadClient;
+import java.util.ArrayList;
+import java.util.List;
public class FileLoader implements Runnable
{
+ private static final String TAB = "\t";
String file;
DataSourceType protocol;
DataSourceType protocol, FileFormatI format)
{
this.viewport = viewport;
- if (file instanceof File) {
+ if (file instanceof File)
+ {
this.selectedFile = (File) file;
file = selectedFile.getPath();
}
return alignFrame;
}
- public void updateRecentlyOpened()
+ public void LoadFileOntoAlignmentWaitTillLoaded(AlignViewport viewport,
+ String file, DataSourceType sourceType, FileFormatI format)
{
Vector<String> recent = new Vector<>();
if (protocol == DataSourceType.PASTE)
+ this.viewport = viewport;
+ this.file = file;
+ this.protocol = sourceType;
+ this.format = format;
+ _LoadFileWaitTillLoaded();
+ }
+
+
+ /**
+ * Updates (or creates) the tab-separated list of recently opened files held
+ * under the given property name by inserting the filePath at the front of the
+ * list. Duplicates are removed, and the list is limited to 11 entries. The
+ * method returns the updated value of the property.
+ *
+ * @param filePath
+ * @param sourceType
+ */
+ public static String updateRecentlyOpened(String filePath,
+ DataSourceType sourceType)
+ {
+ if (sourceType != DataSourceType.FILE
+ && sourceType != DataSourceType.URL)
{
- // do nothing if the file was pasted in as text... there is no filename to
- // refer to it as.
- return;
+ return null;
}
- if (file != null
- && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
+ String propertyName = sourceType == DataSourceType.FILE ? "RECENT_FILE"
+ : "RECENT_URL";
+ String historyItems = Cache.getProperty(propertyName);
+ if (filePath != null
+ && filePath.indexOf(System.getProperty("java.io.tmpdir")) > -1)
{
// ignore files loaded from the system's temporary directory
- return;
+ return null;
}
- String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
- : "RECENT_URL";
-
- String historyItems = Cache.getProperty(type);
- StringTokenizer st;
+ List<String> recent = new ArrayList<>();
if (historyItems != null)
{
- st = new StringTokenizer(historyItems, "\t");
+ StringTokenizer st = new StringTokenizer(historyItems, TAB);
while (st.hasMoreTokens())
{
- recent.addElement(st.nextToken().trim());
+ String trimmed = st.nextToken().trim();
+ recent.add(trimmed);
}
}
- if (recent.contains(file))
+ /*
+ * if file was already in the list, it moves to the top
+ */
+ if (recent.contains(filePath))
{
- recent.remove(file);
+ recent.remove(filePath);
}
- StringBuffer newHistory = new StringBuffer(file);
+ StringBuilder newHistory = new StringBuilder(filePath);
for (int i = 0; i < recent.size() && i < 10; i++)
{
- newHistory.append("\t");
- newHistory.append(recent.elementAt(i));
+ newHistory.append(TAB);
+ newHistory.append(recent.get(i));
}
- Cache.setProperty(type, newHistory.toString());
+ String newProperty = newHistory.toString();
+ Cache.setProperty(propertyName, newProperty);
- if (protocol == DataSourceType.FILE)
- {
- Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
- }
+ return newProperty;
}
@Override
Runtime rt = Runtime.getRuntime();
try
{
- if (Desktop.instance != null)
+ if (Desktop.getInstance() != null)
{
- Desktop.instance.startLoading(file);
+ Desktop.getInstance().startLoading(file);
}
if (format == null)
{
format = new IdentifyFile().identify(source, false);
// identify stream and rewind rather than close
}
- else if (selectedFile != null) {
+ else if (selectedFile != null)
+ {
format = new IdentifyFile().identify(selectedFile, protocol);
}
else
if (format == null)
{
- Desktop.instance.stopLoading();
+ Desktop.getInstance().stopLoading();
System.err.println("The input file \"" + file
+ "\" has null or unidentifiable data content!");
if (!Jalview.isHeadlessMode())
{
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
MessageManager.getString("label.couldnt_read_data")
+ " in " + file + "\n"
+ AppletFormatAdapter.getSupportedFormats(),
}
// TODO: cache any stream datasources as a temporary file (eg. PDBs
// retrieved via URL)
- if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
+ if (Desktop.getDesktopPane() != null && Desktop.getDesktopPane().isShowMemoryUsage())
{
System.gc();
memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
// We read the data anyway - it might make sense.
}
// BH 2018 switch to File object here instead of filename
- alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(selectedFile == null ? file : selectedFile);
+ alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(
+ selectedFile == null ? file : selectedFile);
}
else
{
file.lastIndexOf("."));
String tempStructureFileStr = createNamedJvTempFile(
urlLeafName, structExt);
-
+
// BH - switching to File object here so as to hold
// ._bytes array directly
File tempFile = new File(tempStructureFileStr);
UrlDownloadClient.download(file, tempFile);
-
- al = fa.readFile(tempFile, DataSourceType.FILE,
- format);
+
+ al = fa.readFile(tempFile, DataSourceType.FILE, format);
source = fa.getAlignFile();
}
else
{
- if (selectedFile == null) {
+ if (selectedFile == null)
+ {
al = fa.readFile(file, protocol, format);
-
- } else {
+
+ }
+ else
+ {
al = fa.readFile(selectedFile, protocol, format);
- }
+ }
source = fa.getAlignFile(); // keep reference for later if
-
- // necessary.
+
+ // necessary.
}
}
} catch (java.io.IOException ex)
// register PDB entries with desktop's structure selection
// manager
StructureSelectionManager
- .getStructureSelectionManager(Desktop.instance)
+ .getStructureSelectionManager(Desktop.getInstance())
.registerPDBEntry(pdbe);
}
}
.getFeatureColourScheme();
if (viewport != null)
{
+ // TODO: test if this needs to be done after addAlignment ? (like in 2.11.2)
+ if (proxyColourScheme != null)
+ {
+ viewport.applyFeaturesStyle(proxyColourScheme);
+ }
// append to existing alignment
viewport.addAlignment(al, title);
- viewport.applyFeaturesStyle(proxyColourScheme);
+ if (source instanceof HMMFile)
+ {
+ AlignmentI alignment = viewport.getAlignment();
+ SequenceI seq = alignment
+ .getSequenceAt(alignment.getHeight() - 1);
+ if (seq.hasHMMProfile())
+ {
+ /*
+ * fudge: move HMM consensus sequence from last to first
+ */
+ alignment.deleteSequence(alignment.getAbsoluteHeight() - 1);
+ alignment.insertSequenceAt(0, seq);
+ }
+ viewport.getAlignPanel().adjustAnnotationHeight();
+ viewport.updateSequenceIdColours();
+ }
}
else
{
// add metadata and update ui
if (!(protocol == DataSourceType.PASTE))
{
- alignFrame.setFileName(file, format);
- alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
+ alignFrame.setFile(file, selectedFile, protocol, format);
}
if (proxyColourScheme != null)
{
// status in Jalview 3
// TODO: define 'virtual desktop' for benefit of headless scripts
// that perform queries to find the 'current working alignment'
- Desktop.addInternalFrame(alignFrame, title,
+
+ Dimension dim = Platform.getDimIfEmbedded(alignFrame,
AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
+ alignFrame.setSize(dim);
+ Desktop.addInternalFrame(alignFrame, title, dim.width,
+ dim.height);
}
try
{
- alignFrame.setMaximum(jalview.bin.Cache
- .getDefault("SHOW_FULLSCREEN", false));
+ alignFrame.setMaximum(
+ Cache.getDefault("SHOW_FULLSCREEN", false));
} catch (java.beans.PropertyVetoException ex)
{
}
}
else
{
- if (Desktop.instance != null)
+ if (Desktop.getInstance() != null)
{
- Desktop.instance.stopLoading();
+ Desktop.getInstance().stopLoading();
}
final String errorMessage = MessageManager.getString(
"label.couldnt_load_file") + " " + title + "\n" + error;
// TODO: refactor FileLoader to be independent of Desktop / Applet GUI
// bits ?
- if (raiseGUI && Desktop.desktop != null)
+ if (raiseGUI && Desktop.getDesktopPane() != null)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
errorMessage,
MessageManager
.getString("label.error_loading_file"),
}
}
- updateRecentlyOpened();
+ updateRecentlyOpened(file, protocol);
+
+ if (protocol == DataSourceType.FILE && format != null)
+ {
+ Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
+ }
} catch (Exception er)
{
@Override
public void run()
{
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
MessageManager.formatMessage(
"label.problems_opening_file", new String[]
{ file }),
@Override
public void run()
{
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
MessageManager.formatMessage(
"warn.out_of_memory_loading_file", new String[]
{ file }),
// memory
// after
// load
- if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
+ if (Desktop.getDesktopPane() != null && Desktop.getDesktopPane().isShowMemoryUsage())
{
if (alignFrame != null)
{
}
}
// remove the visual delay indicator
- if (Desktop.instance != null)
+ if (Desktop.getInstance() != null)
{
- Desktop.instance.stopLoading();
+ Desktop.getInstance().stopLoading();
}
}
package jalview.io;
import java.util.Locale;
-
import java.io.File;
import java.io.IOException;
*/
public class IdentifyFile
{
-
- public FileFormatI identify(Object file, DataSourceType protocol) throws FileFormatException
+
+ public FileFormatI identify(Object file, DataSourceType protocol)
+ throws FileFormatException
{
// BH 2018
- return (file instanceof File ? identify((File) file, protocol) : identify((String) file, protocol));
-
+ return (file instanceof File ? identify((File) file, protocol)
+ : identify((String) file, protocol));
+
}
public FileFormatI identify(File file, DataSourceType sourceType)
if (source.inFile != null)
{
String fileStr = source.inFile.getName();
- if (fileStr.contains(".jar")
- || fileStr.contains(".zip") || fileStr.contains(".jvp"))
+ if (fileStr.contains(".jar") || fileStr.contains(".zip")
+ || fileStr.contains(".jvp"))
{
// possibly a Jalview archive (but check further)
reply = FileFormat.Jalview;
reply = FileFormat.ScoreMatrix;
break;
}
+ if (data.startsWith("HMMER3"))
+ {
+ reply = FileFormat.HMMER3;
+ break;
+ }
if (data.startsWith("LOCUS"))
{
reply = FileFormat.GenBank;
reply = FileFormat.Rnaml;
break;
}
+ if (upper.substring(lessThan).startsWith("<BSML"))
+ {
+ reply = FileFormat.BSML;
+ break;
+ }
}
if ((data.length() < 1) || (data.indexOf("#") == 0))
}
}
-
}
*/
package jalview.io;
-import jalview.bin.Cache;
import jalview.datamodel.DBRefEntry;
import jalview.datamodel.SequenceI;
+import jalview.util.Platform;
++import jalview.bin.Console;
import java.util.List;
}
};
+ private static Regex VALIDATION_REGEX;
+
+ private static Regex getRegex()
+ {
+ return (VALIDATION_REGEX == null
+ ? VALIDATION_REGEX = Platform
+ .newRegex("\\s*((([-0-9]+).?)|FIRST|LAST|@)", null)
+ : VALIDATION_REGEX);
+ }
private resCode validResidueCode(String field)
{
Integer val = null;
- Regex r = new Regex("\\s*((([-0-9]+).?)|FIRST|LAST|@)");
+ Regex r = getRegex();
+
if (!r.search(field))
{
return null; // invalid
{
value = r.stringMatched(1);
}
- // jalview.bin.Cache.log.debug("from '" + field + "' matched '" + value +
- // Cache.debug("from '" + field + "' matched '" + value +
++ // jalview.bin.Console.debug("from '" + field + "' matched '" + value +
// "'");
try
{
}
else
{
- // jalview.bin.Cache.log.debug(
- // Cache.debug(
++ // jalview.bin.Console.debug(
// "Ignoring non-Modeller description: invalid integer-like
// field '" + field + "'");
type = -1; /* invalid field! - throw the FieldSet away */
List<DBRefEntry> dbr = seq.getDatasetSequence().getDBRefs();
for (int i = 0, ni = dbr.size(); i < ni; i++)
{
- DBRefEntry dbri = dbr.get(i);
+ DBRefEntry dbri = dbr.get(i);
if (dbri != null)
{
// JBPNote PDB dbRefEntry needs properties to propagate onto
// ModellerField
// JBPNote Need to get info from the user about whether the sequence
// is the one being modelled, or if it is a template.
- if (dbri.getSource().equals(jalview.datamodel.DBRefSource.PDB))
+ if (dbri.getSource()
+ .equals(jalview.datamodel.DBRefSource.PDB))
{
fields.put(Fields[LOCALID], dbri.getAccessionId());
t = 2;
import jalview.datamodel.SequenceNode;
import jalview.util.MessageManager;
+import jalview.util.Platform;
import java.io.BufferedReader;
import java.io.File;
import com.stevesoft.pat.Regex;
+// TODO This class does not conform to Java standards for field name capitalization.
-
/**
* Parse a new hanpshire style tree Caveats: NHX files are NOT supported and the
* tree distances and topology are unreliable when they are parsed. TODO: on
*/
public class NewickFile extends FileParse
{
- SequenceNode root;
+ private SequenceNode root;
private boolean HasBootstrap = false;
private boolean RootHasDistance = false;
// File IO Flags
- boolean ReplaceUnderscores = false;
+ private boolean ReplaceUnderscores = false;
- boolean printRootInfo = true;
+ private boolean printRootInfo = true;
- private Regex[] NodeSafeName = new Regex[] {
- new Regex().perlCode("m/[\\[,:'()]/"), // test for
- // requiring
- // quotes
- new Regex().perlCode("s/'/''/"), // escaping quote
- // characters
- new Regex().perlCode("s/\\/w/_/") // unqoted whitespace
- // transformation
- };
+ private static final int REGEX_PERL_NODE_REQUIRE_QUOTE = 0;
- char QuoteChar = '\'';
+ private static final int REGEX_PERL_NODE_ESCAPE_QUOTE = 1;
+
+ private static final int REGEX_PERL_NODE_UNQUOTED_WHITESPACE = 2;
+
+ private static final int REGEX_MAJOR_SYMS = 3;
+
+ private static final int REGEX_QNODE_NAME = 4;
+
+ private static final int REGEX_COMMENT = 5;
+
+ private static final int REGEX_UQNODE_NAME = 6;
+
+ private static final int REGEX_NBOOTSTRAP = 7;
+
+ private static final int REGEX_NDIST = 8;
+
+ private static final int REGEX_NO_LINES = 9;
+
+ private static final int REGEX_PERL_EXPAND_QUOTES = 10;
+
+ private static final int REGEX_MAX = 11;
+
+ private static final Regex[] REGEX = new Regex[REGEX_MAX];
+
+ private static Regex getRegex(int id)
+ {
+ if (REGEX[id] == null)
+ {
+ String code = null;
+ String code2 = null;
+ String codePerl = null;
+ switch (id)
+ {
+ case REGEX_PERL_NODE_REQUIRE_QUOTE:
+ codePerl = "m/[\\[,:'()]/";
+ break;
+ case REGEX_PERL_NODE_ESCAPE_QUOTE:
+ codePerl = "s/'/''/";
+ break;
+ case REGEX_PERL_NODE_UNQUOTED_WHITESPACE:
+ codePerl = "s/\\/w/_/";
+ break;
+ case REGEX_PERL_EXPAND_QUOTES:
+ codePerl = "s/''/'/";
+ break;
+ case REGEX_MAJOR_SYMS:
+ code = "[(\\['),;]";
+ break;
+ case REGEX_QNODE_NAME:
+ code = "'([^']|'')+'";
+ break;
+ case REGEX_COMMENT:
+ code = "]";
+ break;
+ case REGEX_UQNODE_NAME:
+ code = "\\b([^' :;\\](),]+)";
+ break;
+ case REGEX_NBOOTSTRAP:
+ code = "\\s*([0-9+]+)\\s*:";
+ break;
+ case REGEX_NDIST:
+ code = ":([-0-9Ee.+]+)";
+ break;
+ case REGEX_NO_LINES:
+ code = "\n+";
+ code2 = "";
+ break;
+ default:
+ return null;
+ }
+ return codePerl == null ? Platform.newRegex(code, code2)
+ : Platform.newRegexPerl(codePerl);
+ }
+ return REGEX[id];
+ }
+
+
+ private char quoteChar = '\'';
/**
* Creates a new NewickFile object.
*/
public void parse() throws IOException
{
+ Platform.ensureRegex();
String nf;
{ // fill nf with complete tree file
String nodename = null;
String commentString2 = null; // comments after simple node props
- float DefDistance = (float) 0.001; // @param Default distance for a node -
+ double DefDistance = (float) 0.001; // @param Default distance for a node -
// very very small
int DefBootstrap = -1; // @param Default bootstrap for a node
- float distance = DefDistance;
+ double distance = DefDistance;
int bootstrap = DefBootstrap;
boolean ascending = false; // flag indicating that we are leaving the
// current node
- Regex majorsyms = new Regex("[(\\['),;]");
+ Regex majorsyms = getRegex(REGEX_MAJOR_SYMS); // "[(\\['),;]"
int nextcp = 0;
int ncp = cp;
// Deal with quoted fields
case '\'':
- Regex qnodename = new Regex("'([^']|'')+'");
+ Regex qnodename = getRegex(REGEX_QNODE_NAME);// "'([^']|'')+'");
if (qnodename.searchFrom(nf, fcp))
{
nodename = new String(
qnodename.stringMatched().substring(1, nl - 1));
// unpack any escaped colons
- Regex xpandquotes = Regex.perlCode("s/''/'/");
+ Regex xpandquotes = getRegex(REGEX_PERL_EXPAND_QUOTES);
String widernodename = xpandquotes.replaceAll(nodename);
nodename = widernodename;
// jump to after end of quoted nodename
* '"+nf.substring(cp,fcp)+"'"); }
*/
// verify termination.
- Regex comment = new Regex("]");
+ Regex comment = getRegex(REGEX_COMMENT); // "]"
if (comment.searchFrom(nf, fcp))
{
// Skip the comment field
+ fstring.substring(cend + 1);
}
- Regex uqnodename = new Regex("\\b([^' :;\\](),]+)");
- Regex nbootstrap = new Regex("\\s*([0-9+]+)\\s*:");
- Regex ndist = new Regex(":([-0-9Ee.+]+)");
+ Regex uqnodename = getRegex(REGEX_UQNODE_NAME);// "\\b([^' :;\\](),]+)"
+ Regex nbootstrap = getRegex(REGEX_NBOOTSTRAP);// "\\s*([0-9+]+)\\s*:");
+ Regex ndist = getRegex(REGEX_NDIST);// ":([-0-9Ee.+]+)");
if (!parsednodename && uqnodename.search(fstring)
&& ((uqnodename.matchedFrom(1) == 0) || (fstring
{
try
{
- distance = (Float.valueOf(ndist.stringMatched(1))).floatValue();
+ distance = (Double.valueOf(ndist.stringMatched(1))).floatValue();
HasDistances = true;
nodehasdistance = true;
} catch (Exception e)
*/
char getQuoteChar()
{
- return QuoteChar;
+ return quoteChar;
}
/**
*/
char setQuoteChar(char c)
{
- char old = QuoteChar;
- QuoteChar = c;
+ char old = quoteChar;
+ quoteChar = c;
return old;
}
*/
private String nodeName(String name)
{
- if (NodeSafeName[0].search(name))
+ if (getRegex(REGEX_PERL_NODE_REQUIRE_QUOTE).search(name))
{
- return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
+ return quoteChar
+ + getRegex(REGEX_PERL_NODE_ESCAPE_QUOTE).replaceAll(name)
+ + quoteChar;
}
else
{
- return NodeSafeName[2].replaceAll(name);
+ return getRegex(REGEX_PERL_NODE_UNQUOTED_WHITESPACE).replaceAll(name);
}
}
trf.parse();
System.out.println("Original file :\n");
- Regex nonl = new Regex("\n+", "");
+ Regex nonl = getRegex(REGEX_NO_LINES);// "\n+", "");
System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
System.out.println("Parsed file.\n");
*/
package jalview.io;
- import java.util.Locale;
+ import java.util.ArrayList;
+
import java.util.Collection;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
+ import java.util.Locale;
import java.util.Map;
import jalview.api.FeatureColourI;
+import jalview.datamodel.AlignmentAnnotation;
import jalview.datamodel.DBRefEntry;
import jalview.datamodel.DBRefSource;
import jalview.datamodel.GeneLociI;
private static String linkImageURL;
- // public static final String[][] PRIMARY_SOURCES moved to DBRefSource.java
+ // public static final String[][] PRIMARY_SOURCES moved to DBRefSource.java
/*
* Comparator to order DBRefEntry by Source + accession id (case-insensitive),
{
return 1;
}
- int comp = s1 == null ? -1
- : (s2 == null ? 1 : s1.compareToIgnoreCase(s2));
+ int comp = s1 == null ? -1 : (s2 == null ? 1 : s1
+ .compareToIgnoreCase(s2));
if (comp == 0)
{
String a1 = ref1.getAccessionId();
String a2 = ref2.getAccessionId();
- comp = a1 == null ? -1
- : (a2 == null ? 1 : a1.compareToIgnoreCase(a2));
+ comp = a1 == null ? -1 : (a2 == null ? 1 : a1
+ .compareToIgnoreCase(a2));
}
return comp;
}
- // private boolean isPrimarySource(String source)
- // {
- // for (String[] primary : DBRefSource.PRIMARY_SOURCES)
- // {
- // for (String s : primary)
- // {
- // if (source.equals(s))
- // {
- // return true;
- // }
- // }
- // }
- // return false;
- // }
+// private boolean isPrimarySource(String source)
+// {
+// for (String[] primary : DBRefSource.PRIMARY_SOURCES)
+// {
+// for (String s : primary)
+// {
+// if (source.equals(s))
+// {
+// return true;
+// }
+// }
+// }
+// return false;
+// }
};
private boolean forTooltip;
* @param minmax
* @param maxlength
*/
- public int appendFeatures(final StringBuilder sb, int residuePos,
- List<SequenceFeature> features, FeatureRendererModel fr,
- int maxlength)
+ public int appendFeatures(final StringBuilder sb,
+ int residuePos, List<SequenceFeature> features,
+ FeatureRendererModel fr, int maxlength)
{
for (int i = 0; i < features.size(); i++)
{
* if this is a virtual features, convert begin/end to the
* coordinates of the sequence it is mapped to
*/
- int[] beginRange = null;
- int[] endRange = null;
+ int[] beginRange = null; // feature start in local coordinates
+ int[] endRange = null; // feature end in local coordinates
if (mf != null)
{
- beginRange = mf.getMappedPositions(begin, begin);
- endRange = mf.getMappedPositions(end, end);
+ if (feature.isContactFeature())
+ {
+ /*
+ * map start and end points individually
+ */
+ beginRange = mf.getMappedPositions(begin, begin);
+ endRange = begin == end ? beginRange
+ : mf.getMappedPositions(end, end);
+ }
+ else
+ {
+ /*
+ * map the feature extent
+ */
+ beginRange = mf.getMappedPositions(begin, end);
+ endRange = beginRange;
+ }
if (beginRange == null || endRange == null)
{
// something went wrong
{
if (sb0.length() > 6)
{
- sb.append("<br>");
+ sb.append("<br/>");
}
sb.append(feature.getType()).append(" ").append(begin).append(":")
.append(end);
if (sb0.length() > 6)
{
- sb.append("<br>");
+ sb.append("<br/>");
}
// TODO: remove this hack to display link only features
boolean linkOnly = feature.getValue("linkonly") != null;
int linkindex = description.toLowerCase(Locale.ROOT).indexOf("<a ");
boolean hasLink = linkindex > -1
&& linkindex < MAX_DESCRIPTION_LENGTH;
- if (description.length() > MAX_DESCRIPTION_LENGTH && !hasLink)
+ if (
+ // BH suggestion maxlength == 0 &&
+ description.length() > MAX_DESCRIPTION_LENGTH && !hasLink)
{
description = description.substring(0, MAX_DESCRIPTION_LENGTH)
+ ELLIPSIS;
{
for (List<String> urllink : createLinksFrom(null, urlstring))
{
- sb.append("<br/> <a href=\"" + urllink.get(3) + "\" target=\""
- + urllink.get(0) + "\">"
- + (urllink.get(0).toLowerCase(Locale.ROOT).equals(
- urllink.get(1).toLowerCase(Locale.ROOT))
- ? urllink.get(0)
- : (urllink.get(0) + ":"
- + urllink.get(1)))
- + "</a><br/>");
+ sb.append("<br> <a href=\""
+ + urllink.get(3)
+ + "\" target=\""
+ + urllink.get(0)
+ + "\">"
+ + (urllink.get(0).toLowerCase(Locale.ROOT)
+ .equals(urllink.get(1).toLowerCase(Locale.ROOT)) ? urllink
+ .get(0) : (urllink.get(0) + ":" + urllink
+ .get(1)))
+ + "</a><br>");
}
} catch (Exception x)
{
- System.err.println(
- "problem when creating links from " + urlstring);
+ System.err.println("problem when creating links from "
+ + urlstring);
x.printStackTrace();
}
}
sb.append(tmp);
maxWidth = Math.max(maxWidth, tmp.length());
}
-
+ sb.append("\n");
SequenceI ds = sequence;
while (ds.getDatasetSequence() != null)
{
ds = ds.getDatasetSequence();
}
+
+ /*
+ * add any annotation scores
+ */
+ AlignmentAnnotation[] anns = ds.getAnnotation();
+ if (anns!=null && anns.length>0) {
+ boolean first=true;
+ for (int i = 0; anns != null && i < anns.length; i++)
+ {
+ AlignmentAnnotation aa = anns[i];
+ if (aa != null && aa.hasScore() && aa.sequenceRef != null)
+ {
+ if (first) {
+ sb.append("<br>").append("Annotation Scores<br>");
+ first=false;
+ }
+ sb.append("<br>").append(aa.label).append(": ")
+ .append(aa.getScore());
+ }
+ }
+ }
if (showDbRefs)
{
maxWidth = Math.max(maxWidth, appendDbRefs(sb, ds, summary));
}
+ sb.append("\n");
/*
* add non-positional features if wanted
maxWidth = Math.max(maxWidth, sz);
}
}
-
-
+ if (sequence.getAnnotation("Search Scores") != null)
+ {
+ sb.append("<br>");
+ String eValue = " E-Value: "
+ + sequence.getAnnotation("Search Scores")[0].getEValue();
+ String bitScore = " Bit Score: "
+ + sequence.getAnnotation("Search Scores")[0].getBitScore();
+ sb.append(eValue);
+ sb.append("<br>");
+ sb.append(bitScore);
+ maxWidth = Math.max(maxWidth, eValue.length());
+ maxWidth = Math.max(maxWidth, bitScore.length());
+ sb.append("<br>");
+ }
sb.append("</i>");
-
return maxWidth;
}
protected int appendDbRefs(final StringBuilder sb, SequenceI ds,
boolean summary)
{
- List<DBRefEntry> dbrefs = ds.getDBRefs();
- if (dbrefs == null)
+ List<DBRefEntry> dbrefs, dbrefset = ds.getDBRefs();
+
+ if (dbrefset == null)
{
return 0;
}
+ // PATCH for JAL-3980 defensive copy
+
+ dbrefs = new ArrayList<DBRefEntry>();
+
+ dbrefs.addAll(dbrefset);
-
// note this sorts the refs held on the sequence!
dbrefs.sort(comparator);
boolean ellipsis = false;
countForSource++;
if (countForSource == 1 || !summary)
{
- sb.append("<br>");
+ sb.append("<br/>\n");
}
if (countForSource <= MAX_REFS_PER_SOURCE || !summary)
{
lineLength += accessionId.length() + 1;
if (countForSource > 1 && summary)
{
- sb.append(", ").append(accessionId);
+ sb.append(",\n ").append(accessionId);
lineLength++;
}
else
}
if (moreSources)
{
- sb.append("<br>").append(source).append(COMMA).append(ELLIPSIS);
+ sb.append("<br/>\n").append(source).append(COMMA).append(ELLIPSIS);
}
if (ellipsis)
{
- sb.append("<br>(");
+ sb.append("<br/>\n(");
sb.append(MessageManager.getString("label.output_seq_details"));
sb.append(")");
}
SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
FeatureRendererModel fr)
{
- int maxWidth = createSequenceAnnotationReport(tip, sequence, showDbRefs,
- showNpFeats, fr, true);
+ int maxWidth = createSequenceAnnotationReport(tip, sequence,
+ showDbRefs, showNpFeats, fr, true);
if (maxWidth > 60)
{
*/
package jalview.io;
+import jalview.analysis.Rna;
+import jalview.datamodel.AlignmentAnnotation;
+import jalview.datamodel.AlignmentI;
+import jalview.datamodel.Annotation;
+import jalview.datamodel.DBRefEntry;
+import jalview.datamodel.DBRefSource;
+import jalview.datamodel.Mapping;
+import jalview.datamodel.Sequence;
+import jalview.datamodel.SequenceFeature;
+import jalview.datamodel.SequenceI;
+import jalview.schemes.ResidueProperties;
+import jalview.util.Comparison;
+import jalview.util.DBRefUtils;
+import jalview.util.Format;
+import jalview.util.MessageManager;
+import jalview.util.Platform;
+
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
import fr.orsay.lri.varna.factories.RNAFactory;
import fr.orsay.lri.varna.models.rna.RNA;
-import jalview.analysis.Rna;
-import jalview.datamodel.AlignmentAnnotation;
-import jalview.datamodel.AlignmentI;
-import jalview.datamodel.Annotation;
-import jalview.datamodel.DBRefEntry;
-import jalview.datamodel.DBRefSource;
-import jalview.datamodel.Mapping;
-import jalview.datamodel.Sequence;
-import jalview.datamodel.SequenceFeature;
-import jalview.datamodel.SequenceI;
-import jalview.schemes.ResidueProperties;
-import jalview.util.Comparison;
-import jalview.util.DBRefUtils;
-import jalview.util.Format;
-import jalview.util.MessageManager;
- // import org.apache.log4j.*;
-
/**
* This class is supposed to parse a Stockholm format file into Jalview There
* are TODOs in this class: we do not know what the database source and version
{
private static final String ANNOTATION = "annotation";
- // private static final Regex OPEN_PAREN = new Regex("(<|\\[)", "(");
- //
- // private static final Regex CLOSE_PAREN = new Regex("(>|\\])", ")");
-
- public static final Regex DETECT_BRACKETS = new Regex(
- "(<|>|\\[|\\]|\\(|\\)|\\{|\\})");
+ private static final char UNDERSCORE = '_';
+
+ // WUSS extended symbols. Avoid ambiguity with protein SS annotations by using NOT_RNASS first.
- // WUSS extended symbols. Avoid ambiguity with protein SS annotations by using
- // NOT_RNASS first.
public static final String RNASS_BRACKETS = "<>[](){}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
+ public static final int REGEX_STOCKHOLM = 0;
+
+ public static final int REGEX_BRACKETS = 1;
// use the following regex to decide an annotations (whole) line is NOT an RNA
// SS (it contains only E,H,e,h and other non-brace/non-alpha chars)
- private static final Regex NOT_RNASS = new Regex(
- "^[^<>[\\](){}ADFJ-RUVWYZadfj-ruvwyz]*$");
+ public static final int REGEX_NOT_RNASS = 2;
+
+ private static final int REGEX_ANNOTATION = 3;
+
+ private static final int REGEX_PFAM = 4;
+
+ private static final int REGEX_RFAM = 5;
+
+ private static final int REGEX_ALIGN_END = 6;
+
+ private static final int REGEX_SPLIT_ID = 7;
+
+ private static final int REGEX_SUBTYPE = 8;
+
+ private static final int REGEX_ANNOTATION_LINE = 9;
+
+ private static final int REGEX_REMOVE_ID = 10;
+
+ private static final int REGEX_OPEN_PAREN = 11;
+
+ private static final int REGEX_CLOSE_PAREN = 12;
+
+ public static final int REGEX_MAX = 13;
+
+ private static Regex REGEX[] = new Regex[REGEX_MAX];
+
+ /**
+ * Centralize all actual Regex instantialization in Platform.
+ * // JBPNote: Why is this 'centralisation' better ?
+ * @param id
+ * @return
+ */
+ private static Regex getRegex(int id)
+ {
+ if (REGEX[id] == null)
+ {
+ String pat = null, pat2 = null;
+ switch (id)
+ {
+ case REGEX_STOCKHOLM:
+ pat = "# STOCKHOLM ([\\d\\.]+)";
+ break;
+ case REGEX_BRACKETS:
+ // for reference; not used
+ pat = "(<|>|\\[|\\]|\\(|\\)|\\{|\\})";
+ break;
+ case REGEX_NOT_RNASS:
- pat = "^[^<>[\\](){}A-DF-Za-df-z]*$";
++ pat = "^[^<>[\\](){}ADFJ-RUVWYZadfj-ruvwyz]*$"; // update 2.11.2
+ break;
+ case REGEX_ANNOTATION:
+ pat = "(\\w+)\\s*(.*)";
+ break;
+ case REGEX_PFAM:
+ pat = "PF[0-9]{5}(.*)";
+ break;
+ case REGEX_RFAM:
+ pat = "RF[0-9]{5}(.*)";
+ break;
+ case REGEX_ALIGN_END:
+ pat = "^\\s*\\/\\/";
+ break;
+ case REGEX_SPLIT_ID:
+ pat = "(\\S+)\\/(\\d+)\\-(\\d+)";
+ break;
+ case REGEX_SUBTYPE:
+ pat = "(\\S+)\\s+(\\S*)\\s+(.*)";
+ break;
+ case REGEX_ANNOTATION_LINE:
+ pat = "#=(G[FSRC]?)\\s+(.*)";
+ break;
+ case REGEX_REMOVE_ID:
+ pat = "(\\S+)\\s+(\\S+)";
+ break;
+ case REGEX_OPEN_PAREN:
+ pat = "(<|\\[)";
+ pat2 = "(";
+ break;
+ case REGEX_CLOSE_PAREN:
+ pat = "(>|\\])";
+ pat2 = ")";
+ break;
+ default:
+ return null;
+ }
+ REGEX[id] = Platform.newRegex(pat, pat2);
+ }
+ return REGEX[id];
+ }
StringBuffer out; // output buffer
- AlignmentI al;
+ private AlignmentI al;
public StockholmFile()
{
}
/**
- * Creates a new StockholmFile object for output.
+ * Creates a new StockholmFile object for output
*/
public StockholmFile(AlignmentI al)
{
// First, we have to check that this file has STOCKHOLM format, i.e. the
// first line must match
- r = new Regex("# STOCKHOLM ([\\d\\.]+)");
+ r = getRegex(REGEX_STOCKHOLM);
if (!r.search(nextLine()))
{
throw new IOException(MessageManager
- .getString("exception.stockholm_invalid_format") +" ("+r+")");
+ .getString("exception.stockholm_invalid_format"));
}
else
{
}
// We define some Regexes here that will be used regularily later
- rend = new Regex("^\\s*\\/\\/"); // Find the end of an alignment
- p = new Regex("(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
+ rend = getRegex(REGEX_ALIGN_END);//"^\\s*\\/\\/"); // Find the end of an alignment
+ p = getRegex(REGEX_SPLIT_ID);//"(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
// id/from/to
- s = new Regex("(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses annotation subtype
- r = new Regex("#=(G[FSRC]?)\\s+(.*)"); // Finds any annotation line
- x = new Regex("(\\S+)\\s+(\\S+)"); // split id from sequence
+ s = getRegex(REGEX_SUBTYPE);// "(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses
+ // annotation subtype
+ r = getRegex(REGEX_ANNOTATION_LINE);// "#=(G[FSRC]?)\\s+(.*)"); // Finds any
+ // annotation line
+ x = getRegex(REGEX_REMOVE_ID);// "(\\S+)\\s+(\\S+)"); // split id from
+ // sequence
// Convert all bracket types to parentheses (necessary for passing to VARNA)
- Regex openparen = new Regex("(<|\\[)", "(");
- Regex closeparen = new Regex("(>|\\])", ")");
+ Regex openparen = getRegex(REGEX_OPEN_PAREN);//"(<|\\[)", "(");
+ Regex closeparen = getRegex(REGEX_CLOSE_PAREN);//"(>|\\])", ")");
- // // Detect if file is RNA by looking for bracket types
- // Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
+// // Detect if file is RNA by looking for bracket types
- // Regex detectbrackets = getRegex("(<|>|\\[|\\]|\\(|\\))");
++// Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
rend.optimize();
p.optimize();
this.noSeqs = seqs.size();
String dbsource = null;
- Regex pf = new Regex("PF[0-9]{5}(.*)"); // Finds AC for Pfam
- Regex rf = new Regex("RF[0-9]{5}(.*)"); // Finds AC for Rfam
+ Regex pf = getRegex(REGEX_PFAM); // Finds AC for Pfam
+ Regex rf = getRegex(REGEX_RFAM); // Finds AC for Rfam
if (getAlignmentProperty("AC") != null)
{
String dbType = getAlignmentProperty("AC").toString();
if (accAnnotations != null && accAnnotations.containsKey("AC"))
{
- String dbr = (String) accAnnotations.get("AC");
- if (dbr != null)
- {
- // we could get very clever here - but for now - just try to
- // guess accession type from type of sequence, source of alignment
- // plus
+ String dbr = (String) accAnnotations.get("AC");
+ if (dbr != null)
+ {
+ // we could get very clever here - but for now - just try to
+ // guess accession type from type of sequence, source of alignment plus
// structure
- // of accession
- guessDatabaseFor(seqO, dbr, dbsource);
+ // of accession
+ guessDatabaseFor(seqO, dbr, dbsource);
}
// else - do what ? add the data anyway and prompt the user to
// specify what references these are ?
*/
// Let's save the annotations, maybe we'll be able to do something
// with them later...
- Regex an = new Regex("(\\w+)\\s*(.*)");
+ Regex an = getRegex(REGEX_ANNOTATION);
if (an.search(annContent))
{
if (an.stringMatched(1).equals("NH"))
treeName = an.stringMatched(2);
treeString = new StringBuffer();
}
- // TODO: JAL-3532 - this is where GF comments and database
- // references are lost
- // suggest overriding this method for Stockholm files to catch and
- // properly
+ // TODO: JAL-3532 - this is where GF comments and database references are lost
+ // suggest overriding this method for Stockholm files to catch and properly
// process CC, DR etc into multivalued properties
setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
}
if (features.containsKey(this.id2type(type)))
{
// logger.debug("Found content for " + this.id2type(type));
- content = (Hashtable) features.get(this.id2type(type));
+ content = (Hashtable) features
+ .get(this.id2type(type));
}
else
{
// logger.debug("Creating new content holder for " +
// this.id2type(type));
content = new Hashtable();
- features.put(this.id2type(type), content);
+ features.put(id2type(type), content);
}
String ns = (String) content.get(ANNOTATION);
}
if (dbsource == null)
{
- // make up an origin based on whether the sequence looks like it is
- // nucleotide
+ // make up an origin based on whether the sequence looks like it is nucleotide
// or protein
dbsource = (seqO.isProtein()) ? "PFAM" : "RFAM";
}
Vector<AlignmentAnnotation> annotation, String label,
String annots)
{
- String convert1, convert2 = null;
-
- // convert1 = OPEN_PAREN.replaceAll(annots);
- // convert2 = CLOSE_PAREN.replaceAll(convert1);
+ String convert1, convert2 = null;
+ // String convert1 = OPEN_PAREN.replaceAll(annots);
+ // String convert2 = CLOSE_PAREN.replaceAll(convert1);
// annots = convert2;
String type = label;
if (type.equalsIgnoreCase("secondary structure"))
{
ss = true;
- isrnass = !NOT_RNASS.search(annots); // sorry about the double negative
+ isrnass = !getRegex(REGEX_NOT_RNASS).search(annots); // sorry about the double
+ // negative
// here (it's easier for dealing with
// other non-alpha-non-brace chars)
}
for (int i = 0; i < annots.length(); i++)
{
String pos = annots.substring(i, i + 1);
+ // TODO 2.12 release: verify this Stockholm IO behaviour change in release notes
+ if (UNDERSCORE == pos.charAt(0))
+ {
+ pos = " ";
+ }
Annotation ann;
ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
// be written out
return ref.getSource().toString() + " ; "
+ ref.getAccessionId().toString();
}
-
@Override
public String print(SequenceI[] s, boolean jvSuffix)
{
}
else
{
- for (int idb = 0; idb < seq.getDBRefs().size(); idb++)
+ for (int idb = 0; idb < ndb; idb++)
{
- DBRefEntry dbref = seq.getDBRefs().get(idb);
+ DBRefEntry dbref = seqrefs.get(idb);
dataRef.put(tmp, dbref_to_ac_record(dbref));
// if we put in a uniprot or EMBL record then we're done:
- if (isAA && DBRefSource.UNIPROT
- .equals(DBRefUtils.getCanonicalName(dbref.getSource())))
- {
- break;
- }
- if (!isAA && DBRefSource.EMBL
+ if ((isAA ? DBRefSource.UNIPROT : DBRefSource.EMBL)
.equals(DBRefUtils.getCanonicalName(dbref.getSource())))
{
break;
if (alAnot != null)
{
Annotation[] ann;
- for (int j = 0, nj = alAnot.length; j < nj; j++)
+ for (int j = 0; j < alAnot.length; j++)
{
- String key = type2id(alAnot[j].label);
- boolean isrna = alAnot[j].isValidStruc();
-
- if (isrna)
- {
- // hardwire to secondary structure if there is RNA secondary
- // structure on the annotation
- key = "SS";
- }
- if (key == null)
+ if (alAnot[j].annotations != null)
{
+ String key = type2id(alAnot[j].label);
+ boolean isrna = alAnot[j].isValidStruc();
- continue;
- }
+ if (isrna)
+ {
+ // hardwire to secondary structure if there is RNA secondary
+ // structure on the annotation
+ key = "SS";
+ }
+ if (key == null)
+ {
+ continue;
+ }
- // out.append("#=GR ");
- out.append(new Format("%-" + maxid + "s").form(
- "#=GR " + printId(seq, jvSuffix) + " " + key + " "));
- ann = alAnot[j].annotations;
- String sseq = "";
- for (int k = 0, nk = ann.length; k < nk; k++)
- {
- sseq += outputCharacter(key, k, isrna, ann, seq);
- }
- out.append(sseq);
- out.append(newline);
+ // out.append("#=GR ");
+ out.append(new Format("%-" + maxid + "s").form(
+ "#=GR " + printId(s[i], jvSuffix) + " " + key + " "));
+ ann = alAnot[j].annotations;
+ String sseq = "";
+ for (int k = 0; k < ann.length; k++)
+ {
+ sseq += outputCharacter(key, k, isrna, ann, s[i]);
+ }
+ out.append(sseq);
+ out.append(newline);
+ }
}
}
}
else
{
- key = type2id(aa.label.toLowerCase());
+ key = type2id(aa.label.toLowerCase(Locale.ROOT));
if (key == null)
{
label = aa.label;
: seq;
}
+ /**
+ * make a friendly ID string.
+ *
+ * @param dataName
+ * @return truncated dataName to after last '/'
+ */
+ private String safeName(String dataName)
+ {
+ int b = 0;
+ while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
+ {
+ dataName = dataName.substring(b + 1).trim();
+
+ }
+ int e = (dataName.length() - dataName.indexOf(".")) + 1;
+ dataName = dataName.substring(1, e).trim();
+ return dataName;
+ }
+
+
public String print()
{
out = new StringBuffer();
}
}
+
protected static String id2type(String id)
{
if (typeIds.containsKey(id))
"Warning : Unknown Stockholm annotation type: " + type);
return key;
}
-
- /**
- * make a friendly ID string.
- *
- * @param dataName
- * @return truncated dataName to after last '/'
- */
- private String safeName(String dataName)
- {
- int b = 0;
- while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
- {
- dataName = dataName.substring(b + 1).trim();
-
- }
- int e = (dataName.length() - dataName.indexOf(".")) + 1;
- dataName = dataName.substring(1, e).trim();
- return dataName;
- }
}
*/
package jalview.io;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.AlignedCodonFrame;
import jalview.datamodel.AlignmentAnnotation;
import jalview.datamodel.GraphLine;
import jalview.io.vamsas.Rangetype;
import jalview.project.Jalview2XML;
import jalview.util.MessageManager;
+import jalview.util.jarInputStreamProvider;
import jalview.viewmodel.AlignmentViewport;
+import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
Vobject obj = getjv2vObj(seqsetidobj);
if (obj != null && !(obj instanceof Alignment))
{
- Cache.log.warn(
+ Console.warn(
"IMPLEMENTATION ERROR?: Unexpected mapping for unmapped jalview string object content:"
+ seqsetidobj + " to object " + obj);
}
}
else
{
- Cache.log.warn("Unexpected mapping for Jalview String Object ID "
+ Console.warn("Unexpected mapping for Jalview String Object ID "
+ seqsetidobj + " to another jalview dataset object "
+ seqsetidobj);
}
}
}
- if (Cache.log.isDebugEnabled())
+ if (Console.isDebugEnabled())
{
- Cache.log.debug(
+ Console.debug(
"Returning null VorbaID binding for jalview object " + jvobj);
}
return null;
if (id == null)
{
id = cdoc.registerObject(vobj);
- Cache.log.debug(
+ Console.debug(
"Registering new object and returning null for getvObj2jv");
return null;
}
if (id == null || vobj.getVorbaId() == null
|| cdoc.getObject(id) != vobj)
{
- Cache.log.error("Failed to get id for "
+ Console.error("Failed to get id for "
+ (vobj.isRegisterable() ? "registerable"
: "unregisterable")
+ " object " + vobj);
if (vobj2jv.containsKey(vobj.getVorbaId())
&& !((VorbaId) vobj2jv.get(vobj.getVorbaId())).equals(jvobj))
{
- Cache.log.debug(
+ Console.debug(
"Warning? Overwriting existing vamsas id binding for "
+ vobj.getVorbaId(),
new Exception(MessageManager.getString(
else if (jv2vobj.containsKey(jvobj)
&& !((VorbaId) jv2vobj.get(jvobj)).equals(vobj.getVorbaId()))
{
- Cache.log.debug(
+ Console.debug(
"Warning? Overwriting existing jalview object binding for "
+ jvobj,
new Exception("Overwriting jalview object binding."));
}
/*
- * Cache.log.error("Attempt to make conflicting object binding! "+vobj+" id "
+ * Cache.error("Attempt to make conflicting object binding! "+vobj+" id "
* +vobj.getVorbaId()+" already bound to "+getvObj2jv(vobj)+" and "+jvobj+"
* already bound to "+getjv2vObj(jvobj),new Exception("Excessive call to
* bindjvvobj")); }
*/
// we just update the hash's regardless!
- Cache.log.debug("Binding " + vobj.getVorbaId() + " to " + jvobj);
+ Console.debug("Binding " + vobj.getVorbaId() + " to " + jvobj);
vobj2jv.put(vobj.getVorbaId(), jvobj);
// JBPNote - better implementing a hybrid invertible hash.
jv2vobj.put(jvobj, vobj.getVorbaId());
DataSet dataset = null;
if (jds == null)
{
- Cache.log.warn("Creating new dataset for an alignment.");
+ Console.warn("Creating new dataset for an alignment.");
jal.setDataset(null);
jds = jal.getDataset();
}
if (dataset == null)
{
- Cache.log.warn("Creating new vamsas dataset for alignment view "
+ Console.warn("Creating new vamsas dataset for alignment view "
+ av.getSequenceSetId());
// we create a new dataset on the default vamsas root.
root = cdoc.getVamsasRoots()[0]; // default vamsas root for modifying.
if (aa[i].groupRef != null)
{
// TODO: store any group associated annotation references
- Cache.log.warn(
+ Console.warn(
"Group associated sequence annotation is not stored in VAMSAS document.");
continue;
}
// LOCK METHODS)
{
// verify annotation - update (perhaps)
- Cache.log.info(
+ Console.info(
"update alignment sequence annotation. not yet implemented.");
}
else
{
// verify annotation - update (perhaps)
- Cache.log.info(
+ Console.info(
"updated alignment sequence annotation added.");
}
}
// /SAVE THE TREES
// /////////////////////////////////
// FIND ANY ASSOCIATED TREES
- if (Desktop.desktop != null)
+ if (Desktop.getDesktopPane() != null)
{
- javax.swing.JInternalFrame[] frames = Desktop.instance
+ javax.swing.JInternalFrame[] frames = Desktop.getInstance()
.getAllFrames();
for (int t = 0; t < frames.length; t++)
}
if (getjv2vObj(jvalsq.getDatasetSequence()) == null)
{
- Cache.log.warn(
+ Console.warn(
"Serious Implementation error - Unbound dataset sequence in alignment: "
+ jvalsq.getDatasetSequence());
}
alseq.setDescription(valseq.getDescription());
modal = true;
}
- if (modal && Cache.log.isDebugEnabled())
+ if (modal && Console.isDebugEnabled())
{
- Cache.log.debug(
+ Console.debug(
"Updating apparently edited sequence " + alseq.getName());
}
}
}
else
{
- Cache.log.error(
+ Console.error(
"Invalid dataset sequence id (null) for alignment sequence "
+ valseq.getVorbaId());
}
// and
// mapValuesToString
fromxml.setSkipList(skipList);
- jalview.util.jarInputStreamProvider jprovider = new jalview.util.jarInputStreamProvider()
+ jarInputStreamProvider jprovider = new jarInputStreamProvider()
{
@Override
@Override
public JarInputStream getJarInputStream() throws IOException
{
- jalview.bin.Cache.log.debug(
+ Console.debug(
"Returning client input stream for Jalview from Vamsas Document.");
return new JarInputStream(cappdata.getClientInputStream());
}
+
+ @Override
+ public File getFile()
+ {
+ return null;
+ }
};
if (dojvsync)
{
fromxml.setSkipList(skipList);
fromxml.setObjectMappingTables(mapKeysToString(vobj2jv),
mapValuesToString(jv2vobj));
- jalview.util.jarInputStreamProvider jarstream = new jalview.util.jarInputStreamProvider()
+ jarInputStreamProvider jarstream = new jarInputStreamProvider()
{
@Override
@Override
public JarInputStream getJarInputStream() throws IOException
{
- jalview.bin.Cache.log.debug(
+ Console.debug(
"Returning user input stream for Jalview from Vamsas Document.");
return new JarInputStream(cappdata.getUserInputStream());
}
+
+ @Override
+ public File getFile()
+ {
+ return null;
+ }
};
if (dojvsync)
{
// TODO implement this : af.getNumberOfViews
String seqsetidobj = av.getSequenceSetId();
views = Desktop.getViewports(seqsetidobj);
- Cache.log
- .debug("Found " + (views == null ? " no " : "" + views.length)
- + " views for '" + av.getSequenceSetId() + "'");
+ Console.debug("Found " + (views == null ? " no " : "" + views.length)
+ + " views for '" + av.getSequenceSetId() + "'");
if (views.length > 1)
{
// we need to close the original document view.
if (mappings != null)
{
jalview.structure.StructureSelectionManager
- .getStructureSelectionManager(Desktop.instance)
+ .getStructureSelectionManager(Desktop.getInstance())
.registerMappings(mappings);
}
}
} catch (Exception e)
{
// TODO raise GUI warning if user requests it.
- jalview.bin.Cache.log.error(
+ Console.error(
"Couldn't update jalview client application data. Giving up - local settings probably lost.",
e);
}
}
else
{
- jalview.bin.Cache.log.error(
+ Console.error(
"Couldn't access client application data for vamsas session. This is probably a vamsas client bug.");
}
}
int jremain = 0;
if (jdataset == null)
{
- Cache.log.debug("Initialising new jalview dataset fields");
+ Console.debug("Initialising new jalview dataset fields");
newds = true;
dsseqs = new Vector();
}
else
{
- Cache.log.debug("Update jalview dataset from vamsas.");
+ Console.debug("Update jalview dataset from vamsas.");
jremain = jdataset.getHeight();
dsseqs = jdataset.getSequences();
}
dsseqs.set(i, null);
}
jdataset = new jalview.datamodel.Alignment(seqs);
- Cache.log.debug("New vamsas dataset imported into jalview.");
+ Console.debug("New vamsas dataset imported into jalview.");
bindjvvobj(jdataset, dataset);
}
// ////////
// annotations
if (dsSeq == null)
{
- jalview.bin.Cache.log.warn(
+ Console.warn(
"Couldn't resolve jalview sequenceI for dataset object reference "
+ ((Vobject) dataset
.getDataSetAnnotations(dsa)
// JBPNote: we could just add them to all alignments but
// that may complicate cross references in the jalview
// datamodel
- Cache.log.warn(
+ Console.warn(
"Ignoring dataset annotation with annotationElements. Not yet supported in jalview.");
}
}
}
else
{
- Cache.log.warn(
+ Console.warn(
"Ignoring multiply referenced dataset sequence annotation for binding to datsaet sequence features.");
}
}
// OBJECT LOCK
// METHODS)
{
- Cache.log.info(
+ Console.info(
"UNIMPLEMENTED: not recovering user modifiable sequence alignment annotation");
// TODO: should at least replace with new one - otherwise
// things will break
dsseqs.set(i, null);
}
jal = new jalview.datamodel.Alignment(seqs);
- Cache.log.debug("New vamsas alignment imported into jalview "
+ Console.debug("New vamsas alignment imported into jalview "
+ alignment.getVorbaId().getId());
jal.setDataset(jdataset);
}
// jan.update(getjAlignmentAnnotation(jal, an[a])); // update
// from another annotation object in place.
- Cache.log.debug(
+ Console.debug(
"update from vamsas alignment annotation to existing jalview alignment annotation.");
if (an[j].getModifiable() == null) // TODO: USE VAMSAS
// LIBRARY OBJECT LOCK
{
// TODO: user defined annotation is totally mutable... - so
// load it up or throw away if locally edited.
- Cache.log.info(
+ Console.info(
"NOT IMPLEMENTED - Recovering user-modifiable annotation - yet...");
}
// TODO: compare annotation element rows
AlignFrame alignFrame;
if (av == null)
{
- Cache.log.debug("New alignframe for alignment "
+ Console.debug("New alignframe for alignment "
+ alignment.getVorbaId());
// ///////////////////////////////
// construct alignment view
}
// TODO: automatically create meaningful title for a vamsas
// alignment using its provenance.
- if (Cache.log.isDebugEnabled())
+ if (Console.isDebugEnabled())
{
title = title + "(" + alignment.getVorbaId() + ")";
vstree.UpdateSequenceTreeMap(tp);
} catch (RuntimeException e)
{
- Cache.log.warn("update of labels failed.", e);
+ Console.warn("update of labels failed.", e);
}
}
else
{
- Cache.log.warn("Cannot create tree for tree " + t
+ Console.warn("Cannot create tree for tree " + t
+ " in document ("
+ alignment.getTree(t).getVorbaId());
}
if (anot[row][pos] != null)
{
// only time this should happen is if the After flag is set.
- Cache.log.debug("Ignoring duplicate annotation site at " + pos);
+ Console.debug("Ignoring duplicate annotation site at " + pos);
continue;
}
if (anot[1 - row][pos] != null)
else if (glyphs[g].getDict().equals(
uk.ac.vamsas.objects.utils.GlyphDictionary.PROTEIN_HD_HYDRO))
{
- Cache.log.debug("ignoring hydrophobicity glyph marker.");
+ Console.debug("ignoring hydrophobicity glyph marker.");
AeContent[HASHPHOB] = true;
char c = (dc = glyphs[g].getContent()).charAt(0);
// dc may get overwritten - but we still set the colour.
}
else
{
- Cache.log.debug(
+ Console.debug(
"IMPLEMENTATION TODO: Ignoring unknown glyph type "
+ glyphs[g].getDict());
}
AeContent[HASVALS] = true;
if (ae[aa].getValueCount() > 1)
{
- Cache.log.warn(
+ Console.warn(
"ignoring additional " + (ae[aa].getValueCount() - 1)
+ " values in annotation element.");
}
}
else
{
- Cache.log.warn("Ignoring out of bound annotation element " + aa
+ Console.warn("Ignoring out of bound annotation element " + aa
+ " in " + annotation.getVorbaId().getId());
}
}
val = Float.valueOf(props[p].getContent());
} catch (Exception e)
{
- Cache.log.warn("Failed to parse threshold property");
+ Console.warn("Failed to parse threshold property");
}
if (val != null)
{
}
if (parsedRangeAnnotation == null)
{
- Cache.log.debug(
+ Console.debug(
"Inserting empty annotation row elements for a whole-alignment annotation.");
}
else
{
if (parsedRangeAnnotation[3] != null)
{
- Cache.log.warn("Ignoring 'After' annotation row in "
+ Console.warn("Ignoring 'After' annotation row in "
+ annotation.getVorbaId());
}
jalview.datamodel.Annotation[] arow = (jalview.datamodel.Annotation[]) parsedRangeAnnotation[2];
}
if (annotation.getLinkCount() > 0)
{
- Cache.log.warn("Ignoring " + annotation.getLinkCount()
+ Console.warn("Ignoring " + annotation.getLinkCount()
+ "links added to AlignmentAnnotation.");
}
if (annotation.getModifiable() == null
}
} catch (Exception e)
{
- Cache.log.info(
+ Console.info(
"UNIMPLEMENTED : Couldn't parse non-integer group value for setting graphGroup correctly.");
}
return jan;
DataSet dataset = null;
if (jal.getDataset() == null)
{
- Cache.log.warn("Creating new dataset for an alignment.");
+ Console.warn("Creating new dataset for an alignment.");
jal.setDataset(null);
}
dataset = (DataSet) ((Alignment) getjv2vObj(
if (dataset == null)
{
dataset = (DataSet) getjv2vObj(jal.getDataset());
- Cache.log.error(
+ Console.error(
"Can't find the correct dataset for the alignment in this view. Creating new one.");
}
}
else
{
- Cache.log.warn(
+ Console.warn(
"NO Vamsas Binding for local sequence! NOT CREATING MAPPING FOR "
+ dmps[smp].getDisplayId(true) + " to "
+ mps[smp].getTo().getName());
/**
* An override that
* <ul>
- * <li>uses Source (column 2) as feature type instead of the default column 3</li>
+ * <li>uses Source (column 2) as feature type instead of the default column
+ * 3</li>
* <li>sets "InterProScan" as the feature group</li>
* <li>extracts "signature_desc" attribute as the feature description</li>
* </ul>
*/
public static boolean recognises(String[] columns)
{
- SequenceOntologyI so = SequenceOntologyFactory.getInstance();
+ SequenceOntologyI so = SequenceOntologyFactory.getSequenceOntology();
String type = columns[TYPE_COL];
if (so.isA(type, SequenceOntologyI.PROTEIN_MATCH)
|| (".".equals(columns[SOURCE_COL])
*/
package jalview.io.vamsas;
+ import jalview.bin.Console;
import jalview.datamodel.AlignedCodonFrame;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.DBRefEntry;
}
if (from != null && sequenceMapping.getLoc() != from)
{
- jalview.bin.Cache.log.warn("Probable IMPLEMENTATION ERROR: " + from
+ Console.warn("Probable IMPLEMENTATION ERROR: " + from
+ " doesn't match the local mapping sequence.");
}
if (ds != null && sequenceMapping.is__stored_in_document()
&& sequenceMapping.getV_parent() != ds)
{
- jalview.bin.Cache.log.warn("Probable IMPLEMENTATION ERROR: " + ds
+ Console.warn("Probable IMPLEMENTATION ERROR: " + ds
+ " doesn't match the parent of the bound sequence mapping object.");
}
}
SequenceType to = (SequenceType) getjv2vObj(jvto);
if (to == null)
{
- jalview.bin.Cache.log.warn(
+ Console.warn(
"FIXME NONFATAL - do a second update: Ignoring Forward Reference to seuqence not yet bound to vamsas seuqence object");
return;
}
if (!dnaToProt)
{
- jalview.bin.Cache.log.warn(
+ Console.warn(
"Ignoring Mapping - don't support protein to protein mapping in vamsas document yet.");
return;
}
// mapping
bindjvvobj(mjvmapping.getMap(), sequenceMapping);
- jalview.bin.Cache.log.debug(
+ Console.debug(
"Successfully created mapping " + sequenceMapping.getVorbaId());
}
// private void update(jalview.util.MapList mjvmapping,
// SequenceMapping sequenceMapping)
{
- jalview.bin.Cache.log
- .error("Not implemented: Jalview Update Alcodon Mapping:TODO!");
+ Console.error("Not implemented: Jalview Update Alcodon Mapping:TODO!");
}
private void update(SequenceMapping sequenceMapping,
jalview.datamodel.Mapping mjvmapping)
{
- jalview.bin.Cache.log
- .error("Not implemented: Update DBRef Mapping from Jalview");
+ Console.error("Not implemented: Update DBRef Mapping from Jalview");
}
private void update(jalview.datamodel.Mapping mjvmapping,
SequenceMapping sequenceMapping)
{
- jalview.bin.Cache.log.error(
- "Not implemented: Jalview Update Sequence DBRef Mapping");
+ Console.error("Not implemented: Jalview Update Sequence DBRef Mapping");
}
/**
}
if (sdloc == null || sdmap == null)
{
- jalview.bin.Cache.log.info("Ignoring non sequence-sequence mapping");
+ Console.info("Ignoring non sequence-sequence mapping");
return;
}
mobj = this.getvObj2jv(sdloc);
if (from == null || to == null)
{
- jalview.bin.Cache.log.error(
+ Console.error(
"Probable Vamsas implementation error : unbound dataset sequences involved in a mapping are being parsed!");
return;
}
}
bindjvvobj(mapping, sequenceMapping);
jalview.structure.StructureSelectionManager
- .getStructureSelectionManager(Desktop.instance)
+ .getStructureSelectionManager(Desktop.getInstance())
.registerMapping(acf);
// Try to link up any conjugate database references in the two sequences
// matchConjugateDBRefs(from, to, mapping);
{
if (from.getDBRefs() == null && to.getDBRefs() == null)
{
- if (jalview.bin.Cache.log.isDebugEnabled())
+ if (Console.isDebugEnabled())
{
- jalview.bin.Cache.log.debug("Not matching conjugate refs for "
- + from.getName() + " and " + to.getName());
+ Console.debug("Not matching conjugate refs for " + from.getName()
+ + " and " + to.getName());
}
return;
}
- if (jalview.bin.Cache.log.isDebugEnabled())
+ if (Console.isDebugEnabled())
{
- jalview.bin.Cache.log.debug("Matching conjugate refs for "
- + from.getName() + " and " + to.getName());
+ Console.debug("Matching conjugate refs for " + from.getName()
+ + " and " + to.getName());
}
List<DBRefEntry> fdb = from.getDBRefs();
List<DBRefEntry> tdb = new ArrayList<DBRefEntry>(to.getDBRefs());
int tdblen = to.getDBRefs().size();
- //
- //
- // YOWSER
- //
- // System.arraycopy(to.getDBRefs(), 0, tdb, 0, tdblen);
- //
- //
- //
- //
+ //
+ //
+ // YOWSER
+ //
+ // System.arraycopy(to.getDBRefs(), 0, tdb, 0, tdblen);
+ //
+ //
+ //
+ //
Vector matched = new Vector();
jalview.util.MapList smapI = smap.getInverse();
for (int f = 0, fn = fdb.size(); f < fn; f++)
boolean fmpnnl = (fmp != null);
// if (fmpnnl && fmp.getTo()!=null)
// {
- // jalview.bin.Cache.log.debug("Not overwriting existing To reference in
+ // Cache.debug("Not overwriting existing To reference in
// "+fe);
// continue;
// }
*/
package jalview.jbgui;
-import jalview.analysis.AnnotationSorter.SequenceAnnotationOrder;
-import jalview.analysis.GeneticCodeI;
-import jalview.analysis.GeneticCodes;
-import jalview.api.SplitContainerI;
-import jalview.bin.Cache;
-import jalview.gui.JvSwingUtils;
-import jalview.gui.Preferences;
-import jalview.io.FileFormats;
-import jalview.schemes.ResidueColourScheme;
-import jalview.util.MessageManager;
-import jalview.util.Platform;
+
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
+import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
+import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
+import jalview.analysis.AnnotationSorter.SequenceAnnotationOrder;
+import jalview.analysis.GeneticCodeI;
+import jalview.analysis.GeneticCodes;
+import jalview.api.SplitContainerI;
+import jalview.bin.Cache;
+import jalview.gui.JvSwingUtils;
+import jalview.gui.Preferences;
+import jalview.hmmer.HmmerCommand;
+import jalview.io.FileFormatException;
+import jalview.io.FileFormats;
+import jalview.schemes.ResidueColourScheme;
+import jalview.util.MessageManager;
+import jalview.util.Platform;
-
-
@SuppressWarnings("serial")
public class GAlignFrame extends JInternalFrame
{
public JMenu webService = new JMenu();// BH 2019 was protected, but not
// sufficient for AlignFrame thread run
+ // JBP - followed suite for these other service related GUI elements.
+ // TODO: check we really need these to be public
+ public JMenu hmmerMenu = new JMenu();
- public JMenuItem webServiceNoServices;// BH 2019 was protected, but not
- // sufficient for AlignFrame thread run
+ public JMenuItem webServiceNoServices;
protected JCheckBoxMenuItem viewBoxesMenuItem = new JCheckBoxMenuItem();
protected JCheckBoxMenuItem normaliseSequenceLogo = new JCheckBoxMenuItem();
+ protected JCheckBoxMenuItem showInformationHistogram = new JCheckBoxMenuItem();
+
+ protected JCheckBoxMenuItem showHMMSequenceLogo = new JCheckBoxMenuItem();
+
+ protected JCheckBoxMenuItem normaliseHMMSequenceLogo = new JCheckBoxMenuItem();
-
protected JCheckBoxMenuItem applyAutoAnnotationSettings = new JCheckBoxMenuItem();
protected JMenuItem openFeatureSettings;
{
// for Web-page embedding using id=align-frame-div
- setName("jalview-alignment");
+ setName(Platform.getAppID("alignment"));
-
jbInit();
setJMenuBar(alignFrameMenuBar);
private void jbInit() throws Exception
{
initColourMenu();
+
+
JMenuItem saveAs = new JMenuItem(
MessageManager.getString("action.save_as"));
ActionListener al = new ActionListener()
saveAs_actionPerformed();
}
};
+
+
// FIXME getDefaultToolkit throws an exception in Headless mode
- KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_S,
- jalview.util.ShortcutKeyMaskExWrapper.getMenuShortcutKeyMaskEx()
- | jalview.util.ShortcutKeyMaskExWrapper.SHIFT_DOWN_MASK,
+ KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_S, Platform.SHORTCUT_KEY_MASK | InputEvent.SHIFT_DOWN_MASK,
false);
addMenuActionAndAccelerator(keyStroke, saveAs, al);
+
+
closeMenuItem.setText(MessageManager.getString("action.close"));
- keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_W,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_W, Platform.SHORTCUT_KEY_MASK, false);
al = new ActionListener()
{
@Override
}
};
addMenuActionAndAccelerator(keyStroke, closeMenuItem, al);
+
+
JMenu editMenu = new JMenu(MessageManager.getString("action.edit"));
JMenu viewMenu = new JMenu(MessageManager.getString("action.view"));
JMenu annotationsMenu = new JMenu(
JMenu calculateMenu = new JMenu(
MessageManager.getString("action.calculate"));
webService.setText(MessageManager.getString("action.web_service"));
-
+ initHMMERMenu();
JMenuItem selectAllSequenceMenuItem = new JMenuItem(
MessageManager.getString("action.select_all"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_A,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
al = new ActionListener()
{
@Override
}
};
addMenuActionAndAccelerator(keyStroke, selectAllSequenceMenuItem, al);
+
+
JMenuItem deselectAllSequenceMenuItem = new JMenuItem(
MessageManager.getString("action.deselect_all"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
}
};
addMenuActionAndAccelerator(keyStroke, deselectAllSequenceMenuItem, al);
+
+
JMenuItem invertSequenceMenuItem = new JMenuItem(
MessageManager.getString("action.invert_sequence_selection"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_I,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
al = new ActionListener()
{
@Override
}
};
addMenuActionAndAccelerator(keyStroke, invertSequenceMenuItem, al);
+
+
JMenuItem grpsFromSelection = new JMenuItem(
MessageManager.getString("action.make_groups_selection"));
grpsFromSelection.addActionListener(new ActionListener()
JMenuItem remove2LeftMenuItem = new JMenuItem(
MessageManager.getString("action.remove_left"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_L,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
al = new ActionListener()
{
@Override
}
};
addMenuActionAndAccelerator(keyStroke, remove2LeftMenuItem, al);
+
+
JMenuItem remove2RightMenuItem = new JMenuItem(
MessageManager.getString("action.remove_right"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_R,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
al = new ActionListener()
{
@Override
}
};
addMenuActionAndAccelerator(keyStroke, remove2RightMenuItem, al);
+
+
JMenuItem removeGappedColumnMenuItem = new JMenuItem(
MessageManager.getString("action.remove_empty_columns"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_E,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
al = new ActionListener()
{
@Override
}
};
addMenuActionAndAccelerator(keyStroke, removeGappedColumnMenuItem, al);
+
+
JMenuItem removeAllGapsMenuItem = new JMenuItem(
MessageManager.getString("action.remove_all_gaps"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_E,
- jalview.util.ShortcutKeyMaskExWrapper.getMenuShortcutKeyMaskEx()
- | jalview.util.ShortcutKeyMaskExWrapper.SHIFT_DOWN_MASK,
+ Platform.SHORTCUT_KEY_MASK
+ | InputEvent.SHIFT_DOWN_MASK,
false);
al = new ActionListener()
{
}
};
addMenuActionAndAccelerator(keyStroke, removeAllGapsMenuItem, al);
+
+
JMenuItem justifyLeftMenuItem = new JMenuItem(
MessageManager.getString("action.left_justify_alignment"));
justifyLeftMenuItem.addActionListener(new ActionListener()
sortGroupMenuItem_actionPerformed(e);
}
});
+
+ JMenuItem sortEValueMenuItem = new JMenuItem(
+ MessageManager.getString("action.by_evalue"));
+ sortEValueMenuItem.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ sortEValueMenuItem_actionPerformed(e);
+ }
+ });
+ JMenuItem sortBitScoreMenuItem = new JMenuItem(
+ MessageManager.getString("action.by_bit_score"));
+ sortBitScoreMenuItem.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ sortBitScoreMenuItem_actionPerformed(e);
+ }
+ });
+
JMenuItem removeRedundancyMenuItem = new JMenuItem(
MessageManager.getString("action.remove_redundancy"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_D,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
al = new ActionListener()
{
@Override
};
addMenuActionAndAccelerator(keyStroke, removeRedundancyMenuItem, al);
+ JMenuItem filterByEValue = new JMenuItem(
+ MessageManager.getString("action.filter_by_evalue"));
+ filterByEValue.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ filterByEValue_actionPerformed();
+ }
+
+ });
+
+ JMenuItem filterByScore = new JMenuItem(
+ MessageManager.getString("action.filter_by_score"));
+ filterByScore.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ filterByScore_actionPerformed();
+ }
+
+ });
+
JMenuItem pairwiseAlignmentMenuItem = new JMenuItem(
MessageManager.getString("action.pairwise_alignment"));
pairwiseAlignmentMenuItem.addActionListener(new ActionListener()
pairwiseAlignmentMenuItem_actionPerformed(e);
}
});
+
+
this.getContentPane().setLayout(new BorderLayout());
alignFrameMenuBar.setFont(new java.awt.Font("Verdana", 0, 11));
statusBar.setBackground(Color.white);
statusBar.setFont(new java.awt.Font("Verdana", 0, 11));
statusBar.setBorder(BorderFactory.createLineBorder(Color.black));
statusBar.setText(MessageManager.getString("label.status_bar"));
outputTextboxMenu
.setText(MessageManager.getString("label.out_to_textbox"));
-
annotationPanelMenuItem.setActionCommand("");
annotationPanelMenuItem
.setText(MessageManager.getString("label.show_annotations"));
final JCheckBoxMenuItem sortAnnByLabel = new JCheckBoxMenuItem(
MessageManager.getString("label.sort_annotations_by_label"));
-
sortAnnBySequence.setSelected(
sortAnnotationsBy == SequenceAnnotationOrder.SEQUENCE_AND_LABEL);
sortAnnBySequence.addActionListener(new ActionListener()
colourTextMenuItem_actionPerformed(e);
}
});
+
+
JMenuItem htmlMenuItem = new JMenuItem(
MessageManager.getString("label.html"));
htmlMenuItem.addActionListener(new ActionListener()
htmlMenuItem_actionPerformed(e);
}
});
+
+
JMenuItem createBioJS = new JMenuItem(
MessageManager.getString("label.biojs_html_export"));
createBioJS.addActionListener(new java.awt.event.ActionListener()
bioJSMenuItem_actionPerformed(e);
}
});
+
+
JMenuItem overviewMenuItem = new JMenuItem(
MessageManager.getString("label.overview_window"));
overviewMenuItem.addActionListener(new ActionListener()
overviewMenuItem_actionPerformed(e);
}
});
+
+
undoMenuItem.setEnabled(false);
undoMenuItem.setText(MessageManager.getString("action.undo"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_Z,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
al = new ActionListener()
{
@Override
}
};
addMenuActionAndAccelerator(keyStroke, undoMenuItem, al);
+
+
redoMenuItem.setEnabled(false);
redoMenuItem.setText(MessageManager.getString("action.redo"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_Y,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
al = new ActionListener()
{
@Override
}
};
addMenuActionAndAccelerator(keyStroke, redoMenuItem, al);
+
+
wrapMenuItem.setText(MessageManager.getString("label.wrap"));
wrapMenuItem.addActionListener(new ActionListener()
{
wrapMenuItem_actionPerformed(e);
}
});
+
+
JMenuItem printMenuItem = new JMenuItem(
MessageManager.getString("action.print"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_P,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
al = new ActionListener()
{
@Override
}
};
addMenuActionAndAccelerator(keyStroke, printMenuItem, al);
+
+
renderGapsMenuItem
.setText(MessageManager.getString("action.show_gaps"));
renderGapsMenuItem.setState(true);
renderGapsMenuItem_actionPerformed(e);
}
});
+
+
JMenuItem findMenuItem = new JMenuItem(
MessageManager.getString("action.find"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
findMenuItem.setToolTipText(JvSwingUtils.wrapTooltip(true,
MessageManager.getString("label.find_tip")));
al = new ActionListener()
showSeqFeatures.setText(
MessageManager.getString("label.show_sequence_features"));
-
showSeqFeatures.addActionListener(new ActionListener()
{
@Override
.setText(MessageManager.getString("label.show_database_refs"));
showDbRefsMenuitem.addActionListener(new ActionListener()
{
+
+
@Override
public void actionPerformed(ActionEvent e)
{
showDbRefs_actionPerformed(e);
}
+
+
});
showNpFeatsMenuitem.setText(
MessageManager.getString("label.show_non_positional_features"));
showNpFeatsMenuitem.addActionListener(new ActionListener()
{
+
+
@Override
public void actionPerformed(ActionEvent e)
{
showNpFeats_actionPerformed(e);
}
+
+
});
showGroupConservation
.setText(MessageManager.getString("label.group_conservation"));
showGroupConservation.addActionListener(new ActionListener()
{
+
+
@Override
public void actionPerformed(ActionEvent e)
{
showGroupConservation_actionPerformed(e);
}
+
+
});
showGroupConsensus
.setText(MessageManager.getString("label.group_consensus"));
showGroupConsensus.addActionListener(new ActionListener()
{
+
+
@Override
public void actionPerformed(ActionEvent e)
{
showGroupConsensus_actionPerformed(e);
}
+
+
});
showConsensusHistogram.setText(
MessageManager.getString("label.show_consensus_histogram"));
showConsensusHistogram.addActionListener(new ActionListener()
{
+
+
@Override
public void actionPerformed(ActionEvent e)
{
showConsensusHistogram_actionPerformed(e);
}
+
+
});
showSequenceLogo
.setText(MessageManager.getString("label.show_consensus_logo"));
showSequenceLogo.addActionListener(new ActionListener()
{
+
+
@Override
public void actionPerformed(ActionEvent e)
{
showSequenceLogo_actionPerformed(e);
}
+
+
});
normaliseSequenceLogo
.setText(MessageManager.getString("label.norm_consensus_logo"));
normaliseSequenceLogo.addActionListener(new ActionListener()
{
+
+
@Override
public void actionPerformed(ActionEvent e)
{
normaliseSequenceLogo_actionPerformed(e);
}
+
+
});
applyAutoAnnotationSettings
.setText(MessageManager.getString("label.apply_all_groups"));
applyAutoAnnotationSettings_actionPerformed(e);
}
});
+
+
ButtonGroup buttonGroup = new ButtonGroup();
final JRadioButtonMenuItem showAutoFirst = new JRadioButtonMenuItem(
MessageManager.getString("label.show_first"));
sortAnnotations_actionPerformed();
}
});
+
+
JMenuItem deleteGroups = new JMenuItem(
MessageManager.getString("action.undefine_groups"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_U,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
al = new ActionListener()
{
@Override
}
};
addMenuActionAndAccelerator(keyStroke, deleteGroups, al);
+
+
JMenuItem annotationColumn = new JMenuItem(
MessageManager.getString("action.select_by_annotation"));
annotationColumn.addActionListener(new ActionListener()
annotationColumn_actionPerformed(e);
}
});
+
+
JMenuItem createGroup = new JMenuItem(
MessageManager.getString("action.create_group"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_G,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
al = new ActionListener()
{
@Override
}
};
addMenuActionAndAccelerator(keyStroke, createGroup, al);
+
+
JMenuItem unGroup = new JMenuItem(
MessageManager.getString("action.remove_group"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_G,
- jalview.util.ShortcutKeyMaskExWrapper.getMenuShortcutKeyMaskEx()
- | jalview.util.ShortcutKeyMaskExWrapper.SHIFT_DOWN_MASK,
+ Platform.SHORTCUT_KEY_MASK
+ | InputEvent.SHIFT_DOWN_MASK,
false);
al = new ActionListener()
{
}
};
addMenuActionAndAccelerator(keyStroke, unGroup, al);
+
+
copy.setText(MessageManager.getString("action.copy"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
al = new ActionListener()
{
}
};
addMenuActionAndAccelerator(keyStroke, copy, al);
+
+
cut.setText(MessageManager.getString("action.cut"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_X,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
al = new ActionListener()
{
@Override
}
};
addMenuActionAndAccelerator(keyStroke, cut, al);
+
+
JMenuItem delete = new JMenuItem(
MessageManager.getString("action.delete"));
delete.addActionListener(new ActionListener()
delete_actionPerformed();
}
});
+
+
pasteMenu.setText(MessageManager.getString("action.paste"));
JMenuItem pasteNew = new JMenuItem(
MessageManager.getString("label.to_new_alignment"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_V,
- jalview.util.ShortcutKeyMaskExWrapper.getMenuShortcutKeyMaskEx()
- | jalview.util.ShortcutKeyMaskExWrapper.SHIFT_DOWN_MASK,
+ Platform.SHORTCUT_KEY_MASK
+ | InputEvent.SHIFT_DOWN_MASK,
false);
al = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
- pasteNew_actionPerformed(e);
+ try
+ {
+ pasteNew_actionPerformed(e);
+ } catch (IOException | InterruptedException e1)
+ {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ }
}
};
addMenuActionAndAccelerator(keyStroke, pasteNew, al);
+
+
JMenuItem pasteThis = new JMenuItem(
MessageManager.getString("label.to_this_alignment"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_V,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
al = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
- pasteThis_actionPerformed(e);
+ try
+ {
+ pasteThis_actionPerformed(e);
+ } catch (IOException | InterruptedException e1)
+ {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ }
}
};
addMenuActionAndAccelerator(keyStroke, pasteThis, al);
+
+
JMenuItem createPNG = new JMenuItem("PNG");
createPNG.addActionListener(new ActionListener()
{
});
createPNG.setActionCommand(
MessageManager.getString("label.save_png_image"));
+
JMenuItem font = new JMenuItem(MessageManager.getString("action.font"));
font.addActionListener(new ActionListener()
{
});
seqLimits.setText(
MessageManager.getString("label.show_sequence_limits"));
- seqLimits.setState(jalview.bin.Cache.getDefault("SHOW_JVSUFFIX", true));
+ seqLimits.setState(Cache.getDefault("SHOW_JVSUFFIX", true));
seqLimits.addActionListener(new ActionListener()
{
@Override
createEPS(null);
}
});
+
+
JMenuItem createSVG = new JMenuItem("SVG");
createSVG.addActionListener(new ActionListener()
{
createSVG(null);
}
});
+
+
JMenuItem loadTreeMenuItem = new JMenuItem(
MessageManager.getString("label.load_associated_tree"));
loadTreeMenuItem.setActionCommand(
loadTreeMenuItem_actionPerformed(e);
}
});
+
+
scaleAbove.setVisible(false);
scaleAbove.setText(MessageManager.getString("action.scale_above"));
scaleAbove.addActionListener(new ActionListener()
.setText(MessageManager.getString("label.automatic_scrolling"));
followHighlightMenuItem.addActionListener(new ActionListener()
{
+
+
@Override
public void actionPerformed(ActionEvent e)
{
followHighlight_actionPerformed();
}
+
+
});
+
+
sortByTreeMenu
.setText(MessageManager.getString("action.by_tree_order"));
sort.setText(MessageManager.getString("action.sort"));
@Override
public void menuSelected(MenuEvent e)
{
- buildTreeSortMenu();
+ enableSortMenuOptions();
}
@Override
{
}
});
+ sortByTreeMenu.addMenuListener(new MenuListener()
+ {
+ @Override
+ public void menuSelected(MenuEvent e)
+ {
+ buildTreeSortMenu();
+ }
+
+ @Override
+ public void menuDeselected(MenuEvent e)
+ {
+ }
+
+ @Override
+ public void menuCanceled(MenuEvent e)
+ {
+ }
+ });
sortByAnnotScore
.setText(MessageManager.getString("label.sort_by_score"));
sort.add(sortByAnnotScore);
sort.addMenuListener(new javax.swing.event.MenuListener()
{
+
+
@Override
public void menuCanceled(MenuEvent e)
{
}
+
+
@Override
public void menuDeselected(MenuEvent e)
{
}
+
+
@Override
public void menuSelected(MenuEvent e)
{
.setText(MessageManager.getString("action.calculate_tree_pca"));
padGapsMenuitem.setText(MessageManager.getString("label.pad_gaps"));
- padGapsMenuitem
- .setState(jalview.bin.Cache.getDefault("PAD_GAPS", false));
+ padGapsMenuitem.setState(Cache.getDefault("PAD_GAPS", false));
padGapsMenuitem.addActionListener(new ActionListener()
{
@Override
showReverse_actionPerformed(true);
}
});
+
+
JMenuItem extractScores = new JMenuItem(
MessageManager.getString("label.extract_scores"));
extractScores.addActionListener(new ActionListener()
});
extractScores.setVisible(true);
// JBPNote: TODO: make gui for regex based score extraction
+
+
// for show products actions see AlignFrame.canShowProducts
showProducts.setText(MessageManager.getString("label.get_cross_refs"));
+
+
runGroovy.setText(MessageManager.getString("label.run_groovy"));
runGroovy.setToolTipText(
MessageManager.getString("label.run_groovy_tip"));
fetchSequence_actionPerformed();
}
});
+
+
JMenuItem associatedData = new JMenuItem(
MessageManager.getString("label.load_features_annotations"));
associatedData.addActionListener(new ActionListener()
@Override
public void actionPerformed(ActionEvent e)
{
- associatedData_actionPerformed(e);
+ try
+ {
+ associatedData_actionPerformed(e);
+ } catch (IOException | InterruptedException e1)
+ {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ }
}
});
loadVcf = new JMenuItem(
});
autoCalculate.setText(
MessageManager.getString("label.autocalculate_consensus"));
- autoCalculate.setState(
- jalview.bin.Cache.getDefault("AUTO_CALC_CONSENSUS", true));
+ autoCalculate.setState(Cache.getDefault("AUTO_CALC_CONSENSUS", true));
autoCalculate.addActionListener(new ActionListener()
{
@Override
MessageManager.getString("label.sort_alignment_new_tree"));
sortByTree.setToolTipText("<html>" + MessageManager.getString(
"label.enable_automatically_sort_alignment_when_open_new_tree"));
- sortByTree
- .setState(jalview.bin.Cache.getDefault("SORT_BY_TREE", false));
+ sortByTree.setState(Cache.getDefault("SORT_BY_TREE", false));
sortByTree.addActionListener(new ActionListener()
{
@Override
listenToViewSelections_actionPerformed(e);
}
});
+
+
JMenu addSequenceMenu = new JMenu(
MessageManager.getString("label.add_sequences"));
JMenuItem addFromFile = new JMenuItem(
hiddenMarkers_actionPerformed(e);
}
});
+
+
JMenuItem invertColSel = new JMenuItem(
MessageManager.getString("action.invert_column_selection"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_I,
- jalview.util.ShortcutKeyMaskExWrapper.getMenuShortcutKeyMaskEx()
- | jalview.util.ShortcutKeyMaskExWrapper.ALT_DOWN_MASK,
+ Platform.SHORTCUT_KEY_MASK
+ | InputEvent.ALT_DOWN_MASK,
false);
al = new ActionListener()
{
}
};
addMenuActionAndAccelerator(keyStroke, invertColSel, al);
+
+
showComplementMenuItem.setVisible(false);
showComplementMenuItem.addActionListener(new ActionListener()
{
showComplement_actionPerformed(showComplementMenuItem.getState());
}
});
+
+
tabbedPane.addChangeListener(new javax.swing.event.ChangeListener()
{
@Override
tabbedPane_mousePressed(e);
}
}
+
+
@Override
public void mouseReleased(MouseEvent e)
{
tabbedPane_focusGained(e);
}
});
+
+
JMenuItem save = new JMenuItem(MessageManager.getString("action.save"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_S,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
al = new ActionListener()
{
@Override
}
};
addMenuActionAndAccelerator(keyStroke, save, al);
+
+
reload.setEnabled(false);
reload.setText(MessageManager.getString("action.reload"));
reload.addActionListener(new ActionListener()
reload_actionPerformed(e);
}
});
+
+
JMenuItem newView = new JMenuItem(
MessageManager.getString("action.new_view"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_T,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false);
+ Platform.SHORTCUT_KEY_MASK, false);
al = new ActionListener()
{
@Override
}
};
addMenuActionAndAccelerator(keyStroke, newView, al);
+
+
tabbedPane.setToolTipText("<html><i>"
+ MessageManager.getString("label.rename_tab_eXpand_reGroup")
+ "</i></html>");
+
+
formatMenu.setText(MessageManager.getString("action.format"));
JMenu selectMenu = new JMenu(MessageManager.getString("action.select"));
idRightAlign_actionPerformed(e);
}
});
+
+
gatherViews.setEnabled(false);
gatherViews.setText(MessageManager.getString("action.gather_views"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_G, 0, false);
}
};
addMenuActionAndAccelerator(keyStroke, gatherViews, al);
+
+
expandViews.setEnabled(false);
expandViews.setText(MessageManager.getString("action.expand_views"));
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_X, 0, false);
}
};
addMenuActionAndAccelerator(keyStroke, expandViews, al);
+
+
JMenuItem pageSetup = new JMenuItem(
MessageManager.getString("action.page_setup"));
pageSetup.addActionListener(new ActionListener()
});
JMenuItem selectHighlighted = new JMenuItem(
MessageManager.getString("action.select_highlighted_columns"));
+ selectHighlighted.setToolTipText(JvSwingUtils.wrapTooltip(true,
+ MessageManager.getString("tooltip.select_highlighted_columns")));
+ al = new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent actionEvent)
+ {
+ selectHighlightedColumns_actionPerformed(actionEvent);
+ }
+ };
+ JMenuItem Filter = new JMenuItem(
+ MessageManager.getString("action.select_highlighted_columns"));
selectHighlighted.setToolTipText(
MessageManager.getString("tooltip.select_highlighted_columns"));
al = new ActionListener()
MessageManager.getString("label.sequence_id_tooltip"));
JMenu autoAnnMenu = new JMenu(
MessageManager.getString("label.autocalculated_annotation"));
+
+
JMenu exportImageMenu = new JMenu(
MessageManager.getString("label.export_image"));
JMenu fileMenu = new JMenu(MessageManager.getString("action.file"));
alignFrameMenuBar.add(formatMenu);
alignFrameMenuBar.add(colourMenu);
alignFrameMenuBar.add(calculateMenu);
+ alignFrameMenuBar.add(webService);
if (!Platform.isJS())
{
- alignFrameMenuBar.add(webService);
+ alignFrameMenuBar.add(hmmerMenu);
}
+
+
fileMenu.add(fetchSequence);
fileMenu.add(addSequenceMenu);
fileMenu.add(reload);
}
fileMenu.addSeparator();
fileMenu.add(closeMenuItem);
+
+
pasteMenu.add(pasteNew);
pasteMenu.add(pasteThis);
editMenu.add(undoMenuItem);
// editMenu.add(justifyRightMenuItem);
// editMenu.addSeparator();
editMenu.add(padGapsMenuitem);
+
+ editMenu.addSeparator();
+ editMenu.add(filterByEValue);
+ editMenu.add(filterByScore);
+
showMenu.add(showAllColumns);
showMenu.add(showAllSeqs);
showMenu.add(showAllhidden);
viewMenu.add(alignmentProperties);
viewMenu.addSeparator();
viewMenu.add(overviewMenuItem);
+
+
annotationsMenu.add(annotationPanelMenuItem);
annotationsMenu.addSeparator();
annotationsMenu.add(showAllAlAnnotations);
sort.add(sortLengthMenuItem);
sort.add(sortGroupMenuItem);
sort.add(sortPairwiseMenuItem);
+ sort.add(sortEValueMenuItem);
+ sort.add(sortBitScoreMenuItem);
sort.add(sortByTreeMenu);
calculateMenu.add(sort);
calculateMenu.add(calculateTree);
calculateMenu.addSeparator();
calculateMenu.add(runGroovy);
}
+
webServiceNoServices = new JMenuItem(
MessageManager.getString("label.no_services"));
webService.add(webServiceNoServices);
this.getContentPane().add(statusPanel, java.awt.BorderLayout.SOUTH);
statusPanel.add(statusBar, null);
this.getContentPane().add(tabbedPane, java.awt.BorderLayout.CENTER);
+
+
formatMenu.add(font);
formatMenu.addSeparator();
formatMenu.add(wrapMenuItem);
// selectMenu.add(listenToViewSelections);
}
+ /**
+ * Constructs the entries on the HMMER menu
+ */
+ protected void initHMMERMenu()
+ {
+ /*
+ * hmmbuild
+ */
+ JMenu hmmBuild = new JMenu(MessageManager.getString("label.hmmbuild"));
+ JMenuItem hmmBuildSettings = new JMenuItem(
+ MessageManager.getString("label.edit_settings_and_run"));
+ hmmBuildSettings.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ hmmBuild_actionPerformed(false);
+ }
+ });
+ JMenuItem hmmBuildRun = new JMenuItem(MessageManager.formatMessage(
+ "label.action_with_default_settings", "hmmbuild"));
+ hmmBuildRun.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ hmmBuild_actionPerformed(true);
+ }
+ });
+ hmmBuild.add(hmmBuildRun);
+ hmmBuild.add(hmmBuildSettings);
+
+ /*
+ * hmmalign
+ */
+ JMenu hmmAlign = new JMenu(MessageManager.getString("label.hmmalign"));
+ JMenuItem hmmAlignRun = new JMenuItem(MessageManager.formatMessage(
+ "label.action_with_default_settings", "hmmalign"));
+ hmmAlignRun.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ hmmAlign_actionPerformed(true);
+ }
+ });
+ JMenuItem hmmAlignSettings = new JMenuItem(
+ MessageManager.getString("label.edit_settings_and_run"));
+ hmmAlignSettings.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ hmmAlign_actionPerformed(false);
+ }
+ });
+ hmmAlign.add(hmmAlignRun);
+ hmmAlign.add(hmmAlignSettings);
+
+ /*
+ * hmmsearch
+ */
+ JMenu hmmSearch = new JMenu(
+ MessageManager.getString("label.hmmsearch"));
+ JMenuItem hmmSearchSettings = new JMenuItem(
+ MessageManager.getString("label.edit_settings_and_run"));
+ hmmSearchSettings.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ hmmSearch_actionPerformed(false);
+ }
+ });
+ JMenuItem hmmSearchRun = new JMenuItem(MessageManager.formatMessage(
+ "label.action_with_default_settings", "hmmsearch"));
+ hmmSearchRun.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ hmmSearch_actionPerformed(true);
+ }
+ });
+ JMenuItem addDatabase = new JMenuItem(
+ MessageManager.getString("label.add_database"));
+ addDatabase.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ try
+ {
+ addDatabase_actionPerformed();
+ } catch (IOException e1)
+ {
+ e1.printStackTrace();
+ }
+ }
+ });
+ hmmSearch.add(hmmSearchRun);
+ hmmSearch.add(hmmSearchSettings);
+ // hmmSearch.add(addDatabase);
+
+ /*
+ * jackhmmer
+ */
+ JMenu jackhmmer = new JMenu(
+ MessageManager.getString("label.jackhmmer"));
+ JMenuItem jackhmmerSettings = new JMenuItem(
+ MessageManager.getString("label.edit_settings_and_run"));
+ jackhmmerSettings.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ jackhmmer_actionPerformed(false);
+ }
+ });
+ JMenuItem jackhmmerRun = new JMenuItem(MessageManager.formatMessage(
+ "label.action_with_default_settings", "jackhmmer"));
+ jackhmmerRun.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ jackhmmer_actionPerformed(true);
+ }
+
+ });
+ /*
+ JMenuItem addDatabase = new JMenuItem(
+ MessageManager.getString("label.add_database"));
+ addDatabase.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ try
+ {
+ addDatabase_actionPerformed();
+ } catch (IOException e1)
+ {
+ e1.printStackTrace();
+ }
+ }
+ });
+ */
+ jackhmmer.add(jackhmmerRun);
+ jackhmmer.add(jackhmmerSettings);
+ // hmmSearch.add(addDatabase);
+
+ /*
+ * top level menu
+ */
+ hmmerMenu.setText(MessageManager.getString("action.hmmer"));
+ hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
+ hmmerMenu.add(hmmBuild);
+ hmmerMenu.add(hmmAlign);
+ hmmerMenu.add(hmmSearch);
+ hmmerMenu.add(jackhmmer);
+
+ }
+
+ protected void enableSortMenuOptions()
+ {
+ }
+
protected void loadVcf_actionPerformed()
{
}
{
}
+ protected void sortEValueMenuItem_actionPerformed(ActionEvent e)
+ {
+ }
+
+ protected void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
+ {
+ }
-
protected void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
{
}
}
protected void pasteNew_actionPerformed(ActionEvent e)
+ throws IOException, InterruptedException
{
}
protected void pasteThis_actionPerformed(ActionEvent e)
+ throws IOException, InterruptedException
{
}
{
}
+ protected void hmmBuild_actionPerformed(boolean withDefaults)
+ {
+ }
+
+ protected void hmmSearch_actionPerformed(boolean withDefaults)
+ {
+ }
+
+ protected void jackhmmer_actionPerformed(boolean b)
+ {
+ }
+
+ protected void addDatabase_actionPerformed()
+ throws FileFormatException, IOException
+ {
+ }
+
+ protected void hmmAlign_actionPerformed(boolean withDefaults)
+ {
+ }
-
public void createPNG(java.io.File f)
{
}
{
}
+ protected void filterByEValue_actionPerformed()
+ {
+ }
+
+ protected void filterByScore_actionPerformed()
+ {
+ }
-
protected void scaleRight_actionPerformed(ActionEvent e)
{
}
}
public void associatedData_actionPerformed(ActionEvent e)
+ throws IOException, InterruptedException
{
}
protected void showComplement_actionPerformed(boolean complement)
{
}
+
-
}
*/
package jalview.jbgui;
-import jalview.gui.JvSwingUtils;
-import jalview.util.MessageManager;
+
import java.awt.BorderLayout;
import java.awt.Font;
-import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
+import jalview.gui.JvSwingUtils;
+import jalview.util.MessageManager;
+import jalview.util.Platform;
-
/**
* DOCUMENT ME!
*
textarea.setBorder(null);
selectAll.setText(MessageManager.getString("action.select_all"));
- selectAll
- .setAccelerator(
- javax.swing.KeyStroke
- .getKeyStroke(java.awt.event.KeyEvent.VK_A,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false));
+ selectAll.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
+ java.awt.event.KeyEvent.VK_A,
+ Platform.SHORTCUT_KEY_MASK, false));
selectAll.addActionListener(new ActionListener()
{
@Override
});
jMenu1.setText(MessageManager.getString("action.file"));
save.setText(MessageManager.getString("action.save"));
- save.setAccelerator(
- javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false));
+ save.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
+ java.awt.event.KeyEvent.VK_S,
+ Platform.SHORTCUT_KEY_MASK, false));
save.addActionListener(new ActionListener()
{
@Override
save_actionPerformed(e);
}
});
- copyItem.setAccelerator(
- javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false));
- pasteMenu
- .setAccelerator(
- javax.swing.KeyStroke
- .getKeyStroke(java.awt.event.KeyEvent.VK_V,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false));
+ copyItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
+ java.awt.event.KeyEvent.VK_C,
+ Platform.SHORTCUT_KEY_MASK, false));
+ pasteMenu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
+ java.awt.event.KeyEvent.VK_V,
+ Platform.SHORTCUT_KEY_MASK, false));
editMenubar.add(jMenu1);
editMenubar.add(editMenu);
textarea.setFont(new java.awt.Font("Monospaced", Font.PLAIN, 12));
*/
package jalview.jbgui;
- import jalview.api.AlignmentViewPanel;
- import jalview.io.FileFormatException;
- import jalview.util.MessageManager;
- import jalview.util.Platform;
+
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
+ import jalview.api.AlignmentViewPanel;
+ import jalview.bin.Cache;
+ import jalview.io.FileFormatException;
+ import jalview.util.MessageManager;
+ import jalview.util.Platform;
-
/**
* DOCUMENT ME!
*
public class GDesktop extends JFrame
{
- protected static JMenu windowMenu = new JMenu();
+ protected JMenu windowMenu = new JMenu();
JMenuBar desktopMenubar = new JMenuBar();
e.printStackTrace();
}
- if (Platform.allowMnemonics())
+ if (Platform.allowMnemonics())
{
- // BH was !Platform.isAMacAndNotJS()) i.e. "JS or not Mac"
- // but here we want just not a Mac, period, right?
+ //BH was !Platform.isAMacAndNotJS()) i.e. "JS or not Mac"
+ // but here we want just not a Mac, period, right?
FileMenu.setMnemonic('F');
inputLocalFileMenuItem.setMnemonic('L');
inputURLMenuItem.setMnemonic('U');
*/
private void jbInit() throws Exception
{
+ boolean apqHandlersSet = false;
+ /**
+ * APQHandlers sets handlers for About, Preferences and Quit actions
+ * peculiar to macOS's application menu. APQHandlers will check to see if a
+ * handler is supported before setting it.
+ */
+ try
+ {
++ // TODO: if (!Platform.isJS()
+ apqHandlersSet = APQHandlers.setAPQHandlers(this);
+ } catch (Exception e)
+ {
+ System.out.println("Cannot set APQHandlers");
+ // e.printStackTrace();
+ } catch (Throwable t)
+ {
+ jalview.bin.Console
+ .warn("Error setting APQHandlers: " + t.toString());
+ jalview.bin.Console.trace(Cache.getStackTraceString(t));
+ }
- setName("jalview-desktop");
+ setName(Platform.getAppID("desktop"));
FileMenu.setText(MessageManager.getString("action.file"));
HelpMenu.setText(MessageManager.getString("action.help"));
inputLocalFileMenuItem
.setText(MessageManager.getString("label.load_tree_from_file"));
- inputLocalFileMenuItem
- .setAccelerator(
- javax.swing.KeyStroke
- .getKeyStroke(java.awt.event.KeyEvent.VK_O,
- jalview.util.ShortcutKeyMaskExWrapper
- .getMenuShortcutKeyMaskEx(),
- false));
+ inputLocalFileMenuItem.setAccelerator(
+ javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O,
+ Platform.SHORTCUT_KEY_MASK,
+ false));
inputLocalFileMenuItem
.addActionListener(new java.awt.event.ActionListener()
{
}
});
+ Float specversion = Platform.isJS() ? Float.valueOf(8)
+ : Float.parseFloat(
+ System.getProperty("java.specification.version"));
+
desktopMenubar.add(FileMenu);
desktopMenubar.add(toolsMenu);
desktopMenubar.add(HelpMenu);
FileMenu.add(inputMenu);
FileMenu.add(inputSequence);
FileMenu.addSeparator();
- // FileMenu.add(saveState);
+ //FileMenu.add(saveState);
FileMenu.add(saveAsState);
FileMenu.add(loadState);
FileMenu.addSeparator();
- FileMenu.add(quit);
- HelpMenu.add(aboutMenuItem);
+ if (!APQHandlers.setQuit)
+ {
+ FileMenu.add(quit);
+ }
+ if (!APQHandlers.setAbout)
+ {
+ HelpMenu.add(aboutMenuItem);
+ }
HelpMenu.add(documentationMenuItem);
- if (!Platform.isAMacAndNotJS() || specversion < 11)
+ if (!APQHandlers.setPreferences)
{
toolsMenu.add(preferences);
}
*/
protected void quit()
{
- // System.out.println("********** GDesktop.quit()");
+ //System.out.println("********** GDesktop.quit()");
}
/**
*/
package jalview.jbgui;
+import jalview.bin.Cache;
++import jalview.bin.Console;
++import jalview.bin.MemorySetting;
+import jalview.fts.core.FTSDataColumnPreferences;
+import jalview.fts.core.FTSDataColumnPreferences.PreferenceSource;
+import jalview.fts.service.pdb.PDBFTSRestClient;
+import jalview.gui.Desktop;
+import jalview.gui.JalviewBooleanRadioButtons;
+import jalview.gui.JvOptionPane;
+import jalview.gui.JvSwingUtils;
+import jalview.gui.StructureViewer.ViewerType;
+import jalview.io.BackupFilenameParts;
+import jalview.io.BackupFiles;
+import jalview.io.BackupFilesPresetEntry;
+import jalview.io.IntKeyStringValueEntry;
+import jalview.util.MessageManager;
+import jalview.util.Platform;
++import jalview.util.StringUtils;
+
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.util.Arrays;
import java.util.List;
+import javax.swing.AbstractButton;
import javax.swing.AbstractCellEditor;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
+import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
+ import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
-import jalview.bin.Cache;
-import jalview.bin.Console;
-import jalview.bin.MemorySetting;
-import jalview.fts.core.FTSDataColumnPreferences;
-import jalview.fts.core.FTSDataColumnPreferences.PreferenceSource;
-import jalview.fts.service.pdb.PDBFTSRestClient;
-import jalview.gui.Desktop;
-import jalview.gui.JalviewBooleanRadioButtons;
-import jalview.gui.JvOptionPane;
-import jalview.gui.JvSwingUtils;
-import jalview.gui.StructureViewer.ViewerType;
-import jalview.io.BackupFilenameParts;
-import jalview.io.BackupFiles;
-import jalview.io.BackupFilesPresetEntry;
-import jalview.io.IntKeyStringValueEntry;
-import jalview.util.MessageManager;
-import jalview.util.Platform;
-import jalview.util.StringUtils;
++import net.miginfocom.swing.MigLayout;
+
/**
* Base class for the Preferences panel.
*
protected JCheckBox showConsensLogo = new JCheckBox();
+ protected JCheckBox showInformationHistogram = new JCheckBox();
+
+ protected JCheckBox showHMMLogo = new JCheckBox();
protected JCheckBox showDbRefTooltip = new JCheckBox();
protected JCheckBox showNpTooltip = new JCheckBox();
protected JCheckBox structFromPdb = new JCheckBox();
-
protected JCheckBox addSecondaryStructure = new JCheckBox();
protected JCheckBox addTempFactor = new JCheckBox();
protected JPasswordField proxyAuthPasswordPB = new JPasswordField();
+ protected JTextField defaultBrowser = new JTextField();
+
protected ButtonGroup proxyType = new ButtonGroup();
protected JRadioButton noProxy = new JRadioButton();
protected JCheckBox sortByTree = new JCheckBox();
/*
+ * hmmer tab and components
+ */
+ protected JPanel hmmerTab;
+
+ protected JCheckBox hmmrTrimTermini;
+
+ protected AbstractButton hmmerBackgroundUniprot;
+
+ protected AbstractButton hmmerBackgroundAlignment;
+
+ protected JTextField hmmerSequenceCount;
+
+ protected JTextField hmmerPath;
+
+ protected JTextField cygwinPath;
+
+ /*
* Web Services tab
*/
protected JPanel wsTab = new JPanel();
+ protected JPanel slivkaTab = new JPanel();
/*
* Backups tab components
* a lot of these are member variables instead of local variables only so that they
private final JTabbedPane tabbedPane = new JTabbedPane();
private JLabel messageLabel = new JLabel("", JLabel.CENTER);
+
+ /*
+ * Startup tab components
+ */
+
+ protected JCheckBox customiseMemorySetting = new JCheckBox();
+
+ protected JLabel exampleMemoryLabel = new JLabel();
+
+ protected JTextArea exampleMemoryMessageTextArea = new JTextArea();
+
+ protected JLabel maxMemoryLabel = new JLabel();
+
+ protected JLabel jvmMemoryPercentLabel = new JLabel();
+
+ protected JSlider jvmMemoryPercentSlider = new JSlider();
+
+ protected JLabel jvmMemoryPercentDisplay = new JLabel();
+
+ protected JLabel jvmMemoryMaxLabel = new JLabel();
+
+ protected JTextField jvmMemoryMaxTextField = new JTextField(null, 8);
+
+ protected JComboBox<Object> lafCombo = new JComboBox<>();
-
/**
* Creates a new GPreferences object.
*/
{
// final JTabbedPane tabbedPane = new JTabbedPane();
this.setLayout(new BorderLayout());
+
// message label at top
this.add(messageLabel, BorderLayout.NORTH);
+
JPanel okCancelPanel = initOkCancelPanel();
this.add(tabbedPane, BorderLayout.CENTER);
this.add(okCancelPanel, BorderLayout.SOUTH);
tabbedPane.add(initEditingTab(),
MessageManager.getString("label.editing"));
- tabbedPane.add(initHMMERTab(), MessageManager.getString("label.hmmer"));
- tabbedPane.add(initStartupTab(),
- MessageManager.getString("label.startup"));
-
/*
* See WsPreferences for the real work of configuring this tab.
*/
if (!Platform.isJS())
{
++ tabbedPane.add(initHMMERTab(), MessageManager.getString("label.hmmer"));
++ tabbedPane.add(initStartupTab(),
++ MessageManager.getString("label.startup"));
wsTab.setLayout(new BorderLayout());
tabbedPane.add(wsTab, MessageManager.getString("label.web_services"));
}
+
+ slivkaTab.setLayout(new BorderLayout());
+ tabbedPane.add(slivkaTab, "Slivka Services");
/*
* Handler to validate a tab before leaving it - currently only for
}
}
lastTab = tabbedPane.getSelectedComponent();
+
clearMessage();
}
}
/**
- * Initialises the Output tab
+ * Initialises the hmmer tabbed panel
+ *
+ * @return
+ */
+ private JPanel initHMMERTab()
+ {
+ hmmerTab = new JPanel();
+ hmmerTab.setLayout(new BoxLayout(hmmerTab, BoxLayout.Y_AXIS));
+ hmmerTab.setLayout(new MigLayout("flowy"));
+
+ /*
+ * path to hmmer binaries folder
+ */
+ JPanel installationPanel = new JPanel(new MigLayout("flowy"));
+ // new FlowLayout(FlowLayout.LEFT));
+ JvSwingUtils.createTitledBorder(installationPanel,
+ MessageManager.getString("label.installation"), true);
+ hmmerTab.add(installationPanel);
+ JLabel hmmerLocation = new JLabel(
+ MessageManager.getString("label.hmmer_location"));
+ hmmerLocation.setFont(LABEL_FONT);
+ final int pathFieldLength = 40;
+ hmmerPath = new JTextField(pathFieldLength);
+ hmmerPath.addMouseListener(new MouseAdapter()
+ {
+ @Override
+ public void mouseClicked(MouseEvent e)
+ {
+ if (e.getClickCount() == 2)
+ {
+ String chosen = openFileChooser(true);
+ if (chosen != null)
+ {
+ hmmerPath.setText(chosen);
+ validateHmmerPath();
+ }
+ }
+ }
+ });
+ installationPanel.add(hmmerLocation);
+ installationPanel.add(hmmerPath);
+
+ /*
+ * path to Cygwin binaries folder (for Windows)
+ */
+ if (Platform.isWindowsAndNotJS())
+ {
+ JLabel cygwinLocation = new JLabel(
+ MessageManager.getString("label.cygwin_location"));
+ cygwinLocation.setFont(LABEL_FONT);
+ cygwinPath = new JTextField(pathFieldLength);
+ cygwinPath.addMouseListener(new MouseAdapter()
+ {
+ @Override
+ public void mouseClicked(MouseEvent e)
+ {
+ if (e.getClickCount() == 2)
+ {
+ String chosen = openFileChooser(true);
+ if (chosen != null)
+ {
+ cygwinPath.setText(chosen);
+ validateCygwinPath();
+ }
+ }
+ }
+ });
+ installationPanel.add(cygwinLocation);
+ installationPanel.add(cygwinPath);
+ }
+
+ /*
+ * preferences for hmmalign
+ */
+ JPanel alignOptionsPanel = new JPanel(new MigLayout());
+ // new FlowLayout(FlowLayout.LEFT));
+ JvSwingUtils.createTitledBorder(alignOptionsPanel,
+ MessageManager.getString("label.hmmalign_options"), true);
+ hmmerTab.add(alignOptionsPanel);
+ hmmrTrimTermini = new JCheckBox();
+ hmmrTrimTermini.setFont(LABEL_FONT);
+ hmmrTrimTermini.setText(MessageManager.getString("label.trim_termini"));
+ alignOptionsPanel.add(hmmrTrimTermini);
+
+ /*
+ * preferences for hmmsearch
+ */
+ JPanel searchOptions = new JPanel(new MigLayout());
+ // FlowLayout(FlowLayout.LEFT));
+ JvSwingUtils.createTitledBorder(searchOptions,
+ MessageManager.getString("label.hmmsearch_options"), true);
+ hmmerTab.add(searchOptions);
+ JLabel sequencesToKeep = new JLabel(
+ MessageManager.getString("label.no_of_sequences"));
+ sequencesToKeep.setFont(LABEL_FONT);
+ searchOptions.add(sequencesToKeep);
+ hmmerSequenceCount = new JTextField(5);
+ searchOptions.add(hmmerSequenceCount);
+
+ /*
+ * preferences for Information Content annotation
+ */
+ // JPanel dummy = new JPanel(new FlowLayout(FlowLayout.LEFT));
+ JPanel annotationOptions = new JPanel(new MigLayout("left"));
+ JvSwingUtils.createTitledBorder(annotationOptions,
+ MessageManager.getString("label.information_annotation"), true);
+ // dummy.add(annotationOptions);
+ hmmerTab.add(annotationOptions);
+ ButtonGroup backgroundOptions = new ButtonGroup();
+ hmmerBackgroundUniprot = new JRadioButton(
+ MessageManager.getString("label.freq_uniprot"));
+ hmmerBackgroundUniprot.setFont(LABEL_FONT);
+ hmmerBackgroundAlignment = new JRadioButton(
+ MessageManager.getString("label.freq_alignment"));
+ hmmerBackgroundAlignment.setFont(LABEL_FONT);
+ backgroundOptions.add(hmmerBackgroundUniprot);
+ backgroundOptions.add(hmmerBackgroundAlignment);
+ backgroundOptions.setSelected(hmmerBackgroundUniprot.getModel(), true);
+ // disable buttons for now as annotation only uses Uniprot background
+ hmmerBackgroundAlignment.setEnabled(false);
+ hmmerBackgroundUniprot.setEnabled(false);
+ annotationOptions.add(hmmerBackgroundUniprot, "wrap");
+ annotationOptions.add(hmmerBackgroundAlignment);
+
+ return hmmerTab;
+ }
+
+ /**
+ * Initialises the Output tabbed panel.
*
* @return
*/
connectTab = new JPanel();
connectTab.setLayout(new GridBagLayout());
- // Label for browser text box
- JLabel browserLabel = new JLabel();
- browserLabel.setFont(LABEL_FONT);
- browserLabel.setHorizontalAlignment(SwingConstants.TRAILING);
- browserLabel.setText(
- MessageManager.getString("label.default_browser_unix"));
- defaultBrowser.setFont(LABEL_FONT);
- defaultBrowser.setText("");
- final String tooltip = JvSwingUtils.wrapTooltip(true,
- MessageManager.getString("label.double_click_to_browse"));
- defaultBrowser.setToolTipText(tooltip);
- defaultBrowser.addMouseListener(new MouseAdapter()
- {
- @Override
- public void mouseClicked(MouseEvent e)
- {
- if (e.getClickCount() > 1)
- {
- defaultBrowser_mouseClicked(e);
- }
- }
- });
+
JPanel proxyPanel = initConnTabProxyPanel();
initConnTabCheckboxes();
- // Add default Browser text box
- connectTab.add(browserLabel,
- new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
- GridBagConstraints.WEST, GridBagConstraints.NONE,
- new Insets(10, 0, 5, 5), 5, 1));
- defaultBrowser.setFont(LABEL_FONT);
- defaultBrowser.setText("");
-
- connectTab.add(defaultBrowser, new GridBagConstraints(1, 0, 1, 1, 1.0,
- 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
- new Insets(10, 0, 5, 10), 30, 1));
-
// Add proxy server panel
connectTab.add(proxyPanel, new GridBagConstraints(0, 1, 2, 1, 1.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
proxyAuth_actionPerformed();
}
});
+
setCustomProxyEnabled();
// Make proxy server panel
protColourLabel.setHorizontalAlignment(SwingConstants.LEFT);
protColourLabel.setText(
MessageManager.getString("label.prot_alignment_colour") + " ");
- JvSwingUtils.addtoLayout(coloursTab,
+ GPreferences.addtoLayout(coloursTab,
MessageManager
.getString("label.default_colour_scheme_for_alignment"),
protColourLabel, protColour);
nucColourLabel.setHorizontalAlignment(SwingConstants.LEFT);
nucColourLabel.setText(
MessageManager.getString("label.nuc_alignment_colour") + " ");
- JvSwingUtils.addtoLayout(coloursTab,
+ GPreferences.addtoLayout(coloursTab,
MessageManager
.getString("label.default_colour_scheme_for_alignment"),
nucColourLabel, nucColour);
annotationShding.setBorder(new TitledBorder(
MessageManager.getString("label.annotation_shading_default")));
annotationShding.setLayout(new GridLayout(1, 2));
- JvSwingUtils.addtoLayout(annotationShding,
+ GPreferences.addtoLayout(annotationShding,
MessageManager.getString(
"label.default_minimum_colour_annotation_shading"),
mincolourLabel, minColour);
- JvSwingUtils.addtoLayout(annotationShding,
+ GPreferences.addtoLayout(annotationShding,
MessageManager.getString(
"label.default_maximum_colour_annotation_shading"),
maxcolourLabel, maxColour);
structureTab.add(structFromPdb);
// indent checkboxes that are conditional on the first one
-
ypos += lineSpacing;
addSecondaryStructure.setFont(LABEL_FONT);
addSecondaryStructure
{
if (structureViewerPath.isEnabled() && e.getClickCount() == 2)
{
- structureViewer_actionPerformed(
- (String) structViewer.getSelectedItem());
- }
- });
- structureTab.add(structViewer);
- ypos += lineSpacing;
- structureViewerPathLabel = new JLabel();
- structureViewerPathLabel.setFont(LABEL_FONT);// new Font("SansSerif", 0,
- // 11));
- structureViewerPathLabel.setHorizontalAlignment(SwingConstants.LEFT);
- structureViewerPathLabel.setText(MessageManager
- .formatMessage("label.viewer_path", "Chimera(X)"));
- structureViewerPathLabel
- .setBounds(new Rectangle(10, ypos, 170, height));
- structureViewerPathLabel.setEnabled(false);
- structureTab.add(structureViewerPathLabel);
-
- structureViewerPath.setFont(LABEL_FONT);
- structureViewerPath.setText("");
- structureViewerPath.setEnabled(false);
- final String tooltip = JvSwingUtils.wrapTooltip(true,
- MessageManager.getString("label.viewer_path_tip"));
- structureViewerPath.setToolTipText(tooltip);
- structureViewerPath.setBounds(new Rectangle(190, ypos, 290, height));
- structureViewerPath.addMouseListener(new MouseAdapter()
- {
- if (structureViewerPath.isEnabled() && e.getClickCount() == 2)
- {
-- String chosen = openFileChooser();
++ String chosen = openFileChooser(false);
if (chosen != null)
{
structureViewerPath.setText(chosen);
viewerLabel.setVisible(false);
structViewer.setVisible(false);
}
+
return structureTab;
}
}
/**
- * Show a dialog for the user to choose a file. Returns the chosen path, or
- * null on Cancel.
+ * Show a dialog for the user to choose a file. Returns the chosen path, or null
+ * on Cancel.
*
* @return
*/
- protected String openFileChooser()
+ protected String openFileChooser(boolean forFolder)
{
String choice = null;
JFileChooser chooser = new JFileChooser();
true);
}
+ if (forFolder)
+ {
+ chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
+ }
-
// chooser.setFileView(new JalviewFileView());
chooser.setDialogTitle(
MessageManager.getString("label.open_local_file"));
visualTab.add(fontNameCB);
visualTab.add(fontSizeCB);
visualTab.add(fontStyleCB);
+
+
if (Platform.isJS())
{
startupCheckbox.setVisible(false);
startupFileTextfield.setVisible(false);
}
+
+
return visualTab;
}
{
BackupFilesPresetEntry savedPreset = BackupFilesPresetEntry
.getSavedBackupEntry();
- enableBackupFiles.setSelected(
- Cache.getDefault(BackupFiles.ENABLED, !Platform.isJS()));
+ enableBackupFiles
+ .setSelected(Cache.getDefault(BackupFiles.ENABLED, !Platform.isJS()));
BackupFilesPresetEntry backupfilesCustomEntry = BackupFilesPresetEntry
.createBackupFilesPresetEntry(Cache
updateBackupFilesExampleLabel();
}
+ /*
+ * Load the saved Memory settings
+ */
+ protected void loadLastSavedMemorySettings()
+ {
+ customiseMemorySetting.setSelected(
+ Cache.getDefault(MemorySetting.CUSTOMISED_SETTINGS, false));
+ jvmMemoryPercentSlider
+ .setValue(Cache.getDefault(MemorySetting.MEMORY_JVMMEMPC, 90));
+ jvmMemoryMaxTextField.setText(
+ Cache.getDefault(MemorySetting.MEMORY_JVMMEMMAX, "32g"));
+ }
-
private boolean warnAboutSuffixReverseChange()
{
BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
&& nowSuffixTemplate.equals(savedSuffixTemplate);
}
+ /* Initialises the Startup tabbed panel.
+ *
+ * @return
+ * */
+
+ private JPanel initStartupTab()
+ {
+ JPanel startupTab = new JPanel();
+ startupTab.setBorder(
+ new TitledBorder(MessageManager.getString("label.memory")));
+ startupTab.setLayout(new GridBagLayout());
+
+ GridBagConstraints gbc = new GridBagConstraints();
+ gbc.weightx = 0.0;
+ gbc.weighty = 0.0;
+ gbc.anchor = GridBagConstraints.FIRST_LINE_START;
+ gbc.fill = GridBagConstraints.NONE;
+
+ initMemoryPanel();
+
+ gbc.gridheight = 1;
+ gbc.gridwidth = 3;
+
+ gbc.gridy = 0; // row 1
+ gbc.gridx = 0;
+ JLabel memoryText = new JLabel();
+ memoryText.setFont(LABEL_FONT_ITALIC);
+ memoryText
+ .setText(MessageManager.getString("label.memory_setting_text"));
+ startupTab.add(memoryText, gbc);
+
+ gbc.gridy++; // row 2
+ gbc.gridx = 0;
+ JPanel exampleMemoryPanel = new JPanel();
+ exampleMemoryPanel
+ .setLayout(new BoxLayout(exampleMemoryPanel, BoxLayout.Y_AXIS));
+ exampleMemoryPanel.setToolTipText(JvSwingUtils.wrapTooltip(true,
+ MessageManager.getString("label.memory_example_tooltip")));
+ JLabel exampleTextLabel = new JLabel();
+ exampleTextLabel
+ .setText(MessageManager.getString("label.memory_example_text"));
+ exampleTextLabel.setForeground(Color.GRAY);
+ exampleTextLabel.setFont(LABEL_FONT);
+ exampleMemoryPanel.add(exampleTextLabel);
+ exampleMemoryPanel.add(exampleMemoryLabel);
+ exampleMemoryPanel.setBackground(Color.WHITE);
+ exampleMemoryPanel.setBorder(BorderFactory.createEtchedBorder());
+ startupTab.add(exampleMemoryPanel, gbc);
+
+ gbc.gridy++; // row 3
+ gbc.gridx = 0;
+ startupTab.add(customiseMemorySetting, gbc);
+
+ gbc.gridy += 2; // row 4 with a gap
+ gbc.gridx = 0;
+ startupTab.add(maxMemoryLabel, gbc);
+
+ gbc.gridy += 2; // row 5
+ gbc.gridx = 0;
+ gbc.gridwidth = 1;
+ startupTab.add(jvmMemoryPercentLabel, gbc);
+ gbc.gridx++;
+ startupTab.add(jvmMemoryPercentSlider, gbc);
+ gbc.gridx++;
+ // gbc.weightx = 0.1;
+ startupTab.add(jvmMemoryPercentDisplay, gbc);
+ // gbc.weightx = 1.0;
+ gbc.gridwidth = 3;
+
+ gbc.gridy++; // row 6
+ gbc.gridx = 0;
+ startupTab.add(jvmMemoryMaxLabel, gbc);
+ gbc.gridx++;
+ startupTab.add(jvmMemoryMaxTextField, gbc);
+
+ gbc.gridy++; // row 7
+ gbc.gridx = 0;
+ gbc.gridwidth = 4;
+ exampleMemoryMessageTextArea.setBackground(startupTab.getBackground());
+ JScrollPane sp = new JScrollPane(exampleMemoryMessageTextArea);
+ sp.setBorder(BorderFactory.createEmptyBorder());
+ sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
+ sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
+ startupTab.add(sp, gbc);
+
+ // fill empty space to push widget to top left
+ gbc.gridy++;
+ gbc.weighty = 1.0;
+ gbc.gridx = 100;
+ gbc.gridwidth = 1;
+ gbc.weightx = 1.0;
+ startupTab.add(new JPanel(), gbc);
+
+ setMemoryPercentDisplay();
+ memoryOptionsSetEnabled();
+ return startupTab;
+ }
+
+ private void initMemoryPanel()
+ {
+ // Enable memory settings checkbox
+ customiseMemorySetting.setFont(LABEL_FONT_BOLD);
+ customiseMemorySetting.setText(
+ MessageManager.getString("label.customise_memory_settings"));
+ customiseMemorySetting.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ memoryOptionsSetEnabled();
+ }
+ });
+
+ loadLastSavedMemorySettings();
+
+ exampleMemoryLabel.setFont(LABEL_FONT_BOLD);
+ exampleMemoryLabel.setBackground(Color.WHITE);
+
+ maxMemoryLabel = new JLabel(
+ MessageManager.getString("label.maximum_memory_used"));
+ maxMemoryLabel.setFont(LABEL_FONT_BOLD);
+
+ // Maximum memory percentage slider
+ jvmMemoryPercentLabel.setFont(LABEL_FONT);
+ jvmMemoryPercentLabel.setText(
+ MessageManager.getString("label.percent_of_physical_memory"));
+ jvmMemoryPercentSlider.setPaintLabels(true);
+ jvmMemoryPercentSlider.setPaintTicks(true);
+ jvmMemoryPercentSlider.setPaintTrack(true);
+ jvmMemoryPercentSlider.setMajorTickSpacing(50);
+ jvmMemoryPercentSlider.setMinorTickSpacing(10);
+ jvmMemoryPercentSlider.addChangeListener(new ChangeListener()
+ {
+ @Override
+ public void stateChanged(ChangeEvent e)
+ {
+ setMemoryPercentDisplay();
+ }
+ });
+ jvmMemoryPercentDisplay.setFont(LABEL_FONT);
+ setMemoryPercentDisplay();
+
+ // Maximum memory cap textbox
+ jvmMemoryMaxLabel.setFont(LABEL_FONT);
+ jvmMemoryMaxLabel
+ .setText(MessageManager.getString("label.maximum_memory"));
+ initMemoryMaxTextField();
+
+ exampleMemoryMessageTextArea.setFont(LABEL_FONT_ITALIC);
+ exampleMemoryMessageTextArea.setForeground(Color.GRAY);
+ exampleMemoryMessageTextArea.setEditable(false);
+ exampleMemoryMessageTextArea.setLineWrap(true);
+ exampleMemoryMessageTextArea.setWrapStyleWord(true);
+ exampleMemoryMessageTextArea.setText(" ");
+ exampleMemoryMessageTextArea.setRows(2);
+ exampleMemoryMessageTextArea.setColumns(40);
+
+ setExampleMemoryLabel();
+ }
+
+ private void initMemoryMaxTextField()
+ {
+ jvmMemoryMaxTextField.setToolTipText(
+ MessageManager.getString("label.maximum_memory_tooltip"));
+ jvmMemoryMaxTextField.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent arg0)
+ {
+ validateMemoryMaxTextField();
+ setExampleMemoryLabel();
+ }
+ });
+
+ jvmMemoryMaxTextField.addKeyListener(new KeyListener()
+ {
+ @Override
+ public void keyReleased(KeyEvent e)
+ {
+ validateMemoryMaxTextField();
+ setExampleMemoryLabel();
+ }
+
+ @Override
+ public void keyPressed(KeyEvent e)
+ {
+ }
+
+ // try and stop invalid typing
+ @Override
+ public void keyTyped(KeyEvent e)
+ {
+ char c = Character.toLowerCase(e.getKeyChar());
+ String text = jvmMemoryMaxTextField.getText();
+ String suffixes = "tgmkb";
+ int pos = jvmMemoryMaxTextField.getCaretPosition();
+ int suffixPos = StringUtils.firstCharPosIgnoreCase(text, suffixes);
+ if (!((('0' <= c && c <= '9')
+ && (suffixPos == -1 || pos <= suffixPos)) // digits only allowed
+ // before suffix
+ || (suffixes.indexOf(Character.toLowerCase(c)) >= 0 // valid
+ // suffix
+ && pos == text.length() // at end of text and
+ && suffixPos == -1) // there isn't already one
+ ))
+ {
+ // don't process
+ e.consume();
+ }
+ }
+ });
+ }
+
+ private boolean isMemoryMaxTextFieldValid()
+ {
+ return MemorySetting
+ .isValidMemoryString(jvmMemoryMaxTextField.getText());
+ }
+
+ private void validateMemoryMaxTextField()
+ {
+ if (isMemoryMaxTextFieldValid())
+ {
+ jvmMemoryMaxTextField.setBackground(Color.WHITE);
+ }
+ else
+ {
+ jvmMemoryMaxTextField.setBackground(Color.PINK);
+ }
+ }
+
+ private void setMemoryPercentDisplay()
+ {
+ jvmMemoryPercentDisplay
+ .setText(jvmMemoryPercentSlider.getValue() + "%");
+ setExampleMemoryLabel();
+ }
+
+ private void setExampleMemoryLabel()
+ {
+ boolean selected = customiseMemorySetting.isSelected();
+ int jvmmempc = jvmMemoryPercentSlider.getValue();
+ String jvmmemmax = jvmMemoryMaxTextField.getText();
+
+ long mem;
+ if (selected && (0 <= jvmmempc && jvmmempc <= 100)
+ && MemorySetting.isValidMemoryString(jvmmemmax))
+ {
+ mem = MemorySetting.getMemorySetting(jvmmemmax,
+ String.valueOf(jvmmempc), false, true);
+ }
+ else
+ {
+ mem = MemorySetting.getMemorySetting(null, null, false, true);
+ }
+ exampleMemoryLabel.setText(MemorySetting.memoryLongToString(mem));
+ String message = MemorySetting.getAdjustmentMessage();
+ exampleMemoryMessageTextArea.setText(
+ MessageManager.getString("label.adjustments_for_this_computer")
+ + ": "
+ + (message == null
+ ? MessageManager.getString("label.none")
+ : message));
+ }
+
+ private void memoryOptionsSetEnabled()
+ {
+ boolean enabled = customiseMemorySetting.isSelected();
+ // leave exampleMemoryLabel enabled always
+ maxMemoryLabel.setEnabled(enabled);
+ jvmMemoryPercentLabel.setEnabled(enabled);
+ jvmMemoryPercentSlider.setEnabled(enabled);
+ jvmMemoryPercentDisplay.setEnabled(enabled);
+ jvmMemoryMaxLabel.setEnabled(enabled);
+ jvmMemoryMaxTextField.setEnabled(enabled);
+ exampleMemoryMessageTextArea.setEnabled(enabled);
+ setExampleMemoryLabel();
+ }
+
/**
* Initialises the Backups tabbed panel.
*
}
});
-
// enable checkbox 1 col
gbc.gridwidth = 1;
gbc.gridheight = 1;
presetsComboLabel = new JLabel(title + ":");
presetsPanel.add(presetsComboLabel, gbc);
- List<Object> entries = Arrays.asList(
- (Object[]) BackupFilesPresetEntry.backupfilesPresetEntries);
+ List<Object> entries = Arrays
+ .asList((Object[]) BackupFilesPresetEntry.backupfilesPresetEntries);
List<String> tooltips = Arrays.asList(
BackupFilesPresetEntry.backupfilesPresetEntryDescriptions);
backupfilesPresetsCombo = JvSwingUtils.buildComboWithTooltips(entries,
{
if (customiseCheckbox.isSelected())
{
- // got here by clicking on customiseCheckbox so don't change the
- // values
+ // got here by clicking on customiseCheckbox so don't change the values
backupfilesCustomOptionsSetEnabled();
}
else
private JPanel initBackupsTabFilenameExamplesPanel()
{
- String title = MessageManager.getString("label.scheme_examples");
+ String title = MessageManager
+ .getString("label.scheme_examples");
TitledBorder tb = new TitledBorder(title);
exampleFilesPanel.setBorder(tb);
exampleFilesPanel.setLayout(new GridBagLayout());
-
backupfilesExampleLabel.setEditable(false);
backupfilesExampleLabel
.setBackground(exampleFilesPanel.getBackground());
}
else
{
- Cache.log.error(
+ Console.error(
"Preset '" + value + "' [key:" + key + "] not implemented");
}
.getSelectedItem();
} catch (Exception ex)
{
- Cache.log.error(
+ Console.error(
"Problem casting Combo entry to IntKeyStringValueEntry.");
e = null;
}
}
protected void setComboIntStringKey(
- JComboBox<Object> backupfilesPresetsCombo2, int key)
+ JComboBox<Object> backupfilesPresetsCombo2,
+ int key)
{
for (int i = 0; i < backupfilesPresetsCombo2.getItemCount(); i++)
{
e = (IntKeyStringValueEntry) backupfilesPresetsCombo2.getItemAt(i);
} catch (Exception ex)
{
- Cache.log.error(
+ Console.error(
"Problem casting Combo entry to IntKeyStringValueEntry. Skipping item. ");
continue;
}
boolean ret = false;
String warningMessage = MessageManager
.getString("label.warning_confirm_change_reverse");
- int confirm = JvOptionPane.showConfirmDialog(Desktop.desktop,
+ int confirm = JvOptionPane.showConfirmDialog(Desktop.getDesktopPane(),
warningMessage,
MessageManager.getString("label.change_increment_decrement"),
JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE);
JPanel jp = new JPanel();
jp.setLayout(new FlowLayout());
- oldBackupFilesLabel.setText(
- MessageManager.getString("label.autodelete_old_backup_files"));
+ oldBackupFilesLabel
+ .setText(MessageManager
+ .getString("label.autodelete_old_backup_files"));
oldBackupFilesLabel.setFont(LABEL_FONT);
oldBackupFilesLabel.setHorizontalAlignment(SwingConstants.LEFT);
jp.add(oldBackupFilesLabel);
}
- // add some extra empty lines to pad out the example files box. ugh, please
- // tell
+ // add some extra empty lines to pad out the example files box. ugh, please tell
// me how to do this better
int remainingLines = lowersurround + uppersurround + 1 - lineNumber;
if (remainingLines > 0)
i = ((Integer) s.getValue()).intValue();
} catch (Exception e)
{
- Cache.log.error(
+ Console.error(
"Exception casting the initial value of s.getValue()");
}
}
i = (Integer) s.getValue();
} catch (Exception e)
{
- Cache.log.error("Failed casting (Integer) JSpinner s.getValue()");
+ Console.error("Failed casting (Integer) JSpinner s.getValue()");
}
return i;
}
private void backupfilesKeepAllSetEnabled(boolean tryEnabled)
{
boolean enabled = tryEnabled && enableBackupFiles.isSelected()
- && customiseCheckbox.isSelected() && suffixTemplate.getText()
+ && customiseCheckbox.isSelected()
+ && suffixTemplate.getText()
.indexOf(BackupFiles.NUM_PLACEHOLDER) > -1;
keepfilesPanel.setEnabled(enabled);
backupfilesKeepAll.setEnabled(enabled);
}
+ public void defaultBrowser_mouseClicked(MouseEvent e)
+ {
+
+ }
+
public void linkURLList_keyTyped(KeyEvent e)
{
}
}
+
+ protected void validateHmmerPath()
+ {
+ }
+
+ protected void validateCygwinPath()
+ {
+ }
+
+ /**
+ * A helper method to add a panel containing a label and a component to a
+ * panel
+ *
+ * @param panel
+ * @param tooltip
+ * @param label
+ * @param valBox
+ */
+ protected static void addtoLayout(JPanel panel, String tooltip,
+ JComponent label, JComponent valBox)
+ {
+ JPanel laypanel = new JPanel(new GridLayout(1, 2));
+ JPanel labPanel = new JPanel(new BorderLayout());
+ JPanel valPanel = new JPanel();
+ labPanel.setBounds(new Rectangle(7, 7, 158, 23));
+ valPanel.setBounds(new Rectangle(172, 7, 270, 23));
+ labPanel.add(label, BorderLayout.WEST);
+ valPanel.add(valBox);
+ laypanel.add(labPanel);
+ laypanel.add(valPanel);
+ valPanel.setToolTipText(tooltip);
+ labPanel.setToolTipText(tooltip);
+ valBox.setToolTipText(tooltip);
+ panel.add(laypanel);
+ panel.validate();
+ }
}
-
*/
package jalview.project;
++
import static jalview.math.RotatableMatrix.Axis.X;
import static jalview.math.RotatableMatrix.Axis.Y;
import static jalview.math.RotatableMatrix.Axis.Z;
-import java.awt.Color;
-import java.awt.Font;
-import java.awt.Rectangle;
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.lang.reflect.InvocationTargetException;
-import java.math.BigInteger;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.IdentityHashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.Vector;
-import java.util.jar.JarEntry;
-import java.util.jar.JarInputStream;
-import java.util.jar.JarOutputStream;
-
-import javax.swing.JInternalFrame;
-import javax.swing.SwingUtilities;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBElement;
-import javax.xml.bind.Marshaller;
-import javax.xml.datatype.DatatypeConfigurationException;
-import javax.xml.datatype.DatatypeFactory;
-import javax.xml.datatype.XMLGregorianCalendar;
-import javax.xml.stream.XMLInputFactory;
-import javax.xml.stream.XMLStreamReader;
+
import jalview.analysis.Conservation;
import jalview.analysis.PCA;
import jalview.analysis.scoremodels.ScoreModels;
import jalview.analysis.scoremodels.SimilarityParams;
+import jalview.api.AlignmentViewPanel;
import jalview.api.FeatureColourI;
import jalview.api.ViewStyleI;
import jalview.api.analysis.ScoreModelI;
import jalview.api.analysis.SimilarityParamsI;
import jalview.api.structures.JalviewStructureDisplayI;
import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.AlignedCodonFrame;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentAnnotation;
import jalview.datamodel.DBRefEntry;
import jalview.datamodel.GeneLocus;
import jalview.datamodel.GraphLine;
+import jalview.datamodel.HiddenMarkovModel;
import jalview.datamodel.PDBEntry;
import jalview.datamodel.Point;
import jalview.datamodel.RnaViewerModel;
import jalview.gui.AlignViewport;
import jalview.gui.AlignmentPanel;
import jalview.gui.AppVarna;
+import jalview.gui.ChimeraViewFrame;
import jalview.gui.Desktop;
+import jalview.gui.FeatureRenderer;
import jalview.gui.JvOptionPane;
import jalview.gui.OOMWarning;
import jalview.gui.PCAPanel;
import jalview.io.BackupFiles;
import jalview.io.DataSourceType;
import jalview.io.FileFormat;
+import jalview.io.HMMFile;
import jalview.io.NewickFile;
import jalview.math.Matrix;
import jalview.math.MatrixI;
import jalview.viewmodel.seqfeatures.FeatureRendererModel;
import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
import jalview.viewmodel.seqfeatures.FeaturesDisplayed;
-import jalview.ws.jws2.Jws2Discoverer;
+import jalview.ws.api.ServiceWithParameters;
+import jalview.ws.jws2.PreferredServiceRegistry;
import jalview.ws.jws2.dm.AAConSettings;
-import jalview.ws.jws2.jabaws2.Jws2Instance;
import jalview.ws.params.ArgumentI;
import jalview.ws.params.AutoCalcSetting;
import jalview.ws.params.WsParamSetI;
import jalview.xml.binding.jalview.ThresholdType;
import jalview.xml.binding.jalview.VAMSAS;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.Rectangle;
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
++import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.math.BigInteger;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.IdentityHashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
++import java.util.Locale;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.Vector;
+import java.util.jar.JarEntry;
+import java.util.jar.JarInputStream;
+import java.util.jar.JarOutputStream;
+
+import javax.swing.JInternalFrame;
+import javax.swing.SwingUtilities;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBElement;
+import javax.xml.bind.Marshaller;
+import javax.xml.datatype.DatatypeConfigurationException;
+import javax.xml.datatype.DatatypeFactory;
+import javax.xml.datatype.XMLGregorianCalendar;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamReader;
-
/**
* Write out the current jalview desktop state as a Jalview XML stream.
*
public class Jalview2XML
{
-- // BH 2018 we add the .jvp binary extension to J2S so that
-- // it will declare that binary when we do the file save from the browser
-
- static
- {
- Platform.addJ2SBinaryType(".jvp?");
- }
-
- private static final String VIEWER_PREFIX = "viewer_";
-
- private static final String RNA_PREFIX = "rna_";
++ // BH 2018 we add the .jvp binary extension to J2S so that
++ // it will declare that binary when we do the file save from the browser
- private static final String HMMER_PREFIX = "hmmer_";
- private static final String UTF_8 = "UTF-8";
- static
- {
- Platform.addJ2SBinaryType(".jvp?");
- }
++ static
++ {
++ Platform.addJ2SBinaryType(".jvp?");
++ }
- /**
- * prefix for recovering datasets for alignments with multiple views where
- * non-existent dataset IDs were written for some views
- */
- private static final String UNIQSEQSETID = "uniqueSeqSetId.";
- private static final String VIEWER_PREFIX = "viewer_";
++ private static final String VIEWER_PREFIX = "viewer_";
- // use this with nextCounter() to make unique names for entities
- private int counter = 0;
- private static final String RNA_PREFIX = "rna_";
++ private static final String RNA_PREFIX = "rna_";
- /*
- * SequenceI reference -> XML ID string in jalview XML. Populated as XML reps
- * of sequence objects are created.
- */
- IdentityHashMap<SequenceI, String> seqsToIds = null;
- private static final String UTF_8 = "UTF-8";
++ private static final String HMMER_PREFIX = "hmmer_";
++ private static final String UTF_8 = "UTF-8";
-- /**
- * jalview XML Sequence ID to jalview sequence object reference (both dataset
- * and alignment sequences. Populated as XML reps of sequence objects are
- * created.)
- */
- Map<String, SequenceI> seqRefIds = null;
- * prefix for recovering datasets for alignments with multiple views where
- * non-existent dataset IDs were written for some views
- */
- private static final String UNIQSEQSETID = "uniqueSeqSetId.";
++ /**
++ * prefix for recovering datasets for alignments with multiple views where
++ * non-existent dataset IDs were written for some views
++ */
++ private static final String UNIQSEQSETID = "uniqueSeqSetId.";
- Map<String, SequenceI> incompleteSeqs = null;
- // use this with nextCounter() to make unique names for entities
- private int counter = 0;
++ // use this with nextCounter() to make unique names for entities
++ private int counter = 0;
- List<SeqFref> frefedSequence = null;
- /*
- * SequenceI reference -> XML ID string in jalview XML. Populated as XML reps
- * of sequence objects are created.
- */
- IdentityHashMap<SequenceI, String> seqsToIds = null;
++ /*
++ * SequenceI reference -> XML ID string in jalview XML. Populated as XML reps
++ * of sequence objects are created.
++ */
++ IdentityHashMap<SequenceI, String> seqsToIds = null;
- boolean raiseGUI = true; // whether errors are raised in dialog boxes or not
- /**
- * jalview XML Sequence ID to jalview sequence object reference (both dataset
- * and alignment sequences. Populated as XML reps of sequence objects are
- * created.)
- */
- Map<String, SequenceI> seqRefIds = null;
++ /**
++ * jalview XML Sequence ID to jalview sequence object reference (both dataset
++ * and alignment sequences. Populated as XML reps of sequence objects are
++ * created.)
++ */
++ Map<String, SequenceI> seqRefIds = null;
- /*
- * Map of reconstructed AlignFrame objects that appear to have come from
- * SplitFrame objects (have a dna/protein complement view).
- */
- private Map<Viewport, AlignFrame> splitFrameCandidates = new HashMap<>();
- Map<String, SequenceI> incompleteSeqs = null;
++ Map<String, SequenceI> incompleteSeqs = null;
- /*
- * Map from displayed rna structure models to their saved session state jar
- * entry names
- */
- private Map<RnaModel, String> rnaSessions = new HashMap<>();
- List<SeqFref> frefedSequence = null;
++ List<SeqFref> frefedSequence = null;
- /**
- * contains last error message (if any) encountered by XML loader.
- */
- String errorMessage = null;
- boolean raiseGUI = true; // whether errors are raised in dialog boxes or not
++ boolean raiseGUI = true; // whether errors are raised in dialog boxes or not
- /**
- * flag to control whether the Jalview2XML_V1 parser should be deferred to if
- * exceptions are raised during project XML parsing
- */
- public boolean attemptversion1parse = false;
- /*
- * Map of reconstructed AlignFrame objects that appear to have come from
- * SplitFrame objects (have a dna/protein complement view).
- */
- private Map<Viewport, AlignFrame> splitFrameCandidates = new HashMap<>();
++ /*
++ * Map of reconstructed AlignFrame objects that appear to have come from
++ * SplitFrame objects (have a dna/protein complement view).
++ */
++ private Map<Viewport, AlignFrame> splitFrameCandidates = new HashMap<>();
-- /*
- * JalviewJS only -- to allow read file bytes to be saved in the
- * created AlignFrame, allowing File | Reload of a project file to work
- *
- * BH 2019 JAL-3436
- */
- private File jarFile;
- * Map from displayed rna structure models to their saved session state jar
- * entry names
- */
- private Map<RnaModel, String> rnaSessions = new HashMap<>();
++ /*
++ * Map from displayed rna structure models to their saved session state jar
++ * entry names
++ */
++ private Map<RnaModel, String> rnaSessions = new HashMap<>();
-- /**
-- * A helper method for safely using the value of an optional attribute that
-- * may be null if not present in the XML. Answers the boolean value, or false
-- * if null.
-- *
-- * @param b
-- * @return
-- */
-- public static boolean safeBoolean(Boolean b)
-- {
-- return b == null ? false : b.booleanValue();
-- }
++ /**
++ * contains last error message (if any) encountered by XML loader.
++ */
++ String errorMessage = null;
-- /**
-- * A helper method for safely using the value of an optional attribute that
-- * may be null if not present in the XML. Answers the integer value, or zero
-- * if null.
-- *
-- * @param i
-- * @return
-- */
-- public static int safeInt(Integer i)
-- {
-- return i == null ? 0 : i.intValue();
-- }
++ /**
++ * flag to control whether the Jalview2XML_V1 parser should be deferred to if
++ * exceptions are raised during project XML parsing
++ */
++ public boolean attemptversion1parse = false;
-- /**
-- * A helper method for safely using the value of an optional attribute that
-- * may be null if not present in the XML. Answers the float value, or zero if
-- * null.
-- *
-- * @param f
-- * @return
-- */
-- public static float safeFloat(Float f)
-- {
-- return f == null ? 0f : f.floatValue();
-- }
++ /*
++ * JalviewJS only -- to allow read file bytes to be saved in the
++ * created AlignFrame, allowing File | Reload of a project file to work
++ *
++ * BH 2019 JAL-3436
++ */
++ private File jarFile;
-- /**
-- * create/return unique hash string for sq
-- *
-- * @param sq
-- * @return new or existing unique string for sq
-- */
-- String seqHash(SequenceI sq)
-- {
-- if (seqsToIds == null)
++ /**
++ * A helper method for safely using the value of an optional attribute that
++ * may be null if not present in the XML. Answers the boolean value, or false
++ * if null.
++ *
++ * @param b
++ * @return
++ */
++ public static boolean safeBoolean(Boolean b)
{
-- initSeqRefs();
++ return b == null ? false : b.booleanValue();
}
-- if (seqsToIds.containsKey(sq))
++
++ /**
++ * A helper method for safely using the value of an optional attribute that
++ * may be null if not present in the XML. Answers the integer value, or zero
++ * if null.
++ *
++ * @param i
++ * @return
++ */
++ public static int safeInt(Integer i)
{
-- return seqsToIds.get(sq);
++ return i == null ? 0 : i.intValue();
}
-- else
++
++ /**
++ * A helper method for safely using the value of an optional attribute that
++ * may be null if not present in the XML. Answers the float value, or zero if
++ * null.
++ *
++ * @param f
++ * @return
++ */
++ public static float safeFloat(Float f)
{
-- // create sequential key
-- String key = "sq" + (seqsToIds.size() + 1);
-- key = makeHashCode(sq, key); // check we don't have an external reference
-- // for it already.
-- seqsToIds.put(sq, key);
-- return key;
++ return f == null ? 0f : f.floatValue();
}
-- }
-- void initSeqRefs()
-- {
-- if (seqsToIds == null)
++ /**
++ * create/return unique hash string for sq
++ *
++ * @param sq
++ * @return new or existing unique string for sq
++ */
++ String seqHash(SequenceI sq)
{
-- seqsToIds = new IdentityHashMap<>();
++ if (seqsToIds == null)
++ {
++ initSeqRefs();
++ }
++ if (seqsToIds.containsKey(sq))
++ {
++ return seqsToIds.get(sq);
++ }
++ else
++ {
++ // create sequential key
++ String key = "sq" + (seqsToIds.size() + 1);
++ key = makeHashCode(sq, key); // check we don't have an external reference
++ // for it already.
++ seqsToIds.put(sq, key);
++ return key;
++ }
}
-- if (seqRefIds == null)
++
++ void initSeqRefs()
{
-- seqRefIds = new HashMap<>();
++ if (seqsToIds == null)
++ {
++ seqsToIds = new IdentityHashMap<>();
++ }
++ if (seqRefIds == null)
++ {
++ seqRefIds = new HashMap<>();
++ }
++ if (incompleteSeqs == null)
++ {
++ incompleteSeqs = new HashMap<>();
++ }
++ if (frefedSequence == null)
++ {
++ frefedSequence = new ArrayList<>();
++ }
}
-- if (incompleteSeqs == null)
++
++ public Jalview2XML()
{
-- incompleteSeqs = new HashMap<>();
}
-- if (frefedSequence == null)
++
++ public Jalview2XML(boolean raiseGUI)
{
-- frefedSequence = new ArrayList<>();
++ this.raiseGUI = raiseGUI;
}
-- }
-- public Jalview2XML()
-- {
-- }
++ /**
++ * base class for resolving forward references to sequences by their ID
++ *
++ * @author jprocter
++ *
++ */
++ abstract class SeqFref
++ {
++ String sref;
++
++ String type;
++
++ public SeqFref(String _sref, String type)
++ {
++ sref = _sref;
++ this.type = type;
++ }
++
++ public String getSref()
++ {
++ return sref;
++ }
++
++ public SequenceI getSrefSeq()
++ {
++ return seqRefIds.get(sref);
++ }
++
++ public boolean isResolvable()
++ {
++ return seqRefIds.get(sref) != null;
++ }
++
++ public SequenceI getSrefDatasetSeq()
++ {
++ SequenceI sq = seqRefIds.get(sref);
++ if (sq != null)
++ {
++ while (sq.getDatasetSequence() != null)
++ {
++ sq = sq.getDatasetSequence();
++ }
++ }
++ return sq;
++ }
++
++ /**
++ * @return true if the forward reference was fully resolved
++ */
++ abstract boolean resolve();
++
++ @Override
++ public String toString()
++ {
++ return type + " reference to " + sref;
++ }
++ }
-- public Jalview2XML(boolean raiseGUI)
-- {
-- this.raiseGUI = raiseGUI;
-- }
++ /**
++ * create forward reference for a mapping
++ *
++ * @param sref
++ * @param _jmap
++ * @return
++ */
++ protected SeqFref newMappingRef(final String sref,
++ final jalview.datamodel.Mapping _jmap)
++ {
++ SeqFref fref = new SeqFref(sref, "Mapping")
++ {
++ public jalview.datamodel.Mapping jmap = _jmap;
++
++ @Override
++ boolean resolve()
++ {
++ SequenceI seq = getSrefDatasetSeq();
++ if (seq == null)
++ {
++ return false;
++ }
++ jmap.setTo(seq);
++ return true;
++ }
++ };
++ return fref;
++ }
++
++ protected SeqFref newAlcodMapRef(final String sref,
++ final AlignedCodonFrame _cf,
++ final jalview.datamodel.Mapping _jmap)
++ {
++
++ SeqFref fref = new SeqFref(sref, "Codon Frame")
++ {
++ AlignedCodonFrame cf = _cf;
++
++ public jalview.datamodel.Mapping mp = _jmap;
++
++ @Override
++ public boolean isResolvable()
++ {
++ return super.isResolvable() && mp.getTo() != null;
++ }
++
++ @Override
++ boolean resolve()
++ {
++ SequenceI seq = getSrefDatasetSeq();
++ if (seq == null)
++ {
++ return false;
++ }
++ cf.addMap(seq, mp.getTo(), mp.getMap());
++ return true;
++ }
++ };
++ return fref;
++ }
++
++ protected void resolveFrefedSequences()
++ {
++ Iterator<SeqFref> nextFref = frefedSequence.iterator();
++ int toresolve = frefedSequence.size();
++ int unresolved = 0, failedtoresolve = 0;
++ while (nextFref.hasNext())
++ {
++ SeqFref ref = nextFref.next();
++ if (ref.isResolvable())
++ {
++ try
++ {
++ if (ref.resolve())
++ {
++ nextFref.remove();
++ }
++ else
++ {
++ failedtoresolve++;
++ }
++ } catch (Exception x)
++ {
++ System.err.println(
++ "IMPLEMENTATION ERROR: Failed to resolve forward reference for sequence "
++ + ref.getSref());
++ x.printStackTrace();
++ failedtoresolve++;
++ }
++ }
++ else
++ {
++ unresolved++;
++ }
++ }
++ if (unresolved > 0)
++ {
++ System.err.println("Jalview Project Import: There were " + unresolved
++ + " forward references left unresolved on the stack.");
++ }
++ if (failedtoresolve > 0)
++ {
++ System.err.println("SERIOUS! " + failedtoresolve
++ + " resolvable forward references failed to resolve.");
++ }
++ if (incompleteSeqs != null && incompleteSeqs.size() > 0)
++ {
++ System.err.println(
++ "Jalview Project Import: There are " + incompleteSeqs.size()
++ + " sequences which may have incomplete metadata.");
++ if (incompleteSeqs.size() < 10)
++ {
++ for (SequenceI s : incompleteSeqs.values())
++ {
++ System.err.println(s.toString());
++ }
++ }
++ else
++ {
++ System.err.println(
++ "Too many to report. Skipping output of incomplete sequences.");
++ }
++ }
++ }
-- /**
-- * base class for resolving forward references to sequences by their ID
-- *
-- * @author jprocter
-- *
-- */
-- abstract class SeqFref
-- {
-- String sref;
++ /**
++ * This maintains a map of viewports, the key being the seqSetId. Important to
++ * set historyItem and redoList for multiple views
++ */
++ Map<String, AlignViewport> viewportsAdded = new HashMap<>();
-- String type;
++ Map<String, AlignmentAnnotation> annotationIds = new HashMap<>();
-- public SeqFref(String _sref, String type)
-- {
-- sref = _sref;
-- this.type = type;
++ String uniqueSetSuffix = "";
++
++ /**
++ * List of pdbfiles added to Jar
++ */
++ List<String> pdbfiles = null;
++
++ // SAVES SEVERAL ALIGNMENT WINDOWS TO SAME JARFILE
++ public void saveState(File statefile)
++ {
++ FileOutputStream fos = null;
++
++ try
++ {
++
++ fos = new FileOutputStream(statefile);
++
++ JarOutputStream jout = new JarOutputStream(fos);
++ saveState(jout);
++ fos.close();
++
++ } catch (Exception e)
++ {
++ Console.error("Couln't write Jalview state to " + statefile, e);
++ // TODO: inform user of the problem - they need to know if their data was
++ // not saved !
++ if (errorMessage == null)
++ {
++ errorMessage = "Did't write Jalview Archive to output file '"
++ + statefile + "' - See console error log for details";
++ }
++ else
++ {
++ errorMessage += "(Didn't write Jalview Archive to output file '"
++ + statefile + ")";
++ }
++ e.printStackTrace();
++ } finally
++ {
++ if (fos != null)
++ {
++ try
++ {
++ fos.close();
++ } catch (IOException e)
++ {
++ // ignore
++ }
++ }
++ }
++ reportErrors();
}
-- public String getSref()
++ /**
++ * Writes a jalview project archive to the given Jar output stream.
++ *
++ * @param jout
++ */
++ public void saveState(JarOutputStream jout)
{
-- return sref;
++ AlignFrame[] frames = Desktop.getAlignFrames();
++
++ if (frames == null)
++ {
++ return;
++ }
++ saveAllFrames(Arrays.asList(frames), jout);
}
-- public SequenceI getSrefSeq()
-- {
-- return seqRefIds.get(sref);
++ /**
++ * core method for storing state for a set of AlignFrames.
++ *
++ * @param frames
++ * - frames involving all data to be exported (including those
++ * contained in splitframes, though not the split frames themselves)
++ * @param jout
++ * - project output stream
++ */
++ private void saveAllFrames(List<AlignFrame> frames, JarOutputStream jout)
++ {
++ Hashtable<String, AlignFrame> dsses = new Hashtable<>();
++
++ /*
++ * ensure cached data is clear before starting
++ */
++ // todo tidy up seqRefIds, seqsToIds initialisation / reset
++ rnaSessions.clear();
++ splitFrameCandidates.clear();
++
++ try
++ {
++
++ // NOTE UTF-8 MUST BE USED FOR WRITING UNICODE CHARS
++ // //////////////////////////////////////////////////
++
++ List<String> shortNames = new ArrayList<>();
++ List<String> viewIds = new ArrayList<>();
++
++ // REVERSE ORDER
++ for (int i = frames.size() - 1; i > -1; i--)
++ {
++ AlignFrame af = frames.get(i);
++ AlignViewport vp = af.getViewport();
++ // skip ?
++ if (skipList != null && skipList
++ .containsKey(vp.getSequenceSetId()))
++ {
++ continue;
++ }
++
++ String shortName = makeFilename(af, shortNames);
++
++ AlignmentI alignment = vp.getAlignment();
++ List<? extends AlignmentViewPanel> panels = af.getAlignPanels();
++ int apSize = panels.size();
++
++ for (int ap = 0; ap < apSize; ap++)
++ {
++ AlignmentPanel apanel = (AlignmentPanel) panels.get(ap);
++ String fileName = apSize == 1 ? shortName : ap + shortName;
++ if (!fileName.endsWith(".xml"))
++ {
++ fileName = fileName + ".xml";
++ }
++
++ saveState(apanel, fileName, jout, viewIds);
++
++ }
++ if (apSize > 0)
++ {
++ // BH moved next bit out of inner loop, not that it really matters.
++ // so we are testing to make sure we actually have an alignment,
++ // apparently.
++ String dssid = getDatasetIdRef(alignment.getDataset());
++ if (!dsses.containsKey(dssid))
++ {
++ // We have not already covered this data by reference from another
++ // frame.
++ dsses.put(dssid, af);
++ }
++ }
++ }
++
++ writeDatasetFor(dsses, "" + jout.hashCode() + " " + uniqueSetSuffix,
++ jout);
++
++ try
++ {
++ jout.flush();
++ } catch (Exception foo)
++ {
++ }
++ jout.close();
++ } catch (Exception ex)
++ {
++ // TODO: inform user of the problem - they need to know if their data was
++ // not saved !
++ if (errorMessage == null)
++ {
++ errorMessage = "Couldn't write Jalview Archive - see error output for details";
++ }
++ ex.printStackTrace();
++ }
}
-- public boolean isResolvable()
-- {
-- return seqRefIds.get(sref) != null;
++ /**
++ * Generates a distinct file name, based on the title of the AlignFrame, by
++ * appending _n for increasing n until an unused name is generated. The new
++ * name (without its extension) is added to the list.
++ *
++ * @param af
++ * @param namesUsed
++ * @return the generated name, with .xml extension
++ */
++ protected String makeFilename(AlignFrame af, List<String> namesUsed)
++ {
++ String shortName = af.getTitle();
++
++ if (shortName.indexOf(File.separatorChar) > -1)
++ {
++ shortName = shortName
++ .substring(shortName.lastIndexOf(File.separatorChar) + 1);
++ }
++
++ int count = 1;
++
++ while (namesUsed.contains(shortName))
++ {
++ if (shortName.endsWith("_" + (count - 1)))
++ {
++ shortName = shortName.substring(0, shortName.lastIndexOf("_"));
++ }
++
++ shortName = shortName.concat("_" + count);
++ count++;
++ }
++
++ namesUsed.add(shortName);
++
++ if (!shortName.endsWith(".xml"))
++ {
++ shortName = shortName + ".xml";
++ }
++ return shortName;
++ }
++
++ // USE THIS METHOD TO SAVE A SINGLE ALIGNMENT WINDOW
++ public boolean saveAlignment(AlignFrame af, String jarFile,
++ String fileName)
++ {
++ try
++ {
++ // create backupfiles object and get new temp filename destination
++ boolean doBackup = BackupFiles.getEnabled();
++ BackupFiles backupfiles = doBackup ? new BackupFiles(jarFile) : null;
++ FileOutputStream fos = new FileOutputStream(doBackup ?
++ backupfiles.getTempFilePath() : jarFile);
++
++ JarOutputStream jout = new JarOutputStream(fos);
++ List<AlignFrame> frames = new ArrayList<>();
++
++ // resolve splitframes
++ if (af.getViewport().getCodingComplement() != null)
++ {
++ frames = ((SplitFrame) af.getSplitViewContainer()).getAlignFrames();
++ }
++ else
++ {
++ frames.add(af);
++ }
++ saveAllFrames(frames, jout);
++ try
++ {
++ jout.flush();
++ } catch (Exception foo)
++ {
++ }
++ jout.close();
++ boolean success = true;
++
++ if (doBackup)
++ {
++ backupfiles.setWriteSuccess(success);
++ success = backupfiles.rollBackupsAndRenameTempFile();
++ }
++
++ return success;
++ } catch (Exception ex)
++ {
++ errorMessage = "Couldn't Write alignment view to Jalview Archive - see error output for details";
++ ex.printStackTrace();
++ return false;
++ }
}
-- public SequenceI getSrefDatasetSeq()
++ /**
++ * Each AlignFrame has a single data set associated with it. Note that none of
++ * these frames are split frames, because Desktop.getAlignFrames() collects
++ * top and bottom separately here.
++ *
++ * @param dsses
++ * @param fileName
++ * @param jout
++ */
++ private void writeDatasetFor(Hashtable<String, AlignFrame> dsses,
++ String fileName, JarOutputStream jout)
{
-- SequenceI sq = seqRefIds.get(sref);
-- if (sq != null)
-- {
-- while (sq.getDatasetSequence() != null)
-- {
-- sq = sq.getDatasetSequence();
-- }
-- }
-- return sq;
++
++ // Note that in saveAllFrames we have associated each specific dataset to
++ // ONE of its associated frames.
++ for (String dssids : dsses.keySet())
++ {
++ AlignFrame _af = dsses.get(dssids);
++ String jfileName = fileName + " Dataset for " + _af.getTitle();
++ if (!jfileName.endsWith(".xml"))
++ {
++ jfileName = jfileName + ".xml";
++ }
++ saveState(_af.alignPanel, jfileName, true, jout, null);
++ }
}
/**
-- * @return true if the forward reference was fully resolved
++ * create a JalviewModel from an alignment view and marshall it to a
++ * JarOutputStream
++ *
++ * @param ap
++ * panel to create jalview model for
++ * @param fileName
++ * name of alignment panel written to output stream
++ * @param jout
++ * jar output stream
++ * @param viewIds
++ * @param out
++ * jar entry name
*/
-- abstract boolean resolve();
--
-- @Override
-- public String toString()
++ protected JalviewModel saveState(AlignmentPanel ap, String fileName,
++ JarOutputStream jout, List<String> viewIds)
{
-- return type + " reference to " + sref;
++ return saveState(ap, fileName, false, jout, viewIds);
}
-- }
-- /**
-- * create forward reference for a mapping
-- *
-- * @param sref
-- * @param _jmap
-- * @return
-- */
- protected SeqFref newMappingRef(final String sref,
- final jalview.datamodel.Mapping _jmap)
- {
- SeqFref fref = new SeqFref(sref, "Mapping")
- {
- public jalview.datamodel.Mapping jmap = _jmap;
- public SeqFref newMappingRef(final String sref,
- final jalview.datamodel.Mapping _jmap)
- {
- SeqFref fref = new SeqFref(sref, "Mapping")
- {
- public jalview.datamodel.Mapping jmap = _jmap;
++ /**
++ * create a JalviewModel from an alignment view and marshall it to a
++ * JarOutputStream
++ *
++ * @param ap
++ * panel to create jalview model for
++ * @param fileName
++ * name of alignment panel written to output stream
++ * @param storeDS
++ * when true, only write the dataset for the alignment, not the data
++ * associated with the view.
++ * @param jout
++ * jar output stream
++ * @param out
++ * jar entry name
++ */
++ protected JalviewModel saveState(AlignmentPanel ap, String fileName,
++ boolean storeDS, JarOutputStream jout, List<String> viewIds)
++ {
++ if (viewIds == null)
++ {
++ viewIds = new ArrayList<>();
++ }
++
++ initSeqRefs();
++
++ List<UserColourScheme> userColours = new ArrayList<>();
++
++ AlignViewport av = ap.av;
++ ViewportRanges vpRanges = av.getRanges();
++
++ final ObjectFactory objectFactory = new ObjectFactory();
++ JalviewModel object = objectFactory.createJalviewModel();
++ object.setVamsasModel(new VAMSAS());
++
++ // object.setCreationDate(new java.util.Date(System.currentTimeMillis()));
++ try
++ {
++ GregorianCalendar c = new GregorianCalendar();
++ DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
++ XMLGregorianCalendar now = datatypeFactory.newXMLGregorianCalendar(c);// gregorianCalendar);
++ object.setCreationDate(now);
++ } catch (DatatypeConfigurationException e)
++ {
++ System.err.println("error writing date: " + e.toString());
++ }
++ object.setVersion(Cache.getDefault("VERSION", "Development Build"));
++
++ /**
++ * rjal is full height alignment, jal is actual alignment with full metadata
++ * but excludes hidden sequences.
++ */
++ jalview.datamodel.AlignmentI rjal = av.getAlignment(), jal = rjal;
++
++ if (av.hasHiddenRows())
++ {
++ rjal = jal.getHiddenSequences().getFullAlignment();
++ }
++
++ SequenceSet vamsasSet = new SequenceSet();
++ Sequence vamsasSeq;
++ // JalviewModelSequence jms = new JalviewModelSequence();
++
++ vamsasSet.setGapChar(jal.getGapCharacter() + "");
++
++ if (jal.getDataset() != null)
++ {
++ // dataset id is the dataset's hashcode
++ vamsasSet.setDatasetId(getDatasetIdRef(jal.getDataset()));
++ if (storeDS)
++ {
++ // switch jal and the dataset
++ jal = jal.getDataset();
++ rjal = jal;
++ }
++ }
++ if (jal.getProperties() != null)
++ {
++ Enumeration en = jal.getProperties().keys();
++ while (en.hasMoreElements())
++ {
++ String key = en.nextElement().toString();
++ SequenceSetProperties ssp = new SequenceSetProperties();
++ ssp.setKey(key);
++ ssp.setValue(jal.getProperties().get(key).toString());
++ // vamsasSet.addSequenceSetProperties(ssp);
++ vamsasSet.getSequenceSetProperties().add(ssp);
++ }
++ }
++
++ JSeq jseq;
++ Set<String> calcIdSet = new HashSet<>();
++ // record the set of vamsas sequence XML POJO we create.
++ HashMap<String, Sequence> vamsasSetIds = new HashMap<>();
++ // SAVE SEQUENCES
++ for (final SequenceI jds : rjal.getSequences())
++ {
++ final SequenceI jdatasq = jds.getDatasetSequence() == null ? jds
++ : jds.getDatasetSequence();
++ String id = seqHash(jds);
++ if (vamsasSetIds.get(id) == null)
++ {
++ if (seqRefIds.get(id) != null && !storeDS)
++ {
++ // This happens for two reasons: 1. multiple views are being
++ // serialised.
++ // 2. the hashCode has collided with another sequence's code. This
++ // DOES
++ // HAPPEN! (PF00072.15.stk does this)
++ // JBPNote: Uncomment to debug writing out of files that do not read
++ // back in due to ArrayOutOfBoundExceptions.
++ // System.err.println("vamsasSeq backref: "+id+"");
++ // System.err.println(jds.getName()+"
++ // "+jds.getStart()+"-"+jds.getEnd()+" "+jds.getSequenceAsString());
++ // System.err.println("Hashcode: "+seqHash(jds));
++ // SequenceI rsq = (SequenceI) seqRefIds.get(id + "");
++ // System.err.println(rsq.getName()+"
++ // "+rsq.getStart()+"-"+rsq.getEnd()+" "+rsq.getSequenceAsString());
++ // System.err.println("Hashcode: "+seqHash(rsq));
++ }
++ else
++ {
++ vamsasSeq = createVamsasSequence(id, jds);
++ // vamsasSet.addSequence(vamsasSeq);
++ vamsasSet.getSequence().add(vamsasSeq);
++ vamsasSetIds.put(id, vamsasSeq);
++ seqRefIds.put(id, jds);
++ }
++ }
++ jseq = new JSeq();
++ jseq.setStart(jds.getStart());
++ jseq.setEnd(jds.getEnd());
++ jseq.setColour(av.getSequenceColour(jds).getRGB());
++
++ jseq.setId(id); // jseq id should be a string not a number
++ if (!storeDS)
++ {
++ // Store any sequences this sequence represents
++ if (av.hasHiddenRows())
++ {
++ // use rjal, contains the full height alignment
++ jseq.setHidden(
++ av.getAlignment().getHiddenSequences().isHidden(jds));
++
++ if (av.isHiddenRepSequence(jds))
++ {
++ jalview.datamodel.SequenceI[] reps = av
++ .getRepresentedSequences(jds).getSequencesInOrder(rjal);
++
++ for (int h = 0; h < reps.length; h++)
++ {
++ if (reps[h] != jds)
++ {
++ // jseq.addHiddenSequences(rjal.findIndex(reps[h]));
++ jseq.getHiddenSequences().add(rjal.findIndex(reps[h]));
++ }
++ }
++ }
++ }
++ // mark sequence as reference - if it is the reference for this view
++ if (jal.hasSeqrep())
++ {
++ jseq.setViewreference(jds == jal.getSeqrep());
++ }
++ }
++
++ // TODO: omit sequence features from each alignment view's XML dump if we
++ // are storing dataset
++ List<SequenceFeature> sfs = jds.getSequenceFeatures();
++ for (SequenceFeature sf : sfs)
++ {
++ // Features features = new Features();
++ Feature features = new Feature();
++
++ features.setBegin(sf.getBegin());
++ features.setEnd(sf.getEnd());
++ features.setDescription(sf.getDescription());
++ features.setType(sf.getType());
++ features.setFeatureGroup(sf.getFeatureGroup());
++ features.setScore(sf.getScore());
++ if (sf.links != null)
++ {
++ for (int l = 0; l < sf.links.size(); l++)
++ {
++ OtherData keyValue = new OtherData();
++ keyValue.setKey("LINK_" + l);
++ keyValue.setValue(sf.links.elementAt(l).toString());
++ // features.addOtherData(keyValue);
++ features.getOtherData().add(keyValue);
++ }
++ }
++ if (sf.otherDetails != null)
++ {
++ /*
++ * save feature attributes, which may be simple strings or
++ * map valued (have sub-attributes)
++ */
++ for (Entry<String, Object> entry : sf.otherDetails.entrySet())
++ {
++ String key = entry.getKey();
++ Object value = entry.getValue();
++ if (value instanceof Map<?, ?>)
++ {
++ for (Entry<String, Object> subAttribute : ((Map<String, Object>) value)
++ .entrySet())
++ {
++ OtherData otherData = new OtherData();
++ otherData.setKey(key);
++ otherData.setKey2(subAttribute.getKey());
++ otherData.setValue(subAttribute.getValue().toString());
++ // features.addOtherData(otherData);
++ features.getOtherData().add(otherData);
++ }
++ }
++ else
++ {
++ OtherData otherData = new OtherData();
++ otherData.setKey(key);
++ otherData.setValue(value.toString());
++ // features.addOtherData(otherData);
++ features.getOtherData().add(otherData);
++ }
++ }
++ }
++
++ // jseq.addFeatures(features);
++ jseq.getFeatures().add(features);
++ }
++
++ /*
++ * save PDB entries for sequence
++ */
++ if (jdatasq.getAllPDBEntries() != null)
++ {
++ Enumeration<PDBEntry> en = jdatasq.getAllPDBEntries().elements();
++ while (en.hasMoreElements())
++ {
++ Pdbids pdb = new Pdbids();
++ jalview.datamodel.PDBEntry entry = en.nextElement();
++
++ String pdbId = entry.getId();
++ pdb.setId(pdbId);
++ pdb.setType(entry.getType());
++
++ /*
++ * Store any structure views associated with this sequence. This
++ * section copes with duplicate entries in the project, so a dataset
++ * only view *should* be coped with sensibly.
++ */
++ // This must have been loaded, is it still visible?
++ JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
++ String matchedFile = null;
++ for (int f = frames.length - 1; f > -1; f--)
++ {
++ if (frames[f] instanceof StructureViewerBase)
++ {
++ StructureViewerBase viewFrame = (StructureViewerBase) frames[f];
++ matchedFile = saveStructureViewer(ap, jds, pdb, entry,
++ viewIds, matchedFile, viewFrame);
++ /*
++ * Only store each structure viewer's state once in the project
++ * jar. First time through only (storeDS==false)
++ */
++ String viewId = viewFrame.getViewId();
++ String viewerType = viewFrame.getViewerType().toString();
++ if (!storeDS && !viewIds.contains(viewId))
++ {
++ viewIds.add(viewId);
++ File viewerState = viewFrame.saveSession();
++ if (viewerState != null)
++ {
++ copyFileToJar(jout, viewerState.getPath(),
++ getViewerJarEntryName(viewId), viewerType);
++ }
++ else
++ {
++ Console.error(
++ "Failed to save viewer state for " + viewerType);
++ }
++ }
++ }
++ }
++
++ if (matchedFile != null || entry.getFile() != null)
++ {
++ if (entry.getFile() != null)
++ {
++ // use entry's file
++ matchedFile = entry.getFile();
++ }
++ pdb.setFile(matchedFile); // entry.getFile());
++ if (pdbfiles == null)
++ {
++ pdbfiles = new ArrayList<>();
++ }
++
++ if (!pdbfiles.contains(pdbId))
++ {
++ pdbfiles.add(pdbId);
++ copyFileToJar(jout, matchedFile, pdbId, pdbId);
++ }
++ }
++
++ Enumeration<String> props = entry.getProperties();
++ if (props.hasMoreElements())
++ {
++ // PdbentryItem item = new PdbentryItem();
++ while (props.hasMoreElements())
++ {
++ Property prop = new Property();
++ String key = props.nextElement();
++ prop.setName(key);
++ prop.setValue(entry.getProperty(key).toString());
++ // item.addProperty(prop);
++ pdb.getProperty().add(prop);
++ }
++ // pdb.addPdbentryItem(item);
++ }
++
++ // jseq.addPdbids(pdb);
++ jseq.getPdbids().add(pdb);
++ }
++ }
++
++ saveRnaViewers(jout, jseq, jds, viewIds, ap, storeDS);
++
++ if (jds.hasHMMProfile())
++ {
++ saveHmmerProfile(jout, jseq, jds);
++ }
++ // jms.addJSeq(jseq);
++ object.getJSeq().add(jseq);
++ }
++
++ if (!storeDS && av.hasHiddenRows())
++ {
++ jal = av.getAlignment();
++ }
++ // SAVE MAPPINGS
++ // FOR DATASET
++ if (storeDS && jal.getCodonFrames() != null)
++ {
++ List<AlignedCodonFrame> jac = jal.getCodonFrames();
++ for (AlignedCodonFrame acf : jac)
++ {
++ AlcodonFrame alc = new AlcodonFrame();
++ if (acf.getProtMappings() != null
++ && acf.getProtMappings().length > 0)
++ {
++ boolean hasMap = false;
++ SequenceI[] dnas = acf.getdnaSeqs();
++ jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
++ for (int m = 0; m < pmaps.length; m++)
++ {
++ AlcodMap alcmap = new AlcodMap();
++ alcmap.setDnasq(seqHash(dnas[m]));
++ alcmap.setMapping(
++ createVamsasMapping(pmaps[m], dnas[m], null, false));
++ // alc.addAlcodMap(alcmap);
++ alc.getAlcodMap().add(alcmap);
++ hasMap = true;
++ }
++ if (hasMap)
++ {
++ // vamsasSet.addAlcodonFrame(alc);
++ vamsasSet.getAlcodonFrame().add(alc);
++ }
++ }
++ // TODO: delete this ? dead code from 2.8.3->2.9 ?
++ // {
++ // AlcodonFrame alc = new AlcodonFrame();
++ // vamsasSet.addAlcodonFrame(alc);
++ // for (int p = 0; p < acf.aaWidth; p++)
++ // {
++ // Alcodon cmap = new Alcodon();
++ // if (acf.codons[p] != null)
++ // {
++ // // Null codons indicate a gapped column in the translated peptide
++ // // alignment.
++ // cmap.setPos1(acf.codons[p][0]);
++ // cmap.setPos2(acf.codons[p][1]);
++ // cmap.setPos3(acf.codons[p][2]);
++ // }
++ // alc.addAlcodon(cmap);
++ // }
++ // if (acf.getProtMappings() != null
++ // && acf.getProtMappings().length > 0)
++ // {
++ // SequenceI[] dnas = acf.getdnaSeqs();
++ // jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
++ // for (int m = 0; m < pmaps.length; m++)
++ // {
++ // AlcodMap alcmap = new AlcodMap();
++ // alcmap.setDnasq(seqHash(dnas[m]));
++ // alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
++ // false));
++ // alc.addAlcodMap(alcmap);
++ // }
++ // }
++ }
++ }
++
++ // SAVE TREES
++ // /////////////////////////////////
++ if (!storeDS && av.getCurrentTree() != null)
++ {
++ // FIND ANY ASSOCIATED TREES
++ // NOT IMPLEMENTED FOR HEADLESS STATE AT PRESENT
++ if (Desktop.getDesktopPane() != null)
++ {
++ JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
++
++ for (int t = 0; t < frames.length; t++)
++ {
++ if (frames[t] instanceof TreePanel)
++ {
++ TreePanel tp = (TreePanel) frames[t];
++
++ if (tp.getTreeCanvas().getViewport().getAlignment() == jal)
++ {
++ JalviewModel.Tree tree = new JalviewModel.Tree();
++ tree.setTitle(tp.getTitle());
++ tree.setCurrentTree((av.getCurrentTree() == tp.getTree()));
++ tree.setNewick(tp.getTree().print());
++ tree.setThreshold(tp.getTreeCanvas().getThreshold());
++
++ tree.setFitToWindow(tp.fitToWindow.getState());
++ tree.setFontName(tp.getTreeFont().getName());
++ tree.setFontSize(tp.getTreeFont().getSize());
++ tree.setFontStyle(tp.getTreeFont().getStyle());
++ tree.setMarkUnlinked(tp.placeholdersMenu.getState());
++
++ tree.setShowBootstrap(tp.bootstrapMenu.getState());
++ tree.setShowDistances(tp.distanceMenu.getState());
++
++ tree.setHeight(tp.getHeight());
++ tree.setWidth(tp.getWidth());
++ tree.setXpos(tp.getX());
++ tree.setYpos(tp.getY());
++ tree.setId(makeHashCode(tp, null));
++ tree.setLinkToAllViews(
++ tp.getTreeCanvas().isApplyToAllViews());
++
++ // jms.addTree(tree);
++ object.getTree().add(tree);
++ }
++ }
++ }
++ }
++ }
++
++ /*
++ * save PCA viewers
++ */
++ if (!storeDS && Desktop.getDesktopPane() != null)
++ {
++ for (JInternalFrame frame : Desktop.getDesktopPane().getAllFrames())
++ {
++ if (frame instanceof PCAPanel)
++ {
++ PCAPanel panel = (PCAPanel) frame;
++ if (panel.getAlignViewport().getAlignment() == jal)
++ {
++ savePCA(panel, object);
++ }
++ }
++ }
++ }
++
++ // SAVE ANNOTATIONS
++ /**
++ * store forward refs from an annotationRow to any groups
++ */
++ IdentityHashMap<SequenceGroup, String> groupRefs = new IdentityHashMap<>();
++ if (storeDS)
++ {
++ for (SequenceI sq : jal.getSequences())
++ {
++ // Store annotation on dataset sequences only
++ AlignmentAnnotation[] aa = sq.getAnnotation();
++ if (aa != null && aa.length > 0)
++ {
++ storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
++ vamsasSet);
++ }
++ }
++ }
++ else
++ {
++ if (jal.getAlignmentAnnotation() != null)
++ {
++ // Store the annotation shown on the alignment.
++ AlignmentAnnotation[] aa = jal.getAlignmentAnnotation();
++ storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
++ vamsasSet);
++ }
++ }
++ // SAVE GROUPS
++ if (jal.getGroups() != null)
++ {
++ JGroup[] groups = new JGroup[jal.getGroups().size()];
++ int i = -1;
++ for (jalview.datamodel.SequenceGroup sg : jal.getGroups())
++ {
++ JGroup jGroup = new JGroup();
++ groups[++i] = jGroup;
++
++ jGroup.setStart(sg.getStartRes());
++ jGroup.setEnd(sg.getEndRes());
++ jGroup.setName(sg.getName());
++ if (groupRefs.containsKey(sg))
++ {
++ // group has references so set its ID field
++ jGroup.setId(groupRefs.get(sg));
++ }
++ ColourSchemeI colourScheme = sg.getColourScheme();
++ if (colourScheme != null)
++ {
++ ResidueShaderI groupColourScheme = sg.getGroupColourScheme();
++ if (groupColourScheme.conservationApplied())
++ {
++ jGroup.setConsThreshold(groupColourScheme.getConservationInc());
++
++ if (colourScheme instanceof jalview.schemes.UserColourScheme)
++ {
++ jGroup.setColour(
++ setUserColourScheme(colourScheme, userColours,
++ object));
++ }
++ else
++ {
++ jGroup.setColour(colourScheme.getSchemeName());
++ }
++ }
++ else if (colourScheme instanceof jalview.schemes.AnnotationColourGradient)
++ {
++ jGroup.setColour("AnnotationColourGradient");
++ jGroup.setAnnotationColours(constructAnnotationColours(
++ (jalview.schemes.AnnotationColourGradient) colourScheme,
++ userColours, object));
++ }
++ else if (colourScheme instanceof jalview.schemes.UserColourScheme)
++ {
++ jGroup.setColour(
++ setUserColourScheme(colourScheme, userColours, object));
++ }
++ else
++ {
++ jGroup.setColour(colourScheme.getSchemeName());
++ }
++
++ jGroup.setPidThreshold(groupColourScheme.getThreshold());
++ }
++
++ jGroup.setOutlineColour(sg.getOutlineColour().getRGB());
++ jGroup.setDisplayBoxes(sg.getDisplayBoxes());
++ jGroup.setDisplayText(sg.getDisplayText());
++ jGroup.setColourText(sg.getColourText());
++ jGroup.setTextCol1(sg.textColour.getRGB());
++ jGroup.setTextCol2(sg.textColour2.getRGB());
++ jGroup.setTextColThreshold(sg.thresholdTextColour);
++ jGroup.setShowUnconserved(sg.getShowNonconserved());
++ jGroup.setIgnoreGapsinConsensus(sg.getIgnoreGapsConsensus());
++ jGroup.setShowConsensusHistogram(sg.isShowConsensusHistogram());
++ jGroup.setShowSequenceLogo(sg.isShowSequenceLogo());
++ jGroup.setNormaliseSequenceLogo(sg.isNormaliseSequenceLogo());
++ for (SequenceI seq : sg.getSequences())
++ {
++ // jGroup.addSeq(seqHash(seq));
++ jGroup.getSeq().add(seqHash(seq));
++ }
++ }
++
++ //jms.setJGroup(groups);
++ Object group;
++ for (JGroup grp : groups)
++ {
++ object.getJGroup().add(grp);
++ }
++ }
++ if (!storeDS)
++ {
++ // /////////SAVE VIEWPORT
++ Viewport view = new Viewport();
++ view.setTitle(ap.alignFrame.getTitle());
++ view.setSequenceSetId(
++ makeHashCode(av.getSequenceSetId(), av.getSequenceSetId()));
++ view.setId(av.getViewId());
++ if (av.getCodingComplement() != null)
++ {
++ view.setComplementId(av.getCodingComplement().getViewId());
++ }
++ view.setViewName(av.getViewName());
++ view.setGatheredViews(av.isGatherViewsHere());
++
++ Rectangle size = ap.av.getExplodedGeometry();
++ Rectangle position = size;
++ if (size == null)
++ {
++ size = ap.alignFrame.getBounds();
++ if (av.getCodingComplement() != null)
++ {
++ position = ((SplitFrame) ap.alignFrame.getSplitViewContainer())
++ .getBounds();
++ }
++ else
++ {
++ position = size;
++ }
++ }
++ view.setXpos(position.x);
++ view.setYpos(position.y);
++
++ view.setWidth(size.width);
++ view.setHeight(size.height);
++
++ view.setStartRes(vpRanges.getStartRes());
++ view.setStartSeq(vpRanges.getStartSeq());
++
++ if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
++ {
++ view.setBgColour(setUserColourScheme(av.getGlobalColourScheme(),
++ userColours, object));
++ }
++ else if (av
++ .getGlobalColourScheme() instanceof jalview.schemes.AnnotationColourGradient)
++ {
++ AnnotationColourScheme ac = constructAnnotationColours(
++ (jalview.schemes.AnnotationColourGradient) av
++ .getGlobalColourScheme(),
++ userColours, object);
++
++ view.setAnnotationColours(ac);
++ view.setBgColour("AnnotationColourGradient");
++ }
++ else
++ {
++ view.setBgColour(ColourSchemeProperty
++ .getColourName(av.getGlobalColourScheme()));
++ }
++
++ ResidueShaderI vcs = av.getResidueShading();
++ ColourSchemeI cs = av.getGlobalColourScheme();
++
++ if (cs != null)
++ {
++ if (vcs.conservationApplied())
++ {
++ view.setConsThreshold(vcs.getConservationInc());
++ if (cs instanceof jalview.schemes.UserColourScheme)
++ {
++ view.setBgColour(setUserColourScheme(cs, userColours, object));
++ }
++ }
++ view.setPidThreshold(vcs.getThreshold());
++ }
++
++ view.setConservationSelected(av.getConservationSelected());
++ view.setPidSelected(av.getAbovePIDThreshold());
++ final Font font = av.getFont();
++ view.setFontName(font.getName());
++ view.setFontSize(font.getSize());
++ view.setFontStyle(font.getStyle());
++ view.setScaleProteinAsCdna(av.getViewStyle().isScaleProteinAsCdna());
++ view.setRenderGaps(av.isRenderGaps());
++ view.setShowAnnotation(av.isShowAnnotation());
++ view.setShowBoxes(av.getShowBoxes());
++ view.setShowColourText(av.getColourText());
++ view.setShowFullId(av.getShowJVSuffix());
++ view.setRightAlignIds(av.isRightAlignIds());
++ view.setShowSequenceFeatures(av.isShowSequenceFeatures());
++ view.setShowText(av.getShowText());
++ view.setShowUnconserved(av.getShowUnconserved());
++ view.setWrapAlignment(av.getWrapAlignment());
++ view.setTextCol1(av.getTextColour().getRGB());
++ view.setTextCol2(av.getTextColour2().getRGB());
++ view.setTextColThreshold(av.getThresholdTextColour());
++ view.setShowConsensusHistogram(av.isShowConsensusHistogram());
++ view.setShowSequenceLogo(av.isShowSequenceLogo());
++ view.setNormaliseSequenceLogo(av.isNormaliseSequenceLogo());
++ view.setShowGroupConsensus(av.isShowGroupConsensus());
++ view.setShowGroupConservation(av.isShowGroupConservation());
++ view.setShowNPfeatureTooltip(av.isShowNPFeats());
++ view.setShowDbRefTooltip(av.isShowDBRefs());
++ view.setFollowHighlight(av.isFollowHighlight());
++ view.setFollowSelection(av.followSelection);
++ view.setIgnoreGapsinConsensus(av.isIgnoreGapsConsensus());
++ view.setShowComplementFeatures(av.isShowComplementFeatures());
++ view.setShowComplementFeaturesOnTop(
++ av.isShowComplementFeaturesOnTop());
++ if (av.getFeaturesDisplayed() != null)
++ {
++ FeatureSettings fs = new FeatureSettings();
++
++ FeatureRendererModel fr = ap.getSeqPanel().seqCanvas
++ .getFeatureRenderer();
++ String[] renderOrder = fr.getRenderOrder().toArray(new String[0]);
++
++ Vector<String> settingsAdded = new Vector<>();
++ if (renderOrder != null)
++ {
++ for (String featureType : renderOrder)
++ {
++ FeatureSettings.Setting setting = new FeatureSettings.Setting();
++ setting.setType(featureType);
++
++ /*
++ * save any filter for the feature type
++ */
++ FeatureMatcherSetI filter = fr.getFeatureFilter(featureType);
++ if (filter != null) {
++ Iterator<FeatureMatcherI> filters = filter.getMatchers().iterator();
++ FeatureMatcherI firstFilter = filters.next();
++ setting.setMatcherSet(Jalview2XML.marshalFilter(
++ firstFilter, filters, filter.isAnded()));
++ }
++
++ /*
++ * save colour scheme for the feature type
++ */
++ FeatureColourI fcol = fr.getFeatureStyle(featureType);
++ if (!fcol.isSimpleColour())
++ {
++ setting.setColour(fcol.getMaxColour().getRGB());
++ setting.setMincolour(fcol.getMinColour().getRGB());
++ setting.setMin(fcol.getMin());
++ setting.setMax(fcol.getMax());
++ setting.setColourByLabel(fcol.isColourByLabel());
++ if (fcol.isColourByAttribute())
++ {
++ String[] attName = fcol.getAttributeName();
++ setting.getAttributeName().add(attName[0]);
++ if (attName.length > 1)
++ {
++ setting.getAttributeName().add(attName[1]);
++ }
++ }
++ setting.setAutoScale(fcol.isAutoScaled());
++ setting.setThreshold(fcol.getThreshold());
++ Color noColour = fcol.getNoColour();
++ if (noColour == null)
++ {
++ setting.setNoValueColour(NoValueColour.NONE);
++ }
++ else if (noColour.equals(fcol.getMaxColour()))
++ {
++ setting.setNoValueColour(NoValueColour.MAX);
++ }
++ else
++ {
++ setting.setNoValueColour(NoValueColour.MIN);
++ }
++ // -1 = No threshold, 0 = Below, 1 = Above
++ setting.setThreshstate(fcol.isAboveThreshold() ? 1
++ : (fcol.isBelowThreshold() ? 0 : -1));
++ }
++ else
++ {
++ setting.setColour(fcol.getColour().getRGB());
++ }
++
++ setting.setDisplay(
++ av.getFeaturesDisplayed().isVisible(featureType));
++ float rorder = fr
++ .getOrder(featureType);
++ if (rorder > -1)
++ {
++ setting.setOrder(rorder);
++ }
++ /// fs.addSetting(setting);
++ fs.getSetting().add(setting);
++ settingsAdded.addElement(featureType);
++ }
++ }
++
++ // is groups actually supposed to be a map here ?
++ Iterator<String> en = fr.getFeatureGroups().iterator();
++ Vector<String> groupsAdded = new Vector<>();
++ while (en.hasNext())
++ {
++ String grp = en.next();
++ if (groupsAdded.contains(grp))
++ {
++ continue;
++ }
++ Group g = new Group();
++ g.setName(grp);
++ g.setDisplay(((Boolean) fr.checkGroupVisibility(grp, false))
++ .booleanValue());
++ // fs.addGroup(g);
++ fs.getGroup().add(g);
++ groupsAdded.addElement(grp);
++ }
++ // jms.setFeatureSettings(fs);
++ object.setFeatureSettings(fs);
++ }
++
++ if (av.hasHiddenColumns())
++ {
++ jalview.datamodel.HiddenColumns hidden = av.getAlignment()
++ .getHiddenColumns();
++ if (hidden == null)
++ {
++ Console.warn(
++ "REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
++ }
++ else
++ {
++ Iterator<int[]> hiddenRegions = hidden.iterator();
++ while (hiddenRegions.hasNext())
++ {
++ int[] region = hiddenRegions.next();
++ HiddenColumns hc = new HiddenColumns();
++ hc.setStart(region[0]);
++ hc.setEnd(region[1]);
++ // view.addHiddenColumns(hc);
++ view.getHiddenColumns().add(hc);
++ }
++ }
++ }
++ if (calcIdSet.size() > 0)
++ {
++ for (String calcId : calcIdSet)
++ {
++ if (calcId.trim().length() > 0)
++ {
++ CalcIdParam cidp = createCalcIdParam(calcId, av);
++ // Some calcIds have no parameters.
++ if (cidp != null)
++ {
++ // view.addCalcIdParam(cidp);
++ view.getCalcIdParam().add(cidp);
++ }
++ }
++ }
++ }
++
++ // jms.addViewport(view);
++ object.getViewport().add(view);
++ }
++ // object.setJalviewModelSequence(jms);
++ // object.getVamsasModel().addSequenceSet(vamsasSet);
++ object.getVamsasModel().getSequenceSet().add(vamsasSet);
++
++ if (jout != null && fileName != null)
++ {
++ // We may not want to write the object to disk,
++ // eg we can copy the alignViewport to a new view object
++ // using save and then load
++ try
++ {
++ fileName = fileName.replace('\\', '/');
++ System.out.println("Writing jar entry " + fileName);
++ JarEntry entry = new JarEntry(fileName);
++ jout.putNextEntry(entry);
++ PrintWriter pout = new PrintWriter(
++ new OutputStreamWriter(jout, UTF_8));
++ JAXBContext jaxbContext = JAXBContext
++ .newInstance(JalviewModel.class);
++ Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
++
++ // output pretty printed
++ // jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
++ jaxbMarshaller.marshal(
++ new ObjectFactory().createJalviewModel(object), pout);
++
++ // jaxbMarshaller.marshal(object, pout);
++ // marshaller.marshal(object);
++ pout.flush();
++ jout.closeEntry();
++ } catch (Exception ex)
++ {
++ // TODO: raise error in GUI if marshalling failed.
++ System.err.println("Error writing Jalview project");
++ ex.printStackTrace();
++ }
++ }
++ return object;
++ }
++ /**
++ * Saves the HMMER profile associated with the sequence as a file in the jar,
++ * in HMMER format, and saves the name of the file as a child element of the
++ * XML sequence element
++ *
++ * @param jout
++ * @param xmlSeq
++ * @param seq
++ */
++ protected void saveHmmerProfile(JarOutputStream jout, JSeq xmlSeq,
++ SequenceI seq)
++ {
++ HiddenMarkovModel profile = seq.getHMM();
++ if (profile == null)
++ {
++ Console.warn("Want to save HMM profile for " + seq.getName()
++ + " but none found");
++ return;
++ }
++ HMMFile hmmFile = new HMMFile(profile);
++ String hmmAsString = hmmFile.print();
++ String jarEntryName = HMMER_PREFIX + nextCounter();
++ try
++ {
++ writeJarEntry(jout, jarEntryName, hmmAsString.getBytes());
++ xmlSeq.setHmmerProfile(jarEntryName);
++ } catch (IOException e)
++ {
++ Console.warn("Error saving HMM profile: " + e.getMessage());
++ }
++ }
+
- @Override
- boolean resolve()
- {
- SequenceI seq = getSrefDatasetSeq();
- if (seq == null)
- {
- return false;
- }
- jmap.setTo(seq);
- return true;
- }
- };
- return fref;
- }
++
++ /**
++ * Writes PCA viewer attributes and computed values to an XML model object and
++ * adds it to the JalviewModel. Any exceptions are reported by logging.
++ */
++ protected void savePCA(PCAPanel panel, JalviewModel object)
++ {
++ try
++ {
++ PcaViewer viewer = new PcaViewer();
++ viewer.setHeight(panel.getHeight());
++ viewer.setWidth(panel.getWidth());
++ viewer.setXpos(panel.getX());
++ viewer.setYpos(panel.getY());
++ viewer.setTitle(panel.getTitle());
++ PCAModel pcaModel = panel.getPcaModel();
++ viewer.setScoreModelName(pcaModel.getScoreModelName());
++ viewer.setXDim(panel.getSelectedDimensionIndex(X));
++ viewer.setYDim(panel.getSelectedDimensionIndex(Y));
++ viewer.setZDim(panel.getSelectedDimensionIndex(Z));
++ viewer.setBgColour(
++ panel.getRotatableCanvas().getBackgroundColour().getRGB());
++ viewer.setScaleFactor(panel.getRotatableCanvas().getScaleFactor());
++ float[] spMin = panel.getRotatableCanvas().getSeqMin();
++ SeqPointMin spmin = new SeqPointMin();
++ spmin.setXPos(spMin[0]);
++ spmin.setYPos(spMin[1]);
++ spmin.setZPos(spMin[2]);
++ viewer.setSeqPointMin(spmin);
++ float[] spMax = panel.getRotatableCanvas().getSeqMax();
++ SeqPointMax spmax = new SeqPointMax();
++ spmax.setXPos(spMax[0]);
++ spmax.setYPos(spMax[1]);
++ spmax.setZPos(spMax[2]);
++ viewer.setSeqPointMax(spmax);
++ viewer.setShowLabels(panel.getRotatableCanvas().isShowLabels());
++ viewer.setLinkToAllViews(
++ panel.getRotatableCanvas().isApplyToAllViews());
++ SimilarityParamsI sp = pcaModel.getSimilarityParameters();
++ viewer.setIncludeGaps(sp.includeGaps());
++ viewer.setMatchGaps(sp.matchGaps());
++ viewer.setIncludeGappedColumns(sp.includeGappedColumns());
++ viewer.setDenominateByShortestLength(sp.denominateByShortestLength());
++
++ /*
++ * sequence points on display
++ */
++ for (jalview.datamodel.SequencePoint spt : pcaModel
++ .getSequencePoints())
++ {
++ SequencePoint point = new SequencePoint();
++ point.setSequenceRef(seqHash(spt.getSequence()));
++ point.setXPos(spt.coord.x);
++ point.setYPos(spt.coord.y);
++ point.setZPos(spt.coord.z);
++ viewer.getSequencePoint().add(point);
++ }
++
++ /*
++ * (end points of) axes on display
++ */
++ for (Point p : panel.getRotatableCanvas().getAxisEndPoints())
++ {
++
++ Axis axis = new Axis();
++ axis.setXPos(p.x);
++ axis.setYPos(p.y);
++ axis.setZPos(p.z);
++ viewer.getAxis().add(axis);
++ }
++
++ /*
++ * raw PCA data (note we are not restoring PCA inputs here -
++ * alignment view, score model, similarity parameters)
++ */
++ PcaDataType data = new PcaDataType();
++ viewer.setPcaData(data);
++ PCA pca = pcaModel.getPcaData();
++
++ DoubleMatrix pm = new DoubleMatrix();
++ saveDoubleMatrix(pca.getPairwiseScores(), pm);
++ data.setPairwiseMatrix(pm);
++
++ DoubleMatrix tm = new DoubleMatrix();
++ saveDoubleMatrix(pca.getTridiagonal(), tm);
++ data.setTridiagonalMatrix(tm);
++
++ DoubleMatrix eigenMatrix = new DoubleMatrix();
++ data.setEigenMatrix(eigenMatrix);
++ saveDoubleMatrix(pca.getEigenmatrix(), eigenMatrix);
++
++ object.getPcaViewer().add(viewer);
++ } catch (Throwable t)
++ {
++ Console.error("Error saving PCA: " + t.getMessage());
++ }
++ }
- protected SeqFref newAlcodMapRef(final String sref,
- final AlignedCodonFrame _cf,
- final jalview.datamodel.Mapping _jmap)
- {
- @Override
- boolean resolve()
- {
- SequenceI seq = getSrefDatasetSeq();
- if (seq == null)
- {
- return false;
- }
- jmap.setTo(seq);
- return true;
- }
- };
- return fref;
- }
++ /**
++ * Stores values from a matrix into an XML element, including (if present) the
++ * D or E vectors
++ *
++ * @param m
++ * @param xmlMatrix
++ * @see #loadDoubleMatrix(DoubleMatrix)
++ */
++ protected void saveDoubleMatrix(MatrixI m, DoubleMatrix xmlMatrix)
++ {
++ xmlMatrix.setRows(m.height());
++ xmlMatrix.setColumns(m.width());
++ for (int i = 0; i < m.height(); i++)
++ {
++ DoubleVector row = new DoubleVector();
++ for (int j = 0; j < m.width(); j++)
++ {
++ row.getV().add(m.getValue(i, j));
++ }
++ xmlMatrix.getRow().add(row);
++ }
++ if (m.getD() != null)
++ {
++ DoubleVector dVector = new DoubleVector();
++ for (double d : m.getD())
++ {
++ dVector.getV().add(d);
++ }
++ xmlMatrix.setD(dVector);
++ }
++ if (m.getE() != null)
++ {
++ DoubleVector eVector = new DoubleVector();
++ for (double e : m.getE())
++ {
++ eVector.getV().add(e);
++ }
++ xmlMatrix.setE(eVector);
++ }
++ }
- SeqFref fref = new SeqFref(sref, "Codon Frame")
- {
- AlignedCodonFrame cf = _cf;
- public SeqFref newAlcodMapRef(final String sref,
- final AlignedCodonFrame _cf,
- final jalview.datamodel.Mapping _jmap)
- {
++ /**
++ * Loads XML matrix data into a new Matrix object, including the D and/or E
++ * vectors (if present)
++ *
++ * @param mData
++ * @return
++ * @see Jalview2XML#saveDoubleMatrix(MatrixI, DoubleMatrix)
++ */
++ protected MatrixI loadDoubleMatrix(DoubleMatrix mData)
++ {
++ int rows = mData.getRows();
++ double[][] vals = new double[rows][];
++
++ for (int i = 0; i < rows; i++)
++ {
++ List<Double> dVector = mData.getRow().get(i).getV();
++ vals[i] = new double[dVector.size()];
++ int dvi = 0;
++ for (Double d : dVector)
++ {
++ vals[i][dvi++] = d;
++ }
++ }
++
++ MatrixI m = new Matrix(vals);
++
++ if (mData.getD() != null)
++ {
++ List<Double> dVector = mData.getD().getV();
++ double[] vec = new double[dVector.size()];
++ int dvi = 0;
++ for (Double d : dVector)
++ {
++ vec[dvi++] = d;
++ }
++ m.setD(vec);
++ }
++ if (mData.getE() != null)
++ {
++ List<Double> dVector = mData.getE().getV();
++ double[] vec = new double[dVector.size()];
++ int dvi = 0;
++ for (Double d : dVector)
++ {
++ vec[dvi++] = d;
++ }
++ m.setE(vec);
++ }
++
++ return m;
++ }
- public jalview.datamodel.Mapping mp = _jmap;
- SeqFref fref = new SeqFref(sref, "Codon Frame")
- {
- AlignedCodonFrame cf = _cf;
++ /**
++ * Save any Varna viewers linked to this sequence. Writes an rnaViewer element
++ * for each viewer, with
++ * <ul>
++ * <li>viewer geometry (position, size, split pane divider location)</li>
++ * <li>index of the selected structure in the viewer (currently shows gapped
++ * or ungapped)</li>
++ * <li>the id of the annotation holding RNA secondary structure</li>
++ * <li>(currently only one SS is shown per viewer, may be more in future)</li>
++ * </ul>
++ * Varna viewer state is also written out (in native Varna XML) to separate
++ * project jar entries. A separate entry is written for each RNA structure
++ * displayed, with the naming convention
++ * <ul>
++ * <li>rna_viewId_sequenceId_annotationId_[gapped|trimmed]</li>
++ * </ul>
++ *
++ * @param jout
++ * @param jseq
++ * @param jds
++ * @param viewIds
++ * @param ap
++ * @param storeDataset
++ */
++ protected void saveRnaViewers(JarOutputStream jout, JSeq jseq,
++ final SequenceI jds, List<String> viewIds, AlignmentPanel ap,
++ boolean storeDataset)
++ {
++ if (Desktop.getDesktopPane() == null)
++ {
++ return;
++ }
++ JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
++ for (int f = frames.length - 1; f > -1; f--)
++ {
++ if (frames[f] instanceof AppVarna)
++ {
++ AppVarna varna = (AppVarna) frames[f];
++ /*
++ * link the sequence to every viewer that is showing it and is linked to
++ * its alignment panel
++ */
++ if (varna.isListeningFor(jds) && ap == varna.getAlignmentPanel())
++ {
++ String viewId = varna.getViewId();
++ RnaViewer rna = new RnaViewer();
++ rna.setViewId(viewId);
++ rna.setTitle(varna.getTitle());
++ rna.setXpos(varna.getX());
++ rna.setYpos(varna.getY());
++ rna.setWidth(varna.getWidth());
++ rna.setHeight(varna.getHeight());
++ rna.setDividerLocation(varna.getDividerLocation());
++ rna.setSelectedRna(varna.getSelectedIndex());
++ // jseq.addRnaViewer(rna);
++ jseq.getRnaViewer().add(rna);
++
++ /*
++ * Store each Varna panel's state once in the project per sequence.
++ * First time through only (storeDataset==false)
++ */
++ // boolean storeSessions = false;
++ // String sequenceViewId = viewId + seqsToIds.get(jds);
++ // if (!storeDataset && !viewIds.contains(sequenceViewId))
++ // {
++ // viewIds.add(sequenceViewId);
++ // storeSessions = true;
++ // }
++ for (RnaModel model : varna.getModels())
++ {
++ if (model.seq == jds)
++ {
++ /*
++ * VARNA saves each view (sequence or alignment secondary
++ * structure, gapped or trimmed) as a separate XML file
++ */
++ String jarEntryName = rnaSessions.get(model);
++ if (jarEntryName == null)
++ {
++
++ String varnaStateFile = varna.getStateInfo(model.rna);
++ jarEntryName = RNA_PREFIX + viewId + "_" + nextCounter();
++ copyFileToJar(jout, varnaStateFile, jarEntryName, "Varna");
++ rnaSessions.put(model, jarEntryName);
++ }
++ SecondaryStructure ss = new SecondaryStructure();
++ String annotationId = varna.getAnnotation(jds).annotationId;
++ ss.setAnnotationId(annotationId);
++ ss.setViewerState(jarEntryName);
++ ss.setGapped(model.gapped);
++ ss.setTitle(model.title);
++ // rna.addSecondaryStructure(ss);
++ rna.getSecondaryStructure().add(ss);
++ }
++ }
++ }
++ }
++ }
++ }
- @Override
- public boolean isResolvable()
- {
- return super.isResolvable() && mp.getTo() != null;
- }
- public jalview.datamodel.Mapping mp = _jmap;
++ /**
++ * Copy the contents of a file to a new entry added to the output jar
++ *
++ * @param jout
++ * @param infilePath
++ * @param jarEntryName
++ * @param msg
++ * additional identifying info to log to the console
++ */
++ protected void copyFileToJar(JarOutputStream jout, String infilePath,
++ String jarEntryName, String msg)
++ {
++ try (InputStream is = new FileInputStream(infilePath))
++ {
++ File file = new File(infilePath);
++ if (file.exists() && jout != null)
++ {
++ System.out.println(
++ "Writing jar entry " + jarEntryName + " (" + msg + ")");
++ jout.putNextEntry(new JarEntry(jarEntryName));
++ copyAll(is, jout);
++ jout.closeEntry();
++ // dis = new DataInputStream(new FileInputStream(file));
++ // byte[] data = new byte[(int) file.length()];
++ // dis.readFully(data);
++ // writeJarEntry(jout, jarEntryName, data);
++ }
++ } catch (Exception ex)
++ {
++ ex.printStackTrace();
++ }
++ }
-- @Override
- boolean resolve()
- {
- SequenceI seq = getSrefDatasetSeq();
- if (seq == null)
- {
- return false;
- }
- cf.addMap(seq, mp.getTo(), mp.getMap());
- return true;
- }
- };
- return fref;
- }
- public boolean isResolvable()
- {
- return super.isResolvable() && mp.getTo() != null;
- }
-
- @Override
- boolean resolve()
- {
- SequenceI seq = getSrefDatasetSeq();
- if (seq == null)
- {
- return false;
- }
- cf.addMap(seq, mp.getTo(), mp.getMap());
- return true;
- }
- };
- return fref;
- }
-
- public void resolveFrefedSequences()
- {
- Iterator<SeqFref> nextFref = frefedSequence.iterator();
- int toresolve = frefedSequence.size();
- int unresolved = 0, failedtoresolve = 0;
- while (nextFref.hasNext())
- {
- SeqFref ref = nextFref.next();
- if (ref.isResolvable())
- {
- try
- {
- if (ref.resolve())
- {
- nextFref.remove();
- }
- else
- {
- failedtoresolve++;
- }
- } catch (Exception x)
- {
- System.err.println(
- "IMPLEMENTATION ERROR: Failed to resolve forward reference for sequence "
- + ref.getSref());
- x.printStackTrace();
- failedtoresolve++;
- }
- }
- else
- {
- unresolved++;
- }
- }
- if (unresolved > 0)
- {
- System.err.println("Jalview Project Import: There were " + unresolved
- + " forward references left unresolved on the stack.");
- }
- if (failedtoresolve > 0)
- {
- System.err.println("SERIOUS! " + failedtoresolve
- + " resolvable forward references failed to resolve.");
- }
- if (incompleteSeqs != null && incompleteSeqs.size() > 0)
- {
- System.err.println(
- "Jalview Project Import: There are " + incompleteSeqs.size()
- + " sequences which may have incomplete metadata.");
- if (incompleteSeqs.size() < 10)
- {
- for (SequenceI s : incompleteSeqs.values())
- {
- System.err.println(s.toString());
- }
- }
- else
- {
- System.err.println(
- "Too many to report. Skipping output of incomplete sequences.");
- }
- }
- }
-
- /**
- * This maintains a map of viewports, the key being the seqSetId. Important to
- * set historyItem and redoList for multiple views
- */
- Map<String, AlignViewport> viewportsAdded = new HashMap<>();
-
- Map<String, AlignmentAnnotation> annotationIds = new HashMap<>();
-
- String uniqueSetSuffix = "";
-
- /**
- * List of pdbfiles added to Jar
- */
- List<String> pdbfiles = null;
-
- // SAVES SEVERAL ALIGNMENT WINDOWS TO SAME JARFILE
- public void saveState(File statefile)
- {
- FileOutputStream fos = null;
-
- try
- {
-
- fos = new FileOutputStream(statefile);
-
- JarOutputStream jout = new JarOutputStream(fos);
- saveState(jout);
- fos.close();
-
- } catch (Exception e)
- {
- Console.error("Couln't write Jalview state to " + statefile, e);
- // TODO: inform user of the problem - they need to know if their data was
- // not saved !
- if (errorMessage == null)
- {
- errorMessage = "Did't write Jalview Archive to output file '"
- + statefile + "' - See console error log for details";
- }
- else
- {
- errorMessage += "(Didn't write Jalview Archive to output file '"
- + statefile + ")";
- }
- e.printStackTrace();
- } finally
- {
- if (fos != null)
- {
- try
- {
- fos.close();
- } catch (IOException e)
- {
- // ignore
- }
- }
- }
- reportErrors();
- }
-
- /**
- * Writes a jalview project archive to the given Jar output stream.
- *
- * @param jout
- */
- public void saveState(JarOutputStream jout)
- {
- AlignFrame[] frames = Desktop.getAlignFrames();
-
- if (frames == null)
- {
- return;
- }
- saveAllFrames(Arrays.asList(frames), jout);
- }
-
- /**
- * core method for storing state for a set of AlignFrames.
- *
- * @param frames
- * - frames involving all data to be exported (including containing
- * splitframes)
- * @param jout
- * - project output stream
- */
- private void saveAllFrames(List<AlignFrame> frames, JarOutputStream jout)
- {
- Hashtable<String, AlignFrame> dsses = new Hashtable<>();
-
- /*
- * ensure cached data is clear before starting
- */
- // todo tidy up seqRefIds, seqsToIds initialisation / reset
- rnaSessions.clear();
- splitFrameCandidates.clear();
-
- try
- {
-
- // NOTE UTF-8 MUST BE USED FOR WRITING UNICODE CHARS
- // //////////////////////////////////////////////////
-
- List<String> shortNames = new ArrayList<>();
- List<String> viewIds = new ArrayList<>();
-
- // REVERSE ORDER
- for (int i = frames.size() - 1; i > -1; i--)
- {
- AlignFrame af = frames.get(i);
- // skip ?
- if (skipList != null && skipList
- .containsKey(af.getViewport().getSequenceSetId()))
- {
- continue;
- }
-
- String shortName = makeFilename(af, shortNames);
-
- int apSize = af.getAlignPanels().size();
-
- for (int ap = 0; ap < apSize; ap++)
- {
- AlignmentPanel apanel = (AlignmentPanel) af.getAlignPanels()
- .get(ap);
- String fileName = apSize == 1 ? shortName : ap + shortName;
- if (!fileName.endsWith(".xml"))
- {
- fileName = fileName + ".xml";
- }
-
- saveState(apanel, fileName, jout, viewIds);
-
- String dssid = getDatasetIdRef(
- af.getViewport().getAlignment().getDataset());
- if (!dsses.containsKey(dssid))
- {
- dsses.put(dssid, af);
- }
- }
- }
-
- writeDatasetFor(dsses, "" + jout.hashCode() + " " + uniqueSetSuffix,
- jout);
-
- try
- {
- jout.flush();
- } catch (Exception foo)
- {
- }
- jout.close();
- } catch (Exception ex)
- {
- // TODO: inform user of the problem - they need to know if their data was
- // not saved !
- if (errorMessage == null)
- {
- errorMessage = "Couldn't write Jalview Archive - see error output for details";
- }
- ex.printStackTrace();
- }
- }
-
- /**
- * Generates a distinct file name, based on the title of the AlignFrame, by
- * appending _n for increasing n until an unused name is generated. The new
- * name (without its extension) is added to the list.
- *
- * @param af
- * @param namesUsed
- * @return the generated name, with .xml extension
- */
- protected String makeFilename(AlignFrame af, List<String> namesUsed)
- {
- String shortName = af.getTitle();
-
- if (shortName.indexOf(File.separatorChar) > -1)
- {
- shortName = shortName
- .substring(shortName.lastIndexOf(File.separatorChar) + 1);
- }
-
- int count = 1;
-
- while (namesUsed.contains(shortName))
- {
- if (shortName.endsWith("_" + (count - 1)))
- {
- shortName = shortName.substring(0, shortName.lastIndexOf("_"));
- }
-
- shortName = shortName.concat("_" + count);
- count++;
- }
-
- namesUsed.add(shortName);
-
- if (!shortName.endsWith(".xml"))
- {
- shortName = shortName + ".xml";
- }
- return shortName;
- }
-
- // USE THIS METHOD TO SAVE A SINGLE ALIGNMENT WINDOW
- public boolean saveAlignment(AlignFrame af, String jarFile,
- String fileName)
- {
- try
- {
- // create backupfiles object and get new temp filename destination
- boolean doBackup = BackupFiles.getEnabled();
- BackupFiles backupfiles = doBackup ? new BackupFiles(jarFile) : null;
- FileOutputStream fos = new FileOutputStream(
- doBackup ? backupfiles.getTempFilePath() : jarFile);
-
- JarOutputStream jout = new JarOutputStream(fos);
- List<AlignFrame> frames = new ArrayList<>();
-
- // resolve splitframes
- if (af.getViewport().getCodingComplement() != null)
- {
- frames = ((SplitFrame) af.getSplitViewContainer()).getAlignFrames();
- }
- else
- {
- frames.add(af);
- }
- saveAllFrames(frames, jout);
- try
- {
- jout.flush();
- } catch (Exception foo)
- {
- }
- jout.close();
- boolean success = true;
-
- if (doBackup)
- {
- backupfiles.setWriteSuccess(success);
- success = backupfiles.rollBackupsAndRenameTempFile();
- }
-
- return success;
- } catch (Exception ex)
- {
- errorMessage = "Couldn't Write alignment view to Jalview Archive - see error output for details";
- ex.printStackTrace();
- return false;
- }
- }
-
- private void writeDatasetFor(Hashtable<String, AlignFrame> dsses,
- String fileName, JarOutputStream jout)
- {
-
- for (String dssids : dsses.keySet())
- {
- AlignFrame _af = dsses.get(dssids);
- String jfileName = fileName + " Dataset for " + _af.getTitle();
- if (!jfileName.endsWith(".xml"))
- {
- jfileName = jfileName + ".xml";
- }
- saveState(_af.alignPanel, jfileName, true, jout, null);
- }
- }
-
- /**
- * create a JalviewModel from an alignment view and marshall it to a
- * JarOutputStream
- *
- * @param ap
- * panel to create jalview model for
- * @param fileName
- * name of alignment panel written to output stream
- * @param jout
- * jar output stream
- * @param viewIds
- * @param out
- * jar entry name
- */
- public JalviewModel saveState(AlignmentPanel ap, String fileName,
- JarOutputStream jout, List<String> viewIds)
- {
- return saveState(ap, fileName, false, jout, viewIds);
- }
-
- /**
- * create a JalviewModel from an alignment view and marshall it to a
- * JarOutputStream
- *
- * @param ap
- * panel to create jalview model for
- * @param fileName
- * name of alignment panel written to output stream
- * @param storeDS
- * when true, only write the dataset for the alignment, not the data
- * associated with the view.
- * @param jout
- * jar output stream
- * @param out
- * jar entry name
- */
- public JalviewModel saveState(AlignmentPanel ap, String fileName,
- boolean storeDS, JarOutputStream jout, List<String> viewIds)
- {
- if (viewIds == null)
- {
- viewIds = new ArrayList<>();
- }
-
- initSeqRefs();
-
- List<UserColourScheme> userColours = new ArrayList<>();
-
- AlignViewport av = ap.av;
- ViewportRanges vpRanges = av.getRanges();
-
- final ObjectFactory objectFactory = new ObjectFactory();
- JalviewModel object = objectFactory.createJalviewModel();
- object.setVamsasModel(new VAMSAS());
-
- // object.setCreationDate(new java.util.Date(System.currentTimeMillis()));
- try
- {
- GregorianCalendar c = new GregorianCalendar();
- DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
- XMLGregorianCalendar now = datatypeFactory.newXMLGregorianCalendar(c);// gregorianCalendar);
- object.setCreationDate(now);
- } catch (DatatypeConfigurationException e)
- {
- System.err.println("error writing date: " + e.toString());
- }
- object.setVersion(Cache.getDefault("VERSION", "Development Build"));
-
- /**
- * rjal is full height alignment, jal is actual alignment with full metadata
- * but excludes hidden sequences.
- */
- jalview.datamodel.AlignmentI rjal = av.getAlignment(), jal = rjal;
-
- if (av.hasHiddenRows())
- {
- rjal = jal.getHiddenSequences().getFullAlignment();
- }
-
- SequenceSet vamsasSet = new SequenceSet();
- Sequence vamsasSeq;
- // JalviewModelSequence jms = new JalviewModelSequence();
-
- vamsasSet.setGapChar(jal.getGapCharacter() + "");
-
- if (jal.getDataset() != null)
- {
- // dataset id is the dataset's hashcode
- vamsasSet.setDatasetId(getDatasetIdRef(jal.getDataset()));
- if (storeDS)
- {
- // switch jal and the dataset
- jal = jal.getDataset();
- rjal = jal;
- }
- }
- if (jal.getProperties() != null)
- {
- Enumeration en = jal.getProperties().keys();
- while (en.hasMoreElements())
- {
- String key = en.nextElement().toString();
- SequenceSetProperties ssp = new SequenceSetProperties();
- ssp.setKey(key);
- ssp.setValue(jal.getProperties().get(key).toString());
- // vamsasSet.addSequenceSetProperties(ssp);
- vamsasSet.getSequenceSetProperties().add(ssp);
- }
- }
-
- JSeq jseq;
- Set<String> calcIdSet = new HashSet<>();
- // record the set of vamsas sequence XML POJO we create.
- HashMap<String, Sequence> vamsasSetIds = new HashMap<>();
- // SAVE SEQUENCES
- for (final SequenceI jds : rjal.getSequences())
- {
- final SequenceI jdatasq = jds.getDatasetSequence() == null ? jds
- : jds.getDatasetSequence();
- String id = seqHash(jds);
- if (vamsasSetIds.get(id) == null)
- {
- if (seqRefIds.get(id) != null && !storeDS)
- {
- // This happens for two reasons: 1. multiple views are being
- // serialised.
- // 2. the hashCode has collided with another sequence's code. This
- // DOES
- // HAPPEN! (PF00072.15.stk does this)
- // JBPNote: Uncomment to debug writing out of files that do not read
- // back in due to ArrayOutOfBoundExceptions.
- // System.err.println("vamsasSeq backref: "+id+"");
- // System.err.println(jds.getName()+"
- // "+jds.getStart()+"-"+jds.getEnd()+" "+jds.getSequenceAsString());
- // System.err.println("Hashcode: "+seqHash(jds));
- // SequenceI rsq = (SequenceI) seqRefIds.get(id + "");
- // System.err.println(rsq.getName()+"
- // "+rsq.getStart()+"-"+rsq.getEnd()+" "+rsq.getSequenceAsString());
- // System.err.println("Hashcode: "+seqHash(rsq));
- }
- else
- {
- vamsasSeq = createVamsasSequence(id, jds);
- // vamsasSet.addSequence(vamsasSeq);
- vamsasSet.getSequence().add(vamsasSeq);
- vamsasSetIds.put(id, vamsasSeq);
- seqRefIds.put(id, jds);
- }
- }
- jseq = new JSeq();
- jseq.setStart(jds.getStart());
- jseq.setEnd(jds.getEnd());
- jseq.setColour(av.getSequenceColour(jds).getRGB());
-
- jseq.setId(id); // jseq id should be a string not a number
- if (!storeDS)
- {
- // Store any sequences this sequence represents
- if (av.hasHiddenRows())
- {
- // use rjal, contains the full height alignment
- jseq.setHidden(
- av.getAlignment().getHiddenSequences().isHidden(jds));
-
- if (av.isHiddenRepSequence(jds))
- {
- jalview.datamodel.SequenceI[] reps = av
- .getRepresentedSequences(jds).getSequencesInOrder(rjal);
-
- for (int h = 0; h < reps.length; h++)
- {
- if (reps[h] != jds)
- {
- // jseq.addHiddenSequences(rjal.findIndex(reps[h]));
- jseq.getHiddenSequences().add(rjal.findIndex(reps[h]));
- }
- }
- }
- }
- // mark sequence as reference - if it is the reference for this view
- if (jal.hasSeqrep())
- {
- jseq.setViewreference(jds == jal.getSeqrep());
- }
- }
-
- // TODO: omit sequence features from each alignment view's XML dump if we
- // are storing dataset
- List<SequenceFeature> sfs = jds.getSequenceFeatures();
- for (SequenceFeature sf : sfs)
- {
- // Features features = new Features();
- Feature features = new Feature();
-
- features.setBegin(sf.getBegin());
- features.setEnd(sf.getEnd());
- features.setDescription(sf.getDescription());
- features.setType(sf.getType());
- features.setFeatureGroup(sf.getFeatureGroup());
- features.setScore(sf.getScore());
- if (sf.links != null)
- {
- for (int l = 0; l < sf.links.size(); l++)
- {
- OtherData keyValue = new OtherData();
- keyValue.setKey("LINK_" + l);
- keyValue.setValue(sf.links.elementAt(l).toString());
- // features.addOtherData(keyValue);
- features.getOtherData().add(keyValue);
- }
- }
- if (sf.otherDetails != null)
- {
- /*
- * save feature attributes, which may be simple strings or
- * map valued (have sub-attributes)
- */
- for (Entry<String, Object> entry : sf.otherDetails.entrySet())
- {
- String key = entry.getKey();
- Object value = entry.getValue();
- if (value instanceof Map<?, ?>)
- {
- for (Entry<String, Object> subAttribute : ((Map<String, Object>) value)
- .entrySet())
- {
- OtherData otherData = new OtherData();
- otherData.setKey(key);
- otherData.setKey2(subAttribute.getKey());
- otherData.setValue(subAttribute.getValue().toString());
- // features.addOtherData(otherData);
- features.getOtherData().add(otherData);
- }
- }
- else
- {
- OtherData otherData = new OtherData();
- otherData.setKey(key);
- otherData.setValue(value.toString());
- // features.addOtherData(otherData);
- features.getOtherData().add(otherData);
- }
- }
- }
-
- // jseq.addFeatures(features);
- jseq.getFeatures().add(features);
- }
-
- if (jdatasq.getAllPDBEntries() != null)
- {
- Enumeration<PDBEntry> en = jdatasq.getAllPDBEntries().elements();
- while (en.hasMoreElements())
- {
- Pdbids pdb = new Pdbids();
- jalview.datamodel.PDBEntry entry = en.nextElement();
-
- String pdbId = entry.getId();
- pdb.setId(pdbId);
- pdb.setType(entry.getType());
-
- /*
- * Store any structure views associated with this sequence. This
- * section copes with duplicate entries in the project, so a dataset
- * only view *should* be coped with sensibly.
- */
- // This must have been loaded, is it still visible?
- JInternalFrame[] frames = Desktop.desktop.getAllFrames();
- String matchedFile = null;
- for (int f = frames.length - 1; f > -1; f--)
- {
- if (frames[f] instanceof StructureViewerBase)
- {
- StructureViewerBase viewFrame = (StructureViewerBase) frames[f];
- matchedFile = saveStructureViewer(ap, jds, pdb, entry,
- viewIds, matchedFile, viewFrame);
- /*
- * Only store each structure viewer's state once in the project
- * jar. First time through only (storeDS==false)
- */
- String viewId = viewFrame.getViewId();
- String viewerType = viewFrame.getViewerType().toString();
- if (!storeDS && !viewIds.contains(viewId))
- {
- viewIds.add(viewId);
- File viewerState = viewFrame.saveSession();
- if (viewerState != null)
- {
- copyFileToJar(jout, viewerState.getPath(),
- getViewerJarEntryName(viewId), viewerType);
- }
- else
- {
- Console.error(
- "Failed to save viewer state for " + viewerType);
- }
- }
- }
- }
-
- if (matchedFile != null || entry.getFile() != null)
- {
- if (entry.getFile() != null)
- {
- // use entry's file
- matchedFile = entry.getFile();
- }
- pdb.setFile(matchedFile); // entry.getFile());
- if (pdbfiles == null)
- {
- pdbfiles = new ArrayList<>();
- }
-
- if (!pdbfiles.contains(pdbId))
- {
- pdbfiles.add(pdbId);
- copyFileToJar(jout, matchedFile, pdbId, pdbId);
- }
- }
-
- Enumeration<String> props = entry.getProperties();
- if (props.hasMoreElements())
- {
- // PdbentryItem item = new PdbentryItem();
- while (props.hasMoreElements())
- {
- Property prop = new Property();
- String key = props.nextElement();
- prop.setName(key);
- prop.setValue(entry.getProperty(key).toString());
- // item.addProperty(prop);
- pdb.getProperty().add(prop);
- }
- // pdb.addPdbentryItem(item);
- }
-
- // jseq.addPdbids(pdb);
- jseq.getPdbids().add(pdb);
- }
- }
-
- saveRnaViewers(jout, jseq, jds, viewIds, ap, storeDS);
-
- // jms.addJSeq(jseq);
- object.getJSeq().add(jseq);
- }
-
- if (!storeDS && av.hasHiddenRows())
- {
- jal = av.getAlignment();
- }
- // SAVE MAPPINGS
- // FOR DATASET
- if (storeDS && jal.getCodonFrames() != null)
- {
- List<AlignedCodonFrame> jac = jal.getCodonFrames();
- for (AlignedCodonFrame acf : jac)
- {
- AlcodonFrame alc = new AlcodonFrame();
- if (acf.getProtMappings() != null
- && acf.getProtMappings().length > 0)
- {
- boolean hasMap = false;
- SequenceI[] dnas = acf.getdnaSeqs();
- jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
- for (int m = 0; m < pmaps.length; m++)
- {
- AlcodMap alcmap = new AlcodMap();
- alcmap.setDnasq(seqHash(dnas[m]));
- alcmap.setMapping(
- createVamsasMapping(pmaps[m], dnas[m], null, false));
- // alc.addAlcodMap(alcmap);
- alc.getAlcodMap().add(alcmap);
- hasMap = true;
- }
- if (hasMap)
- {
- // vamsasSet.addAlcodonFrame(alc);
- vamsasSet.getAlcodonFrame().add(alc);
- }
- }
- // TODO: delete this ? dead code from 2.8.3->2.9 ?
- // {
- // AlcodonFrame alc = new AlcodonFrame();
- // vamsasSet.addAlcodonFrame(alc);
- // for (int p = 0; p < acf.aaWidth; p++)
- // {
- // Alcodon cmap = new Alcodon();
- // if (acf.codons[p] != null)
- // {
- // // Null codons indicate a gapped column in the translated peptide
- // // alignment.
- // cmap.setPos1(acf.codons[p][0]);
- // cmap.setPos2(acf.codons[p][1]);
- // cmap.setPos3(acf.codons[p][2]);
- // }
- // alc.addAlcodon(cmap);
- // }
- // if (acf.getProtMappings() != null
- // && acf.getProtMappings().length > 0)
- // {
- // SequenceI[] dnas = acf.getdnaSeqs();
- // jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
- // for (int m = 0; m < pmaps.length; m++)
- // {
- // AlcodMap alcmap = new AlcodMap();
- // alcmap.setDnasq(seqHash(dnas[m]));
- // alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
- // false));
- // alc.addAlcodMap(alcmap);
- // }
- // }
- }
- }
-
- // SAVE TREES
- // /////////////////////////////////
- if (!storeDS && av.getCurrentTree() != null)
- {
- // FIND ANY ASSOCIATED TREES
- // NOT IMPLEMENTED FOR HEADLESS STATE AT PRESENT
- if (Desktop.desktop != null)
- {
- JInternalFrame[] frames = Desktop.desktop.getAllFrames();
-
- for (int t = 0; t < frames.length; t++)
- {
- if (frames[t] instanceof TreePanel)
- {
- TreePanel tp = (TreePanel) frames[t];
-
- if (tp.getTreeCanvas().getViewport().getAlignment() == jal)
- {
- JalviewModel.Tree tree = new JalviewModel.Tree();
- tree.setTitle(tp.getTitle());
- tree.setCurrentTree((av.getCurrentTree() == tp.getTree()));
- tree.setNewick(tp.getTree().print());
- tree.setThreshold(tp.getTreeCanvas().getThreshold());
-
- tree.setFitToWindow(tp.fitToWindow.getState());
- tree.setFontName(tp.getTreeFont().getName());
- tree.setFontSize(tp.getTreeFont().getSize());
- tree.setFontStyle(tp.getTreeFont().getStyle());
- tree.setMarkUnlinked(tp.placeholdersMenu.getState());
-
- tree.setShowBootstrap(tp.bootstrapMenu.getState());
- tree.setShowDistances(tp.distanceMenu.getState());
-
- tree.setHeight(tp.getHeight());
- tree.setWidth(tp.getWidth());
- tree.setXpos(tp.getX());
- tree.setYpos(tp.getY());
- tree.setId(makeHashCode(tp, null));
- tree.setLinkToAllViews(
- tp.getTreeCanvas().isApplyToAllViews());
-
- // jms.addTree(tree);
- object.getTree().add(tree);
- }
- }
- }
- }
- }
-
- /*
- * save PCA viewers
- */
- if (!storeDS && Desktop.desktop != null)
- {
- for (JInternalFrame frame : Desktop.desktop.getAllFrames())
- {
- if (frame instanceof PCAPanel)
- {
- PCAPanel panel = (PCAPanel) frame;
- if (panel.getAlignViewport().getAlignment() == jal)
- {
- savePCA(panel, object);
- }
- }
- }
- }
-
- // SAVE ANNOTATIONS
- /**
- * store forward refs from an annotationRow to any groups
- */
- IdentityHashMap<SequenceGroup, String> groupRefs = new IdentityHashMap<>();
- if (storeDS)
- {
- for (SequenceI sq : jal.getSequences())
- {
- // Store annotation on dataset sequences only
- AlignmentAnnotation[] aa = sq.getAnnotation();
- if (aa != null && aa.length > 0)
- {
- storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
- vamsasSet);
- }
- }
- }
- else
- {
- if (jal.getAlignmentAnnotation() != null)
- {
- // Store the annotation shown on the alignment.
- AlignmentAnnotation[] aa = jal.getAlignmentAnnotation();
- storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
- vamsasSet);
- }
- }
- // SAVE GROUPS
- if (jal.getGroups() != null)
- {
- JGroup[] groups = new JGroup[jal.getGroups().size()];
- int i = -1;
- for (jalview.datamodel.SequenceGroup sg : jal.getGroups())
- {
- JGroup jGroup = new JGroup();
- groups[++i] = jGroup;
-
- jGroup.setStart(sg.getStartRes());
- jGroup.setEnd(sg.getEndRes());
- jGroup.setName(sg.getName());
- if (groupRefs.containsKey(sg))
- {
- // group has references so set its ID field
- jGroup.setId(groupRefs.get(sg));
- }
- ColourSchemeI colourScheme = sg.getColourScheme();
- if (colourScheme != null)
- {
- ResidueShaderI groupColourScheme = sg.getGroupColourScheme();
- if (groupColourScheme.conservationApplied())
- {
- jGroup.setConsThreshold(groupColourScheme.getConservationInc());
-
- if (colourScheme instanceof jalview.schemes.UserColourScheme)
- {
- jGroup.setColour(setUserColourScheme(colourScheme,
- userColours, object));
- }
- else
- {
- jGroup.setColour(colourScheme.getSchemeName());
- }
- }
- else if (colourScheme instanceof jalview.schemes.AnnotationColourGradient)
- {
- jGroup.setColour("AnnotationColourGradient");
- jGroup.setAnnotationColours(constructAnnotationColours(
- (jalview.schemes.AnnotationColourGradient) colourScheme,
- userColours, object));
- }
- else if (colourScheme instanceof jalview.schemes.UserColourScheme)
- {
- jGroup.setColour(
- setUserColourScheme(colourScheme, userColours, object));
- }
- else
- {
- jGroup.setColour(colourScheme.getSchemeName());
- }
-
- jGroup.setPidThreshold(groupColourScheme.getThreshold());
- }
-
- jGroup.setOutlineColour(sg.getOutlineColour().getRGB());
- jGroup.setDisplayBoxes(sg.getDisplayBoxes());
- jGroup.setDisplayText(sg.getDisplayText());
- jGroup.setColourText(sg.getColourText());
- jGroup.setTextCol1(sg.textColour.getRGB());
- jGroup.setTextCol2(sg.textColour2.getRGB());
- jGroup.setTextColThreshold(sg.thresholdTextColour);
- jGroup.setShowUnconserved(sg.getShowNonconserved());
- jGroup.setIgnoreGapsinConsensus(sg.getIgnoreGapsConsensus());
- jGroup.setShowConsensusHistogram(sg.isShowConsensusHistogram());
- jGroup.setShowSequenceLogo(sg.isShowSequenceLogo());
- jGroup.setNormaliseSequenceLogo(sg.isNormaliseSequenceLogo());
- for (SequenceI seq : sg.getSequences())
- {
- // jGroup.addSeq(seqHash(seq));
- jGroup.getSeq().add(seqHash(seq));
- }
- }
-
- // jms.setJGroup(groups);
- Object group;
- for (JGroup grp : groups)
- {
- object.getJGroup().add(grp);
- }
- }
- if (!storeDS)
- {
- // /////////SAVE VIEWPORT
- Viewport view = new Viewport();
- view.setTitle(ap.alignFrame.getTitle());
- view.setSequenceSetId(
- makeHashCode(av.getSequenceSetId(), av.getSequenceSetId()));
- view.setId(av.getViewId());
- if (av.getCodingComplement() != null)
- {
- view.setComplementId(av.getCodingComplement().getViewId());
- }
- view.setViewName(av.getViewName());
- view.setGatheredViews(av.isGatherViewsHere());
-
- Rectangle size = ap.av.getExplodedGeometry();
- Rectangle position = size;
- if (size == null)
- {
- size = ap.alignFrame.getBounds();
- if (av.getCodingComplement() != null)
- {
- position = ((SplitFrame) ap.alignFrame.getSplitViewContainer())
- .getBounds();
- }
- else
- {
- position = size;
- }
- }
- view.setXpos(position.x);
- view.setYpos(position.y);
-
- view.setWidth(size.width);
- view.setHeight(size.height);
-
- view.setStartRes(vpRanges.getStartRes());
- view.setStartSeq(vpRanges.getStartSeq());
-
- if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
- {
- view.setBgColour(setUserColourScheme(av.getGlobalColourScheme(),
- userColours, object));
- }
- else if (av
- .getGlobalColourScheme() instanceof jalview.schemes.AnnotationColourGradient)
- {
- AnnotationColourScheme ac = constructAnnotationColours(
- (jalview.schemes.AnnotationColourGradient) av
- .getGlobalColourScheme(),
- userColours, object);
-
- view.setAnnotationColours(ac);
- view.setBgColour("AnnotationColourGradient");
- }
- else
- {
- view.setBgColour(ColourSchemeProperty
- .getColourName(av.getGlobalColourScheme()));
- }
-
- ResidueShaderI vcs = av.getResidueShading();
- ColourSchemeI cs = av.getGlobalColourScheme();
-
- if (cs != null)
- {
- if (vcs.conservationApplied())
- {
- view.setConsThreshold(vcs.getConservationInc());
- if (cs instanceof jalview.schemes.UserColourScheme)
- {
- view.setBgColour(setUserColourScheme(cs, userColours, object));
- }
- }
- view.setPidThreshold(vcs.getThreshold());
- }
-
- view.setConservationSelected(av.getConservationSelected());
- view.setPidSelected(av.getAbovePIDThreshold());
- final Font font = av.getFont();
- view.setFontName(font.getName());
- view.setFontSize(font.getSize());
- view.setFontStyle(font.getStyle());
- view.setScaleProteinAsCdna(av.getViewStyle().isScaleProteinAsCdna());
- view.setRenderGaps(av.isRenderGaps());
- view.setShowAnnotation(av.isShowAnnotation());
- view.setShowBoxes(av.getShowBoxes());
- view.setShowColourText(av.getColourText());
- view.setShowFullId(av.getShowJVSuffix());
- view.setRightAlignIds(av.isRightAlignIds());
- view.setShowSequenceFeatures(av.isShowSequenceFeatures());
- view.setShowText(av.getShowText());
- view.setShowUnconserved(av.getShowUnconserved());
- view.setWrapAlignment(av.getWrapAlignment());
- view.setTextCol1(av.getTextColour().getRGB());
- view.setTextCol2(av.getTextColour2().getRGB());
- view.setTextColThreshold(av.getThresholdTextColour());
- view.setShowConsensusHistogram(av.isShowConsensusHistogram());
- view.setShowSequenceLogo(av.isShowSequenceLogo());
- view.setNormaliseSequenceLogo(av.isNormaliseSequenceLogo());
- view.setShowGroupConsensus(av.isShowGroupConsensus());
- view.setShowGroupConservation(av.isShowGroupConservation());
- view.setShowNPfeatureTooltip(av.isShowNPFeats());
- view.setShowDbRefTooltip(av.isShowDBRefs());
- view.setFollowHighlight(av.isFollowHighlight());
- view.setFollowSelection(av.followSelection);
- view.setIgnoreGapsinConsensus(av.isIgnoreGapsConsensus());
- view.setShowComplementFeatures(av.isShowComplementFeatures());
- view.setShowComplementFeaturesOnTop(
- av.isShowComplementFeaturesOnTop());
- if (av.getFeaturesDisplayed() != null)
- {
- FeatureSettings fs = new FeatureSettings();
-
- FeatureRendererModel fr = ap.getSeqPanel().seqCanvas
- .getFeatureRenderer();
- String[] renderOrder = fr.getRenderOrder().toArray(new String[0]);
-
- Vector<String> settingsAdded = new Vector<>();
- if (renderOrder != null)
- {
- for (String featureType : renderOrder)
- {
- FeatureSettings.Setting setting = new FeatureSettings.Setting();
- setting.setType(featureType);
-
- /*
- * save any filter for the feature type
- */
- FeatureMatcherSetI filter = fr.getFeatureFilter(featureType);
- if (filter != null)
- {
- Iterator<FeatureMatcherI> filters = filter.getMatchers()
- .iterator();
- FeatureMatcherI firstFilter = filters.next();
- setting.setMatcherSet(Jalview2XML.marshalFilter(firstFilter,
- filters, filter.isAnded()));
- }
-
- /*
- * save colour scheme for the feature type
- */
- FeatureColourI fcol = fr.getFeatureStyle(featureType);
- if (!fcol.isSimpleColour())
- {
- setting.setColour(fcol.getMaxColour().getRGB());
- setting.setMincolour(fcol.getMinColour().getRGB());
- setting.setMin(fcol.getMin());
- setting.setMax(fcol.getMax());
- setting.setColourByLabel(fcol.isColourByLabel());
- if (fcol.isColourByAttribute())
- {
- String[] attName = fcol.getAttributeName();
- setting.getAttributeName().add(attName[0]);
- if (attName.length > 1)
- {
- setting.getAttributeName().add(attName[1]);
- }
- }
- setting.setAutoScale(fcol.isAutoScaled());
- setting.setThreshold(fcol.getThreshold());
- Color noColour = fcol.getNoColour();
- if (noColour == null)
- {
- setting.setNoValueColour(NoValueColour.NONE);
- }
- else if (noColour.equals(fcol.getMaxColour()))
- {
- setting.setNoValueColour(NoValueColour.MAX);
- }
- else
- {
- setting.setNoValueColour(NoValueColour.MIN);
- }
- // -1 = No threshold, 0 = Below, 1 = Above
- setting.setThreshstate(fcol.isAboveThreshold() ? 1
- : (fcol.isBelowThreshold() ? 0 : -1));
- }
- else
- {
- setting.setColour(fcol.getColour().getRGB());
- }
-
- setting.setDisplay(
- av.getFeaturesDisplayed().isVisible(featureType));
- float rorder = fr.getOrder(featureType);
- if (rorder > -1)
- {
- setting.setOrder(rorder);
- }
- /// fs.addSetting(setting);
- fs.getSetting().add(setting);
- settingsAdded.addElement(featureType);
- }
- }
-
- // is groups actually supposed to be a map here ?
- Iterator<String> en = fr.getFeatureGroups().iterator();
- Vector<String> groupsAdded = new Vector<>();
- while (en.hasNext())
- {
- String grp = en.next();
- if (groupsAdded.contains(grp))
- {
- continue;
- }
- Group g = new Group();
- g.setName(grp);
- g.setDisplay(((Boolean) fr.checkGroupVisibility(grp, false))
- .booleanValue());
- // fs.addGroup(g);
- fs.getGroup().add(g);
- groupsAdded.addElement(grp);
- }
- // jms.setFeatureSettings(fs);
- object.setFeatureSettings(fs);
- }
-
- if (av.hasHiddenColumns())
- {
- jalview.datamodel.HiddenColumns hidden = av.getAlignment()
- .getHiddenColumns();
- if (hidden == null)
- {
- Console.warn(
- "REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
- }
- else
- {
- Iterator<int[]> hiddenRegions = hidden.iterator();
- while (hiddenRegions.hasNext())
- {
- int[] region = hiddenRegions.next();
- HiddenColumns hc = new HiddenColumns();
- hc.setStart(region[0]);
- hc.setEnd(region[1]);
- // view.addHiddenColumns(hc);
- view.getHiddenColumns().add(hc);
- }
- }
- }
- if (calcIdSet.size() > 0)
- {
- for (String calcId : calcIdSet)
- {
- if (calcId.trim().length() > 0)
- {
- CalcIdParam cidp = createCalcIdParam(calcId, av);
- // Some calcIds have no parameters.
- if (cidp != null)
- {
- // view.addCalcIdParam(cidp);
- view.getCalcIdParam().add(cidp);
- }
- }
- }
- }
-
- // jms.addViewport(view);
- object.getViewport().add(view);
- }
- // object.setJalviewModelSequence(jms);
- // object.getVamsasModel().addSequenceSet(vamsasSet);
- object.getVamsasModel().getSequenceSet().add(vamsasSet);
-
- if (jout != null && fileName != null)
- {
- // We may not want to write the object to disk,
- // eg we can copy the alignViewport to a new view object
- // using save and then load
- try
- {
- fileName = fileName.replace('\\', '/');
- System.out.println("Writing jar entry " + fileName);
- JarEntry entry = new JarEntry(fileName);
- jout.putNextEntry(entry);
- PrintWriter pout = new PrintWriter(
- new OutputStreamWriter(jout, UTF_8));
- JAXBContext jaxbContext = JAXBContext
- .newInstance(JalviewModel.class);
- Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
-
- // output pretty printed
- // jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- jaxbMarshaller.marshal(
- new ObjectFactory().createJalviewModel(object), pout);
-
- // jaxbMarshaller.marshal(object, pout);
- // marshaller.marshal(object);
- pout.flush();
- jout.closeEntry();
- } catch (Exception ex)
- {
- // TODO: raise error in GUI if marshalling failed.
- System.err.println("Error writing Jalview project");
- ex.printStackTrace();
- }
- }
- return object;
- }
-
- /**
- * Writes PCA viewer attributes and computed values to an XML model object and
- * adds it to the JalviewModel. Any exceptions are reported by logging.
- */
- protected void savePCA(PCAPanel panel, JalviewModel object)
- {
- try
- {
- PcaViewer viewer = new PcaViewer();
- viewer.setHeight(panel.getHeight());
- viewer.setWidth(panel.getWidth());
- viewer.setXpos(panel.getX());
- viewer.setYpos(panel.getY());
- viewer.setTitle(panel.getTitle());
- PCAModel pcaModel = panel.getPcaModel();
- viewer.setScoreModelName(pcaModel.getScoreModelName());
- viewer.setXDim(panel.getSelectedDimensionIndex(X));
- viewer.setYDim(panel.getSelectedDimensionIndex(Y));
- viewer.setZDim(panel.getSelectedDimensionIndex(Z));
- viewer.setBgColour(
- panel.getRotatableCanvas().getBackgroundColour().getRGB());
- viewer.setScaleFactor(panel.getRotatableCanvas().getScaleFactor());
- float[] spMin = panel.getRotatableCanvas().getSeqMin();
- SeqPointMin spmin = new SeqPointMin();
- spmin.setXPos(spMin[0]);
- spmin.setYPos(spMin[1]);
- spmin.setZPos(spMin[2]);
- viewer.setSeqPointMin(spmin);
- float[] spMax = panel.getRotatableCanvas().getSeqMax();
- SeqPointMax spmax = new SeqPointMax();
- spmax.setXPos(spMax[0]);
- spmax.setYPos(spMax[1]);
- spmax.setZPos(spMax[2]);
- viewer.setSeqPointMax(spmax);
- viewer.setShowLabels(panel.getRotatableCanvas().isShowLabels());
- viewer.setLinkToAllViews(
- panel.getRotatableCanvas().isApplyToAllViews());
- SimilarityParamsI sp = pcaModel.getSimilarityParameters();
- viewer.setIncludeGaps(sp.includeGaps());
- viewer.setMatchGaps(sp.matchGaps());
- viewer.setIncludeGappedColumns(sp.includeGappedColumns());
- viewer.setDenominateByShortestLength(sp.denominateByShortestLength());
-
- /*
- * sequence points on display
- */
- for (jalview.datamodel.SequencePoint spt : pcaModel
- .getSequencePoints())
- {
- SequencePoint point = new SequencePoint();
- point.setSequenceRef(seqHash(spt.getSequence()));
- point.setXPos(spt.coord.x);
- point.setYPos(spt.coord.y);
- point.setZPos(spt.coord.z);
- viewer.getSequencePoint().add(point);
- }
-
- /*
- * (end points of) axes on display
- */
- for (Point p : panel.getRotatableCanvas().getAxisEndPoints())
- {
-
- Axis axis = new Axis();
- axis.setXPos(p.x);
- axis.setYPos(p.y);
- axis.setZPos(p.z);
- viewer.getAxis().add(axis);
- }
-
- /*
- * raw PCA data (note we are not restoring PCA inputs here -
- * alignment view, score model, similarity parameters)
- */
- PcaDataType data = new PcaDataType();
- viewer.setPcaData(data);
- PCA pca = pcaModel.getPcaData();
-
- DoubleMatrix pm = new DoubleMatrix();
- saveDoubleMatrix(pca.getPairwiseScores(), pm);
- data.setPairwiseMatrix(pm);
-
- DoubleMatrix tm = new DoubleMatrix();
- saveDoubleMatrix(pca.getTridiagonal(), tm);
- data.setTridiagonalMatrix(tm);
-
- DoubleMatrix eigenMatrix = new DoubleMatrix();
- data.setEigenMatrix(eigenMatrix);
- saveDoubleMatrix(pca.getEigenmatrix(), eigenMatrix);
-
- object.getPcaViewer().add(viewer);
- } catch (Throwable t)
- {
- Console.error("Error saving PCA: " + t.getMessage());
- }
- }
-
- /**
- * Stores values from a matrix into an XML element, including (if present) the
- * D or E vectors
- *
- * @param m
- * @param xmlMatrix
- * @see #loadDoubleMatrix(DoubleMatrix)
- */
- protected void saveDoubleMatrix(MatrixI m, DoubleMatrix xmlMatrix)
- {
- xmlMatrix.setRows(m.height());
- xmlMatrix.setColumns(m.width());
- for (int i = 0; i < m.height(); i++)
- {
- DoubleVector row = new DoubleVector();
- for (int j = 0; j < m.width(); j++)
- {
- row.getV().add(m.getValue(i, j));
- }
- xmlMatrix.getRow().add(row);
- }
- if (m.getD() != null)
- {
- DoubleVector dVector = new DoubleVector();
- for (double d : m.getD())
- {
- dVector.getV().add(d);
- }
- xmlMatrix.setD(dVector);
- }
- if (m.getE() != null)
- {
- DoubleVector eVector = new DoubleVector();
- for (double e : m.getE())
- {
- eVector.getV().add(e);
- }
- xmlMatrix.setE(eVector);
- }
- }
-
- /**
- * Loads XML matrix data into a new Matrix object, including the D and/or E
- * vectors (if present)
- *
- * @param mData
- * @return
- * @see Jalview2XML#saveDoubleMatrix(MatrixI, DoubleMatrix)
- */
- protected MatrixI loadDoubleMatrix(DoubleMatrix mData)
- {
- int rows = mData.getRows();
- double[][] vals = new double[rows][];
-
- for (int i = 0; i < rows; i++)
- {
- List<Double> dVector = mData.getRow().get(i).getV();
- vals[i] = new double[dVector.size()];
- int dvi = 0;
- for (Double d : dVector)
- {
- vals[i][dvi++] = d;
- }
- }
-
- MatrixI m = new Matrix(vals);
-
- if (mData.getD() != null)
- {
- List<Double> dVector = mData.getD().getV();
- double[] vec = new double[dVector.size()];
- int dvi = 0;
- for (Double d : dVector)
- {
- vec[dvi++] = d;
- }
- m.setD(vec);
- }
- if (mData.getE() != null)
- {
- List<Double> dVector = mData.getE().getV();
- double[] vec = new double[dVector.size()];
- int dvi = 0;
- for (Double d : dVector)
- {
- vec[dvi++] = d;
- }
- m.setE(vec);
- }
-
- return m;
- }
-
- /**
- * Save any Varna viewers linked to this sequence. Writes an rnaViewer element
- * for each viewer, with
- * <ul>
- * <li>viewer geometry (position, size, split pane divider location)</li>
- * <li>index of the selected structure in the viewer (currently shows gapped
- * or ungapped)</li>
- * <li>the id of the annotation holding RNA secondary structure</li>
- * <li>(currently only one SS is shown per viewer, may be more in future)</li>
- * </ul>
- * Varna viewer state is also written out (in native Varna XML) to separate
- * project jar entries. A separate entry is written for each RNA structure
- * displayed, with the naming convention
- * <ul>
- * <li>rna_viewId_sequenceId_annotationId_[gapped|trimmed]</li>
- * </ul>
- *
- * @param jout
- * @param jseq
- * @param jds
- * @param viewIds
- * @param ap
- * @param storeDataset
- */
- protected void saveRnaViewers(JarOutputStream jout, JSeq jseq,
- final SequenceI jds, List<String> viewIds, AlignmentPanel ap,
- boolean storeDataset)
- {
- if (Desktop.desktop == null)
- {
- return;
- }
- JInternalFrame[] frames = Desktop.desktop.getAllFrames();
- for (int f = frames.length - 1; f > -1; f--)
- {
- if (frames[f] instanceof AppVarna)
- {
- AppVarna varna = (AppVarna) frames[f];
- /*
- * link the sequence to every viewer that is showing it and is linked to
- * its alignment panel
- */
- if (varna.isListeningFor(jds) && ap == varna.getAlignmentPanel())
- {
- String viewId = varna.getViewId();
- RnaViewer rna = new RnaViewer();
- rna.setViewId(viewId);
- rna.setTitle(varna.getTitle());
- rna.setXpos(varna.getX());
- rna.setYpos(varna.getY());
- rna.setWidth(varna.getWidth());
- rna.setHeight(varna.getHeight());
- rna.setDividerLocation(varna.getDividerLocation());
- rna.setSelectedRna(varna.getSelectedIndex());
- // jseq.addRnaViewer(rna);
- jseq.getRnaViewer().add(rna);
-
- /*
- * Store each Varna panel's state once in the project per sequence.
- * First time through only (storeDataset==false)
- */
- // boolean storeSessions = false;
- // String sequenceViewId = viewId + seqsToIds.get(jds);
- // if (!storeDataset && !viewIds.contains(sequenceViewId))
- // {
- // viewIds.add(sequenceViewId);
- // storeSessions = true;
- // }
- for (RnaModel model : varna.getModels())
- {
- if (model.seq == jds)
- {
- /*
- * VARNA saves each view (sequence or alignment secondary
- * structure, gapped or trimmed) as a separate XML file
- */
- String jarEntryName = rnaSessions.get(model);
- if (jarEntryName == null)
- {
-
- String varnaStateFile = varna.getStateInfo(model.rna);
- jarEntryName = RNA_PREFIX + viewId + "_" + nextCounter();
- copyFileToJar(jout, varnaStateFile, jarEntryName, "Varna");
- rnaSessions.put(model, jarEntryName);
- }
- SecondaryStructure ss = new SecondaryStructure();
- String annotationId = varna.getAnnotation(jds).annotationId;
- ss.setAnnotationId(annotationId);
- ss.setViewerState(jarEntryName);
- ss.setGapped(model.gapped);
- ss.setTitle(model.title);
- // rna.addSecondaryStructure(ss);
- rna.getSecondaryStructure().add(ss);
- }
- }
- }
- }
- }
- }
-
- /**
- * Copy the contents of a file to a new entry added to the output jar
- *
- * @param jout
- * @param infilePath
- * @param jarEntryName
- * @param msg
- * additional identifying info to log to the console
- */
- protected void copyFileToJar(JarOutputStream jout, String infilePath,
- String jarEntryName, String msg)
- {
- try (InputStream is = new FileInputStream(infilePath))
- {
- File file = new File(infilePath);
- if (file.exists() && jout != null)
- {
- System.out.println(
- "Writing jar entry " + jarEntryName + " (" + msg + ")");
- jout.putNextEntry(new JarEntry(jarEntryName));
- copyAll(is, jout);
- jout.closeEntry();
- // dis = new DataInputStream(new FileInputStream(file));
- // byte[] data = new byte[(int) file.length()];
- // dis.readFully(data);
- // writeJarEntry(jout, jarEntryName, data);
- }
- } catch (Exception ex)
- {
- ex.printStackTrace();
- }
- }
-
- /**
- * Copies input to output, in 4K buffers; handles any data (text or binary)
- *
- * @param in
- * @param out
- * @throws IOException
- */
- protected void copyAll(InputStream in, OutputStream out)
- throws IOException
- {
- byte[] buffer = new byte[4096];
- int bytesRead = 0;
- while ((bytesRead = in.read(buffer)) != -1)
- {
- out.write(buffer, 0, bytesRead);
- }
- }
-
- /**
- * Save the state of a structure viewer
- *
- * @param ap
- * @param jds
- * @param pdb
- * the archive XML element under which to save the state
- * @param entry
- * @param viewIds
- * @param matchedFile
- * @param viewFrame
- * @return
- */
- protected String saveStructureViewer(AlignmentPanel ap, SequenceI jds,
- Pdbids pdb, PDBEntry entry, List<String> viewIds,
- String matchedFile, StructureViewerBase viewFrame)
- {
- final AAStructureBindingModel bindingModel = viewFrame.getBinding();
-
- /*
- * Look for any bindings for this viewer to the PDB file of interest
- * (including part matches excluding chain id)
- */
- for (int peid = 0; peid < bindingModel.getPdbCount(); peid++)
- {
- final PDBEntry pdbentry = bindingModel.getPdbEntry(peid);
- final String pdbId = pdbentry.getId();
- if (!pdbId.equals(entry.getId()) && !(entry.getId().length() > 4
- && entry.getId().toLowerCase(Locale.ROOT)
- .startsWith(pdbId.toLowerCase(Locale.ROOT))))
- {
- /*
- * not interested in a binding to a different PDB entry here
- */
- continue;
- }
- if (matchedFile == null)
- {
- matchedFile = pdbentry.getFile();
- }
- else if (!matchedFile.equals(pdbentry.getFile()))
- {
- Console.warn(
- "Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
- + pdbentry.getFile());
- }
- // record the
- // file so we
- // can get at it if the ID
- // match is ambiguous (e.g.
- // 1QIP==1qipA)
-
- for (int smap = 0; smap < viewFrame.getBinding()
- .getSequence()[peid].length; smap++)
- {
- // if (jal.findIndex(jmol.jmb.sequence[peid][smap]) > -1)
- if (jds == viewFrame.getBinding().getSequence()[peid][smap])
- {
- StructureState state = new StructureState();
- state.setVisible(true);
- state.setXpos(viewFrame.getX());
- state.setYpos(viewFrame.getY());
- state.setWidth(viewFrame.getWidth());
- state.setHeight(viewFrame.getHeight());
- final String viewId = viewFrame.getViewId();
- state.setViewId(viewId);
- state.setAlignwithAlignPanel(viewFrame.isUsedforaligment(ap));
- state.setColourwithAlignPanel(viewFrame.isUsedForColourBy(ap));
- state.setColourByJmol(viewFrame.isColouredByViewer());
- state.setType(viewFrame.getViewerType().toString());
- // pdb.addStructureState(state);
- pdb.getStructureState().add(state);
- }
- }
- }
- return matchedFile;
- }
-
- /**
- * Populates the AnnotationColourScheme xml for save. This captures the
- * settings of the options in the 'Colour by Annotation' dialog.
- *
- * @param acg
- * @param userColours
- * @param jm
- * @return
- */
- private AnnotationColourScheme constructAnnotationColours(
- AnnotationColourGradient acg, List<UserColourScheme> userColours,
- JalviewModel jm)
- {
- AnnotationColourScheme ac = new AnnotationColourScheme();
- ac.setAboveThreshold(acg.getAboveThreshold());
- ac.setThreshold(acg.getAnnotationThreshold());
- // 2.10.2 save annotationId (unique) not annotation label
- ac.setAnnotation(acg.getAnnotation().annotationId);
- if (acg.getBaseColour() instanceof UserColourScheme)
- {
- ac.setColourScheme(
- setUserColourScheme(acg.getBaseColour(), userColours, jm));
- }
- else
- {
- ac.setColourScheme(
- ColourSchemeProperty.getColourName(acg.getBaseColour()));
- }
-
- ac.setMaxColour(acg.getMaxColour().getRGB());
- ac.setMinColour(acg.getMinColour().getRGB());
- ac.setPerSequence(acg.isSeqAssociated());
- ac.setPredefinedColours(acg.isPredefinedColours());
- return ac;
- }
-
- private void storeAlignmentAnnotation(AlignmentAnnotation[] aa,
- IdentityHashMap<SequenceGroup, String> groupRefs,
- AlignmentViewport av, Set<String> calcIdSet, boolean storeDS,
- SequenceSet vamsasSet)
- {
-
- for (int i = 0; i < aa.length; i++)
- {
- Annotation an = new Annotation();
-
- AlignmentAnnotation annotation = aa[i];
- if (annotation.annotationId != null)
- {
- annotationIds.put(annotation.annotationId, annotation);
- }
-
- an.setId(annotation.annotationId);
-
- an.setVisible(annotation.visible);
-
- an.setDescription(annotation.description);
-
- if (annotation.sequenceRef != null)
- {
- // 2.9 JAL-1781 xref on sequence id rather than name
- an.setSequenceRef(seqsToIds.get(annotation.sequenceRef));
- }
- if (annotation.groupRef != null)
- {
- String groupIdr = groupRefs.get(annotation.groupRef);
- if (groupIdr == null)
- {
- // make a locally unique String
- groupRefs.put(annotation.groupRef,
- groupIdr = ("" + System.currentTimeMillis()
- + annotation.groupRef.getName()
- + groupRefs.size()));
- }
- an.setGroupRef(groupIdr.toString());
- }
-
- // store all visualization attributes for annotation
- an.setGraphHeight(annotation.graphHeight);
- an.setCentreColLabels(annotation.centreColLabels);
- an.setScaleColLabels(annotation.scaleColLabel);
- an.setShowAllColLabels(annotation.showAllColLabels);
- an.setBelowAlignment(annotation.belowAlignment);
-
- if (annotation.graph > 0)
- {
- an.setGraph(true);
- an.setGraphType(annotation.graph);
- an.setGraphGroup(annotation.graphGroup);
- if (annotation.getThreshold() != null)
- {
- ThresholdLine line = new ThresholdLine();
- line.setLabel(annotation.getThreshold().label);
- line.setValue(annotation.getThreshold().value);
- line.setColour(annotation.getThreshold().colour.getRGB());
- an.setThresholdLine(line);
- }
- }
- else
- {
- an.setGraph(false);
- }
-
- an.setLabel(annotation.label);
-
- if (annotation == av.getAlignmentQualityAnnot()
- || annotation == av.getAlignmentConservationAnnotation()
- || annotation == av.getAlignmentConsensusAnnotation()
- || annotation.autoCalculated)
- {
- // new way of indicating autocalculated annotation -
- an.setAutoCalculated(annotation.autoCalculated);
- }
- if (annotation.hasScore())
- {
- an.setScore(annotation.getScore());
- }
-
- if (annotation.getCalcId() != null)
- {
- calcIdSet.add(annotation.getCalcId());
- an.setCalcId(annotation.getCalcId());
- }
- if (annotation.hasProperties())
- {
- for (String pr : annotation.getProperties())
- {
- jalview.xml.binding.jalview.Annotation.Property prop = new jalview.xml.binding.jalview.Annotation.Property();
- prop.setName(pr);
- prop.setValue(annotation.getProperty(pr));
- // an.addProperty(prop);
- an.getProperty().add(prop);
- }
- }
-
- AnnotationElement ae;
- if (annotation.annotations != null)
- {
- an.setScoreOnly(false);
- for (int a = 0; a < annotation.annotations.length; a++)
- {
- if ((annotation == null) || (annotation.annotations[a] == null))
- {
- continue;
- }
-
- ae = new AnnotationElement();
- if (annotation.annotations[a].description != null)
- {
- ae.setDescription(annotation.annotations[a].description);
- }
- if (annotation.annotations[a].displayCharacter != null)
- {
- ae.setDisplayCharacter(
- annotation.annotations[a].displayCharacter);
- }
-
- if (!Float.isNaN(annotation.annotations[a].value))
- {
- ae.setValue(annotation.annotations[a].value);
- }
-
- ae.setPosition(a);
- if (annotation.annotations[a].secondaryStructure > ' ')
- {
- ae.setSecondaryStructure(
- annotation.annotations[a].secondaryStructure + "");
- }
-
- if (annotation.annotations[a].colour != null
- && annotation.annotations[a].colour != java.awt.Color.black)
- {
- ae.setColour(annotation.annotations[a].colour.getRGB());
- }
-
- // an.addAnnotationElement(ae);
- an.getAnnotationElement().add(ae);
- if (annotation.autoCalculated)
- {
- // only write one non-null entry into the annotation row -
- // sufficient to get the visualization attributes necessary to
- // display data
- continue;
- }
- }
- }
- else
- {
- an.setScoreOnly(true);
- }
- if (!storeDS || (storeDS && !annotation.autoCalculated))
- {
- // skip autocalculated annotation - these are only provided for
- // alignments
- // vamsasSet.addAnnotation(an);
- vamsasSet.getAnnotation().add(an);
- }
- }
-
- }
-
- private CalcIdParam createCalcIdParam(String calcId, AlignViewport av)
- {
- AutoCalcSetting settings = av.getCalcIdSettingsFor(calcId);
- if (settings != null)
- {
- CalcIdParam vCalcIdParam = new CalcIdParam();
- vCalcIdParam.setCalcId(calcId);
- // vCalcIdParam.addServiceURL(settings.getServiceURI());
- vCalcIdParam.getServiceURL().add(settings.getServiceURI());
- // generic URI allowing a third party to resolve another instance of the
- // service used for this calculation
- for (String url : settings.getServiceURLs())
- {
- // vCalcIdParam.addServiceURL(urls);
- vCalcIdParam.getServiceURL().add(url);
- }
- vCalcIdParam.setVersion("1.0");
- if (settings.getPreset() != null)
- {
- WsParamSetI setting = settings.getPreset();
- vCalcIdParam.setName(setting.getName());
- vCalcIdParam.setDescription(setting.getDescription());
- }
- else
- {
- vCalcIdParam.setName("");
- vCalcIdParam.setDescription("Last used parameters");
- }
- // need to be able to recover 1) settings 2) user-defined presets or
- // recreate settings from preset 3) predefined settings provided by
- // service - or settings that can be transferred (or discarded)
- vCalcIdParam.setParameters(
- settings.getWsParamFile().replace("\n", "|\\n|"));
- vCalcIdParam.setAutoUpdate(settings.isAutoUpdate());
- // todo - decide if updateImmediately is needed for any projects.
-
- return vCalcIdParam;
- }
- return null;
- }
-
- private boolean recoverCalcIdParam(CalcIdParam calcIdParam,
- AlignViewport av)
- {
- if (calcIdParam.getVersion().equals("1.0"))
- {
- final String[] calcIds = calcIdParam.getServiceURL()
- .toArray(new String[0]);
- Jws2Instance service = Jws2Discoverer.getDiscoverer()
- .getPreferredServiceFor(calcIds);
- if (service != null)
- {
- WsParamSetI parmSet = null;
- try
- {
- parmSet = service.getParamStore().parseServiceParameterFile(
- calcIdParam.getName(), calcIdParam.getDescription(),
- calcIds,
- calcIdParam.getParameters().replace("|\\n|", "\n"));
- } catch (IOException x)
- {
- Console.warn("Couldn't parse parameter data for "
- + calcIdParam.getCalcId(), x);
- return false;
- }
- List<ArgumentI> argList = null;
- if (calcIdParam.getName().length() > 0)
- {
- parmSet = service.getParamStore()
- .getPreset(calcIdParam.getName());
- if (parmSet != null)
- {
- // TODO : check we have a good match with settings in AACon -
- // otherwise we'll need to create a new preset
- }
- }
- else
- {
- argList = parmSet.getArguments();
- parmSet = null;
- }
- AAConSettings settings = new AAConSettings(
- calcIdParam.isAutoUpdate(), service, parmSet, argList);
- av.setCalcIdSettingsFor(calcIdParam.getCalcId(), settings,
- calcIdParam.isNeedsUpdate());
- return true;
- }
- else
- {
- Console.warn(
- "Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server.");
- return false;
- }
- }
- throw new Error(MessageManager.formatMessage(
- "error.unsupported_version_calcIdparam", new Object[]
- { calcIdParam.toString() }));
- }
-
- /**
- * External mapping between jalview objects and objects yielding a valid and
- * unique object ID string. This is null for normal Jalview project IO, but
- * non-null when a jalview project is being read or written as part of a
- * vamsas session.
- */
- IdentityHashMap jv2vobj = null;
-
- /**
- * Construct a unique ID for jvobj using either existing bindings or if none
- * exist, the result of the hashcode call for the object.
- *
- * @param jvobj
- * jalview data object
- * @return unique ID for referring to jvobj
- */
- private String makeHashCode(Object jvobj, String altCode)
- {
- if (jv2vobj != null)
- {
- Object id = jv2vobj.get(jvobj);
- if (id != null)
- {
- return id.toString();
- }
- // check string ID mappings
- if (jvids2vobj != null && jvobj instanceof String)
- {
- id = jvids2vobj.get(jvobj);
- }
- if (id != null)
- {
- return id.toString();
- }
- // give up and warn that something has gone wrong
- Console.warn(
- "Cannot find ID for object in external mapping : " + jvobj);
- }
- return altCode;
- }
-
- /**
- * return local jalview object mapped to ID, if it exists
- *
- * @param idcode
- * (may be null)
- * @return null or object bound to idcode
- */
- private Object retrieveExistingObj(String idcode)
- {
- if (idcode != null && vobj2jv != null)
- {
- return vobj2jv.get(idcode);
- }
- return null;
- }
-
- /**
- * binding from ID strings from external mapping table to jalview data model
- * objects.
- */
- private Hashtable vobj2jv;
-
- private Sequence createVamsasSequence(String id, SequenceI jds)
- {
- return createVamsasSequence(true, id, jds, null);
- }
-
- private Sequence createVamsasSequence(boolean recurse, String id,
- SequenceI jds, SequenceI parentseq)
- {
- Sequence vamsasSeq = new Sequence();
- vamsasSeq.setId(id);
- vamsasSeq.setName(jds.getName());
- vamsasSeq.setSequence(jds.getSequenceAsString());
- vamsasSeq.setDescription(jds.getDescription());
- List<DBRefEntry> dbrefs = null;
- if (jds.getDatasetSequence() != null)
- {
- vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
- }
- else
- {
- // seqId==dsseqid so we can tell which sequences really are
- // dataset sequences only
- vamsasSeq.setDsseqid(id);
- dbrefs = jds.getDBRefs();
- if (parentseq == null)
- {
- parentseq = jds;
- }
- }
-
- /*
- * save any dbrefs; special subclass GeneLocus is flagged as 'locus'
- */
- if (dbrefs != null)
- {
- for (int d = 0, nd = dbrefs.size(); d < nd; d++)
- {
- DBRef dbref = new DBRef();
- DBRefEntry ref = dbrefs.get(d);
- dbref.setSource(ref.getSource());
- dbref.setVersion(ref.getVersion());
- dbref.setAccessionId(ref.getAccessionId());
- dbref.setCanonical(ref.isCanonical());
- if (ref instanceof GeneLocus)
- {
- dbref.setLocus(true);
- }
- if (ref.hasMap())
- {
- Mapping mp = createVamsasMapping(ref.getMap(), parentseq, jds,
- recurse);
- dbref.setMapping(mp);
- }
- vamsasSeq.getDBRef().add(dbref);
- }
- }
- return vamsasSeq;
- }
-
- private Mapping createVamsasMapping(jalview.datamodel.Mapping jmp,
- SequenceI parentseq, SequenceI jds, boolean recurse)
- {
- Mapping mp = null;
- if (jmp.getMap() != null)
- {
- mp = new Mapping();
-
- jalview.util.MapList mlst = jmp.getMap();
- List<int[]> r = mlst.getFromRanges();
- for (int[] range : r)
- {
- MapListFrom mfrom = new MapListFrom();
- mfrom.setStart(range[0]);
- mfrom.setEnd(range[1]);
- // mp.addMapListFrom(mfrom);
- mp.getMapListFrom().add(mfrom);
- }
- r = mlst.getToRanges();
- for (int[] range : r)
- {
- MapListTo mto = new MapListTo();
- mto.setStart(range[0]);
- mto.setEnd(range[1]);
- // mp.addMapListTo(mto);
- mp.getMapListTo().add(mto);
- }
- mp.setMapFromUnit(BigInteger.valueOf(mlst.getFromRatio()));
- mp.setMapToUnit(BigInteger.valueOf(mlst.getToRatio()));
- if (jmp.getTo() != null)
- {
- // MappingChoice mpc = new MappingChoice();
-
- // check/create ID for the sequence referenced by getTo()
-
- String jmpid = "";
- SequenceI ps = null;
- if (parentseq != jmp.getTo()
- && parentseq.getDatasetSequence() != jmp.getTo())
- {
- // chaining dbref rather than a handshaking one
- jmpid = seqHash(ps = jmp.getTo());
- }
- else
- {
- jmpid = seqHash(ps = parentseq);
- }
- // mpc.setDseqFor(jmpid);
- mp.setDseqFor(jmpid);
- if (!seqRefIds.containsKey(jmpid))
- {
- Console.debug("creatign new DseqFor ID");
- seqRefIds.put(jmpid, ps);
- }
- else
- {
- Console.debug("reusing DseqFor ID");
- }
-
- // mp.setMappingChoice(mpc);
- }
- }
- return mp;
- }
-
- String setUserColourScheme(jalview.schemes.ColourSchemeI cs,
- List<UserColourScheme> userColours, JalviewModel jm)
- {
- String id = null;
- jalview.schemes.UserColourScheme ucs = (jalview.schemes.UserColourScheme) cs;
- boolean newucs = false;
- if (!userColours.contains(ucs))
- {
- userColours.add(ucs);
- newucs = true;
- }
- id = "ucs" + userColours.indexOf(ucs);
- if (newucs)
- {
- // actually create the scheme's entry in the XML model
- java.awt.Color[] colours = ucs.getColours();
- UserColours uc = new UserColours();
- // UserColourScheme jbucs = new UserColourScheme();
- JalviewUserColours jbucs = new JalviewUserColours();
-
- for (int i = 0; i < colours.length; i++)
- {
- Colour col = new Colour();
- col.setName(ResidueProperties.aa[i]);
- col.setRGB(jalview.util.Format.getHexString(colours[i]));
- // jbucs.addColour(col);
- jbucs.getColour().add(col);
- }
- if (ucs.getLowerCaseColours() != null)
- {
- colours = ucs.getLowerCaseColours();
- for (int i = 0; i < colours.length; i++)
- {
- Colour col = new Colour();
- col.setName(ResidueProperties.aa[i].toLowerCase(Locale.ROOT));
- col.setRGB(jalview.util.Format.getHexString(colours[i]));
- // jbucs.addColour(col);
- jbucs.getColour().add(col);
- }
- }
-
- uc.setId(id);
- uc.setUserColourScheme(jbucs);
- // jm.addUserColours(uc);
- jm.getUserColours().add(uc);
- }
-
- return id;
- }
-
- jalview.schemes.UserColourScheme getUserColourScheme(JalviewModel jm,
- String id)
- {
- List<UserColours> uc = jm.getUserColours();
- UserColours colours = null;
- /*
- for (int i = 0; i < uc.length; i++)
- {
- if (uc[i].getId().equals(id))
- {
- colours = uc[i];
- break;
- }
- }
- */
- for (UserColours c : uc)
- {
- if (c.getId().equals(id))
- {
- colours = c;
- break;
- }
- }
-
- java.awt.Color[] newColours = new java.awt.Color[24];
-
- for (int i = 0; i < 24; i++)
- {
- newColours[i] = new java.awt.Color(Integer.parseInt(
- // colours.getUserColourScheme().getColour(i).getRGB(), 16));
- colours.getUserColourScheme().getColour().get(i).getRGB(),
- 16));
- }
-
- jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
- newColours);
-
- if (colours.getUserColourScheme().getColour().size()/*Count()*/ > 24)
- {
- newColours = new java.awt.Color[23];
- for (int i = 0; i < 23; i++)
- {
- newColours[i] = new java.awt.Color(
- Integer.parseInt(colours.getUserColourScheme().getColour()
- .get(i + 24).getRGB(), 16));
- }
- ucs.setLowerCaseColours(newColours);
- }
-
- return ucs;
- }
-
- /**
- * contains last error message (if any) encountered by XML loader.
- */
- String errorMessage = null;
-
- /**
- * flag to control whether the Jalview2XML_V1 parser should be deferred to if
- * exceptions are raised during project XML parsing
- */
- public boolean attemptversion1parse = false;
-
- /**
- * Load a jalview project archive from a jar file
- *
- * @param file
- * - HTTP URL or filename
- */
- public AlignFrame loadJalviewAlign(final Object file)
- {
-
- jalview.gui.AlignFrame af = null;
-
- try
- {
- // create list to store references for any new Jmol viewers created
- newStructureViewers = new Vector<>();
- // UNMARSHALLER SEEMS TO CLOSE JARINPUTSTREAM, MOST ANNOYING
- // Workaround is to make sure caller implements the JarInputStreamProvider
- // interface
- // so we can re-open the jar input stream for each entry.
-
- jarInputStreamProvider jprovider = createjarInputStreamProvider(file);
- af = loadJalviewAlign(jprovider);
- if (af != null)
- {
- af.setMenusForViewport();
- }
- } catch (MalformedURLException e)
- {
- errorMessage = "Invalid URL format for '" + file + "'";
- reportErrors();
- } finally
- {
- try
- {
- SwingUtilities.invokeAndWait(new Runnable()
- {
- @Override
- public void run()
- {
- setLoadingFinishedForNewStructureViewers();
- }
- });
- } catch (Exception x)
- {
- System.err.println("Error loading alignment: " + x.getMessage());
- }
- }
- return af;
- }
-
- @SuppressWarnings("unused")
- private jarInputStreamProvider createjarInputStreamProvider(
- final Object ofile) throws MalformedURLException
- {
-
- // BH 2018 allow for bytes already attached to File object
- try
- {
- String file = (ofile instanceof File
- ? ((File) ofile).getCanonicalPath()
- : ofile.toString());
- byte[] bytes = Platform.isJS() ? Platform.getFileBytes((File) ofile)
- : null;
- URL url = null;
- errorMessage = null;
- uniqueSetSuffix = null;
- seqRefIds = null;
- viewportsAdded.clear();
- frefedSequence = null;
-
- if (HttpUtils.startsWithHttpOrHttps(file))
- {
- url = new URL(file);
- }
- final URL _url = url;
- return new jarInputStreamProvider()
- {
-
- @Override
- public JarInputStream getJarInputStream() throws IOException
- {
- if (bytes != null)
- {
- // System.out.println("Jalview2XML: opening byte jarInputStream for
- // bytes.length=" + bytes.length);
- return new JarInputStream(new ByteArrayInputStream(bytes));
- }
- if (_url != null)
- {
- // System.out.println("Jalview2XML: opening url jarInputStream for "
- // + _url);
- return new JarInputStream(_url.openStream());
- }
- else
- {
- // System.out.println("Jalview2XML: opening file jarInputStream for
- // " + file);
- return new JarInputStream(new FileInputStream(file));
- }
- }
-
- @Override
- public String getFilename()
- {
- return file;
- }
- };
- } catch (IOException e)
- {
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * Recover jalview session from a jalview project archive. Caller may
- * initialise uniqueSetSuffix, seqRefIds, viewportsAdded and frefedSequence
- * themselves. Any null fields will be initialised with default values,
- * non-null fields are left alone.
- *
- * @param jprovider
- * @return
- */
- public AlignFrame loadJalviewAlign(final jarInputStreamProvider jprovider)
- {
- errorMessage = null;
- if (uniqueSetSuffix == null)
- {
- uniqueSetSuffix = System.currentTimeMillis() % 100000 + "";
- }
- if (seqRefIds == null)
- {
- initSeqRefs();
- }
- AlignFrame af = null, _af = null;
- IdentityHashMap<AlignmentI, AlignmentI> importedDatasets = new IdentityHashMap<>();
- Map<String, AlignFrame> gatherToThisFrame = new HashMap<>();
- final String file = jprovider.getFilename();
- try
- {
- JarInputStream jin = null;
- JarEntry jarentry = null;
- int entryCount = 1;
-
- do
- {
- jin = jprovider.getJarInputStream();
- for (int i = 0; i < entryCount; i++)
- {
- jarentry = jin.getNextJarEntry();
- }
-
- if (jarentry != null && jarentry.getName().endsWith(".xml"))
- {
- JAXBContext jc = JAXBContext
- .newInstance("jalview.xml.binding.jalview");
- XMLStreamReader streamReader = XMLInputFactory.newInstance()
- .createXMLStreamReader(jin);
- javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
- JAXBElement<JalviewModel> jbe = um.unmarshal(streamReader,
- JalviewModel.class);
- JalviewModel object = jbe.getValue();
-
- if (true) // !skipViewport(object))
- {
- _af = loadFromObject(object, file, true, jprovider);
- if (_af != null && object.getViewport().size() > 0)
- // getJalviewModelSequence().getViewportCount() > 0)
- {
- if (af == null)
- {
- // store a reference to the first view
- af = _af;
- }
- if (_af.getViewport().isGatherViewsHere())
- {
- // if this is a gathered view, keep its reference since
- // after gathering views, only this frame will remain
- af = _af;
- gatherToThisFrame.put(_af.getViewport().getSequenceSetId(),
- _af);
- }
- // Save dataset to register mappings once all resolved
- importedDatasets.put(
- af.getViewport().getAlignment().getDataset(),
- af.getViewport().getAlignment().getDataset());
- }
- }
- entryCount++;
- }
- else if (jarentry != null)
- {
- // Some other file here.
- entryCount++;
- }
- } while (jarentry != null);
- jin.close();
- resolveFrefedSequences();
- } catch (IOException ex)
- {
- ex.printStackTrace();
- errorMessage = "Couldn't locate Jalview XML file : " + file;
- System.err.println(
- "Exception whilst loading jalview XML file : " + ex + "\n");
- } catch (Exception ex)
- {
- System.err.println("Parsing as Jalview Version 2 file failed.");
- ex.printStackTrace(System.err);
- if (attemptversion1parse)
- {
- // used to attempt to parse as V1 castor-generated xml
- }
- if (Desktop.instance != null)
- {
- Desktop.instance.stopLoading();
- }
- if (af != null)
- {
- System.out.println("Successfully loaded archive file");
- return af;
- }
- ex.printStackTrace();
-
- System.err.println(
- "Exception whilst loading jalview XML file : " + ex + "\n");
- } catch (OutOfMemoryError e)
- {
- // Don't use the OOM Window here
- errorMessage = "Out of memory loading jalview XML file";
- System.err.println("Out of memory whilst loading jalview XML file");
- e.printStackTrace();
- }
-
- /*
- * Regather multiple views (with the same sequence set id) to the frame (if
- * any) that is flagged as the one to gather to, i.e. convert them to tabbed
- * views instead of separate frames. Note this doesn't restore a state where
- * some expanded views in turn have tabbed views - the last "first tab" read
- * in will play the role of gatherer for all.
- */
- for (AlignFrame fr : gatherToThisFrame.values())
- {
- Desktop.instance.gatherViews(fr);
- }
-
- restoreSplitFrames();
- for (AlignmentI ds : importedDatasets.keySet())
- {
- if (ds.getCodonFrames() != null)
- {
- StructureSelectionManager
- .getStructureSelectionManager(Desktop.instance)
- .registerMappings(ds.getCodonFrames());
- }
- }
- if (errorMessage != null)
- {
- reportErrors();
- }
-
- if (Desktop.instance != null)
- {
- Desktop.instance.stopLoading();
- }
-
- return af;
- }
-
- /**
- * Try to reconstruct and display SplitFrame windows, where each contains
- * complementary dna and protein alignments. Done by pairing up AlignFrame
- * objects (created earlier) which have complementary viewport ids associated.
- */
- protected void restoreSplitFrames()
- {
- List<SplitFrame> gatherTo = new ArrayList<>();
- List<AlignFrame> addedToSplitFrames = new ArrayList<>();
- Map<String, AlignFrame> dna = new HashMap<>();
-
- /*
- * Identify the DNA alignments
- */
- for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
- .entrySet())
- {
- AlignFrame af = candidate.getValue();
- if (af.getViewport().getAlignment().isNucleotide())
- {
- dna.put(candidate.getKey().getId(), af);
- }
- }
-
- /*
- * Try to match up the protein complements
- */
- for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
- .entrySet())
- {
- AlignFrame af = candidate.getValue();
- if (!af.getViewport().getAlignment().isNucleotide())
- {
- String complementId = candidate.getKey().getComplementId();
- // only non-null complements should be in the Map
- if (complementId != null && dna.containsKey(complementId))
- {
- final AlignFrame dnaFrame = dna.get(complementId);
- SplitFrame sf = createSplitFrame(dnaFrame, af);
- addedToSplitFrames.add(dnaFrame);
- addedToSplitFrames.add(af);
- dnaFrame.setMenusForViewport();
- af.setMenusForViewport();
- if (af.getViewport().isGatherViewsHere())
- {
- gatherTo.add(sf);
- }
- }
- }
- }
-
- /*
- * Open any that we failed to pair up (which shouldn't happen!) as
- * standalone AlignFrame's.
- */
- for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
- .entrySet())
- {
- AlignFrame af = candidate.getValue();
- if (!addedToSplitFrames.contains(af))
- {
- Viewport view = candidate.getKey();
- Desktop.addInternalFrame(af, view.getTitle(),
- safeInt(view.getWidth()), safeInt(view.getHeight()));
- af.setMenusForViewport();
- System.err.println("Failed to restore view " + view.getTitle()
- + " to split frame");
- }
- }
-
- /*
- * Gather back into tabbed views as flagged.
- */
- for (SplitFrame sf : gatherTo)
- {
- Desktop.instance.gatherViews(sf);
- }
-
- splitFrameCandidates.clear();
- }
-
- /**
- * Construct and display one SplitFrame holding DNA and protein alignments.
- *
- * @param dnaFrame
- * @param proteinFrame
- * @return
- */
- protected SplitFrame createSplitFrame(AlignFrame dnaFrame,
- AlignFrame proteinFrame)
- {
- SplitFrame splitFrame = new SplitFrame(dnaFrame, proteinFrame);
- String title = MessageManager.getString("label.linked_view_title");
- int width = (int) dnaFrame.getBounds().getWidth();
- int height = (int) (dnaFrame.getBounds().getHeight()
- + proteinFrame.getBounds().getHeight() + 50);
-
- /*
- * SplitFrame location is saved to both enclosed frames
- */
- splitFrame.setLocation(dnaFrame.getX(), dnaFrame.getY());
- Desktop.addInternalFrame(splitFrame, title, width, height);
-
- /*
- * And compute cDNA consensus (couldn't do earlier with consensus as
- * mappings were not yet present)
- */
- proteinFrame.getViewport().alignmentChanged(proteinFrame.alignPanel);
-
- return splitFrame;
- }
-
- /**
- * check errorMessage for a valid error message and raise an error box in the
- * GUI or write the current errorMessage to stderr and then clear the error
- * state.
- */
- protected void reportErrors()
- {
- reportErrors(false);
- }
-
- protected void reportErrors(final boolean saving)
- {
- if (errorMessage != null)
- {
- final String finalErrorMessage = errorMessage;
- if (raiseGUI)
- {
- javax.swing.SwingUtilities.invokeLater(new Runnable()
- {
- @Override
- public void run()
- {
- JvOptionPane.showInternalMessageDialog(Desktop.desktop,
- finalErrorMessage,
- "Error " + (saving ? "saving" : "loading")
- + " Jalview file",
- JvOptionPane.WARNING_MESSAGE);
- }
- });
- }
- else
- {
- System.err.println("Problem loading Jalview file: " + errorMessage);
- }
- }
- errorMessage = null;
- }
-
- Map<String, String> alreadyLoadedPDB = new HashMap<>();
-
- /**
- * when set, local views will be updated from view stored in JalviewXML
- * Currently (28th Sep 2008) things will go horribly wrong in vamsas document
- * sync if this is set to true.
- */
- private final boolean updateLocalViews = false;
-
- /**
- * Returns the path to a temporary file holding the PDB file for the given PDB
- * id. The first time of asking, searches for a file of that name in the
- * Jalview project jar, and copies it to a new temporary file. Any repeat
- * requests just return the path to the file previously created.
- *
- * @param jprovider
- * @param pdbId
- * @return
- */
- String loadPDBFile(jarInputStreamProvider jprovider, String pdbId,
- String origFile)
- {
- if (alreadyLoadedPDB.containsKey(pdbId))
- {
- return alreadyLoadedPDB.get(pdbId).toString();
- }
-
- String tempFile = copyJarEntry(jprovider, pdbId, "jalview_pdb",
- origFile);
- if (tempFile != null)
- {
- alreadyLoadedPDB.put(pdbId, tempFile);
- }
- return tempFile;
- }
-
- /**
- * Copies the jar entry of given name to a new temporary file and returns the
- * path to the file, or null if the entry is not found.
- *
- * @param jprovider
- * @param jarEntryName
- * @param prefix
- * a prefix for the temporary file name, must be at least three
- * characters long
- * @param suffixModel
- * null or original file - so new file can be given the same suffix
- * as the old one
- * @return
- */
- protected String copyJarEntry(jarInputStreamProvider jprovider,
- String jarEntryName, String prefix, String suffixModel)
- {
- String suffix = ".tmp";
- if (suffixModel == null)
- {
- suffixModel = jarEntryName;
- }
- int sfpos = suffixModel.lastIndexOf(".");
- if (sfpos > -1 && sfpos < (suffixModel.length() - 1))
- {
- suffix = "." + suffixModel.substring(sfpos + 1);
- }
-
- try (JarInputStream jin = jprovider.getJarInputStream())
- {
- JarEntry entry = null;
- do
- {
- entry = jin.getNextJarEntry();
- } while (entry != null && !entry.getName().equals(jarEntryName));
-
- if (entry != null)
- {
- // in = new BufferedReader(new InputStreamReader(jin, UTF_8));
- File outFile = File.createTempFile(prefix, suffix);
- outFile.deleteOnExit();
- try (OutputStream os = new FileOutputStream(outFile))
- {
- copyAll(jin, os);
- }
- String t = outFile.getAbsolutePath();
- return t;
- }
- else
- {
- Console.warn(
- "Couldn't find entry in Jalview Jar for " + jarEntryName);
- }
- } catch (Exception ex)
- {
- ex.printStackTrace();
- }
-
- return null;
- }
-
- private class JvAnnotRow
- {
- public JvAnnotRow(int i, AlignmentAnnotation jaa)
- {
- order = i;
- template = jaa;
- }
-
- /**
- * persisted version of annotation row from which to take vis properties
- */
- public jalview.datamodel.AlignmentAnnotation template;
-
- /**
- * original position of the annotation row in the alignment
- */
- public int order;
- }
-
- /**
- * Load alignment frame from jalview XML DOM object
- *
- * @param jalviewModel
- * DOM
- * @param file
- * filename source string
- * @param loadTreesAndStructures
- * when false only create Viewport
- * @param jprovider
- * data source provider
- * @return alignment frame created from view stored in DOM
- */
- AlignFrame loadFromObject(JalviewModel jalviewModel, String file,
- boolean loadTreesAndStructures, jarInputStreamProvider jprovider)
- {
- SequenceSet vamsasSet = jalviewModel.getVamsasModel().getSequenceSet()
- .get(0);
- List<Sequence> vamsasSeqs = vamsasSet.getSequence();
-
- // JalviewModelSequence jms = object.getJalviewModelSequence();
-
- // Viewport view = (jms.getViewportCount() > 0) ? jms.getViewport(0)
- // : null;
- Viewport view = (jalviewModel.getViewport().size() > 0)
- ? jalviewModel.getViewport().get(0)
- : null;
-
- // ////////////////////////////////
- // INITIALISE ALIGNMENT SEQUENCESETID AND VIEWID
- //
- //
- // If we just load in the same jar file again, the sequenceSetId
- // will be the same, and we end up with multiple references
- // to the same sequenceSet. We must modify this id on load
- // so that each load of the file gives a unique id
-
- /**
- * used to resolve correct alignment dataset for alignments with multiple
- * views
- */
- String uniqueSeqSetId = null;
- String viewId = null;
- if (view != null)
- {
- uniqueSeqSetId = view.getSequenceSetId() + uniqueSetSuffix;
- viewId = (view.getId() == null ? null
- : view.getId() + uniqueSetSuffix);
- }
-
- // ////////////////////////////////
- // LOAD SEQUENCES
-
- List<SequenceI> hiddenSeqs = null;
-
- List<SequenceI> tmpseqs = new ArrayList<>();
-
- boolean multipleView = false;
- SequenceI referenceseqForView = null;
- // JSeq[] jseqs = object.getJalviewModelSequence().getJSeq();
- List<JSeq> jseqs = jalviewModel.getJSeq();
- int vi = 0; // counter in vamsasSeq array
- for (int i = 0; i < jseqs.size(); i++)
- {
- JSeq jseq = jseqs.get(i);
- String seqId = jseq.getId();
-
- SequenceI tmpSeq = seqRefIds.get(seqId);
- if (tmpSeq != null)
- {
- if (!incompleteSeqs.containsKey(seqId))
- {
- // may not need this check, but keep it for at least 2.9,1 release
- if (tmpSeq.getStart() != jseq.getStart()
- || tmpSeq.getEnd() != jseq.getEnd())
- {
- System.err.println(String.format(
- "Warning JAL-2154 regression: updating start/end for sequence %s from %d/%d to %d/%d",
- tmpSeq.getName(), tmpSeq.getStart(), tmpSeq.getEnd(),
- jseq.getStart(), jseq.getEnd()));
- }
- }
- else
- {
- incompleteSeqs.remove(seqId);
- }
- if (vamsasSeqs.size() > vi
- && vamsasSeqs.get(vi).getId().equals(seqId))
- {
- // most likely we are reading a dataset XML document so
- // update from vamsasSeq section of XML for this sequence
- tmpSeq.setName(vamsasSeqs.get(vi).getName());
- tmpSeq.setDescription(vamsasSeqs.get(vi).getDescription());
- tmpSeq.setSequence(vamsasSeqs.get(vi).getSequence());
- vi++;
- }
- else
- {
- // reading multiple views, so vamsasSeq set is a subset of JSeq
- multipleView = true;
- }
- tmpSeq.setStart(jseq.getStart());
- tmpSeq.setEnd(jseq.getEnd());
- tmpseqs.add(tmpSeq);
- }
- else
- {
- Sequence vamsasSeq = vamsasSeqs.get(vi);
- tmpSeq = new jalview.datamodel.Sequence(vamsasSeq.getName(),
- vamsasSeq.getSequence());
- tmpSeq.setDescription(vamsasSeq.getDescription());
- tmpSeq.setStart(jseq.getStart());
- tmpSeq.setEnd(jseq.getEnd());
- tmpSeq.setVamsasId(uniqueSetSuffix + seqId);
- seqRefIds.put(vamsasSeq.getId(), tmpSeq);
- tmpseqs.add(tmpSeq);
- vi++;
- }
-
- if (safeBoolean(jseq.isViewreference()))
- {
- referenceseqForView = tmpseqs.get(tmpseqs.size() - 1);
- }
-
- if (jseq.isHidden() != null && jseq.isHidden().booleanValue())
- {
- if (hiddenSeqs == null)
- {
- hiddenSeqs = new ArrayList<>();
- }
- protected void resolveFrefedSequences()
- {
- Iterator<SeqFref> nextFref = frefedSequence.iterator();
- int toresolve = frefedSequence.size();
- int unresolved = 0, failedtoresolve = 0;
- while (nextFref.hasNext())
- {
- SeqFref ref = nextFref.next();
- if (ref.isResolvable())
- {
- try
- {
- if (ref.resolve())
- {
- nextFref.remove();
- }
- else
- {
- failedtoresolve++;
- }
- } catch (Exception x)
- {
- System.err.println(
- "IMPLEMENTATION ERROR: Failed to resolve forward reference for sequence "
- + ref.getSref());
- x.printStackTrace();
- failedtoresolve++;
- }
- }
- else
- {
- unresolved++;
- }
- }
- if (unresolved > 0)
- {
- System.err.println("Jalview Project Import: There were " + unresolved
- + " forward references left unresolved on the stack.");
- }
- if (failedtoresolve > 0)
- hiddenSeqs.add(tmpSeq);
- }
- }
-
- // /
- // Create the alignment object from the sequence set
- // ///////////////////////////////
- SequenceI[] orderedSeqs = tmpseqs
- .toArray(new SequenceI[tmpseqs.size()]);
-
- AlignmentI al = null;
- // so we must create or recover the dataset alignment before going further
- // ///////////////////////////////
- if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
- {
- // older jalview projects do not have a dataset - so creat alignment and
- // dataset
- al = new Alignment(orderedSeqs);
- al.setDataset(null);
- }
- else
- {
- boolean isdsal = jalviewModel.getViewport().isEmpty();
- if (isdsal)
- {
- // we are importing a dataset record, so
- // recover reference to an alignment already materialsed as dataset
- al = getDatasetFor(vamsasSet.getDatasetId());
- }
- if (al == null)
- {
- // materialse the alignment
- al = new Alignment(orderedSeqs);
- }
- if (isdsal)
- {
- addDatasetRef(vamsasSet.getDatasetId(), al);
- }
-
- // finally, verify all data in vamsasSet is actually present in al
- // passing on flag indicating if it is actually a stored dataset
- recoverDatasetFor(vamsasSet, al, isdsal, uniqueSeqSetId);
- }
-
- if (referenceseqForView != null)
- {
- al.setSeqrep(referenceseqForView);
- }
- // / Add the alignment properties
- for (int i = 0; i < vamsasSet.getSequenceSetProperties().size(); i++)
- {
- SequenceSetProperties ssp = vamsasSet.getSequenceSetProperties()
- .get(i);
- al.setProperty(ssp.getKey(), ssp.getValue());
- }
-
- // ///////////////////////////////
-
- Hashtable pdbloaded = new Hashtable(); // TODO nothing writes to this??
- if (!multipleView)
- {
- // load sequence features, database references and any associated PDB
- // structures for the alignment
- //
- // prior to 2.10, this part would only be executed the first time a
- // sequence was encountered, but not afterwards.
- // now, for 2.10 projects, this is also done if the xml doc includes
- // dataset sequences not actually present in any particular view.
- //
- for (int i = 0; i < vamsasSeqs.size(); i++)
- {
- JSeq jseq = jseqs.get(i);
- if (jseq.getFeatures().size() > 0)
- {
- List<Feature> features = jseq.getFeatures();
- for (int f = 0; f < features.size(); f++)
- {
- Feature feat = features.get(f);
- SequenceFeature sf = new SequenceFeature(feat.getType(),
- feat.getDescription(), feat.getBegin(), feat.getEnd(),
- safeFloat(feat.getScore()), feat.getFeatureGroup());
- sf.setStatus(feat.getStatus());
-
- /*
- * load any feature attributes - include map-valued attributes
- */
- Map<String, Map<String, String>> mapAttributes = new HashMap<>();
- for (int od = 0; od < feat.getOtherData().size(); od++)
- {
- OtherData keyValue = feat.getOtherData().get(od);
- String attributeName = keyValue.getKey();
- String attributeValue = keyValue.getValue();
- if (attributeName.startsWith("LINK"))
- {
- sf.addLink(attributeValue);
- }
- else
- {
- String subAttribute = keyValue.getKey2();
- if (subAttribute == null)
- {
- // simple string-valued attribute
- sf.setValue(attributeName, attributeValue);
- }
- else
- {
- // attribute 'key' has sub-attribute 'key2'
- if (!mapAttributes.containsKey(attributeName))
- {
- mapAttributes.put(attributeName, new HashMap<>());
- }
- mapAttributes.get(attributeName).put(subAttribute,
- attributeValue);
- }
- }
- }
- for (Entry<String, Map<String, String>> mapAttribute : mapAttributes
- .entrySet())
- {
- sf.setValue(mapAttribute.getKey(), mapAttribute.getValue());
- }
-
- // adds feature to datasequence's feature set (since Jalview 2.10)
- al.getSequenceAt(i).addSequenceFeature(sf);
- }
- }
- if (vamsasSeqs.get(i).getDBRef().size() > 0)
- {
- // adds dbrefs to datasequence's set (since Jalview 2.10)
- addDBRefs(
- al.getSequenceAt(i).getDatasetSequence() == null
- ? al.getSequenceAt(i)
- : al.getSequenceAt(i).getDatasetSequence(),
- vamsasSeqs.get(i));
- }
- if (jseq.getPdbids().size() > 0)
- {
- List<Pdbids> ids = jseq.getPdbids();
- for (int p = 0; p < ids.size(); p++)
- {
- Pdbids pdbid = ids.get(p);
- jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
- entry.setId(pdbid.getId());
- if (pdbid.getType() != null)
- {
- if (PDBEntry.Type.getType(pdbid.getType()) != null)
- {
- entry.setType(PDBEntry.Type.getType(pdbid.getType()));
- }
- else
- {
- entry.setType(PDBEntry.Type.FILE);
- }
- }
- // jprovider is null when executing 'New View'
- if (pdbid.getFile() != null && jprovider != null)
- {
- if (!pdbloaded.containsKey(pdbid.getFile()))
- {
- entry.setFile(loadPDBFile(jprovider, pdbid.getId(),
- pdbid.getFile()));
- }
- else
- {
- entry.setFile(pdbloaded.get(pdbid.getId()).toString());
- }
- }
- /*
- if (pdbid.getPdbentryItem() != null)
- {
- for (PdbentryItem item : pdbid.getPdbentryItem())
- {
- for (Property pr : item.getProperty())
- {
- entry.setProperty(pr.getName(), pr.getValue());
- }
- }
- }
- */
- for (Property prop : pdbid.getProperty())
- {
- entry.setProperty(prop.getName(), prop.getValue());
- }
- StructureSelectionManager
- .getStructureSelectionManager(Desktop.instance)
- .registerPDBEntry(entry);
- // adds PDBEntry to datasequence's set (since Jalview 2.10)
- if (al.getSequenceAt(i).getDatasetSequence() != null)
- {
- al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
- }
- else
- {
- al.getSequenceAt(i).addPDBId(entry);
- }
- }
- }
- }
- } // end !multipleview
-
- // ///////////////////////////////
- // LOAD SEQUENCE MAPPINGS
-
- if (vamsasSet.getAlcodonFrame().size() > 0)
- {
- // TODO Potentially this should only be done once for all views of an
- // alignment
- List<AlcodonFrame> alc = vamsasSet.getAlcodonFrame();
- for (int i = 0; i < alc.size(); i++)
- {
- AlignedCodonFrame cf = new AlignedCodonFrame();
- if (alc.get(i).getAlcodMap().size() > 0)
- {
- List<AlcodMap> maps = alc.get(i).getAlcodMap();
- for (int m = 0; m < maps.size(); m++)
- {
- AlcodMap map = maps.get(m);
- SequenceI dnaseq = seqRefIds.get(map.getDnasq());
- // Load Mapping
- jalview.datamodel.Mapping mapping = null;
- // attach to dna sequence reference.
- if (map.getMapping() != null)
- {
- mapping = addMapping(map.getMapping());
- if (dnaseq != null && mapping.getTo() != null)
- {
- cf.addMap(dnaseq, mapping.getTo(), mapping.getMap());
- }
- else
- {
- // defer to later
- frefedSequence
- .add(newAlcodMapRef(map.getDnasq(), cf, mapping));
- }
- }
- }
- al.addCodonFrame(cf);
- }
- }
- }
-
- // ////////////////////////////////
- // LOAD ANNOTATIONS
- List<JvAnnotRow> autoAlan = new ArrayList<>();
-
- /*
- * store any annotations which forward reference a group's ID
++ /**
++ * Write the data to a new entry of given name in the output jar file
++ *
++ * @param jout
++ * @param jarEntryName
++ * @param data
++ * @throws IOException
+ */
- Map<String, List<AlignmentAnnotation>> groupAnnotRefs = new Hashtable<>();
-
- if (vamsasSet.getAnnotation().size()/*Count()*/ > 0)
- {
- List<Annotation> an = vamsasSet.getAnnotation();
-
- for (int i = 0; i < an.size(); i++)
- {
- Annotation annotation = an.get(i);
-
- /**
- * test if annotation is automatically calculated for this view only
- */
- boolean autoForView = false;
- if (annotation.getLabel().equals("Quality")
- || annotation.getLabel().equals("Conservation")
- || annotation.getLabel().equals("Consensus"))
- {
- // Kludge for pre 2.5 projects which lacked the autocalculated flag
- autoForView = true;
- // JAXB has no has() test; schema defaults value to false
- // if (!annotation.hasAutoCalculated())
- // {
- // annotation.setAutoCalculated(true);
- // }
- }
- if (autoForView || annotation.isAutoCalculated())
- {
- // remove ID - we don't recover annotation from other views for
- // view-specific annotation
- annotation.setId(null);
- }
-
- // set visibility for other annotation in this view
- String annotationId = annotation.getId();
- if (annotationId != null && annotationIds.containsKey(annotationId))
- {
- AlignmentAnnotation jda = annotationIds.get(annotationId);
- // in principle Visible should always be true for annotation displayed
- // in multiple views
- if (annotation.isVisible() != null)
- {
- jda.visible = annotation.isVisible();
- }
-
- al.addAnnotation(jda);
-
- continue;
- }
- // Construct new annotation from model.
- List<AnnotationElement> ae = annotation.getAnnotationElement();
- jalview.datamodel.Annotation[] anot = null;
- java.awt.Color firstColour = null;
- int anpos;
- if (!annotation.isScoreOnly())
- {
- anot = new jalview.datamodel.Annotation[al.getWidth()];
- for (int aa = 0; aa < ae.size() && aa < anot.length; aa++)
- {
- AnnotationElement annElement = ae.get(aa);
- anpos = annElement.getPosition();
-
- if (anpos >= anot.length)
- {
- continue;
- }
-
- float value = safeFloat(annElement.getValue());
- anot[anpos] = new jalview.datamodel.Annotation(
- annElement.getDisplayCharacter(),
- annElement.getDescription(),
- (annElement.getSecondaryStructure() == null
- || annElement.getSecondaryStructure()
- .length() == 0)
- ? ' '
- : annElement
- .getSecondaryStructure()
- .charAt(0),
- value);
- anot[anpos].colour = new Color(safeInt(annElement.getColour()));
- if (firstColour == null)
- {
- firstColour = anot[anpos].colour;
- }
- }
- }
- jalview.datamodel.AlignmentAnnotation jaa = null;
-
- if (annotation.isGraph())
- {
- float llim = 0, hlim = 0;
- // if (autoForView || an[i].isAutoCalculated()) {
- // hlim=11f;
- // }
- jaa = new jalview.datamodel.AlignmentAnnotation(
- annotation.getLabel(), annotation.getDescription(), anot,
- llim, hlim, safeInt(annotation.getGraphType()));
-
- jaa.graphGroup = safeInt(annotation.getGraphGroup());
- jaa._linecolour = firstColour;
- if (annotation.getThresholdLine() != null)
- {
- jaa.setThreshold(new jalview.datamodel.GraphLine(
- safeFloat(annotation.getThresholdLine().getValue()),
- annotation.getThresholdLine().getLabel(),
- new java.awt.Color(safeInt(
- annotation.getThresholdLine().getColour()))));
- }
- if (autoForView || annotation.isAutoCalculated())
- {
- // Hardwire the symbol display line to ensure that labels for
- // histograms are displayed
- jaa.hasText = true;
- }
- }
- else
- {
- jaa = new jalview.datamodel.AlignmentAnnotation(
- annotation.getLabel(), annotation.getDescription(), anot);
- jaa._linecolour = firstColour;
- }
- // register new annotation
- if (annotation.getId() != null)
- {
- annotationIds.put(annotation.getId(), jaa);
- jaa.annotationId = annotation.getId();
- }
- // recover sequence association
- String sequenceRef = annotation.getSequenceRef();
- if (sequenceRef != null)
- {
- // from 2.9 sequenceRef is to sequence id (JAL-1781)
- SequenceI sequence = seqRefIds.get(sequenceRef);
- if (sequence == null)
- {
- // in pre-2.9 projects sequence ref is to sequence name
- sequence = al.findName(sequenceRef);
- }
- if (sequence != null)
- {
- jaa.createSequenceMapping(sequence, 1, true);
- sequence.addAlignmentAnnotation(jaa);
- }
- }
- // and make a note of any group association
- if (annotation.getGroupRef() != null
- && annotation.getGroupRef().length() > 0)
- {
- List<jalview.datamodel.AlignmentAnnotation> aal = groupAnnotRefs
- .get(annotation.getGroupRef());
- if (aal == null)
- {
- aal = new ArrayList<>();
- groupAnnotRefs.put(annotation.getGroupRef(), aal);
- }
- aal.add(jaa);
- }
-
- if (annotation.getScore() != null)
- {
- jaa.setScore(annotation.getScore().doubleValue());
- }
- if (annotation.isVisible() != null)
- {
- jaa.visible = annotation.isVisible().booleanValue();
- }
-
- if (annotation.isCentreColLabels() != null)
- {
- jaa.centreColLabels = annotation.isCentreColLabels()
- .booleanValue();
- }
-
- if (annotation.isScaleColLabels() != null)
- {
- jaa.scaleColLabel = annotation.isScaleColLabels().booleanValue();
- }
- if (annotation.isAutoCalculated())
- {
- // newer files have an 'autoCalculated' flag and store calculation
- // state in viewport properties
- jaa.autoCalculated = true; // means annotation will be marked for
- // update at end of load.
- }
- if (annotation.getGraphHeight() != null)
- {
- jaa.graphHeight = annotation.getGraphHeight().intValue();
- }
- jaa.belowAlignment = annotation.isBelowAlignment();
- jaa.setCalcId(annotation.getCalcId());
- if (annotation.getProperty().size() > 0)
- {
- for (Annotation.Property prop : annotation.getProperty())
- {
- jaa.setProperty(prop.getName(), prop.getValue());
- }
- }
- if (jaa.autoCalculated)
- {
- autoAlan.add(new JvAnnotRow(i, jaa));
- }
- else
- // if (!autoForView)
- {
- // add autocalculated group annotation and any user created annotation
- // for the view
- al.addAnnotation(jaa);
- }
- }
- }
- // ///////////////////////
- // LOAD GROUPS
- // Create alignment markup and styles for this view
- if (jalviewModel.getJGroup().size() > 0)
- {
- List<JGroup> groups = jalviewModel.getJGroup();
- boolean addAnnotSchemeGroup = false;
- for (int i = 0; i < groups.size(); i++)
- {
- JGroup jGroup = groups.get(i);
- ColourSchemeI cs = null;
- if (jGroup.getColour() != null)
- {
- if (jGroup.getColour().startsWith("ucs"))
- {
- cs = getUserColourScheme(jalviewModel, jGroup.getColour());
- }
- else if (jGroup.getColour().equals("AnnotationColourGradient")
- && jGroup.getAnnotationColours() != null)
- {
- addAnnotSchemeGroup = true;
- }
- else
- {
- cs = ColourSchemeProperty.getColourScheme(null, al,
- jGroup.getColour());
- }
- }
- int pidThreshold = safeInt(jGroup.getPidThreshold());
-
- Vector<SequenceI> seqs = new Vector<>();
-
- for (int s = 0; s < jGroup.getSeq().size(); s++)
- {
- String seqId = jGroup.getSeq().get(s);
- SequenceI ts = seqRefIds.get(seqId);
-
- if (ts != null)
- {
- seqs.addElement(ts);
- }
- }
-
- if (seqs.size() < 1)
- {
- continue;
- }
-
- SequenceGroup sg = new SequenceGroup(seqs, jGroup.getName(), cs,
- safeBoolean(jGroup.isDisplayBoxes()),
- safeBoolean(jGroup.isDisplayText()),
- safeBoolean(jGroup.isColourText()),
- safeInt(jGroup.getStart()), safeInt(jGroup.getEnd()));
- sg.getGroupColourScheme().setThreshold(pidThreshold, true);
- sg.getGroupColourScheme()
- .setConservationInc(safeInt(jGroup.getConsThreshold()));
- sg.setOutlineColour(new Color(safeInt(jGroup.getOutlineColour())));
-
- sg.textColour = new Color(safeInt(jGroup.getTextCol1()));
- sg.textColour2 = new Color(safeInt(jGroup.getTextCol2()));
- sg.setShowNonconserved(safeBoolean(jGroup.isShowUnconserved()));
- sg.thresholdTextColour = safeInt(jGroup.getTextColThreshold());
- // attributes with a default in the schema are never null
- sg.setShowConsensusHistogram(jGroup.isShowConsensusHistogram());
- sg.setshowSequenceLogo(jGroup.isShowSequenceLogo());
- sg.setNormaliseSequenceLogo(jGroup.isNormaliseSequenceLogo());
- sg.setIgnoreGapsConsensus(jGroup.isIgnoreGapsinConsensus());
- if (jGroup.getConsThreshold() != null
- && jGroup.getConsThreshold().intValue() != 0)
- {
- Conservation c = new Conservation("All", sg.getSequences(null), 0,
- sg.getWidth() - 1);
- c.calculate();
- c.verdict(false, 25);
- sg.cs.setConservation(c);
- }
-
- if (jGroup.getId() != null && groupAnnotRefs.size() > 0)
- {
- // re-instate unique group/annotation row reference
- List<AlignmentAnnotation> jaal = groupAnnotRefs
- .get(jGroup.getId());
- if (jaal != null)
- {
- for (AlignmentAnnotation jaa : jaal)
- {
- jaa.groupRef = sg;
- if (jaa.autoCalculated)
- {
- // match up and try to set group autocalc alignment row for this
- // annotation
- if (jaa.label.startsWith("Consensus for "))
- {
- sg.setConsensus(jaa);
- }
- // match up and try to set group autocalc alignment row for this
- // annotation
- if (jaa.label.startsWith("Conservation for "))
- {
- sg.setConservationRow(jaa);
- }
- }
- }
- }
- }
- al.addGroup(sg);
- if (addAnnotSchemeGroup)
- {
- // reconstruct the annotation colourscheme
- sg.setColourScheme(
- constructAnnotationColour(jGroup.getAnnotationColours(),
- null, al, jalviewModel, false));
- }
- }
- }
- if (view == null)
++ protected void writeJarEntry(JarOutputStream jout, String jarEntryName,
++ byte[] data) throws IOException
{
- System.err.println("SERIOUS! " + failedtoresolve
- + " resolvable forward references failed to resolve.");
- // only dataset in this model, so just return.
- return null;
++ if (jout != null)
++ {
++ jarEntryName = jarEntryName.replace('\\','/');
++ System.out.println("Writing jar entry " + jarEntryName);
++ jout.putNextEntry(new JarEntry(jarEntryName));
++ DataOutputStream dout = new DataOutputStream(jout);
++ dout.write(data, 0, data.length);
++ dout.flush();
++ jout.closeEntry();
++ }
}
- if (incompleteSeqs != null && incompleteSeqs.size() > 0)
- // ///////////////////////////////
- // LOAD VIEWPORT
-
- AlignFrame af = null;
- AlignViewport av = null;
- // now check to see if we really need to create a new viewport.
- if (multipleView && viewportsAdded.size() == 0)
- {
- // We recovered an alignment for which a viewport already exists.
- // TODO: fix up any settings necessary for overlaying stored state onto
- // state recovered from another document. (may not be necessary).
- // we may need a binding from a viewport in memory to one recovered from
- // XML.
- // and then recover its containing af to allow the settings to be applied.
- // TODO: fix for vamsas demo
- System.err.println(
- "About to recover a viewport for existing alignment: Sequence set ID is "
- + uniqueSeqSetId);
- Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
- if (seqsetobj != null)
- {
- if (seqsetobj instanceof String)
- {
- uniqueSeqSetId = (String) seqsetobj;
- System.err.println(
- "Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
- + uniqueSeqSetId);
- }
- else
- {
- System.err.println(
- "Warning : Collision between sequence set ID string and existing jalview object mapping.");
- }
+
- }
- }
+ /**
- * indicate that annotation colours are applied across all groups (pre
- * Jalview 2.8.1 behaviour)
++ * Copies input to output, in 4K buffers; handles any data (text or binary)
++ *
++ * @param in
++ * @param out
++ * @throws IOException
+ */
- boolean doGroupAnnColour = Jalview2XML.isVersionStringLaterThan("2.8.1",
- jalviewModel.getVersion());
-
- AlignmentPanel ap = null;
- boolean isnewview = true;
- if (viewId != null)
- {
- // Check to see if this alignment already has a view id == viewId
- jalview.gui.AlignmentPanel views[] = Desktop
- .getAlignmentPanels(uniqueSeqSetId);
- if (views != null && views.length > 0)
- {
- for (int v = 0; v < views.length; v++)
- {
- if (views[v].av.getViewId().equalsIgnoreCase(viewId))
- {
- // recover the existing alignpanel, alignframe, viewport
- af = views[v].alignFrame;
- av = views[v].av;
- ap = views[v];
- // TODO: could even skip resetting view settings if we don't want to
- // change the local settings from other jalview processes
- isnewview = false;
- }
- }
- }
- }
-
- if (isnewview)
++ protected void copyAll(InputStream in, OutputStream out)
++ throws IOException
{
- System.err.println(
- "Jalview Project Import: There are " + incompleteSeqs.size()
- + " sequences which may have incomplete metadata.");
- if (incompleteSeqs.size() < 10)
- {
- for (SequenceI s : incompleteSeqs.values())
- {
- System.err.println(s.toString());
- }
- }
- else
- {
- System.err.println(
- "Too many to report. Skipping output of incomplete sequences.");
- }
- af = loadViewport(file, jseqs, hiddenSeqs, al, jalviewModel, view,
- uniqueSeqSetId, viewId, autoAlan);
- av = af.getViewport();
- ap = af.alignPanel;
++ byte[] buffer = new byte[4096];
++ int bytesRead = 0;
++ while ((bytesRead = in.read(buffer)) != -1)
++ {
++ out.write(buffer, 0, bytesRead);
++ }
}
- }
- /**
- * This maintains a map of viewports, the key being the seqSetId. Important to
- * set historyItem and redoList for multiple views
- */
- Map<String, AlignViewport> viewportsAdded = new HashMap<>();
-
- Map<String, AlignmentAnnotation> annotationIds = new HashMap<>();
- /*
- * Load any trees, PDB structures and viewers
++ /**
++ * Save the state of a structure viewer
+ *
- * Not done if flag is false (when this method is used for New View)
++ * @param ap
++ * @param jds
++ * @param pdb
++ * the archive XML element under which to save the state
++ * @param entry
++ * @param viewIds
++ * @param matchedFile
++ * @param viewFrame
++ * @return
+ */
- if (loadTreesAndStructures)
- {
- loadTrees(jalviewModel, view, af, av, ap);
- loadPCAViewers(jalviewModel, ap);
- loadPDBStructures(jprovider, jseqs, af, ap);
- loadRnaViewers(jprovider, jseqs, ap);
++ protected String saveStructureViewer(AlignmentPanel ap, SequenceI jds,
++ Pdbids pdb, PDBEntry entry, List<String> viewIds,
++ String matchedFile, StructureViewerBase viewFrame)
++ {
++ final AAStructureBindingModel bindingModel = viewFrame.getBinding();
++
++ /*
++ * Look for any bindings for this viewer to the PDB file of interest
++ * (including part matches excluding chain id)
++ */
++ for (int peid = 0; peid < bindingModel.getPdbCount(); peid++)
++ {
++ final PDBEntry pdbentry = bindingModel.getPdbEntry(peid);
++ final String pdbId = pdbentry.getId();
++ if (!pdbId.equals(entry.getId())
++ && !(entry.getId().length() > 4 && entry.getId().toLowerCase(Locale.ROOT)
++ .startsWith(pdbId.toLowerCase(Locale.ROOT))))
++ {
++ /*
++ * not interested in a binding to a different PDB entry here
++ */
++ continue;
++ }
++ if (matchedFile == null)
++ {
++ matchedFile = pdbentry.getFile();
++ }
++ else if (!matchedFile.equals(pdbentry.getFile()))
++ {
++ Console.warn(
++ "Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
++ + pdbentry.getFile());
++ }
++ // record the
++ // file so we
++ // can get at it if the ID
++ // match is ambiguous (e.g.
++ // 1QIP==1qipA)
++
++ for (int smap = 0; smap < viewFrame.getBinding()
++ .getSequence()[peid].length; smap++)
++ {
++ // if (jal.findIndex(jmol.jmb.sequence[peid][smap]) > -1)
++ if (jds == viewFrame.getBinding().getSequence()[peid][smap])
++ {
++ StructureState state = new StructureState();
++ state.setVisible(true);
++ state.setXpos(viewFrame.getX());
++ state.setYpos(viewFrame.getY());
++ state.setWidth(viewFrame.getWidth());
++ state.setHeight(viewFrame.getHeight());
++ final String viewId = viewFrame.getViewId();
++ state.setViewId(viewId);
++ state.setAlignwithAlignPanel(viewFrame.isUsedforaligment(ap));
++ state.setColourwithAlignPanel(viewFrame.isUsedForColourBy(ap));
++ state.setColourByJmol(viewFrame.isColouredByViewer());
++ state.setType(viewFrame.getViewerType().toString());
++ // pdb.addStructureState(state);
++ pdb.getStructureState().add(state);
++ }
++ }
++ }
++ return matchedFile;
+ }
- // and finally return.
- return af;
- }
- String uniqueSetSuffix = "";
- /**
- * Instantiate and link any saved RNA (Varna) viewers. The state of the Varna
- * panel is restored from separate jar entries, two (gapped and trimmed) per
- * sequence and secondary structure.
- *
- * Currently each viewer shows just one sequence and structure (gapped and
- * trimmed), however this method is designed to support multiple sequences or
- * structures in viewers if wanted in future.
- *
- * @param jprovider
- * @param jseqs
- * @param ap
- */
- private void loadRnaViewers(jarInputStreamProvider jprovider,
- List<JSeq> jseqs, AlignmentPanel ap)
- {
- /*
- * scan the sequences for references to viewers; create each one the first
- * time it is referenced, add Rna models to existing viewers
++ /**
++ * Populates the AnnotationColourScheme xml for save. This captures the
++ * settings of the options in the 'Colour by Annotation' dialog.
++ *
++ * @param acg
++ * @param userColours
++ * @param jm
++ * @return
+ */
- for (JSeq jseq : jseqs)
- {
- for (int i = 0; i < jseq.getRnaViewer().size(); i++)
- {
- RnaViewer viewer = jseq.getRnaViewer().get(i);
- AppVarna appVarna = findOrCreateVarnaViewer(viewer, uniqueSetSuffix,
- ap);
++ private AnnotationColourScheme constructAnnotationColours(
++ AnnotationColourGradient acg, List<UserColourScheme> userColours,
++ JalviewModel jm)
++ {
++ AnnotationColourScheme ac = new AnnotationColourScheme();
++ ac.setAboveThreshold(acg.getAboveThreshold());
++ ac.setThreshold(acg.getAnnotationThreshold());
++ // 2.10.2 save annotationId (unique) not annotation label
++ ac.setAnnotation(acg.getAnnotation().annotationId);
++ if (acg.getBaseColour() instanceof UserColourScheme)
++ {
++ ac.setColourScheme(
++ setUserColourScheme(acg.getBaseColour(), userColours, jm));
++ }
++ else
++ {
++ ac.setColourScheme(
++ ColourSchemeProperty.getColourName(acg.getBaseColour()));
++ }
++
++ ac.setMaxColour(acg.getMaxColour().getRGB());
++ ac.setMinColour(acg.getMinColour().getRGB());
++ ac.setPerSequence(acg.isSeqAssociated());
++ ac.setPredefinedColours(acg.isPredefinedColours());
++ return ac;
++ }
++
++ private void storeAlignmentAnnotation(AlignmentAnnotation[] aa,
++ IdentityHashMap<SequenceGroup, String> groupRefs,
++ AlignmentViewport av, Set<String> calcIdSet, boolean storeDS,
++ SequenceSet vamsasSet)
++ {
++
++ for (int i = 0; i < aa.length; i++)
++ {
++ Annotation an = new Annotation();
++
++ AlignmentAnnotation annotation = aa[i];
++ if (annotation.annotationId != null)
++ {
++ annotationIds.put(annotation.annotationId, annotation);
++ }
++
++ an.setId(annotation.annotationId);
++
++ an.setVisible(annotation.visible);
++
++ an.setDescription(annotation.description);
++
++ if (annotation.sequenceRef != null)
++ {
++ // 2.9 JAL-1781 xref on sequence id rather than name
++ an.setSequenceRef(seqsToIds.get(annotation.sequenceRef));
++ }
++ if (annotation.groupRef != null)
++ {
++ String groupIdr = groupRefs.get(annotation.groupRef);
++ if (groupIdr == null)
++ {
++ // make a locally unique String
++ groupRefs.put(annotation.groupRef,
++ groupIdr = ("" + System.currentTimeMillis()
++ + annotation.groupRef.getName()
++ + groupRefs.size()));
++ }
++ an.setGroupRef(groupIdr.toString());
++ }
++
++ // store all visualization attributes for annotation
++ an.setGraphHeight(annotation.graphHeight);
++ an.setCentreColLabels(annotation.centreColLabels);
++ an.setScaleColLabels(annotation.scaleColLabel);
++ an.setShowAllColLabels(annotation.showAllColLabels);
++ an.setBelowAlignment(annotation.belowAlignment);
++
++ if (annotation.graph > 0)
++ {
++ an.setGraph(true);
++ an.setGraphType(annotation.graph);
++ an.setGraphGroup(annotation.graphGroup);
++ if (annotation.getThreshold() != null)
++ {
++ ThresholdLine line = new ThresholdLine();
++ line.setLabel(annotation.getThreshold().label);
++ line.setValue(annotation.getThreshold().value);
++ line.setColour(annotation.getThreshold().colour.getRGB());
++ an.setThresholdLine(line);
++ }
++ }
++ else
++ {
++ an.setGraph(false);
++ }
++
++ an.setLabel(annotation.label);
++
++ if (annotation == av.getAlignmentQualityAnnot()
++ || annotation == av.getAlignmentConservationAnnotation()
++ || annotation == av.getAlignmentConsensusAnnotation()
++ || annotation.autoCalculated)
++ {
++ // new way of indicating autocalculated annotation -
++ an.setAutoCalculated(annotation.autoCalculated);
++ }
++ if (annotation.hasScore())
++ {
++ an.setScore(annotation.getScore());
++ }
++
++ if (annotation.getCalcId() != null)
++ {
++ calcIdSet.add(annotation.getCalcId());
++ an.setCalcId(annotation.getCalcId());
++ }
++ if (annotation.hasProperties())
++ {
++ for (String pr : annotation.getProperties())
++ {
++ jalview.xml.binding.jalview.Annotation.Property prop = new jalview.xml.binding.jalview.Annotation.Property();
++ prop.setName(pr);
++ prop.setValue(annotation.getProperty(pr));
++ // an.addProperty(prop);
++ an.getProperty().add(prop);
++ }
++ }
++
++ AnnotationElement ae;
++ if (annotation.annotations != null)
++ {
++ an.setScoreOnly(false);
++ for (int a = 0; a < annotation.annotations.length; a++)
++ {
++ if ((annotation == null) || (annotation.annotations[a] == null))
++ {
++ continue;
++ }
++
++ ae = new AnnotationElement();
++ if (annotation.annotations[a].description != null)
++ {
++ ae.setDescription(annotation.annotations[a].description);
++ }
++ if (annotation.annotations[a].displayCharacter != null)
++ {
++ ae.setDisplayCharacter(
++ annotation.annotations[a].displayCharacter);
++ }
++
++ if (!Float.isNaN(annotation.annotations[a].value))
++ {
++ ae.setValue(annotation.annotations[a].value);
++ }
++
++ ae.setPosition(a);
++ if (annotation.annotations[a].secondaryStructure > ' ')
++ {
++ ae.setSecondaryStructure(
++ annotation.annotations[a].secondaryStructure + "");
++ }
++
++ if (annotation.annotations[a].colour != null
++ && annotation.annotations[a].colour != java.awt.Color.black)
++ {
++ ae.setColour(annotation.annotations[a].colour.getRGB());
++ }
++
++ // an.addAnnotationElement(ae);
++ an.getAnnotationElement().add(ae);
++ if (annotation.autoCalculated)
++ {
++ // only write one non-null entry into the annotation row -
++ // sufficient to get the visualization attributes necessary to
++ // display data
++ continue;
++ }
++ }
++ }
++ else
++ {
++ an.setScoreOnly(true);
++ }
++ if (!storeDS || (storeDS && !annotation.autoCalculated))
++ {
++ // skip autocalculated annotation - these are only provided for
++ // alignments
++ // vamsasSet.addAnnotation(an);
++ vamsasSet.getAnnotation().add(an);
++ }
++ }
++
++ }
++
++ private CalcIdParam createCalcIdParam(String calcId, AlignViewport av)
++ {
++ AutoCalcSetting settings = av.getCalcIdSettingsFor(calcId);
++ if (settings != null)
++ {
++ CalcIdParam vCalcIdParam = new CalcIdParam();
++ vCalcIdParam.setCalcId(calcId);
++ // vCalcIdParam.addServiceURL(settings.getServiceURI());
++ vCalcIdParam.getServiceURL().add(settings.getServiceURI());
++ // generic URI allowing a third party to resolve another instance of the
++ // service used for this calculation
++ for (String url : settings.getServiceURLs())
++ {
++ // vCalcIdParam.addServiceURL(urls);
++ vCalcIdParam.getServiceURL().add(url);
++ }
++ vCalcIdParam.setVersion("1.0");
++ if (settings.getPreset() != null)
++ {
++ WsParamSetI setting = settings.getPreset();
++ vCalcIdParam.setName(setting.getName());
++ vCalcIdParam.setDescription(setting.getDescription());
++ }
++ else
++ {
++ vCalcIdParam.setName("");
++ vCalcIdParam.setDescription("Last used parameters");
++ }
++ // need to be able to recover 1) settings 2) user-defined presets or
++ // recreate settings from preset 3) predefined settings provided by
++ // service - or settings that can be transferred (or discarded)
++ vCalcIdParam.setParameters(
++ settings.getWsParamFile().replace("\n", "|\\n|"));
++ vCalcIdParam.setAutoUpdate(settings.isAutoUpdate());
++ // todo - decide if updateImmediately is needed for any projects.
++
++ return vCalcIdParam;
++ }
++ return null;
++ }
++
++ private boolean recoverCalcIdParam(CalcIdParam calcIdParam,
++ AlignViewport av)
++ {
++ if (calcIdParam.getVersion().equals("1.0"))
++ {
++ final String[] calcIds = calcIdParam.getServiceURL().toArray(new String[0]);
++ ServiceWithParameters service = PreferredServiceRegistry.getRegistry()
++ .getPreferredServiceFor(calcIds);
++ if (service != null)
++ {
++ WsParamSetI parmSet = null;
++ try
++ {
++ parmSet = service.getParamStore().parseServiceParameterFile(
++ calcIdParam.getName(), calcIdParam.getDescription(),
++ calcIds,
++ calcIdParam.getParameters().replace("|\\n|", "\n"));
++ } catch (IOException x)
++ {
++ Console.warn("Couldn't parse parameter data for "
++ + calcIdParam.getCalcId(), x);
++ return false;
++ }
++ List<ArgumentI> argList = null;
++ if (calcIdParam.getName().length() > 0)
++ {
++ parmSet = service.getParamStore()
++ .getPreset(calcIdParam.getName());
++ if (parmSet != null)
++ {
++ // TODO : check we have a good match with settings in AACon -
++ // otherwise we'll need to create a new preset
++ }
++ }
++ else
++ {
++ argList = parmSet.getArguments();
++ parmSet = null;
++ }
++ AutoCalcSetting settings = new AAConSettings(
++ calcIdParam.isAutoUpdate(), service, parmSet, argList);
++ av.setCalcIdSettingsFor(calcIdParam.getCalcId(), settings,
++ calcIdParam.isNeedsUpdate());
++ return true;
++ }
++ else
++ {
++ Console.warn(
++ "Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server.");
++ return false;
++ }
++ }
++ throw new Error(MessageManager.formatMessage(
++ "error.unsupported_version_calcIdparam", new Object[]
++ { calcIdParam.toString() }));
++ }
- /**
- * List of pdbfiles added to Jar
- */
- List<String> pdbfiles = null;
- for (int j = 0; j < viewer.getSecondaryStructure().size(); j++)
- {
- SecondaryStructure ss = viewer.getSecondaryStructure().get(j);
- SequenceI seq = seqRefIds.get(jseq.getId());
- AlignmentAnnotation ann = this.annotationIds
- .get(ss.getAnnotationId());
++ /**
++ * External mapping between jalview objects and objects yielding a valid and
++ * unique object ID string. This is null for normal Jalview project IO, but
++ * non-null when a jalview project is being read or written as part of a
++ * vamsas session.
++ */
++ IdentityHashMap jv2vobj = null;
- // SAVES SEVERAL ALIGNMENT WINDOWS TO SAME JARFILE
- public void saveState(File statefile)
- {
- FileOutputStream fos = null;
- /*
- * add the structure to the Varna display (with session state copied
- * from the jar to a temporary file)
- */
- boolean gapped = safeBoolean(ss.isGapped());
- String rnaTitle = ss.getTitle();
- String sessionState = ss.getViewerState();
- String tempStateFile = copyJarEntry(jprovider, sessionState,
- "varna", null);
- RnaModel rna = new RnaModel(rnaTitle, ann, seq, null, gapped);
- appVarna.addModelSession(rna, rnaTitle, tempStateFile);
- }
- appVarna.setInitialSelection(safeInt(viewer.getSelectedRna()));
- }
++ /**
++ * Construct a unique ID for jvobj using either existing bindings or if none
++ * exist, the result of the hashcode call for the object.
++ *
++ * @param jvobj
++ * jalview data object
++ * @return unique ID for referring to jvobj
++ */
++ private String makeHashCode(Object jvobj, String altCode)
++ {
++ if (jv2vobj != null)
++ {
++ Object id = jv2vobj.get(jvobj);
++ if (id != null)
++ {
++ return id.toString();
++ }
++ // check string ID mappings
++ if (jvids2vobj != null && jvobj instanceof String)
++ {
++ id = jvids2vobj.get(jvobj);
++ }
++ if (id != null)
++ {
++ return id.toString();
++ }
++ // give up and warn that something has gone wrong
++ Console.warn(
++ "Cannot find ID for object in external mapping : " + jvobj);
++ }
++ return altCode;
+ }
- }
- try
- /**
- * Locate and return an already instantiated matching AppVarna, or create one
- * if not found
- *
- * @param viewer
- * @param viewIdSuffix
- * @param ap
- * @return
- */
- protected AppVarna findOrCreateVarnaViewer(RnaViewer viewer,
- String viewIdSuffix, AlignmentPanel ap)
- {
- /*
- * on each load a suffix is appended to the saved viewId, to avoid conflicts
- * if load is repeated
++ /**
++ * return local jalview object mapped to ID, if it exists
++ *
++ * @param idcode
++ * (may be null)
++ * @return null or object bound to idcode
+ */
- String postLoadId = viewer.getViewId() + viewIdSuffix;
- for (JInternalFrame frame : getAllFrames())
++ private Object retrieveExistingObj(String idcode)
{
- if (frame instanceof AppVarna)
- {
- AppVarna varna = (AppVarna) frame;
- if (postLoadId.equals(varna.getViewId()))
- {
- // this viewer is already instantiated
- // could in future here add ap as another 'parent' of the
- // AppVarna window; currently just 1-to-many
- return varna;
- }
- }
++ if (idcode != null && vobj2jv != null)
++ {
++ return vobj2jv.get(idcode);
++ }
++ return null;
+ }
- fos = new FileOutputStream(statefile);
- /*
- * viewer not found - make it
++ /**
++ * binding from ID strings from external mapping table to jalview data model
++ * objects.
+ */
- RnaViewerModel model = new RnaViewerModel(postLoadId, viewer.getTitle(),
- safeInt(viewer.getXpos()), safeInt(viewer.getYpos()),
- safeInt(viewer.getWidth()), safeInt(viewer.getHeight()),
- safeInt(viewer.getDividerLocation()));
- AppVarna varna = new AppVarna(model, ap);
++ private Hashtable vobj2jv;
++
++ private Sequence createVamsasSequence(String id, SequenceI jds)
++ {
++ return createVamsasSequence(true, id, jds, null);
++ }
++
++ private Sequence createVamsasSequence(boolean recurse, String id,
++ SequenceI jds, SequenceI parentseq)
++ {
++ Sequence vamsasSeq = new Sequence();
++ vamsasSeq.setId(id);
++ vamsasSeq.setName(jds.getName());
++ vamsasSeq.setSequence(jds.getSequenceAsString());
++ vamsasSeq.setDescription(jds.getDescription());
++ List<DBRefEntry> dbrefs = null;
++ if (jds.getDatasetSequence() != null)
++ {
++ vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
++ }
++ else
++ {
++ // seqId==dsseqid so we can tell which sequences really are
++ // dataset sequences only
++ vamsasSeq.setDsseqid(id);
++ dbrefs = jds.getDBRefs();
++ if (parentseq == null)
++ {
++ parentseq = jds;
++ }
++ }
++
++ /*
++ * save any dbrefs; special subclass GeneLocus is flagged as 'locus'
++ */
++ if (dbrefs != null)
++ {
++ for (int d = 0, nd = dbrefs.size(); d < nd; d++)
++ {
++ DBRef dbref = new DBRef();
++ DBRefEntry ref = dbrefs.get(d);
++ dbref.setSource(ref.getSource());
++ dbref.setVersion(ref.getVersion());
++ dbref.setAccessionId(ref.getAccessionId());
++ dbref.setCanonical(ref.isCanonical());
++ if (ref instanceof GeneLocus)
++ {
++ dbref.setLocus(true);
++ }
++ if (ref.hasMap())
++ {
++ Mapping mp = createVamsasMapping(ref.getMap(), parentseq,
++ jds, recurse);
++ dbref.setMapping(mp);
++ }
++ vamsasSeq.getDBRef().add(dbref);
++ }
++ }
++ return vamsasSeq;
++ }
++
++ private Mapping createVamsasMapping(jalview.datamodel.Mapping jmp,
++ SequenceI parentseq, SequenceI jds, boolean recurse)
++ {
++ Mapping mp = null;
++ if (jmp.getMap() != null)
++ {
++ mp = new Mapping();
++
++ jalview.util.MapList mlst = jmp.getMap();
++ List<int[]> r = mlst.getFromRanges();
++ for (int[] range : r)
++ {
++ MapListFrom mfrom = new MapListFrom();
++ mfrom.setStart(range[0]);
++ mfrom.setEnd(range[1]);
++ // mp.addMapListFrom(mfrom);
++ mp.getMapListFrom().add(mfrom);
++ }
++ r = mlst.getToRanges();
++ for (int[] range : r)
++ {
++ MapListTo mto = new MapListTo();
++ mto.setStart(range[0]);
++ mto.setEnd(range[1]);
++ // mp.addMapListTo(mto);
++ mp.getMapListTo().add(mto);
++ }
++ mp.setMapFromUnit(BigInteger.valueOf(mlst.getFromRatio()));
++ mp.setMapToUnit(BigInteger.valueOf(mlst.getToRatio()));
++ if (jmp.getTo() != null)
++ {
++ // MappingChoice mpc = new MappingChoice();
++
++ // check/create ID for the sequence referenced by getTo()
++
++ String jmpid = "";
++ SequenceI ps = null;
++ if (parentseq != jmp.getTo()
++ && parentseq.getDatasetSequence() != jmp.getTo())
++ {
++ // chaining dbref rather than a handshaking one
++ jmpid = seqHash(ps = jmp.getTo());
++ }
++ else
++ {
++ jmpid = seqHash(ps = parentseq);
++ }
++ // mpc.setDseqFor(jmpid);
++ mp.setDseqFor(jmpid);
++ if (!seqRefIds.containsKey(jmpid))
++ {
++ Console.debug("creatign new DseqFor ID");
++ seqRefIds.put(jmpid, ps);
++ }
++ else
++ {
++ Console.debug("reusing DseqFor ID");
++ }
++
++ // mp.setMappingChoice(mpc);
++ }
++ }
++ return mp;
++ }
++
++ String setUserColourScheme(jalview.schemes.ColourSchemeI cs,
++ List<UserColourScheme> userColours, JalviewModel jm)
++ {
++ String id = null;
++ jalview.schemes.UserColourScheme ucs = (jalview.schemes.UserColourScheme) cs;
++ boolean newucs = false;
++ if (!userColours.contains(ucs))
++ {
++ userColours.add(ucs);
++ newucs = true;
++ }
++ id = "ucs" + userColours.indexOf(ucs);
++ if (newucs)
++ {
++ // actually create the scheme's entry in the XML model
++ java.awt.Color[] colours = ucs.getColours();
++ UserColours uc = new UserColours();
++ // UserColourScheme jbucs = new UserColourScheme();
++ JalviewUserColours jbucs = new JalviewUserColours();
++
++ for (int i = 0; i < colours.length; i++)
++ {
++ Colour col = new Colour();
++ col.setName(ResidueProperties.aa[i]);
++ col.setRGB(jalview.util.Format.getHexString(colours[i]));
++ // jbucs.addColour(col);
++ jbucs.getColour().add(col);
++ }
++ if (ucs.getLowerCaseColours() != null)
++ {
++ colours = ucs.getLowerCaseColours();
++ for (int i = 0; i < colours.length; i++)
++ {
++ Colour col = new Colour();
++ col.setName(ResidueProperties.aa[i].toLowerCase(Locale.ROOT));
++ col.setRGB(jalview.util.Format.getHexString(colours[i]));
++ // jbucs.addColour(col);
++ jbucs.getColour().add(col);
++ }
++ }
++
++ uc.setId(id);
++ uc.setUserColourScheme(jbucs);
++ // jm.addUserColours(uc);
++ jm.getUserColours().add(uc);
++ }
++
++ return id;
++ }
++
++ jalview.schemes.UserColourScheme getUserColourScheme(JalviewModel jm,
++ String id)
++ {
++ List<UserColours> uc = jm.getUserColours();
++ UserColours colours = null;
++ /*
++ for (int i = 0; i < uc.length; i++)
++ {
++ if (uc[i].getId().equals(id))
++ {
++ colours = uc[i];
++ break;
++ }
++ }
++ */
++ for (UserColours c : uc)
++ {
++ if (c.getId().equals(id))
++ {
++ colours = c;
++ break;
++ }
++ }
++
++ java.awt.Color[] newColours = new java.awt.Color[24];
++
++ for (int i = 0; i < 24; i++)
++ {
++ newColours[i] = new java.awt.Color(Integer.parseInt(
++ // colours.getUserColourScheme().getColour(i).getRGB(), 16));
++ colours.getUserColourScheme().getColour().get(i).getRGB(),
++ 16));
++ }
++
++ jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
++ newColours);
++
++ if (colours.getUserColourScheme().getColour().size()/*Count()*/ > 24)
++ {
++ newColours = new java.awt.Color[23];
++ for (int i = 0; i < 23; i++)
++ {
++ newColours[i] = new java.awt.Color(
++ Integer.parseInt(colours.getUserColourScheme().getColour()
++ .get(i + 24).getRGB(), 16));
++ }
++ ucs.setLowerCaseColours(newColours);
++ }
++
++ return ucs;
++ }
- JarOutputStream jout = new JarOutputStream(fos);
- saveState(jout);
- fos.close();
- return varna;
- }
++ /**
++ * Load a jalview project archive from a jar file
++ *
++ * @param file
++ * - HTTP URL or filename
++ */
++ public AlignFrame loadJalviewAlign(final Object file)
++ {
++
++ jalview.gui.AlignFrame af = null;
++
++ try
++ {
++ // create list to store references for any new Jmol viewers created
++ newStructureViewers = new Vector<>();
++ // UNMARSHALLER SEEMS TO CLOSE JARINPUTSTREAM, MOST ANNOYING
++ // Workaround is to make sure caller implements the JarInputStreamProvider
++ // interface
++ // so we can re-open the jar input stream for each entry.
++
++ jarInputStreamProvider jprovider = createjarInputStreamProvider(file);
++ af = loadJalviewAlign(jprovider);
++ if (af != null)
++ {
++ af.setMenusForViewport();
++ }
++ } catch (MalformedURLException e)
++ {
++ errorMessage = "Invalid URL format for '" + file + "'";
++ reportErrors();
++ } finally
++ {
++ try
++ {
++ // was invokeAndWait
++
++ // BH 2019 -- can't wait
++ SwingUtilities.invokeLater(new Runnable()
++ {
++ @Override
++ public void run()
++ {
++ setLoadingFinishedForNewStructureViewers();
++ }
++ });
++ } catch (Exception x)
++ {
++ System.err.println("Error loading alignment: " + x.getMessage());
++ }
++ }
++ this.jarFile = null;
++ return af;
++ }
++
++ @SuppressWarnings("unused")
++ private jarInputStreamProvider createjarInputStreamProvider(
++ final Object ofile) throws MalformedURLException
++ {
++
++ try
++ {
++ String file = (ofile instanceof File
++ ? ((File) ofile).getCanonicalPath()
++ : ofile.toString());
++ byte[] bytes = Platform.isJS() ? Platform.getFileBytes((File) ofile)
++ : null;
++ if (bytes != null)
++ {
++ this.jarFile = (File) ofile;
++ }
++ URL url;
++ errorMessage = null;
++ uniqueSetSuffix = null;
++ seqRefIds = null;
++ viewportsAdded.clear();
++ frefedSequence = null;
++
++ if (HttpUtils.startsWithHttpOrHttps(file))
++ {
++ url = new URL(file);
++ } else {
++ url = null;
++ }
++ return new jarInputStreamProvider()
++ {
++
++ @Override
++ public JarInputStream getJarInputStream() throws IOException
++ {
++ InputStream is = bytes != null ? new ByteArrayInputStream(bytes)
++ : (url != null ? url.openStream()
++ : new FileInputStream(file));
++ return new JarInputStream(is);
++ }
++
++ @Override
++ public File getFile()
++ {
++ return jarFile;
++ }
++
++ @Override
++ public String getFilename()
++ {
++ return file;
++ }
++ };
++ } catch (IOException e)
++ {
++ e.printStackTrace();
++ return null;
++ }
++ }
- } catch (Exception e)
- {
- Cache.log.error("Couln't write Jalview state to " + statefile, e);
- // TODO: inform user of the problem - they need to know if their data was
- // not saved !
- if (errorMessage == null)
- {
- errorMessage = "Did't write Jalview Archive to output file '"
- + statefile + "' - See console error log for details";
- }
- else
- {
- errorMessage += "(Didn't write Jalview Archive to output file '"
- + statefile + ")";
- }
- e.printStackTrace();
- } finally
- {
- if (fos != null)
- {
- try
- {
- fos.close();
- } catch (IOException e)
- {
- // ignore
- }
- }
- /**
- * Load any saved trees
- *
- * @param jm
- * @param view
- * @param af
- * @param av
- * @param ap
- */
- protected void loadTrees(JalviewModel jm, Viewport view, AlignFrame af,
- AlignViewport av, AlignmentPanel ap)
- {
- // TODO result of automated refactoring - are all these parameters needed?
- try
- {
- for (int t = 0; t < jm.getTree().size(); t++)
- {
++ /**
++ * Recover jalview session from a jalview project archive. Caller may
++ * initialise uniqueSetSuffix, seqRefIds, viewportsAdded and frefedSequence
++ * themselves. Any null fields will be initialised with default values,
++ * non-null fields are left alone.
++ *
++ * @param jprovider
++ * @return
++ */
++ public AlignFrame loadJalviewAlign(final jarInputStreamProvider jprovider)
++ {
++ errorMessage = null;
++ if (uniqueSetSuffix == null)
++ {
++ uniqueSetSuffix = System.currentTimeMillis() % 100000 + "";
++ }
++ if (seqRefIds == null)
++ {
++ initSeqRefs();
++ }
++ AlignFrame af = null, _af = null;
++ IdentityHashMap<AlignmentI, AlignmentI> importedDatasets = new IdentityHashMap<>();
++ Map<String, AlignFrame> gatherToThisFrame = new HashMap<>();
++ String fileName = jprovider.getFilename();
++ File file = jprovider.getFile();
++ List<AlignFrame> alignFrames = new ArrayList<>();
++ try
++ {
++ JarInputStream jin = null;
++ JarEntry jarentry = null;
++ int entryCount = 1;
++
++ // Look for all the entry names ending with ".xml"
++ // This includes all panels and at least one frame.
++ // Platform.timeCheck(null, Platform.TIME_MARK);
++ do
++ {
++ jin = jprovider.getJarInputStream();
++ for (int i = 0; i < entryCount; i++)
++ {
++ jarentry = jin.getNextJarEntry();
++ }
++ String name = (jarentry == null ? null : jarentry.getName());
++
++ // System.out.println("Jalview2XML opening " + name);
++ if (name != null && name.endsWith(".xml"))
++ {
++ // DataSet for.... is read last.
++
++
++ // The question here is what to do with the two
++ // .xml files in the jvp file.
++ // Some number of them, "...Dataset for...", will be the
++ // Only AlignPanels and will have Viewport.
++ // One or more will be the source data, with the DBRefs.
++ //
++ // JVP file writing (above) ensures tha the AlignPanels are written
++ // first, then all relevant datasets (which are
++ // Jalview.datamodel.Alignment).
++ //
++
++ // Platform.timeCheck("Jalview2XML JAXB " + name, Platform.TIME_MARK);
++ JAXBContext jc = JAXBContext
++ .newInstance("jalview.xml.binding.jalview");
++ XMLStreamReader streamReader = XMLInputFactory.newInstance()
++ .createXMLStreamReader(jin);
++ javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
++ JAXBElement<JalviewModel> jbe = um
++ .unmarshal(streamReader, JalviewModel.class);
++ JalviewModel model = jbe.getValue();
++
++ if (true) // !skipViewport(object))
++ {
++ // Q: Do we have to load from the model, even if it
++ // does not have a viewport, could we discover that early on?
++ // Q: Do we need to load this object?
++ _af = loadFromObject(model, fileName, file, true, jprovider);
++ // Platform.timeCheck("Jalview2XML.loadFromObject",
++ // Platform.TIME_MARK);
++
++ if (_af != null)
++ {
++ alignFrames.add(_af);
++ }
++ if (_af != null && model.getViewport().size() > 0)
++ {
++
++ // That is, this is one of the AlignmentPanel models
++ if (af == null)
++ {
++ // store a reference to the first view
++ af = _af;
++ }
++ if (_af.getViewport().isGatherViewsHere())
++ {
++ // if this is a gathered view, keep its reference since
++ // after gathering views, only this frame will remain
++ af = _af;
++ gatherToThisFrame.put(_af.getViewport().getSequenceSetId(),
++ _af);
++ }
++ // Save dataset to register mappings once all resolved
++ importedDatasets.put(
++ af.getViewport().getAlignment().getDataset(),
++ af.getViewport().getAlignment().getDataset());
++ }
++ }
++ entryCount++;
++ }
++ else if (jarentry != null)
++ {
++ // Some other file here.
++ entryCount++;
++ }
++ } while (jarentry != null);
++ jin.close();
++ resolveFrefedSequences();
++ } catch (IOException ex)
++ {
++ ex.printStackTrace();
++ errorMessage = "Couldn't locate Jalview XML file : " + fileName;
++ System.err.println(
++ "Exception whilst loading jalview XML file : " + ex + "\n");
++ } catch (Exception ex)
++ {
++ System.err.println("Parsing as Jalview Version 2 file failed.");
++ ex.printStackTrace(System.err);
++ if (attemptversion1parse)
++ {
++ // used to attempt to parse as V1 castor-generated xml
++ }
++ if (Desktop.getInstance() != null)
++ {
++ Desktop.getInstance().stopLoading();
++ }
++ if (af != null)
++ {
++ System.out.println("Successfully loaded archive file");
++ return af;
++ }
++ ex.printStackTrace();
++
++ System.err.println(
++ "Exception whilst loading jalview XML file : " + ex + "\n");
++ } catch (OutOfMemoryError e)
++ {
++ // Don't use the OOM Window here
++ errorMessage = "Out of memory loading jalview XML file";
++ System.err.println("Out of memory whilst loading jalview XML file");
++ e.printStackTrace();
++ } finally
++ {
++ for (AlignFrame alf : alignFrames)
++ {
++ alf.alignPanel.setHoldRepaint(false);
++ }
++ }
++
++ /*
++ * Regather multiple views (with the same sequence set id) to the frame (if
++ * any) that is flagged as the one to gather to, i.e. convert them to tabbed
++ * views instead of separate frames. Note this doesn't restore a state where
++ * some expanded views in turn have tabbed views - the last "first tab" read
++ * in will play the role of gatherer for all.
++ */
++ for (AlignFrame fr : gatherToThisFrame.values())
++ {
++ Desktop.getInstance().gatherViews(fr);
++ }
++
++ restoreSplitFrames();
++ for (AlignmentI ds : importedDatasets.keySet())
++ {
++ if (ds.getCodonFrames() != null)
++ {
++ Desktop.getStructureSelectionManager()
++ .registerMappings(ds.getCodonFrames());
++ }
++ }
++ if (errorMessage != null)
++ {
++ reportErrors();
++ }
++
++ if (Desktop.getInstance() != null)
++ {
++ Desktop.getInstance().stopLoading();
++ }
++
++ return af;
+ }
- reportErrors();
- }
-
- /**
- * Writes a jalview project archive to the given Jar output stream.
- *
- * @param jout
- */
- public void saveState(JarOutputStream jout)
- {
- AlignFrame[] frames = Desktop.getAlignFrames();
- if (frames == null)
- {
- return;
- Tree tree = jm.getTree().get(t);
++ /**
++ * Try to reconstruct and display SplitFrame windows, where each contains
++ * complementary dna and protein alignments. Done by pairing up AlignFrame
++ * objects (created earlier) which have complementary viewport ids associated.
++ */
++ protected void restoreSplitFrames()
++ {
++ List<SplitFrame> gatherTo = new ArrayList<>();
++ List<AlignFrame> addedToSplitFrames = new ArrayList<>();
++ Map<String, AlignFrame> dna = new HashMap<>();
++
++ /*
++ * Identify the DNA alignments
++ */
++ for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
++ .entrySet())
++ {
++ AlignFrame af = candidate.getValue();
++ if (af.getViewport().getAlignment().isNucleotide())
++ {
++ dna.put(candidate.getKey().getId(), af);
++ }
++ }
++
++ /*
++ * Try to match up the protein complements
++ */
++ for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
++ .entrySet())
++ {
++ AlignFrame af = candidate.getValue();
++ if (!af.getViewport().getAlignment().isNucleotide())
++ {
++ String complementId = candidate.getKey().getComplementId();
++ // only non-null complements should be in the Map
++ if (complementId != null && dna.containsKey(complementId))
++ {
++ final AlignFrame dnaFrame = dna.get(complementId);
++ SplitFrame sf = createSplitFrame(dnaFrame, af);
++ addedToSplitFrames.add(dnaFrame);
++ addedToSplitFrames.add(af);
++ dnaFrame.setMenusForViewport();
++ af.setMenusForViewport();
++ if (af.getViewport().isGatherViewsHere())
++ {
++ gatherTo.add(sf);
++ }
++ }
++ }
++ }
++
++ /*
++ * Open any that we failed to pair up (which shouldn't happen!) as
++ * standalone AlignFrame's.
++ */
++ for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
++ .entrySet())
++ {
++ AlignFrame af = candidate.getValue();
++ if (!addedToSplitFrames.contains(af))
++ {
++ Viewport view = candidate.getKey();
++ Desktop.addInternalFrame(af, view.getTitle(),
++ safeInt(view.getWidth()), safeInt(view.getHeight()));
++ af.setMenusForViewport();
++ System.err.println("Failed to restore view " + view.getTitle()
++ + " to split frame");
++ }
++ }
++
++ /*
++ * Gather back into tabbed views as flagged.
++ */
++ for (SplitFrame sf : gatherTo)
++ {
++ Desktop.getInstance().gatherViews(sf);
++ }
++
++ splitFrameCandidates.clear();
+ }
- saveAllFrames(Arrays.asList(frames), jout);
- }
-
- /**
- * core method for storing state for a set of AlignFrames.
- *
- * @param frames
- * - frames involving all data to be exported (including those
- * contained in splitframes, though not the split frames themselves)
- * @param jout
- * - project output stream
- */
- private void saveAllFrames(List<AlignFrame> frames, JarOutputStream jout)
- {
- Hashtable<String, AlignFrame> dsses = new Hashtable<>();
- /*
- * ensure cached data is clear before starting
- TreePanel tp = (TreePanel) retrieveExistingObj(tree.getId());
- if (tp == null)
- {
- tp = af.showNewickTree(new NewickFile(tree.getNewick()),
- tree.getTitle(), safeInt(tree.getWidth()),
- safeInt(tree.getHeight()), safeInt(tree.getXpos()),
- safeInt(tree.getYpos()));
- if (tree.getId() != null)
- {
- // perhaps bind the tree id to something ?
- }
- }
- else
- {
- // update local tree attributes ?
- // TODO: should check if tp has been manipulated by user - if so its
- // settings shouldn't be modified
- tp.setTitle(tree.getTitle());
- tp.setBounds(new Rectangle(safeInt(tree.getXpos()),
- safeInt(tree.getYpos()), safeInt(tree.getWidth()),
- safeInt(tree.getHeight())));
- tp.setViewport(av); // af.viewport;
- // TODO: verify 'associate with all views' works still
- tp.getTreeCanvas().setViewport(av); // af.viewport;
- tp.getTreeCanvas().setAssociatedPanel(ap); // af.alignPanel;
- }
- tp.getTreeCanvas().setApplyToAllViews(tree.isLinkToAllViews());
- if (tp == null)
- {
- Console.warn(
- "There was a problem recovering stored Newick tree: \n"
- + tree.getNewick());
- continue;
- }
++ /**
++ * Construct and display one SplitFrame holding DNA and protein alignments.
++ *
++ * @param dnaFrame
++ * @param proteinFrame
++ * @return
+ */
- // todo tidy up seqRefIds, seqsToIds initialisation / reset
- rnaSessions.clear();
- splitFrameCandidates.clear();
-
- try
++ protected SplitFrame createSplitFrame(AlignFrame dnaFrame,
++ AlignFrame proteinFrame)
+ {
++ SplitFrame splitFrame = new SplitFrame(dnaFrame, proteinFrame);
++ String title = MessageManager.getString("label.linked_view_title");
++ int width = (int) dnaFrame.getBounds().getWidth();
++ int height = (int) (dnaFrame.getBounds().getHeight()
++ + proteinFrame.getBounds().getHeight() + 50);
- // NOTE UTF-8 MUST BE USED FOR WRITING UNICODE CHARS
- // //////////////////////////////////////////////////
-
- List<String> shortNames = new ArrayList<>();
- List<String> viewIds = new ArrayList<>();
-
- // REVERSE ORDER
- for (int i = frames.size() - 1; i > -1; i--)
- {
- AlignFrame af = frames.get(i);
- AlignViewport vp = af.getViewport();
- // skip ?
- if (skipList != null && skipList
- .containsKey(vp.getSequenceSetId()))
- {
- continue;
- }
-
- String shortName = makeFilename(af, shortNames);
-
- AlignmentI alignment = vp.getAlignment();
- List<? extends AlignmentViewPanel> panels = af.getAlignPanels();
- int apSize = panels.size();
-
- for (int ap = 0; ap < apSize; ap++)
- {
- AlignmentPanel apanel = (AlignmentPanel) panels.get(ap);
- String fileName = apSize == 1 ? shortName : ap + shortName;
- if (!fileName.endsWith(".xml"))
- {
- fileName = fileName + ".xml";
- }
-
- saveState(apanel, fileName, jout, viewIds);
- tp.fitToWindow.setState(safeBoolean(tree.isFitToWindow()));
- tp.fitToWindow_actionPerformed(null);
++ /*
++ * SplitFrame location is saved to both enclosed frames
++ */
++ splitFrame.setLocation(dnaFrame.getX(), dnaFrame.getY());
++ Desktop.addInternalFrame(splitFrame, title, width, height);
- }
- if (apSize > 0)
- {
- // BH moved next bit out of inner loop, not that it really matters.
- // so we are testing to make sure we actually have an alignment,
- // apparently.
- String dssid = getDatasetIdRef(alignment.getDataset());
- if (!dsses.containsKey(dssid))
- {
- // We have not already covered this data by reference from another
- // frame.
- dsses.put(dssid, af);
- }
- }
- }
- if (tree.getFontName() != null)
- {
- tp.setTreeFont(
- new Font(tree.getFontName(), safeInt(tree.getFontStyle()),
- safeInt(tree.getFontSize())));
- }
- else
- {
- tp.setTreeFont(
- new Font(view.getFontName(), safeInt(view.getFontStyle()),
- safeInt(view.getFontSize())));
- }
++ /*
++ * And compute cDNA consensus (couldn't do earlier with consensus as
++ * mappings were not yet present)
++ */
++ proteinFrame.getViewport().alignmentChanged(proteinFrame.alignPanel);
- writeDatasetFor(dsses, "" + jout.hashCode() + " " + uniqueSetSuffix,
- jout);
-
- try
- {
- jout.flush();
- } catch (Exception foo)
- {
- }
- jout.close();
- } catch (Exception ex)
- {
- // TODO: inform user of the problem - they need to know if their data was
- // not saved !
- if (errorMessage == null)
- {
- errorMessage = "Couldn't write Jalview Archive - see error output for details";
- }
- ex.printStackTrace();
- tp.showPlaceholders(safeBoolean(tree.isMarkUnlinked()));
- tp.showBootstrap(safeBoolean(tree.isShowBootstrap()));
- tp.showDistances(safeBoolean(tree.isShowDistances()));
++ return splitFrame;
+ }
- }
-
- /**
- * Generates a distinct file name, based on the title of the AlignFrame, by
- * appending _n for increasing n until an unused name is generated. The new
- * name (without its extension) is added to the list.
- *
- * @param af
- * @param namesUsed
- * @return the generated name, with .xml extension
- */
- protected String makeFilename(AlignFrame af, List<String> namesUsed)
- {
- String shortName = af.getTitle();
- if (shortName.indexOf(File.separatorChar) > -1)
- {
- shortName = shortName
- .substring(shortName.lastIndexOf(File.separatorChar) + 1);
- }
- tp.getTreeCanvas().setThreshold(safeFloat(tree.getThreshold()));
++ /**
++ * check errorMessage for a valid error message and raise an error box in the
++ * GUI or write the current errorMessage to stderr and then clear the error
++ * state.
++ */
++ protected void reportErrors()
++ {
++ reportErrors(false);
++ }
++
++ protected void reportErrors(final boolean saving)
++ {
++ if (errorMessage != null)
++ {
++ final String finalErrorMessage = errorMessage;
++ if (raiseGUI)
++ {
++ javax.swing.SwingUtilities.invokeLater(new Runnable()
++ {
++ @Override
++ public void run()
++ {
++ JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
++ finalErrorMessage,
++ "Error " + (saving ? "saving" : "loading")
++ + " Jalview file",
++ JvOptionPane.WARNING_MESSAGE);
++ }
++ });
++ }
++ else
++ {
++ System.err.println("Problem loading Jalview file: " + errorMessage);
++ }
++ }
++ errorMessage = null;
++ }
++
++ Map<String, String> alreadyLoadedPDB = new HashMap<>();
- int count = 1;
- if (safeBoolean(tree.isCurrentTree()))
- {
- af.getViewport().setCurrentTree(tp.getTree());
- }
- }
++ /**
++ * when set, local views will be updated from view stored in JalviewXML
++ * Currently (28th Sep 2008) things will go horribly wrong in vamsas document
++ * sync if this is set to true.
++ */
++ private final boolean updateLocalViews = false;
- while (namesUsed.contains(shortName))
- } catch (Exception ex)
++ /**
++ * Returns the path to a temporary file holding the PDB file for the given PDB
++ * id. The first time of asking, searches for a file of that name in the
++ * Jalview project jar, and copies it to a new temporary file. Any repeat
++ * requests just return the path to the file previously created.
++ *
++ * @param jprovider
++ * @param pdbId
++ * @return
++ */
++ String loadPDBFile(jarInputStreamProvider jprovider, String pdbId,
++ String origFile)
{
- if (shortName.endsWith("_" + (count - 1)))
- {
- shortName = shortName.substring(0, shortName.lastIndexOf("_"));
- }
- ex.printStackTrace();
++ if (alreadyLoadedPDB.containsKey(pdbId))
++ {
++ return alreadyLoadedPDB.get(pdbId).toString();
++ }
+
- shortName = shortName.concat("_" + count);
- count++;
++ String tempFile = copyJarEntry(jprovider, pdbId, "jalview_pdb",
++ origFile);
++ if (tempFile != null)
++ {
++ alreadyLoadedPDB.put(pdbId, tempFile);
++ }
++ return tempFile;
}
- }
- namesUsed.add(shortName);
-
- if (!shortName.endsWith(".xml"))
- {
- shortName = shortName + ".xml";
- /**
- * Load and link any saved structure viewers.
- *
- * @param jprovider
- * @param jseqs
- * @param af
- * @param ap
- */
- protected void loadPDBStructures(jarInputStreamProvider jprovider,
- List<JSeq> jseqs, AlignFrame af, AlignmentPanel ap)
- {
- /*
- * Run through all PDB ids on the alignment, and collect mappings between
- * distinct view ids and all sequences referring to that view.
++ /**
++ * Copies the jar entry of given name to a new temporary file and returns the
++ * path to the file, or null if the entry is not found.
++ *
++ * @param jprovider
++ * @param jarEntryName
++ * @param prefix
++ * a prefix for the temporary file name, must be at least three
++ * characters long
++ * @param suffixModel
++ * null or original file - so new file can be given the same suffix
++ * as the old one
++ * @return
+ */
- Map<String, StructureViewerModel> structureViewers = new LinkedHashMap<>();
++ protected String copyJarEntry(jarInputStreamProvider jprovider,
++ String jarEntryName, String prefix, String suffixModel)
++ {
++ BufferedReader in = null;
++ PrintWriter out = null;
++ String suffix = ".tmp";
++ if (suffixModel == null)
++ {
++ suffixModel = jarEntryName;
++ }
++ int sfpos = suffixModel.lastIndexOf(".");
++ if (sfpos > -1 && sfpos < (suffixModel.length() - 1))
++ {
++ suffix = "." + suffixModel.substring(sfpos + 1);
++ }
++
++ try (JarInputStream jin = jprovider.getJarInputStream())
++ {
++ JarEntry entry = null;
++ do
++ {
++ entry = jin.getNextJarEntry();
++ } while (entry != null && !entry.getName().equals(jarEntryName));
++
++ if (entry != null)
++ {
++ // in = new BufferedReader(new InputStreamReader(jin, UTF_8));
++ File outFile = File.createTempFile(prefix, suffix);
++ outFile.deleteOnExit();
++ try (OutputStream os = new FileOutputStream(outFile))
++ {
++ copyAll(jin, os);
++ }
++ String t = outFile.getAbsolutePath();
++ return t;
++ }
++ else
++ {
++ Console.warn(
++ "Couldn't find entry in Jalview Jar for " + jarEntryName);
++ }
++ } catch (Exception ex)
++ {
++ ex.printStackTrace();
++ }
++
++ return null;
++ }
++
++ private class JvAnnotRow
++ {
++ public JvAnnotRow(int i, AlignmentAnnotation jaa)
++ {
++ order = i;
++ template = jaa;
++ }
++
++ /**
++ * persisted version of annotation row from which to take vis properties
++ */
++ public jalview.datamodel.AlignmentAnnotation template;
++
++ /**
++ * original position of the annotation row in the alignment
++ */
++ public int order;
+ }
- return shortName;
- }
- // USE THIS METHOD TO SAVE A SINGLE ALIGNMENT WINDOW
- public boolean saveAlignment(AlignFrame af, String jarFile,
- String fileName)
- {
- try
- for (int i = 0; i < jseqs.size(); i++)
++ /**
++ * Load alignment frame from jalview XML DOM object. For a DOM object that
++ * includes one or more Viewport elements (one with a title that does NOT
++ * contain "Dataset for"), create the frame.
++ *
++ * @param jalviewModel
++ * DOM
++ * @param fileName
++ * filename source string
++ * @param file
++ * @param loadTreesAndStructures
++ * when false only create Viewport
++ * @param jprovider
++ * data source provider
++ * @return alignment frame created from view stored in DOM
++ */
++ AlignFrame loadFromObject(JalviewModel jalviewModel, String fileName,
++ File file, boolean loadTreesAndStructures, jarInputStreamProvider jprovider)
{
- // create backupfiles object and get new temp filename destination
- boolean doBackup = BackupFiles.getEnabled();
- BackupFiles backupfiles = doBackup ? new BackupFiles(jarFile) : null;
- FileOutputStream fos = new FileOutputStream(doBackup ?
- backupfiles.getTempFilePath() : jarFile);
- JSeq jseq = jseqs.get(i);
- if (jseq.getPdbids().size() > 0)
- {
- List<Pdbids> ids = jseq.getPdbids();
- for (int p = 0; p < ids.size(); p++)
- {
- Pdbids pdbid = ids.get(p);
- final int structureStateCount = pdbid.getStructureState().size();
- for (int s = 0; s < structureStateCount; s++)
- {
- // check to see if we haven't already created this structure view
- final StructureState structureState = pdbid.getStructureState()
- .get(s);
- String sviewid = (structureState.getViewId() == null) ? null
- : structureState.getViewId() + uniqueSetSuffix;
- jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
- // Originally : pdbid.getFile()
- // : TODO: verify external PDB file recovery still works in normal
- // jalview project load
- jpdb.setFile(
- loadPDBFile(jprovider, pdbid.getId(), pdbid.getFile()));
- jpdb.setId(pdbid.getId());
-
- int x = safeInt(structureState.getXpos());
- int y = safeInt(structureState.getYpos());
- int width = safeInt(structureState.getWidth());
- int height = safeInt(structureState.getHeight());
-
- // Probably don't need to do this anymore...
- // Desktop.desktop.getComponentAt(x, y);
- // TODO: NOW: check that this recovers the PDB file correctly.
- String pdbFile = loadPDBFile(jprovider, pdbid.getId(),
- pdbid.getFile());
- jalview.datamodel.SequenceI seq = seqRefIds
- .get(jseq.getId() + "");
- if (sviewid == null)
- {
- sviewid = "_jalview_pre2_4_" + x + "," + y + "," + width + ","
- + height;
- }
- if (!structureViewers.containsKey(sviewid))
- {
- String viewerType = structureState.getType();
- if (viewerType == null) // pre Jalview 2.9
- {
- viewerType = ViewerType.JMOL.toString();
- }
- structureViewers.put(sviewid,
- new StructureViewerModel(x, y, width, height, false,
- false, true, structureState.getViewId(),
- viewerType));
- // Legacy pre-2.7 conversion JAL-823 :
- // do not assume any view has to be linked for colour by
- // sequence
- }
++ SequenceSet vamsasSet = jalviewModel.getVamsasModel().getSequenceSet().get(0);
++ List<Sequence> vamsasSeqs = vamsasSet.getSequence();
- JarOutputStream jout = new JarOutputStream(fos);
- List<AlignFrame> frames = new ArrayList<>();
- // assemble String[] { pdb files }, String[] { id for each
- // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
- // seqs_file 2}, boolean[] {
- // linkAlignPanel,superposeWithAlignpanel}} from hash
- StructureViewerModel jmoldat = structureViewers.get(sviewid);
- jmoldat.setAlignWithPanel(jmoldat.isAlignWithPanel()
- || structureState.isAlignwithAlignPanel());
-
- /*
- * Default colour by linked panel to false if not specified (e.g.
- * for pre-2.7 projects)
- */
- boolean colourWithAlignPanel = jmoldat.isColourWithAlignPanel();
- colourWithAlignPanel |= structureState.isColourwithAlignPanel();
- jmoldat.setColourWithAlignPanel(colourWithAlignPanel);
-
- /*
- * Default colour by viewer to true if not specified (e.g. for
- * pre-2.7 projects)
- */
- boolean colourByViewer = jmoldat.isColourByViewer();
- colourByViewer &= structureState.isColourByJmol();
- jmoldat.setColourByViewer(colourByViewer);
-
- if (jmoldat.getStateData().length() < structureState.getValue()
- /*Content()*/.length())
- {
- jmoldat.setStateData(structureState.getValue());// Content());
- }
- if (pdbid.getFile() != null)
- {
- File mapkey = new File(pdbid.getFile());
- StructureData seqstrmaps = jmoldat.getFileData().get(mapkey);
- if (seqstrmaps == null)
- {
- jmoldat.getFileData().put(mapkey,
- seqstrmaps = jmoldat.new StructureData(pdbFile,
- pdbid.getId()));
- }
- if (!seqstrmaps.getSeqList().contains(seq))
- {
- seqstrmaps.getSeqList().add(seq);
- // TODO and chains?
- }
- }
- else
- {
- errorMessage = ("The Jmol views in this project were imported\nfrom an older version of Jalview.\nPlease review the sequence colour associations\nin the Colour by section of the Jmol View menu.\n\nIn the case of problems, see note at\nhttp://issues.jalview.org/browse/JAL-747");
- Console.warn(errorMessage);
- }
- }
- }
- }
- }
- // Instantiate the associated structure views
- for (Entry<String, StructureViewerModel> entry : structureViewers
- .entrySet())
- {
- try
- {
- createOrLinkStructureViewer(entry, af, ap, jprovider);
- } catch (Exception e)
- {
- System.err.println(
- "Error loading structure viewer: " + e.getMessage());
- // failed - try the next one
- }
- }
- }
++ // JalviewModelSequence jms = object.getJalviewModelSequence();
- // resolve splitframes
- if (af.getViewport().getCodingComplement() != null)
- {
- frames = ((SplitFrame) af.getSplitViewContainer()).getAlignFrames();
- }
- else
- {
- frames.add(af);
- }
- saveAllFrames(frames, jout);
- try
- {
- jout.flush();
- } catch (Exception foo)
- {
- }
- jout.close();
- boolean success = true;
- /**
- *
- * @param viewerData
- * @param af
- * @param ap
- * @param jprovider
- */
- protected void createOrLinkStructureViewer(
- Entry<String, StructureViewerModel> viewerData, AlignFrame af,
- AlignmentPanel ap, jarInputStreamProvider jprovider)
- {
- final StructureViewerModel stateData = viewerData.getValue();
++ // Viewport view = (jms.getViewportCount() > 0) ? jms.getViewport(0)
++ // : null;
++ Viewport view = (jalviewModel.getViewport().size() > 0)
++ ? jalviewModel.getViewport().get(0)
++ : null;
- if (doBackup)
- {
- backupfiles.setWriteSuccess(success);
- success = backupfiles.rollBackupsAndRenameTempFile();
- }
- /*
- * Search for any viewer windows already open from other alignment views
- * that exactly match the stored structure state
- */
- StructureViewerBase comp = findMatchingViewer(viewerData);
++ // ////////////////////////////////
++ // INITIALISE ALIGNMENT SEQUENCESETID AND VIEWID
++ //
++ //
++ // If we just load in the same jar file again, the sequenceSetId
++ // will be the same, and we end up with multiple references
++ // to the same sequenceSet. We must modify this id on load
++ // so that each load of the file gives a unique id
++
++ /**
++ * used to resolve correct alignment dataset for alignments with multiple
++ * views
++ */
++ String uniqueSeqSetId = null;
++ String viewId = null;
++ if (view != null)
++ {
++ uniqueSeqSetId = view.getSequenceSetId() + uniqueSetSuffix;
++ viewId = (view.getId() == null ? null
++ : view.getId() + uniqueSetSuffix);
++ }
++
++ // ////////////////////////////////
++ // LOAD SEQUENCES
++
++ List<SequenceI> hiddenSeqs = null;
++
++ List<SequenceI> tmpseqs = new ArrayList<>();
++
++ boolean multipleView = false;
++ SequenceI referenceseqForView = null;
++ // JSeq[] jseqs = object.getJalviewModelSequence().getJSeq();
++ List<JSeq> jseqs = jalviewModel.getJSeq();
++ int vi = 0; // counter in vamsasSeq array
++ for (int i = 0; i < jseqs.size(); i++)
++ {
++ JSeq jseq = jseqs.get(i);
++ String seqId = jseq.getId();
++
++ SequenceI tmpSeq = seqRefIds.get(seqId);
++ if (tmpSeq != null)
++ {
++ if (!incompleteSeqs.containsKey(seqId))
++ {
++ // may not need this check, but keep it for at least 2.9,1 release
++ if (tmpSeq.getStart() != jseq.getStart()
++ || tmpSeq.getEnd() != jseq.getEnd())
++ {
++ Console.warn(
++ String.format("Warning JAL-2154 regression: updating start/end for sequence %s from %d/%d to %d/%d",
++ tmpSeq.getName(), tmpSeq.getStart(),
++ tmpSeq.getEnd(), jseq.getStart(),
++ jseq.getEnd()));
++ }
++ }
++ else
++ {
++ incompleteSeqs.remove(seqId);
++ }
++ if (vamsasSeqs.size() > vi
++ && vamsasSeqs.get(vi).getId().equals(seqId))
++ {
++ // most likely we are reading a dataset XML document so
++ // update from vamsasSeq section of XML for this sequence
++ tmpSeq.setName(vamsasSeqs.get(vi).getName());
++ tmpSeq.setDescription(vamsasSeqs.get(vi).getDescription());
++ tmpSeq.setSequence(vamsasSeqs.get(vi).getSequence());
++ vi++;
++ }
++ else
++ {
++ // reading multiple views, so vamsasSeq set is a subset of JSeq
++ multipleView = true;
++ }
++ tmpSeq.setStart(jseq.getStart());
++ tmpSeq.setEnd(jseq.getEnd());
++ tmpseqs.add(tmpSeq);
++ }
++ else
++ {
++ Sequence vamsasSeq = vamsasSeqs.get(vi);
++ tmpSeq = new jalview.datamodel.Sequence(vamsasSeq.getName(),
++ vamsasSeq.getSequence());
++ tmpSeq.setDescription(vamsasSeq.getDescription());
++ tmpSeq.setStart(jseq.getStart());
++ tmpSeq.setEnd(jseq.getEnd());
++ tmpSeq.setVamsasId(uniqueSetSuffix + seqId);
++ seqRefIds.put(vamsasSeq.getId(), tmpSeq);
++ tmpseqs.add(tmpSeq);
++ vi++;
++ }
++
++ if (safeBoolean(jseq.isViewreference()))
++ {
++ referenceseqForView = tmpseqs.get(tmpseqs.size() - 1);
++ }
++
++ if (jseq.isHidden() != null && jseq.isHidden().booleanValue())
++ {
++ if (hiddenSeqs == null)
++ {
++ hiddenSeqs = new ArrayList<>();
++ }
++
++ hiddenSeqs.add(tmpSeq);
++ }
++ }
++
++ // /
++ // Create the alignment object from the sequence set
++ // ///////////////////////////////
++ SequenceI[] orderedSeqs = tmpseqs
++ .toArray(new SequenceI[tmpseqs.size()]);
- return success;
- } catch (Exception ex)
- {
- errorMessage = "Couldn't Write alignment view to Jalview Archive - see error output for details";
- ex.printStackTrace();
- return false;
- if (comp != null)
- {
- linkStructureViewer(ap, comp, stateData);
- return;
++ AlignmentI al = null;
++ // so we must create or recover the dataset alignment before going further
++ // ///////////////////////////////
++ if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
++ {
++ // older jalview projects do not have a dataset - so creat alignment and
++ // dataset
++ al = new Alignment(orderedSeqs);
++ al.setDataset(null);
++ }
++ else
++ {
++ boolean isdsal = jalviewModel.getViewport().isEmpty();
++ if (isdsal)
++ {
++ // we are importing a dataset record, so
++ // recover reference to an alignment already materialsed as dataset
++ al = getDatasetFor(vamsasSet.getDatasetId());
++ }
++ if (al == null)
++ {
++ // materialse the alignment
++ al = new Alignment(orderedSeqs);
++ }
++ if (isdsal)
++ {
++ addDatasetRef(vamsasSet.getDatasetId(), al);
++ }
++
++ // finally, verify all data in vamsasSet is actually present in al
++ // passing on flag indicating if it is actually a stored dataset
++ recoverDatasetFor(vamsasSet, al, isdsal, uniqueSeqSetId);
++ }
++
++ if (referenceseqForView != null)
++ {
++ al.setSeqrep(referenceseqForView);
++ }
++ // / Add the alignment properties
++ for (int i = 0; i < vamsasSet.getSequenceSetProperties().size(); i++)
++ {
++ SequenceSetProperties ssp = vamsasSet.getSequenceSetProperties()
++ .get(i);
++ al.setProperty(ssp.getKey(), ssp.getValue());
++ }
++
++ // ///////////////////////////////
++
++ Hashtable pdbloaded = new Hashtable(); // TODO nothing writes to this??
++ if (!multipleView)
++ {
++ // load sequence features, database references and any associated PDB
++ // structures for the alignment
++ //
++ // prior to 2.10, this part would only be executed the first time a
++ // sequence was encountered, but not afterwards.
++ // now, for 2.10 projects, this is also done if the xml doc includes
++ // dataset sequences not actually present in any particular view.
++ //
++ for (int i = 0; i < vamsasSeqs.size(); i++)
++ {
++ JSeq jseq = jseqs.get(i);
++ if (jseq.getFeatures().size() > 0)
++ {
++ List<Feature> features = jseq.getFeatures();
++ for (int f = 0; f < features.size(); f++)
++ {
++ Feature feat = features.get(f);
++ SequenceFeature sf = new SequenceFeature(feat.getType(),
++ feat.getDescription(), feat.getBegin(), feat.getEnd(),
++ safeFloat(feat.getScore()), feat.getFeatureGroup());
++ sf.setStatus(feat.getStatus());
++
++ /*
++ * load any feature attributes - include map-valued attributes
++ */
++ Map<String, Map<String, String>> mapAttributes = new HashMap<>();
++ for (int od = 0; od < feat.getOtherData().size(); od++)
++ {
++ OtherData keyValue = feat.getOtherData().get(od);
++ String attributeName = keyValue.getKey();
++ String attributeValue = keyValue.getValue();
++ if (attributeName.startsWith("LINK"))
++ {
++ sf.addLink(attributeValue);
++ }
++ else
++ {
++ String subAttribute = keyValue.getKey2();
++ if (subAttribute == null)
++ {
++ // simple string-valued attribute
++ sf.setValue(attributeName, attributeValue);
++ }
++ else
++ {
++ // attribute 'key' has sub-attribute 'key2'
++ if (!mapAttributes.containsKey(attributeName))
++ {
++ mapAttributes.put(attributeName, new HashMap<>());
++ }
++ mapAttributes.get(attributeName).put(subAttribute,
++ attributeValue);
++ }
++ }
++ }
++ for (Entry<String, Map<String, String>> mapAttribute : mapAttributes
++ .entrySet())
++ {
++ sf.setValue(mapAttribute.getKey(), mapAttribute.getValue());
++ }
++
++ // adds feature to datasequence's feature set (since Jalview 2.10)
++ al.getSequenceAt(i).addSequenceFeature(sf);
++ }
++ }
++ if (vamsasSeqs.get(i).getDBRef().size() > 0)
++ {
++ // adds dbrefs to datasequence's set (since Jalview 2.10)
++ addDBRefs(
++ al.getSequenceAt(i).getDatasetSequence() == null
++ ? al.getSequenceAt(i)
++ : al.getSequenceAt(i).getDatasetSequence(),
++ vamsasSeqs.get(i));
++ }
++ if (jseq.getPdbids().size() > 0)
++ {
++ List<Pdbids> ids = jseq.getPdbids();
++ for (int p = 0; p < ids.size(); p++)
++ {
++ Pdbids pdbid = ids.get(p);
++ jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
++ entry.setId(pdbid.getId());
++ if (pdbid.getType() != null)
++ {
++ if (PDBEntry.Type.getType(pdbid.getType()) != null)
++ {
++ entry.setType(PDBEntry.Type.getType(pdbid.getType()));
++ }
++ else
++ {
++ entry.setType(PDBEntry.Type.FILE);
++ }
++ }
++ // jprovider is null when executing 'New View'
++ if (pdbid.getFile() != null && jprovider != null)
++ {
++ if (!pdbloaded.containsKey(pdbid.getFile()))
++ {
++ entry.setFile(loadPDBFile(jprovider, pdbid.getId(),
++ pdbid.getFile()));
++ }
++ else
++ {
++ entry.setFile(pdbloaded.get(pdbid.getId()).toString());
++ }
++ }
++ /*
++ if (pdbid.getPdbentryItem() != null)
++ {
++ for (PdbentryItem item : pdbid.getPdbentryItem())
++ {
++ for (Property pr : item.getProperty())
++ {
++ entry.setProperty(pr.getName(), pr.getValue());
++ }
++ }
++ }
++ */
++ for (Property prop : pdbid.getProperty())
++ {
++ entry.setProperty(prop.getName(), prop.getValue());
++ }
++ Desktop.getStructureSelectionManager()
++ .registerPDBEntry(entry);
++ // adds PDBEntry to datasequence's set (since Jalview 2.10)
++ if (al.getSequenceAt(i).getDatasetSequence() != null)
++ {
++ al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
++ }
++ else
++ {
++ al.getSequenceAt(i).addPDBId(entry);
++ }
++ }
++ }
++ /*
++ * load any HMMER profile
++ */
++ // TODO fix this
++
++ String hmmJarFile = jseqs.get(i).getHmmerProfile();
++ if (hmmJarFile != null && jprovider != null)
++ {
++ loadHmmerProfile(jprovider, hmmJarFile, al.getSequenceAt(i));
++ }
++ }
++ } // end !multipleview
++
++ // ///////////////////////////////
++ // LOAD SEQUENCE MAPPINGS
++
++ if (vamsasSet.getAlcodonFrame().size() > 0)
++ {
++ // TODO Potentially this should only be done once for all views of an
++ // alignment
++ List<AlcodonFrame> alc = vamsasSet.getAlcodonFrame();
++ for (int i = 0; i < alc.size(); i++)
++ {
++ AlignedCodonFrame cf = new AlignedCodonFrame();
++ if (alc.get(i).getAlcodMap().size() > 0)
++ {
++ List<AlcodMap> maps = alc.get(i).getAlcodMap();
++ for (int m = 0; m < maps.size(); m++)
++ {
++ AlcodMap map = maps.get(m);
++ SequenceI dnaseq = seqRefIds.get(map.getDnasq());
++ // Load Mapping
++ jalview.datamodel.Mapping mapping = null;
++ // attach to dna sequence reference.
++ if (map.getMapping() != null)
++ {
++ mapping = addMapping(map.getMapping());
++ if (dnaseq != null && mapping.getTo() != null)
++ {
++ cf.addMap(dnaseq, mapping.getTo(), mapping.getMap());
++ }
++ else
++ {
++ // defer to later
++ frefedSequence.add(
++ newAlcodMapRef(map.getDnasq(), cf, mapping));
++ }
++ }
++ }
++ al.addCodonFrame(cf);
++ }
++ }
++ }
++
++ // ////////////////////////////////
++ // LOAD ANNOTATIONS
++ List<JvAnnotRow> autoAlan = new ArrayList<>();
++
++ /*
++ * store any annotations which forward reference a group's ID
++ */
++ Map<String, List<AlignmentAnnotation>> groupAnnotRefs = new Hashtable<>();
++
++ if (vamsasSet.getAnnotation().size()/*Count()*/ > 0)
++ {
++ List<Annotation> an = vamsasSet.getAnnotation();
++
++ for (int i = 0; i < an.size(); i++)
++ {
++ Annotation annotation = an.get(i);
++
++ /**
++ * test if annotation is automatically calculated for this view only
++ */
++ boolean autoForView = false;
++ if (annotation.getLabel().equals("Quality")
++ || annotation.getLabel().equals("Conservation")
++ || annotation.getLabel().equals("Consensus"))
++ {
++ // Kludge for pre 2.5 projects which lacked the autocalculated flag
++ autoForView = true;
++ // JAXB has no has() test; schema defaults value to false
++ // if (!annotation.hasAutoCalculated())
++ // {
++ // annotation.setAutoCalculated(true);
++ // }
++ }
++ if (autoForView || annotation.isAutoCalculated())
++ {
++ // remove ID - we don't recover annotation from other views for
++ // view-specific annotation
++ annotation.setId(null);
++ }
++
++ // set visibility for other annotation in this view
++ String annotationId = annotation.getId();
++ if (annotationId != null && annotationIds.containsKey(annotationId))
++ {
++ AlignmentAnnotation jda = annotationIds.get(annotationId);
++ // in principle Visible should always be true for annotation displayed
++ // in multiple views
++ if (annotation.isVisible() != null)
++ {
++ jda.visible = annotation.isVisible();
++ }
++
++ al.addAnnotation(jda);
++
++ continue;
++ }
++ // Construct new annotation from model.
++ List<AnnotationElement> ae = annotation.getAnnotationElement();
++ jalview.datamodel.Annotation[] anot = null;
++ java.awt.Color firstColour = null;
++ int anpos;
++ if (!annotation.isScoreOnly())
++ {
++ anot = new jalview.datamodel.Annotation[al.getWidth()];
++ for (int aa = 0; aa < ae.size() && aa < anot.length; aa++)
++ {
++ AnnotationElement annElement = ae.get(aa);
++ anpos = annElement.getPosition();
++
++ if (anpos >= anot.length)
++ {
++ continue;
++ }
++
++ float value = safeFloat(annElement.getValue());
++ anot[anpos] = new jalview.datamodel.Annotation(
++ annElement.getDisplayCharacter(),
++ annElement.getDescription(),
++ (annElement.getSecondaryStructure() == null
++ || annElement.getSecondaryStructure()
++ .length() == 0)
++ ? ' '
++ : annElement
++ .getSecondaryStructure()
++ .charAt(0),
++ value);
++ anot[anpos].colour = new Color(safeInt(annElement.getColour()));
++ if (firstColour == null)
++ {
++ firstColour = anot[anpos].colour;
++ }
++ }
++ }
++ // create the new AlignmentAnnotation
++ jalview.datamodel.AlignmentAnnotation jaa = null;
++
++ if (annotation.isGraph())
++ {
++ float llim = 0, hlim = 0;
++ // if (autoForView || an[i].isAutoCalculated()) {
++ // hlim=11f;
++ // }
++ jaa = new jalview.datamodel.AlignmentAnnotation(
++ annotation.getLabel(), annotation.getDescription(), anot,
++ llim, hlim, safeInt(annotation.getGraphType()));
++
++ jaa.graphGroup = safeInt(annotation.getGraphGroup());
++ jaa._linecolour = firstColour;
++ if (annotation.getThresholdLine() != null)
++ {
++ jaa.setThreshold(new jalview.datamodel.GraphLine(
++ safeFloat(annotation.getThresholdLine().getValue()),
++ annotation.getThresholdLine().getLabel(),
++ new java.awt.Color(safeInt(
++ annotation.getThresholdLine().getColour()))));
++ }
++ if (autoForView || annotation.isAutoCalculated())
++ {
++ // Hardwire the symbol display line to ensure that labels for
++ // histograms are displayed
++ jaa.hasText = true;
++ }
++ }
++ else
++ {
++ jaa = new jalview.datamodel.AlignmentAnnotation(
++ annotation.getLabel(), annotation.getDescription(), anot);
++ jaa._linecolour = firstColour;
++ }
++ // register new annotation
++ // Annotation graphs such as Conservation will not have id.
++ if (annotation.getId() != null)
++ {
++ annotationIds.put(annotation.getId(), jaa);
++ jaa.annotationId = annotation.getId();
++ }
++ // recover sequence association
++ String sequenceRef = annotation.getSequenceRef();
++ if (sequenceRef != null)
++ {
++ // from 2.9 sequenceRef is to sequence id (JAL-1781)
++ SequenceI sequence = seqRefIds.get(sequenceRef);
++ if (sequence == null)
++ {
++ // in pre-2.9 projects sequence ref is to sequence name
++ sequence = al.findName(sequenceRef);
++ }
++ if (sequence != null)
++ {
++ jaa.createSequenceMapping(sequence, 1, true);
++ sequence.addAlignmentAnnotation(jaa);
++ }
++ }
++ // and make a note of any group association
++ if (annotation.getGroupRef() != null
++ && annotation.getGroupRef().length() > 0)
++ {
++ List<jalview.datamodel.AlignmentAnnotation> aal = groupAnnotRefs
++ .get(annotation.getGroupRef());
++ if (aal == null)
++ {
++ aal = new ArrayList<>();
++ groupAnnotRefs.put(annotation.getGroupRef(), aal);
++ }
++ aal.add(jaa);
++ }
++
++ if (annotation.getScore() != null)
++ {
++ jaa.setScore(annotation.getScore().doubleValue());
++ }
++ if (annotation.isVisible() != null)
++ {
++ jaa.visible = annotation.isVisible().booleanValue();
++ }
++
++ if (annotation.isCentreColLabels() != null)
++ {
++ jaa.centreColLabels = annotation.isCentreColLabels()
++ .booleanValue();
++ }
++
++ if (annotation.isScaleColLabels() != null)
++ {
++ jaa.scaleColLabel = annotation.isScaleColLabels().booleanValue();
++ }
++ if (annotation.isAutoCalculated())
++ {
++ // newer files have an 'autoCalculated' flag and store calculation
++ // state in viewport properties
++ jaa.autoCalculated = true; // means annotation will be marked for
++ // update at end of load.
++ }
++ if (annotation.getGraphHeight() != null)
++ {
++ jaa.graphHeight = annotation.getGraphHeight().intValue();
++ }
++ jaa.belowAlignment = annotation.isBelowAlignment();
++ jaa.setCalcId(annotation.getCalcId());
++ if (annotation.getProperty().size() > 0)
++ {
++ for (Annotation.Property prop : annotation
++ .getProperty())
++ {
++ jaa.setProperty(prop.getName(), prop.getValue());
++ }
++ }
++ if (jaa.autoCalculated)
++ {
++ autoAlan.add(new JvAnnotRow(i, jaa));
++ }
++ else
++ // if (!autoForView)
++ {
++ // add autocalculated group annotation and any user created annotation
++ // for the view
++ al.addAnnotation(jaa);
++ }
++ }
++ }
++ // ///////////////////////
++ // LOAD GROUPS
++ // Create alignment markup and styles for this view
++ if (jalviewModel.getJGroup().size() > 0)
++ {
++ List<JGroup> groups = jalviewModel.getJGroup();
++ boolean addAnnotSchemeGroup = false;
++ for (int i = 0; i < groups.size(); i++)
++ {
++ JGroup jGroup = groups.get(i);
++ ColourSchemeI cs = null;
++ if (jGroup.getColour() != null)
++ {
++ if (jGroup.getColour().startsWith("ucs"))
++ {
++ cs = getUserColourScheme(jalviewModel, jGroup.getColour());
++ }
++ else if (jGroup.getColour().equals("AnnotationColourGradient")
++ && jGroup.getAnnotationColours() != null)
++ {
++ addAnnotSchemeGroup = true;
++ }
++ else
++ {
++ cs = ColourSchemeProperty.getColourScheme(null, al,
++ jGroup.getColour());
++ }
++ }
++ int pidThreshold = safeInt(jGroup.getPidThreshold());
++
++ Vector<SequenceI> seqs = new Vector<>();
++
++ for (int s = 0; s < jGroup.getSeq().size(); s++)
++ {
++ String seqId = jGroup.getSeq().get(s);
++ SequenceI ts = seqRefIds.get(seqId);
++
++ if (ts != null)
++ {
++ seqs.addElement(ts);
++ }
++ }
++
++ if (seqs.size() < 1)
++ {
++ continue;
++ }
++
++ SequenceGroup sg = new SequenceGroup(seqs, jGroup.getName(), cs,
++ safeBoolean(jGroup.isDisplayBoxes()),
++ safeBoolean(jGroup.isDisplayText()),
++ safeBoolean(jGroup.isColourText()),
++ safeInt(jGroup.getStart()), safeInt(jGroup.getEnd()));
++ sg.getGroupColourScheme().setThreshold(pidThreshold, true);
++ sg.getGroupColourScheme()
++ .setConservationInc(safeInt(jGroup.getConsThreshold()));
++ sg.setOutlineColour(new Color(safeInt(jGroup.getOutlineColour())));
++
++ sg.textColour = new Color(safeInt(jGroup.getTextCol1()));
++ sg.textColour2 = new Color(safeInt(jGroup.getTextCol2()));
++ sg.setShowNonconserved(safeBoolean(jGroup.isShowUnconserved()));
++ sg.thresholdTextColour = safeInt(jGroup.getTextColThreshold());
++ // attributes with a default in the schema are never null
++ sg.setShowConsensusHistogram(jGroup.isShowConsensusHistogram());
++ sg.setshowSequenceLogo(jGroup.isShowSequenceLogo());
++ sg.setNormaliseSequenceLogo(jGroup.isNormaliseSequenceLogo());
++ sg.setIgnoreGapsConsensus(jGroup.isIgnoreGapsinConsensus());
++ if (jGroup.getConsThreshold() != null
++ && jGroup.getConsThreshold().intValue() != 0)
++ {
++ Conservation c = new Conservation("All", sg.getSequences(null), 0,
++ sg.getWidth() - 1);
++ c.calculate();
++ c.verdict(false, 25);
++ sg.cs.setConservation(c);
++ }
++
++ if (jGroup.getId() != null && groupAnnotRefs.size() > 0)
++ {
++ // re-instate unique group/annotation row reference
++ List<AlignmentAnnotation> jaal = groupAnnotRefs
++ .get(jGroup.getId());
++ if (jaal != null)
++ {
++ for (AlignmentAnnotation jaa : jaal)
++ {
++ jaa.groupRef = sg;
++ if (jaa.autoCalculated)
++ {
++ // match up and try to set group autocalc alignment row for this
++ // annotation
++ if (jaa.label.startsWith("Consensus for "))
++ {
++ sg.setConsensus(jaa);
++ }
++ // match up and try to set group autocalc alignment row for this
++ // annotation
++ if (jaa.label.startsWith("Conservation for "))
++ {
++ sg.setConservationRow(jaa);
++ }
++ }
++ }
++ }
++ }
++ al.addGroup(sg);
++ if (addAnnotSchemeGroup)
++ {
++ // reconstruct the annotation colourscheme
++ sg.setColourScheme(
++ constructAnnotationColour(jGroup.getAnnotationColours(),
++ null, al, jalviewModel, false));
++ }
++ }
++ }
++ if (view == null)
++ {
++ // only dataset in this model, so just return.
++ return null;
++ }
++ // ///////////////////////////////
++ // LOAD VIEWPORT
++
++ // now check to see if we really need to create a new viewport.
++ if (multipleView && viewportsAdded.size() == 0)
++ {
++ // We recovered an alignment for which a viewport already exists.
++ // TODO: fix up any settings necessary for overlaying stored state onto
++ // state recovered from another document. (may not be necessary).
++ // we may need a binding from a viewport in memory to one recovered from
++ // XML.
++ // and then recover its containing af to allow the settings to be applied.
++ // TODO: fix for vamsas demo
++ System.err.println(
++ "About to recover a viewport for existing alignment: Sequence set ID is "
++ + uniqueSeqSetId);
++ Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
++ if (seqsetobj != null)
++ {
++ if (seqsetobj instanceof String)
++ {
++ uniqueSeqSetId = (String) seqsetobj;
++ System.err.println(
++ "Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
++ + uniqueSeqSetId);
++ }
++ else
++ {
++ System.err.println(
++ "Warning : Collision between sequence set ID string and existing jalview object mapping.");
++ }
++
++ }
++ }
++ /**
++ * indicate that annotation colours are applied across all groups (pre
++ * Jalview 2.8.1 behaviour)
++ */
++ boolean doGroupAnnColour = Jalview2XML.isVersionStringLaterThan("2.8.1",
++ jalviewModel.getVersion());
++
++ AlignFrame af = null;
++ AlignmentPanel ap = null;
++ AlignViewport av = null;
++ if (viewId != null)
++ {
++ // Check to see if this alignment already has a view id == viewId
++ jalview.gui.AlignmentPanel views[] = Desktop
++ .getAlignmentPanels(uniqueSeqSetId);
++ if (views != null && views.length > 0)
++ {
++ for (int v = 0; v < views.length; v++)
++ {
++ ap = views[v];
++ av = ap.av;
++ if (av.getViewId().equalsIgnoreCase(viewId))
++ {
++ // recover the existing alignpanel, alignframe, viewport
++ af = ap.alignFrame;
++ break;
++ // TODO: could even skip resetting view settings if we don't want to
++ // change the local settings from other jalview processes
++ }
++ }
++ }
++ }
++
++ if (af == null)
++ {
++ af = loadViewport(fileName, file, jseqs, hiddenSeqs, al, jalviewModel, view,
++ uniqueSeqSetId, viewId, autoAlan);
++ av = af.getViewport();
++ // note that this only retrieves the most recently accessed
++ // tab of an AlignFrame.
++ ap = af.alignPanel;
++ }
++
++ /*
++ * Load any trees, PDB structures and viewers
++ *
++ * Not done if flag is false (when this method is used for New View)
++ */
++ final AlignFrame af0 = af;
++ final AlignViewport av0 = av;
++ final AlignmentPanel ap0 = ap;
++ // Platform.timeCheck("Jalview2XML.loadFromObject-beforetree",
++ // Platform.TIME_MARK);
++ if (loadTreesAndStructures)
++ {
++ if (!jalviewModel.getTree().isEmpty())
++ {
++ SwingUtilities.invokeLater(new Runnable()
++ {
++ @Override
++ public void run()
++ {
++ // Platform.timeCheck(null, Platform.TIME_MARK);
++ loadTrees(jalviewModel, view, af0, av0, ap0);
++ // Platform.timeCheck("Jalview2XML.loadTrees", Platform.TIME_MARK);
++ }
++ });
++ }
++ if (!jalviewModel.getPcaViewer().isEmpty())
++ {
++ SwingUtilities.invokeLater(new Runnable()
++ {
++ @Override
++ public void run()
++ {
++ // Platform.timeCheck(null, Platform.TIME_MARK);
++ loadPCAViewers(jalviewModel, ap0);
++ // Platform.timeCheck("Jalview2XML.loadPCA", Platform.TIME_MARK);
++ }
++ });
++ }
++ SwingUtilities.invokeLater(new Runnable()
++ {
++ @Override
++ public void run()
++ {
++ // Platform.timeCheck(null, Platform.TIME_MARK);
++ loadPDBStructures(jprovider, jseqs, af0, ap0);
++ // Platform.timeCheck("Jalview2XML.loadPDB", Platform.TIME_MARK);
++ }
++ });
++ SwingUtilities.invokeLater(new Runnable()
++ {
++ @Override
++ public void run()
++ {
++ loadRnaViewers(jprovider, jseqs, ap0);
++ }
++ });
++ }
++ // and finally return.
++ // but do not set holdRepaint true just yet, because this could be the
++ // initial frame with just its dataset.
++ return af;
}
- }
- /**
- * Each AlignFrame has a single data set associated with it. Note that none of
- * these frames are split frames, because Desktop.getAlignFrames() collects
- * top and bottom separately here.
- *
- * @param dsses
- * @param fileName
- * @param jout
- */
- private void writeDatasetFor(Hashtable<String, AlignFrame> dsses,
- String fileName, JarOutputStream jout)
- {
-
- // Note that in saveAllFrames we have associated each specific dataset to
- // ONE of its associated frames.
- for (String dssids : dsses.keySet())
- {
- AlignFrame _af = dsses.get(dssids);
- String jfileName = fileName + " Dataset for " + _af.getTitle();
- if (!jfileName.endsWith(".xml"))
- {
- jfileName = jfileName + ".xml";
- }
- saveState(_af.alignPanel, jfileName, true, jout, null);
- String type = stateData.getType();
- try
- {
- ViewerType viewerType = ViewerType.valueOf(type);
- createStructureViewer(viewerType, viewerData, af, jprovider);
- } catch (IllegalArgumentException | NullPointerException e)
- {
- // TODO JAL-3619 show error dialog / offer an alternative viewer
- Console.error("Invalid structure viewer type: " + type);
++ /**
++ * Loads a HMMER profile from a file stored in the project, and associates it
++ * with the specified sequence
++ *
++ * @param jprovider
++ * @param hmmJarFile
++ * @param seq
++ */
++ protected void loadHmmerProfile(jarInputStreamProvider jprovider,
++ String hmmJarFile, SequenceI seq)
++ {
++ try
++ {
++ String hmmFile = copyJarEntry(jprovider, hmmJarFile, "hmm", null);
++ HMMFile parser = new HMMFile(hmmFile, DataSourceType.FILE);
++ HiddenMarkovModel hmmModel = parser.getHMM();
++ hmmModel = new HiddenMarkovModel(hmmModel, seq);
++ seq.setHMM(hmmModel);
++ } catch (IOException e)
++ {
++ Console.warn("Error loading HMM profile for " + seq.getName() + ": "
++ + e.getMessage());
++ }
}
-- }
--
-- /**
- * create a JalviewModel from an alignment view and marshall it to a
- * JarOutputStream
- *
- * @param ap
- * panel to create jalview model for
- * @param fileName
- * name of alignment panel written to output stream
- * @param jout
- * jar output stream
- * @param viewIds
- * @param out
- * jar entry name
- */
- protected JalviewModel saveState(AlignmentPanel ap, String fileName,
- JarOutputStream jout, List<String> viewIds)
- {
- return saveState(ap, fileName, false, jout, viewIds);
- }
- * Generates a name for the entry in the project jar file to hold state
- * information for a structure viewer
- *
- * @param viewId
- * @return
- */
- protected String getViewerJarEntryName(String viewId)
- {
- return VIEWER_PREFIX + viewId;
- }
-- /**
- * create a JalviewModel from an alignment view and marshall it to a
- * JarOutputStream
- *
- * @param ap
- * panel to create jalview model for
- * @param fileName
- * name of alignment panel written to output stream
- * @param storeDS
- * when true, only write the dataset for the alignment, not the data
- * associated with the view.
- * @param jout
- * jar output stream
- * @param out
- * jar entry name
- */
- protected JalviewModel saveState(AlignmentPanel ap, String fileName,
- boolean storeDS, JarOutputStream jout, List<String> viewIds)
- {
- if (viewIds == null)
- {
- viewIds = new ArrayList<>();
- * Returns any open frame that matches given structure viewer data. The match
- * is based on the unique viewId, or (for older project versions) the frame's
- * geometry.
- *
- * @param viewerData
- * @return
- */
- protected StructureViewerBase findMatchingViewer(
- Entry<String, StructureViewerModel> viewerData)
- {
- final String sviewid = viewerData.getKey();
- final StructureViewerModel svattrib = viewerData.getValue();
- StructureViewerBase comp = null;
- JInternalFrame[] frames = getAllFrames();
- for (JInternalFrame frame : frames)
- {
- if (frame instanceof StructureViewerBase)
- {
- /*
- * Post jalview 2.4 schema includes structure view id
- */
- if (sviewid != null && ((StructureViewerBase) frame).getViewId()
- .equals(sviewid))
- {
- comp = (StructureViewerBase) frame;
- break; // break added in 2.9
- }
- /*
- * Otherwise test for matching position and size of viewer frame
- */
- else if (frame.getX() == svattrib.getX()
- && frame.getY() == svattrib.getY()
- && frame.getHeight() == svattrib.getHeight()
- && frame.getWidth() == svattrib.getWidth())
- {
- comp = (StructureViewerBase) frame;
- // no break in faint hope of an exact match on viewId
- }
- }
++ /**
++ * Instantiate and link any saved RNA (Varna) viewers. The state of the Varna
++ * panel is restored from separate jar entries, two (gapped and trimmed) per
++ * sequence and secondary structure.
++ *
++ * Currently each viewer shows just one sequence and structure (gapped and
++ * trimmed), however this method is designed to support multiple sequences or
++ * structures in viewers if wanted in future.
++ *
++ * @param jprovider
++ * @param jseqs
++ * @param ap
++ */
++ protected void loadRnaViewers(jarInputStreamProvider jprovider,
++ List<JSeq> jseqs, AlignmentPanel ap)
++ {
++ /*
++ * scan the sequences for references to viewers; create each one the first
++ * time it is referenced, add Rna models to existing viewers
++ */
++ for (JSeq jseq : jseqs)
++ {
++ for (int i = 0; i < jseq.getRnaViewer().size(); i++)
++ {
++ RnaViewer viewer = jseq.getRnaViewer().get(i);
++ AppVarna appVarna = findOrCreateVarnaViewer(viewer, uniqueSetSuffix,
++ ap);
++
++ for (int j = 0; j < viewer.getSecondaryStructure().size(); j++)
++ {
++ SecondaryStructure ss = viewer.getSecondaryStructure().get(j);
++ SequenceI seq = seqRefIds.get(jseq.getId());
++ AlignmentAnnotation ann = this.annotationIds
++ .get(ss.getAnnotationId());
++
++ /*
++ * add the structure to the Varna display (with session state copied
++ * from the jar to a temporary file)
++ */
++ boolean gapped = safeBoolean(ss.isGapped());
++ String rnaTitle = ss.getTitle();
++ String sessionState = ss.getViewerState();
++ String tempStateFile = copyJarEntry(jprovider, sessionState,
++ "varna", null);
++ RnaModel rna = new RnaModel(rnaTitle, ann, seq, null, gapped);
++ appVarna.addModelSession(rna, rnaTitle, tempStateFile);
++ }
++ appVarna.setInitialSelection(safeInt(viewer.getSelectedRna()));
++ }
++ }
}
- return comp;
- }
- initSeqRefs();
-
- List<UserColourScheme> userColours = new ArrayList<>();
-
- AlignViewport av = ap.av;
- ViewportRanges vpRanges = av.getRanges();
-
- final ObjectFactory objectFactory = new ObjectFactory();
- JalviewModel object = objectFactory.createJalviewModel();
- object.setVamsasModel(new VAMSAS());
-
- // object.setCreationDate(new java.util.Date(System.currentTimeMillis()));
- try
- {
- GregorianCalendar c = new GregorianCalendar();
- DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
- XMLGregorianCalendar now = datatypeFactory.newXMLGregorianCalendar(c);// gregorianCalendar);
- object.setCreationDate(now);
- } catch (DatatypeConfigurationException e)
- {
- System.err.println("error writing date: " + e.toString());
- /**
- * Link an AlignmentPanel to an existing structure viewer.
- *
- * @param ap
- * @param viewer
- * @param oldFiles
- * @param useinViewerSuperpos
- * @param usetoColourbyseq
- * @param viewerColouring
- */
- protected void linkStructureViewer(AlignmentPanel ap,
- StructureViewerBase viewer, StructureViewerModel stateData)
- {
- // NOTE: if the jalview project is part of a shared session then
- // view synchronization should/could be done here.
++ /**
++ * Locate and return an already instantiated matching AppVarna, or create one
++ * if not found
++ *
++ * @param viewer
++ * @param viewIdSuffix
++ * @param ap
++ * @return
++ */
++ protected AppVarna findOrCreateVarnaViewer(RnaViewer viewer,
++ String viewIdSuffix, AlignmentPanel ap)
++ {
++ /*
++ * on each load a suffix is appended to the saved viewId, to avoid conflicts
++ * if load is repeated
++ */
++ String postLoadId = viewer.getViewId() + viewIdSuffix;
++ for (JInternalFrame frame : getAllFrames())
++ {
++ if (frame instanceof AppVarna)
++ {
++ AppVarna varna = (AppVarna) frame;
++ if (postLoadId.equals(varna.getViewId()))
++ {
++ // this viewer is already instantiated
++ // could in future here add ap as another 'parent' of the
++ // AppVarna window; currently just 1-to-many
++ return varna;
++ }
++ }
++ }
++
++ /*
++ * viewer not found - make it
++ */
++ RnaViewerModel model = new RnaViewerModel(postLoadId, viewer.getTitle(),
++ safeInt(viewer.getXpos()), safeInt(viewer.getYpos()),
++ safeInt(viewer.getWidth()), safeInt(viewer.getHeight()),
++ safeInt(viewer.getDividerLocation()));
++ AppVarna varna = new AppVarna(model, ap);
++
++ return varna;
+ }
- object.setVersion(
- jalview.bin.Cache.getDefault("VERSION", "Development Build"));
- final boolean useinViewerSuperpos = stateData.isAlignWithPanel();
- final boolean usetoColourbyseq = stateData.isColourWithAlignPanel();
- final boolean viewerColouring = stateData.isColourByViewer();
- Map<File, StructureData> oldFiles = stateData.getFileData();
+ /**
- * rjal is full height alignment, jal is actual alignment with full metadata
- * but excludes hidden sequences.
++ * Load any saved trees
++ *
++ * @param jm
++ * @param view
++ * @param af
++ * @param av
++ * @param ap
+ */
- jalview.datamodel.AlignmentI rjal = av.getAlignment(), jal = rjal;
-
- if (av.hasHiddenRows())
- {
- rjal = jal.getHiddenSequences().getFullAlignment();
++ protected void loadTrees(JalviewModel jm, Viewport view,
++ AlignFrame af, AlignViewport av, AlignmentPanel ap)
++ {
++ // TODO result of automated refactoring - are all these parameters needed?
++ try
++ {
++ for (int t = 0; t < jm.getTree().size(); t++)
++ {
++
++ Tree tree = jm.getTree().get(t);
++
++ TreePanel tp = (TreePanel) retrieveExistingObj(tree.getId());
++ if (tp == null)
++ {
++ tp = af.showNewickTree(new NewickFile(tree.getNewick()),
++ tree.getTitle(), safeInt(tree.getWidth()),
++ safeInt(tree.getHeight()), safeInt(tree.getXpos()),
++ safeInt(tree.getYpos()));
++ if (tp == null)
++ {
++ Console.warn("There was a problem recovering stored Newick tree: \n"
++ + tree.getNewick());
++ continue;
++ }
++ if (tree.getId() != null)
++ {
++ // perhaps bind the tree id to something ?
++ }
++ }
++ else
++ {
++ // update local tree attributes ?
++ // TODO: should check if tp has been manipulated by user - if so its
++ // settings shouldn't be modified
++ tp.setTitle(tree.getTitle());
++ tp.setBounds(new Rectangle(safeInt(tree.getXpos()),
++ safeInt(tree.getYpos()), safeInt(tree.getWidth()),
++ safeInt(tree.getHeight())));
++ tp.setViewport(av); // af.viewport;
++ // TODO: verify 'associate with all views' works still
++ tp.getTreeCanvas().setViewport(av); // af.viewport;
++ tp.getTreeCanvas().setAssociatedPanel(ap); // af.alignPanel;
++ }
++ tp.getTreeCanvas().setApplyToAllViews(tree.isLinkToAllViews());
++
++ tp.fitToWindow.setState(safeBoolean(tree.isFitToWindow()));
++ tp.fitToWindow_actionPerformed(null);
++
++ if (tree.getFontName() != null)
++ {
++ tp.setTreeFont(
++ new Font(tree.getFontName(), safeInt(tree.getFontStyle()),
++ safeInt(tree.getFontSize())));
++ }
++ else
++ {
++ tp.setTreeFont(
++ new Font(view.getFontName(), safeInt(view.getFontStyle()),
++ safeInt(view.getFontSize())));
++ }
++
++ tp.showPlaceholders(safeBoolean(tree.isMarkUnlinked()));
++ tp.showBootstrap(safeBoolean(tree.isShowBootstrap()));
++ tp.showDistances(safeBoolean(tree.isShowDistances()));
++
++ tp.getTreeCanvas().setThreshold(safeFloat(tree.getThreshold()));
++
++ if (safeBoolean(tree.isCurrentTree()))
++ {
++ af.getViewport().setCurrentTree(tp.getTree());
++ }
++ }
++
++ } catch (Exception ex)
++ {
++ ex.printStackTrace();
++ }
+ }
- SequenceSet vamsasSet = new SequenceSet();
- Sequence vamsasSeq;
- // JalviewModelSequence jms = new JalviewModelSequence();
-
- vamsasSet.setGapChar(jal.getGapCharacter() + "");
-
- if (jal.getDataset() != null)
- {
- // dataset id is the dataset's hashcode
- vamsasSet.setDatasetId(getDatasetIdRef(jal.getDataset()));
- if (storeDS)
- {
- // switch jal and the dataset
- jal = jal.getDataset();
- rjal = jal;
- }
- }
- if (jal.getProperties() != null)
- {
- Enumeration en = jal.getProperties().keys();
- while (en.hasMoreElements())
- {
- String key = en.nextElement().toString();
- SequenceSetProperties ssp = new SequenceSetProperties();
- ssp.setKey(key);
- ssp.setValue(jal.getProperties().get(key).toString());
- // vamsasSet.addSequenceSetProperties(ssp);
- vamsasSet.getSequenceSetProperties().add(ssp);
- }
- /*
- * Add mapping for sequences in this view to an already open viewer
++ /**
++ * Load and link any saved structure viewers.
++ *
++ * @param jprovider
++ * @param jseqs
++ * @param af
++ * @param ap
+ */
- final AAStructureBindingModel binding = viewer.getBinding();
- for (File id : oldFiles.keySet())
- {
- // add this and any other pdb files that should be present in the
- // viewer
- StructureData filedat = oldFiles.get(id);
- String pdbFile = filedat.getFilePath();
- SequenceI[] seq = filedat.getSeqList().toArray(new SequenceI[0]);
- binding.getSsm().setMapping(seq, null, pdbFile, DataSourceType.FILE,
- null);
- binding.addSequenceForStructFile(pdbFile, seq);
++ protected void loadPDBStructures(jarInputStreamProvider jprovider,
++ List<JSeq> jseqs, AlignFrame af, AlignmentPanel ap)
++ {
++ /*
++ * Run through all PDB ids on the alignment, and collect mappings between
++ * distinct view ids and all sequences referring to that view.
++ */
++ Map<String, StructureViewerModel> structureViewers = new LinkedHashMap<>();
++
++ for (int i = 0; i < jseqs.size(); i++)
++ {
++ JSeq jseq = jseqs.get(i);
++ if (jseq.getPdbids().size() > 0)
++ {
++ List<Pdbids> ids = jseq.getPdbids();
++ for (int p = 0; p < ids.size(); p++)
++ {
++ Pdbids pdbid = ids.get(p);
++ final int structureStateCount = pdbid.getStructureState().size();
++ for (int s = 0; s < structureStateCount; s++)
++ {
++ // check to see if we haven't already created this structure view
++ final StructureState structureState = pdbid
++ .getStructureState().get(s);
++ String sviewid = (structureState.getViewId() == null) ? null
++ : structureState.getViewId() + uniqueSetSuffix;
++ jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
++ // Originally : pdbid.getFile()
++ // : TODO: verify external PDB file recovery still works in normal
++ // jalview project load
++ jpdb.setFile(
++ loadPDBFile(jprovider, pdbid.getId(), pdbid.getFile()));
++ jpdb.setId(pdbid.getId());
++
++ int x = safeInt(structureState.getXpos());
++ int y = safeInt(structureState.getYpos());
++ int width = safeInt(structureState.getWidth());
++ int height = safeInt(structureState.getHeight());
++
++ // Probably don't need to do this anymore...
++ // Desktop.getDesktop().getComponentAt(x, y);
++ // TODO: NOW: check that this recovers the PDB file correctly.
++ String pdbFile = loadPDBFile(jprovider, pdbid.getId(),
++ pdbid.getFile());
++ jalview.datamodel.SequenceI seq = seqRefIds
++ .get(jseq.getId() + "");
++ if (sviewid == null)
++ {
++ sviewid = "_jalview_pre2_4_" + x + "," + y + "," + width + ","
++ + height;
++ }
++ if (!structureViewers.containsKey(sviewid))
++ {
++ String viewerType = structureState.getType();
++ if (viewerType == null) // pre Jalview 2.9
++ {
++ viewerType = ViewerType.JMOL.toString();
++ }
++ structureViewers.put(sviewid,
++ new StructureViewerModel(x, y, width, height, false,
++ false, true, structureState.getViewId(),
++ viewerType));
++ // Legacy pre-2.7 conversion JAL-823 :
++ // do not assume any view has to be linked for colour by
++ // sequence
++ }
++
++ // assemble String[] { pdb files }, String[] { id for each
++ // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
++ // seqs_file 2}, boolean[] {
++ // linkAlignPanel,superposeWithAlignpanel}} from hash
++ StructureViewerModel jmoldat = structureViewers.get(sviewid);
++ jmoldat.setAlignWithPanel(jmoldat.isAlignWithPanel()
++ || structureState.isAlignwithAlignPanel());
++
++ /*
++ * Default colour by linked panel to false if not specified (e.g.
++ * for pre-2.7 projects)
++ */
++ boolean colourWithAlignPanel = jmoldat.isColourWithAlignPanel();
++ colourWithAlignPanel |= structureState.isColourwithAlignPanel();
++ jmoldat.setColourWithAlignPanel(colourWithAlignPanel);
++
++ /*
++ * Default colour by viewer to true if not specified (e.g. for
++ * pre-2.7 projects)
++ */
++ boolean colourByViewer = jmoldat.isColourByViewer();
++ colourByViewer &= structureState.isColourByJmol();
++ jmoldat.setColourByViewer(colourByViewer);
++
++ if (jmoldat.getStateData().length() < structureState
++ .getValue()/*Content()*/.length())
++ {
++ jmoldat.setStateData(structureState.getValue());// Content());
++ }
++ if (pdbid.getFile() != null)
++ {
++ File mapkey = new File(pdbid.getFile());
++ StructureData seqstrmaps = jmoldat.getFileData().get(mapkey);
++ if (seqstrmaps == null)
++ {
++ jmoldat.getFileData().put(mapkey,
++ seqstrmaps = jmoldat.new StructureData(pdbFile,
++ pdbid.getId()));
++ }
++ if (!seqstrmaps.getSeqList().contains(seq))
++ {
++ seqstrmaps.getSeqList().add(seq);
++ // TODO and chains?
++ }
++ }
++ else
++ {
++ errorMessage = ("The Jmol views in this project were imported\nfrom an older version of Jalview.\nPlease review the sequence colour associations\nin the Colour by section of the Jmol View menu.\n\nIn the case of problems, see note at\nhttp://issues.jalview.org/browse/JAL-747");
++ Console.warn(errorMessage);
++ }
++ }
++ }
++ }
++ }
++ // Instantiate the associated structure views
++ for (Entry<String, StructureViewerModel> entry : structureViewers
++ .entrySet())
++ {
++ try
++ {
++ createOrLinkStructureViewer(entry, af, ap, jprovider);
++ } catch (Exception e)
++ {
++ System.err.println(
++ "Error loading structure viewer: " + e.getMessage());
++ // failed - try the next one
++ }
++ }
}
- // and add the AlignmentPanel's reference to the view panel
- viewer.addAlignmentPanel(ap);
- if (useinViewerSuperpos)
- {
- viewer.useAlignmentPanelForSuperposition(ap);
+
- JSeq jseq;
- Set<String> calcIdSet = new HashSet<>();
- // record the set of vamsas sequence XML POJO we create.
- HashMap<String, Sequence> vamsasSetIds = new HashMap<>();
- // SAVE SEQUENCES
- for (final SequenceI jds : rjal.getSequences())
- {
- final SequenceI jdatasq = jds.getDatasetSequence() == null ? jds
- : jds.getDatasetSequence();
- String id = seqHash(jds);
- if (vamsasSetIds.get(id) == null)
- {
- if (seqRefIds.get(id) != null && !storeDS)
- {
- // This happens for two reasons: 1. multiple views are being
- // serialised.
- // 2. the hashCode has collided with another sequence's code. This
- // DOES
- // HAPPEN! (PF00072.15.stk does this)
- // JBPNote: Uncomment to debug writing out of files that do not read
- // back in due to ArrayOutOfBoundExceptions.
- // System.err.println("vamsasSeq backref: "+id+"");
- // System.err.println(jds.getName()+"
- // "+jds.getStart()+"-"+jds.getEnd()+" "+jds.getSequenceAsString());
- // System.err.println("Hashcode: "+seqHash(jds));
- // SequenceI rsq = (SequenceI) seqRefIds.get(id + "");
- // System.err.println(rsq.getName()+"
- // "+rsq.getStart()+"-"+rsq.getEnd()+" "+rsq.getSequenceAsString());
- // System.err.println("Hashcode: "+seqHash(rsq));
- }
- else
- {
- vamsasSeq = createVamsasSequence(id, jds);
- // vamsasSet.addSequence(vamsasSeq);
- vamsasSet.getSequence().add(vamsasSeq);
- vamsasSetIds.put(id, vamsasSeq);
- seqRefIds.put(id, jds);
- }
- }
- jseq = new JSeq();
- jseq.setStart(jds.getStart());
- jseq.setEnd(jds.getEnd());
- jseq.setColour(av.getSequenceColour(jds).getRGB());
-
- jseq.setId(id); // jseq id should be a string not a number
- if (!storeDS)
- {
- // Store any sequences this sequence represents
- if (av.hasHiddenRows())
- {
- // use rjal, contains the full height alignment
- jseq.setHidden(
- av.getAlignment().getHiddenSequences().isHidden(jds));
-
- if (av.isHiddenRepSequence(jds))
- {
- jalview.datamodel.SequenceI[] reps = av
- .getRepresentedSequences(jds).getSequencesInOrder(rjal);
-
- for (int h = 0; h < reps.length; h++)
- {
- if (reps[h] != jds)
- {
- // jseq.addHiddenSequences(rjal.findIndex(reps[h]));
- jseq.getHiddenSequences().add(rjal.findIndex(reps[h]));
- }
- }
- }
- }
- // mark sequence as reference - if it is the reference for this view
- if (jal.hasSeqrep())
- {
- jseq.setViewreference(jds == jal.getSeqrep());
- }
- }
-
- // TODO: omit sequence features from each alignment view's XML dump if we
- // are storing dataset
- List<SequenceFeature> sfs = jds.getSequenceFeatures();
- for (SequenceFeature sf : sfs)
- {
- // Features features = new Features();
- Feature features = new Feature();
-
- features.setBegin(sf.getBegin());
- features.setEnd(sf.getEnd());
- features.setDescription(sf.getDescription());
- features.setType(sf.getType());
- features.setFeatureGroup(sf.getFeatureGroup());
- features.setScore(sf.getScore());
- if (sf.links != null)
- {
- for (int l = 0; l < sf.links.size(); l++)
- {
- OtherData keyValue = new OtherData();
- keyValue.setKey("LINK_" + l);
- keyValue.setValue(sf.links.elementAt(l).toString());
- // features.addOtherData(keyValue);
- features.getOtherData().add(keyValue);
- }
- }
- if (sf.otherDetails != null)
- {
- /*
- * save feature attributes, which may be simple strings or
- * map valued (have sub-attributes)
- */
- for (Entry<String, Object> entry : sf.otherDetails.entrySet())
- {
- String key = entry.getKey();
- Object value = entry.getValue();
- if (value instanceof Map<?, ?>)
- {
- for (Entry<String, Object> subAttribute : ((Map<String, Object>) value)
- .entrySet())
- {
- OtherData otherData = new OtherData();
- otherData.setKey(key);
- otherData.setKey2(subAttribute.getKey());
- otherData.setValue(subAttribute.getValue().toString());
- // features.addOtherData(otherData);
- features.getOtherData().add(otherData);
- }
- }
- else
- {
- OtherData otherData = new OtherData();
- otherData.setKey(key);
- otherData.setValue(value.toString());
- // features.addOtherData(otherData);
- features.getOtherData().add(otherData);
- }
- }
- }
-
- // jseq.addFeatures(features);
- jseq.getFeatures().add(features);
- }
-
- /*
- * save PDB entries for sequence
- */
- if (jdatasq.getAllPDBEntries() != null)
- {
- Enumeration<PDBEntry> en = jdatasq.getAllPDBEntries().elements();
- while (en.hasMoreElements())
- {
- Pdbids pdb = new Pdbids();
- jalview.datamodel.PDBEntry entry = en.nextElement();
-
- String pdbId = entry.getId();
- pdb.setId(pdbId);
- pdb.setType(entry.getType());
-
- /*
- * Store any structure views associated with this sequence. This
- * section copes with duplicate entries in the project, so a dataset
- * only view *should* be coped with sensibly.
- */
- // This must have been loaded, is it still visible?
- JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
- String matchedFile = null;
- for (int f = frames.length - 1; f > -1; f--)
- {
- if (frames[f] instanceof StructureViewerBase)
- {
- StructureViewerBase viewFrame = (StructureViewerBase) frames[f];
- matchedFile = saveStructureViewer(ap, jds, pdb, entry,
- viewIds, matchedFile, viewFrame);
- /*
- * Only store each structure viewer's state once in the project
- * jar. First time through only (storeDS==false)
- */
- String viewId = viewFrame.getViewId();
- String viewerType = viewFrame.getViewerType().toString();
- if (!storeDS && !viewIds.contains(viewId))
- {
- viewIds.add(viewId);
- File viewerState = viewFrame.saveSession();
- if (viewerState != null)
- {
- copyFileToJar(jout, viewerState.getPath(),
- getViewerJarEntryName(viewId), viewerType);
- }
- else
- {
- Cache.log.error(
- "Failed to save viewer state for " + viewerType);
- }
- }
- }
- }
-
- if (matchedFile != null || entry.getFile() != null)
- {
- if (entry.getFile() != null)
- {
- // use entry's file
- matchedFile = entry.getFile();
- }
- pdb.setFile(matchedFile); // entry.getFile());
- if (pdbfiles == null)
- {
- pdbfiles = new ArrayList<>();
- }
-
- if (!pdbfiles.contains(pdbId))
- {
- pdbfiles.add(pdbId);
- copyFileToJar(jout, matchedFile, pdbId, pdbId);
- }
- }
-
- Enumeration<String> props = entry.getProperties();
- if (props.hasMoreElements())
- {
- // PdbentryItem item = new PdbentryItem();
- while (props.hasMoreElements())
- {
- Property prop = new Property();
- String key = props.nextElement();
- prop.setName(key);
- prop.setValue(entry.getProperty(key).toString());
- // item.addProperty(prop);
- pdb.getProperty().add(prop);
- }
- // pdb.addPdbentryItem(item);
- }
-
- // jseq.addPdbids(pdb);
- jseq.getPdbids().add(pdb);
- }
- }
-
- saveRnaViewers(jout, jseq, jds, viewIds, ap, storeDS);
-
- if (jds.hasHMMProfile())
- {
- saveHmmerProfile(jout, jseq, jds);
- }
- // jms.addJSeq(jseq);
- object.getJSeq().add(jseq);
++ /**
++ *
++ * @param viewerData
++ * @param af
++ * @param ap
++ * @param jprovider
++ */
++ protected void createOrLinkStructureViewer(
++ Entry<String, StructureViewerModel> viewerData, AlignFrame af,
++ AlignmentPanel ap, jarInputStreamProvider jprovider)
++ {
++ final StructureViewerModel stateData = viewerData.getValue();
++
++ /*
++ * Search for any viewer windows already open from other alignment views
++ * that exactly match the stored structure state
++ */
++ StructureViewerBase comp = findMatchingViewer(viewerData);
++
++ if (comp != null)
++ {
++ linkStructureViewer(ap, comp, stateData);
++ return;
++ }
++
++ String type = stateData.getType();
++ try
++ {
++ ViewerType viewerType = ViewerType.valueOf(type);
++ createStructureViewer(viewerType, viewerData, af, jprovider);
++ } catch (IllegalArgumentException | NullPointerException e)
++ {
++ // TODO JAL-3619 show error dialog / offer an alternative viewer
++ Console.error("Invalid structure viewer type: " + type);
++ }
}
-
- if (!storeDS && av.hasHiddenRows())
- {
- jal = av.getAlignment();
- }
- // SAVE MAPPINGS
- // FOR DATASET
- if (storeDS && jal.getCodonFrames() != null)
- {
- List<AlignedCodonFrame> jac = jal.getCodonFrames();
- for (AlignedCodonFrame acf : jac)
- {
- AlcodonFrame alc = new AlcodonFrame();
- if (acf.getProtMappings() != null
- && acf.getProtMappings().length > 0)
- {
- boolean hasMap = false;
- SequenceI[] dnas = acf.getdnaSeqs();
- jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
- for (int m = 0; m < pmaps.length; m++)
- {
- AlcodMap alcmap = new AlcodMap();
- alcmap.setDnasq(seqHash(dnas[m]));
- alcmap.setMapping(
- createVamsasMapping(pmaps[m], dnas[m], null, false));
- // alc.addAlcodMap(alcmap);
- alc.getAlcodMap().add(alcmap);
- hasMap = true;
- }
- if (hasMap)
- {
- // vamsasSet.addAlcodonFrame(alc);
- vamsasSet.getAlcodonFrame().add(alc);
- }
- }
- // TODO: delete this ? dead code from 2.8.3->2.9 ?
- // {
- // AlcodonFrame alc = new AlcodonFrame();
- // vamsasSet.addAlcodonFrame(alc);
- // for (int p = 0; p < acf.aaWidth; p++)
- // {
- // Alcodon cmap = new Alcodon();
- // if (acf.codons[p] != null)
- // {
- // // Null codons indicate a gapped column in the translated peptide
- // // alignment.
- // cmap.setPos1(acf.codons[p][0]);
- // cmap.setPos2(acf.codons[p][1]);
- // cmap.setPos3(acf.codons[p][2]);
- // }
- // alc.addAlcodon(cmap);
- // }
- // if (acf.getProtMappings() != null
- // && acf.getProtMappings().length > 0)
- // {
- // SequenceI[] dnas = acf.getdnaSeqs();
- // jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
- // for (int m = 0; m < pmaps.length; m++)
- // {
- // AlcodMap alcmap = new AlcodMap();
- // alcmap.setDnasq(seqHash(dnas[m]));
- // alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
- // false));
- // alc.addAlcodMap(alcmap);
- // }
- // }
- }
- }
-
- // SAVE TREES
- // /////////////////////////////////
- if (!storeDS && av.getCurrentTree() != null)
- {
- // FIND ANY ASSOCIATED TREES
- // NOT IMPLEMENTED FOR HEADLESS STATE AT PRESENT
- if (Desktop.getDesktopPane() != null)
- {
- JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
-
- for (int t = 0; t < frames.length; t++)
- {
- if (frames[t] instanceof TreePanel)
- {
- TreePanel tp = (TreePanel) frames[t];
-
- if (tp.getTreeCanvas().getViewport().getAlignment() == jal)
- {
- JalviewModel.Tree tree = new JalviewModel.Tree();
- tree.setTitle(tp.getTitle());
- tree.setCurrentTree((av.getCurrentTree() == tp.getTree()));
- tree.setNewick(tp.getTree().print());
- tree.setThreshold(tp.getTreeCanvas().getThreshold());
-
- tree.setFitToWindow(tp.fitToWindow.getState());
- tree.setFontName(tp.getTreeFont().getName());
- tree.setFontSize(tp.getTreeFont().getSize());
- tree.setFontStyle(tp.getTreeFont().getStyle());
- tree.setMarkUnlinked(tp.placeholdersMenu.getState());
-
- tree.setShowBootstrap(tp.bootstrapMenu.getState());
- tree.setShowDistances(tp.distanceMenu.getState());
-
- tree.setHeight(tp.getHeight());
- tree.setWidth(tp.getWidth());
- tree.setXpos(tp.getX());
- tree.setYpos(tp.getY());
- tree.setId(makeHashCode(tp, null));
- tree.setLinkToAllViews(
- tp.getTreeCanvas().isApplyToAllViews());
-
- // jms.addTree(tree);
- object.getTree().add(tree);
- }
- }
- }
- }
- }
-
- /*
- * save PCA viewers
- */
- if (!storeDS && Desktop.getDesktopPane() != null)
- {
- for (JInternalFrame frame : Desktop.getDesktopPane().getAllFrames())
- {
- if (frame instanceof PCAPanel)
- {
- PCAPanel panel = (PCAPanel) frame;
- if (panel.getAlignViewport().getAlignment() == jal)
- {
- savePCA(panel, object);
- }
- }
- }
- }
-
- // SAVE ANNOTATIONS
- else
+ /**
- * store forward refs from an annotationRow to any groups
- */
- IdentityHashMap<SequenceGroup, String> groupRefs = new IdentityHashMap<>();
- if (storeDS)
- {
- for (SequenceI sq : jal.getSequences())
- {
- // Store annotation on dataset sequences only
- AlignmentAnnotation[] aa = sq.getAnnotation();
- if (aa != null && aa.length > 0)
- {
- storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
- vamsasSet);
- }
- }
- }
- else
- {
- if (jal.getAlignmentAnnotation() != null)
- {
- // Store the annotation shown on the alignment.
- AlignmentAnnotation[] aa = jal.getAlignmentAnnotation();
- storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
- vamsasSet);
- }
- }
- // SAVE GROUPS
- if (jal.getGroups() != null)
- {
- JGroup[] groups = new JGroup[jal.getGroups().size()];
- int i = -1;
- for (jalview.datamodel.SequenceGroup sg : jal.getGroups())
- {
- JGroup jGroup = new JGroup();
- groups[++i] = jGroup;
-
- jGroup.setStart(sg.getStartRes());
- jGroup.setEnd(sg.getEndRes());
- jGroup.setName(sg.getName());
- if (groupRefs.containsKey(sg))
- {
- // group has references so set its ID field
- jGroup.setId(groupRefs.get(sg));
- }
- ColourSchemeI colourScheme = sg.getColourScheme();
- if (colourScheme != null)
- {
- ResidueShaderI groupColourScheme = sg.getGroupColourScheme();
- if (groupColourScheme.conservationApplied())
- {
- jGroup.setConsThreshold(groupColourScheme.getConservationInc());
-
- if (colourScheme instanceof jalview.schemes.UserColourScheme)
- {
- jGroup.setColour(
- setUserColourScheme(colourScheme, userColours,
- object));
- }
- else
- {
- jGroup.setColour(colourScheme.getSchemeName());
- }
- }
- else if (colourScheme instanceof jalview.schemes.AnnotationColourGradient)
- {
- jGroup.setColour("AnnotationColourGradient");
- jGroup.setAnnotationColours(constructAnnotationColours(
- (jalview.schemes.AnnotationColourGradient) colourScheme,
- userColours, object));
- }
- else if (colourScheme instanceof jalview.schemes.UserColourScheme)
- {
- jGroup.setColour(
- setUserColourScheme(colourScheme, userColours, object));
- }
- else
- {
- jGroup.setColour(colourScheme.getSchemeName());
- }
-
- jGroup.setPidThreshold(groupColourScheme.getThreshold());
- }
-
- jGroup.setOutlineColour(sg.getOutlineColour().getRGB());
- jGroup.setDisplayBoxes(sg.getDisplayBoxes());
- jGroup.setDisplayText(sg.getDisplayText());
- jGroup.setColourText(sg.getColourText());
- jGroup.setTextCol1(sg.textColour.getRGB());
- jGroup.setTextCol2(sg.textColour2.getRGB());
- jGroup.setTextColThreshold(sg.thresholdTextColour);
- jGroup.setShowUnconserved(sg.getShowNonconserved());
- jGroup.setIgnoreGapsinConsensus(sg.getIgnoreGapsConsensus());
- jGroup.setShowConsensusHistogram(sg.isShowConsensusHistogram());
- jGroup.setShowSequenceLogo(sg.isShowSequenceLogo());
- jGroup.setNormaliseSequenceLogo(sg.isNormaliseSequenceLogo());
- for (SequenceI seq : sg.getSequences())
- {
- // jGroup.addSeq(seqHash(seq));
- jGroup.getSeq().add(seqHash(seq));
- }
- }
-
- //jms.setJGroup(groups);
- Object group;
- for (JGroup grp : groups)
- {
- object.getJGroup().add(grp);
- }
- }
- if (!storeDS)
- {
- // /////////SAVE VIEWPORT
- Viewport view = new Viewport();
- view.setTitle(ap.alignFrame.getTitle());
- view.setSequenceSetId(
- makeHashCode(av.getSequenceSetId(), av.getSequenceSetId()));
- view.setId(av.getViewId());
- if (av.getCodingComplement() != null)
- {
- view.setComplementId(av.getCodingComplement().getViewId());
- }
- view.setViewName(av.getViewName());
- view.setGatheredViews(av.isGatherViewsHere());
-
- Rectangle size = ap.av.getExplodedGeometry();
- Rectangle position = size;
- if (size == null)
- {
- size = ap.alignFrame.getBounds();
- if (av.getCodingComplement() != null)
- {
- position = ((SplitFrame) ap.alignFrame.getSplitViewContainer())
- .getBounds();
- }
- else
- {
- position = size;
- }
- }
- view.setXpos(position.x);
- view.setYpos(position.y);
-
- view.setWidth(size.width);
- view.setHeight(size.height);
-
- view.setStartRes(vpRanges.getStartRes());
- view.setStartSeq(vpRanges.getStartSeq());
-
- if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
- {
- view.setBgColour(setUserColourScheme(av.getGlobalColourScheme(),
- userColours, object));
- }
- else if (av
- .getGlobalColourScheme() instanceof jalview.schemes.AnnotationColourGradient)
- {
- AnnotationColourScheme ac = constructAnnotationColours(
- (jalview.schemes.AnnotationColourGradient) av
- .getGlobalColourScheme(),
- userColours, object);
-
- view.setAnnotationColours(ac);
- view.setBgColour("AnnotationColourGradient");
- }
- else
- {
- view.setBgColour(ColourSchemeProperty
- .getColourName(av.getGlobalColourScheme()));
- }
-
- ResidueShaderI vcs = av.getResidueShading();
- ColourSchemeI cs = av.getGlobalColourScheme();
-
- if (cs != null)
- {
- if (vcs.conservationApplied())
- {
- view.setConsThreshold(vcs.getConservationInc());
- if (cs instanceof jalview.schemes.UserColourScheme)
- {
- view.setBgColour(setUserColourScheme(cs, userColours, object));
- }
- }
- view.setPidThreshold(vcs.getThreshold());
- }
-
- view.setConservationSelected(av.getConservationSelected());
- view.setPidSelected(av.getAbovePIDThreshold());
- final Font font = av.getFont();
- view.setFontName(font.getName());
- view.setFontSize(font.getSize());
- view.setFontStyle(font.getStyle());
- view.setScaleProteinAsCdna(av.getViewStyle().isScaleProteinAsCdna());
- view.setRenderGaps(av.isRenderGaps());
- view.setShowAnnotation(av.isShowAnnotation());
- view.setShowBoxes(av.getShowBoxes());
- view.setShowColourText(av.getColourText());
- view.setShowFullId(av.getShowJVSuffix());
- view.setRightAlignIds(av.isRightAlignIds());
- view.setShowSequenceFeatures(av.isShowSequenceFeatures());
- view.setShowText(av.getShowText());
- view.setShowUnconserved(av.getShowUnconserved());
- view.setWrapAlignment(av.getWrapAlignment());
- view.setTextCol1(av.getTextColour().getRGB());
- view.setTextCol2(av.getTextColour2().getRGB());
- view.setTextColThreshold(av.getThresholdTextColour());
- view.setShowConsensusHistogram(av.isShowConsensusHistogram());
- view.setShowSequenceLogo(av.isShowSequenceLogo());
- view.setNormaliseSequenceLogo(av.isNormaliseSequenceLogo());
- view.setShowGroupConsensus(av.isShowGroupConsensus());
- view.setShowGroupConservation(av.isShowGroupConservation());
- view.setShowNPfeatureTooltip(av.isShowNPFeats());
- view.setShowDbRefTooltip(av.isShowDBRefs());
- view.setFollowHighlight(av.isFollowHighlight());
- view.setFollowSelection(av.followSelection);
- view.setIgnoreGapsinConsensus(av.isIgnoreGapsConsensus());
- view.setShowComplementFeatures(av.isShowComplementFeatures());
- view.setShowComplementFeaturesOnTop(
- av.isShowComplementFeaturesOnTop());
- if (av.getFeaturesDisplayed() != null)
- {
- FeatureSettings fs = new FeatureSettings();
-
- FeatureRendererModel fr = ap.getSeqPanel().seqCanvas
- .getFeatureRenderer();
- String[] renderOrder = fr.getRenderOrder().toArray(new String[0]);
-
- Vector<String> settingsAdded = new Vector<>();
- if (renderOrder != null)
- {
- for (String featureType : renderOrder)
- {
- FeatureSettings.Setting setting = new FeatureSettings.Setting();
- setting.setType(featureType);
-
- /*
- * save any filter for the feature type
- */
- FeatureMatcherSetI filter = fr.getFeatureFilter(featureType);
- if (filter != null) {
- Iterator<FeatureMatcherI> filters = filter.getMatchers().iterator();
- FeatureMatcherI firstFilter = filters.next();
- setting.setMatcherSet(Jalview2XML.marshalFilter(
- firstFilter, filters, filter.isAnded()));
- }
-
- /*
- * save colour scheme for the feature type
- */
- FeatureColourI fcol = fr.getFeatureStyle(featureType);
- if (!fcol.isSimpleColour())
- {
- setting.setColour(fcol.getMaxColour().getRGB());
- setting.setMincolour(fcol.getMinColour().getRGB());
- setting.setMin(fcol.getMin());
- setting.setMax(fcol.getMax());
- setting.setColourByLabel(fcol.isColourByLabel());
- if (fcol.isColourByAttribute())
- {
- String[] attName = fcol.getAttributeName();
- setting.getAttributeName().add(attName[0]);
- if (attName.length > 1)
- {
- setting.getAttributeName().add(attName[1]);
- }
- }
- setting.setAutoScale(fcol.isAutoScaled());
- setting.setThreshold(fcol.getThreshold());
- Color noColour = fcol.getNoColour();
- if (noColour == null)
- {
- setting.setNoValueColour(NoValueColour.NONE);
- }
- else if (noColour.equals(fcol.getMaxColour()))
- {
- setting.setNoValueColour(NoValueColour.MAX);
- }
- else
- {
- setting.setNoValueColour(NoValueColour.MIN);
- }
- // -1 = No threshold, 0 = Below, 1 = Above
- setting.setThreshstate(fcol.isAboveThreshold() ? 1
- : (fcol.isBelowThreshold() ? 0 : -1));
- }
- else
- {
- setting.setColour(fcol.getColour().getRGB());
- }
-
- setting.setDisplay(
- av.getFeaturesDisplayed().isVisible(featureType));
- float rorder = fr
- .getOrder(featureType);
- if (rorder > -1)
- {
- setting.setOrder(rorder);
- }
- /// fs.addSetting(setting);
- fs.getSetting().add(setting);
- settingsAdded.addElement(featureType);
- }
- }
-
- // is groups actually supposed to be a map here ?
- Iterator<String> en = fr.getFeatureGroups().iterator();
- Vector<String> groupsAdded = new Vector<>();
- while (en.hasNext())
- {
- String grp = en.next();
- if (groupsAdded.contains(grp))
- {
- continue;
- }
- Group g = new Group();
- g.setName(grp);
- g.setDisplay(((Boolean) fr.checkGroupVisibility(grp, false))
- .booleanValue());
- // fs.addGroup(g);
- fs.getGroup().add(g);
- groupsAdded.addElement(grp);
- }
- // jms.setFeatureSettings(fs);
- object.setFeatureSettings(fs);
- }
-
- if (av.hasHiddenColumns())
- {
- jalview.datamodel.HiddenColumns hidden = av.getAlignment()
- .getHiddenColumns();
- if (hidden == null)
- {
- warn("REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
- }
- else
- {
- Iterator<int[]> hiddenRegions = hidden.iterator();
- while (hiddenRegions.hasNext())
- {
- int[] region = hiddenRegions.next();
- HiddenColumns hc = new HiddenColumns();
- hc.setStart(region[0]);
- hc.setEnd(region[1]);
- // view.addHiddenColumns(hc);
- view.getHiddenColumns().add(hc);
- }
- }
- }
- if (calcIdSet.size() > 0)
- {
- for (String calcId : calcIdSet)
- {
- if (calcId.trim().length() > 0)
- {
- CalcIdParam cidp = createCalcIdParam(calcId, av);
- // Some calcIds have no parameters.
- if (cidp != null)
- {
- // view.addCalcIdParam(cidp);
- view.getCalcIdParam().add(cidp);
- }
- }
- }
- }
-
- // jms.addViewport(view);
- object.getViewport().add(view);
- }
- // object.setJalviewModelSequence(jms);
- // object.getVamsasModel().addSequenceSet(vamsasSet);
- object.getVamsasModel().getSequenceSet().add(vamsasSet);
-
- if (jout != null && fileName != null)
- {
- // We may not want to write the object to disk,
- // eg we can copy the alignViewport to a new view object
- // using save and then load
- try
- {
- fileName = fileName.replace('\\', '/');
- System.out.println("Writing jar entry " + fileName);
- JarEntry entry = new JarEntry(fileName);
- jout.putNextEntry(entry);
- PrintWriter pout = new PrintWriter(
- new OutputStreamWriter(jout, UTF_8));
- JAXBContext jaxbContext = JAXBContext
- .newInstance(JalviewModel.class);
- Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
-
- // output pretty printed
- // jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- jaxbMarshaller.marshal(
- new ObjectFactory().createJalviewModel(object), pout);
-
- // jaxbMarshaller.marshal(object, pout);
- // marshaller.marshal(object);
- pout.flush();
- jout.closeEntry();
- } catch (Exception ex)
- {
- // TODO: raise error in GUI if marshalling failed.
- System.err.println("Error writing Jalview project");
- ex.printStackTrace();
- }
- }
- return object;
- }
- /**
- * Saves the HMMER profile associated with the sequence as a file in the jar,
- * in HMMER format, and saves the name of the file as a child element of the
- * XML sequence element
- *
- * @param jout
- * @param xmlSeq
- * @param seq
- */
- protected void saveHmmerProfile(JarOutputStream jout, JSeq xmlSeq,
- SequenceI seq)
- {
- HiddenMarkovModel profile = seq.getHMM();
- if (profile == null)
- {
- warn("Want to save HMM profile for " + seq.getName()
- + " but none found");
- return;
- }
- HMMFile hmmFile = new HMMFile(profile);
- String hmmAsString = hmmFile.print();
- String jarEntryName = HMMER_PREFIX + nextCounter();
- try
- {
- writeJarEntry(jout, jarEntryName, hmmAsString.getBytes());
- xmlSeq.setHmmerProfile(jarEntryName);
- } catch (IOException e)
- {
- warn("Error saving HMM profile: " + e.getMessage());
- }
- }
-
-
- /**
- * Writes PCA viewer attributes and computed values to an XML model object and
- * adds it to the JalviewModel. Any exceptions are reported by logging.
- */
- protected void savePCA(PCAPanel panel, JalviewModel object)
- {
- try
- {
- PcaViewer viewer = new PcaViewer();
- viewer.setHeight(panel.getHeight());
- viewer.setWidth(panel.getWidth());
- viewer.setXpos(panel.getX());
- viewer.setYpos(panel.getY());
- viewer.setTitle(panel.getTitle());
- PCAModel pcaModel = panel.getPcaModel();
- viewer.setScoreModelName(pcaModel.getScoreModelName());
- viewer.setXDim(panel.getSelectedDimensionIndex(X));
- viewer.setYDim(panel.getSelectedDimensionIndex(Y));
- viewer.setZDim(panel.getSelectedDimensionIndex(Z));
- viewer.setBgColour(
- panel.getRotatableCanvas().getBackgroundColour().getRGB());
- viewer.setScaleFactor(panel.getRotatableCanvas().getScaleFactor());
- float[] spMin = panel.getRotatableCanvas().getSeqMin();
- SeqPointMin spmin = new SeqPointMin();
- spmin.setXPos(spMin[0]);
- spmin.setYPos(spMin[1]);
- spmin.setZPos(spMin[2]);
- viewer.setSeqPointMin(spmin);
- float[] spMax = panel.getRotatableCanvas().getSeqMax();
- SeqPointMax spmax = new SeqPointMax();
- spmax.setXPos(spMax[0]);
- spmax.setYPos(spMax[1]);
- spmax.setZPos(spMax[2]);
- viewer.setSeqPointMax(spmax);
- viewer.setShowLabels(panel.getRotatableCanvas().isShowLabels());
- viewer.setLinkToAllViews(
- panel.getRotatableCanvas().isApplyToAllViews());
- SimilarityParamsI sp = pcaModel.getSimilarityParameters();
- viewer.setIncludeGaps(sp.includeGaps());
- viewer.setMatchGaps(sp.matchGaps());
- viewer.setIncludeGappedColumns(sp.includeGappedColumns());
- viewer.setDenominateByShortestLength(sp.denominateByShortestLength());
-
- /*
- * sequence points on display
- */
- for (jalview.datamodel.SequencePoint spt : pcaModel
- .getSequencePoints())
- {
- SequencePoint point = new SequencePoint();
- point.setSequenceRef(seqHash(spt.getSequence()));
- point.setXPos(spt.coord.x);
- point.setYPos(spt.coord.y);
- point.setZPos(spt.coord.z);
- viewer.getSequencePoint().add(point);
- }
-
- /*
- * (end points of) axes on display
- */
- for (Point p : panel.getRotatableCanvas().getAxisEndPoints())
- {
-
- Axis axis = new Axis();
- axis.setXPos(p.x);
- axis.setYPos(p.y);
- axis.setZPos(p.z);
- viewer.getAxis().add(axis);
- }
-
- /*
- * raw PCA data (note we are not restoring PCA inputs here -
- * alignment view, score model, similarity parameters)
- */
- PcaDataType data = new PcaDataType();
- viewer.setPcaData(data);
- PCA pca = pcaModel.getPcaData();
-
- DoubleMatrix pm = new DoubleMatrix();
- saveDoubleMatrix(pca.getPairwiseScores(), pm);
- data.setPairwiseMatrix(pm);
-
- DoubleMatrix tm = new DoubleMatrix();
- saveDoubleMatrix(pca.getTridiagonal(), tm);
- data.setTridiagonalMatrix(tm);
-
- DoubleMatrix eigenMatrix = new DoubleMatrix();
- data.setEigenMatrix(eigenMatrix);
- saveDoubleMatrix(pca.getEigenmatrix(), eigenMatrix);
-
- object.getPcaViewer().add(viewer);
- } catch (Throwable t)
- {
- Cache.log.error("Error saving PCA: " + t.getMessage());
- }
- }
-
- /**
- * Stores values from a matrix into an XML element, including (if present) the
- * D or E vectors
- *
- * @param m
- * @param xmlMatrix
- * @see #loadDoubleMatrix(DoubleMatrix)
- */
- protected void saveDoubleMatrix(MatrixI m, DoubleMatrix xmlMatrix)
- {
- xmlMatrix.setRows(m.height());
- xmlMatrix.setColumns(m.width());
- for (int i = 0; i < m.height(); i++)
- {
- DoubleVector row = new DoubleVector();
- for (int j = 0; j < m.width(); j++)
- {
- row.getV().add(m.getValue(i, j));
- }
- xmlMatrix.getRow().add(row);
- }
- if (m.getD() != null)
- {
- DoubleVector dVector = new DoubleVector();
- for (double d : m.getD())
- {
- dVector.getV().add(d);
- }
- xmlMatrix.setD(dVector);
- }
- if (m.getE() != null)
- {
- DoubleVector eVector = new DoubleVector();
- for (double e : m.getE())
- {
- eVector.getV().add(e);
- }
- xmlMatrix.setE(eVector);
- }
- }
-
- /**
- * Loads XML matrix data into a new Matrix object, including the D and/or E
- * vectors (if present)
- *
- * @param mData
- * @return
- * @see Jalview2XML#saveDoubleMatrix(MatrixI, DoubleMatrix)
- */
- protected MatrixI loadDoubleMatrix(DoubleMatrix mData)
- {
- int rows = mData.getRows();
- double[][] vals = new double[rows][];
-
- for (int i = 0; i < rows; i++)
- {
- List<Double> dVector = mData.getRow().get(i).getV();
- vals[i] = new double[dVector.size()];
- int dvi = 0;
- for (Double d : dVector)
- {
- vals[i][dvi++] = d;
- }
- }
-
- MatrixI m = new Matrix(vals);
-
- if (mData.getD() != null)
- {
- List<Double> dVector = mData.getD().getV();
- double[] vec = new double[dVector.size()];
- int dvi = 0;
- for (Double d : dVector)
- {
- vec[dvi++] = d;
- }
- m.setD(vec);
- }
- if (mData.getE() != null)
- {
- List<Double> dVector = mData.getE().getV();
- double[] vec = new double[dVector.size()];
- int dvi = 0;
- for (Double d : dVector)
- {
- vec[dvi++] = d;
- }
- m.setE(vec);
- }
-
- return m;
- }
-
- /**
- * Save any Varna viewers linked to this sequence. Writes an rnaViewer element
- * for each viewer, with
- * <ul>
- * <li>viewer geometry (position, size, split pane divider location)</li>
- * <li>index of the selected structure in the viewer (currently shows gapped
- * or ungapped)</li>
- * <li>the id of the annotation holding RNA secondary structure</li>
- * <li>(currently only one SS is shown per viewer, may be more in future)</li>
- * </ul>
- * Varna viewer state is also written out (in native Varna XML) to separate
- * project jar entries. A separate entry is written for each RNA structure
- * displayed, with the naming convention
- * <ul>
- * <li>rna_viewId_sequenceId_annotationId_[gapped|trimmed]</li>
- * </ul>
- *
- * @param jout
- * @param jseq
- * @param jds
- * @param viewIds
- * @param ap
- * @param storeDataset
- */
- protected void saveRnaViewers(JarOutputStream jout, JSeq jseq,
- final SequenceI jds, List<String> viewIds, AlignmentPanel ap,
- boolean storeDataset)
- {
- if (Desktop.getDesktopPane() == null)
- {
- return;
- }
- JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
- for (int f = frames.length - 1; f > -1; f--)
- {
- if (frames[f] instanceof AppVarna)
- {
- AppVarna varna = (AppVarna) frames[f];
- /*
- * link the sequence to every viewer that is showing it and is linked to
- * its alignment panel
- */
- if (varna.isListeningFor(jds) && ap == varna.getAlignmentPanel())
- {
- String viewId = varna.getViewId();
- RnaViewer rna = new RnaViewer();
- rna.setViewId(viewId);
- rna.setTitle(varna.getTitle());
- rna.setXpos(varna.getX());
- rna.setYpos(varna.getY());
- rna.setWidth(varna.getWidth());
- rna.setHeight(varna.getHeight());
- rna.setDividerLocation(varna.getDividerLocation());
- rna.setSelectedRna(varna.getSelectedIndex());
- // jseq.addRnaViewer(rna);
- jseq.getRnaViewer().add(rna);
-
- /*
- * Store each Varna panel's state once in the project per sequence.
- * First time through only (storeDataset==false)
- */
- // boolean storeSessions = false;
- // String sequenceViewId = viewId + seqsToIds.get(jds);
- // if (!storeDataset && !viewIds.contains(sequenceViewId))
- // {
- // viewIds.add(sequenceViewId);
- // storeSessions = true;
- // }
- for (RnaModel model : varna.getModels())
- {
- if (model.seq == jds)
- {
- /*
- * VARNA saves each view (sequence or alignment secondary
- * structure, gapped or trimmed) as a separate XML file
- */
- String jarEntryName = rnaSessions.get(model);
- if (jarEntryName == null)
- {
-
- String varnaStateFile = varna.getStateInfo(model.rna);
- jarEntryName = RNA_PREFIX + viewId + "_" + nextCounter();
- copyFileToJar(jout, varnaStateFile, jarEntryName, "Varna");
- rnaSessions.put(model, jarEntryName);
- }
- SecondaryStructure ss = new SecondaryStructure();
- String annotationId = varna.getAnnotation(jds).annotationId;
- ss.setAnnotationId(annotationId);
- ss.setViewerState(jarEntryName);
- ss.setGapped(model.gapped);
- ss.setTitle(model.title);
- // rna.addSecondaryStructure(ss);
- rna.getSecondaryStructure().add(ss);
- }
- }
- }
- }
- }
- }
-
- /**
- * Copy the contents of a file to a new entry added to the output jar
- *
- * @param jout
- * @param infilePath
- * @param jarEntryName
- * @param msg
- * additional identifying info to log to the console
- */
- protected void copyFileToJar(JarOutputStream jout, String infilePath,
- String jarEntryName, String msg)
- {
- try (InputStream is = new FileInputStream(infilePath))
- {
- File file = new File(infilePath);
- if (file.exists() && jout != null)
- {
- System.out.println(
- "Writing jar entry " + jarEntryName + " (" + msg + ")");
- jout.putNextEntry(new JarEntry(jarEntryName));
- copyAll(is, jout);
- jout.closeEntry();
- // dis = new DataInputStream(new FileInputStream(file));
- // byte[] data = new byte[(int) file.length()];
- // dis.readFully(data);
- // writeJarEntry(jout, jarEntryName, data);
- }
- } catch (Exception ex)
- {
- ex.printStackTrace();
- }
- }
-
- /**
- * Copies input to output, in 4K buffers; handles any data (text or binary)
- *
- * @param in
- * @param out
- * @throws IOException
- */
- protected void copyAll(InputStream in, OutputStream out)
- throws IOException
- {
- byte[] buffer = new byte[4096];
- int bytesRead = 0;
- while ((bytesRead = in.read(buffer)) != -1)
- {
- out.write(buffer, 0, bytesRead);
- }
- }
-
- /**
- * Save the state of a structure viewer
- *
- * @param ap
- * @param jds
- * @param pdb
- * the archive XML element under which to save the state
- * @param entry
- * @param viewIds
- * @param matchedFile
- * @param viewFrame
- * @return
- */
- protected String saveStructureViewer(AlignmentPanel ap, SequenceI jds,
- Pdbids pdb, PDBEntry entry, List<String> viewIds,
- String matchedFile, StructureViewerBase viewFrame)
- {
- final AAStructureBindingModel bindingModel = viewFrame.getBinding();
-
- /*
- * Look for any bindings for this viewer to the PDB file of interest
- * (including part matches excluding chain id)
- */
- for (int peid = 0; peid < bindingModel.getPdbCount(); peid++)
- {
- final PDBEntry pdbentry = bindingModel.getPdbEntry(peid);
- final String pdbId = pdbentry.getId();
- if (!pdbId.equals(entry.getId())
- && !(entry.getId().length() > 4 && entry.getId().toLowerCase(Locale.ROOT)
- .startsWith(pdbId.toLowerCase(Locale.ROOT))))
- {
- /*
- * not interested in a binding to a different PDB entry here
- */
- continue;
- }
- if (matchedFile == null)
- {
- matchedFile = pdbentry.getFile();
- }
- else if (!matchedFile.equals(pdbentry.getFile()))
- {
- Cache.log.warn(
- "Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
- + pdbentry.getFile());
- }
- // record the
- // file so we
- // can get at it if the ID
- // match is ambiguous (e.g.
- // 1QIP==1qipA)
-
- for (int smap = 0; smap < viewFrame.getBinding()
- .getSequence()[peid].length; smap++)
- {
- // if (jal.findIndex(jmol.jmb.sequence[peid][smap]) > -1)
- if (jds == viewFrame.getBinding().getSequence()[peid][smap])
- {
- StructureState state = new StructureState();
- state.setVisible(true);
- state.setXpos(viewFrame.getX());
- state.setYpos(viewFrame.getY());
- state.setWidth(viewFrame.getWidth());
- state.setHeight(viewFrame.getHeight());
- final String viewId = viewFrame.getViewId();
- state.setViewId(viewId);
- state.setAlignwithAlignPanel(viewFrame.isUsedforaligment(ap));
- state.setColourwithAlignPanel(viewFrame.isUsedForColourBy(ap));
- state.setColourByJmol(viewFrame.isColouredByViewer());
- state.setType(viewFrame.getViewerType().toString());
- // pdb.addStructureState(state);
- pdb.getStructureState().add(state);
- }
- }
- }
- return matchedFile;
- }
-
- /**
- * Populates the AnnotationColourScheme xml for save. This captures the
- * settings of the options in the 'Colour by Annotation' dialog.
- *
- * @param acg
- * @param userColours
- * @param jm
- * @return
- */
- private AnnotationColourScheme constructAnnotationColours(
- AnnotationColourGradient acg, List<UserColourScheme> userColours,
- JalviewModel jm)
- {
- AnnotationColourScheme ac = new AnnotationColourScheme();
- ac.setAboveThreshold(acg.getAboveThreshold());
- ac.setThreshold(acg.getAnnotationThreshold());
- // 2.10.2 save annotationId (unique) not annotation label
- ac.setAnnotation(acg.getAnnotation().annotationId);
- if (acg.getBaseColour() instanceof UserColourScheme)
- {
- ac.setColourScheme(
- setUserColourScheme(acg.getBaseColour(), userColours, jm));
- }
- else
- {
- ac.setColourScheme(
- ColourSchemeProperty.getColourName(acg.getBaseColour()));
- }
-
- ac.setMaxColour(acg.getMaxColour().getRGB());
- ac.setMinColour(acg.getMinColour().getRGB());
- ac.setPerSequence(acg.isSeqAssociated());
- ac.setPredefinedColours(acg.isPredefinedColours());
- return ac;
- }
-
- private void storeAlignmentAnnotation(AlignmentAnnotation[] aa,
- IdentityHashMap<SequenceGroup, String> groupRefs,
- AlignmentViewport av, Set<String> calcIdSet, boolean storeDS,
- SequenceSet vamsasSet)
- {
-
- for (int i = 0; i < aa.length; i++)
- {
- Annotation an = new Annotation();
-
- AlignmentAnnotation annotation = aa[i];
- if (annotation.annotationId != null)
- {
- annotationIds.put(annotation.annotationId, annotation);
- }
-
- an.setId(annotation.annotationId);
-
- an.setVisible(annotation.visible);
-
- an.setDescription(annotation.description);
-
- if (annotation.sequenceRef != null)
- {
- // 2.9 JAL-1781 xref on sequence id rather than name
- an.setSequenceRef(seqsToIds.get(annotation.sequenceRef));
- }
- if (annotation.groupRef != null)
- {
- String groupIdr = groupRefs.get(annotation.groupRef);
- if (groupIdr == null)
- {
- // make a locally unique String
- groupRefs.put(annotation.groupRef,
- groupIdr = ("" + System.currentTimeMillis()
- + annotation.groupRef.getName()
- + groupRefs.size()));
- }
- an.setGroupRef(groupIdr.toString());
- }
-
- // store all visualization attributes for annotation
- an.setGraphHeight(annotation.graphHeight);
- an.setCentreColLabels(annotation.centreColLabels);
- an.setScaleColLabels(annotation.scaleColLabel);
- an.setShowAllColLabels(annotation.showAllColLabels);
- an.setBelowAlignment(annotation.belowAlignment);
-
- if (annotation.graph > 0)
- {
- an.setGraph(true);
- an.setGraphType(annotation.graph);
- an.setGraphGroup(annotation.graphGroup);
- if (annotation.getThreshold() != null)
- {
- ThresholdLine line = new ThresholdLine();
- line.setLabel(annotation.getThreshold().label);
- line.setValue(annotation.getThreshold().value);
- line.setColour(annotation.getThreshold().colour.getRGB());
- an.setThresholdLine(line);
- }
- }
- else
- {
- an.setGraph(false);
- }
-
- an.setLabel(annotation.label);
-
- if (annotation == av.getAlignmentQualityAnnot()
- || annotation == av.getAlignmentConservationAnnotation()
- || annotation == av.getAlignmentConsensusAnnotation()
- || annotation.autoCalculated)
- {
- // new way of indicating autocalculated annotation -
- an.setAutoCalculated(annotation.autoCalculated);
- }
- if (annotation.hasScore())
- {
- an.setScore(annotation.getScore());
- }
-
- if (annotation.getCalcId() != null)
- {
- calcIdSet.add(annotation.getCalcId());
- an.setCalcId(annotation.getCalcId());
- }
- if (annotation.hasProperties())
- {
- for (String pr : annotation.getProperties())
- {
- jalview.xml.binding.jalview.Annotation.Property prop = new jalview.xml.binding.jalview.Annotation.Property();
- prop.setName(pr);
- prop.setValue(annotation.getProperty(pr));
- // an.addProperty(prop);
- an.getProperty().add(prop);
- }
- }
-
- AnnotationElement ae;
- if (annotation.annotations != null)
- {
- an.setScoreOnly(false);
- for (int a = 0; a < annotation.annotations.length; a++)
- {
- if ((annotation == null) || (annotation.annotations[a] == null))
- {
- continue;
- }
-
- ae = new AnnotationElement();
- if (annotation.annotations[a].description != null)
- {
- ae.setDescription(annotation.annotations[a].description);
- }
- if (annotation.annotations[a].displayCharacter != null)
- {
- ae.setDisplayCharacter(
- annotation.annotations[a].displayCharacter);
- }
-
- if (!Float.isNaN(annotation.annotations[a].value))
- {
- ae.setValue(annotation.annotations[a].value);
- }
-
- ae.setPosition(a);
- if (annotation.annotations[a].secondaryStructure > ' ')
- {
- ae.setSecondaryStructure(
- annotation.annotations[a].secondaryStructure + "");
- }
-
- if (annotation.annotations[a].colour != null
- && annotation.annotations[a].colour != java.awt.Color.black)
- {
- ae.setColour(annotation.annotations[a].colour.getRGB());
- }
-
- // an.addAnnotationElement(ae);
- an.getAnnotationElement().add(ae);
- if (annotation.autoCalculated)
- {
- // only write one non-null entry into the annotation row -
- // sufficient to get the visualization attributes necessary to
- // display data
- continue;
- }
- }
- }
- else
- {
- an.setScoreOnly(true);
- }
- if (!storeDS || (storeDS && !annotation.autoCalculated))
- {
- // skip autocalculated annotation - these are only provided for
- // alignments
- // vamsasSet.addAnnotation(an);
- vamsasSet.getAnnotation().add(an);
- }
- }
-
- }
-
- private CalcIdParam createCalcIdParam(String calcId, AlignViewport av)
- {
- AutoCalcSetting settings = av.getCalcIdSettingsFor(calcId);
- if (settings != null)
- {
- CalcIdParam vCalcIdParam = new CalcIdParam();
- vCalcIdParam.setCalcId(calcId);
- // vCalcIdParam.addServiceURL(settings.getServiceURI());
- vCalcIdParam.getServiceURL().add(settings.getServiceURI());
- // generic URI allowing a third party to resolve another instance of the
- // service used for this calculation
- for (String url : settings.getServiceURLs())
- {
- // vCalcIdParam.addServiceURL(urls);
- vCalcIdParam.getServiceURL().add(url);
- }
- vCalcIdParam.setVersion("1.0");
- if (settings.getPreset() != null)
- {
- WsParamSetI setting = settings.getPreset();
- vCalcIdParam.setName(setting.getName());
- vCalcIdParam.setDescription(setting.getDescription());
- }
- else
- {
- vCalcIdParam.setName("");
- vCalcIdParam.setDescription("Last used parameters");
- }
- // need to be able to recover 1) settings 2) user-defined presets or
- // recreate settings from preset 3) predefined settings provided by
- // service - or settings that can be transferred (or discarded)
- vCalcIdParam.setParameters(
- settings.getWsParamFile().replace("\n", "|\\n|"));
- vCalcIdParam.setAutoUpdate(settings.isAutoUpdate());
- // todo - decide if updateImmediately is needed for any projects.
-
- return vCalcIdParam;
- }
- return null;
- }
-
- private boolean recoverCalcIdParam(CalcIdParam calcIdParam,
- AlignViewport av)
- {
- if (calcIdParam.getVersion().equals("1.0"))
- {
- final String[] calcIds = calcIdParam.getServiceURL().toArray(new String[0]);
- ServiceWithParameters service = PreferredServiceRegistry.getRegistry()
- .getPreferredServiceFor(calcIds);
- if (service != null)
- {
- WsParamSetI parmSet = null;
- try
- {
- parmSet = service.getParamStore().parseServiceParameterFile(
- calcIdParam.getName(), calcIdParam.getDescription(),
- calcIds,
- calcIdParam.getParameters().replace("|\\n|", "\n"));
- } catch (IOException x)
- {
- warn("Couldn't parse parameter data for "
- + calcIdParam.getCalcId(), x);
- return false;
- }
- List<ArgumentI> argList = null;
- if (calcIdParam.getName().length() > 0)
- {
- parmSet = service.getParamStore()
- .getPreset(calcIdParam.getName());
- if (parmSet != null)
- {
- // TODO : check we have a good match with settings in AACon -
- // otherwise we'll need to create a new preset
- }
- }
- else
- {
- argList = parmSet.getArguments();
- parmSet = null;
- }
- AutoCalcSetting settings = new AAConSettings(
- calcIdParam.isAutoUpdate(), service, parmSet, argList);
- av.setCalcIdSettingsFor(calcIdParam.getCalcId(), settings,
- calcIdParam.isNeedsUpdate());
- return true;
- }
- else
- {
- warn("Cannot resolve a service for the parameters used in this project. Try configuring a server in the Web Services preferences tab.");
- return false;
- }
- }
- throw new Error(MessageManager.formatMessage(
- "error.unsupported_version_calcIdparam", new Object[]
- { calcIdParam.toString() }));
- }
-
- /**
- * External mapping between jalview objects and objects yielding a valid and
- * unique object ID string. This is null for normal Jalview project IO, but
- * non-null when a jalview project is being read or written as part of a
- * vamsas session.
- */
- IdentityHashMap jv2vobj = null;
-
- /**
- * Construct a unique ID for jvobj using either existing bindings or if none
- * exist, the result of the hashcode call for the object.
- *
- * @param jvobj
- * jalview data object
- * @return unique ID for referring to jvobj
- */
- private String makeHashCode(Object jvobj, String altCode)
- {
- if (jv2vobj != null)
- {
- Object id = jv2vobj.get(jvobj);
- if (id != null)
- {
- return id.toString();
- }
- // check string ID mappings
- if (jvids2vobj != null && jvobj instanceof String)
- {
- id = jvids2vobj.get(jvobj);
- }
- if (id != null)
- {
- return id.toString();
- }
- // give up and warn that something has gone wrong
- warn("Cannot find ID for object in external mapping : " + jvobj);
- }
- return altCode;
- }
-
- /**
- * return local jalview object mapped to ID, if it exists
- *
- * @param idcode
- * (may be null)
- * @return null or object bound to idcode
- */
- private Object retrieveExistingObj(String idcode)
- {
- if (idcode != null && vobj2jv != null)
- {
- return vobj2jv.get(idcode);
- }
- return null;
- }
-
- /**
- * binding from ID strings from external mapping table to jalview data model
- * objects.
- */
- private Hashtable vobj2jv;
-
- private Sequence createVamsasSequence(String id, SequenceI jds)
- {
- return createVamsasSequence(true, id, jds, null);
- }
-
- private Sequence createVamsasSequence(boolean recurse, String id,
- SequenceI jds, SequenceI parentseq)
- {
- Sequence vamsasSeq = new Sequence();
- vamsasSeq.setId(id);
- vamsasSeq.setName(jds.getName());
- vamsasSeq.setSequence(jds.getSequenceAsString());
- vamsasSeq.setDescription(jds.getDescription());
- List<DBRefEntry> dbrefs = null;
- if (jds.getDatasetSequence() != null)
- {
- vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
- }
- else
- {
- // seqId==dsseqid so we can tell which sequences really are
- // dataset sequences only
- vamsasSeq.setDsseqid(id);
- dbrefs = jds.getDBRefs();
- if (parentseq == null)
- {
- parentseq = jds;
- }
- }
-
- /*
- * save any dbrefs; special subclass GeneLocus is flagged as 'locus'
- */
- if (dbrefs != null)
- {
- for (int d = 0, nd = dbrefs.size(); d < nd; d++)
- {
- DBRef dbref = new DBRef();
- DBRefEntry ref = dbrefs.get(d);
- dbref.setSource(ref.getSource());
- dbref.setVersion(ref.getVersion());
- dbref.setAccessionId(ref.getAccessionId());
- dbref.setCanonical(ref.isCanonical());
- if (ref instanceof GeneLocus)
- {
- dbref.setLocus(true);
- }
- if (ref.hasMap())
- {
- Mapping mp = createVamsasMapping(ref.getMap(), parentseq,
- jds, recurse);
- dbref.setMapping(mp);
- }
- vamsasSeq.getDBRef().add(dbref);
- }
- }
- return vamsasSeq;
- }
-
- private Mapping createVamsasMapping(jalview.datamodel.Mapping jmp,
- SequenceI parentseq, SequenceI jds, boolean recurse)
- {
- Mapping mp = null;
- if (jmp.getMap() != null)
- {
- mp = new Mapping();
-
- jalview.util.MapList mlst = jmp.getMap();
- List<int[]> r = mlst.getFromRanges();
- for (int[] range : r)
- {
- MapListFrom mfrom = new MapListFrom();
- mfrom.setStart(range[0]);
- mfrom.setEnd(range[1]);
- // mp.addMapListFrom(mfrom);
- mp.getMapListFrom().add(mfrom);
- }
- r = mlst.getToRanges();
- for (int[] range : r)
- {
- MapListTo mto = new MapListTo();
- mto.setStart(range[0]);
- mto.setEnd(range[1]);
- // mp.addMapListTo(mto);
- mp.getMapListTo().add(mto);
- }
- mp.setMapFromUnit(BigInteger.valueOf(mlst.getFromRatio()));
- mp.setMapToUnit(BigInteger.valueOf(mlst.getToRatio()));
- if (jmp.getTo() != null)
- {
- // MappingChoice mpc = new MappingChoice();
-
- // check/create ID for the sequence referenced by getTo()
-
- String jmpid = "";
- SequenceI ps = null;
- if (parentseq != jmp.getTo()
- && parentseq.getDatasetSequence() != jmp.getTo())
- {
- // chaining dbref rather than a handshaking one
- jmpid = seqHash(ps = jmp.getTo());
- }
- else
- {
- jmpid = seqHash(ps = parentseq);
- }
- // mpc.setDseqFor(jmpid);
- mp.setDseqFor(jmpid);
- if (!seqRefIds.containsKey(jmpid))
- {
- jalview.bin.Cache.log.debug("creatign new DseqFor ID");
- seqRefIds.put(jmpid, ps);
- }
- else
- {
- jalview.bin.Cache.log.debug("reusing DseqFor ID");
- }
-
- // mp.setMappingChoice(mpc);
- }
- }
- return mp;
- }
-
- String setUserColourScheme(jalview.schemes.ColourSchemeI cs,
- List<UserColourScheme> userColours, JalviewModel jm)
- {
- String id = null;
- jalview.schemes.UserColourScheme ucs = (jalview.schemes.UserColourScheme) cs;
- boolean newucs = false;
- if (!userColours.contains(ucs))
- {
- userColours.add(ucs);
- newucs = true;
- }
- id = "ucs" + userColours.indexOf(ucs);
- if (newucs)
- {
- // actually create the scheme's entry in the XML model
- java.awt.Color[] colours = ucs.getColours();
- UserColours uc = new UserColours();
- // UserColourScheme jbucs = new UserColourScheme();
- JalviewUserColours jbucs = new JalviewUserColours();
-
- for (int i = 0; i < colours.length; i++)
- {
- Colour col = new Colour();
- col.setName(ResidueProperties.aa[i]);
- col.setRGB(jalview.util.Format.getHexString(colours[i]));
- // jbucs.addColour(col);
- jbucs.getColour().add(col);
- }
- if (ucs.getLowerCaseColours() != null)
- {
- colours = ucs.getLowerCaseColours();
- for (int i = 0; i < colours.length; i++)
- {
- Colour col = new Colour();
- col.setName(ResidueProperties.aa[i].toLowerCase(Locale.ROOT));
- col.setRGB(jalview.util.Format.getHexString(colours[i]));
- // jbucs.addColour(col);
- jbucs.getColour().add(col);
- }
- }
-
- uc.setId(id);
- uc.setUserColourScheme(jbucs);
- // jm.addUserColours(uc);
- jm.getUserColours().add(uc);
- }
-
- return id;
- }
-
- jalview.schemes.UserColourScheme getUserColourScheme(JalviewModel jm,
- String id)
- {
- List<UserColours> uc = jm.getUserColours();
- UserColours colours = null;
- /*
- for (int i = 0; i < uc.length; i++)
- {
- if (uc[i].getId().equals(id))
- {
- colours = uc[i];
- break;
- }
- }
- */
- for (UserColours c : uc)
- {
- if (c.getId().equals(id))
- {
- colours = c;
- break;
- }
- }
-
- java.awt.Color[] newColours = new java.awt.Color[24];
-
- for (int i = 0; i < 24; i++)
- {
- newColours[i] = new java.awt.Color(Integer.parseInt(
- // colours.getUserColourScheme().getColour(i).getRGB(), 16));
- colours.getUserColourScheme().getColour().get(i).getRGB(),
- 16));
- }
-
- jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
- newColours);
-
- if (colours.getUserColourScheme().getColour().size()/*Count()*/ > 24)
- {
- newColours = new java.awt.Color[23];
- for (int i = 0; i < 23; i++)
- {
- newColours[i] = new java.awt.Color(
- Integer.parseInt(colours.getUserColourScheme().getColour()
- .get(i + 24).getRGB(), 16));
- }
- ucs.setLowerCaseColours(newColours);
- }
-
- return ucs;
- }
- /**
- * contains last error message (if any) encountered by XML loader.
- */
- String errorMessage = null;
-
- /**
- * flag to control whether the Jalview2XML_V1 parser should be deferred to if
- * exceptions are raised during project XML parsing
- */
- public boolean attemptversion1parse = false;
-
- /**
- * Load a jalview project archive from a jar file
- *
- * @param file
- * - HTTP URL or filename
- */
- public AlignFrame loadJalviewAlign(final Object file)
- {
-
- jalview.gui.AlignFrame af = null;
-
- try
- {
- // create list to store references for any new Jmol viewers created
- newStructureViewers = new Vector<>();
- // UNMARSHALLER SEEMS TO CLOSE JARINPUTSTREAM, MOST ANNOYING
- // Workaround is to make sure caller implements the JarInputStreamProvider
- // interface
- // so we can re-open the jar input stream for each entry.
-
- jarInputStreamProvider jprovider = createjarInputStreamProvider(file);
- af = loadJalviewAlign(jprovider);
- if (af != null)
- {
- af.setMenusForViewport();
- }
- } catch (MalformedURLException e)
- {
- errorMessage = "Invalid URL format for '" + file + "'";
- reportErrors();
- } finally
- {
- try
- {
- // was invokeAndWait
-
- // BH 2019 -- can't wait
- SwingUtilities.invokeLater(new Runnable()
- {
- @Override
- public void run()
- {
- setLoadingFinishedForNewStructureViewers();
- }
- });
- } catch (Exception x)
- {
- System.err.println("Error loading alignment: " + x.getMessage());
- }
- }
- this.jarFile = null;
- return af;
- }
-
- @SuppressWarnings("unused")
- private jarInputStreamProvider createjarInputStreamProvider(
- final Object ofile) throws MalformedURLException
- {
- try
- {
- String file = (ofile instanceof File
- ? ((File) ofile).getCanonicalPath()
- : ofile.toString());
- byte[] bytes = Platform.isJS() ? Platform.getFileBytes((File) ofile)
- : null;
- if (bytes != null)
- {
- this.jarFile = (File) ofile;
- }
- URL url = null;
- errorMessage = null;
- uniqueSetSuffix = null;
- seqRefIds = null;
- viewportsAdded.clear();
- frefedSequence = null;
-
- if (HttpUtils.startsWithHttpOrHttps(file))
- {
- url = new URL(file);
- }
- return new jarInputStreamProvider()
- {
- @Override
- public JarInputStream getJarInputStream() throws IOException
- {
- InputStream is = bytes != null ? new ByteArrayInputStream(bytes)
- : (url != null ? url.openStream()
- : new FileInputStream(file));
- return new JarInputStream(is);
- }
-
- @Override
- public File getFile()
- {
- return jarFile;
- }
-
- @Override
- public String getFilename()
- {
- return file;
- }
- };
- } catch (IOException e)
- {
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * Recover jalview session from a jalview project archive. Caller may
- * initialise uniqueSetSuffix, seqRefIds, viewportsAdded and frefedSequence
- * themselves. Any null fields will be initialised with default values,
- * non-null fields are left alone.
- *
- * @param jprovider
- * @return
- */
- public AlignFrame loadJalviewAlign(final jarInputStreamProvider jprovider)
- {
- errorMessage = null;
- if (uniqueSetSuffix == null)
- {
- uniqueSetSuffix = System.currentTimeMillis() % 100000 + "";
- }
- if (seqRefIds == null)
- {
- initSeqRefs();
- }
- AlignFrame af = null, _af = null;
- IdentityHashMap<AlignmentI, AlignmentI> importedDatasets = new IdentityHashMap<>();
- Map<String, AlignFrame> gatherToThisFrame = new HashMap<>();
- String fileName = jprovider.getFilename();
- File file = jprovider.getFile();
- List<AlignFrame> alignFrames = new ArrayList<>();
- try
- {
- JarInputStream jin = null;
- JarEntry jarentry = null;
- int entryCount = 1;
-
- // Look for all the entry names ending with ".xml"
- // This includes all panels and at least one frame.
- // Platform.timeCheck(null, Platform.TIME_MARK);
- do
- {
- jin = jprovider.getJarInputStream();
- for (int i = 0; i < entryCount; i++)
- {
- jarentry = jin.getNextJarEntry();
- }
- String name = (jarentry == null ? null : jarentry.getName());
-
- // System.out.println("Jalview2XML opening " + name);
- if (name != null && name.endsWith(".xml"))
- {
- // DataSet for.... is read last.
-
-
- // The question here is what to do with the two
- // .xml files in the jvp file.
- // Some number of them, "...Dataset for...", will be the
- // Only AlignPanels and will have Viewport.
- // One or more will be the source data, with the DBRefs.
- //
- // JVP file writing (above) ensures tha the AlignPanels are written
- // first, then all relevant datasets (which are
- // Jalview.datamodel.Alignment).
- //
-
- // Platform.timeCheck("Jalview2XML JAXB " + name, Platform.TIME_MARK);
- JAXBContext jc = JAXBContext
- .newInstance("jalview.xml.binding.jalview");
- XMLStreamReader streamReader = XMLInputFactory.newInstance()
- .createXMLStreamReader(jin);
- javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
- JAXBElement<JalviewModel> jbe = um
- .unmarshal(streamReader, JalviewModel.class);
- JalviewModel model = jbe.getValue();
-
- if (true) // !skipViewport(object))
- {
- // Q: Do we have to load from the model, even if it
- // does not have a viewport, could we discover that early on?
- // Q: Do we need to load this object?
- _af = loadFromObject(model, fileName, file, true, jprovider);
- // Platform.timeCheck("Jalview2XML.loadFromObject",
- // Platform.TIME_MARK);
-
- if (_af != null)
- {
- alignFrames.add(_af);
- }
- if (_af != null && model.getViewport().size() > 0)
- {
-
- // That is, this is one of the AlignmentPanel models
- if (af == null)
- {
- // store a reference to the first view
- af = _af;
- }
- if (_af.getViewport().isGatherViewsHere())
- {
- // if this is a gathered view, keep its reference since
- // after gathering views, only this frame will remain
- af = _af;
- gatherToThisFrame.put(_af.getViewport().getSequenceSetId(),
- _af);
- }
- // Save dataset to register mappings once all resolved
- importedDatasets.put(
- af.getViewport().getAlignment().getDataset(),
- af.getViewport().getAlignment().getDataset());
- }
- }
- entryCount++;
- }
- else if (jarentry != null)
- {
- // Some other file here.
- entryCount++;
- }
- } while (jarentry != null);
- resolveFrefedSequences();
- } catch (IOException ex)
- {
- ex.printStackTrace();
- errorMessage = "Couldn't locate Jalview XML file : " + fileName;
- System.err.println(
- "Exception whilst loading jalview XML file : " + ex + "\n");
- } catch (Exception ex)
- {
- System.err.println("Parsing as Jalview Version 2 file failed.");
- ex.printStackTrace(System.err);
- if (attemptversion1parse)
- {
- // used to attempt to parse as V1 castor-generated xml
- }
- if (Desktop.getInstance() != null)
- {
- Desktop.getInstance().stopLoading();
- }
- if (af != null)
- {
- System.out.println("Successfully loaded archive file");
- return af;
- }
- ex.printStackTrace();
-
- System.err.println(
- "Exception whilst loading jalview XML file : " + ex + "\n");
- } catch (OutOfMemoryError e)
- {
- // Don't use the OOM Window here
- errorMessage = "Out of memory loading jalview XML file";
- System.err.println("Out of memory whilst loading jalview XML file");
- e.printStackTrace();
- } finally
- {
- for (AlignFrame alf : alignFrames)
- {
- alf.alignPanel.setHoldRepaint(false);
- }
- }
-
- /*
- * Regather multiple views (with the same sequence set id) to the frame (if
- * any) that is flagged as the one to gather to, i.e. convert them to tabbed
- * views instead of separate frames. Note this doesn't restore a state where
- * some expanded views in turn have tabbed views - the last "first tab" read
- * in will play the role of gatherer for all.
- */
- for (AlignFrame fr : gatherToThisFrame.values())
- {
- Desktop.getInstance().gatherViews(fr);
- }
-
- restoreSplitFrames();
- for (AlignmentI ds : importedDatasets.keySet())
- {
- if (ds.getCodonFrames() != null)
- {
- Desktop.getStructureSelectionManager()
- .registerMappings(ds.getCodonFrames());
- }
- }
- if (errorMessage != null)
- {
- reportErrors();
- }
-
- if (Desktop.getInstance() != null)
- {
- Desktop.getInstance().stopLoading();
- }
-
- return af;
- }
-
- /**
- * Try to reconstruct and display SplitFrame windows, where each contains
- * complementary dna and protein alignments. Done by pairing up AlignFrame
- * objects (created earlier) which have complementary viewport ids associated.
- */
- protected void restoreSplitFrames()
- {
- List<SplitFrame> gatherTo = new ArrayList<>();
- List<AlignFrame> addedToSplitFrames = new ArrayList<>();
- Map<String, AlignFrame> dna = new HashMap<>();
-
- /*
- * Identify the DNA alignments
- */
- for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
- .entrySet())
- {
- AlignFrame af = candidate.getValue();
- if (af.getViewport().getAlignment().isNucleotide())
- {
- dna.put(candidate.getKey().getId(), af);
- }
- }
-
- /*
- * Try to match up the protein complements
- */
- for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
- .entrySet())
- {
- AlignFrame af = candidate.getValue();
- if (!af.getViewport().getAlignment().isNucleotide())
- {
- String complementId = candidate.getKey().getComplementId();
- // only non-null complements should be in the Map
- if (complementId != null && dna.containsKey(complementId))
- {
- final AlignFrame dnaFrame = dna.get(complementId);
- SplitFrame sf = createSplitFrame(dnaFrame, af);
- addedToSplitFrames.add(dnaFrame);
- addedToSplitFrames.add(af);
- dnaFrame.setMenusForViewport();
- af.setMenusForViewport();
- if (af.getViewport().isGatherViewsHere())
- {
- gatherTo.add(sf);
- }
- }
- }
- }
-
- /*
- * Open any that we failed to pair up (which shouldn't happen!) as
- * standalone AlignFrame's.
- */
- for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
- .entrySet())
- {
- AlignFrame af = candidate.getValue();
- if (!addedToSplitFrames.contains(af))
- {
- Viewport view = candidate.getKey();
- Desktop.addInternalFrame(af, view.getTitle(),
- safeInt(view.getWidth()), safeInt(view.getHeight()));
- af.setMenusForViewport();
- System.err.println("Failed to restore view " + view.getTitle()
- + " to split frame");
- }
- }
-
- /*
- * Gather back into tabbed views as flagged.
- */
- for (SplitFrame sf : gatherTo)
- {
- Desktop.getInstance().gatherViews(sf);
- }
-
- splitFrameCandidates.clear();
- }
-
- /**
- * Construct and display one SplitFrame holding DNA and protein alignments.
- *
- * @param dnaFrame
- * @param proteinFrame
- * @return
- */
- protected SplitFrame createSplitFrame(AlignFrame dnaFrame,
- AlignFrame proteinFrame)
- {
- SplitFrame splitFrame = new SplitFrame(dnaFrame, proteinFrame);
- String title = MessageManager.getString("label.linked_view_title");
- int width = (int) dnaFrame.getBounds().getWidth();
- int height = (int) (dnaFrame.getBounds().getHeight()
- + proteinFrame.getBounds().getHeight() + 50);
-
- /*
- * SplitFrame location is saved to both enclosed frames
- */
- splitFrame.setLocation(dnaFrame.getX(), dnaFrame.getY());
- Desktop.addInternalFrame(splitFrame, title, width, height);
-
- /*
- * And compute cDNA consensus (couldn't do earlier with consensus as
- * mappings were not yet present)
- */
- proteinFrame.getViewport().alignmentChanged(proteinFrame.alignPanel);
-
- return splitFrame;
- }
-
- /**
- * check errorMessage for a valid error message and raise an error box in the
- * GUI or write the current errorMessage to stderr and then clear the error
- * state.
- */
- protected void reportErrors()
- {
- reportErrors(false);
- }
-
- protected void reportErrors(final boolean saving)
- {
- if (errorMessage != null)
- {
- final String finalErrorMessage = errorMessage;
- if (raiseGUI)
- {
- javax.swing.SwingUtilities.invokeLater(new Runnable()
- {
- @Override
- public void run()
- {
- JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
- finalErrorMessage,
- "Error " + (saving ? "saving" : "loading")
- + " Jalview file",
- JvOptionPane.WARNING_MESSAGE);
- }
- });
- }
- else
- {
- System.err.println("Problem loading Jalview file: " + errorMessage);
- }
- }
- errorMessage = null;
- }
-
- Map<String, String> alreadyLoadedPDB = new HashMap<>();
-
- /**
- * when set, local views will be updated from view stored in JalviewXML
- * Currently (28th Sep 2008) things will go horribly wrong in vamsas document
- * sync if this is set to true.
- */
- private final boolean updateLocalViews = false;
-
- /**
- * Returns the path to a temporary file holding the PDB file for the given PDB
- * id. The first time of asking, searches for a file of that name in the
- * Jalview project jar, and copies it to a new temporary file. Any repeat
- * requests just return the path to the file previously created.
- *
- * @param jprovider
- * @param pdbId
- * @return
- */
- String loadPDBFile(jarInputStreamProvider jprovider, String pdbId,
- String origFile)
- {
- if (alreadyLoadedPDB.containsKey(pdbId))
- {
- return alreadyLoadedPDB.get(pdbId).toString();
- }
-
- String tempFile = copyJarEntry(jprovider, pdbId, "jalview_pdb",
- origFile);
- if (tempFile != null)
- {
- alreadyLoadedPDB.put(pdbId, tempFile);
- }
- return tempFile;
- }
-
- /**
- * Copies the jar entry of given name to a new temporary file and returns the
- * path to the file, or null if the entry is not found.
- *
- * @param jprovider
- * @param jarEntryName
- * @param prefix
- * a prefix for the temporary file name, must be at least three
- * characters long
- * @param origFile
- * null or original file - so new file can be given the same suffix
- * as the old one
- * @return
- */
- protected String copyJarEntry(jarInputStreamProvider jprovider,
- String jarEntryName, String prefix, String origFile)
- {
- BufferedReader in = null;
- PrintWriter out = null;
- String suffix = ".tmp";
- if (origFile == null)
- {
- origFile = jarEntryName;
- }
- int sfpos = origFile.lastIndexOf(".");
- if (sfpos > -1 && sfpos < (origFile.length() - 3))
- {
- suffix = "." + origFile.substring(sfpos + 1);
- }
- try (JarInputStream jin = jprovider.getJarInputStream())
- {
-
- JarEntry entry = null;
- do
- {
- entry = jin.getNextJarEntry();
- } while (entry != null && !entry.getName().equals(jarEntryName));
- if (entry != null)
- {
- // in = new BufferedReader(new InputStreamReader(jin, UTF_8));
- File outFile = File.createTempFile(prefix, suffix);
- outFile.deleteOnExit();
- try (OutputStream os = new FileOutputStream(outFile))
- {
- copyAll(jin, os);
- }
- String t = outFile.getAbsolutePath();
- return t;
- }
- else
- {
- warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
- }
- } catch (Exception ex)
- {
- ex.printStackTrace();
- }
-
- return null;
- }
-
- private class JvAnnotRow
- {
- public JvAnnotRow(int i, AlignmentAnnotation jaa)
- {
- order = i;
- template = jaa;
- }
-
- /**
- * persisted version of annotation row from which to take vis properties
- */
- public jalview.datamodel.AlignmentAnnotation template;
-
- /**
- * original position of the annotation row in the alignment
- */
- public int order;
- }
-
- /**
- * Load alignment frame from jalview XML DOM object. For a DOM object that
- * includes one or more Viewport elements (one with a title that does NOT
- * contain "Dataset for"), create the frame.
- *
- * @param jalviewModel
- * DOM
- * @param fileName
- * filename source string
- * @param file
- * @param loadTreesAndStructures
- * when false only create Viewport
- * @param jprovider
- * data source provider
- * @return alignment frame created from view stored in DOM
- */
- AlignFrame loadFromObject(JalviewModel jalviewModel, String fileName,
- File file, boolean loadTreesAndStructures, jarInputStreamProvider jprovider)
- {
- SequenceSet vamsasSet = jalviewModel.getVamsasModel().getSequenceSet().get(0);
- List<Sequence> vamsasSeqs = vamsasSet.getSequence();
-
- // JalviewModelSequence jms = object.getJalviewModelSequence();
-
- // Viewport view = (jms.getViewportCount() > 0) ? jms.getViewport(0)
- // : null;
- Viewport view = (jalviewModel.getViewport().size() > 0)
- ? jalviewModel.getViewport().get(0)
- : null;
-
- // ////////////////////////////////
- // INITIALISE ALIGNMENT SEQUENCESETID AND VIEWID
- //
- //
- // If we just load in the same jar file again, the sequenceSetId
- // will be the same, and we end up with multiple references
- // to the same sequenceSet. We must modify this id on load
- // so that each load of the file gives a unique id
-
- /**
- * used to resolve correct alignment dataset for alignments with multiple
- * views
- */
- String uniqueSeqSetId = null;
- String viewId = null;
- if (view != null)
- {
- uniqueSeqSetId = view.getSequenceSetId() + uniqueSetSuffix;
- viewId = (view.getId() == null ? null
- : view.getId() + uniqueSetSuffix);
- }
-
- // ////////////////////////////////
- // LOAD SEQUENCES
-
- List<SequenceI> hiddenSeqs = null;
-
- List<SequenceI> tmpseqs = new ArrayList<>();
-
- boolean multipleView = false;
- SequenceI referenceseqForView = null;
- // JSeq[] jseqs = object.getJalviewModelSequence().getJSeq();
- List<JSeq> jseqs = jalviewModel.getJSeq();
- int vi = 0; // counter in vamsasSeq array
- for (int i = 0; i < jseqs.size(); i++)
- {
- JSeq jseq = jseqs.get(i);
- String seqId = jseq.getId();
-
- SequenceI tmpSeq = seqRefIds.get(seqId);
- if (tmpSeq != null)
- {
- if (!incompleteSeqs.containsKey(seqId))
- {
- // may not need this check, but keep it for at least 2.9,1 release
- if (tmpSeq.getStart() != jseq.getStart()
- || tmpSeq.getEnd() != jseq.getEnd())
- {
- System.err.println(
- String.format("Warning JAL-2154 regression: updating start/end for sequence %s from %d/%d to %d/%d",
- tmpSeq.getName(), tmpSeq.getStart(),
- tmpSeq.getEnd(), jseq.getStart(),
- jseq.getEnd()));
- }
- }
- else
- {
- incompleteSeqs.remove(seqId);
- }
- if (vamsasSeqs.size() > vi
- && vamsasSeqs.get(vi).getId().equals(seqId))
- {
- // most likely we are reading a dataset XML document so
- // update from vamsasSeq section of XML for this sequence
- tmpSeq.setName(vamsasSeqs.get(vi).getName());
- tmpSeq.setDescription(vamsasSeqs.get(vi).getDescription());
- tmpSeq.setSequence(vamsasSeqs.get(vi).getSequence());
- vi++;
- }
- else
- {
- // reading multiple views, so vamsasSeq set is a subset of JSeq
- multipleView = true;
- }
- tmpSeq.setStart(jseq.getStart());
- tmpSeq.setEnd(jseq.getEnd());
- tmpseqs.add(tmpSeq);
- }
- else
- {
- Sequence vamsasSeq = vamsasSeqs.get(vi);
- tmpSeq = new jalview.datamodel.Sequence(vamsasSeq.getName(),
- vamsasSeq.getSequence());
- tmpSeq.setDescription(vamsasSeq.getDescription());
- tmpSeq.setStart(jseq.getStart());
- tmpSeq.setEnd(jseq.getEnd());
- tmpSeq.setVamsasId(uniqueSetSuffix + seqId);
- seqRefIds.put(vamsasSeq.getId(), tmpSeq);
- tmpseqs.add(tmpSeq);
- vi++;
- }
-
- if (safeBoolean(jseq.isViewreference()))
- {
- referenceseqForView = tmpseqs.get(tmpseqs.size() - 1);
- }
-
- if (jseq.isHidden() != null && jseq.isHidden().booleanValue())
- {
- if (hiddenSeqs == null)
- {
- hiddenSeqs = new ArrayList<>();
- }
-
- hiddenSeqs.add(tmpSeq);
- }
- }
-
- // /
- // Create the alignment object from the sequence set
- // ///////////////////////////////
- SequenceI[] orderedSeqs = tmpseqs
- .toArray(new SequenceI[tmpseqs.size()]);
-
- AlignmentI al = null;
- // so we must create or recover the dataset alignment before going further
- // ///////////////////////////////
- if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
- {
- // older jalview projects do not have a dataset - so creat alignment and
- // dataset
- al = new Alignment(orderedSeqs);
- al.setDataset(null);
- }
- else
- {
- boolean isdsal = jalviewModel.getViewport().isEmpty();
- if (isdsal)
- {
- // we are importing a dataset record, so
- // recover reference to an alignment already materialsed as dataset
- al = getDatasetFor(vamsasSet.getDatasetId());
- }
- if (al == null)
- {
- // materialse the alignment
- al = new Alignment(orderedSeqs);
- }
- if (isdsal)
- {
- addDatasetRef(vamsasSet.getDatasetId(), al);
- }
-
- // finally, verify all data in vamsasSet is actually present in al
- // passing on flag indicating if it is actually a stored dataset
- recoverDatasetFor(vamsasSet, al, isdsal, uniqueSeqSetId);
- }
-
- if (referenceseqForView != null)
- {
- al.setSeqrep(referenceseqForView);
- }
- // / Add the alignment properties
- for (int i = 0; i < vamsasSet.getSequenceSetProperties().size(); i++)
- {
- SequenceSetProperties ssp = vamsasSet.getSequenceSetProperties()
- .get(i);
- al.setProperty(ssp.getKey(), ssp.getValue());
- }
-
- // ///////////////////////////////
-
- Hashtable pdbloaded = new Hashtable(); // TODO nothing writes to this??
- if (!multipleView)
- {
- // load sequence features, database references and any associated PDB
- // structures for the alignment
- //
- // prior to 2.10, this part would only be executed the first time a
- // sequence was encountered, but not afterwards.
- // now, for 2.10 projects, this is also done if the xml doc includes
- // dataset sequences not actually present in any particular view.
- //
- for (int i = 0; i < vamsasSeqs.size(); i++)
- {
- JSeq jseq = jseqs.get(i);
- if (jseq.getFeatures().size() > 0)
- {
- List<Feature> features = jseq.getFeatures();
- for (int f = 0; f < features.size(); f++)
- {
- Feature feat = features.get(f);
- SequenceFeature sf = new SequenceFeature(feat.getType(),
- feat.getDescription(), feat.getBegin(), feat.getEnd(),
- safeFloat(feat.getScore()), feat.getFeatureGroup());
- sf.setStatus(feat.getStatus());
-
- /*
- * load any feature attributes - include map-valued attributes
- */
- Map<String, Map<String, String>> mapAttributes = new HashMap<>();
- for (int od = 0; od < feat.getOtherData().size(); od++)
- {
- OtherData keyValue = feat.getOtherData().get(od);
- String attributeName = keyValue.getKey();
- String attributeValue = keyValue.getValue();
- if (attributeName.startsWith("LINK"))
- {
- sf.addLink(attributeValue);
- }
- else
- {
- String subAttribute = keyValue.getKey2();
- if (subAttribute == null)
- {
- // simple string-valued attribute
- sf.setValue(attributeName, attributeValue);
- }
- else
- {
- // attribute 'key' has sub-attribute 'key2'
- if (!mapAttributes.containsKey(attributeName))
- {
- mapAttributes.put(attributeName, new HashMap<>());
- }
- mapAttributes.get(attributeName).put(subAttribute,
- attributeValue);
- }
- }
- }
- for (Entry<String, Map<String, String>> mapAttribute : mapAttributes
- .entrySet())
- {
- sf.setValue(mapAttribute.getKey(), mapAttribute.getValue());
- }
-
- // adds feature to datasequence's feature set (since Jalview 2.10)
- al.getSequenceAt(i).addSequenceFeature(sf);
- }
- }
- if (vamsasSeqs.get(i).getDBRef().size() > 0)
- {
- // adds dbrefs to datasequence's set (since Jalview 2.10)
- addDBRefs(
- al.getSequenceAt(i).getDatasetSequence() == null
- ? al.getSequenceAt(i)
- : al.getSequenceAt(i).getDatasetSequence(),
- vamsasSeqs.get(i));
- }
- if (jseq.getPdbids().size() > 0)
- {
- List<Pdbids> ids = jseq.getPdbids();
- for (int p = 0; p < ids.size(); p++)
- {
- Pdbids pdbid = ids.get(p);
- jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
- entry.setId(pdbid.getId());
- if (pdbid.getType() != null)
- {
- if (PDBEntry.Type.getType(pdbid.getType()) != null)
- {
- entry.setType(PDBEntry.Type.getType(pdbid.getType()));
- }
- else
- {
- entry.setType(PDBEntry.Type.FILE);
- }
- }
- // jprovider is null when executing 'New View'
- if (pdbid.getFile() != null && jprovider != null)
- {
- if (!pdbloaded.containsKey(pdbid.getFile()))
- {
- entry.setFile(loadPDBFile(jprovider, pdbid.getId(),
- pdbid.getFile()));
- }
- else
- {
- entry.setFile(pdbloaded.get(pdbid.getId()).toString());
- }
- }
- /*
- if (pdbid.getPdbentryItem() != null)
- {
- for (PdbentryItem item : pdbid.getPdbentryItem())
- {
- for (Property pr : item.getProperty())
- {
- entry.setProperty(pr.getName(), pr.getValue());
- }
- }
- }
- */
- for (Property prop : pdbid.getProperty())
- {
- entry.setProperty(prop.getName(), prop.getValue());
- }
- Desktop.getStructureSelectionManager()
- .registerPDBEntry(entry);
- // adds PDBEntry to datasequence's set (since Jalview 2.10)
- if (al.getSequenceAt(i).getDatasetSequence() != null)
- {
- al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
- }
- else
- {
- al.getSequenceAt(i).addPDBId(entry);
- }
- }
- }
- /*
- * load any HMMER profile
- */
- // TODO fix this
-
- String hmmJarFile = jseqs.get(i).getHmmerProfile();
- if (hmmJarFile != null && jprovider != null)
- {
- loadHmmerProfile(jprovider, hmmJarFile, al.getSequenceAt(i));
- }
- }
- } // end !multipleview
-
- // ///////////////////////////////
- // LOAD SEQUENCE MAPPINGS
-
- if (vamsasSet.getAlcodonFrame().size() > 0)
- {
- // TODO Potentially this should only be done once for all views of an
- // alignment
- List<AlcodonFrame> alc = vamsasSet.getAlcodonFrame();
- for (int i = 0; i < alc.size(); i++)
- {
- AlignedCodonFrame cf = new AlignedCodonFrame();
- if (alc.get(i).getAlcodMap().size() > 0)
- {
- List<AlcodMap> maps = alc.get(i).getAlcodMap();
- for (int m = 0; m < maps.size(); m++)
- {
- AlcodMap map = maps.get(m);
- SequenceI dnaseq = seqRefIds.get(map.getDnasq());
- // Load Mapping
- jalview.datamodel.Mapping mapping = null;
- // attach to dna sequence reference.
- if (map.getMapping() != null)
- {
- mapping = addMapping(map.getMapping());
- if (dnaseq != null && mapping.getTo() != null)
- {
- cf.addMap(dnaseq, mapping.getTo(), mapping.getMap());
- }
- else
- {
- // defer to later
- frefedSequence.add(
- newAlcodMapRef(map.getDnasq(), cf, mapping));
- }
- }
- }
- al.addCodonFrame(cf);
- }
- }
- }
-
- // ////////////////////////////////
- // LOAD ANNOTATIONS
- List<JvAnnotRow> autoAlan = new ArrayList<>();
-
- /*
- * store any annotations which forward reference a group's ID
- */
- Map<String, List<AlignmentAnnotation>> groupAnnotRefs = new Hashtable<>();
-
- if (vamsasSet.getAnnotation().size()/*Count()*/ > 0)
- {
- List<Annotation> an = vamsasSet.getAnnotation();
-
- for (int i = 0; i < an.size(); i++)
- {
- Annotation annotation = an.get(i);
-
- /**
- * test if annotation is automatically calculated for this view only
- */
- boolean autoForView = false;
- if (annotation.getLabel().equals("Quality")
- || annotation.getLabel().equals("Conservation")
- || annotation.getLabel().equals("Consensus"))
- {
- // Kludge for pre 2.5 projects which lacked the autocalculated flag
- autoForView = true;
- // JAXB has no has() test; schema defaults value to false
- // if (!annotation.hasAutoCalculated())
- // {
- // annotation.setAutoCalculated(true);
- // }
- }
- if (autoForView || annotation.isAutoCalculated())
- {
- // remove ID - we don't recover annotation from other views for
- // view-specific annotation
- annotation.setId(null);
- }
-
- // set visibility for other annotation in this view
- String annotationId = annotation.getId();
- if (annotationId != null && annotationIds.containsKey(annotationId))
- {
- AlignmentAnnotation jda = annotationIds.get(annotationId);
- // in principle Visible should always be true for annotation displayed
- // in multiple views
- if (annotation.isVisible() != null)
- {
- jda.visible = annotation.isVisible();
- }
-
- al.addAnnotation(jda);
-
- continue;
- }
- // Construct new annotation from model.
- List<AnnotationElement> ae = annotation.getAnnotationElement();
- jalview.datamodel.Annotation[] anot = null;
- java.awt.Color firstColour = null;
- int anpos;
- if (!annotation.isScoreOnly())
- {
- anot = new jalview.datamodel.Annotation[al.getWidth()];
- for (int aa = 0; aa < ae.size() && aa < anot.length; aa++)
- {
- AnnotationElement annElement = ae.get(aa);
- anpos = annElement.getPosition();
-
- if (anpos >= anot.length)
- {
- continue;
- }
-
- float value = safeFloat(annElement.getValue());
- anot[anpos] = new jalview.datamodel.Annotation(
- annElement.getDisplayCharacter(),
- annElement.getDescription(),
- (annElement.getSecondaryStructure() == null
- || annElement.getSecondaryStructure()
- .length() == 0)
- ? ' '
- : annElement
- .getSecondaryStructure()
- .charAt(0),
- value);
- anot[anpos].colour = new Color(safeInt(annElement.getColour()));
- if (firstColour == null)
- {
- firstColour = anot[anpos].colour;
- }
- }
- }
- // create the new AlignmentAnnotation
- jalview.datamodel.AlignmentAnnotation jaa = null;
-
- if (annotation.isGraph())
- {
- float llim = 0, hlim = 0;
- // if (autoForView || an[i].isAutoCalculated()) {
- // hlim=11f;
- // }
- jaa = new jalview.datamodel.AlignmentAnnotation(
- annotation.getLabel(), annotation.getDescription(), anot,
- llim, hlim, safeInt(annotation.getGraphType()));
-
- jaa.graphGroup = safeInt(annotation.getGraphGroup());
- jaa._linecolour = firstColour;
- if (annotation.getThresholdLine() != null)
- {
- jaa.setThreshold(new jalview.datamodel.GraphLine(
- safeFloat(annotation.getThresholdLine().getValue()),
- annotation.getThresholdLine().getLabel(),
- new java.awt.Color(safeInt(
- annotation.getThresholdLine().getColour()))));
- }
- if (autoForView || annotation.isAutoCalculated())
- {
- // Hardwire the symbol display line to ensure that labels for
- // histograms are displayed
- jaa.hasText = true;
- }
- }
- else
- {
- jaa = new jalview.datamodel.AlignmentAnnotation(
- annotation.getLabel(), annotation.getDescription(), anot);
- jaa._linecolour = firstColour;
- }
- // register new annotation
- // Annotation graphs such as Conservation will not have id.
- if (annotation.getId() != null)
- {
- annotationIds.put(annotation.getId(), jaa);
- jaa.annotationId = annotation.getId();
- }
- // recover sequence association
- String sequenceRef = annotation.getSequenceRef();
- if (sequenceRef != null)
- {
- // from 2.9 sequenceRef is to sequence id (JAL-1781)
- SequenceI sequence = seqRefIds.get(sequenceRef);
- if (sequence == null)
- {
- // in pre-2.9 projects sequence ref is to sequence name
- sequence = al.findName(sequenceRef);
- }
- if (sequence != null)
- {
- jaa.createSequenceMapping(sequence, 1, true);
- sequence.addAlignmentAnnotation(jaa);
- }
- }
- // and make a note of any group association
- if (annotation.getGroupRef() != null
- && annotation.getGroupRef().length() > 0)
- {
- List<jalview.datamodel.AlignmentAnnotation> aal = groupAnnotRefs
- .get(annotation.getGroupRef());
- if (aal == null)
- {
- aal = new ArrayList<>();
- groupAnnotRefs.put(annotation.getGroupRef(), aal);
- }
- aal.add(jaa);
- }
-
- if (annotation.getScore() != null)
- {
- jaa.setScore(annotation.getScore().doubleValue());
- }
- if (annotation.isVisible() != null)
- {
- jaa.visible = annotation.isVisible().booleanValue();
- }
-
- if (annotation.isCentreColLabels() != null)
- {
- jaa.centreColLabels = annotation.isCentreColLabels()
- .booleanValue();
- }
-
- if (annotation.isScaleColLabels() != null)
- {
- jaa.scaleColLabel = annotation.isScaleColLabels().booleanValue();
- }
- if (annotation.isAutoCalculated())
- {
- // newer files have an 'autoCalculated' flag and store calculation
- // state in viewport properties
- jaa.autoCalculated = true; // means annotation will be marked for
- // update at end of load.
- }
- if (annotation.getGraphHeight() != null)
- {
- jaa.graphHeight = annotation.getGraphHeight().intValue();
- }
- jaa.belowAlignment = annotation.isBelowAlignment();
- jaa.setCalcId(annotation.getCalcId());
- if (annotation.getProperty().size() > 0)
- {
- for (Annotation.Property prop : annotation
- .getProperty())
- {
- jaa.setProperty(prop.getName(), prop.getValue());
- }
- }
- if (jaa.autoCalculated)
- {
- autoAlan.add(new JvAnnotRow(i, jaa));
- }
- else
- // if (!autoForView)
- {
- // add autocalculated group annotation and any user created annotation
- // for the view
- al.addAnnotation(jaa);
- }
- }
- }
- // ///////////////////////
- // LOAD GROUPS
- // Create alignment markup and styles for this view
- if (jalviewModel.getJGroup().size() > 0)
- {
- List<JGroup> groups = jalviewModel.getJGroup();
- boolean addAnnotSchemeGroup = false;
- for (int i = 0; i < groups.size(); i++)
- {
- JGroup jGroup = groups.get(i);
- ColourSchemeI cs = null;
- if (jGroup.getColour() != null)
- {
- if (jGroup.getColour().startsWith("ucs"))
- {
- cs = getUserColourScheme(jalviewModel, jGroup.getColour());
- }
- else if (jGroup.getColour().equals("AnnotationColourGradient")
- && jGroup.getAnnotationColours() != null)
- {
- addAnnotSchemeGroup = true;
- }
- else
- {
- cs = ColourSchemeProperty.getColourScheme(null, al,
- jGroup.getColour());
- }
- }
- int pidThreshold = safeInt(jGroup.getPidThreshold());
-
- Vector<SequenceI> seqs = new Vector<>();
-
- for (int s = 0; s < jGroup.getSeq().size(); s++)
- {
- String seqId = jGroup.getSeq().get(s);
- SequenceI ts = seqRefIds.get(seqId);
-
- if (ts != null)
- {
- seqs.addElement(ts);
- }
- }
-
- if (seqs.size() < 1)
- {
- continue;
- }
-
- SequenceGroup sg = new SequenceGroup(seqs, jGroup.getName(), cs,
- safeBoolean(jGroup.isDisplayBoxes()),
- safeBoolean(jGroup.isDisplayText()),
- safeBoolean(jGroup.isColourText()),
- safeInt(jGroup.getStart()), safeInt(jGroup.getEnd()));
- sg.getGroupColourScheme().setThreshold(pidThreshold, true);
- sg.getGroupColourScheme()
- .setConservationInc(safeInt(jGroup.getConsThreshold()));
- sg.setOutlineColour(new Color(safeInt(jGroup.getOutlineColour())));
-
- sg.textColour = new Color(safeInt(jGroup.getTextCol1()));
- sg.textColour2 = new Color(safeInt(jGroup.getTextCol2()));
- sg.setShowNonconserved(safeBoolean(jGroup.isShowUnconserved()));
- sg.thresholdTextColour = safeInt(jGroup.getTextColThreshold());
- // attributes with a default in the schema are never null
- sg.setShowConsensusHistogram(jGroup.isShowConsensusHistogram());
- sg.setshowSequenceLogo(jGroup.isShowSequenceLogo());
- sg.setNormaliseSequenceLogo(jGroup.isNormaliseSequenceLogo());
- sg.setIgnoreGapsConsensus(jGroup.isIgnoreGapsinConsensus());
- if (jGroup.getConsThreshold() != null
- && jGroup.getConsThreshold().intValue() != 0)
- {
- Conservation c = new Conservation("All", sg.getSequences(null), 0,
- sg.getWidth() - 1);
- c.calculate();
- c.verdict(false, 25);
- sg.cs.setConservation(c);
- }
-
- if (jGroup.getId() != null && groupAnnotRefs.size() > 0)
- {
- // re-instate unique group/annotation row reference
- List<AlignmentAnnotation> jaal = groupAnnotRefs
- .get(jGroup.getId());
- if (jaal != null)
- {
- for (AlignmentAnnotation jaa : jaal)
- {
- jaa.groupRef = sg;
- if (jaa.autoCalculated)
- {
- // match up and try to set group autocalc alignment row for this
- // annotation
- if (jaa.label.startsWith("Consensus for "))
- {
- sg.setConsensus(jaa);
- }
- // match up and try to set group autocalc alignment row for this
- // annotation
- if (jaa.label.startsWith("Conservation for "))
- {
- sg.setConservationRow(jaa);
- }
- }
- }
- }
- }
- al.addGroup(sg);
- if (addAnnotSchemeGroup)
- {
- // reconstruct the annotation colourscheme
- sg.setColourScheme(
- constructAnnotationColour(jGroup.getAnnotationColours(),
- null, al, jalviewModel, false));
- }
- }
- }
- if (view == null)
- {
- // only dataset in this model, so just return.
- return null;
- }
- // ///////////////////////////////
- // LOAD VIEWPORT
-
- // now check to see if we really need to create a new viewport.
- if (multipleView && viewportsAdded.size() == 0)
- {
- // We recovered an alignment for which a viewport already exists.
- // TODO: fix up any settings necessary for overlaying stored state onto
- // state recovered from another document. (may not be necessary).
- // we may need a binding from a viewport in memory to one recovered from
- // XML.
- // and then recover its containing af to allow the settings to be applied.
- // TODO: fix for vamsas demo
- System.err.println(
- "About to recover a viewport for existing alignment: Sequence set ID is "
- + uniqueSeqSetId);
- Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
- if (seqsetobj != null)
- {
- if (seqsetobj instanceof String)
- {
- uniqueSeqSetId = (String) seqsetobj;
- System.err.println(
- "Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
- + uniqueSeqSetId);
- }
- else
- {
- System.err.println(
- "Warning : Collision between sequence set ID string and existing jalview object mapping.");
- }
-
- }
- }
- /**
- * indicate that annotation colours are applied across all groups (pre
- * Jalview 2.8.1 behaviour)
- */
- boolean doGroupAnnColour = Jalview2XML.isVersionStringLaterThan("2.8.1",
- jalviewModel.getVersion());
-
- AlignFrame af = null;
- AlignmentPanel ap = null;
- AlignViewport av = null;
- if (viewId != null)
- {
- // Check to see if this alignment already has a view id == viewId
- jalview.gui.AlignmentPanel views[] = Desktop
- .getAlignmentPanels(uniqueSeqSetId);
- if (views != null && views.length > 0)
- {
- for (int v = 0; v < views.length; v++)
- {
- ap = views[v];
- av = ap.av;
- if (av.getViewId().equalsIgnoreCase(viewId))
- {
- // recover the existing alignpanel, alignframe, viewport
- af = ap.alignFrame;
- break;
- // TODO: could even skip resetting view settings if we don't want to
- // change the local settings from other jalview processes
- }
- }
- }
- }
-
- if (af == null)
- {
- af = loadViewport(fileName, file, jseqs, hiddenSeqs, al, jalviewModel, view,
- uniqueSeqSetId, viewId, autoAlan);
- av = af.getViewport();
- // note that this only retrieves the most recently accessed
- // tab of an AlignFrame.
- ap = af.alignPanel;
- }
-
- /*
- * Load any trees, PDB structures and viewers
- *
- * Not done if flag is false (when this method is used for New View)
- */
- final AlignFrame af0 = af;
- final AlignViewport av0 = av;
- final AlignmentPanel ap0 = ap;
- // Platform.timeCheck("Jalview2XML.loadFromObject-beforetree",
- // Platform.TIME_MARK);
- if (loadTreesAndStructures)
- {
- if (!jalviewModel.getTree().isEmpty())
- {
- SwingUtilities.invokeLater(new Runnable()
- {
- @Override
- public void run()
- {
- // Platform.timeCheck(null, Platform.TIME_MARK);
- loadTrees(jalviewModel, view, af0, av0, ap0);
- // Platform.timeCheck("Jalview2XML.loadTrees", Platform.TIME_MARK);
- }
- });
- }
- if (!jalviewModel.getPcaViewer().isEmpty())
- {
- SwingUtilities.invokeLater(new Runnable()
- {
- @Override
- public void run()
- {
- // Platform.timeCheck(null, Platform.TIME_MARK);
- loadPCAViewers(jalviewModel, ap0);
- // Platform.timeCheck("Jalview2XML.loadPCA", Platform.TIME_MARK);
- }
- });
- }
- SwingUtilities.invokeLater(new Runnable()
- {
- @Override
- public void run()
- {
- // Platform.timeCheck(null, Platform.TIME_MARK);
- loadPDBStructures(jprovider, jseqs, af0, ap0);
- // Platform.timeCheck("Jalview2XML.loadPDB", Platform.TIME_MARK);
- }
- });
- SwingUtilities.invokeLater(new Runnable()
- {
- @Override
- public void run()
- {
- loadRnaViewers(jprovider, jseqs, ap0);
- }
- });
- }
- // and finally return.
- // but do not set holdRepaint true just yet, because this could be the
- // initial frame with just its dataset.
- return af;
- }
-
- /**
- * Loads a HMMER profile from a file stored in the project, and associates it
- * with the specified sequence
- *
- * @param jprovider
- * @param hmmJarFile
- * @param seq
- */
- protected void loadHmmerProfile(jarInputStreamProvider jprovider,
- String hmmJarFile, SequenceI seq)
- {
- try
- {
- String hmmFile = copyJarEntry(jprovider, hmmJarFile, "hmm", null);
- HMMFile parser = new HMMFile(hmmFile, DataSourceType.FILE);
- HiddenMarkovModel hmmModel = parser.getHMM();
- hmmModel = new HiddenMarkovModel(hmmModel, seq);
- seq.setHMM(hmmModel);
- } catch (IOException e)
- {
- warn("Error loading HMM profile for " + seq.getName() + ": "
- + e.getMessage());
- }
- }
-
- /**
- * Instantiate and link any saved RNA (Varna) viewers. The state of the Varna
- * panel is restored from separate jar entries, two (gapped and trimmed) per
- * sequence and secondary structure.
- *
- * Currently each viewer shows just one sequence and structure (gapped and
- * trimmed), however this method is designed to support multiple sequences or
- * structures in viewers if wanted in future.
- *
- * @param jprovider
- * @param jseqs
- * @param ap
- */
- protected void loadRnaViewers(jarInputStreamProvider jprovider,
- List<JSeq> jseqs, AlignmentPanel ap)
- {
- /*
- * scan the sequences for references to viewers; create each one the first
- * time it is referenced, add Rna models to existing viewers
- */
- for (JSeq jseq : jseqs)
- {
- for (int i = 0; i < jseq.getRnaViewer().size(); i++)
- {
- RnaViewer viewer = jseq.getRnaViewer().get(i);
- AppVarna appVarna = findOrCreateVarnaViewer(viewer, uniqueSetSuffix,
- ap);
-
- for (int j = 0; j < viewer.getSecondaryStructure().size(); j++)
- {
- SecondaryStructure ss = viewer.getSecondaryStructure().get(j);
- SequenceI seq = seqRefIds.get(jseq.getId());
- AlignmentAnnotation ann = this.annotationIds
- .get(ss.getAnnotationId());
-
- /*
- * add the structure to the Varna display (with session state copied
- * from the jar to a temporary file)
- */
- boolean gapped = safeBoolean(ss.isGapped());
- String rnaTitle = ss.getTitle();
- String sessionState = ss.getViewerState();
- String tempStateFile = copyJarEntry(jprovider, sessionState,
- "varna", null);
- RnaModel rna = new RnaModel(rnaTitle, ann, seq, null, gapped);
- appVarna.addModelSession(rna, rnaTitle, tempStateFile);
- }
- appVarna.setInitialSelection(safeInt(viewer.getSelectedRna()));
- }
- }
- }
-
- /**
- * Locate and return an already instantiated matching AppVarna, or create one
- * if not found
- *
- * @param viewer
- * @param viewIdSuffix
- * @param ap
- * @return
- */
- protected AppVarna findOrCreateVarnaViewer(RnaViewer viewer,
- String viewIdSuffix, AlignmentPanel ap)
- {
- /*
- * on each load a suffix is appended to the saved viewId, to avoid conflicts
- * if load is repeated
- */
- String postLoadId = viewer.getViewId() + viewIdSuffix;
- for (JInternalFrame frame : getAllFrames())
- {
- if (frame instanceof AppVarna)
- {
- AppVarna varna = (AppVarna) frame;
- if (postLoadId.equals(varna.getViewId()))
- {
- // this viewer is already instantiated
- // could in future here add ap as another 'parent' of the
- // AppVarna window; currently just 1-to-many
- return varna;
- }
- }
- }
-
- /*
- * viewer not found - make it
- */
- RnaViewerModel model = new RnaViewerModel(postLoadId, viewer.getTitle(),
- safeInt(viewer.getXpos()), safeInt(viewer.getYpos()),
- safeInt(viewer.getWidth()), safeInt(viewer.getHeight()),
- safeInt(viewer.getDividerLocation()));
- AppVarna varna = new AppVarna(model, ap);
-
- return varna;
- }
-
- /**
- * Load any saved trees
- *
- * @param jm
- * @param view
- * @param af
- * @param av
- * @param ap
- */
- protected void loadTrees(JalviewModel jm, Viewport view,
- AlignFrame af, AlignViewport av, AlignmentPanel ap)
- {
- // TODO result of automated refactoring - are all these parameters needed?
- try
- {
- for (int t = 0; t < jm.getTree().size(); t++)
- {
-
- Tree tree = jm.getTree().get(t);
-
- TreePanel tp = (TreePanel) retrieveExistingObj(tree.getId());
- if (tp == null)
- {
- tp = af.showNewickTree(new NewickFile(tree.getNewick()),
- tree.getTitle(), safeInt(tree.getWidth()),
- safeInt(tree.getHeight()), safeInt(tree.getXpos()),
- safeInt(tree.getYpos()));
- if (tp == null)
- {
- warn("There was a problem recovering stored Newick tree: \n"
- + tree.getNewick());
- continue;
- }
- if (tree.getId() != null)
- {
- // perhaps bind the tree id to something ?
- }
- }
- else
- {
- // update local tree attributes ?
- // TODO: should check if tp has been manipulated by user - if so its
- // settings shouldn't be modified
- tp.setTitle(tree.getTitle());
- tp.setBounds(new Rectangle(safeInt(tree.getXpos()),
- safeInt(tree.getYpos()), safeInt(tree.getWidth()),
- safeInt(tree.getHeight())));
- tp.setViewport(av); // af.viewport;
- // TODO: verify 'associate with all views' works still
- tp.getTreeCanvas().setViewport(av); // af.viewport;
- tp.getTreeCanvas().setAssociatedPanel(ap); // af.alignPanel;
- }
- tp.getTreeCanvas().setApplyToAllViews(tree.isLinkToAllViews());
-
- tp.fitToWindow.setState(safeBoolean(tree.isFitToWindow()));
- tp.fitToWindow_actionPerformed(null);
-
- if (tree.getFontName() != null)
- {
- tp.setTreeFont(
- new Font(tree.getFontName(), safeInt(tree.getFontStyle()),
- safeInt(tree.getFontSize())));
- }
- else
- {
- tp.setTreeFont(
- new Font(view.getFontName(), safeInt(view.getFontStyle()),
- safeInt(view.getFontSize())));
- }
-
- tp.showPlaceholders(safeBoolean(tree.isMarkUnlinked()));
- tp.showBootstrap(safeBoolean(tree.isShowBootstrap()));
- tp.showDistances(safeBoolean(tree.isShowDistances()));
-
- tp.getTreeCanvas().setThreshold(safeFloat(tree.getThreshold()));
-
- if (safeBoolean(tree.isCurrentTree()))
- {
- af.getViewport().setCurrentTree(tp.getTree());
- }
- }
-
- } catch (Exception ex)
- {
- ex.printStackTrace();
- }
- }
-
- /**
- * Load and link any saved structure viewers.
- *
- * @param jprovider
- * @param jseqs
- * @param af
- * @param ap
- */
- protected void loadPDBStructures(jarInputStreamProvider jprovider,
- List<JSeq> jseqs, AlignFrame af, AlignmentPanel ap)
- {
- /*
- * Run through all PDB ids on the alignment, and collect mappings between
- * distinct view ids and all sequences referring to that view.
- */
- Map<String, StructureViewerModel> structureViewers = new LinkedHashMap<>();
-
- for (int i = 0; i < jseqs.size(); i++)
- {
- JSeq jseq = jseqs.get(i);
- if (jseq.getPdbids().size() > 0)
- {
- List<Pdbids> ids = jseq.getPdbids();
- for (int p = 0; p < ids.size(); p++)
- {
- Pdbids pdbid = ids.get(p);
- final int structureStateCount = pdbid.getStructureState().size();
- for (int s = 0; s < structureStateCount; s++)
- {
- // check to see if we haven't already created this structure view
- final StructureState structureState = pdbid
- .getStructureState().get(s);
- String sviewid = (structureState.getViewId() == null) ? null
- : structureState.getViewId() + uniqueSetSuffix;
- jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
- // Originally : pdbid.getFile()
- // : TODO: verify external PDB file recovery still works in normal
- // jalview project load
- jpdb.setFile(
- loadPDBFile(jprovider, pdbid.getId(), pdbid.getFile()));
- jpdb.setId(pdbid.getId());
-
- int x = safeInt(structureState.getXpos());
- int y = safeInt(structureState.getYpos());
- int width = safeInt(structureState.getWidth());
- int height = safeInt(structureState.getHeight());
-
- // Probably don't need to do this anymore...
- // Desktop.getDesktop().getComponentAt(x, y);
- // TODO: NOW: check that this recovers the PDB file correctly.
- String pdbFile = loadPDBFile(jprovider, pdbid.getId(),
- pdbid.getFile());
- jalview.datamodel.SequenceI seq = seqRefIds
- .get(jseq.getId() + "");
- if (sviewid == null)
- {
- sviewid = "_jalview_pre2_4_" + x + "," + y + "," + width + ","
- + height;
- }
- if (!structureViewers.containsKey(sviewid))
- {
- String viewerType = structureState.getType();
- if (viewerType == null) // pre Jalview 2.9
- {
- viewerType = ViewerType.JMOL.toString();
- }
- structureViewers.put(sviewid,
- new StructureViewerModel(x, y, width, height, false,
- false, true, structureState.getViewId(),
- viewerType));
- // Legacy pre-2.7 conversion JAL-823 :
- // do not assume any view has to be linked for colour by
- // sequence
- }
-
- // assemble String[] { pdb files }, String[] { id for each
- // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
- // seqs_file 2}, boolean[] {
- // linkAlignPanel,superposeWithAlignpanel}} from hash
- StructureViewerModel jmoldat = structureViewers.get(sviewid);
- jmoldat.setAlignWithPanel(jmoldat.isAlignWithPanel()
- || structureState.isAlignwithAlignPanel());
-
- /*
- * Default colour by linked panel to false if not specified (e.g.
- * for pre-2.7 projects)
- */
- boolean colourWithAlignPanel = jmoldat.isColourWithAlignPanel();
- colourWithAlignPanel |= structureState.isColourwithAlignPanel();
- jmoldat.setColourWithAlignPanel(colourWithAlignPanel);
-
- /*
- * Default colour by viewer to true if not specified (e.g. for
- * pre-2.7 projects)
- */
- boolean colourByViewer = jmoldat.isColourByViewer();
- colourByViewer &= structureState.isColourByJmol();
- jmoldat.setColourByViewer(colourByViewer);
-
- if (jmoldat.getStateData().length() < structureState
- .getValue()/*Content()*/.length())
- {
- jmoldat.setStateData(structureState.getValue());// Content());
- }
- if (pdbid.getFile() != null)
- {
- File mapkey = new File(pdbid.getFile());
- StructureData seqstrmaps = jmoldat.getFileData().get(mapkey);
- if (seqstrmaps == null)
- {
- jmoldat.getFileData().put(mapkey,
- seqstrmaps = jmoldat.new StructureData(pdbFile,
- pdbid.getId()));
- }
- if (!seqstrmaps.getSeqList().contains(seq))
- {
- seqstrmaps.getSeqList().add(seq);
- // TODO and chains?
- }
- }
- else
- {
- errorMessage = ("The Jmol views in this project were imported\nfrom an older version of Jalview.\nPlease review the sequence colour associations\nin the Colour by section of the Jmol View menu.\n\nIn the case of problems, see note at\nhttp://issues.jalview.org/browse/JAL-747");
- warn(errorMessage);
- }
- }
- }
- }
- }
- // Instantiate the associated structure views
- for (Entry<String, StructureViewerModel> entry : structureViewers
- .entrySet())
- {
- try
- {
- createOrLinkStructureViewer(entry, af, ap, jprovider);
- } catch (Exception e)
- {
- System.err.println(
- "Error loading structure viewer: " + e.getMessage());
- // failed - try the next one
- }
- }
- }
-
- /**
- *
- * @param viewerData
- * @param af
- * @param ap
- * @param jprovider
- */
- protected void createOrLinkStructureViewer(
- Entry<String, StructureViewerModel> viewerData, AlignFrame af,
- AlignmentPanel ap, jarInputStreamProvider jprovider)
- {
- final StructureViewerModel stateData = viewerData.getValue();
-
- /*
- * Search for any viewer windows already open from other alignment views
- * that exactly match the stored structure state
- */
- StructureViewerBase comp = findMatchingViewer(viewerData);
-
- if (comp != null)
- {
- linkStructureViewer(ap, comp, stateData);
- return;
- }
-
- String type = stateData.getType();
- try
- {
- ViewerType viewerType = ViewerType.valueOf(type);
- createStructureViewer(viewerType, viewerData, af, jprovider);
- } catch (IllegalArgumentException | NullPointerException e)
- {
- // TODO JAL-3619 show error dialog / offer an alternative viewer
- Cache.log.error("Invalid structure viewer type: " + type);
- }
-
- }
-
- /**
- * Creates a new structure viewer window
- *
- * @param viewerType
- * @param viewerData
- * @param af
- * @param jprovider
- */
- protected void createStructureViewer(ViewerType viewerType,
- final Entry<String, StructureViewerModel> viewerData,
- AlignFrame af, jarInputStreamProvider jprovider)
- {
- final StructureViewerModel viewerModel = viewerData.getValue();
- String sessionFilePath = null;
-
- if (viewerType == ViewerType.JMOL)
- {
- sessionFilePath = rewriteJmolSession(viewerModel, jprovider);
- }
- else
- {
- String viewerJarEntryName = getViewerJarEntryName(
- viewerModel.getViewId());
- sessionFilePath = copyJarEntry(jprovider, viewerJarEntryName,
- "viewerSession", ".tmp");
- }
- final String sessionPath = sessionFilePath;
- final String sviewid = viewerData.getKey();
- // BH again was invokeAndWait
- // try
- // {
- javax.swing.SwingUtilities.invokeLater(new Runnable()
- {
- @Override
- public void run()
- {
- JalviewStructureDisplayI sview = null;
- try
- {
- sview = StructureViewer.createView(viewerType, af.alignPanel,
- viewerModel, sessionPath, sviewid);
- addNewStructureViewer(sview);
- } catch (OutOfMemoryError ex)
- {
- new OOMWarning("Restoring structure view for " + viewerType,
- (OutOfMemoryError) ex.getCause());
- if (sview != null && sview.isVisible())
- {
- sview.closeViewer(false);
- sview.setVisible(false);
- sview.dispose();
- }
- }
- }
- });
- // } catch (InvocationTargetException | InterruptedException ex)
- // {
- // warn("Unexpected error when opening " + viewerType
- // + " structure viewer", ex);
- // }
- }
-
- /**
- * Rewrites a Jmol session script, saves it to a temporary file, and returns
- * the path of the file. "load file" commands are rewritten to change the
- * original PDB file names to those created as the Jalview project is loaded.
- *
- * @param svattrib
- * @param jprovider
- * @return
- */
- private String rewriteJmolSession(StructureViewerModel svattrib,
- jarInputStreamProvider jprovider)
- {
- String state = svattrib.getStateData(); // Jalview < 2.9
- if (state == null || state.isEmpty()) // Jalview >= 2.9
- {
- String jarEntryName = getViewerJarEntryName(svattrib.getViewId());
- state = readJarEntry(jprovider, jarEntryName);
- }
- // TODO or simpler? for each key in oldFiles,
- // replace key.getPath() in state with oldFiles.get(key).getFilePath()
- // (allowing for different path escapings)
- StringBuilder rewritten = new StringBuilder(state.length());
- int cp = 0, ncp, ecp;
- Map<File, StructureData> oldFiles = svattrib.getFileData();
- while ((ncp = state.indexOf("load ", cp)) > -1)
- {
- do
- {
- // look for next filename in load statement
- rewritten.append(state.substring(cp,
- ncp = (state.indexOf("\"", ncp + 1) + 1)));
- String oldfilenam = state.substring(ncp,
- ecp = state.indexOf("\"", ncp));
- // recover the new mapping data for this old filename
- // have to normalize filename - since Jmol and jalview do
- // filename translation differently.
- StructureData filedat = oldFiles.get(new File(oldfilenam));
- if (filedat == null)
- {
- String reformatedOldFilename = oldfilenam.replaceAll("/", "\\\\");
- filedat = oldFiles.get(new File(reformatedOldFilename));
- }
- rewritten.append(Platform.escapeBackslashes(filedat.getFilePath()));
- rewritten.append("\"");
- cp = ecp + 1; // advance beyond last \" and set cursor so we can
- // look for next file statement.
- } while ((ncp = state.indexOf("/*file*/", cp)) > -1);
- }
- if (cp > 0)
- {
- // just append rest of state
- rewritten.append(state.substring(cp));
- }
- else
- {
- System.err.print("Ignoring incomplete Jmol state for PDB ids: ");
- rewritten = new StringBuilder(state);
- rewritten.append("; load append ");
- for (File id : oldFiles.keySet())
- {
- // add pdb files that should be present in the viewer
- StructureData filedat = oldFiles.get(id);
- rewritten.append(" \"").append(filedat.getFilePath()).append("\"");
- }
- rewritten.append(";");
- }
-
- if (rewritten.length() == 0)
- {
- return null;
- }
- final String history = "history = ";
- int historyIndex = rewritten.indexOf(history);
- if (historyIndex > -1)
- {
- /*
- * change "history = [true|false];" to "history = [1|0];"
- */
- historyIndex += history.length();
- String val = rewritten.substring(historyIndex, historyIndex + 5);
- if (val.startsWith("true"))
- {
- rewritten.replace(historyIndex, historyIndex + 4, "1");
- }
- else if (val.startsWith("false"))
- {
- rewritten.replace(historyIndex, historyIndex + 5, "0");
- }
- }
-
- try
- {
- File tmp = File.createTempFile("viewerSession", ".tmp");
- try (OutputStream os = new FileOutputStream(tmp))
- {
- InputStream is = new ByteArrayInputStream(
- rewritten.toString().getBytes());
- copyAll(is, os);
- return tmp.getAbsolutePath();
- }
- } catch (IOException e)
- {
- Cache.log.error("Error restoring Jmol session: " + e.toString());
- }
- return null;
- }
-
- /**
- * Generates a name for the entry in the project jar file to hold state
- * information for a structure viewer
- *
- * @param viewId
- * @return
- */
- protected String getViewerJarEntryName(String viewId)
- {
- return VIEWER_PREFIX + viewId;
- }
-
- /**
- * Returns any open frame that matches given structure viewer data. The match
- * is based on the unique viewId, or (for older project versions) the frame's
- * geometry.
- *
- * @param viewerData
- * @return
- */
- protected StructureViewerBase findMatchingViewer(
- Entry<String, StructureViewerModel> viewerData)
- {
- final String sviewid = viewerData.getKey();
- final StructureViewerModel svattrib = viewerData.getValue();
- StructureViewerBase comp = null;
- JInternalFrame[] frames = getAllFrames();
- for (JInternalFrame frame : frames)
- {
- if (frame instanceof StructureViewerBase)
- {
- /*
- * Post jalview 2.4 schema includes structure view id
- */
- if (sviewid != null && ((StructureViewerBase) frame).getViewId()
- .equals(sviewid))
- {
- comp = (StructureViewerBase) frame;
- break; // break added in 2.9
- }
- /*
- * Otherwise test for matching position and size of viewer frame
- */
- else if (frame.getX() == svattrib.getX()
- && frame.getY() == svattrib.getY()
- && frame.getHeight() == svattrib.getHeight()
- && frame.getWidth() == svattrib.getWidth())
- {
- comp = (StructureViewerBase) frame;
- // no break in faint hope of an exact match on viewId
- }
- }
- }
- return comp;
- }
-
- /**
- * Link an AlignmentPanel to an existing structure viewer.
- *
- * @param ap
- * @param viewer
- * @param oldFiles
- * @param useinViewerSuperpos
- * @param usetoColourbyseq
- * @param viewerColouring
- */
- protected void linkStructureViewer(AlignmentPanel ap,
- StructureViewerBase viewer, StructureViewerModel stateData)
- {
- // NOTE: if the jalview project is part of a shared session then
- // view synchronization should/could be done here.
-
- final boolean useinViewerSuperpos = stateData.isAlignWithPanel();
- final boolean usetoColourbyseq = stateData.isColourWithAlignPanel();
- final boolean viewerColouring = stateData.isColourByViewer();
- Map<File, StructureData> oldFiles = stateData.getFileData();
-
- /*
- * Add mapping for sequences in this view to an already open viewer
- */
- final AAStructureBindingModel binding = viewer.getBinding();
- for (File id : oldFiles.keySet())
- {
- // add this and any other pdb files that should be present in the
- // viewer
- StructureData filedat = oldFiles.get(id);
- String pdbFile = filedat.getFilePath();
- SequenceI[] seq = filedat.getSeqList().toArray(new SequenceI[0]);
- binding.getSsm().setMapping(seq, null, pdbFile, DataSourceType.FILE,
- null);
- binding.addSequenceForStructFile(pdbFile, seq);
- }
- // and add the AlignmentPanel's reference to the view panel
- viewer.addAlignmentPanel(ap);
- if (useinViewerSuperpos)
- {
- viewer.useAlignmentPanelForSuperposition(ap);
- }
- else
++ * Generates a name for the entry in the project jar file to hold state
++ * information for a structure viewer
++ *
++ * @param viewId
++ * @return
++ */
++ protected String getViewerJarEntryName(String viewId)
{
-- viewer.excludeAlignmentPanelForSuperposition(ap);
++ return VIEWER_PREFIX + viewId;
}
-- if (usetoColourbyseq)
-- {
-- viewer.useAlignmentPanelForColourbyseq(ap, !viewerColouring);
++
++ /**
++ * Returns any open frame that matches given structure viewer data. The match
++ * is based on the unique viewId, or (for older project versions) the frame's
++ * geometry.
++ *
++ * @param viewerData
++ * @return
++ */
++ protected StructureViewerBase findMatchingViewer(
++ Entry<String, StructureViewerModel> viewerData)
++ {
++ final String sviewid = viewerData.getKey();
++ final StructureViewerModel svattrib = viewerData.getValue();
++ StructureViewerBase comp = null;
++ JInternalFrame[] frames = getAllFrames();
++ for (JInternalFrame frame : frames)
++ {
++ if (frame instanceof StructureViewerBase)
++ {
++ /*
++ * Post jalview 2.4 schema includes structure view id
++ */
++ if (sviewid != null && ((StructureViewerBase) frame).getViewId()
++ .equals(sviewid))
++ {
++ comp = (StructureViewerBase) frame;
++ break; // break added in 2.9
++ }
++ /*
++ * Otherwise test for matching position and size of viewer frame
++ */
++ else if (frame.getX() == svattrib.getX()
++ && frame.getY() == svattrib.getY()
++ && frame.getHeight() == svattrib.getHeight()
++ && frame.getWidth() == svattrib.getWidth())
++ {
++ comp = (StructureViewerBase) frame;
++ // no break in faint hope of an exact match on viewId
++ }
++ }
++ }
++ return comp;
}
-- else
-- {
-- viewer.excludeAlignmentPanelForColourbyseq(ap);
++
++ /**
++ * Link an AlignmentPanel to an existing structure viewer.
++ *
++ * @param ap
++ * @param viewer
++ * @param oldFiles
++ * @param useinViewerSuperpos
++ * @param usetoColourbyseq
++ * @param viewerColouring
++ */
++ protected void linkStructureViewer(AlignmentPanel ap,
++ StructureViewerBase viewer, StructureViewerModel stateData)
++ {
++ // NOTE: if the jalview project is part of a shared session then
++ // view synchronization should/could be done here.
++
++ final boolean useinViewerSuperpos = stateData.isAlignWithPanel();
++ final boolean usetoColourbyseq = stateData.isColourWithAlignPanel();
++ final boolean viewerColouring = stateData.isColourByViewer();
++ Map<File, StructureData> oldFiles = stateData.getFileData();
++
++ /*
++ * Add mapping for sequences in this view to an already open viewer
++ */
++ final AAStructureBindingModel binding = viewer.getBinding();
++ for (File id : oldFiles.keySet())
++ {
++ // add this and any other pdb files that should be present in the
++ // viewer
++ StructureData filedat = oldFiles.get(id);
++ String pdbFile = filedat.getFilePath();
++ SequenceI[] seq = filedat.getSeqList().toArray(new SequenceI[0]);
++ binding.getSsm().setMapping(seq, null, pdbFile, DataSourceType.FILE,
++ null);
++ binding.addSequenceForStructFile(pdbFile, seq);
++ }
++ // and add the AlignmentPanel's reference to the view panel
++ viewer.addAlignmentPanel(ap);
++ if (useinViewerSuperpos)
++ {
++ viewer.useAlignmentPanelForSuperposition(ap);
++ }
++ else
++ {
++ viewer.excludeAlignmentPanelForSuperposition(ap);
++ }
++ if (usetoColourbyseq)
++ {
++ viewer.useAlignmentPanelForColourbyseq(ap, !viewerColouring);
++ }
++ else
++ {
++ viewer.excludeAlignmentPanelForColourbyseq(ap);
++ }
}
-- }
-- /**
-- * Get all frames within the Desktop.
-- *
-- * @return
-- */
-- protected JInternalFrame[] getAllFrames()
-- {
-- JInternalFrame[] frames = null;
-- // TODO is this necessary - is it safe - risk of hanging?
-- do
-- {
-- try
-- {
- frames = Desktop.getDesktopPane().getAllFrames();
- } catch (ArrayIndexOutOfBoundsException e)
- {
- // occasional No such child exceptions are thrown here...
- try
- {
- Thread.sleep(10);
- } catch (InterruptedException f)
- {
- }
- }
- } while (frames == null);
- return frames;
- }
- frames = Desktop.desktop.getAllFrames();
- } catch (ArrayIndexOutOfBoundsException e)
- {
- // occasional No such child exceptions are thrown here...
- try
- {
- Thread.sleep(10);
- } catch (InterruptedException f)
- {
- }
- }
- } while (frames == null);
- return frames;
- }
++ /**
++ * Get all frames within the Desktop.
++ *
++ * @return
++ */
++ protected JInternalFrame[] getAllFrames()
++ {
++ JInternalFrame[] frames = null;
++ // TODO is this necessary - is it safe - risk of hanging?
++ do
++ {
++ try
++ {
++ frames = Desktop.getDesktopPane().getAllFrames();
++ } catch (ArrayIndexOutOfBoundsException e)
++ {
++ // occasional No such child exceptions are thrown here...
++ try
++ {
++ Thread.sleep(10);
++ } catch (InterruptedException f)
++ {
++ }
++ }
++ } while (frames == null);
++ return frames;
++ }
-- /**
-- * Answers true if 'version' is equal to or later than 'supported', where each
-- * is formatted as major/minor versions like "2.8.3" or "2.3.4b1" for bugfix
-- * changes. Development and test values for 'version' are leniently treated
-- * i.e. answer true.
-- *
-- * @param supported
-- * - minimum version we are comparing against
-- * @param version
-- * - version of data being processsed
-- * @return
-- */
-- public static boolean isVersionStringLaterThan(String supported,
-- String version)
++ /**
++ * Answers true if 'version' is equal to or later than 'supported', where each
++ * is formatted as major/minor versions like "2.8.3" or "2.3.4b1" for bugfix
++ * changes. Development and test values for 'version' are leniently treated
++ * i.e. answer true.
++ *
++ * @param supported
++ * - minimum version we are comparing against
++ * @param version
++ * - version of data being processsed
++ * @return
++ */
++ public static boolean isVersionStringLaterThan(String supported,
++ String version)
{
if (supported == null || version == null
|| version.equalsIgnoreCase("DEVELOPMENT BUILD")
}
}
- AlignFrame loadViewport(String file, List<JSeq> JSEQ,
+ AlignFrame loadViewport(String fileName, File file, List<JSeq> JSEQ,
List<SequenceI> hiddenSeqs, AlignmentI al, JalviewModel jm,
Viewport view, String uniqueSeqSetId, String viewId,
List<JvAnnotRow> autoAlan)
// }
;
- af.setFileName(file, FileFormat.Jalview);
+ af.alignPanel.setHoldRepaint(true);
+ af.setFile(fileName, file, null, FileFormat.Jalview);
+ af.setFileObject(jarFile); // BH 2019 JAL-3436
final AlignViewport viewport = af.getViewport();
for (int i = 0; i < JSEQ.size(); i++)
viewport.setViewName(view.getViewName());
af.setInitialTabVisible();
}
- af.setBounds(safeInt(view.getXpos()), safeInt(view.getYpos()),
- safeInt(view.getWidth()), safeInt(view.getHeight()));
+ int x = safeInt(view.getXpos());
+ int y = safeInt(view.getYpos());
+ int w = safeInt(view.getWidth());
+ int h = safeInt(view.getHeight());
+ // // BH we cannot let the title bar go off the top
+ // if (Platform.isJS())
+ // {
+ // x = Math.max(50 - w, x);
+ // y = Math.max(0, y);
+ // }
+
+ af.setBounds(x, y, w, h);
// startSeq set in af.alignPanel.updateLayout below
af.alignPanel.updateLayout();
ColourSchemeI cs = null;
}
else
{
- warn("Couldn't recover parameters for "
+ Console.warn("Couldn't recover parameters for "
+ calcIdParam.getCalcId());
}
}
String complementaryViewId = view.getComplementId();
if (complementaryViewId == null)
{
- Desktop.addInternalFrame(af, view.getTitle(),
+ Dimension dim = Platform.getDimIfEmbedded(af,
safeInt(view.getWidth()), safeInt(view.getHeight()));
+ Desktop.addInternalFrame(af, view.getTitle(), dim.width, dim.height);
// recompute any autoannotation
af.alignPanel.updateAnnotation(false, true);
reorderAutoannotation(af, al, autoAlan);
String id = object.getViewport().get(0).getSequenceSetId();
if (skipList.containsKey(id))
{
- if (Cache.log != null && Cache.log.isDebugEnabled())
- {
- Cache.log.debug("Skipping seuqence set id " + id);
- }
+ Console.debug("Skipping seuqence set id " + id);
return true;
}
return false;
}
- public void addToSkipList(AlignFrame af)
+ protected void addToSkipList(AlignFrame af)
{
if (skipList == null)
{
skipList.put(af.getViewport().getSequenceSetId(), af);
}
- public void clearSkipList()
+ protected void clearSkipList()
{
if (skipList != null)
{
addDatasetRef(vamsasSet.getDatasetId(), ds);
}
}
- Vector dseqs = null;
+ Vector<SequenceI> dseqs = null;
if (!ignoreUnrefed)
{
// recovering an alignment View
{
if (ds != null && ds != seqSetDS)
{
- warn("JAL-3171 regression: Overwriting a dataset reference for an alignment"
- + " - CDS/Protein crossreference data may be lost");
+ Console.warn(
+ "JAL-3171 regression: Overwriting a dataset reference for an alignment"
+ + " - CDS/Protein crossreference data may be lost");
if (xtant_ds != null)
{
// This can only happen if the unique sequence set ID was bound to a
// dataset that did not contain any of the sequences in the view
// currently being restored.
- warn("JAL-3171 SERIOUS! TOTAL CONFUSION - please consider contacting the Jalview Development team so they can investigate why your project caused this message to be displayed.");
+ Console.warn(
+ "JAL-3171 SERIOUS! TOTAL CONFUSION - please consider contacting the Jalview Development team so they can investigate why your project caused this message to be displayed.");
}
}
ds = seqSetDS;
SequenceI[] dsseqs = new SequenceI[dseqs.size()];
dseqs.copyInto(dsseqs);
ds = new jalview.datamodel.Alignment(dsseqs);
- // debug("Jalview2XML Created new dataset " + vamsasSet.getDatasetId()
- Console.debug("Created new dataset " + vamsasSet.getDatasetId()
- + " for alignment " + System.identityHashCode(al));
++// Console.debug("Jalview2XML Created new dataset " + vamsasSet.getDatasetId()
+// + " for alignment " + System.identityHashCode(al));
addDatasetRef(vamsasSet.getDatasetId(), ds);
}
// set the dataset for the newly imported alignment.
AlignmentI prevDS = seqToDataset.put(restoredSeq.getDsseqid(), ds);
if (prevDS != null && prevDS != ds)
{
- warn("Dataset sequence appears in many datasets: "
+ Console.warn("Dataset sequence appears in many datasets: "
+ restoredSeq.getDsseqid());
// TODO: try to merge!
}
}
}
+
/**
*
* @param vamsasSeq
{
if (dataset.getDataset() != null)
{
- warn("Serious issue! Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
+ Console.warn(
+ "Serious issue! Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
}
String datasetId = makeHashCode(dataset, null);
if (datasetId == null)
seqRefIds.put(sqid, djs);
}
- jalview.bin.Cache.log.debug("about to recurse on addDBRefs.");
+ Console.debug("about to recurse on addDBRefs.");
addDBRefs(djs, ms);
}
viewportsAdded.clear();
- AlignFrame af = loadFromObject(jm, null, false, null);
+ AlignFrame af = loadFromObject(jm, null, null, false, null);
af.getAlignPanels().clear();
af.closeMenuItem_actionPerformed(true);
+ af.alignPanel.setHoldRepaint(false);
+ this.jarFile = null;
/*
* if(ap.av.getAlignment().getAlignmentAnnotation()!=null) { for(int i=0;
private Hashtable jvids2vobj;
- private void warn(String msg)
- {
- warn(msg, null);
- }
-
- private void warn(String msg, Exception e)
- {
- if (Cache.log != null)
- {
- if (e != null)
- {
- Cache.log.warn(msg, e);
- }
- else
- {
- Cache.log.warn(msg);
- }
- }
- else
- {
- System.err.println("Warning: " + msg);
- if (e != null)
- {
- e.printStackTrace();
- }
- }
- }
-
- private void debug(String string)
- {
- debug(string, null);
- }
-
- private void debug(String msg, Exception e)
- {
- if (Cache.log != null)
- {
- if (e != null)
- {
- Cache.log.debug(msg, e);
- }
- else
- {
- Cache.log.debug(msg);
- }
- }
- else
- {
- System.err.println("Warning: " + msg);
- if (e != null)
- {
- e.printStackTrace();
- }
- }
- }
-
/**
* set the object to ID mapping tables used to write/recover objects and XML
* ID strings for the jalview project. If external tables are provided then
if (!jvann.annotationId.equals(anid))
{
// TODO verify that this is the correct behaviour
- this.warn("Overriding Annotation ID for " + anid
+ Console.warn("Overriding Annotation ID for " + anid
+ " from different id : " + jvann.annotationId);
jvann.annotationId = anid;
}
}
else
{
- Cache.log.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
+ Console.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
}
}
}
}
else
{
- warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
+ Console.warn(
+ "Couldn't find entry in Jalview Jar for " + jarEntryName);
}
} catch (Exception ex)
{
axis.getXPos(), axis.getYPos(), axis.getZPos());
}
+ Dimension dim = Platform.getDimIfEmbedded(panel, 475, 450);
Desktop.addInternalFrame(panel, MessageManager.formatMessage(
- "label.calc_title", "PCA", modelName), 475, 450);
+ "label.calc_title", "PCA", modelName), dim.width,
+ dim.height);
}
} catch (Exception ex)
{
- Cache.log.error("Error loading PCA: " + ex.toString());
+ Console.error("Error loading PCA: " + ex.toString());
+ }
+ }
+
+ /**
+ * Creates a new structure viewer window
+ *
+ * @param viewerType
+ * @param viewerData
+ * @param af
+ * @param jprovider
+ */
+ protected void createStructureViewer(ViewerType viewerType,
+ final Entry<String, StructureViewerModel> viewerData,
+ AlignFrame af, jarInputStreamProvider jprovider)
+ {
+ final StructureViewerModel viewerModel = viewerData.getValue();
+ String sessionFilePath = null;
+
+ if (viewerType == ViewerType.JMOL)
+ {
+ sessionFilePath = rewriteJmolSession(viewerModel, jprovider);
+ }
+ else
+ {
+ String viewerJarEntryName = getViewerJarEntryName(
+ viewerModel.getViewId());
+ sessionFilePath = copyJarEntry(jprovider, viewerJarEntryName,
+ "viewerSession", ".tmp");
+ }
+ final String sessionPath = sessionFilePath;
+ final String sviewid = viewerData.getKey();
- try
- {
- SwingUtilities.invokeAndWait(new Runnable()
++// BH again was invokeAndWait
++ // try
++ // {
++ javax.swing.SwingUtilities.invokeLater(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ JalviewStructureDisplayI sview = null;
+ try
+ {
+ sview = StructureViewer.createView(viewerType, af.alignPanel,
+ viewerModel, sessionPath, sviewid);
+ addNewStructureViewer(sview);
+ } catch (OutOfMemoryError ex)
+ {
+ new OOMWarning("Restoring structure view for " + viewerType,
+ (OutOfMemoryError) ex.getCause());
+ if (sview != null && sview.isVisible())
+ {
+ sview.closeViewer(false);
+ sview.setVisible(false);
+ sview.dispose();
+ }
+ }
+ }
+ });
- } catch (InvocationTargetException | InterruptedException ex)
- {
- Console.warn("Unexpected error when opening " + viewerType
- + " structure viewer", ex);
- }
++// } catch (InvocationTargetException | InterruptedException ex)
++// {
++// Console.warn("Unexpected error when opening " + viewerType
++// + " structure viewer", ex);
++// }
+ }
+
+ /**
+ * Rewrites a Jmol session script, saves it to a temporary file, and returns
+ * the path of the file. "load file" commands are rewritten to change the
+ * original PDB file names to those created as the Jalview project is loaded.
+ *
+ * @param svattrib
+ * @param jprovider
+ * @return
+ */
+ private String rewriteJmolSession(StructureViewerModel svattrib,
+ jarInputStreamProvider jprovider)
+ {
+ String state = svattrib.getStateData(); // Jalview < 2.9
+ if (state == null || state.isEmpty()) // Jalview >= 2.9
+ {
+ String jarEntryName = getViewerJarEntryName(svattrib.getViewId());
+ state = readJarEntry(jprovider, jarEntryName);
+ }
+ // TODO or simpler? for each key in oldFiles,
+ // replace key.getPath() in state with oldFiles.get(key).getFilePath()
+ // (allowing for different path escapings)
+ StringBuilder rewritten = new StringBuilder(state.length());
+ int cp = 0, ncp, ecp;
+ Map<File, StructureData> oldFiles = svattrib.getFileData();
+ while ((ncp = state.indexOf("load ", cp)) > -1)
+ {
+ do
+ {
+ // look for next filename in load statement
+ rewritten.append(state.substring(cp,
+ ncp = (state.indexOf("\"", ncp + 1) + 1)));
+ String oldfilenam = state.substring(ncp,
+ ecp = state.indexOf("\"", ncp));
+ // recover the new mapping data for this old filename
+ // have to normalize filename - since Jmol and jalview do
+ // filename translation differently.
+ StructureData filedat = oldFiles.get(new File(oldfilenam));
+ if (filedat == null)
+ {
+ String reformatedOldFilename = oldfilenam.replaceAll("/", "\\\\");
+ filedat = oldFiles.get(new File(reformatedOldFilename));
+ }
+ rewritten.append(Platform.escapeBackslashes(filedat.getFilePath()));
+ rewritten.append("\"");
+ cp = ecp + 1; // advance beyond last \" and set cursor so we can
+ // look for next file statement.
+ } while ((ncp = state.indexOf("/*file*/", cp)) > -1);
+ }
+ if (cp > 0)
+ {
+ // just append rest of state
+ rewritten.append(state.substring(cp));
+ }
+ else
+ {
+ System.err.print("Ignoring incomplete Jmol state for PDB ids: ");
+ rewritten = new StringBuilder(state);
+ rewritten.append("; load append ");
+ for (File id : oldFiles.keySet())
+ {
+ // add pdb files that should be present in the viewer
+ StructureData filedat = oldFiles.get(id);
+ rewritten.append(" \"").append(filedat.getFilePath()).append("\"");
+ }
+ rewritten.append(";");
+ }
+
+ if (rewritten.length() == 0)
+ {
+ return null;
+ }
+ final String history = "history = ";
+ int historyIndex = rewritten.indexOf(history);
+ if (historyIndex > -1)
+ {
+ /*
+ * change "history = [true|false];" to "history = [1|0];"
+ */
+ historyIndex += history.length();
+ String val = rewritten.substring(historyIndex, historyIndex + 5);
+ if (val.startsWith("true"))
+ {
+ rewritten.replace(historyIndex, historyIndex + 4, "1");
+ }
+ else if (val.startsWith("false"))
+ {
+ rewritten.replace(historyIndex, historyIndex + 5, "0");
+ }
+ }
+
+ try
+ {
+ File tmp = File.createTempFile("viewerSession", ".tmp");
+ try (OutputStream os = new FileOutputStream(tmp))
+ {
+ InputStream is = new ByteArrayInputStream(
+ rewritten.toString().getBytes());
+ copyAll(is, os);
+ return tmp.getAbsolutePath();
+ }
+ } catch (IOException e)
+ {
+ Console.error("Error restoring Jmol session: " + e.toString());
}
+ return null;
}
/**
* @param fcol
* @return
*/
- public static Colour marshalColour(String featureType,
- FeatureColourI fcol)
+ public static Colour marshalColour(
+ String featureType, FeatureColourI fcol)
{
Colour col = new Colour();
if (fcol.isSimpleColour())
boolean and)
{
jalview.xml.binding.jalview.FeatureMatcherSet result = new jalview.xml.binding.jalview.FeatureMatcherSet();
+
if (filters.hasNext())
{
/*
}
result.setMatchCondition(matcherModel);
}
+
return result;
}
* @param matcherSetModel
* @return
*/
- public static FeatureMatcherSetI parseFilter(String featureType,
+ public static FeatureMatcherSetI parseFilter(
+ String featureType,
jalview.xml.binding.jalview.FeatureMatcherSet matcherSetModel)
{
FeatureMatcherSetI result = new FeatureMatcherSet();
featureType, e.getMessage()));
// return as much as was parsed up to the error
}
+
return result;
}
* @throws IllegalStateException
* if AND and OR conditions are mixed
*/
- protected static void parseFilterConditions(FeatureMatcherSetI matcherSet,
+ protected static void parseFilterConditions(
+ FeatureMatcherSetI matcherSet,
jalview.xml.binding.jalview.FeatureMatcherSet matcherSetModel,
boolean and)
{
else if (filterBy == FilterBy.BY_SCORE)
{
matchCondition = FeatureMatcher.byScore(cond, pattern);
+
}
else if (filterBy == FilterBy.BY_ATTRIBUTE)
{
matchCondition = FeatureMatcher.byAttribute(cond, pattern,
attNames);
}
+
/*
* note this throws IllegalStateException if AND-ing to a
* previously OR-ed compound condition, or vice versa
public static FeatureColourI parseColour(Colour colourModel)
{
FeatureColourI colour = null;
+
if (colourModel.getMax() != null)
{
Color mincol = null;
Color maxcol = null;
Color noValueColour = null;
+
try
{
mincol = new Color(Integer.parseInt(colourModel.getMinRGB(), 16));
maxcol = new Color(Integer.parseInt(colourModel.getRGB(), 16));
} catch (Exception e)
{
- Cache.log.warn("Couldn't parse out graduated feature color.", e);
+ Console.warn("Couldn't parse out graduated feature color.", e);
}
+
NoValueColour noCol = colourModel.getNoValueColour();
if (noCol == NoValueColour.MIN)
{
{
noValueColour = maxcol;
}
+
colour = new FeatureColour(maxcol, mincol, maxcol, noValueColour,
safeFloat(colourModel.getMin()),
safeFloat(colourModel.getMax()));
Color color = new Color(Integer.parseInt(colourModel.getRGB(), 16));
colour = new FeatureColour(color);
}
+
return colour;
}
}
++
import jalview.datamodel.Annotation;
import jalview.datamodel.ColumnSelection;
import jalview.datamodel.HiddenColumns;
+import jalview.datamodel.HiddenMarkovModel;
import jalview.datamodel.ProfilesI;
import jalview.schemes.ColourSchemeI;
import jalview.schemes.NucleotideColourScheme;
import jalview.schemes.ResidueProperties;
import jalview.schemes.ZappoColourScheme;
import jalview.util.Platform;
+import jalview.workers.InformationThread;
import java.awt.BasicStroke;
import java.awt.Color;
private final boolean USE_FILL_ROUND_RECT = Platform.isAMacAndNotJS();
- boolean av_renderHistogram = true, av_renderProfile = true,
- av_normaliseProfile = false;
+ // todo remove these flags, read from group/viewport where needed
+ boolean av_renderHistogram = true;
+
+ boolean av_renderProfile = true;
+
+ boolean av_normaliseProfile = false;
+
+ boolean av_infoHeight = false;
ResidueShaderI profcolour = null;
private boolean av_ignoreGapsConsensus;
+ private boolean av_ignoreBelowBackground;
+
/**
* attributes set from AwtRenderPanelI
*/
complementConsensus = av.getComplementConsensusHash();
hStrucConsensus = av.getRnaStructureConsensusHash();
av_ignoreGapsConsensus = av.isIgnoreGapsConsensus();
+ av_ignoreBelowBackground = av.isIgnoreBelowBackground();
+ av_infoHeight = av.isInfoLetterHeight();
}
+
+
/**
* Returns profile data; the first element is the profile type, the second is
* the number of distinct values, the third the total count, and the remainder
// properties/rendering attributes as a global 'alignment group' which holds
// all vis settings for the alignment as a whole rather than a subset
//
- if (aa.autoCalculated && (aa.label.startsWith("Consensus")
- || aa.label.startsWith("cDNA Consensus")))
+ if (InformationThread.HMM_CALC_ID.equals(aa.getCalcId()))
+ {
+ HiddenMarkovModel hmm = aa.sequenceRef.getHMM();
+ return AAFrequency.extractHMMProfile(hmm, column,
+ av_ignoreBelowBackground, av_infoHeight); // TODO check if this follows standard
+ // pipeline
+ }
+ if (aa.autoCalculated
+ && (aa.label.startsWith("Consensus") || aa.label
+ .startsWith("cDNA Consensus")))
{
boolean forComplement = aa.label.startsWith("cDNA Consensus");
- if (aa.groupRef != null && aa.groupRef.consensusData != null
+ if (aa.groupRef != null && aa.groupRef.getConsensusData() != null
&& aa.groupRef.isShowSequenceLogo())
{
// TODO? group consensus for cDNA complement
return AAFrequency.extractProfile(
- aa.groupRef.consensusData.get(column),
- aa.groupRef.getIgnoreGapsConsensus());
+ aa.groupRef.getConsensusData().get(column),
+ aa.groupRef.getIgnoreGapsConsensus());
}
// TODO extend annotation row to enable dynamic and static profile data to
// be stored
boolean validRes = false;
boolean validEnd = false;
boolean labelAllCols = false;
- // boolean centreColLabels;
- // boolean centreColLabelsDef = av.isCentreColumnLabels();
+ // boolean centreColLabels;
+ // boolean centreColLabelsDef = av.isCentreColumnLabels();
boolean scaleColLabel = false;
final AlignmentAnnotation consensusAnnot = av
.getAlignmentConsensusAnnotation();
renderProfile = av_renderProfile;
normaliseProfile = av_normaliseProfile;
}
+ else if (InformationThread.HMM_CALC_ID.equals(row.getCalcId()))
+ {
+ if (row.groupRef != null)
+ {
+ renderHistogram = row.groupRef.isShowInformationHistogram();
+ renderProfile = row.groupRef.isShowHMMSequenceLogo();
+ normaliseProfile = row.groupRef.isNormaliseHMMSequenceLogo();
+ }
+ else
+ {
+ renderHistogram = av.isShowInformationHistogram();
+ renderProfile = av.isShowHMMSequenceLogo();
+ normaliseProfile = av.isNormaliseHMMSequenceLogo();
+ }
+ }
+ else if (row == consensusAnnot || row == structConsensusAnnot
+ || row == complementConsensusAnnot)
+ {
+ renderHistogram = av_renderHistogram;
+ renderProfile = av_renderProfile;
+ normaliseProfile = av_normaliseProfile;
+ }
Annotation[] row_annotations = row.annotations;
if (!row.visible)
{
continue;
}
- // centreColLabels = row.centreColLabels || centreColLabelsDef;
+ // centreColLabels = row.centreColLabels || centreColLabelsDef;
labelAllCols = row.showAllColLabels;
scaleColLabel = row.scaleColLabel;
lastSS = ' ';
public class AnnotationColourGradient extends FollowerColourScheme
{
+ /**
+ * map positional scores to transparency rather than colour
+ */
+ boolean positionToTransparency = false;
+
+ /**
+ * compute shade based on annotation row score
+ */
+ boolean perLineScore = false;
+
public static final int NO_THRESHOLD = -1;
public static final int BELOW_THRESHOLD = 0;
acg.predefinedColours = predefinedColours;
acg.seqAssociated = seqAssociated;
acg.noGradient = noGradient;
+ acg.positionToTransparency = positionToTransparency;
+ acg.perLineScore = perLineScore;
return acg;
}
AnnotatedCollectionI alcontext = alignment instanceof AlignmentI
? alignment
: alignment.getContext();
- boolean f = true, rna = false;
- for (AlignmentAnnotation alan : alcontext
- .findAnnotation(annotation.getCalcId()))
+ boolean f = true, sf = true, rna = false;
+ long plcount = 0, ancount = 0;
+ for (AlignmentAnnotation alan : alcontext.findAnnotation(annotation
+ .getCalcId()))
{
if (alan.sequenceRef != null
&& (alan.label != null && annotation != null
&& alan.label.equals(annotation.label)))
{
+ ancount++;
if (!rna && alan.isRNA())
{
rna = true;
aamin = alan.graphMin;
}
f = false;
+ if (alan.score == alan.score)
+ {
+ if (sf || alan.score < plmin)
+ {
+ plmin = alan.score;
+ }
+ if (sf || alan.score > plmax)
+ {
+ plmax = alan.score;
+ }
+ sf = false;
+ plcount++;
+ }
}
}
+ if (plcount > 0 && plcount == ancount)
+ {
+ perLineScore = plmax!=plmin;
+ aamax=plmax;
+ }
+ else
+ {
+ perLineScore = false;
+ }
if (rna)
{
ColourSchemeProperty.initRnaHelicesShading(1 + (int) aamax);
}
}
- float aamin = 0f, aamax = 0f;
+ /**
+ * positional annotation max/min
+ */
+ double aamin = 0.0, aamax = 0.0;
+
+ /**
+ * per line score max/min
+ */
+ double plmin = Double.NaN, plmax = Double.NaN;
public AlignmentAnnotation getAnnotation()
{
{
range = ann.graphMax == ann.threshold.value ? 1f
: (value - ann.threshold.value)
- / (ann.graphMax - ann.threshold.value);
+ / (ann.graphMax - ann.threshold.value);
}
else if (thresholdIsMinMax && ann.threshold != null
&& aboveAnnotationThreshold == BELOW_THRESHOLD
}
}
- int dr = (int) (redRange * range + redMin);
- int dg = (int) (greenRange * range + greenMin);
- int db = (int) (blueRange * range + blueMin);
-
- return new Color(dr, dg, db);
+ // midtr sets the ceiling for bleaching out the shading
+ int trans = 0, midtr = 239;
+ if (perLineScore)
+ {
+ trans = (int) ((1f - range) * midtr);
+ range = (float) ((ann.score - plmin) / (plmax - aamin));
+ }
+ int dr = (int) (redRange * range + redMin),
+ dg = (int) (greenRange * range + greenMin),
+ db = (int) (blueRange * range + blueMin);
+ if (ann.score == ann.score && positionToTransparency)
+ {
+ return new Color(Math.min(dr + trans, midtr), Math.min(dg
+ + trans, midtr), Math.min(db + trans, midtr));
+ }
+ else
+ {
+ return new Color(dr, dg, db);
+ }
}
public boolean isPredefinedColours()
{
return false;
}
+
+ public boolean isPositionToTransparency()
+ {
+ return positionToTransparency;
+ }
+
+ public void setPositionToTransparency(boolean positionToTransparency)
+ {
+ this.positionToTransparency = positionToTransparency;
+ }
}
import java.util.Locale;
import jalview.api.AlignViewportI;
+import jalview.bin.ApplicationSingletonProvider;
+import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
import jalview.datamodel.AnnotatedCollectionI;
import jalview.datamodel.SequenceCollectionI;
import jalview.datamodel.SequenceI;
+import jalview.util.ColorUtils;
+import java.awt.Color;
import java.util.LinkedHashMap;
import java.util.Map;
-public class ColourSchemes
+public class ColourSchemes implements ApplicationSingletonI
{
- /*
- * singleton instance of this class
- */
- private static ColourSchemes instance = new ColourSchemes();
-
- /*
- * a map from scheme name (lower-cased) to an instance of it
- */
- private Map<String, ColourSchemeI> schemes;
/**
* Returns the singleton instance of this class
*/
public static ColourSchemes getInstance()
{
- return instance;
+ return (ColourSchemes) ApplicationSingletonProvider
+ .getInstance(ColourSchemes.class);
}
private ColourSchemes()
}
/**
+ * ColourSchemeProperty "static"
+ */
+ public Color[] rnaHelices = null;
+
+ /**
+ * delete the existing cached RNA helices colours
+ */
+ public static void resetRnaHelicesShading()
+ {
+ getInstance().rnaHelices = null;
+ }
+
+ public static void initRnaHelicesShading(int n)
+ {
+ int i = 0;
+ ColourSchemes j = getInstance();
+
+ if (j.rnaHelices == null)
+ {
+ j.rnaHelices = new Color[n + 1];
+ }
+ else if (j.rnaHelices != null && j.rnaHelices.length <= n)
+ {
+ Color[] t = new Color[n + 1];
+ System.arraycopy(j.rnaHelices, 0, t, 0, j.rnaHelices.length);
+ i = j.rnaHelices.length;
+ j.rnaHelices = t;
+ }
+ else
+ {
+ return;
+ }
+ // Generate random colors and store
+ for (; i <= n; i++)
+ {
+ j.rnaHelices[i] = ColorUtils.generateRandomColor(Color.white);
+ }
+ }
+
+ /**
+ * a map from scheme name (lower-cased) to an instance of it
+ */
+ private Map<String, ColourSchemeI> schemes;
+
+ /**
* Loads an instance of each standard or user-defined colour scheme
*
* @return
* represent
* @return
*/
- public ColourSchemeI getColourScheme(String name,
- AlignViewportI viewport, AnnotatedCollectionI forData,
+ public ColourSchemeI getColourScheme(String name, AlignViewportI viewport,
+ AnnotatedCollectionI forData,
Map<SequenceI, SequenceCollectionI> hiddenRepSequences)
{
if (name == null)
return null;
}
ColourSchemeI cs = schemes.get(name.toLowerCase(Locale.ROOT));
- return cs == null ? null
- : cs.getInstance(viewport, forData);
+ return cs == null ? null : cs.getInstance(viewport, forData);
}
/**
PID("% Identity", PIDColourScheme.class),
Zappo("Zappo", ZappoColourScheme.class),
Taylor("Taylor", TaylorColourScheme.class),
+ Flower("gecos:flower", FlowerColourScheme.class),
+ Blossom("gecos:blossom", BlossomColourScheme.class),
+ Sunset("gecos:sunset", SunsetColourScheme.class),
+ Ocean("gecos:ocean", OceanColourScheme.class),
Hydrophobic("Hydrophobic", HydrophobicColourScheme.class),
Helix("Helix Propensity", HelixColourScheme.class),
Strand("Strand Propensity", StrandColourScheme.class),
PurinePyrimidine("Purine/Pyrimidine", PurinePyrimidineColourScheme.class),
RNAHelices("RNA Helices", RNAHelicesColour.class),
TCoffee("T-Coffee Scores", TCoffeeColourScheme.class),
- IdColour("Sequence ID", IdColourScheme.class);
+ IdColour("Sequence ID", IdColourScheme.class),
+ HMMERU("HMMER-Uniprot", HmmerGlobalBackground.class),
+ HMMERA("HMMER-Alignment", HmmerLocalBackground.class),
+ HMMMatchScore("HMM Match Score", HMMMatchScoreColourScheme.class);
// RNAInteraction("RNA Interaction type", RNAInteractionColourScheme.class)
private String name;
public class ResidueProperties
{
+ // alphabet names used in Hidden Markov Model files
+ public static final String ALPHABET_RNA = "RNA";
+
+ public static final String ALPHABET_DNA = "DNA";
+
+ public static final String ALPHABET_AMINO = "amino";
+
// Stores residue codes/names and colours and other things
public static final int[] aaIndex; // aaHash version 2.1.1 and below
// lookup from modified amino acid (e.g. MSE) to canonical form (e.g. MET)
public static final Map<String, String> modifications = new HashMap<>();
+ // residue background frequencies across different alphabets
+ public static final Map<String, Map<Character, Float>> backgroundFrequencies = new HashMap<>();
+
static
{
aaIndex = new int[255];
Color.white // ' '
};
+ /*
+ * flower, blossom, sunset, ocean colour schemes from geocos.
+ * See https://gecos.biotite-python.org/
+ * https://raw.githubusercontent.com/biotite-dev/biotite/master/src/biotite/sequence/graphics/color_schemes/flower.json
+ * and https://bmcbioinformatics.biomedcentral.com/articles/10.1186/s12859-020-3526-6
+ * (https://doi.org/10.1186/s12859-020-3526-6)
+ */
+ public static final Color[] flower = { new Color(177, 138, 81), // A
+ new Color(131, 191, 241), // R
+ new Color(11, 206, 198), // N
+ new Color(1, 165, 120), // D
+ new Color(255, 87, 1), // C
+ new Color(114, 149, 174), // Q
+ new Color(45, 160, 161), // E
+ new Color(177, 194, 60), // G
+ new Color(1, 148, 249), // H
+ new Color(242, 118, 99), // I
+ new Color(223, 110, 117), // L
+ new Color(127, 195, 215), // K
+ new Color(254, 157, 175), // M
+ new Color(250, 85, 157), // F
+ new Color(79, 163, 42), // P
+ new Color(180, 189, 155), // S
+ new Color(210, 181, 118), // T
+ new Color(255, 45, 237), // W
+ new Color(201, 110, 207), // Y
+ new Color(253, 153, 123), // V
+ Color.white, // B
+ Color.white, // Z
+ Color.white, // X
+ Color.white, // -
+ Color.white, // *
+ Color.white // .
+ };
+
+ public static final Color[] blossom = { new Color(139, 196, 180), // A
+ new Color(252, 149, 2), // R
+ new Color(181, 194, 6), // N
+ new Color(95, 165, 5), // D
+ new Color(8, 147, 254), // C
+ new Color(191, 133, 39), // Q
+ new Color(219, 181, 1), // E
+ new Color(0, 211, 130), // G
+ new Color(255, 87, 1), // H
+ new Color(154, 186, 243), // I
+ new Color(205, 165, 220), // L
+ new Color(254, 165, 39), // K
+ new Color(245, 161, 184), // M
+ new Color(247, 79, 168), // F
+ new Color(16, 214, 49), // P
+ new Color(126, 157, 89), // S
+ new Color(0, 162, 156), // T
+ new Color(254, 8, 251), // W
+ new Color(255, 78, 122), // Y
+ new Color(135, 192, 228), // V
+ Color.white, // B
+ Color.white, // Z
+ Color.white, // X
+ Color.white, // -
+ Color.white, // *
+ Color.white // .
+ };
+
+ public static final Color[] sunset = { new Color(254, 160, 253), // A
+ new Color(133, 116, 106), // R
+ new Color(171, 200, 245), // N
+ new Color(46, 123, 190), // D
+ new Color(252, 12, 254), // C
+ new Color(140, 110, 129), // Q
+ new Color(103, 120, 146), // E
+ new Color(39, 153, 255), // G
+ new Color(219, 197, 142), // H
+ new Color(250, 33, 161), // I
+ new Color(224, 30, 130), // L
+ new Color(222, 190, 204), // K
+ new Color(209, 62, 123), // M
+ new Color(255, 56, 93), // F
+ new Color(87, 102, 249), // P
+ new Color(231, 180, 253), // S
+ new Color(166, 88, 183), // T
+ new Color(255, 55, 1), // W
+ new Color(203, 83, 57), // Y
+ new Color(254, 81, 184), // V
+ Color.white, // B
+ Color.white, // Z
+ Color.white, // X
+ Color.white, // -
+ Color.white, // *
+ Color.white // .
+ };
+
+ public static final Color[] ocean = { new Color(198, 202, 155), // A
+ new Color(12, 160, 168), // R
+ new Color(10, 223, 195), // N
+ new Color(76, 223, 161), // D
+ new Color(198, 129, 54), // C
+ new Color(139, 211, 209), // Q
+ new Color(96, 218, 201), // E
+ new Color(51, 165, 81), // G
+ new Color(0, 207, 254), // H
+ new Color(242, 186, 170), // I
+ new Color(187, 138, 131), // L
+ new Color(64, 160, 144), // K
+ new Color(164, 139, 136), // M
+ new Color(171, 136, 174), // F
+ new Color(175, 211, 101), // P
+ new Color(109, 155, 116), // S
+ new Color(141, 149, 102), // T
+ new Color(117, 138, 238), // W
+ new Color(186, 195, 252), // Y
+ new Color(233, 190, 164), // V
+ Color.white, // B
+ Color.white, // Z
+ Color.white, // X
+ Color.white, // -
+ Color.white, // *
+ Color.white // .
+ };
+
// Dunno where I got these numbers from
public static final double[] hyd2 = { 0.62, // A
0.29, // R
public static String STOP = "STOP";
- public static List<String> STOP_CODONS = Arrays.asList("TGA", "TAA", "TAG");
+ public static List<String> STOP_CODONS = Arrays.asList("TGA", "TAA",
+ "TAG");
public static String START = "ATG";
}
+ static
+ {
+ Map<Character, Float> amino = new HashMap<>();
+ amino.put('A', 0.0826f);
+ amino.put('Q', 0.0393f);
+ amino.put('L', 0.0965f);
+ amino.put('S', 0.0661f);
+ amino.put('R', 0.0553f);
+ amino.put('E', 0.0674f);
+ amino.put('K', 0.0582f);
+ amino.put('T', 0.0535f);
+ amino.put('N', 0.0406f);
+ amino.put('G', 0.0708f);
+ amino.put('M', 0.0241f);
+ amino.put('W', 0.0109f);
+ amino.put('D', 0.0546f);
+ amino.put('H', 0.0227f);
+ amino.put('F', 0.0386f);
+ amino.put('Y', 0.0292f);
+ amino.put('C', 0.0137f);
+ amino.put('I', 0.0593f);
+ amino.put('P', 0.0472f);
+ amino.put('V', 0.0686f);
+ backgroundFrequencies.put(ALPHABET_AMINO, amino);
+ // todo: these don't match https://www.ebi.ac.uk/uniprot/TrEMBLstats - what
+ // are they?
+ }
+
+ // TODO get correct frequencies
+
+ static
+ {
+ Map<Character, Float> dna = new HashMap<>();
+ dna.put('A', 0.25f);
+ dna.put('C', 0.25f);
+ dna.put('T', 0.25f);
+ dna.put('G', 0.25f);
+ backgroundFrequencies.put(ALPHABET_DNA, dna);
+
+ }
+
+ static
+ {
+ Map<Character, Float> rna = new HashMap<>();
+ rna.put('A', 0.25f);
+ rna.put('C', 0.25f);
+ rna.put('T', 0.25f);
+ rna.put('G', 0.25f);
+ backgroundFrequencies.put(ALPHABET_RNA, rna);
+
+ }
+
public static String getCanonicalAminoAcid(String aA)
{
String canonical = modifications.get(aA);
*/
package jalview.structure;
-import java.io.PrintStream;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.IdentityHashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Vector;
+
import jalview.analysis.AlignSeq;
import jalview.api.StructureSelectionManagerProvider;
+import jalview.bin.ApplicationSingletonProvider;
+import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.commands.CommandI;
import jalview.commands.EditCommand;
import jalview.commands.OrderCommand;
import jalview.ws.sifts.SiftsClient;
import jalview.ws.sifts.SiftsException;
import jalview.ws.sifts.SiftsSettings;
+
+import java.io.PrintStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.List;
++import java.util.Locale;
+import java.util.Map;
+import java.util.Vector;
+
import mc_view.Atom;
import mc_view.PDBChain;
import mc_view.PDBfile;
-public class StructureSelectionManager
+public class StructureSelectionManager implements ApplicationSingletonI
{
public final static String NEWLINE = System.lineSeparator();
- static IdentityHashMap<StructureSelectionManagerProvider, StructureSelectionManager> instances;
+
private List<StructureMapping> mappings = new ArrayList<>();
private boolean processSecondaryStructure = false;
private List<CommandListener> commandListeners = new ArrayList<>();
private List<SelectionListener> sel_listeners = new ArrayList<>();
-
+ /*
+ * instances of this class scoped by some context class
+ */
+ private IdentityHashMap<StructureSelectionManagerProvider, StructureSelectionManager> selectionManagers;
+
+ /**
+ * Answers an instance of this class for the current application (Java or JS
+ * 'applet') scope
+ *
+ * @return
+ */
+ private static StructureSelectionManager getInstance()
+ {
+ return (StructureSelectionManager) ApplicationSingletonProvider
+ .getInstance(StructureSelectionManager.class);
+ }
+
+ /**
+ * Private constructor as all 'singleton' instances are managed here or by
+ * ApplicationSingletonProvider
+ */
+ private StructureSelectionManager()
+ {
+ selectionManagers = new IdentityHashMap<>();
+ }
+
+ /**
+ * Answers an instance of this class for the current application (Java or JS
+ * 'applet') scope, and scoped to the specified context
+ *
+ * @param context
+ * @return
+ */
+ public static StructureSelectionManager getStructureSelectionManager(
+ StructureSelectionManagerProvider context)
+ {
+ return getInstance().getInstanceForContext(context);
+ }
+
+ /**
+ * Answers an instance of this class scoped to the given context. The instance
+ * is created on the first request for the context, thereafter the same
+ * instance is returned. Note that the context may be null (this is the case
+ * when running headless without a Desktop).
+ *
+ * @param context
+ * @return
+ */
+ StructureSelectionManager getInstanceForContext(
+ StructureSelectionManagerProvider context)
+ {
+ StructureSelectionManager instance = selectionManagers.get(context);
+ if (instance == null)
+ {
+ instance = new StructureSelectionManager();
+ selectionManagers.put(context, instance);
+ }
+ return instance;
+ }
++/** Null provider in 2.11.2
++
++
++ private static StructureSelectionManager nullProvider = null;
+
++ public static StructureSelectionManager getStructureSelectionManager(
++ StructureSelectionManagerProvider context)
++ {
++ if (context == null)
++ {
++ if (nullProvider == null)
++ {
++ if (instances != null)
++ {
++ throw new Error(MessageManager.getString(
++ "error.implementation_error_structure_selection_manager_null"),
++ new NullPointerException(MessageManager
++ .getString("exception.ssm_context_is_null")));
++ }
++ else
++ {
++ nullProvider = new StructureSelectionManager();
++ }
++ return nullProvider;
++ }
++ }
++ if (instances == null)
++ {
++ instances = new java.util.IdentityHashMap<>();
++ }
++ StructureSelectionManager instance = instances.get(context);
++ if (instance == null)
++ {
++ if (nullProvider != null)
++ {
++ instance = nullProvider;
++ }
++ else
++ {
++ instance = new StructureSelectionManager();
++ }
++ instances.put(context, instance);
++ }
++ return instance;
++ }
++*/
/**
* @return true if will try to use external services for processing secondary
|| pdbIdFileName.containsKey(idOrFile);
}
- private static StructureSelectionManager nullProvider = null;
-
- public static StructureSelectionManager getStructureSelectionManager(
- StructureSelectionManagerProvider context)
- {
- if (context == null)
- {
- if (nullProvider == null)
- {
- if (instances != null)
- {
- throw new Error(MessageManager.getString(
- "error.implementation_error_structure_selection_manager_null"),
- new NullPointerException(MessageManager
- .getString("exception.ssm_context_is_null")));
- }
- else
- {
- nullProvider = new StructureSelectionManager();
- }
- return nullProvider;
- }
- }
- if (instances == null)
- {
- instances = new java.util.IdentityHashMap<>();
- }
- StructureSelectionManager instance = instances.get(context);
- if (instance == null)
- {
- if (nullProvider != null)
- {
- instance = nullProvider;
- }
- else
- {
- instance = new StructureSelectionManager();
- }
- instances.put(context, instance);
- }
- return instance;
- }
-
/**
* flag controlling whether SeqMappings are relayed from received sequence
* mouse over events to other sequences
return relaySeqMappings;
}
- Vector listeners = new Vector();
+ Vector<Object> listeners = new Vector<>();
/**
* register a listener for alignment sequence mouseover events
* Import structure data and register a structure mapping for broadcasting
* colouring, mouseovers and selection events (convenience wrapper).
*
+ * This is the standard entry point.
+ *
* @param sequence
* - one or more sequences to be mapped to pdbFile
* @param targetChains
* @return null or the structure data parsed as a pdb file
*/
synchronized public StructureFile setMapping(SequenceI[] sequence,
- String[] targetChains, String pdbFile, DataSourceType protocol,
+ String[] targetChains, String pdbFile, DataSourceType protocol,
IProgressIndicator progress)
{
return computeMapping(true, sequence, targetChains, pdbFile, protocol,
* broadcasting colouring, mouseovers and selection events (convenience
* wrapper).
*
+ *
+ *
* @param forStructureView
- * when true, record the mapping for use in mouseOvers
+ * when true (testng only), record the mapping for use in mouseOvers
+ * (testng only)
* @param sequence
* - one or more sequences to be mapped to pdbFile
* @param targetChains
* mapping operation
* @return null or the structure data parsed as a pdb file
*/
- synchronized public StructureFile computeMapping(boolean forStructureView,
- SequenceI[] sequenceArray, String[] targetChainIds,
- String pdbFile, DataSourceType sourceType,
+ synchronized private StructureFile computeMapping(
+ boolean forStructureView, SequenceI[] sequenceArray,
+ String[] targetChainIds, String pdbFile, DataSourceType sourceType,
IProgressIndicator progress)
{
long progressSessionId = System.currentTimeMillis() * 3;
registerPDBFile(pdb.getId().trim(), pdbFile);
}
// if PDBId is unavailable then skip SIFTS mapping execution path
- // TODO: JAL-3868 need to know if structure is actually from
- // PDB (has valid PDB ID and has provenance suggesting it
+ // TODO: JAL-3868 need to know if structure is actually from
+ // PDB (has valid PDB ID and has provenance suggesting it
// actually came from PDB)
boolean isProtein = false;
- for (SequenceI s : sequenceArray)
- {
- if (s.isProtein())
- {
+ for (SequenceI s:sequenceArray) {
+ if (s.isProtein()) {
isProtein = true;
break;
}
}
- isMapUsingSIFTs = isMapUsingSIFTs && pdb.isPPDBIdAvailable()
- && !pdb.getId().startsWith("AF-") && isProtein;
+ isMapUsingSIFTs = isMapUsingSIFTs && pdb.isPPDBIdAvailable() && !pdb.getId().startsWith("AF-") && isProtein;
} catch (Exception ex)
{
} catch (SiftsException e)
{
isMapUsingSIFTs = false;
- Cache.log.error("SIFTS mapping failed", e);
- Cache.log.error("Falling back on Needleman & Wunsch alignment");
+ Console.error("SIFTS mapping failed", e);
+ Console.error("Falling back on Needleman & Wunsch alignment");
siftsClient = null;
}
List<StructureMapping> seqToStrucMapping = new ArrayList<>();
if (isMapUsingSIFTs && seq.isProtein())
{
- if (progress != null)
- {
- progress.setProgressBar(
- MessageManager
- .getString("status.obtaining_mapping_with_sifts"),
+ if (progress!=null) {
+ progress.setProgressBar(MessageManager
+ .getString("status.obtaining_mapping_with_sifts"),
progressSessionId);
}
jalview.datamodel.Mapping sqmpping = maxAlignseq
pdb, maxChain, sqmpping, maxAlignseq, siftsClient);
seqToStrucMapping.add(siftsMapping);
maxChain.makeExactMapping(siftsMapping, seq);
- maxChain.transferRESNUMFeatures(seq, "IEA: SIFTS");
+ maxChain.transferRESNUMFeatures(seq, "IEA: SIFTS",
+ pdb.getId().toLowerCase(Locale.ROOT));
maxChain.transferResidueAnnotation(siftsMapping, null);
ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
} catch (SiftsException e)
{
// fall back to NW alignment
- Cache.log.error(e.getMessage());
+ Console.error(e.getMessage());
StructureMapping nwMapping = getNWMappings(seq, pdbFile,
targetChainId, maxChain, pdb, maxAlignseq);
seqToStrucMapping.add(nwMapping);
maxChain.makeExactMapping(maxAlignseq, seq);
- maxChain.transferRESNUMFeatures(seq, "IEA:Jalview"); // FIXME: is
- // this
- // "IEA:Jalview" ?
+ maxChain.transferRESNUMFeatures(seq, "IEA:Jalview",
+ pdb.getId().toLowerCase(Locale.ROOT)); // FIXME: is
+ // this
+ // "IEA:Jalview" ?
maxChain.transferResidueAnnotation(nwMapping, sqmpping);
ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
}
StructureMapping siftsMapping = null;
try
{
- siftsMapping = getStructureMapping(seq, pdbFile, chain.id,
- pdb, chain, sqmpping, maxAlignseq, siftsClient);
+ siftsMapping = getStructureMapping(seq,
+ pdbFile, chain.id, pdb, chain, sqmpping, maxAlignseq,
+ siftsClient);
foundSiftsMappings.add(siftsMapping);
chain.makeExactMapping(siftsMapping, seq);
- chain.transferRESNUMFeatures(seq, "IEA: SIFTS");// FIXME: is this
+ chain.transferRESNUMFeatures(seq, "IEA: SIFTS",
+ pdb.getId().toLowerCase(Locale.ROOT));// FIXME: is this
// "IEA:SIFTS" ?
chain.transferResidueAnnotation(siftsMapping, null);
} catch (SiftsException e)
{
System.err.println(e.getMessage());
- } catch (Exception e)
+ }
+ catch (Exception e)
{
- System.err.println(
- "Unexpected exception during SIFTS mapping - falling back to NW for this sequence/structure pair");
+ System.err
+ .println(
+ "Unexpected exception during SIFTS mapping - falling back to NW for this sequence/structure pair");
System.err.println(e.getMessage());
}
}
StructureMapping nwMapping = getNWMappings(seq, pdbFile,
maxChainId, maxChain, pdb, maxAlignseq);
seqToStrucMapping.add(nwMapping);
- maxChain.transferRESNUMFeatures(seq, null); // FIXME: is this
- // "IEA:Jalview" ?
+ maxChain.transferRESNUMFeatures(seq, null,
+ pdb.getId().toLowerCase(Locale.ROOT)); // FIXME: is this
+ // "IEA:Jalview" ?
maxChain.transferResidueAnnotation(nwMapping, sqmpping);
ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
}
{
if (progress != null)
{
- progress.setProgressBar(
- MessageManager.getString(
- "status.obtaining_mapping_with_nw_alignment"),
+ progress.setProgressBar(MessageManager
+ .getString("status.obtaining_mapping_with_nw_alignment"),
progressSessionId);
}
StructureMapping nwMapping = getNWMappings(seq, pdbFile, maxChainId,
{
ds = ds.getDatasetSequence();
}
+ ;
if (ds.getAnnotation() != null)
{
for (AlignmentAnnotation ala : ds.getAnnotation())
private StructureMapping getStructureMapping(SequenceI seq,
String pdbFile, String targetChainId, StructureFile pdb,
PDBChain maxChain, jalview.datamodel.Mapping sqmpping,
- AlignSeq maxAlignseq, SiftsClient siftsClient)
- throws SiftsException
+ AlignSeq maxAlignseq, SiftsClient siftsClient) throws SiftsException
{
StructureMapping curChainMapping = siftsClient
.getSiftsStructureMapping(seq, pdbFile, targetChainId);
maxChain.makeExactMapping(maxAlignseq, seq);
jalview.datamodel.Mapping sqmpping = maxAlignseq
.getMappingFromS1(false);
- maxChain.transferRESNUMFeatures(seq, null);
+ maxChain.transferRESNUMFeatures(seq, null,
+ pdb.getId().toLowerCase(Locale.ROOT));
HashMap<Integer, int[]> mapping = new HashMap<>();
int resNum = -10000;
if (s != null)
{
result = s;
+ }
}
}
- }
return result;
}
}
/**
- * Resets this object to its initial state by removing all registered
- * listeners, codon mappings, PDB file mappings
+ * Reset this object to its initial state by removing all registered
+ * listeners, codon mappings, PDB file mappings.
+ *
+ * Called only by Desktop and testng.
+ *
*/
public void resetAll()
{
}
}
- public void addSelectionListener(SelectionListener selecter)
+ public List<SelectionListener> getListeners() {
+ return sel_listeners;
+ }
+
+ public void addSelectionListener(SelectionListener selecter)
{
if (!sel_listeners.contains(selecter))
{
{
slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
}
-
+ ;
}
}
}
+
/**
- * release all references associated with this manager provider
+ * Removes the instance associated with this provider
*
- * @param jalviewLite
+ * @param provider
*/
-
- public static void release(StructureSelectionManagerProvider jalviewLite)
+ public static void release(StructureSelectionManagerProvider provider)
{
- // synchronized (instances)
- {
- if (instances == null)
- {
- return;
- }
- StructureSelectionManager mnger = (instances.get(jalviewLite));
- if (mnger != null)
- {
- instances.remove(jalviewLite);
- try
- {
- /* bsoares 2019-03-20 finalize deprecated, no apparent external
- * resources to close
- */
- // mnger.finalize();
- } catch (Throwable x)
- {
- }
- }
- }
+ getInstance().selectionManagers.remove(provider);
}
-
+
public void registerPDBEntry(PDBEntry pdbentry)
{
if (pdbentry.getFile() != null
* @return hashmap of identifiers.org data, keyed by MIRIAM id
*/
@SuppressWarnings("unchecked")
- private HashMap<String, UrlLink> readIdentifiers(String idFileName)
+ private HashMap<String, UrlLink> readIdentifiers(String idFileName)
{
// identifiers.org data
HashMap<String, UrlLink> idData = new HashMap<>();
String errorMessage = null;
try
{
- // NOTE: THIS WILL FAIL IN SWINGJS BECAUSE IT INVOLVES A FILE READER
-
+ // NOTE: THIS WILL FAIL IN SWINGJS BECAUSE IT INVOLVES A FILE READER
-
FileReader reader = new FileReader(idFileName);
String key = "";
- Map<String, Object> obj = (Map<String, Object>) JSONUtils.parse(reader);
+ Map<String, Object> obj = (Map<String, Object>) JSONUtils
+ .parse(reader);
if (obj.containsKey(ID_ORG_KEY))
{
key = ID_ORG_KEY;
}
} catch (IOException | ParseException e)
{
- // unnecessary e.printStackTrace();
- // Note how in JavaScript we can grab the first bytes from any file
- // reader.
- // Typical report here is "NetworkError" because the file does not exist.
- // "https://." is coming from System.getProperty("user.home"), but this
- // could
- // be set by the page developer to anything, of course.
errorMessage = e.toString();
idData.clear();
}
// BH 2018 -- added more valuable report
if (errorMessage != null)
{
- System.err.println("IdentifiersUrlProvider: cannot read " + idFileName + ": " + errorMessage);
+ System.err.println("IdentifiersUrlProvider: cannot read " + idFileName
+ + ": " + errorMessage);
}
return idData;
}
*/
package jalview.util;
- import java.io.File;
+ import java.awt.Desktop;
import java.io.IOException;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Field;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
+ import java.net.URI;
+ import java.net.URISyntaxException;
+ import java.util.ArrayList;
+ import java.util.List;
+
+ import jalview.bin.Cache;
+ import jalview.bin.Console;
- /**
- * BrowserLauncher is a class that provides one static method, openURL, which
- * opens the default web browser for the current user of the system to the given
- * URL. It may support other protocols depending on the system -- mailto, ftp,
- * etc. -- but that has not been rigorously tested and is not guaranteed to
- * work.
- * <p>
- * Yes, this is platform-specific code, and yes, it may rely on classes on
- * certain platforms that are not part of the standard JDK. What we're trying to
- * do, though, is to take something that's frequently desirable but inherently
- * platform-specific -- opening a default browser -- and allow programmers (you,
- * for example) to do so without worrying about dropping into native code or
- * doing anything else similarly evil.
- * <p>
- * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant
- * systems without modification or a need for additional libraries. All classes
- * that are required on certain platforms to allow this to run are dynamically
- * loaded at runtime via reflection and, if not found, will not cause this to do
- * anything other than returning an error when opening the browser.
- * <p>
- * There are certain system requirements for this class, as it's running through
- * Runtime.exec(), which is Java's way of making a native system call.
- * Currently, this requires that a Macintosh have a Finder which supports the
- * GURL event, which is true for Mac OS 8.0 and 8.1 systems that have the
- * Internet Scripting AppleScript dictionary installed in the Scripting
- * Additions folder in the Extensions folder (which is installed by default as
- * far as I know under Mac OS 8.0 and 8.1), and for all Mac OS 8.5 and later
- * systems. On Windows, it only runs under Win32 systems (Windows 95, 98, and NT
- * 4.0, as well as later versions of all). On other systems, this drops back
- * from the inherently platform-sensitive concept of a default browser and
- * simply attempts to launch Netscape via a shell command.
- * <p>
- * This code is Copyright 1999-2001 by Eric Albert (ejalbert\@cs.stanford.edu)
- * and may be redistributed or modified in any form without restrictions as long
- * as the portion of this comment from this paragraph through the end of the
- * comment is not removed. The author requests that he be notified of any
- * application, applet, or other binary that makes use of this code, but that's
- * more out of curiosity than anything and is not required. This software
- * includes no warranty. The author is not repsonsible for any loss of data or
- * functionality or any adverse or unexpected effects of using this software.
- * <p>
- * Credits: <br>
- * Steven Spencer, JavaWorld magazine
- * (<a href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java
- * Tip 66</a>) <br>
- * Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea
- * Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
- *
- * @author Eric Albert (<a href=
- * "mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
- * @version 1.4b1 (Released June 20, 2001)
- */
public class BrowserLauncher
{
- /**
- * The Java virtual machine that we are running on. Actually, in most cases we
- * only care about the operating system, but some operating systems require us
- * to switch on the VM.
- */
- private static int jvm;
-
- /** The browser for the system */
- private static Object browser;
-
- /**
- * Caches whether any classes, methods, and fields that are not part of the
- * JDK and need to be dynamically loaded at runtime loaded successfully.
- * <p>
- * Note that if this is <code>false</code>, <code>openURL()</code> will always
- * return an IOException.
- */
- private static boolean loadedWithoutErrors;
-
- /** The com.apple.mrj.MRJFileUtils class */
- private static Class mrjFileUtilsClass;
-
- /** The com.apple.mrj.MRJOSType class */
- private static Class mrjOSTypeClass;
-
- /** The com.apple.MacOS.AEDesc class */
- private static Class aeDescClass;
-
- /** The <init>(int) method of com.apple.MacOS.AETarget */
- private static Constructor aeTargetConstructor;
-
- /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
- private static Constructor appleEventConstructor;
-
- /** The <init>(String) method of com.apple.MacOS.AEDesc */
- private static Constructor aeDescConstructor;
-
- /** The findFolder method of com.apple.mrj.MRJFileUtils */
- private static Method findFolder;
-
- /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
- private static Method getFileCreator;
-
- /** The getFileType method of com.apple.mrj.MRJFileUtils */
- private static Method getFileType;
-
- /** The openURL method of com.apple.mrj.MRJFileUtils */
- private static Method openURL;
-
- /** The makeOSType method of com.apple.MacOS.OSUtils */
- private static Method makeOSType;
-
- /** The putParameter method of com.apple.MacOS.AppleEvent */
- private static Method putParameter;
-
- /** The sendNoReply method of com.apple.MacOS.AppleEvent */
- private static Method sendNoReply;
-
- /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
- private static Object kSystemFolderType;
-
- /** The keyDirectObject AppleEvent parameter type */
- private static Integer keyDirectObject;
-
- /** The kAutoGenerateReturnID AppleEvent code */
- private static Integer kAutoGenerateReturnID;
-
- /** The kAnyTransactionID AppleEvent code */
- private static Integer kAnyTransactionID;
-
- /** The linkage object required for JDirect 3 on Mac OS X. */
- private static Object linkage;
-
- /** The framework to reference on Mac OS X */
- private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
-
- /** JVM constant for MRJ 2.0 */
- private static final int MRJ_2_0 = 0;
-
- /** JVM constant for MRJ 2.1 or later */
- private static final int MRJ_2_1 = 1;
-
- /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
- private static final int MRJ_3_0 = 3;
-
- /** JVM constant for MRJ 3.1 */
- private static final int MRJ_3_1 = 4;
-
- /** JVM constant for any Windows NT JVM */
- private static final int WINDOWS_NT = 5;
-
- /** JVM constant for any Windows 9x JVM */
- private static final int WINDOWS_9x = 6;
-
- /** JVM constant for any other platform */
- private static final int OTHER = -1;
-
- /**
- * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep
- * non-U.S. English systems from working properly.
- */
- private static final String FINDER_TYPE = "FNDR";
-
- /**
- * The creator code of the Finder on a Macintosh, which is needed to send
- * AppleEvents to the application.
- */
- private static final String FINDER_CREATOR = "MACS";
-
- /** The name for the AppleEvent type corresponding to a GetURL event. */
- private static final String GURL_EVENT = "GURL";
-
- /**
- * The first parameter that needs to be passed into Runtime.exec() to open the
- * default web browser on Windows.
- */
- private static final String FIRST_WINDOWS_PARAMETER = "/c";
-
- /** The second parameter for Runtime.exec() on Windows. */
- private static final String SECOND_WINDOWS_PARAMETER = "start";
-
- /**
- * The third parameter for Runtime.exec() on Windows. This is a "title"
- * parameter that the command line expects. Setting this parameter allows URLs
- * containing spaces to work.
- */
- private static final String THIRD_WINDOWS_PARAMETER = "\"\"";
+ private static BrowserLauncher INSTANCE = null;
- /**
- * The shell parameters for Netscape that opens a given URL in an already-open
- * copy of Netscape on many command-line systems.
- */
- private static final String NETSCAPE_REMOTE_PARAMETER = "-remote";
+ private static String preferredBrowser = null;
- private static final String NETSCAPE_OPEN_PARAMETER_START = "openURL(";
-
- private static final String NETSCAPE_OPEN_NEW_WINDOW = ", new-window";
-
- private static final String NETSCAPE_OPEN_PARAMETER_END = ")";
-
- /**
- * The message from any exception thrown throughout the initialization
- * process.
- */
- private static String errorMessage;
-
- /**
- * An initialization block that determines the operating system and loads the
- * necessary runtime data.
- */
- static
+ public static BrowserLauncher getInstance()
{
-
- loadedWithoutErrors = true;
-
- if (!Platform.isJS())
- /**
- * Java only
- *
- * @j2sIgnore
- *
- */
+ if (INSTANCE != null)
{
- String osName = System.getProperty("os.name");
-
- if (osName.startsWith("Mac OS"))
- {
- String mrjVersion = System.getProperty("mrj.version");
- String majorMRJVersion;
- if (mrjVersion == null)
- {
- // must be on some later build with mrj support
- majorMRJVersion = "3.1";
- }
- else
- {
- majorMRJVersion = mrjVersion.substring(0, 3);
- }
-
- try
- {
- double version = Double.valueOf(majorMRJVersion).doubleValue();
-
- if (version == 2)
- {
- jvm = MRJ_2_0;
- }
- else if ((version >= 2.1) && (version < 3))
- {
- // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
- // works via Runtime.exec() and 2.2 supports that but has an openURL()
- // method
- // as well that we currently ignore.
- jvm = MRJ_2_1;
- }
- else if (version == 3.0)
- {
- jvm = MRJ_3_0;
- }
- else if (version >= 3.1)
- {
- // Assume that all 3.1 and later versions of MRJ work the same.
- jvm = MRJ_3_1;
- }
- else
- {
- loadedWithoutErrors = false;
- errorMessage = "Unsupported MRJ version: " + version;
- }
- } catch (NumberFormatException nfe)
- {
- loadedWithoutErrors = false;
- errorMessage = "Invalid MRJ version: " + mrjVersion;
- }
- }
- else if (osName.startsWith("Windows"))
- {
- if (osName.indexOf("9") != -1)
- {
- jvm = WINDOWS_9x;
- }
- else
- {
- jvm = WINDOWS_NT;
- }
- }
- else
- {
- jvm = OTHER;
- }
-
- if (loadedWithoutErrors)
- { // if we haven't hit any errors yet
- loadedWithoutErrors = loadClasses();
- }
+ return INSTANCE;
}
+ INSTANCE = new BrowserLauncher();
+ return INSTANCE;
}
- /**
- * This class should be never be instantiated; this just ensures so.
- */
- private BrowserLauncher()
+ public static void openURL(String url)
{
- }
-
- /**
- * Called by a static initializer to load any classes, fields, and methods
- * required at runtime to locate the user's web browser.
- *
- * @return <code>true</code> if all intialization succeeded <code>false</code>
- * if any portion of the initialization failed
- */
- private static boolean loadClasses()
- {
-
- if (!Platform.isJS())
- /**
- * Java only
- *
- * @j2sIgnore
- *
- */
- {
- switch (jvm)
+ if (Platform.isJS())
{
- case MRJ_2_0:
-
- try
- {
- Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
- Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
- Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
- Class aeClass = Class.forName("com.apple.MacOS.ae");
- aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
-
- aeTargetConstructor = aeTargetClass
- .getDeclaredConstructor(new Class[]
- { int.class });
- appleEventConstructor = appleEventClass
- .getDeclaredConstructor(new Class[]
- { int.class, int.class, aeTargetClass, int.class,
- int.class });
- aeDescConstructor = aeDescClass
- .getDeclaredConstructor(new Class[]
- { String.class });
-
- makeOSType = osUtilsClass.getDeclaredMethod("makeOSType",
- new Class[]
- { String.class });
- putParameter = appleEventClass.getDeclaredMethod("putParameter",
- new Class[]
- { int.class, aeDescClass });
- sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply",
- new Class[] {});
-
- Field keyDirectObjectField = aeClass
- .getDeclaredField("keyDirectObject");
- keyDirectObject = (Integer) keyDirectObjectField.get(null);
-
- Field autoGenerateReturnIDField = appleEventClass
- .getDeclaredField("kAutoGenerateReturnID");
- kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField
- .get(null);
-
- Field anyTransactionIDField = appleEventClass
- .getDeclaredField("kAnyTransactionID");
- kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
- } catch (ClassNotFoundException cnfe)
- {
- errorMessage = cnfe.getMessage();
-
- return false;
- } catch (NoSuchMethodException nsme)
- {
- errorMessage = nsme.getMessage();
-
- return false;
- } catch (NoSuchFieldException nsfe)
- {
- errorMessage = nsfe.getMessage();
-
- return false;
- } catch (IllegalAccessException iae)
- {
- errorMessage = iae.getMessage();
-
- return false;
- }
-
- break;
-
- case MRJ_2_1:
-
- try
- {
- mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
- mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
-
- Field systemFolderField = mrjFileUtilsClass
- .getDeclaredField("kSystemFolderType");
- kSystemFolderType = systemFolderField.get(null);
- findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder",
- new Class[]
- { mrjOSTypeClass });
- getFileCreator = mrjFileUtilsClass
- .getDeclaredMethod("getFileCreator", new Class[]
- { File.class });
- getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType",
- new Class[]
- { File.class });
- } catch (ClassNotFoundException cnfe)
- {
- errorMessage = cnfe.getMessage();
-
- return false;
- } catch (NoSuchFieldException nsfe)
- {
- errorMessage = nsfe.getMessage();
-
- return false;
- } catch (NoSuchMethodException nsme)
- {
- errorMessage = nsme.getMessage();
-
- return false;
- } catch (SecurityException se)
- {
- errorMessage = se.getMessage();
-
- return false;
- } catch (IllegalAccessException iae)
- {
- errorMessage = iae.getMessage();
-
- return false;
- }
-
- break;
-
- case MRJ_3_0:
-
- try
- {
- Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
- Constructor constructor = linker
- .getConstructor(new Class[]
- { Class.class });
- linkage = constructor
- .newInstance(new Object[]
- { BrowserLauncher.class });
- } catch (ClassNotFoundException cnfe)
- {
- errorMessage = cnfe.getMessage();
-
- return false;
- } catch (NoSuchMethodException nsme)
- {
- errorMessage = nsme.getMessage();
-
- return false;
- } catch (InvocationTargetException ite)
- {
- errorMessage = ite.getMessage();
-
- return false;
- } catch (InstantiationException ie)
- {
- errorMessage = ie.getMessage();
-
- return false;
- } catch (IllegalAccessException iae)
- {
- errorMessage = iae.getMessage();
-
- return false;
- }
-
- break;
-
- case MRJ_3_1:
-
- try
- {
- mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
- openURL = mrjFileUtilsClass.getDeclaredMethod("openURL",
- new Class[]
- { String.class });
- } catch (ClassNotFoundException cnfe)
- {
- errorMessage = cnfe.getMessage();
-
- return false;
- } catch (NoSuchMethodException nsme)
- {
- errorMessage = nsme.getMessage();
-
- return false;
- }
-
- break;
-
- default:
- break;
- }
-
- Platform.openURL(url);
++ try {
++ Platform.openURL(url);
++ } catch (Throwable t) {
++ System.err.println("Couldn't open "+url);
++ System.err.print(t.getStackTrace());
++ }
+ return;
}
- return true;
- }
-
- /**
- * Attempts to locate the default web browser on the local system. s results
- * so it only locates the browser once for each use of this class per JVM
- * instance.
- *
- * @return The browser for the system. Note that this may not be what you
- * would consider to be a standard web browser; instead, it's the
- * application that gets called to open the default web browser. In
- * some cases, this will be a non-String object that provides the
- * means of calling the default browser.
- */
- private static Object locateBrowser()
- {
- if (!Platform.isJS())
+ else
/**
* Java only
*
* @j2sIgnore
- *
*/
{
- if (browser != null)
- {
- return browser;
- }
-
- switch (jvm)
- {
- case MRJ_2_0:
-
- try
- {
- Integer finderCreatorCode = (Integer) makeOSType.invoke(null,
- new Object[]
- { FINDER_CREATOR });
- Object aeTarget = aeTargetConstructor
- .newInstance(new Object[]
- { finderCreatorCode });
- Integer gurlType = (Integer) makeOSType.invoke(null,
- new Object[]
- { GURL_EVENT });
- Object appleEvent = appleEventConstructor
- .newInstance(new Object[]
- { gurlType, gurlType, aeTarget, kAutoGenerateReturnID,
- kAnyTransactionID });
-
- // Don't set browser = appleEvent because then the next time we call
- // locateBrowser(), we'll get the same AppleEvent, to which we'll
- // already have
- // added the relevant parameter. Instead, regenerate the AppleEvent
- // every time.
- // There's probably a way to do this better; if any has any ideas,
- // please let
- // me know.
- return appleEvent;
- } catch (IllegalAccessException iae)
- {
- browser = null;
- errorMessage = iae.getMessage();
-
- return browser;
- } catch (InstantiationException ie)
- {
- browser = null;
- errorMessage = ie.getMessage();
-
- return browser;
- } catch (InvocationTargetException ite)
- {
- browser = null;
- errorMessage = ite.getMessage();
-
- return browser;
- }
-
- case MRJ_2_1:
-
- File systemFolder;
-
- try
- {
- systemFolder = (File) findFolder.invoke(null,
- new Object[]
- { kSystemFolderType });
- } catch (IllegalArgumentException iare)
- {
- browser = null;
- errorMessage = iare.getMessage();
-
- return browser;
- } catch (IllegalAccessException iae)
- {
- browser = null;
- errorMessage = iae.getMessage();
-
- return browser;
- } catch (InvocationTargetException ite)
- {
- browser = null;
- errorMessage = ite.getTargetException().getClass() + ": "
- + ite.getTargetException().getMessage();
-
- return browser;
- }
-
- String[] systemFolderFiles = systemFolder.list();
-
- // Avoid a FilenameFilter because that can't be stopped mid-list
- for (int i = 0; i < systemFolderFiles.length; i++)
+ Desktop d = Desktop.getDesktop();
+ if (d != null && d.isSupported(Desktop.Action.BROWSE))
{
try
{
- File file = new File(systemFolder, systemFolderFiles[i]);
-
- if (!file.isFile())
- {
- continue;
- }
-
- // We're looking for a file with a creator code of 'MACS' and
- // a type of 'FNDR'. Only requiring the type results in non-Finder
- // applications being picked up on certain Mac OS 9 systems,
- // especially German ones, and sending a GURL event to those
- // applications results in a logout under Multiple Users.
- Object fileType = getFileType.invoke(null, new Object[] { file });
-
- if (FINDER_TYPE.equals(fileType.toString()))
- {
- Object fileCreator = getFileCreator.invoke(null,
- new Object[]
- { file });
-
- if (FINDER_CREATOR.equals(fileCreator.toString()))
- {
- browser = file.toString(); // Actually the Finder, but that's OK
-
- return browser;
- }
- }
- } catch (IllegalArgumentException iare)
- {
- errorMessage = iare.getMessage();
-
- return null;
- } catch (IllegalAccessException iae)
+ d.browse(new URI(url));
+ } catch (IOException e)
{
- browser = null;
- errorMessage = iae.getMessage();
-
- return browser;
- } catch (InvocationTargetException ite)
+ Console.warn(MessageManager.formatMessage(
+ "exception.browser_unable_to_launch", url));
+ Console.warn(e.getMessage());
+ Console.debug(Cache.getStackTraceString(e));
+ } catch (URISyntaxException e1)
{
- browser = null;
- errorMessage = ite.getTargetException().getClass() + ": "
- + ite.getTargetException().getMessage();
-
- return browser;
+ Console.warn(MessageManager.formatMessage(
+ "exception.browser_unable_to_launch", url));
+ Console.warn(e1.getMessage());
+ Console.debug(Cache.getStackTraceString(e1));
}
}
-
- browser = null;
-
- break;
-
- case MRJ_3_0:
- case MRJ_3_1:
- browser = ""; // Return something non-null
-
- break;
-
- case WINDOWS_NT:
- browser = "cmd.exe";
-
- break;
-
- case WINDOWS_9x:
- browser = "command.com";
-
- break;
-
- case OTHER:
- default:
- browser = jalview.bin.Cache.getDefault("DEFAULT_BROWSER", "firefox");
-
- break;
- }
-
+ else
+ {
+ Console.warn(MessageManager
+ .formatMessage("exception.browser_os_not_supported", url));
+ }
}
-
- return browser;
-
}
- /**
- * used to ensure that browser is up-to-date after a configuration change
- * (Unix DEFAULT_BROWSER property change).
- */
public static void resetBrowser()
{
- browser = null;
+ resetBrowser(false);
}
- /**
- * Attempts to open the default web browser to the given URL.
- *
- * @param url
- * The URL to open
- * @throws IOException
- * If the web browser could not be located or does not run
- */
- public static void openURL(String url) throws IOException
+ public static void resetBrowser(boolean removeIfNull)
{
-
- if (Platform.isJS())
- {
- Platform.openURL(url);
- return;
- }
- else
- /**
- * Java only
- *
- * @j2sIgnore
- */
- {
-
- if (!loadedWithoutErrors)
+ String defaultBrowser = Cache.getProperty("DEFAULT_BROWSER");
+ preferredBrowser = defaultBrowser;
+ // System.setProperty(getBrowserSystemProperty(),
+ // Cache.getProperty("DEFAULT_BROWSER"));
+ if (defaultBrowser == null && removeIfNull)
{
- throw new IOException(MessageManager
- .formatMessage("exception.browser_not_found", new String[]
- { errorMessage }));
+ // System.clearProperty(getBrowserSystemProperty());
}
- Object browser = locateBrowser();
-
- if (browser == null)
- {
- throw new IOException(MessageManager.formatMessage(
- "exception.browser_unable_to_locate", new String[]
- { errorMessage }));
- }
-
- switch (jvm)
- {
- case MRJ_2_0:
-
- Object aeDesc = null;
-
- try
- {
- aeDesc = aeDescConstructor.newInstance(new Object[] { url });
- putParameter.invoke(browser,
- new Object[]
- { keyDirectObject, aeDesc });
- sendNoReply.invoke(browser, new Object[] {});
- } catch (InvocationTargetException ite)
- {
- throw new IOException(MessageManager.formatMessage(
- "exception.invocation_target_exception_creating_aedesc",
- new String[]
- { ite.getMessage() }));
- } catch (IllegalAccessException iae)
- {
- throw new IOException(MessageManager.formatMessage(
- "exception.illegal_access_building_apple_evt", new String[]
- { iae.getMessage() }));
- } catch (InstantiationException ie)
- {
- throw new IOException(MessageManager.formatMessage(
- "exception.illegal_access_building_apple_evt", new String[]
- { ie.getMessage() }));
- } finally
- {
- aeDesc = null; // Encourage it to get disposed if it was created
- browser = null; // Ditto
- }
-
- break;
-
- case MRJ_2_1:
- Runtime.getRuntime().exec(new String[] { (String) browser, url });
-
- break;
-
- case MRJ_3_0:
-
- int[] instance = new int[1];
- int result = ICStart(instance, 0);
-
- if (result == 0)
- {
- int[] selectionStart = new int[] { 0 };
- byte[] urlBytes = url.getBytes();
- int[] selectionEnd = new int[] { urlBytes.length };
- result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes,
- urlBytes.length, selectionStart, selectionEnd);
-
- if (result == 0)
- {
- // Ignore the return value; the URL was launched successfully
- // regardless of what happens here.
- ICStop(instance);
- }
- else
- {
- throw new IOException(MessageManager.formatMessage(
- "exception.unable_to_launch_url", new String[]
- { Integer.valueOf(result).toString() }));
- }
- }
- else
- {
- throw new IOException(MessageManager.formatMessage(
- "exception.unable_to_create_internet_config", new String[]
- { Integer.valueOf(result).toString() }));
- }
-
- break;
-
- case MRJ_3_1:
-
- try
- {
- openURL.invoke(null, new Object[] { url });
- } catch (InvocationTargetException ite)
- {
- throw new IOException(MessageManager.formatMessage(
- "exception.invocation_target_calling_url", new String[]
- { ite.getMessage() }));
- } catch (IllegalAccessException iae)
- {
- throw new IOException(MessageManager.formatMessage(
- "exception.illegal_access_calling_url", new String[]
- { iae.getMessage() }));
- }
-
- break;
-
- case WINDOWS_NT:
- case WINDOWS_9x:
-
- // Add quotes around the URL to allow ampersands and other special
- // characters to work.
- Process process = Runtime.getRuntime()
- .exec(new String[]
- { (String) browser, FIRST_WINDOWS_PARAMETER,
- SECOND_WINDOWS_PARAMETER, THIRD_WINDOWS_PARAMETER,
- '"' + url + '"' });
-
- // This avoids a memory leak on some versions of Java on Windows.
- // That's hinted at in
- // <http://developer.java.sun.com/developer/qow/archive/68/>.
- try
- {
- process.waitFor();
- process.exitValue();
- } catch (InterruptedException ie)
- {
- throw new IOException(MessageManager.formatMessage(
- "exception.interrupted_launching_browser", new String[]
- { ie.getMessage() }));
- }
-
- break;
-
- case OTHER:
-
- // Assume that we're on Unix and that Netscape (actually Firefox) is
- // installed
- // First, attempt to open the URL in a currently running session of
- // Netscape
- // JBPNote log debug
-
- /*
- * System.out.println("Executing : "+browser+" "+
- * NETSCAPE_REMOTE_PARAMETER+" "+ NETSCAPE_OPEN_PARAMETER_START + url +
- * NETSCAPE_OPEN_NEW_WINDOW + NETSCAPE_OPEN_PARAMETER_END);
- */
- process = Runtime.getRuntime()
- .exec(new String[]
- { (String) browser, NETSCAPE_REMOTE_PARAMETER,
-
- NETSCAPE_OPEN_PARAMETER_START + url
- + NETSCAPE_OPEN_NEW_WINDOW
- + NETSCAPE_OPEN_PARAMETER_END });
-
- try
- {
- int exitCode = process.waitFor();
-
- if (exitCode != 0)
- { // if Netscape was not open
- Runtime.getRuntime().exec(new String[] { (String) browser, url });
- }
- } catch (InterruptedException ie)
- {
- throw new IOException(MessageManager.formatMessage(
- "exception.interrupted_launching_browser", new String[]
- { ie.getMessage() }));
- }
-
- break;
-
- default:
-
- // This should never occur, but if it does, we'll try the simplest thing
- // possible
- Runtime.getRuntime().exec(new String[] { (String) browser, url });
-
- break;
- }
- }
}
+ public static List<String> getBrowserList()
+ {
+ return new ArrayList<String>();
+ }
- /**
- * Methods required for Mac OS X. The presence of native methods does not
- * cause any problems on other platforms.
- */
- private native static int ICStart(int[] instance, int signature);
-
- private native static int ICStop(int[] instance);
+ public static String getBrowserSystemProperty()
+ {
+ // return IBrowserLaunching.BROWSER_SYSTEM_PROPERTY;
+ return "jalview.default.browser";
+ }
- private native static int ICLaunchURL(int instance, byte[] hint,
- byte[] data, int len, int[] selectionStart, int[] selectionEnd);
-}
+}
public class ColorUtils
{
private static final int MAX_CACHE_SIZE = 1729;
+
/*
* a cache for colours generated from text strings
*/
colour = colour.trim();
Color col = null;
- try
- {
- int value = Integer.parseInt(colour, 16);
- col = new Color(value);
- } catch (NumberFormatException ex)
+ if (StringUtils.isHexString(colour))
{
+ try
+ {
+ int value = Integer.parseInt(colour, 16);
+ col = new Color(value);
+ } catch (NumberFormatException ex)
+ {
+ }
}
if (col == null)
*/
public static final boolean isGap(char c)
{
- return (c == GAP_DASH || c == GAP_DOT || c == GAP_SPACE) ? true : false;
+ return (c == GAP_DASH || c == GAP_DOT || c == GAP_SPACE);
}
/**
*/
public static final boolean isNucleotide(SequenceI seq)
{
- if (seq==null)
+ if (seq == null)
{
return false;
}
* Check for nucleotide count > 85% of total count (in a form that evades
* int / float conversion or divide by zero).
*/
- if ((ntCount+nCount) * 100 > EIGHTY_FIVE * (ntCount + aaCount))
+ if ((ntCount + nCount) * 100 > EIGHTY_FIVE * (ntCount + aaCount))
{
- return ntCount>0; // all N is considered protein. Could use a threshold here too
+ return ntCount > 0; // all N is considered protein. Could use a threshold
+ // here too
}
else
{
*/
private static Map<String, String> canonicalSourceNameLookup = new HashMap<>();
- public final static int DB_SOURCE = 1;
- public final static int DB_VERSION = 2;
- public final static int DB_ID = 4;
- public final static int DB_MAP = 8;
-
- public final static int SEARCH_MODE_NO_MAP_NO_VERSION = DB_SOURCE | DB_ID;
- public final static int SEARCH_MODE_FULL = DB_SOURCE | DB_VERSION | DB_ID | DB_MAP;
-
- static
- {
- // TODO load these from a resource file?
- canonicalSourceNameLookup.put("uniprotkb/swiss-prot", DBRefSource.UNIPROT);
- canonicalSourceNameLookup.put("uniprotkb/trembl", DBRefSource.UNIPROT);
-
- // Ensembl values for dbname in xref REST service:
- canonicalSourceNameLookup.put("uniprot/sptrembl", DBRefSource.UNIPROT);
- canonicalSourceNameLookup.put("uniprot/swissprot", DBRefSource.UNIPROT);
-
- canonicalSourceNameLookup.put("pdb", DBRefSource.PDB);
- canonicalSourceNameLookup.put("ensembl", DBRefSource.ENSEMBL);
- // Ensembl Gn and Tr are for Ensembl genomic and transcript IDs as served
- // from ENA.
- canonicalSourceNameLookup.put("ensembl-tr", DBRefSource.ENSEMBL);
- canonicalSourceNameLookup.put("ensembl-gn", DBRefSource.ENSEMBL);
-
- // guarantee we always have lowercase entries for canonical string lookups
- for (String k : canonicalSourceNameLookup.keySet())
- {
- canonicalSourceNameLookup.put(k.toLowerCase(Locale.ROOT),
- canonicalSourceNameLookup.get(k));
- }
- }
+ public final static int DB_SOURCE = 1;
+
+ public final static int DB_VERSION = 2;
+
+ public final static int DB_ID = 4;
+
+ public final static int DB_MAP = 8;
+
+ public final static int SEARCH_MODE_NO_MAP_NO_VERSION = DB_SOURCE | DB_ID;
+
+ public final static int SEARCH_MODE_FULL = DB_SOURCE | DB_VERSION | DB_ID
+ | DB_MAP;
+
+ static
+ {
+ // TODO load these from a resource file?
+ canonicalSourceNameLookup.put("uniprotkb/swiss-prot",
+ DBRefSource.UNIPROT);
+ canonicalSourceNameLookup.put("uniprotkb/trembl", DBRefSource.UNIPROT);
+
+ // Ensembl values for dbname in xref REST service:
+ canonicalSourceNameLookup.put("uniprot/sptrembl", DBRefSource.UNIPROT);
+ canonicalSourceNameLookup.put("uniprot/swissprot", DBRefSource.UNIPROT);
+
+ canonicalSourceNameLookup.put("pdb", DBRefSource.PDB);
+ canonicalSourceNameLookup.put("ensembl", DBRefSource.ENSEMBL);
+ // Ensembl Gn and Tr are for Ensembl genomic and transcript IDs as served
+ // from ENA.
+ canonicalSourceNameLookup.put("ensembl-tr", DBRefSource.ENSEMBL);
+ canonicalSourceNameLookup.put("ensembl-gn", DBRefSource.ENSEMBL);
+
+ // guarantee we always have lowercase entries for canonical string lookups
+ for (String k : canonicalSourceNameLookup.keySet())
+ {
+ canonicalSourceNameLookup.put(k.toLowerCase(Locale.ROOT),
+ canonicalSourceNameLookup.get(k));
+ }
+ }
/**
* Returns those DBRefEntry objects whose source identifier (once converted to
* Jalview's canonical form) is in the list of sources to search for. Returns
* null if no matches found.
*
- * @param dbrefs DBRefEntry objects to search
- * @param sources array of sources to select
+ * @param dbrefs
+ * DBRefEntry objects to search
+ * @param sources
+ * array of sources to select
* @return
*/
- public static List<DBRefEntry> selectRefs(List<DBRefEntry> dbrefs, String[] sources)
+ public static List<DBRefEntry> selectRefs(List<DBRefEntry> dbrefs,
+ String[] sources)
{
- if (dbrefs == null || sources == null)
- {
- return dbrefs;
- }
-
- // BH TODO (what?)
- HashSet<String> srcs = new HashSet<String>();
- for (String src : sources)
- {
- srcs.add(src.toUpperCase(Locale.ROOT));
- }
-
- int nrefs = dbrefs.size();
- List<DBRefEntry> res = new ArrayList<DBRefEntry>();
- for (int ib = 0; ib < nrefs; ib++)
- {
- DBRefEntry dbr = dbrefs.get(ib);
- String source = getCanonicalName(dbr.getSource());
- if (srcs.contains(source.toUpperCase(Locale.ROOT)))
- {
- res.add(dbr);
- }
- }
- if (res.size() > 0)
- {
- // List<DBRefEntry> reply = new DBRefEntry[res.size()];
- return res;// .toArray(reply);
- }
- return null;
+ if (dbrefs == null || sources == null)
+ {
+ return dbrefs;
+ }
+
+ // BH TODO (what?)
+ HashSet<String> srcs = new HashSet<String>();
+ for (String src : sources)
+ {
+ srcs.add(src.toUpperCase(Locale.ROOT));
+ }
+
+ int nrefs = dbrefs.size();
+ List<DBRefEntry> res = new ArrayList<DBRefEntry>();
+ for (int ib = 0; ib < nrefs; ib++)
+ {
+ DBRefEntry dbr = dbrefs.get(ib);
+ String source = getCanonicalName(dbr.getSource());
+ if (srcs.contains(source.toUpperCase(Locale.ROOT)))
+ {
+ res.add(dbr);
+ }
+ }
+ if (res.size() > 0)
+ {
+ // List<DBRefEntry> reply = new DBRefEntry[res.size()];
+ return res;// .toArray(reply);
+ }
+ return null;
}
- private static boolean selectRefsBS(List<DBRefEntry> dbrefs, int sourceKeys, BitSet bsSelect)
+ private static boolean selectRefsBS(List<DBRefEntry> dbrefs,
+ int sourceKeys, BitSet bsSelect)
{
- if (dbrefs == null || sourceKeys == 0)
- {
- return false;
- }
- for (int i = 0, n = dbrefs.size(); i < n; i++)
- {
- DBRefEntry dbr = dbrefs.get(i);
- if ((dbr.getSourceKey() & sourceKeys) != 0)
- {
- bsSelect.clear(i);
- }
- }
- return !bsSelect.isEmpty();
+ if (dbrefs == null || sourceKeys == 0)
+ {
+ return false;
+ }
+ for (int i = 0, n = dbrefs.size(); i < n; i++)
+ {
+ DBRefEntry dbr = dbrefs.get(i);
+ if ((dbr.getSourceKey() & sourceKeys) != 0)
+ {
+ bsSelect.clear(i);
+ }
+ }
+ return !bsSelect.isEmpty();
}
/**
return rfs;
}
- /**
- * look up source in an internal list of database reference sources and return
- * the canonical jalview name for the source, or the original string if it has
- * no canonical form.
- *
- * @param source
- * @return canonical jalview source (one of jalview.datamodel.DBRefSource.*) or
- * original source
- */
- public static String getCanonicalName(String source)
- {
- if (source == null)
- {
- return null;
- }
- String canonical = canonicalSourceNameLookup.get(source.toLowerCase(Locale.ROOT));
- return canonical == null ? source : canonical;
- }
-
- /**
- * Returns a (possibly empty) list of those references that match the given
- * entry. Currently uses a comparator which matches if
- * <ul>
- * <li>database sources are the same</li>
- * <li>accession ids are the same</li>
- * <li>both have no mapping, or the mappings are the same</li>
- * </ul>
- *
- * @param ref Set of references to search
- * @param entry pattern to match
- * @param mode SEARCH_MODE_FULL for all; SEARCH_MODE_NO_MAP_NO_VERSION optional
- * @return
- */
- public static List<DBRefEntry> searchRefs(List<DBRefEntry> ref, DBRefEntry entry, int mode) {
- return searchRefs(ref, entry, matchDbAndIdAndEitherMapOrEquivalentMapList, mode);
- }
-
- /**
- * Returns a list of those references that match the given accession id
- * <ul>
- * <li>database sources are the same</li>
- * <li>accession ids are the same</li>
- * <li>both have no mapping, or the mappings are the same</li>
- * </ul>
- *
- * @param refs Set of references to search
- * @param accId accession id to match
- * @return
- */
- public static List<DBRefEntry> searchRefs(List<DBRefEntry> refs, String accId) {
- List<DBRefEntry> rfs = new ArrayList<DBRefEntry>();
- if (refs == null || accId == null) {
- return rfs;
- }
- for (int i = 0, n = refs.size(); i < n; i++) {
- DBRefEntry e = refs.get(i);
- if (accId.equals(e.getAccessionId())) {
- rfs.add(e);
- }
- }
- return rfs;
- // return searchRefs(refs, new DBRefEntry("", "", accId), matchId, SEARCH_MODE_FULL);
- }
-
- /**
- * Returns a (possibly empty) list of those references that match the given
- * entry, according to the given comparator.
- *
- * @param refs an array of database references to search
- * @param entry an entry to compare against
- * @param comparator
- * @param mode SEARCH_MODE_FULL for all; SEARCH_MODE_NO_MAP_NO_VERSION
- * optional
- * @return
- */
- static List<DBRefEntry> searchRefs(List<DBRefEntry> refs, DBRefEntry entry, DbRefComp comparator, int mode) {
- List<DBRefEntry> rfs = new ArrayList<DBRefEntry>();
- if (refs == null || entry == null) {
- return rfs;
- }
- for (int i = 0, n = refs.size(); i < n; i++) {
- DBRefEntry e = refs.get(i);
- if (comparator.matches(entry, e, SEARCH_MODE_FULL)) {
- rfs.add(e);
- }
- }
- return rfs;
- }
-
- interface DbRefComp {
- default public boolean matches(DBRefEntry refa, DBRefEntry refb) {
- return matches(refa, refb, SEARCH_MODE_FULL);
- };
-
- public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode);
- }
-
- /**
- * match on all non-null fields in refa
- */
- // TODO unused - remove? would be broken by equating "" with null
- public static DbRefComp matchNonNullonA = new DbRefComp() {
- @Override
- public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode) {
- if ((mode & DB_SOURCE) != 0 &&
- (refa.getSource() == null || DBRefUtils.getCanonicalName(refb.getSource())
- .equals(DBRefUtils.getCanonicalName(refa.getSource())))) {
- if ((mode & DB_VERSION) != 0 &&
- (refa.getVersion() == null || refb.getVersion().equals(refa.getVersion()))) {
- if ((mode & DB_ID) != 0 &&
- (refa.getAccessionId() == null || refb.getAccessionId().equals(refa.getAccessionId()))) {
- if ((mode & DB_MAP) != 0 &&
- (refa.getMap() == null || (refb.getMap() != null && refb.getMap().equals(refa.getMap())))) {
- return true;
- }
- }
- }
- }
- return false;
- }
- };
-
- /**
- * either field is null or field matches for all of source, version, accession
- * id and map.
- */
- // TODO unused - remove?
- public static DbRefComp matchEitherNonNull = new DbRefComp() {
- @Override
- public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode) {
- if (nullOrEqualSource(refa.getSource(), refb.getSource())
- && nullOrEqual(refa.getVersion(), refb.getVersion())
- && nullOrEqual(refa.getAccessionId(), refb.getAccessionId())
- && nullOrEqual(refa.getMap(), refb.getMap())) {
- return true;
- }
- return false;
- }
-
- };
+ /**
+ * look up source in an internal list of database reference sources and return
+ * the canonical jalview name for the source, or the original string if it has
+ * no canonical form.
+ *
+ * @param source
+ * @return canonical jalview source (one of jalview.datamodel.DBRefSource.*)
+ * or original source
+ */
+ public static String getCanonicalName(String source)
+ {
+ if (source == null)
+ {
+ return null;
+ }
+ String canonical = canonicalSourceNameLookup
+ .get(source.toLowerCase(Locale.ROOT));
+ return canonical == null ? source : canonical;
+ }
+
+ /**
+ * Returns a (possibly empty) list of those references that match the given
+ * entry. Currently uses a comparator which matches if
+ * <ul>
+ * <li>database sources are the same</li>
+ * <li>accession ids are the same</li>
+ * <li>both have no mapping, or the mappings are the same</li>
+ * </ul>
+ *
+ * @param ref
+ * Set of references to search
+ * @param entry
+ * pattern to match
+ * @param mode
+ * SEARCH_MODE_FULL for all; SEARCH_MODE_NO_MAP_NO_VERSION optional
+ * @return
+ */
+ public static List<DBRefEntry> searchRefs(List<DBRefEntry> ref,
+ DBRefEntry entry, int mode)
+ {
+ return searchRefs(ref, entry,
+ matchDbAndIdAndEitherMapOrEquivalentMapList, mode);
+ }
+
+ /**
+ * Returns a list of those references that match the given accession id
+ * <ul>
+ * <li>database sources are the same</li>
+ * <li>accession ids are the same</li>
+ * <li>both have no mapping, or the mappings are the same</li>
+ * </ul>
+ *
+ * @param refs
+ * Set of references to search
+ * @param accId
+ * accession id to match
+ * @return
+ */
+ public static List<DBRefEntry> searchRefs(List<DBRefEntry> refs,
+ String accId)
+ {
+ List<DBRefEntry> rfs = new ArrayList<DBRefEntry>();
+ if (refs == null || accId == null)
+ {
+ return rfs;
+ }
+ for (int i = 0, n = refs.size(); i < n; i++)
+ {
+ DBRefEntry e = refs.get(i);
+ if (accId.equals(e.getAccessionId()))
+ {
+ rfs.add(e);
+ }
+ }
+ return rfs;
+ // return searchRefs(refs, new DBRefEntry("", "", accId), matchId,
+ // SEARCH_MODE_FULL);
+ }
+
+ /**
+ * Returns a (possibly empty) list of those references that match the given
+ * entry, according to the given comparator.
+ *
+ * @param refs
+ * an array of database references to search
+ * @param entry
+ * an entry to compare against
+ * @param comparator
+ * @param mode
+ * SEARCH_MODE_FULL for all; SEARCH_MODE_NO_MAP_NO_VERSION optional
+ * @return
+ */
+ static List<DBRefEntry> searchRefs(List<DBRefEntry> refs,
+ DBRefEntry entry, DbRefComp comparator, int mode)
+ {
+ List<DBRefEntry> rfs = new ArrayList<DBRefEntry>();
+ if (refs == null || entry == null)
+ {
+ return rfs;
+ }
+ for (int i = 0, n = refs.size(); i < n; i++)
+ {
+ DBRefEntry e = refs.get(i);
+ if (comparator.matches(entry, e, SEARCH_MODE_FULL))
+ {
+ rfs.add(e);
+ }
+ }
+ return rfs;
+ }
+
+ interface DbRefComp
+ {
+ default public boolean matches(DBRefEntry refa, DBRefEntry refb)
+ {
+ return matches(refa, refb, SEARCH_MODE_FULL);
+ };
+
+ public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode);
+ }
+
+ /**
+ * match on all non-null fields in refa
+ */
+ // TODO unused - remove? would be broken by equating "" with null
+ public static DbRefComp matchNonNullonA = new DbRefComp()
+ {
+ @Override
+ public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode)
+ {
+ if ((mode & DB_SOURCE) != 0 && (refa.getSource() == null
+ || DBRefUtils.getCanonicalName(refb.getSource()).equals(
+ DBRefUtils.getCanonicalName(refa.getSource()))))
+ {
+ if ((mode & DB_VERSION) != 0 && (refa.getVersion() == null
+ || refb.getVersion().equals(refa.getVersion())))
+ {
+ if ((mode & DB_ID) != 0 && (refa.getAccessionId() == null
+ || refb.getAccessionId().equals(refa.getAccessionId())))
+ {
+ if ((mode & DB_MAP) != 0
+ && (refa.getMap() == null || (refb.getMap() != null
+ && refb.getMap().equals(refa.getMap()))))
+ {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+ };
+
+ /**
+ * either field is null or field matches for all of source, version, accession
+ * id and map.
+ */
+ // TODO unused - remove?
+ public static DbRefComp matchEitherNonNull = new DbRefComp()
+ {
+ @Override
+ public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode)
+ {
+ if (nullOrEqualSource(refa.getSource(), refb.getSource())
+ && nullOrEqual(refa.getVersion(), refb.getVersion())
+ && nullOrEqual(refa.getAccessionId(), refb.getAccessionId())
+ && nullOrEqual(refa.getMap(), refb.getMap()))
+ {
+ return true;
+ }
+ return false;
+ }
+
+ };
+ private static Regex PARSE_REGEX;
+
+ private static Regex getParseRegex()
+ {
+ return (PARSE_REGEX == null ? PARSE_REGEX = Platform.newRegex(
+ "([0-9][0-9A-Za-z]{3})\\s*(.?)\\s*;\\s*([0-9]+)-([0-9]+)")
+ : PARSE_REGEX);
+ }
+
/**
* Parses a DBRefEntry and adds it to the sequence, also a PDBEntry if the
* database is PDB.
* Check for PFAM style stockhom PDB accession id citation e.g.
* "1WRI A; 7-80;"
*/
- Regex r = new com.stevesoft.pat.Regex(
- "([0-9][0-9A-Za-z]{3})\\s*(.?)\\s*;\\s*([0-9]+)-([0-9]+)");
+ Regex r = getParseRegex();
if (r.search(acn.trim()))
{
String pdbid = r.stringMatched(1);
return ref;
}
- /**
- * accession ID and DB must be identical. Version is ignored. Map is either not
- * defined or is a match (or is compatible?)
- */
- // TODO unused - remove?
- public static DbRefComp matchDbAndIdAndEitherMap = new DbRefComp() {
- @Override
- public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode) {
- if (refa.getSource() != null && refb.getSource() != null && DBRefUtils.getCanonicalName(refb.getSource())
- .equals(DBRefUtils.getCanonicalName(refa.getSource()))) {
- // We dont care about version
- if (refa.getAccessionId() != null && refb.getAccessionId() != null
- // FIXME should be && not || here?
- || refb.getAccessionId().equals(refa.getAccessionId())) {
- if ((refa.getMap() == null || refb.getMap() == null) || (refa.getMap() != null
- && refb.getMap() != null && refb.getMap().equals(refa.getMap()))) {
- return true;
- }
- }
- }
- return false;
- }
- };
-
- /**
- * accession ID and DB must be identical. Version is ignored. No map on either
- * or map but no maplist on either or maplist of map on a is the complement of
- * maplist of map on b.
- */
- // TODO unused - remove?
- public static DbRefComp matchDbAndIdAndComplementaryMapList = new DbRefComp() {
- @Override
- public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode) {
- if (refa.getSource() != null && refb.getSource() != null && DBRefUtils.getCanonicalName(refb.getSource())
- .equals(DBRefUtils.getCanonicalName(refa.getSource()))) {
- // We dont care about version
- if (refa.getAccessionId() != null && refb.getAccessionId() != null
- || refb.getAccessionId().equals(refa.getAccessionId())) {
- if ((refa.getMap() == null && refb.getMap() == null)
- || (refa.getMap() != null && refb.getMap() != null)) {
- if ((refb.getMap().getMap() == null && refa.getMap().getMap() == null)
- || (refb.getMap().getMap() != null && refa.getMap().getMap() != null
- && refb.getMap().getMap().getInverse().equals(refa.getMap().getMap()))) {
- return true;
- }
- }
- }
- }
- return false;
- }
- };
-
- /**
- * accession ID and DB must be identical. Version is ignored. No map on both or
- * or map but no maplist on either or maplist of map on a is equivalent to the
- * maplist of map on b.
- */
- // TODO unused - remove?
- public static DbRefComp matchDbAndIdAndEquivalentMapList = new DbRefComp() {
- @Override
- public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode) {
- if (refa.getSource() != null && refb.getSource() != null && DBRefUtils.getCanonicalName(refb.getSource())
- .equals(DBRefUtils.getCanonicalName(refa.getSource()))) {
- // We dont care about version
- // if ((refa.getVersion()==null || refb.getVersion()==null)
- // || refb.getVersion().equals(refa.getVersion()))
- // {
- if (refa.getAccessionId() != null && refb.getAccessionId() != null
- || refb.getAccessionId().equals(refa.getAccessionId())) {
- if (refa.getMap() == null && refb.getMap() == null) {
- return true;
- }
- if (refa.getMap() != null && refb.getMap() != null
- && ((refb.getMap().getMap() == null && refa.getMap().getMap() == null)
- || (refb.getMap().getMap() != null && refa.getMap().getMap() != null
- && refb.getMap().getMap().equals(refa.getMap().getMap())))) {
- return true;
- }
- }
- }
- return false;
- }
- };
-
- /**
- * accession ID and DB must be identical, or null on a. Version is ignored. No
- * map on either or map but no maplist on either or maplist of map on a is
- * equivalent to the maplist of map on b.
- */
- public static DbRefComp matchDbAndIdAndEitherMapOrEquivalentMapList = new DbRefComp()
- {
- @Override
- public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode)
- {
- if (refa.getSource() != null && refb.getSource() != null && DBRefUtils.getCanonicalName(refb.getSource())
- .equals(DBRefUtils.getCanonicalName(refa.getSource())))
- {
- // We dont care about version
- if (refa.getAccessionId() == null || refa.getAccessionId().equals(refb.getAccessionId()))
- {
- if (refa.getMap() == null || refb.getMap() == null)
- {
- return true;
- }
- if ((refa.getMap() != null && refb.getMap() != null)
- && (refb.getMap().getMap() == null && refa.getMap().getMap() == null)
- || (refb.getMap().getMap() != null && refa.getMap().getMap() != null
- && (refb.getMap().getMap().equals(refa.getMap().getMap()))))
- {
- return true;
- }
- }
- }
- return false;
- }
- };
-
- /**
+ /**
+ * accession ID and DB must be identical. Version is ignored. Map is either
+ * not defined or is a match (or is compatible?)
+ */
+ // TODO unused - remove?
+ public static DbRefComp matchDbAndIdAndEitherMap = new DbRefComp()
+ {
+ @Override
+ public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode)
+ {
+ if (refa.getSource() != null && refb.getSource() != null
+ && DBRefUtils.getCanonicalName(refb.getSource()).equals(
+ DBRefUtils.getCanonicalName(refa.getSource())))
+ {
+ // We dont care about version
+ if (refa.getAccessionId() != null && refb.getAccessionId() != null
+ // FIXME should be && not || here?
+ || refb.getAccessionId().equals(refa.getAccessionId()))
+ {
+ if ((refa.getMap() == null || refb.getMap() == null)
+ || (refa.getMap() != null && refb.getMap() != null
+ && refb.getMap().equals(refa.getMap())))
+ {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ };
+
+ /**
+ * accession ID and DB must be identical. Version is ignored. No map on either
+ * or map but no maplist on either or maplist of map on a is the complement of
+ * maplist of map on b.
+ */
+ // TODO unused - remove?
+ public static DbRefComp matchDbAndIdAndComplementaryMapList = new DbRefComp()
+ {
+ @Override
+ public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode)
+ {
+ if (refa.getSource() != null && refb.getSource() != null
+ && DBRefUtils.getCanonicalName(refb.getSource()).equals(
+ DBRefUtils.getCanonicalName(refa.getSource())))
+ {
+ // We dont care about version
+ if (refa.getAccessionId() != null && refb.getAccessionId() != null
+ || refb.getAccessionId().equals(refa.getAccessionId()))
+ {
+ if ((refa.getMap() == null && refb.getMap() == null)
+ || (refa.getMap() != null && refb.getMap() != null))
+ {
+ if ((refb.getMap().getMap() == null
+ && refa.getMap().getMap() == null)
+ || (refb.getMap().getMap() != null
+ && refa.getMap().getMap() != null
+ && refb.getMap().getMap().getInverse()
+ .equals(refa.getMap().getMap())))
+ {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+ };
+
+ /**
+ * accession ID and DB must be identical. Version is ignored. No map on both
+ * or or map but no maplist on either or maplist of map on a is equivalent to
+ * the maplist of map on b.
+ */
+ // TODO unused - remove?
+ public static DbRefComp matchDbAndIdAndEquivalentMapList = new DbRefComp()
+ {
+ @Override
+ public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode)
+ {
+ if (refa.getSource() != null && refb.getSource() != null
+ && DBRefUtils.getCanonicalName(refb.getSource()).equals(
+ DBRefUtils.getCanonicalName(refa.getSource())))
+ {
+ // We dont care about version
+ // if ((refa.getVersion()==null || refb.getVersion()==null)
+ // || refb.getVersion().equals(refa.getVersion()))
+ // {
+ if (refa.getAccessionId() != null && refb.getAccessionId() != null
+ || refb.getAccessionId().equals(refa.getAccessionId()))
+ {
+ if (refa.getMap() == null && refb.getMap() == null)
+ {
+ return true;
+ }
+ if (refa.getMap() != null && refb.getMap() != null
+ && ((refb.getMap().getMap() == null
+ && refa.getMap().getMap() == null)
+ || (refb.getMap().getMap() != null
+ && refa.getMap().getMap() != null
+ && refb.getMap().getMap()
+ .equals(refa.getMap().getMap()))))
+ {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ };
+
+ /**
+ * accession ID and DB must be identical, or null on a. Version is ignored. No
+ * map on either or map but no maplist on either or maplist of map on a is
+ * equivalent to the maplist of map on b.
+ */
+ public static DbRefComp matchDbAndIdAndEitherMapOrEquivalentMapList = new DbRefComp()
+ {
+ @Override
+ public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode)
+ {
+ if (refa.getSource() != null && refb.getSource() != null
+ && DBRefUtils.getCanonicalName(refb.getSource()).equals(
+ DBRefUtils.getCanonicalName(refa.getSource())))
+ {
+ // We dont care about version
+ if (refa.getAccessionId() == null
+ || refa.getAccessionId().equals(refb.getAccessionId()))
+ {
+ if (refa.getMap() == null || refb.getMap() == null)
+ {
+ return true;
+ }
+ if ((refa.getMap() != null && refb.getMap() != null)
+ && (refb.getMap().getMap() == null
+ && refa.getMap().getMap() == null)
+ || (refb.getMap().getMap() != null
+ && refa.getMap().getMap() != null
+ && (refb.getMap().getMap()
+ .equals(refa.getMap().getMap()))))
+ {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ };
+
+ /**
* Returns the (possibly empty) list of those supplied dbrefs which have the
* specified source database, with a case-insensitive match of source name
*
return matches;
}
- /**
- * Returns true if either object is null, or they are equal
- *
- * @param o1
- * @param o2
- * @return
- */
- public static boolean nullOrEqual(Object o1, Object o2) {
- if (o1 == null || o2 == null) {
- return true;
- }
- return o1.equals(o2);
- }
-
- /**
- * canonicalise source string before comparing. null is always wildcard
- *
- * @param o1 - null or source string to compare
- * @param o2 - null or source string to compare
- * @return true if either o1 or o2 are null, or o1 equals o2 under
- * DBRefUtils.getCanonicalName
- * (o1).equals(DBRefUtils.getCanonicalName(o2))
- */
- public static boolean nullOrEqualSource(String o1, String o2) {
- if (o1 == null || o2 == null) {
- return true;
- }
- return DBRefUtils.getCanonicalName(o1).equals(DBRefUtils.getCanonicalName(o2));
- }
-
- /**
- * Selects just the DNA or protein references from a set of references
- *
- * @param selectDna if true, select references to 'standard' DNA databases, else
- * to 'standard' peptide databases
- * @param refs a set of references to select from
- * @return
- */
- public static List<DBRefEntry> selectDbRefs(boolean selectDna, List<DBRefEntry> refs) {
- return selectRefs(refs, selectDna ? DBRefSource.DNACODINGDBS : DBRefSource.PROTEINDBS);
- // could attempt to find other cross
- // refs here - ie PDB xrefs
- // (not dna, not protein seq)
- }
-
- /**
- * Returns the (possibly empty) list of those supplied dbrefs which have the
- * specified source database, with a case-insensitive match of source name
- *
- * @param dbRefs
- * @param source
- * @return
- */
- public static List<DBRefEntry> searchRefsForSource(List<DBRefEntry> dbRefs, String source) {
- List<DBRefEntry> matches = new ArrayList<DBRefEntry>();
- if (dbRefs != null && source != null) {
- for (DBRefEntry dbref : dbRefs) {
- if (source.equalsIgnoreCase(dbref.getSource())) {
- matches.add(dbref);
- }
- }
- }
- return matches;
- }
-
- /**
- * promote direct database references to primary for nucleotide or protein
- * sequences if they have an appropriate primary ref
- * <table>
- * <tr>
- * <th>Seq Type</th>
- * <th>Primary DB</th>
- * <th>Direct which will be promoted</th>
- * </tr>
- * <tr align=center>
- * <td>peptides</td>
- * <td>Ensembl</td>
- * <td>Uniprot</td>
- * </tr>
- * <tr align=center>
- * <td>peptides</td>
- * <td>Ensembl</td>
- * <td>Uniprot</td>
- * </tr>
- * <tr align=center>
- * <td>dna</td>
- * <td>Ensembl</td>
- * <td>ENA</td>
- * </tr>
- * </table>
- *
- * @param sequence
- */
- public static void ensurePrimaries(SequenceI sequence, List<DBRefEntry> pr) {
- if (pr.size() == 0) {
- // nothing to do
- return;
- }
- int sstart = sequence.getStart();
- int send = sequence.getEnd();
- boolean isProtein = sequence.isProtein();
- BitSet bsSelect = new BitSet();
-
- // List<DBRefEntry> selfs = new ArrayList<DBRefEntry>();
- // {
-
- // List<DBRefEntry> selddfs = selectDbRefs(!isprot, sequence.getDBRefs());
- // if (selfs == null || selfs.size() == 0)
- // {
- // // nothing to do
- // return;
- // }
-
- List<DBRefEntry> dbrefs = sequence.getDBRefs();
- bsSelect.set(0, dbrefs.size());
-
- if (!selectRefsBS(dbrefs, isProtein ? DBRefSource.PROTEIN_MASK : DBRefSource.DNA_CODING_MASK, bsSelect))
- return;
-
- // selfs.addAll(selfArray);
- // }
-
- // filter non-primary refs
- for (int ip = pr.size(); --ip >= 0;) {
- DBRefEntry p = pr.get(ip);
- for (int i = bsSelect.nextSetBit(0); i >= 0; i = bsSelect.nextSetBit(i + 1)) {
- if (dbrefs.get(i) == p)
- bsSelect.clear(i);
- }
- // while (selfs.contains(p))
- // {
- // selfs.remove(p);
- // }
- }
- // List<DBRefEntry> toPromote = new ArrayList<DBRefEntry>();
-
- for (int ip = pr.size(), keys = 0; --ip >= 0 && keys != DBRefSource.PRIMARY_MASK;) {
- DBRefEntry p = pr.get(ip);
- if (isProtein) {
- switch (getCanonicalName(p.getSource())) {
- case DBRefSource.UNIPROT:
- keys |= DBRefSource.UNIPROT_MASK;
- break;
- case DBRefSource.ENSEMBL:
- keys |= DBRefSource.ENSEMBL_MASK;
- break;
- }
- } else {
- // TODO: promote transcript refs ??
- }
- if (keys == 0 || !selectRefsBS(dbrefs, keys, bsSelect))
- return;
- // if (candidates != null)
- {
- for (int ic = bsSelect.nextSetBit(0); ic >= 0; ic = bsSelect.nextSetBit(ic + 1))
- // for (int ic = 0, n = candidates.size(); ic < n; ic++)
- {
- DBRefEntry cand = dbrefs.get(ic);// candidates.get(ic);
- if (cand.hasMap()) {
- Mapping map = cand.getMap();
- SequenceI cto = map.getTo();
- if (cto != null && cto != sequence) {
- // can't promote refs with mappings to other sequences
- continue;
- }
- MapList mlist = map.getMap();
- if (mlist.getFromLowest() != sstart && mlist.getFromHighest() != send) {
- // can't promote refs with mappings from a region of this sequence
- // - eg CDS
- continue;
- }
- }
- // and promote - not that version must be non-null here,
- // as p must have passed isPrimaryCandidate()
- cand.setVersion(p.getVersion() + " (promoted)");
- bsSelect.clear(ic);
- // selfs.remove(cand);
- // toPromote.add(cand);
- if (!cand.isPrimaryCandidate()) {
- System.out.println("Warning: Couldn't promote dbref " + cand.toString() + " for sequence "
- + sequence.toString());
- }
- }
- }
- }
- }
+ /**
+ * Returns true if either object is null, or they are equal
+ *
+ * @param o1
+ * @param o2
+ * @return
+ */
+ public static boolean nullOrEqual(Object o1, Object o2)
+ {
+ if (o1 == null || o2 == null)
+ {
+ return true;
+ }
+ return o1.equals(o2);
+ }
+
+ /**
+ * canonicalise source string before comparing. null is always wildcard
+ *
+ * @param o1
+ * - null or source string to compare
+ * @param o2
+ * - null or source string to compare
+ * @return true if either o1 or o2 are null, or o1 equals o2 under
+ * DBRefUtils.getCanonicalName
+ * (o1).equals(DBRefUtils.getCanonicalName(o2))
+ */
+ public static boolean nullOrEqualSource(String o1, String o2)
+ {
+ if (o1 == null || o2 == null)
+ {
+ return true;
+ }
+ return DBRefUtils.getCanonicalName(o1)
+ .equals(DBRefUtils.getCanonicalName(o2));
+ }
+
+ /**
+ * Selects just the DNA or protein references from a set of references
+ *
+ * @param selectDna
+ * if true, select references to 'standard' DNA databases, else to
+ * 'standard' peptide databases
+ * @param refs
+ * a set of references to select from
+ * @return
+ */
+ public static List<DBRefEntry> selectDbRefs(boolean selectDna,
+ List<DBRefEntry> refs)
+ {
+ return selectRefs(refs,
+ selectDna ? DBRefSource.DNACODINGDBS : DBRefSource.PROTEINDBS);
+ // could attempt to find other cross
+ // refs here - ie PDB xrefs
+ // (not dna, not protein seq)
+ }
+
+ /**
+ * Returns the (possibly empty) list of those supplied dbrefs which have the
+ * specified source database, with a case-insensitive match of source name
+ *
+ * @param dbRefs
+ * @param source
+ * @return
+ */
+ public static List<DBRefEntry> searchRefsForSource(
+ List<DBRefEntry> dbRefs, String source)
+ {
+ List<DBRefEntry> matches = new ArrayList<DBRefEntry>();
+ if (dbRefs != null && source != null)
+ {
+ for (DBRefEntry dbref : dbRefs)
+ {
+ if (source.equalsIgnoreCase(dbref.getSource()))
+ {
+ matches.add(dbref);
+ }
+ }
+ }
+ return matches;
+ }
+
+ /**
+ * promote direct database references to primary for nucleotide or protein
+ * sequences if they have an appropriate primary ref
+ * <table>
+ * <tr>
+ * <th>Seq Type</th>
+ * <th>Primary DB</th>
+ * <th>Direct which will be promoted</th>
+ * </tr>
+ * <tr align=center>
+ * <td>peptides</td>
+ * <td>Ensembl</td>
+ * <td>Uniprot</td>
+ * </tr>
+ * <tr align=center>
+ * <td>peptides</td>
+ * <td>Ensembl</td>
+ * <td>Uniprot</td>
+ * </tr>
+ * <tr align=center>
+ * <td>dna</td>
+ * <td>Ensembl</td>
+ * <td>ENA</td>
+ * </tr>
+ * </table>
+ *
+ * @param sequence
+ */
+ public static void ensurePrimaries(SequenceI sequence,
+ List<DBRefEntry> pr)
+ {
+ if (pr.size() == 0)
+ {
+ // nothing to do
+ return;
+ }
+ int sstart = sequence.getStart();
+ int send = sequence.getEnd();
+ boolean isProtein = sequence.isProtein();
+ BitSet bsSelect = new BitSet();
+
+ // List<DBRefEntry> selfs = new ArrayList<DBRefEntry>();
+ // {
+
+ // List<DBRefEntry> selddfs = selectDbRefs(!isprot, sequence.getDBRefs());
+ // if (selfs == null || selfs.size() == 0)
+ // {
+ // // nothing to do
+ // return;
+ // }
+
+ List<DBRefEntry> dbrefs = sequence.getDBRefs();
+ bsSelect.set(0, dbrefs.size());
+
+ if (!selectRefsBS(dbrefs, isProtein ? DBRefSource.PROTEIN_MASK
+ : DBRefSource.DNA_CODING_MASK, bsSelect))
+ return;
+
+ // selfs.addAll(selfArray);
+ // }
+
+ // filter non-primary refs
+ for (int ip = pr.size(); --ip >= 0;)
+ {
+ DBRefEntry p = pr.get(ip);
+ for (int i = bsSelect.nextSetBit(0); i >= 0; i = bsSelect
+ .nextSetBit(i + 1))
+ {
+ if (dbrefs.get(i) == p)
+ bsSelect.clear(i);
+ }
+ // while (selfs.contains(p))
+ // {
+ // selfs.remove(p);
+ // }
+ }
+ // List<DBRefEntry> toPromote = new ArrayList<DBRefEntry>();
+
+ for (int ip = pr.size(), keys = 0; --ip >= 0
+ && keys != DBRefSource.PRIMARY_MASK;)
+ {
+ DBRefEntry p = pr.get(ip);
+ if (isProtein)
+ {
+ switch (getCanonicalName(p.getSource()))
+ {
+ case DBRefSource.UNIPROT:
+ keys |= DBRefSource.UNIPROT_MASK;
+ break;
+ case DBRefSource.ENSEMBL:
+ keys |= DBRefSource.ENSEMBL_MASK;
+ break;
+ }
+ }
+ else
+ {
+ // TODO: promote transcript refs ??
+ }
+ if (keys == 0 || !selectRefsBS(dbrefs, keys, bsSelect))
+ return;
+ // if (candidates != null)
+ {
+ for (int ic = bsSelect.nextSetBit(0); ic >= 0; ic = bsSelect
+ .nextSetBit(ic + 1))
+ // for (int ic = 0, n = candidates.size(); ic < n; ic++)
+ {
+ DBRefEntry cand = dbrefs.get(ic);// candidates.get(ic);
+ if (cand.hasMap())
+ {
+ Mapping map = cand.getMap();
+ SequenceI cto = map.getTo();
+ if (cto != null && cto != sequence)
+ {
+ // can't promote refs with mappings to other sequences
+ continue;
+ }
+ MapList mlist = map.getMap();
+ if (mlist.getFromLowest() != sstart
+ && mlist.getFromHighest() != send)
+ {
+ // can't promote refs with mappings from a region of this sequence
+ // - eg CDS
+ continue;
+ }
+ }
+ // and promote - not that version must be non-null here,
+ // as p must have passed isPrimaryCandidate()
+ cand.setVersion(p.getVersion() + " (promoted)");
+ bsSelect.clear(ic);
+ // selfs.remove(cand);
+ // toPromote.add(cand);
+ if (!cand.isPrimaryCandidate())
+ {
+ System.out.println(
+ "Warning: Couldn't promote dbref " + cand.toString()
+ + " for sequence " + sequence.toString());
+ }
+ }
+ }
+ }
+ }
}
*/
package jalview.util;
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
}
return false;
}
+
public static boolean startsWithHttpOrHttps(String file)
{
return file.startsWith("http://") || file.startsWith("https://");
}
+
+
/**
* wrapper to get/post to a URL or check headers
- *
* @param url
* @param ids
* @param readTimeout
* @throws IOException
* @throws ProtocolException
*/
- public static boolean checkUrlAvailable(URL url, int readTimeout)
- throws IOException, ProtocolException
+ public static boolean checkUrlAvailable(URL url,
+ int readTimeout) throws IOException, ProtocolException
{
// System.out.println(System.currentTimeMillis() + " " + url);
return connection.getResponseCode() == 200;
}
+ /**
+ * download from given URL and return a pointer to temporary file
+ */
+ public static File fetchURLToTemp(String url) throws OutOfMemoryError,
+ IOException
+ {
+ long time = System.currentTimeMillis();
+ URL rcall = new URL(url);
+
+ InputStream is = new BufferedInputStream(rcall.openStream());
+ File outFile = null;
+ try
+ {
+ outFile = File.createTempFile("jalview", ".xml");
+ outFile.deleteOnExit();
+ if (outFile.length() == 0)
+ {
+ outFile.delete();
+ return null;
+ }
+ } catch (Exception ex)
+ {
+ }
+
+ if (outFile != null)
+ {
+ FileOutputStream fio = new FileOutputStream(outFile);
+ byte[] bb = new byte[32 * 1024];
+ int l;
+ while ((l = is.read(bb)) > 0)
+ {
+ fio.write(bb, 0, l);
+ }
+ fio.close();
+ is.close();
+ return outFile;
+ }
+ else
+ {
+ return null;
+ }
+ }
}
import java.util.BitSet;
import java.util.List;
+ import jalview.bin.Console;
+
/**
* A simple way of bijectively mapping a non-contiguous linear range to another
* non-contiguous linear range.
if (range.length != 2)
{
// throw new IllegalArgumentException(range);
- System.err.println("Invalid format for fromRange "
+ Console.error("Invalid format for fromRange "
+ Arrays.toString(range) + " may cause errors");
}
fromLowest = Math.min(fromLowest, Math.min(range[0], range[1]));
if (range.length != 2)
{
// throw new IllegalArgumentException(range);
- System.err.println("Invalid format for toRange "
- + Arrays.toString(range) + " may cause errors");
+ Console.error("Invalid format for toRange " + Arrays.toString(range)
+ + " may cause errors");
}
toLowest = Math.min(toLowest, Math.min(range[0], range[1]));
toHighest = Math.max(toHighest, Math.max(range[0], range[1]));
int mp[][] = new int[to - from + 2][];
for (int i = 0; i < mp.length; i++)
{
- int[] m = shift(i + from, shiftTo, sourceRatio, shiftFrom, targetRatio);
+ int[] m = shift(i + from, shiftTo, sourceRatio, shiftFrom,
+ targetRatio);
if (m != null)
{
if (i == 0)
for (int[] range : map.getFromRanges())
{
- addRange(range, fromShifts);
+ MappingUtils.addRange(range, fromShifts);
}
for (int[] range : map.getToRanges())
{
- addRange(range, toShifts);
+ MappingUtils.addRange(range, toShifts);
}
}
/**
- * Adds the given range to a list of ranges. If the new range just extends
- * existing ranges, the current endpoint is updated instead.
- *
- * @param range
- * @param addTo
- */
- static void addRange(int[] range, List<int[]> addTo)
- {
- /*
- * list is empty - add to it!
- */
- if (addTo.size() == 0)
- {
- addTo.add(range);
- return;
- }
-
- int[] last = addTo.get(addTo.size() - 1);
- boolean lastForward = last[1] >= last[0];
- boolean newForward = range[1] >= range[0];
-
- /*
- * contiguous range in the same direction - just update endpoint
- */
- if (lastForward == newForward && last[1] == range[0])
- {
- last[1] = range[1];
- return;
- }
-
- /*
- * next range starts at +1 in forward sense - update endpoint
- */
- if (lastForward && newForward && range[0] == last[1] + 1)
- {
- last[1] = range[1];
- return;
- }
-
- /*
- * next range starts at -1 in reverse sense - update endpoint
- */
- if (!lastForward && !newForward && range[0] == last[1] - 1)
- {
- last[1] = range[1];
- return;
- }
-
- /*
- * just add the new range
- */
- addTo.add(range);
- }
-
- /**
* Returns true if mapping is from forward strand, false if from reverse
* strand. Result is just based on the first 'from' range that is not a single
* position. Default is true unless proven to be false. Behaviour is not well
}
/**
- * Returns the [start1, end1, start2, end2, ...] positions in the 'from' range
- * that map to positions between {@code start} and {@code end} in the 'to'
- * range. Note that for a reverse strand mapping this will return ranges with
- * end < start. Returns null if no mapped positions are found in start-end.
+ * <<<<<<< HEAD Returns the [start1, end1, start2, end2, ...] positions in the
+ * 'from' range that map to positions between {@code start} and {@code end} in
+ * the 'to' range. Note that for a reverse strand mapping this will return
+ * ranges with end < start. Returns null if no mapped positions are found in
+ * start-end.
*
* @param start
* @param end
*/
public int[] locateInFrom(int start, int end)
{
- return mapPositions(start, end, toShifts, fromShifts,
- toRatio, fromRatio);
+ return mapPositions(start, end, toShifts, fromShifts, toRatio,
+ fromRatio);
}
/**
*/
public int[] locateInTo(int start, int end)
{
- return mapPositions(start, end, fromShifts, toShifts,
- fromRatio, toRatio);
+ return mapPositions(start, end, fromShifts, toShifts, fromRatio,
+ toRatio);
}
/**
* @return
*/
protected final static BitSet getMappedOffsetsForPositions(int start,
- int end, List<int[]> sourceRange, int sourceWordLength, int targetWordLength)
+ int end, List<int[]> sourceRange, int sourceWordLength,
+ int targetWordLength)
{
BitSet overlaps = new BitSet();
int offset = 0;
return added;
}
+
+ /*
+ * Returns the [start, end...] positions in the range mapped from, that are
+ * mapped to by part or all of the given begin-end of the range mapped to.
+ * Returns null if begin-end does not overlap any position mapped to.
+ *
+ * @param begin
+ * @param end
+ * @return
+ */
+ public int[] getOverlapsInFrom(final int begin, final int end)
+ {
+ int[] overlaps = MappingUtils.findOverlap(toShifts, begin, end);
+
+ return overlaps == null ? null : locateInFrom(overlaps[0], overlaps[1]);
+ }
+
+ /**
+ * Returns the [start, end...] positions in the range mapped to, that are
+ * mapped to by part or all of the given begin-end of the range mapped from.
+ * Returns null if begin-end does not overlap any position mapped from.
+ *
+ * @param begin
+ * @param end
+ * @return
+ */
+ public int[] getOverlapsInTo(final int begin, final int end)
+ {
+ int[] overlaps = MappingUtils.findOverlap(fromShifts, begin, end);
+
+ return overlaps == null ? null : locateInTo(overlaps[0], overlaps[1]);
+ }
}
*/
package jalview.util;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
+
import jalview.analysis.AlignmentSorter;
import jalview.api.AlignViewportI;
+ import jalview.bin.Console;
import jalview.commands.CommandI;
import jalview.commands.EditCommand;
import jalview.commands.EditCommand.Action;
import jalview.commands.EditCommand.Edit;
import jalview.commands.OrderCommand;
import jalview.datamodel.AlignedCodonFrame;
+ import jalview.datamodel.AlignedCodonFrame.SequenceToSequenceMapping;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.AlignmentOrder;
import jalview.datamodel.ColumnSelection;
import jalview.datamodel.HiddenColumns;
+ import jalview.datamodel.Mapping;
import jalview.datamodel.SearchResultMatchI;
import jalview.datamodel.SearchResults;
import jalview.datamodel.SearchResultsI;
import jalview.datamodel.SequenceGroup;
import jalview.datamodel.SequenceI;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
-
/**
* Helper methods for manipulations involving sequence mappings.
*
action = action.getUndoAction();
}
// TODO write this
- System.err.println("MappingUtils.mapCutOrPaste not yet implemented");
+ Console.error("MappingUtils.mapCutOrPaste not yet implemented");
}
/**
*/
int startResiduePos = selected.findPosition(firstUngappedPos);
int endResiduePos = selected.findPosition(lastUngappedPos);
+
- for (AlignedCodonFrame acf : codonFrames)
+ for (SequenceI seq : mapTo.getAlignment().getSequences())
{
- SequenceI mappedSequence = targetIsNucleotide
- ? acf.getDnaForAaSeq(selected)
- : acf.getAaForDnaSeq(selected);
- if (mappedSequence != null)
+ int mappedStartResidue = 0;
+ int mappedEndResidue = 0;
+ for (AlignedCodonFrame acf : codonFrames)
{
- for (SequenceI seq : mapTo.getAlignment().getSequences())
+ // rather than use acf.getCoveringMapping() we iterate through all
+ // mappings to make sure all CDS are selected for a protein
+ for (SequenceToSequenceMapping map : acf.getMappings())
{
- int mappedStartResidue = 0;
- int mappedEndResidue = 0;
- if (seq.getDatasetSequence() == mappedSequence)
+ if (map.covers(selected) && map.covers(seq))
{
/*
* Found a sequence mapping. Locate the start/end mapped residues.
List<AlignedCodonFrame> mapping = Arrays
.asList(new AlignedCodonFrame[]
{ acf });
+ // locate start
SearchResultsI sr = buildSearchResults(selected,
startResiduePos, mapping);
for (SearchResultMatchI m : sr.getResults())
mappedStartResidue = m.getStart();
mappedEndResidue = m.getEnd();
}
+ // locate end - allowing for adjustment of start range
sr = buildSearchResults(selected, endResiduePos, mapping);
for (SearchResultMatchI m : sr.getResults())
{
{
for (AlignedCodonFrame acf : mappings)
{
- SequenceI mappedSeq = mappingToNucleotide ? acf.getDnaForAaSeq(seq)
- : acf.getAaForDnaSeq(seq);
- if (mappedSeq != null)
+ for (SequenceI seq2 : mapTo.getSequences())
{
- for (SequenceI seq2 : mapTo.getSequences())
+ /*
+ * the corresponding peptide / CDS is the one for which there is
+ * a complete ('covering') mapping to 'seq'
+ */
+ SequenceI peptide = mappingToNucleotide ? seq2 : seq;
+ SequenceI cds = mappingToNucleotide ? seq : seq2;
+ SequenceToSequenceMapping s2s = acf.getCoveringMapping(cds,
+ peptide);
+ if (s2s != null)
{
- if (seq2.getDatasetSequence() == mappedSeq)
- {
- mappedOrder.add(seq2);
- j++;
- break;
- }
+ mappedOrder.add(seq2);
+ j++;
+ break;
}
}
}
if (colsel == null)
{
- return;
+ return; // mappedColumns;
}
char fromGapChar = mapFrom.getAlignment().getGapCharacter();
while (regions.hasNext())
{
mapHiddenColumns(regions.next(), codonFrames, newHidden,
- fromSequences, toSequences, fromGapChar);
+ fromSequences,
+ toSequences, fromGapChar);
}
- return;
+ return; // mappedColumns;
}
/**
*/
for (SequenceI toSeq : toSequences)
{
- if (toSeq.getDatasetSequence() == mappedSeq)
+ if (toSeq.getDatasetSequence() == mappedSeq
+ && mappedStartResidue >= toSeq.getStart()
+ && mappedEndResidue <= toSeq.getEnd())
{
int mappedStartCol = toSeq.findIndex(mappedStartResidue);
int mappedEndCol = toSeq.findIndex(mappedEndResidue);
{
if (range.length % 2 != 0)
{
- System.err.println(
+ Console.error(
"Error unbalance start/end ranges: " + ranges.toString());
return 0;
}
int min = Math.min(range[0], range[1]);
int max = Math.max(range[0], range[1]);
-
+
return (min <= queryRange[0] && max >= queryRange[0]
&& min <= queryRange[1] && max >= queryRange[1]);
}
* a list of (single) [start, end] ranges
* @return
*/
- public static void removeEndPositions(int positions,
- List<int[]> ranges)
+ public static void removeEndPositions(int positions, List<int[]> ranges)
{
int toRemove = positions;
Iterator<int[]> it = new ReverseListIterator<>(ranges);
/*
* not coded for [start1, end1, start2, end2, ...]
*/
- System.err
- .println("MappingUtils.removeEndPositions doesn't handle multiple ranges");
+ Console.error(
+ "MappingUtils.removeEndPositions doesn't handle multiple ranges");
return;
}
/*
* not coded for a reverse strand range (end < start)
*/
- System.err
- .println("MappingUtils.removeEndPositions doesn't handle reverse strand");
+ Console.error(
+ "MappingUtils.removeEndPositions doesn't handle reverse strand");
return;
}
if (length > toRemove)
}
}
}
+ /**
+ * Adds the given range to a list of ranges. If the new range just extends
+ * existing ranges, the current endpoint is updated instead.
+ *
+ * @param range
+ * @param addTo
+ */
+ public static void addRange(int[] range, List<int[]> addTo)
+ {
+ /*
+ * list is empty - add to it!
+ */
+ if (addTo.size() == 0)
+ {
+ addTo.add(range);
+ return;
+ }
+
+ int[] last = addTo.get(addTo.size() - 1);
+ boolean lastForward = last[1] >= last[0];
+ boolean newForward = range[1] >= range[0];
+
+ /*
+ * contiguous range in the same direction - just update endpoint
+ */
+ if (lastForward == newForward && last[1] == range[0])
+ {
+ last[1] = range[1];
+ return;
+ }
+
+ /*
+ * next range starts at +1 in forward sense - update endpoint
+ */
+ if (lastForward && newForward && range[0] == last[1] + 1)
+ {
+ last[1] = range[1];
+ return;
+ }
+
+ /*
+ * next range starts at -1 in reverse sense - update endpoint
+ */
+ if (!lastForward && !newForward && range[0] == last[1] - 1)
+ {
+ last[1] = range[1];
+ return;
+ }
+
+ /*
+ * just add the new range
+ */
+ addTo.add(range);
+ }
/**
* Converts a list of {@code start-end} ranges to a single array of
}
return result;
}
+
+ /*
+ * Returns the maximal start-end positions in the given (ordered) list of
+ * ranges which is overlapped by the given begin-end range, or null if there
+ * is no overlap.
+ *
+ * <pre>
+ * Examples:
+ * if ranges is {[4, 8], [10, 12], [16, 19]}
+ * then
+ * findOverlap(ranges, 1, 20) == [4, 19]
+ * findOverlap(ranges, 6, 11) == [6, 11]
+ * findOverlap(ranges, 9, 15) == [10, 12]
+ * findOverlap(ranges, 13, 15) == null
+ * </pre>
+ *
+ * @param ranges
+ * @param begin
+ * @param end
+ * @return
+ */
+ protected static int[] findOverlap(List<int[]> ranges, final int begin,
+ final int end)
+ {
+ boolean foundStart = false;
+ int from = 0;
+ int to = 0;
+
+ /*
+ * traverse the ranges to find the first position (if any) >= begin,
+ * and the last position (if any) <= end
+ */
+ for (int[] range : ranges)
+ {
+ if (!foundStart)
+ {
+ if (range[0] >= begin)
+ {
+ /*
+ * first range that starts with, or follows, begin
+ */
+ foundStart = true;
+ from = Math.max(range[0], begin);
+ }
+ else if (range[1] >= begin)
+ {
+ /*
+ * first range that contains begin
+ */
+ foundStart = true;
+ from = begin;
+ }
+ }
+
+ if (range[0] <= end)
+ {
+ to = Math.min(end, range[1]);
+ }
+ }
+
+ return foundStart && to >= from ? new int[] { from, to } : null;
+ }
}
import java.util.ResourceBundle.Control;
import java.util.Set;
- import org.apache.log4j.Logger;
+ import jalview.log.JLoggerLog4j;
/**
*
{
private static ResourceBundle rb;
- // BH 2018 switched to org.apache.llog4j.Logger
- private static Logger log = Logger
+ private static JLoggerLog4j log = JLoggerLog4j
.getLogger(MessageManager.class.getCanonicalName());
private static Locale loc;
// Locale.setDefault(loc);
/* Getting messages for GV */
log.info("Getting messages for lang: " + loc);
- rb = ResourceBundle.getBundle("lang.Messages", Platform.getLocaleOrNone(loc), Control.getControl(Control.FORMAT_PROPERTIES));
+ Control control = Control.getControl(Control.FORMAT_PROPERTIES);
- rb = ResourceBundle.getBundle("lang.Messages", loc, control);
++ rb = ResourceBundle.getBundle("lang.Messages", Platform.getLocaleOrNone(loc), control);
// if (log.isLoggable(Level.FINEST))
// {
// // this might take a while, so we only do it if it will be shown
} catch (Exception e)
{
String msg = "I18N missing: " + loc + "\t" + key;
- logWarning(key, msg);
+ logWarning(key, msg);
}
return value;
}
*/
public static String getStringOrReturn(String keyroot, String name)
{
- String smkey = keyroot + name.toLowerCase(Locale.ROOT).replaceAll(" ", "");
+ String smkey = keyroot
+ + name.toLowerCase(Locale.ROOT).replaceAll(" ", "");
try
{
name = rb.getString(smkey);
} catch (Exception x)
{
- String msg = "I18N missing key with root " + keyroot + ": " + loc + "\t"
- + smkey;
- logWarning(smkey, msg);
+ String msg = "I18N missing key with root " + keyroot + ": " + loc
+ + "\t" + smkey;
+ logWarning(smkey, msg);
}
return name;
}
* @param key
* @param msg
*/
- private static void logWarning(String key, String msg)
- {
- if (!reportedMissing.contains(key))
+ private static void logWarning(String key, String msg)
{
+ if (!reportedMissing.contains(key))
+ {
reportedMissing.add(key);
- log.info(msg);
- }
+ log.info(msg);
+ }
}
}
*/
package jalview.util;
-import jalview.javascript.json.JSON;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
+import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
+import java.lang.reflect.Method;
import java.net.URL;
+import java.nio.channels.Channels;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.Date;
+import java.util.Locale;
+import java.util.Map;
import java.util.Properties;
+import java.util.logging.ConsoleHandler;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import javax.swing.SwingUtilities;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
+import com.stevesoft.pat.Regex;
+
+import jalview.bin.Jalview;
+import jalview.javascript.json.JSON;
+import swingjs.api.JSUtilI;
/**
* System platform information used by Applet and Application
*
private static Boolean isNoJSMac = null, isNoJSWin = null, isMac = null,
isWin = null, isLinux = null;
-
private static Boolean isHeadless = null;
+ private static swingjs.api.JSUtilI jsutil;
+
+ static
+ {
+ if (isJS)
+ {
+ try
+ {
+ // this is ok - it's a highly embedded method in Java; the deprecation
+ // is
+ // really a recommended best practice.
+ jsutil = ((JSUtilI) Class.forName("swingjs.JSUtil").newInstance());
+ } catch (InstantiationException | IllegalAccessException
+ | ClassNotFoundException e)
+ {
+ e.printStackTrace();
+ }
+ }
+ }
-
/**
* added to group mouse events into Windows and nonWindows (mac, unix, linux)
*
: isMac);
}
+ public static int SHORTCUT_KEY_MASK = (Platform.isMac()
+ ? KeyEvent.META_DOWN_MASK
+ : KeyEvent.CTRL_DOWN_MASK);
+
+ static
+ {
+ if (!GraphicsEnvironment.isHeadless())
+ {
+ // Using non-deprecated Extended key mask modifiers, but Java 8 has no
+ // getMenuShortcutKeyMaskEx method
+ Toolkit tk = Toolkit.getDefaultToolkit();
+ Method method = null;
+ try
+ {
+ method = tk.getClass().getMethod("getMenuShortcutKeyMaskEx");
+ } catch (Exception e)
+ {
+ System.err.println(
+ "Could not find Toolkit method getMenuShortcutKeyMaskEx. Trying getMenuShortcutKeyMask.");
+ }
+ if (method == null)
+ {
+ try
+ {
+ method = tk.getClass().getMethod("getMenuShortcutKeyMask");
+ } catch (Exception e)
+ {
+ System.err.println(
+ "Could not find Toolkit method getMenuShortcutKeyMaskEx or getMenuShortcutKeyMask.");
+ e.printStackTrace();
+ }
+ }
+ if (method != null)
+ {
+ try
+ {
+ method.setAccessible(true);
+ SHORTCUT_KEY_MASK = ((int) method.invoke(tk, new Object[0]));
+ } catch (Exception e)
+ {
+ e.printStackTrace();
+ }
+ }
+ if (SHORTCUT_KEY_MASK <= 0xF)
+ {
+ // shift this into the extended region (was Java 8)
+ SHORTCUT_KEY_MASK = SHORTCUT_KEY_MASK << 6;
+ }
+ }
+ }
/**
* added to group mouse events into Windows and nonWindows (mac, unix, linux)
*
public static boolean isLinux()
{
return (isLinux == null
- ? (isLinux = (System.getProperty("os.name").indexOf("Linux") >= 0))
+ ? (isLinux = (System.getProperty("os.name")
+ .indexOf("Linux") >= 0))
: isLinux);
}
}
/**
- * Check if we are on a Microsoft plaform...
+ * Check if we are on a Microsoft platform...
*
* @return true if we have to cope with another platform variation
*/
*/
protected static boolean isControlDown(MouseEvent e, boolean aMac)
{
- if (!aMac)
- {
- return e.isControlDown();
-
- // Jalview 2.11 code below: above is as amended for JalviewJS
- // /*
- // * answer false for right mouse button
- // */
- // if (e.isPopupTrigger())
- // {
- // return false;
- // }
- // return
- // (jalview.util.ShortcutKeyMaskExWrapper.getMenuShortcutKeyMaskEx() //
- // .getMenuShortcutKeyMaskEx()
- // & jalview.util.ShortcutKeyMaskExWrapper
- // .getModifiersEx(e)) != 0; // getModifiers()) != 0;
- }
- // answer false for right mouse button
- // shortcut key will be META for a Mac
- return !e.isPopupTrigger()
- && (Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
- & e.getModifiers()) != 0;
- // could we use e.isMetaDown() here?
+ //
+ // System.out.println(e.isPopupTrigger()
+ // + " " + ((SHORTCUT_KEY_MASK & e.getModifiersEx()) != 0)
+ // + " " + e.isControlDown());
+ return (aMac
+ ? !e.isPopupTrigger()
+ && (SHORTCUT_KEY_MASK & e.getModifiersEx()) != 0
+ : e.isControlDown());
}
// BH: I don't know about that previous method. Here is what SwingJS uses.
public static long time, mark, set, duration;
+ /**
+ * typical usage:
+ *
+ * Platform.timeCheck(null, Platform.TIME_MARK);
+ *
+ * ...
+ *
+ * Platform.timeCheck("some message", Platform.TIME_MARK);
+ *
+ * reset...[set/mark]n...get
+ *
+ * @param msg
+ * @param mode
+ */
public static void timeCheck(String msg, int mode)
{
long t = System.currentTimeMillis();
{
case TIME_RESET:
time = mark = t;
+ duration = 0;
if (msg != null)
{
System.err.println("Platform: timer reset\t\t\t" + msg);
case TIME_MARK:
if (set > 0)
{
+ // total time between set/mark points
duration += (t - set);
}
else
public static void cacheFileData(String path, Object data)
{
- if (!isJS() || data == null)
+ if (isJS && data != null)
{
- return;
+ jsutil.cachePathData(path, data);
}
- /**
- * @j2sNative
- *
- * swingjs.JSUtil.cacheFileData$S$O(path, data);
- *
- */
}
public static void cacheFileData(File file)
{
- byte[] data;
- if (!isJS() || (data = Platform.getFileBytes(file)) == null)
+ if (isJS)
{
- return;
+ byte[] data = Platform.getFileBytes(file);
+ {
+ if (data != null)
+ {
+ cacheFileData(file.toString(), data);
+ }
+ }
}
- cacheFileData(file.toString(), data);
}
public static byte[] getFileBytes(File f)
{
- return /** @j2sNative f && swingjs.JSUtil.getFileAsBytes$O(f) || */
- null;
+ return (isJS && f != null ? jsutil.getBytes(f) : null);
}
public static byte[] getFileAsBytes(String fileStr)
{
- byte[] bytes = null;
- // BH 2018 hack for no support for access-origin
- /**
- * @j2sNative bytes = swingjs.JSUtil.getFileAsBytes$O(fileStr)
- */
- cacheFileData(fileStr, bytes);
- return bytes;
+ if (isJS && fileStr != null)
+ {
+ byte[] bytes = (byte[]) jsutil.getFile(fileStr, false);
+ cacheFileData(fileStr, bytes);
+ return bytes;
+ }
+ return null;
}
- @SuppressWarnings("unused")
public static String getFileAsString(String url)
{
- String ret = null;
- /**
- * @j2sNative
- *
- * ret = swingjs.JSUtil.getFileAsString$S(url);
- *
- *
- */
- cacheFileData(url, ret);
- return ret;
+ if (isJS && url != null)
+ {
+ String ret = (String) jsutil.getFile(url, true);
+ cacheFileData(url, ret);
+ return ret;
+ }
+ return null;
}
public static boolean setFileBytes(File f, String urlstring)
{
- if (!isJS())
+ if (isJS && f != null && urlstring != null)
{
- return false;
+ @SuppressWarnings("unused")
+ byte[] bytes = getFileAsBytes(urlstring);
+ jsutil.setFileBytes(f, bytes);
+ return true;
}
- @SuppressWarnings("unused")
- byte[] bytes = getFileAsBytes(urlstring);
- // TODO temporary doubling of 秘bytes and _bytes;
- // just remove _bytes when new transpiler has been installed
- /**
- * @j2sNative f.\u79d8bytes = f._bytes = bytes;
- */
- return true;
+ return false;
}
public static void addJ2SBinaryType(String ext)
{
- /**
- * @j2sNative
- *
- * J2S._binaryTypes.push("." + ext + "?");
- *
- */
+ if (isJS)
+ {
+ jsutil.addBinaryFileType(ext);
+ }
}
/**
* @param url
* @return true if window has been opened
*/
- public static boolean openURL(String url)
+ public static boolean openURL(String url) throws IOException
{
if (!isJS())
{
public static String getUniqueAppletID()
{
- /**
- * @j2sNative return swingjs.JSUtil.getApplet$()._uniqueId;
- *
- */
- return null;
+ return (isJS ? (String) jsutil.getAppletAttribute("_uniqueId") : null);
}
*/
public static void readInfoProperties(String prefix, Properties p)
{
- if (!isJS())
+ if (isJS)
{
- return;
- }
- String id = getUniqueAppletID();
- String key = "", value = "";
- /**
- * @j2sNative var info = swingjs.JSUtil.getApplet$().__Info || {}; for (var
- * key in info) { if (key.indexOf(prefix) == 0) { value = "" +
- * info[key];
- */
+ String id = getUniqueAppletID();
- System.out.println(
- "Platform id=" + id + " reading Info." + key + " = " + value);
- p.put(id + "_" + key, value);
+ String key = "";
+ String value = "";
+ @SuppressWarnings("unused")
+ Object info = jsutil.getAppletAttribute("__Info");
+ /**
+ * @j2sNative for (key in info) { value = info[key];
+ */
- /**
- * @j2sNative
- *
- *
- * } }
- */
+ if (key.indexOf(prefix) == 0)
+ {
+ System.out.println("Platform id=" + id + " reading Info." + key
+ + " = " + value);
+ p.put(key, value);
+
+ }
+
+ /**
+ * @j2sNative }
+ */
+ }
}
public static void setAjaxJSON(URL url)
public static void streamToFile(InputStream is, File outFile)
throws IOException
{
- if (isJS() && /**
- * @j2sNative outFile.setBytes$O && outFile.setBytes$O(is) &&
- */
- true)
+ if (isJS)
{
+ jsutil.setFileBytes(outFile, is);
return;
}
FileOutputStream fio = new FileOutputStream(outFile);
public static void addJ2SDirectDatabaseCall(String domain)
{
- if (isJS())
+ if (isJS)
{
+ jsutil.addDirectDatabaseCall(domain);
System.out.println(
-- "Platform adding known access-control-allow-origin * for domain "
-- + domain);
++ "Platform adding known access-control-allow-origin * for domain "
++ + domain);
+ /**
+ * @j2sNative
+ *
+ * J2S.addDirectDatabaseCall(domain);
+ */
}
}
+ /**
+ * Allow for URL-line command arguments. Untested.
+ *
+ */
public static void getURLCommandArguments()
{
-
- try
- {
+ try {
/**
* Retrieve the first query field as command arguments to Jalview. Include
* only if prior to "?j2s" or "&j2s" or "#". Assign the applet's
*
* @j2sNative var a =
* decodeURI((document.location.href.replace("&","?").split("?j2s")[0]
- * + "?").split("?")[1].split("#")[0]); a &&
- * (System.out.println("URL arguments detected were "+a)) &&
- * (J2S.thisApplet.__Info.urlargs = a.split(" "));
- * (!J2S.thisApplet.__Info.args || J2S.thisApplet.__Info.args
- * == "" || J2S.thisApplet.__Info.args == "??") &&
- * (J2S.thisApplet.__Info.args = a) && (System.out.println("URL
- * arguments were passed to J2S main."));
+ * + "?").split("?")[1].split("#")[0]); a && (System.out.println("URL arguments detected were "+a)) &&
+ * (J2S.thisApplet.__Info.urlargs = a.split(" "));
+ * (!J2S.thisApplet.__Info.args || J2S.thisApplet.__Info.args == "" || J2S.thisApplet.__Info.args == "??") && (J2S.thisApplet.__Info.args = a) && (System.out.println("URL arguments were passed to J2S main."));
*/
} catch (Throwable t)
{
}
-
}
/**
String p2 = path2.replace('\\', '/');
return p1.equals(p2);
}
+ ///////////// JAL-3253 Applet additions //////////////
+
+ /**
+ * Retrieve the object's embedded size from a div's style on a page if
+ * embedded in SwingJS.
+ *
+ * @param frame
+ * JFrame or JInternalFrame
+ * @param defaultWidth
+ * use -1 to return null (no default size)
+ * @param defaultHeight
+ * @return the embedded dimensions or null (no default size or not embedded)
+ */
+ public static Dimension getDimIfEmbedded(Component frame,
+ int defaultWidth, int defaultHeight)
+ {
+ Dimension d = null;
+ if (isJS)
+ {
+ d = (Dimension) getEmbeddedAttribute(frame, "dim");
+ }
+ return (d == null && defaultWidth >= 0
+ ? new Dimension(defaultWidth, defaultHeight)
+ : d);
+
+ }
+
+ public static Regex newRegex(String regex)
+ {
+ return newRegex(regex, null);
+ }
+
+ public static Regex newRegex(String searchString, String replaceString)
+ {
+ ensureRegex();
+ return (replaceString == null ? new Regex(searchString)
+ : new Regex(searchString, replaceString));
+ }
+
+ public static Regex newRegexPerl(String code)
+ {
+ ensureRegex();
+ return Regex.perlCode(code);
+ }
+
+ /**
+ * Initialize Java debug logging. A representative sample -- adapt as desired.
+ */
+ public static void startJavaLogging()
+ {
+ /**
+ * @j2sIgnore
+ */
+ {
+ logClass("java.awt.EventDispatchThread", "java.awt.EventQueue",
+ "java.awt.Component", "java.awt.focus.Component",
+ "java.awt.event.Component",
+ "java.awt.focus.DefaultKeyboardFocusManager");
+ }
+ }
+
+ /**
+ * Initiate Java logging for a given class. Only for Java, not JavaScript;
+ * Allows debugging of complex event processing.
+ *
+ * @param className
+ */
+ public static void logClass(String... classNames)
+ {
+ /**
+ * @j2sIgnore
+ *
+ *
+ */
+ {
+ Logger rootLogger = Logger.getLogger("");
+ rootLogger.setLevel(Level.ALL);
+ ConsoleHandler consoleHandler = new ConsoleHandler();
+ consoleHandler.setLevel(Level.ALL);
+ for (int i = classNames.length; --i >= 0;)
+ {
+ Logger logger = Logger.getLogger(classNames[i]);
+ logger.setLevel(Level.ALL);
+ logger.addHandler(consoleHandler);
+ }
+ }
+ }
+
+ /**
+ * load a resource -- probably a core file -- if and only if a particular
+ * class has not been instantialized. We use a String here because if we used
+ * a .class object, that reference itself would simply load the class, and we
+ * want the core package to include that as well.
+ *
+ * @param resourcePath
+ * @param className
+ */
+ public static void loadStaticResource(String resourcePath,
+ String className)
+ {
+ if (isJS)
+ {
+ jsutil.loadResourceIfClassUnknown(resourcePath, className);
+ }
+ }
+
+ public static void ensureRegex()
+ {
+ if (isJS)
+ {
+ loadStaticResource("core/core_stevesoft.z.js",
+ "com.stevesoft.pat.Regex");
+ }
+ }
+
+ /**
+ * Set the "app" property of the HTML5 applet object, for example,
+ * "testApplet.app", to point to the Jalview instance. This will be the object
+ * that page developers use that is similar to the original Java applet object
+ * that was accessed via LiveConnect.
+ *
+ * @param j
+ */
+ public static void setAppClass(Object j)
+ {
+ if (isJS)
+ {
+ jsutil.setAppClass(j);
+ }
+ }
+
+ /**
+ *
+ * If this frame is embedded in a web page, return a known type.
+ *
+ * @param frame
+ * a JFrame or JInternalFrame
+ * @param type
+ * "name", "node", "init", "dim", or any DOM attribute, such as "id"
+ * @return null if frame is not embedded.
+ */
+ public static Object getEmbeddedAttribute(Component frame, String type)
+ {
+ return (isJS ? jsutil.getEmbeddedAttribute(frame, type) : null);
+ }
+
+ public static void stackTrace()
+ {
+ try
+ {
+ throw new NullPointerException();
+ } catch (Exception e)
+ {
+ e.printStackTrace();
+ }
+
+ }
+
+ public static URL getDocumentBase()
+ {
+ return (isJS ? jsutil.getDocumentBase() : null);
+ }
+
+ public static URL getCodeBase()
+ {
+ return (isJS ? jsutil.getCodeBase() : null);
+ }
+
+ public static String getUserPath(String subpath)
+ {
+ char sep = File.separatorChar;
+ return System.getProperty("user.home") + sep
+ + subpath.replace('/', sep);
+ }
+
+ /**
+ * This method enables checking if a cached file has exceeded a certain
+ * threshold(in days)
+ *
+ * @param file
+ * the cached file
+ * @param noOfDays
+ * the threshold in days
+ * @return
+ */
+ public static boolean isFileOlderThanThreshold(File file, int noOfDays)
+ {
+ if (isJS())
+ {
+ // not meaningful in SwingJS -- this is a session-specific temp file. It
+ // doesn't have a timestamp.
+ return false;
+ }
+ Path filePath = file.toPath();
+ BasicFileAttributes attr;
+ int diffInDays = 0;
+ try
+ {
+ attr = Files.readAttributes(filePath, BasicFileAttributes.class);
+ diffInDays = (int) ((new Date().getTime()
+ - attr.lastModifiedTime().toMillis())
+ / (1000 * 60 * 60 * 24));
+ // System.out.println("Diff in days : " + diffInDays);
+ } catch (IOException e)
+ {
+ e.printStackTrace();
+ }
+ return noOfDays <= diffInDays;
+ }
+
+ /**
+ * Get the leading integer part of a string that begins with an integer.
+ *
+ * @param input
+ * - the string input to process
+ * @param failValue
+ * - value returned if unsuccessful
+ * @return
+ */
+ public static int getLeadingIntegerValue(String input, int failValue)
+ {
+ if (input == null)
+ {
+ return failValue;
+ }
+ if (isJS)
+ {
+ int val = /** @j2sNative 1 ? parseInt(input) : */
+ 0;
+ return (val == val + 0 ? val : failValue);
+ }
+ // JavaScript does not support Regex ? lookahead
+ String[] parts = input.split("(?=\\D)(?<=\\d)");
+ if (parts != null && parts.length > 0 && parts[0].matches("[0-9]+"))
+ {
+ return Integer.valueOf(parts[0]);
+ }
+ return failValue;
+ }
+
+ public static Map<String, Object> getAppletInfoAsMap()
+ {
+ return (isJS ? jsutil.getAppletInfoAsMap() : null);
+ }
+
+ /**
+ * Get the SwingJS applet ID and combine that with the frameType
+ *
+ * @param frameType
+ * "alignment", "desktop", etc., or null
+ * @return
+ */
+ public static String getAppID(String frameType)
+ {
+
+ String id = Jalview.getInstance().j2sAppletID;
+ if (id == null)
+ {
+ Jalview.getInstance().j2sAppletID = id = (isJS
+ ? (String) jsutil.getAppletAttribute("_id")
+ : "jalview");
+ }
+ return id + (frameType == null ? "" : "-" + frameType);
+ }
+
+ /**
+ * Option to avoid unnecessary seeking of nonexistent resources in JavaScript.
+ * Works in Java as well.
+ *
+ * @param loc
+ * @return
+ */
+ public static Locale getLocaleOrNone(Locale loc)
+ {
+ return (isJS && loc.getLanguage() == "en" ? new Locale("") : loc);
+ }
+
+ /**
+ * From UrlDownloadClient; trivial in JavaScript; painful in Java.
+ *
+ * @param urlstring
+ * @param outfile
+ * @throws IOException
+ */
+ public static void download(String urlstring, String outfile)
+ throws IOException
+ {
+ Path temp = null;
+ try (InputStream is = new URL(urlstring).openStream())
+ {
+ if (isJS)
+ { // so much easier!
+ streamToFile(is, new File(outfile));
+ return;
+ }
+ temp = Files.createTempFile(".jalview_", ".tmp");
+ try (FileOutputStream fos = new FileOutputStream(temp.toString());
+ ReadableByteChannel rbc = Channels.newChannel(is))
+ {
+ fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
+ // copy tempfile to outfile once our download completes
+ // incase something goes wrong
+ Files.copy(temp, Paths.get(outfile),
+ StandardCopyOption.REPLACE_EXISTING);
+ }
+ } catch (IOException e)
+ {
+ throw e;
+ } finally
+ {
+ try
+ {
+ if (temp != null)
+ {
+ Files.deleteIfExists(temp);
+ }
+ } catch (IOException e)
+ {
+ System.out.println("Exception while deleting download temp file: "
+ + e.getMessage());
+ }
+ }
+ }
}
}
/**
+ * Returns the last part of 'input' after the last occurrence of 'token'. For
+ * example to extract only the filename from a full path or URL.
+ *
+ * @param input
+ * @param token
+ * a delimiter which must be in regular expression format
+ * @return
+ */
+ public static String getLastToken(String input, String token)
+ {
+ if (input == null)
+ {
+ return null;
+ }
+ if (token == null)
+ {
+ return input;
+ }
+ String[] st = input.split(token);
+ return st[st.length - 1];
+ }
+
+ /**
* Parses the input string into components separated by the delimiter. Unlike
* String.split(), this method will ignore occurrences of the delimiter which
* are nested within single quotes in name-value pair values, e.g. a='b,c'.
{
return s.toUpperCase(Locale.ROOT);
}
- return s.substring(0, 1).toUpperCase(Locale.ROOT) + s.substring(1).toLowerCase(Locale.ROOT);
+ return s.substring(0, 1).toUpperCase(Locale.ROOT)
+ + s.substring(1).toLowerCase(Locale.ROOT);
}
/**
{
text = text.substring(0, endTag);
}
-
+
if (startTag == -1 && (text.contains("<") || text.contains(">")))
{
text = text.replaceAll("<", "<");
}
/**
- * Answers the input string with any occurrences of the 'encodeable' characters
- * replaced by their URL encoding
+ * Answers the input string with any occurrences of the 'encodeable'
+ * characters replaced by their URL encoding
*
* @param s
* @param encodable
return enc;
}
+ /**
+ * Answers true if the string is not empty and consists only of digits, or
+ * characters 'a'-'f' or 'A'-'F', else false
+ *
+ * @param s
+ * @return
+ */
+ public static boolean isHexString(String s)
+ {
+ int j = s.length();
+ if (j == 0)
+ {
+ return false;
+ }
+ for (int i = 0; i < j; i++)
+ {
+ int c = s.charAt(i);
+ if (!(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F'))
+ {
+ return false;
+ }
+ }
+ return true;
+ }
++
+ public static int firstCharPosIgnoreCase(String text, String chars)
+ {
+ int min = text.length() + 1;
+ for (char c : chars.toLowerCase(Locale.ROOT).toCharArray())
+ {
+ int i = text.toLowerCase(Locale.ROOT).indexOf(c);
+ if (0 <= i && i < min)
+ {
+ min = i;
+ }
+ }
+ return min < text.length() + 1 ? min : -1;
+ }
}
import jalview.analysis.AnnotationSorter.SequenceAnnotationOrder;
import jalview.analysis.Conservation;
import jalview.analysis.TreeModel;
-import jalview.api.AlignCalcManagerI;
+import jalview.api.AlignCalcManagerI2;
+import jalview.api.AlignCalcWorkerI;
import jalview.api.AlignExportSettingsI;
import jalview.api.AlignViewportI;
import jalview.api.AlignmentViewPanel;
import jalview.util.MappingUtils;
import jalview.util.MessageManager;
import jalview.viewmodel.styles.ViewStyle;
-import jalview.workers.AlignCalcManager;
+import jalview.workers.AlignCalcManager2;
import jalview.workers.ComplementConsensusThread;
import jalview.workers.ConsensusThread;
+import jalview.workers.InformationThread;
import jalview.workers.StrucConsensusThread;
import java.awt.Color;
public abstract class AlignmentViewport
implements AlignViewportI, CommandListener, VamsasSource
{
+ public static final String PROPERTY_ALIGNMENT = "alignment";
+ public static final String PROPERTY_SEQUENCE = "sequence";
protected ViewportRanges ranges;
protected ViewStyleI viewStyle = new ViewStyle();
* alignment displayed in the viewport. Please use get/setter
*/
protected AlignmentI alignment;
+
+ /*
+ * probably unused indicator that view is of a dataset rather than an
+ * alignment
+ */
+
+ protected boolean ignoreBelowBackGroundFrequencyCalculation = false;
+
+ protected boolean infoLetterHeight = false;
+
+ protected AlignmentAnnotation occupancy;
+
+ /**
+ * results of alignment consensus analysis for visible portion of view
+ */
+ protected ProfilesI consensusProfiles;
+
+ /**
+ * HMM profile for the alignment
+ */
+ protected ProfilesI hmmProfiles;
public AlignmentViewport(AlignmentI al)
{
*/
protected boolean isDataset = false;
+
public void setDataset(boolean b)
{
isDataset = b;
protected ColumnSelection colSel = new ColumnSelection();
- public boolean autoCalculateConsensus = true;
+ protected boolean autoCalculateConsensusAndConservation = true;
+
+ public boolean getAutoCalculateConsensusAndConservation()
+ { // BH 2019.07.24
+ return autoCalculateConsensusAndConservation;
+ }
+
+ public void setAutoCalculateConsensusAndConservation(boolean b)
+ {
+ autoCalculateConsensusAndConservation = b;
+ }
protected boolean autoCalculateStrucConsensus = true;
+ public boolean getAutoCalculateStrucConsensus()
+ { // BH 2019.07.24
+ return autoCalculateStrucConsensus;
+ }
+
+ public void setAutoCalculateStrucConsensus(boolean b)
+ {
+ autoCalculateStrucConsensus = b;
+ }
protected boolean ignoreGapsInConsensusCalculation = false;
protected ResidueShaderI residueShading = new ResidueShader();
+
@Override
public void setGlobalColourScheme(ColourSchemeI cs)
{
* retain any colour thresholds per group while
* changing choice of colour scheme (JAL-2386)
*/
- sg.setColourScheme(cs == null ? null : cs.getInstance(this, sg));
+ sg.setColourScheme(
+ cs == null ? null : cs.getInstance(this, sg));
if (cs != null)
{
sg.getGroupColourScheme().alignmentChanged(sg,
return residueShading;
}
+
protected AlignmentAnnotation consensus;
protected AlignmentAnnotation complementConsensus;
protected Conservation hconservation = null;
+
@Override
public void setConservation(Conservation cons)
{
}
@Override
+ public void setHmmProfiles(ProfilesI info)
+ {
+ hmmProfiles = info;
+ }
+
+ @Override
+ public ProfilesI getHmmProfiles()
+ {
+ return hmmProfiles;
+ }
+
+ @Override
public Hashtable<String, Object>[] getComplementConsensusHash()
{
return hcomplementConsensus;
return strucConsensus;
}
- protected AlignCalcManagerI calculator = new AlignCalcManager();
+ protected AlignCalcManagerI2 calculator = new AlignCalcManager2();
/**
* trigger update of conservation annotation
// see note in mantis : issue number 8585
if (alignment.isNucleotide()
|| (conservation == null && quality == null)
- || !autoCalculateConsensus)
+ || !autoCalculateConsensusAndConservation)
{
return;
}
- if (calculator.getRegisteredWorkersOfClass(
- jalview.workers.ConservationThread.class) == null)
+ if (calculator.getWorkersOfClass(
+ jalview.workers.ConservationThread.class).isEmpty())
{
calculator.registerWorker(
new jalview.workers.ConservationThread(this, ap));
public void updateConsensus(final AlignmentViewPanel ap)
{
// see note in mantis : issue number 8585
- if (consensus == null || !autoCalculateConsensus)
+ if (consensus == null || !autoCalculateConsensusAndConservation)
{
return;
}
- if (calculator
- .getRegisteredWorkersOfClass(ConsensusThread.class) == null)
+ if (calculator.getWorkersOfClass(ConsensusThread.class).isEmpty())
{
calculator.registerWorker(new ConsensusThread(this, ap));
}
}
if (doConsensus)
{
- if (calculator.getRegisteredWorkersOfClass(
- ComplementConsensusThread.class) == null)
+ if (calculator.getWorkersOfClass(ComplementConsensusThread.class).isEmpty())
{
- calculator
- .registerWorker(new ComplementConsensusThread(this, ap));
+ calculator.registerWorker(new ComplementConsensusThread(this, ap));
}
}
}
}
+ @Override
+ public void initInformationWorker(final AlignmentViewPanel ap)
+ {
+ if (calculator.getWorkersOfClass(InformationThread.class).isEmpty())
+ {
+ calculator.registerWorker(new InformationThread(this, ap));
+ }
+ }
// --------START Structure Conservation
public void updateStrucConsensus(final AlignmentViewPanel ap)
{
{
return;
}
- if (calculator.getRegisteredWorkersOfClass(
- StrucConsensusThread.class) == null)
+ if (calculator.getWorkersOfClass(StrucConsensusThread.class).isEmpty())
{
calculator.registerWorker(new StrucConsensusThread(this, ap));
}
{
return false;
}
- if (calculator.workingInvolvedWith(alignmentAnnotation))
+ if (calculator.isWorkingWithAnnotation(alignmentAnnotation))
{
// System.err.println("grey out ("+alignmentAnnotation.label+")");
return true;
strucConsensus = null;
conservation = null;
quality = null;
+ consensusProfiles = null;
groupConsensus = null;
groupConservation = null;
hconsensus = null;
hconservation = null;
hcomplementConsensus = null;
gapcounts = null;
+ calculator.shutdown();
calculator = null;
residueShading = null; // may hold a reference to Consensus
changeSupport = null;
ranges = null;
currentTree = null;
selectionGroup = null;
+ colSel = null;
setAlignment(null);
}
}
@Override
- public AlignCalcManagerI getCalcManager()
+ public AlignCalcManagerI2 getCalcManager()
{
return calculator;
}
protected boolean showConsensusHistogram = true;
/**
+ * should hmm profile be rendered by default
+ */
+ protected boolean hmmShowSequenceLogo = false;
+
+ /**
+ * should hmm profile be rendered normalised to row height
+ */
+ protected boolean hmmNormaliseSequenceLogo = false;
+
+ /**
+ * should information histograms be rendered by default
+ */
+ protected boolean hmmShowHistogram = true;
+
+ /**
* @return the showConsensusProfile
*/
@Override
}
/**
+ * @return the showInformationProfile
+ */
+ @Override
+ public boolean isShowHMMSequenceLogo()
+ {
+ return hmmShowSequenceLogo;
+ }
+
+ /**
* @param showSequenceLogo
* the new value
*/
// TODO: decouple settings setting from calculation when refactoring
// annotation update method from alignframe to viewport
this.showSequenceLogo = showSequenceLogo;
- calculator.updateAnnotationFor(ConsensusThread.class);
- calculator.updateAnnotationFor(ComplementConsensusThread.class);
- calculator.updateAnnotationFor(StrucConsensusThread.class);
+ for (AlignCalcWorkerI worker : calculator.getWorkers())
+ {
+ if (worker.getClass().equals(ConsensusThread.class) ||
+ worker.getClass().equals(ComplementConsensusThread.class) ||
+ worker.getClass().equals(StrucConsensusThread.class))
+ {
+ worker.updateAnnotation();
+ }
+ }
}
this.showSequenceLogo = showSequenceLogo;
}
+ public void setShowHMMSequenceLogo(boolean showHMMSequenceLogo)
+ {
+ if (showHMMSequenceLogo != this.hmmShowSequenceLogo)
+ {
+ this.hmmShowSequenceLogo = showHMMSequenceLogo;
+ // TODO: updateAnnotation if description (tooltip) will show
+ // profile in place of information content?
+ // calculator.updateAnnotationFor(InformationThread.class);
+ }
+ this.hmmShowSequenceLogo = showHMMSequenceLogo;
+ }
/**
* @param showConsensusHistogram
* the showConsensusHistogram to set
}
/**
+ * @param showInformationHistogram
+ */
+ public void setShowInformationHistogram(boolean showInformationHistogram)
+ {
+ this.hmmShowHistogram = showInformationHistogram;
+ }
+
+ /**
* @return the showGroupConservation
*/
public boolean isShowGroupConservation()
}
/**
+ *
+ * @return flag to indicate if the information content histogram should be
+ * rendered by default
+ */
+ @Override
+ public boolean isShowInformationHistogram()
+ {
+ return this.hmmShowHistogram;
+ }
+
+ /**
* when set, updateAlignment will always ensure sequences are of equal length
*/
private boolean padGaps = false;
ignoreGapsInConsensusCalculation);
}
}
+ }
+ public void setIgnoreBelowBackground(boolean b, AlignmentViewPanel ap)
+ {
+ ignoreBelowBackGroundFrequencyCalculation = b;
+ }
+
+ public void setInfoLetterHeight(boolean b, AlignmentViewPanel ap)
+ {
+ infoLetterHeight = b;
}
private long sgrouphash = -1, colselhash = -1;
* checks current colsel against record of last hash value, and optionally
* updates record.
*
- * @param b
+ * @param updateHash
* update the record of last hash value
* @return true if colsel changed since last call (when b is true)
*/
- public boolean isColSelChanged(boolean b)
+ public boolean isColSelChanged(boolean updateHash)
{
int hc = (colSel == null || colSel.isEmpty()) ? -1 : colSel.hashCode();
if (hc != -1 && hc != colselhash)
{
- if (b)
+ if (updateHash)
{
colselhash = hc;
}
return true;
}
+ notifySequence();
return false;
}
return ignoreGapsInConsensusCalculation;
}
+ @Override
+ public boolean isIgnoreBelowBackground()
+ {
+ return ignoreBelowBackGroundFrequencyCalculation;
+ }
+
+ @Override
+ public boolean isInfoLetterHeight()
+ {
+ return infoLetterHeight;
+ }
// property change stuff
// JBPNote Prolly only need this in the applet version.
private PropertyChangeSupport changeSupport = new PropertyChangeSupport(
}
}
- /**
- * Property change listener for changes in alignment
- *
- * @param prop
- * DOCUMENT ME!
- * @param oldvalue
- * DOCUMENT ME!
- * @param newvalue
- * DOCUMENT ME!
- */
- public void firePropertyChange(String prop, Object oldvalue,
- Object newvalue)
- {
- changeSupport.firePropertyChange(prop, oldvalue, newvalue);
- }
// common hide/show column stuff
ranges.setStartEndSeq(startSeq, endSeq + tmp.size());
- firePropertyChange("alignment", null, alignment.getSequences());
// used to set hasHiddenRows/hiddenRepSequences here, after the property
// changed event
+ notifySequence();
sendSelection();
}
}
ranges.setStartEndSeq(startSeq, endSeq + tmp.size());
- firePropertyChange("alignment", null, alignment.getSequences());
+ notifyAlignment();
sendSelection();
}
}
setSequenceAnnotationsVisible(seq[i], false);
}
ranges.setStartSeq(startSeq);
- firePropertyChange("alignment", null, alignment.getSequences());
+ notifyAlignment();
}
}
AlignmentAnnotation clone = new AlignmentAnnotation(annot);
if (selectedOnly && selectionGroup != null)
{
- clone.makeVisibleAnnotation(selectionGroup.getStartRes(),
- selectionGroup.getEndRes(), alignment.getHiddenColumns());
+ clone.makeVisibleAnnotation(
+ selectionGroup.getStartRes(), selectionGroup.getEndRes(),
+ alignment.getHiddenColumns());
}
else
{
{
alignment.padGaps();
}
- if (autoCalculateConsensus)
+ if (autoCalculateConsensusAndConservation)
{
updateConsensus(ap);
}
- if (hconsensus != null && autoCalculateConsensus)
+ if (hconsensus != null && autoCalculateConsensusAndConservation)
{
updateConservation(ap);
}
updateAllColourSchemes();
calculator.restartWorkers();
- // alignment.adjustSequenceAnnotations();
}
/**
boolean showprf = isShowSequenceLogo();
boolean showConsHist = isShowConsensusHistogram();
boolean normLogo = isNormaliseSequenceLogo();
+ boolean showHMMPrf = isShowHMMSequenceLogo();
+ boolean showInfoHist = isShowInformationHistogram();
+ boolean normHMMLogo = isNormaliseHMMSequenceLogo();
/**
* TODO reorder the annotation rows according to group/sequence ordering on
sg.setshowSequenceLogo(showprf);
sg.setShowConsensusHistogram(showConsHist);
sg.setNormaliseSequenceLogo(normLogo);
+ sg.setShowHMMSequenceLogo(showHMMPrf);
+ sg.setShowInformationHistogram(showInfoHist);
+ sg.setNormaliseHMMSequenceLogo(normHMMLogo);
}
if (conv)
{
return sq;
}
+ public boolean hasReferenceAnnotation()
+ {
+ AlignmentAnnotation[] annots = this.alignment.getAlignmentAnnotation();
+ for (AlignmentAnnotation annot : annots)
+ {
+ if ("RF".equals(annot.label) || annot.label.contains("Reference"))
+ {
+ return true;
+ }
+ }
+ return false;
+ }
@Override
public void setCurrentTree(TreeModel tree)
{
}
@Override
- public AlignmentExportData getAlignExportData(
- AlignExportSettingsI options)
+ public AlignmentExportData getAlignExportData(AlignExportSettingsI options)
{
AlignmentI alignmentToExport = null;
String[] omitHidden = null;
omitHidden, alignmentStartEnd);
return ed;
}
+
+ @Override
+ public boolean isNormaliseSequenceLogo()
+ {
+ return normaliseSequenceLogo;
+ }
+ public void setNormaliseSequenceLogo(boolean state)
+ {
+ normaliseSequenceLogo = state;
+ }
+
+ @Override
+ public boolean isNormaliseHMMSequenceLogo()
+ {
+ return hmmNormaliseSequenceLogo;
+ }
+
+ public void setNormaliseHMMSequenceLogo(boolean state)
+ {
+ hmmNormaliseSequenceLogo = state;
+ }
/**
* flag set to indicate if structure views might be out of sync with sequences
* in the alignment
return (alignment.getHiddenColumns().getVisContigsIterator(start, end,
false));
}
+ /**
+ * Filters out sequences with an eValue higher than the specified value. The
+ * filtered sequences are hidden or deleted. Sequences with no eValues are also
+ * filtered out.
+ *
+ * @param eValue
+ * @param delete
+ */
+ public void filterByEvalue(double eValue)
+ {
+ for (SequenceI seq : alignment.getSequencesArray())
+ {
+ if ((seq.getAnnotation("Search Scores") == null
+ || seq.getAnnotation("Search Scores")[0].getEValue() > eValue)
+ && seq.getHMM() == null)
+ {
+ hideSequence(new SequenceI[] { seq });
+ }
+ }
+ }
+
+ /**
+ * Filters out sequences with an score lower than the specified value. The
+ * filtered sequences are hidden or deleted.
+ *
+ * @param score
+ * @param delete
+ */
+ public void filterByScore(double score)
+ {
+ for (SequenceI seq : alignment.getSequencesArray())
+ {
+ if ((seq.getAnnotation("Search Scores") == null
+ || seq.getAnnotation("Search Scores")[0]
+ .getBitScore() < score)
+ && seq.getHMM() == null)
+ {
+ hideSequence(new SequenceI[] { seq });
+ }
+ }
+ }
+
+ /**
+ * Notify TreePanel and AlignmentPanel of some sort of alignment change.
+ */
+ public void notifyAlignment()
+ {
+ changeSupport.firePropertyChange(PROPERTY_ALIGNMENT, null, alignment.getSequences());
+ }
+
+ /**
+ * Notify AlignmentPanel of a sequence column selection or visibility changes.
+ */
+ public void notifySequence()
+ {
+ changeSupport.firePropertyChange(PROPERTY_SEQUENCE, null, null);
+ }
}
*/
package jalview.viewmodel;
+import java.awt.Dimension;
+
import jalview.api.AlignmentColsCollectionI;
import jalview.api.AlignmentRowsCollectionI;
import jalview.datamodel.AlignmentI;
private int ydiff; // when dragging, difference in alignment units between
// start sequence and original mouse click position
+
+ /**
+ * for testng only
+ *
+ * @param vpranges
+ * @param showAnnotationPanel
+ */
+ @Deprecated
+ public OverviewDimensionsShowHidden(ViewportRanges vpranges, boolean showAnnotationPanel) {
+ this(vpranges, showAnnotationPanel, null);
+ }
+
/**
* Create an OverviewDimensions object
*
* true if the annotation panel is to be shown, false otherwise
*/
public OverviewDimensionsShowHidden(ViewportRanges vpranges,
- boolean showAnnotationPanel)
+ boolean showAnnotationPanel, Dimension dim)
{
- super(vpranges, showAnnotationPanel);
+ super(vpranges, showAnnotationPanel, dim);
ranges = vpranges;
resetAlignmentDims();
}
heightRatio = (float) alheight / sequencesHeight;
}
-
/**
* {@inheritDoc} Callers should have already called resetAlignmentDims to
* refresh widthRatio
* Set first residue visible in the viewport, and retain the current width.
* Fires a property change event.
*
- * @param res
+ * @param res
* residue position
*/
public void setStartRes(int res)
int[] oldvalues = updateStartEndRes(start, end);
int oldstartres = oldvalues[0];
int oldendres = oldvalues[1];
+
+ if (oldstartres == startRes && oldendres == endRes)
+ {
+ return; // BH 2019.07.27 standard check for no changes
+ }
+ // "STARTRES" is a misnomer here -- really "STARTORENDRES"
+ // note that this could be "no change" if the range is just being expanded
changeSupport.firePropertyChange(STARTRES, oldstartres, startRes);
if (oldstartres == startRes)
{
+ // only caught in ViewportRangesTest
+ // No listener cares about this
+ // "ENDRES" is a misnomer here -- really "ENDONLYRES"
+ // BH 2019.07.27 adds end change check
+ // fire only if only the end is changed
// event won't be fired if start positions are same
// fire an event for the end positions in case they changed
- changeSupport.firePropertyChange(ENDRES, oldendres, endRes);
+ changeSupport.firePropertyChange(ENDRES, oldendres, endRes);
}
}
*/
public void setStartEndSeq(int start, int end)
{
- // System.out.println("ViewportRange setStartEndSeq " + start + " " + end);
int[] oldvalues = updateStartEndSeq(start, end);
int oldstartseq = oldvalues[0];
int oldendseq = oldvalues[1];
*/
private int[] updateStartEndSeq(int start, int end)
{
- int oldstartseq = this.startSeq;
- int visibleHeight = getVisibleAlignmentHeight();
- if (start > visibleHeight - 1)
- {
- startSeq = Math.max(visibleHeight - 1, 0);
- }
- else if (start < 0)
- {
- startSeq = 0;
- }
- else
- {
- startSeq = start;
- }
+// if (end == 3 && this.endSeq == 14 || end == 13 && this.endSeq == 3) {
+// new NullPointerException().printStackTrace(System.out);
+// System.out.println("ViewportRange updateStartEndSeq " + start + " " + end + " " + Thread.currentThread());
+// }
+ int oldstartseq = this.startSeq;
int oldendseq = this.endSeq;
- if (end >= visibleHeight)
- {
- endSeq = Math.max(visibleHeight - 1, 0);
- }
- else if (end < 0)
- {
- endSeq = 0;
- }
- else
- {
- endSeq = end;
- }
+ int max = getVisibleAlignmentHeight() - 1;
+ startSeq = Math.max(0, Math.min(start, max));
+ endSeq = Math.max(0, Math.min(end, max));
return new int[] { oldstartseq, oldendseq };
}
*/
public void setViewportStartAndWidth(int start, int w)
{
- int vpstart = start;
- if (vpstart < 0)
- {
- vpstart = 0;
- }
-
- /*
- * if not wrapped, don't leave white space at the right margin
- */
+ int vpstart = Math.max(0, start);
+
if (!wrappedMode)
{
- if ((w <= getVisibleAlignmentWidth())
- && (vpstart + w - 1 > getVisibleAlignmentWidth() - 1))
+ // if not wrapped, don't leave white space at the right margin
+ int maxStart = getVisibleAlignmentWidth() - w;
+ if (maxStart >= 0)
{
- vpstart = getVisibleAlignmentWidth() - w;
+ vpstart = Math.min(vpstart, maxStart);
}
}
*/
public void setViewportStartAndHeight(int start, int h)
{
- int vpstart = start;
-
- int visHeight = getVisibleAlignmentHeight();
- if (vpstart < 0)
- {
- vpstart = 0;
- }
- else if (h <= visHeight && vpstart + h > visHeight)
- // viewport height is less than the full alignment and we are running off
- // the bottom
+ int vpstart = Math.max(0, start);
+ int maxStart = getVisibleAlignmentHeight() - h;
+ if (maxStart > 0)
{
- vpstart = visHeight - h;
+ // can't start higher than vertical extent will allow
+ // (viewport height is less than the full alignment
+ // and we are running off the bottom)
+ vpstart = Math.min(vpstart, maxStart);
}
- // System.out.println("ViewportRanges setviewportStartAndHeight " + vpstart
- // + " " + start + " " + h + " " + getVisibleAlignmentHeight());
-
setStartEndSeq(vpstart, vpstart + h - 1);
}
}
int residuesToScroll = width * widthsToScroll;
- int newStartRes = up ? oldStartRes - residuesToScroll : oldStartRes
- + residuesToScroll;
+ int newStartRes = up ? oldStartRes - residuesToScroll
+ : oldStartRes + residuesToScroll;
if (newStartRes < 0)
{
newStartRes = 0;
{
scrollUp(false);
}
-
+
HiddenColumns hidden = al.getHiddenColumns();
while (x < hidden.visibleToAbsoluteColumn(startRes))
{
return maxScroll;
}
+
+
+ @Override
+ public String toString() {
+ return "[ViewportRange " + startSeq + "-" + endSeq + ", "+ startRes + "-" + endRes + "]";
+ }
}
--- /dev/null
+package jalview.workers;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.WeakHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import static java.lang.String.format;
+import static java.util.Collections.synchronizedMap;
+import static java.util.Collections.unmodifiableList;
+
+import java.util.ArrayList;
+
+import jalview.api.AlignCalcListener;
+import jalview.api.AlignCalcManagerI2;
+import jalview.api.AlignCalcWorkerI;
+import jalview.api.PollableAlignCalcWorkerI;
+import jalview.bin.Cache;
++import jalview.bin.Console;
+import jalview.datamodel.AlignmentAnnotation;
+
+public class AlignCalcManager2 implements AlignCalcManagerI2
+{
+ private abstract class WorkerManager
+ {
+ protected volatile boolean enabled = true;
+
+ protected AlignCalcWorkerI worker;
+
+ WorkerManager(AlignCalcWorkerI worker)
+ {
+ this.worker = worker;
+ }
+
+ protected AlignCalcWorkerI getWorker()
+ {
+ return worker;
+ }
+
+ boolean isEnabled()
+ {
+ return enabled;
+ }
+
+ void setEnabled(boolean enabled)
+ {
+ this.enabled = enabled;
+ }
+
+ synchronized void restart()
+ {
+ if (!isEnabled())
+ {
+ return;
+ }
+ if (!isRegistered())
+ {
+ setEnabled(false);
+ }
+ if (isWorking())
+ {
+ cancel();
+ }
+ submit();
+ }
+
+ protected boolean isRegistered()
+ {
+ return registered.containsKey(getWorker());
+ }
+
+ abstract boolean isWorking();
+
+ protected abstract void submit();
+
+ abstract void cancel();
+ }
+
+ private class SimpleWorkerManager extends WorkerManager
+ {
+ private Future<?> task = null;
+
+ SimpleWorkerManager(AlignCalcWorkerI worker)
+ {
+ super(worker);
+ }
+
+ @Override
+ boolean isWorking()
+ {
+ return task != null && !task.isDone();
+ }
+
+ @Override
+ protected void submit()
+ {
+ if (task != null && !(task.isDone() || task.isCancelled()))
+ {
+ throw new IllegalStateException(
+ "Cannot submit new task if the prevoius one is still running");
+ }
- Cache.log.debug(
++ Console.debug(
+ format("Worker %s queued", getWorker().getClass().getName()));
+ task = executor.submit(() -> {
+ try
+ {
- Cache.log.debug(format("Worker %s started",
++ Console.debug(format("Worker %s started",
+ getWorker().getClass().getName()));
+ getWorker().run();
- Cache.log.debug(format("Worker %s finished",
++ Console.debug(format("Worker %s finished",
+ getWorker().getClass().getName()));
+ } catch (InterruptedException e)
+ {
- Cache.log.debug(format("Worker %s interrupted",
++ Console.debug(format("Worker %s interrupted",
+ getWorker().getClass().getName()));
+ } catch (Throwable th)
+ {
- Cache.log.debug(format("Worker %s failed",
++ Console.debug(format("Worker %s failed",
+ getWorker().getClass().getName()), th);
+ } finally
+ {
+ if (!isRegistered())
+ {
+ // delete worker reference so garbage collector can remove it
+ worker = null;
+ }
+ }
+ });
+ }
+
+ @Override
+ synchronized void cancel()
+ {
+ if (!isWorking())
+ {
+ return;
+ }
- Cache.log.debug(format("Cancelling worker %s",
++ Console.debug(format("Cancelling worker %s",
+ getWorker().getClass().getName()));
+ task.cancel(true);
+ }
+ }
+
+ private class PollableWorkerManager extends WorkerManager
+ {
+ private Future<?> task = null;
+
+ PollableWorkerManager(PollableAlignCalcWorkerI worker)
+ {
+ super(worker);
+ }
+
+ @Override
+ protected PollableAlignCalcWorkerI getWorker()
+ {
+ return (PollableAlignCalcWorkerI) super.getWorker();
+ }
+
+ @Override
+ boolean isWorking()
+ {
+ return task != null && !task.isDone();
+ }
+
+ protected void submit()
+ {
+ if (task != null && !(task.isDone() || task.isCancelled()))
+ {
+ throw new IllegalStateException(
+ "Cannot submit new task if the prevoius one is still running");
+ }
- Cache.log.debug(
++ Console.debug(
+ format("Worker %s queued", getWorker().getClass().getName()));
+ final var runnable = new Runnable()
+ {
+ private boolean started = false;
+
+ private boolean completed = false;
+
+ Future<?> future = null;
+
+ @Override
+ public void run()
+ {
+ try
+ {
+ if (!started)
+ {
- Cache.log.debug(format("Worker %s started",
++ Console.debug(format("Worker %s started",
+ getWorker().getClass().getName()));
+ getWorker().startUp();
+ started = true;
+ }
+ else if (!completed)
+ {
- Cache.log.debug(format("Polling worker %s",
++ Console.debug(format("Polling worker %s",
+ getWorker().getClass().getName()));
+ if (getWorker().poll())
+ {
- Cache.log.debug(format("Worker %s finished",
++ Console.debug(format("Worker %s finished",
+ getWorker().getClass().getName()));
+ completed = true;
+ }
+ }
+ } catch (Throwable th)
+ {
- Cache.log.debug(format("Worker %s failed",
++ Console.debug(format("Worker %s failed",
+ getWorker().getClass().getName()), th);
+ completed = true;
+ }
+ if (completed)
+ {
+ final var worker = getWorker();
+ if (!isRegistered())
+ PollableWorkerManager.super.worker = null;
- Cache.log.debug(format("Finalizing completed worker %s",
++ Console.debug(format("Finalizing completed worker %s",
+ worker.getClass().getName()));
+ worker.done();
+ // almost impossible, but the future may be null at this point
+ // let it throw NPE to cancel forcefully
+ future.cancel(false);
+ }
+ }
+ };
+ runnable.future = task = executor.scheduleWithFixedDelay(runnable, 10,
+ 1000, TimeUnit.MILLISECONDS);
+ }
+
+ synchronized protected void cancel()
+ {
+ if (!isWorking())
+ {
+ return;
+ }
- Cache.log.debug(format("Cancelling worker %s",
++ Console.debug(format("Cancelling worker %s",
+ getWorker().getClass().getName()));
+ task.cancel(false);
+ executor.submit(() -> {
+ final var worker = getWorker();
+ if (!isRegistered())
+ PollableWorkerManager.super.worker = null;
+ if (worker != null)
+ {
+ worker.cancel();
- Cache.log.debug(format("Finalizing cancelled worker %s",
++ Console.debug(format("Finalizing cancelled worker %s",
+ worker.getClass().getName()));
+ worker.done();
+ }
+ });
+ }
+ }
+
+ private final ScheduledExecutorService executor = Executors
+ .newSingleThreadScheduledExecutor();
+
+ private final Map<AlignCalcWorkerI, WorkerManager> registered = synchronizedMap(
+ new HashMap<>());
+
+ private final Map<AlignCalcWorkerI, WorkerManager> oneshot = synchronizedMap(
+ new WeakHashMap<>());
+
+ private final List<AlignCalcListener> listeners = new CopyOnWriteArrayList<>();
+
+ private WorkerManager createManager(AlignCalcWorkerI worker)
+ {
+ if (worker instanceof PollableAlignCalcWorkerI)
+ {
+ return new PollableWorkerManager((PollableAlignCalcWorkerI) worker);
+ }
+ else
+ {
+ return new SimpleWorkerManager(worker);
+ }
+ }
+
+ @Override
+ public void registerWorker(AlignCalcWorkerI worker)
+ {
+ Objects.requireNonNull(worker);
+ WorkerManager manager = createManager(worker);
+ registered.putIfAbsent(worker, manager);
+ startWorker(worker);
+ }
+
+ @Override
+ public List<AlignCalcWorkerI> getWorkers()
+ {
+ List<AlignCalcWorkerI> result = new ArrayList<>(registered.size());
+ result.addAll(registered.keySet());
+ return result;
+ }
+
+ @Override
+ public List<AlignCalcWorkerI> getWorkersOfClass(
+ Class<? extends AlignCalcWorkerI> cls)
+ {
+ List<AlignCalcWorkerI> collected = new ArrayList<>();
+ for (var worker : getWorkers())
+ {
+ if (worker.getClass().equals(cls))
+ {
+ collected.add(worker);
+ }
+ }
+ return unmodifiableList(collected);
+ }
+
+ @Override
+ public void removeWorker(AlignCalcWorkerI worker)
+ {
+ if (worker.isDeletable())
+ {
+ registered.remove(worker);
+ }
+ }
+
+ @Override
+ public void removeWorkerForAnnotation(AlignmentAnnotation annot)
+ {
+ synchronized (registered)
+ {
+ for (var worker : getWorkers())
+ {
+ if (worker.involves(annot))
+ {
+ removeWorker(worker);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void removeWorkersOfClass(Class<? extends AlignCalcWorkerI> cls)
+ {
+ synchronized (registered)
+ {
+ for (var worker : getWorkers())
+ {
+ if (worker.getClass().equals(cls))
+ {
+ removeWorker(worker);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void disableWorker(AlignCalcWorkerI worker)
+ {
+ // Null pointer check might be needed
+ registered.get(worker).setEnabled(false);
+ }
+
+ @Override
+ public void enableWorker(AlignCalcWorkerI worker)
+ {
+ // Null pointer check might be needed
+ registered.get(worker).setEnabled(true);
+ }
+
+ @Override
+ public boolean isDisabled(AlignCalcWorkerI worker)
+ {
+ if (registered.containsKey(worker))
+ {
+ return !registered.get(worker).isEnabled();
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ @Override
+ public boolean isWorking(AlignCalcWorkerI worker)
+ {
+ var manager = registered.get(worker);
+ if (manager == null)
+ manager = oneshot.get(worker);
+ if (manager == null)
+ return false;
+ else
+ return manager.isWorking();
+ }
+
+ @Override
+ public boolean isWorkingWithAnnotation(AlignmentAnnotation annot)
+ {
+ synchronized (registered)
+ {
+ for (var entry : registered.entrySet())
+ if (entry.getKey().involves(annot) && entry.getValue().isWorking())
+ return true;
+ }
+ synchronized (oneshot)
+ {
+ for (var entry : registered.entrySet())
+ if (entry.getKey().involves(annot) && entry.getValue().isWorking())
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean isWorking()
+ {
+ synchronized (registered)
+ {
+ for (var manager : registered.values())
+ if (manager.isWorking())
+ return true;
+ }
+ synchronized (oneshot)
+ {
+ for (var manager : oneshot.values())
+ if (manager.isWorking())
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public void startWorker(AlignCalcWorkerI worker)
+ {
+ Objects.requireNonNull(worker);
+ var manager = registered.get(worker);
+ if (manager == null)
+ {
- Cache.log.warn("Starting unregistered worker " + worker);
++ Console.warn("Starting unregistered worker " + worker);
+ manager = createManager(worker);
+ oneshot.put(worker, manager);
+ }
+ manager.restart();
+ }
+
+ @Override
+ public void restartWorkers()
+ {
+ synchronized (registered)
+ {
+ for (var manager : registered.values())
+ {
+ manager.restart();
+ }
+ }
+ }
+
+ @Override
+ public void cancelWorker(AlignCalcWorkerI worker)
+ {
+ Objects.requireNonNull(worker);
+ var manager = registered.get(worker);
+ if (manager == null)
+ manager = oneshot.get(worker);
+ if (manager == null)
+ {
+ throw new NoSuchElementException();
+ }
+ manager.cancel();
+ }
+
+ private void notifyQueued(AlignCalcWorkerI worker)
+ {
+ for (AlignCalcListener listener : listeners)
+ {
+ listener.workerQueued(worker);
+ }
+ }
+
+ private void notifyStarted(AlignCalcWorkerI worker)
+ {
+ for (AlignCalcListener listener : listeners)
+ {
+ listener.workerStarted(worker);
+ }
+ }
+
+ private void notifyCompleted(AlignCalcWorkerI worker)
+ {
+ for (AlignCalcListener listener : listeners)
+ {
+ try
+ {
+ listener.workerCompleted(worker);
+ } catch (RuntimeException e)
+ {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ private void notifyCancelled(AlignCalcWorkerI worker)
+ {
+ for (AlignCalcListener listener : listeners)
+ {
+ try
+ {
+ listener.workerCancelled(worker);
+ } catch (RuntimeException e)
+ {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ private void notifyExceptional(AlignCalcWorkerI worker,
+ Throwable throwable)
+ {
+ for (AlignCalcListener listener : listeners)
+ {
+ try
+ {
+ listener.workerExceptional(worker, throwable);
+ } catch (RuntimeException e)
+ {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ @Override
+ public void addAlignCalcListener(AlignCalcListener listener)
+ {
+ listeners.add(listener);
+ }
+
+ @Override
+ public void removeAlignCalcListener(AlignCalcListener listener)
+ {
+ listeners.remove(listener);
+ }
+
+ @Override
+ public void shutdown()
+ {
+ executor.shutdownNow();
+ listeners.clear();
+ registered.clear();
+ }
+
+}
*/
package jalview.ws;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.AlignedCodonFrame;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentI;
import java.util.ArrayList;
import java.util.List;
-public abstract class AWSThread extends Thread
+import static java.lang.String.format;
+
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import javax.swing.Timer;
+
+public abstract class AWSThread
{
+
+ private javax.swing.Timer timer;
/**
* view that this job was associated with
/**
* are there jobs still running in this thread.
+ *
+ * fixme: initialize with an empty array?
*/
protected boolean jobComplete = false;
/**
* one or more jobs being managed by this thread.
*/
- protected AWsJob jobs[] = null;
+ protected AWsJob[] jobs = null;
/**
* full name of service
*/
private AlignFrame alignFrame;
- /**
- * generic web service job/subjob poll loop
- */
- @Override
- public void run()
+ public void start()
{
if (jobs == null)
{
jobComplete = true;
- Cache.log.debug(
++ Console.debug(
+ "WebServiceJob poll loop finished with no jobs created.");
+ wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
+ wsInfo.appendProgressText(
+ MessageManager.getString("info.no_jobs_ran"));
+ wsInfo.setFinishedNoResults();
+ return;
}
- while (!jobComplete)
+ timer = new Timer(5000, new ActionListener()
{
- jstate = new JobStateSummary();
- for (int j = 0; j < jobs.length; j++)
+
+ @Override
+ public void actionPerformed(ActionEvent e)
{
+
- if (!jobs[j].submitted && jobs[j].hasValidInput())
- {
- StartJob(jobs[j]);
- }
-
- if (jobs[j].submitted && !jobs[j].subjobComplete)
+ JobStateSummary jstate = new JobStateSummary();
+ for (final AWsJob job : jobs)
{
- try
+ if (!job.submitted && job.hasValidInput())
{
- pollJob(jobs[j]);
- if (!jobs[j].hasResponse())
- {
- throw (new Exception(
- "Timed out when communicating with server\nTry again later.\n"));
- }
- Console.debug("Job " + j + " Result state " + jobs[j].getState()
- + "(ServerError=" + jobs[j].isServerError() + ")");
- } catch (Exception ex)
+ StartJob(job);
+ }
- Cache.log.debug(format(
++ Console.debug(format(
+ "Job %s is %ssubmitted", job, job.submitted ? "" : "not "));
+ if (job.submitted && !job.subjobComplete)
{
- Cache.log.debug(format(
- // Deal with Transaction exceptions
- wsInfo.appendProgressText(jobs[j].jobnum, MessageManager
- .formatMessage("info.server_exception", new Object[]
- { WebServiceName, ex.getMessage() }));
- // always output the exception's stack trace to the log
- Console.warn(WebServiceName + " job(" + jobs[j].jobnum
- + ") Server exception.");
- // todo: could limit trace to cause if this is a SOAPFaultException.
- ex.printStackTrace();
-
- if (jobs[j].allowedServerExceptions > 0)
++ Console.debug(format(
+ "Polling Job %s Result state was:%s(ServerError=%b)",
+ job, job.getState(), job.isServerError()));
+ try
+ {
+ pollJob(job);
+ if (!job.hasResponse())
+ throw new Exception("Timed out when communicating with server. Try again later.");
+ else
- Cache.log.debug(format("Job %s Result state:%s(ServerError=%b)",
++ Console.debug(format("Job %s Result state:%s(ServerError=%b)",
+ job, job.getState(), job.isServerError()));
+ } catch (Exception exc)
{
- jobs[j].allowedServerExceptions--;
- Console.debug("Sleeping after a server exception.");
- try
+ // Deal with Transaction exceptions
+ wsInfo.appendProgressText(job.jobnum, MessageManager
+ .formatMessage("info.server_exception", WebServiceName,
+ exc.getMessage()));
+ // always output the exception's stack trace to the log
- Cache.log.warn(format("%s job(%s) Server exception.",
++ Console.warn(format("%s job(%s) Server exception.",
+ WebServiceName, job.jobnum));
+ exc.printStackTrace();
+
+ if (job.allowedServerExceptions > 0)
{
- Thread.sleep(5000);
- } catch (InterruptedException ex1)
+ job.allowedServerExceptions--;
+ }
+ else
{
- Cache.log.warn(format("Dropping job %s %s", job, job.jobId));
++ Console.warn(format("Dropping job %s %s", job, job.jobId));
+ job.subjobComplete = true;
+ wsInfo.setStatus(job.jobnum, WebserviceInfo.STATE_STOPPED_SERVERERROR);
}
- }
- else
+ } catch (OutOfMemoryError oomerror)
{
- Console.warn("Dropping job " + j + " " + jobs[j].jobId);
- jobs[j].subjobComplete = true;
- wsInfo.setStatus(jobs[j].jobnum,
- WebserviceInfo.STATE_STOPPED_SERVERERROR);
+ jobComplete = true;
+ job.subjobComplete = true;
+ job.clearResponse();
+ wsInfo.setStatus(job.jobnum, WebserviceInfo.STATE_STOPPED_ERROR);
- Cache.log.error(format("Out of memory when retrieving Job %s id:%s/%s",
++ Console.error(format("Out of memory when retrieving Job %s id:%s/%s",
+ job, WsUrl, job.jobId), oomerror);
+ new jalview.gui.OOMWarning("retrieving result for " + WebServiceName, oomerror);
+ System.gc();
}
- } catch (OutOfMemoryError er)
- {
- jobComplete = true;
- jobs[j].subjobComplete = true;
- jobs[j].clearResponse(); // may contain out of date result data
- wsInfo.setStatus(jobs[j].jobnum,
- WebserviceInfo.STATE_STOPPED_ERROR);
- Console.error("Out of memory when retrieving Job " + j + " id:"
- + WsUrl + "/" + jobs[j].jobId, er);
- new jalview.gui.OOMWarning(
- "retrieving result for " + WebServiceName, er);
- System.gc();
}
+ jstate.updateJobPanelState(wsInfo, OutputHeader, job);
}
- jstate.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
- }
- // Decide on overall state based on collected jobs[] states
- updateGlobalStatus(jstate);
- if (!jobComplete)
- {
- try
+ // Decide on overall state based on collected jobs[] states
+ updateGlobalStatus(jstate);
+ if (jobComplete)
{
- Thread.sleep(5000);
- } catch (InterruptedException e)
- {
- Console.debug("Interrupted sleep waiting for next job poll.", e);
+ timer.stop();
+ // jobs should never be null at this point
+ parseResult(); // tidy up and make results available to user
+
}
- // System.out.println("I'm alive "+alTitle);
}
- }
- if (jobComplete && jobs != null)
- {
- parseResult(); // tidy up and make results available to user
- }
- else
- {
- Console.debug(
- "WebServiceJob poll loop finished with no jobs created.");
- wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
- wsInfo.appendProgressText(
- MessageManager.getString("info.no_jobs_ran"));
- wsInfo.setFinishedNoResults();
- }
+ });
+ timer.setInitialDelay(0);
+ timer.start();
}
protected void updateGlobalStatus(JobStateSummary jstate)
}
}
}
+
- public AWSThread()
- {
- super();
- }
-
- public AWSThread(Runnable target)
- {
- super(target);
- }
-
- public AWSThread(String name)
- {
- super(name);
- }
-
- public AWSThread(ThreadGroup group, Runnable target)
+
+ public void interrupt()
{
- super(group, target);
- }
-
- public AWSThread(ThreadGroup group, String name)
- {
- super(group, name);
- }
-
- public AWSThread(Runnable target, String name)
- {
- super(target, name);
- }
-
- public AWSThread(ThreadGroup group, Runnable target, String name)
- {
- super(group, target, name);
+ timer.stop();
}
/**
}
}
- public AWSThread(ThreadGroup group, Runnable target, String name,
- long stackSize)
- {
- super(group, target, name, stackSize);
- }
+
/**
*
* @return gap character to use for any alignment generation
*
* @param alignFrame
* reference for copying mappings across
- * @param wsInfo
+ * @param wsinfo
* gui attachment point
* @param input
* input data for the calculation
.getCodonFrames();
if (cf != null)
{
- codonframe = new ArrayList<AlignedCodonFrame>();
+ codonframe = new ArrayList<>();
codonframe.addAll(cf);
}
}
*/
package jalview.ws;
+import jalview.bin.ApplicationSingletonProvider;
+import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
import jalview.ext.ensembl.EnsemblGene;
import jalview.ws.dbsources.EmblCdsSource;
import jalview.ws.dbsources.EmblSource;
* This implements the run-time discovery of sequence database clients.
*
*/
-public class SequenceFetcher extends ASequenceFetcher
+public class SequenceFetcher extends ASequenceFetcher implements ApplicationSingletonI
{
+ /*
+ * set a mock fetcher here for testing only - reset to null afterwards
+ */
+ private static SequenceFetcher mockFetcher;
+
+ /**
+ * Set the instance object to use (intended for unit testing with mock
+ * objects).
+ *
+ * Be sure to reset to null in the tearDown method of any tests!
+ *
+ * @param sf
+ */
+ public static void setMockFetcher(SequenceFetcher sf)
+ {
+ mockFetcher = sf;
+ }
+
+ /**
+ * Returns a new SequenceFetcher singleton, or a mock object if one has been
+ * set.
+ *
+ * @return
+ */
+ public static SequenceFetcher getInstance()
+ {
+ return mockFetcher != null ? mockFetcher
+ : (SequenceFetcher) ApplicationSingletonProvider
+ .getInstance(SequenceFetcher.class);
+ }
+
/**
* Thread safe construction of database proxies TODO: extend to a configurable
* database plugin mechanism where classes are instantiated by reflection and
}
/**
- * return an ordered list of database sources excluding alignment only databases
+ * return an ordered list of database sources excluding alignment only
+ * databases
*/
public String[] getNonAlignmentSources()
{
--- /dev/null
+package jalview.ws.api;
+
+import jalview.bin.Cache;
++import jalview.bin.Console;
+import jalview.gui.AlignFrame;
+import jalview.ws.jws2.MsaWSClient;
+import jalview.ws.jws2.SequenceAnnotationWSClient;
+import jalview.ws.params.ParamManager;
+
+import javax.swing.JMenu;
+
+public abstract class ServiceWithParameters extends UIinfo
+{
+
+ protected jalview.ws.uimodel.AlignAnalysisUIText aaui;
+
+ public ServiceWithParameters(String serviceType, String action,
+ String name, String description, String hosturl)
+ {
+ super(serviceType, action, name, description, hosturl);
+ }
+
+ public abstract void initParamStore(ParamManager userParameterStore);
+
+ public jalview.ws.uimodel.AlignAnalysisUIText getAlignAnalysisUI()
+ {
+ return aaui;
+ }
+
+ public void setAlignAnalysisUI(
+ jalview.ws.uimodel.AlignAnalysisUIText aaui)
+ {
+ this.aaui = aaui;
+ }
+
+ public boolean isInteractiveUpdate()
+ {
+ return aaui != null && aaui.isAA();
+ }
+ // config flags for SeqAnnotationServiceCalcWorker
+
+ public boolean isProteinService()
+ {
+ return aaui == null ? true : aaui.isPr();
+ }
+
+ public boolean isNucleotideService()
+ {
+ return aaui == null ? false : aaui.isNa();
+ }
+
+ public boolean isNeedsAlignedSequences()
+ {
+ return aaui == null ? false : aaui.isNeedsAlignedSeqs();
+ }
+
+ public boolean isAlignmentAnalysis()
+ {
+ return aaui == null ? false : aaui.isAA();
+ }
+
+ public boolean isFilterSymbols()
+ {
+ return aaui != null ? aaui.isFilterSymbols() : true;
+ }
+
+ public int getMinimumInputSequences()
+ {
+ return aaui != null ? aaui.getMinimumSequences() : 1;
+ }
+
+ public String getNameURI()
+ {
+ return "java:" + getName();
+ }
+
+ public String getUri()
+ {
+ // TODO verify that service parameter sets in projects are consistent with
+ // Jalview 2.10.4
+ // this is only valid for Jaba 1.0 - this formula might have to change!
+ return getHostURL()
+ + (getHostURL().lastIndexOf("/") == (getHostURL().length() - 1)
+ ? ""
+ : "/")
+ + getName();
+ }
+
+ protected enum ServiceClient
+ {
+ MSAWSCLIENT, SEQUENCEANNOTATIONWSCLIENT;
+ };
+
+ protected ServiceClient style = null;
+
+ public void attachWSMenuEntry(JMenu atpoint, AlignFrame alignFrame)
+ {
+ switch (style)
+ {
+ case MSAWSCLIENT:
+ new MsaWSClient().attachWSMenuEntry(atpoint, this, alignFrame);
+ break;
+ case SEQUENCEANNOTATIONWSCLIENT:
+ new SequenceAnnotationWSClient().attachWSMenuEntry(atpoint, this,
+ alignFrame);
+ break;
+ default:
- Cache.log.warn("Implementation error ? Service " + getName()
++ Console.warn("Implementation error ? Service " + getName()
+ + " has Unknown service style " + style);
+ }
+ }
+}
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.ws.dbsources;
import java.util.Locale;
import com.stevesoft.pat.Regex;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.SequenceI;
import jalview.io.DataSourceType;
import jalview.io.EmblFlatFile;
import jalview.io.FileParse;
++import jalview.util.Platform;
import jalview.ws.ebi.EBIFetchClient;
/**
*/
public abstract class EmblFlatfileSource extends EbiFileRetrievedProxy
{
- private static final Regex ACCESSION_REGEX = null;
- private static final Regex ACCESSION_REGEX = new Regex("^[A-Z]+[0-9]+");
++ private static Regex ACCESSION_REGEX = null;
@Override
public String getDbVersion()
@Override
public Regex getAccessionValidator()
{
+ if (ACCESSION_REGEX == null)
+ {
+ ACCESSION_REGEX = Platform.newRegex("^[A-Z]+[0-9]+");
+ }
return ACCESSION_REGEX;
}
try
{
reply = dbFetch.fetchDataAsFile(
- dbName.toLowerCase(Locale.ROOT) + ":" + query.trim(), null, "gz");
+ dbName.toLowerCase(Locale.ROOT) + ":" + query.trim(), null,
+ "gz");
} catch (Exception e)
{
stopQuery();
if (al == null)
{
- Cache.log.error(
- "No record found for '" + dbName + ":" + query + "'");
+ Console.error("No record found for '" + dbName + ":" + query + "'");
}
}
*/
package jalview.ws.dbsources;
+import java.util.Locale;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
-import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
-import com.stevesoft.pat.Regex;
+
import jalview.analysis.SequenceIdMatcher;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.DBRefEntry;
import jalview.util.DnaUtils;
import jalview.util.MapList;
import jalview.util.MappingUtils;
+import jalview.util.MessageManager;
++import jalview.util.Platform;
import jalview.ws.ebi.EBIFetchClient;
import jalview.xml.binding.embl.EntryType;
import jalview.xml.binding.embl.EntryType.Feature;
import jalview.xml.binding.embl.ROOT;
import jalview.xml.binding.embl.XrefType;
++import com.stevesoft.pat.Regex;
++
+/**
+ * Provides XML binding and parsing of EMBL or EMBLCDS records retrieved from
+ * (e.g.) {@code https://www.ebi.ac.uk/ena/data/view/x53828&display=xml}.
+ *
+ * @deprecated endpoint withdrawn August 2020 (JAL-3692), use EmblFlatfileSource
+ */
-
++@Deprecated
public abstract class EmblXmlSource extends EbiFileRetrievedProxy
{
- private static final Regex ACCESSION_REGEX = new Regex("^[A-Z]+[0-9]+");
+ // TODO: delete class or update tyhis validator for 2.12 style Platform.regex
- private static final Regex ACCESSION_REGEX = new Regex("^[A-Z]+[0-9]+");
++ private static final Regex ACCESSION_REGEX = Platform.newRegex("^[A-Z]+[0-9]+");
+
/*
* JAL-1856 Embl returns this text for query not found
*/
try
{
reply = dbFetch.fetchDataAsFile(
- emprefx.toLowerCase(Locale.ROOT) + ":" + query.trim(),
- "display=xml", "xml");
+ emprefx.toLowerCase(Locale.ROOT) + ":" + query.trim(), "display=xml",
+ "xml");
} catch (Exception e)
{
stopQuery();
else
{
// final product length truncation check
- int[] exons2 = adjustForProteinLength(translationLength, exons);
- dnaToProteinMapping = new Mapping(product, exons2,
+ int[] cdsRanges = adjustForProteinLength(translationLength,
+ exons);
+ dnaToProteinMapping = new Mapping(product, cdsRanges,
new int[]
{ 1, translationLength }, 3, 1);
if (product != null)
{
return new int[] {};
}
+
try
{
List<int[]> ranges = DnaUtils.parseLocation(location);
return listToArray(ranges);
} catch (ParseException e)
{
- Cache.log.warn(
+ Console.warn(
String.format("Not parsing inexact CDS location %s in ENA %s",
location, accession));
return new int[] {};
}
return getAccessionValidator().search(accession);
}
+
/**
* Truncates (if necessary) the exon intervals to match 3 times the length of
- * the protein; also accepts 3 bases longer (for stop codon not included in
- * protein)
+ * the protein (including truncation for stop codon included in exon)
*
* @param proteinLength
* @param exon
}
int expectedCdsLength = proteinLength * 3;
int exonLength = MappingUtils.getLength(Arrays.asList(exon));
+
/*
- * if exon length matches protein, or is shorter, or longer by the
- * length of a stop codon (3 bases), then leave it unchanged
+ * if exon length matches protein, or is shorter, then leave it unchanged
*/
- if (expectedCdsLength >= exonLength
- || expectedCdsLength == exonLength - 3)
+ if (expectedCdsLength >= exonLength)
{
return exon;
}
+
int origxon[];
int sxpos = -1;
int endxon = 0;
// .println("Truncating final exon interval on region by "
// + (cdspos - cdslength));
}
+
/*
* shrink the final exon - reduce end position if forward
* strand, increase it if reverse
break;
}
}
+
if (sxpos != -1)
{
// and trim the exon interval set if necessary
import jalview.io.PDBFeatureSettings;
import jalview.structure.StructureImportSettings;
import jalview.util.MessageManager;
+import jalview.util.Platform;
import jalview.ws.ebi.EBIFetchClient;
import java.io.File;
private static final int PDB_ID_LENGTH = 4;
+ private static Regex ACCESSION_REGEX;
+
public Pdb()
{
super();
@Override
public Regex getAccessionValidator()
{
- return new Regex("([1-9][0-9A-Za-z]{3}):?([ _A-Za-z0-9]?)");
+ if (ACCESSION_REGEX == null)
+ {
+ ACCESSION_REGEX = Platform
+ .newRegex("([1-9][0-9A-Za-z]{3}):?([ _A-Za-z0-9]?)");
+ }
+ return ACCESSION_REGEX;
}
/*
// todo get rid of Type and use FileFormatI instead?
FileFormatI fileFormat = (pdbFileFormat == Type.PDB) ? FileFormat.PDB
: FileFormat.MMCif;
- pdbAlignment = new FormatAdapter().readFile(tmpFile, DataSourceType.FILE,
- fileFormat);
+ pdbAlignment = new FormatAdapter().readFile(tmpFile,
+ DataSourceType.FILE, fileFormat);
if (pdbAlignment != null)
{
List<SequenceI> toremove = new ArrayList<SequenceI>();
package jalview.ws.dbsources;
import java.util.Locale;
-
import jalview.bin.Cache;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.SequenceFeature;
import jalview.datamodel.SequenceI;
import jalview.schemes.ResidueProperties;
++import jalview.util.Platform;
import jalview.util.StringUtils;
import jalview.ws.seqfetcher.DbSourceProxyImpl;
import jalview.xml.binding.uniprot.DbReferenceType;
private static final String DEFAULT_UNIPROT_DOMAIN = "https://www.uniprot.org";
private static final String BAR_DELIMITER = "|";
+ private static Regex ACCESSION_REGEX;
/**
* Constructor
@Override
public Regex getAccessionValidator()
{
- return new Regex("([A-Z]+[0-9]+[A-Z0-9]+|[A-Z0-9]+_[A-Z0-9]+)");
+ if (ACCESSION_REGEX == null)
+ {
+ ACCESSION_REGEX = Platform
+ .newRegex("([A-Z]+[0-9]+[A-Z0-9]+|[A-Z0-9]+_[A-Z0-9]+)");
+ }
+ return ACCESSION_REGEX;
}
/*
"(UNIPROT\\|?|UNIPROT_|UNIREF\\d+_|UNIREF\\d+\\|?)", "");
AlignmentI al = null;
- String downloadstring = getDomain() + "/uniprot/" + queries
- + ".xml";
+ String downloadstring = getDomain() + "/uniprot/" + queries + ".xml";
URL url = new URL(downloadstring);
- HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
+ HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
// anything other than 200 means we don't have data
- // TODO: JAL-3882 reuse the EnsemblRestClient's fair
+ // TODO: JAL-3882 reuse the EnsemblRestClient's fair
// use/backoff logic to retry when the server tells us to go away
if (urlconn.getResponseCode() == 200)
{
- List<SequenceI> seqs = new ArrayList<>();
- for (Entry entry : entries)
+ InputStream istr = urlconn.getInputStream();
+ List<Entry> entries = getUniprotEntries(istr);
+ if (entries != null)
{
- seqs.add(uniprotEntryToSequence(entry));
+ List<SequenceI> seqs = new ArrayList<>();
+ for (Entry entry : entries)
+ {
+ seqs.add(uniprotEntryToSequence(entry));
+ }
+ al = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
}
- al = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
}
+
stopQuery();
return al;
-
+
} catch (Exception e)
{
throw (e);
String seqString = entry.getSequence().getValue().replaceAll("\\s*",
"");
- SequenceI sequence = new Sequence(id,
- seqString);
+ SequenceI sequence = new Sequence(id, seqString);
sequence.setDescription(getUniprotEntryDescription(entry));
/*
*/
final String dbVersion = getDbVersion();
List<DBRefEntry> dbRefs = new ArrayList<>();
- boolean canonical=true;
+ boolean canonical = true;
for (String accessionId : entry.getAccession())
{
DBRefEntry dbRef = new DBRefEntry(DBRefSource.UNIPROT, dbVersion,
- accessionId,null,canonical);
- canonical=false;
+ accessionId, null, canonical);
+ canonical = false;
dbRefs.add(dbRef);
}
dbRefs.add(dbr);
}
}
-- if ("Ensembl".equals(type))
++ // from 2.11.2.6 - probably see a conflict here
++ if (type != null
++ && type.toLowerCase(Locale.ROOT).startsWith("ensembl"))
{
++ // remove version
++ String[] vrs = dbref.getId().split("\\.");
++ String version = vrs.length > 1 ? vrs[1]
++ : DBRefSource.UNIPROT + ":" + dbVersion;
++ dbr.setAccessionId(vrs[0]);
++ dbr.setVersion(version);
/*
* e.g. Uniprot accession Q9BXM7 has
* <dbReference type="Ensembl" id="ENST00000321556">
"protein sequence ID");
if (cdsId != null && cdsId.trim().length() > 0)
{
++ // remove version
++ String[] cdsVrs = cdsId.split("\\.");
++ String cdsVersion = cdsVrs.length > 1 ? cdsVrs[1]
++ : DBRefSource.UNIPROT + ":" + dbVersion;
dbr = new DBRefEntry(DBRefSource.ENSEMBL,
-- DBRefSource.UNIPROT + ":" + dbVersion, cdsId.trim());
++ DBRefSource.UNIPROT + ":" + cdsVersion, cdsVrs[0]);
dbRefs.add(dbr);
}
}
XMLStreamReader streamReader = XMLInputFactory.newInstance()
.createXMLStreamReader(is);
javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
- JAXBElement<jalview.xml.binding.uniprot.Uniprot> uniprotElement =
- um.unmarshal(streamReader, jalview.xml.binding.uniprot.Uniprot.class);
- jalview.xml.binding.uniprot.Uniprot uniprot = uniprotElement.getValue();
-
+ JAXBElement<jalview.xml.binding.uniprot.Uniprot> uniprotElement = um
+ .unmarshal(streamReader,
+ jalview.xml.binding.uniprot.Uniprot.class);
+ jalview.xml.binding.uniprot.Uniprot uniprot = uniprotElement
+ .getValue();
+
if (uniprot != null && !uniprot.getEntry().isEmpty())
{
entries = uniprot.getEntry();
} catch (JAXBException | XMLStreamException
| FactoryConfigurationError e)
{
- if (e instanceof javax.xml.bind.UnmarshalException && e.getCause()!=null && e.getCause() instanceof XMLStreamException && e.getCause().getMessage().contains("[row,col]:[1,1]"))
+ if (e instanceof javax.xml.bind.UnmarshalException
+ && e.getCause() != null
+ && e.getCause() instanceof XMLStreamException
+ && e.getCause().getMessage().contains("[row,col]:[1,1]"))
{
// trying to parse an empty stream
return null;
* along with Jalview. If not, see <http://www.gnu.org/licenses/>.
* The Jalview Authors are detailed in the 'AUTHORS' file.
*/
-package jalview.ws.jws2;
+package jalview.ws.gui;
-import jalview.analysis.AlignSeq;
+import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.AlignmentOrder;
import jalview.datamodel.AlignmentView;
import jalview.datamodel.HiddenColumns;
-import jalview.datamodel.Sequence;
import jalview.datamodel.SequenceI;
import jalview.gui.AlignFrame;
import jalview.gui.Desktop;
import jalview.gui.SplitFrame;
import jalview.gui.WebserviceInfo;
import jalview.util.MessageManager;
+import jalview.ws.AWSThread;
import jalview.ws.AWsJob;
import jalview.ws.JobStateSummary;
import jalview.ws.WSClientI;
-import jalview.ws.jws2.dm.JabaWsParamSet;
+import jalview.ws.api.CancellableI;
+import jalview.ws.api.JobId;
+import jalview.ws.api.MultipleSequenceAlignmentI;
+import jalview.ws.gui.WsJob.JobState;
+import jalview.ws.params.ArgumentI;
import jalview.ws.params.WsParamSetI;
import java.util.ArrayList;
-import java.util.Hashtable;
import java.util.List;
import javax.swing.JInternalFrame;
-import compbio.data.msa.MsaWS;
-import compbio.metadata.Argument;
-import compbio.metadata.ChunkHolder;
-import compbio.metadata.JobStatus;
-import compbio.metadata.Preset;
-
-class MsaWSThread extends AWS2Thread implements WSClientI
+public class MsaWSThread extends AWSThread implements WSClientI
{
boolean submitGaps = false; // pass sequences including gaps to alignment
// order
- class MsaWSJob extends JWs2Job
- {
- long lastChunk = 0;
-
- WsParamSetI preset = null;
-
- List<Argument> arguments = null;
-
- /**
- * input
- */
- ArrayList<compbio.data.sequence.FastaSequence> seqs = new ArrayList<compbio.data.sequence.FastaSequence>();
-
- /**
- * output
- */
- compbio.data.sequence.Alignment alignment;
-
- // set if the job didn't get run - then the input is simply returned to the
- // user
- private boolean returnInput = false;
-
- /**
- * MsaWSJob
- *
- * @param jobNum
- * int
- * @param jobId
- * String
- */
- public MsaWSJob(int jobNum, SequenceI[] inSeqs)
- {
- this.jobnum = jobNum;
- if (!prepareInput(inSeqs, 2))
- {
- submitted = true;
- subjobComplete = true;
- returnInput = true;
- }
-
- }
-
- Hashtable<String, Map> SeqNames = new Hashtable();
-
- Vector<String[]> emptySeqs = new Vector();
-
- /**
- * prepare input sequences for MsaWS service
- *
- * @param seqs
- * jalview sequences to be prepared
- * @param minlen
- * minimum number of residues required for this MsaWS service
- * @return true if seqs contains sequences to be submitted to service.
- */
- // TODO: return compbio.seqs list or nothing to indicate validity.
- private boolean prepareInput(SequenceI[] seqs, int minlen)
- {
- int nseqs = 0;
- if (minlen < 0)
- {
- throw new Error(MessageManager.getString(
- "error.implementation_error_minlen_must_be_greater_zero"));
- }
- for (int i = 0; i < seqs.length; i++)
- {
- if (seqs[i].getEnd() - seqs[i].getStart() > minlen - 1)
- {
- nseqs++;
- }
- }
- boolean valid = nseqs > 1; // need at least two seqs
- compbio.data.sequence.FastaSequence seq;
- for (int i = 0, n = 0; i < seqs.length; i++)
- {
-
- String newname = jalview.analysis.SeqsetUtils.unique_name(i); // same
- // for
- // any
- // subjob
- SeqNames.put(newname,
- jalview.analysis.SeqsetUtils.SeqCharacterHash(seqs[i]));
- if (valid && seqs[i].getEnd() - seqs[i].getStart() > minlen - 1)
- {
- // make new input sequence with or without gaps
- seq = new compbio.data.sequence.FastaSequence(newname,
- (submitGaps) ? seqs[i].getSequenceAsString()
- : AlignSeq.extractGaps(
- jalview.util.Comparison.GapChars,
- seqs[i].getSequenceAsString()));
- this.seqs.add(seq);
- }
- else
- {
- String empty = null;
- if (seqs[i].getEnd() >= seqs[i].getStart())
- {
- empty = (submitGaps) ? seqs[i].getSequenceAsString()
- : AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
- seqs[i].getSequenceAsString());
- }
- emptySeqs.add(new String[] { newname, empty });
- }
- }
- return valid;
- }
-
- /**
- *
- * @return true if getAlignment will return a valid alignment result.
- */
- @Override
- public boolean hasResults()
- {
- if (subjobComplete && isFinished() && (alignment != null
- || (emptySeqs != null && emptySeqs.size() > 0)))
- {
- return true;
- }
- return false;
- }
-
- /**
- *
- * get the alignment including any empty sequences in the original order
- * with original ids. Caller must access the alignment.getMetadata() object
- * to annotate the final result passsed to the user.
- *
- * @return { SequenceI[], AlignmentOrder }
- */
- public Object[] getAlignment()
- {
- // is this a generic subjob or a Jws2 specific Object[] return signature
- if (hasResults())
- {
- SequenceI[] alseqs = null;
- char alseq_gapchar = '-';
- int alseq_l = 0;
- if (alignment.getSequences().size() > 0)
- {
- alseqs = new SequenceI[alignment.getSequences().size()];
- for (compbio.data.sequence.FastaSequence seq : alignment
- .getSequences())
- {
- alseqs[alseq_l++] = new Sequence(seq.getId(),
- seq.getSequence());
- }
- alseq_gapchar = alignment.getMetadata().getGapchar();
-
- }
- // add in the empty seqs.
- if (emptySeqs.size() > 0)
- {
- SequenceI[] t_alseqs = new SequenceI[alseq_l + emptySeqs.size()];
- // get width
- int i, w = 0;
- if (alseq_l > 0)
- {
- for (i = 0, w = alseqs[0].getLength(); i < alseq_l; i++)
- {
- if (w < alseqs[i].getLength())
- {
- w = alseqs[i].getLength();
- }
- t_alseqs[i] = alseqs[i];
- alseqs[i] = null;
- }
- }
- // check that aligned width is at least as wide as emptySeqs width.
- int ow = w, nw = w;
- for (i = 0, w = emptySeqs.size(); i < w; i++)
- {
- String[] es = emptySeqs.get(i);
- if (es != null && es[1] != null)
- {
- int sw = es[1].length();
- if (nw < sw)
- {
- nw = sw;
- }
- }
- }
- // make a gapped string.
- StringBuffer insbuff = new StringBuffer(w);
- for (i = 0; i < nw; i++)
- {
- insbuff.append(alseq_gapchar);
- }
- if (ow < nw)
- {
- for (i = 0; i < alseq_l; i++)
- {
- int sw = t_alseqs[i].getLength();
- if (nw > sw)
- {
- // pad at end
- alseqs[i].setSequence(t_alseqs[i].getSequenceAsString()
- + insbuff.substring(0, sw - nw));
- }
- }
- }
- for (i = 0, w = emptySeqs.size(); i < w; i++)
- {
- String[] es = emptySeqs.get(i);
- if (es[1] == null)
- {
- t_alseqs[i + alseq_l] = new jalview.datamodel.Sequence(es[0],
- insbuff.toString(), 1, 0);
- }
- else
- {
- if (es[1].length() < nw)
- {
- t_alseqs[i + alseq_l] = new jalview.datamodel.Sequence(
- es[0],
- es[1] + insbuff.substring(0, nw - es[1].length()),
- 1, 1 + es[1].length());
- }
- else
- {
- t_alseqs[i + alseq_l] = new jalview.datamodel.Sequence(
- es[0], es[1]);
- }
- }
- }
- alseqs = t_alseqs;
- }
- AlignmentOrder msaorder = new AlignmentOrder(alseqs);
- // always recover the order - makes parseResult()'s life easier.
- jalview.analysis.AlignmentSorter.recoverOrder(alseqs);
- // account for any missing sequences
- jalview.analysis.SeqsetUtils.deuniquify(SeqNames, alseqs);
- return new Object[] { alseqs, msaorder };
- }
- return null;
- }
-
- /**
- * mark subjob as cancelled and set result object appropriatly
- */
- void cancel()
- {
- cancelled = true;
- subjobComplete = true;
- alignment = null;
- }
-
- /**
- *
- * @return boolean true if job can be submitted.
- */
- @Override
- public boolean hasValidInput()
- {
- // TODO: get attributes for this MsaWS instance to check if it can do two
- // sequence alignment.
- if (seqs != null && seqs.size() >= 2) // two or more sequences is valid ?
- {
- return true;
- }
- return false;
- }
-
- StringBuffer jobProgress = new StringBuffer();
-
- public void setStatus(String string)
- {
- jobProgress.setLength(0);
- jobProgress.append(string);
- }
-
- @Override
- public String getStatus()
- {
- return jobProgress.toString();
- }
-
- @Override
- public boolean hasStatus()
- {
- return jobProgress != null;
- }
-
- /**
- * @return the lastChunk
- */
- public long getLastChunk()
- {
- return lastChunk;
- }
-
- /**
- * @param lastChunk
- * the lastChunk to set
- */
- public void setLastChunk(long lastChunk)
- {
- this.lastChunk = lastChunk;
- }
-
- String alignmentProgram = null;
-
- public String getAlignmentProgram()
- {
- return alignmentProgram;
- }
-
- public boolean hasArguments()
- {
- return (arguments != null && arguments.size() > 0)
- || (preset != null && preset instanceof JabaWsParamSet);
- }
-
- public List<Argument> getJabaArguments()
- {
- List<Argument> newargs = new ArrayList<Argument>();
- if (preset != null && preset instanceof JabaWsParamSet)
- {
- newargs.addAll(((JabaWsParamSet) preset).getjabaArguments());
- }
- if (arguments != null && arguments.size() > 0)
- {
- newargs.addAll(arguments);
- }
- return newargs;
- }
-
- /**
- * add a progess header to status string containing presets/args used
- */
- public void addInitialStatus()
- {
- if (preset != null)
- {
- jobProgress.append("Using "
- + (preset instanceof JabaPreset ? "Server" : "User")
- + "Preset: " + preset.getName());
- if (preset instanceof JabaWsParamSet)
- {
- for (Argument opt : ((JabaWsParamSet) preset).getjabaArguments())
- {
- jobProgress.append(
- opt.getName() + " " + opt.getDefaultValue() + "\n");
- }
- }
- }
- if (arguments != null && arguments.size() > 0)
- {
- jobProgress.append("With custom parameters : \n");
- // merge arguments with preset's own arguments.
- for (Argument opt : arguments)
- {
- jobProgress.append(
- opt.getName() + " " + opt.getDefaultValue() + "\n");
- }
- }
- jobProgress.append("\nJob Output:\n");
- }
-
- public boolean isPresetJob()
- {
- return preset != null && preset instanceof JabaPreset;
- }
-
- public Preset getServerPreset()
- {
- return (isPresetJob()) ? ((JabaPreset) preset).p : null;
- }
- }
+
String alTitle; // name which will be used to form new alignment window.
AlignmentI dataset; // dataset to which the new alignment will be
// associated.
- @SuppressWarnings("unchecked")
- MsaWS server = null;
+ MultipleSequenceAlignmentI server = null;
/**
* set basic options for this (group) of Msa jobs
* @param presorder
* boolean
*/
- private MsaWSThread(MsaWS server, String wsUrl, WebserviceInfo wsinfo,
+ private MsaWSThread(MultipleSequenceAlignmentI server, String wsUrl,
+ WebserviceInfo wsinfo,
jalview.gui.AlignFrame alFrame, AlignmentView alview,
String wsname, boolean subgaps, boolean presorder)
{
}
/**
- * create one or more Msa jobs to align visible seuqences in _msa
+ * create one or more Msa jobs to align visible sequences in _msa
*
* @param title
* String
* @param seqset
* Alignment
*/
- MsaWSThread(MsaWS server2, WsParamSetI preset, List<Argument> paramset,
+ public MsaWSThread(MultipleSequenceAlignmentI server2, WsParamSetI preset,
+ List<ArgumentI> paramset,
String wsUrl, WebserviceInfo wsinfo,
jalview.gui.AlignFrame alFrame, String wsname, String title,
AlignmentView _msa, boolean subgaps, boolean presorder,
if (conmsa != null)
{
int nvalid = 0, njobs = conmsa.length;
- jobs = new MsaWSJob[njobs];
+ jobs = new AWsJob[njobs];
for (int j = 0; j < njobs; j++)
{
if (j != 0)
{
- jobs[j] = new MsaWSJob(wsinfo.addJobPane(), conmsa[j]);
+ jobs[j] = new MsaWSJob(this, wsinfo.addJobPane(), conmsa[j]);
}
else
{
- jobs[j] = new MsaWSJob(0, conmsa[j]);
+ jobs[j] = new MsaWSJob(this, 0, conmsa[j]);
}
- if (((MsaWSJob) jobs[j]).hasValidInput())
+ if (jobs[j].hasValidInput())
{
nvalid++;
}
- ((MsaWSJob) jobs[j]).preset = preset;
- ((MsaWSJob) jobs[j]).arguments = paramset;
+ jobs[j].setPreset(preset);
+ jobs[j].setArguments(paramset);
((MsaWSJob) jobs[j]).alignmentProgram = wsname;
if (njobs > 0)
{
@Override
public boolean isCancellable()
{
- return true;
+ return server instanceof CancellableI;
}
@Override
public void cancelJob()
{
+ // TODO decide if when some jobs are not cancellable to shut down the thread
+ // anyhow ?
if (!jobComplete && jobs != null)
{
boolean cancelled = true;
String cancelledMessage = "";
try
{
- boolean cancelledJob = server.cancelJob(jobs[job].getJobId());
- if (true) // cancelledJob || true)
+ CancellableI service = (CancellableI) server;
+ boolean cancelledJob = service.cancel((WsJob) jobs[job]);
+ if (cancelledJob)
{
// CANCELLED_JOB
- // if the Jaba server indicates the job can't be cancelled, its
- // because its running on the server's local execution engine
- // so we just close the window anyway.
cancelledMessage = "Job cancelled.";
((MsaWSJob) jobs[job]).cancel(); // TODO: refactor to avoid this
// ugliness -
{
cancelledMessage += ("\nProblems cancelling the job : Exception received...\n"
+ exc + "\n");
- Cache.log.warn(
+ Console.warn(
"Exception whilst cancelling " + jobs[job].getJobId(),
exc);
}
// this is standard code, but since the interface doesn't comprise of a
// basic one that implements (getJobStatus, pullExecStatistics) we have to
// repeat the code for all jw2s services.
- j.setjobStatus(server.getJobStatus(job.getJobId()));
- updateJobProgress(j);
- }
-
- /**
- *
- * @param j
- * @return true if more job progress data was available
- * @throws Exception
- */
- protected boolean updateJobProgress(MsaWSJob j) throws Exception
- {
- StringBuffer response = j.jobProgress;
- long lastchunk = j.getLastChunk();
- boolean changed = false;
- do
- {
- j.setLastChunk(lastchunk);
- ChunkHolder chunk = server.pullExecStatistics(j.getJobId(),
- lastchunk);
- if (chunk != null)
- {
- changed |= chunk.getChunk().length() > 0;
- response.append(chunk.getChunk());
- lastchunk = chunk.getNextPosition();
- try
- {
- Thread.sleep(50);
- } catch (InterruptedException x)
- {
- }
- ;
- }
- ;
- } while (lastchunk >= 0 && j.getLastChunk() != lastchunk);
- return changed;
+ server.updateStatus(j);
+ server.updateJobProgress(j);
}
@Override
MsaWSJob j = (MsaWSJob) job;
if (j.isSubmitted())
{
- if (Cache.log.isDebugEnabled())
+ if (Console.isDebugEnabled())
{
- Cache.log.debug(
+ Console.debug(
"Tried to submit an already submitted job " + j.getJobId());
}
return;
if (j.seqs == null || j.seqs.size() == 0)
{
// special case - selection consisted entirely of empty sequences...
- j.setjobStatus(JobStatus.FINISHED);
+ j.setState(JobState.FINISHED);
j.setStatus(MessageManager.getString("label.empty_alignment_job"));
}
try
{
j.addInitialStatus(); // list the presets/parameters used for the job in
// status
- if (j.isPresetJob())
- {
- j.setJobId(server.presetAlign(j.seqs, j.getServerPreset()));
- }
- else if (j.hasArguments())
+ try
{
- j.setJobId(server.customAlign(j.seqs, j.getJabaArguments()));
- }
- else
+ JobId jobHandle = server.align(j.seqs, j.getPreset(),
+ j.getArguments());
+ if (jobHandle != null)
+ {
+ j.setJobHandle(jobHandle);
+ }
+
+ } catch (Throwable throwable)
{
- Cache.log.error("failed to send the job to the alignment server", throwable);
- j.setJobId(server.align(j.seqs));
++ Console.error("failed to send the job to the alignment server", throwable);
+ if (!server.handleSubmitError(throwable, j, wsInfo))
+ {
+ if (throwable instanceof Exception)
+ {
+ throw ((Exception) throwable);
+ }
+ if (throwable instanceof Error)
+ {
+ throw ((Error) throwable);
+ }
+ }
}
+ ///// generic
+
if (j.getJobId() != null)
{
j.setSubmitted(true);
new String[]
{ WsUrl }));
}
- } catch (compbio.metadata.UnsupportedRuntimeException _lex)
- {
- lex = _lex;
- wsInfo.appendProgressText(MessageManager.formatMessage(
- "info.job_couldnt_be_run_server_doesnt_support_program",
- new String[]
- { _lex.getMessage() }));
- wsInfo.warnUser(_lex.getMessage(),
- MessageManager.getString("warn.service_not_supported"));
- wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
- wsInfo.setStatus(j.getJobnum(),
- WebserviceInfo.STATE_STOPPED_SERVERERROR);
- } catch (compbio.metadata.LimitExceededException _lex)
- {
- lex = _lex;
- wsInfo.appendProgressText(MessageManager.formatMessage(
- "info.job_couldnt_be_run_exceeded_hard_limit", new String[]
- { _lex.getMessage() }));
- wsInfo.warnUser(_lex.getMessage(),
- MessageManager.getString("warn.input_is_too_big"));
- wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
- wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
- } catch (compbio.metadata.WrongParameterException _lex)
- {
- lex = _lex;
- wsInfo.warnUser(_lex.getMessage(),
- MessageManager.getString("warn.invalid_job_param_set"));
- wsInfo.appendProgressText(MessageManager.formatMessage(
- "info.job_couldnt_be_run_incorrect_param_setting",
- new String[]
- { _lex.getMessage() }));
- wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
- wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
- } catch (Error e)
+ }
+ //// jabaws specific
+
+ //// generic
+ catch (Error e)
{
// For unexpected errors
System.err.println(WebServiceName
{
try
{
- jpchanged = updateJobProgress(msjob);
+ jpchanged = server.updateJobProgress(msjob);
jpex = false;
if (jpchanged)
{
} catch (Exception e)
{
- Cache.log.warn(
+ Console.warn(
"Exception when retrieving remaining Job progress data for job "
+ msjob.getJobId() + " on server " + WsUrl);
e.printStackTrace();
}
} while (nunchanged > 0 && nexcept > 0);
- if (Cache.log.isDebugEnabled())
+ if (Console.isDebugEnabled())
{
System.out.println("Job Execution file for job: "
+ msjob.getJobId() + " on server " + WsUrl);
System.out.println("*** End of status");
}
+ ///// jabaws specific(ish) Get Result from Server when available
try
{
- msjob.alignment = server.getResult(msjob.getJobId());
- } catch (compbio.metadata.ResultNotAvailableException e)
- {
- // job has failed for some reason - probably due to invalid
- // parameters
- Console.debug(
- "Results not available for finished job - marking as broken job.",
- e);
- msjob.jobProgress.append(
- "\nResult not available. Probably due to invalid input or parameter settings. Server error message below:\n\n"
- + e.getLocalizedMessage());
- msjob.setjobStatus(JobStatus.FAILED);
+ msjob.alignment = server.getAlignmentFor(msjob.getJobHandle());
} catch (Exception e)
{
- Console.error("Couldn't get Alignment for job.", e);
- // TODO: Increment count and retry ?
- msjob.setjobStatus(JobStatus.UNDEFINED);
+ if (!server.handleCollectionException(e, msjob, wsInfo))
+ {
- Cache.log.error("Couldn't get Alignment for job.", e);
++ Console.error("Couldn't get Alignment for job.", e);
+ // TODO: Increment count and retry ?
+ msjob.setState(JobState.SERVERERROR);
+ }
}
}
finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
&& jobs[j].hasResults())
{
results++;
- compbio.data.sequence.Alignment alignment = ((MsaWSJob) jobs[j]).alignment;
- if (alignment != null)
- {
- // server.close(jobs[j].getJobnum());
- // wsInfo.appendProgressText(jobs[j].getJobnum(),
- // "\nAlignment Object Method Notes\n");
- // wsInfo.appendProgressText(jobs[j].getJobnum(),
- // "Calculated with
- // "+alignment.getMetadata().getProgram().toString());
- // JBPNote The returned files from a webservice could be
- // hidden behind icons in the monitor window that,
- // when clicked, pop up their corresponding data
- }
}
}
} catch (Exception ex)
{
- Cache.log.error(
+ Console.error(
"Unexpected exception when processing results for " + alTitle,
ex);
wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
void displayResults(boolean newFrame)
{
// view input or result data for each block
- List<AlignmentOrder> alorders = new ArrayList<AlignmentOrder>();
+ List<AlignmentOrder> alorders = new ArrayList<>();
SequenceI[][] results = new SequenceI[jobs.length][];
AlignmentOrder[] orders = new AlignmentOrder[jobs.length];
String lastProgram = null;
if (newFrame)
{
displayInNewFrame(al, alorders, hidden);
+
}
else
{
else
{
// construct a non-redundant ordering set
- List<String> names = new ArrayList<String>();
+ List<String> names = new ArrayList<>();
for (int i = 0, l = alorders.size(); i < l; i++)
{
String orderName = " Region " + i;
*/
package jalview.ws.jws1;
-import jalview.bin.Cache;
-import jalview.bin.Console;
-import jalview.gui.JvOptionPane;
-import jalview.util.MessageManager;
+
import java.net.URL;
import java.util.Hashtable;
import java.util.StringTokenizer;
import ext.vamsas.RegistryServiceSoapBindingStub;
import ext.vamsas.ServiceHandle;
import ext.vamsas.ServiceHandles;
+import jalview.bin.Cache;
++import jalview.bin.Console;
+import jalview.bin.ApplicationSingletonProvider;
+import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
+import jalview.gui.JvOptionPane;
+import jalview.util.MessageManager;
-public class Discoverer implements Runnable
+public class Discoverer implements Runnable, ApplicationSingletonI
{
-
+ public static Discoverer getInstance()
+ {
+ return (Discoverer) ApplicationSingletonProvider.getInstance(Discoverer.class);
+ }
+
+ private Discoverer()
+ {
+ // use getInstance()
+ }
-
ext.vamsas.IRegistry registry; // the root registry service.
private java.beans.PropertyChangeSupport changeSupport = new java.beans.PropertyChangeSupport(
// timeout
} catch (Exception ex)
{
- jalview.bin.Cache.log.error(
+ Console.error(
"Serious! Service location failed\nfor URL :" + WsURL + "\n",
ex);
return server;
}
- static private java.net.URL RootServiceURL = null;
+ private java.net.URL RootServiceURL = null;
- static public Vector<URL> ServiceURLList = null;
+ private Vector<URL> ServiceURLList = null;
- static private boolean reallyDiscoverServices = true;
+ public Vector<URL> getServiceURLList() {
+ return ServiceURLList;
+ }
+
+ private boolean reallyDiscoverServices = true;
- public static java.util.Hashtable<String, Vector<ServiceHandle>> services = null;
+ private java.util.Hashtable<String, Vector<ServiceHandle>> services = null;
// stored by
// abstractServiceType
// string
- public static java.util.Vector<ServiceHandle> serviceList = null;
+ public java.util.Vector<ServiceHandle> serviceList = null;
- static private Vector<URL> getDiscoveryURLS()
+ private Vector<URL> getDiscoveryURLS()
{
Vector<URL> urls = new Vector<>();
- String RootServiceURLs = jalview.bin.Cache.getDefault("DISCOVERY_URLS",
+ String RootServiceURLs = Cache.getDefault("DISCOVERY_URLS",
"http://www.compbio.dundee.ac.uk/JalviewWS/services/ServiceRegistry");
try
}
else
{
- jalview.bin.Cache.log
- .info("Ignoring duplicate url in DISCOVERY_URLS list");
+ Console.info("Ignoring duplicate url in DISCOVERY_URLS list");
}
} catch (Exception ex)
{
- jalview.bin.Cache.log
- .warn("Problem whilst trying to make a URL from '"
- + ((url != null) ? url : "<null>") + "'");
- jalview.bin.Cache.log.warn(
+ Console.warn("Problem whilst trying to make a URL from '"
+ + ((url != null) ? url : "<null>") + "'");
+ Console.warn(
"This was probably due to a malformed comma separated list"
+ " in the DISCOVERY_URLS entry of $(HOME)/.jalview_properties)");
- jalview.bin.Cache.log.debug("Exception was ", ex);
+ Console.debug("Exception was ", ex);
}
}
} catch (Exception ex)
{
- jalview.bin.Cache.log.warn(
+ Console.warn(
"Error parsing comma separated list of urls in DISCOVERY_URLS.",
ex);
}
*/
static public void doDiscovery()
{
- Console.debug("(Re)-Initialising the discovery URL list.");
+ getInstance().discovery();
+ }
+
+ private void discovery()
+ {
- jalview.bin.Cache.log
++ Console
+ .debug("(Re)-Initialising the discovery URL list.");
try
{
- reallyDiscoverServices = Cache.getDefault("DISCOVERY_START", false);
+ Discoverer d = getInstance();
- reallyDiscoverServices = jalview.bin.Cache
++ reallyDiscoverServices = Cache
+ .getDefault("DISCOVERY_START", false);
if (reallyDiscoverServices)
{
ServiceURLList = getDiscoveryURLS();
}
else
{
- jalview.bin.Cache.log.debug("Setting default services");
+ Console.debug("Setting default services");
services = new Hashtable<>();
// Muscle, Clustal and JPred.
ServiceHandle[] defServices = { new ServiceHandle("MsaWS",
ServiceHandles shs = null;
try
{
- jalview.bin.Cache.log.debug("Discovering services using " + location);
+ Console.debug("Discovering services using " + location);
shs = locateWebService(location).getServices();
} catch (org.apache.axis.AxisFault f)
{
// JBPNote - should do this a better way!
if (f.getFaultReason().indexOf("(407)") > -1)
{
- if (jalview.gui.Desktop.desktop != null)
+ if (jalview.gui.Desktop.getDesktopPane() != null)
{
- JvOptionPane.showMessageDialog(jalview.gui.Desktop.desktop,
+ JvOptionPane.showMessageDialog(jalview.gui.Desktop.getDesktopPane(),
MessageManager.getString("label.set_proxy_settings"),
MessageManager
.getString("label.proxy_authorization_failed"),
}
else
{
- jalview.bin.Cache.log.warn("No Discovery service at " + location);
- jalview.bin.Cache.log.debug("Axis Fault", f);
+ Console.warn("No Discovery service at " + location);
+ Console.debug("Axis Fault", f);
}
} catch (Exception e)
{
- jalview.bin.Cache.log.warn("No Discovery service at " + location);
- jalview.bin.Cache.log.debug("Discovery Service General Exception", e);
+ Console.warn("No Discovery service at " + location);
+ Console.debug("Discovery Service General Exception", e);
}
if ((shs != null) && shs.getServices().length > 0)
{
* Hashtable
* @return boolean
*/
- static private boolean buildServiceLists(ServiceHandle[] sh,
+ private boolean buildServiceLists(ServiceHandle[] sh,
Vector<ServiceHandle> cat,
Hashtable<String, Vector<ServiceHandle>> sscat)
{
{
if (!cat.contains(sh[i]))
{
- jalview.bin.Cache.log.debug("A " + sh[i].getAbstractName()
- + " service called " + sh[i].getName() + " exists at "
- + sh[i].getEndpointURL() + "\n");
+ Console.debug("A " + sh[i].getAbstractName() + " service called "
+ + sh[i].getName() + " exists at " + sh[i].getEndpointURL()
+ + "\n");
if (!sscat.containsKey(sh[i].getAbstractName()))
{
sscat.put(sh[i].getAbstractName(), cat = new Vector<>());
disc_serv = new java.net.URL(sh[i].getEndpointURL());
if (!ServiceURLList.contains(disc_serv))
{
- jalview.bin.Cache.log.debug(
+ Console.debug(
"Adding new discovery service at " + disc_serv);
ServiceURLList.add(disc_serv);
seenNewDiscovery = true;
}
} catch (Exception e)
{
- jalview.bin.Cache.log
- .debug("Ignoring bad discovery service URL "
- + sh[i].getEndpointURL(), e);
+ Console.debug("Ignoring bad discovery service URL "
+ + sh[i].getEndpointURL(), e);
}
}
}
int s_url = 0;
if (ServiceURLList == null)
{
- jalview.bin.Cache.log
- .debug("No service endpoints to use for service discovery.");
+ Console.debug("No service endpoints to use for service discovery.");
return;
}
while (s_url < ServiceURLList.size())
{
- if ((sh = getServices(ServiceURLList.get(s_url))) != null)
+ if ((sh = getServices(
+ ServiceURLList.get(s_url))) != null)
{
buildServiceLists(sh, cat, sscat);
}
else
{
- jalview.bin.Cache.log.warn("No services at "
- + (ServiceURLList.get(s_url))
+ Console.warn("No services at " + (ServiceURLList.get(s_url))
+ " - check DISCOVERY_URLS property in .jalview_properties");
}
s_url++;
@Override
public void run()
{
- Cache.log.info("Discovering jws1 services");
- final Discoverer discoverer = this;
- Thread discoverThread = new Thread()
- {
- @Override
- public void run()
- {
- Discoverer.doDiscovery();
- discoverer.discoverServices();
- }
- };
- discoverThread.start();
++ Console.info("Discovering jws1 services");
+ Discoverer.doDiscovery();
+ discoverServices();
}
/**
* binding service abstract name to handler class
*/
- private static Hashtable<String, WS1Client> serviceClientBindings;
+ private Hashtable<String, WS1Client> serviceClientBindings;
public static WS1Client getServiceClient(ServiceHandle sh)
{
+ return getInstance().getClient(sh);
+ }
+
+ /**
+ * notes on discovery service 1. need to allow multiple discovery source urls.
+ * 2. user interface to add/control list of urls in preferences notes on
+ * wsclient discovery 1. need a classpath property with list of additional
+ * plugin directories 2. optional config to cite specific bindings between
+ * class name and Abstract service name. 3. precedence for automatic discovery
+ * by using getAbstractName for WSClient - user added plugins override default
+ * plugins ? notes on wsclient gui code for gui attachment now moved to
+ * wsclient implementation. Needs more abstraction but approach seems to work.
+ * is it possible to 'generalise' the data retrieval calls further ? current
+ * methods are very specific (gatherForMSA or gatherForSeqOrMsaSecStrPred),
+ * new methods for conservation (group or alignment), treecalc (aligned
+ * profile), seqannot (sequences selected from dataset, annotation back to
+ * dataset).
+ *
+ */
+
+ private WS1Client getClient(ServiceHandle sh)
+ {
if (serviceClientBindings == null)
{
// get a list from Config or create below
serviceClientBindings.put("SecStrPred", new JPredClient());
serviceClientBindings.put("SeqSearch", new SeqSearchWSClient());
}
- WS1Client instance = serviceClientBindings.get(sh.getAbstractName());
+ WS1Client instance = serviceClientBindings
+ .get(sh.getAbstractName());
if (instance == null)
{
System.err.println(
}
return instance;
}
-
- /**
- * notes on discovery service 1. need to allow multiple discovery source urls.
- * 2. user interface to add/control list of urls in preferences notes on
- * wsclient discovery 1. need a classpath property with list of additional
- * plugin directories 2. optional config to cite specific bindings between
- * class name and Abstract service name. 3. precedence for automatic discovery
- * by using getAbstractName for WSClient - user added plugins override default
- * plugins ? notes on wsclient gui code for gui attachment now moved to
- * wsclient implementation. Needs more abstraction but approach seems to work.
- * is it possible to 'generalise' the data retrieval calls further ? current
- * methods are very specific (gatherForMSA or gatherForSeqOrMsaSecStrPred),
- * new methods for conservation (group or alignment), treecalc (aligned
- * profile), seqannot (sequences selected from dataset, annotation back to
- * dataset).
- *
- */
+ public static Hashtable<String, Vector<ServiceHandle>> getServices()
+ {
+ return getInstance().services;
+ }
}
package jalview.ws.jws1;
import java.util.Locale;
--
import jalview.analysis.AlignSeq;
+import jalview.analysis.SeqsetUtils.SequenceInfo;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.AlignmentView;
import jalview.datamodel.SeqCigar;
import jalview.datamodel.SequenceI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;
+import java.util.Map;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
Jpred server = locateWebService();
if (server == null)
{
- Cache.log.warn("Couldn't find a Jpred webservice to invoke!");
+ Console.warn("Couldn't find a Jpred webservice to invoke!");
return;
}
SeqCigar[] msf = null;
aln[i] = msf[i].getSeq('-');
}
- Hashtable SequenceInfo = jalview.analysis.SeqsetUtils.uniquify(aln,
- true);
+ Map<String, SequenceInfo> SequenceInfo =
+ jalview.analysis.SeqsetUtils.uniquify(aln, true);
if (viewonly)
{
// Remove hidden regions from sequence objects.
+ (viewonly ? "visible " : "") + "sequence " + seq.getName()
+ " from " + title;
String seqname = seq.getName();
- Hashtable SequenceInfo = jalview.analysis.SeqsetUtils
+ SequenceInfo SequenceInfo = jalview.analysis.SeqsetUtils
.SeqCharacterHash(seq);
if (viewonly)
{
aln[i] = new jalview.datamodel.Sequence(msf[i]);
}
- Hashtable SequenceInfo = jalview.analysis.SeqsetUtils.uniquify(aln,
- true);
+ Map<String, SequenceInfo> SequenceInfo =
+ jalview.analysis.SeqsetUtils.uniquify(aln, true);
Jpred server = locateWebService();
if (server == null)
String altitle = "JPred prediction for sequence " + seq.getName()
+ " from " + title;
- Hashtable SequenceInfo = jalview.analysis.SeqsetUtils
+ SequenceInfo SequenceInfo = jalview.analysis.SeqsetUtils
.SeqCharacterHash(seq);
Jpred server = locateWebService();
WsURL = "http://www.compbio.dundee.ac.uk/JalviewWS/services/jpred";
WebserviceInfo wsInfo = new WebserviceInfo(WebServiceJobTitle,
- WebServiceReference, true);
+ WebServiceReference, Desktop.FRAME_MAKE_VISIBLE);
return wsInfo;
}
} catch (Exception ex)
{
- JvOptionPane.showMessageDialog(Desktop.desktop,
+ JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
MessageManager.formatMessage(
"label.secondary_structure_prediction_service_couldnt_be_located",
new String[]
import jalview.analysis.AlignSeq;
import jalview.analysis.SeqsetUtils;
+import jalview.analysis.SeqsetUtils.SequenceInfo;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentAnnotation;
import jalview.datamodel.AlignmentI;
import java.util.Hashtable;
import java.util.List;
+import java.util.Map;
import vamsas.objects.simple.JpredResult;
vamsas.objects.simple.Msfalignment msa;
- java.util.Hashtable SequenceInfo = null;
+ Object SequenceInfo = null;
int msaIndex = 0; // the position of the original sequence in the array of
JpredResult result = (JpredResult) this.result;
- Cache.log.debug("Parsing output from JNet job.");
+ Console.debug("Parsing output from JNet job.");
// JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt",
// "File");
JPredFile prediction = new JPredFile(result.getPredfile(),
DataSourceType.PASTE);
SequenceI[] preds = prediction.getSeqsAsArray();
- Cache.log.debug("Got prediction profile.");
+ Console.debug("Got prediction profile.");
if ((this.msa != null) && (result.getAligfile() != null))
{
- Cache.log.debug("Getting associated alignment.");
+ Console.debug("Getting associated alignment.");
// we ignore the returned alignment if we only predicted on a single
// sequence
FileFormatI format = new IdentifyFile()
{
sqs[i] = al.getSequenceAt(i);
}
- if (!SeqsetUtils.deuniquify(SequenceInfo, sqs))
+ if (!SeqsetUtils.deuniquify((Map<String, SequenceInfo>)SequenceInfo, sqs))
{
throw (new Exception(MessageManager.getString(
"exception.couldnt_recover_sequence_properties_for_alignment")));
}
if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(
- al.getSequenceAt(FirstSeq), SequenceInfo))
+ al.getSequenceAt(FirstSeq), (SequenceInfo)SequenceInfo))
{
throw (new Exception(MessageManager.getString(
"exception.couldnt_recover_sequence_props_for_jnet_query")));
}
}
- public JPredJob(Hashtable SequenceInfo, SequenceI seq, int[] delMap)
+ public JPredJob(Object SequenceInfo, SequenceI seq, int[] delMap)
{
super();
this.predMap = delMap;
}
}
- public JPredJob(Hashtable SequenceInfo, SequenceI[] msf, int[] delMap)
+ public JPredJob(Object SequenceInfo, SequenceI[] msf, int[] delMap)
{
this(SequenceInfo, msf[0], delMap);
if (sequence != null)
}
JPredThread(WebserviceInfo wsinfo, String altitle,
- ext.vamsas.Jpred server, String wsurl, Hashtable SequenceInfo,
+ ext.vamsas.Jpred server, String wsurl, SequenceInfo SequenceInfo,
SequenceI seq, int[] delMap, AlignmentView alview,
AlignFrame alframe)
{
}
JPredThread(WebserviceInfo wsinfo, String altitle,
- ext.vamsas.Jpred server, Hashtable SequenceInfo, SequenceI[] msf,
- int[] delMap, AlignmentView alview, AlignFrame alframe,
- String wsurl)
+ ext.vamsas.Jpred server, Map<String, SequenceInfo> SequenceInfo,
+ SequenceI[] msf, int[] delMap, AlignmentView alview,
+ AlignFrame alframe, String wsurl)
{
this(wsinfo, altitle, server, wsurl, alview, alframe);
JPredJob job = new JPredJob(SequenceInfo, msf, delMap);
{
job.setSubmitted(true);
job.setSubjobComplete(false);
- Cache.log.info(WsUrl + " Job Id '" + job.getJobId() + "'");
+ Console.info(WsUrl + " Job Id '" + job.getJobId() + "'");
}
}
else
"JPredWS Client: Failed to submit the prediction. Quite possibly because of a server error - see below)\n"
+ e.getMessage() + "\n");
- jalview.bin.Cache.log.warn("Server Exception", e);
+ Console.warn("Server Exception", e);
}
else
{
"info.failed_to_submit_prediction", new String[]
{ e.getMessage(), wsInfo.getProgressText() }));
- jalview.bin.Cache.log
- .debug("Failed Submission of job " + j.getJobnum(), e);
+ Console.debug("Failed Submission of job " + j.getJobnum(), e);
}
j.setAllowedServerExceptions(-1);
} catch (Exception ex)
{
- Cache.log.error(
+ Console.error(
"Unexpected exception when processing results for " + altitle,
ex);
wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
msa = (j.msa != null) ? true : msa;
try
{
- jalview.bin.Cache.log.debug("Parsing output of job " + jn);
+ Console.debug("Parsing output of job " + jn);
jobres = j.getResultSet();
- jalview.bin.Cache.log.debug("Finished parsing output.");
+ Console.debug("Finished parsing output.");
if (jobs.length == 1)
{
res = jobres;
}
} catch (Exception e)
{
- jalview.bin.Cache.log
- .error("JNet Client: JPred Annotation Parse Error", e);
+ Console.error("JNet Client: JPred Annotation Parse Error", e);
wsInfo.setStatus(j.getJobnum(),
WebserviceInfo.STATE_STOPPED_ERROR);
wsInfo.appendProgressText(j.getJobnum(),
}
else
{
- Cache.log.info("Append results onto existing alignment.");
+ Console.info("Append results onto existing alignment.");
}
}
}
package jalview.ws.jws1;
import jalview.analysis.AlignSeq;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.AlignmentOrder;
import jalview.ws.JobStateSummary;
import jalview.ws.WSClientI;
-import java.util.Hashtable;
import java.util.Vector;
import vamsas.objects.simple.MsaResult;
}
- Hashtable SeqNames = new Hashtable();
-
Vector emptySeqs = new Vector();
/**
{
cancelledMessage += ("\nProblems cancelling the job : Exception received...\n"
+ exc + "\n");
- Cache.log.warn(
+ Console.warn(
"Exception whilst cancelling " + jobs[job].getJobId(),
exc);
}
MsaWSJob j = (MsaWSJob) job;
if (j.isSubmitted())
{
- if (Cache.log.isDebugEnabled())
+ if (Console.isDebugEnabled())
{
- Cache.log.debug(
+ Console.debug(
"Tried to submit an already submitted job " + j.getJobId());
}
return;
&& jobs[j].hasResults())
{
results++;
- // if (Cache.log.isDebugEnabled())
+ // if (Cache.isDebugEnabled())
// {
// System.out.println("Job lob for job
// "+jobs[j].getJobId()+":"+jobs[j].getJobnum());
} catch (Exception ex)
{
- Cache.log.error(
+ Console.error(
"Unexpected exception when processing results for " + alTitle,
ex);
wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
*/
package jalview.ws.jws1;
+ import jalview.bin.Console;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.AlignmentView;
import jalview.gui.AlignFrame;
*/
ext.vamsas.SeqSearchI server;
- AlignFrame alignFrame;
-
/**
* Creates a new MsaWSClient object that uses a service given by an externally
* retrieved ServiceHandle
// name to service client name
if (!sh.getAbstractName().equals(this.getServiceActionKey()))
{
- JvOptionPane.showMessageDialog(Desktop.desktop,
+ JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
MessageManager.formatMessage(
"label.service_called_is_not_seq_search_service",
new String[]
if ((wsInfo = setWebService(sh)) == null)
{
- JvOptionPane.showMessageDialog(Desktop.desktop,
+ JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
MessageManager.formatMessage(
"label.seq_search_service_is_unknown", new String[]
{ sh.getName() }),
.getSupportedDatabases();
} catch (Exception e)
{
- jalview.bin.Cache.log.warn(
+ Console.warn(
"Database list request failed, so disabling SeqSearch Service client "
+ sh.getName() + " at " + sh.getEndpointURL(),
e);
import jalview.analysis.AlignSeq;
import jalview.api.FeatureColourI;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.AlignmentView;
import jalview.ws.WSClientI;
import java.util.HashMap;
-import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;
}
- Hashtable SeqNames = new Hashtable();
-
Vector emptySeqs = new Vector();
/**
{
cancelledMessage += ("\nProblems cancelling the job : Exception received...\n"
+ exc + "\n");
- Cache.log.warn(
+ Console.warn(
"Exception whilst cancelling " + jobs[job].getJobId(),
exc);
}
SeqSearchWSJob j = (SeqSearchWSJob) job;
if (j.isSubmitted())
{
- if (Cache.log.isDebugEnabled())
+ if (Console.isDebugEnabled())
{
- Cache.log.debug(
+ Console.debug(
"Tried to submit an already submitted job " + j.getJobId());
}
return;
} catch (Exception ex)
{
- Cache.log.error(
+ Console.error(
"Unexpected exception when processing results for " + alTitle,
ex);
wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
*/
package jalview.ws.jws2;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
+import jalview.gui.AlignFrame;
+import jalview.ws.api.ServiceWithParameters;
+import jalview.ws.params.ArgumentI;
+import jalview.ws.params.WsParamSetI;
-
import java.util.List;
-import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
-import javax.swing.JMenuItem;
-import javax.swing.event.MenuEvent;
-import javax.swing.event.MenuListener;
-
-import compbio.metadata.Argument;
-import jalview.api.AlignCalcWorkerI;
-import jalview.bin.Console;
-import jalview.gui.AlignFrame;
-import jalview.gui.Desktop;
-import jalview.gui.JvSwingUtils;
-import jalview.gui.WebserviceInfo;
-import jalview.gui.WsJobParameters;
-import jalview.util.MessageManager;
-import jalview.ws.jws2.dm.AAConSettings;
-import jalview.ws.jws2.dm.JabaWsParamSet;
-import jalview.ws.jws2.jabaws2.Jws2Instance;
-import jalview.ws.params.WsParamSetI;
-import jalview.ws.uimodel.AlignAnalysisUIText;
/**
* provides metadata for a jabaws2 service instance - resolves names, etc.
*/
public abstract class Jws2Client extends jalview.ws.WSClient
{
- protected AlignFrame alignFrame;
-
- protected WsParamSetI preset;
-
- protected List<Argument> paramset;
+ /**
+ * instantiate a new service client. preset and arguments are assumed to be
+ * valid for the service
+ *
+ * @param _alignFrame
+ * @param preset
+ * @param arguments
+ */
public Jws2Client(AlignFrame _alignFrame, WsParamSetI preset,
- List<Argument> arguments)
- {
- alignFrame = _alignFrame;
- this.preset = preset;
- if (preset != null)
- {
- if (!((preset instanceof JabaPreset)
- || preset instanceof JabaWsParamSet))
- {
- /*
- * { this.preset = ((JabaPreset) preset).p; } else if (preset instanceof
- * JabaWsParamSet) { List<Argument> newargs = new ArrayList<Argument>();
- * JabaWsParamSet pset = ((JabaWsParamSet) preset); for (Option opt :
- * pset.getjabaArguments()) { newargs.add(opt); } if (arguments != null
- * && arguments.size() > 0) { // merge arguments with preset's own
- * arguments. for (Argument opt : arguments) { newargs.add(opt); } }
- * paramset = newargs; } else {
- */
- throw new Error(MessageManager.getString(
- "error.implementation_error_can_only_instantiate_jaba_param_sets"));
- }
- }
- else
- {
- // just provided with a bunch of arguments
- this.paramset = arguments;
- }
- }
-
- boolean processParams(Jws2Instance sh, boolean editParams)
+ List<ArgumentI> arguments)
{
- return processParams(sh, editParams, false);
- }
-
- protected boolean processParams(Jws2Instance sh, boolean editParams,
- boolean adjustingExisting)
- {
-
- if (editParams)
- {
- if (sh.paramStore == null)
- {
- sh.paramStore = new JabaParamStore(sh,
- Desktop.getUserParameterStore());
- }
- WsJobParameters jobParams = (preset == null && paramset != null
- && paramset.size() > 0)
- ? new WsJobParameters(null, sh, null, paramset)
- : new WsJobParameters(sh, preset);
- if (adjustingExisting)
- {
- jobParams.setName(MessageManager
- .getString("label.adjusting_parameters_for_calculation"));
- }
- if (!jobParams.showRunDialog())
- {
- return false;
- }
- WsParamSetI prset = jobParams.getPreset();
- if (prset == null)
- {
- paramset =
- /* JAL-3739 always take values from input form */
- /* jobParams.isServiceDefaults() ? null : */
- JabaParamStore.getJabafromJwsArgs(jobParams.getJobParams());
- this.preset = null;
- }
- else
- {
- this.preset = prset; // ((JabaPreset) prset).p;
- paramset = null; // no user supplied parameters.
- }
- }
- return true;
+ super(_alignFrame, preset, arguments);
}
// anonymous constructor - used for headless method calls only
}
- protected WebserviceInfo setWebService(Jws2Instance serv, boolean b)
- {
- // serviceHandle = serv;
- String serviceInstance = serv.action; // serv.service.getClass().getName();
- WebServiceName = serv.serviceType;
- WebServiceJobTitle = serv.getActionText();
- WsURL = serv.hosturl;
- if (!b)
- {
- return new WebserviceInfo(WebServiceJobTitle,
- WebServiceJobTitle + " using service hosted at "
- + serv.hosturl + "\n"
- + (serv.description != null ? serv.description : ""),
- false);
- }
- return null;
- }
/*
* Jws2Instance serviceHandle; (non-Javadoc)
* @param service
* @param alignFrame
*/
- abstract void attachWSMenuEntry(JMenu wsmenu, final Jws2Instance service,
+ abstract void attachWSMenuEntry(JMenu wsmenu,
+ final ServiceWithParameters service,
final AlignFrame alignFrame);
- protected boolean registerAAConWSInstance(final JMenu wsmenu,
- final Jws2Instance service, final AlignFrame alignFrame)
- {
- final AlignAnalysisUIText aaui = service.getAlignAnalysisUI(); // null ; //
- // AlignAnalysisUIText.aaConGUI.get(service.serviceType.toString());
- if (aaui == null)
- {
- // not an instantaneous calculation GUI type service
- return false;
- }
- // create the instaneous calculation GUI bits and update state if existing
- // GUI elements already present
-
- JCheckBoxMenuItem _aaConEnabled = null;
- for (int i = 0; i < wsmenu.getItemCount(); i++)
- {
- JMenuItem item = wsmenu.getItem(i);
- if (item instanceof JCheckBoxMenuItem
- && item.getText().equals(aaui.getAAconToggle()))
- {
- _aaConEnabled = (JCheckBoxMenuItem) item;
- }
- }
- // is there an aaCon worker already present - if so, set it to use the
- // given service handle
- {
- List<AlignCalcWorkerI> aaconClient = alignFrame.getViewport()
- .getCalcManager()
- .getRegisteredWorkersOfClass(aaui.getClient());
- if (aaconClient != null && aaconClient.size() > 0)
- {
- AbstractJabaCalcWorker worker = (AbstractJabaCalcWorker) aaconClient
- .get(0);
- if (!worker.service.hosturl.equals(service.hosturl))
- {
- // javax.swing.SwingUtilities.invokeLater(new Runnable()
- {
- // @Override
- // public void run()
- {
- removeCurrentAAConWorkerFor(aaui, alignFrame);
- buildCurrentAAConWorkerFor(aaui, alignFrame, service);
- }
- } // );
- }
- }
- }
-
- // is there a service already registered ? there shouldn't be if we are
- // being called correctly
- if (_aaConEnabled == null)
- {
- final JCheckBoxMenuItem aaConEnabled = new JCheckBoxMenuItem(
- aaui.getAAconToggle());
-
- aaConEnabled.setToolTipText(
- JvSwingUtils.wrapTooltip(true, aaui.getAAconToggleTooltip()));
- aaConEnabled.addActionListener(new ActionListener()
- {
- @Override
- public void actionPerformed(ActionEvent arg0)
- {
- List<AlignCalcWorkerI> aaconClient = alignFrame.getViewport()
- .getCalcManager()
- .getRegisteredWorkersOfClass(aaui.getClient());
- if (aaconClient != null && aaconClient.size() > 0)
- {
- removeCurrentAAConWorkerFor(aaui, alignFrame);
- }
- else
- {
- buildCurrentAAConWorkerFor(aaui, alignFrame);
-
- }
- }
-
- });
- wsmenu.add(aaConEnabled);
- final JMenuItem modifyParams = new JMenuItem(
- aaui.getAAeditSettings());
- modifyParams.setToolTipText(JvSwingUtils.wrapTooltip(true,
- aaui.getAAeditSettingsTooltip()));
- modifyParams.addActionListener(new ActionListener()
- {
-
- @Override
- public void actionPerformed(ActionEvent arg0)
- {
- showAAConAnnotationSettingsFor(aaui, alignFrame);
- }
- });
- wsmenu.add(modifyParams);
- wsmenu.addMenuListener(new MenuListener()
- {
-
- @Override
- public void menuSelected(MenuEvent arg0)
- {
- // TODO: refactor to the implementing class.
- if (alignFrame.getViewport().getAlignment().isNucleotide()
- ? aaui.isNa()
- : aaui.isPr())
- {
- aaConEnabled.setEnabled(true);
- modifyParams.setEnabled(true);
- }
- else
- {
- aaConEnabled.setEnabled(false);
- modifyParams.setEnabled(false);
- }
- List<AlignCalcWorkerI> aaconClient = alignFrame.getViewport()
- .getCalcManager()
- .getRegisteredWorkersOfClass(aaui.getClient());
- if (aaconClient != null && aaconClient.size() > 0)
- {
- aaConEnabled.setSelected(true);
- }
- else
- {
- aaConEnabled.setSelected(false);
- }
- }
-
- @Override
- public void menuDeselected(MenuEvent arg0)
- {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void menuCanceled(MenuEvent arg0)
- {
- // TODO Auto-generated method stub
-
- }
- });
-
- }
- return true;
- }
-
- private static void showAAConAnnotationSettingsFor(
- final AlignAnalysisUIText aaui, AlignFrame alignFrame)
- {
- /*
- * preferred settings Whether AACon is automatically recalculated Which
- * AACon server to use What parameters to use
- */
- // could actually do a class search for this too
- AAConSettings fave = (AAConSettings) alignFrame.getViewport()
- .getCalcIdSettingsFor(aaui.getCalcId());
- if (fave == null)
- {
- fave = createDefaultAAConSettings(aaui);
- }
- new SequenceAnnotationWSClient(fave, alignFrame, true);
-
- }
-
- private static void buildCurrentAAConWorkerFor(
- final AlignAnalysisUIText aaui, AlignFrame alignFrame)
- {
- buildCurrentAAConWorkerFor(aaui, alignFrame, null);
- }
-
- private static void buildCurrentAAConWorkerFor(
- final AlignAnalysisUIText aaui, AlignFrame alignFrame,
- Jws2Instance service)
- {
- /*
- * preferred settings Whether AACon is automatically recalculated Which
- * AACon server to use What parameters to use
- */
- AAConSettings fave = (AAConSettings) alignFrame.getViewport()
- .getCalcIdSettingsFor(aaui.getCalcId());
- if (fave == null)
- {
- fave = createDefaultAAConSettings(aaui, service);
- }
- else
- {
- if (service != null
- && !fave.getService().hosturl.equals(service.hosturl))
- {
- Console.debug("Changing AACon service to " + service.hosturl
- + " from " + fave.getService().hosturl);
- fave.setService(service);
- }
- }
- new SequenceAnnotationWSClient(fave, alignFrame, false);
- }
-
- private static AAConSettings createDefaultAAConSettings(
- AlignAnalysisUIText aaui)
- {
- return createDefaultAAConSettings(aaui, null);
- }
-
- private static AAConSettings createDefaultAAConSettings(
- AlignAnalysisUIText aaui, Jws2Instance service)
- {
- if (service != null)
- {
- if (!service.serviceType.toString()
- .equals(compbio.ws.client.Services.AAConWS.toString()))
- {
- Console.warn(
- "Ignoring invalid preferred service for AACon calculations (service type was "
- + service.serviceType + ")");
- service = null;
- }
- else
- {
- // check service is actually in the list of currently avaialable
- // services
- if (!Jws2Discoverer.getDiscoverer().getServices().contains(service))
- {
- // it isn't ..
- service = null;
- }
- }
- }
- if (service == null)
- {
- // get the default service for AACon
- service = Jws2Discoverer.getDiscoverer().getPreferredServiceFor(null,
- aaui.getServiceType());
- }
- if (service == null)
- {
- // TODO raise dialog box explaining error, and/or open the JABA
- // preferences menu.
- throw new Error(
- MessageManager.getString("error.no_aacon_service_found"));
- }
- return new AAConSettings(true, service, null, null);
- }
-
- private static void removeCurrentAAConWorkerFor(AlignAnalysisUIText aaui,
- AlignFrame alignFrame)
- {
- alignFrame.getViewport().getCalcManager()
- .removeRegisteredWorkersOfClass(aaui.getClient());
- }
}
--- /dev/null
+package jalview.ws.jws2;
+
+import jalview.api.AlignCalcWorkerI;
+import jalview.bin.Cache;
++import jalview.bin.Console;
+import jalview.gui.AlignFrame;
+import jalview.gui.JvSwingUtils;
+import jalview.util.MessageManager;
+import jalview.ws.api.ServiceWithParameters;
+import jalview.ws.jws2.dm.AAConSettings;
+import jalview.ws.jws2.jabaws2.Jws2Instance;
+import jalview.ws.params.AutoCalcSetting;
+import jalview.ws.uimodel.AlignAnalysisUIText;
+
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.util.List;
+
+import javax.swing.JCheckBoxMenuItem;
+import javax.swing.JMenu;
+import javax.swing.JMenuItem;
+import javax.swing.event.MenuEvent;
+import javax.swing.event.MenuListener;
+
+public class Jws2ClientFactory
+{
+ static boolean registerAAConWSInstance(final JMenu wsmenu,
+ final ServiceWithParameters service, final AlignFrame alignFrame)
+ {
+ final AlignAnalysisUIText aaui = service.getAlignAnalysisUI(); // null
+ // ; //
+ // AlignAnalysisUIText.aaConGUI.get(service.serviceType.toString());
+ if (aaui == null)
+ {
+ // not an instantaneous calculation GUI type service
+ return false;
+ }
+ // create the instaneous calculation GUI bits and update state if existing
+ // GUI elements already present
+
+ JCheckBoxMenuItem _aaConEnabled = null;
+ for (int i = 0; i < wsmenu.getItemCount(); i++)
+ {
+ JMenuItem item = wsmenu.getItem(i);
+ if (item instanceof JCheckBoxMenuItem
+ && item.getText().equals(aaui.getAAconToggle()))
+ {
+ _aaConEnabled = (JCheckBoxMenuItem) item;
+ }
+ }
+ // is there an aaCon worker already present - if so, set it to use the
+ // given service handle
+ {
+ List<AlignCalcWorkerI> aaconClient = alignFrame.getViewport()
+ .getCalcManager()
+ .getWorkersOfClass(aaui.getClient());
+ if (aaconClient != null && aaconClient.size() > 0)
+ {
+ SeqAnnotationServiceCalcWorker worker = (SeqAnnotationServiceCalcWorker) aaconClient
+ .get(0);
+ if (!worker.service.getHostURL().equals(service.getHostURL()))
+ {
+ // javax.swing.SwingUtilities.invokeLater(new Runnable()
+ {
+ // @Override
+ // public void run()
+ {
+ removeCurrentAAConWorkerFor(aaui, alignFrame);
+ buildCurrentAAConWorkerFor(aaui, alignFrame, service);
+ }
+ } // );
+ }
+ }
+ }
+
+ // is there a service already registered ? there shouldn't be if we are
+ // being called correctly
+ if (_aaConEnabled == null)
+ {
+ final JCheckBoxMenuItem aaConEnabled = new JCheckBoxMenuItem(
+ aaui.getAAconToggle());
+
+ aaConEnabled.setToolTipText(
+ JvSwingUtils.wrapTooltip(true, aaui.getAAconToggleTooltip()));
+ aaConEnabled.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent arg0)
+ {
+
+ List<AlignCalcWorkerI> aaconClient = alignFrame.getViewport()
+ .getCalcManager()
+ .getWorkersOfClass(SeqAnnotationServiceCalcWorker.class);
+ if (aaconClient != null)
+ {
+ for (AlignCalcWorkerI worker : aaconClient)
+ {
+ if (((SeqAnnotationServiceCalcWorker) worker).getService()
+ .getClass().equals(aaui.getClient()))
+ {
+ removeCurrentAAConWorkerFor(aaui, alignFrame);
+ return;
+ }
+ }
+ }
+ buildCurrentAAConWorkerFor(aaui, alignFrame);
+ }
+
+ });
+ wsmenu.add(aaConEnabled);
+ final JMenuItem modifyParams = new JMenuItem(
+ aaui.getAAeditSettings());
+ modifyParams.setToolTipText(JvSwingUtils.wrapTooltip(true,
+ aaui.getAAeditSettingsTooltip()));
+ modifyParams.addActionListener(new ActionListener()
+ {
+
+ @Override
+ public void actionPerformed(ActionEvent arg0)
+ {
+ showAAConAnnotationSettingsFor(aaui, alignFrame);
+ }
+ });
+ wsmenu.add(modifyParams);
+ wsmenu.addMenuListener(new MenuListener()
+ {
+
+ @Override
+ public void menuSelected(MenuEvent arg0)
+ {
+ // TODO: refactor to the implementing class.
+ if (alignFrame.getViewport().getAlignment().isNucleotide()
+ ? aaui.isNa()
+ : aaui.isPr())
+ {
+ aaConEnabled.setEnabled(true);
+ modifyParams.setEnabled(true);
+ }
+ else
+ {
+ aaConEnabled.setEnabled(false);
+ modifyParams.setEnabled(false);
+ return;
+ }
+ List<AlignCalcWorkerI> aaconClient = alignFrame.getViewport()
+ .getCalcManager()
+ .getWorkersOfClass(SeqAnnotationServiceCalcWorker.class);
+
+ boolean serviceEnabled = false;
+ if (aaconClient != null)
+ {
+ // NB code duplicatino again!
+ for (AlignCalcWorkerI _worker : aaconClient)
+ {
+ SeqAnnotationServiceCalcWorker worker = (SeqAnnotationServiceCalcWorker) _worker;
+ // this could be cleaner ?
+ if (worker.hasService()
+ && aaui.getClient()
+ .equals(worker.getService().getClass()))
+ {
+ serviceEnabled = true;
+ }
+ }
+ }
+ aaConEnabled.setSelected(serviceEnabled);
+ }
+
+ @Override
+ public void menuDeselected(MenuEvent arg0)
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void menuCanceled(MenuEvent arg0)
+ {
+ // TODO Auto-generated method stub
+
+ }
+ });
+
+ }
+ return true;
+ }
+
+ private static void showAAConAnnotationSettingsFor(
+ final AlignAnalysisUIText aaui, AlignFrame alignFrame)
+ {
+ /*
+ * preferred settings Whether AACon is automatically recalculated Which
+ * AACon server to use What parameters to use
+ */
+ // could actually do a class search for this too
+ AutoCalcSetting fave = alignFrame.getViewport()
+ .getCalcIdSettingsFor(aaui.getCalcId());
+ if (fave == null)
+ {
+ fave = createDefaultAAConSettings(aaui);
+ }
+ new SequenceAnnotationWSClient(fave, alignFrame, true);
+
+ }
+
+ private static void buildCurrentAAConWorkerFor(
+ final AlignAnalysisUIText aaui, AlignFrame alignFrame)
+ {
+ buildCurrentAAConWorkerFor(aaui, alignFrame, null);
+ }
+
+ private static void buildCurrentAAConWorkerFor(
+ final AlignAnalysisUIText aaui, AlignFrame alignFrame,
+ ServiceWithParameters service)
+ {
+ /*
+ * preferred settings Whether AACon is automatically recalculated Which
+ * AACon server to use What parameters to use
+ */
+ AutoCalcSetting fave = alignFrame.getViewport()
+ .getCalcIdSettingsFor(aaui.getCalcId());
+ if (fave == null)
+ {
+ fave = createDefaultAAConSettings(aaui, service);
+ }
+ else
+ {
+ if (service != null && !fave.getService().getHostURL()
+ .equals(service.getHostURL()))
+ {
- Cache.log.debug("Changing AACon service to " + service.getHostURL()
++ Console.debug("Changing AACon service to " + service.getHostURL()
+ + " from " + fave.getService().getHostURL());
+ fave.setService(service);
+ }
+ }
+ new SequenceAnnotationWSClient(fave, alignFrame, false);
+ }
+
+ private static AutoCalcSetting createDefaultAAConSettings(
+ AlignAnalysisUIText aaui)
+ {
+ return createDefaultAAConSettings(aaui, null);
+ }
+
+ private static AutoCalcSetting createDefaultAAConSettings(
+ AlignAnalysisUIText aaui, ServiceWithParameters service)
+ {
+ if (service != null)
+ {
+ // if (!service.getServiceType()
+ // .equals(compbio.ws.client.Services.AAConWS.toString()))
+ // {
- // Cache.log.warn(
++ // Console.warn(
+ // "Ignoring invalid preferred service for AACon calculations (service
+ // type was "
+ // + service.getServiceType() + ")");
+ // service = null;
+ // }
+ // else
+ {
+ // check service is actually in the list of currently avaialable
+ // services
+ if (!PreferredServiceRegistry.getRegistry().contains(service))
+ {
+ // it isn't ..
+ service = null;
+ }
+ }
+ }
+ if (service == null)
+ {
+ // get the default service for AACon
+ service = PreferredServiceRegistry.getRegistry().getPreferredServiceFor(null,
+ aaui.getServiceType());
+ }
+ if (service == null)
+ {
+ // TODO raise dialog box explaining error, and/or open the JABA
+ // preferences menu.
+ throw new Error(
+ MessageManager.getString("error.no_aacon_service_found"));
+ }
+ return service instanceof Jws2Instance
+ ? new AAConSettings(true, service, null, null)
+ : new AutoCalcSetting(service, null, null, true);
+ }
+
+ private static void removeCurrentAAConWorkerFor(AlignAnalysisUIText aaui,
+ AlignFrame alignFrame)
+ {
+ alignFrame.getViewport().getCalcManager()
+ .removeWorkersOfClass(aaui.getClient());
+ }
- }
++}
package jalview.ws.jws2;
import jalview.bin.Cache;
+ import jalview.bin.Console;
+import jalview.bin.ApplicationSingletonProvider;
+import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
import jalview.gui.AlignFrame;
-import jalview.gui.Desktop;
-import jalview.gui.JvSwingUtils;
import jalview.util.MessageManager;
-import jalview.ws.WSMenuEntryProviderI;
+import jalview.ws.ServiceChangeListener;
+import jalview.ws.WSDiscovererI;
+import jalview.ws.api.ServiceWithParameters;
import jalview.ws.jws2.jabaws2.Jws2Instance;
import jalview.ws.params.ParamDatastoreI;
-import java.awt.Color;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
+import java.util.Collections;
import java.util.HashSet;
-import java.util.Hashtable;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArraySet;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.FutureTask;
import javax.swing.JMenu;
-import javax.swing.JMenuItem;
import compbio.ws.client.Services;
* @author JimP
*
*/
-public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
+public class Jws2Discoverer implements WSDiscovererI, Runnable, ApplicationSingletonI
{
-
+ /**
+ * Returns the singleton instance of this class.
+ *
+ * @return
+ */
+ public static Jws2Discoverer getInstance()
+ {
+ return (Jws2Discoverer) ApplicationSingletonProvider
+ .getInstance(Jws2Discoverer.class);
+ }
-
public static final String COMPBIO_JABAWS = "http://www.compbio.dundee.ac.uk/jabaws";
/*
private final static String JWS2HOSTURLS = "JWS2HOSTURLS";
/*
- * Singleton instance
- */
- private static Jws2Discoverer discoverer;
-
- /*
* Override for testing only
*/
- private static List<String> testUrls = null;
+ private List<String> testUrls = null;
// preferred url has precedence over others
private String preferredUrl;
+
- private PropertyChangeSupport changeSupport = new PropertyChangeSupport(
- this);
+
+ private Set<ServiceChangeListener> serviceListeners = new CopyOnWriteArraySet<>();
+
private Vector<String> invalidServiceUrls = null;
private Vector<String> urlsWithoutServices = null;
private volatile boolean running = false;
private volatile boolean aborted = false;
+
- private Thread oldthread = null;
+
+ private volatile Thread oldthread = null;
/**
* holds list of services.
{
}
-
- /**
- * change listeners are notified of "services" property changes
- *
- * @param listener
- * to be added that consumes new services Hashtable object.
- */
- public void addPropertyChangeListener(
- java.beans.PropertyChangeListener listener)
+ @Override
+ public void addServiceChangeListener(ServiceChangeListener listener)
{
- changeSupport.addPropertyChangeListener(listener);
+ serviceListeners.add(listener);
}
- /**
- *
- *
- * @param listener
- * to be removed
- */
- public void removePropertyChangeListener(
- java.beans.PropertyChangeListener listener)
+ @Override
+ public void removeServiceChangeListener(ServiceChangeListener listener)
+ {
+ serviceListeners.remove(listener);
+ }
+
+ private void notifyServiceListeners(List<? extends ServiceWithParameters> services)
{
- changeSupport.removePropertyChangeListener(listener);
+ if (services == null) services = this.services;
+ for (var listener : serviceListeners) {
+ listener.servicesChanged(this, services);
+ }
}
/**
{
try
{
- Cache.log.debug(
+ Console.debug(
"Waiting around for old discovery thread to finish.");
// wait around until old discoverer dies
Thread.sleep(100);
}
}
aborted = false;
- Cache.log.debug("Old discovery thread has finished.");
+ Console.debug("Old discovery thread has finished.");
}
running = true;
ignoredServices.add(ignored);
}
- changeSupport.firePropertyChange("services", services,
- new Vector<Jws2Instance>());
+ notifyServiceListeners(Collections.emptyList());
oldthread = Thread.currentThread();
try
{
- Class foo = getClass().getClassLoader()
- .loadClass("compbio.ws.client.Jws2Client");
+ getClass().getClassLoader().loadClass("compbio.ws.client.Jws2Client");
} catch (ClassNotFoundException e)
{
System.err.println(
}
if (aborted)
{
- Cache.log.debug(
+ Console.debug(
"Aborting " + qrys.size() + " JABAWS discovery threads.");
for (JabaWsServerQuery squery : qrys)
{
for (Jws2Instance svc : services)
{
svcs[ipos] = svc;
- spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
- + svctypes.indexOf(svc.serviceType);
+ spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHostURL()) + 1
+ + svctypes.indexOf(svc.getName());
}
jalview.util.QuickSort.sort(spos, svcs);
services = new Vector<>();
for (Jws2Instance svc : svcs)
{
- if (!ignoredServices.contains(svc.serviceType))
+ if (!ignoredServices.contains(svc.getName()))
{
services.add(svc);
}
}
oldthread = null;
running = false;
- changeSupport.firePropertyChange("services", new Vector<Jws2Instance>(),
- services);
+ notifyServiceListeners(services);
}
/**
}
/**
- * attach all available web services to the appropriate submenu in the given
- * JMenu
- */
- @Override
- public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
- {
- // dynamically regenerate service list.
- populateWSMenuEntry(wsmenu, alignFrame, null);
- }
-
- private boolean isRecalculable(String action)
- {
- return (action != null && action.equalsIgnoreCase("conservation"));
- }
-
- private void populateWSMenuEntry(JMenu jws2al,
- final AlignFrame alignFrame, String typeFilter)
- {
- if (running || services == null || services.size() == 0)
- {
- return;
- }
-
- /**
- * eventually, JWS2 services will appear under the same align/etc submenus.
- * for moment we keep them separate.
- */
- JMenu atpoint;
- List<Jws2Instance> enumerableServices = new ArrayList<>();
- // jws2al.removeAll();
- Map<String, Jws2Instance> preferredHosts = new HashMap<>();
- Map<String, List<Jws2Instance>> alternates = new HashMap<>();
- for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
- {
- if (!isRecalculable(service.action))
- {
- // add 'one shot' services to be displayed using the classic menu
- // structure
- enumerableServices.add(service);
- }
- else
- {
- if (!preferredHosts.containsKey(service.serviceType))
- {
- Jws2Instance preferredInstance = getPreferredServiceFor(
- alignFrame, service.serviceType);
- if (preferredInstance != null)
- {
- preferredHosts.put(service.serviceType, preferredInstance);
- }
- else
- {
- preferredHosts.put(service.serviceType, service);
- }
- }
- List<Jws2Instance> ph = alternates.get(service.serviceType);
- if (preferredHosts.get(service.serviceType) != service)
- {
- if (ph == null)
- {
- ph = new ArrayList<>();
- }
- ph.add(service);
- alternates.put(service.serviceType, ph);
- }
- }
-
- }
-
- // create GUI element for classic services
- addEnumeratedServices(jws2al, alignFrame, enumerableServices);
- // and the instantaneous services
- for (final Jws2Instance service : preferredHosts.values())
- {
- atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
- JMenuItem hitm;
- if (atpoint.getItemCount() > 1)
- {
- // previous service of this type already present
- atpoint.addSeparator();
- }
- atpoint.add(hitm = new JMenuItem(service.getHost()));
- hitm.setForeground(Color.blue);
- hitm.addActionListener(new ActionListener()
- {
-
- @Override
- public void actionPerformed(ActionEvent e)
- {
- Desktop.showUrl(service.getHost());
- }
- });
- hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
- MessageManager.getString("label.open_jabaws_web_page")));
-
- service.attachWSMenuEntry(atpoint, alignFrame);
- if (alternates.containsKey(service.serviceType))
- {
- atpoint.add(hitm = new JMenu(
- MessageManager.getString("label.switch_server")));
- hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
- MessageManager.getString("label.choose_jabaws_server")));
- for (final Jws2Instance sv : alternates.get(service.serviceType))
- {
- JMenuItem itm;
- hitm.add(itm = new JMenuItem(sv.getHost()));
- itm.setForeground(Color.blue);
- itm.addActionListener(new ActionListener()
- {
-
- @Override
- public void actionPerformed(ActionEvent arg0)
- {
- new Thread(new Runnable()
- {
- @Override
- public void run()
- {
- setPreferredServiceFor(alignFrame, sv.serviceType,
- sv.action, sv);
- changeSupport.firePropertyChange("services",
- new Vector<Jws2Instance>(), services);
- }
- }).start();
-
- }
- });
- }
- }
- }
- }
-
- /**
- * add services using the Java 2.5/2.6/2.7 system which optionally creates
- * submenus to index by host and service program type
- */
- private void addEnumeratedServices(final JMenu jws2al,
- final AlignFrame alignFrame,
- List<Jws2Instance> enumerableServices)
- {
- boolean byhost = Cache.getDefault("WSMENU_BYHOST", false),
- bytype = Cache.getDefault("WSMENU_BYTYPE", false);
- /**
- * eventually, JWS2 services will appear under the same align/etc submenus.
- * for moment we keep them separate.
- */
- JMenu atpoint;
-
- List<String> hostLabels = new ArrayList<>();
- Hashtable<String, String> lasthostFor = new Hashtable<>();
- Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<>();
- ArrayList<String> hostlist = new ArrayList<>();
- for (Jws2Instance service : enumerableServices)
- {
- ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
- if (hostservices == null)
- {
- hosts.put(service.getHost(), hostservices = new ArrayList<>());
- hostlist.add(service.getHost());
- }
- hostservices.add(service);
- }
- // now add hosts in order of the given array
- for (String host : hostlist)
- {
- Jws2Instance orderedsvcs[] = hosts.get(host)
- .toArray(new Jws2Instance[1]);
- String sortbytype[] = new String[orderedsvcs.length];
- for (int i = 0; i < sortbytype.length; i++)
- {
- sortbytype[i] = orderedsvcs[i].serviceType;
- }
- jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
- for (final Jws2Instance service : orderedsvcs)
- {
- atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
- String type = service.serviceType;
- if (byhost)
- {
- atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
- if (atpoint.getToolTipText() == null)
- {
- atpoint.setToolTipText(MessageManager
- .formatMessage("label.services_at", new String[]
- { host }));
- }
- }
- if (bytype)
- {
- atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
- if (atpoint.getToolTipText() == null)
- {
- atpoint.setToolTipText(service.getActionText());
- }
- }
- if (!byhost && !hostLabels.contains(
- host + service.serviceType + service.getActionText()))
- // !hostLabels.contains(host + (bytype ?
- // service.serviceType+service.getActionText() : "")))
- {
- // add a marker indicating where this service is hosted
- // relies on services from the same host being listed in a
- // contiguous
- // group
- JMenuItem hitm;
- if (hostLabels.contains(host))
- {
- atpoint.addSeparator();
- }
- else
- {
- hostLabels.add(host);
- }
- if (lasthostFor.get(service.action) == null
- || !lasthostFor.get(service.action).equals(host))
- {
- atpoint.add(hitm = new JMenuItem(host));
- hitm.setForeground(Color.blue);
- hitm.addActionListener(new ActionListener()
- {
-
- @Override
- public void actionPerformed(ActionEvent e)
- {
- Desktop.showUrl(service.getHost());
- }
- });
- hitm.setToolTipText(
- JvSwingUtils.wrapTooltip(true, MessageManager
- .getString("label.open_jabaws_web_page")));
- lasthostFor.put(service.action, host);
- }
- hostLabels.add(
- host + service.serviceType + service.getActionText());
- }
-
- service.attachWSMenuEntry(atpoint, alignFrame);
- }
- }
- }
-
- /**
*
* @param args
* @j2sIgnore
*/
public static void main(String[] args)
{
+ Jws2Discoverer instance = getInstance();
if (args.length > 0)
{
- testUrls = new ArrayList<>();
+ instance.testUrls = new ArrayList<>();
for (String url : args)
{
- testUrls.add(url);
+ instance.testUrls.add(url);
}
}
- Thread runner = getDiscoverer()
- .startDiscoverer(new PropertyChangeListener()
- {
-
- @Override
- public void propertyChange(PropertyChangeEvent evt)
- {
- if (getDiscoverer().services != null)
- {
- System.out.println("Changesupport: There are now "
- + getDiscoverer().services.size() + " services");
- int i = 1;
- for (Jws2Instance instance : getDiscoverer().services)
- {
- System.out.println("Service " + i++ + " "
- + instance.getClass() + "@" + instance.getHost()
- + ": " + instance.getActionText());
- }
-
- }
- }
- });
- while (runner.isAlive())
- {
- try
- {
- Thread.sleep(50);
- } catch (InterruptedException e)
+ var discoverer = getInstance();
+ discoverer.addServiceChangeListener((_discoverer, _services) -> {
+ if (discoverer.services != null)
{
+ System.out.println("Changesupport: There are now "
+ + discoverer.services.size() + " services");
+ int i = 1;
+ for (ServiceWithParameters s_instance : discoverer.services)
+ {
+ System.out.println(
+ "Service " + i++ + " " + s_instance.getClass()
+ + "@" + s_instance.getHostURL() + ": "
+ + s_instance.getActionText());
+ }
+
}
+ });
+ try
+ {
+ discoverer.startDiscoverer().get();
+ } catch (InterruptedException | ExecutionException e)
+ {
}
try
{
}
}
- /**
- * Returns the singleton instance of this class.
- *
- * @return
- */
- public static Jws2Discoverer getDiscoverer()
- {
- if (discoverer == null)
- {
- discoverer = new Jws2Discoverer();
- }
- return discoverer;
- }
+ @Override
public boolean hasServices()
{
return !running && services != null && services.size() > 0;
}
+ @Override
public boolean isRunning()
{
return running;
}
+ @Override
public void setServiceUrls(List<String> wsUrls)
{
if (wsUrls != null && !wsUrls.isEmpty())
*
* @return
*/
+ @Override
public List<String> getServiceUrls()
{
if (testUrls != null)
}
else
{
- Cache.log.warn("Ignoring duplicate url " + url + " in "
+ Console.warn("Ignoring duplicate url " + url + " in "
+ JWS2HOSTURLS + " list");
}
} catch (MalformedURLException ex)
{
- Cache.log.warn("Problem whilst trying to make a URL from '"
+ Console.warn("Problem whilst trying to make a URL from '"
+ ((url != null) ? url : "<null>") + "'");
- Cache.log.warn(
+ Console.warn(
"This was probably due to a malformed comma separated list"
+ " in the " + JWS2HOSTURLS
+ " entry of $(HOME)/.jalview_properties)");
- Cache.log.debug("Exception was ", ex);
+ Console.debug("Exception was ", ex);
}
}
} catch (Exception ex)
{
- Cache.log.warn("Error parsing comma separated list of urls in "
+ Console.warn("Error parsing comma separated list of urls in "
+ JWS2HOSTURLS + " preference.", ex);
}
return urls;
}
- public Vector<Jws2Instance> getServices()
+ @Override
+ public Vector<ServiceWithParameters> getServices()
{
return (services == null) ? new Vector<>() : new Vector<>(services);
}
* @param foo
* @return
*/
- public static boolean testServiceUrl(URL foo)
+ @Override
+ public boolean testServiceUrl(URL foo)
{
try
{
* @param changeSupport2
* @return new thread
*/
- public Thread startDiscoverer(PropertyChangeListener changeSupport2)
+ @Override
+ public CompletableFuture<WSDiscovererI> startDiscoverer()
{
/* if (restart())
{
{
setAborted(true);
}
- addPropertyChangeListener(changeSupport2);
- Thread thr = new Thread(this);
- thr.start();
- return thr;
+ CompletableFuture<WSDiscovererI> task = CompletableFuture
+ .supplyAsync(() -> {
+ run();
+ return Jws2Discoverer.this;
+ });
+ return task;
}
/**
* @return a human readable report of any problems with the service URLs used
* for discovery
*/
+ @Override
public String getErrorMessages()
{
if (!isRunning() && !isAborted())
return null;
}
+ @Override
public int getServerStatusFor(String url)
{
if (validServiceUrls != null && validServiceUrls.contains(url))
{
- return 1;
+ return STATUS_OK;
}
if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
{
- return 0;
+ return STATUS_NO_SERVICES;
}
if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
{
- return -1;
+ return STATUS_INVALID;
}
- return -2;
- }
-
- /**
- * pick the user's preferred service based on a set of URLs (jaba server
- * locations) and service URIs (specifying version and service interface
- * class)
- *
- * @param serviceURL
- * @return null or best match for given uri/ls.
- */
- public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
- {
- HashSet<String> urls = new HashSet<>();
- urls.addAll(Arrays.asList(serviceURLs));
- Jws2Instance match = null;
- if (services != null)
- {
- for (Jws2Instance svc : services)
- {
- if (urls.contains(svc.getServiceTypeURI()))
- {
- if (match == null)
- {
- // for moment we always pick service from server ordered first in
- // user's preferences
- match = svc;
- }
- if (urls.contains(svc.getUri()))
- {
- // stop and return - we've matched type URI and URI for service
- // endpoint
- return svc;
- }
- }
- }
- }
- return match;
- }
-
- Map<String, Map<String, String>> preferredServiceMap = new HashMap<>();
-
- /**
- * get current preferred service of the given type, or global default
- *
- * @param af
- * null or a specific alignFrame
- * @param serviceType
- * Jws2Instance.serviceType for service
- * @return null if no service of this type is available, the preferred service
- * for the serviceType and af if specified and if defined.
- */
- public Jws2Instance getPreferredServiceFor(AlignFrame af,
- String serviceType)
- {
- String serviceurl = null;
- synchronized (preferredServiceMap)
- {
- String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
- Map<String, String> prefmap = preferredServiceMap.get(afid);
- if (afid.length() > 0 && prefmap == null)
- {
- // recover global setting, if any
- prefmap = preferredServiceMap.get("");
- }
- if (prefmap != null)
- {
- serviceurl = prefmap.get(serviceType);
- }
-
- }
- Jws2Instance response = null;
- for (Jws2Instance svc : services)
- {
- if (svc.serviceType.equals(serviceType))
- {
- if (serviceurl == null || serviceurl.equals(svc.getHost()))
- {
- response = svc;
- break;
- }
- }
- }
- return response;
- }
-
- public void setPreferredServiceFor(AlignFrame af, String serviceType,
- String serviceAction, Jws2Instance selectedServer)
- {
- String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
- if (preferredServiceMap == null)
- {
- preferredServiceMap = new HashMap<>();
- }
- Map<String, String> prefmap = preferredServiceMap.get(afid);
- if (prefmap == null)
- {
- prefmap = new HashMap<>();
- preferredServiceMap.put(afid, prefmap);
- }
- prefmap.put(serviceType, selectedServer.getHost());
- prefmap.put(serviceAction, selectedServer.getHost());
- }
-
- public void setPreferredServiceFor(String serviceType,
- String serviceAction, Jws2Instance selectedServer)
- {
- setPreferredServiceFor(null, serviceType, serviceAction,
- selectedServer);
+ return STATUS_UNKNOWN;
}
/**
*/
package jalview.ws.jws2;
-import java.util.Locale;
+import jalview.datamodel.AlignmentI;
+import jalview.datamodel.AlignmentView;
+import jalview.gui.AlignFrame;
+import jalview.gui.Desktop;
+import jalview.gui.JvOptionPane;
+import jalview.gui.JvSwingUtils;
+import jalview.util.MessageManager;
+import jalview.ws.WSMenuEntryProviderI;
+import jalview.ws.api.JalviewServiceEndpointProviderI;
+import jalview.ws.api.MultipleSequenceAlignmentI;
+import jalview.ws.api.ServiceWithParameters;
+import jalview.ws.gui.MsaWSThread;
+import jalview.ws.params.ArgumentI;
+import jalview.ws.params.WsParamSetI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
+import java.util.Locale;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.ToolTipManager;
-import compbio.data.msa.MsaWS;
-import compbio.metadata.Argument;
-import jalview.datamodel.AlignmentI;
-import jalview.datamodel.AlignmentView;
-import jalview.gui.AlignFrame;
-import jalview.gui.Desktop;
-import jalview.gui.JvOptionPane;
-import jalview.gui.JvSwingUtils;
-import jalview.util.MessageManager;
-import jalview.ws.jws2.jabaws2.Jws2Instance;
-import jalview.ws.params.WsParamSetI;
/**
- * DOCUMENT ME!
+ * MsaWSClient
*
- * @author $author$
+ * Instantiates web service menu items for multiple alignment services, and
+ * holds logic for constructing a web service thread.
+ *
+ * TODO remove dependency on Jws2Client methods for creating AACon service UI
+ * elements.
+ *
+ * @author Jim Procter et al
* @version $Revision$
*/
-public class MsaWSClient extends Jws2Client
+public class MsaWSClient extends Jws2Client implements WSMenuEntryProviderI
{
/**
- * server is a WSDL2Java generated stub for an archetypal MsaWSI service.
+ * server is a proxy class implementing the core methods for submitting,
+ * monitoring and retrieving results from a multiple sequence alignment
+ * service
*/
- MsaWS server;
+ MultipleSequenceAlignmentI server;
- public MsaWSClient(Jws2Instance sh, String altitle,
+ public MsaWSClient(ServiceWithParameters sh, String altitle,
jalview.datamodel.AlignmentView msa, boolean submitGaps,
boolean preserveOrder, AlignmentI seqdataset,
AlignFrame _alignFrame)
// TODO Auto-generated constructor stub
}
- public MsaWSClient(Jws2Instance sh, WsParamSetI preset, String altitle,
+ public MsaWSClient(ServiceWithParameters sh, WsParamSetI preset,
+ String altitle,
jalview.datamodel.AlignmentView msa, boolean submitGaps,
boolean preserveOrder, AlignmentI seqdataset,
AlignFrame _alignFrame)
* DOCUMENT ME!
*/
- public MsaWSClient(Jws2Instance sh, WsParamSetI preset,
- List<Argument> arguments, boolean editParams, String altitle,
+ public MsaWSClient(ServiceWithParameters sh, WsParamSetI preset,
+ List<ArgumentI> arguments, boolean editParams, String altitle,
jalview.datamodel.AlignmentView msa, boolean submitGaps,
boolean preserveOrder, AlignmentI seqdataset,
AlignFrame _alignFrame)
{
super(_alignFrame, preset, arguments);
- if (!processParams(sh, editParams))
- {
- return;
- }
-
- if (!(sh.service instanceof MsaWS))
- {
- // redundant at mo - but may change
- JvOptionPane.showMessageDialog(Desktop.desktop,
- MessageManager.formatMessage(
- "label.service_called_is_not_msa_service",
- new String[]
- { sh.serviceType }),
- MessageManager.getString("label.internal_jalview_error"),
- JvOptionPane.WARNING_MESSAGE);
-
- return;
- }
- server = (MsaWS) sh.service;
- if ((wsInfo = setWebService(sh, false)) == null)
- {
- JvOptionPane.showMessageDialog(Desktop.desktop, MessageManager
- .formatMessage("label.msa_service_is_unknown", new String[]
- { sh.serviceType }),
- MessageManager.getString("label.internal_jalview_error"),
- JvOptionPane.WARNING_MESSAGE);
-
- return;
- }
-
- startMsaWSClient(altitle, msa, submitGaps, preserveOrder, seqdataset);
+ processParams(sh, editParams).thenAccept((startJob) -> {
+ if (!startJob)
+ return;
+
+ if (!(sh instanceof JalviewServiceEndpointProviderI
+ && ((JalviewServiceEndpointProviderI) sh)
+ .getEndpoint() instanceof MultipleSequenceAlignmentI))
+ {
+ // redundant at mo - but may change
+ JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
+ MessageManager.formatMessage(
+ "label.service_called_is_not_msa_service",
+ new String[]
+ { sh.getName() }),
+ MessageManager.getString("label.internal_jalview_error"),
+ JvOptionPane.WARNING_MESSAGE);
+
+ return;
+ }
+ serviceHandle = sh;
+ server = (MultipleSequenceAlignmentI) ((JalviewServiceEndpointProviderI) sh)
+ .getEndpoint();
+ if ((wsInfo = setWebService(sh, false)) == null)
+ {
+ JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), MessageManager
+ .formatMessage("label.msa_service_is_unknown", new String[]
+ { sh.getName() }),
+ MessageManager.getString("label.internal_jalview_error"),
+ JvOptionPane.WARNING_MESSAGE);
+
+ return;
+ }
+
+ startMsaWSClient(altitle, msa, submitGaps, preserveOrder, seqdataset);
+ });
}
@Override
public void attachWSMenuEntry(JMenu rmsawsmenu,
- final Jws2Instance service, final AlignFrame alignFrame)
- final Jws2Instance service, final AlignFrame af)
++ final ServiceWithParameters service, final AlignFrame alignFrame)
{
- if (registerAAConWSInstance(rmsawsmenu, service, alignFrame))
- if (registerAAConWSInstance(rmsawsmenu, service, af))
++ if (Jws2ClientFactory.registerAAConWSInstance(rmsawsmenu,
++ service, alignFrame))
{
-- // Alignment dependent analysis calculation WS gui
++ // Alignment dependent analysis calculation WS gui
return;
}
+ serviceHandle = service;
setWebService(service, true); // headless
+ attachWSMenuEntry(rmsawsmenu, alignFrame);
+ }
+
+ @Override
+ public void attachWSMenuEntry(JMenu wsmenu, AlignFrame alignFrame)
+ {
boolean finished = true, submitGaps = false;
- JMenu msawsmenu = rmsawsmenu;
+ /**
+ * temp variables holding msa service submenu or root service menu
+ */
+ JMenu msawsmenu = wsmenu;
+ JMenu rmsawsmenu = wsmenu;
String svcname = WebServiceName;
if (svcname.endsWith("WS"))
{
rmsawsmenu.add(msawsmenu);
calcName = "";
}
- boolean hasparams = service.hasParameters();
+ boolean hasparams = serviceHandle.hasParameters();
+ ServiceWithParameters service = (ServiceWithParameters) serviceHandle;
do
{
String action = "Align ";
@Override
public void actionPerformed(ActionEvent e)
{
- AlignmentView msa = af.gatherSequencesForAlignment();
+ AlignmentView msa = alignFrame.gatherSequencesForAlignment();
if (msa != null)
{
- new MsaWSClient(service, af.getTitle(), msa, withGaps, true,
- af.getViewport().getAlignment().getDataset(), af);
+ new MsaWSClient(service, alignFrame.getTitle(), msa, withGaps,
+ true,
+ alignFrame.getViewport().getAlignment().getDataset(),
+ alignFrame);
}
}
@Override
public void actionPerformed(ActionEvent e)
{
- AlignmentView msa = af.gatherSequencesForAlignment();
+ AlignmentView msa = alignFrame.gatherSequencesForAlignment();
if (msa != null)
{
- startJob(service, af, withGaps, msa);
+ new MsaWSClient(service, null, null, true,
+ alignFrame.getTitle(), msa, withGaps, true,
+ alignFrame.getViewport().getAlignment().getDataset(),
+ alignFrame);
}
}
final int showToolTipFor = ToolTipManager.sharedInstance()
.getDismissDelay();
- for (final WsParamSetI preSet : presets)
+ for (final WsParamSetI preset : presets)
{
- final JMenuItem methodR = new JMenuItem(preSet.getName());
+ final JMenuItem methodR = new JMenuItem(preset.getName());
final int QUICK_TOOLTIP = 1500;
// JAL-1582 shorten tooltip display time in these menu items as
// they can obscure other options
});
String tooltip = JvSwingUtils.wrapTooltip(true, "<strong>"
- + (preSet.isModifiable()
+ + (preset.isModifiable()
? MessageManager.getString("label.user_preset")
: MessageManager
.getString("label.service_preset"))
- + "</strong><br/>" + preSet.getDescription());
+ + "</strong><br/>" + preset.getDescription());
methodR.setToolTipText(tooltip);
methodR.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
- AlignmentView msa = af.gatherSequencesForAlignment();
+ AlignmentView msa = alignFrame
+ .gatherSequencesForAlignment();
if (msa != null)
{
- MsaWSClient msac = new MsaWSClient(service, preSet,
- af.getTitle(), msa, false, true,
- af.getViewport().getAlignment().getDataset(), af);
+ MsaWSClient msac = new MsaWSClient(service, preset,
+ alignFrame.getTitle(), msa, false, true,
+ alignFrame.getViewport().getAlignment()
+ .getDataset(),
+ alignFrame);
}
}
}
} while (!finished);
}
-
- protected void startJob(final Jws2Instance service, final AlignFrame af,
- final boolean withGaps, AlignmentView msa)
- {
- try
- {
- new MsaWSClient(service, null, null, true, af.getTitle(), msa,
- withGaps, true, af.getViewport().getAlignment().getDataset(),
- af);
- } catch (Exception e)
- {
- JvOptionPane.showMessageDialog(alignFrame, e.getMessage(),
- MessageManager.getString("label.state_job_error"),
- JvOptionPane.WARNING_MESSAGE);
-
- }
- }
}
--- /dev/null
+/*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
+package jalview.ws.jws2;
+
+import jalview.analysis.AlignSeq;
+import jalview.analysis.AlignmentAnnotationUtils;
+import jalview.analysis.SeqsetUtils;
+import jalview.api.AlignViewportI;
+import jalview.api.AlignmentViewPanel;
+import jalview.api.FeatureColourI;
+import jalview.api.PollableAlignCalcWorkerI;
+import jalview.bin.Cache;
++import jalview.bin.Console;
+import jalview.datamodel.AlignmentAnnotation;
+import jalview.datamodel.AlignmentI;
+import jalview.datamodel.AnnotatedCollectionI;
+import jalview.datamodel.Annotation;
+import jalview.datamodel.ContiguousI;
+import jalview.datamodel.Mapping;
+import jalview.datamodel.SequenceI;
+import jalview.datamodel.features.FeatureMatcherSetI;
+import jalview.gui.AlignFrame;
+import jalview.gui.Desktop;
+import jalview.gui.IProgressIndicator;
+import jalview.gui.IProgressIndicatorHandler;
+import jalview.gui.JvOptionPane;
+import jalview.gui.WebserviceInfo;
+import jalview.schemes.FeatureSettingsAdapter;
+import jalview.schemes.ResidueProperties;
+import jalview.util.MapList;
+import jalview.util.MessageManager;
+import jalview.workers.AlignCalcWorker;
+import jalview.ws.JobStateSummary;
+import jalview.ws.api.CancellableI;
+import jalview.ws.api.JalviewServiceEndpointProviderI;
+import jalview.ws.api.JobId;
+import jalview.ws.api.SequenceAnnotationServiceI;
+import jalview.ws.api.ServiceWithParameters;
+import jalview.ws.api.WSAnnotationCalcManagerI;
+import jalview.ws.gui.AnnotationWsJob;
+import jalview.ws.jws2.dm.AAConSettings;
+import jalview.ws.params.ArgumentI;
+import jalview.ws.params.WsParamSetI;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class SeqAnnotationServiceCalcWorker extends AlignCalcWorker
+ implements WSAnnotationCalcManagerI, PollableAlignCalcWorkerI
+{
+
+ protected ServiceWithParameters service;
+
+ protected WsParamSetI preset;
+
+ protected List<ArgumentI> arguments;
+
+ protected IProgressIndicator guiProgress;
+
+ protected boolean submitGaps = true;
+
+ /**
+ * by default, we filter out non-standard residues before submission
+ */
+ protected boolean filterNonStandardResidues = true;
+
+ /**
+ * Recover any existing parameters for this service
+ */
+ protected void initViewportParams()
+ {
+ if (getCalcId() != null)
+ {
+ ((jalview.gui.AlignViewport) alignViewport).setCalcIdSettingsFor(
+ getCalcId(),
+ new AAConSettings(true, service, this.preset, arguments),
+ true);
+ }
+ }
+
+ /**
+ *
+ * @return null or a string used to recover all annotation generated by this
+ * worker
+ */
+ public String getCalcId()
+ {
+ return service.getAlignAnalysisUI() == null ? null
+ : service.getAlignAnalysisUI().getCalcId();
+ }
+
+ public WsParamSetI getPreset()
+ {
+ return preset;
+ }
+
+ public List<ArgumentI> getArguments()
+ {
+ return arguments;
+ }
+
+ /**
+ * reconfigure and restart the AAConClient. This method will spawn a new
+ * thread that will wait until any current jobs are finished, modify the
+ * parameters and restart the conservation calculation with the new values.
+ *
+ * @param newpreset
+ * @param newarguments
+ */
+ public void updateParameters(final WsParamSetI newpreset,
+ final List<ArgumentI> newarguments)
+ {
+ preset = newpreset;
+ arguments = newarguments;
+ calcMan.startWorker(this);
+ initViewportParams();
+ }
+ protected boolean alignedSeqs = true;
+
+ protected boolean nucleotidesAllowed = false;
+
+ protected boolean proteinAllowed = false;
+
+ /**
+ * record sequences for mapping result back to afterwards
+ */
+ protected boolean bySequence = false;
+
+ protected Map<String, SequenceI> seqNames;
+
+ // TODO: convert to bitset
+ protected boolean[] gapMap;
+
+ int realw;
+
+ protected int start;
+
+ int end;
+
+ private AlignFrame alignFrame;
+
+ public boolean[] getGapMap()
+ {
+ return gapMap;
+ }
+
+ public SeqAnnotationServiceCalcWorker(ServiceWithParameters service,
+ AlignFrame alignFrame,
+ WsParamSetI preset, List<ArgumentI> paramset)
+ {
+ super(alignFrame.getCurrentView(), alignFrame.alignPanel);
+ // TODO: both these fields needed ?
+ this.alignFrame = alignFrame;
+ this.guiProgress = alignFrame;
+ this.preset = preset;
+ this.arguments = paramset;
+ this.service = service;
+ try
+ {
+ annotService = (jalview.ws.api.SequenceAnnotationServiceI) ((JalviewServiceEndpointProviderI) service)
+ .getEndpoint();
+ } catch (ClassCastException cce)
+ {
+ annotService = null;
+ JvOptionPane.showMessageDialog(Desktop.getInstance(),
+ MessageManager.formatMessage(
+ "label.service_called_is_not_an_annotation_service",
+ new String[]
+ { service.getName() }),
+ MessageManager.getString("label.internal_jalview_error"),
+ JvOptionPane.WARNING_MESSAGE);
+
+ }
+ cancellable = CancellableI.class.isInstance(annotService);
+ // configure submission flags
+ proteinAllowed = service.isProteinService();
+ nucleotidesAllowed = service.isNucleotideService();
+ alignedSeqs = service.isNeedsAlignedSequences();
+ bySequence = !service.isAlignmentAnalysis();
+ filterNonStandardResidues = service.isFilterSymbols();
+ min_valid_seqs = service.getMinimumInputSequences();
+ submitGaps = service.isAlignmentAnalysis();
+
+ if (service.isInteractiveUpdate())
+ {
+ initViewportParams();
+ }
+ }
+
+ /**
+ *
+ * @return true if the submission thread should attempt to submit data
+ */
+ public boolean hasService()
+ {
+ return annotService != null;
+ }
+
+ protected SequenceAnnotationServiceI annotService;
+ protected final boolean cancellable;
+
+ volatile JobId rslt = null;
+
+ AnnotationWsJob running = null;
+
+ private int min_valid_seqs;
+
+
+ private long progressId = -1;
+ JobStateSummary job = null;
+ WebserviceInfo info = null;
+ List<SequenceI> seqs = null;
+
+ @Override public void startUp() throws Throwable
+ {
+ if (alignViewport.isClosed())
+ {
+ abortAndDestroy();
+ return;
+ }
+ if (!hasService())
+ {
+ return;
+ }
+
+ StringBuffer msg = new StringBuffer();
+ job = new JobStateSummary();
+ info = new WebserviceInfo("foo", "bar", false);
+
+ seqs = getInputSequences(
+ alignViewport.getAlignment(),
+ bySequence ? alignViewport.getSelectionGroup() : null);
+
+ if (seqs == null || !checkValidInputSeqs(seqs))
+ {
- jalview.bin.Cache.log.debug(
++ jalview.bin.Console.debug(
+ "Sequences for analysis service were null or not valid");
+ return;
+ }
+
+ if (guiProgress != null)
+ {
+ guiProgress.setProgressBar(service.getActionText(),
+ progressId = System.currentTimeMillis());
+ }
- jalview.bin.Cache.log.debug("submitted " + seqs.size()
++ jalview.bin.Console.debug("submitted " + seqs.size()
+ + " sequences to " + service.getActionText());
+
+ rslt = annotService.submitToService(seqs, getPreset(),
+ getArguments());
+ if (rslt == null)
+ {
+ return;
+ }
+ // TODO: handle job submission error reporting here.
- Cache.log.debug("Service " + service.getUri() + "\nSubmitted job ID: "
++ Console.debug("Service " + service.getUri() + "\nSubmitted job ID: "
+ + rslt);
+ // ///
+ // otherwise, construct WsJob and any UI handlers
+ running = new AnnotationWsJob();
+ running.setJobHandle(rslt);
+ running.setSeqNames(seqNames);
+ running.setStartPos(start);
+ running.setSeqs(seqs);
+ job.updateJobPanelState(info, "", running);
+ if (guiProgress != null)
+ {
+ guiProgress.registerHandler(progressId,
+ new IProgressIndicatorHandler()
+ {
+
+ @Override
+ public boolean cancelActivity(long id)
+ {
+ calcMan.cancelWorker(SeqAnnotationServiceCalcWorker.this);
+ return true;
+ }
+
+ @Override
+ public boolean canCancel()
+ {
+ return cancellable;
+ }
+ });
+ }
+ }
+
+ @Override public boolean poll() throws Throwable
+ {
+ boolean finished = false;
+
- Cache.log.debug("Updating status for annotation service.");
++ Console.debug("Updating status for annotation service.");
+ annotService.updateStatus(running);
+ job.updateJobPanelState(info, "", running);
+ if (running.isSubjobComplete())
+ {
- Cache.log.debug(
++ Console.debug(
+ "Finished polling analysis service job: status reported is "
+ + running.getState());
+ finished = true;
+ }
+ else
+ {
- Cache.log.debug("Status now " + running.getState());
++ Console.debug("Status now " + running.getState());
+ }
+
+ // pull any stats - some services need to flush log output before
+ // results are available
- Cache.log.debug("Updating progress log for annotation service.");
++ Console.debug("Updating progress log for annotation service.");
+
+ try
+ {
+ annotService.updateJobProgress(running);
+ } catch (Throwable thr)
+ {
- Cache.log.debug("Ignoring exception during progress update.",
++ Console.debug("Ignoring exception during progress update.",
+ thr);
+ }
- Cache.log.debug("Result of poll: " + running.getStatus());
++ Console.debug("Result of poll: " + running.getStatus());
+
+
+ if (finished)
+ {
- Cache.log.debug("Job poll loop exited. Job is " + running.getState());
++ Console.debug("Job poll loop exited. Job is " + running.getState());
+ if (running.isFinished())
+ {
+ // expect there to be results to collect
+ // configure job with the associated view's feature renderer, if one
+ // exists.
+ // TODO: here one would also grab the 'master feature renderer' in order
+ // to enable/disable
+ // features automatically according to user preferences
+ running.setFeatureRenderer(
+ ((jalview.gui.AlignmentPanel) ap).cloneFeatureRenderer());
- Cache.log.debug("retrieving job results.");
++ Console.debug("retrieving job results.");
+ final Map<String, FeatureColourI> featureColours = new HashMap<>();
+ final Map<String, FeatureMatcherSetI> featureFilters = new HashMap<>();
+ List<AlignmentAnnotation> returnedAnnot = annotService
+ .getAnnotationResult(running.getJobHandle(), seqs,
+ featureColours, featureFilters);
+
- Cache.log.debug("Obtained " + (returnedAnnot == null ? "no rows"
++ Console.debug("Obtained " + (returnedAnnot == null ? "no rows"
+ : ("" + returnedAnnot.size())));
- Cache.log.debug("There were " + featureColours.size()
++ Console.debug("There were " + featureColours.size()
+ + " feature colours and " + featureFilters.size()
+ + " filters defined.");
+
+ // TODO
+ // copy over each annotation row reurned and also defined on each
+ // sequence, excluding regions not annotated due to gapMap/column
+ // visibility
+
+ // update calcId if it is not already set on returned annotation
+ if (returnedAnnot != null)
+ {
+ for (AlignmentAnnotation aa : returnedAnnot)
+ {
+ // assume that any CalcIds already set
+ if (getCalcId() != null && aa.getCalcId() == null
+ || "".equals(aa.getCalcId()))
+ {
+ aa.setCalcId(getCalcId());
+ }
+ // autocalculated annotation are created by interactive alignment
+ // analysis services
+ aa.autoCalculated = service.isAlignmentAnalysis()
+ && service.isInteractiveUpdate();
+ }
+ }
+
+ running.setAnnotation(returnedAnnot);
+
+ if (running.hasResults())
+ {
- jalview.bin.Cache.log.debug("Updating result annotation from Job "
++ jalview.bin.Console.debug("Updating result annotation from Job "
+ + rslt + " at " + service.getUri());
+ updateResultAnnotation(true);
+ if (running.isTransferSequenceFeatures())
+ {
+ // TODO
+ // look at each sequence and lift over any features, excluding
+ // regions
+ // not annotated due to gapMap/column visibility
+
- jalview.bin.Cache.log.debug(
++ jalview.bin.Console.debug(
+ "Updating feature display settings and transferring features from Job "
+ + rslt + " at " + service.getUri());
+ // TODO: consider merge rather than apply here
+ alignViewport.applyFeaturesStyle(new FeatureSettingsAdapter()
+ {
+ @Override
+ public FeatureColourI getFeatureColour(String type)
+ {
+ return featureColours.get(type);
+ }
+
+ @Override
+ public FeatureMatcherSetI getFeatureFilters(String type)
+ {
+ return featureFilters.get(type);
+ }
+
+ @Override
+ public boolean isFeatureDisplayed(String type)
+ {
+ return featureColours.containsKey(type);
+ }
+
+ });
+ // TODO: JAL-1150 - create sequence feature settings API for
+ // defining
+ // styles and enabling/disabling feature overlay on alignment panel
+
+ if (alignFrame.alignPanel == ap)
+ {
+ alignViewport.setShowSequenceFeatures(true);
+ alignFrame.setMenusForViewport();
+ }
+ }
+ ap.adjustAnnotationHeight();
+ }
+ }
- Cache.log.debug("Annotation Service Worker thread finished.");
++ Console.debug("Annotation Service Worker thread finished.");
+
+ }
+
+ return finished;
+ }
+
+ @Override public void cancel()
+ {
+ cancelCurrentJob();
+ }
+
+ @Override public void done()
+ {
+ if (ap != null)
+ {
+ if (guiProgress != null && progressId != -1)
+ {
+ guiProgress.removeProgressBar(progressId);
+ }
+ // TODO: may not need to paintAlignment again !
+ ap.paintAlignment(false, false);
+ }
+ }
+
+ /**
+ * validate input for dynamic/non-dynamic update context TODO: move to
+ * analysis interface ?
+ * @param seqs
+ *
+ * @return true if input is valid
+ */
+ boolean checkValidInputSeqs(List<SequenceI> seqs)
+ {
+ int nvalid = 0;
+ for (SequenceI sq : seqs)
+ {
+ if (sq.getStart() <= sq.getEnd()
+ && (sq.isProtein() ? proteinAllowed : nucleotidesAllowed))
+ {
+ if (submitGaps
+ || sq.getLength() == (sq.getEnd() - sq.getStart() + 1))
+ {
+ nvalid++;
+ }
+ }
+ }
+ return nvalid >= min_valid_seqs;
+ }
+
+ public void cancelCurrentJob()
+ {
+ try
+ {
+ String id = running.getJobId();
+ if (cancellable && ((CancellableI) annotService).cancel(running))
+ {
+ System.err.println("Cancelled job " + id);
+ }
+ else
+ {
+ System.err.println("Job " + id + " couldn't be cancelled.");
+ }
+ } catch (Exception q)
+ {
+ q.printStackTrace();
+ }
+ }
+
+ /**
+ * Interactive updating. Analysis calculations that work on the currently
+ * displayed alignment data should cancel existing jobs when the input data
+ * has changed.
+ *
+ * @return true if a running job should be cancelled because new input data is
+ * available for analysis
+ */
+ boolean isInteractiveUpdate()
+ {
+ return service.isInteractiveUpdate();
+ }
+
+ /**
+ * decide what sequences will be analysed TODO: refactor to generate
+ * List<SequenceI> for submission to service interface
+ *
+ * @param alignment
+ * @param inputSeqs
+ * @return
+ */
+ public List<SequenceI> getInputSequences(AlignmentI alignment,
+ AnnotatedCollectionI inputSeqs)
+ {
+ if (alignment == null || alignment.getWidth() <= 0
+ || alignment.getSequences() == null || alignment.isNucleotide()
+ ? !nucleotidesAllowed
+ : !proteinAllowed)
+ {
+ return null;
+ }
+ if (inputSeqs == null || inputSeqs.getWidth() <= 0
+ || inputSeqs.getSequences() == null
+ || inputSeqs.getSequences().size() < 1)
+ {
+ inputSeqs = alignment;
+ }
+
+ List<SequenceI> seqs = new ArrayList<>();
+
+ int minlen = 10;
+ int ln = -1;
+ if (bySequence)
+ {
+ seqNames = new HashMap<>();
+ }
+ gapMap = new boolean[0];
+ start = inputSeqs.getStartRes();
+ end = inputSeqs.getEndRes();
+ // TODO: URGENT! unify with JPred / MSA code to handle hidden regions
+ // correctly
+ // TODO: push attributes into WsJob instance (so they can be safely
+ // persisted/restored
+ for (SequenceI sq : (inputSeqs.getSequences()))
+ {
+ if (bySequence
+ ? sq.findPosition(end + 1)
+ - sq.findPosition(start + 1) > minlen - 1
+ : sq.getEnd() - sq.getStart() > minlen - 1)
+ {
+ String newname = SeqsetUtils.unique_name(seqs.size() + 1);
+ // make new input sequence with or without gaps
+ if (seqNames != null)
+ {
+ seqNames.put(newname, sq);
+ }
+ SequenceI seq;
+ if (submitGaps)
+ {
+ seqs.add(seq = new jalview.datamodel.Sequence(newname,
+ sq.getSequenceAsString()));
+ if (gapMap == null || gapMap.length < seq.getLength())
+ {
+ boolean[] tg = gapMap;
+ gapMap = new boolean[seq.getLength()];
+ System.arraycopy(tg, 0, gapMap, 0, tg.length);
+ for (int p = tg.length; p < gapMap.length; p++)
+ {
+ gapMap[p] = false; // init as a gap
+ }
+ }
+ for (int apos : sq.gapMap())
+ {
+ char sqc = sq.getCharAt(apos);
+ if (!filterNonStandardResidues
+ || (sq.isProtein() ? ResidueProperties.aaIndex[sqc] < 20
+ : ResidueProperties.nucleotideIndex[sqc] < 5))
+ {
+ gapMap[apos] = true; // aligned and real amino acid residue
+ }
+ ;
+ }
+ }
+ else
+ {
+ // TODO: add ability to exclude hidden regions
+ seqs.add(seq = new jalview.datamodel.Sequence(newname,
+ AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
+ sq.getSequenceAsString(start, end + 1))));
+ // for annotation need to also record map to sequence start/end
+ // position in range
+ // then transfer back to original sequence on return.
+ }
+ if (seq.getLength() > ln)
+ {
+ ln = seq.getLength();
+ }
+ }
+ }
+ if (alignedSeqs && submitGaps)
+ {
+ realw = 0;
+ for (int i = 0; i < gapMap.length; i++)
+ {
+ if (gapMap[i])
+ {
+ realw++;
+ }
+ }
+ // try real hard to return something submittable
+ // TODO: some of AAcon measures need a minimum of two or three amino
+ // acids at each position, and AAcon doesn't gracefully degrade.
+ for (int p = 0; p < seqs.size(); p++)
+ {
+ SequenceI sq = seqs.get(p);
+ // strip gapped columns
+ char[] padded = new char[realw],
+ orig = sq.getSequence();
+ for (int i = 0, pp = 0; i < realw; pp++)
+ {
+ if (gapMap[pp])
+ {
+ if (orig.length > pp)
+ {
+ padded[i++] = orig[pp];
+ }
+ else
+ {
+ padded[i++] = '-';
+ }
+ }
+ }
+ seqs.set(p, new jalview.datamodel.Sequence(sq.getName(),
+ new String(padded)));
+ }
+ }
+ return seqs;
+ }
+
+ @Override
+ public void updateAnnotation()
+ {
+ updateResultAnnotation(false);
+ }
+
+ public void updateResultAnnotation(boolean immediate)
+ {
+ if ((immediate || !calcMan.isWorking(this)) && running != null
+ && running.hasResults())
+ {
+ List<AlignmentAnnotation> ourAnnot = running.getAnnotation(),
+ newAnnots = new ArrayList<>();
+ //
+ // update graphGroup for all annotation
+ //
+ /**
+ * find a graphGroup greater than any existing ones this could be a method
+ * provided by alignment Alignment.getNewGraphGroup() - returns next
+ * unused graph group
+ */
+ int graphGroup = 1;
+ if (alignViewport.getAlignment().getAlignmentAnnotation() != null)
+ {
+ for (AlignmentAnnotation ala : alignViewport.getAlignment()
+ .getAlignmentAnnotation())
+ {
+ if (ala.graphGroup > graphGroup)
+ {
+ graphGroup = ala.graphGroup;
+ }
+ }
+ }
+ /**
+ * update graphGroup in the annotation rows returned from service
+ */
+ // TODO: look at sequence annotation rows and update graph groups in the
+ // case of reference annotation.
+ for (AlignmentAnnotation ala : ourAnnot)
+ {
+ if (ala.graphGroup > 0)
+ {
+ ala.graphGroup += graphGroup;
+ }
+ SequenceI aseq = null;
+
+ /**
+ * transfer sequence refs and adjust gapmap
+ */
+ if (ala.sequenceRef != null)
+ {
+ SequenceI seq = running.getSeqNames()
+ .get(ala.sequenceRef.getName());
+ aseq = seq;
+ while (seq.getDatasetSequence() != null)
+ {
+ seq = seq.getDatasetSequence();
+ }
+ }
+ Annotation[] resAnnot = ala.annotations,
+ gappedAnnot = new Annotation[Math.max(
+ alignViewport.getAlignment().getWidth(),
+ gapMap.length)];
+ for (int p = 0, ap = start; ap < gappedAnnot.length; ap++)
+ {
+ if (gapMap != null && gapMap.length > ap && !gapMap[ap])
+ {
+ gappedAnnot[ap] = new Annotation("", "", ' ', Float.NaN);
+ }
+ else if (p < resAnnot.length)
+ {
+ gappedAnnot[ap] = resAnnot[p++];
+ }
+ }
+ ala.sequenceRef = aseq;
+ ala.annotations = gappedAnnot;
+ AlignmentAnnotation newAnnot = getAlignViewport().getAlignment()
+ .updateFromOrCopyAnnotation(ala);
+ if (aseq != null)
+ {
+
+ aseq.addAlignmentAnnotation(newAnnot);
+ newAnnot.adjustForAlignment();
+
+ AlignmentAnnotationUtils.replaceAnnotationOnAlignmentWith(
+ newAnnot, newAnnot.label, newAnnot.getCalcId());
+ }
+ newAnnots.add(newAnnot);
+
+ }
+ for (SequenceI sq : running.getSeqs())
+ {
+ if (!sq.getFeatures().hasFeatures()
+ && (sq.getDBRefs() == null || sq.getDBRefs().size() == 0))
+ {
+ continue;
+ }
+ running.setTransferSequenceFeatures(true);
+ SequenceI seq = running.getSeqNames().get(sq.getName());
+ SequenceI dseq;
+ ContiguousI seqRange = seq.findPositions(start, end);
+
+ while ((dseq = seq).getDatasetSequence() != null)
+ {
+ seq = seq.getDatasetSequence();
+ }
+ List<ContiguousI> sourceRange = new ArrayList();
+ if (gapMap != null && gapMap.length >= end)
+ {
+ int lastcol = start, col = start;
+ do
+ {
+ if (col == end || !gapMap[col])
+ {
+ if (lastcol <= (col - 1))
+ {
+ seqRange = seq.findPositions(lastcol, col);
+ sourceRange.add(seqRange);
+ }
+ lastcol = col + 1;
+ }
+ } while (++col <= end);
+ }
+ else
+ {
+ sourceRange.add(seq.findPositions(start, end));
+ }
+ int i = 0;
+ int source_startend[] = new int[sourceRange.size() * 2];
+
+ for (ContiguousI range : sourceRange)
+ {
+ source_startend[i++] = range.getBegin();
+ source_startend[i++] = range.getEnd();
+ }
+ Mapping mp = new Mapping(
+ new MapList(source_startend, new int[]
+ { seq.getStart(), seq.getEnd() }, 1, 1));
+ dseq.transferAnnotation(sq, mp);
+
+ }
+ updateOurAnnots(newAnnots);
+ }
+ }
+
+ protected void updateOurAnnots(List<AlignmentAnnotation> ourAnnot)
+ {
+ List<AlignmentAnnotation> our = ourAnnots;
+ ourAnnots = ourAnnot;
+ AlignmentI alignment = alignViewport.getAlignment();
+ if (our != null)
+ {
+ if (our.size() > 0)
+ {
+ for (AlignmentAnnotation an : our)
+ {
+ if (!ourAnnots.contains(an))
+ {
+ // remove the old annotation
+ alignment.deleteAnnotation(an);
+ }
+ }
+ }
+ our.clear();
+ }
+
+ // validate rows and update Alignmment state
+ for (AlignmentAnnotation an : ourAnnots)
+ {
+ alignViewport.getAlignment().validateAnnotation(an);
+ }
+ // TODO: may need a menu refresh after this
+ // af.setMenusForViewport();
+ ap.adjustAnnotationHeight();
+
+ }
+
+ public SequenceAnnotationServiceI getService()
+ {
+ return annotService;
+ }
+
+}
*/
package jalview.ws.jws2;
-import java.util.Locale;
-
import jalview.api.AlignCalcWorkerI;
import jalview.gui.AlignFrame;
import jalview.gui.Desktop;
import jalview.gui.JvSwingUtils;
import jalview.util.MessageManager;
-import jalview.ws.jws2.dm.AAConSettings;
-import jalview.ws.jws2.jabaws2.Jws2Instance;
+import jalview.ws.api.ServiceWithParameters;
+import jalview.ws.params.AutoCalcSetting;
import jalview.ws.params.WsParamSetI;
import jalview.ws.uimodel.AlignAnalysisUIText;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
+import java.util.Locale;
+
import javax.swing.JMenu;
import javax.swing.JMenuItem;
// TODO Auto-generated constructor stub
}
- public SequenceAnnotationWSClient(final Jws2Instance sh,
+ public SequenceAnnotationWSClient(final ServiceWithParameters sh,
AlignFrame alignFrame, WsParamSetI preset, boolean editParams)
{
super(alignFrame, preset, null);
// dan think. Do I need to change this method to run RNAalifold through the
// GUI
- public void initSequenceAnnotationWSClient(final Jws2Instance sh,
- AlignFrame alignFrame, WsParamSetI preset, boolean editParams)
+ private void initSequenceAnnotationWSClient(final ServiceWithParameters sh,
+ AlignFrame alignFrame, final WsParamSetI preset, boolean editParams)
{
// dan changed! dan test. comment out if conditional
// if (alignFrame.getViewport().getAlignment().isNucleotide())
// columns
List<AlignCalcWorkerI> clnts = alignFrame.getViewport()
- .getCalcManager().getRegisteredWorkersOfClass(clientClass);
- AbstractJabaCalcWorker worker;
- if (clnts == null || clnts.size() == 0)
+ .getCalcManager()
+ .getWorkersOfClass(SeqAnnotationServiceCalcWorker.class);
+
+ SeqAnnotationServiceCalcWorker tmpworker = null;
+ if (clnts != null)
{
- if (!processParams(sh, editParams))
+ for (AlignCalcWorkerI _worker : clnts)
{
- return;
+ tmpworker = (SeqAnnotationServiceCalcWorker) _worker;
+ if (tmpworker.hasService()
+ && tmpworker.getService().getClass().equals(clientClass))
+ {
+ break;
+ }
+ tmpworker = null;
}
- try
- {
- worker = (AbstractJabaCalcWorker) (clientClass
- .getConstructor(new Class[]
- { Jws2Instance.class, AlignFrame.class, WsParamSetI.class,
- List.class })
- .newInstance(new Object[]
- { sh, alignFrame, this.preset, paramset }));
- } catch (Exception x)
- {
- x.printStackTrace();
- throw new Error(
+ }
+ final var worker = tmpworker;
+ if (worker == null)
+ {
+ processParams(sh, editParams).thenAccept((startJob) -> {
+ if (startJob)
+ {
+ final SeqAnnotationServiceCalcWorker worker_;
+ try
+ {
+ worker_ = new SeqAnnotationServiceCalcWorker(sh, alignFrame, this.preset,
+ paramset);
+ } catch (Exception x)
+ {
+ x.printStackTrace();
+ throw new Error(
MessageManager.getString("error.implementation_error"),
x);
- }
- alignFrame.getViewport().getCalcManager().registerWorker(worker);
- alignFrame.getViewport().getCalcManager().startWorker(worker);
+ }
+ alignFrame.getViewport().getCalcManager().registerWorker(worker_);
+ // also starts the worker
+ startSeqAnnotationWorker(sh, alignFrame, preset, editParams);
+ }
+ });
}
else
{
- worker = (AbstractJabaCalcWorker) clnts.get(0);
+ WsParamSetI preset_;
if (editParams)
{
paramset = worker.getArguments();
- preset = worker.getPreset();
+ preset_ = worker.getPreset();
}
-
- if (!processParams(sh, editParams, true))
+ else
{
- return;
+ preset_ = preset;
}
- // reinstate worker if it was blacklisted (might have happened due to
- // invalid parameters)
- alignFrame.getViewport().getCalcManager().enableWorker(worker);
- worker.updateParameters(this.preset, paramset);
+ processParams(sh, editParams, true).thenAccept((startJob) -> {
+ if (startJob)
+ {
+ // reinstate worker if it was blacklisted (might have happened due
+ // to
+ // invalid parameters)
+ alignFrame.getViewport().getCalcManager().enableWorker(worker);
+ worker.updateParameters(this.preset, paramset);
+ startSeqAnnotationWorker(sh, alignFrame, preset_, editParams);
+ }
+ });
}
}
-- if (sh.action.toLowerCase(Locale.ROOT).contains("disorder"))
++ else
++ {
++ startSeqAnnotationWorker(sh, alignFrame, preset, editParams);
++ }
++ }
++
++ private void startSeqAnnotationWorker(ServiceWithParameters sh,
++ AlignFrame alignFrame, WsParamSetI preset, boolean editParams)
++ {
++ if (!sh.isInteractiveUpdate())
{
// build IUPred style client. take sequences, returns annotation per
// sequence.
- if (!processParams(sh, editParams))
- {
- return;
- }
-
- alignFrame.getViewport().getCalcManager().startWorker(
- new AADisorderClient(sh, alignFrame, preset, paramset));
+ processParams(sh, editParams).thenAccept((startJob) -> {
+ if (startJob)
+ {
+ alignFrame.getViewport().getCalcManager().startWorker(
+ new SeqAnnotationServiceCalcWorker(sh, alignFrame, preset, paramset));
+ }
+ });
}
}
- public SequenceAnnotationWSClient(AAConSettings fave,
+ public SequenceAnnotationWSClient(AutoCalcSetting fave,
AlignFrame alignFrame, boolean b)
{
- super(alignFrame, fave.getPreset(), fave.getJobArgset());
+ super(alignFrame, fave.getPreset(), fave.getArgumentSet());
initSequenceAnnotationWSClient(fave.getService(), alignFrame,
fave.getPreset(), b);
}
* @see jalview.ws.jws2.Jws2Client#attachWSMenuEntry(javax.swing.JMenu,
* jalview.ws.jws2.jabaws2.Jws2Instance, jalview.gui.AlignFrame)
*/
- public void attachWSMenuEntry(JMenu wsmenu, final Jws2Instance service,
+ @Override
+ public void attachWSMenuEntry(JMenu wsmenu,
+ final ServiceWithParameters service,
final AlignFrame alignFrame)
{
- if (registerAAConWSInstance(wsmenu, service, alignFrame))
+ if (Jws2ClientFactory.registerAAConWSInstance(wsmenu,
+ service, alignFrame))
{
// Alignment dependent analysis calculation WS gui
return;
}
boolean hasparams = service.hasParameters();
- // Assume name ends in WS
- String calcName = service.serviceType.substring(0,
- service.serviceType.length() - 2);
+ String calcName = service.getName();
+ if (calcName.endsWith("WS"))
+ {
+ // Remove "WS" suffix
+ calcName = calcName.substring(0, calcName.length() - 2);
+ }
JMenuItem annotservice = new JMenuItem(MessageManager.formatMessage(
"label.calcname_with_default_settings", new String[]
@Override
public void actionPerformed(ActionEvent e)
{
- new SequenceAnnotationWSClient(service, alignFrame, null, false);
+ new SequenceAnnotationWSClient(service, alignFrame,
+ null, false);
}
});
wsmenu.add(annotservice);
annotservice.addActionListener(new ActionListener()
{
+ @Override
public void actionPerformed(ActionEvent e)
{
- new SequenceAnnotationWSClient(service, alignFrame, null, true);
+ new SequenceAnnotationWSClient(service, alignFrame,
+ null, true);
}
});
wsmenu.add(annotservice);
+ "</strong><br/>" + preset.getDescription()));
methodR.addActionListener(new ActionListener()
{
+ @Override
public void actionPerformed(ActionEvent e)
{
- new SequenceAnnotationWSClient(service, alignFrame, preset,
+ new SequenceAnnotationWSClient(service,
+ alignFrame, preset,
false);
}
{
annotservice = new JMenuItem(
MessageManager.getString("label.view_documentation"));
- if (service.docUrl != null)
+ if (service != null && service.hasDocumentationUrl())
{
annotservice.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
- Desktop.instance.showUrl(service.docUrl);
+ Desktop.getInstance().showUrl(service.getDocumentationUrl());
}
});
annotservice.setToolTipText(
JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage(
"label.view_service_doc_url", new String[]
- { service.docUrl, service.docUrl })));
+ { service.getDocumentationUrl(),
+ service.getDocumentationUrl() })));
wsmenu.add(annotservice);
}
}
--- /dev/null
+/*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
+package jalview.ws.jws2.jabaws2;
+
+import jalview.analysis.AlignmentAnnotationUtils;
+import jalview.api.FeatureColourI;
+import jalview.bin.Cache;
++import jalview.bin.Console;
+import jalview.datamodel.AlignmentAnnotation;
+import jalview.datamodel.AlignmentI;
+import jalview.datamodel.GraphLine;
+import jalview.datamodel.SequenceFeature;
+import jalview.datamodel.SequenceI;
+import jalview.datamodel.features.FeatureMatcherSetI;
+import jalview.schemes.FeatureColour;
+import jalview.util.ColorUtils;
+
+import java.awt.Color;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import compbio.data.sequence.Range;
+import compbio.data.sequence.Score;
+import compbio.data.sequence.ScoreManager.ScoreHolder;
+
+public class AADisorderClient extends JabawsAnnotationInstance
+{
+ // static configuration
+ public static String getServiceActionText()
+ {
+ return "Submitting amino acid sequences for disorder prediction.";
+ }
+
+ // minSeq = 1; protein only, no gaps
+
+ // instance
+ public AADisorderClient(Jws2Instance handle)
+ {
+ super(handle);
+
+ }
+
+ @Override
+ List<AlignmentAnnotation> annotationFromScoreManager(AlignmentI seqs,
+ Map<String, FeatureColourI> featureColours,
+ Map<String, FeatureMatcherSetI> featureFilters)
+ {
+
+ Map<String, String[]> featureTypeMap = featureMap.get(our.getName());
+ Map<String, Map<String, Object>> annotTypeMap = annotMap
+ .get(our.getName());
+ boolean dispFeatures = false;
+ Map<String, SequenceFeature> fc = new Hashtable<>(),
+ fex = new Hashtable();
+ List<AlignmentAnnotation> ourAnnot = new ArrayList<>();
+ int graphGroup = 1, lastAnnot = 0;
+
+ for (SequenceI seq : seqs.getSequences())
+ {
+ String seqId = seq.getName();
+ boolean sameGroup = false;
+ SequenceI dseq, aseq;
+ int base = seq.findPosition(0) - 1;
+ aseq = seq;
+ while ((dseq = seq).getDatasetSequence() != null)
+ {
+ seq = seq.getDatasetSequence();
+ }
+ ScoreHolder scores = null;
+ try
+ {
+ scores = scoremanager.getAnnotationForSequence(seqId);
+ } catch (Exception q)
+ {
- Cache.log.info("Couldn't recover disorder prediction for sequence "
++ Console.info("Couldn't recover disorder prediction for sequence "
+ + seq.getName() + "(Prediction name was " + seqId + ")"
+ + "\nSee http://issues.jalview.org/browse/JAL-1319 for one possible reason why disorder predictions might fail.",
+ q);
+ }
+ float last = Float.NaN, val = Float.NaN;
+ if (scores != null && scores.scores != null)
+ {
+ for (Score scr : scores.scores)
+ {
+
+ if (scr.getRanges() != null && scr.getRanges().size() > 0)
+ {
+ Iterator<Float> vals = scr.getScores().iterator();
+ // make features on sequence
+ for (Range rn : scr.getRanges())
+ {
+ // TODO: Create virtual feature settings
+ SequenceFeature sf;
+ String[] type = featureTypeMap.get(scr.getMethod());
+ if (type == null)
+ {
+ // create a default type for this feature
+ type = new String[] {
+ typeName + " (" + scr.getMethod() + ")",
+ our.getActionText() };
+ }
+ if (vals.hasNext())
+ {
+ val = vals.next().floatValue();
+ sf = new SequenceFeature(type[0], type[1], base + rn.from,
+ base + rn.to, val, methodName);
+ }
+ else
+ {
+ sf = new SequenceFeature(type[0], type[1], base + rn.from,
+ base + rn.to, methodName);
+ }
+ dseq.addSequenceFeature(sf);
+ // mark feature as requiring a graduated colourscheme if has
+ // variable scores
+ if (!Float.isNaN(last) && !Float.isNaN(val) && last != val)
+ {
+ fc.put(sf.getType(), sf);
+ } else
+ {
+ fex.put(sf.getType(), sf);
+ }
+ last = val;
+ dispFeatures = true;
+ }
+ }
+ else
+ {
+ if (scr.getScores().size() == 0)
+ {
+ continue;
+ }
+ String typename, calcName;
+ AlignmentAnnotation annot = createAnnotationRowsForScores(
+ seqs, null, ourAnnot,
+ typename = our.getName() + " (" + scr.getMethod() + ")",
+ calcName = our.getNameURI() + "/" + scr.getMethod(),
+ aseq, base + 1, scr);
+ annot.graph = AlignmentAnnotation.LINE_GRAPH;
+
+ Map<String, Object> styleMap = (annotTypeMap == null) ? null
+ : annotTypeMap.get(scr.getMethod());
+
+ annot.visible = (styleMap == null
+ || styleMap.get(INVISIBLE) == null);
+ double[] thrsh = (styleMap == null) ? null
+ : (double[]) styleMap.get(THRESHOLD);
+ float[] range = (styleMap == null) ? null
+ : (float[]) styleMap.get(RANGE);
+ if (range != null)
+ {
+ annot.graphMin = range[0];
+ annot.graphMax = range[1];
+ }
+ if (styleMap == null || styleMap.get(DONTCOMBINE) == null)
+ {
+ {
+ if (!sameGroup)
+ {
+ graphGroup++;
+ sameGroup = true;
+ }
+
+ annot.graphGroup = graphGroup;
+ }
+ }
+
+ annot.description = "<html>" + our.getActionText()
+ + " - raw scores";
+ if (thrsh != null)
+ {
+ String threshNote = (thrsh[0] > 0 ? "Above " : "Below ")
+ + thrsh[1] + " indicates disorder";
+ annot.threshold = new GraphLine((float) thrsh[1], threshNote,
+ Color.red);
+ annot.description += "<br/>" + threshNote;
+ }
+ annot.description += "</html>";
+ Color col = ColorUtils
+ .createColourFromName(typeName + scr.getMethod());
+ for (int p = 0, ps = annot.annotations.length; p < ps; p++)
+ {
+ if (annot.annotations[p] != null)
+ {
+ annot.annotations[p].colour = col;
+ }
+ }
+ annot._linecolour = col;
+ // finally, update any dataset annotation
+ AlignmentAnnotationUtils.replaceAnnotationOnAlignmentWith(annot,
+ typename, calcName);
+ }
+ }
+ }
+ if (lastAnnot + 1 == ourAnnot.size())
+ {
+ // remove singleton alignment annotation row
+ ourAnnot.get(lastAnnot).graphGroup = -1;
+ }
+ }
+ {
+ if (dispFeatures)
+ {
+ // TODO: virtual feature settings
+ // feature colours need to merged with current viewport's colours
+ // simple feature colours promoted to colour-by-score ranges using
+ // currently assigned or created feature colour
+ for (String ft : fex.keySet())
+ {
+ Color col = ColorUtils.createColourFromName(ft);
+ // set graduated color as fading to white for minimum, and
+ // autoscaling to values on alignment
+
+ FeatureColourI ggc;
+ if (fc.get(ft) != null)
+ {
+ ggc = new FeatureColour(col, Color.white, col,
+
+ Color.white, Float.MIN_VALUE, Float.MAX_VALUE);
+ ggc.setAutoScaled(true);
+ }
+ else
+ {
+ ggc = new FeatureColour(col);
+ }
+ featureColours.put(ft, ggc);
+ }
+
+ }
+ return ourAnnot;
+ }
+ }
+
+ private static final String THRESHOLD = "THRESHOLD";
+
+ private static final String RANGE = "RANGE";
+
+ String typeName;
+
+ String methodName;
+
+ String groupName;
+
+ private static Map<String, Map<String, String[]>> featureMap;
+
+ private static Map<String, Map<String, Map<String, Object>>> annotMap;
+
+ private static String DONTCOMBINE = "DONTCOMBINE";
+
+ private static String INVISIBLE = "INVISIBLE";
+ static
+ {
+ // TODO: turn this into some kind of configuration file that's a bit easier
+ // to edit
+ featureMap = new HashMap<>();
+ Map<String, String[]> fmap;
+ featureMap.put(compbio.ws.client.Services.IUPredWS.toString(),
+ fmap = new HashMap<>());
+ fmap.put("Glob",
+ new String[]
+ { "Globular Domain", "Predicted globular domain" });
+ featureMap.put(compbio.ws.client.Services.JronnWS.toString(),
+ fmap = new HashMap<>());
+ featureMap.put(compbio.ws.client.Services.DisemblWS.toString(),
+ fmap = new HashMap<>());
+ fmap.put("REM465", new String[] { "REM465", "Missing density" });
+ fmap.put("HOTLOOPS", new String[] { "HOTLOOPS", "Flexible loops" });
+ fmap.put("COILS", new String[] { "COILS", "Random coil" });
+ featureMap.put(compbio.ws.client.Services.GlobPlotWS.toString(),
+ fmap = new HashMap<>());
+ fmap.put("GlobDoms",
+ new String[]
+ { "Globular Domain", "Predicted globular domain" });
+ fmap.put("Disorder",
+ new String[]
+ { "Protein Disorder", "Probable unstructured peptide region" });
+ Map<String, Map<String, Object>> amap;
+ annotMap = new HashMap<>();
+ annotMap.put(compbio.ws.client.Services.GlobPlotWS.toString(),
+ amap = new HashMap<>());
+ amap.put("Dydx", new HashMap<String, Object>());
+ amap.get("Dydx").put(DONTCOMBINE, DONTCOMBINE);
+ amap.get("Dydx").put(THRESHOLD, new double[] { 1, 0 });
+ amap.get("Dydx").put(RANGE, new float[] { -1, +1 });
+
+ amap.put("SmoothedScore", new HashMap<String, Object>());
+ amap.get("SmoothedScore").put(INVISIBLE, INVISIBLE);
+ amap.put("RawScore", new HashMap<String, Object>());
+ amap.get("RawScore").put(INVISIBLE, INVISIBLE);
+ annotMap.put(compbio.ws.client.Services.DisemblWS.toString(),
+ amap = new HashMap<>());
+ amap.put("COILS", new HashMap<String, Object>());
+ amap.put("HOTLOOPS", new HashMap<String, Object>());
+ amap.put("REM465", new HashMap<String, Object>());
+ amap.get("COILS").put(THRESHOLD, new double[] { 1, 0.516 });
+ amap.get("COILS").put(RANGE, new float[] { 0, 1 });
+
+ amap.get("HOTLOOPS").put(THRESHOLD, new double[] { 1, 0.6 });
+ amap.get("HOTLOOPS").put(RANGE, new float[] { 0, 1 });
+ amap.get("REM465").put(THRESHOLD, new double[] { 1, 0.1204 });
+ amap.get("REM465").put(RANGE, new float[] { 0, 1 });
+
+ annotMap.put(compbio.ws.client.Services.IUPredWS.toString(),
+ amap = new HashMap<>());
+ amap.put("Long", new HashMap<String, Object>());
+ amap.put("Short", new HashMap<String, Object>());
+ amap.get("Long").put(THRESHOLD, new double[] { 1, 0.5 });
+ amap.get("Long").put(RANGE, new float[] { 0, 1 });
+ amap.get("Short").put(THRESHOLD, new double[] { 1, 0.5 });
+ amap.get("Short").put(RANGE, new float[] { 0, 1 });
+ annotMap.put(compbio.ws.client.Services.JronnWS.toString(),
+ amap = new HashMap<>());
+ amap.put("JRonn", new HashMap<String, Object>());
+ amap.get("JRonn").put(THRESHOLD, new double[] { 1, 0.5 });
+ amap.get("JRonn").put(RANGE, new float[] { 0, 1 });
+ }
+
+}
--- /dev/null
+package jalview.ws.jws2.jabaws2;
+
+import jalview.bin.Cache;
++import jalview.bin.Console;
+import jalview.gui.WebserviceInfo;
+import jalview.util.MessageManager;
+import jalview.ws.gui.WsJob;
+import jalview.ws.gui.WsJob.JobState;
+import jalview.ws.jws2.JabaParamStore;
+import jalview.ws.jws2.JabaPreset;
+import jalview.ws.jws2.dm.JabaWsParamSet;
+import jalview.ws.params.WsParamSetI;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import compbio.metadata.Argument;
+import compbio.metadata.ChunkHolder;
+import compbio.metadata.JobStatus;
+import compbio.metadata.Preset;
+
+/**
+ * Base class for JABAWS service instances. Provides helper methods for
+ * interfacing with Jalview.
+ *
+ * @author jprocter
+ *
+ */
+public class JabawsServiceInstance<T extends compbio.data.msa.JManagement>
+ implements
+ jalview.ws.api.JalviewWebServiceI, jalview.ws.api.CancellableI
+{
+ /**
+ * our service instance handler generated by the discoverer
+ */
+ Jws2Instance our;
+ protected T service;
+ protected Map<JobStatus, JobState> jwsState = new HashMap<>();
+
+ @Override
+ public boolean cancel(WsJob job)
+ {
+ service.cancelJob(job.getJobId());
+ // if the Jaba server indicates the job can't be cancelled, its
+ // because its running on the server's local execution engine
+ // so we just close the window anyway.
+
+ return true;
+ }
+
+
+ public JabawsServiceInstance(Jws2Instance handle)
+ {
+ our = handle;
+ service = (T) handle.service;
+ }
+
+ @Override
+ public void updateStatus(WsJob job)
+ {
+ JobStatus jwsstatus = service.getJobStatus(job.getJobId());
+ job.setState(jwsState.get(jwsstatus));
+ }
+
+ @Override
+ public boolean updateJobProgress(WsJob job) throws Exception
+ {
+ StringBuilder response = new StringBuilder(job.getStatus());
+ long lastchunk = job.getNextChunk();
+ if (lastchunk == -1)
+ {
- Cache.log.debug("No more status messages for job " + job.getJobId());
++ Console.debug("No more status messages for job " + job.getJobId());
+ return false;
+ }
+ boolean changed = false;
+ do
+ {
+ ChunkHolder chunk = service.pullExecStatistics(job.getJobId(),
+ lastchunk);
+ if (chunk != null)
+ {
+ changed |= chunk.getChunk().length() > 0;
+ response.append(chunk.getChunk());
+ lastchunk = chunk.getNextPosition();
+ try
+ {
+ Thread.sleep(50);
+ } catch (InterruptedException x)
+ {
+ }
+ ;
+ }
+ ;
+ job.setnextChunk(lastchunk);
+ } while (lastchunk >= 0 && job.getNextChunk() != lastchunk);
+ if (job instanceof WsJob)
+ {
+ // TODO decide if WsJob will be the bean for all ng-webservices
+ job.setStatus(response.toString());
+ }
+ return changed;
+ }
+
+ {
+ jwsState.put(JobStatus.CANCELLED, JobState.CANCELLED);
+ jwsState.put(JobStatus.COLLECTED, JobState.FINISHED);
+ jwsState.put(JobStatus.FAILED, JobState.FAILED);
+ jwsState.put(JobStatus.FINISHED, JobState.FINISHED);
+ jwsState.put(JobStatus.PENDING, JobState.QUEUED);
+ jwsState.put(JobStatus.RUNNING, JobState.RUNNING);
+ jwsState.put(JobStatus.STARTED, JobState.RUNNING);
+ jwsState.put(JobStatus.SUBMITTED, JobState.SUBMITTED);
+ jwsState.put(JobStatus.UNDEFINED, JobState.UNKNOWN);
+ }
+
+ public boolean isPresetJob(WsJob job)
+ {
+ return job.getPreset() != null && job.getPreset() instanceof JabaPreset;
+ }
+
+ public Preset getServerPreset(WsJob job)
+ {
+ return (isPresetJob(job))
+ ? ((JabaPreset) job.getPreset()).getJabaPreset()
+ : null;
+ }
+
+ public List<Argument> getJabaArguments(WsParamSetI preset)
+ {
+ List<Argument> newargs = new ArrayList<>();
+ if (preset != null)
+ {
+ if (preset instanceof JabaWsParamSet)
+ {
+ newargs.addAll(((JabaWsParamSet) preset).getjabaArguments());
+ }
+ else
+ {
+ newargs.addAll(
+ JabaParamStore.getJabafromJwsArgs(preset.getArguments()));
+ }
+ }
+ return newargs;
+ }
+
+ @Override
+ public boolean handleSubmitError(Throwable _lex, WsJob j,
+ WebserviceInfo wsInfo) throws Exception, Error
+ {
+ if (_lex instanceof compbio.metadata.UnsupportedRuntimeException)
+ {
+ wsInfo.appendProgressText(MessageManager.formatMessage(
+ "info.job_couldnt_be_run_server_doesnt_support_program",
+ new String[]
+ { _lex.getMessage() }));
+ wsInfo.warnUser(_lex.getMessage(),
+ MessageManager.getString("warn.service_not_supported"));
+ wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
+ wsInfo.setStatus(j.getJobnum(),
+ WebserviceInfo.STATE_STOPPED_SERVERERROR);
+ return true;
+ }
+ if (_lex instanceof compbio.metadata.LimitExceededException)
+ {
+ wsInfo.appendProgressText(MessageManager.formatMessage(
+ "info.job_couldnt_be_run_exceeded_hard_limit", new String[]
+ { _lex.getMessage() }));
+ wsInfo.warnUser(_lex.getMessage(),
+ MessageManager.getString("warn.input_is_too_big"));
+ wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
+ wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
+ return true;
+ }
+ if (_lex instanceof compbio.metadata.WrongParameterException)
+ {
+ wsInfo.warnUser(_lex.getMessage(),
+ MessageManager.getString("warn.invalid_job_param_set"));
+ wsInfo.appendProgressText(MessageManager.formatMessage(
+ "info.job_couldnt_be_run_incorrect_param_setting",
+ new String[]
+ { _lex.getMessage() }));
+ wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
+ wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
+ return true;
+ }
+ // pass on to generic error handler
+ return false;
+ }
+
+ @Override
+ public boolean handleCollectionException(Exception ex, WsJob msjob,
+ WebserviceInfo wsInfo)
+ {
+ if (ex instanceof compbio.metadata.ResultNotAvailableException)
+ {
+ // job has failed for some reason - probably due to invalid
+ // parameters
- Cache.log.debug(
++ Console.debug(
+ "Results not available for finished job - marking as broken job.",
+ ex);
+ String status = msjob.getStatus();
+
+ msjob.setStatus(status
+ + "\nResult not available. Probably due to invalid input or parameter settings. Server error message below:\n\n"
+ + ex.getLocalizedMessage());
+ msjob.setState(WsJob.JobState.BROKEN);
+ return true;
+ }
+ return false;
+ }
+}
*/
package jalview.ws.rest;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.io.FileParse;
import jalview.io.packed.DataProvider;
import jalview.io.packed.DataProvider.JvDataType;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.mime.MultipartEntity;
+import org.apache.http.util.EntityUtils;
import org.apache.james.mime4j.MimeException;
import org.apache.james.mime4j.parser.MimeStreamParser;
+
/**
* data source instantiated from the response of an httpclient request.
*
}
jalview.io.packed.JalviewDataset ds = restJob.newJalviewDataset();
// Decide how we deal with content.
- if (en instanceof MultipartEntity)
+ // TODO : verify we are detecting a multipart response correctly
+ if (en.getContentType().getValue().startsWith("multipart/form-data"))
{
// Multipart messages should be properly typed, so we parse them as we go.
- MultipartEntity mpe = (MultipartEntity) en;
- // multipart
JalviewMimeContentHandler handler = new JalviewMimeContentHandler(ds);
MimeStreamParser parser = new MimeStreamParser();
parser.setContentHandler(handler);
try
{
- parser.parse(mpe.getContent());
+ parser.parse(en.getContent());
} catch (MimeException me)
{
error = true;
errormessage = "Couldn't parse message from web service.";
- Cache.log.warn("Failed to parse MIME multipart content", me);
+ Console.warn("Failed to parse MIME multipart content", me);
- en.consumeContent();
+ EntityUtils.consume(en);
}
return new ParsePackedSet().getAlignment(ds,
handler.getJalviewDataProviders());
: en.getContentEncoding().getValue();
if (en.getContentType() != null)
{
- Cache.log.debug("Result Type: " + en.getContentType().toString());
+ Console.debug("Result Type: " + en.getContentType().toString());
}
else
{
- Cache.log.debug("No Result Type Specified.");
+ Console.debug("No Result Type Specified.");
}
if (enc == null || enc.length() < 1)
{
- Cache.log.debug("Assuming 'Default' Result Encoding.");
+ Console.debug("Assuming 'Default' Result Encoding.");
}
else
{
- Cache.log.debug("Result Encoded as : " + enc);
+ Console.debug("Result Encoded as : " + enc);
}
// attempt to identify file and construct an appropriate DataSource
// identifier for it.
: new InputStreamReader(en.getContent());
} catch (UnsupportedEncodingException e)
{
- Cache.log.error("Can't handle encoding '" + enc
+ Console.error("Can't handle encoding '" + enc
+ "' for response from webservice.", e);
- en.consumeContent();
+ EntityUtils.consume(en);
error = true;
errormessage = "Can't handle encoding for response from webservice";
return;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
-import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
{
NUC, PROT, MIX;
- public static Collection<String> toStringValues()
+ public static List<String> toStringValues()
{
- Collection<String> c = new ArrayList<String>();
+ List<String> c = new ArrayList<>();
for (molType type : values())
{
c.add(type.toString());
public int max = 0; // unbounded
- protected ArrayList<Class> inputData = new ArrayList<Class>();
+ protected List<Class> inputData = new ArrayList<>();
/**
* initialise the InputType with a list of jalview data classes that the
public boolean validFor(RestJob restJob)
{
if (!validFor(restJob.rsd))
+ {
return false;
+ }
for (Class cl : inputData)
{
if (!restJob.hasDataOfType(cl))
public boolean validFor(RestServiceDescription restServiceDescription)
{
if (!restServiceDescription.inputParams.values().contains(this))
+ {
return false;
+ }
return true;
}
{
valid = false;
warnings.append("Invalid value for parameter "
- + mtch.group(1).toLowerCase(Locale.ROOT) + " '" + mtch.group(2)
- + "' (expected an integer)\n");
+ + mtch.group(1).toLowerCase(Locale.ROOT) + " '"
+ + mtch.group(2) + "' (expected an integer)\n");
}
if (!configureProperty(mtch.group(1), mtch.group(2), warnings))
public List<OptionI> getBaseOptions()
{
- ArrayList<OptionI> opts = new ArrayList<OptionI>();
+ ArrayList<OptionI> opts = new ArrayList<>();
opts.add(new IntegerParameter("min",
"Minimum number of data of this type", true, 1, min, 0, -1));
opts.add(new IntegerParameter("max",
public void configureFromArgumentI(List<ArgumentI> currentSettings)
throws InvalidArgumentException
{
- ArrayList<String> urltoks = new ArrayList<String>();
+ List<String> urltoks = new ArrayList<>();
String rg;
for (ArgumentI arg : currentSettings)
{
*/
package jalview.ws.rest;
+import jalview.bin.ApplicationSingletonProvider;
+import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
import jalview.bin.Cache;
import jalview.datamodel.AlignmentView;
import jalview.gui.AlignFrame;
import jalview.gui.Desktop;
import jalview.gui.JvOptionPane;
import jalview.gui.WebserviceInfo;
-import jalview.io.packed.DataProvider.JvDataType;
import jalview.util.MessageManager;
import jalview.ws.WSClient;
import jalview.ws.WSClientI;
import jalview.ws.WSMenuEntryProviderI;
+import jalview.ws.rest.clientdefs.ShmrRestClient;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
-import java.util.Hashtable;
import java.util.Vector;
import javax.swing.JMenu;
*
*/
public class RestClient extends WSClient
- implements WSClientI, WSMenuEntryProviderI
+implements WSClientI, WSMenuEntryProviderI, ApplicationSingletonI
{
-
+ @SuppressWarnings("unused")
+ private RestClient()
+ {
+ // accessed by ApplicationSingletonProvider
+ }
+
+
+private static RestClient getInstance()
+{
+return (RestClient) ApplicationSingletonProvider.getInstance(RestClient.class);
+}
+
+public static final String RSBS_SERVICES = "RSBS_SERVICES";
+
+
+ protected Vector<String> services = null;
-
-
RestServiceDescription service;
public RestClient(RestServiceDescription rsd)
{
WebServiceJobTitle = MessageManager
.formatMessage("label.webservice_job_title", new String[]
- { service.details.Action, service.details.Name });
- WebServiceName = service.details.Name;
+ { service.details.getAction(), service.details.getName() });
+ WebServiceName = service.details.getName();
WebServiceReference = "No reference - go to url for more info";
- if (service.details.description != null)
+ if (service.details.getDescription() != null)
{
- WebServiceReference = service.details.description;
+ WebServiceReference = service.details.getDescription();
}
if (!headless)
{
wsInfo = new WebserviceInfo(WebServiceJobTitle,
- WebServiceName + "\n" + WebServiceReference, true);
+ WebServiceName + "\n" + WebServiceReference, Desktop.FRAME_MAKE_VISIBLE);
wsInfo.setRenderAsHtml(true);
}
public void attachWSMenuEntry(final JMenu wsmenu,
final AlignFrame alignFrame)
{
- JMenuItem submit = new JMenuItem(service.details.Name);
+ JMenuItem submit = new JMenuItem(service.details.getName());
submit.setToolTipText(MessageManager
.formatMessage("label.rest_client_submit", new String[]
- { service.details.Action, service.details.Name }));
+ { service.details.getAction(), service.details.getName() }));
submit.addActionListener(new ActionListener()
{
else
{
// TODO: try to tell the user why the job couldn't be started.
- JvOptionPane.showMessageDialog(Desktop.desktop,
+ JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
(jobsthread.hasWarnings() ? jobsthread.getWarnings()
: MessageManager.getString(
"label.job_couldnt_be_started_check_input")),
}
}
- public static RestClient makeShmmrRestClient()
- {
- String action = "Analysis",
- description = "Sequence Harmony and Multi-Relief (Brandt et al. 2010)",
- name = MessageManager.getString("label.multiharmony");
- Hashtable<String, InputType> iparams = new Hashtable<String, InputType>();
- jalview.ws.rest.params.JobConstant toolp;
- // toolp = new jalview.ws.rest.JobConstant("tool","jalview");
- // iparams.put(toolp.token, toolp);
- // toolp = new jalview.ws.rest.params.JobConstant("mbjob[method]","shmr");
- // iparams.put(toolp.token, toolp);
- // toolp = new
- // jalview.ws.rest.params.JobConstant("mbjob[description]","step 1");
- // iparams.put(toolp.token, toolp);
- // toolp = new jalview.ws.rest.params.JobConstant("start_search","1");
- // iparams.put(toolp.token, toolp);
- // toolp = new jalview.ws.rest.params.JobConstant("blast","0");
- // iparams.put(toolp.token, toolp);
-
- jalview.ws.rest.params.Alignment aliinput = new jalview.ws.rest.params.Alignment();
- // SHMR server has a 65K limit for content pasted into the 'ali' parameter,
- // so we always upload our files.
- aliinput.token = "ali_file";
- aliinput.writeAsFile = true;
- iparams.put(aliinput.token, aliinput);
- jalview.ws.rest.params.SeqGroupIndexVector sgroups = new jalview.ws.rest.params.SeqGroupIndexVector();
- sgroups.setMinsize(2);
- sgroups.min = 2;// need at least two group defined to make a partition
- iparams.put("groups", sgroups);
- sgroups.token = "groups";
- sgroups.sep = " ";
- RestServiceDescription shmrService = new RestServiceDescription(action,
- description, name,
- "http://zeus.few.vu.nl/programs/shmrwww/index.php?tool=jalview", // ?tool=jalview&mbjob[method]=shmr&mbjob[description]=step1",
- "?tool=jalview", iparams, true, false, '-');
- // a priori knowledge of the data returned from the service
- shmrService.addResultDatatype(JvDataType.ANNOTATION);
- return new RestClient(shmrService);
- }
+
public AlignmentPanel recoverAlignPanelForView()
{
AlignmentPanel[] aps = Desktop
return true;
}
- protected static Vector<String> services = null;
-
- public static final String RSBS_SERVICES = "RSBS_SERVICES";
+
public static RestClient[] getRestClients()
{
+ return getInstance().getClients();
+ }
+
+ private RestClient[] getClients()
+ {
if (services == null)
{
- services = new Vector<String>();
+ services = new Vector<>();
try
{
for (RestServiceDescription descr : RestServiceDescription
- .parseDescriptions(jalview.bin.Cache.getDefault(
- .parseDescriptions(Cache.getDefault(RSBS_SERVICES,
- makeShmmrRestClient().service.toString())))
++ .parseDescriptions(Cache.getDefault(
+ RSBS_SERVICES,
+ ShmrRestClient.makeShmmrRestClient().service.toString())))
{
services.add(descr.toString());
}
public String getAction()
{
- return service.details.Action;
+ return service.details.getAction();
}
public RestServiceDescription getRestDescription()
public static Vector<String> getRsbsDescriptions()
{
- Vector<String> rsbsDescrs = new Vector<String>();
+ Vector<String> rsbsDescrs = new Vector<>();
for (RestClient rsbs : getRestClients())
{
rsbsDescrs.add(rsbs.getRestDescription().toString());
{
if (rsbsUrls != null)
{
+
// TODO: consider validating services ?
- services = new Vector<String>(rsbsUrls);
+ getInstance().services = new Vector<String>(rsbsUrls);
StringBuffer sprop = new StringBuffer();
- for (String s : services)
+ for (String s : getInstance().services)
{
sprop.append(s);
}
import java.util.Locale;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentAnnotation;
import jalview.datamodel.AlignmentI;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.protocol.BasicHttpContext;
-import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
public class RestJobThread extends AWSThread
protected void doHttpReq(Stage stg, RestJob rj, String postUrl)
throws Exception
{
- StringBuffer respText = new StringBuffer();
- // con.setContentHandlerFactory(new
- // jalview.ws.io.mime.HttpContentHandler());
HttpRequestBase request = null;
String messages = "";
if (stg == Stage.SUBMIT)
{
DefaultHttpClient httpclient = new DefaultHttpClient();
- HttpContext localContext = new BasicHttpContext();
HttpResponse response = null;
try
{
+ "</a><br>See Console output for details.";
rj.setAllowedServerExceptions(0);// unrecoverable;
rj.error = true;
- Cache.log.fatal("Unexpected REST Job " + getStage(stg)
+ Console.fatal("Unexpected REST Job " + getStage(stg)
+ "exception for URL " + rj.rsd.postUrl);
throw (he);
} catch (IOException e)
+ "Job. <br>Problematic url was <a href=\""
+ request.getURI() + "\">" + request.getURI()
+ "</a><br>See Console output for details.";
- Cache.log.warn("IO Exception for REST Job " + getStage(stg)
+ Console.warn("IO Exception for REST Job " + getStage(stg)
+ "exception for URL " + rj.rsd.postUrl);
throw (e);
{
case 200:
rj.running = false;
- Cache.log.debug("Processing result set.");
+ Console.debug("Processing result set.");
processResultSet(rj, response, request);
break;
-
case 202:
- rj.statMessage = "<br>Job submitted successfully. Results available at this URL:\n"
- + "<a href=" + rj.getJobId() + "\">" + rj.getJobId()
- + "</a><br>";
- rj.running = true;
+ markJobAsRunning(rj);
break;
-
+ case 201:
+ // Created - redirect may be present. Fallthrough to 302
case 302:
- Header[] loc;
- if (!rj.isSubmitted()
- && (loc = response
- .getHeaders(HTTPConstants.HEADER_LOCATION)) != null
- && loc.length > 0)
- {
- if (loc.length > 1)
- {
- Console.warn("Ignoring additional " + (loc.length - 1)
- + " location(s) provided in response header ( next one is '"
- + loc[1].getValue() + "' )");
- }
- rj.setJobId(loc[0].getValue());
- rj.setSubmitted(true);
- }
+ extractJobId(rj, response);
completeStatus(rj, response);
break;
case 500:
- // Failed.
- rj.setSubmitted(true);
- rj.setAllowedServerExceptions(0);
- rj.setSubjobComplete(true);
- rj.error = true;
- rj.running = false;
- completeStatus(rj, response,
- "" + getStage(stg) + "failed. Reason below:\n");
+ markAsFailed(rj, response);
+ completeStatus(rj, response, "" + getStage(stg)
+ + "failed. Reason below:\n");
break;
default:
// Some other response. Probably need to pop up the content in a window.
// TODO: deal with all other HTTP response codes from server.
- Cache.log.warn("Unhandled response status when " + getStage(stg)
+ Console.warn("Unhandled response status when " + getStage(stg)
+ "for " + postUrl + ": " + response.getStatusLine());
rj.error = true;
rj.setAllowedServerExceptions(0);
+ "</a><br/>Filtered response content below:<br/>");
} catch (IOException e)
{
- Cache.log.debug("IOException when consuming unhandled response",
- e);
+ Console.debug("IOException when consuming unhandled response", e);
}
;
}
}
}
+ private void markAsFailed(RestJob rj, HttpResponse response)
+ {
+ // Failed.
+ rj.setSubmitted(true);
+ rj.setAllowedServerExceptions(0);
+ rj.setSubjobComplete(true);
+ rj.error = true;
+ rj.running = false;
+ }
+
+ /**
+ * set the jobRunning flag and post a link to the physical result page encoded
+ * in rj.getJobId()
+ *
+ * @param rj
+ */
+ private void markJobAsRunning(RestJob rj)
+ {
+ rj.statMessage = "<br>Job submitted successfully. Results available at this URL:\n"
+ + "<a href="
+ + rj.getJobId()
+ + "\">"
+ + rj.getJobId()
+ + "</a><br>";
+ rj.running = true;
+ }
+
+ /**
+ * extract the job ID URL from the redirect page. Does nothing if job is
+ * already running.
+ *
+ * @param rj
+ * @param response
+ */
+ private void extractJobId(RestJob rj, HttpResponse response)
+ {
+ Header[] loc;
+ if (!rj.isSubmitted())
+ {
+
+ // redirect URL - typical for IBIVU type jobs.
+ if ((loc = response.getHeaders(HTTPConstants.HEADER_LOCATION)) != null
+ && loc.length > 0)
+ {
+ if (loc.length > 1)
+ {
- Cache.log
- .warn("Ignoring additional "
++ Console.warn("Ignoring additional "
+ + (loc.length - 1)
+ + " location(s) provided in response header ( next one is '"
+ + loc[1].getValue() + "' )");
+ }
+ rj.setJobId(loc[0].getValue());
+ rj.setSubmitted(true);
+ }
+ }
+ }
-
/**
* job has completed. Something valid should be available from con
*
{
job.setSubjobComplete(true);
job.setAllowedServerExceptions(-1);
- Cache.log.error("Exception when trying to start Rest Job.", ex);
+ Console.error("Exception when trying to start Rest Job.", ex);
}
}
{
// crazy users will see this message
// TODO: finish this! and remove the message below!
- Cache.log.warn("Rest job result parser is currently INCOMPLETE!");
+ Console.warn("Rest job result parser is currently INCOMPLETE!");
int validres = 0;
for (RestJob rj : (RestJob[]) jobs)
{
String ln = null;
try
{
- Cache.log.debug("Parsing data for job " + rj.getJobId());
+ Console.debug("Parsing data for job " + rj.getJobId());
rj.parseResultSet();
if (rj.hasResults())
{
validres++;
}
- Cache.log.debug("Finished parsing data for job " + rj.getJobId());
+ Console.debug("Finished parsing data for job " + rj.getJobId());
} catch (Error ex)
{
- Cache.log.warn(
+ Console.warn(
"Failed to finish parsing data for job " + rj.getJobId());
ex.printStackTrace();
} catch (Exception ex)
{
- Cache.log.warn(
+ Console.warn(
"Failed to finish parsing data for job " + rj.getJobId());
ex.printStackTrace();
} finally
/**
* alignment panels derived from each alignment set returned by service.
*/
- ArrayList<jalview.gui.AlignmentPanel> destPanels = new ArrayList<>();
+ ArrayList<jalview.gui.AlignmentPanel> destPanels = new ArrayList<jalview.gui.AlignmentPanel>();
/**
* list of instructions for how to process each distinct alignment set
* returned by the job set
*/
- ArrayList<AddDataTo> resultDest = new ArrayList<>();
+ ArrayList<AddDataTo> resultDest = new ArrayList<AddDataTo>();
/**
* when false, zeroth pane is panel derived from input deta.
*/
boolean vsepjobs = restClient.service.isVseparable();
// total number of distinct alignment sets generated by job set.
int numAlSets = 0, als = 0;
- List<AlignmentI> destAls = new ArrayList<>();
- List<jalview.datamodel.HiddenColumns> destColsel = new ArrayList<>();
- List<List<NewickFile>> trees = new ArrayList<>();
+ List<AlignmentI> destAls = new ArrayList<AlignmentI>();
+ List<jalview.datamodel.HiddenColumns> destColsel = new ArrayList<jalview.datamodel.HiddenColumns>();
+ List<List<NewickFile>> trees = new ArrayList<List<NewickFile>>();
do
{
if (alset.trees != null)
{
- trees.add(new ArrayList<>(alset.trees));
+ trees.add(new ArrayList<NewickFile>(alset.trees));
}
else
{
*/
int vrestjob = 0;
// Destination alignments for all result data.
- ArrayList<SequenceGroup> visgrps = new ArrayList<>();
- Hashtable<String, SequenceGroup> groupNames = new Hashtable<>();
+ ArrayList<SequenceGroup> visgrps = new ArrayList<SequenceGroup>();
+ Hashtable<String, SequenceGroup> groupNames = new Hashtable<String, SequenceGroup>();
ArrayList<AlignmentAnnotation> visAlAn = null;
for (nvertsep = 0; nvertsep < nvertseps; nvertsep++)
{
{
// TODO: decide if multiple multiple alignments returned by
// non-vseparable services are allowed.
- Cache.log.warn(
+ Console.warn(
"dealing with multiple alignment products returned by non-vertically separable service.");
}
// recover reference to last alignment created for this rest frame
}
else
{
- Cache.log.warn(
+ Console.warn(
"Couldn't resolve original sequence for new sequence.");
}
}
grass = groupNames.get(alan[nrj][an].groupRef.getName());
if (grass == null)
{
- Cache.log.error(
+ Console.error(
"Couldn't relocate group referemce for group "
+ alan[nrj][an].groupRef.getName());
}
}
if (visAlAn == null)
{
- visAlAn = new ArrayList<>();
+ visAlAn = new ArrayList<AlignmentAnnotation>();
}
AlignmentAnnotation visan = null;
for (AlignmentAnnotation v : visAlAn)
{
// TODO: process each newick file, lifting over sequence refs to
// current alignment, if necessary.
- Cache.log.error(
+ Console.error(
"Tree recovery from restjob not yet implemented.");
}
}
HiddenColumns destcs;
String alTitle = MessageManager
.formatMessage("label.webservice_job_title_on", new String[]
- { restClient.service.details.Action,
- restClient.service.details.Name, restClient.viewTitle });
+ { restClient.service.details.getAction(),
+ restClient.service.details.getName(),
+ restClient.viewTitle });
switch (action)
{
case newAlignment:
*/
public boolean isValid()
{
- ArrayList<String> _warnings = new ArrayList<>();
+ ArrayList<String> _warnings = new ArrayList<String>();
boolean validt = true;
if (jobs != null)
{
*/
package jalview.ws.sifts;
-import java.util.Locale;
-
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
private final static String NEWLINE = System.lineSeparator();
+ private static final boolean GET_STREAM = false;
+ private static final boolean CACHE_FILE = true;
private String curSourceDBRef;
private HashSet<String> curDBRefAccessionIdsString;
+ private boolean doCache = false;
private enum CoordinateSys
{
UNIPROT("UniProt"), PDB("PDBresnum"), PDBe("PDBe");
-
private String name;
private CoordinateSys(String name)
{
NAME_SEC_STRUCTURE("nameSecondaryStructure"),
CODE_SEC_STRUCTURE("codeSecondaryStructure"), ANNOTATION("Annotation");
-
private String code;
private ResidueDetailType(String code)
{
this.pdb = pdb;
this.pdbId = pdb.getId();
- File siftsFile = getSiftsFile(pdbId);
- siftsEntry = parseSIFTs(siftsFile);
+ if (doCache) {
+ File siftsFile = getSiftsFile(pdbId);
+ siftsEntry = parseSIFTs(siftsFile);
+ } else {
+ siftsEntry = parseSIFTSStreamFor(pdbId);
+ }
+ }
+
+ /**
+ * A more streamlined version of SIFT reading that allows for streaming of the data.
+ *
+ * @param pdbId
+ * @return
+ * @throws SiftsException
+ */
+ private static Entry parseSIFTSStreamFor(String pdbId) throws SiftsException
+ {
+ try
+ {
+ InputStream is = (InputStream) downloadSifts(pdbId, GET_STREAM);
+ return parseSIFTs(is);
+ } catch (Exception e)
+ {
+ throw new SiftsException(e.getMessage());
+ }
}
/**
*/
private Entry parseSIFTs(File siftFile) throws SiftsException
{
- try (InputStream in = new FileInputStream(siftFile);
- GZIPInputStream gzis = new GZIPInputStream(in);)
+ try (InputStream in = new FileInputStream(siftFile)) {
+ return parseSIFTs(in);
+ } catch (Exception e)
+ {
+ e.printStackTrace();
+ throw new SiftsException(e.getMessage());
+ }
+ }
+
+ private static Entry parseSIFTs(InputStream in) throws Exception {
+ try (GZIPInputStream gzis = new GZIPInputStream(in);)
{
// System.out.println("File : " + siftFile.getAbsolutePath());
JAXBContext jc = JAXBContext.newInstance("jalview.xml.binding.sifts");
Unmarshaller um = jc.createUnmarshaller();
JAXBElement<Entry> jbe = um.unmarshal(streamReader, Entry.class);
return jbe.getValue();
- } catch (Exception e)
- {
- e.printStackTrace();
- throw new SiftsException(e.getMessage());
}
}
// The line below is required for unit testing... don't comment it out!!!
System.out.println(">>> SIFTS File already downloaded for " + pdbId);
-- if (isFileOlderThanThreshold(siftsFile,
++ if (Platform.isFileOlderThanThreshold(siftsFile,
SiftsSettings.getCacheThresholdInDays()))
{
File oldSiftsFile = new File(siftsFileName + "_old");
}
/**
- * This method enables checking if a cached file has exceeded a certain
- * threshold(in days)
- *
- * @param file
- * the cached file
- * @param noOfDays
- * the threshold in days
- * @return
- */
- public static boolean isFileOlderThanThreshold(File file, int noOfDays)
- {
- Path filePath = file.toPath();
- BasicFileAttributes attr;
- int diffInDays = 0;
- try
- {
- attr = Files.readAttributes(filePath, BasicFileAttributes.class);
- diffInDays = (int) ((new Date().getTime()
- - attr.lastModifiedTime().toMillis())
- / (1000 * 60 * 60 * 24));
- // System.out.println("Diff in days : " + diffInDays);
- } catch (IOException e)
- {
- e.printStackTrace();
- }
- return noOfDays <= diffInDays;
- }
-
- /**
* Download a SIFTs XML file for a given PDB Id from an FTP repository
*
* @param pdbId
*/
public static File downloadSiftsFile(String pdbId)
throws SiftsException, IOException
+ {
+ return (File) downloadSifts(pdbId, CACHE_FILE);
+ }
+
+ /**
+ * Download SIFTs XML with the option to cache a file or to get a stream.
+ *
+ * @param pdbId
+ * @param asFile
+ * @return
+ * @throws IOException
+ */
+ private static Object downloadSifts(String pdbId, boolean asFile) throws IOException
{
+ pdbId = pdbId.toLowerCase(Locale.ROOT);
if (pdbId.contains(".cif"))
{
pdbId = pdbId.replace(".cif", "");
}
String siftFile = pdbId + ".xml.gz";
- String siftsFileFTPURL = SIFTS_FTP_BASE_URL + siftFile;
-
- /*
- * Download the file from URL to either
- * Java: directory of cached downloaded SIFTS files
- * Javascript: temporary 'file' (in-memory cache)
- */
File downloadTo = null;
- if (Platform.isJS())
- {
- downloadTo = File.createTempFile(siftFile, ".xml.gz");
- }
- else
+ if (asFile)
{
downloadTo = new File(
SiftsSettings.getSiftDownloadDirectory() + siftFile);
- File siftsDownloadDir = new File(
- SiftsSettings.getSiftDownloadDirectory());
+ File siftsDownloadDir = new File(SiftsSettings.getSiftDownloadDirectory());
if (!siftsDownloadDir.exists())
{
siftsDownloadDir.mkdirs();
}
}
- // System.out.println(">> Download ftp url : " + siftsFileFTPURL);
- // long now = System.currentTimeMillis();
+ String siftsFileFTPURL = SIFTS_FTP_BASE_URL + siftFile;
URL url = new URL(siftsFileFTPURL);
URLConnection conn = url.openConnection();
- InputStream inputStream = conn.getInputStream();
- FileOutputStream outputStream = new FileOutputStream(downloadTo);
- byte[] buffer = new byte[BUFFER_SIZE];
- int bytesRead = -1;
- while ((bytesRead = inputStream.read(buffer)) != -1)
- {
- outputStream.write(buffer, 0, bytesRead);
- }
- outputStream.close();
- inputStream.close();
- // System.out.println(">>> File downloaded : " + downloadedSiftsFile
- // + " took " + (System.currentTimeMillis() - now) + "ms");
+ InputStream is = conn.getInputStream();
+ if (!asFile)
+ return is;
+ // This is MUCH more efficent in JavaScript, as we already have the bytes
+ Platform.streamToFile(is, downloadTo);
+ is.close();
return downloadTo;
}
.getMapRegion();
for (MapRegion mapRegion : mapRegions)
{
- accessions
- .add(mapRegion.getDb().getDbAccessionId().toLowerCase(Locale.ROOT));
+ accessions.add(mapRegion.getDb().getDbAccessionId()
+ .toLowerCase(Locale.ROOT));
}
}
}
SequenceI seq, java.io.PrintStream os) throws SiftsException
{
List<Integer> omitNonObserved = new ArrayList<>();
- int nonObservedShiftIndex = 0, pdbeNonObserved = 0;
+ int nonObservedShiftIndex = 0,pdbeNonObserved=0;
// System.out.println("Generating mappings for : " + entityId);
Entity entity = null;
entity = getEntityById(entityId);
HashSet<String> dbRefAccessionIdsString = new HashSet<String>();
for (DBRefEntry dbref : seq.getDBRefs())
{
- dbRefAccessionIdsString.add(dbref.getAccessionId().toLowerCase(Locale.ROOT));
+ dbRefAccessionIdsString
+ .add(dbref.getAccessionId().toLowerCase(Locale.ROOT));
}
- dbRefAccessionIdsString.add(sourceDBRef.getAccessionId().toLowerCase(Locale.ROOT));
+ dbRefAccessionIdsString
+ .add(sourceDBRef.getAccessionId().toLowerCase(Locale.ROOT));
curDBRefAccessionIdsString = dbRefAccessionIdsString;
curSourceDBRef = sourceDBRef.getAccessionId();
TreeMap<Integer, String> resNumMap = new TreeMap<Integer, String>();
List<Segment> segments = entity.getSegment();
SegmentHelperPojo shp = new SegmentHelperPojo(seq, mapping, resNumMap,
- omitNonObserved, nonObservedShiftIndex, pdbeNonObserved);
+ omitNonObserved, nonObservedShiftIndex,pdbeNonObserved);
processSegments(segments, shp);
try
{
{
throw new SiftsException("SIFTS mapping failed");
}
- // also construct a mapping object between the seq-coord sys and the PDB
- // seq's coord sys
+ // also construct a mapping object between the seq-coord sys and the PDB seq's coord sys
Integer[] keys = mapping.keySet().toArray(new Integer[0]);
Arrays.sort(keys);
seqStart = keys[0];
seqEnd = keys[keys.length - 1];
- List<int[]> from = new ArrayList<>(), to = new ArrayList<>();
- int[] _cfrom = null, _cto = null;
+ List<int[]> from=new ArrayList<>(),to=new ArrayList<>();
+ int[]_cfrom=null,_cto=null;
String matchedSeq = originalSeq;
- if (seqStart != UNASSIGNED) // fixme! seqStart can map to -1 for a pdb
- // sequence that starts <-1
+ if (seqStart != UNASSIGNED) // fixme! seqStart can map to -1 for a pdb sequence that starts <-1
{
- for (int seqps : keys)
+ for (int seqps:keys)
{
int pdbpos = mapping.get(seqps)[PDBE_POS];
if (pdbpos == UNASSIGNED)
// not correct - pdbpos might be -1, but leave it for now
continue;
}
- if (_cfrom == null || seqps != _cfrom[1] + 1)
+ if (_cfrom==null || seqps!=_cfrom[1]+1)
{
- _cfrom = new int[] { seqps, seqps };
+ _cfrom = new int[] { seqps,seqps};
from.add(_cfrom);
_cto = null; // discontinuity
+ } else {
+ _cfrom[1]= seqps;
}
- else
- {
- _cfrom[1] = seqps;
- }
- if (_cto == null || pdbpos != 1 + _cto[1])
+ if (_cto==null || pdbpos!=1+_cto[1])
{
- _cto = new int[] { pdbpos, pdbpos };
+ _cto = new int[] { pdbpos,pdbpos};
to.add(_cto);
- }
- else
- {
+ } else {
_cto[1] = pdbpos;
}
}
;
seqFromPdbMapping = new jalview.datamodel.Mapping(null, _cto, _cfrom,
- 1, 1);
+ 1,
+ 1);
pdbStart = mapping.get(seqStart)[PDB_RES_POS];
pdbEnd = mapping.get(seqEnd)[PDB_RES_POS];
int orignalSeqStart = seq.getStart();
for (Residue residue : residues)
{
boolean isObserved = isResidueObserved(residue);
- int pdbeIndex = getLeadingIntegerValue(residue.getDbResNum(),
+ int pdbeIndex = Platform.getLeadingIntegerValue(residue.getDbResNum(),
UNASSIGNED);
int currSeqIndex = UNASSIGNED;
List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
pdbRefDb = cRefDb;
if (firstPDBResNum == UNASSIGNED)
{
- firstPDBResNum = getLeadingIntegerValue(cRefDb.getDbResNum(),
+ firstPDBResNum = Platform.getLeadingIntegerValue(cRefDb.getDbResNum(),
UNASSIGNED);
}
else
if (cRefDb.getDbCoordSys().equalsIgnoreCase(seqCoordSys.getName())
&& isAccessionMatched(cRefDb.getDbAccessionId()))
{
- currSeqIndex = getLeadingIntegerValue(cRefDb.getDbResNum(),
+ currSeqIndex = Platform.getLeadingIntegerValue(cRefDb.getDbResNum(),
UNASSIGNED);
if (pdbRefDb != null)
{
}
// if (currSeqIndex >= seq.getStart() && currSeqIndex <= seqlength) //
// true
- // numbering
- // is
- // not
- // up
- // to
- // seq.getEnd()
+ // numbering
+ // is
+ // not
+ // up
+ // to
+ // seq.getEnd()
{
int resNum = (pdbRefDb == null)
- ? getLeadingIntegerValue(residue.getDbResNum(),
+ ? Platform.getLeadingIntegerValue(residue.getDbResNum(),
UNASSIGNED)
- : getLeadingIntegerValue(pdbRefDb.getDbResNum(),
+ : Platform.getLeadingIntegerValue(pdbRefDb.getDbResNum(),
UNASSIGNED);
if (isObserved)
}
/**
- * Get the leading integer part of a string that begins with an integer.
- *
- * @param input
- * - the string input to process
- * @param failValue
- * - value returned if unsuccessful
- * @return
- */
- static int getLeadingIntegerValue(String input, int failValue)
- {
- if (input == null)
- {
- return failValue;
- }
- String[] parts = input.split("(?=\\D)(?<=\\d)");
- if (parts != null && parts.length > 0 && parts[0].matches("[0-9]+"))
- {
- return Integer.valueOf(parts[0]);
- }
- return failValue;
- }
-
- /**
*
* @param chainId
* Target chain to populate mapping of its atom positions.
{
boolean isStrictMatch = true;
return isStrictMatch ? curSourceDBRef.equalsIgnoreCase(accession)
- : curDBRefAccessionIdsString.contains(accession.toLowerCase(Locale.ROOT));
+ : curDBRefAccessionIdsString
+ .contains(accession.toLowerCase(Locale.ROOT));
}
private boolean isFoundInSiftsEntry(String accessionId)
{
return pdbeNonObserved;
}
-
public SequenceI getSeq()
{
return seq;
--- /dev/null
+package jalview.ws.slivkaws;
+
+import jalview.api.FeatureColourI;
+import jalview.bin.Cache;
++import jalview.bin.Console;
+import jalview.datamodel.Alignment;
+import jalview.datamodel.AlignmentAnnotation;
+import jalview.datamodel.SequenceI;
+import jalview.datamodel.features.FeatureMatcherSetI;
+import jalview.io.AnnotationFile;
+import jalview.io.DataSourceType;
+import jalview.io.FeaturesFile;
+import jalview.util.MessageManager;
+import jalview.ws.api.JobId;
+import jalview.ws.api.SequenceAnnotationServiceI;
+import jalview.ws.params.ArgumentI;
+import jalview.ws.params.WsParamSetI;
+import jalview.ws.uimodel.AlignAnalysisUIText;
+
+import java.io.IOError;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+
+import compbio.data.msa.Category;
+import uk.ac.dundee.compbio.slivkaclient.RemoteFile;
+import uk.ac.dundee.compbio.slivkaclient.SlivkaClient;
+import uk.ac.dundee.compbio.slivkaclient.SlivkaService;
+
+public class SlivkaAnnotationServiceInstance extends SlivkaWSInstance implements SequenceAnnotationServiceI
+{
+ public SlivkaAnnotationServiceInstance(SlivkaClient client,
+ SlivkaService service, String category)
+ {
+ super(client, service, category);
+ if (category == Category.CATEGORY_CONSERVATION)
+ {
+ /* FIXME: the category name is hardcoded for AACon, names other than
+ * "AAConWS" doesn't work. */
+ setAlignAnalysisUI(new AlignAnalysisUIText(getName(),
+ SlivkaAnnotationServiceInstance.class,
+ "Slivka.AACons", false, true, true, true, true, 2,
+ MessageManager.getString("label.aacon_calculations"),
+ MessageManager.getString("tooltip.aacon_calculations"),
+ MessageManager.getString("label.aacon_settings"),
+ MessageManager.getString("tooltip.aacon_settings")));
+ }
+ style = ServiceClient.SEQUENCEANNOTATIONWSCLIENT;
+ }
+
+ @Override
+ public JobId submitToService(List<SequenceI> seqs, WsParamSetI preset, List<ArgumentI> paramset) throws Throwable
+ {
+ return super.submit(seqs, preset, paramset);
+ }
+
+ @Override
+ public List<AlignmentAnnotation> getAnnotationResult(JobId jobId,
+ List<SequenceI> seqs, Map<String, FeatureColourI> featureColours,
+ Map<String, FeatureMatcherSetI> featureFilters) throws Throwable
+ {
+ RemoteFile annotFile = null;
+ RemoteFile featFile = null;
+ try
+ {
+ var slivkaJob = client.getJob(jobId.getJobId());
+ Collection<RemoteFile> files = slivkaJob.getResults();
+ for (RemoteFile f : files)
+ {
+ if (f.getMediaType().equals("application/jalview-annotations"))
+ {
+ annotFile = f;
+ }
+ else if (f.getMediaType().equals("application/jalview-features"))
+ {
+ featFile = f;
+ }
+ }
+ } catch (IOException e)
+ {
+ throw new IOError(e);
+ }
+ Alignment aln = new Alignment(seqs.toArray(new SequenceI[0]));
+ if (annotFile == null
+ || !new AnnotationFile().readAnnotationFileWithCalcId(aln, service.getId(), annotFile.getContentUrl().toString(), DataSourceType.URL))
+ {
- Cache.log.debug("No annotation from slivka job\n" + annotFile);
++ Console.debug("No annotation from slivka job\n" + annotFile);
+ }
+ else {
- Cache.log.debug("Annotation file loaded " + annotFile);
++ Console.debug("Annotation file loaded " + annotFile);
+ }
+ if (featFile == null
+ || !new FeaturesFile(featFile.getContentUrl().toString(), DataSourceType.URL).parse(aln, featureColours, true))
+ {
- Cache.log.debug("No features from slivka job\n" + featFile);
++ Console.debug("No features from slivka job\n" + featFile);
+ }
+ else {
- Cache.log.debug("Features feil loaded " + featFile);
++ Console.debug("Features feil loaded " + featFile);
+ }
+ return Arrays.asList(aln.getAlignmentAnnotation());
+ }
+}
--- /dev/null
+package jalview.ws.slivkaws;
+
+import jalview.bin.Cache;
++import jalview.bin.Console;
+import jalview.ws.ServiceChangeListener;
+import jalview.ws.WSDiscovererI;
+import jalview.ws.api.ServiceWithParameters;
+import javajs.http.HttpClientFactory;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.Vector;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArraySet;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import compbio.data.msa.Category;
+import uk.ac.dundee.compbio.slivkaclient.SlivkaClient;
+import uk.ac.dundee.compbio.slivkaclient.SlivkaService;
+
+public class SlivkaWSDiscoverer implements WSDiscovererI
+{
+ private static final String SLIVKA_HOST_URLS = "SLIVKAHOSTURLS";
+
+ private static final String COMPBIO_SLIVKA = "https://www.compbio.dundee.ac.uk/slivka/";
+
+ private static SlivkaWSDiscoverer instance = null;
+
+ private List<ServiceWithParameters> services = List.of();
+
+ private SlivkaWSDiscoverer()
+ {
+ }
+
+ public static SlivkaWSDiscoverer getInstance()
+ {
+ if (instance == null)
+ {
+ instance = new SlivkaWSDiscoverer();
+ }
+ return instance;
+ }
+
+ private Set<ServiceChangeListener> serviceListeners = new CopyOnWriteArraySet<>();
+
+ @Override
+ public void addServiceChangeListener(ServiceChangeListener l)
+ {
+ serviceListeners.add(l);
+ }
+
+ @Override
+ public void removeServiceChangeListener(ServiceChangeListener l)
+ {
+ serviceListeners.remove(l);
+ }
+
+ public void notifyServiceListeners(List<ServiceWithParameters> services)
+ {
+ for (var listener : serviceListeners)
+ {
+ listener.servicesChanged(this, services);
+ }
+ }
+
+ private final ExecutorService executor = Executors
+ .newSingleThreadExecutor();
+
+ private Vector<Future<?>> discoveryTasks = new Vector<>();
+
+ public CompletableFuture<WSDiscovererI> startDiscoverer()
+ {
+ CompletableFuture<WSDiscovererI> task = CompletableFuture
+ .supplyAsync(() -> {
+ reloadServices();
+ return SlivkaWSDiscoverer.this;
+ }, executor);
+ discoveryTasks.add(task);
+ return task;
+ }
+
+ private List<ServiceWithParameters> reloadServices()
+ {
- Cache.log.info("Reloading Slivka services");
++ Console.info("Reloading Slivka services");
+ notifyServiceListeners(Collections.emptyList());
+ ArrayList<ServiceWithParameters> instances = new ArrayList<>();
+
+ for (String url : getServiceUrls())
+ {
+ SlivkaClient client = new SlivkaClient(url);
+
+ List<SlivkaService> services;
+ try
+ {
+ services = client.getServices();
+ } catch (IOException e)
+ {
+ e.printStackTrace();
+ continue;
+ }
+ for (SlivkaService service : services)
+ {
+ SlivkaWSInstance newInstance = null;
+ for (String classifier : service.classifiers)
+ {
+ String[] path = classifier.split("\\s*::\\s*");
+ if (path.length >= 3 && path[0].toLowerCase().equals("operation")
+ && path[1].toLowerCase().equals("analysis"))
+ {
+ switch (path[path.length - 1].toLowerCase())
+ {
+ case "rna secondary structure prediction":
+ newInstance = new RNAalifoldServiceInstance(client,
+ service, "Secondary Structure Prediction");
+ break;
+ case "sequence alignment analysis (conservation)":
+ newInstance = new SlivkaAnnotationServiceInstance(client,
+ service, Category.CATEGORY_CONSERVATION);
+ break;
+ case "protein sequence analysis":
+ newInstance = new SlivkaAnnotationServiceInstance(client,
+ service, Category.CATEGORY_DISORDER);
+ break;
+ case "protein secondary structure prediction":
+ newInstance = new SlivkaAnnotationServiceInstance(client,
+ service, "Secondary Structure Prediction");
+ break;
+ case "multiple sequence alignment":
+ newInstance = new SlivkaMsaServiceInstance(client, service,
+ Category.CATEGORY_ALIGNMENT);
+ break;
+ }
+ }
+ if (newInstance != null)
+ break;
+ }
+ if (newInstance != null)
+ instances.add(newInstance);
+ }
+ }
+
+ services = instances;
- Cache.log.info("Slivka services reloading finished");
++ Console.info("Slivka services reloading finished");
+ notifyServiceListeners(instances);
+ return instances;
+ }
+
+ @Override
+ public List<ServiceWithParameters> getServices()
+ {
+ return services;
+ }
+
+ @Override
+ public boolean hasServices()
+ {
+ return !isRunning() && services.size() > 0;
+ }
+
+ @Override
+ public boolean isRunning()
+ {
+ return !discoveryTasks.stream().allMatch(Future::isDone);
+ }
+
+ @Override
+ public void setServiceUrls(List<String> wsUrls)
+ {
+ if (wsUrls != null && !wsUrls.isEmpty())
+ {
+ Cache.setProperty(SLIVKA_HOST_URLS, String.join(",", wsUrls));
+ }
+ else
+ {
+ Cache.removeProperty(SLIVKA_HOST_URLS);
+ }
+ }
+
+ @Override
+ public List<String> getServiceUrls()
+ {
+ String surls = Cache.getDefault(SLIVKA_HOST_URLS, COMPBIO_SLIVKA);
+ String[] urls = surls.split(",");
+ ArrayList<String> valid = new ArrayList<>(urls.length);
+ for (String url : urls)
+ {
+ try
+ {
+ new URL(url);
+ valid.add(url);
+ } catch (MalformedURLException e)
+ {
- Cache.log.warn("Problem whilst trying to make a URL from '"
++ Console.warn("Problem whilst trying to make a URL from '"
+ + ((url != null) ? url : "<null>") + "'");
- Cache.log.warn(
++ Console.warn(
+ "This was probably due to a malformed comma separated list"
+ + " in the " + SLIVKA_HOST_URLS
+ + " entry of $(HOME)/.jalview_properties)");
- Cache.log.debug("Exception was ", e);
++ Console.debug("Exception was ", e);
+ }
+ }
+ return valid;
+ }
+
+ @Override
+ public boolean testServiceUrl(URL url)
+ {
+ return getServerStatusFor(url.toString()) == STATUS_OK;
+ }
+
+ @Override
+ public int getServerStatusFor(String url)
+ {
+ try
+ {
+ List<?> services = new SlivkaClient(url).getServices();
+ return services.isEmpty() ? STATUS_NO_SERVICES : STATUS_OK;
+ } catch (IOException | org.json.JSONException e)
+ {
- Cache.log.error("Slivka could not retrieve services list", e);
++ Console.error("Slivka could not retrieve services list", e);
+ return STATUS_INVALID;
+ }
+ }
+
+ @Override
+ public String getErrorMessages()
+ {
+ // TODO Auto-generated method stub
+ return "";
+ }
+}
package jalview.ws.utils;
-import jalview.util.Platform;
+
import java.io.File;
-import java.io.FileOutputStream;
import java.io.IOException;
-
-import java.net.URL;
-import java.nio.channels.Channels;
-import java.nio.channels.ReadableByteChannel;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.nio.file.StandardCopyOption;
+import jalview.util.Platform;
public class UrlDownloadClient
{
+ public UrlDownloadClient()
+ {
+
+ }
+
/**
* Download and save a file from a URL
*
public static void download(String urlstring, String outfile)
throws IOException
{
+
- FileOutputStream fos = null;
- ReadableByteChannel rbc = null;
- Path temp = null;
- try
- {
- temp = Files.createTempFile(".jalview_", ".tmp");
-
- URL url = new URL(urlstring);
- rbc = Channels.newChannel(url.openStream());
- fos = new FileOutputStream(temp.toString());
- fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
-
- // copy tempfile to outfile once our download completes
- // incase something goes wrong
- Files.copy(temp, Paths.get(outfile),
- StandardCopyOption.REPLACE_EXISTING);
- } catch (IOException e)
- {
- throw e;
- } finally
- {
- try
- {
- if (fos != null)
- {
- fos.close();
- }
- } catch (IOException e)
- {
- System.out.println(
- "Exception while closing download file output stream: "
- + e.getMessage());
- }
- try
- {
- if (rbc != null)
- {
- rbc.close();
- }
- } catch (IOException e)
- {
- System.out.println("Exception while closing download channel: "
- + e.getMessage());
- }
- try
- {
- if (temp != null)
- {
- Files.deleteIfExists(temp);
- }
- } catch (IOException e)
- {
- System.out.println("Exception while deleting download temp file: "
- + e.getMessage());
- }
- }
+ Platform.download(urlstring, outfile);
+
}
- public static void download(String urlstring, File tempFile)
- throws IOException
+ public static void download(String urlstring, File tempFile) throws IOException
{
if (!Platform.setFileBytes(tempFile, urlstring))
{
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
-import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
* @author JSON.org
* @version 2016-08-15
*/
- public class JSONObject {
- /**
- * JSONObject.NULL is equivalent to the value that JavaScript calls null, whilst
- * Java's null is equivalent to the value that JavaScript calls undefined.
- */
- private static final class Null {
-
- /**
- * There is only intended to be a single instance of the NULL object, so the
- * clone method returns itself.
- *
- * @return NULL.
- */
- @Override
- protected final Object clone() {
- return this;
- }
-
- /**
- * A Null object is equal to the null value and to itself.
- *
- * @param object An object to test for nullness.
- * @return true if the object parameter is the JSONObject.NULL object or null.
- */
- @Override
- public boolean equals(Object object) {
- return object == null || object == this;
- }
-
- /**
- * A Null object is equal to the null value and to itself.
- *
- * @return always returns 0.
- */
- @Override
- public int hashCode() {
- return 0;
- }
-
- /**
- * Get the "null" string value.
- *
- * @return The string "null".
- */
- @Override
- public String toString() {
- return "null";
- }
- }
-
- /**
- * The map where the JSONObject's properties are kept.
- */
- private final Map<String, Object> map;
-
- /**
- * It is sometimes more convenient and less ambiguous to have a
- * <code>NULL</code> object than to use Java's <code>null</code> value.
- * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>.
- * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>.
- */
- public static final Object NULL = new Null();
-
- /**
- * Construct an empty JSONObject.
- */
- public JSONObject() {
- // HashMap is used on purpose to ensure that elements are unordered by
- // the specification.
- // JSON tends to be a portable transfer format to allows the container
- // implementations to rearrange their items for a faster element
- // retrieval based on associative access.
- // Therefore, an implementation mustn't rely on the order of the item.
- this.map = new HashMap<String, Object>();
- }
-
- /**
- * Construct a JSONObject from a subset of another JSONObject. An array of
- * strings is used to identify the keys that should be copied. Missing keys are
- * ignored.
- *
- * @param jo A JSONObject.
- * @param names An array of strings.
- */
- public JSONObject(JSONObject jo, String[] names) {
- this(names.length);
- for (int i = 0; i < names.length; i += 1) {
- try {
- this.putOnce(names[i], jo.opt(names[i]));
- } catch (Exception ignore) {
- }
- }
- }
-
- /**
- * Construct a JSONObject from a JSONTokener.
- *
- * @param x A JSONTokener object containing the source string.
- * @throws JSONException If there is a syntax error in the source string or a
- * duplicated key.
- */
- public JSONObject(JSONTokener x) throws JSONException {
- this();
- char c;
- String key;
-
- if (x.nextClean() != '{') {
- throw x.syntaxError("A JSONObject text must begin with '{'");
- }
- for (;;) {
- c = x.nextClean();
- switch (c) {
- case 0:
- throw x.syntaxError("A JSONObject text must end with '}'");
- case '}':
- return;
- default:
- x.back();
- key = x.nextValue().toString();
- }
-
- // The key is followed by ':'.
-
- c = x.nextClean();
- if (c != ':') {
- throw x.syntaxError("Expected a ':' after a key");
- }
-
- // Use syntaxError(..) to include error location
-
- if (key != null) {
- // Check if key exists
- if (this.opt(key) != null) {
- // key already exists
- throw x.syntaxError("Duplicate key \"" + key + "\"");
- }
- // Only add value if non-null
- Object value = x.nextValue();
- if (value != null) {
- this.put(key, value);
- }
- }
-
- // Pairs are separated by ','.
-
- switch (x.nextClean()) {
- case ';':
- case ',':
- if (x.nextClean() == '}') {
- return;
- }
- x.back();
- break;
- case '}':
- return;
- default:
- throw x.syntaxError("Expected a ',' or '}'");
- }
- }
- }
-
- /**
- * Construct a JSONObject from a Map.
- *
- * @param m A map object that can be used to initialize the contents of the
- * JSONObject.
- * @throws JSONException If a value in the map is non-finite number.
- * @throws NullPointerException If a key in the map is <code>null</code>
- */
- public JSONObject(Map<?, ?> m) {
- if (m == null) {
- this.map = new HashMap<String, Object>();
- } else {
- this.map = new HashMap<String, Object>(m.size());
- for (final Entry<?, ?> e : m.entrySet()) {
- if (e.getKey() == null) {
- throw new NullPointerException("Null key.");
- }
- final Object value = e.getValue();
- if (value != null) {
- this.map.put(String.valueOf(e.getKey()), wrap(value));
- }
- }
- }
- }
-
- /**
- * Construct a JSONObject from an Object using bean getters. It reflects on all
- * of the public methods of the object. For each of the methods with no
- * parameters and a name starting with <code>"get"</code> or <code>"is"</code>
- * followed by an uppercase letter, the method is invoked, and a key and the
- * value returned from the getter method are put into the new JSONObject.
- * <p>
- * The key is formed by removing the <code>"get"</code> or <code>"is"</code>
- * prefix. If the second remaining character is not upper case, then the first
- * character is converted to lower case.
- * <p>
- * Methods that are <code>static</code>, return <code>void</code>, have
- * parameters, or are "bridge" methods, are ignored.
- * <p>
- * For example, if an object has a method named <code>"getName"</code>, and if
- * the result of calling <code>object.getName()</code> is
- * <code>"Larry Fine"</code>, then the JSONObject will contain
- * <code>"name": "Larry Fine"</code>.
- * <p>
- * The {@link JSONPropertyName} annotation can be used on a bean getter to
- * override key name used in the JSONObject. For example, using the object above
- * with the <code>getName</code> method, if we annotated it with:
- *
- * <pre>
- * @JSONPropertyName("FullName")
- * public String getName() {
- * return this.name;
- * }
- * </pre>
- *
- * The resulting JSON object would contain <code>"FullName": "Larry Fine"</code>
- * <p>
- * Similarly, the {@link JSONPropertyName} annotation can be used on non-
- * <code>get</code> and <code>is</code> methods. We can also override key name
- * used in the JSONObject as seen below even though the field would normally be
- * ignored:
- *
- * <pre>
- * @JSONPropertyName("FullName")
- * public String fullName() {
- * return this.name;
- * }
- * </pre>
- *
- * The resulting JSON object would contain <code>"FullName": "Larry Fine"</code>
- * <p>
- * The {@link JSONPropertyIgnore} annotation can be used to force the bean
- * property to not be serialized into JSON. If both {@link JSONPropertyIgnore}
- * and {@link JSONPropertyName} are defined on the same method, a depth
- * comparison is performed and the one closest to the concrete class being
- * serialized is used. If both annotations are at the same level, then the
- * {@link JSONPropertyIgnore} annotation takes precedent and the field is not
- * serialized. For example, the following declaration would prevent the
- * <code>getName</code> method from being serialized:
- *
- * <pre>
- * @JSONPropertyName("FullName")
- * @JSONPropertyIgnore
- * public String getName() {
- * return this.name;
- * }
- * </pre>
- * <p>
- *
- * @param bean An object that has getter methods that should be used to make a
- * JSONObject.
- */
- public JSONObject(Object bean) {
- this();
- this.populateMap(bean);
- }
-
- /**
- * Construct a JSONObject from an Object, using reflection to find the public
- * members. The resulting JSONObject's keys will be the strings from the names
- * array, and the values will be the field values associated with those keys in
- * the object. If a key is not found or not visible, then it will not be copied
- * into the new JSONObject.
- *
- * @param object An object that has fields that should be used to make a
- * JSONObject.
- * @param names An array of strings, the names of the fields to be obtained
- * from the object.
- */
- public JSONObject(Object object, String names[]) {
- this(names.length);
- Class<?> c = object.getClass();
- for (int i = 0; i < names.length; i += 1) {
- String name = names[i];
- try {
- this.putOpt(name, c.getField(name).get(object));
- } catch (Exception ignore) {
- }
- }
- }
-
- /**
- * Construct a JSONObject from a source JSON text string. This is the most
- * commonly used JSONObject constructor.
- *
- * @param source A string beginning with <code>{</code> <small>(left
- * brace)</small> and ending with <code>}</code>
- * <small>(right brace)</small>.
- * @exception JSONException If there is a syntax error in the source string or a
- * duplicated key.
- */
- public JSONObject(String source) throws JSONException {
- this(new JSONTokener(source));
- }
-
- /**
- * Construct a JSONObject from a ResourceBundle.
- *
- * @param baseName The ResourceBundle base name.
- * @param locale The Locale to load the ResourceBundle for.
- * @throws JSONException If any JSONExceptions are detected.
- */
- public JSONObject(String baseName, Locale locale) throws JSONException {
- this();
- ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale,
- Thread.currentThread().getContextClassLoader());
-
- // Iterate through the keys in the bundle.
-
- Enumeration<String> keys = bundle.getKeys();
- while (keys.hasMoreElements()) {
- Object key = keys.nextElement();
- if (key != null) {
-
- // Go through the path, ensuring that there is a nested JSONObject for each
- // segment except the last. Add the value using the last segment's name into
- // the deepest nested JSONObject.
-
- String[] path = ((String) key).split("\\.");
- int last = path.length - 1;
- JSONObject target = this;
- for (int i = 0; i < last; i += 1) {
- String segment = path[i];
- JSONObject nextTarget = target.optJSONObject(segment);
- if (nextTarget == null) {
- nextTarget = new JSONObject();
- target.put(segment, nextTarget);
- }
- target = nextTarget;
- }
- target.put(path[last], bundle.getString((String) key));
- }
- }
- }
-
- /**
- * Constructor to specify an initial capacity of the internal map. Useful for
- * library internal calls where we know, or at least can best guess, how big
- * this JSONObject will be.
- *
- * @param initialCapacity initial capacity of the internal map.
- */
- protected JSONObject(int initialCapacity) {
- this.map = new HashMap<String, Object>(initialCapacity);
- }
-
- /**
- * Accumulate values under a key. It is similar to the put method except that if
- * there is already an object stored under the key then a JSONArray is stored
- * under the key to hold all of the accumulated values. If there is already a
- * JSONArray, then the new value is appended to it. In contrast, the put method
- * replaces the previous value.
- *
- * If only one value is accumulated that is not a JSONArray, then the result
- * will be the same as using put. But if multiple values are accumulated, then
- * the result will be like append.
- *
- * @param key A key string.
- * @param value An object to be accumulated under the key.
- * @return this.
- * @throws JSONException If the value is non-finite number.
- * @throws NullPointerException If the key is <code>null</code>.
- */
- public JSONObject accumulate(String key, Object value) throws JSONException {
- testValidity(value);
- Object object = this.opt(key);
- if (object == null) {
- this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value);
- } else if (object instanceof JSONArray) {
- ((JSONArray) object).put(value);
- } else {
- this.put(key, new JSONArray().put(object).put(value));
- }
- return this;
- }
-
- /**
- * Append values to the array under a key. If the key does not exist in the
- * JSONObject, then the key is put in the JSONObject with its value being a
- * JSONArray containing the value parameter. If the key was already associated
- * with a JSONArray, then the value parameter is appended to it.
- *
- * @param key A key string.
- * @param value An object to be accumulated under the key.
- * @return this.
- * @throws JSONException If the value is non-finite number or if the
- * current value associated with the key is not a
- * JSONArray.
- * @throws NullPointerException If the key is <code>null</code>.
- */
- public JSONObject append(String key, Object value) throws JSONException {
- testValidity(value);
- Object object = this.opt(key);
- if (object == null) {
- this.put(key, new JSONArray().put(value));
- } else if (object instanceof JSONArray) {
- this.put(key, ((JSONArray) object).put(value));
- } else {
- throw new JSONException("JSONObject[" + key + "] is not a JSONArray.");
- }
- return this;
- }
-
- /**
- * Produce a string from a double. The string "null" will be returned if the
- * number is not finite.
- *
- * @param d A double.
- * @return A String.
- */
- public static String doubleToString(double d) {
- if (Double.isInfinite(d) || Double.isNaN(d)) {
- return "null";
- }
-
- // Shave off trailing zeros and decimal point, if possible.
-
- String string = Double.toString(d);
- if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) {
- while (string.endsWith("0")) {
- string = string.substring(0, string.length() - 1);
- }
- if (string.endsWith(".")) {
- string = string.substring(0, string.length() - 1);
- }
- }
- return string;
- }
-
- /**
- * Get the value object associated with a key.
- *
- * @param key A key string.
- * @return The object associated with the key.
- * @throws JSONException if the key is not found.
- */
- public Object get(String key) throws JSONException {
- if (key == null) {
- throw new JSONException("Null key.");
- }
- Object object = this.opt(key);
- if (object == null) {
- throw new JSONException("JSONObject[" + quote(key) + "] not found.");
- }
- return object;
- }
-
- /**
- * Get the enum value associated with a key.
- *
- * @param clazz The type of enum to retrieve.
- * @param key A key string.
- * @return The enum value associated with the key
- * @throws JSONException if the key is not found or if the value cannot be
- * converted to an enum.
- */
- public <E extends Enum<E>> E getEnum(Class<E> clazz, String key) throws JSONException {
- E val = optEnum(clazz, key);
- if (val == null) {
- // JSONException should really take a throwable argument.
- // If it did, I would re-implement this with the Enum.valueOf
- // method and place any thrown exception in the JSONException
- throw new JSONException(
- "JSONObject[" + quote(key) + "] is not an enum of type " + quote(clazz.getSimpleName()) + ".");
- }
- return val;
- }
-
- /**
- * Get the boolean value associated with a key.
- *
- * @param key A key string.
- * @return The truth.
- * @throws JSONException if the value is not a Boolean or the String "true" or
- * "false".
- */
- public boolean getBoolean(String key) throws JSONException {
- Object object = this.get(key);
- if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object).equalsIgnoreCase("false"))) {
- return false;
- } else if (object.equals(Boolean.TRUE)
- || (object instanceof String && ((String) object).equalsIgnoreCase("true"))) {
- return true;
- }
- throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean.");
- }
-
- /**
- * Get the BigInteger value associated with a key.
- *
- * @param key A key string.
- * @return The numeric value.
- * @throws JSONException if the key is not found or if the value cannot be
- * converted to BigInteger.
- */
- public BigInteger getBigInteger(String key) throws JSONException {
- Object object = this.get(key);
- try {
- return new BigInteger(object.toString());
- } catch (Exception e) {
- throw new JSONException("JSONObject[" + quote(key) + "] could not be converted to BigInteger.", e);
- }
- }
-
- /**
- * Get the BigDecimal value associated with a key.
- *
- * @param key A key string.
- * @return The numeric value.
- * @throws JSONException if the key is not found or if the value cannot be
- * converted to BigDecimal.
- */
- public BigDecimal getBigDecimal(String key) throws JSONException {
- Object object = this.get(key);
- if (object instanceof BigDecimal) {
- return (BigDecimal) object;
- }
- try {
- return new BigDecimal(object.toString());
- } catch (Exception e) {
- throw new JSONException("JSONObject[" + quote(key) + "] could not be converted to BigDecimal.", e);
- }
- }
-
- /**
- * Get the double value associated with a key.
- *
- * @param key A key string.
- * @return The numeric value.
- * @throws JSONException if the key is not found or if the value is not a Number
- * object and cannot be converted to a number.
- */
- public double getDouble(String key) throws JSONException {
- Object object = this.get(key);
- try {
- return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble(object.toString());
- } catch (Exception e) {
- throw new JSONException("JSONObject[" + quote(key) + "] is not a number.", e);
- }
- }
-
- /**
- * Get the float value associated with a key.
- *
- * @param key A key string.
- * @return The numeric value.
- * @throws JSONException if the key is not found or if the value is not a Number
- * object and cannot be converted to a number.
- */
- public float getFloat(String key) throws JSONException {
- Object object = this.get(key);
- try {
- return object instanceof Number ? ((Number) object).floatValue() : Float.parseFloat(object.toString());
- } catch (Exception e) {
- throw new JSONException("JSONObject[" + quote(key) + "] is not a number.", e);
- }
- }
-
- /**
- * Get the Number value associated with a key.
- *
- * @param key A key string.
- * @return The numeric value.
- * @throws JSONException if the key is not found or if the value is not a Number
- * object and cannot be converted to a number.
- */
- public Number getNumber(String key) throws JSONException {
- Object object = this.get(key);
- try {
- if (object instanceof Number) {
- return (Number) object;
- }
- return stringToNumber(object.toString());
- } catch (Exception e) {
- throw new JSONException("JSONObject[" + quote(key) + "] is not a number.", e);
- }
- }
-
- /**
- * Get the int value associated with a key.
- *
- * @param key A key string.
- * @return The integer value.
- * @throws JSONException if the key is not found or if the value cannot be
- * converted to an integer.
- */
- public int getInt(String key) throws JSONException {
- Object object = this.get(key);
- try {
- return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object);
- } catch (Exception e) {
- throw new JSONException("JSONObject[" + quote(key) + "] is not an int.", e);
- }
- }
-
- /**
- * Get the JSONArray value associated with a key.
- *
- * @param key A key string.
- * @return A JSONArray which is the value.
- * @throws JSONException if the key is not found or if the value is not a
- * JSONArray.
- */
- public JSONArray getJSONArray(String key) throws JSONException {
- Object object = this.get(key);
- if (object instanceof JSONArray) {
- return (JSONArray) object;
- }
- throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray.");
- }
-
- /**
- * Get the JSONObject value associated with a key.
- *
- * @param key A key string.
- * @return A JSONObject which is the value.
- * @throws JSONException if the key is not found or if the value is not a
- * JSONObject.
- */
- public JSONObject getJSONObject(String key) throws JSONException {
- Object object = this.get(key);
- if (object instanceof JSONObject) {
- return (JSONObject) object;
- }
- throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject.");
- }
-
- /**
- * Get the long value associated with a key.
- *
- * @param key A key string.
- * @return The long value.
- * @throws JSONException if the key is not found or if the value cannot be
- * converted to a long.
- */
- public long getLong(String key) throws JSONException {
- Object object = this.get(key);
- try {
- return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object);
- } catch (Exception e) {
- throw new JSONException("JSONObject[" + quote(key) + "] is not a long.", e);
- }
- }
-
- /**
- * Get an array of field names from a JSONObject.
- *
- * @return An array of field names, or null if there are no names.
- */
- public static String[] getNames(JSONObject jo) {
- if (jo.isEmpty()) {
- return null;
- }
- return jo.keySet().toArray(new String[jo.length()]);
- }
-
- /**
- * Get an array of field names from an Object.
- *
- * @return An array of field names, or null if there are no names.
- */
- public static String[] getNames(Object object) {
- if (object == null) {
- return null;
- }
- Class<?> klass = object.getClass();
- Field[] fields = klass.getFields();
- int length = fields.length;
- if (length == 0) {
- return null;
- }
- String[] names = new String[length];
- for (int i = 0; i < length; i += 1) {
- names[i] = fields[i].getName();
- }
- return names;
- }
-
- /**
- * Get the string associated with a key.
- *
- * @param key A key string.
- * @return A string which is the value.
- * @throws JSONException if there is no string value for the key.
- */
- public String getString(String key) throws JSONException {
- Object object = this.get(key);
- if (object instanceof String) {
- return (String) object;
- }
- throw new JSONException("JSONObject[" + quote(key) + "] not a string.");
- }
-
- /**
- * Determine if the JSONObject contains a specific key.
- *
- * @param key A key string.
- * @return true if the key exists in the JSONObject.
- */
- public boolean has(String key) {
- return this.map.containsKey(key);
- }
-
- /**
- * Increment a property of a JSONObject. If there is no such property, create
- * one with a value of 1. If there is such a property, and if it is an Integer,
- * Long, Double, or Float, then add one to it.
- *
- * @param key A key string.
- * @return this.
- * @throws JSONException If there is already a property with this name that is
- * not an Integer, Long, Double, or Float.
- */
- public JSONObject increment(String key) throws JSONException {
- Object value = this.opt(key);
- if (value == null) {
- this.put(key, 1);
- } else if (value instanceof BigInteger) {
- this.put(key, ((BigInteger) value).add(BigInteger.ONE));
- } else if (value instanceof BigDecimal) {
- this.put(key, ((BigDecimal) value).add(BigDecimal.ONE));
- } else if (value instanceof Integer) {
- this.put(key, ((Integer) value).intValue() + 1);
- } else if (value instanceof Long) {
- this.put(key, ((Long) value).longValue() + 1L);
- } else if (value instanceof Double) {
- this.put(key, ((Double) value).doubleValue() + 1.0d);
- } else if (value instanceof Float) {
- this.put(key, ((Float) value).floatValue() + 1.0f);
- } else {
- throw new JSONException("Unable to increment [" + quote(key) + "].");
- }
- return this;
- }
-
- /**
- * Determine if the value associated with the key is <code>null</code> or if
- * there is no value.
- *
- * @param key A key string.
- * @return true if there is no value associated with the key or if the value is
- * the JSONObject.NULL object.
- */
- public boolean isNull(String key) {
- return JSONObject.NULL.equals(this.opt(key));
- }
-
- /**
- * Get an enumeration of the keys of the JSONObject. Modifying this key Set will
- * also modify the JSONObject. Use with caution.
- *
- * @see Set#iterator()
- *
- * @return An iterator of the keys.
- */
- public Iterator<String> keys() {
- return this.keySet().iterator();
- }
-
- /**
- * Get a set of keys of the JSONObject. Modifying this key Set will also modify
- * the JSONObject. Use with caution.
- *
- * @see Map#keySet()
- *
- * @return A keySet.
- */
- public Set<String> keySet() {
- return this.map.keySet();
- }
-
- /**
- * Get a set of entries of the JSONObject. These are raw values and may not
- * match what is returned by the JSONObject get* and opt* functions. Modifying
- * the returned EntrySet or the Entry objects contained therein will modify the
- * backing JSONObject. This does not return a clone or a read-only view.
- *
- * Use with caution.
- *
- * @see Map#entrySet()
- *
- * @return An Entry Set
- */
- protected Set<Entry<String, Object>> entrySet() {
- return this.map.entrySet();
- }
-
- /**
- * Get the number of keys stored in the JSONObject.
- *
- * @return The number of keys in the JSONObject.
- */
- public int length() {
- return this.map.size();
- }
-
- /**
- * Check if JSONObject is empty.
- *
- * @return true if JSONObject is empty, otherwise false.
- */
- public boolean isEmpty() {
- return map.isEmpty();
- }
-
- /**
- * Produce a JSONArray containing the names of the elements of this JSONObject.
- *
- * @return A JSONArray containing the key strings, or null if the JSONObject is
- * empty.
- */
- public JSONArray names() {
- if (this.map.isEmpty()) {
- return null;
- }
- return new JSONArray(this.map.keySet());
- }
-
- /**
- * Produce a string from a Number.
- *
- * @param number A Number
- * @return A String.
- * @throws JSONException If n is a non-finite number.
- */
- public static String numberToString(Number number) throws JSONException {
- if (number == null) {
- throw new JSONException("Null pointer");
- }
- testValidity(number);
-
- // Shave off trailing zeros and decimal point, if possible.
-
- String string = number.toString();
- if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) {
- while (string.endsWith("0")) {
- string = string.substring(0, string.length() - 1);
- }
- if (string.endsWith(".")) {
- string = string.substring(0, string.length() - 1);
- }
- }
- return string;
- }
-
- /**
- * Get an optional value associated with a key.
- *
- * @param key A key string.
- * @return An object which is the value, or null if there is no value.
- */
- public Object opt(String key) {
- return key == null ? null : this.map.get(key);
- }
-
- /**
- * Get the enum value associated with a key.
- *
- * @param clazz The type of enum to retrieve.
- * @param key A key string.
- * @return The enum value associated with the key or null if not found
- */
- public <E extends Enum<E>> E optEnum(Class<E> clazz, String key) {
- return this.optEnum(clazz, key, null);
- }
-
- /**
- * Get the enum value associated with a key.
- *
- * @param clazz The type of enum to retrieve.
- * @param key A key string.
- * @param defaultValue The default in case the value is not found
- * @return The enum value associated with the key or defaultValue if the value
- * is not found or cannot be assigned to <code>clazz</code>
- */
- public <E extends Enum<E>> E optEnum(Class<E> clazz, String key, E defaultValue) {
- try {
- Object val = this.opt(key);
- if (NULL.equals(val)) {
- return defaultValue;
- }
- if (clazz.isAssignableFrom(val.getClass())) {
- // we just checked it!
- @SuppressWarnings("unchecked")
- E myE = (E) val;
- return myE;
- }
- return Enum.valueOf(clazz, val.toString());
- } catch (IllegalArgumentException e) {
- return defaultValue;
- } catch (NullPointerException e) {
- return defaultValue;
- }
- }
-
- /**
- * Get an optional boolean associated with a key. It returns false if there is
- * no such key, or if the value is not Boolean.TRUE or the String "true".
- *
- * @param key A key string.
- * @return The truth.
- */
- public boolean optBoolean(String key) {
- return this.optBoolean(key, false);
- }
-
- /**
- * Get an optional boolean associated with a key. It returns the defaultValue if
- * there is no such key, or if it is not a Boolean or the String "true" or
- * "false" (case insensitive).
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return The truth.
- */
- public boolean optBoolean(String key, boolean defaultValue) {
- Object val = this.opt(key);
- if (NULL.equals(val)) {
- return defaultValue;
- }
- if (val instanceof Boolean) {
- return ((Boolean) val).booleanValue();
- }
- try {
- // we'll use the get anyway because it does string conversion.
- return this.getBoolean(key);
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
- /**
- * Get an optional BigDecimal associated with a key, or the defaultValue if
- * there is no such key or if its value is not a number. If the value is a
- * string, an attempt will be made to evaluate it as a number.
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return An object which is the value.
- */
- public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) {
- Object val = this.opt(key);
- if (NULL.equals(val)) {
- return defaultValue;
- }
- if (val instanceof BigDecimal) {
- return (BigDecimal) val;
- }
- if (val instanceof BigInteger) {
- return new BigDecimal((BigInteger) val);
- }
- if (val instanceof Double || val instanceof Float) {
- return new BigDecimal(((Number) val).doubleValue());
- }
- if (val instanceof Long || val instanceof Integer || val instanceof Short || val instanceof Byte) {
- return new BigDecimal(((Number) val).longValue());
- }
- // don't check if it's a string in case of unchecked Number subclasses
- try {
- return new BigDecimal(val.toString());
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
- /**
- * Get an optional BigInteger associated with a key, or the defaultValue if
- * there is no such key or if its value is not a number. If the value is a
- * string, an attempt will be made to evaluate it as a number.
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return An object which is the value.
- */
- public BigInteger optBigInteger(String key, BigInteger defaultValue) {
- Object val = this.opt(key);
- if (NULL.equals(val)) {
- return defaultValue;
- }
- if (val instanceof BigInteger) {
- return (BigInteger) val;
- }
- if (val instanceof BigDecimal) {
- return ((BigDecimal) val).toBigInteger();
- }
- if (val instanceof Double || val instanceof Float) {
- return new BigDecimal(((Number) val).doubleValue()).toBigInteger();
- }
- if (val instanceof Long || val instanceof Integer || val instanceof Short || val instanceof Byte) {
- return BigInteger.valueOf(((Number) val).longValue());
- }
- // don't check if it's a string in case of unchecked Number subclasses
- try {
- // the other opt functions handle implicit conversions, i.e.
- // jo.put("double",1.1d);
- // jo.optInt("double"); -- will return 1, not an error
- // this conversion to BigDecimal then to BigInteger is to maintain
- // that type cast support that may truncate the decimal.
- final String valStr = val.toString();
- if (isDecimalNotation(valStr)) {
- return new BigDecimal(valStr).toBigInteger();
- }
- return new BigInteger(valStr);
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
- /**
- * Get an optional double associated with a key, or NaN if there is no such key
- * or if its value is not a number. If the value is a string, an attempt will be
- * made to evaluate it as a number.
- *
- * @param key A string which is the key.
- * @return An object which is the value.
- */
- public double optDouble(String key) {
- return this.optDouble(key, Double.NaN);
- }
-
- /**
- * Get an optional double associated with a key, or the defaultValue if there is
- * no such key or if its value is not a number. If the value is a string, an
- * attempt will be made to evaluate it as a number.
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return An object which is the value.
- */
- public double optDouble(String key, double defaultValue) {
- Object val = this.opt(key);
- if (NULL.equals(val)) {
- return defaultValue;
- }
- if (val instanceof Number) {
- return ((Number) val).doubleValue();
- }
- if (val instanceof String) {
- try {
- return Double.parseDouble((String) val);
- } catch (Exception e) {
- return defaultValue;
- }
- }
- return defaultValue;
- }
-
- /**
- * Get the optional double value associated with an index. NaN is returned if
- * there is no value for the index, or if the value is not a number and cannot
- * be converted to a number.
- *
- * @param key A key string.
- * @return The value.
- */
- public float optFloat(String key) {
- return this.optFloat(key, Float.NaN);
- }
-
- /**
- * Get the optional double value associated with an index. The defaultValue is
- * returned if there is no value for the index, or if the value is not a number
- * and cannot be converted to a number.
- *
- * @param key A key string.
- * @param defaultValue The default value.
- * @return The value.
- */
- public float optFloat(String key, float defaultValue) {
- Object val = this.opt(key);
- if (JSONObject.NULL.equals(val)) {
- return defaultValue;
- }
- if (val instanceof Number) {
- return ((Number) val).floatValue();
- }
- if (val instanceof String) {
- try {
- return Float.parseFloat((String) val);
- } catch (Exception e) {
- return defaultValue;
- }
- }
- return defaultValue;
- }
-
- /**
- * Get an optional int value associated with a key, or zero if there is no such
- * key or if the value is not a number. If the value is a string, an attempt
- * will be made to evaluate it as a number.
- *
- * @param key A key string.
- * @return An object which is the value.
- */
- public int optInt(String key) {
- return this.optInt(key, 0);
- }
-
- /**
- * Get an optional int value associated with a key, or the default if there is
- * no such key or if the value is not a number. If the value is a string, an
- * attempt will be made to evaluate it as a number.
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return An object which is the value.
- */
- public int optInt(String key, int defaultValue) {
- Object val = this.opt(key);
- if (NULL.equals(val)) {
- return defaultValue;
- }
- if (val instanceof Number) {
- return ((Number) val).intValue();
- }
-
- if (val instanceof String) {
- try {
- return new BigDecimal((String) val).intValue();
- } catch (Exception e) {
- return defaultValue;
- }
- }
- return defaultValue;
- }
-
- /**
- * Get an optional JSONArray associated with a key. It returns null if there is
- * no such key, or if its value is not a JSONArray.
- *
- * @param key A key string.
- * @return A JSONArray which is the value.
- */
- public JSONArray optJSONArray(String key) {
- Object o = this.opt(key);
- return o instanceof JSONArray ? (JSONArray) o : null;
- }
-
- /**
- * Get an optional JSONObject associated with a key. It returns null if there is
- * no such key, or if its value is not a JSONObject.
- *
- * @param key A key string.
- * @return A JSONObject which is the value.
- */
- public JSONObject optJSONObject(String key) {
- Object object = this.opt(key);
- return object instanceof JSONObject ? (JSONObject) object : null;
- }
-
- /**
- * Get an optional long value associated with a key, or zero if there is no such
- * key or if the value is not a number. If the value is a string, an attempt
- * will be made to evaluate it as a number.
- *
- * @param key A key string.
- * @return An object which is the value.
- */
- public long optLong(String key) {
- return this.optLong(key, 0);
- }
-
- /**
- * Get an optional long value associated with a key, or the default if there is
- * no such key or if the value is not a number. If the value is a string, an
- * attempt will be made to evaluate it as a number.
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return An object which is the value.
- */
- public long optLong(String key, long defaultValue) {
- Object val = this.opt(key);
- if (NULL.equals(val)) {
- return defaultValue;
- }
- if (val instanceof Number) {
- return ((Number) val).longValue();
- }
-
- if (val instanceof String) {
- try {
- return new BigDecimal((String) val).longValue();
- } catch (Exception e) {
- return defaultValue;
- }
- }
- return defaultValue;
- }
-
- /**
- * Get an optional {@link Number} value associated with a key, or
- * <code>null</code> if there is no such key or if the value is not a number. If
- * the value is a string, an attempt will be made to evaluate it as a number
- * ({@link BigDecimal}). This method would be used in cases where type coercion
- * of the number value is unwanted.
- *
- * @param key A key string.
- * @return An object which is the value.
- */
- public Number optNumber(String key) {
- return this.optNumber(key, null);
- }
-
- /**
- * Get an optional {@link Number} value associated with a key, or the default if
- * there is no such key or if the value is not a number. If the value is a
- * string, an attempt will be made to evaluate it as a number. This method would
- * be used in cases where type coercion of the number value is unwanted.
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return An object which is the value.
- */
- public Number optNumber(String key, Number defaultValue) {
- Object val = this.opt(key);
- if (NULL.equals(val)) {
- return defaultValue;
- }
- if (val instanceof Number) {
- return (Number) val;
- }
-
- if (val instanceof String) {
- try {
- return stringToNumber((String) val);
- } catch (Exception e) {
- return defaultValue;
- }
- }
- return defaultValue;
- }
-
- /**
- * Get an optional string associated with a key. It returns an empty string if
- * there is no such key. If the value is not a string and is not null, then it
- * is converted to a string.
- *
- * @param key A key string.
- * @return A string which is the value.
- */
- public String optString(String key) {
- return this.optString(key, "");
- }
-
- /**
- * Get an optional string associated with a key. It returns the defaultValue if
- * there is no such key.
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return A string which is the value.
- */
- public String optString(String key, String defaultValue) {
- Object object = this.opt(key);
- return NULL.equals(object) ? defaultValue : object.toString();
- }
-
- /**
- * Populates the internal map of the JSONObject with the bean properties. The
- * bean can not be recursive.
- *
- * @see JSONObject#JSONObject(Object)
- *
- * @param bean the bean
- */
- private void populateMap(Object bean) {
- Class<?> klass = bean.getClass();
-
- // If klass is a System class then set includeSuperClass to false.
-
- boolean includeSuperClass = klass.getClassLoader() != null;
-
- Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods();
- for (final Method method : methods) {
- final int modifiers = method.getModifiers();
- if (Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) && method.getParameterTypes().length == 0
- && !method.isBridge() && method.getReturnType() != Void.TYPE
- && isValidMethodName(method.getName())) {
- final String key = getKeyNameFromMethod(method);
- if (key != null && !key.isEmpty()) {
- try {
- final Object result = method.invoke(bean);
- if (result != null) {
- this.map.put(key, wrap(result));
- // we don't use the result anywhere outside of wrap
- // if it's a resource we should be sure to close it
- // after calling toString
- if (result instanceof Closeable) {
- try {
- ((Closeable) result).close();
- } catch (IOException ignore) {
- }
- }
- }
- } catch (IllegalAccessException ignore) {
- } catch (IllegalArgumentException ignore) {
- } catch (InvocationTargetException ignore) {
- }
- }
- }
- }
- }
-
- private boolean isValidMethodName(String name) {
- return !"getClass".equals(name) && !"getDeclaringClass".equals(name);
- }
-
- private String getKeyNameFromMethod(Method method) {
- final int ignoreDepth = -1;// getAnnotationDepth(method, JSONPropertyIgnore.class);
- // if (ignoreDepth > 0) {
- // final int forcedNameDepth = getAnnotationDepth(method, JSONPropertyName.class);
- // if (forcedNameDepth < 0 || ignoreDepth <= forcedNameDepth) {
- // // the hierarchy asked to ignore, and the nearest name override
- // // was higher or non-existent
- // return null;
- // }
- // }
- // JSONPropertyName annotation = getAnnotation(method, JSONPropertyName.class);
- // if (annotation != null && annotation.value() != null && !annotation.value().isEmpty()) {
- // return annotation.value();
- // }
- String key;
- final String name = method.getName();
- if (name.startsWith("get") && name.length() > 3) {
- key = name.substring(3);
- } else if (name.startsWith("is") && name.length() > 2) {
- key = name.substring(2);
- } else {
- return null;
- }
- // if the first letter in the key is not uppercase, then skip.
- // This is to maintain backwards compatibility before PR406
- // (https://github.com/stleary/JSON-java/pull/406/)
- if (Character.isLowerCase(key.charAt(0))) {
- return null;
- }
- if (key.length() == 1) {
- key = key.toLowerCase(Locale.ROOT);
- } else if (!Character.isUpperCase(key.charAt(1))) {
- key = key.substring(0, 1).toLowerCase(Locale.ROOT) + key.substring(1);
- }
- return (/** @j2sNative 1 ? key.split("$")[0] : */
- key);
- }
-
- // /**
- // * Searches the class hierarchy to see if the method or it's super
- // * implementations and interfaces has the annotation.
- // *
- // * @param <A>
- // * type of the annotation
- // *
- // * @param m
- // * method to check
- // * @param annotationClass
- // * annotation to look for
- // * @return the {@link Annotation} if the annotation exists on the current method
- // * or one of it's super class definitions
- // */
- // private static <A extends Annotation> A getAnnotation(final Method m, final Class<A> annotationClass) {
- // return null;
- // // if we have invalid data the result is null
- // if (true || m == null || annotationClass == null) {
- // return null;
- // }
- //
- // if (m.isAnnotationPresent(annotationClass)) {
- // return m.getAnnotation(annotationClass);
- // }
- //
- // // if we've already reached the Object class, return null;
- // Class<?> c = m.getDeclaringClass();
- // if (c.getSuperclass() == null) {
- // return null;
- // }
- //
- // // check directly implemented interfaces for the method being checked
- // for (Class<?> i : c.getInterfaces()) {
- // try {
- // Method im = i.getMethod(m.getName(), m.getParameterTypes());
- // return getAnnotation(im, annotationClass);
- // } catch (final SecurityException ex) {
- // continue;
- // } catch (final NoSuchMethodException ex) {
- // continue;
- // }
- // }
- //
- // try {
- // return getAnnotation(
- // c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()),
- // annotationClass);
- // } catch (final SecurityException ex) {
- // return null;
- // } catch (final NoSuchMethodException ex) {
- // return null;
- // }
- // }
- //
- // /**
- // * Searches the class hierarchy to see if the method or it's super
- // * implementations and interfaces has the annotation. Returns the depth of the
- // * annotation in the hierarchy.
- // *
- // * @param <A>
- // * type of the annotation
- // *
- // * @param m
- // * method to check
- // * @param annotationClass
- // * annotation to look for
- // * @return Depth of the annotation or -1 if the annotation is not on the method.
- // */
- // private static int getAnnotationDepth(final Method m, final Class<? extends Annotation> annotationClass) {
- // // if we have invalid data the result is -1
- // if (m == null || annotationClass == null) {
- // return -1;
- // }
- // if (m.isAnnotationPresent(annotationClass)) {
- // return 1;
- // }
- //
- // // if we've already reached the Object class, return -1;
- // Class<?> c = m.getDeclaringClass();
- // if (c.getSuperclass() == null) {
- // return -1;
- // }
- //
- // // check directly implemented interfaces for the method being checked
- // for (Class<?> i : c.getInterfaces()) {
- // try {
- // Method im = i.getMethod(m.getName(), m.getParameterTypes());
- // int d = getAnnotationDepth(im, annotationClass);
- // if (d > 0) {
- // // since the annotation was on the interface, add 1
- // return d + 1;
- // }
- // } catch (final SecurityException ex) {
- // continue;
- // } catch (final NoSuchMethodException ex) {
- // continue;
- // }
- // }
- //
- // try {
- // int d = getAnnotationDepth(
- // c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()),
- // annotationClass);
- // if (d > 0) {
- // // since the annotation was on the superclass, add 1
- // return d + 1;
- // }
- // return -1;
- // } catch (final SecurityException ex) {
- // return -1;
- // } catch (final NoSuchMethodException ex) {
- // return -1;
- // }
- // }
-
- /**
- * Put a key/boolean pair in the JSONObject.
- *
- * @param key A key string.
- * @param value A boolean which is the value.
- * @return this.
- * @throws JSONException If the value is non-finite number.
- * @throws NullPointerException If the key is <code>null</code>.
- */
- public JSONObject put(String key, boolean value) throws JSONException {
- return this.put(key, value ? Boolean.TRUE : Boolean.FALSE);
- }
-
- /**
- * Put a key/value pair in the JSONObject, where the value will be a JSONArray
- * which is produced from a Collection.
- *
- * @param key A key string.
- * @param value A Collection value.
- * @return this.
- * @throws JSONException If the value is non-finite number.
- * @throws NullPointerException If the key is <code>null</code>.
- */
- public JSONObject put(String key, Collection<?> value) throws JSONException {
- return this.put(key, new JSONArray(value));
- }
-
- /**
- * Put a key/double pair in the JSONObject.
- *
- * @param key A key string.
- * @param value A double which is the value.
- * @return this.
- * @throws JSONException If the value is non-finite number.
- * @throws NullPointerException If the key is <code>null</code>.
- */
- public JSONObject put(String key, double value) throws JSONException {
- return this.put(key, Double.valueOf(value));
- }
-
- /**
- * Put a key/float pair in the JSONObject.
- *
- * @param key A key string.
- * @param value A float which is the value.
- * @return this.
- * @throws JSONException If the value is non-finite number.
- * @throws NullPointerException If the key is <code>null</code>.
- */
- public JSONObject put(String key, float value) throws JSONException {
- return this.put(key, Float.valueOf(value));
- }
-
- /**
- * Put a key/int pair in the JSONObject.
- *
- * @param key A key string.
- * @param value An int which is the value.
- * @return this.
- * @throws JSONException If the value is non-finite number.
- * @throws NullPointerException If the key is <code>null</code>.
- */
- public JSONObject put(String key, int value) throws JSONException {
- return this.put(key, Integer.valueOf(value));
- }
-
- /**
- * Put a key/long pair in the JSONObject.
- *
- * @param key A key string.
- * @param value A long which is the value.
- * @return this.
- * @throws JSONException If the value is non-finite number.
- * @throws NullPointerException If the key is <code>null</code>.
- */
- public JSONObject put(String key, long value) throws JSONException {
- return this.put(key, Long.valueOf(value));
- }
-
- /**
- * Put a key/value pair in the JSONObject, where the value will be a JSONObject
- * which is produced from a Map.
- *
- * @param key A key string.
- * @param value A Map value.
- * @return this.
- * @throws JSONException If the value is non-finite number.
- * @throws NullPointerException If the key is <code>null</code>.
- */
- public JSONObject put(String key, Map<?, ?> value) throws JSONException {
- return this.put(key, new JSONObject(value));
- }
-
- /**
- * Put a key/value pair in the JSONObject. If the value is <code>null</code>,
- * then the key will be removed from the JSONObject if it is present.
- *
- * @param key A key string.
- * @param value An object which is the value. It should be of one of these
- * types: Boolean, Double, Integer, JSONArray, JSONObject, Long,
- * String, or the JSONObject.NULL object.
- * @return this.
- * @throws JSONException If the value is non-finite number.
- * @throws NullPointerException If the key is <code>null</code>.
- */
- public JSONObject put(String key, Object value) throws JSONException {
- if (key == null) {
- throw new NullPointerException("Null key.");
- }
- if (value != null) {
- testValidity(value);
- this.map.put(key, value);
- } else {
- this.remove(key);
- }
- return this;
- }
-
- /**
- * Put a key/value pair in the JSONObject, but only if the key and the value are
- * both non-null, and only if there is not already a member with that name.
- *
- * @param key string
- * @param value object
- * @return this.
- * @throws JSONException if the key is a duplicate
- */
- public JSONObject putOnce(String key, Object value) throws JSONException {
- if (key != null && value != null) {
- if (this.opt(key) != null) {
- throw new JSONException("Duplicate key \"" + key + "\"");
- }
- return this.put(key, value);
- }
- return this;
- }
-
- /**
- * Put a key/value pair in the JSONObject, but only if the key and the value are
- * both non-null.
- *
- * @param key A key string.
- * @param value An object which is the value. It should be of one of these
- * types: Boolean, Double, Integer, JSONArray, JSONObject, Long,
- * String, or the JSONObject.NULL object.
- * @return this.
- * @throws JSONException If the value is a non-finite number.
- */
- public JSONObject putOpt(String key, Object value) throws JSONException {
- if (key != null && value != null) {
- return this.put(key, value);
- }
- return this;
- }
-
- /**
- * Creates a JSONPointer using an initialization string and tries to match it to
- * an item within this JSONObject. For example, given a JSONObject initialized
- * with this document:
- *
- * <pre>
- * {
- * "a":{"b":"c"}
- * }
- * </pre>
- *
- * and this JSONPointer string:
- *
- * <pre>
- * "/a/b"
- * </pre>
- *
- * Then this method will return the String "c". A JSONPointerException may be
- * thrown from code called by this method.
- *
- * @param jsonPointer string that can be used to create a JSONPointer
- * @return the item matched by the JSONPointer, otherwise null
- */
- public Object query(String jsonPointer) {
- return query(new JSONPointer(jsonPointer));
- }
-
- /**
- * Uses a user initialized JSONPointer and tries to match it to an item within
- * this JSONObject. For example, given a JSONObject initialized with this
- * document:
- *
- * <pre>
- * {
- * "a":{"b":"c"}
- * }
- * </pre>
- *
- * and this JSONPointer:
- *
- * <pre>
- * "/a/b"
- * </pre>
- *
- * Then this method will return the String "c". A JSONPointerException may be
- * thrown from code called by this method.
- *
- * @param jsonPointer string that can be used to create a JSONPointer
- * @return the item matched by the JSONPointer, otherwise null
- */
- public Object query(JSONPointer jsonPointer) {
- return jsonPointer.queryFrom(this);
- }
-
- /**
- * Queries and returns a value from this object using {@code jsonPointer}, or
- * returns null if the query fails due to a missing key.
- *
- * @param jsonPointer the string representation of the JSON pointer
- * @return the queried value or {@code null}
- * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax
- */
- public Object optQuery(String jsonPointer) {
- return optQuery(new JSONPointer(jsonPointer));
- }
-
- /**
- * Queries and returns a value from this object using {@code jsonPointer}, or
- * returns null if the query fails due to a missing key.
- *
- * @param jsonPointer The JSON pointer
- * @return the queried value or {@code null}
- * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax
- */
- public Object optQuery(JSONPointer jsonPointer) {
- try {
- return jsonPointer.queryFrom(this);
- } catch (JSONPointerException e) {
- return null;
- }
- }
-
- /**
- * Produce a string in double quotes with backslash sequences in all the right
- * places. A backslash will be inserted within </, producing <\/, allowing JSON
- * text to be delivered in HTML. In JSON text, a string cannot contain a control
- * character or an unescaped quote or backslash.
- *
- * @param string A String
- * @return A String correctly formatted for insertion in a JSON text.
- */
- public static String quote(String string) {
- StringWriter sw = new StringWriter();
- synchronized (sw.getBuffer()) {
- try {
- return quote(string, sw).toString();
- } catch (IOException ignored) {
- // will never happen - we are writing to a string writer
- return "";
- }
- }
- }
-
- public static Writer quote(String string, Writer w) throws IOException {
- if (string == null || string.isEmpty()) {
- w.write("\"\"");
- return w;
- }
-
- char b;
- char c = 0;
- String hhhh;
- int i;
- int len = string.length();
-
- w.write('"');
- for (i = 0; i < len; i += 1) {
- b = c;
- c = string.charAt(i);
- switch (c) {
- case '\\':
- case '"':
- w.write('\\');
- w.write(c);
- break;
- case '/':
- if (b == '<') {
- w.write('\\');
- }
- w.write(c);
- break;
- case '\b':
- w.write("\\b");
- break;
- case '\t':
- w.write("\\t");
- break;
- case '\n':
- w.write("\\n");
- break;
- case '\f':
- w.write("\\f");
- break;
- case '\r':
- w.write("\\r");
- break;
- default:
- if (c < ' ' || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) {
- w.write("\\u");
- hhhh = Integer.toHexString(c);
- w.write("0000", 0, 4 - hhhh.length());
- w.write(hhhh);
- } else {
- w.write(c);
- }
- }
- }
- w.write('"');
- return w;
- }
-
- /**
- * Remove a name and its value, if present.
- *
- * @param key The name to be removed.
- * @return The value that was associated with the name, or null if there was no
- * value.
- */
- public Object remove(String key) {
- return this.map.remove(key);
- }
-
- /**
- * Determine if two JSONObjects are similar. They must contain the same set of
- * names which must be associated with similar values.
- *
- * @param other The other JSONObject
- * @return true if they are equal
- */
- public boolean similar(Object other) {
- try {
- if (!(other instanceof JSONObject)) {
- return false;
- }
- if (!this.keySet().equals(((JSONObject) other).keySet())) {
- return false;
- }
- for (final Entry<String, ?> entry : this.entrySet()) {
- String name = entry.getKey();
- Object valueThis = entry.getValue();
- Object valueOther = ((JSONObject) other).get(name);
- if (valueThis == valueOther) {
- continue;
- }
- if (valueThis == null) {
- return false;
- }
- if (valueThis instanceof JSONObject) {
- if (!((JSONObject) valueThis).similar(valueOther)) {
- return false;
- }
- } else if (valueThis instanceof JSONArray) {
- if (!((JSONArray) valueThis).similar(valueOther)) {
- return false;
- }
- } else if (!valueThis.equals(valueOther)) {
- return false;
- }
- }
- return true;
- } catch (Throwable exception) {
- return false;
- }
- }
-
- /**
- * Tests if the value should be tried as a decimal. It makes no test if there
- * are actual digits.
- *
- * @param val value to test
- * @return true if the string is "-0" or if it contains '.', 'e', or 'E', false
- * otherwise.
- */
- protected static boolean isDecimalNotation(final String val) {
- return val.indexOf('.') > -1 || val.indexOf('e') > -1 || val.indexOf('E') > -1 || "-0".equals(val);
- }
-
- /**
- * Converts a string to a number using the narrowest possible type. Possible
- * returns for this function are BigDecimal, Double, BigInteger, Long, and
- * Integer. When a Double is returned, it should always be a valid Double and
- * not NaN or +-infinity.
- *
- * @param val value to convert
- * @return Number representation of the value.
- * @throws NumberFormatException thrown if the value is not a valid number. A
- * public caller should catch this and wrap it in
- * a {@link JSONException} if applicable.
- */
- protected static Number stringToNumber(final String val) throws NumberFormatException {
- char initial = val.charAt(0);
- if ((initial >= '0' && initial <= '9') || initial == '-') {
- // decimal representation
- if (isDecimalNotation(val)) {
- // quick dirty way to see if we need a BigDecimal instead of a Double
- // this only handles some cases of overflow or underflow
- if (val.length() > 14) {
- return new BigDecimal(val);
- }
- final Double d = Double.valueOf(val);
- if (d.isInfinite() || d.isNaN()) {
- // if we can't parse it as a double, go up to BigDecimal
- // this is probably due to underflow like 4.32e-678
- // or overflow like 4.65e5324. The size of the string is small
- // but can't be held in a Double.
- return new BigDecimal(val);
- }
- return d;
- }
- // integer representation.
- // This will narrow any values to the smallest reasonable Object representation
- // (Integer, Long, or BigInteger)
-
- // string version
- // The compare string length method reduces GC,
- // but leads to smaller integers being placed in larger wrappers even though not
- // needed. i.e. 1,000,000,000 -> Long even though it's an Integer
- // 1,000,000,000,000,000,000 -> BigInteger even though it's a Long
- // if(val.length()<=9){
- // return Integer.valueOf(val);
- // }
- // if(val.length()<=18){
- // return Long.valueOf(val);
- // }
- // return new BigInteger(val);
-
- // BigInteger version: We use a similar bitLenth compare as
- // BigInteger#intValueExact uses. Increases GC, but objects hold
- // only what they need. i.e. Less runtime overhead if the value is
- // long lived. Which is the better tradeoff? This is closer to what's
- // in stringToValue.
- BigInteger bi = new BigInteger(val);
- if (bi.bitLength() <= 31) {
- return Integer.valueOf(bi.intValue());
- }
- if (bi.bitLength() <= 63) {
- return Long.valueOf(bi.longValue());
- }
- return bi;
- }
- throw new NumberFormatException("val [" + val + "] is not a valid number.");
- }
-
- /**
- * Try to convert a string into a number, boolean, or null. If the string can't
- * be converted, return the string.
- *
- * @param string A String.
- * @return A simple JSON value.
- */
- // Changes to this method must be copied to the corresponding method in
- // the XML class to keep full support for Android
- public static Object stringToValue(String string) {
- if (string.equals("")) {
- return string;
- }
- if (string.equalsIgnoreCase("true")) {
- return Boolean.TRUE;
- }
- if (string.equalsIgnoreCase("false")) {
- return Boolean.FALSE;
- }
- if (string.equalsIgnoreCase("null")) {
- return JSONObject.NULL;
- }
-
- /*
- * If it might be a number, try converting it. If a number cannot be produced,
- * then the value will just be a string.
- */
-
- char initial = string.charAt(0);
- if ((initial >= '0' && initial <= '9') || initial == '-') {
- try {
- // if we want full Big Number support this block can be replaced with:
- // return stringToNumber(string);
- if (isDecimalNotation(string)) {
- Double d = Double.valueOf(string);
- if (!d.isInfinite() && !d.isNaN()) {
- return d;
- }
- } else {
- Long myLong = Long.valueOf(string);
- if (string.equals(myLong.toString())) {
- if (myLong.longValue() == myLong.intValue()) {
- return Integer.valueOf(myLong.intValue());
- }
- return myLong;
- }
- }
- } catch (Exception ignore) {
- }
- }
- return string;
- }
-
- /**
- * Throw an exception if the object is a NaN or infinite number.
- *
- * @param o The object to test.
- * @throws JSONException If o is a non-finite number.
- */
- public static void testValidity(Object o) throws JSONException {
- if (o != null) {
- if (o instanceof Double) {
- if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
- throw new JSONException("JSON does not allow non-finite numbers.");
- }
- } else if (o instanceof Float) {
- if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
- throw new JSONException("JSON does not allow non-finite numbers.");
- }
- }
- }
- }
-
- /**
- * Produce a JSONArray containing the values of the members of this JSONObject.
- *
- * @param names A JSONArray containing a list of key strings. This determines
- * the sequence of the values in the result.
- * @return A JSONArray of values.
- * @throws JSONException If any of the values are non-finite numbers.
- */
- public JSONArray toJSONArray(JSONArray names) throws JSONException {
- if (names == null || names.isEmpty()) {
- return null;
- }
- JSONArray ja = new JSONArray();
- for (int i = 0; i < names.length(); i += 1) {
- ja.put(this.opt(names.getString(i)));
- }
- return ja;
- }
-
- /**
- * Make a JSON text of this JSONObject. For compactness, no whitespace is added.
- * If this would not result in a syntactically correct JSON text, then null will
- * be returned instead.
- * <p>
- * <b> Warning: This method assumes that the data structure is acyclical. </b>
- *
- * @return a printable, displayable, portable, transmittable representation of
- * the object, beginning with <code>{</code> <small>(left
- * brace)</small> and ending with <code>}</code> <small>(right
- * brace)</small>.
- */
- @Override
- public String toString() {
- try {
- return this.toString(0);
- } catch (Exception e) {
- return null;
- }
- }
-
- /**
- * Make a pretty-printed JSON text of this JSONObject.
- *
- * <p>
- * If <code>indentFactor > 0</code> and the {@link JSONObject} has only one key,
- * then the object will be output on a single line:
- *
- * <pre>
- * {@code {"key": 1}}
- * </pre>
- *
- * <p>
- * If an object has 2 or more keys, then it will be output across multiple
- * lines: <code><pre>{
- * "key1": 1,
- * "key2": "value 2",
- * "key3": 3
- * }</pre></code>
- * <p>
- * <b> Warning: This method assumes that the data structure is acyclical. </b>
- *
- * @param indentFactor The number of spaces to add to each level of indentation.
- * @return a printable, displayable, portable, transmittable representation of
- * the object, beginning with <code>{</code> <small>(left
- * brace)</small> and ending with <code>}</code> <small>(right
- * brace)</small>.
- * @throws JSONException If the object contains an invalid number.
- */
- public String toString(int indentFactor) throws JSONException {
- StringWriter w = new StringWriter();
- synchronized (w.getBuffer()) {
- return this.write(w, indentFactor, 0).toString();
- }
- }
-
- /**
- * Make a JSON text of an Object value. If the object has an
- * value.toJSONString() method, then that method will be used to produce the
- * JSON text. The method is required to produce a strictly conforming text. If
- * the object does not contain a toJSONString method (which is the most common
- * case), then a text will be produced by other means. If the value is an array
- * or Collection, then a JSONArray will be made from it and its toJSONString
- * method will be called. If the value is a MAP, then a JSONObject will be made
- * from it and its toJSONString method will be called. Otherwise, the value's
- * toString method will be called, and the result will be quoted.
- *
- * <p>
- * Warning: This method assumes that the data structure is acyclical.
- *
- * @param value The value to be serialized.
- * @return a printable, displayable, transmittable representation of the object,
- * beginning with <code>{</code> <small>(left brace)</small> and
- * ending with <code>}</code> <small>(right brace)</small>.
- * @throws JSONException If the value is or contains an invalid number.
- */
- public static String valueToString(Object value) throws JSONException {
- // moves the implementation to JSONWriter as:
- // 1. It makes more sense to be part of the writer class
- // 2. For Android support this method is not available. By implementing it in
- // the Writer
- // Android users can use the writer with the built in Android JSONObject
- // implementation.
- return JSONWriter.valueToString(value);
- }
-
- /**
- * Wrap an object, if necessary. If the object is <code>null</code>, return the
- * NULL object. If it is an array or collection, wrap it in a JSONArray. If it
- * is a map, wrap it in a JSONObject. If it is a standard property (Double,
- * String, et al) then it is already wrapped. Otherwise, if it comes from one of
- * the java packages, turn it into a string. And if it doesn't, try to wrap it
- * in a JSONObject. If the wrapping fails, then null is returned.
- *
- * @param object The object to wrap
- * @return The wrapped value
- */
- public static Object wrap(Object object) {
- try {
- if (object == null) {
- return NULL;
- }
- if (object instanceof JSONObject || object instanceof JSONArray || NULL.equals(object)
- || object instanceof JSONString || object instanceof Byte || object instanceof Character
- || object instanceof Short || object instanceof Integer || object instanceof Long
- || object instanceof Boolean || object instanceof Float || object instanceof Double
- || object instanceof String || object instanceof BigInteger || object instanceof BigDecimal
- || object instanceof Enum) {
- return object;
- }
-
- if (object instanceof Collection) {
- Collection<?> coll = (Collection<?>) object;
- return new JSONArray(coll);
- }
- if (object.getClass().isArray()) {
- return new JSONArray(object);
- }
- if (object instanceof Map) {
- Map<?, ?> map = (Map<?, ?>) object;
- return new JSONObject(map);
- }
- Package objectPackage = object.getClass().getPackage();
- String objectPackageName = objectPackage != null ? objectPackage.getName() : "";
- if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.")
- || object.getClass().getClassLoader() == null) {
- return object.toString();
- }
- return new JSONObject(object);
- } catch (Exception exception) {
- return null;
- }
- }
-
- /**
- * Write the contents of the JSONObject as JSON text to a writer. For
- * compactness, no whitespace is added.
- * <p>
- * <b> Warning: This method assumes that the data structure is acyclical. </b>
- *
- * @return The writer.
- * @throws JSONException
- */
- public Writer write(Writer writer) throws JSONException {
- return this.write(writer, 0, 0);
- }
-
- static final Writer writeValue(Writer writer, Object value, int indentFactor, int indent)
- throws JSONException, IOException {
- if (value == null || value.equals(null)) {
- writer.write("null");
- } else if (value instanceof JSONString) {
- Object o;
- try {
- o = ((JSONString) value).toJSONString();
- } catch (Exception e) {
- throw new JSONException(e);
- }
- writer.write(o != null ? o.toString() : quote(value.toString()));
- } else if (value instanceof Number) {
- // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary
- final String numberAsString = numberToString((Number) value);
- try {
- // Use the BigDecimal constructor for its parser to validate the format.
- @SuppressWarnings("unused")
- BigDecimal testNum = new BigDecimal(numberAsString);
- // Close enough to a JSON number that we will use it unquoted
- writer.write(numberAsString);
- } catch (NumberFormatException ex) {
- // The Number value is not a valid JSON number.
- // Instead we will quote it as a string
- quote(numberAsString, writer);
- }
- } else if (value instanceof Boolean) {
- writer.write(value.toString());
- } else if (value instanceof Enum<?>) {
- writer.write(quote(((Enum<?>) value).name()));
- } else if (value instanceof JSONObject) {
- ((JSONObject) value).write(writer, indentFactor, indent);
- } else if (value instanceof JSONArray) {
- ((JSONArray) value).write(writer, indentFactor, indent);
- } else if (value instanceof Map) {
- Map<?, ?> map = (Map<?, ?>) value;
- new JSONObject(map).write(writer, indentFactor, indent);
- } else if (value instanceof Collection) {
- Collection<?> coll = (Collection<?>) value;
- new JSONArray(coll).write(writer, indentFactor, indent);
- } else if (value.getClass().isArray()) {
- new JSONArray(value).write(writer, indentFactor, indent);
- } else {
- quote(value.toString(), writer);
- }
- return writer;
- }
-
- static final void indent(Writer writer, int indent) throws IOException {
- for (int i = 0; i < indent; i += 1) {
- writer.write(' ');
- }
- }
-
- /**
- * Write the contents of the JSONObject as JSON text to a writer.
- *
- * <p>
- * If <code>indentFactor > 0</code> and the {@link JSONObject} has only one key,
- * then the object will be output on a single line:
- *
- * <pre>
- * {@code {"key": 1}}
- * </pre>
- *
- * <p>
- * If an object has 2 or more keys, then it will be output across multiple
- * lines: <code><pre>{
- * "key1": 1,
- * "key2": "value 2",
- * "key3": 3
- * }</pre></code>
- * <p>
- * <b> Warning: This method assumes that the data structure is acyclical. </b>
- *
- * @param writer Writes the serialized JSON
- * @param indentFactor The number of spaces to add to each level of indentation.
- * @param indent The indentation of the top level.
- * @return The writer.
- * @throws JSONException
- */
- public Writer write(Writer writer, int indentFactor, int indent) throws JSONException {
- try {
- boolean commanate = false;
- final int length = this.length();
- writer.write('{');
-
- if (length == 1) {
- final Entry<String, ?> entry = this.entrySet().iterator().next();
- final String key = entry.getKey();
- writer.write(quote(key));
- writer.write(':');
- if (indentFactor > 0) {
- writer.write(' ');
- }
- try {
- writeValue(writer, entry.getValue(), indentFactor, indent);
- } catch (Exception e) {
- throw new JSONException("Unable to write JSONObject value for key: " + key, e);
- }
- } else if (length != 0) {
- final int newindent = indent + indentFactor;
- for (final Entry<String, ?> entry : this.entrySet()) {
- if (commanate) {
- writer.write(',');
- }
- if (indentFactor > 0) {
- writer.write('\n');
- }
- indent(writer, newindent);
- final String key = entry.getKey();
- writer.write(quote(key));
- writer.write(':');
- if (indentFactor > 0) {
- writer.write(' ');
- }
- try {
- writeValue(writer, entry.getValue(), indentFactor, newindent);
- } catch (Exception e) {
- throw new JSONException("Unable to write JSONObject value for key: " + key, e);
- }
- commanate = true;
- }
- if (indentFactor > 0) {
- writer.write('\n');
- }
- indent(writer, indent);
- }
- writer.write('}');
- return writer;
- } catch (IOException exception) {
- throw new JSONException(exception);
- }
- }
-
- /**
- * Returns a java.util.Map containing all of the entries in this object. If an
- * entry in the object is a JSONArray or JSONObject it will also be converted.
- * <p>
- * Warning: This method assumes that the data structure is acyclical.
- *
- * @return a java.util.Map containing the entries of this object
- */
- public Map<String, Object> toMap() {
- Map<String, Object> results = new HashMap<String, Object>();
- for (Entry<String, Object> entry : this.entrySet()) {
- Object value;
- if (entry.getValue() == null || NULL.equals(entry.getValue())) {
- value = null;
- } else if (entry.getValue() instanceof JSONObject) {
- value = ((JSONObject) entry.getValue()).toMap();
- } else if (entry.getValue() instanceof JSONArray) {
- value = ((JSONArray) entry.getValue()).toList();
- } else {
- value = entry.getValue();
- }
- results.put(entry.getKey(), value);
- }
- return results;
- }
+ public class JSONObject
+ {
+ /**
+ * JSONObject.NULL is equivalent to the value that JavaScript calls null,
+ * whilst Java's null is equivalent to the value that JavaScript calls
+ * undefined.
+ */
+ private static final class Null
+ {
+
+ /**
+ * There is only intended to be a single instance of the NULL object, so the
+ * clone method returns itself.
+ *
+ * @return NULL.
+ */
+ @Override
+ protected final Object clone()
+ {
+ return this;
+ }
+
+ /**
+ * A Null object is equal to the null value and to itself.
+ *
+ * @param object
+ * An object to test for nullness.
+ * @return true if the object parameter is the JSONObject.NULL object or
+ * null.
+ */
+ @Override
+ public boolean equals(Object object)
+ {
+ return object == null || object == this;
+ }
+
+ /**
+ * A Null object is equal to the null value and to itself.
+ *
+ * @return always returns 0.
+ */
+ @Override
+ public int hashCode()
+ {
+ return 0;
+ }
+
+ /**
+ * Get the "null" string value.
+ *
+ * @return The string "null".
+ */
+ @Override
+ public String toString()
+ {
+ return "null";
+ }
+ }
+
+ /**
+ * The map where the JSONObject's properties are kept.
+ */
+ private final Map<String, Object> map;
+
+ /**
+ * It is sometimes more convenient and less ambiguous to have a
+ * <code>NULL</code> object than to use Java's <code>null</code> value.
+ * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>.
+ * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>.
+ */
+ public static final Object NULL = new Null();
+
+ /**
+ * Construct an empty JSONObject.
+ */
+ public JSONObject()
+ {
+ // HashMap is used on purpose to ensure that elements are unordered by
+ // the specification.
+ // JSON tends to be a portable transfer format to allows the container
+ // implementations to rearrange their items for a faster element
+ // retrieval based on associative access.
+ // Therefore, an implementation mustn't rely on the order of the item.
+ this.map = new HashMap<String, Object>();
+ }
+
+ /**
+ * Construct a JSONObject from a subset of another JSONObject. An array of
+ * strings is used to identify the keys that should be copied. Missing keys
+ * are ignored.
+ *
+ * @param jo
+ * A JSONObject.
+ * @param names
+ * An array of strings.
+ */
+ public JSONObject(JSONObject jo, String[] names)
+ {
+ this(names.length);
+ for (int i = 0; i < names.length; i += 1)
+ {
+ try
+ {
+ this.putOnce(names[i], jo.opt(names[i]));
+ } catch (Exception ignore)
+ {
+ }
+ }
+ }
+
+ /**
+ * Construct a JSONObject from a JSONTokener.
+ *
+ * @param x
+ * A JSONTokener object containing the source string.
+ * @throws JSONException
+ * If there is a syntax error in the source string or a duplicated
+ * key.
+ */
+ public JSONObject(JSONTokener x) throws JSONException
+ {
+ this();
+ char c;
+ String key;
+
+ if (x.nextClean() != '{')
+ {
+ throw x.syntaxError("A JSONObject text must begin with '{'");
+ }
+ for (;;)
+ {
+ c = x.nextClean();
+ switch (c)
+ {
+ case 0:
+ throw x.syntaxError("A JSONObject text must end with '}'");
+ case '}':
+ return;
+ default:
+ x.back();
+ key = x.nextValue().toString();
+ }
+
+ // The key is followed by ':'.
+
+ c = x.nextClean();
+ if (c != ':')
+ {
+ throw x.syntaxError("Expected a ':' after a key");
+ }
+
+ // Use syntaxError(..) to include error location
+
+ if (key != null)
+ {
+ // Check if key exists
+ if (this.opt(key) != null)
+ {
+ // key already exists
+ throw x.syntaxError("Duplicate key \"" + key + "\"");
+ }
+ // Only add value if non-null
+ Object value = x.nextValue();
+ if (value != null)
+ {
+ this.put(key, value);
+ }
+ }
+
+ // Pairs are separated by ','.
+
+ switch (x.nextClean())
+ {
+ case ';':
+ case ',':
+ if (x.nextClean() == '}')
+ {
+ return;
+ }
+ x.back();
+ break;
+ case '}':
+ return;
+ default:
+ throw x.syntaxError("Expected a ',' or '}'");
+ }
+ }
+ }
+
+ /**
+ * Construct a JSONObject from a Map.
+ *
+ * @param m
+ * A map object that can be used to initialize the contents of the
+ * JSONObject.
+ * @throws JSONException
+ * If a value in the map is non-finite number.
+ * @throws NullPointerException
+ * If a key in the map is <code>null</code>
+ */
+ public JSONObject(Map<?, ?> m)
+ {
+ if (m == null)
+ {
+ this.map = new HashMap<String, Object>();
+ }
+ else
+ {
+ this.map = new HashMap<String, Object>(m.size());
+ for (final Entry<?, ?> e : m.entrySet())
+ {
+ if (e.getKey() == null)
+ {
+ throw new NullPointerException("Null key.");
+ }
+ final Object value = e.getValue();
+ if (value != null)
+ {
+ this.map.put(String.valueOf(e.getKey()), wrap(value));
+ }
+ }
+ }
+ }
+
+ /**
+ * Construct a JSONObject from an Object using bean getters. It reflects on
+ * all of the public methods of the object. For each of the methods with no
+ * parameters and a name starting with <code>"get"</code> or <code>"is"</code>
+ * followed by an uppercase letter, the method is invoked, and a key and the
+ * value returned from the getter method are put into the new JSONObject.
+ * <p>
+ * The key is formed by removing the <code>"get"</code> or <code>"is"</code>
+ * prefix. If the second remaining character is not upper case, then the first
+ * character is converted to lower case.
+ * <p>
+ * Methods that are <code>static</code>, return <code>void</code>, have
+ * parameters, or are "bridge" methods, are ignored.
+ * <p>
+ * For example, if an object has a method named <code>"getName"</code>, and if
+ * the result of calling <code>object.getName()</code> is
+ * <code>"Larry Fine"</code>, then the JSONObject will contain
+ * <code>"name": "Larry Fine"</code>.
+ * <p>
+ * The {@link JSONPropertyName} annotation can be used on a bean getter to
+ * override key name used in the JSONObject. For example, using the object
+ * above with the <code>getName</code> method, if we annotated it with:
+ *
+ * <pre>
+ * @JSONPropertyName("FullName")
+ * public String getName()
+ * {
+ * return this.name;
+ * }
+ * </pre>
+ *
+ * The resulting JSON object would contain
+ * <code>"FullName": "Larry Fine"</code>
+ * <p>
+ * Similarly, the {@link JSONPropertyName} annotation can be used on non-
+ * <code>get</code> and <code>is</code> methods. We can also override key name
+ * used in the JSONObject as seen below even though the field would normally
+ * be ignored:
+ *
+ * <pre>
+ * @JSONPropertyName("FullName")
+ * public String fullName()
+ * {
+ * return this.name;
+ * }
+ * </pre>
+ *
+ * The resulting JSON object would contain
+ * <code>"FullName": "Larry Fine"</code>
+ * <p>
+ * The {@link JSONPropertyIgnore} annotation can be used to force the bean
+ * property to not be serialized into JSON. If both {@link JSONPropertyIgnore}
+ * and {@link JSONPropertyName} are defined on the same method, a depth
+ * comparison is performed and the one closest to the concrete class being
+ * serialized is used. If both annotations are at the same level, then the
+ * {@link JSONPropertyIgnore} annotation takes precedent and the field is not
+ * serialized. For example, the following declaration would prevent the
+ * <code>getName</code> method from being serialized:
+ *
+ * <pre>
+ * @JSONPropertyName("FullName")
+ * @JSONPropertyIgnore
+ * public String getName()
+ * {
+ * return this.name;
+ * }
+ * </pre>
+ * <p>
+ *
+ * @param bean
+ * An object that has getter methods that should be used to make a
+ * JSONObject.
+ */
+ public JSONObject(Object bean)
+ {
+ this();
+ this.populateMap(bean);
+ }
+
+ /**
+ * Construct a JSONObject from an Object, using reflection to find the public
+ * members. The resulting JSONObject's keys will be the strings from the names
+ * array, and the values will be the field values associated with those keys
+ * in the object. If a key is not found or not visible, then it will not be
+ * copied into the new JSONObject.
+ *
+ * @param object
+ * An object that has fields that should be used to make a
+ * JSONObject.
+ * @param names
+ * An array of strings, the names of the fields to be obtained from
+ * the object.
+ */
+ public JSONObject(Object object, String names[])
+ {
+ this(names.length);
+ Class<?> c = object.getClass();
+ for (int i = 0; i < names.length; i += 1)
+ {
+ String name = names[i];
+ try
+ {
+ this.putOpt(name, c.getField(name).get(object));
+ } catch (Exception ignore)
+ {
+ }
+ }
+ }
+
+ /**
+ * Construct a JSONObject from a source JSON text string. This is the most
+ * commonly used JSONObject constructor.
+ *
+ * @param source
+ * A string beginning with <code>{</code> <small>(left
+ * brace)</small> and ending with <code>}</code> <small>(right
+ * brace)</small>.
+ * @exception JSONException
+ * If there is a syntax error in the source string or a
+ * duplicated key.
+ */
+ public JSONObject(String source) throws JSONException
+ {
+ this(new JSONTokener(source));
+ }
+
+ /**
+ * Construct a JSONObject from a ResourceBundle.
+ *
+ * @param baseName
+ * The ResourceBundle base name.
+ * @param locale
+ * The Locale to load the ResourceBundle for.
+ * @throws JSONException
+ * If any JSONExceptions are detected.
+ */
+ public JSONObject(String baseName, Locale locale) throws JSONException
+ {
+ this();
+ ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale,
+ Thread.currentThread().getContextClassLoader());
+
+ // Iterate through the keys in the bundle.
+
+ Enumeration<String> keys = bundle.getKeys();
+ while (keys.hasMoreElements())
+ {
+ Object key = keys.nextElement();
+ if (key != null)
+ {
+
+ // Go through the path, ensuring that there is a nested JSONObject for
+ // each
+ // segment except the last. Add the value using the last segment's name
+ // into
+ // the deepest nested JSONObject.
+
+ String[] path = ((String) key).split("\\.");
+ int last = path.length - 1;
+ JSONObject target = this;
+ for (int i = 0; i < last; i += 1)
+ {
+ String segment = path[i];
+ JSONObject nextTarget = target.optJSONObject(segment);
+ if (nextTarget == null)
+ {
+ nextTarget = new JSONObject();
+ target.put(segment, nextTarget);
+ }
+ target = nextTarget;
+ }
+ target.put(path[last], bundle.getString((String) key));
+ }
+ }
+ }
+
+ /**
+ * Constructor to specify an initial capacity of the internal map. Useful for
+ * library internal calls where we know, or at least can best guess, how big
+ * this JSONObject will be.
+ *
+ * @param initialCapacity
+ * initial capacity of the internal map.
+ */
+ protected JSONObject(int initialCapacity)
+ {
+ this.map = new HashMap<String, Object>(initialCapacity);
+ }
+
+ /**
+ * Accumulate values under a key. It is similar to the put method except that
+ * if there is already an object stored under the key then a JSONArray is
+ * stored under the key to hold all of the accumulated values. If there is
+ * already a JSONArray, then the new value is appended to it. In contrast, the
+ * put method replaces the previous value.
+ *
+ * If only one value is accumulated that is not a JSONArray, then the result
+ * will be the same as using put. But if multiple values are accumulated, then
+ * the result will be like append.
+ *
+ * @param key
+ * A key string.
+ * @param value
+ * An object to be accumulated under the key.
+ * @return this.
+ * @throws JSONException
+ * If the value is non-finite number.
+ * @throws NullPointerException
+ * If the key is <code>null</code>.
+ */
+ public JSONObject accumulate(String key, Object value)
+ throws JSONException
+ {
+ testValidity(value);
+ Object object = this.opt(key);
+ if (object == null)
+ {
+ this.put(key, value instanceof JSONArray ? new JSONArray().put(value)
+ : value);
+ }
+ else if (object instanceof JSONArray)
+ {
+ ((JSONArray) object).put(value);
+ }
+ else
+ {
+ this.put(key, new JSONArray().put(object).put(value));
+ }
+ return this;
+ }
+
+ /**
+ * Append values to the array under a key. If the key does not exist in the
+ * JSONObject, then the key is put in the JSONObject with its value being a
+ * JSONArray containing the value parameter. If the key was already associated
+ * with a JSONArray, then the value parameter is appended to it.
+ *
+ * @param key
+ * A key string.
+ * @param value
+ * An object to be accumulated under the key.
+ * @return this.
+ * @throws JSONException
+ * If the value is non-finite number or if the current value
+ * associated with the key is not a JSONArray.
+ * @throws NullPointerException
+ * If the key is <code>null</code>.
+ */
+ public JSONObject append(String key, Object value) throws JSONException
+ {
+ testValidity(value);
+ Object object = this.opt(key);
+ if (object == null)
+ {
+ this.put(key, new JSONArray().put(value));
+ }
+ else if (object instanceof JSONArray)
+ {
+ this.put(key, ((JSONArray) object).put(value));
+ }
+ else
+ {
+ throw new JSONException(
+ "JSONObject[" + key + "] is not a JSONArray.");
+ }
+ return this;
+ }
+
+ /**
+ * Produce a string from a double. The string "null" will be returned if the
+ * number is not finite.
+ *
+ * @param d
+ * A double.
+ * @return A String.
+ */
+ public static String doubleToString(double d)
+ {
+ if (Double.isInfinite(d) || Double.isNaN(d))
+ {
+ return "null";
+ }
+
+ // Shave off trailing zeros and decimal point, if possible.
+
+ String string = Double.toString(d);
+ if (string.indexOf('.') > 0 && string.indexOf('e') < 0
+ && string.indexOf('E') < 0)
+ {
+ while (string.endsWith("0"))
+ {
+ string = string.substring(0, string.length() - 1);
+ }
+ if (string.endsWith("."))
+ {
+ string = string.substring(0, string.length() - 1);
+ }
+ }
+ return string;
+ }
+
+ /**
+ * Get the value object associated with a key.
+ *
+ * @param key
+ * A key string.
+ * @return The object associated with the key.
+ * @throws JSONException
+ * if the key is not found.
+ */
+ public Object get(String key) throws JSONException
+ {
+ if (key == null)
+ {
+ throw new JSONException("Null key.");
+ }
+ Object object = this.opt(key);
+ if (object == null)
+ {
+ throw new JSONException("JSONObject[" + quote(key) + "] not found.");
+ }
+ return object;
+ }
+
+ /**
+ * Get the enum value associated with a key.
+ *
+ * @param clazz
+ * The type of enum to retrieve.
+ * @param key
+ * A key string.
+ * @return The enum value associated with the key
+ * @throws JSONException
+ * if the key is not found or if the value cannot be converted to an
+ * enum.
+ */
+ public <E extends Enum<E>> E getEnum(Class<E> clazz, String key)
+ throws JSONException
+ {
+ E val = optEnum(clazz, key);
+ if (val == null)
+ {
+ // JSONException should really take a throwable argument.
+ // If it did, I would re-implement this with the Enum.valueOf
+ // method and place any thrown exception in the JSONException
+ throw new JSONException(
+ "JSONObject[" + quote(key) + "] is not an enum of type "
+ + quote(clazz.getSimpleName()) + ".");
+ }
+ return val;
+ }
+
+ /**
+ * Get the boolean value associated with a key.
+ *
+ * @param key
+ * A key string.
+ * @return The truth.
+ * @throws JSONException
+ * if the value is not a Boolean or the String "true" or "false".
+ */
+ public boolean getBoolean(String key) throws JSONException
+ {
+ Object object = this.get(key);
+ if (object.equals(Boolean.FALSE) || (object instanceof String
+ && ((String) object).equalsIgnoreCase("false")))
+ {
+ return false;
+ }
+ else if (object.equals(Boolean.TRUE) || (object instanceof String
+ && ((String) object).equalsIgnoreCase("true")))
+ {
+ return true;
+ }
+ throw new JSONException(
+ "JSONObject[" + quote(key) + "] is not a Boolean.");
+ }
+
+ /**
+ * Get the BigInteger value associated with a key.
+ *
+ * @param key
+ * A key string.
+ * @return The numeric value.
+ * @throws JSONException
+ * if the key is not found or if the value cannot be converted to
+ * BigInteger.
+ */
+ public BigInteger getBigInteger(String key) throws JSONException
+ {
+ Object object = this.get(key);
+ try
+ {
+ return new BigInteger(object.toString());
+ } catch (Exception e)
+ {
+ throw new JSONException("JSONObject[" + quote(key)
+ + "] could not be converted to BigInteger.", e);
+ }
+ }
+
+ /**
+ * Get the BigDecimal value associated with a key.
+ *
+ * @param key
+ * A key string.
+ * @return The numeric value.
+ * @throws JSONException
+ * if the key is not found or if the value cannot be converted to
+ * BigDecimal.
+ */
+ public BigDecimal getBigDecimal(String key) throws JSONException
+ {
+ Object object = this.get(key);
+ if (object instanceof BigDecimal)
+ {
+ return (BigDecimal) object;
+ }
+ try
+ {
+ return new BigDecimal(object.toString());
+ } catch (Exception e)
+ {
+ throw new JSONException("JSONObject[" + quote(key)
+ + "] could not be converted to BigDecimal.", e);
+ }
+ }
+
+ /**
+ * Get the double value associated with a key.
+ *
+ * @param key
+ * A key string.
+ * @return The numeric value.
+ * @throws JSONException
+ * if the key is not found or if the value is not a Number object
+ * and cannot be converted to a number.
+ */
+ public double getDouble(String key) throws JSONException
+ {
+ Object object = this.get(key);
+ try
+ {
+ return object instanceof Number ? ((Number) object).doubleValue()
+ : Double.parseDouble(object.toString());
+ } catch (Exception e)
+ {
+ throw new JSONException(
+ "JSONObject[" + quote(key) + "] is not a number.", e);
+ }
+ }
+
+ /**
+ * Get the float value associated with a key.
+ *
+ * @param key
+ * A key string.
+ * @return The numeric value.
+ * @throws JSONException
+ * if the key is not found or if the value is not a Number object
+ * and cannot be converted to a number.
+ */
+ public float getFloat(String key) throws JSONException
+ {
+ Object object = this.get(key);
+ try
+ {
+ return object instanceof Number ? ((Number) object).floatValue()
+ : Float.parseFloat(object.toString());
+ } catch (Exception e)
+ {
+ throw new JSONException(
+ "JSONObject[" + quote(key) + "] is not a number.", e);
+ }
+ }
+
+ /**
+ * Get the Number value associated with a key.
+ *
+ * @param key
+ * A key string.
+ * @return The numeric value.
+ * @throws JSONException
+ * if the key is not found or if the value is not a Number object
+ * and cannot be converted to a number.
+ */
+ public Number getNumber(String key) throws JSONException
+ {
+ Object object = this.get(key);
+ try
+ {
+ if (object instanceof Number)
+ {
+ return (Number) object;
+ }
+ return stringToNumber(object.toString());
+ } catch (Exception e)
+ {
+ throw new JSONException(
+ "JSONObject[" + quote(key) + "] is not a number.", e);
+ }
+ }
+
+ /**
+ * Get the int value associated with a key.
+ *
+ * @param key
+ * A key string.
+ * @return The integer value.
+ * @throws JSONException
+ * if the key is not found or if the value cannot be converted to an
+ * integer.
+ */
+ public int getInt(String key) throws JSONException
+ {
+ Object object = this.get(key);
+ try
+ {
+ return object instanceof Number ? ((Number) object).intValue()
+ : Integer.parseInt((String) object);
+ } catch (Exception e)
+ {
+ throw new JSONException(
+ "JSONObject[" + quote(key) + "] is not an int.", e);
+ }
+ }
+
+ /**
+ * Get the JSONArray value associated with a key.
+ *
+ * @param key
+ * A key string.
+ * @return A JSONArray which is the value.
+ * @throws JSONException
+ * if the key is not found or if the value is not a JSONArray.
+ */
+ public JSONArray getJSONArray(String key) throws JSONException
+ {
+ Object object = this.get(key);
+ if (object instanceof JSONArray)
+ {
+ return (JSONArray) object;
+ }
+ throw new JSONException(
+ "JSONObject[" + quote(key) + "] is not a JSONArray.");
+ }
+
+ /**
+ * Get the JSONObject value associated with a key.
+ *
+ * @param key
+ * A key string.
+ * @return A JSONObject which is the value.
+ * @throws JSONException
+ * if the key is not found or if the value is not a JSONObject.
+ */
+ public JSONObject getJSONObject(String key) throws JSONException
+ {
+ Object object = this.get(key);
+ if (object instanceof JSONObject)
+ {
+ return (JSONObject) object;
+ }
+ throw new JSONException(
+ "JSONObject[" + quote(key) + "] is not a JSONObject.");
+ }
+
+ /**
+ * Get the long value associated with a key.
+ *
+ * @param key
+ * A key string.
+ * @return The long value.
+ * @throws JSONException
+ * if the key is not found or if the value cannot be converted to a
+ * long.
+ */
+ public long getLong(String key) throws JSONException
+ {
+ Object object = this.get(key);
+ try
+ {
+ return object instanceof Number ? ((Number) object).longValue()
+ : Long.parseLong((String) object);
+ } catch (Exception e)
+ {
+ throw new JSONException(
+ "JSONObject[" + quote(key) + "] is not a long.", e);
+ }
+ }
+
+ /**
+ * Get an array of field names from a JSONObject.
+ *
+ * @return An array of field names, or null if there are no names.
+ */
+ public static String[] getNames(JSONObject jo)
+ {
+ if (jo.isEmpty())
+ {
+ return null;
+ }
+ return jo.keySet().toArray(new String[jo.length()]);
+ }
+
+ /**
+ * Get an array of field names from an Object.
+ *
+ * @return An array of field names, or null if there are no names.
+ */
+ public static String[] getNames(Object object)
+ {
+ if (object == null)
+ {
+ return null;
+ }
+ Class<?> klass = object.getClass();
+ Field[] fields = klass.getFields();
+ int length = fields.length;
+ if (length == 0)
+ {
+ return null;
+ }
+ String[] names = new String[length];
+ for (int i = 0; i < length; i += 1)
+ {
+ names[i] = fields[i].getName();
+ }
+ return names;
+ }
+
+ /**
+ * Get the string associated with a key.
+ *
+ * @param key
+ * A key string.
+ * @return A string which is the value.
+ * @throws JSONException
+ * if there is no string value for the key.
+ */
+ public String getString(String key) throws JSONException
+ {
+ Object object = this.get(key);
+ if (object instanceof String)
+ {
+ return (String) object;
+ }
+ throw new JSONException("JSONObject[" + quote(key) + "] not a string.");
+ }
+
+ /**
+ * Determine if the JSONObject contains a specific key.
+ *
+ * @param key
+ * A key string.
+ * @return true if the key exists in the JSONObject.
+ */
+ public boolean has(String key)
+ {
+ return this.map.containsKey(key);
+ }
+
+ /**
+ * Increment a property of a JSONObject. If there is no such property, create
+ * one with a value of 1. If there is such a property, and if it is an
+ * Integer, Long, Double, or Float, then add one to it.
+ *
+ * @param key
+ * A key string.
+ * @return this.
+ * @throws JSONException
+ * If there is already a property with this name that is not an
+ * Integer, Long, Double, or Float.
+ */
+ public JSONObject increment(String key) throws JSONException
+ {
+ Object value = this.opt(key);
+ if (value == null)
+ {
+ this.put(key, 1);
+ }
+ else if (value instanceof BigInteger)
+ {
+ this.put(key, ((BigInteger) value).add(BigInteger.ONE));
+ }
+ else if (value instanceof BigDecimal)
+ {
+ this.put(key, ((BigDecimal) value).add(BigDecimal.ONE));
+ }
+ else if (value instanceof Integer)
+ {
+ this.put(key, ((Integer) value).intValue() + 1);
+ }
+ else if (value instanceof Long)
+ {
+ this.put(key, ((Long) value).longValue() + 1L);
+ }
+ else if (value instanceof Double)
+ {
+ this.put(key, ((Double) value).doubleValue() + 1.0d);
+ }
+ else if (value instanceof Float)
+ {
+ this.put(key, ((Float) value).floatValue() + 1.0f);
+ }
+ else
+ {
+ throw new JSONException("Unable to increment [" + quote(key) + "].");
+ }
+ return this;
+ }
+
+ /**
+ * Determine if the value associated with the key is <code>null</code> or if
+ * there is no value.
+ *
+ * @param key
+ * A key string.
+ * @return true if there is no value associated with the key or if the value
+ * is the JSONObject.NULL object.
+ */
+ public boolean isNull(String key)
+ {
+ return JSONObject.NULL.equals(this.opt(key));
+ }
+
+ /**
+ * Get an enumeration of the keys of the JSONObject. Modifying this key Set
+ * will also modify the JSONObject. Use with caution.
+ *
+ * @see Set#iterator()
+ *
+ * @return An iterator of the keys.
+ */
+ public Iterator<String> keys()
+ {
+ return this.keySet().iterator();
+ }
+
+ /**
+ * Get a set of keys of the JSONObject. Modifying this key Set will also
+ * modify the JSONObject. Use with caution.
+ *
+ * @see Map#keySet()
+ *
+ * @return A keySet.
+ */
+ public Set<String> keySet()
+ {
+ return this.map.keySet();
+ }
+
+ /**
+ * Get a set of entries of the JSONObject. These are raw values and may not
+ * match what is returned by the JSONObject get* and opt* functions. Modifying
+ * the returned EntrySet or the Entry objects contained therein will modify
+ * the backing JSONObject. This does not return a clone or a read-only view.
+ *
+ * Use with caution.
+ *
+ * @see Map#entrySet()
+ *
+ * @return An Entry Set
+ */
+ protected Set<Entry<String, Object>> entrySet()
+ {
+ return this.map.entrySet();
+ }
+
+ /**
+ * Get the number of keys stored in the JSONObject.
+ *
+ * @return The number of keys in the JSONObject.
+ */
+ public int length()
+ {
+ return this.map.size();
+ }
+
+ /**
+ * Check if JSONObject is empty.
+ *
+ * @return true if JSONObject is empty, otherwise false.
+ */
+ public boolean isEmpty()
+ {
+ return map.isEmpty();
+ }
+
+ /**
+ * Produce a JSONArray containing the names of the elements of this
+ * JSONObject.
+ *
+ * @return A JSONArray containing the key strings, or null if the JSONObject
+ * is empty.
+ */
+ public JSONArray names()
+ {
+ if (this.map.isEmpty())
+ {
+ return null;
+ }
+ return new JSONArray(this.map.keySet());
+ }
+
+ /**
+ * Produce a string from a Number.
+ *
+ * @param number
+ * A Number
+ * @return A String.
+ * @throws JSONException
+ * If n is a non-finite number.
+ */
+ public static String numberToString(Number number) throws JSONException
+ {
+ if (number == null)
+ {
+ throw new JSONException("Null pointer");
+ }
+ testValidity(number);
+
+ // Shave off trailing zeros and decimal point, if possible.
+
+ String string = number.toString();
+ if (string.indexOf('.') > 0 && string.indexOf('e') < 0
+ && string.indexOf('E') < 0)
+ {
+ while (string.endsWith("0"))
+ {
+ string = string.substring(0, string.length() - 1);
+ }
+ if (string.endsWith("."))
+ {
+ string = string.substring(0, string.length() - 1);
+ }
+ }
+ return string;
+ }
+
+ /**
+ * Get an optional value associated with a key.
+ *
+ * @param key
+ * A key string.
+ * @return An object which is the value, or null if there is no value.
+ */
+ public Object opt(String key)
+ {
+ return key == null ? null : this.map.get(key);
+ }
+
+ /**
+ * Get the enum value associated with a key.
+ *
+ * @param clazz
+ * The type of enum to retrieve.
+ * @param key
+ * A key string.
+ * @return The enum value associated with the key or null if not found
+ */
+ public <E extends Enum<E>> E optEnum(Class<E> clazz, String key)
+ {
+ return this.optEnum(clazz, key, null);
+ }
+
+ /**
+ * Get the enum value associated with a key.
+ *
+ * @param clazz
+ * The type of enum to retrieve.
+ * @param key
+ * A key string.
+ * @param defaultValue
+ * The default in case the value is not found
+ * @return The enum value associated with the key or defaultValue if the value
+ * is not found or cannot be assigned to <code>clazz</code>
+ */
+ public <E extends Enum<E>> E optEnum(Class<E> clazz, String key,
+ E defaultValue)
+ {
+ try
+ {
+ Object val = this.opt(key);
+ if (NULL.equals(val))
+ {
+ return defaultValue;
+ }
+ if (clazz.isAssignableFrom(val.getClass()))
+ {
+ // we just checked it!
+ @SuppressWarnings("unchecked")
+ E myE = (E) val;
+ return myE;
+ }
+ return Enum.valueOf(clazz, val.toString());
+ } catch (IllegalArgumentException e)
+ {
+ return defaultValue;
+ } catch (NullPointerException e)
+ {
+ return defaultValue;
+ }
+ }
+
+ /**
+ * Get an optional boolean associated with a key. It returns false if there is
+ * no such key, or if the value is not Boolean.TRUE or the String "true".
+ *
+ * @param key
+ * A key string.
+ * @return The truth.
+ */
+ public boolean optBoolean(String key)
+ {
+ return this.optBoolean(key, false);
+ }
+
+ /**
+ * Get an optional boolean associated with a key. It returns the defaultValue
+ * if there is no such key, or if it is not a Boolean or the String "true" or
+ * "false" (case insensitive).
+ *
+ * @param key
+ * A key string.
+ * @param defaultValue
+ * The default.
+ * @return The truth.
+ */
+ public boolean optBoolean(String key, boolean defaultValue)
+ {
+ Object val = this.opt(key);
+ if (NULL.equals(val))
+ {
+ return defaultValue;
+ }
+ if (val instanceof Boolean)
+ {
+ return ((Boolean) val).booleanValue();
+ }
+ try
+ {
+ // we'll use the get anyway because it does string conversion.
+ return this.getBoolean(key);
+ } catch (Exception e)
+ {
+ return defaultValue;
+ }
+ }
+
+ /**
+ * Get an optional BigDecimal associated with a key, or the defaultValue if
+ * there is no such key or if its value is not a number. If the value is a
+ * string, an attempt will be made to evaluate it as a number.
+ *
+ * @param key
+ * A key string.
+ * @param defaultValue
+ * The default.
+ * @return An object which is the value.
+ */
+ public BigDecimal optBigDecimal(String key, BigDecimal defaultValue)
+ {
+ Object val = this.opt(key);
+ if (NULL.equals(val))
+ {
+ return defaultValue;
+ }
+ if (val instanceof BigDecimal)
+ {
+ return (BigDecimal) val;
+ }
+ if (val instanceof BigInteger)
+ {
+ return new BigDecimal((BigInteger) val);
+ }
+ if (val instanceof Double || val instanceof Float)
+ {
+ return new BigDecimal(((Number) val).doubleValue());
+ }
+ if (val instanceof Long || val instanceof Integer
+ || val instanceof Short || val instanceof Byte)
+ {
+ return new BigDecimal(((Number) val).longValue());
+ }
+ // don't check if it's a string in case of unchecked Number subclasses
+ try
+ {
+ return new BigDecimal(val.toString());
+ } catch (Exception e)
+ {
+ return defaultValue;
+ }
+ }
+
+ /**
+ * Get an optional BigInteger associated with a key, or the defaultValue if
+ * there is no such key or if its value is not a number. If the value is a
+ * string, an attempt will be made to evaluate it as a number.
+ *
+ * @param key
+ * A key string.
+ * @param defaultValue
+ * The default.
+ * @return An object which is the value.
+ */
+ public BigInteger optBigInteger(String key, BigInteger defaultValue)
+ {
+ Object val = this.opt(key);
+ if (NULL.equals(val))
+ {
+ return defaultValue;
+ }
+ if (val instanceof BigInteger)
+ {
+ return (BigInteger) val;
+ }
+ if (val instanceof BigDecimal)
+ {
+ return ((BigDecimal) val).toBigInteger();
+ }
+ if (val instanceof Double || val instanceof Float)
+ {
+ return new BigDecimal(((Number) val).doubleValue()).toBigInteger();
+ }
+ if (val instanceof Long || val instanceof Integer
+ || val instanceof Short || val instanceof Byte)
+ {
+ return BigInteger.valueOf(((Number) val).longValue());
+ }
+ // don't check if it's a string in case of unchecked Number subclasses
+ try
+ {
+ // the other opt functions handle implicit conversions, i.e.
+ // jo.put("double",1.1d);
+ // jo.optInt("double"); -- will return 1, not an error
+ // this conversion to BigDecimal then to BigInteger is to maintain
+ // that type cast support that may truncate the decimal.
+ final String valStr = val.toString();
+ if (isDecimalNotation(valStr))
+ {
+ return new BigDecimal(valStr).toBigInteger();
+ }
+ return new BigInteger(valStr);
+ } catch (Exception e)
+ {
+ return defaultValue;
+ }
+ }
+
+ /**
+ * Get an optional double associated with a key, or NaN if there is no such
+ * key or if its value is not a number. If the value is a string, an attempt
+ * will be made to evaluate it as a number.
+ *
+ * @param key
+ * A string which is the key.
+ * @return An object which is the value.
+ */
+ public double optDouble(String key)
+ {
+ return this.optDouble(key, Double.NaN);
+ }
+
+ /**
+ * Get an optional double associated with a key, or the defaultValue if there
+ * is no such key or if its value is not a number. If the value is a string,
+ * an attempt will be made to evaluate it as a number.
+ *
+ * @param key
+ * A key string.
+ * @param defaultValue
+ * The default.
+ * @return An object which is the value.
+ */
+ public double optDouble(String key, double defaultValue)
+ {
+ Object val = this.opt(key);
+ if (NULL.equals(val))
+ {
+ return defaultValue;
+ }
+ if (val instanceof Number)
+ {
+ return ((Number) val).doubleValue();
+ }
+ if (val instanceof String)
+ {
+ try
+ {
+ return Double.parseDouble((String) val);
+ } catch (Exception e)
+ {
+ return defaultValue;
+ }
+ }
+ return defaultValue;
+ }
+
+ /**
+ * Get the optional double value associated with an index. NaN is returned if
+ * there is no value for the index, or if the value is not a number and cannot
+ * be converted to a number.
+ *
+ * @param key
+ * A key string.
+ * @return The value.
+ */
+ public float optFloat(String key)
+ {
+ return this.optFloat(key, Float.NaN);
+ }
+
+ /**
+ * Get the optional double value associated with an index. The defaultValue is
+ * returned if there is no value for the index, or if the value is not a
+ * number and cannot be converted to a number.
+ *
+ * @param key
+ * A key string.
+ * @param defaultValue
+ * The default value.
+ * @return The value.
+ */
+ public float optFloat(String key, float defaultValue)
+ {
+ Object val = this.opt(key);
+ if (JSONObject.NULL.equals(val))
+ {
+ return defaultValue;
+ }
+ if (val instanceof Number)
+ {
+ return ((Number) val).floatValue();
+ }
+ if (val instanceof String)
+ {
+ try
+ {
+ return Float.parseFloat((String) val);
+ } catch (Exception e)
+ {
+ return defaultValue;
+ }
+ }
+ return defaultValue;
+ }
+
+ /**
+ * Get an optional int value associated with a key, or zero if there is no
+ * such key or if the value is not a number. If the value is a string, an
+ * attempt will be made to evaluate it as a number.
+ *
+ * @param key
+ * A key string.
+ * @return An object which is the value.
+ */
+ public int optInt(String key)
+ {
+ return this.optInt(key, 0);
+ }
+
+ /**
+ * Get an optional int value associated with a key, or the default if there is
+ * no such key or if the value is not a number. If the value is a string, an
+ * attempt will be made to evaluate it as a number.
+ *
+ * @param key
+ * A key string.
+ * @param defaultValue
+ * The default.
+ * @return An object which is the value.
+ */
+ public int optInt(String key, int defaultValue)
+ {
+ Object val = this.opt(key);
+ if (NULL.equals(val))
+ {
+ return defaultValue;
+ }
+ if (val instanceof Number)
+ {
+ return ((Number) val).intValue();
+ }
+
+ if (val instanceof String)
+ {
+ try
+ {
+ return new BigDecimal((String) val).intValue();
+ } catch (Exception e)
+ {
+ return defaultValue;
+ }
+ }
+ return defaultValue;
+ }
+
+ /**
+ * Get an optional JSONArray associated with a key. It returns null if there
+ * is no such key, or if its value is not a JSONArray.
+ *
+ * @param key
+ * A key string.
+ * @return A JSONArray which is the value.
+ */
+ public JSONArray optJSONArray(String key)
+ {
+ Object o = this.opt(key);
+ return o instanceof JSONArray ? (JSONArray) o : null;
+ }
+
+ /**
+ * Get an optional JSONObject associated with a key. It returns null if there
+ * is no such key, or if its value is not a JSONObject.
+ *
+ * @param key
+ * A key string.
+ * @return A JSONObject which is the value.
+ */
+ public JSONObject optJSONObject(String key)
+ {
+ Object object = this.opt(key);
+ return object instanceof JSONObject ? (JSONObject) object : null;
+ }
+
+ /**
+ * Get an optional long value associated with a key, or zero if there is no
+ * such key or if the value is not a number. If the value is a string, an
+ * attempt will be made to evaluate it as a number.
+ *
+ * @param key
+ * A key string.
+ * @return An object which is the value.
+ */
+ public long optLong(String key)
+ {
+ return this.optLong(key, 0);
+ }
+
+ /**
+ * Get an optional long value associated with a key, or the default if there
+ * is no such key or if the value is not a number. If the value is a string,
+ * an attempt will be made to evaluate it as a number.
+ *
+ * @param key
+ * A key string.
+ * @param defaultValue
+ * The default.
+ * @return An object which is the value.
+ */
+ public long optLong(String key, long defaultValue)
+ {
+ Object val = this.opt(key);
+ if (NULL.equals(val))
+ {
+ return defaultValue;
+ }
+ if (val instanceof Number)
+ {
+ return ((Number) val).longValue();
+ }
+
+ if (val instanceof String)
+ {
+ try
+ {
+ return new BigDecimal((String) val).longValue();
+ } catch (Exception e)
+ {
+ return defaultValue;
+ }
+ }
+ return defaultValue;
+ }
+
+ /**
+ * Get an optional {@link Number} value associated with a key, or
+ * <code>null</code> if there is no such key or if the value is not a number.
+ * If the value is a string, an attempt will be made to evaluate it as a
+ * number ({@link BigDecimal}). This method would be used in cases where type
+ * coercion of the number value is unwanted.
+ *
+ * @param key
+ * A key string.
+ * @return An object which is the value.
+ */
+ public Number optNumber(String key)
+ {
+ return this.optNumber(key, null);
+ }
+
+ /**
+ * Get an optional {@link Number} value associated with a key, or the default
+ * if there is no such key or if the value is not a number. If the value is a
+ * string, an attempt will be made to evaluate it as a number. This method
+ * would be used in cases where type coercion of the number value is unwanted.
+ *
+ * @param key
+ * A key string.
+ * @param defaultValue
+ * The default.
+ * @return An object which is the value.
+ */
+ public Number optNumber(String key, Number defaultValue)
+ {
+ Object val = this.opt(key);
+ if (NULL.equals(val))
+ {
+ return defaultValue;
+ }
+ if (val instanceof Number)
+ {
+ return (Number) val;
+ }
+
+ if (val instanceof String)
+ {
+ try
+ {
+ return stringToNumber((String) val);
+ } catch (Exception e)
+ {
+ return defaultValue;
+ }
+ }
+ return defaultValue;
+ }
+
+ /**
+ * Get an optional string associated with a key. It returns an empty string if
+ * there is no such key. If the value is not a string and is not null, then it
+ * is converted to a string.
+ *
+ * @param key
+ * A key string.
+ * @return A string which is the value.
+ */
+ public String optString(String key)
+ {
+ return this.optString(key, "");
+ }
+
+ /**
+ * Get an optional string associated with a key. It returns the defaultValue
+ * if there is no such key.
+ *
+ * @param key
+ * A key string.
+ * @param defaultValue
+ * The default.
+ * @return A string which is the value.
+ */
+ public String optString(String key, String defaultValue)
+ {
+ Object object = this.opt(key);
+ return NULL.equals(object) ? defaultValue : object.toString();
+ }
+
+ /**
+ * Populates the internal map of the JSONObject with the bean properties. The
+ * bean can not be recursive.
+ *
+ * @see JSONObject#JSONObject(Object)
+ *
+ * @param bean
+ * the bean
+ */
+ private void populateMap(Object bean)
+ {
+ Class<?> klass = bean.getClass();
+
+ // If klass is a System class then set includeSuperClass to false.
+
+ boolean includeSuperClass = klass.getClassLoader() != null;
+
+ Method[] methods = includeSuperClass ? klass.getMethods()
+ : klass.getDeclaredMethods();
+ for (final Method method : methods)
+ {
+ final int modifiers = method.getModifiers();
+ if (Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers)
+ && method.getParameterTypes().length == 0
+ && !method.isBridge() && method.getReturnType() != Void.TYPE
+ && isValidMethodName(method.getName()))
+ {
+ final String key = getKeyNameFromMethod(method);
+ if (key != null && !key.isEmpty())
+ {
+ try
+ {
+ final Object result = method.invoke(bean);
+ if (result != null)
+ {
+ this.map.put(key, wrap(result));
+ // we don't use the result anywhere outside of wrap
+ // if it's a resource we should be sure to close it
+ // after calling toString
+ if (result instanceof Closeable)
+ {
+ try
+ {
+ ((Closeable) result).close();
+ } catch (IOException ignore)
+ {
+ }
+ }
+ }
+ } catch (IllegalAccessException ignore)
+ {
+ } catch (IllegalArgumentException ignore)
+ {
+ } catch (InvocationTargetException ignore)
+ {
+ }
+ }
+ }
+ }
+ }
+
+ private boolean isValidMethodName(String name)
+ {
+ return !"getClass".equals(name) && !"getDeclaringClass".equals(name);
+ }
+
+ private String getKeyNameFromMethod(Method method)
+ {
+ final int ignoreDepth = -1;// getAnnotationDepth(method,
+ // JSONPropertyIgnore.class);
+ // if (ignoreDepth > 0) {
+ // final int forcedNameDepth = getAnnotationDepth(method,
+ // JSONPropertyName.class);
+ // if (forcedNameDepth < 0 || ignoreDepth <= forcedNameDepth) {
+ // // the hierarchy asked to ignore, and the nearest name override
+ // // was higher or non-existent
+ // return null;
+ // }
+ // }
+ // JSONPropertyName annotation = getAnnotation(method,
+ // JSONPropertyName.class);
+ // if (annotation != null && annotation.value() != null &&
+ // !annotation.value().isEmpty()) {
+ // return annotation.value();
+ // }
+ String key;
+ final String name = method.getName();
+ if (name.startsWith("get") && name.length() > 3)
+ {
+ key = name.substring(3);
+ }
+ else if (name.startsWith("is") && name.length() > 2)
+ {
+ key = name.substring(2);
+ }
+ else
+ {
+ return null;
+ }
+ // if the first letter in the key is not uppercase, then skip.
+ // This is to maintain backwards compatibility before PR406
+ // (https://github.com/stleary/JSON-java/pull/406/)
+ if (Character.isLowerCase(key.charAt(0)))
+ {
+ return null;
+ }
+ if (key.length() == 1)
+ {
+ key = key.toLowerCase(Locale.ROOT);
+ }
+ else if (!Character.isUpperCase(key.charAt(1)))
+ {
+ key = key.substring(0, 1).toLowerCase(Locale.ROOT) + key.substring(1);
+ }
+ return (/** @j2sNative 1 ? key.split("$")[0] : */
+ key);
+ }
+
+ // /**
+ // * Searches the class hierarchy to see if the method or it's super
+ // * implementations and interfaces has the annotation.
+ // *
+ // * @param <A>
+ // * type of the annotation
+ // *
+ // * @param m
+ // * method to check
+ // * @param annotationClass
+ // * annotation to look for
+ // * @return the {@link Annotation} if the annotation exists on the current
+ // method
+ // * or one of it's super class definitions
+ // */
+ // private static <A extends Annotation> A getAnnotation(final Method m, final
+ // Class<A> annotationClass) {
+ // return null;
+ // // if we have invalid data the result is null
+ // if (true || m == null || annotationClass == null) {
+ // return null;
+ // }
+ //
+ // if (m.isAnnotationPresent(annotationClass)) {
+ // return m.getAnnotation(annotationClass);
+ // }
+ //
+ // // if we've already reached the Object class, return null;
+ // Class<?> c = m.getDeclaringClass();
+ // if (c.getSuperclass() == null) {
+ // return null;
+ // }
+ //
+ // // check directly implemented interfaces for the method being checked
+ // for (Class<?> i : c.getInterfaces()) {
+ // try {
+ // Method im = i.getMethod(m.getName(), m.getParameterTypes());
+ // return getAnnotation(im, annotationClass);
+ // } catch (final SecurityException ex) {
+ // continue;
+ // } catch (final NoSuchMethodException ex) {
+ // continue;
+ // }
+ // }
+ //
+ // try {
+ // return getAnnotation(
+ // c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()),
+ // annotationClass);
+ // } catch (final SecurityException ex) {
+ // return null;
+ // } catch (final NoSuchMethodException ex) {
+ // return null;
+ // }
+ // }
+ //
+ // /**
+ // * Searches the class hierarchy to see if the method or it's super
+ // * implementations and interfaces has the annotation. Returns the depth of
+ // the
+ // * annotation in the hierarchy.
+ // *
+ // * @param <A>
+ // * type of the annotation
+ // *
+ // * @param m
+ // * method to check
+ // * @param annotationClass
+ // * annotation to look for
+ // * @return Depth of the annotation or -1 if the annotation is not on the
+ // method.
+ // */
+ // private static int getAnnotationDepth(final Method m, final Class<? extends
+ // Annotation> annotationClass) {
+ // // if we have invalid data the result is -1
+ // if (m == null || annotationClass == null) {
+ // return -1;
+ // }
+ // if (m.isAnnotationPresent(annotationClass)) {
+ // return 1;
+ // }
+ //
+ // // if we've already reached the Object class, return -1;
+ // Class<?> c = m.getDeclaringClass();
+ // if (c.getSuperclass() == null) {
+ // return -1;
+ // }
+ //
+ // // check directly implemented interfaces for the method being checked
+ // for (Class<?> i : c.getInterfaces()) {
+ // try {
+ // Method im = i.getMethod(m.getName(), m.getParameterTypes());
+ // int d = getAnnotationDepth(im, annotationClass);
+ // if (d > 0) {
+ // // since the annotation was on the interface, add 1
+ // return d + 1;
+ // }
+ // } catch (final SecurityException ex) {
+ // continue;
+ // } catch (final NoSuchMethodException ex) {
+ // continue;
+ // }
+ // }
+ //
+ // try {
+ // int d = getAnnotationDepth(
+ // c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()),
+ // annotationClass);
+ // if (d > 0) {
+ // // since the annotation was on the superclass, add 1
+ // return d + 1;
+ // }
+ // return -1;
+ // } catch (final SecurityException ex) {
+ // return -1;
+ // } catch (final NoSuchMethodException ex) {
+ // return -1;
+ // }
+ // }
+
+ /**
+ * Put a key/boolean pair in the JSONObject.
+ *
+ * @param key
+ * A key string.
+ * @param value
+ * A boolean which is the value.
+ * @return this.
+ * @throws JSONException
+ * If the value is non-finite number.
+ * @throws NullPointerException
+ * If the key is <code>null</code>.
+ */
+ public JSONObject put(String key, boolean value) throws JSONException
+ {
+ return this.put(key, value ? Boolean.TRUE : Boolean.FALSE);
+ }
+
+ /**
+ * Put a key/value pair in the JSONObject, where the value will be a JSONArray
+ * which is produced from a Collection.
+ *
+ * @param key
+ * A key string.
+ * @param value
+ * A Collection value.
+ * @return this.
+ * @throws JSONException
+ * If the value is non-finite number.
+ * @throws NullPointerException
+ * If the key is <code>null</code>.
+ */
+ public JSONObject put(String key, Collection<?> value)
+ throws JSONException
+ {
+ return this.put(key, new JSONArray(value));
+ }
+
+ /**
+ * Put a key/double pair in the JSONObject.
+ *
+ * @param key
+ * A key string.
+ * @param value
+ * A double which is the value.
+ * @return this.
+ * @throws JSONException
+ * If the value is non-finite number.
+ * @throws NullPointerException
+ * If the key is <code>null</code>.
+ */
+ public JSONObject put(String key, double value) throws JSONException
+ {
+ return this.put(key, Double.valueOf(value));
+ }
+
+ /**
+ * Put a key/float pair in the JSONObject.
+ *
+ * @param key
+ * A key string.
+ * @param value
+ * A float which is the value.
+ * @return this.
+ * @throws JSONException
+ * If the value is non-finite number.
+ * @throws NullPointerException
+ * If the key is <code>null</code>.
+ */
+ public JSONObject put(String key, float value) throws JSONException
+ {
+ return this.put(key, Float.valueOf(value));
+ }
+
+ /**
+ * Put a key/int pair in the JSONObject.
+ *
+ * @param key
+ * A key string.
+ * @param value
+ * An int which is the value.
+ * @return this.
+ * @throws JSONException
+ * If the value is non-finite number.
+ * @throws NullPointerException
+ * If the key is <code>null</code>.
+ */
+ public JSONObject put(String key, int value) throws JSONException
+ {
+ return this.put(key, Integer.valueOf(value));
+ }
+
+ /**
+ * Put a key/long pair in the JSONObject.
+ *
+ * @param key
+ * A key string.
+ * @param value
+ * A long which is the value.
+ * @return this.
+ * @throws JSONException
+ * If the value is non-finite number.
+ * @throws NullPointerException
+ * If the key is <code>null</code>.
+ */
+ public JSONObject put(String key, long value) throws JSONException
+ {
+ return this.put(key, Long.valueOf(value));
+ }
+
+ /**
+ * Put a key/value pair in the JSONObject, where the value will be a
+ * JSONObject which is produced from a Map.
+ *
+ * @param key
+ * A key string.
+ * @param value
+ * A Map value.
+ * @return this.
+ * @throws JSONException
+ * If the value is non-finite number.
+ * @throws NullPointerException
+ * If the key is <code>null</code>.
+ */
+ public JSONObject put(String key, Map<?, ?> value) throws JSONException
+ {
+ return this.put(key, new JSONObject(value));
+ }
+
+ /**
+ * Put a key/value pair in the JSONObject. If the value is <code>null</code>,
+ * then the key will be removed from the JSONObject if it is present.
+ *
+ * @param key
+ * A key string.
+ * @param value
+ * An object which is the value. It should be of one of these types:
+ * Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or
+ * the JSONObject.NULL object.
+ * @return this.
+ * @throws JSONException
+ * If the value is non-finite number.
+ * @throws NullPointerException
+ * If the key is <code>null</code>.
+ */
+ public JSONObject put(String key, Object value) throws JSONException
+ {
+ if (key == null)
+ {
+ throw new NullPointerException("Null key.");
+ }
+ if (value != null)
+ {
+ testValidity(value);
+ this.map.put(key, value);
+ }
+ else
+ {
+ this.remove(key);
+ }
+ return this;
+ }
+
+ /**
+ * Put a key/value pair in the JSONObject, but only if the key and the value
+ * are both non-null, and only if there is not already a member with that
+ * name.
+ *
+ * @param key
+ * string
+ * @param value
+ * object
+ * @return this.
+ * @throws JSONException
+ * if the key is a duplicate
+ */
+ public JSONObject putOnce(String key, Object value) throws JSONException
+ {
+ if (key != null && value != null)
+ {
+ if (this.opt(key) != null)
+ {
+ throw new JSONException("Duplicate key \"" + key + "\"");
+ }
+ return this.put(key, value);
+ }
+ return this;
+ }
+
+ /**
+ * Put a key/value pair in the JSONObject, but only if the key and the value
+ * are both non-null.
+ *
+ * @param key
+ * A key string.
+ * @param value
+ * An object which is the value. It should be of one of these types:
+ * Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or
+ * the JSONObject.NULL object.
+ * @return this.
+ * @throws JSONException
+ * If the value is a non-finite number.
+ */
+ public JSONObject putOpt(String key, Object value) throws JSONException
+ {
+ if (key != null && value != null)
+ {
+ return this.put(key, value);
+ }
+ return this;
+ }
+
+ /**
+ * Creates a JSONPointer using an initialization string and tries to match it
+ * to an item within this JSONObject. For example, given a JSONObject
+ * initialized with this document:
+ *
+ * <pre>
+ * {
+ * "a":{"b":"c"}
+ * }
+ * </pre>
+ *
+ * and this JSONPointer string:
+ *
+ * <pre>
+ * "/a/b"
+ * </pre>
+ *
+ * Then this method will return the String "c". A JSONPointerException may be
+ * thrown from code called by this method.
+ *
+ * @param jsonPointer
+ * string that can be used to create a JSONPointer
+ * @return the item matched by the JSONPointer, otherwise null
+ */
+ public Object query(String jsonPointer)
+ {
+ return query(new JSONPointer(jsonPointer));
+ }
+
+ /**
+ * Uses a user initialized JSONPointer and tries to match it to an item within
+ * this JSONObject. For example, given a JSONObject initialized with this
+ * document:
+ *
+ * <pre>
+ * {
+ * "a":{"b":"c"}
+ * }
+ * </pre>
+ *
+ * and this JSONPointer:
+ *
+ * <pre>
+ * "/a/b"
+ * </pre>
+ *
+ * Then this method will return the String "c". A JSONPointerException may be
+ * thrown from code called by this method.
+ *
+ * @param jsonPointer
+ * string that can be used to create a JSONPointer
+ * @return the item matched by the JSONPointer, otherwise null
+ */
+ public Object query(JSONPointer jsonPointer)
+ {
+ return jsonPointer.queryFrom(this);
+ }
+
+ /**
+ * Queries and returns a value from this object using {@code jsonPointer}, or
+ * returns null if the query fails due to a missing key.
+ *
+ * @param jsonPointer
+ * the string representation of the JSON pointer
+ * @return the queried value or {@code null}
+ * @throws IllegalArgumentException
+ * if {@code jsonPointer} has invalid syntax
+ */
+ public Object optQuery(String jsonPointer)
+ {
+ return optQuery(new JSONPointer(jsonPointer));
+ }
+
+ /**
+ * Queries and returns a value from this object using {@code jsonPointer}, or
+ * returns null if the query fails due to a missing key.
+ *
+ * @param jsonPointer
+ * The JSON pointer
+ * @return the queried value or {@code null}
+ * @throws IllegalArgumentException
+ * if {@code jsonPointer} has invalid syntax
+ */
+ public Object optQuery(JSONPointer jsonPointer)
+ {
+ try
+ {
+ return jsonPointer.queryFrom(this);
+ } catch (JSONPointerException e)
+ {
+ return null;
+ }
+ }
+
+ /**
+ * Produce a string in double quotes with backslash sequences in all the right
+ * places. A backslash will be inserted within </, producing <\/, allowing
+ * JSON text to be delivered in HTML. In JSON text, a string cannot contain a
+ * control character or an unescaped quote or backslash.
+ *
+ * @param string
+ * A String
+ * @return A String correctly formatted for insertion in a JSON text.
+ */
+ public static String quote(String string)
+ {
+ StringWriter sw = new StringWriter();
+ synchronized (sw.getBuffer())
+ {
+ try
+ {
+ return quote(string, sw).toString();
+ } catch (IOException ignored)
+ {
+ // will never happen - we are writing to a string writer
+ return "";
+ }
+ }
+ }
+
+ public static Writer quote(String string, Writer w) throws IOException
+ {
+ if (string == null || string.isEmpty())
+ {
+ w.write("\"\"");
+ return w;
+ }
+
+ char b;
+ char c = 0;
+ String hhhh;
+ int i;
+ int len = string.length();
+
+ w.write('"');
+ for (i = 0; i < len; i += 1)
+ {
+ b = c;
+ c = string.charAt(i);
+ switch (c)
+ {
+ case '\\':
+ case '"':
+ w.write('\\');
+ w.write(c);
+ break;
+ case '/':
+ if (b == '<')
+ {
+ w.write('\\');
+ }
+ w.write(c);
+ break;
+ case '\b':
+ w.write("\\b");
+ break;
+ case '\t':
+ w.write("\\t");
+ break;
+ case '\n':
+ w.write("\\n");
+ break;
+ case '\f':
+ w.write("\\f");
+ break;
+ case '\r':
+ w.write("\\r");
+ break;
+ default:
+ if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
+ || (c >= '\u2000' && c < '\u2100'))
+ {
+ w.write("\\u");
+ hhhh = Integer.toHexString(c);
+ w.write("0000", 0, 4 - hhhh.length());
+ w.write(hhhh);
+ }
+ else
+ {
+ w.write(c);
+ }
+ }
+ }
+ w.write('"');
+ return w;
+ }
+
+ /**
+ * Remove a name and its value, if present.
+ *
+ * @param key
+ * The name to be removed.
+ * @return The value that was associated with the name, or null if there was
+ * no value.
+ */
+ public Object remove(String key)
+ {
+ return this.map.remove(key);
+ }
+
+ /**
+ * Determine if two JSONObjects are similar. They must contain the same set of
+ * names which must be associated with similar values.
+ *
+ * @param other
+ * The other JSONObject
+ * @return true if they are equal
+ */
+ public boolean similar(Object other)
+ {
+ try
+ {
+ if (!(other instanceof JSONObject))
+ {
+ return false;
+ }
+ if (!this.keySet().equals(((JSONObject) other).keySet()))
+ {
+ return false;
+ }
+ for (final Entry<String, ?> entry : this.entrySet())
+ {
+ String name = entry.getKey();
+ Object valueThis = entry.getValue();
+ Object valueOther = ((JSONObject) other).get(name);
+ if (valueThis == valueOther)
+ {
+ continue;
+ }
+ if (valueThis == null)
+ {
+ return false;
+ }
+ if (valueThis instanceof JSONObject)
+ {
+ if (!((JSONObject) valueThis).similar(valueOther))
+ {
+ return false;
+ }
+ }
+ else if (valueThis instanceof JSONArray)
+ {
+ if (!((JSONArray) valueThis).similar(valueOther))
+ {
+ return false;
+ }
+ }
+ else if (!valueThis.equals(valueOther))
+ {
+ return false;
+ }
+ }
+ return true;
+ } catch (Throwable exception)
+ {
+ return false;
+ }
+ }
+
+ /**
+ * Tests if the value should be tried as a decimal. It makes no test if there
+ * are actual digits.
+ *
+ * @param val
+ * value to test
+ * @return true if the string is "-0" or if it contains '.', 'e', or 'E',
+ * false otherwise.
+ */
+ protected static boolean isDecimalNotation(final String val)
+ {
+ return val.indexOf('.') > -1 || val.indexOf('e') > -1
+ || val.indexOf('E') > -1 || "-0".equals(val);
+ }
+
+ /**
+ * Converts a string to a number using the narrowest possible type. Possible
+ * returns for this function are BigDecimal, Double, BigInteger, Long, and
+ * Integer. When a Double is returned, it should always be a valid Double and
+ * not NaN or +-infinity.
+ *
+ * @param val
+ * value to convert
+ * @return Number representation of the value.
+ * @throws NumberFormatException
+ * thrown if the value is not a valid number. A public caller should
+ * catch this and wrap it in a {@link JSONException} if applicable.
+ */
+ protected static Number stringToNumber(final String val)
+ throws NumberFormatException
+ {
+ char initial = val.charAt(0);
+ if ((initial >= '0' && initial <= '9') || initial == '-')
+ {
+ // decimal representation
+ if (isDecimalNotation(val))
+ {
+ // quick dirty way to see if we need a BigDecimal instead of a Double
+ // this only handles some cases of overflow or underflow
+ if (val.length() > 14)
+ {
+ return new BigDecimal(val);
+ }
+ final Double d = Double.valueOf(val);
+ if (d.isInfinite() || d.isNaN())
+ {
+ // if we can't parse it as a double, go up to BigDecimal
+ // this is probably due to underflow like 4.32e-678
+ // or overflow like 4.65e5324. The size of the string is small
+ // but can't be held in a Double.
+ return new BigDecimal(val);
+ }
+ return d;
+ }
+ // integer representation.
+ // This will narrow any values to the smallest reasonable Object
+ // representation
+ // (Integer, Long, or BigInteger)
+
+ // string version
+ // The compare string length method reduces GC,
+ // but leads to smaller integers being placed in larger wrappers even
+ // though not
+ // needed. i.e. 1,000,000,000 -> Long even though it's an Integer
+ // 1,000,000,000,000,000,000 -> BigInteger even though it's a Long
+ // if(val.length()<=9){
+ // return Integer.valueOf(val);
+ // }
+ // if(val.length()<=18){
+ // return Long.valueOf(val);
+ // }
+ // return new BigInteger(val);
+
+ // BigInteger version: We use a similar bitLenth compare as
+ // BigInteger#intValueExact uses. Increases GC, but objects hold
+ // only what they need. i.e. Less runtime overhead if the value is
+ // long lived. Which is the better tradeoff? This is closer to what's
+ // in stringToValue.
+ BigInteger bi = new BigInteger(val);
+ if (bi.bitLength() <= 31)
+ {
+ return Integer.valueOf(bi.intValue());
+ }
+ if (bi.bitLength() <= 63)
+ {
+ return Long.valueOf(bi.longValue());
+ }
+ return bi;
+ }
+ throw new NumberFormatException(
+ "val [" + val + "] is not a valid number.");
+ }
+
+ /**
+ * Try to convert a string into a number, boolean, or null. If the string
+ * can't be converted, return the string.
+ *
+ * @param string
+ * A String.
+ * @return A simple JSON value.
+ */
+ // Changes to this method must be copied to the corresponding method in
+ // the XML class to keep full support for Android
+ public static Object stringToValue(String string)
+ {
+ if (string.equals(""))
+ {
+ return string;
+ }
+ if (string.equalsIgnoreCase("true"))
+ {
+ return Boolean.TRUE;
+ }
+ if (string.equalsIgnoreCase("false"))
+ {
+ return Boolean.FALSE;
+ }
+ if (string.equalsIgnoreCase("null"))
+ {
+ return JSONObject.NULL;
+ }
+
+ /*
+ * If it might be a number, try converting it. If a number cannot be produced,
+ * then the value will just be a string.
+ */
+
+ char initial = string.charAt(0);
+ if ((initial >= '0' && initial <= '9') || initial == '-')
+ {
+ try
+ {
+ // if we want full Big Number support this block can be replaced with:
+ // return stringToNumber(string);
+ if (isDecimalNotation(string))
+ {
+ Double d = Double.valueOf(string);
+ if (!d.isInfinite() && !d.isNaN())
+ {
+ return d;
+ }
+ }
+ else
+ {
+ Long myLong = Long.valueOf(string);
+ if (string.equals(myLong.toString()))
+ {
+ if (myLong.longValue() == myLong.intValue())
+ {
+ return Integer.valueOf(myLong.intValue());
+ }
+ return myLong;
+ }
+ }
+ } catch (Exception ignore)
+ {
+ }
+ }
+ return string;
+ }
+
+ /**
+ * Throw an exception if the object is a NaN or infinite number.
+ *
+ * @param o
+ * The object to test.
+ * @throws JSONException
+ * If o is a non-finite number.
+ */
+ public static void testValidity(Object o) throws JSONException
+ {
+ if (o != null)
+ {
+ if (o instanceof Double)
+ {
+ if (((Double) o).isInfinite() || ((Double) o).isNaN())
+ {
+ throw new JSONException(
+ "JSON does not allow non-finite numbers.");
+ }
+ }
+ else if (o instanceof Float)
+ {
+ if (((Float) o).isInfinite() || ((Float) o).isNaN())
+ {
+ throw new JSONException(
+ "JSON does not allow non-finite numbers.");
+ }
+ }
+ }
+ }
+
+ /**
+ * Produce a JSONArray containing the values of the members of this
+ * JSONObject.
+ *
+ * @param names
+ * A JSONArray containing a list of key strings. This determines the
+ * sequence of the values in the result.
+ * @return A JSONArray of values.
+ * @throws JSONException
+ * If any of the values are non-finite numbers.
+ */
+ public JSONArray toJSONArray(JSONArray names) throws JSONException
+ {
+ if (names == null || names.isEmpty())
+ {
+ return null;
+ }
+ JSONArray ja = new JSONArray();
+ for (int i = 0; i < names.length(); i += 1)
+ {
+ ja.put(this.opt(names.getString(i)));
+ }
+ return ja;
+ }
+
+ /**
+ * Make a JSON text of this JSONObject. For compactness, no whitespace is
+ * added. If this would not result in a syntactically correct JSON text, then
+ * null will be returned instead.
+ * <p>
+ * <b> Warning: This method assumes that the data structure is acyclical. </b>
+ *
+ * @return a printable, displayable, portable, transmittable representation of
+ * the object, beginning with <code>{</code> <small>(left
+ * brace)</small> and ending with <code>}</code> <small>(right
+ * brace)</small>.
+ */
+ @Override
+ public String toString()
+ {
+ try
+ {
+ return this.toString(0);
+ } catch (Exception e)
+ {
+ return null;
+ }
+ }
+
+ /**
+ * Make a pretty-printed JSON text of this JSONObject.
+ *
+ * <p>
+ * If <code>indentFactor > 0</code> and the {@link JSONObject} has only one
+ * key, then the object will be output on a single line:
+ *
+ * <pre>
+ * {@code {"key": 1}}
+ * </pre>
+ *
+ * <p>
+ * If an object has 2 or more keys, then it will be output across multiple
+ * lines: <code><pre>{
+ * "key1": 1,
+ * "key2": "value 2",
+ * "key3": 3
+ * }</pre></code>
+ * <p>
+ * <b> Warning: This method assumes that the data structure is acyclical. </b>
+ *
+ * @param indentFactor
+ * The number of spaces to add to each level of indentation.
+ * @return a printable, displayable, portable, transmittable representation of
+ * the object, beginning with <code>{</code> <small>(left
+ * brace)</small> and ending with <code>}</code> <small>(right
+ * brace)</small>.
+ * @throws JSONException
+ * If the object contains an invalid number.
+ */
+ public String toString(int indentFactor) throws JSONException
+ {
+ StringWriter w = new StringWriter();
+ synchronized (w.getBuffer())
+ {
+ return this.write(w, indentFactor, 0).toString();
+ }
+ }
+
+ /**
+ * Make a JSON text of an Object value. If the object has an
+ * value.toJSONString() method, then that method will be used to produce the
+ * JSON text. The method is required to produce a strictly conforming text. If
+ * the object does not contain a toJSONString method (which is the most common
+ * case), then a text will be produced by other means. If the value is an
+ * array or Collection, then a JSONArray will be made from it and its
+ * toJSONString method will be called. If the value is a MAP, then a
+ * JSONObject will be made from it and its toJSONString method will be called.
+ * Otherwise, the value's toString method will be called, and the result will
+ * be quoted.
+ *
+ * <p>
+ * Warning: This method assumes that the data structure is acyclical.
+ *
+ * @param value
+ * The value to be serialized.
+ * @return a printable, displayable, transmittable representation of the
+ * object, beginning with <code>{</code> <small>(left
+ * brace)</small> and ending with <code>}</code> <small>(right
+ * brace)</small>.
+ * @throws JSONException
+ * If the value is or contains an invalid number.
+ */
+ public static String valueToString(Object value) throws JSONException
+ {
+ // moves the implementation to JSONWriter as:
+ // 1. It makes more sense to be part of the writer class
+ // 2. For Android support this method is not available. By implementing it
+ // in
+ // the Writer
+ // Android users can use the writer with the built in Android JSONObject
+ // implementation.
+ return JSONWriter.valueToString(value);
+ }
+
+ /**
+ * Wrap an object, if necessary. If the object is <code>null</code>, return
+ * the NULL object. If it is an array or collection, wrap it in a JSONArray.
+ * If it is a map, wrap it in a JSONObject. If it is a standard property
+ * (Double, String, et al) then it is already wrapped. Otherwise, if it comes
+ * from one of the java packages, turn it into a string. And if it doesn't,
+ * try to wrap it in a JSONObject. If the wrapping fails, then null is
+ * returned.
+ *
+ * @param object
+ * The object to wrap
+ * @return The wrapped value
+ */
+ public static Object wrap(Object object)
+ {
+ try
+ {
+ if (object == null)
+ {
+ return NULL;
+ }
+ if (object instanceof JSONObject || object instanceof JSONArray
+ || NULL.equals(object) || object instanceof JSONString
+ || object instanceof Byte || object instanceof Character
+ || object instanceof Short || object instanceof Integer
+ || object instanceof Long || object instanceof Boolean
+ || object instanceof Float || object instanceof Double
+ || object instanceof String || object instanceof BigInteger
+ || object instanceof BigDecimal || object instanceof Enum)
+ {
+ return object;
+ }
+
+ if (object instanceof Collection)
+ {
+ Collection<?> coll = (Collection<?>) object;
+ return new JSONArray(coll);
+ }
+ if (object.getClass().isArray())
+ {
+ return new JSONArray(object);
+ }
+ if (object instanceof Map)
+ {
+ Map<?, ?> map = (Map<?, ?>) object;
+ return new JSONObject(map);
+ }
+ Package objectPackage = object.getClass().getPackage();
+ String objectPackageName = objectPackage != null
+ ? objectPackage.getName()
+ : "";
+ if (objectPackageName.startsWith("java.")
+ || objectPackageName.startsWith("javax.")
+ || object.getClass().getClassLoader() == null)
+ {
+ return object.toString();
+ }
+ return new JSONObject(object);
+ } catch (Exception exception)
+ {
+ return null;
+ }
+ }
+
+ /**
+ * Write the contents of the JSONObject as JSON text to a writer. For
+ * compactness, no whitespace is added.
+ * <p>
+ * <b> Warning: This method assumes that the data structure is acyclical. </b>
+ *
+ * @return The writer.
+ * @throws JSONException
+ */
+ public Writer write(Writer writer) throws JSONException
+ {
+ return this.write(writer, 0, 0);
+ }
+
+ static final Writer writeValue(Writer writer, Object value,
+ int indentFactor, int indent) throws JSONException, IOException
+ {
+ if (value == null || value.equals(null))
+ {
+ writer.write("null");
+ }
+ else if (value instanceof JSONString)
+ {
+ Object o;
+ try
+ {
+ o = ((JSONString) value).toJSONString();
+ } catch (Exception e)
+ {
+ throw new JSONException(e);
+ }
+ writer.write(o != null ? o.toString() : quote(value.toString()));
+ }
+ else if (value instanceof Number)
+ {
+ // not all Numbers may match actual JSON Numbers. i.e. fractions or
+ // Imaginary
+ final String numberAsString = numberToString((Number) value);
+ try
+ {
+ // Use the BigDecimal constructor for its parser to validate the format.
+ @SuppressWarnings("unused")
+ BigDecimal testNum = new BigDecimal(numberAsString);
+ // Close enough to a JSON number that we will use it unquoted
+ writer.write(numberAsString);
+ } catch (NumberFormatException ex)
+ {
+ // The Number value is not a valid JSON number.
+ // Instead we will quote it as a string
+ quote(numberAsString, writer);
+ }
+ }
+ else if (value instanceof Boolean)
+ {
+ writer.write(value.toString());
+ }
+ else if (value instanceof Enum<?>)
+ {
+ writer.write(quote(((Enum<?>) value).name()));
+ }
+ else if (value instanceof JSONObject)
+ {
+ ((JSONObject) value).write(writer, indentFactor, indent);
+ }
+ else if (value instanceof JSONArray)
+ {
+ ((JSONArray) value).write(writer, indentFactor, indent);
+ }
+ else if (value instanceof Map)
+ {
+ Map<?, ?> map = (Map<?, ?>) value;
+ new JSONObject(map).write(writer, indentFactor, indent);
+ }
+ else if (value instanceof Collection)
+ {
+ Collection<?> coll = (Collection<?>) value;
+ new JSONArray(coll).write(writer, indentFactor, indent);
+ }
+ else if (value.getClass().isArray())
+ {
+ new JSONArray(value).write(writer, indentFactor, indent);
+ }
+ else
+ {
+ quote(value.toString(), writer);
+ }
+ return writer;
+ }
+
+ static final void indent(Writer writer, int indent) throws IOException
+ {
+ for (int i = 0; i < indent; i += 1)
+ {
+ writer.write(' ');
+ }
+ }
+
+ /**
+ * Write the contents of the JSONObject as JSON text to a writer.
+ *
+ * <p>
+ * If <code>indentFactor > 0</code> and the {@link JSONObject} has only one
+ * key, then the object will be output on a single line:
+ *
+ * <pre>
+ * {@code {"key": 1}}
+ * </pre>
+ *
+ * <p>
+ * If an object has 2 or more keys, then it will be output across multiple
+ * lines: <code><pre>{
+ * "key1": 1,
+ * "key2": "value 2",
+ * "key3": 3
+ * }</pre></code>
+ * <p>
+ * <b> Warning: This method assumes that the data structure is acyclical. </b>
+ *
+ * @param writer
+ * Writes the serialized JSON
+ * @param indentFactor
+ * The number of spaces to add to each level of indentation.
+ * @param indent
+ * The indentation of the top level.
+ * @return The writer.
+ * @throws JSONException
+ */
+ public Writer write(Writer writer, int indentFactor, int indent)
+ throws JSONException
+ {
+ try
+ {
+ boolean commanate = false;
+ final int length = this.length();
+ writer.write('{');
+
+ if (length == 1)
+ {
+ final Entry<String, ?> entry = this.entrySet().iterator().next();
+ final String key = entry.getKey();
+ writer.write(quote(key));
+ writer.write(':');
+ if (indentFactor > 0)
+ {
+ writer.write(' ');
+ }
+ try
+ {
+ writeValue(writer, entry.getValue(), indentFactor, indent);
+ } catch (Exception e)
+ {
+ throw new JSONException(
+ "Unable to write JSONObject value for key: " + key, e);
+ }
+ }
+ else if (length != 0)
+ {
+ final int newindent = indent + indentFactor;
+ for (final Entry<String, ?> entry : this.entrySet())
+ {
+ if (commanate)
+ {
+ writer.write(',');
+ }
+ if (indentFactor > 0)
+ {
+ writer.write('\n');
+ }
+ indent(writer, newindent);
+ final String key = entry.getKey();
+ writer.write(quote(key));
+ writer.write(':');
+ if (indentFactor > 0)
+ {
+ writer.write(' ');
+ }
+ try
+ {
+ writeValue(writer, entry.getValue(), indentFactor, newindent);
+ } catch (Exception e)
+ {
+ throw new JSONException(
+ "Unable to write JSONObject value for key: " + key, e);
+ }
+ commanate = true;
+ }
+ if (indentFactor > 0)
+ {
+ writer.write('\n');
+ }
+ indent(writer, indent);
+ }
+ writer.write('}');
+ return writer;
+ } catch (IOException exception)
+ {
+ throw new JSONException(exception);
+ }
+ }
+
+ /**
+ * Returns a java.util.Map containing all of the entries in this object. If an
+ * entry in the object is a JSONArray or JSONObject it will also be converted.
+ * <p>
+ * Warning: This method assumes that the data structure is acyclical.
+ *
+ * @return a java.util.Map containing the entries of this object
+ */
+ public Map<String, Object> toMap()
+ {
+ Map<String, Object> results = new HashMap<String, Object>();
+ for (Entry<String, Object> entry : this.entrySet())
+ {
+ Object value;
+ if (entry.getValue() == null || NULL.equals(entry.getValue()))
+ {
+ value = null;
+ }
+ else if (entry.getValue() instanceof JSONObject)
+ {
+ value = ((JSONObject) entry.getValue()).toMap();
+ }
+ else if (entry.getValue() instanceof JSONArray)
+ {
+ value = ((JSONArray) entry.getValue()).toList();
+ }
+ else
+ {
+ value = entry.getValue();
+ }
+ results.put(entry.getKey(), value);
+ }
+ return results;
+ }
}
import java.awt.Component;
import java.io.File;
+import java.io.IOException;
import java.io.InputStream;
+import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
+import java.util.Map;
import java.util.Properties;
+import java.util.function.Function;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+import javax.swing.JComponent;
import swingjs.api.js.HTML5Applet;
- public interface JSUtilI {
+ public interface JSUtilI
+ {
- /**
- * Indicate to SwingJS that the given file type is binary.
- *
- * @param ext
- */
- void addBinaryFileType(String ext);
-
- /**
- * Indicate to SwingJS that we can load files using AJAX from the given
- * domain, such as "www.stolaf.edu", because we know that CORS access has been
- * provided.
- *
- * @param domain
- */
- void addDirectDatabaseCall(String domain);
-
- /**
- * Cache or uncache data under the given path name.
- *
- * @param path
- * @param data
- * null to remove from the cache
- */
- void cachePathData(String path, Object data);
-
- /**
- * Get the HTML5 object corresponding to the specified Component, or the
- * current thread if null.
- *
- * @param c
- * the associated component, or null for the current thread
- * @return HTML5 applet object
- */
- HTML5Applet getAppletForComponent(Component c);
-
- /**
- * Get an attribute applet.foo for the applet found using getApplet(null).
- *
- * @param key
- * @return
- */
- Object getAppletAttribute(String key);
-
- /**
- * Get the code base (swingjs/j2s, probably) for the applet found using
- * getApplet(null).
- *
- * @return
- */
- URL getCodeBase();
-
- /**
- * Get the document base (wherever the page is) for the applet found using
- * getApplet(null).
- *
- * @return
- */
-
- URL getDocumentBase();
-
- /**
- * Get an attribute from the div on the page that is associated with this
- * frame, i.e. with id frame.getName() + "-div".
- *
- * @param frame
- * @param type
- * "node" or "dim"
- * @return
- */
- Object getEmbeddedAttribute(Component frame, String type);
-
- /**
- * Get a file synchronously.
- *
- * @param path
- * @param asString
- * true for String; false for byte[]
- * @return byte[] or String
- */
- Object getFile(String path, boolean asString);
-
- /**
- * Get the 秘bytes field associated with a file, but only if the File object
- * itself has them attached, not downloading them.
- *
- * @param f
- * @return
- */
- byte[] getBytes(File f);
-
- /**
- * Retrieve a HashMap consisting of whatever the application wants, but
- * guaranteed to be unique to this app context, that is, for the applet found
- * using getApplet(null).
- *
- * @param contextKey
- * @return
- */
- HashMap<?, ?> getJSContext(Object contextKey);
-
- /**
- * Load a resource -- probably a core file -- if and only if a particular
- * class has not been instantialized. We use a String here because if we used
- * a .class object, that reference itself would simply load the class, and we
- * want the core package to include that as well.
- *
- * @param resourcePath
- * @param className
- */
- void loadResourceIfClassUnknown(String resource, String className);
-
- /**
- * Read all applet.__Info properties for the applet found using
- * getApplet(null) that start with the given prefix, such as "jalview_". A
- * null prefix retrieves all properties. Note that non-string properties will
- * be stringified.
- *
- * @param prefix
- * an application prefix, or null for all properties
- * @param p
- * properties to be appended to
- */
- void readInfoProperties(String prefix, Properties p);
-
- /**
- * Set an attribute for the applet found using getApplet(null). That is,
- * applet[key] = val.
- *
- * @param key
- * @param val
- */
- void setAppletAttribute(String key, Object val);
-
- /**
- * Set an attribute of applet's Info map for the applet found using
- * getApplet(null). That is, applet.__Info[key] = val.
- *
- * @param infoKey
- * @param val
- */
- void setAppletInfo(String infoKey, Object val);
-
- /**
- * Set the given File object's 秘bytes field from an InputStream or a byte[]
- * array. If the file is a JSTempFile, then also cache those bytes.
- *
- * @param f
- * @param isOrBytes
- * BufferedInputStream, ByteArrayInputStream, FileInputStream, or
- * byte[]
- * @return
- */
- boolean setFileBytes(File f, Object isOrBytes);
-
- /**
- * Same as setFileBytes, but also caches the data if it is a JSTempFile.
- *
- * @param is
- * @param outFile
- * @return
- */
- boolean streamToFile(InputStream is, File outFile);
-
- /**
- * Switch the flag in SwingJS to use or not use the JavaScript Map object in
- * Hashtable, HashMap, and HashSet. Default is enabled.
- *
- */
-
- void setJavaScriptMapObjectEnabled(boolean enabled);
+ /**
+ * The HTML5 canvas delivers [r g b a r g b a ...] which is not a Java option.
+ * The closest Java option is TYPE_4BYTE_ABGR, but that is not quite what we
+ * need. SwingJS decodes TYPE_4BYTE_HTML5 as TYPE_4BYTE_RGBA"
+ *
+ * ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
+ *
+ * int[] nBits = { 8, 8, 8, 8 };
+ *
+ * int[] bOffs = { 0, 1, 2, 3 };
+ *
+ * colorModel = new ComponentColorModel(cs, nBits, true, false,
+ * Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
+ *
+ * raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height,
+ * width * 4, 4, bOffs, null);
+ *
+ * Note, however, that this buffer type should only be used for direct buffer access
+ * using
+ *
+ *
+ *
+ */
+ public static final int TYPE_4BYTE_HTML5 = -6;
+
+ /**
+ * The HTML5 VIDEO element wrapped in a BufferedImage.
+ *
+ * To be extended to allow video capture?
+ */
+ public static final int TYPE_HTML5_VIDEO = Integer.MIN_VALUE;
+
+ /**
+ * Indicate to SwingJS that the given file type is binary.
+ *
+ * @param ext
+ */
+ void addBinaryFileType(String ext);
+
+ /**
+ * Indicate to SwingJS that we can load files using AJAX from the given domain,
+ * such as "www.stolaf.edu", because we know that CORS access has been provided.
+ *
+ * @param domain
+ */
+ void addDirectDatabaseCall(String domain);
+
+ /**
+ * Cache or uncache data under the given path name.
+ *
+ * @param path
+ * @param data null to remove from the cache
+ */
+ void cachePathData(String path, Object data);
+
+ /**
+ * Get the HTML5 object corresponding to the specified Component, or the current thread if null.
+ *
+ * @param c the associated component, or null for the current thread
+ * @return HTML5 applet object
+ */
+ HTML5Applet getAppletForComponent(Component c);
+
+ /**
+ * Get an attribute applet.foo for the applet found using getApplet(null).
+ *
+ * @param key
+ * @return
+ */
+ Object getAppletAttribute(String key);
+
+
+ /**
+ * Get the applet's __Info map or an attribute of that map for the applet found using
+ * getApplet(null). That is, applet.__Info or applet.__Info[InfoKey].
+ *
+ * @param infoKey if null, return the full __Info map
+ */
+ Object getAppletInfo(String infoKey);
+
+ /**
+ * Get the code base (swingjs/j2s, probably) for the applet found using
+ * getApplet(null).
+ *
+ * @return
+ */
+ URL getCodeBase();
+
+ /**
+ * Get the document base (wherever the page is) for the applet found using
+ * getApplet(null).
+ *
+ * @return
+ */
+
+ URL getDocumentBase();
+
+ /**
+ * Get an attribute from the div on the page that is associated with this frame,
+ * i.e. with id frame.getName() + "-div".
+ *
+ * @param frame
+ * @param type "node" or "dim"
+ * @return
+ */
+ Object getEmbeddedAttribute(Component frame, String type);
+
+ /**
+ * Get a file synchronously.
+ *
+ * @param path
+ * @param asString true for String; false for byte[]
+ * @return byte[] or String
+ */
+ Object getFile(String path, boolean asString);
+
+ /**
+ * Get the 秘bytes field associated with a file, but only if the File object itself has
+ * them attached, not downloading them.
+ *
+ * @param f
+ * @return
+ */
+ byte[] getBytes(File f);
+
+ /**
+ * Retrieve a HashMap consisting of whatever the application wants, but
+ * guaranteed to be unique to this app context, that is, for the applet found using
+ * getApplet(null).
+ *
+ * @param contextKey
+ * @return
+ */
+ HashMap<?, ?> getJSContext(Object contextKey);
+
+ /**
+ * Load a resource -- probably a core file -- if and only if a particular class
+ * has not been instantialized. We use a String here because if we used a .class
+ * object, that reference itself would simply load the class, and we want the
+ * core package to include that as well.
+ *
+ * @param resourcePath
+ * @param className
+ */
+ void loadResourceIfClassUnknown(String resource, String className);
+
+ /**
+ * Read all applet.__Info properties for the applet found using
+ * getApplet(null) that start with the given prefix, such as "jalview_".
+ * A null prefix retrieves all properties. Note that non-string properties will be
+ * stringified.
+ *
+ * @param prefix an application prefix, or null for all properties
+ * @param p properties to be appended to
+ */
+ void readInfoProperties(String prefix, Properties p);
+
+ /**
+ * Set an attribute for the applet found using
+ * getApplet(null). That is, applet[key] = val.
+ *
+ * @param key
+ * @param val
+ */
+ void setAppletAttribute(String key, Object val);
+
+ /**
+ * Set an attribute of applet's Info map for the applet found using
+ * getApplet(null). That is, applet.__Info[key] = val.
+ *
+ * @param infoKey
+ * @param val
+ */
+ void setAppletInfo(String infoKey, Object val);
+
+ /**
+ * Set the given File object's 秘bytes field from an InputStream or a byte[] array.
+ * If the file is a JSTempFile, then also cache those bytes.
+ *
+ * @param f
+ * @param isOrBytes BufferedInputStream, ByteArrayInputStream, FileInputStream, or byte[]
+ * @return
+ */
+ boolean setFileBytes(File f, Object isOrBytes);
+
+ /**
+ * Set the given URL object's _streamData field from an InputStream or a byte[] array.
+ *
+ * @param f
+ * @param isOrBytes BufferedInputStream, ByteArrayInputStream, FileInputStream, or byte[]
+ * @return
+ */
+ boolean setURLBytes(URL url, Object isOrBytes);
+
+ /**
+ * Same as setFileBytes.
+ *
+ * @param is
+ * @param outFile
+ * @return
+ */
+ boolean streamToFile(InputStream is, File outFile);
+
+ /**
+ * Switch the flag in SwingJS to use or not use the JavaScript Map object in
+ * Hashtable, HashMap, and HashSet. Default is enabled.
+ * *
+ */
+ void setJavaScriptMapObjectEnabled(boolean enabled);
+
+
+ /**
+ * Open a URL in a browser tab.
+ *
+ * @param url
+ * @param target null or specific tab, such as "_blank"
+ */
+ void displayURL(String url, String target);
+
+ /**
+ * Retrieve cached bytes for a path (with unnormalized name)
+ * from J2S._javaFileCache.
+ *
+ * @param path
+ *
+ * @return byte[] or null
+ */
+ byte[] getCachedBytes(String path);
+
+ /**
+ * Attach cached bytes to a file-like object, including URL,
+ * or anything having a 秘bytes field (File, URI, Path)
+ * from J2S._javaFileCache. That is, allow two such objects
+ * to share the same underlying byte[ ] array.
+ *
+ *
+ * @param URLorURIorFile
+ * @return byte[] or null
+ */
+ byte[] addJSCachedBytes(Object URLorURIorFile);
+
+ /**
+ * Seek an open ZipInputStream to the supplied ZipEntry, if possible.
+ *
+ * @param zis the ZipInputStream
+ * @param ze the ZipEntry
+ * @return the length of this entry, or -1 if, for whatever reason, this was not possible
+ */
+ long seekZipEntry(ZipInputStream zis, ZipEntry ze);
+
+ /**
+ * Retrieve the byte array associated with a ZipEntry.
+ *
+ * @param ze
+ * @return
+ */
+ byte[] getZipBytes(ZipEntry ze);
+
+ /**
+ * Java 9 method to read all (remaining) bytes from an InputStream. In SwingJS,
+ * this may just create a new reference to an underlying Int8Array without
+ * copying it.
+ *
+ * @param zis
+ * @return
+ * @throws IOException
+ */
+ byte[] readAllBytes(InputStream zis) throws IOException;
+
+ /**
+ * Java 9 method to transfer all (remaining) bytes from an InputStream to an OutputStream.
+ *
+ * @param is
+ * @param out
+ * @return
+ * @throws IOException
+ */
+ long transferTo(InputStream is, OutputStream out) throws IOException;
+
+ /**
+ * Retrieve any bytes already attached to this URL.
+ *
+ * @param url
+ * @return
+ */
+ byte[] getURLBytes(URL url);
+
+ /**
+ * Set a message in the lower-left-hand corner SwingJS status block.
+ *
+ * @param msg
+ * @param doFadeOut
+ */
+ void showStatus(String msg, boolean doFadeOut);
+
+ /**
+ * Asynchronously retrieve the byte[] for a URL.
+ *
+ * @param url
+ * @param whenDone
+ */
+ void getURLBytesAsync(URL url, Function<byte[], Void> whenDone);
+
+ /**
+ * Experimental method to completely disable a Swing Component's user interface.
+ *
+ * @param jc
+ * @param enabled
+ */
+ void setUIEnabled(JComponent jc, boolean enabled);
+
+
+ /**
+ * Play an audio
+ * @param buffer
+ * @param format a javax.sound.sampled.AudioFormat
+ * @throws Exception
+ */
+ void playAudio(byte[] buffer, Object format) throws Exception;
+
+ /**
+ * For either an applet or an application, get the ORIGINAL __Info as a Map that
+ * has a full set up lower-case keys along with whatever non-all-lower-case keys
+ * provided at start-up.
+ *
+ * @return
+ */
+ Map<String, Object> getAppletInfoAsMap();
+
+
+ void setAppClass(Object j);
}
import jalview.datamodel.AlignmentAnnotation;
import jalview.datamodel.Annotation;
+import jalview.datamodel.HiddenMarkovModel;
import jalview.datamodel.Profile;
import jalview.datamodel.ProfileI;
+import jalview.datamodel.Profiles;
import jalview.datamodel.ProfilesI;
import jalview.datamodel.ResidueCount;
import jalview.datamodel.Sequence;
import jalview.datamodel.SequenceI;
import jalview.gui.JvOptionPane;
+import jalview.io.DataSourceType;
+import jalview.io.FileParse;
+import jalview.io.HMMFile;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
import java.util.Hashtable;
public class AAFrequencyTest
{
+ HiddenMarkovModel hmm;
@BeforeClass(alwaysRun = true)
public void setUpJvOptionPane()
JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
}
+ @BeforeClass(alwaysRun = true)
+ public void setUp() throws IOException, MalformedURLException
+ {
+ /*
+ * load a dna (ACGT) HMM file to a HiddenMarkovModel
+ */
+ HMMFile hmmFile = new HMMFile(new FileParse(
+ "test/jalview/io/test_MADE1_hmm.txt", DataSourceType.FILE));
+ hmm = hmmFile.getHMM();
+ }
+
@Test(groups = { "Functional" })
public void testCalculate_noProfile()
{
SequenceI seq4 = new Sequence("Seq4", "CA--t");
SequenceI[] seqs = new SequenceI[] { seq1, seq2, seq3, seq4 };
int width = seq1.getLength();
- ProfilesI result = AAFrequency.calculate(seqs, width, 0, width,
- false);
+ ProfilesI result = AAFrequency.calculate(seqs, width, 0, width, false);
// col 0 is 100% C
ProfileI col = result.get(0);
SequenceI seq4 = new Sequence("Seq4", "CA-t");
SequenceI[] seqs = new SequenceI[] { seq1, seq2, seq3, seq4 };
int width = seq1.getLength();
- ProfilesI result = AAFrequency.calculate(seqs, width, 0, width,
- true);
+ ProfilesI result = AAFrequency.calculate(seqs, width, 0, width, true);
ProfileI profile = result.get(0);
assertEquals(4, profile.getCounts().getCount('C'));
AlignmentAnnotation consensus = new AlignmentAnnotation("Consensus",
"PID", new Annotation[width]);
- AAFrequency
- .completeConsensus(consensus, profiles, 0, 5, false, true, 4);
+ AAFrequency.completeConsensus(consensus, profiles, 0, 5, false, true,
+ 4);
Annotation ann = consensus.annotations[0];
assertEquals("C 100%", ann.description);
SequenceI[] seqs = new SequenceI[] { seq1, seq2, seq3, seq4 };
int width = seq1.getLength();
ProfilesI profiles = AAFrequency.calculate(seqs, width, 0, width, true);
-
+
AlignmentAnnotation consensus = new AlignmentAnnotation("Consensus",
"PID", new Annotation[width]);
- AAFrequency
- .completeConsensus(consensus, profiles, 0, 5, true, false, 4);
-
+ AAFrequency.completeConsensus(consensus, profiles, 0, 5, true, false,
+ 4);
+
Annotation ann = consensus.annotations[0];
assertEquals("C 100%", ann.description);
assertEquals("C", ann.displayCharacter);
counts.put('L', 38);
counts.put('H', 2);
profile.setCounts(counts);
-
+
/*
* [0, noOfValues, totalPercent, char1, count1, ...]
* G: 70/200 = 35%
*/
int[] extracted = AAFrequency.extractProfile(profile, false);
int[] expected = new int[] { AlignmentAnnotation.SEQUENCE_PROFILE, 4,
- 85, 'G', 35, 'R', 30, 'L', 19, 'H',
- 1 };
+ 85, 'G', 35, 'R', 30, 'L', 19, 'H', 1 };
org.testng.Assert.assertEquals(extracted, expected);
-
+
/*
* add some counts of 1; these round down to 0% and should be discarded
*/
expected = new int[] { AlignmentAnnotation.SEQUENCE_PROFILE, 4, 84, 'G',
34, 'R', 30, 'L', 19, 'H', 1 };
org.testng.Assert.assertEquals(extracted, expected);
-
+
}
@Test(groups = { "Functional" })
codonCounts[0] = 120;
codonCounts[1] = 110;
profile.put(AAFrequency.PROFILE, codonCounts);
-
+
/*
* [0, noOfValues, totalPercent, char1, count1, ...]
* codon1: 30/110 = 27.2 = 27%
* max count 70 for modal residue 'G'
*/
Hashtable profile = new Hashtable();
-
+
/*
* cdna profile is {seqCount, ungappedCount, codonCount1, ...codonCount64}
* where 1..64 positions correspond to encoded codons
codonCounts[0] = 120;
codonCounts[1] = 110;
profile.put(AAFrequency.PROFILE, codonCounts);
-
+
/*
* [0, noOfValues, totalPercent, char1, count1, ...]
* codon1: 30/120 = 25%
encoded2, 58, encoded1, 25, encoded3, 7 };
org.testng.Assert.assertEquals(extracted, expected);
}
+
+ @Test(groups = { "Functional" })
+ public void testExtractHMMProfile()
+ throws MalformedURLException, IOException
+ {
+ int[] expected = { 0, 4, 100, 'T', 71, 'C', 12, 'G', 9, 'A', 9 };
+ int[] actual = AAFrequency.extractHMMProfile(hmm, 17, false, false);
+ for (int i = 0; i < actual.length; i++)
+ {
+ if (i == 2)
+ {
+ assertEquals(actual[i], expected[i]);
+ }
+ else
+ {
+ assertEquals(actual[i], expected[i]);
+ }
+ }
+
+ int[] expected2 = { 0, 4, 100, 'A', 85, 'C', 0, 'G', 0, 'T', 0 };
+ int[] actual2 = AAFrequency.extractHMMProfile(hmm, 2, true, false);
+ for (int i = 0; i < actual2.length; i++)
+ {
+ if (i == 2)
+ {
+ assertEquals(actual[i], expected[i]);
+ }
+ else
+ {
+ assertEquals(actual[i], expected[i]);
+ }
+ }
+
+ assertNull(AAFrequency.extractHMMProfile(null, 98978867, true, false));
+ }
+
+ @Test(groups = { "Functional" })
+ public void testGetAnalogueCount()
+ {
+ /*
+ * 'T' in column 0 has emission probability 0.7859, scales to 7859
+ */
+ int count = AAFrequency.getAnalogueCount(hmm, 0, 'T', false, false);
+ assertEquals(7859, count);
+
+ /*
+ * same with 'use info height': value is multiplied by log ratio
+ * log(value / background) / log(2) = log(0.7859/0.25)/0.693
+ * = log(3.1)/0.693 = 1.145/0.693 = 1.66
+ * so value becomes 1.2987 and scales up to 12987
+ */
+ count = AAFrequency.getAnalogueCount(hmm, 0, 'T', false, true);
+ assertEquals(12987, count);
+
+ /*
+ * 'G' in column 20 has emission probability 0.75457, scales to 7546
+ */
+ count = AAFrequency.getAnalogueCount(hmm, 20, 'G', false, false);
+ assertEquals(7546, count);
+
+ /*
+ * 'G' in column 1077 has emission probability 0.0533, here
+ * ignored (set to 0) since below background of 0.25
+ */
+ count = AAFrequency.getAnalogueCount(hmm, 1077, 'G', true, false);
+ assertEquals(0, count);
+ }
+
+ @Test(groups = { "Functional" })
+ public void testCompleteInformation()
+ {
+ ProfileI prof1 = new Profile(1, 0, 100, "A");
+ ProfileI prof2 = new Profile(1, 0, 100, "-");
+
+ ProfilesI profs = new Profiles(new ProfileI[] { prof1, prof2 });
+ Annotation ann1 = new Annotation(6.5f);
+ Annotation ann2 = new Annotation(0f);
+ Annotation[] annots = new Annotation[] { ann1, ann2 };
+ SequenceI seq = new Sequence("", "AA", 0, 0);
+ seq.setHMM(hmm);
+ AlignmentAnnotation annot = new AlignmentAnnotation("", "", annots);
+ annot.setSequenceRef(seq);
+ AAFrequency.completeInformation(annot, profs, 0, 1);
+ float ic = annot.annotations[0].value;
+ assertEquals(0.91532f, ic, 0.0001f);
+ ic = annot.annotations[1].value;
+ assertEquals(0f, ic, 0.0001f);
+ int i = 0;
+ }
}
import java.util.Locale;
-import jalview.datamodel.Alignment;
-import jalview.datamodel.AlignmentI;
-import jalview.datamodel.Sequence;
-import jalview.datamodel.SequenceI;
-import jalview.gui.JvOptionPane;
-import jalview.io.FastaFile;
-
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Random;
-import org.testng.annotations.BeforeClass;
+import jalview.datamodel.Alignment;
+import jalview.datamodel.AlignmentI;
+import jalview.datamodel.Sequence;
+import jalview.datamodel.SequenceI;
+import jalview.io.FastaFile;
/**
- * Generates, and outputs in Fasta format, a random peptide or nucleotide alignment for given
- * sequence length and count. Will regenerate the same alignment each time if
- * the same random seed is used (so may be used for reproducible unit tests).
- * Not guaranteed to reproduce the same results between versions, as the rules
- * may get tweaked to produce more 'realistic' results.
+ * Generates, and outputs in Fasta format, a random peptide or nucleotide
+ * alignment for given sequence length and count. Will regenerate the same
+ * alignment each time if the same random seed is used (so may be used for
+ * reproducible unit tests). Not guaranteed to reproduce the same results
+ * between versions, as the rules may get tweaked to produce more 'realistic'
+ * results.
*
* @author gmcarstairs
*/
int gapPercentage = Integer.valueOf(args[4]);
int changePercentage = Integer.valueOf(args[5]);
- ps.println("; " + height + " sequences of " + width
- + " bases with " + gapPercentage + "% gaps and "
- + changePercentage + "% mutations (random seed = " + randomSeed
- + ")");
+ ps.println("; " + height + " sequences of " + width + " bases with "
+ + gapPercentage + "% gaps and " + changePercentage
+ + "% mutations (random seed = " + randomSeed + ")");
new AlignmentGenerator(nucleotide, ps).generate(width, height,
randomSeed, gapPercentage, changePercentage);
System.out.println("arg0: n (for nucleotide) or p (for peptide)");
System.out.println("arg1: number of (non-gap) bases per sequence");
System.out.println("arg2: number of sequences");
- System.out
- .println("arg3: an integer as random seed (same seed = same results)");
+ System.out.println(
+ "arg3: an integer as random seed (same seed = same results)");
System.out.println("arg4: percentage of gaps to (randomly) generate");
- System.out
- .println("arg5: percentage of 'mutations' to (randomly) generate");
- System.out
- .println("arg6: (optional) path to output file (default is sysout)");
+ System.out.println(
+ "arg5: percentage of 'mutations' to (randomly) generate");
+ System.out.println(
+ "arg6: (optional) path to output file (default is sysout)");
System.out.println("Example: AlignmentGenerator n 12 15 387 10 5");
- System.out
- .println("- 15 nucleotide sequences of 12 bases each, approx 10% gaps and 5% mutations, random seed = 387");
+ System.out.println(
+ "- 15 nucleotide sequences of 12 bases each, approx 10% gaps and 5% mutations, random seed = 387");
}
for (int count = 0; count < length;)
{
boolean addGap = random.nextInt(100) < gapPercentage;
- char c = addGap ? GAP : BASES[random.nextInt(Integer.MAX_VALUE)
- % BASES.length];
+ char c = addGap ? GAP
+ : BASES[random.nextInt(Integer.MAX_VALUE) % BASES.length];
seq.append(c);
if (!addGap)
{
* @param changePercentage
* @return
*/
- private SequenceI generateAnotherSequence(char[] ds, int seqno,
- int width, int changePercentage)
+ private SequenceI generateAnotherSequence(char[] ds, int seqno, int width,
+ int changePercentage)
{
int length = ds.length;
char[] seq = new char[length];
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.analysis;
import static org.testng.Assert.assertSame;
/*
* sort with no score features does nothing
*/
- PA.setValue(AlignmentSorter.class, "sortByFeatureCriteria", null);
+ PA.setValue(AlignmentSorter.getInstance(), "sortByFeatureCriteria", null);
AlignmentSorter.sortByFeature(null, null, 0, al.getWidth(), al,
AlignmentSorter.FEATURE_SCORE);
* seq3 KD(-4), KD(3.0) average -0.5
* seq4 Helix(NaN) - should sort as if largest score
*/
- seq1.addSequenceFeature(new SequenceFeature("Cath", "", 2, 3, 2.0f,
- "g1"));
- seq1.addSequenceFeature(new SequenceFeature("Pfam", "", 4, 5, 4.0f,
- "g2"));
- seq2.addSequenceFeature(new SequenceFeature("Cath", "", 2, 3, 2.5f,
- "g3"));
- seq2.addSequenceFeature(new SequenceFeature("Metal", "", 2, 3,
- Float.NaN, "g4"));
+ seq1.addSequenceFeature(
+ new SequenceFeature("Cath", "", 2, 3, 2.0f, "g1"));
+ seq1.addSequenceFeature(
+ new SequenceFeature("Pfam", "", 4, 5, 4.0f, "g2"));
+ seq2.addSequenceFeature(
+ new SequenceFeature("Cath", "", 2, 3, 2.5f, "g3"));
+ seq2.addSequenceFeature(
+ new SequenceFeature("Metal", "", 2, 3, Float.NaN, "g4"));
seq3.addSequenceFeature(new SequenceFeature("kD", "", 2, 3, -4f, "g5"));
- seq3.addSequenceFeature(new SequenceFeature("kD", "", 5, 6, 3.0f, "g6"));
- seq4.addSequenceFeature(new SequenceFeature("Helix", "", 2, 3,
- Float.NaN, "g7"));
+ seq3.addSequenceFeature(
+ new SequenceFeature("kD", "", 5, 6, 3.0f, "g6"));
+ seq4.addSequenceFeature(
+ new SequenceFeature("Helix", "", 2, 3, Float.NaN, "g7"));
/*
* sort by ascending score, no filter on feature type or group
* NB sort order for the same feature set (none) gets toggled, so descending
*/
- PA.setValue(AlignmentSorter.class, "sortByFeatureAscending", true);
+ PA.setValue(AlignmentSorter.getInstance(), "sortByFeatureAscending", true);
AlignmentSorter.sortByFeature(null, null, 0, al.getWidth(), al,
AlignmentSorter.FEATURE_SCORE);
assertSame(al.getSequenceAt(3), seq3); // -0.5
* seq3 average is now 3.0
* next sort is ascending (not toggled) as for a different group spec
*/
- List<String> groups = Arrays.asList(new String[] { "g1", "g2", "g3",
- "g6" });
+ List<String> groups = Arrays
+ .asList(new String[]
+ { "g1", "g2", "g3", "g6" });
AlignmentSorter.sortByFeature(types, groups, 0, al.getWidth(), al,
AlignmentSorter.FEATURE_SCORE);
assertSame(al.getSequenceAt(0), seq1); // 2.0
import static org.testng.AssertJUnit.assertSame;
import static org.testng.AssertJUnit.assertTrue;
-import jalview.analysis.AlignmentUtils.DnaVariant;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
import jalview.datamodel.AlignedCodonFrame;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentAnnotation;
import jalview.datamodel.Sequence;
import jalview.datamodel.SequenceFeature;
import jalview.datamodel.SequenceI;
-import jalview.datamodel.features.SequenceFeatures;
import jalview.gui.JvOptionPane;
import jalview.io.AppletFormatAdapter;
import jalview.io.DataSourceType;
import jalview.io.gff.SequenceOntologyI;
import jalview.util.MapList;
import jalview.util.MappingUtils;
-import jalview.ws.params.InvalidArgumentException;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
-
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
public class AlignmentUtilsTests
{
SequenceI s1 = ts.deriveSequence().getSubSequence(i, i + 7);
al.addSequence(s1);
}
- System.out.println(new AppletFormatAdapter().formatSequences(
- FileFormat.Clustal,
- al, true));
+ System.out.println(new AppletFormatAdapter()
+ .formatSequences(FileFormat.Clustal, al, true));
for (int flnk = -1; flnk < 25; flnk++)
{
AlignmentI exp = AlignmentUtils.expandContext(al, flnk);
System.out.println("\nFlank size: " + flnk);
- System.out.println(new AppletFormatAdapter().formatSequences(
- FileFormat.Clustal, exp, true));
+ System.out.println(new AppletFormatAdapter()
+ .formatSequences(FileFormat.Clustal, exp, true));
if (flnk == -1)
{
/*
{
String ung = sq.getSequenceAsString().replaceAll("-+", "");
final String errorMsg = "Flanking sequence not the same as original dataset sequence.\n"
- + ung
- + "\n"
+ + ung + "\n"
+ sq.getDatasetSequence().getSequenceAsString();
- assertTrue(errorMsg, ung.equalsIgnoreCase(sq.getDatasetSequence()
- .getSequenceAsString()));
+ assertTrue(errorMsg, ung.equalsIgnoreCase(
+ sq.getDatasetSequence().getSequenceAsString()));
}
}
else if (flnk == 24)
* Expand the subsequence to the full sequence abcDEFghi
*/
AlignmentI expanded = AlignmentUtils.expandContext(al, -1);
- assertEquals("abcDEFghi", expanded.getSequenceAt(0)
- .getSequenceAsString());
+ assertEquals("abcDEFghi",
+ expanded.getSequenceAt(0).getSequenceAsString());
/*
* Confirm the alignment and sequence have the same SS annotation,
protected AlignmentI loadAlignment(final String data, FileFormatI format)
throws IOException
{
- AlignmentI a = new FormatAdapter().readFile(data,
- DataSourceType.PASTE, format);
+ AlignmentI a = new FormatAdapter().readFile(data, DataSourceType.PASTE,
+ format);
a.setDataset(null);
return a;
}
MapList mapList = protMappings[0].getMap();
assertEquals(3, mapList.getFromRatio());
assertEquals(1, mapList.getToRatio());
- assertTrue(Arrays.equals(new int[] { 1, 9 }, mapList.getFromRanges()
- .get(0)));
+ assertTrue(
+ Arrays.equals(new int[]
+ { 1, 9 }, mapList.getFromRanges().get(0)));
assertEquals(1, mapList.getFromRanges().size());
- assertTrue(Arrays.equals(new int[] { 1, 3 },
- mapList.getToRanges().get(0)));
+ assertTrue(
+ Arrays.equals(new int[]
+ { 1, 3 }, mapList.getToRanges().get(0)));
assertEquals(1, mapList.getToRanges().size());
// V12346 mapped to A33333
* Exons at codon 2 (AAA) and 4 (TTT)
*/
MapList map = new MapList(new int[] { 4, 6, 10, 12 },
- new int[] { 1, 2 }, 3, 1);
+ new int[]
+ { 1, 2 }, 3, 1);
/*
* Simple case: no gaps in dna
/*
* Add gaps to dna - but ignore when realigning.
*/
- checkAlignSequenceAs("-G-G-G--A--A---AC-CC-T-TT-GG-G-", "--A-L-",
- false, false, map, "GGG---AAACCCTTTGGG");
+ checkAlignSequenceAs("-G-G-G--A--A---AC-CC-T-TT-GG-G-", "--A-L-", false,
+ false, map, "GGG---AAACCCTTTGGG");
/*
* Add gaps to dna - include within exons only when realigning.
*/
- checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-",
- true, false, map, "GGG---A--A---ACCCT-TTGGG");
+ checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-", true,
+ false, map, "GGG---A--A---ACCCT-TTGGG");
/*
* Include gaps outside exons only when realigning.
/*
* Include gaps following first intron if we are 'preserving mapped gaps'
*/
- checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-",
- true, true, map, "-G-G-G--A--A---A-C-CC-T-TT-GG-G-");
+ checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-", true,
+ true, map, "-G-G-G--A--A---A-C-CC-T-TT-GG-G-");
/*
* Include all gaps in dna when realigning.
*/
- checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-",
- true, true, map, "-G-G-G--A--A---A-C-CC-T-TT-GG-G-");
+ checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-", true,
+ true, map, "-G-G-G--A--A---A-C-CC-T-TT-GG-G-");
}
/**
/*
* Exons at codon 2 (AAA) and 4 (TTT) mapped to A and P
*/
- final MapList map = new MapList(new int[] { 4, 6, 10, 12 }, new int[] {
- 1, 1, 3, 3 }, 3, 1);
+ final MapList map = new MapList(new int[] { 4, 6, 10, 12 },
+ new int[]
+ { 1, 1, 3, 3 }, 3, 1);
/*
* -L- 'aligns' ccc------
SequenceI alignFrom = new Sequence("Seq2", alignModel);
alignFrom.createDatasetSequence();
AlignedCodonFrame acf = new AlignedCodonFrame();
- acf.addMap(alignMe.getDatasetSequence(),
- alignFrom.getDatasetSequence(), map);
+ acf.addMap(alignMe.getDatasetSequence(), alignFrom.getDatasetSequence(),
+ map);
AlignmentUtils.alignSequenceAs(alignMe, alignFrom, acf, "---", '-',
preserveMappedGaps, preserveUnmappedGaps);
/*
* Intron GGGAAA followed by exon CCCTTT
*/
- MapList map = new MapList(new int[] { 7, 12 }, new int[] { 1, 2 }, 3, 1);
+ MapList map = new MapList(new int[] { 7, 12 }, new int[] { 1, 2 }, 3,
+ 1);
checkAlignSequenceAs("GG-G-AA-A-C-CC-T-TT", "AL", false, true, map,
"GG-G-AA-ACCCTTT");
SequenceI prot2 = new Sequence("Seq2", "CHYQ");
SequenceI prot3 = new Sequence("Seq3", "CHYQ");
SequenceI prot4 = new Sequence("Seq4", "R-QSV"); // unmapped, unchanged
- AlignmentI protein = new Alignment(new SequenceI[] { prot1, prot2,
- prot3, prot4 });
+ AlignmentI protein = new Alignment(
+ new SequenceI[]
+ { prot1, prot2, prot3, prot4 });
protein.setDataset(null);
- MapList map = new MapList(new int[] { 1, 12 }, new int[] { 1, 4 }, 3, 1);
+ MapList map = new MapList(new int[] { 1, 12 }, new int[] { 1, 4 }, 3,
+ 1);
AlignedCodonFrame acf = new AlignedCodonFrame();
acf.addMap(dna1.getDatasetSequence(), prot1.getDatasetSequence(), map);
acf.addMap(dna2.getDatasetSequence(), prot2.getDatasetSequence(), map);
"F*PK*G".toCharArray()));
// wrong protein
- assertFalse(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(),
- 0, "FPMG".toCharArray()));
+ assertFalse(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(), 0,
+ "FPMG".toCharArray()));
// truncated dna
assertFalse(AlignmentUtils.translatesAs("tttcccaaagg".toCharArray(), 0,
"FPKG".toCharArray()));
// truncated protein
- assertFalse(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(),
- 0, "FPK".toCharArray()));
+ assertFalse(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(), 0,
+ "FPK".toCharArray()));
// overlong dna (doesn't end in stop codon)
- assertFalse(AlignmentUtils.translatesAs(
- "tttcccaaagggttt".toCharArray(), 0, "FPKG".toCharArray()));
+ assertFalse(AlignmentUtils.translatesAs("tttcccaaagggttt".toCharArray(),
+ 0, "FPKG".toCharArray()));
// dna + stop codon + more
assertFalse(AlignmentUtils.translatesAs(
"tttcccaaagggttaga".toCharArray(), 0, "FPKG".toCharArray()));
// overlong protein
- assertFalse(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(),
- 0, "FPKGQ".toCharArray()));
+ assertFalse(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(), 0,
+ "FPKGQ".toCharArray()));
}
/**
MapList mapList = protMappings[0].getMap();
assertEquals(3, mapList.getFromRatio());
assertEquals(1, mapList.getToRatio());
- assertTrue(Arrays.equals(new int[] { 1, 9 }, mapList.getFromRanges()
- .get(0)));
+ assertTrue(
+ Arrays.equals(new int[]
+ { 1, 9 }, mapList.getFromRanges().get(0)));
assertEquals(1, mapList.getFromRanges().size());
- assertTrue(Arrays.equals(new int[] { 1, 3 },
- mapList.getToRanges().get(0)));
+ assertTrue(
+ Arrays.equals(new int[]
+ { 1, 3 }, mapList.getToRanges().get(0)));
assertEquals(1, mapList.getToRanges().size());
// V12346 mapped from A33333 starting position 4
mapList = protMappings[0].getMap();
assertEquals(3, mapList.getFromRatio());
assertEquals(1, mapList.getToRatio());
- assertTrue(Arrays.equals(new int[] { 4, 12 }, mapList.getFromRanges()
- .get(0)));
+ assertTrue(
+ Arrays.equals(new int[]
+ { 4, 12 }, mapList.getFromRanges().get(0)));
assertEquals(1, mapList.getFromRanges().size());
- assertTrue(Arrays.equals(new int[] { 1, 3 },
- mapList.getToRanges().get(0)));
+ assertTrue(
+ Arrays.equals(new int[]
+ { 1, 3 }, mapList.getToRanges().get(0)));
assertEquals(1, mapList.getToRanges().size());
// V12347 mapped to A11111 starting position 4
mapList = protMappings[0].getMap();
assertEquals(3, mapList.getFromRatio());
assertEquals(1, mapList.getToRatio());
- assertTrue(Arrays.equals(new int[] { 4, 12 }, mapList.getFromRanges()
- .get(0)));
+ assertTrue(
+ Arrays.equals(new int[]
+ { 4, 12 }, mapList.getFromRanges().get(0)));
assertEquals(1, mapList.getFromRanges().size());
- assertTrue(Arrays.equals(new int[] { 1, 3 },
- mapList.getToRanges().get(0)));
+ assertTrue(
+ Arrays.equals(new int[]
+ { 1, 3 }, mapList.getToRanges().get(0)));
assertEquals(1, mapList.getToRanges().size());
// no mapping involving the 'extra' A44444
List<SequenceI> dnaseqs = new ArrayList<>();
dnaseqs.add(new Sequence("EMBL|A11111", "GAAATCCAG")); // = EIQ
dnaseqs.add(new Sequence("EMBL|A22222", "GAAATTCAG")); // = EIQ
- AlignmentI cdna = new Alignment(dnaseqs.toArray(new SequenceI[dnaseqs
- .size()]));
+ AlignmentI cdna = new Alignment(
+ dnaseqs.toArray(new SequenceI[dnaseqs.size()]));
cdna.setDataset(null);
// Xref A22222 to V12345 (should get mapped)
ann2.setSequenceRef(seq2);
AlignmentAnnotation ann3 = new AlignmentAnnotation("Structure", "ann3",
anns);
- AlignmentAnnotation ann4 = new AlignmentAnnotation("Temp", "ann4", anns);
+ AlignmentAnnotation ann4 = new AlignmentAnnotation("Temp", "ann4",
+ anns);
ann4.setSequenceRef(seq1);
- AlignmentAnnotation ann5 = new AlignmentAnnotation("Temp", "ann5", anns);
+ AlignmentAnnotation ann5 = new AlignmentAnnotation("Temp", "ann5",
+ anns);
ann5.setSequenceRef(seq2);
- AlignmentAnnotation ann6 = new AlignmentAnnotation("Temp", "ann6", anns);
+ AlignmentAnnotation ann6 = new AlignmentAnnotation("Temp", "ann6",
+ anns);
AlignmentI al = new Alignment(new SequenceI[] { seq1, seq2, seq3 });
al.addAnnotation(ann1); // Structure for Seq1
al.addAnnotation(ann2); // Structure for Seq2
assertTrue(AlignmentUtils.haveCrossRef(seq2, seq1));
// now the other way round
- seq1.setDBRefs(null);
+ seq1.setDBRefs(null);
seq2.addDBRef(new DBRefEntry("EMBL", "1", "A12345"));
assertTrue(AlignmentUtils.haveCrossRef(seq1, seq2));
assertTrue(AlignmentUtils.haveCrossRef(seq2, seq1));
* put a variant feature on dna2 base 8
* - should transfer to cds2 base 5
*/
- dna2.addSequenceFeature(new SequenceFeature("variant", "hgmd", 8, 8,
- 0f, null));
+ dna2.addSequenceFeature(
+ new SequenceFeature("variant", "hgmd", 8, 8, 0f, null));
/*
* need a sourceDbRef if we are to construct dbrefs to the CDS
* CDS sequences are 'discovered' from dna-to-protein mappings on the alignment
* dataset (e.g. added from dbrefs by CrossRef.findXrefSequences)
*/
- MapList mapfordna1 = new MapList(new int[] { 4, 6, 10, 12 }, new int[] {
- 1, 2 }, 3, 1);
+ MapList mapfordna1 = new MapList(new int[] { 4, 6, 10, 12 },
+ new int[]
+ { 1, 2 }, 3, 1);
AlignedCodonFrame acf = new AlignedCodonFrame();
acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(),
mapfordna1);
dna.addCodonFrame(acf);
MapList mapfordna2 = new MapList(new int[] { 1, 3, 7, 9, 13, 15 },
- new int[] { 1, 3 }, 3, 1);
+ new int[]
+ { 1, 3 }, 3, 1);
acf = new AlignedCodonFrame();
acf.addMap(dna2.getDatasetSequence(), pep2.getDatasetSequence(),
mapfordna2);
/*
* execute method under test:
*/
- AlignmentI cds = AlignmentUtils.makeCdsAlignment(new SequenceI[] {
- dna1, dna2 }, dna.getDataset(), null);
+ AlignmentI cds = AlignmentUtils
+ .makeCdsAlignment(new SequenceI[]
+ { dna1, dna2 }, dna.getDataset(), null);
/*
* verify cds sequences
assertEquals(dna1xref.getAccessionId(), dbref.getAccessionId());
assertNotNull(dbref.getMap());
assertSame(pep1.getDatasetSequence(), dbref.getMap().getTo());
- MapList cdsMapping = new MapList(new int[] { 1, 6 },
- new int[] { 1, 2 }, 3, 1);
+ MapList cdsMapping = new MapList(new int[] { 1, 6 }, new int[] { 1, 2 },
+ 3, 1);
assertEquals(cdsMapping, dbref.getMap().getMap());
/*
DBRefEntry dbRefEntry = dna1.getDBRefs().get(2);
assertSame(cds1Dss, dbRefEntry.getMap().getTo());
MapList dnaToCdsMapping = new MapList(new int[] { 4, 6, 10, 12 },
- new int[] { 1, 6 }, 1, 1);
+ new int[]
+ { 1, 6 }, 1, 1);
assertEquals(dnaToCdsMapping, dbRefEntry.getMap().getMap());
assertEquals(3, dna2.getDBRefs().size());
dbRefEntry = dna2.getDBRefs().get(2);
assertSame(cds2Dss, dbRefEntry.getMap().getTo());
dnaToCdsMapping = new MapList(new int[] { 1, 3, 7, 9, 13, 15 },
- new int[] { 1, 9 }, 1, 1);
+ new int[]
+ { 1, 9 }, 1, 1);
assertEquals(dnaToCdsMapping, dbRefEntry.getMap().getMap());
/*
assertEquals(2, cds1Dss.getDBRefs().size());
dbRefEntry = cds1Dss.getDBRefs().get(1);
assertSame(dna1.getDatasetSequence(), dbRefEntry.getMap().getTo());
- MapList cdsToDnaMapping = new MapList(new int[] { 1, 6 }, new int[] {
- 4, 6, 10, 12 }, 1, 1);
+ MapList cdsToDnaMapping = new MapList(new int[] { 1, 6 },
+ new int[]
+ { 4, 6, 10, 12 }, 1, 1);
assertEquals(cdsToDnaMapping, dbRefEntry.getMap().getMap());
assertEquals(2, cds2Dss.getDBRefs().size());
dbRefEntry = cds2Dss.getDBRefs().get(1);
assertSame(dna2.getDatasetSequence(), dbRefEntry.getMap().getTo());
- cdsToDnaMapping = new MapList(new int[] { 1, 9 }, new int[] { 1, 3, 7,
- 9, 13, 15 }, 1, 1);
+ cdsToDnaMapping = new MapList(new int[] { 1, 9 },
+ new int[]
+ { 1, 3, 7, 9, 13, 15 }, 1, 1);
assertEquals(cdsToDnaMapping, dbRefEntry.getMap().getMap());
/*
pep1.createDatasetSequence();
pep2.createDatasetSequence();
pep3.createDatasetSequence();
- pep1.getDatasetSequence().addDBRef(
- new DBRefEntry("EMBLCDS", "2", "A12345"));
- pep2.getDatasetSequence().addDBRef(
- new DBRefEntry("EMBLCDS", "3", "A12346"));
- pep3.getDatasetSequence().addDBRef(
- new DBRefEntry("EMBLCDS", "4", "A12347"));
+ pep1.getDatasetSequence()
+ .addDBRef(new DBRefEntry("EMBLCDS", "2", "A12345"));
+ pep2.getDatasetSequence()
+ .addDBRef(new DBRefEntry("EMBLCDS", "3", "A12346"));
+ pep3.getDatasetSequence()
+ .addDBRef(new DBRefEntry("EMBLCDS", "4", "A12347"));
/*
* Create the CDS alignment
*/
// map ...GGG...TTT to GF
MapList map = new MapList(new int[] { 4, 6, 10, 12 },
- new int[] { 1, 2 }, 3, 1);
+ new int[]
+ { 1, 2 }, 3, 1);
AlignedCodonFrame acf = new AlignedCodonFrame();
acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
dna.addCodonFrame(acf);
/*
* execute method under test
*/
- AlignmentI cdsal = AlignmentUtils.makeCdsAlignment(
- new SequenceI[] { dna1 }, dna.getDataset(), null);
+ AlignmentI cdsal = AlignmentUtils
+ .makeCdsAlignment(new SequenceI[]
+ { dna1 }, dna.getDataset(), null);
/*
* Verify we have 3 cds sequences, mapped to pep1/2/3 respectively
.findMappingsForSequence(pep1, dnaMappings);
assertEquals(1, mappings.size());
assertEquals(1, mappings.get(0).getMappings().size());
- assertSame(pep1.getDatasetSequence(), mappings.get(0).getMappings()
- .get(0).getMapping().getTo());
+ assertSame(pep1.getDatasetSequence(),
+ mappings.get(0).getMappings().get(0).getMapping().getTo());
/*
* dna1 to cds1
Mapping mapping = dnaToCds1Mappings.get(0).getMappings().get(0)
.getMapping();
assertSame(cds.get(0).getDatasetSequence(), mapping.getTo());
- assertEquals("G(1) in CDS should map to G(4) in DNA", 4, mapping
- .getMap().getToPosition(1));
+ assertEquals("G(1) in CDS should map to G(4) in DNA", 4,
+ mapping.getMap().getToPosition(1));
/*
* dna1 to pep2
mappings = MappingUtils.findMappingsForSequence(pep2, dnaMappings);
assertEquals(1, mappings.size());
assertEquals(1, mappings.get(0).getMappings().size());
- assertSame(pep2.getDatasetSequence(), mappings.get(0).getMappings()
- .get(0).getMapping().getTo());
+ assertSame(pep2.getDatasetSequence(),
+ mappings.get(0).getMappings().get(0).getMapping().getTo());
/*
* dna1 to cds2
.findMappingsForSequence(cds.get(1), dnaMappings);
mapping = dnaToCds2Mappings.get(0).getMappings().get(0).getMapping();
assertSame(cds.get(1).getDatasetSequence(), mapping.getTo());
- assertEquals("c(4) in CDS should map to c(7) in DNA", 7, mapping
- .getMap().getToPosition(4));
+ assertEquals("c(4) in CDS should map to c(7) in DNA", 7,
+ mapping.getMap().getToPosition(4));
/*
* dna1 to pep3
mappings = MappingUtils.findMappingsForSequence(pep3, dnaMappings);
assertEquals(1, mappings.size());
assertEquals(1, mappings.get(0).getMappings().size());
- assertSame(pep3.getDatasetSequence(), mappings.get(0).getMappings()
- .get(0).getMapping().getTo());
+ assertSame(pep3.getDatasetSequence(),
+ mappings.get(0).getMappings().get(0).getMapping().getTo());
/*
* dna1 to cds3
.findMappingsForSequence(cds.get(2), dnaMappings);
mapping = dnaToCds3Mappings.get(0).getMappings().get(0).getMapping();
assertSame(cds.get(2).getDatasetSequence(), mapping.getTo());
- assertEquals("T(4) in CDS should map to T(10) in DNA", 10, mapping
- .getMap().getToPosition(4));
+ assertEquals("T(4) in CDS should map to T(10) in DNA", 10,
+ mapping.getMap().getToPosition(4));
}
@Test(groups = { "Functional" })
AlignedCodonFrame acf = new AlignedCodonFrame();
// this is like a domain or motif match of part of a peptide sequence
- MapList map = new MapList(new int[] { 6, 12 }, new int[] { 1, 7 }, 1, 1);
- acf.addMap(alignFrom.getDatasetSequence(),
- alignMe.getDatasetSequence(), map);
+ MapList map = new MapList(new int[] { 6, 12 }, new int[] { 1, 7 }, 1,
+ 1);
+ acf.addMap(alignFrom.getDatasetSequence(), alignMe.getDatasetSequence(),
+ map);
AlignmentUtils.alignSequenceAs(alignMe, alignFrom, acf, "-", '-', true,
true);
SequenceI cds = new Sequence("cds/10-15", "TAGGCC");
// no overlap
- dna.addSequenceFeature(new SequenceFeature("type1", "desc1", 1, 2, 1f,
- null));
+ dna.addSequenceFeature(
+ new SequenceFeature("type1", "desc1", 1, 2, 1f, null));
// partial overlap - to [1, 1]
- dna.addSequenceFeature(new SequenceFeature("type2", "desc2", 3, 4, 2f,
- null));
+ dna.addSequenceFeature(
+ new SequenceFeature("type2", "desc2", 3, 4, 2f, null));
// exact overlap - to [1, 3]
- dna.addSequenceFeature(new SequenceFeature("type3", "desc3", 4, 6, 3f,
- null));
+ dna.addSequenceFeature(
+ new SequenceFeature("type3", "desc3", 4, 6, 3f, null));
// spanning overlap - to [2, 5]
- dna.addSequenceFeature(new SequenceFeature("type4", "desc4", 5, 11, 4f,
- null));
+ dna.addSequenceFeature(
+ new SequenceFeature("type4", "desc4", 5, 11, 4f, null));
// exactly overlaps whole mapped range [1, 6]
- dna.addSequenceFeature(new SequenceFeature("type5", "desc5", 4, 12, 5f,
- null));
+ dna.addSequenceFeature(
+ new SequenceFeature("type5", "desc5", 4, 12, 5f, null));
// no overlap (internal)
- dna.addSequenceFeature(new SequenceFeature("type6", "desc6", 7, 9, 6f,
- null));
+ dna.addSequenceFeature(
+ new SequenceFeature("type6", "desc6", 7, 9, 6f, null));
// no overlap (3' end)
- dna.addSequenceFeature(new SequenceFeature("type7", "desc7", 13, 15,
- 7f, null));
+ dna.addSequenceFeature(
+ new SequenceFeature("type7", "desc7", 13, 15, 7f, null));
// overlap (3' end) - to [6, 6]
- dna.addSequenceFeature(new SequenceFeature("type8", "desc8", 12, 12,
- 8f, null));
+ dna.addSequenceFeature(
+ new SequenceFeature("type8", "desc8", 12, 12, 8f, null));
// extended overlap - to [6, +]
- dna.addSequenceFeature(new SequenceFeature("type9", "desc9", 12, 13,
- 9f, null));
+ dna.addSequenceFeature(
+ new SequenceFeature("type9", "desc9", 12, 13, 9f, null));
MapList map = new MapList(new int[] { 4, 6, 10, 12 },
- new int[] { 1, 6 }, 1, 1);
+ new int[]
+ { 1, 6 }, 1, 1);
/*
* transferFeatures() will build 'partial overlap' for regions
SequenceI cds = new Sequence("cds/10-15", "TAGGCC");
MapList map = new MapList(new int[] { 4, 6, 10, 12 },
- new int[] { 1, 6 }, 1, 1);
+ new int[]
+ { 1, 6 }, 1, 1);
// [5, 11] maps to [2, 5]
- dna.addSequenceFeature(new SequenceFeature("type4", "desc4", 5, 11, 4f,
- null));
+ dna.addSequenceFeature(
+ new SequenceFeature("type4", "desc4", 5, 11, 4f, null));
// [4, 12] maps to [1, 6]
- dna.addSequenceFeature(new SequenceFeature("type5", "desc5", 4, 12, 5f,
- null));
+ dna.addSequenceFeature(
+ new SequenceFeature("type5", "desc5", 4, 12, 5f, null));
// [12, 12] maps to [6, 6]
- dna.addSequenceFeature(new SequenceFeature("type8", "desc8", 12, 12,
- 8f, null));
+ dna.addSequenceFeature(
+ new SequenceFeature("type8", "desc8", 12, 12, 8f, null));
// desc4 and desc8 are the 'omit these' varargs
AlignmentUtils.transferFeatures(dna, cds, map, null, "type4", "type8");
SequenceI cds = new Sequence("cds/10-15", "TAGGCC");
MapList map = new MapList(new int[] { 4, 6, 10, 12 },
- new int[] { 1, 6 }, 1, 1);
+ new int[]
+ { 1, 6 }, 1, 1);
// [5, 11] maps to [2, 5]
- dna.addSequenceFeature(new SequenceFeature("type4", "desc4", 5, 11, 4f,
- null));
+ dna.addSequenceFeature(
+ new SequenceFeature("type4", "desc4", 5, 11, 4f, null));
// [4, 12] maps to [1, 6]
- dna.addSequenceFeature(new SequenceFeature("type5", "desc5", 4, 12, 5f,
- null));
+ dna.addSequenceFeature(
+ new SequenceFeature("type5", "desc5", 4, 12, 5f, null));
// [12, 12] maps to [6, 6]
- dna.addSequenceFeature(new SequenceFeature("type8", "desc8", 12, 12,
- 8f, null));
+ dna.addSequenceFeature(
+ new SequenceFeature("type8", "desc8", 12, 12, 8f, null));
// "type5" is the 'select this type' argument
AlignmentUtils.transferFeatures(dna, cds, map, "type5");
dna.setDataset(null);
MapList map = new MapList(new int[] { 4, 12, 16, 18 },
- new int[] { 1, 4 }, 3, 1);
+ new int[]
+ { 1, 4 }, 3, 1);
AlignedCodonFrame acf = new AlignedCodonFrame();
acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
dna.addCodonFrame(acf);
map = new MapList(new int[] { 4, 8, 12, 12, 16, 18 },
- new int[] { 1, 3 }, 3, 1);
+ new int[]
+ { 1, 3 }, 3, 1);
acf = new AlignedCodonFrame();
acf.addMap(dna2.getDatasetSequence(), pep2.getDatasetSequence(), map);
dna.addCodonFrame(acf);
- AlignmentI cds = AlignmentUtils.makeCdsAlignment(new SequenceI[] {
- dna1, dna2, dna3 }, dna.getDataset(), null);
+ AlignmentI cds = AlignmentUtils
+ .makeCdsAlignment(new SequenceI[]
+ { dna1, dna2, dna3 }, dna.getDataset(), null);
List<SequenceI> cdsSeqs = cds.getSequences();
assertEquals(2, cdsSeqs.size());
assertEquals("GGGCCCTTTGGG", cdsSeqs.get(0).getSequenceAsString());
pep1CdsMappings);
assertEquals(1, sr.getResults().size());
SearchResultMatchI m = sr.getResults().get(0);
- assertEquals(cds.getSequenceAt(0).getDatasetSequence(), m.getSequence());
+ assertEquals(cds.getSequenceAt(0).getDatasetSequence(),
+ m.getSequence());
assertEquals(1, m.getStart());
assertEquals(3, m.getEnd());
sr = MappingUtils.buildSearchResults(pep1, 2, pep1CdsMappings);
sr = MappingUtils.buildSearchResults(pep2, 1, pep2CdsMappings);
assertEquals(1, sr.getResults().size());
m = sr.getResults().get(0);
- assertEquals(cds.getSequenceAt(1).getDatasetSequence(), m.getSequence());
+ assertEquals(cds.getSequenceAt(1).getDatasetSequence(),
+ m.getSequence());
assertEquals(1, m.getStart());
assertEquals(3, m.getEnd());
sr = MappingUtils.buildSearchResults(pep2, 2, pep2CdsMappings);
SequenceI prot1 = new Sequence("Seq1", "XKFG"); // X for incomplete start
SequenceI prot2 = new Sequence("Seq2", "NG");
SequenceI prot3 = new Sequence("Seq3", "XG"); // X for incomplete start
- AlignmentI protein = new Alignment(new SequenceI[] { prot1, prot2,
- prot3 });
+ AlignmentI protein = new Alignment(
+ new SequenceI[]
+ { prot1, prot2, prot3 });
protein.setDataset(null);
// map dna1 [3, 11] to prot1 [2, 4] KFG
- MapList map = new MapList(new int[] { 3, 11 }, new int[] { 2, 4 }, 3, 1);
+ MapList map = new MapList(new int[] { 3, 11 }, new int[] { 2, 4 }, 3,
+ 1);
AlignedCodonFrame acf = new AlignedCodonFrame();
acf.addMap(dna1.getDatasetSequence(), prot1.getDatasetSequence(), map);
dna.addCodonFrame(acf);
AlignmentUtils.alignAs(cds, dna);
assertEquals("---GGGTTT", cds.getSequenceAt(0).getSequenceAsString());
- assertEquals("CCC------AAA", cds.getSequenceAt(1).getSequenceAsString());
+ assertEquals("CCC------AAA",
+ cds.getSequenceAt(1).getSequenceAsString());
}
@Test(groups = { "Functional" })
SequenceI seq1 = new Sequence("cds", "AAATTT");
from.createDatasetSequence();
seq1.createDatasetSequence();
- Mapping mapping = new Mapping(seq1, new MapList(
- new int[] { 3, 6, 9, 10 }, new int[] { 1, 6 }, 1, 1));
+ Mapping mapping = new Mapping(seq1,
+ new MapList(new int[]
+ { 3, 6, 9, 10 }, new int[] { 1, 6 }, 1, 1));
Map<Integer, Map<SequenceI, Character>> map = new TreeMap<>();
AlignmentUtils.addMappedPositions(seq1, from, mapping, map);
SequenceI seq1 = new Sequence("cds", "AAATTT");
from.createDatasetSequence();
seq1.createDatasetSequence();
- Mapping mapping = new Mapping(seq1, new MapList(
- new int[] { 3, 6, 9, 10 }, new int[] { 1, 6 }, 1, 1));
+ Mapping mapping = new Mapping(seq1,
+ new MapList(new int[]
+ { 3, 6, 9, 10 }, new int[] { 1, 6 }, 1, 1));
Map<Integer, Map<SequenceI, Character>> map = new TreeMap<>();
AlignmentUtils.addMappedPositions(seq1, from, mapping, map);
AlignedCodonFrame acf = new AlignedCodonFrame();
MapList map = new MapList(new int[] { 4, 6, 10, 12 },
- new int[] { 1, 2 }, 3, 1);
+ new int[]
+ { 1, 2 }, 3, 1);
acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
acf.addMap(dna1.getDatasetSequence(), pep3.getDatasetSequence(), map);
dna.addCodonFrame(acf);
/*
* execute method under test to find CDS for EMBL peptides only
*/
- AlignmentI cds = AlignmentUtils.makeCdsAlignment(new SequenceI[] {
- dna1, dna2 }, dna.getDataset(), emblPeptides.getSequencesArray());
+ AlignmentI cds = AlignmentUtils
+ .makeCdsAlignment(new SequenceI[]
+ { dna1, dna2 }, dna.getDataset(),
+ emblPeptides.getSequencesArray());
assertEquals(2, cds.getSequences().size());
assertEquals("GGGTTT", cds.getSequenceAt(0).getSequenceAsString());
*/
assertTrue(AlignmentUtils.alignAsSameSequences(al1, al2));
String aligned1 = "-cc-GG-GTTT-aaa";
- assertEquals(aligned1,
- al1.getSequenceAt(0).getSequenceAsString());
+ assertEquals(aligned1, al1.getSequenceAt(0).getSequenceAsString());
String aligned2 = "C--C-Cgg-gtttAAA";
- assertEquals(aligned2,
- al1.getSequenceAt(1).getSequenceAsString());
+ assertEquals(aligned2, al1.getSequenceAt(1).getSequenceAsString());
/*
* add another sequence to 'aligned' - should still succeed, since
SequenceI uas1 = dna1.deriveSequence();
SequenceI uas2 = dna1.deriveSequence().getSubSequence(3, 7);
SequenceI uas3 = dna2.deriveSequence();
- AlignmentI tobealigned = new Alignment(new SequenceI[] { uas1, uas2,
- uas3 });
+ AlignmentI tobealigned = new Alignment(
+ new SequenceI[]
+ { uas1, uas2, uas3 });
((Alignment) tobealigned).createDatasetAlignment();
/*
SequenceI pep1 = new Sequence("pep1", "MLS");
pep1.createDatasetSequence();
List<AlignedCodonFrame> seqMappings = new ArrayList<>();
- MapList mapList = new MapList(
+ MapList mapList = new MapList(new int[] { 5, 6, 9, 15 },
new int[]
- { 5, 6, 9, 15 }, new int[] { 1, 3 }, 3, 1);
+ { 1, 3 }, 3, 1);
Mapping dnaToPeptide = new Mapping(pep1.getDatasetSequence(), mapList);
-
+
// add dna to peptide mapping
seqMappings.add(acf1);
acf1.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(),
// need to tidy up use of lists of mappings in AlignedCodonFrame
AlignedCodonFrame acf2 = new AlignedCodonFrame();
mappings.add(acf2);
- MapList cdsToPeptideMapping = new MapList(new int[]
- { 1, 9 }, new int[] { 1, 3 }, 3, 1);
+ MapList cdsToPeptideMapping = new MapList(new int[] { 1, 9 },
+ new int[]
+ { 1, 3 }, 3, 1);
acf2.addMap(cds1.getDatasetSequence(), pep1.getDatasetSequence(),
cdsToPeptideMapping);
assertNull(AlignmentUtils.findCdsForProtein(mappings, dna1, seqMappings,
List<AlignedCodonFrame> mappings = new ArrayList<>();
AlignedCodonFrame acf1 = new AlignedCodonFrame();
mappings.add(acf1);
-
+
SequenceI dna1 = new Sequence("dna1", "ATGCTATCTTAA");
dna1.createDatasetSequence();
-
+
// NB we currently exclude STOP codon from CDS sequences
// the test would need to change if this changes in future
SequenceI cds1 = new Sequence("cds1", "ATGCTATCT");
cds1.createDatasetSequence();
-
+
SequenceI pep1 = new Sequence("pep1", "MLS");
pep1.createDatasetSequence();
List<AlignedCodonFrame> seqMappings = new ArrayList<>();
- MapList mapList = new MapList(
- new int[]
- { 1, 9 }, new int[] { 1, 3 }, 3, 1);
+ MapList mapList = new MapList(new int[] { 1, 9 }, new int[] { 1, 3 }, 3,
+ 1);
Mapping dnaToPeptide = new Mapping(pep1.getDatasetSequence(), mapList);
-
+
// add dna to peptide mapping
seqMappings.add(acf1);
acf1.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(),
mapList);
-
+
/*
* first case - transcript lacks CDS features - it appears to be
* the CDS sequence and is returned
SequenceI seq = AlignmentUtils.findCdsForProtein(mappings, dna1,
seqMappings, dnaToPeptide);
assertSame(seq, dna1.getDatasetSequence());
-
+
/*
* second case - transcript has CDS feature - this means it is
* not returned as a match for CDS (CDS sequences don't have CDS features)
// need to tidy up use of lists of mappings in AlignedCodonFrame
AlignedCodonFrame acf2 = new AlignedCodonFrame();
mappings.add(acf2);
- MapList cdsToPeptideMapping = new MapList(new int[]
- { 1, 9 }, new int[] { 1, 3 }, 3, 1);
+ MapList cdsToPeptideMapping = new MapList(new int[] { 1, 9 },
+ new int[]
+ { 1, 3 }, 3, 1);
acf2.addMap(cds1.getDatasetSequence(), pep1.getDatasetSequence(),
cdsToPeptideMapping);
assertNull(AlignmentUtils.findCdsForProtein(mappings, dna1, seqMappings,
dnaToPeptide));
-
+
/*
* fourth case - add dna-to-CDS mapping - CDS is now found!
*/
import static org.testng.AssertJUnit.assertSame;
import static org.testng.AssertJUnit.assertTrue;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
import jalview.datamodel.AlignedCodonFrame;
import jalview.datamodel.AlignedCodonFrame.SequenceToSequenceMapping;
import jalview.datamodel.Alignment;
import jalview.util.DBRefUtils;
import jalview.util.MapList;
import jalview.ws.SequenceFetcher;
-import jalview.ws.SequenceFetcherFactory;
-import jalview.ws.params.InvalidArgumentException;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
public class CrossRefTest
{
DBRefEntry ref8 = new DBRefEntry("PFAM", "1", "A123");
// ENSEMBL is a source of either dna or protein sequence data
DBRefEntry ref9 = new DBRefEntry("ENSEMBL", "1", "A123");
- List<DBRefEntry> refs = Arrays.asList(new DBRefEntry[] { ref1, ref2, ref3, ref4, ref5,
- ref6, ref7, ref8, ref9 });
+ List<DBRefEntry> refs = Arrays
+ .asList(new DBRefEntry[]
+ { ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9 });
/*
* Just the DNA refs:
* and others to dna coding databases
*/
sources.clear();
- seq.setDBRefs(null);
+ seq.setDBRefs(null);
seq.addDBRef(new DBRefEntry("UNIPROT", "0", "A1234"));
seq.addDBRef(new DBRefEntry("EMBLCDS", "0", "E2347"));
SequenceI seq2 = new Sequence("Seq2", "MGKYQARLSS");
* peptide sequence with UNIPROT dbref
*/
SequenceI dna1 = new Sequence("AF039662", "GGGGCAGCACAAGAAC");
- Mapping map = new Mapping(new Sequence("pep2", "MLAVSRG"), new MapList(
- new int[] { 1, 21 }, new int[] { 1, 7 }, 3, 1));
+ Mapping map = new Mapping(new Sequence("pep2", "MLAVSRG"),
+ new MapList(new int[]
+ { 1, 21 }, new int[] { 1, 7 }, 3, 1));
DBRefEntry dbref = new DBRefEntry("UNIPROT", "0", "Q9ZTS2", map);
dna1.addDBRef(dbref);
dna1.addDBRef(new DBRefEntry("EMBL", "0", "AF039662"));
acf = new AlignedCodonFrame();
dbref = new DBRefEntry("UNIPROT", "0", "Q9ZTS2");
found = testee.searchDataset(!dna1.isProtein(), dna1, dbref, result,
- acf, false, DBRefUtils.SEARCH_MODE_FULL); // search dataset with a protein xref from a dna
- // sequence to locate the protein product
+ acf, false, DBRefUtils.SEARCH_MODE_FULL); // search dataset with a
+ // protein xref from a dna
+ // sequence to locate the protein product
assertTrue(found);
assertEquals(1, result.size());
assertSame(pep1, result.get(0));
acf = new AlignedCodonFrame();
dbref = new DBRefEntry("UNIPROT", "0", "Q9ZTS2");
found = testee.searchDataset(!pep1.isProtein(), pep1, dbref, result,
- acf, false, DBRefUtils.SEARCH_MODE_FULL); // search dataset with a protein's direct dbref to
- // locate dna sequences with matching xref
+ acf, false, DBRefUtils.SEARCH_MODE_FULL); // search dataset with a
+ // protein's direct dbref
+ // to
+ // locate dna sequences with matching xref
assertTrue(found);
assertEquals(1, result.size());
assertSame(dna1, result.get(0));
pep1.createDatasetSequence();
pep2.createDatasetSequence();
- pep1.getDatasetSequence().addDBRef(
- new DBRefEntry("Pfam", "0", "PF00111"));
- pep1.addSequenceFeature(new SequenceFeature("type", "desc", 12, 14, 1f,
- "group"));
+ pep1.getDatasetSequence()
+ .addDBRef(new DBRefEntry("Pfam", "0", "PF00111"));
+ pep1.addSequenceFeature(
+ new SequenceFeature("type", "desc", 12, 14, 1f, "group"));
pep2.getDatasetSequence().addDBRef(new DBRefEntry("PDB", "0", "3JTK"));
- pep2.addSequenceFeature(new SequenceFeature("type2", "desc2", 13, 15,
- 12f, "group2"));
+ pep2.addSequenceFeature(
+ new SequenceFeature("type2", "desc2", 13, 15, 12f, "group2"));
MapList mapList = new MapList(new int[] { 1, 24 }, new int[] { 1, 3 },
3, 1);
assertEquals(copy.getName(), original.getName());
assertEquals(copy.getStart(), original.getStart());
assertEquals(copy.getEnd(), original.getEnd());
- assertEquals(copy.getSequenceAsString(), original.getSequenceAsString());
+ assertEquals(copy.getSequenceAsString(),
+ original.getSequenceAsString());
}
/**
@Test(groups = { "Functional_Failing" })
public void testFindXrefSequences_withFetch()
{
+ // JBPNote: this fails because pep1 and pep2 do not have DbRefEntrys with
+ // mappings
+ // Fix#1 would be to revise the test data so it fits with 2.11.2+ Jalview
+ // assumptions
+ // that ENA retrievals yield dbrefs with Mappings
+
SequenceI dna1 = new Sequence("AF039662", "GGGGCAGCACAAGAAC");
dna1.addDBRef(new DBRefEntry("UNIPROT", "ENA:0", "Q9ZTS2"));
dna1.addDBRef(new DBRefEntry("UNIPROT", "ENA:0", "P30419"));
dna1.addDBRef(new DBRefEntry("UNIPROT", "ENA:0", "P00314"));
final SequenceI pep1 = new Sequence("Q9ZTS2", "MYQLIRSSW");
- pep1.addDBRef(new DBRefEntry("UNIPROT", "0", "Q9ZTS2"));
+ pep1.addDBRef(new DBRefEntry("UNIPROT", "0", "Q9ZTS2", null, true));
final SequenceI pep2 = new Sequence("P00314", "MRKLLAASG");
- pep2.addDBRef(new DBRefEntry("UNIPROT", "0", "P00314"));
+ pep2.addDBRef(new DBRefEntry("UNIPROT", "0", "P00314", null, true));
/*
* argument false suppresses adding DAS sources
return new SequenceI[] { pep1, pep2 };
}
};
- SequenceFetcherFactory.setSequenceFetcher(mockFetcher);
+ SequenceFetcher.setMockFetcher(mockFetcher);
/*
* find UNIPROT xrefs for nucleotide sequence
@AfterClass(alwaysRun = true)
public void tearDown()
{
- SequenceFetcherFactory.setSequenceFetcher(null);
+ SequenceFetcher.setMockFetcher(null);
}
/**
/*
* 'transcript' with CDS feature (supports mapping to protein)
*/
- SequenceI braf001 = new Sequence("ENST00000288602", "taagATGGCGGCGCTGa");
+ SequenceI braf001 = new Sequence("ENST00000288602",
+ "taagATGGCGGCGCTGa");
braf001.addDBRef(new DBRefEntry("UNIPROT", "0", "P15056"));
- braf001.addSequenceFeature(new SequenceFeature("CDS", "", 5, 16, 0f,
- null));
+ braf001.addSequenceFeature(
+ new SequenceFeature("CDS", "", 5, 16, 0f, null));
/*
* 'spliced transcript' with CDS ranges
*/
- SequenceI braf002 = new Sequence("ENST00000497784", "gCAGGCtaTCTGTTCaa");
+ SequenceI braf002 = new Sequence("ENST00000497784",
+ "gCAGGCtaTCTGTTCaa");
braf002.addDBRef(new DBRefEntry("UNIPROT", "ENSEMBL|0", "H7C5K3"));
- braf002.addSequenceFeature(new SequenceFeature("CDS", "", 2, 6, 0f,
- null));
- braf002.addSequenceFeature(new SequenceFeature("CDS", "", 9, 15, 0f,
- null));
+ braf002.addSequenceFeature(
+ new SequenceFeature("CDS", "", 2, 6, 0f, null));
+ braf002.addSequenceFeature(
+ new SequenceFeature("CDS", "", 9, 15, 0f, null));
/*
* TODO code is fragile - use of SequenceIdMatcher depends on fetched
return new SequenceI[] { pep1, pep2 };
}
};
- SequenceFetcherFactory.setSequenceFetcher(mockFetcher);
+ SequenceFetcher.setMockFetcher(mockFetcher);
/*
* find UNIPROT xrefs for gene and transcripts
/*
* J03321 with mappings to P0CE19 and P0CE20
*/
- final SequenceI j03321 = new Sequence("EMBL|J03321", "AAACCCTTTGGGAAAA");
+ final SequenceI j03321 = new Sequence("EMBL|J03321",
+ "AAACCCTTTGGGAAAA");
DBRefEntry dbref1 = new DBRefEntry("UNIPROT", "0", "P0CE19");
MapList mapList = new MapList(new int[] { 1, 12 }, new int[] { 1, 4 },
3, 1);
DBRefEntry dbref3 = new DBRefEntry("UNIPROT", "0", "P0CE19");
MapList map2 = new MapList(new int[] { 4, 15 }, new int[] { 1, 4 }, 3,
1);
- dbref3.setMap(new Mapping(new Sequence("UNIPROT|P0CE19", "KPFG"), map2));
+ dbref3.setMap(
+ new Mapping(new Sequence("UNIPROT|P0CE19", "KPFG"), map2));
x06707.addDBRef(dbref3);
DBRefEntry dbref4 = new DBRefEntry("UNIPROT", "0", "P0CE20");
MapList map3 = new MapList(new int[] { 4, 15 }, new int[] { 1, 4 }, 3,
1);
- dbref4.setMap(new Mapping(new Sequence("UNIPROT|P0CE20", "PFGK"), map3));
+ dbref4.setMap(
+ new Mapping(new Sequence("UNIPROT|P0CE20", "PFGK"), map3));
x06707.addDBRef(dbref4);
/*
}
}
};
- SequenceFetcherFactory.setSequenceFetcher(mockFetcher);
+ SequenceFetcher.setMockFetcher(mockFetcher);
/*
* find EMBL xrefs for Uniprot seqs and verify that
/*
* verify dbrefs on EMBL are mapped to alignment seqs
*/
-
+
assertSame(p0ce19, j03321.getDBRefs().get(0).getMap().getTo());
assertSame(p0ce20, j03321.getDBRefs().get(1).getMap().getTo());
assertSame(p0ce19, x06707.getDBRefs().get(0).getMap().getTo());
assertFalse(CrossRef.sameSequence(null, seq1));
assertTrue(CrossRef.sameSequence(seq1, new Sequence("seq2", "ABCDEF")));
assertTrue(CrossRef.sameSequence(seq1, new Sequence("seq2", "abcdef")));
- assertFalse(CrossRef
- .sameSequence(seq1, new Sequence("seq2", "ABCDE-F")));
+ assertFalse(
+ CrossRef.sameSequence(seq1, new Sequence("seq2", "ABCDE-F")));
assertFalse(CrossRef.sameSequence(seq1, new Sequence("seq2", "BCDEF")));
}
}
public void setUp()
{
Cache.loadProperties("test/jalview/io/testProps.jvprops");
- Cache.applicationProperties.setProperty("PAD_GAPS",
+ Cache.setPropertyNoSave("PAD_GAPS",
Boolean.FALSE.toString());
//@formatter:off
* single symbol should find *all* matching symbols
*/
Finder f = new Finder(av);
- f.findAll("M", false,false,false);
+ f.findAll("M", false, false, false);
SearchResultsI sr = f.getSearchResults();
- assertEquals(sr.getCount(),5);
-
+ assertEquals(sr.getCount(), 5);
+
}
+
/**
* Test for (undocumented) find residue by position
*/
sg.addSequence(al.getSequenceAt(1), false);
sg.addSequence(al.getSequenceAt(2), false);
av.setSelectionGroup(sg);
-
+
/*
* search for 'e' should match two sequence ids and one residue
*/
}
/**
- * Test that find does not report hidden positions, but does report matches that
- * span hidden gaps
+ * Test that find does not report hidden positions, but does report matches
+ * that span hidden gaps
*/
@Test(groups = "Functional")
public void testFind_withHiddenColumns()
* --bcdEFH
* aa---aMMMMMaaa
*/
-
+
/*
* hide columns 2-4 and 6-7
*/
hc.hideColumns(2, 4);
hc.hideColumns(6, 7);
al.setHiddenColumns(hc);
-
+
/*
* select rows 2-3
*/
import jalview.gui.JvOptionPane;
import java.util.Hashtable;
+import java.util.Map;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
}
-
/**
* test for JAL-2046 bug - duplication of sequence features on reconstructed
* alignment
@Test(groups = { "Functional" })
public void testSeqFeatureAddition()
{
- SequenceI[] sqset = new SequenceI[] {
- new Sequence("Aseq1", "AREALSEQ"),
+ SequenceI[] sqset = new SequenceI[] { new Sequence("Aseq1", "AREALSEQ"),
new Sequence("Aseq2", "AREALSEQ") };
AlignmentI al = new Alignment(sqset);
SequenceFeature sf1 = new SequenceFeature("f1", "foo", 2, 3, "far");
SequenceFeature sf2 = new SequenceFeature("f2", "foo", 2, 3, "far");
ds.getSequenceAt(0).addSequenceFeature(sf1);
- Hashtable unq = SeqsetUtils.uniquify(sqset, true);
+ Map<String, SeqsetUtils.SequenceInfo> unq = SeqsetUtils.uniquify(sqset, true);
SequenceI[] sqset2 = new SequenceI[] {
new Sequence(sqset[0].getName(), sqset[0].getSequenceAsString()),
new Sequence(sqset[1].getName(), sqset[1].getSequenceAsString()) };
// are on the shared dataset sequence
Assert.assertEquals(sqset[0].getSequenceFeatures().size(), 2);
Assert.assertEquals(sqset2[0].getSequenceFeatures().size(), 2);
- Assert.assertSame(sqset[0].getSequenceFeatures().get(0), sqset2[0]
- .getSequenceFeatures().get(0));
- Assert.assertSame(sqset[0].getSequenceFeatures().get(1), sqset2[0]
- .getSequenceFeatures().get(1));
+ Assert.assertSame(sqset[0].getSequenceFeatures().get(0),
+ sqset2[0].getSequenceFeatures().get(0));
+ Assert.assertSame(sqset[0].getSequenceFeatures().get(1),
+ sqset2[0].getSequenceFeatures().get(1));
}
}
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
+import jalview.api.AlignViewportI;
import jalview.api.analysis.ScoreModelI;
import jalview.api.analysis.SimilarityParamsI;
import jalview.datamodel.Alignment;
import jalview.datamodel.SequenceFeature;
import jalview.datamodel.SequenceI;
import jalview.gui.AlignFrame;
-import jalview.gui.AlignViewport;
import jalview.gui.JvOptionPane;
import jalview.io.DataSourceType;
import jalview.io.FileLoader;
*/
public AlignFrame getTestAlignmentFrame()
{
- AlignFrame alf = new FileLoader(false).LoadFileWaitTillLoaded(
- alntestFile, DataSourceType.PASTE);
+ AlignFrame alf = new FileLoader(false)
+ .LoadFileWaitTillLoaded(alntestFile, DataSourceType.PASTE);
AlignmentI al = alf.getViewport().getAlignment();
Assert.assertEquals(al.getHeight(), 4);
Assert.assertEquals(al.getWidth(), 5);
alf.getFeatureRenderer().setVisible("sf2");
alf.getFeatureRenderer().setVisible("sf3");
alf.getFeatureRenderer().findAllFeatures(true);
- Assert.assertEquals(alf.getFeatureRenderer().getDisplayedFeatureTypes()
- .size(), 3, "Number of feature types");
+ Assert.assertEquals(
+ alf.getFeatureRenderer().getDisplayedFeatureTypes().size(), 3,
+ "Number of feature types");
assertTrue(alf.getCurrentView().areFeaturesDisplayed());
return alf;
}
alf.getCurrentView().getAlignPanel());
alf.selectAllSequenceMenuItem_actionPerformed(null);
- MatrixI dm = sm.findDistances(
- alf.getViewport().getAlignmentView(true),
+ MatrixI dm = sm.findDistances(alf.getViewport().getAlignmentView(true),
SimilarityParams.Jalview);
assertEquals(dm.getValue(0, 2), 0d,
"FER1_MESCR (0) should be identical with RAPSA (2)");
sm = ScoreModels.getInstance().getScoreModel(sm.getName(),
alf.getCurrentView().getAlignPanel());
alf.selectAllSequenceMenuItem_actionPerformed(null);
- MatrixI dm = sm.findDistances(
- alf.getViewport().getAlignmentView(true),
+ MatrixI dm = sm.findDistances(alf.getViewport().getAlignmentView(true),
SimilarityParams.Jalview);
assertEquals(dm.getValue(0, 2), 0d,
"FER1_MESCR (0) should be identical with RAPSA (2)");
sm = ScoreModels.getInstance().getScoreModel(sm.getName(),
alf.getCurrentView().getAlignPanel());
alf.selectAllSequenceMenuItem_actionPerformed(null);
- MatrixI dm = sm.findDistances(
- alf.getViewport().getAlignmentView(true),
+ MatrixI dm = sm.findDistances(alf.getViewport().getAlignmentView(true),
SimilarityParams.Jalview);
- assertEquals(
- dm.getValue(0, 2),
- 0d,
+ assertEquals(dm.getValue(0, 2), 0d,
"After hiding last two columns FER1_MESCR (0) should still be identical with RAPSA (2)");
- assertEquals(
- dm.getValue(0, 1),
- 0d,
+ assertEquals(dm.getValue(0, 1), 0d,
"After hiding last two columns FER1_MESCR (0) should now also be identical with SPIOL (1)");
for (int s = 0; s < 3; s++)
{
- assertTrue(dm.getValue(s, 3) > 0d, "After hiding last two columns "
- + alf.getViewport().getAlignment().getSequenceAt(s).getName()
- + "(" + s + ") should still be distinct from FER1_MAIZE (3)");
+ assertTrue(dm.getValue(s, 3) > 0d,
+ "After hiding last two columns "
+ + alf.getViewport().getAlignment().getSequenceAt(s)
+ .getName()
+ + "(" + s
+ + ") should still be distinct from FER1_MAIZE (3)");
}
}
assertTrue(sf.isContactFeature());
af.refreshFeatureUI(true);
af.getFeatureRenderer().setAllVisible(Arrays.asList("disulphide bond"));
- Assert.assertEquals(af.getFeatureRenderer().getDisplayedFeatureTypes()
- .size(), 1, "Should be just one feature type displayed");
+ Assert.assertEquals(
+ af.getFeatureRenderer().getDisplayedFeatureTypes().size(), 1,
+ "Should be just one feature type displayed");
// step through and check for pointwise feature presence/absence
- Assert.assertEquals(af.getFeatureRenderer().findFeaturesAtColumn(aseq, 1)
- .size(), 0);
+ Assert.assertEquals(
+ af.getFeatureRenderer().findFeaturesAtColumn(aseq, 1).size(),
+ 0);
// step through and check for pointwise feature presence/absence
- Assert.assertEquals(af.getFeatureRenderer().findFeaturesAtColumn(aseq, 2)
- .size(), 1);
+ Assert.assertEquals(
+ af.getFeatureRenderer().findFeaturesAtColumn(aseq, 2).size(),
+ 1);
// step through and check for pointwise feature presence/absence
- Assert.assertEquals(af.getFeatureRenderer().findFeaturesAtColumn(aseq, 3)
- .size(), 0);
+ Assert.assertEquals(
+ af.getFeatureRenderer().findFeaturesAtColumn(aseq, 3).size(),
+ 0);
// step through and check for pointwise feature presence/absence
- Assert.assertEquals(af.getFeatureRenderer().findFeaturesAtColumn(aseq, 4)
- .size(), 0);
+ Assert.assertEquals(
+ af.getFeatureRenderer().findFeaturesAtColumn(aseq, 4).size(),
+ 0);
// step through and check for pointwise feature presence/absence
- Assert.assertEquals(af.getFeatureRenderer().findFeaturesAtColumn(aseq, 5)
- .size(), 1);
+ Assert.assertEquals(
+ af.getFeatureRenderer().findFeaturesAtColumn(aseq, 5).size(),
+ 1);
// step through and check for pointwise feature presence/absence
- Assert.assertEquals(af.getFeatureRenderer().findFeaturesAtColumn(aseq, 6)
- .size(), 0);
+ Assert.assertEquals(
+ af.getFeatureRenderer().findFeaturesAtColumn(aseq, 6).size(),
+ 0);
}
@Test(groups = { "Functional" })
* 20120 (two features of the same type doesn't affect score)
* giving an average (pairwise distance) of 5/5 or 1.0
*/
- s1.addSequenceFeature(new SequenceFeature("domain", null, 1, 3, 0f,
- null));
- s1.addSequenceFeature(new SequenceFeature("variant", null, 2, 4, 0f,
- null));
- s1.addSequenceFeature(new SequenceFeature("variant", null, 3, 5, 0f,
- null));
- s2.addSequenceFeature(new SequenceFeature("domain", null, 2, 4, 0f,
- null));
- s2.addSequenceFeature(new SequenceFeature("variant", null, 1, 2, 0f,
- null));
- s2.addSequenceFeature(new SequenceFeature("variant", null, 5, 5, 0f,
- null));
+ s1.addSequenceFeature(
+ new SequenceFeature("domain", null, 1, 3, 0f, null));
+ s1.addSequenceFeature(
+ new SequenceFeature("variant", null, 2, 4, 0f, null));
+ s1.addSequenceFeature(
+ new SequenceFeature("variant", null, 3, 5, 0f, null));
+ s2.addSequenceFeature(
+ new SequenceFeature("domain", null, 2, 4, 0f, null));
+ s2.addSequenceFeature(
+ new SequenceFeature("variant", null, 1, 2, 0f, null));
+ s2.addSequenceFeature(
+ new SequenceFeature("variant", null, 5, 5, 0f, null));
alf.setShowSeqFeatures(true);
alf.getFeatureRenderer().findAllFeatures(true);
alf.getCurrentView().getAlignPanel());
alf.selectAllSequenceMenuItem_actionPerformed(null);
- AlignmentView alignmentView = alf.getViewport()
- .getAlignmentView(true);
+ AlignmentView alignmentView = alf.getViewport().getAlignmentView(true);
MatrixI distances = sm.findDistances(alignmentView,
SimilarityParams.Jalview);
assertEquals(distances.width(), 2);
public void testFindDistances_withParams()
{
AlignFrame af = setupAlignmentView();
- AlignViewport viewport = af.getViewport();
+ AlignViewportI viewport = af.getViewport();
AlignmentView view = viewport.getAlignmentView(false);
ScoreModelI sm = new FeatureDistanceModel();
assertEquals(distances.getValue(1, 1), 0d);
assertEquals(distances.getValue(0, 1), 13d / 6); // should be 13d/6
assertEquals(distances.getValue(1, 0), 13d / 6);
-
+
/*
* exclude gaps
* score = 3 + 3 + 0 + 0 + 0 + 0 = 6/6
SequenceI s1 = new Sequence("s1", "FR K S");
SequenceI s2 = new Sequence("s2", "FS L");
- s1.addSequenceFeature(new SequenceFeature("chain", null, 1, 4, 0f, null));
- s1.addSequenceFeature(new SequenceFeature("domain", null, 1, 4, 0f,
- null));
- s2.addSequenceFeature(new SequenceFeature("chain", null, 1, 3, 0f, null));
- s2.addSequenceFeature(new SequenceFeature("metal", null, 1, 3, 0f, null));
- s2.addSequenceFeature(new SequenceFeature("Pfam", null, 1, 3, 0f, null));
+ s1.addSequenceFeature(
+ new SequenceFeature("chain", null, 1, 4, 0f, null));
+ s1.addSequenceFeature(
+ new SequenceFeature("domain", null, 1, 4, 0f, null));
+ s2.addSequenceFeature(
+ new SequenceFeature("chain", null, 1, 3, 0f, null));
+ s2.addSequenceFeature(
+ new SequenceFeature("metal", null, 1, 3, 0f, null));
+ s2.addSequenceFeature(
+ new SequenceFeature("Pfam", null, 1, 3, 0f, null));
AlignmentI al = new Alignment(new SequenceI[] { s1, s2 });
AlignFrame af = new AlignFrame(al, 300, 300);
af.setShowSeqFeatures(true);
*/
package jalview.bin;
+import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
+import jalview.gui.JvOptionPane;
+import jalview.io.DataSourceType;
+import jalview.io.FileFormat;
+import jalview.io.FileFormatException;
+import jalview.io.FileFormatI;
+import jalview.io.FileFormats;
+import jalview.io.IdentifyFile;
+
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ModuleRef;
import io.github.classgraph.ScanResult;
-import jalview.gui.JvOptionPane;
public class CommandLineOperations
{
JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
}
- private static final int TEST_TIMEOUT = 9000; // Note longer timeout needed
- // on
- // full test run than on
- // individual tests
+ private static final int TEST_TIMEOUT = 13000; // Note longer timeout needed
+ // on
+ // full test run than on
+ // individual tests
- private static final int SETUP_TIMEOUT = 9000;
+ private static final int SETUP_TIMEOUT = 9500;
private static final int MINFILESIZE_SMALL = 2096;
// not expanded by the shell
String classpath = getClassPath();
String _cmd = java_exe + " "
- + (withAwt ? "-Djava.awt.headless=true" : "")
- + " -classpath " + classpath
+ + (withAwt ? "-Djava.awt.headless=true" : "") + " -classpath "
+ + classpath
+ (modules.length() > 2 ? "--add-modules=\"" + modules + "\""
: "")
+ " jalview.bin.Jalview ";
public void setUpForHeadlessCommandLineInputOperations()
throws IOException
{
- String cmds = "nodisplay -open examples/uniref50.fa -sortbytree -props test/jalview/io/testProps.jvprops -colour zappo "
+ String cmds = "nodisplay -open examples/uniref50.fa -sortbytree -props test/jalview/bin/testProps.jvprops -colour zappo "
+ "-jabaws http://www.compbio.dundee.ac.uk/jabaws -nosortbytree "
+ "-features examples/testdata/plantfdx.features -annotations examples/testdata/plantfdx.annotations -tree examples/testdata/uniref50_test_tree";
Worker worker = getJalviewDesktopRunner(true, cmds, SETUP_TIMEOUT);
public void setUpForCommandLineInputOperations() throws IOException
{
String cmds = "-open examples/uniref50.fa -noquestionnaire -nousagestats";
- Worker worker = getJalviewDesktopRunner(false, cmds, SETUP_TIMEOUT);
- String ln = null;
- int count = 0;
- while ((ln = worker.getErrorReader().readLine()) != null)
+ final Worker worker = getJalviewDesktopRunner(false, cmds,
+ SETUP_TIMEOUT);
+
+ // number of lines expected on STDERR when Jalview starts up normally
+ // may need to adjust this if Jalview is excessively noisy ?
+ final int STDERR_SETUPLINES = 50;
+
+ // thread monitors stderr - bails after SETUP_TIMEOUT or when
+ // STDERR_SETUPLINES have been read
+ Thread runner = new Thread(new Runnable()
{
- System.out.println(ln);
- successfulCMDs.add(ln);
- if (++count > 25)
+ @Override
+ public void run()
+ {
+ String ln = null;
+ int count = 0;
+ try
+ {
+ while ((ln = worker.getErrorReader().readLine()) != null)
+ {
+ System.out.println(ln);
+ successfulCMDs.add(ln);
+ if (++count > STDERR_SETUPLINES)
+ {
+ break;
+ }
+ }
+ } catch (Exception e)
+ {
+ System.err.println(
+ "Unexpected Exception reading stderr from the Jalview process");
+ e.printStackTrace();
+ }
+ }
+ });
+ long t = System.currentTimeMillis() + SETUP_TIMEOUT;
+ runner.start();
+ while (!runner.isInterrupted() && System.currentTimeMillis() < t)
+ {
+ try
+ {
+ Thread.sleep(500);
+ } catch (InterruptedException e)
{
- break;
}
}
+ runner.interrupt();
if (worker != null && worker.exit == null)
{
worker.interrupt();
@Test(
groups =
- { "Functional" },
+ { "Functional", "testben" },
dataProvider = "headlessModeOutputOperationsData")
public void testHeadlessModeOutputOperations(String harg, String type,
String fileName, boolean withAWT, int expectedMinFileSize,
- int timeout)
+ int timeout, String fileFormatType)
{
String cmd = harg + type + " " + fileName;
// System.out.println(">>>>>>>>>>>>>>>> Command : " + cmd);
assertTrue(file.exists(), msg);
FileAssert.assertFile(file, msg);
FileAssert.assertMinLength(file, expectedMinFileSize);
+ if (fileFormatType!=null && fileFormatType.length()>0)
+ {
+ FileFormatI format = FileFormats.getInstance()
+ .forName(fileFormatType);
+ if (format!=null)
+ {
+ try
+ {
+ FileFormatI exportedType = new IdentifyFile()
+ .identify(file.getAbsolutePath(), DataSourceType.FILE);
+ assertEquals(exportedType, format,
+ "Exported file type was wrong");
+ } catch (FileFormatException e)
+ {
+ Assert.fail("Couldn't identify file " + file
+ + " as an alignment format", e);
+ }
+ }
+ }
if (worker != null && worker.exit == null)
{
worker.interrupt();
// headless mode input operations
{ "CMD [-color zappo] executed successfully!",
"Failed command : -color zappo" },
- { "CMD [-props test/jalview/io/testProps.jvprops] executed successfully!",
+ { "CMD [-props test/jalview/bin/testProps.jvprops] executed successfully!",
"Failed command : -props File" },
{ "CMD [-sortbytree] executed successfully!",
"Failed command : -sortbytree" },
String workingDir = "test/jalview/bin/";
return new Object[][] { { "nodisplay -open examples/uniref50.fa",
" -eps", workingDir + "test_uniref50_out.eps", true,
- MINFILESIZE_BIG, TEST_TIMEOUT },
+ MINFILESIZE_BIG, TEST_TIMEOUT, null },
{ "nodisplay -open examples/uniref50.fa", " -eps",
- workingDir + "test_uniref50_out.eps", false, MINFILESIZE_BIG,
- TEST_TIMEOUT },
+ workingDir + "test_uniref50_out.eps", false,
+ MINFILESIZE_BIG, TEST_TIMEOUT, null },
{ "nogui -open examples/uniref50.fa", " -eps",
workingDir + "test_uniref50_out.eps", true, MINFILESIZE_BIG,
- TEST_TIMEOUT },
+ TEST_TIMEOUT, null },
{ "nogui -open examples/uniref50.fa", " -eps",
- workingDir + "test_uniref50_out.eps", false, MINFILESIZE_BIG,
- TEST_TIMEOUT },
+ workingDir + "test_uniref50_out.eps", false,
+ MINFILESIZE_BIG, TEST_TIMEOUT, null },
{ "headless -open examples/uniref50.fa", " -eps",
workingDir + "test_uniref50_out.eps", true, MINFILESIZE_BIG,
- TEST_TIMEOUT },
+ TEST_TIMEOUT, null },
{ "headless -open examples/uniref50.fa", " -svg",
- workingDir + "test_uniref50_out.svg", false, MINFILESIZE_BIG,
- TEST_TIMEOUT },
+ workingDir + "test_uniref50_out.svg", false,
+ MINFILESIZE_BIG, TEST_TIMEOUT, null },
{ "headless -open examples/uniref50.fa", " -png",
workingDir + "test_uniref50_out.png", true, MINFILESIZE_BIG,
- TEST_TIMEOUT },
+ TEST_TIMEOUT, null },
{ "headless -open examples/uniref50.fa", " -html",
- workingDir + "test_uniref50_out.html", true, MINFILESIZE_BIG,
- TEST_TIMEOUT },
+ workingDir + "test_uniref50_out.html", true,
+ MINFILESIZE_BIG, TEST_TIMEOUT, null },
{ "headless -open examples/uniref50.fa", " -fasta",
workingDir + "test_uniref50_out.mfa", true, MINFILESIZE_SMALL,
- TEST_TIMEOUT },
+ TEST_TIMEOUT, FileFormat.Fasta.toString() },
{ "headless -open examples/uniref50.fa", " -clustal",
workingDir + "test_uniref50_out.aln", true, MINFILESIZE_SMALL,
- TEST_TIMEOUT },
+ TEST_TIMEOUT, FileFormat.Clustal.toString() },
{ "headless -open examples/uniref50.fa", " -msf",
workingDir + "test_uniref50_out.msf", true, MINFILESIZE_SMALL,
- TEST_TIMEOUT },
+ TEST_TIMEOUT, FileFormat.MSF.toString() },
{ "headless -open examples/uniref50.fa", " -pileup",
workingDir + "test_uniref50_out.aln", true, MINFILESIZE_SMALL,
- TEST_TIMEOUT },
+ TEST_TIMEOUT, FileFormat.Pileup.toString() },
{ "headless -open examples/uniref50.fa", " -pir",
workingDir + "test_uniref50_out.pir", true, MINFILESIZE_SMALL,
- TEST_TIMEOUT },
+ TEST_TIMEOUT, FileFormat.PIR.toString() },
{ "headless -open examples/uniref50.fa", " -pfam",
workingDir + "test_uniref50_out.pfam", true, MINFILESIZE_SMALL,
- TEST_TIMEOUT },
+ TEST_TIMEOUT, FileFormat.Pfam.toString() },
{ "headless -open examples/uniref50.fa", " -blc",
workingDir + "test_uniref50_out.blc", true, MINFILESIZE_SMALL,
- TEST_TIMEOUT },
+ TEST_TIMEOUT, FileFormat.BLC.toString() },
{ "headless -open examples/uniref50.fa", " -jalview",
workingDir + "test_uniref50_out.jvp", true, MINFILESIZE_SMALL,
- TEST_TIMEOUT }, };
+ TEST_TIMEOUT, FileFormat.Jalview.toString() }, };
}
}
createAnnotation(sq);
AlignmentAnnotation alc, alo = sq.getAnnotation()[0];
alc = new AlignmentAnnotation(alo);
+
+ // TODO: this only tests string equals (which is unreliable), should use
+ // refactored tests from StockholmFileTest
+ Assert.assertEquals(alc.toString(), alo.toString());
+
for (String key : alo.getProperties())
{
assertEquals("Property mismatch", alo.getProperty(key),
al[i] = new Annotation(new Annotation("" + sq.getCharAt(i), "",
(char) 0, sq.findPosition(i)));
}
- AlignmentAnnotation alan = new AlignmentAnnotation("For "
- + sq.getName(), "Fake alignment annot", al);
+ AlignmentAnnotation alan = new AlignmentAnnotation(
+ "For " + sq.getName(), "Fake alignment annot", al);
// create a sequence mapping for the annotation vector in its current state
alan.createSequenceMapping(sq, sq.getStart(), false);
alan.setProperty("CreatedBy", "createAnnotation");
{
if (ala.annotations[p] != null)
{
- assertEquals("Mismatch at position " + p
- + " between annotation position value and sequence"
- + ala.annotations[p], (int) ala.annotations[p].value,
+ assertEquals(
+ "Mismatch at position " + p
+ + " between annotation position value and sequence"
+ + ala.annotations[p],
+ (int) ala.annotations[p].value,
ala.sequenceRef.findPosition(p));
}
}
alSeq2.setStart(sqTo.getStart() + align.getSeq2Start() - 1);
alSeq2.setEnd(sqTo.getStart() + align.getSeq2End() - 1);
alSeq2.setDatasetSequence(sqTo);
- System.out.println(new AppletFormatAdapter()
- .formatSequences(
- FileFormat.Stockholm, new Alignment(new SequenceI[] { sqFrom,
- alSeq1, sqTo, alSeq2 }), true));
+ System.out.println(new AppletFormatAdapter().formatSequences(
+ FileFormat.Stockholm, new Alignment(new SequenceI[]
+ { sqFrom, alSeq1, sqTo, alSeq2 }), true));
Mapping mp = align.getMappingFromS1(false);
AlignmentI all = new Alignment(new SequenceI[] { alSeq1, alSeq2 });
all.addAnnotation(almap1);
all.addAnnotation(almap2);
- System.out.println(new AppletFormatAdapter().formatSequences(
- FileFormat.Stockholm,
- all, true));
+ System.out.println(new AppletFormatAdapter()
+ .formatSequences(FileFormat.Stockholm, all, true));
for (int p = 0; p < alSeq1.getLength(); p++)
{
"Mismatch on Original To and transferred annotation on 1",
(orig1 != null) ? orig1.toString() : null,
(trans1 != null) ? trans1.toString() : null);
- String alm1 = ""
- + (almap1.annotations.length > p ? almap1.annotations[p].displayCharacter
- : "Out of range");
- String alm2 = ""
- + (almap2.annotations.length > p ? almap2.annotations[p].displayCharacter
- : "Out of range");
+ String alm1 = "" + (almap1.annotations.length > p
+ ? almap1.annotations[p].displayCharacter
+ : "Out of range");
+ String alm2 = "" + (almap2.annotations.length > p
+ ? almap2.annotations[p].displayCharacter
+ : "Out of range");
assertEquals("Position " + p + " " + alm1 + " " + alm2, alm1, alm2);
}
}
Assert.assertFalse(ann.isQuantitative(),
"Empty annotation set should not be quantitative.");
- ann = new AlignmentAnnotation("an", "some an", new Annotation[] {
- newAnnotation("4"), newAnnotation("1"), newAnnotation("1"),
- newAnnotation("0.1"), newAnnotation("0.3") });
+ ann = new AlignmentAnnotation("an", "some an",
+ new Annotation[]
+ { newAnnotation("4"), newAnnotation("1"), newAnnotation("1"),
+ newAnnotation("0.1"), newAnnotation("0.3") });
Assert.assertTrue(ann.isQuantitative(),
"All numbers annotation set should be quantitative.");
- ann = new AlignmentAnnotation("an", "some an", new Annotation[] {
- newAnnotation("E"), newAnnotation("E"), newAnnotation("E"),
- newAnnotation("E"), newAnnotation("E") });
+ ann = new AlignmentAnnotation("an", "some an",
+ new Annotation[]
+ { newAnnotation("E"), newAnnotation("E"), newAnnotation("E"),
+ newAnnotation("E"), newAnnotation("E") });
Assert.assertFalse(ann.isQuantitative(),
"All 'E' annotation set should not be quantitative.");
- ann = new AlignmentAnnotation("an", "some an", new Annotation[] {
- newAnnotation("E"), newAnnotation("1"), newAnnotation("2"),
- newAnnotation("3"), newAnnotation("E") });
+ ann = new AlignmentAnnotation("an", "some an",
+ new Annotation[]
+ { newAnnotation("E"), newAnnotation("1"), newAnnotation("2"),
+ newAnnotation("3"), newAnnotation("E") });
Assert.assertTrue(ann.isQuantitative(),
"Mixed 'E' annotation set should be quantitative.");
}
return false;
}
}
- return verifyAlignmentDatasetRefs(alignment.getDataset(),
- raiseAssert, message);
+ return verifyAlignmentDatasetRefs(alignment.getDataset(), raiseAssert,
+ message);
}
else
{
{
if (raiseAssert)
{
- Assert.fail(message
- + " DBRefEntry " + dbr + " for sequence "
- + seqds
+ Assert.fail(message + " DBRefEntry " + dbr
+ + " for sequence " + seqds
+ " in alignment has map to sequence not in dataset");
}
return false;
ae.printStackTrace();
Assert.fail(
"Valid test alignment raised assertion errors when raiseAsserts enabled: "
- + msg, ae);
+ + msg,
+ ae);
}
// also check validation passes with asserts disabled
Assert.assertTrue(verifyAlignmentDatasetRefs(al, false, null),
}
if (!assertRaised)
{
- Assert.fail("Invalid test alignment passed when raiseAsserts enabled:"
- + msg);
+ Assert.fail(
+ "Invalid test alignment passed when raiseAsserts enabled:"
+ + msg);
}
// also check validation passes with asserts disabled
Assert.assertFalse(verifyAlignmentDatasetRefs(al, false, null),
@Test(groups = { "Functional" })
public void testVerifyAlignmentDatasetRefs()
{
- SequenceI sq1 = new Sequence("sq1", "ASFDD"), sq2 = new Sequence("sq2",
- "TTTTTT");
+ SequenceI sq1 = new Sequence("sq1", "ASFDD"),
+ sq2 = new Sequence("sq2", "TTTTTT");
// construct simple valid alignment dataset
Alignment al = new Alignment(new SequenceI[] { sq1, sq2 });
"didn't detect dataset sequence with a dataset sequence reference.");
sq1.setDatasetSequence(null);
- assertVerifyAlignment(
- al,
- true,
+ assertVerifyAlignment(al, true,
"didn't reinstate validity after nulling dataset sequence dataset reference");
// now create dataset and check again
// create a dbref on sq1 with a sequence ref to sq2
DBRefEntry dbrs1tos2 = new DBRefEntry("UNIPROT", "1", "Q111111");
- dbrs1tos2.setMap(new Mapping(sq2.getDatasetSequence(),
- new int[] { 1, 5 }, new int[] { 2, 6 }, 1, 1));
+ dbrs1tos2
+ .setMap(new Mapping(sq2.getDatasetSequence(), new int[]
+ { 1, 5 }, new int[] { 2, 6 }, 1, 1));
sq1.getDatasetSequence().addDBRef(dbrs1tos2);
assertVerifyAlignment(al, true,
"verify failed after addition of valid DBRefEntry/map");
// now create a dbref on a new sequence which maps to another sequence
// outside of the dataset
- SequenceI sqout = new Sequence("sqout", "ututututucagcagcag"), sqnew = new Sequence(
- "sqnew", "EEERRR");
+ SequenceI sqout = new Sequence("sqout", "ututututucagcagcag"),
+ sqnew = new Sequence("sqnew", "EEERRR");
DBRefEntry sqnewsqout = new DBRefEntry("ENAFOO", "1", "R000001");
- sqnewsqout.setMap(new Mapping(sqout, new int[] { 1, 6 }, new int[] { 1,
- 18 }, 1, 3));
+ sqnewsqout
+ .setMap(new Mapping(sqout, new int[]
+ { 1, 6 }, new int[] { 1, 18 }, 1, 3));
al.getDataset().addSequence(sqnew);
assertVerifyAlignment(al, true,
"verify failed after addition of new sequence to dataset");
// now start checking exception conditions
sqnew.addDBRef(sqnewsqout);
- assertVerifyAlignment(
- al,
- false,
+ assertVerifyAlignment(al, false,
"verify passed when a dbref with map to sequence outside of dataset was added");
// make the verify pass by adding the outsider back in
al.getDataset().addSequence(sqout);
"aggtutaggcagcagcag");
AlignedCodonFrame alc = new AlignedCodonFrame();
- alc.addMap(sqanotherout, sqnew, new MapList(new int[] { 1, 6 },
- new int[] { 1, 18 }, 3, 1));
+ alc.addMap(sqanotherout, sqnew,
+ new MapList(new int[]
+ { 1, 6 }, new int[] { 1, 18 }, 3, 1));
al.addCodonFrame(alc);
Assert.assertEquals(al.getDataset().getCodonFrames().size(), 1);
- assertVerifyAlignment(
- al,
- false,
+ assertVerifyAlignment(al, false,
"verify passed when alCodonFrame mapping to sequence outside of dataset was added");
// make the verify pass by adding the outsider back in
al.getDataset().addSequence(sqanotherout);
- assertVerifyAlignment(
- al,
- true,
+ assertVerifyAlignment(al, true,
"verify should have passed once all sequences involved in alCodonFrame were added to dataset");
al.getDataset().addSequence(sqanotherout);
assertVerifyAlignment(al, false,
* @param message
* - null or message prepended to exception message.
*/
- public static void assertDatasetIsNormalised(AlignmentI al, String message)
+ public static void assertDatasetIsNormalised(AlignmentI al,
+ String message)
{
if (al.getDataset() != null)
{
assertDatasetIsNormalised(al);
} catch (AssertionError ae)
{
- Assert.fail("Two different sequences should be valid normalised dataset.");
+ Assert.fail(
+ "Two different sequences should be valid normalised dataset.");
}
/*
* now change sq2's name in the alignment. should still be valid
assertDatasetIsNormalised(al);
} catch (AssertionError ae)
{
- Assert.fail("Two different sequences in dataset, but same name in alignment, should be valid normalised dataset.");
+ Assert.fail(
+ "Two different sequences in dataset, but same name in alignment, should be valid normalised dataset.");
}
al.addSequence(sq1seqd);
assertDatasetIsNormalised(al);
} catch (AssertionError ae)
{
- Assert.fail("sq1 and sq1 with different sequence should be distinct.");
+ Assert.fail(
+ "sq1 and sq1 with different sequence should be distinct.");
}
al.addSequence(sq1shift);
assertDatasetIsNormalised(al);
} catch (AssertionError ae)
{
- Assert.fail("sq1 and sq1 with different start/end should be distinct.");
+ Assert.fail(
+ "sq1 and sq1 with different start/end should be distinct.");
}
/*
* finally, the failure case
makeMappings(al1, al2);
((Alignment) al2).alignAs(al1, false, true);
- assertEquals("GC-TC--GUC-GTACT", al2.getSequenceAt(0)
- .getSequenceAsString());
- assertEquals("-GG-GTC--AGG--CAGT", al2.getSequenceAt(1)
- .getSequenceAsString());
+ assertEquals("GC-TC--GUC-GTACT",
+ al2.getSequenceAt(0).getSequenceAsString());
+ assertEquals("-GG-GTC--AGG--CAGT",
+ al2.getSequenceAt(1).getSequenceAsString());
}
/**
* Realign DNA; currently keeping existing gaps in introns only
*/
((Alignment) al1).alignAs(al2, false, true);
- assertEquals("ACG---GCUCCA------ACT---", al1.getSequenceAt(0)
- .getSequenceAsString());
- assertEquals("---CGT---TAACGA---AGT---", al1.getSequenceAt(1)
- .getSequenceAsString());
+ assertEquals("ACG---GCUCCA------ACT---",
+ al1.getSequenceAt(0).getSequenceAsString());
+ assertEquals("---CGT---TAACGA---AGT---",
+ al1.getSequenceAt(1).getSequenceAsString());
}
/**
{
SequenceI seqFrom = alFrom.getSequenceAt(i);
SequenceI seqTo = alTo.getSequenceAt(i);
- MapList ml = new MapList(new int[] { seqFrom.getStart(),
- seqFrom.getEnd() },
- new int[] { seqTo.getStart(), seqTo.getEnd() }, ratio, 1);
+ MapList ml = new MapList(
+ new int[]
+ { seqFrom.getStart(), seqFrom.getEnd() },
+ new int[]
+ { seqTo.getStart(), seqTo.getEnd() }, ratio, 1);
acf.addMap(seqFrom, seqTo, ml);
}
*/
String dna1 = "A-Aa-gG-GCC-cT-TT";
String dna2 = "c--CCGgg-TT--T-AA-A";
- AlignmentI al1 = loadAlignment(">Dna1/6-17\n" + dna1
- + "\n>Dna2/20-31\n" + dna2 + "\n", FileFormat.Fasta);
+ AlignmentI al1 = loadAlignment(
+ ">Dna1/6-17\n" + dna1 + "\n>Dna2/20-31\n" + dna2 + "\n",
+ FileFormat.Fasta);
AlignmentI al2 = loadAlignment(
">Pep1/7-9\n-P--YK\n>Pep2/11-13\nG-T--F\n", FileFormat.Fasta);
AlignedCodonFrame acf = new AlignedCodonFrame();
// Seq1 has intron at dna positions 3,4,9 so splice is AAG GCC TTT
// Seq2 has intron at dna positions 1,5,6 so splice is CCG TTT AAA
- MapList ml1 = new MapList(new int[] { 6, 7, 10, 13, 15, 17 }, new int[]
- { 7, 9 }, 3, 1);
+ MapList ml1 = new MapList(new int[] { 6, 7, 10, 13, 15, 17 },
+ new int[]
+ { 7, 9 }, 3, 1);
acf.addMap(al1.getSequenceAt(0), al2.getSequenceAt(0), ml1);
- MapList ml2 = new MapList(new int[] { 21, 23, 26, 31 }, new int[] { 11,
- 13 }, 3, 1);
+ MapList ml2 = new MapList(new int[] { 21, 23, 26, 31 },
+ new int[]
+ { 11, 13 }, 3, 1);
acf.addMap(al1.getSequenceAt(1), al2.getSequenceAt(1), ml2);
al2.addCodonFrame(acf);
* Align ignoring gaps in dna introns and exons
*/
((Alignment) al1).alignAs(al2, false, false);
- assertEquals("---AAagG------GCCcTTT", al1.getSequenceAt(0)
- .getSequenceAsString());
+ assertEquals("---AAagG------GCCcTTT",
+ al1.getSequenceAt(0).getSequenceAsString());
// note 1 gap in protein corresponds to 'gg-' in DNA (3 positions)
- assertEquals("cCCGgg-TTT------AAA", al1.getSequenceAt(1)
- .getSequenceAsString());
+ assertEquals("cCCGgg-TTT------AAA",
+ al1.getSequenceAt(1).getSequenceAsString());
/*
* Reset and realign, preserving gaps in dna introns and exons
// String dna1 = "A-Aa-gG-GCC-cT-TT";
// String dna2 = "c--CCGgg-TT--T-AA-A";
// assumption: we include 'the greater of' protein/dna gap lengths, not both
- assertEquals("---A-Aa-gG------GCC-cT-TT", al1.getSequenceAt(0)
- .getSequenceAsString());
- assertEquals("c--CCGgg-TT--T------AA-A", al1.getSequenceAt(1)
- .getSequenceAsString());
+ assertEquals("---A-Aa-gG------GCC-cT-TT",
+ al1.getSequenceAt(0).getSequenceAsString());
+ assertEquals("c--CCGgg-TT--T------AA-A",
+ al1.getSequenceAt(1).getSequenceAsString());
}
@Test(groups = "Functional")
// create sequence and alignment datasets
protein.setDataset(null);
AlignedCodonFrame acf = new AlignedCodonFrame();
- List<AlignedCodonFrame> acfList = Arrays.asList(new AlignedCodonFrame[]
- { acf });
+ List<AlignedCodonFrame> acfList = Arrays
+ .asList(new AlignedCodonFrame[]
+ { acf });
protein.getDataset().setCodonFrames(acfList);
AlignmentI copy = new Alignment(protein);
*/
assertFalse(copy.getSequenceAt(0) == protein.getSequenceAt(0));
assertFalse(copy.getSequenceAt(1) == protein.getSequenceAt(1));
- assertSame(copy.getSequenceAt(0).getDatasetSequence(), protein
- .getSequenceAt(0).getDatasetSequence());
- assertSame(copy.getSequenceAt(1).getDatasetSequence(), protein
- .getSequenceAt(1).getDatasetSequence());
+ assertSame(copy.getSequenceAt(0).getDatasetSequence(),
+ protein.getSequenceAt(0).getDatasetSequence());
+ assertSame(copy.getSequenceAt(1).getDatasetSequence(),
+ protein.getSequenceAt(1).getDatasetSequence());
// TODO should the copy constructor copy the dataset?
// or make a new one referring to the same dataset sequences??
// side-effect: dataset created on second sequence
assertNotNull(protein.getSequenceAt(1).getDatasetSequence());
// dataset alignment has references to dataset sequences
- assertEquals(ds.getSequenceAt(0), protein.getSequenceAt(0)
- .getDatasetSequence());
- assertEquals(ds.getSequenceAt(1), protein.getSequenceAt(1)
- .getDatasetSequence());
+ assertEquals(ds.getSequenceAt(0),
+ protein.getSequenceAt(0).getDatasetSequence());
+ assertEquals(ds.getSequenceAt(1),
+ protein.getSequenceAt(1).getDatasetSequence());
// codon frames should have been moved to the dataset
// getCodonFrames() should delegate to the dataset:
// cross-references to two more sequences.
DBRefEntry dbr = new DBRefEntry("SQ1", "", "sq3");
SequenceI sq3 = new Sequence("sq3", "VWANG");
- dbr.setMap(new Mapping(sq3, new MapList(new int[] { 1, 4 }, new int[] {
- 2, 5 }, 1, 1)));
+ dbr.setMap(
+ new Mapping(sq3, new MapList(new int[]
+ { 1, 4 }, new int[] { 2, 5 }, 1, 1)));
sq1.addDBRef(dbr);
SequenceI sq4 = new Sequence("sq4", "ERKWI");
DBRefEntry dbr2 = new DBRefEntry("SQ2", "", "sq4");
- dbr2.setMap(new Mapping(sq4, new MapList(new int[] { 1, 4 }, new int[] {
- 2, 5 }, 1, 1)));
+ dbr2.setMap(
+ new Mapping(sq4, new MapList(new int[]
+ { 1, 4 }, new int[] { 2, 5 }, 1, 1)));
sq2.addDBRef(dbr2);
// and a 1:1 codonframe mapping between them.
AlignedCodonFrame alc = new AlignedCodonFrame();
- alc.addMap(sq1, sq2, new MapList(new int[] { 1, 4 },
- new int[] { 1, 4 }, 1, 1));
+ alc.addMap(sq1, sq2,
+ new MapList(new int[]
+ { 1, 4 }, new int[] { 1, 4 }, 1, 1));
AlignmentI protein = new Alignment(new SequenceI[] { sq1, sq2 });
Assert.assertEquals(align.getDataset().getHeight(), 1,
"Dataset shouldn't have more than one sequence.");
- Sequence seq2 = new Sequence("newtestSeq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
+ Sequence seq2 = new Sequence("newtestSeq",
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
align.addSequence(seq2);
Assert.assertEquals(align.getDataset().getHeight(), 2,
"Dataset should now have two sequences.");
// add dbref from dna to peptide
DBRefEntry dbr = new DBRefEntry("UNIPROT", "", "pep");
- dbr.setMap(new Mapping(pep, new MapList(new int[] { 4, 15 }, new int[] {
- 1, 4 }, 3, 1)));
+ dbr.setMap(
+ new Mapping(pep, new MapList(new int[]
+ { 4, 15 }, new int[] { 1, 4 }, 3, 1)));
dna.addDBRef(dbr);
// add dbref from dna to peptide
DBRefEntry dbr2 = new DBRefEntry("UNIPROT", "", "pep");
- dbr2.setMap(new Mapping(pep, new MapList(new int[] { 1, 12 }, new int[]
- { 1, 4 }, 3, 1)));
+ dbr2.setMap(
+ new Mapping(pep, new MapList(new int[]
+ { 1, 12 }, new int[] { 1, 4 }, 3, 1)));
cds.addDBRef(dbr2);
// add dbref from peptide to dna
DBRefEntry dbr3 = new DBRefEntry("EMBL", "", "dna");
- dbr3.setMap(new Mapping(dna, new MapList(new int[] { 1, 4 }, new int[] {
- 4, 15 }, 1, 3)));
+ dbr3.setMap(
+ new Mapping(dna, new MapList(new int[]
+ { 1, 4 }, new int[] { 4, 15 }, 1, 3)));
pep.addDBRef(dbr3);
// add dbref from peptide to cds
DBRefEntry dbr4 = new DBRefEntry("EMBLCDS", "", "cds");
- dbr4.setMap(new Mapping(cds, new MapList(new int[] { 1, 4 }, new int[] {
- 1, 12 }, 1, 3)));
+ dbr4.setMap(
+ new Mapping(cds, new MapList(new int[]
+ { 1, 4 }, new int[] { 1, 12 }, 1, 3)));
pep.addDBRef(dbr4);
AlignmentI protein = new Alignment(new SequenceI[] { pep });
@Test(
groups = "Functional",
- expectedExceptions = { IllegalArgumentException.class })
+ expectedExceptions =
+ { IllegalArgumentException.class })
public void testSetDataset_selfReference()
{
SequenceI seq = new Sequence("a", "a");
assertEquals('-', alignment.getGapCharacter());
assertSame(seq, alignment.getSequenceAt(0));
- assertEquals("KP--L-FQII-", alignment.getSequenceAt(1)
- .getSequenceAsString());
+ assertEquals("KP--L-FQII-",
+ alignment.getSequenceAt(1).getSequenceAsString());
// todo test coverage for annotations, mappings, groups,
// hidden sequences, properties
"Temperature Factor", null, false, seq, null);
assertNotNull(ala);
assertEquals(seq, ala.sequenceRef);
- assertEquals("", ala.calcId);
+ assertEquals("", ala.getCalcId());
+ }
+
+ @Test(groups = {"Functional"})
+ public void testUpdateFromOrAddAnnotation()
+ {
+ SequenceI seq = new Sequence("seq1", "FRMLPSRT-A--L-");
+ AlignmentI alignment = new Alignment(new SequenceI[] { seq });
+
+ AlignmentAnnotation ala = alignment.findOrCreateAnnotation(
+ "Temperature Factor", null, false, seq, null);
+
+ assertNotNull(ala);
+ assertEquals(seq, ala.sequenceRef);
+ assertEquals("", ala.getCalcId());
+
+ // Assuming findOrCreateForNullCalcId passed then this should work
+
+ assertTrue(ala == alignment.updateFromOrCopyAnnotation(ala));
+ AlignmentAnnotation updatedAla = new AlignmentAnnotation(ala);
+ updatedAla.description = "updated Description";
+ Assert.assertTrue(
+ ala == alignment.updateFromOrCopyAnnotation(updatedAla));
+ Assert.assertEquals(ala.toString(), updatedAla.toString());
+ updatedAla.calcId = "newCalcId";
+ AlignmentAnnotation newUpdatedAla = alignment
+ .updateFromOrCopyAnnotation(updatedAla);
+ Assert.assertTrue(updatedAla != newUpdatedAla);
+ Assert.assertEquals(updatedAla.toString(), newUpdatedAla.toString());
}
@Test(groups = "Functional")
import jalview.datamodel.ResidueCount.SymbolCounts;
import jalview.gui.JvOptionPane;
+import java.util.Arrays;
+
import org.junit.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
assertEquals(rc.getCount('N'), 1);
assertEquals(rc.getCount('?'), 0);
assertEquals(rc.getCount('-'), 0);
+ assertEquals(rc.getTotalResidueCount(), 11);
assertFalse(rc.isCountingInts());
assertFalse(rc.isUsingOtherData());
rc.add('-');
rc.add('.');
rc.add(' ');
-
+
assertEquals(rc.getGapCount(), 4);
assertEquals(rc.getCount(' '), 4);
assertEquals(rc.getCount('-'), 4);
assertEquals(rc.getCount('.'), 4);
+ assertEquals(rc.getTotalResidueCount(), 0);
assertFalse(rc.isUsingOtherData());
assertFalse(rc.isCountingInts());
-
- rc.set(ResidueCount.GAP_COUNT, Short.MAX_VALUE-2);
- assertEquals(rc.getGapCount(), Short.MAX_VALUE-2);
+
+ rc.set(ResidueCount.GAP_COUNT, Short.MAX_VALUE - 2);
+ assertEquals(rc.getGapCount(), Short.MAX_VALUE - 2);
assertFalse(rc.isCountingInts());
rc.addGap();
- assertEquals(rc.getGapCount(), Short.MAX_VALUE-1);
+ assertEquals(rc.getGapCount(), Short.MAX_VALUE - 1);
assertFalse(rc.isCountingInts());
rc.addGap();
assertEquals(rc.getGapCount(), Short.MAX_VALUE);
rc.addGap();
assertTrue(rc.isCountingInts());
- assertEquals(rc.getGapCount(), Short.MAX_VALUE+1);
+ assertEquals(rc.getGapCount(), Short.MAX_VALUE + 1);
}
@Test(groups = "Functional")
assertEquals(rc.getCount('m'), 13);
assertEquals(rc.getCount('G'), 0);
assertEquals(rc.getCount('-'), 0);
+ assertEquals(rc.getTotalResidueCount(), 27);
assertFalse(rc.isCountingInts());
assertFalse(rc.isUsingOtherData());
rc.add('P');
assertEquals(rc.getResiduesForCount(Short.MAX_VALUE + 1), "P");
assertEquals(rc.getResiduesForCount(1), "C");
-
+
// modal count is in the 'other data' counts
rc = new ResidueCount();
rc.add('Q');
rc.add('K');
}
rc.add('F');
-
+
/*
* percentages are rounded (0.5 rounded up)
* 10/40 9/40 7/40 6/40 1/40
assertEquals(rc.getCount('?'), 6);
assertEquals(rc.getCount('!'), 7);
}
+
+ @Test(groups = "Functional")
+ public void testConstructor_forSequences()
+ {
+ SequenceI seq1 = new Sequence("seq1", "abcde--. FCD");
+ SequenceI seq2 = new Sequence("seq2", "ab.kKqBd-.");
+ ResidueCount rc = new ResidueCount(Arrays.asList(seq1, seq2));
+
+ assertEquals(rc.getGapCount(), 7);
+ assertEquals(rc.getTotalResidueCount(), 15); // excludes gaps
+ assertEquals(rc.getCount('a'), 2);
+ assertEquals(rc.getCount('A'), 2);
+ assertEquals(rc.getCount('B'), 3);
+ assertEquals(rc.getCount('c'), 2);
+ assertEquals(rc.getCount('D'), 3);
+ assertEquals(rc.getCount('f'), 1);
+ assertEquals(rc.getCount('K'), 2);
+ assertEquals(rc.getCount('Q'), 1);
+ }
}
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.datamodel;
import static org.testng.Assert.assertEquals;
public class SequenceGroupTest
{
- @Test(groups={"Functional"})
+ @Test(groups = { "Functional" })
public void testAddSequence()
{
SequenceGroup sg = new SequenceGroup();
assertTrue(sg.getSequences().contains(seq3));
}
- @Test(groups={"Functional"})
+ @Test(groups = { "Functional" })
public void testAddOrRemove()
{
SequenceGroup sg = new SequenceGroup();
assertTrue(sg.getSequences().isEmpty());
-
+
SequenceI seq1 = new Sequence("seq1", "abc");
SequenceI seq2 = new Sequence("seq2", "abc");
SequenceI seq3 = new Sequence(seq1);
-
+
sg.addOrRemove(seq1, false);
assertEquals(sg.getSequences().size(), 1);
sg.addOrRemove(seq2, false);
assertFalse(sg.getSequences().contains(seq1));
}
- @Test(groups={"Functional"})
+ @Test(groups = { "Functional" })
public void testGetColourScheme()
{
SequenceGroup sg = new SequenceGroup();
assertSame(scheme, sg.getColourScheme());
}
- @Test(groups={"Functional"})
+ @Test(groups = { "Functional" })
public void testSetContext()
{
SequenceGroup sg1 = new SequenceGroup();
sg.setDisplayBoxes(false);
sg.setDisplayText(false);
sg.setColourText(true);
- sg.isDefined = true;
+ PA.setValue(sg, "isDefined", true);
sg.setShowNonconserved(true);
sg.setOutlineColour(Color.red);
sg.setIdColour(Color.blue);
{
SequenceI s1 = new Sequence("abcde", "fg");
SequenceI s2 = new Sequence("foo", "bar");
- List<SequenceI> seqs = new ArrayList<SequenceI>();
+ List<SequenceI> seqs = new ArrayList<>();
seqs.add(s1);
seqs.add(s2);
SequenceGroup sg = new SequenceGroup(seqs);
import static org.testng.AssertJUnit.assertSame;
import static org.testng.AssertJUnit.assertTrue;
-import jalview.analysis.AlignmentGenerator;
-import jalview.commands.EditCommand;
-import jalview.commands.EditCommand.Action;
-import jalview.datamodel.PDBEntry.Type;
-import jalview.gui.JvOptionPane;
-import jalview.util.MapList;
-import jalview.ws.params.InvalidArgumentException;
-
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
+import jalview.analysis.AlignmentGenerator;
+import jalview.commands.EditCommand;
+import jalview.commands.EditCommand.Action;
+import jalview.datamodel.PDBEntry.Type;
+import jalview.gui.JvOptionPane;
+import jalview.util.MapList;
+
import junit.extensions.PA;
public class SequenceTest
assertEquals("getInsertionsAsBits didn't mark expected number of gaps",
6, gapfield.cardinality());
- assertEquals("getInsertionsAsBits not correct.", expectedgaps, gapfield);
+ assertEquals("getInsertionsAsBits not correct.", expectedgaps,
+ gapfield);
}
@Test(groups = ("Functional"))
@Test(groups = ("Functional"))
public void testIsProteinWithXorNAmbiguityCodes()
{
- // test Protein with N - poly asparagine
+ // test Protein with N - poly asparagine
assertTrue(new Sequence("prot", "ASDFASDFASDFNNNNNNNNN").isProtein());
assertTrue(new Sequence("prot", "NNNNNNNNNNNNNNNNNNNNN").isProtein());
// test Protein with X
assertTrue(seq.getAlignmentAnnotations(null, null).isEmpty());
}
-
@Test(groups = { "Functional" })
public void testGetAlignmentAnnotations_forCalcIdLabelAndDescription()
{
/**
* null matching should fail
*/
- assertTrue(seq.getAlignmentAnnotations("calcId3", "label2",null).isEmpty());
-
- assertTrue(seq.getAlignmentAnnotations("calcId2", "label3",null).isEmpty());
- assertTrue(seq.getAlignmentAnnotations("calcId3", "label5",null).isEmpty());
- assertTrue(seq.getAlignmentAnnotations("calcId2", null,null).isEmpty());
- assertTrue(seq.getAlignmentAnnotations(null, "label3",null).isEmpty());
- assertTrue(seq.getAlignmentAnnotations(null, null,null).isEmpty());
+ assertTrue(seq.getAlignmentAnnotations("calcId3", "label2", null)
+ .isEmpty());
+
+ assertTrue(seq.getAlignmentAnnotations("calcId2", "label3", null)
+ .isEmpty());
+ assertTrue(seq.getAlignmentAnnotations("calcId3", "label5", null)
+ .isEmpty());
+ assertTrue(
+ seq.getAlignmentAnnotations("calcId2", null, null).isEmpty());
+ assertTrue(seq.getAlignmentAnnotations(null, "label3", null).isEmpty());
+ assertTrue(seq.getAlignmentAnnotations(null, null, null).isEmpty());
}
/**
public void testAddAlignmentAnnotation()
{
assertNull(seq.getAnnotation());
- final AlignmentAnnotation annotation = new AlignmentAnnotation("a",
- "b", 2d);
+ final AlignmentAnnotation annotation = new AlignmentAnnotation("a", "b",
+ 2d);
assertNull(annotation.sequenceRef);
seq.addAlignmentAnnotation(annotation);
assertSame(seq, annotation.sequenceRef);
* invalid inputs
*/
assertNull(sq.findPositions(6, 5));
- assertNull(sq.findPositions(0, 5));
- assertNull(sq.findPositions(-1, 5));
/*
* all gapped ranges
assertEquals(new Range(11, 12), sq.findPositions(5, 10)); // DE
assertEquals(new Range(8, 13), sq.findPositions(1, 13)); // the lot
assertEquals(new Range(8, 13), sq.findPositions(1, 99));
+
+ /**
+ * now try on a sequence with no gaps
+ */
+ sq.createDatasetSequence();
+ assertEquals(new Range(8, 13),
+ sq.getDatasetSequence().findPositions(1, 99));
+ assertEquals(new Range(8, 13),
+ sq.getDatasetSequence().findPositions(0, 99));
+
}
/**
/*
* SequenceFeature on sequence
*/
- SequenceFeature sf = new SequenceFeature("Cath", "desc", 2, 4, 2f, null);
+ SequenceFeature sf = new SequenceFeature("Cath", "desc", 2, 4, 2f,
+ null);
sq.addSequenceFeature(sf);
List<SequenceFeature> sfs = sq.getSequenceFeatures();
assertEquals(1, sfs.size());
try
{
sq.getDatasetSequence().setDatasetSequence(sq); // loop!
- Assert.fail("Expected Error to be raised when calling setDatasetSequence with self reference");
+ Assert.fail(
+ "Expected Error to be raised when calling setDatasetSequence with self reference");
} catch (IllegalArgumentException e)
{
// TODO Jalview error/exception class for raising implementation errors
public void testCreateDatasetSequence()
{
SequenceI sq = new Sequence("my", "ASDASD");
- sq.addSequenceFeature(new SequenceFeature("type", "desc", 1, 10, 1f,
- "group"));
+ sq.addSequenceFeature(
+ new SequenceFeature("type", "desc", 1, 10, 1f, "group"));
sq.addDBRef(new DBRefEntry("source", "version", "accession"));
assertNull(sq.getDatasetSequence());
assertNotNull(PA.getValue(sq, "sequenceFeatureStore"));
DBRefEntry pdb1pdb = new DBRefEntry("PDB", "version1", "1PDB");
DBRefEntry pdb2pdb = new DBRefEntry("PDB", "version2", "2PDB");
- List<DBRefEntry> primRefs = Arrays.asList(new DBRefEntry[] { pdb1pdb,
- pdb2pdb });
+ List<DBRefEntry> primRefs = Arrays
+ .asList(new DBRefEntry[]
+ { pdb1pdb, pdb2pdb });
sq.getDatasetSequence().addDBRef(pdb1pdb); // should do nothing
sq.getDatasetSequence().addDBRef(pdb2pdb); // should do nothing
- sq.getDatasetSequence().addDBRef(
- new DBRefEntry("PDB", "version3", "3PDB")); // should do nothing
- sq.getDatasetSequence().addDBRef(
- new DBRefEntry("PDB", "version4", "4PDB")); // should do nothing
+ sq.getDatasetSequence()
+ .addDBRef(new DBRefEntry("PDB", "version3", "3PDB")); // should do
+ // nothing
+ sq.getDatasetSequence()
+ .addDBRef(new DBRefEntry("PDB", "version4", "4PDB")); // should do
+ // nothing
PDBEntry pdbe1a = new PDBEntry("1PDB", "A", Type.PDB, "filePath/test1");
PDBEntry pdbe1b = new PDBEntry("1PDB", "B", Type.PDB, "filePath/test1");
/*
* test we added pdb entries to the dataset sequence
*/
- Assert.assertEquals(sq.getDatasetSequence().getAllPDBEntries(), Arrays
- .asList(new PDBEntry[] { pdbe1a, pdbe1b, pdbe2a, pdbe2b }),
+ Assert.assertEquals(sq.getDatasetSequence().getAllPDBEntries(),
+ Arrays.asList(new PDBEntry[]
+ { pdbe1a, pdbe1b, pdbe2a, pdbe2b }),
"PDB Entries were not found on dataset sequence.");
/*
* we should recover a pdb entry that is on the dataset sequence via PDBEntry
*/
- Assert.assertEquals(pdbe1a,
- sq.getDatasetSequence().getPDBEntry("1PDB"),
+ Assert.assertEquals(pdbe1a, sq.getDatasetSequence().getPDBEntry("1PDB"),
"PDB Entry '1PDB' not found on dataset sequence via getPDBEntry.");
ArrayList<Annotation> annotsList = new ArrayList<>();
System.out.println(">>>>>> " + sq.getSequenceAsString().length());
Annotation[] annots = annotsList.toArray(new Annotation[0]);
sq.addAlignmentAnnotation(new AlignmentAnnotation("Test annot",
"Test annot description", annots));
- sq.getDatasetSequence().addAlignmentAnnotation(
- new AlignmentAnnotation("Test annot", "Test annot description",
- annots));
+ sq.getDatasetSequence().addAlignmentAnnotation(new AlignmentAnnotation(
+ "Test annot", "Test annot description", annots));
Assert.assertEquals(sq.getDescription(), "Test sequence description..");
Assert.assertEquals(sq.getDBRefs().size(), 5); // DBRefs are on dataset
// sequence
Assert.assertNotNull(derived.getAnnotation());
Assert.assertEquals(derived.getAnnotation()[0].annotations.length, 2);
Assert.assertEquals(derived.getDatasetSequence().getDBRefs().size(), 5);
- Assert.assertEquals(derived.getDatasetSequence().getAllPDBEntries()
- .size(), 4);
+ Assert.assertEquals(
+ derived.getDatasetSequence().getAllPDBEntries().size(), 4);
Assert.assertNotNull(derived.getDatasetSequence().getAnnotation());
assertEquals("CD", derived.getSequenceAsString());
assertEquals(6, sq.getEnd());
SequenceI derived = sq.deriveSequence();
assertEquals("ABCDEF", derived.getSequenceAsString());
- assertEquals("ABCDEF", derived.getDatasetSequence()
- .getSequenceAsString());
+ assertEquals("ABCDEF",
+ derived.getDatasetSequence().getSequenceAsString());
}
/**
assertNull(sq.getDatasetSequence());
SequenceI derived = sq.deriveSequence();
assertEquals("AB-C.D EF", derived.getSequenceAsString());
- assertEquals("ABCDEF", derived.getDatasetSequence()
- .getSequenceAsString());
+ assertEquals("ABCDEF",
+ derived.getDatasetSequence().getSequenceAsString());
}
@Test(groups = { "Functional" })
{
SequenceI seq1 = new Sequence("Seq1", "AB-C.D EF");
seq1.setDescription("description");
- seq1.addAlignmentAnnotation(new AlignmentAnnotation("label", "desc",
- 1.3d));
- seq1.addSequenceFeature(new SequenceFeature("type", "desc", 22, 33,
- 12.4f, "group"));
+ seq1.addAlignmentAnnotation(
+ new AlignmentAnnotation("label", "desc", 1.3d));
+ seq1.addSequenceFeature(
+ new SequenceFeature("type", "desc", 22, 33, 12.4f, "group"));
seq1.addPDBId(new PDBEntry("1A70", "B", Type.PDB, "File"));
seq1.addDBRef(new DBRefEntry("EMBL", "1.2", "AZ12345"));
SequenceI seq1 = new Sequence("Seq1", "AB-C.D EF");
seq1.createDatasetSequence();
seq1.setDescription("description");
- seq1.addAlignmentAnnotation(new AlignmentAnnotation("label", "desc",
- 1.3d));
+ seq1.addAlignmentAnnotation(
+ new AlignmentAnnotation("label", "desc", 1.3d));
// JAL-2046 - what is the contract for using a derived sequence's
// addSequenceFeature ?
- seq1.addSequenceFeature(new SequenceFeature("type", "desc", 22, 33,
- 12.4f, "group"));
+ seq1.addSequenceFeature(
+ new SequenceFeature("type", "desc", 22, 33, 12.4f, "group"));
seq1.addPDBId(new PDBEntry("1A70", "B", Type.PDB, "File"));
// here we add DBRef to the dataset sequence:
- seq1.getDatasetSequence().addDBRef(
- new DBRefEntry("EMBL", "1.2", "AZ12345"));
+ seq1.getDatasetSequence()
+ .addDBRef(new DBRefEntry("EMBL", "1.2", "AZ12345"));
SequenceI copy = new Sequence(seq1);
{
SequenceI sq = new Sequence("", "abcde");
// type may not be null
- assertFalse(sq.addSequenceFeature(new SequenceFeature(null, "desc", 4,
- 8, 0f, null)));
- assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
- 8, 0f, null)));
+ assertFalse(sq.addSequenceFeature(
+ new SequenceFeature(null, "desc", 4, 8, 0f, null)));
+ assertTrue(sq.addSequenceFeature(
+ new SequenceFeature("Cath", "desc", 4, 8, 0f, null)));
// can't add a duplicate feature
- assertFalse(sq.addSequenceFeature(new SequenceFeature("Cath", "desc",
- 4, 8, 0f, null)));
+ assertFalse(sq.addSequenceFeature(
+ new SequenceFeature("Cath", "desc", 4, 8, 0f, null)));
// can add a different feature
- assertTrue(sq.addSequenceFeature(new SequenceFeature("Scop", "desc", 4,
- 8, 0f, null))); // different type
- assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath",
- "description", 4, 8, 0f, null)));// different description
- assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 3,
- 8, 0f, null))); // different start position
- assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
- 9, 0f, null))); // different end position
- assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
- 8, 1f, null))); // different score
- assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
- 8, Float.NaN, null))); // score NaN
- assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
- 8, 0f, "Metal"))); // different group
+ assertTrue(sq.addSequenceFeature(
+ new SequenceFeature("Scop", "desc", 4, 8, 0f, null))); // different
+ // type
+ assertTrue(sq.addSequenceFeature(
+ new SequenceFeature("Cath", "description", 4, 8, 0f, null)));// different
+ // description
+ assertTrue(sq.addSequenceFeature(
+ new SequenceFeature("Cath", "desc", 3, 8, 0f, null))); // different
+ // start
+ // position
+ assertTrue(sq.addSequenceFeature(
+ new SequenceFeature("Cath", "desc", 4, 9, 0f, null))); // different
+ // end
+ // position
+ assertTrue(sq.addSequenceFeature(
+ new SequenceFeature("Cath", "desc", 4, 8, 1f, null))); // different
+ // score
+ assertTrue(sq.addSequenceFeature(
+ new SequenceFeature("Cath", "desc", 4, 8, Float.NaN, null))); // score
+ // NaN
+ assertTrue(sq.addSequenceFeature(
+ new SequenceFeature("Cath", "desc", 4, 8, 0f, "Metal"))); // different
+ // group
assertEquals(8, sq.getFeatures().getAllFeatures().size());
}
* matching ref with a mapping - map updated
*/
DBRefEntry dbref5 = new DBRefEntry("UniRef", "1", "p00341");
- Mapping map = new Mapping(new MapList(new int[] { 1, 3 }, new int[] {
- 1, 1 }, 3, 1));
+ Mapping map = new Mapping(
+ new MapList(new int[]
+ { 1, 3 }, new int[] { 1, 1 }, 3, 1));
dbref5.setMap(map);
sq.addDBRef(dbref5);
assertEquals(4, sq.getDBRefs().size());
assertTrue(primaryDBRefs.isEmpty());
// empty dbrefs
- sq.setDBRefs(null);
+ sq.setDBRefs(null);
primaryDBRefs = sq.getPrimaryDBRefs();
assertTrue(primaryDBRefs.isEmpty());
// primary - uniprot with congruent map
DBRefEntry upentry2 = new DBRefEntry("UNIPROT", "0", "Q04762");
- upentry2.setMap(new Mapping(null, new MapList(new int[] { 10, 22 },
- new int[] { 10, 22 }, 1, 1)));
+ upentry2.setMap(
+ new Mapping(null, new MapList(new int[]
+ { 10, 22 }, new int[] { 10, 22 }, 1, 1)));
sq.addDBRef(upentry2);
// primary - uniprot with map of enclosing sequence
DBRefEntry upentry3 = new DBRefEntry("UNIPROT", "0", "Q04763");
- upentry3.setMap(new Mapping(null, new MapList(new int[] { 8, 24 },
- new int[] { 8, 24 }, 1, 1)));
+ upentry3.setMap(
+ new Mapping(null, new MapList(new int[]
+ { 8, 24 }, new int[] { 8, 24 }, 1, 1)));
sq.addDBRef(upentry3);
// not primary - uniprot with map of sub-sequence (5')
DBRefEntry upentry4 = new DBRefEntry("UNIPROT", "0", "Q04764");
- upentry4.setMap(new Mapping(null, new MapList(new int[] { 10, 18 },
- new int[] { 10, 18 }, 1, 1)));
+ upentry4.setMap(
+ new Mapping(null, new MapList(new int[]
+ { 10, 18 }, new int[] { 10, 18 }, 1, 1)));
sq.addDBRef(upentry4);
// not primary - uniprot with map that overlaps 3'
DBRefEntry upentry5 = new DBRefEntry("UNIPROT", "0", "Q04765");
- upentry5.setMap(new Mapping(null, new MapList(new int[] { 12, 22 },
- new int[] { 12, 22 }, 1, 1)));
+ upentry5.setMap(
+ new Mapping(null, new MapList(new int[]
+ { 12, 22 }, new int[] { 12, 22 }, 1, 1)));
sq.addDBRef(upentry5);
// not primary - uniprot with map to different coordinates frame
DBRefEntry upentry6 = new DBRefEntry("UNIPROT", "0", "Q04766");
- upentry6.setMap(new Mapping(null, new MapList(new int[] { 12, 18 },
- new int[] { 112, 118 }, 1, 1)));
+ upentry6.setMap(
+ new Mapping(null, new MapList(new int[]
+ { 12, 18 }, new int[] { 112, 118 }, 1, 1)));
sq.addDBRef(upentry6);
// not primary - dbref to 'non-core' database
// add corroborating PDB entry for primary DBref -
// needs to have a file as well as matching ID
// note PDB ID is not treated as case sensitive
- sq.addPDBId(new PDBEntry("1QIP", null, Type.PDB, new File("/blah")
- .toString()));
+ sq.addPDBId(new PDBEntry("1QIP", null, Type.PDB,
+ new File("/blah").toString()));
// not valid DBRef - no file..
sq.addPDBId(new PDBEntry("1AAA", null, null, null));
@Test(groups = { "Functional" })
public void testGetPrimaryDBRefs_nucleotide()
{
- SequenceI sq = new Sequence("aseq", "TGATCACTCGACTAGCATCAGCATA", 10, 34);
+ SequenceI sq = new Sequence("aseq", "TGATCACTCGACTAGCATCAGCATA", 10,
+ 34);
// primary - Ensembl
DBRefEntry dbr1 = new DBRefEntry("ENSEMBL", "0", "ENSG1234");
// not primary - Ensembl 'transcript' mapping of sub-sequence
DBRefEntry dbr2 = new DBRefEntry("ENSEMBL", "0", "ENST1234");
- dbr2.setMap(new Mapping(null, new MapList(new int[] { 15, 25 },
- new int[] { 1, 11 }, 1, 1)));
+ dbr2.setMap(
+ new Mapping(null, new MapList(new int[]
+ { 15, 25 }, new int[] { 1, 11 }, 1, 1)));
sq.addDBRef(dbr2);
// primary - EMBL with congruent map
DBRefEntry dbr3 = new DBRefEntry("EMBL", "0", "J1234");
- dbr3.setMap(new Mapping(null, new MapList(new int[] { 10, 34 },
- new int[] { 10, 34 }, 1, 1)));
+ dbr3.setMap(
+ new Mapping(null, new MapList(new int[]
+ { 10, 34 }, new int[] { 10, 34 }, 1, 1)));
sq.addDBRef(dbr3);
// not primary - to non-core database
seq.addPDBId(pdbe5);
assertEquals(4, seq.getAllPDBEntries().size());
assertSame(pdbe5, seq.getAllPDBEntries().get(3));
-
- // add with a fake pdbid
+
+ // add with a fake pdbid
// (models don't have an embedded ID)
String realId = "RealIDQ";
- PDBEntry pdbe6 = new PDBEntry(realId,null,Type.PDB,"real/localpath");
- PDBEntry pdbe7 = new PDBEntry("RealID/real/localpath","C",Type.MMCIF,"real/localpath");
+ PDBEntry pdbe6 = new PDBEntry(realId, null, Type.PDB, "real/localpath");
+ PDBEntry pdbe7 = new PDBEntry("RealID/real/localpath", "C", Type.MMCIF,
+ "real/localpath");
pdbe7.setFakedPDBId(true);
seq.addPDBId(pdbe6);
- assertEquals(5,seq.getAllPDBEntries().size());
+ assertEquals(5, seq.getAllPDBEntries().size());
seq.addPDBId(pdbe7);
- assertEquals(5,seq.getAllPDBEntries().size());
+ assertEquals(5, seq.getAllPDBEntries().size());
assertFalse(pdbe6.fakedPDBId());
- assertSame(pdbe6,seq.getAllPDBEntries().get(4));
- assertEquals("C",pdbe6.getChainCode());
+ assertSame(pdbe6, seq.getAllPDBEntries().get(4));
+ assertEquals("C", pdbe6.getChainCode());
assertEquals(realId, pdbe6.getId());
}
@Test(
- groups = { "Functional" },
- expectedExceptions = { IllegalArgumentException.class })
+ groups =
+ { "Functional" },
+ expectedExceptions =
+ { IllegalArgumentException.class })
public void testSetDatasetSequence_toSelf()
{
seq.setDatasetSequence(seq);
}
@Test(
- groups = { "Functional" },
- expectedExceptions = { IllegalArgumentException.class })
+ groups =
+ { "Functional" },
+ expectedExceptions =
+ { IllegalArgumentException.class })
public void testSetDatasetSequence_cascading()
{
SequenceI seq2 = new Sequence("Seq2", "xyz");
"desc", 13, 14, 2f, null);
sq.addSequenceFeature(sfContactFG);
// add single position feature at [I]
- SequenceFeature sfI = new SequenceFeature("Disulfide Bond",
- "desc", 16, 16, null);
+ SequenceFeature sfI = new SequenceFeature("Disulfide Bond", "desc", 16,
+ 16, null);
sq.addSequenceFeature(sfI);
// no features in columns 1-2 (-A)
Sequence sq = new Sequence("test/8-13", "-A--BCD-EF--");
final int tok = (int) PA.getValue(sq, "changeCount");
assertEquals(1, tok);
-
+
// find F pos given A - lastCol gets set in cursor
assertEquals(13,
sq.findPosition(10, new SequenceCursor(sq, 8, 2, tok)));
sq.findPosition(2, new SequenceCursor(sq, 13, 10, tok)));
assertEquals("test:Pos8:Col2:startCol2:endCol10:tok1",
PA.getValue(sq, "cursor").toString());
-
+
// find C pos given C (neither startCol nor endCol is set)
assertEquals(10,
sq.findPosition(6, new SequenceCursor(sq, 10, 6, tok)));
public void testFindPosition_withCursorAndEdits()
{
Sequence sq = new Sequence("test/8-13", "-A--BCD-EF--");
-
+
// find F pos given A
assertEquals(13, sq.findPosition(10, new SequenceCursor(sq, 8, 2, 0)));
int token = (int) PA.getValue(sq, "changeCount"); // 0
*/
SequenceI sq = new Sequence("test", "-ABC--DEF--", 1, 20);
sq.createDatasetSequence();
-
+
assertTrue(sq.findFeatures(1, 9).isEmpty());
// should be no array bounds exception - JAL-2772
assertTrue(sq.findFeatures(1, 15).isEmpty());
-
+
// add feature on BCD
SequenceFeature sfBCD = new SequenceFeature("Cath", "desc", 2, 4, 2f,
null);
sq.addSequenceFeature(sfBCD);
-
+
// no features in columns 1-2 (-A)
List<SequenceFeature> found = sq.findFeatures(1, 2);
assertTrue(found.isEmpty());
-
+
// columns 1-6 (-ABC--) includes BCD
found = sq.findFeatures(1, 6);
assertEquals(1, found.size());
assertEquals(0, seq.firstResidueOutsideIterator(cs.iterator()));
}
- @Test(groups= {"Functional"})
- public void testTransferAnnotation() {
- Sequence origSeq = new Sequence("MYSEQ","THISISASEQ");
- Sequence toSeq = new Sequence("MYSEQ","THISISASEQ");
+
+ @Test(groups = { "Functional" })
+ public void testTransferAnnotation()
+ {
+ Sequence origSeq = new Sequence("MYSEQ", "THISISASEQ");
+ Sequence toSeq = new Sequence("MYSEQ", "THISISASEQ");
origSeq.addDBRef(new DBRefEntry("UNIPROT", "0", "Q12345", null, true));
toSeq.transferAnnotation(origSeq, null);
- assertTrue(toSeq.getDBRefs().size()==1);
-
+ assertTrue(toSeq.getDBRefs().size() == 1);
+
assertTrue(toSeq.getDBRefs().get(0).isCanonical());
-
- // check for promotion of non-canonical
+
+ // check for promotion of non-canonical
// to canonical (e.g. fetch-db-refs on a jalview project pre 2.11.2)
toSeq.setDBRefs(null);
toSeq.addDBRef(new DBRefEntry("UNIPROT", "0", "Q12345", null, false));
toSeq.transferAnnotation(origSeq, null);
- assertTrue(toSeq.getDBRefs().size()==1);
-
- assertTrue("Promotion of non-canonical DBRefEntry failed",toSeq.getDBRefs().get(0).isCanonical());
-
-
+ assertTrue(toSeq.getDBRefs().size() == 1);
+
+ assertTrue("Promotion of non-canonical DBRefEntry failed",
+ toSeq.getDBRefs().get(0).isCanonical());
+
}
}
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.datamodel.features;
import static org.testng.Assert.assertEquals;
"group");
sf.setValue("kd", "-1");
sf.setValue("domain", "Metal");
+ sf.setValue("foo", " ");
sf.setValue("phase", "1");
- sf.setValue("phase", "reverse");
+ sf.setValue("phase", "1reverse");
assertEquals(fa.getDatatype("Pfam", "kd"), Datatype.Number);
assertEquals(fa.getDatatype("Pfam", "domain"), Datatype.Character);
assertEquals(fa.getDatatype("Pfam", "phase"), Datatype.Mixed);
+ assertNull(fa.getDatatype("Pfam", "unobserved"));
+ assertNull(fa.getDatatype("Pfam", "foo"));// empty values are ignored
}
}
@BeforeClass(alwaysRun = true)
public void setUp()
{
- SequenceOntologyFactory.setInstance(new SequenceOntologyLite());
+ SequenceOntologyFactory.setSequenceOntology(new SequenceOntologyLite());
}
@AfterClass(alwaysRun = true)
public void tearDown()
{
- SequenceOntologyFactory.setInstance(null);
+ SequenceOntologyFactory.setSequenceOntology(null);
}
/**
String accId = "ABC123";
EnsemblCdna testee = new EnsemblCdna();
- SequenceFeature sf = new SequenceFeature("transcript", "", 20000,
- 20500, 0f, null);
+ SequenceFeature sf = new SequenceFeature("transcript", "", 20000, 20500,
+ 0f, null);
assertFalse(testee.retainFeature(sf, accId));
sf = new SequenceFeature("aberrant_processed_transcript", "", 20000,
20500, 0f, null);
assertFalse(testee.retainFeature(sf, accId));
- sf = new SequenceFeature("NMD_transcript_variant", "", 20000, 20500,
- 0f, null);
+ sf = new SequenceFeature("NMD_transcript_variant", "", 20000, 20500, 0f,
+ null);
assertFalse(testee.retainFeature(sf, accId));
// other feature with no parent is retained
- sf = new SequenceFeature("sequence_variant", "", 20000, 20500, 0f, null);
+ sf = new SequenceFeature("sequence_variant", "", 20000, 20500, 0f,
+ null);
assertTrue(testee.retainFeature(sf, accId));
// other feature with desired parent is retained
@BeforeClass(alwaysRun = true)
public void setUp()
{
- SequenceOntologyFactory.setInstance(new SequenceOntologyLite());
+ SequenceOntologyFactory.setSequenceOntology(new SequenceOntologyLite());
}
@AfterClass(alwaysRun = true)
public void tearDown()
{
- SequenceOntologyFactory.setInstance(null);
+ SequenceOntologyFactory.setSequenceOntology(null);
}
/**
assertFalse(testee.retainFeature(sf, accId));
// other feature with no parent is retained
- sf = new SequenceFeature("anotherType", "", 20000,
- 20500, 0f, null);
+ sf = new SequenceFeature("anotherType", "", 20000, 20500, 0f, null);
assertTrue(testee.retainFeature(sf, accId));
// other feature with desired parent is retained
public void setUp()
{
Cache.loadProperties("test/jalview/io/testProps.jvprops");
- SequenceOntologyFactory.setInstance(new SequenceOntologyLite());
+ SequenceOntologyFactory.setSequenceOntology(new SequenceOntologyLite());
}
@AfterClass(alwaysRun = true)
public void tearDown()
{
- SequenceOntologyFactory.setInstance(null);
+ SequenceOntologyFactory.setSequenceOntology(null);
}
/**
genomic.addSequenceFeature(sf1);
// transcript sub-type feature
- SequenceFeature sf2 = new SequenceFeature("snRNA", "", 21000, 21500,
- 0f, null);
+ SequenceFeature sf2 = new SequenceFeature("snRNA", "", 21000, 21500, 0f,
+ null);
sf2.setValue("Parent", geneId);
sf2.setValue("id", "transcript2");
genomic.addSequenceFeature(sf2);
genomic.addSequenceFeature(sf3);
// transcript for a different gene - ignored
- SequenceFeature sf4 = new SequenceFeature("snRNA", "", 23000, 23500,
- 0f, null);
+ SequenceFeature sf4 = new SequenceFeature("snRNA", "", 23000, 23500, 0f,
+ null);
sf4.setValue("Parent", "XYZ");
sf4.setValue("id", "transcript4");
genomic.addSequenceFeature(sf4);
sf.setValue("Parent", geneId);
assertTrue(testee.retainFeature(sf, geneId));
- sf = new SequenceFeature("NMD_transcript_variant", "", 20000, 20500,
- 0f, null);
+ sf = new SequenceFeature("NMD_transcript_variant", "", 20000, 20500, 0f,
+ null);
sf.setValue("Parent", geneId);
assertTrue(testee.retainFeature(sf, geneId));
seq.addSequenceFeature(sf3);
// gene sub-type with right ID is valid
- SequenceFeature sf4 = new SequenceFeature("snRNA_gene", "", 1, 2, 0f, null);
+ SequenceFeature sf4 = new SequenceFeature("snRNA_gene", "", 1, 2, 0f,
+ null);
sf4.setValue("id", accId);
seq.addSequenceFeature(sf4);
// transcript not valid:
- SequenceFeature sf5 = new SequenceFeature("transcript", "", 1, 2, 0f, null);
+ SequenceFeature sf5 = new SequenceFeature("transcript", "", 1, 2, 0f,
+ null);
sf5.setValue("id", accId);
seq.addSequenceFeature(sf5);
SequenceFeature sf6 = new SequenceFeature("exon", "", 1, 2, 0f, null);
sf6.setValue("id", accId);
seq.addSequenceFeature(sf6);
-
+
List<SequenceFeature> sfs = new EnsemblGene()
.getIdentifyingFeatures(seq, accId);
assertFalse(sfs.contains(sf1));
assertTrue(fc.isFeatureHidden("transcript"));
assertTrue(fc.isFeatureHidden("CDS"));
- assertEquals(Color.RED, fc.getFeatureColour("sequence_variant")
- .getColour());
- assertEquals(Color.RED, fc.getFeatureColour("feature_variant")
- .getColour());
+ assertEquals(Color.RED,
+ fc.getFeatureColour("sequence_variant").getColour());
+ assertEquals(Color.RED,
+ fc.getFeatureColour("feature_variant").getColour());
assertTrue(fc.getFeatureColour("exon").isColourByLabel());
assertTrue(fc.getFeatureColour("coding_exon").isColourByLabel());
assertEquals(1, fc.compare("sequence_variant", "exon"));
String ids = "ENSG00000158828 ENST00000321556 P30419 ENST00000592782 BRAF";
EnsemblGene testee = new EnsemblGene();
List<String> geneIds = testee.getGeneIds(ids);
- assertEquals(8, geneIds.size());
assertTrue(geneIds.contains("ENSG00000158828"));
assertTrue(geneIds.contains("ENSG00000136448"));
assertTrue(geneIds.contains("ENSG00000157764")); // BRAF human
assertTrue(geneIds.contains("ENSXETG00000004845")); // xenopus
assertTrue(geneIds.contains("ENSDARG00000017661")); // zebrafish
assertTrue(geneIds.contains("ENSGALG00000012865")); // chicken
+ assertEquals(8, geneIds.size());
+
}
}
@BeforeClass(alwaysRun = true)
public void setUp()
{
- SequenceOntologyFactory.setInstance(new SequenceOntologyLite());
+ SequenceOntologyFactory.setSequenceOntology(new SequenceOntologyLite());
}
@AfterClass(alwaysRun = true)
public void tearDown()
{
- SequenceOntologyFactory.setInstance(null);
+ SequenceOntologyFactory.setSequenceOntology(null);
}
/**
String transcriptId = "ABC123";
// transcript at (start+10000) length 501
- SequenceFeature sf = new SequenceFeature("transcript", "", 20000,
- 20500, 0f, null);
+ SequenceFeature sf = new SequenceFeature("transcript", "", 20000, 20500,
+ 0f, null);
sf.setValue("id", transcriptId);
sf.setStrand("+");
genomic.addSequenceFeature(sf);
// Ensembl treats NMD_transcript_variant as if transcript
// although strictly it is a sequence_variant in SO
- sf = new SequenceFeature("NMD_transcript_variant", "", 11000, 12000,
- 0f, null);
+ sf = new SequenceFeature("NMD_transcript_variant", "", 11000, 12000, 0f,
+ null);
sf.setValue("id", transcriptId);
sf.setStrand("+");
genomic.addSequenceFeature(sf);
String accId = "ABC123";
EnsemblGenome testee = new EnsemblGenome();
- SequenceFeature sf = new SequenceFeature("transcript", "", 20000,
- 20500, 0f, null);
+ SequenceFeature sf = new SequenceFeature("transcript", "", 20000, 20500,
+ 0f, null);
assertFalse(testee.retainFeature(sf, accId));
sf = new SequenceFeature("mature_transcript", "", 20000, 20500, 0f,
null);
assertFalse(testee.retainFeature(sf, accId));
- sf = new SequenceFeature("NMD_transcript_variant", "", 20000, 20500,
- 0f, null);
+ sf = new SequenceFeature("NMD_transcript_variant", "", 20000, 20500, 0f,
+ null);
assertFalse(testee.retainFeature(sf, accId));
// other feature with no parent is kept
JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
}
- private static final Object[][] allSeqs = new Object[][] {
- {
- new EnsemblProtein(),
- "CCDS5863.1",
- ">CCDS5863.1\n"
- + "MAALSGGGGGGAEPGQALFNGDMEPEAGAGAGAAASSAADPAIPEEVWNIKQMIKLTQEH\n"
- + "IEALLDKFGGEHNPPSIYLEAYEEYTSKLDALQQREQQLLESLGNGTDFSVSSSASMDTV\n"
- + "TSSSSSSLSVLPSSLSVFQNPTDVARSNPKSPQKPIVRVFLPNKQRTVVPARCGVTVRDS\n"
- + "LKKALMMRGLIPECCAVYRIQDGEKKPIGWDTDISWLTGEELHVEVLENVPLTTHNFVRK\n"
- + "TFFTLAFCDFCRKLLFQGFRCQTCGYKFHQRCSTEVPLMCVNYDQLDLLFVSKFFEHHPI\n"
- + "PQEEASLAETALTSGSSPSAPASDSIGPQILTSPSPSKSIPIPQPFRPADEDHRNQFGQR\n"
- + "DRSSSAPNVHINTIEPVNIDDLIRDQGFRGDGGSTTGLSATPPASLPGSLTNVKALQKSP\n"
- + "GPQRERKSSSSSEDRNRMKTLGRRDSSDDWEIPDGQITVGQRIGSGSFGTVYKGKWHGDV\n"
- + "AVKMLNVTAPTPQQLQAFKNEVGVLRKTRHVNILLFMGYSTKPQLAIVTQWCEGSSLYHH\n"
- + "LHIIETKFEMIKLIDIARQTAQGMDYLHAKSIIHRDLKSNNIFLHEDLTVKIGDFGLATV\n"
- + "KSRWSGSHQFEQLSGSILWMAPEVIRMQDKNPYSFQSDVYAFGIVLYELMTGQLPYSNIN\n"
- + "NRDQIIFMVGRGYLSPDLSKVRSNCPKAMKRLMAECLKKKRDERPLFPQILASIELLARS\n"
- + "LPKIHRSASEPSLNRAGFQTEDFSLYACASPKTPIQAGGYGAFPVH\n" },
- {
- new EnsemblCdna(),
- "CCDS5863.1",
- ">CCDS5863.1\n"
- + "ATGGCGGCGCTGAGCGGTGGCGGTGGTGGCGGCGCGGAGCCGGGCCAGGCTCTGTTCAAC\n"
- + "GGGGACATGGAGCCCGAGGCCGGCGCCGGCGCCGGCGCCGCGGCCTCTTCGGCTGCGGAC\n"
- + "CCTGCCATTCCGGAGGAGGTGTGGAATATCAAACAAATGATTAAGTTGACACAGGAACAT\n"
- + "ATAGAGGCCCTATTGGACAAATTTGGTGGGGAGCATAATCCACCATCAATATATCTGGAG\n"
- + "GCCTATGAAGAATACACCAGCAAGCTAGATGCACTCCAACAAAGAGAACAACAGTTATTG\n"
- + "GAATCTCTGGGGAACGGAACTGATTTTTCTGTTTCTAGCTCTGCATCAATGGATACCGTT\n"
- + "ACATCTTCTTCCTCTTCTAGCCTTTCAGTGCTACCTTCATCTCTTTCAGTTTTTCAAAAT\n"
- + "CCCACAGATGTGGCACGGAGCAACCCCAAGTCACCACAAAAACCTATCGTTAGAGTCTTC\n"
- + "CTGCCCAACAAACAGAGGACAGTGGTACCTGCAAGGTGTGGAGTTACAGTCCGAGACAGT\n"
- + "CTAAAGAAAGCACTGATGATGAGAGGTCTAATCCCAGAGTGCTGTGCTGTTTACAGAATT\n"
- + "CAGGATGGAGAGAAGAAACCAATTGGTTGGGACACTGATATTTCCTGGCTTACTGGAGAA\n"
- + "GAATTGCATGTGGAAGTGTTGGAGAATGTTCCACTTACAACACACAACTTTGTACGAAAA\n"
- + "ACGTTTTTCACCTTAGCATTTTGTGACTTTTGTCGAAAGCTGCTTTTCCAGGGTTTCCGC\n"
- + "TGTCAAACATGTGGTTATAAATTTCACCAGCGTTGTAGTACAGAAGTTCCACTGATGTGT\n"
- + "GTTAATTATGACCAACTTGATTTGCTGTTTGTCTCCAAGTTCTTTGAACACCACCCAATA\n"
- + "CCACAGGAAGAGGCGTCCTTAGCAGAGACTGCCCTAACATCTGGATCATCCCCTTCCGCA\n"
- + "CCCGCCTCGGACTCTATTGGGCCCCAAATTCTCACCAGTCCGTCTCCTTCAAAATCCATT\n"
- + "CCAATTCCACAGCCCTTCCGACCAGCAGATGAAGATCATCGAAATCAATTTGGGCAACGA\n"
- + "GACCGATCCTCATCAGCTCCCAATGTGCATATAAACACAATAGAACCTGTCAATATTGAT\n"
- + "GACTTGATTAGAGACCAAGGATTTCGTGGTGATGGAGGATCAACCACAGGTTTGTCTGCT\n"
- + "ACCCCCCCTGCCTCATTACCTGGCTCACTAACTAACGTGAAAGCCTTACAGAAATCTCCA\n"
- + "GGACCTCAGCGAGAAAGGAAGTCATCTTCATCCTCAGAAGACAGGAATCGAATGAAAACA\n"
- + "CTTGGTAGACGGGACTCGAGTGATGATTGGGAGATTCCTGATGGGCAGATTACAGTGGGA\n"
- + "CAAAGAATTGGATCTGGATCATTTGGAACAGTCTACAAGGGAAAGTGGCATGGTGATGTG\n"
- + "GCAGTGAAAATGTTGAATGTGACAGCACCTACACCTCAGCAGTTACAAGCCTTCAAAAAT\n"
- + "GAAGTAGGAGTACTCAGGAAAACACGACATGTGAATATCCTACTCTTCATGGGCTATTCC\n"
- + "ACAAAGCCACAACTGGCTATTGTTACCCAGTGGTGTGAGGGCTCCAGCTTGTATCACCAT\n"
- + "CTCCATATCATTGAGACCAAATTTGAGATGATCAAACTTATAGATATTGCACGACAGACT\n"
- + "GCACAGGGCATGGATTACTTACACGCCAAGTCAATCATCCACAGAGACCTCAAGAGTAAT\n"
- + "AATATATTTCTTCATGAAGACCTCACAGTAAAAATAGGTGATTTTGGTCTAGCTACAGTG\n"
- + "AAATCTCGATGGAGTGGGTCCCATCAGTTTGAACAGTTGTCTGGATCCATTTTGTGGATG\n"
- + "GCACCAGAAGTCATCAGAATGCAAGATAAAAATCCATACAGCTTTCAGTCAGATGTATAT\n"
- + "GCATTTGGAATTGTTCTGTATGAATTGATGACTGGACAGTTACCTTATTCAAACATCAAC\n"
- + "AACAGGGACCAGATAATTTTTATGGTGGGACGAGGATACCTGTCTCCAGATCTCAGTAAG\n"
- + "GTACGGAGTAACTGTCCAAAAGCCATGAAGAGATTAATGGCAGAGTGCCTCAAAAAGAAA\n"
- + "AGAGATGAGAGACCACTCTTTCCCCAAATTCTCGCCTCTATTGAGCTGCTGGCCCGCTCA\n"
- + "TTGCCAAAAATTCACCGCAGTGCATCAGAACCCTCCTTGAATCGGGCTGGTTTCCAAACA\n"
- + "GAGGATTTTAGTCTATATGCTTGTGCTTCTCCAAAAACACCCATCCAGGCAGGGGGATAT\n"
- + "GGTGCGTTTCCTGTCCACTGA\n" },
- {
- new EnsemblProtein(),
- "ENSP00000288602",
- ">ENSP00000288602\n"
- + "MAALSGGGGGGAEPGQALFNGDMEPEAGAGAGAAASSAADPAIPEEVWNIKQMIKLTQEH\n"
- + "IEALLDKFGGEHNPPSIYLEAYEEYTSKLDALQQREQQLLESLGNGTDFSVSSSASMDTV\n"
- + "TSSSSSSLSVLPSSLSVFQNPTDVARSNPKSPQKPIVRVFLPNKQRTVVPARCGVTVRDS\n"
- + "LKKALMMRGLIPECCAVYRIQDGEKKPIGWDTDISWLTGEELHVEVLENVPLTTHNFVRK\n"
- + "TFFTLAFCDFCRKLLFQGFRCQTCGYKFHQRCSTEVPLMCVNYDQLDLLFVSKFFEHHPI\n"
- + "PQEEASLAETALTSGSSPSAPASDSIGPQILTSPSPSKSIPIPQPFRPADEDHRNQFGQR\n"
- + "DRSSSAPNVHINTIEPVNIDDLIRDQGFRGDG\n"
- // ? insertion added in ENSP00000288602.11, not in P15056
- + "APLNQLMRCLRKYQSRTPSPLLHSVPSEIVFDFEPGPVFR\n"
- // end insertion
- + "GSTTGLSATPPASLPGSLTNVKALQKSP\n"
- + "GPQRERKSSSSSEDRNRMKTLGRRDSSDDWEIPDGQITVGQRIGSGSFGTVYKGKWHGDV\n"
- + "AVKMLNVTAPTPQQLQAFKNEVGVLRKTRHVNILLFMGYSTKPQLAIVTQWCEGSSLYHH\n"
- + "LHIIETKFEMIKLIDIARQTAQGMDYLHAKSIIHRDLKSNNIFLHEDLTVKIGDFGLATV\n"
- + "KSRWSGSHQFEQLSGSILWMAPEVIRMQDKNPYSFQSDVYAFGIVLYELMTGQLPYSNIN\n"
- + "NRDQIIFMVGRGYLSPDLSKVRSNCPKAMKRLMAECLKKKRDERPLFPQILASIELLARS\n"
- + "LPKIHRSASEPSLNRAGFQTEDFSLYACASPKTPIQAGGYGAFPVH" } };
+ private static final Object[][] allSeqs = new Object[][] { {
+ new EnsemblProtein(), "CCDS5863.1",
+ ">CCDS5863.1\n"
+ + "MAALSGGGGGGAEPGQALFNGDMEPEAGAGAGAAASSAADPAIPEEVWNIKQMIKLTQEH\n"
+ + "IEALLDKFGGEHNPPSIYLEAYEEYTSKLDALQQREQQLLESLGNGTDFSVSSSASMDTV\n"
+ + "TSSSSSSLSVLPSSLSVFQNPTDVARSNPKSPQKPIVRVFLPNKQRTVVPARCGVTVRDS\n"
+ + "LKKALMMRGLIPECCAVYRIQDGEKKPIGWDTDISWLTGEELHVEVLENVPLTTHNFVRK\n"
+ + "TFFTLAFCDFCRKLLFQGFRCQTCGYKFHQRCSTEVPLMCVNYDQLDLLFVSKFFEHHPI\n"
+ + "PQEEASLAETALTSGSSPSAPASDSIGPQILTSPSPSKSIPIPQPFRPADEDHRNQFGQR\n"
+ + "DRSSSAPNVHINTIEPVNIDDLIRDQGFRGDGGSTTGLSATPPASLPGSLTNVKALQKSP\n"
+ + "GPQRERKSSSSSEDRNRMKTLGRRDSSDDWEIPDGQITVGQRIGSGSFGTVYKGKWHGDV\n"
+ + "AVKMLNVTAPTPQQLQAFKNEVGVLRKTRHVNILLFMGYSTKPQLAIVTQWCEGSSLYHH\n"
+ + "LHIIETKFEMIKLIDIARQTAQGMDYLHAKSIIHRDLKSNNIFLHEDLTVKIGDFGLATV\n"
+ + "KSRWSGSHQFEQLSGSILWMAPEVIRMQDKNPYSFQSDVYAFGIVLYELMTGQLPYSNIN\n"
+ + "NRDQIIFMVGRGYLSPDLSKVRSNCPKAMKRLMAECLKKKRDERPLFPQILASIELLARS\n"
+ + "LPKIHRSASEPSLNRAGFQTEDFSLYACASPKTPIQAGGYGAFPVH\n" },
+ { new EnsemblCdna(), "CCDS5863.1", ">CCDS5863.1\n"
+ + "ATGGCGGCGCTGAGCGGTGGCGGTGGTGGCGGCGCGGAGCCGGGCCAGGCTCTGTTCAAC\n"
+ + "GGGGACATGGAGCCCGAGGCCGGCGCCGGCGCCGGCGCCGCGGCCTCTTCGGCTGCGGAC\n"
+ + "CCTGCCATTCCGGAGGAGGTGTGGAATATCAAACAAATGATTAAGTTGACACAGGAACAT\n"
+ + "ATAGAGGCCCTATTGGACAAATTTGGTGGGGAGCATAATCCACCATCAATATATCTGGAG\n"
+ + "GCCTATGAAGAATACACCAGCAAGCTAGATGCACTCCAACAAAGAGAACAACAGTTATTG\n"
+ + "GAATCTCTGGGGAACGGAACTGATTTTTCTGTTTCTAGCTCTGCATCAATGGATACCGTT\n"
+ + "ACATCTTCTTCCTCTTCTAGCCTTTCAGTGCTACCTTCATCTCTTTCAGTTTTTCAAAAT\n"
+ + "CCCACAGATGTGGCACGGAGCAACCCCAAGTCACCACAAAAACCTATCGTTAGAGTCTTC\n"
+ + "CTGCCCAACAAACAGAGGACAGTGGTACCTGCAAGGTGTGGAGTTACAGTCCGAGACAGT\n"
+ + "CTAAAGAAAGCACTGATGATGAGAGGTCTAATCCCAGAGTGCTGTGCTGTTTACAGAATT\n"
+ + "CAGGATGGAGAGAAGAAACCAATTGGTTGGGACACTGATATTTCCTGGCTTACTGGAGAA\n"
+ + "GAATTGCATGTGGAAGTGTTGGAGAATGTTCCACTTACAACACACAACTTTGTACGAAAA\n"
+ + "ACGTTTTTCACCTTAGCATTTTGTGACTTTTGTCGAAAGCTGCTTTTCCAGGGTTTCCGC\n"
+ + "TGTCAAACATGTGGTTATAAATTTCACCAGCGTTGTAGTACAGAAGTTCCACTGATGTGT\n"
+ + "GTTAATTATGACCAACTTGATTTGCTGTTTGTCTCCAAGTTCTTTGAACACCACCCAATA\n"
+ + "CCACAGGAAGAGGCGTCCTTAGCAGAGACTGCCCTAACATCTGGATCATCCCCTTCCGCA\n"
+ + "CCCGCCTCGGACTCTATTGGGCCCCAAATTCTCACCAGTCCGTCTCCTTCAAAATCCATT\n"
+ + "CCAATTCCACAGCCCTTCCGACCAGCAGATGAAGATCATCGAAATCAATTTGGGCAACGA\n"
+ + "GACCGATCCTCATCAGCTCCCAATGTGCATATAAACACAATAGAACCTGTCAATATTGAT\n"
+ + "GACTTGATTAGAGACCAAGGATTTCGTGGTGATGGAGGATCAACCACAGGTTTGTCTGCT\n"
+ + "ACCCCCCCTGCCTCATTACCTGGCTCACTAACTAACGTGAAAGCCTTACAGAAATCTCCA\n"
+ + "GGACCTCAGCGAGAAAGGAAGTCATCTTCATCCTCAGAAGACAGGAATCGAATGAAAACA\n"
+ + "CTTGGTAGACGGGACTCGAGTGATGATTGGGAGATTCCTGATGGGCAGATTACAGTGGGA\n"
+ + "CAAAGAATTGGATCTGGATCATTTGGAACAGTCTACAAGGGAAAGTGGCATGGTGATGTG\n"
+ + "GCAGTGAAAATGTTGAATGTGACAGCACCTACACCTCAGCAGTTACAAGCCTTCAAAAAT\n"
+ + "GAAGTAGGAGTACTCAGGAAAACACGACATGTGAATATCCTACTCTTCATGGGCTATTCC\n"
+ + "ACAAAGCCACAACTGGCTATTGTTACCCAGTGGTGTGAGGGCTCCAGCTTGTATCACCAT\n"
+ + "CTCCATATCATTGAGACCAAATTTGAGATGATCAAACTTATAGATATTGCACGACAGACT\n"
+ + "GCACAGGGCATGGATTACTTACACGCCAAGTCAATCATCCACAGAGACCTCAAGAGTAAT\n"
+ + "AATATATTTCTTCATGAAGACCTCACAGTAAAAATAGGTGATTTTGGTCTAGCTACAGTG\n"
+ + "AAATCTCGATGGAGTGGGTCCCATCAGTTTGAACAGTTGTCTGGATCCATTTTGTGGATG\n"
+ + "GCACCAGAAGTCATCAGAATGCAAGATAAAAATCCATACAGCTTTCAGTCAGATGTATAT\n"
+ + "GCATTTGGAATTGTTCTGTATGAATTGATGACTGGACAGTTACCTTATTCAAACATCAAC\n"
+ + "AACAGGGACCAGATAATTTTTATGGTGGGACGAGGATACCTGTCTCCAGATCTCAGTAAG\n"
+ + "GTACGGAGTAACTGTCCAAAAGCCATGAAGAGATTAATGGCAGAGTGCCTCAAAAAGAAA\n"
+ + "AGAGATGAGAGACCACTCTTTCCCCAAATTCTCGCCTCTATTGAGCTGCTGGCCCGCTCA\n"
+ + "TTGCCAAAAATTCACCGCAGTGCATCAGAACCCTCCTTGAATCGGGCTGGTTTCCAAACA\n"
+ + "GAGGATTTTAGTCTATATGCTTGTGCTTCTCCAAAAACACCCATCCAGGCAGGGGGATAT\n"
+ + "GGTGCGTTTCCTGTCCACTGA\n" },
+ { new EnsemblProtein(), "ENSP00000288602", ">ENSP00000288602\n"
+ + "MAALSGGGGGGAEPGQALFNGDMEPEAGAGAGAAASSAADPAIPEEVWNIKQMIKLTQEH\n"
+ + "IEALLDKFGGEHNPPSIYLEAYEEYTSKLDALQQREQQLLESLGNGTDFSVSSSASMDTV\n"
+ + "TSSSSSSLSVLPSSLSVFQNPTDVARSNPKSPQKPIVRVFLPNKQRTVVPARCGVTVRDS\n"
+ + "LKKALMMRGLIPECCAVYRIQDGEKKPIGWDTDISWLTGEELHVEVLENVPLTTHNFVRK\n"
+ + "TFFTLAFCDFCRKLLFQGFRCQTCGYKFHQRCSTEVPLMCVNYDQLDLLFVSKFFEHHPI\n"
+ + "PQEEASLAETALTSGSSPSAPASDSIGPQILTSPSPSKSIPIPQPFRPADEDHRNQFGQR\n"
+ + "DRSSSAPNVHINTIEPVNIDDLIRDQGFRGDG\n"
+ // ? insertion added in ENSP00000288602.11, not in P15056
+ + "APLNQLMRCLRKYQSRTPSPLLHSVPSEIVFDFEPGPVFR\n"
+ // end insertion
+ + "GSTTGLSATPPASLPGSLTNVKALQKSP\n"
+ + "GPQRERKSSSSSEDRNRMKTLGRRDSSDDWEIPDGQITVGQRIGSGSFGTVYKGKWHGDV\n"
+ + "AVKMLNVTAPTPQQLQAFKNEVGVLRKTRHVNILLFMGYSTKPQLAIVTQWCEGSSLYHH\n"
+ + "LHIIETKFEMIKLIDIARQTAQGMDYLHAKSIIHRDLKSNNIFLHEDLTVKIGDFGLATV\n"
+ + "KSRWSGSHQFEQLSGSILWMAPEVIRMQDKNPYSFQSDVYAFGIVLYELMTGQLPYSNIN\n"
+ + "NRDQIIFMVGRGYLSPDLSKVRSNCPKAMKRLMAECLKKKRDERPLFPQILASIELLARS\n"
+ + "LPKIHRSASEPSLNRAGFQTEDFSLYACASPKTPIQAGGYGAFPVH" } };
@BeforeClass(alwaysRun = true)
public void setUp()
{
- SequenceOntologyFactory.setInstance(new SequenceOntologyLite());
+ SequenceOntologyFactory.setSequenceOntology(new SequenceOntologyLite());
}
@AfterClass(alwaysRun = true)
public void tearDown()
{
- SequenceOntologyFactory.setInstance(null);
+ SequenceOntologyFactory.setSequenceOntology(null);
}
@DataProvider(name = "ens_seqs")
for (SequenceI tr : expected)
{
SequenceI[] rseq;
- Assert.assertNotNull(
- rseq = retrieved.findSequenceMatch(tr.getName()),
+ Assert.assertNotNull(rseq = retrieved.findSequenceMatch(tr.getName()),
"Couldn't find sequences matching expected sequence "
+ tr.getName());
Assert.assertEquals(rseq.length, 1,
"Expected only one sequence for sequence ID " + tr.getName());
- Assert.assertEquals(
- rseq[0].getSequenceAsString(),
+ Assert.assertEquals(rseq[0].getSequenceAsString(),
tr.getSequenceAsString(),
"Sequences differ for " + tr.getName() + "\n" + "Exp:"
+ tr.getSequenceAsString() + "\n" + "Got:"
public void testReverseComplementAlleles()
{
String alleles = "C,G,-TAC,HGMD_MUTATION,gac";
- SequenceFeature sf = new SequenceFeature("sequence_variant", alleles,
- 1, 2, 0f, null);
+ SequenceFeature sf = new SequenceFeature("sequence_variant", alleles, 1,
+ 2, 0f, null);
sf.setValue("alleles", alleles);
EnsemblSeqProxy.reverseComplementAlleles(sf);
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
+
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.ColumnSelection;
import jalview.schemes.JalviewColourScheme;
import jalview.structure.AtomSpecModel;
import jalview.structure.StructureCommandI;
+ import jalview.structure.StructureCommandsI.AtomSpecType;
import jalview.structure.StructureMapping;
import jalview.structure.StructureSelectionManager;
-
public class JmolCommandsTest
{
private JmolCommands testee;
SequenceRenderer sr = new SequenceRenderer(af.getViewport());
SequenceI[][] seqs = new SequenceI[][] { { seq1 }, { seq2 } };
String[] files = new String[] { "seq1.pdb", "seq2.pdb" };
-- StructureSelectionManager ssm = new StructureSelectionManager();
++ StructureSelectionManager ssm = StructureSelectionManager.getStructureSelectionManager(null);
+
/*
* map residues 1-10 to residues 21-30 (atoms 105-150) in structures
*/
StructureMapping sm2 = new StructureMapping(seq2, "seq2.pdb", "pdb2",
"B", map, null);
ssm.addStructureMapping(sm2);
- String[] commands = testee.colourBySequence(ssm,
- files,
- seqs, sr, af.alignPanel);
+
++ // TODO - comments in testee suggest this tests an obsolete method!
+ String[] commands = testee.colourBySequence(ssm, files, seqs, sr,
+ af.alignPanel);
assertEquals(commands.length, 2);
- assertEquals(commands[0].commands.length, 1); // from 2.12 merge from 2.11.2
String chainACommand = commands[0];
// M colour is #82827d == (130, 130, 125) (see strand.html help page)
public void testGetAtomSpec()
{
AtomSpecModel model = new AtomSpecModel();
- assertEquals(testee.getAtomSpec(model, false), "");
+ assertEquals(testee.getAtomSpec(model, AtomSpecType.RESIDUE_ONLY), "");
model.addRange("1", 2, 4, "A");
- assertEquals(testee.getAtomSpec(model, false), "2-4:A/1.1");
+ assertEquals(testee.getAtomSpec(model, AtomSpecType.RESIDUE_ONLY),
+ "2-4:A/1.1");
model.addRange("1", 8, 8, "A");
- assertEquals(testee.getAtomSpec(model, false), "2-4:A/1.1|8:A/1.1");
+ assertEquals(testee.getAtomSpec(model, AtomSpecType.RESIDUE_ONLY),
+ "2-4:A/1.1|8:A/1.1");
model.addRange("1", 5, 7, "B");
- assertEquals(testee.getAtomSpec(model, false),
+ assertEquals(testee.getAtomSpec(model, AtomSpecType.RESIDUE_ONLY),
"2-4:A/1.1|8:A/1.1|5-7:B/1.1");
model.addRange("1", 3, 5, "A");
- assertEquals(testee.getAtomSpec(model, false),
+ assertEquals(testee.getAtomSpec(model, AtomSpecType.RESIDUE_ONLY),
"2-5:A/1.1|8:A/1.1|5-7:B/1.1");
model.addRange("2", 1, 4, "B");
- assertEquals(testee.getAtomSpec(model, false),
+ assertEquals(testee.getAtomSpec(model, AtomSpecType.RESIDUE_ONLY),
"2-5:A/1.1|8:A/1.1|5-7:B/1.1|1-4:B/2.1");
model.addRange("2", 5, 9, "C");
- assertEquals(testee.getAtomSpec(model, false),
+ assertEquals(testee.getAtomSpec(model, AtomSpecType.RESIDUE_ONLY),
"2-5:A/1.1|8:A/1.1|5-7:B/1.1|1-4:B/2.1|5-9:C/2.1");
model.addRange("1", 8, 10, "B");
- assertEquals(testee.getAtomSpec(model, false),
+ assertEquals(testee.getAtomSpec(model, AtomSpecType.RESIDUE_ONLY),
"2-5:A/1.1|8:A/1.1|5-10:B/1.1|1-4:B/2.1|5-9:C/2.1");
model.addRange("1", 8, 9, "B");
- assertEquals(testee.getAtomSpec(model, false),
+ assertEquals(testee.getAtomSpec(model, AtomSpecType.RESIDUE_ONLY),
"2-5:A/1.1|8:A/1.1|5-10:B/1.1|1-4:B/2.1|5-9:C/2.1");
model.addRange("2", 3, 10, "C"); // subsumes 5-9
- assertEquals(testee.getAtomSpec(model, false),
+ assertEquals(testee.getAtomSpec(model, AtomSpecType.RESIDUE_ONLY),
"2-5:A/1.1|8:A/1.1|5-10:B/1.1|1-4:B/2.1|3-10:C/2.1");
model.addRange("5", 25, 35, " ");
- assertEquals(testee.getAtomSpec(model, false),
+ assertEquals(testee.getAtomSpec(model, AtomSpecType.RESIDUE_ONLY),
"2-5:A/1.1|8:A/1.1|5-10:B/1.1|1-4:B/2.1|3-10:C/2.1|25-35:/5.1");
}
toAlign.addRange("2", 20, 21, "B");
toAlign.addRange("2", 22, 22, "C");
List<StructureCommandI> command = testee.superposeStructures(ref,
- toAlign);
+ toAlign, AtomSpecType.ALPHA); // doesn't matter for Jmol whether nuc
+ // or protein
assertEquals(command.size(), 1);
String refSpec = "12-14:A/1.1|18:B/1.1|22-23:B/1.1";
String toAlignSpec = "15-17:B/2.1|20-21:B/2.1|22:C/2.1";
public void setUp()
{
Cache.loadProperties("test/jalview/io/testProps.jvprops");
- Cache.applicationProperties.setProperty("STRUCT_FROM_PDB",
+ Cache.setPropertyNoSave("STRUCT_FROM_PDB",
Boolean.TRUE.toString());
- Cache.applicationProperties.setProperty("ADD_TEMPFACT_ANN",
+ Cache.setPropertyNoSave("ADD_TEMPFACT_ANN",
Boolean.FALSE.toString());
- Cache.applicationProperties.setProperty("ADD_SS_ANN",
+ Cache.setPropertyNoSave("ADD_SS_ANN",
Boolean.TRUE.toString());
StructureImportSettings.setDefaultStructureFileFormat("PDB");
StructureImportSettings
/*
* local structures have a fake ID
*/
- assertTrue(structureData.getSeqs().get(0).getAllPDBEntries().get(0).fakedPDBId());
+ assertTrue(structureData.getSeqs().get(0).getAllPDBEntries().get(0)
+ .fakedPDBId());
/*
* the ID is also the group for features derived from structure data
*/
@BeforeClass(alwaysRun = true)
public static void setUpBeforeClass() throws Exception
{
- Jalview.main(new String[] { "-noquestionnaire", "-nonews", "-props",
- "test/jalview/ext/rbvi/chimera/testProps.jvprops" });
+ Jalview.main(
+ new String[]
+ { "-noquestionnaire", "-nonews", "-props",
+ "test/jalview/ext/rbvi/chimera/testProps.jvprops" });
Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
ViewerType.CHIMERA.name());
Cache.setProperty("SHOW_ANNOTATIONS", "false");
@AfterClass(alwaysRun = true)
public static void tearDownAfterClass() throws Exception
{
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
}
@AfterMethod(alwaysRun = true)
assertEquals(pdbIds.size(), 1);
PDBEntry pdbEntry = pdbIds.get(0);
assertEquals(pdbEntry.getId(), "1GAQ");
- StructureViewer structureViewer = new StructureViewer(af.getViewport()
- .getStructureSelectionManager());
+ StructureViewer structureViewer = new StructureViewer(
+ af.getViewport().getStructureSelectionManager());
chimeraViewer = structureViewer.viewStructures(pdbEntry,
- new SequenceI[] { sq }, af.getCurrentView().getAlignPanel());
+ new SequenceI[]
+ { sq }, af.getCurrentView().getAlignPanel());
JalviewChimeraBinding binding = (JalviewChimeraBinding) chimeraViewer
.getBinding();
} catch (InterruptedException e)
{
}
- } while (!binding.isFinishedInit() || !chimeraViewer.isVisible());
+ } while (!binding.isFinishedInit() || !chimeraViewer.isVisible());
assertTrue(binding.isViewerRunning(), "Failed to start Chimera");
assertTrue(chimeraViewer.hasViewerActionsMenu());
// now add another sequence and bind to view
- //
+ //
AlignmentI al = af.getViewport().getAlignment();
PDBEntry xpdb = al.getSequenceAt(0).getPDBEntry("1GAQ");
- sq = new Sequence("1GAQ", al.getSequenceAt(0).getSequence(25, 95).toString());
+ sq = new Sequence("1GAQ",
+ al.getSequenceAt(0).getSequence(25, 95).toString());
al.addSequence(sq);
- structureViewer.viewStructures(new PDBEntry[] { xpdb }, new SequenceI[] { sq }, af.getCurrentView().getAlignPanel());
+ structureViewer.viewStructures(new PDBEntry[] { xpdb },
+ new SequenceI[]
+ { sq }, af.getCurrentView().getAlignPanel());
/*
* Wait for viewer load thread to complete
*/
- do
+ do
{
- try {
+ try
+ {
Thread.sleep(1500);
- } catch (InterruptedException q) {};
+ } catch (InterruptedException q)
+ {
+ }
+ ;
} while (!binding.isLoadingFinished());
-
+
// still just one PDB structure shown
assertEquals(chimeraViewer.getBinding().getPdbCount(), 1);
// and the viewer action menu should still be visible
/*
* use local test PDB and SIFTS files
*/
- String pdbFilePath = new File(
- "test/jalview/ext/rbvi/chimera/4zho.pdb").getPath();
+ String pdbFilePath = new File("test/jalview/ext/rbvi/chimera/4zho.pdb")
+ .getPath();
PDBEntry pdbEntry = new PDBEntry("4ZHO", null, null, pdbFilePath);
String siftsFilePath = new File(
- "test/jalview/ext/rbvi/chimera/4zho.xml.gz")
- .getPath();
+ "test/jalview/ext/rbvi/chimera/4zho.xml.gz").getPath();
SiftsClient.setMockSiftsFile(new File(siftsFilePath));
- StructureViewer structureViewer = new StructureViewer(af.getViewport()
- .getStructureSelectionManager());
+ StructureViewer structureViewer = new StructureViewer(
+ af.getViewport().getStructureSelectionManager());
chimeraViewer = structureViewer.viewStructures(pdbEntry,
- new SequenceI[] { sq }, af.getCurrentView().getAlignPanel());
+ new SequenceI[]
+ { sq }, af.getCurrentView().getAlignPanel());
JalviewChimeraBinding binding = (JalviewChimeraBinding) chimeraViewer
.getBinding();
sq.addSequenceFeature(new SequenceFeature("metal ion-binding site",
"Iron-Sulfur (2Fe-2S)", 96, 96, Float.NaN, null));
// on a sequence region that is partially mapped to structure:
- sq.addSequenceFeature(new SequenceFeature("helix", null, 50, 60,
- Float.NaN, null));
+ sq.addSequenceFeature(
+ new SequenceFeature("helix", null, 50, 60, Float.NaN, null));
// and again:
- sq.addSequenceFeature(new SequenceFeature("chain", null, 50, 70,
- Float.NaN, null));
+ sq.addSequenceFeature(
+ new SequenceFeature("chain", null, 50, 70, Float.NaN, null));
// add numeric valued features - score is set as attribute value
sq.addSequenceFeature(new SequenceFeature("kd", "hydrophobicity", 62,
62, -2.1f, null));
new StructureCommand("list resi att jv_metal_ion_binding_site"),
true);
assertEquals(reply.size(), 4);
- assertTrue(reply
- .contains("residue id #0:40.A jv_metal_ion_binding_site \"Iron-Sulfur (2Fe-2S)\" index 40"));
- assertTrue(reply
- .contains("residue id #0:45.A jv_metal_ion_binding_site \"Iron-Sulfur (2Fe-2S)\" index 45"));
- assertTrue(reply
- .contains("residue id #0:40.B jv_metal_ion_binding_site \"Iron-Sulfur (2Fe-2S)\" index 40"));
- assertTrue(reply
- .contains("residue id #0:45.B jv_metal_ion_binding_site \"Iron-Sulfur (2Fe-2S)\" index 45"));
+ assertTrue(reply.contains(
+ "residue id #0:40.A jv_metal_ion_binding_site \"Iron-Sulfur (2Fe-2S)\" index 40"));
+ assertTrue(reply.contains(
+ "residue id #0:45.A jv_metal_ion_binding_site \"Iron-Sulfur (2Fe-2S)\" index 45"));
+ assertTrue(reply.contains(
+ "residue id #0:40.B jv_metal_ion_binding_site \"Iron-Sulfur (2Fe-2S)\" index 40"));
+ assertTrue(reply.contains(
+ "residue id #0:45.B jv_metal_ion_binding_site \"Iron-Sulfur (2Fe-2S)\" index 45"));
/*
* check attributes with score values
SequenceI fer2Arath = af.getViewport().getAlignment()
.findName("FER2_ARATH");
assertNotNull(fer2Arath, "Didn't find FER2_ARATH");
-
+
/*
* need a Uniprot dbref for SIFTS mapping to work!!
*/
fer2Arath.addDBRef(new DBRefEntry("UNIPROT", "0", "P16972", null));
-
+
/*
* use local test PDB and SIFTS files
*/
- String pdbFilePath = new File(
- "test/jalview/ext/rbvi/chimera/4zho.pdb").getPath();
+ String pdbFilePath = new File("test/jalview/ext/rbvi/chimera/4zho.pdb")
+ .getPath();
PDBEntry pdbEntry = new PDBEntry("4ZHO", null, null, pdbFilePath);
String siftsFilePath = new File(
- "test/jalview/ext/rbvi/chimera/4zho.xml.gz")
- .getPath();
+ "test/jalview/ext/rbvi/chimera/4zho.xml.gz").getPath();
SiftsClient.setMockSiftsFile(new File(siftsFilePath));
-
- StructureViewer structureViewer = new StructureViewer(af.getViewport()
- .getStructureSelectionManager());
+
+ StructureViewer structureViewer = new StructureViewer(
+ af.getViewport().getStructureSelectionManager());
chimeraViewer = structureViewer.viewStructures(pdbEntry,
- new SequenceI[] { fer2Arath }, af.getCurrentView()
- .getAlignPanel());
-
+ new SequenceI[]
+ { fer2Arath }, af.getCurrentView().getAlignPanel());
+
JalviewChimeraBinding binding = (JalviewChimeraBinding) chimeraViewer
.getBinding();
do
{
}
} while (!binding.isFinishedInit());
-
+
assertTrue(binding.isViewerRunning(), "Failed to launch Chimera");
-
+
assertEquals(binding.getPdbCount(), 1);
-
+
/*
* 'perform' menu action to copy Chimera attributes
* to features in Jalview
*/
// TODO rename and pull up method to binding interface
// once functionality is added for Jmol as well
- binding.copyStructureAttributesToFeatures("isHelix", af.getViewport()
- .getAlignPanel());
+ binding.copyStructureAttributesToFeatures("isHelix",
+ af.getViewport().getAlignPanel());
/*
* verify 22 residues have isHelix feature
/*
* fetch a numeric valued attribute
*/
- binding.copyStructureAttributesToFeatures("phi", af.getViewport()
- .getAlignPanel());
+ binding.copyStructureAttributesToFeatures("phi",
+ af.getViewport().getAlignPanel());
fr.setVisible("phi");
List<SequenceFeature> fs = fer2Arath.getFeatures().findFeatures(54, 54,
"phi");
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
-import jalview.gui.JvOptionPane;
-
-import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
+import jalview.gui.JvOptionPane;
import junit.extensions.PA;
public class PDBFTSPanelTest
{
PDBFTSPanel searchPanel = new PDBFTSPanel(null);
JInternalFrame mainFrame = searchPanel.getMainFrame();
- // JComboBox<String> txt_search = PA.gsearchPanel.getTxtSearch();
+ // JComboBox<String> txt_search = PA.gsearchPanel.getTxtSearch();
assertTrue(mainFrame.getTitle().length() == 20);
- assertTrue(mainFrame.getTitle()
- .equalsIgnoreCase("PDB Sequence Fetcher"));
- PA.invokeMethod(PA.getValue(searchPanel, "txt_search"), "setSelectedItem(java.lang.String)", "ABC");
- // txt_search.setSelectedItem("ABC");
+ assertTrue(
+ mainFrame.getTitle().equalsIgnoreCase("PDB Sequence Fetcher"));
+ PA.invokeMethod(PA.getValue(searchPanel, "txt_search"),
+ "setSelectedItem(java.lang.String)", "ABC");
+ // txt_search.setSelectedItem("ABC");
try
{
// wait for web-service to handle response
e.printStackTrace();
}
assertTrue(mainFrame.getTitle().length() > 20);
- assertTrue(!mainFrame.getTitle().equalsIgnoreCase(
- "PDB Sequence Fetcher"));
+ assertTrue(
+ !mainFrame.getTitle().equalsIgnoreCase("PDB Sequence Fetcher"));
}
-
+
@Test
- public void getFTSframeTitleTest() {
+ public void getFTSframeTitleTest()
+ {
PDBFTSPanel searchPanel = new PDBFTSPanel(null);
String outcome = searchPanel.getFTSFrameTitle();
- //System.out.println("FTS Frame title :" + outcome);
+ // System.out.println("FTS Frame title :" + outcome);
assertEquals(outcome, "PDB Sequence Fetcher");
}
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
+import jalview.api.AlignViewportI;
import jalview.api.FeatureColourI;
import jalview.bin.Cache;
import jalview.bin.Jalview;
import jalview.schemes.StrandColourScheme;
import jalview.schemes.TurnColourScheme;
import jalview.util.MessageManager;
+import jalview.viewmodel.AlignmentViewport;
public class AlignFrameTest
{
@AfterMethod(alwaysRun = true)
public void tearDown()
{
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
}
/**
- * configure (read-only) properties for test to ensure Consensus is computed for
- * colour Above PID testing
+ * configure (read-only) properties for test to ensure Consensus is computed
+ * for colour Above PID testing
*/
@BeforeMethod(alwaysRun = true)
public void setUp()
{
Cache.loadProperties("test/jalview/io/testProps.jvprops");
- Cache.applicationProperties.setProperty("SHOW_IDENTITY",
+ Cache.setPropertyNoSave("SHOW_IDENTITY",
Boolean.TRUE.toString());
af = new FileLoader().LoadFileWaitTillLoaded("examples/uniref50.fa",
DataSourceType.FILE);
{
SequenceI seq1 = new Sequence("Seq1", "ABCDEFGHIJ");
SequenceI seq2 = new Sequence("Seq2", "ABCDEFGHIJ");
- seq1.addSequenceFeature(new SequenceFeature("Metal", "", 1, 5, 0f, null));
- seq2.addSequenceFeature(new SequenceFeature("Metal", "", 6, 10, 10f,
- null));
- seq1.addSequenceFeature(new SequenceFeature("Turn", "", 2, 4,
- Float.NaN, null));
- seq2.addSequenceFeature(new SequenceFeature("Turn", "", 7, 9,
- Float.NaN, null));
+ seq1.addSequenceFeature(
+ new SequenceFeature("Metal", "", 1, 5, 0f, null));
+ seq2.addSequenceFeature(
+ new SequenceFeature("Metal", "", 6, 10, 10f, null));
+ seq1.addSequenceFeature(
+ new SequenceFeature("Turn", "", 2, 4, Float.NaN, null));
+ seq2.addSequenceFeature(
+ new SequenceFeature("Turn", "", 7, 9, Float.NaN, null));
AlignmentI al = new Alignment(new SequenceI[] { seq1, seq2 });
AlignFrame alignFrame = new AlignFrame(al, al.getWidth(),
al.getHeight());
assertEquals(alignFrame.getViewport().getAlignment().getHiddenColumns()
.getNumberOfRegions(), 0);
-
/*
* threshold Metal to hide features where score < 5
* seq1 feature in columns 1-5 is hidden
fc.setThreshold(5f);
alignFrame.getFeatureRenderer().setColour("Metal", fc);
assertTrue(alignFrame.hideFeatureColumns("Metal", true));
- HiddenColumns hidden = alignFrame.getViewport().getAlignment().getHiddenColumns();
+ HiddenColumns hidden = alignFrame.getViewport().getAlignment()
+ .getHiddenColumns();
assertEquals(hidden.getNumberOfRegions(), 1);
Iterator<int[]> regions = hidden.iterator();
int[] next = regions.next();
*/
alignFrame.getViewport().showAllHiddenColumns();
assertTrue(alignFrame.hideFeatureColumns("Turn", true));
- regions = alignFrame.getViewport().getAlignment()
- .getHiddenColumns().iterator();
+ regions = alignFrame.getViewport().getAlignment().getHiddenColumns()
+ .iterator();
assertEquals(alignFrame.getViewport().getAlignment().getHiddenColumns()
.getNumberOfRegions(), 2);
next = regions.next();
* <ul>
* <li>with Apply Colour to All Groups not selected, does not change group
* colours</li>
- * <li>with Apply Colour to All Groups selected, does change group colours</li>
+ * <li>with Apply Colour to All Groups selected, does change group
+ * colours</li>
* <li>in neither case, changes alignment or group colour thresholds (PID or
* Conservation)</li>
* </ul>
@Test(groups = "Functional")
public void testChangeColour_background_groupsAndThresholds()
{
- AlignViewport av = af.getViewport();
+ AlignViewportI av = af.getViewport();
AlignmentI al = av.getAlignment();
/*
af.conservationMenuItem_actionPerformed(true);
SliderPanel sp = SliderPanel.getSliderPanel();
assertEquals(sp.getTitle(), MessageManager.formatMessage(
- "label.conservation_colour_increment",
- new String[] { "Background" }));
+ "label.conservation_colour_increment", new String[]
+ { "Background" }));
assertTrue(sp.isForConservation());
sp.valueChanged(20);
assertTrue(av.getResidueShading().conservationApplied());
sp = SliderPanel.getSliderPanel();
assertFalse(sp.isForConservation());
assertEquals(sp.getTitle(), MessageManager.formatMessage(
- "label.percentage_identity_threshold",
- new String[] { "Background" }));
+ "label.percentage_identity_threshold", new String[]
+ { "Background" }));
sp.valueChanged(10);
assertEquals(av.getResidueShading().getThreshold(), 10);
assertTrue(av.getResidueShading().conservationApplied());
*/
PopupMenu popupMenu = new PopupMenu(af.alignPanel, al.getSequenceAt(2),
null);
- popupMenu.changeColour_actionPerformed(JalviewColourScheme.Strand
- .toString());
+ popupMenu.changeColour_actionPerformed(
+ JalviewColourScheme.Strand.toString());
assertTrue(sg.getColourScheme() instanceof StrandColourScheme);
assertEquals(al.getGroups().size(), 1);
assertSame(al.getGroups().get(0), sg);
sp = SliderPanel.getSliderPanel();
assertTrue(sp.isForConservation());
assertEquals(sp.getTitle(), MessageManager.formatMessage(
- "label.conservation_colour_increment",
- new String[] { sg.getName() }));
+ "label.conservation_colour_increment", new String[]
+ { sg.getName() }));
sp.valueChanged(30);
assertTrue(sg.getGroupColourScheme().conservationApplied());
assertEquals(sg.getGroupColourScheme().getConservationInc(), 30);
sp = SliderPanel.getSliderPanel();
assertFalse(sp.isForConservation());
assertEquals(sp.getTitle(), MessageManager.formatMessage(
- "label.percentage_identity_threshold",
- new String[] { sg.getName() }));
+ "label.percentage_identity_threshold", new String[]
+ { sg.getName() }));
sp.valueChanged(40);
assertEquals(sg.getGroupColourScheme().getThreshold(), 40);
// conservation threshold is unchanged:
@Test(groups = "Functional")
public void testColourThresholdActions()
{
- AlignViewport av = af.getViewport();
+ AlignViewportI av = af.getViewport();
AlignmentI al = av.getAlignment();
/*
@Test(groups = "Functional")
public void testNewView_colourThresholds()
{
- AlignViewport av = af.getViewport();
+ AlignViewportI av = af.getViewport();
AlignmentI al = av.getAlignment();
/*
av.setSelectionGroup(sg);
PopupMenu popupMenu = new PopupMenu(af.alignPanel, al.getSequenceAt(0),
null);
- popupMenu.changeColour_actionPerformed(JalviewColourScheme.Strand
- .toString());
+ popupMenu.changeColour_actionPerformed(
+ JalviewColourScheme.Strand.toString());
assertTrue(sg.getColourScheme() instanceof StrandColourScheme);
assertEquals(al.getGroups().size(), 1);
assertSame(al.getGroups().get(0), sg);
sp = SliderPanel.getSliderPanel();
assertTrue(sp.isForConservation());
assertEquals(sp.getTitle(), MessageManager.formatMessage(
- "label.conservation_colour_increment",
- new String[] { "Background" }));
+ "label.conservation_colour_increment", new String[]
+ { "Background" }));
/*
* make a new View, verify alignment and group colour schemes
*/
af.newView_actionPerformed(null);
assertEquals(af.alignPanel.getViewName(), "View 1");
- AlignViewport av2 = af.getViewport();
+ AlignmentViewport av2 = af.getViewport();
assertNotSame(av, av2);
assertSame(av2, af.alignPanel.av);
rs = av2.getResidueShading();
sp = SliderPanel.getSliderPanel();
assertTrue(sp.isForConservation());
assertEquals(sp.getTitle(), MessageManager.formatMessage(
- "label.conservation_colour_increment",
- new String[] { "View 1" }));
+ "label.conservation_colour_increment", new String[]
+ { "View 1" }));
sp.valueChanged(22);
assertEquals(av2.getResidueShading().getConservationInc(), 22);
}
import static org.testng.AssertJUnit.assertSame;
import static org.testng.AssertJUnit.assertTrue;
+import jalview.api.AlignViewportI;
import java.util.ArrayList;
import java.util.List;
import jalview.schemes.PIDColourScheme;
import jalview.structure.StructureSelectionManager;
import jalview.util.MapList;
+import jalview.viewmodel.AlignmentViewport;
import jalview.viewmodel.ViewportRanges;
public class AlignViewportTest
AlignmentI al;
- AlignViewport testee;
+ AlignmentViewport testee;
@BeforeClass(alwaysRun = true)
public static void setUpBeforeClass() throws Exception
{
- Jalview.main(new String[] {
- //"-jabaws", "none",
- "-nonews", "-props",
- "test/jalview/testProps.jvprops" });
+ Jalview.main(
+ new String[]
+ { "-nonews", "-props", "test/jalview/testProps.jvprops" });
/*
* remove any sequence mappings left lying around by other tests
*/
StructureSelectionManager ssm = StructureSelectionManager
- .getStructureSelectionManager(Desktop.instance);
+ .getStructureSelectionManager(Desktop.getInstance());
ssm.resetAll();
}
/*
* alignment with reference to mappings
*/
- AlignFrame af1 = new FileLoader()
- .LoadFileWaitTillLoaded(">Seq1\nCAGT\n", DataSourceType.PASTE);
+ AlignFrame af1 = new FileLoader().LoadFileWaitTillLoaded(
+ ">Seq1\nCAGT\n", DataSourceType.PASTE);
SequenceI s1 = af1.getViewport().getAlignment().getSequenceAt(0);
AlignedCodonFrame acf1 = new AlignedCodonFrame();
- acf1.addMap(s1, s1,
- new MapList(new int[]
- { 1, 4 }, new int[] { 1, 4 }, 1, 1));
+ acf1.addMap(s1, s1, new MapList(new int[] { 1, 4 }, new int[] { 1, 4 },
+ 1, 1));
AlignedCodonFrame acf2 = new AlignedCodonFrame();
- acf2.addMap(s1, s1,
- new MapList(new int[]
- { 1, 4 }, new int[] { 4, 1 }, 1, 1));
+ acf2.addMap(s1, s1, new MapList(new int[] { 1, 4 }, new int[] { 4, 1 },
+ 1, 1));
List<AlignedCodonFrame> mappings = new ArrayList<>();
mappings.add(acf1);
* mappings
*/
StructureSelectionManager ssm = StructureSelectionManager
- .getStructureSelectionManager(Desktop.instance);
+ .getStructureSelectionManager(Desktop.getInstance());
List<AlignedCodonFrame> sequenceMappings = ssm.getSequenceMappings();
assertEquals(2, sequenceMappings.size());
assertTrue(sequenceMappings.contains(acf1));
@Test(groups = { "Functional" })
public void testDeregisterMapping_withNoReference()
{
- Desktop d = Desktop.instance;
+ Desktop d = Desktop.getInstance();
assertNotNull(d);
StructureSelectionManager ssm = StructureSelectionManager
- .getStructureSelectionManager(Desktop.instance);
+ .getStructureSelectionManager(Desktop.getInstance());
ssm.resetAll();
- AlignFrame af1 = new FileLoader()
- .LoadFileWaitTillLoaded(">Seq1\nRSVQ\n", DataSourceType.PASTE);
- AlignFrame af2 = new FileLoader()
- .LoadFileWaitTillLoaded(">Seq2\nDGEL\n", DataSourceType.PASTE);
+ AlignFrame af1 = new FileLoader().LoadFileWaitTillLoaded(
+ ">Seq1\nRSVQ\n", DataSourceType.PASTE);
+ AlignFrame af2 = new FileLoader().LoadFileWaitTillLoaded(
+ ">Seq2\nDGEL\n", DataSourceType.PASTE);
SequenceI cs1 = new Sequence("cseq1", "CCCGGGTTTAAA");
SequenceI cs2 = new Sequence("cseq2", "CTTGAGTCTAGA");
SequenceI s1 = af1.getViewport().getAlignment().getSequenceAt(0);
SequenceI s2 = af2.getViewport().getAlignment().getSequenceAt(0);
// need to be distinct
AlignedCodonFrame acf1 = new AlignedCodonFrame();
- acf1.addMap(cs1, s1,
- new MapList(new int[]
- { 1, 4 }, new int[] { 1, 12 }, 1, 3));
+ acf1.addMap(cs1, s1, new MapList(new int[] { 1, 4 },
+ new int[] { 1, 12 }, 1, 3));
AlignedCodonFrame acf2 = new AlignedCodonFrame();
- acf2.addMap(cs2, s2,
- new MapList(new int[]
- { 1, 4 }, new int[] { 1, 12 }, 1, 3));
+ acf2.addMap(cs2, s2, new MapList(new int[] { 1, 4 },
+ new int[] { 1, 12 }, 1, 3));
AlignedCodonFrame acf3 = new AlignedCodonFrame();
- acf3.addMap(cs2, cs2,
- new MapList(new int[]
- { 1, 12 }, new int[] { 1, 12 }, 1, 1));
+ acf3.addMap(cs2, cs2, new MapList(new int[] { 1, 12 }, new int[] { 1,
+ 12 }, 1, 1));
List<AlignedCodonFrame> mappings1 = new ArrayList<>();
mappings1.add(acf1);
@Test(groups = { "Functional" })
public void testDeregisterMapping_withReference()
{
- Desktop d = Desktop.instance;
+ Desktop d = Desktop.getInstance();
assertNotNull(d);
StructureSelectionManager ssm = StructureSelectionManager
- .getStructureSelectionManager(Desktop.instance);
+ .getStructureSelectionManager(Desktop.getInstance());
ssm.resetAll();
- AlignFrame af1 = new FileLoader()
- .LoadFileWaitTillLoaded(">Seq1\nRSVQ\n", DataSourceType.PASTE);
- AlignFrame af2 = new FileLoader()
- .LoadFileWaitTillLoaded(">Seq2\nDGEL\n", DataSourceType.PASTE);
+ AlignFrame af1 = new FileLoader().LoadFileWaitTillLoaded(
+ ">Seq1\nRSVQ\n", DataSourceType.PASTE);
+ AlignFrame af2 = new FileLoader().LoadFileWaitTillLoaded(
+ ">Seq2\nDGEL\n", DataSourceType.PASTE);
SequenceI cs1 = new Sequence("cseq1", "CCCGGGTTTAAA");
SequenceI cs2 = new Sequence("cseq2", "CTTGAGTCTAGA");
SequenceI s1 = af1.getViewport().getAlignment().getSequenceAt(0);
SequenceI s2 = af2.getViewport().getAlignment().getSequenceAt(0);
// need to be distinct
AlignedCodonFrame acf1 = new AlignedCodonFrame();
- acf1.addMap(cs1, s1,
- new MapList(new int[]
- { 1, 4 }, new int[] { 1, 12 }, 1, 3));
+ acf1.addMap(cs1, s1, new MapList(new int[] { 1, 4 },
+ new int[] { 1, 12 }, 1, 3));
AlignedCodonFrame acf2 = new AlignedCodonFrame();
- acf2.addMap(cs2, s2,
- new MapList(new int[]
- { 1, 4 }, new int[] { 1, 12 }, 1, 3));
+ acf2.addMap(cs2, s2, new MapList(new int[] { 1, 4 },
+ new int[] { 1, 12 }, 1, 3));
AlignedCodonFrame acf3 = new AlignedCodonFrame();
- acf3.addMap(cs2, cs2,
- new MapList(new int[]
- { 1, 12 }, new int[] { 1, 12 }, 1, 1));
+ acf3.addMap(cs2, cs2, new MapList(new int[] { 1, 12 }, new int[] { 1,
+ 12 }, 1, 1));
List<AlignedCodonFrame> mappings1 = new ArrayList<>();
mappings1.add(acf1);
* Test for JAL-1306 - conservation thread should run even when only Quality
* (and not Conservation) is enabled in Preferences
*/
- @Test(groups = { "Functional" }, timeOut = 2000)
+ @Test(groups = { "Functional" }, timeOut=2000)
public void testUpdateConservation_qualityOnly()
{
- Cache.applicationProperties.setProperty("SHOW_ANNOTATIONS",
+ Cache.setPropertyNoSave("SHOW_ANNOTATIONS",
Boolean.TRUE.toString());
- Cache.applicationProperties.setProperty("SHOW_QUALITY",
+ Cache.setPropertyNoSave("SHOW_QUALITY",
Boolean.TRUE.toString());
- Cache.applicationProperties.setProperty("SHOW_CONSERVATION",
+ Cache.setPropertyNoSave("SHOW_CONSERVATION",
Boolean.FALSE.toString());
- Cache.applicationProperties.setProperty("SHOW_OCCUPANCY",
+ Cache.setPropertyNoSave("SHOW_OCCUPANCY",
Boolean.FALSE.toString());
- Cache.applicationProperties.setProperty("SHOW_IDENTITY",
+ Cache.setPropertyNoSave("SHOW_IDENTITY",
Boolean.FALSE.toString());
AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
"examples/uniref50.fa", DataSourceType.FILE);
{
synchronized (this)
{
- do
+ System.out.print("waiting...");
+ int n = 3;
+ while (--n >= 0 || viewport.getCalcManager().isWorking())
{
try
{
} catch (InterruptedException e)
{
}
- } while (viewport.getCalcManager().isWorking());
+ }
+ System.out.println("...done");
}
}
/*
* test for JAL-2283: don't inadvertently turn on colour by conservation
*/
- Cache.applicationProperties.setProperty("DEFAULT_COLOUR_PROT", "None");
- Cache.applicationProperties.setProperty("SHOW_CONSERVATION",
+ Cache.setPropertyNoSave("DEFAULT_COLOUR_PROT", "None");
+ Cache.setPropertyNoSave("SHOW_CONSERVATION",
Boolean.TRUE.toString());
AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
"examples/uniref50.fa", DataSourceType.FILE);
ColourSchemeI cs = new PIDColourScheme();
AlignViewport viewport = af.getViewport();
viewport.setGlobalColourScheme(cs);
- assertFalse(viewport.getResidueShading().conservationApplied());
+ assertFalse(viewport.getResidueShading()
+ .conservationApplied());
/*
* JAL-3201 groups have their own ColourSchemeI instances
{
AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
"examples/uniref50.fa", DataSourceType.FILE);
- AlignViewport av = af.getViewport();
+ AlignViewportI av = af.getViewport();
SequenceGroup sg1 = new SequenceGroup();
SequenceGroup sg2 = new SequenceGroup();
SequenceGroup sg3 = new SequenceGroup();
av.setSelectionGroup(sg3);
assertTrue(sg3.isDefined()); // unchanged
}
-
/**
- * Verify that setting/clearing SHOW_OCCUPANCY preference adds or omits
- * occupancy row from viewport
+ * Verify that setting/clearing SHOW_OCCUPANCY preference adds or omits occupancy row from viewport
*/
@Test(groups = { "Functional" })
public void testShowOrDontShowOccupancy()
{
// disable occupancy
- jalview.bin.Cache.setProperty("SHOW_OCCUPANCY",
- Boolean.FALSE.toString());
+ jalview.bin.Cache.setProperty("SHOW_OCCUPANCY", Boolean.FALSE.toString());
AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
"examples/uniref50.fa", DataSourceType.FILE);
- AlignViewport av = af.getViewport();
+ AlignViewportI av = af.getViewport();
Assert.assertNull(av.getAlignmentGapAnnotation(),
"Preference did not disable occupancy row.");
int c = 0;
c++;
}
Assert.assertEquals(c, 0, "Expected zero occupancy rows.");
-
+
// enable occupancy
- jalview.bin.Cache.setProperty("SHOW_OCCUPANCY",
- Boolean.TRUE.toString());
- af = new FileLoader().LoadFileWaitTillLoaded("examples/uniref50.fa",
- DataSourceType.FILE);
+ jalview.bin.Cache.setProperty("SHOW_OCCUPANCY", Boolean.TRUE.toString());
+ af = new FileLoader().LoadFileWaitTillLoaded(
+ "examples/uniref50.fa", DataSourceType.FILE);
av = af.getViewport();
Assert.assertNotNull(av.getAlignmentGapAnnotation(),
"Preference did not enable occupancy row.");
AlignViewport testme = af.getViewport();
waitForCalculations(testme);
SequenceI cons = testme.getConsensusSeq();
- String s = cons.getSequenceAsString();
- System.out.println("s is " + s);
-
- assertEquals("A-C", s);
+ assertEquals("A-C", cons.getSequenceAsString());
}
@Test(groups = { "Functional" })
/*
* hide first and third sequences
*/
- testee.hideSequence(new SequenceI[] { al.getSequenceAt(0),
- al.getSequenceAt(2) });
+ testee.hideSequence(
+ new SequenceI[]
+ { al.getSequenceAt(0), al.getSequenceAt(2) });
assertEquals(1, al.getHeight());
assertEquals(0, ranges.getStartSeq());
assertEquals(0, ranges.getEndSeq());
import jalview.datamodel.SequenceI;
import jalview.io.DataSourceType;
import jalview.io.FileLoader;
+import jalview.util.Platform;
import jalview.viewmodel.ViewportRanges;
public class AlignmentPanelTest
@BeforeMethod(alwaysRun = true)
public void setUp() throws InvocationTargetException, InterruptedException
{
- Jalview.main(
- new String[]
- { "-nonews", "-props", "test/jalview/testProps.jvprops" });
+ Jalview.main(new String[] { "-nonews",
+ "-props", "test/jalview/testProps.jvprops",
+ "-jabaws", "none"});
- Cache.applicationProperties.setProperty("SHOW_IDENTITY",
+ Cache.setPropertyNoSave("SHOW_IDENTITY",
Boolean.TRUE.toString());
af = new FileLoader().LoadFileWaitTillLoaded("examples/uniref50.fa",
DataSourceType.FILE);
-
+
/*
* ensure the panel has been repainted and so ViewportRanges set
*/
- SwingUtilities.invokeAndWait(new Runnable() {
- @Override
- public void run() {
- af.repaint();
- }});
+ SwingUtilities.invokeAndWait(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ af.repaint();
+ }
+ });
/*
* wait for Consensus thread to complete
af.alignPanel.setScrollValues(-1, 5);
// setting -ve x value does not change residue
+ // no update necessary now
assertEquals(ranges.getEndRes(), oldres);
af.alignPanel.setScrollValues(0, 5);
+
+ // no update necessary now
// setting 0 as x value does not change residue
+ // no update necessary now
assertEquals(ranges.getEndRes(), oldres);
af.alignPanel.setScrollValues(5, 5);
// setting x value to 5 extends endRes by 5 residues
+ System.out.println(ranges);
+ // no update necessary now
assertEquals(ranges.getEndRes(), oldres + 5);
// scroll to position after hidden columns sets endres to oldres (width) +
// position
-
- int scrollpos = 60;
+ int scrollpos = 53; // was 60, but this is too high to allow full scrolling
+ // in Windows
af.getViewport().hideColumns(30, 50);
af.alignPanel.setScrollValues(scrollpos, 5);
+ // no update necessary now
assertEquals(ranges.getEndRes(), oldres + scrollpos);
// scroll to position within hidden columns, still sets endres to oldres +
af.getViewport().showAllHiddenColumns();
af.getViewport().hideColumns(30, 50);
af.alignPanel.setScrollValues(scrollpos, 5);
+ // no update necessary now
assertEquals(ranges.getEndRes(), oldres + scrollpos);
// scroll to position within <width> distance of the end of the alignment
scrollpos = 130;
af.getViewport().showAllHiddenColumns();
af.alignPanel.setScrollValues(scrollpos, 5);
+ // no update necessary now
assertEquals(ranges.getEndRes(),
af.getViewport().getAlignment().getWidth() - 1);
// columns
af.getViewport().hideColumns(30, 50);
af.alignPanel.setScrollValues(scrollpos, 5);
+ // no update necessary now
assertEquals(ranges.getEndRes(),
af.getViewport().getAlignment().getWidth() - 1 - 21); // 21 is the
// number of
}
/**
- * Test the variant of calculateIdWidth that only recomputes the width if it
- * is not already saved in the viewport (initial value is -1)
+ * Test the variant of calculateIdWidth that only recomputes the width if it is
+ * not already saved in the viewport (initial value is -1)
*/
@Test(groups = "Functional")
public void testCalculateIdWidth_noArgs()
* note 4 pixels padding are added to the longest sequence name width
*/
av.setIdWidth(-1); // force recalculation
+
d = af.alignPanel.calculateIdWidth();
- assertEquals(d.width, 166); // 4 + pixel width of "Q93Z60_ARATH/1-118"
+ assertEquals(d.width, Platform.isWin() ? 172 : 166); // 4 + pixel width of "Q93Z60_ARATH/1-118"
assertEquals(d.height, 12);
assertEquals(d.width, av.getIdWidth());
}
* note 4 pixels 'padding' are added to the longest seq name/annotation label
*/
Dimension d = af.alignPanel.calculateIdWidth(2000);
- assertEquals(d.width, 166); // 4 + pixel width of "Q93Z60_ARATH/1-118"
+ assertEquals(d.width, Platform.isWin() ? 172 : 166); // 4 + pixel width of "Q93Z60_ARATH/1-118"
assertEquals(d.height, 12); // fixed value (not used?)
assertEquals(av.getIdWidth(), 18); // not changed by this method
*/
SequenceI seq = af.viewport.getAlignment()
.findSequenceMatch("Q93Z60_ARATH")[0];
- seq.setName(seq.getName() + "MMMMM");
+ String orig = seq.getName();
+ seq.setName(orig + "MMMMM");
d = af.alignPanel.calculateIdWidth(2000);
- assertEquals(d.width, 211); // 4 + pixel width of "Q93Z60_ARATHMMMMM/1-118"
+ assertEquals(d.width, Platform.isWin() ? 219 : 211); // 4 + pixel width of "Q93Z60_ARATHMMMMM/1-118"
assertEquals(d.height, 12);
assertEquals(av.getIdWidth(), 18); // unchanged
+ // for next test:
+ seq.setName(orig);
/*
* make the longest annotation name even longer
FontMetrics fmfor = af.alignPanel
.getFontMetrics(af.alignPanel.getAlabels().getFont());
// Assumption ID_WIDTH_PADDING == 4
+ // AH! But with those added MMMM above, this was NOT the longest label!
int expwidth = 4 + fmfor.stringWidth(aa.label);
d = af.alignPanel.calculateIdWidth(2000);
- assertEquals(d.width, expwidth); // 228 == ID_WIDTH_PADDING + pixel width of
- // "THIS IS A VERY LONG LABEL INDEED"
+ assertEquals(d.width, expwidth); // 191 == ID_WIDTH_PADDING + pixel width of "THIS IS A VERY LONG LABEL INDEED"
assertEquals(d.height, 12);
/*
* override with maxwidth
* note the 4 pixels padding is added to this value
*/
- d = af.alignPanel.calculateIdWidth(213);
- assertEquals(d.width, 217);
+ // BH but we have to be under the max width
+ d = af.alignPanel.calculateIdWidth(180);
+ assertEquals(d.width, 184);
assertEquals(d.height, 12);
}
*/
int w = af.alignPanel.getVisibleIdWidth(true);
assertEquals(w, af.alignPanel.getIdPanel().getWidth());
- assertEquals(w, 115);
+ assertEquals(w, Platform.isWin() ? 112 : 115);
/*
* width for offscreen rendering is the same
* preference for auto id width overrides fixed width
*/
Cache.setProperty("FIGURE_AUTOIDWIDTH", Boolean.TRUE.toString());
- assertEquals(115, af.alignPanel.getVisibleIdWidth(false));
+ assertEquals(Platform.isWin() ? 106 : 115, af.alignPanel.getVisibleIdWidth(false));
}
}
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.gui;
import static org.testng.Assert.assertEquals;
public void setUp()
{
Cache.loadProperties("test/jalview/io/testProps.jvprops");
- Cache.applicationProperties.setProperty("SHOW_ANNOTATIONS",
- Boolean.TRUE.toString());
- Cache.applicationProperties.setProperty(Preferences.SHOW_AUTOCALC_ABOVE,
+ Cache.setPropertyNoSave("SHOW_ANNOTATIONS",
Boolean.TRUE.toString());
+ Cache.setPropertyNoSave(
+ Preferences.SHOW_AUTOCALC_ABOVE, Boolean.TRUE.toString());
af = new FileLoader().LoadFileWaitTillLoaded("examples/uniref50.fa",
DataSourceType.FILE);
testee = new AnnotationRowFilter(af.viewport, af.alignPanel)
null);
ann4.setSequenceRef(seq2);
al.addAnnotation(ann4);
- AlignmentAnnotation ann5 = new AlignmentAnnotation("Jnet", "Jnet",
- null);
+ AlignmentAnnotation ann5 = new AlignmentAnnotation("Jnet", "Jnet", null);
ann5.setSequenceRef(seq2);
al.addAnnotation(ann5);
/*
* a second Jnet annotation for FER_BRANA
*/
- AlignmentAnnotation ann6 = new AlignmentAnnotation("Jnet", "Jnet",
- null);
+ AlignmentAnnotation ann6 = new AlignmentAnnotation("Jnet", "Jnet", null);
ann6.setSequenceRef(seq2);
al.addAnnotation(ann6);
* drop-down items with 'Per-sequence only' not checked
*/
Vector<String> items = testee.getAnnotationItems(false);
- assertEquals(items.toString(),
+ assertEquals(
+ items.toString(),
"[Conservation, Quality, Consensus, Occupancy, ann1Label, Significance, Significance_1, Jronn_FER_CAPAA, Jronn_FER_BRANA, Jnet_FER_BRANA, Jnet_FER_BRANA_2]");
assertEquals(testee.getAnnotationMenuLabel(ann1), "ann1Label");
assertEquals(testee.getAnnotationMenuLabel(ann2), "Significance");
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.gui;
import static org.testng.Assert.assertEquals;
{
// read-only Jalview properties
Cache.loadProperties("test/jalview/io/testProps.jvprops");
- Cache.applicationProperties.setProperty("BLOSUM62_PCA_FOR_NUCLEOTIDE",
+ Cache.setPropertyNoSave("BLOSUM62_PCA_FOR_NUCLEOTIDE",
Boolean.FALSE.toString());
}
/*
* enable inclusion of BLOSUM62 for nucleotide PCA (JAL-2962)
*/
- Cache.applicationProperties.setProperty("BLOSUM62_PCA_FOR_NUCLEOTIDE",
+ Cache.setPropertyNoSave("BLOSUM62_PCA_FOR_NUCLEOTIDE",
Boolean.TRUE.toString());
/*
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.gui;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
+
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
* maximum retained heap usage (in MB) for a passing test
*/
private static int MAX_RESIDUAL_HEAP = 45;
-
/**
* Configure (read-only) Jalview property settings for test
*/
new String[]
{ "-nonews", "-props", "test/jalview/testProps.jvprops" });
String True = Boolean.TRUE.toString();
- Cache.applicationProperties.setProperty("SHOW_ANNOTATIONS", True);
- Cache.applicationProperties.setProperty("SHOW_QUALITY", True);
- Cache.applicationProperties.setProperty("SHOW_CONSERVATION", True);
- Cache.applicationProperties.setProperty("SHOW_OCCUPANCY", True);
- Cache.applicationProperties.setProperty("SHOW_IDENTITY", True);
+ Cache.setPropertyNoSave("SHOW_ANNOTATIONS", True);
+ Cache.setPropertyNoSave("SHOW_QUALITY", True);
+ Cache.setPropertyNoSave("SHOW_CONSERVATION", True);
+ Cache.setPropertyNoSave("SHOW_OCCUPANCY", True);
+ Cache.setPropertyNoSave("SHOW_IDENTITY", True);
}
+ /**
+ * A simple test that memory is released when all windows are closed.
+ * <ul>
+ * <li>generates a reasonably large alignment and loads it</li>
+ * <li>performs various operations on the alignment</li>
+ * <li>closes all windows</li>
+ * <li>requests garbage collection</li>
+ * <li>asserts that the remaining memory footprint (heap usage) is 'not large'
+ * </li>
+ * </ul>
+ * If the test fails, this suggests that a reference to some large object
+ * (perhaps the alignment data, or some annotation / Tree / PCA data) has
+ * failed to be garbage collected. If this is the case, the heap will need to
+ * be inspected manually (suggest using jvisualvm) in order to track down
+ * where large objects are still referenced. The code (for example
+ * AlignmentViewport.dispose()) should then be updated to ensure references to
+ * large objects are set to null when they are no longer required.
+ *
+ * @throws IOException
+ */
@Test(groups = "Memory")
public void testFreeMemoryOnClose() throws IOException
{
File f = generateAlignment();
f.deleteOnExit();
+ long expectedMin = MAX_RESIDUAL_HEAP;
+ long usedMemoryAtStart=getUsedMemory();
+ if (usedMemoryAtStart>expectedMin)
+ {
+ System.err.println("used memory before test is "+usedMemoryAtStart+" > "+expectedMin+"MB .. adjusting minimum.");
+ expectedMin = usedMemoryAtStart;
+ }
doStuffInJalview(f);
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
- checkUsedMemory(MAX_RESIDUAL_HEAP);
+ checkUsedMemory(expectedMin);
}
/**
long availableMemory = Runtime.getRuntime().totalMemory();
long freeMemory = Runtime.getRuntime().freeMemory();
long usedMemory = availableMemory - freeMemory;
-
return (int) (usedMemory / ONE_MB);
}
-
/**
* Requests garbage collection and then checks whether remaining memory in use
* is less than the expected value (in Megabytes)
JvSwingUtils.wrapTooltip(true, tip));
tip = "0123456789012345678901234567890123456789012345678901234567890"; // 61
-
- assertFalse(tip.equals(JvSwingUtils.wrapTooltip(false, tip)));
- assertFalse(("<html>" + tip + "</html>")
- .equals(JvSwingUtils.wrapTooltip(true, tip)));
+ // n/a -- message is too long for "false"
+//
+// assertFalse(tip.equals(JvSwingUtils.wrapTooltip(false, tip)));
+//
+
+ assertFalse(("<html>" + tip + "</html>").equals(JvSwingUtils
+ .wrapTooltip(true, tip)));
}
/**
public void testWrapTooltip_multilineShortText()
{
String tip = "Now is the winter of our discontent<br>Made glorious summer by this sun of York";
- assertEquals(tip, JvSwingUtils.wrapTooltip(false, tip));
- assertEquals("<html>" + tip + "</html>",
- JvSwingUtils.wrapTooltip(true, tip));
+ String tip2 = "Now is the winter of our discontent<br/>Made glorious summer by this sun of York";
+
+// BH not applicable in Jalview; "false" is only for when no <br> and only for short j2s2Discover messages
+//
+// String s = JvSwingUtils.wrapTooltip(false, tip);
+// System.out.println("<html>" + tip + "</html>");
+// assertEquals(tip, s);
+
+ String s;
+ s = JvSwingUtils.wrapTooltip(true, tip);
+ System.out.println(s);
+ assertEquals("<html>" + tip + "</html>", s);
+ s = JvSwingUtils.wrapTooltip(true, tip2);
+ System.out.println(s);
+ assertEquals("<html>" + tip + "</html>", s);
}
/**
@Test(groups = { "Functional" })
public void testWrapTooltip_longText()
{
+ // BH should work in Java and JavaScript
String tip = "Now is the winter of our discontent made glorious summer by this sun of York";
- String expected = "<style> div.ttip {width:350px;white-space:pre-wrap;padding:2px;overflow-wrap:break-word;}</style>"
- + "<div class=\"ttip\">" + tip + " </div>";
- assertEquals("<html>" + expected + "</html>",
- JvSwingUtils.wrapTooltip(true, tip));
- assertEquals(expected, JvSwingUtils.wrapTooltip(false, tip));
+ String expected = JvSwingUtils.HTML_PREFIX + tip + "</div></html>";
+ String s = JvSwingUtils.wrapTooltip(true, tip);
+ assertEquals(expected, s);
+ // BH not applicable in Jalview; "false" is only for when no <br> and only for short j2s2Discover messages
+// s = JvSwingUtils.wrapTooltip(false, tip);
+// assertEquals(expected, s);
}
}
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.gui;
import static org.testng.Assert.assertEquals;
+import jalview.api.AlignViewportI;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.SequenceGroup;
import jalview.io.DataSourceType;
import jalview.io.FileLoader;
-
import javax.swing.JTextArea;
-import junit.extensions.PA;
-
import org.testng.annotations.Test;
+import junit.extensions.PA;
+
public class PairwiseAlignmentPanelTest
{
@Test(groups = "Functional")
{
AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
"examples/uniref50.fa", DataSourceType.FILE);
- AlignViewport viewport = af.getViewport();
+ AlignViewportI viewport = af.getViewport();
AlignmentI al = viewport.getAlignment();
/*
PairwiseAlignPanel testee = new PairwiseAlignPanel(viewport);
- String text = ((JTextArea) PA.getValue(testee, "textarea")).getText();
+ String text = ((JTextArea) PA.getValue(testee, "textarea")).getText().replace("\r\n", "\n");
String expected = "Score = 80.0\n" + "Length of alignment = 4\n"
+ "Sequence FER1_PEA/29-32 (Sequence length = 7)\n"
+ "Sequence Q93XJ9_SOLTU/23-26 (Sequence length = 7)\n\n"
String seqs = ">Q93XJ9_SOLTU/23-29\nL-KAISNV\n>FER1_PEA/26-32\nV-TTTKAF\n";
AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(seqs,
DataSourceType.PASTE);
- AlignViewport viewport = af.getViewport();
+ AlignViewportI viewport = af.getViewport();
PairwiseAlignPanel testee = new PairwiseAlignPanel(viewport);
- String text = ((JTextArea) PA.getValue(testee, "textarea")).getText();
+ String text = ((JTextArea) PA.getValue(testee, "textarea")).getText().replace("\r\n", "\n");
String expected = "Score = 80.0\n" + "Length of alignment = 4\n"
+ "Sequence FER1_PEA/29-32 (Sequence length = 7)\n"
+ "Sequence Q93XJ9_SOLTU/23-26 (Sequence length = 7)\n\n"
import org.testng.annotations.Test;
import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.AlignmentAnnotation;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.Annotation;
public void setUp() throws IOException
{
Cache.loadProperties("test/jalview/io/testProps.jvprops");
- Cache.initLogger();
+ Console.initLogger();
String inMenuString = ("EMBL-EBI Search | http://www.ebi.ac.uk/ebisearch/search.ebi?db=allebi&query=$"
- + SEQUENCE_ID
- + "$"
- + "|"
- + "UNIPROT | http://www.uniprot.org/uniprot/$" + DB_ACCESSION + "$")
- + "|"
+ + SEQUENCE_ID + "$" + "|"
+ + "UNIPROT | http://www.uniprot.org/uniprot/$" + DB_ACCESSION
+ + "$") + "|"
+ ("INTERPRO | http://www.ebi.ac.uk/interpro/entry/$"
+ DB_ACCESSION + "$")
- + "|"
- +
+ + "|" +
// Gene3D entry tests for case (in)sensitivity
("Gene3D | http://gene3d.biochem.ucl.ac.uk/Gene3D/search?sterm=$"
+ DB_ACCESSION + "$&mode=protein");
testee.configureReferenceAnnotationsMenu(menu, seqs);
assertTrue(menu.isEnabled());
String s = MessageManager.getString("label.add_annotations_for");
- String expected = "<html><style> div.ttip {width:350px;white-space:pre-wrap;padding:2px;overflow-wrap:break-word;}</style>"
- + "<div class=\"ttip\">" + s
- + "<br/>Jmol/secondary structure<br/>PDB/Temp </div></html>";
+// String expected = "<html><style> div.ttip {width:350px;white-space:pre-wrap;padding:2px;overflow-wrap:break-word;}</style>"
+// + "<div class=\"ttip\">" + s
+// + "<br/>Jmol/secondary structure<br/>PDB/Temp </div></html>";
+ String expected = "<html>" + s + "<br>Jmol/secondary structure<br>PDB/Temp</html>";
assertEquals(expected, menu.getToolTipText());
}
testee.configureReferenceAnnotationsMenu(menu, seqs);
assertTrue(menu.isEnabled());
String s = MessageManager.getString("label.add_annotations_for");
- String expected = "<html><style> div.ttip {width:350px;white-space:pre-wrap;padding:2px;overflow-wrap:break-word;}</style>"
- + "<div class=\"ttip\">" + s
- + "<br/>Jmol/secondary structure<br/>PDB/Temp </div></html>";
- assertEquals(expected, menu.getToolTipText());
+// String expected = "<html><style> div.ttip {width:350px;white-space:pre-wrap;padding:2px;overflow-wrap:break-word;}</style>"
+// + "<div class=\"ttip\">" + s
+// + "<br/>Jmol/secondary structure<br/>PDB/Temp</html>";
+ String expected = "<html>" + s
+ + "<br>Jmol/secondary structure<br>PDB/Temp</html>";
+ s = menu.getToolTipText();
+ assertEquals(expected, s);
}
/**
// PDB.secondary structure on Sequence0
AlignmentAnnotation annotation = new AlignmentAnnotation(
"secondary structure", "", 0);
+ annotation.annotations = new Annotation[] { new Annotation(2f) };
annotation.setCalcId("PDB");
seqs.get(0).getDatasetSequence().addAlignmentAnnotation(annotation);
if (addToSequence)
// PDB.Temp on Sequence1
annotation = new AlignmentAnnotation("Temp", "", 0);
annotation.setCalcId("PDB");
+ annotation.annotations = new Annotation[] { new Annotation(2f) };
seqs.get(1).getDatasetSequence().addAlignmentAnnotation(annotation);
if (addToSequence)
{
// JMOL.secondary structure on Sequence0
annotation = new AlignmentAnnotation("secondary structure", "", 0);
annotation.setCalcId("Jmol");
+ annotation.annotations = new Annotation[] { new Annotation(2f) };
seqs.get(0).getDatasetSequence().addAlignmentAnnotation(annotation);
if (addToSequence)
{
seq0.addDBRef(new DBRefEntry("INTERPRO", "1", "IPR006058"));
seq1.addDBRef(new DBRefEntry(DBRefSource.UNIPROT, "1", "Q9ZTS2"));
seq1.addDBRef(new DBRefEntry("GENE3D", "1", "3.10.20.30"));
-
+
/*
* check the Link Menu for the first sequence
*/
JMenu linkMenu = PopupMenu.buildLinkMenu(seq0, noFeatures);
assertEquals(linkText, linkMenu.getText());
Component[] linkItems = linkMenu.getMenuComponents();
-
+
/*
* menu items are ordered: SEQUENCE_ID search first, then dbrefs in order
* of database name (and within that by order of dbref addition)
{
// get sequences from the alignment
List<SequenceI> seqs = parentPanel.getAlignment().getSequences();
-
+
// add our own seqs to avoid problems with changes to existing sequences
// (gap at end of sequences varies depending on how tests are run!)
Sequence seqGap1 = new Sequence("GappySeq",
// get the Popup Menu for 7th sequence - no insertions
testee = new PopupMenu(parentPanel, seqs.get(7), null);
testee.hideInsertions_actionPerformed(null);
-
+
HiddenColumns hidden = parentPanel.av.getAlignment().getHiddenColumns();
Iterator<int[]> it = hidden.iterator();
assertFalse(it.hasNext());
/*
* long feature descriptions are truncated to 40 characters
*/
- sf1.setDescription(
- "this is a quite extraordinarily long description");
+ sf1.setDescription("this is a quite extraordinarily long description");
testee.remove(menu); // don't create the sub-menu twice
testee.addFeatureDetails(features, seq, 10);
menu = findMenu(testee, menuText);
*/
package jalview.gui;
-import java.awt.Font;
-import java.awt.FontMetrics;
-
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
+import java.awt.Font;
+import java.awt.FontMetrics;
+
- import org.testng.annotations.BeforeMethod;
++import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
-
import jalview.bin.Cache;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.SearchResults;
import jalview.datamodel.SearchResultsI;
import jalview.io.DataSourceType;
-import jalview.io.DataSourceType;
import jalview.io.FileLoader;
+
+import jalview.util.Platform;
+import jalview.viewmodel.ViewportRanges;
import junit.extensions.PA;
public class SeqCanvasTest
{
+ @BeforeClass(alwaysRun = true)
+ public void setUp()
+ {
++ // 2.11.2 - beforeMethod setup
++ // Cache.loadProperties("test/jalview/io/testProps.jvprops");
++ //Cache.applicationProperties.setProperty("SHOW_IDENTITY",
++ // Boolean.TRUE.toString());
++ // af = new FileLoader().LoadFileWaitTillLoaded("examples/uniref50.fa",
++ // DataSourceType.FILE);
++ // /*
++ // * wait for Consensus thread to complete
++ // */
++ // do
++ // {
++ //try
++ //{
++ // Thread.sleep(50);
++ //} catch (InterruptedException x)
++ //{
++ //}
++ // } while (af.getViewport().getCalcManager().isWorking());
++
+ Cache.loadProperties(null);
- Cache.initLogger();
+ Desktop.getInstance().setVisible(false);
+ }
+
+ private AlignFrame af;
+
/**
* Test the method that computes wrapped width in residues, height of wrapped
* widths in pixels, and the number of widths visible
av.setFont(new Font("SansSerif", Font.PLAIN, 14), true);
int charHeight = av.getCharHeight();
int charWidth = av.getCharWidth();
- assertEquals(charHeight, 17);
- assertEquals(charWidth, 12);
+ assertEquals(charHeight, !Platform.isWin() ? 17 : 19);
+ assertEquals(charWidth, !Platform.isWin() ? 12 : 11);
/*
* first with scales above, left, right
av.setScaleRightWrapped(true);
FontMetrics fm = testee.getFontMetrics(av.getFont());
int labelWidth = fm.stringWidth("000") + charWidth;
- assertEquals(labelWidth, 39); // 3 x 9 + charWidth
+ assertEquals(labelWidth,
+ !Platform.isWin() ? 3 * 9 + charWidth : 3 * 8 + charWidth);
/*
* width 400 pixels leaves (400 - 2*labelWidth) for residue columns
int canvasWidth = 400;
int canvasHeight = 300;
int residueColumns = (canvasWidth - 2 * labelWidth) / charWidth;
- int wrappedWidth = testee.calculateWrappedGeometry(canvasWidth,
- canvasHeight);
+ int wrappedWidth = testee.calculateWrappedGeometry(canvasWidth, canvasHeight);
assertEquals(wrappedWidth, residueColumns);
assertEquals(PA.getValue(testee, "labelWidthWest"), labelWidth);
assertEquals(PA.getValue(testee, "labelWidthEast"), labelWidth);
assertEquals(PA.getValue(testee, "wrappedSpaceAboveAlignment"),
2 * charHeight);
- int repeatingHeight = (int) PA.getValue(testee,
- "wrappedRepeatHeightPx");
+ int repeatingHeight = (int) PA.getValue(testee, "wrappedRepeatHeightPx");
assertEquals(repeatingHeight, charHeight * (2 + al.getHeight()));
assertEquals(PA.getValue(testee, "wrappedVisibleWidths"), 1);
canvasWidth += 2;
wrappedWidth = testee.calculateWrappedGeometry(canvasWidth,
canvasHeight);
- assertEquals(wrappedWidth, 24); // 2px not enough
+ assertEquals(wrappedWidth, !Platform.isWin() ? 24 : 25); // 2px not enough
canvasWidth += 1;
wrappedWidth = testee.calculateWrappedGeometry(canvasWidth,
canvasHeight);
AlignmentI al = av.getAlignment();
assertEquals(al.getWidth(), 157);
assertEquals(al.getHeight(), 15);
-
+
av.setWrapAlignment(true);
av.getRanges().setStartEndSeq(0, 14);
av.setFont(new Font("SansSerif", Font.PLAIN, 14), true);
int charHeight = av.getCharHeight();
int charWidth = av.getCharWidth();
- assertEquals(charHeight, 17);
- assertEquals(charWidth, 12);
-
+ assertEquals(charHeight, !Platform.isWin() ? 17 : 19);
+ assertEquals(charWidth, !Platform.isWin() ? 12 : 11);
SeqCanvas testee = af.alignPanel.getSeqPanel().seqCanvas;
-
+
/*
* first with scales above, left, right
*/
av.setScaleRightWrapped(true);
FontMetrics fm = testee.getFontMetrics(av.getFont());
int labelWidth = fm.stringWidth("000") + charWidth;
- assertEquals(labelWidth, 39); // 3 x 9 + charWidth
+ assertEquals(labelWidth,
+ !Platform.isWin() ? 3 * 9 + charWidth : 3 * 8 + charWidth);
int annotationHeight = testee.getAnnotationHeight();
/*
int canvasWidth = 400;
int canvasHeight = 300;
int residueColumns = (canvasWidth - 2 * labelWidth) / charWidth;
- int wrappedWidth = testee.calculateWrappedGeometry(canvasWidth,
- canvasHeight);
+ int wrappedWidth = testee.calculateWrappedGeometry(canvasWidth, canvasHeight);
assertEquals(wrappedWidth, residueColumns);
assertEquals(PA.getValue(testee, "labelWidthWest"), labelWidth);
assertEquals(PA.getValue(testee, "labelWidthEast"), labelWidth);
assertEquals(PA.getValue(testee, "wrappedSpaceAboveAlignment"),
2 * charHeight);
- int repeatingHeight = (int) PA.getValue(testee,
- "wrappedRepeatHeightPx");
+ int repeatingHeight = (int) PA.getValue(testee, "wrappedRepeatHeightPx");
assertEquals(repeatingHeight, charHeight * (2 + al.getHeight())
+ SeqCanvas.SEQS_ANNOTATION_GAP + annotationHeight);
assertEquals(PA.getValue(testee, "wrappedVisibleWidths"), 1);
-
+
/*
* repeat height is 17 * (2 + 15) = 289 + 3 + annotationHeight = 510
* make canvas height 2 of these plus 3 charHeights
+ 2 * (annotationHeight + SeqCanvas.SEQS_ANNOTATION_GAP);
testee.calculateWrappedGeometry(canvasWidth, canvasHeight);
assertEquals(PA.getValue(testee, "wrappedVisibleWidths"), 3);
-
+
/*
* reduce canvas height by 1 pixel - should not be enough height
* to draw 3 widths
canvasHeight -= 1;
testee.calculateWrappedGeometry(canvasWidth, canvasHeight);
assertEquals(PA.getValue(testee, "wrappedVisibleWidths"), 2);
-
+
/*
* turn off scale above - can now fit in 2 and a bit widths
*/
av.setScaleAboveWrapped(false);
testee.calculateWrappedGeometry(canvasWidth, canvasHeight);
assertEquals(PA.getValue(testee, "wrappedVisibleWidths"), 3);
-
+
/*
* reduce height to enough for 2 widths and not quite a third
* i.e. two repeating heights + spacer + sequence - 1 pixel
assertEquals(repeatingHeight, charHeight * (2 + al.getHeight()));
}
@Test(groups = "Functional")
public void testClear_HighlightAndSelection()
{
+ AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
+ "examples/uniref50.fa", DataSourceType.FILE);
AlignViewport av = af.getViewport();
SearchResultsI highlight = new SearchResults();
highlight.addResult(
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
-
import jalview.api.AlignViewportI;
import jalview.bin.Cache;
import jalview.bin.Jalview;
import jalview.io.FileLoader;
import jalview.util.MessageManager;
import jalview.viewmodel.ViewportRanges;
+
+
import junit.extensions.PA;
public class SeqPanelTest
JvOptionPane.setInteractiveMode(false);
JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
}
+
@Test(groups = "Functional")
public void testSetStatusReturnsNearestResiduePosition()
{
AlignmentI visAl = alignFrame.getViewport().getAlignment();
// Test either side of gap
- assertEquals(
- alignFrame.alignPanel.getSeqPanel().setStatusMessage(
- visAl.getSequenceAt(1), 1, 1), 2);
+ assertEquals(alignFrame.alignPanel.getSeqPanel()
+ .setStatusMessage(visAl.getSequenceAt(1), 1, 1), 2);
assertEquals(((JLabel) PA.getValue(alignFrame, "statusBar")).getText(),
"Sequence 2 ID: Seq2 Residue: ALA (2)");
- assertEquals(
- alignFrame.alignPanel.getSeqPanel().setStatusMessage(
- visAl.getSequenceAt(1), 4, 1), 3);
+ assertEquals(alignFrame.alignPanel.getSeqPanel()
+ .setStatusMessage(visAl.getSequenceAt(1), 4, 1), 3);
assertEquals(((JLabel) PA.getValue(alignFrame, "statusBar")).getText(),
"Sequence 2 ID: Seq2 Residue: GLU (3)");
// no status message at a gap, returns next residue position to the right
- assertEquals(
- alignFrame.alignPanel.getSeqPanel().setStatusMessage(
- visAl.getSequenceAt(1), 2, 1), 3);
+ assertEquals(alignFrame.alignPanel.getSeqPanel()
+ .setStatusMessage(visAl.getSequenceAt(1), 2, 1), 3);
assertEquals(((JLabel) PA.getValue(alignFrame, "statusBar")).getText(),
"Sequence 2 ID: Seq2");
- assertEquals(
- alignFrame.alignPanel.getSeqPanel().setStatusMessage(
- visAl.getSequenceAt(1), 3, 1), 3);
+ assertEquals(alignFrame.alignPanel.getSeqPanel()
+ .setStatusMessage(visAl.getSequenceAt(1), 3, 1), 3);
assertEquals(((JLabel) PA.getValue(alignFrame, "statusBar")).getText(),
"Sequence 2 ID: Seq2");
}
al.getHeight());
AlignmentI visAl = alignFrame.getViewport().getAlignment();
- assertEquals(
- alignFrame.alignPanel.getSeqPanel().setStatusMessage(
- visAl.getSequenceAt(1), 1, 1), 2);
+ assertEquals(alignFrame.alignPanel.getSeqPanel()
+ .setStatusMessage(visAl.getSequenceAt(1), 1, 1), 2);
assertEquals(((JLabel) PA.getValue(alignFrame, "statusBar")).getText(),
"Sequence 2 ID: Seq2 Residue: B (2)");
}
assertNull(SeqPanel.getEditStatusMessage(edit));
SequenceI[] seqs = new SequenceI[] { new Sequence("a", "b") };
-
+
// 1 gap
edit.addEdit(edit.new Edit(Action.INSERT_GAP, seqs, 1, 1, '-'));
String expected = MessageManager.formatMessage("label.insert_gap", "1");
{
EditCommand edit = new EditCommand(); // empty
SequenceI[] seqs = new SequenceI[] { new Sequence("a", "b") };
-
+
// 1 gap inserted, balanced by 1 delete
Edit e1 = edit.new Edit(Action.INSERT_GAP, seqs, 1, 1, '-');
edit.addEdit(e1);
edit.addEdit(e2);
String expected = MessageManager.formatMessage("label.insert_gap", "1");
assertEquals(SeqPanel.getEditStatusMessage(edit), expected);
-
+
// 2 more gaps makes +3
Edit e3 = edit.new Edit(Action.INSERT_GAP, seqs, 1, 2, '-');
edit.addEdit(e3);
edit.addEdit(e4);
expected = MessageManager.formatMessage("label.insert_gaps", "3");
assertEquals(SeqPanel.getEditStatusMessage(edit), expected);
-
+
// 2 deletes makes + 1
Edit e5 = edit.new Edit(Action.DELETE_GAP, seqs, 1, 2, '-');
edit.addEdit(e5);
edit.addEdit(e6);
expected = MessageManager.formatMessage("label.insert_gap", "1");
assertEquals(SeqPanel.getEditStatusMessage(edit), expected);
-
+
// 1 more delete makes 0 - no text
Edit e7 = edit.new Edit(Action.DELETE_GAP, seqs, 1, 1, '-');
edit.addEdit(e7);
edit.addEdit(e8);
expected = MessageManager.formatMessage("label.insert_gaps", "2");
assertNull(SeqPanel.getEditStatusMessage(edit));
-
+
// 1 more delete makes 1 delete
Edit e9 = edit.new Edit(Action.DELETE_GAP, seqs, 1, 1, '-');
edit.addEdit(e9);
edit.addEdit(e10);
expected = MessageManager.formatMessage("label.delete_gap", "1");
assertEquals(SeqPanel.getEditStatusMessage(edit), expected);
-
+
// 2 more deletes makes 3 deletes
Edit e11 = edit.new Edit(Action.DELETE_GAP, seqs, 1, 2, '-');
edit.addEdit(e11);
/*
* mouse at top left of unwrapped panel
*/
- MouseEvent evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y,
- 0, 0, 0, false, 0);
+ MouseEvent evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0,
+ x, y, 0, 0, 0, false, 0);
MousePos pos = testee.findMousePosition(evt);
assertEquals(pos.column, 0);
assertEquals(pos.seqIndex, 0);
final int charHeight = av.getCharHeight();
final int charWidth = av.getCharWidth();
final int alignmentHeight = av.getAlignment().getHeight();
-
+
// sanity checks:
assertTrue(charHeight > 0);
assertTrue(charWidth > 0);
assertTrue(alignFrame.alignPanel.getSeqPanel().getWidth() > 0);
-
+
SeqPanel testee = alignFrame.alignPanel.getSeqPanel();
int x = 0;
int y = 0;
-
+
/*
* mouse at top left of wrapped panel; there is a gap of charHeight
* above the alignment
*/
- MouseEvent evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y,
- 0, 0, 0, false, 0);
+ MouseEvent evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0,
+ x, y, 0, 0, 0, false, 0);
MousePos pos = testee.findMousePosition(evt);
assertEquals(pos.column, 0);
assertEquals(pos.seqIndex, -1); // above sequences
* cursor at bottom of gap above
*/
y = charHeight - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, -1);
assertEquals(pos.annotationIndex, -1);
* cursor over top of first sequence
*/
y = charHeight;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, 0);
assertEquals(pos.annotationIndex, -1);
* cursor at bottom of first sequence
*/
y = 2 * charHeight - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, 0);
assertEquals(pos.annotationIndex, -1);
* cursor at top of second sequence
*/
y = 2 * charHeight;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, 1);
assertEquals(pos.annotationIndex, -1);
* cursor at bottom of second sequence
*/
y = 3 * charHeight - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, 1);
assertEquals(pos.annotationIndex, -1);
* cursor at bottom of last sequence
*/
y = charHeight * (1 + alignmentHeight) - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, alignmentHeight - 1);
assertEquals(pos.annotationIndex, -1);
* method reports index of nearest sequence above
*/
y += 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, alignmentHeight - 1);
assertEquals(pos.annotationIndex, -1);
* cursor still in the gap above annotations, now at the bottom of it
*/
y += SeqCanvas.SEQS_ANNOTATION_GAP - 1; // 3-1 = 2
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, alignmentHeight - 1);
assertEquals(pos.annotationIndex, -1);
* cursor at the top of the n'th annotation
*/
y += 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0,
+ 0, 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, alignmentHeight - 1);
assertEquals(pos.annotationIndex, n); // over n'th annotation
* cursor at the bottom of the n'th annotation
*/
y += annotationRows[n].height - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0,
+ 0, 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, alignmentHeight - 1);
assertEquals(pos.annotationIndex, n);
* cursor in gap between wrapped widths
*/
y += 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, -1);
assertEquals(pos.annotationIndex, -1);
* cursor at bottom of gap between wrapped widths
*/
y += charHeight - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, -1);
assertEquals(pos.annotationIndex, -1);
* cursor at top of first sequence, second wrapped width
*/
y += 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, 0);
assertEquals(pos.annotationIndex, -1);
final int charHeight = av.getCharHeight();
final int charWidth = av.getCharWidth();
final int alignmentHeight = av.getAlignment().getHeight();
-
+
// sanity checks:
assertTrue(charHeight > 0);
assertTrue(charWidth > 0);
assertTrue(alignFrame.alignPanel.getSeqPanel().getWidth() > 0);
-
+
SeqPanel testee = alignFrame.alignPanel.getSeqPanel();
int x = 0;
int y = 0;
-
+
/*
* mouse at top left of wrapped panel; there is a gap of charHeight
* above the alignment
*/
- MouseEvent evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y,
- 0, 0, 0, false, 0);
+ MouseEvent evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0,
+ x, y, 0, 0, 0, false, 0);
MousePos pos = testee.findMousePosition(evt);
assertEquals(pos.column, 0);
assertEquals(pos.seqIndex, -1); // above sequences
assertEquals(pos.annotationIndex, -1);
-
+
/*
* cursor at bottom of gap above
* two charHeights including scale panel
*/
y = 2 * charHeight - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, -1);
assertEquals(pos.annotationIndex, -1);
-
+
/*
* cursor over top of first sequence
*/
y += 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, 0);
assertEquals(pos.annotationIndex, -1);
-
+
/*
* cursor at bottom of first sequence
*/
y += charHeight - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, 0);
assertEquals(pos.annotationIndex, -1);
-
+
/*
* cursor at top of second sequence
*/
y += 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, 1);
assertEquals(pos.annotationIndex, -1);
-
+
/*
* cursor at bottom of second sequence
*/
y += charHeight - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, 1);
assertEquals(pos.annotationIndex, -1);
-
+
/*
* cursor at bottom of last sequence
* (scale + gap + sequences)
*/
y = charHeight * (2 + alignmentHeight) - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, alignmentHeight - 1);
assertEquals(pos.annotationIndex, -1);
-
+
/*
* cursor below sequences, in 3-pixel gap above annotations
*/
y += 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, alignmentHeight - 1);
assertEquals(pos.annotationIndex, -1);
-
+
/*
* cursor still in the gap above annotations, now at the bottom of it
* method reports index of nearest sequence above
*/
y += SeqCanvas.SEQS_ANNOTATION_GAP - 1; // 3-1 = 2
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, alignmentHeight - 1);
assertEquals(pos.annotationIndex, -1);
-
- AlignmentAnnotation[] annotationRows = av.getAlignment().getAlignmentAnnotation();
+
+ AlignmentAnnotation[] annotationRows = av.getAlignment()
+ .getAlignmentAnnotation();
for (int n = 0; n < annotationRows.length; n++)
{
/*
* cursor at the top of the n'th annotation
*/
y += 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0,
+ 0, 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, alignmentHeight - 1);
assertEquals(pos.annotationIndex, n); // over n'th annotation
* cursor at the bottom of the n'th annotation
*/
y += annotationRows[n].height - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0,
+ 0, 0, false, 0);
pos = testee.findMousePosition(evt);
SeqCanvas sc = testee.seqCanvas;
assertEquals(pos.seqIndex, alignmentHeight - 1,
sc.wrappedSpaceAboveAlignment));
assertEquals(pos.annotationIndex, n);
}
-
+
/*
* cursor in gap between wrapped widths
*/
y += 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, -1);
assertEquals(pos.annotationIndex, -1);
-
+
/*
* cursor at bottom of gap between wrapped widths
*/
y += charHeight - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, -1);
assertEquals(pos.annotationIndex, -1);
-
+
/*
* cursor at top of scale, second wrapped width
*/
y += 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, -1);
assertEquals(pos.annotationIndex, -1);
* cursor at bottom of scale, second wrapped width
*/
y += charHeight - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, -1);
assertEquals(pos.annotationIndex, -1);
* cursor at top of first sequence, second wrapped width
*/
y += 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, 0);
assertEquals(pos.annotationIndex, -1);
final int charHeight = av.getCharHeight();
final int charWidth = av.getCharWidth();
final int alignmentHeight = av.getAlignment().getHeight();
-
+
// sanity checks:
assertTrue(charHeight > 0);
assertTrue(charWidth > 0);
assertTrue(alignFrame.alignPanel.getSeqPanel().getWidth() > 0);
-
+
SeqPanel testee = alignFrame.alignPanel.getSeqPanel();
int x = 0;
int y = 0;
-
+
/*
* mouse at top left of wrapped panel; there is a gap of charHeight
* above the alignment
*/
- MouseEvent evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y,
- 0, 0, 0, false, 0);
+ MouseEvent evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0,
+ x, y, 0, 0, 0, false, 0);
MousePos pos = testee.findMousePosition(evt);
assertEquals(pos.column, 0);
assertEquals(pos.seqIndex, -1); // above sequences
assertEquals(pos.annotationIndex, -1);
-
+
/*
* cursor over top of first sequence
*/
y = charHeight;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, 0);
assertEquals(pos.annotationIndex, -1);
* cursor at bottom of last sequence
*/
y = charHeight * (1 + alignmentHeight) - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, alignmentHeight - 1);
assertEquals(pos.annotationIndex, -1);
-
+
/*
* cursor below sequences, at top of charHeight gap between widths
*/
y += 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, -1);
assertEquals(pos.annotationIndex, -1);
-
+
/*
* cursor below sequences, at top of charHeight gap between widths
*/
y += charHeight - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, -1);
assertEquals(pos.annotationIndex, -1);
-
+
/*
* cursor at the top of the first sequence, second width
*/
y += 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, 0);
assertEquals(pos.annotationIndex, -1);
/*
* mouse at top left of unwrapped panel
*/
- MouseEvent evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0,
- 0, 0, 0, false, 0);
+ MouseEvent evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0,
+ x, 0, 0, 0, 0, false, 0);
assertEquals(testee.findColumn(evt), 0);
-
+
/*
* not quite one charWidth across
*/
- x = charWidth-1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0,
- 0, 0, 0, false, 0);
+ x = charWidth - 1;
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0,
+ 0, false, 0);
assertEquals(testee.findColumn(evt), 0);
/*
* one charWidth across
*/
x = charWidth;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0,
+ 0, false, 0);
assertEquals(testee.findColumn(evt), 1);
/*
* two charWidths across
*/
x = 2 * charWidth;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0,
+ 0, false, 0);
assertEquals(testee.findColumn(evt), 2);
/*
* limited to last column of seqcanvas
*/
x = 20000;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0,
+ 0, false, 0);
SeqCanvas seqCanvas = alignFrame.alignPanel.getSeqPanel().seqCanvas;
int w = seqCanvas.getWidth();
// limited to number of whole columns, base 0,
alignFrame.getViewport().hideColumns(4, 9);
x = 5 * charWidth + 2;
// x is in 6th visible column, absolute column 12, or 11 base 0
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0,
+ 0, false, 0);
assertEquals(testee.findColumn(evt), 11);
}
final int charWidth = av.getCharWidth();
assertTrue(charWidth > 0); // sanity check
assertEquals(av.getRanges().getStartRes(), 0);
-
+
/*
* mouse at top left of wrapped panel, no West (left) scale
*/
- MouseEvent evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0,
- 0, 0, 0, false, 0);
+ MouseEvent evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0,
+ x, 0, 0, 0, 0, false, 0);
assertEquals(testee.findColumn(evt), 0);
-
+
/*
* not quite one charWidth across
*/
- x = charWidth-1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0,
- 0, 0, 0, false, 0);
+ x = charWidth - 1;
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0,
+ 0, false, 0);
assertEquals(testee.findColumn(evt), 0);
-
+
/*
* one charWidth across
*/
x = charWidth;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0,
+ 0, false, 0);
assertEquals(testee.findColumn(evt), 1);
/*
int labelWidth = (int) PA.getValue(seqCanvas, "labelWidthWest");
assertTrue(labelWidth > 0);
x = labelWidth - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0,
+ 0, false, 0);
assertEquals(testee.findColumn(evt), -1);
x = labelWidth;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0,
+ 0, false, 0);
assertEquals(testee.findColumn(evt), 0);
/*
int residuesWide = av.getRanges().getViewportWidth();
assertTrue(residuesWide > 0);
x = labelWidth + charWidth * residuesWide - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0,
+ 0, false, 0);
assertEquals(testee.findColumn(evt), residuesWide - 1);
/*
assertTrue(residuesWide2 > 0);
assertTrue(residuesWide2 < residuesWide); // available width reduced
x += 1; // just over left edge of scale right
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, 0, 0, 0,
+ 0, false, 0);
assertEquals(testee.findColumn(evt), -1);
-
+
// todo add startRes offset, hidden columns
}
+
@BeforeClass(alwaysRun = true)
public static void setUpBeforeClass() throws Exception
{
e.printStackTrace();
}
}
+
@Test(groups = "Functional")
public void testFindMousePosition_wrapped_scales_longSequence()
{
Cache.applicationProperties.setProperty("FONT_STYLE", "0");
// sequence of 50 bases, doubled 10 times, = 51200 bases
String dna = "ATGGCCATTGGGCCCAAATTTCCCAAAGGGTTTCCCTGAGGTCAGTCAGA";
- for (int i = 0 ; i < 10 ; i++)
+ for (int i = 0; i < 10; i++)
{
dna += dna;
}
assertEquals(dna.length(), 51200);
- AlignFrame alignFrame = new FileLoader()
- .LoadFileWaitTillLoaded(dna, DataSourceType.PASTE);
+ AlignFrame alignFrame = new FileLoader().LoadFileWaitTillLoaded(dna,
+ DataSourceType.PASTE);
SeqPanel testee = alignFrame.alignPanel.getSeqPanel();
AlignViewport av = alignFrame.getViewport();
av.setScaleAboveWrapped(true);
} catch (InterruptedException e)
{
}
-
+
final int charHeight = av.getCharHeight();
final int charWidth = av.getCharWidth();
assertEquals(charHeight, 17);
assertEquals(charWidth, 12);
-
+
FontMetrics fm = testee.getFontMetrics(av.getFont());
int labelWidth = fm.stringWidth("00000") + charWidth;
assertEquals(labelWidth, 57); // 5 x 9 + charWidth
int x = 0;
int y = 0;
-
+
/*
* mouse at top left of wrapped panel; there is a gap of 2 * charHeight
* above the alignment
*/
- MouseEvent evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y,
- 0, 0, 0, false, 0);
+ MouseEvent evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0,
+ x, y, 0, 0, 0, false, 0);
MousePos pos = testee.findMousePosition(evt);
assertEquals(pos.column, -1); // over scale left, not an alignment column
assertEquals(pos.seqIndex, -1); // above sequences
*/
y += charHeight;
x = labelWidth;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, -1);
assertEquals(pos.column, 0);
assertEquals(pos.annotationIndex, -1);
-
+
/*
* cursor over scale left of first sequence
*/
y += charHeight;
x = 0;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, 0);
assertEquals(pos.column, -1);
assertEquals(pos.annotationIndex, -1);
-
+
/*
* cursor over start of first sequence
*/
x = labelWidth;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, 0);
assertEquals(pos.column, 0);
assertEquals(pos.annotationIndex, -1);
-
+
/*
* move one character right, to bottom pixel of same row
*/
x += charWidth;
y += charHeight - 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, 0);
assertEquals(pos.column, 1);
-
+
/*
* move down one pixel - now in the no man's land between rows
*/
y += 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, -1);
assertEquals(pos.column, 1);
-
+
/*
* move down two char heights less one pixel - still in the no man's land
* (scale above + spacer line)
*/
y += (2 * charHeight - 1);
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, -1);
assertEquals(pos.column, 1);
-
+
/*
* move down one more pixel - now on the next row of the sequence
*/
y += 1;
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, 0);
assertEquals(pos.column, 1 + av.getWrappedWidth());
-
+
/*
* scroll to near the end of the sequence
*/
SearchResultsI sr = new SearchResults();
int scrollTo = dna.length() - 1000;
- sr.addResult(av.getAlignment().getSequenceAt(0), scrollTo, scrollTo);
+ sr.addResult(av.getAlignment().getSequenceAt(0), scrollTo, scrollTo);
alignFrame.alignPanel.scrollToPosition(sr);
-
+
/*
* place the mouse on the first column of the 6th sequence, and
* verify that (computed) findMousePosition matches (actual) ViewportRanges
*/
x = labelWidth;
y = 17 * charHeight; // 17 = 6 times two header rows and 5 sequence rows
- evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0, 0,
- false, 0);
+ evt = new MouseEvent(testee, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, 0,
+ 0, false, 0);
pos = testee.findMousePosition(evt);
assertEquals(pos.seqIndex, 0);
int expected = av.getRanges().getStartRes() + 5 * av.getWrappedWidth();
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertTrue;
+
import java.util.Collection;
import java.util.Vector;
JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
}
- Sequence seq,upSeq,upSeq_nocanonical;
+ Sequence seq, upSeq, upSeq_nocanonical;
@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception
pdbIds.add(dbRef);
seq.setPDBId(pdbIds);
-
+
// Uniprot sequence for 3D-Beacons mocks
- upSeq = new Sequence("P38398",
+ upSeq = new Sequence("P38398",
"MDLSALRVEEVQNVINAMQKILECPICLELIKEPVSTKCDHIFCKFCMLKLLNQKKGPSQCPLCKNDITKRS\n"
- + "LQESTRFSQLVEELLKIICAFQLDTGLEYANSYNFAKKENNSPEHLKDEVSIIQSMGYRNRAKRLLQSEPEN\n"
- + "PSLQETSLSVQLSNLGTVRTLRTKQRIQPQKTSVYIELGSDSSEDTVNKATYCSVGDQELLQITPQGTRDEI\n"
- + "SLDSAKKAACEFSETDVTNTEHHQPSNNDLNTTEKRAAERHPEKYQGSSVSNLHVEPCGTNTHASSLQHENS\n"
- + "SLLLTKDRMNVEKAEFCNKSKQPGLARSQHNRWAGSKETCNDRRTPSTEKKVDLNADPLCERKEWNKQKLPC\n"
- + "SENPRDTEDVPWITLNSSIQKVNEWFSRSDELLGSDDSHDGESESNAKVADVLDVLNEVDEYSGSSEKIDLL\n"
- + "ASDPHEALICKSERVHSKSVESNIEDKIFGKTYRKKASLPNLSHVTENLIIGAFVTEPQIIQERPLTNKLKR\n"
- + "KRRPTSGLHPEDFIKKADLAVQKTPEMINQGTNQTEQNGQVMNITNSGHENKTKGDSIQNEKNPNPIESLEK\n"
- + "ESAFKTKAEPISSSISNMELELNIHNSKAPKKNRLRRKSSTRHIHALELVVSRNLSPPNCTELQIDSCSSSE\n"
- + "EIKKKKYNQMPVRHSRNLQLMEGKEPATGAKKSNKPNEQTSKRHDSDTFPELKLTNAPGSFTKCSNTSELKE\n"
- + "FVNPSLPREEKEEKLETVKVSNNAEDPKDLMLSGERVLQTERSVESSSISLVPGTDYGTQESISLLEVSTLG\n"
- + "KAKTEPNKCVSQCAAFENPKGLIHGCSKDNRNDTEGFKYPLGHEVNHSRETSIEMEESELDAQYLQNTFKVS\n"
- + "KRQSFAPFSNPGNAEEECATFSAHSGSLKKQSPKVTFECEQKEENQGKNESNIKPVQTVNITAGFPVVGQKD\n"
- + "KPVDNAKCSIKGGSRFCLSSQFRGNETGLITPNKHGLLQNPYRIPPLFPIKSFVKTKCKKNLLEENFEEHSM\n"
- + "SPEREMGNENIPSTVSTISRNNIRENVFKEASSSNINEVGSSTNEVGSSINEIGSSDENIQAELGRNRGPKL\n"
- + "NAMLRLGVLQPEVYKQSLPGSNCKHPEIKKQEYEEVVQTVNTDFSPYLISDNLEQPMGSSHASQVCSETPDD\n"
- + "LLDDGEIKEDTSFAENDIKESSAVFSKSVQKGELSRSPSPFTHTHLAQGYRRGAKKLESSEENLSSEDEELP\n"
- + "CFQHLLFGKVNNIPSQSTRHSTVATECLSKNTEENLLSLKNSLNDCSNQVILAKASQEHHLSEETKCSASLF\n"
- + "SSQCSELEDLTANTNTQDPFLIGSSKQMRHQSESQGVGLSDKELVSDDEERGTGLEENNQEEQSMDSNLGEA\n"
- + "ASGCESETSVSEDCSGLSSQSDILTTQQRDTMQHNLIKLQQEMAELEAVLEQHGSQPSNSYPSIISDSSALE\n"
- + "DLRNPEQSTSEKAVLTSQKSSEYPISQNPEGLSADKFEVSADSSTSKNKEPGVERSSPSKCPSLDDRWYMHS\n"
- + "CSGSLQNRNYPSQEELIKVVDVEEQQLEESGPHDLTETSYLPRQDLEGTPYLESGISLFSDDPESDPSEDRA\n"
- + "PESARVGNIPSSTSALKVPQLKVAESAQSPAAAHTTDTAGYNAMEESVSREKPELTASTERVNKRMSMVVSG\n"
- + "LTPEEFMLVYKFARKHHITLTNLITEETTHVVMKTDAEFVCERTLKYFLGIAGGKWVVSYFWVTQSIKERKM\n"
- + "LNEHDFEVRGDVVNGRNHQGPKRARESQDRKIFRGLEICCYGPFTNMPTDQLEWMVQLCGASVVKELSSFTL\n"
- + "GTGVHPIVVVQPDAWTEDNGFHAIGQMCEAPVVTREWVLDSVALYQCQELDTYLIPQIPHSHY\n"
- + "", 1,
- 1863);
+ + "LQESTRFSQLVEELLKIICAFQLDTGLEYANSYNFAKKENNSPEHLKDEVSIIQSMGYRNRAKRLLQSEPEN\n"
+ + "PSLQETSLSVQLSNLGTVRTLRTKQRIQPQKTSVYIELGSDSSEDTVNKATYCSVGDQELLQITPQGTRDEI\n"
+ + "SLDSAKKAACEFSETDVTNTEHHQPSNNDLNTTEKRAAERHPEKYQGSSVSNLHVEPCGTNTHASSLQHENS\n"
+ + "SLLLTKDRMNVEKAEFCNKSKQPGLARSQHNRWAGSKETCNDRRTPSTEKKVDLNADPLCERKEWNKQKLPC\n"
+ + "SENPRDTEDVPWITLNSSIQKVNEWFSRSDELLGSDDSHDGESESNAKVADVLDVLNEVDEYSGSSEKIDLL\n"
+ + "ASDPHEALICKSERVHSKSVESNIEDKIFGKTYRKKASLPNLSHVTENLIIGAFVTEPQIIQERPLTNKLKR\n"
+ + "KRRPTSGLHPEDFIKKADLAVQKTPEMINQGTNQTEQNGQVMNITNSGHENKTKGDSIQNEKNPNPIESLEK\n"
+ + "ESAFKTKAEPISSSISNMELELNIHNSKAPKKNRLRRKSSTRHIHALELVVSRNLSPPNCTELQIDSCSSSE\n"
+ + "EIKKKKYNQMPVRHSRNLQLMEGKEPATGAKKSNKPNEQTSKRHDSDTFPELKLTNAPGSFTKCSNTSELKE\n"
+ + "FVNPSLPREEKEEKLETVKVSNNAEDPKDLMLSGERVLQTERSVESSSISLVPGTDYGTQESISLLEVSTLG\n"
+ + "KAKTEPNKCVSQCAAFENPKGLIHGCSKDNRNDTEGFKYPLGHEVNHSRETSIEMEESELDAQYLQNTFKVS\n"
+ + "KRQSFAPFSNPGNAEEECATFSAHSGSLKKQSPKVTFECEQKEENQGKNESNIKPVQTVNITAGFPVVGQKD\n"
+ + "KPVDNAKCSIKGGSRFCLSSQFRGNETGLITPNKHGLLQNPYRIPPLFPIKSFVKTKCKKNLLEENFEEHSM\n"
+ + "SPEREMGNENIPSTVSTISRNNIRENVFKEASSSNINEVGSSTNEVGSSINEIGSSDENIQAELGRNRGPKL\n"
+ + "NAMLRLGVLQPEVYKQSLPGSNCKHPEIKKQEYEEVVQTVNTDFSPYLISDNLEQPMGSSHASQVCSETPDD\n"
+ + "LLDDGEIKEDTSFAENDIKESSAVFSKSVQKGELSRSPSPFTHTHLAQGYRRGAKKLESSEENLSSEDEELP\n"
+ + "CFQHLLFGKVNNIPSQSTRHSTVATECLSKNTEENLLSLKNSLNDCSNQVILAKASQEHHLSEETKCSASLF\n"
+ + "SSQCSELEDLTANTNTQDPFLIGSSKQMRHQSESQGVGLSDKELVSDDEERGTGLEENNQEEQSMDSNLGEA\n"
+ + "ASGCESETSVSEDCSGLSSQSDILTTQQRDTMQHNLIKLQQEMAELEAVLEQHGSQPSNSYPSIISDSSALE\n"
+ + "DLRNPEQSTSEKAVLTSQKSSEYPISQNPEGLSADKFEVSADSSTSKNKEPGVERSSPSKCPSLDDRWYMHS\n"
+ + "CSGSLQNRNYPSQEELIKVVDVEEQQLEESGPHDLTETSYLPRQDLEGTPYLESGISLFSDDPESDPSEDRA\n"
+ + "PESARVGNIPSSTSALKVPQLKVAESAQSPAAAHTTDTAGYNAMEESVSREKPELTASTERVNKRMSMVVSG\n"
+ + "LTPEEFMLVYKFARKHHITLTNLITEETTHVVMKTDAEFVCERTLKYFLGIAGGKWVVSYFWVTQSIKERKM\n"
+ + "LNEHDFEVRGDVVNGRNHQGPKRARESQDRKIFRGLEICCYGPFTNMPTDQLEWMVQLCGASVVKELSSFTL\n"
+ + "GTGVHPIVVVQPDAWTEDNGFHAIGQMCEAPVVTREWVLDSVALYQCQELDTYLIPQIPHSHY\n"
+ + "",
+ 1, 1863);
upSeq.setDescription("Breast cancer type 1 susceptibility protein");
upSeq_nocanonical = new Sequence(upSeq);
upSeq.createDatasetSequence();
- upSeq.addDBRef(new DBRefEntry("UNIPROT","0","P38398",null,true));
-
+ upSeq.addDBRef(new DBRefEntry("UNIPROT", "0", "P38398", null, true));
+
upSeq_nocanonical.createDatasetSequence();
// not a canonical reference
- upSeq_nocanonical.addDBRef(
- new DBRefEntry("UNIPROT", "0", "P38398", null, false));
-
+ upSeq_nocanonical.addDBRef(new DBRefEntry("UNIPROT","0","P38398",null,false));
}
@AfterMethod(alwaysRun = true)
public void tearDown() throws Exception
{
seq = null;
- upSeq=null;
- upSeq_nocanonical=null;
+ upSeq = null;
+ upSeq_nocanonical = null;
}
@Test(groups = { "Functional" })
SequenceI[] selectedSeqs = new SequenceI[] { seq };
StructureChooser sc = new StructureChooser(selectedSeqs, seq, null);
ThreadwaitFor(200, sc);
-
+
// if structures are not discovered then don't
// populate filter options
sc.populateFilterComboBox(false, false);
int optionsSize = sc.getCmbFilterOption().getItemCount();
System.out.println("Items (no data, no cache): ");
StringBuilder items = new StringBuilder();
- for (int p=0;p<optionsSize;p++)
+ for (int p = 0; p < optionsSize; p++)
{
- items.append
- ("- ").append(sc.getCmbFilterOption().getItemAt(p).getName()).append("\n");
+ items.append("- ")
+ .append(sc.getCmbFilterOption().getItemAt(p).getName())
+ .append("\n");
}
// report items when this fails - seems to be a race condition
- Assert.assertEquals(items.toString(),optionsSize,2);
+ Assert.assertEquals(items.toString(), optionsSize, 2);
sc.populateFilterComboBox(true, false);
optionsSize = sc.getCmbFilterOption().getItemCount();
FilterOption filterOpt = (FilterOption) sc.getCmbFilterOption()
.getSelectedItem();
assertEquals("Cached Structures", filterOpt.getName());
- FTSRestClient.unMock((FTSRestClient) TDBeaconsFTSRestClient.getInstance());
+ FTSRestClient
+ .unMock((FTSRestClient) TDBeaconsFTSRestClient.getInstance());
FTSRestClient.unMock((FTSRestClient) PDBFTSRestClient.getInstance());
}
PDBFTSRestClientTest.setMock();
SequenceI[] selectedSeqs = new SequenceI[] { upSeq_nocanonical };
- StructureChooser sc = new StructureChooser(selectedSeqs, upSeq_nocanonical, null);
+ StructureChooser sc = new StructureChooser(selectedSeqs,
+ upSeq_nocanonical, null);
// mock so should be quick. Exceptions from mocked PDBFTS are expected too
ThreadwaitFor(500, sc);
-
+
assertTrue(sc.isCanQueryTDB() && sc.isNotQueriedTDBYet());
}
@Test(groups = { "Network" })
public void fetchStructuresInfoTest()
{
- FTSRestClient.unMock((FTSRestClient) TDBeaconsFTSRestClient.getInstance());
+ FTSRestClient
+ .unMock((FTSRestClient) TDBeaconsFTSRestClient.getInstance());
PDBFTSRestClient.unMock((FTSRestClient) PDBFTSRestClient.getInstance());
SequenceI[] selectedSeqs = new SequenceI[] { seq };
StructureChooser sc = new StructureChooser(selectedSeqs, seq, null);
- // not mocked, wait for 2s
+ // not mocked, wait for 2s
ThreadwaitFor(2000, sc);
-
+
sc.fetchStructuresMetaData();
Collection<FTSData> ss = (Collection<FTSData>) PA.getValue(sc,
"discoveredStructuresSet");
SequenceI[] selectedSeqs = new SequenceI[] { upSeq };
StructureChooser sc = new StructureChooser(selectedSeqs, seq, null);
ThreadwaitFor(500, sc);
-
+
sc.fetchStructuresMetaData();
Collection<FTSData> ss = (Collection<FTSData>) PA.getValue(sc,
"discoveredStructuresSet");
private void ThreadwaitFor(int i, StructureChooser sc)
{
- long timeout = i+System.currentTimeMillis();
+ long timeout = i + System.currentTimeMillis();
while (!sc.isDialogVisible() && timeout > System.currentTimeMillis())
{
- try {
+ try
+ {
Thread.sleep(50);
} catch (InterruptedException x)
{
-
+
}
}
-
-
}
-
@Test(groups = { "Functional" })
public void sanitizeSeqNameTest()
{
String name = "ab_cdEF|fwxyz012349";
- assertEquals(name, PDBStructureChooserQuerySource.sanitizeSeqName(name));
+ assertEquals(name,
+ PDBStructureChooserQuerySource.sanitizeSeqName(name));
// remove a [nn] substring
name = "abcde12[345]fg";
- assertEquals("abcde12fg", PDBStructureChooserQuerySource.sanitizeSeqName(name));
+ assertEquals("abcde12fg",
+ PDBStructureChooserQuerySource.sanitizeSeqName(name));
// remove characters other than a-zA-Z0-9 | or _
name = "ab[cd],.\t£$*!- \\\"@:e";
- assertEquals("abcde", PDBStructureChooserQuerySource.sanitizeSeqName(name));
+ assertEquals("abcde",
+ PDBStructureChooserQuerySource.sanitizeSeqName(name));
name = "abcde12[345a]fg";
- assertEquals("abcde12345afg", PDBStructureChooserQuerySource.sanitizeSeqName(name));
+ assertEquals("abcde12345afg",
+ PDBStructureChooserQuerySource.sanitizeSeqName(name));
}
}
@BeforeMethod(alwaysRun = true)
public void setup() throws Exception
{
- Cache.applicationProperties.setProperty("STRUCT_FROM_PDB",
+ Cache.setPropertyNoSave("STRUCT_FROM_PDB",
Boolean.TRUE.toString());
- Cache.applicationProperties.setProperty("ADD_SS_ANN",
+ Cache.setPropertyNoSave("ADD_SS_ANN",
Boolean.TRUE.toString());
FileLoader loader = new FileLoader(false);
AlignFrame af = loader.LoadFileWaitTillLoaded("examples/1gaq.txt",
break;
}
}
- assertTrue(
- "Couldn't find sequence associated annotation "
- + aa.label
- + " on the sequence it is associated with.\nSequence associated editing will fail.",
+ assertTrue("Couldn't find sequence associated annotation "
+ + aa.label
+ + " on the sequence it is associated with.\nSequence associated editing will fail.",
found);
}
}
@BeforeClass(alwaysRun = true)
public static void setUpBeforeClass() throws Exception
{
- jalview.bin.Jalview.main(new String[] { "-props",
- "test/jalview/io/testProps.jvprops" });
+ jalview.bin.Jalview
+ .main(new String[]
+ { "-props", "test/jalview/io/testProps.jvprops" });
}
/**
@AfterClass(alwaysRun = true)
public static void tearDownAfterClass() throws Exception
{
- jalview.gui.Desktop.instance.closeAll_actionPerformed(null);
+ jalview.gui.Desktop.getInstance().closeAll_actionPerformed(null);
}
String inFile = "examples/1gaq.txt";
String tfile = File.createTempFile("JalviewTest", ".jvp")
.getAbsolutePath();
- AlignFrame af = new jalview.io.FileLoader().LoadFileWaitTillLoaded(
- inFile, DataSourceType.FILE);
+ AlignFrame af = new jalview.io.FileLoader()
+ .LoadFileWaitTillLoaded(inFile, DataSourceType.FILE);
assertTrue("Didn't read input file " + inFile, af != null);
af.saveAlignment(tfile, FileFormat.Jalview);
assertTrue("Failed to store as a project.",
sq = sq.getDatasetSequence();
}
assertNotNull(sq.getAllPDBEntries());
- assertEquals("Expected only one PDB ID", 1, sq.getAllPDBEntries()
- .size());
+ assertEquals("Expected only one PDB ID", 1,
+ sq.getAllPDBEntries().size());
for (PDBEntry pdbentry : sq.getAllPDBEntries())
{
- System.err.println("PDB Entry " + pdbentry.getId() + " "
- + pdbentry.getFile());
+ System.err.println(
+ "PDB Entry " + pdbentry.getId() + " " + pdbentry.getFile());
boolean exists = false, found = false;
for (AlignmentAnnotation ana : sq.getAnnotation())
{
}
if (exists)
{
- assertTrue("Couldn't find any annotation for " + pdbentry.getId()
- + " (file handle " + pdbentry.getFile() + ")", found);
+ assertTrue(
+ "Couldn't find any annotation for " + pdbentry.getId()
+ + " (file handle " + pdbentry.getFile() + ")",
+ found);
}
}
}
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.io;
import java.io.File;
{
Cache.loadProperties(propsFile);
- Cache.applicationProperties.setProperty(BackupFiles.ENABLED,
+ Cache.setPropertyNoSave(BackupFiles.ENABLED,
Boolean.toString(enabled));
- Cache.applicationProperties.setProperty(
+ Cache.setPropertyNoSave(
BackupFilesPresetEntry.SAVEDCONFIG, bfpe.toString());
/*
- Cache.applicationProperties.setProperty(BackupFiles.ENABLED,
+ Cache.setPropertyNoSave(BackupFiles.ENABLED,
Boolean.toString(enabled));
- Cache.applicationProperties.setProperty(BackupFiles.SUFFIX, suffix);
- Cache.applicationProperties.setProperty(BackupFiles.SUFFIX_DIGITS,
+ Cache.setPropertyNoSave(BackupFiles.SUFFIX, suffix);
+ Cache.setPropertyNoSave(BackupFiles.SUFFIX_DIGITS,
Integer.toString(digits));
- Cache.applicationProperties.setProperty(BackupFiles.REVERSE_ORDER,
+ Cache.setPropertyNoSave(BackupFiles.REVERSE_ORDER,
Boolean.toString(reverse));
- Cache.applicationProperties.setProperty(BackupFiles.NO_MAX,
+ Cache.setPropertyNoSave(BackupFiles.NO_MAX,
Boolean.toString(noMax));
- Cache.applicationProperties.setProperty(BackupFiles.ROLL_MAX,
+ Cache.setPropertyNoSave(BackupFiles.ROLL_MAX,
Integer.toString(rollMax));
- Cache.applicationProperties.setProperty(BackupFiles.CONFIRM_DELETE_OLD,
+ Cache.setPropertyNoSave(BackupFiles.CONFIRM_DELETE_OLD,
"false");
*/
}
cleanupTmpFiles(newFile, suffix, digits);
}
- private void cleanupTmpFiles(String file, String mysuffix, int mydigits)
+ protected static void cleanupTmpFiles(String file, String mysuffix,
+ int mydigits)
{
File newfile = new File(file);
if (newfile.exists())
* remove any sequence mappings created so they don't pollute other tests
*/
StructureSelectionManager ssm = StructureSelectionManager
- .getStructureSelectionManager(Desktop.instance);
+ .getStructureSelectionManager(Desktop.getInstance());
ssm.resetAll();
}
.getFeatureColours();
FeaturesFile featuresFile = new FeaturesFile(
"examples/exampleFeatures.txt", DataSourceType.FILE);
- assertTrue("Test " + "Features file test"
- + "\nFailed to parse features file.",
+ assertTrue(
+ "Test " + "Features file test"
+ + "\nFailed to parse features file.",
featuresFile.parse(al.getDataset(), colours, true));
/*
Map<String, FeatureColourI> colours = af.getFeatureRenderer()
.getFeatureColours();
// GFF2 uses space as name/value separator in column 9
- String gffData = "METAL\tcc9900\n"
- + "GFF\n"
+ String gffData = "METAL\tcc9900\n" + "GFF\n"
+ "FER_CAPAA\tuniprot\tMETAL\t44\t45\t4.0\t.\t.\tNote Iron-sulfur; Note 2Fe-2S\n"
+ "FER1_SOLLC\tuniprot\tPfam\t55\t130\t2.0\t.\t.";
FeaturesFile featuresFile = new FeaturesFile(gffData,
Map<String, FeatureColourI> colours = af.getFeatureRenderer()
.getFeatureColours();
// GFF3 uses '=' separator for name/value pairs in column 9
- // comma (%2C) equals (%3D) or semi-colon (%3B) should be url-escaped in values
+ // comma (%2C) equals (%3D) or semi-colon (%3B) should be url-escaped in
+ // values
String gffData = "##gff-version 3\n"
+ "FER_CAPAA\tuniprot\tMETAL\t39\t39\t0.0\t.\t.\t"
+ "Note=Iron-sulfur (2Fe-2S);Note=another note,and another;evidence=ECO%3B0000255%2CPROSITE%3DProRule:PRU00465;"
assertEquals("21", sf.getValueAsString("CSQ", "AF"));
assertEquals("benign,possibly_damaging",
sf.getValueAsString("CSQ", "POLYPHEN"));
- assertEquals("Benign=good", sf.getValueAsString("CSQ", "clin_sig")); // url decoded
+ assertEquals("Benign=good", sf.getValueAsString("CSQ", "clin_sig")); // url
+ // decoded
// todo change STRAND and !Phase into fields of SequenceFeature instead
assertEquals(".", sf.otherDetails.get("STRAND"));
assertEquals(0, sf.getStrand());
SequenceI seq2 = dataset.findName("seq2");
assertNotNull(seq1);
assertNotNull(seq2);
- assertFalse(
- "Failed to replace dummy seq1 with real sequence",
+ assertFalse("Failed to replace dummy seq1 with real sequence",
seq1 instanceof SequenceDummy
&& ((SequenceDummy) seq1).isDummy());
- assertFalse(
- "Failed to replace dummy seq2 with real sequence",
+ assertFalse("Failed to replace dummy seq2 with real sequence",
seq2 instanceof SequenceDummy
&& ((SequenceDummy) seq2).isDummy());
String placeholderseq = new SequenceDummy("foo").getSequenceAsString();
assertFalse("dummy replacement buggy for seq2",
placeholderseq.equals(seq2.getSequenceAsString()));
assertNotNull("No features added to seq1", seq1.getSequenceFeatures());
- assertEquals("Wrong number of features", 3, seq1.getSequenceFeatures()
- .size());
+ assertEquals("Wrong number of features", 3,
+ seq1.getSequenceFeatures().size());
assertTrue(seq2.getSequenceFeatures().isEmpty());
- assertEquals(
- "Wrong number of features",
- 0,
- seq2.getSequenceFeatures() == null ? 0 : seq2
- .getSequenceFeatures().size());
- assertTrue(
- "Expected at least one CDNA/Protein mapping for seq1",
+ assertEquals("Wrong number of features", 0,
+ seq2.getSequenceFeatures() == null ? 0
+ : seq2.getSequenceFeatures().size());
+ assertTrue("Expected at least one CDNA/Protein mapping for seq1",
dataset.getCodonFrame(seq1) != null
&& dataset.getCodonFrame(seq1).size() > 0);
AlignmentI dataset = new Alignment(new SequenceI[] {});
FeaturesFile ffile = new FeaturesFile(simpleGffFile,
DataSourceType.FILE);
-
+
boolean parseResult = ffile.parse(dataset, null, false, false);
assertTrue("return result should be true", parseResult);
checkDatasetfromSimpleGff3(dataset);
@Test(groups = { "Functional" })
public void simpleGff3FileLoader() throws IOException
{
- AlignFrame af = new FileLoader(false).LoadFileWaitTillLoaded(
- simpleGffFile, DataSourceType.FILE);
+ AlignFrame af = new FileLoader(false)
+ .LoadFileWaitTillLoaded(simpleGffFile, DataSourceType.FILE);
assertTrue(
"Didn't read the alignment into an alignframe from Gff3 File",
af != null);
AlignmentI dataset = new Alignment(new SequenceI[] {});
FeaturesFile ffile = new FeaturesFile(simpleGffFile,
DataSourceType.FILE);
-
+
boolean parseResult = ffile.parse(dataset, null, false, true);
assertTrue("return result (relaxedID matching) should be true",
parseResult);
.getFeatureColours();
String features = "METAL\tcc9900\n"
+ "GAMMA-TURN\tred|0,255,255|20.0|95.0|below|66.0\n"
- + "Pfam\tred\n"
- + "STARTGROUP\tuniprot\n"
+ + "Pfam\tred\n" + "STARTGROUP\tuniprot\n"
+ "Cath\tFER_CAPAA\t-1\t0\t0\tDomain\n" // non-positional feature
+ "Iron\tFER_CAPAA\t-1\t39\t39\tMETAL\n"
+ "Turn\tFER_CAPAA\t-1\t36\t38\tGAMMA-TURN\n"
* empty feature group to check handled correctly
*/
SequenceI seq = al.getSequenceAt(1); // FER_CAPAN
- seq.addSequenceFeature(new SequenceFeature("Pfam", "desc1", 0, 0, 1.3f,
- null));
- seq.addSequenceFeature(new SequenceFeature("Pfam", "desc2", 4, 9,
- Float.NaN, null));
+ seq.addSequenceFeature(
+ new SequenceFeature("Pfam", "desc1", 0, 0, 1.3f, null));
+ seq.addSequenceFeature(
+ new SequenceFeature("Pfam", "desc2", 4, 9, Float.NaN, null));
seq = al.getSequenceAt(2); // FER1_SOLLC
- seq.addSequenceFeature(new SequenceFeature("Pfam", "desc3", 0, 0,
- Float.NaN, ""));
- seq.addSequenceFeature(new SequenceFeature("Pfam", "desc4", 5, 8,
- -2.6f, ""));
+ seq.addSequenceFeature(
+ new SequenceFeature("Pfam", "desc3", 0, 0, Float.NaN, ""));
+ seq.addSequenceFeature(
+ new SequenceFeature("Pfam", "desc4", 5, 8, -2.6f, ""));
/*
* first with no features displayed, exclude non-positional features
/*
* features are output within group, ordered by sequence and type
*/
- expected = "METAL\tcc9900\n"
- + "Pfam\tff0000\n"
+ expected = "METAL\tcc9900\n" + "Pfam\tff0000\n"
+ "GAMMA-TURN\tscore|ff0000|00ffff|noValueMin|20.0|95.0|below|66.0\n"
+ "\nSTARTGROUP\tuniprot\n"
+ "Iron\tFER_CAPAA\t-1\t39\t39\tMETAL\t0.0\n"
fr, false, false);
String gffHeader = "##gff-version 2\n";
assertEquals(gffHeader, exported);
- exported = featuresFile.printGffFormat(al.getSequencesArray(), fr,
- true, false);
+ exported = featuresFile.printGffFormat(al.getSequencesArray(), fr, true,
+ false);
assertEquals(gffHeader, exported);
/*
new SequenceFeature("Domain", "Cath", 0, 0, 0f, "Uniprot"));
al.getSequenceAt(0).addSequenceFeature(
new SequenceFeature("METAL", "Cath", 39, 39, 1.2f, null));
- al.getSequenceAt(1)
- .addSequenceFeature(
- new SequenceFeature("GAMMA-TURN", "Turn", 36, 38, 2.1f,
- "s3dm"));
+ al.getSequenceAt(1).addSequenceFeature(new SequenceFeature("GAMMA-TURN",
+ "Turn", 36, 38, 2.1f, "s3dm"));
SequenceFeature sf = new SequenceFeature("Pfam", "", 20, 20, 0f,
"Uniprot");
sf.setStrand("+");
*/
fr.setGroupVisibility("Uniprot", true);
fr.setGroupVisibility("s3dm", false);
- exported = featuresFile.printGffFormat(al.getSequencesArray(), fr,
- true, false);
+ exported = featuresFile.printGffFormat(al.getSequencesArray(), fr, true,
+ false);
String expected = gffHeader
+ "FER_CAPAA\tUniprot\tDomain\t0\t0\t0.0\t.\t.\n";
assertEquals(expected, exported);
exported = featuresFile.printGffFormat(al.getSequencesArray(), fr,
false, false);
// Pfam feature columns include strand(+), phase(2), attributes
- expected = gffHeader
- + "FER_CAPAA\tCath\tMETAL\t39\t39\t1.2\t.\t.\n"
- // CSQ output as CSQ=att1=value1,att2=value2
- // note all commas are encoded here which is wrong - it should be
- // SIFT=benign,mostly benign,cloudy%2C with meatballs
+ expected = gffHeader + "FER_CAPAA\tCath\tMETAL\t39\t39\t1.2\t.\t.\n"
+ // CSQ output as CSQ=att1=value1,att2=value2
+ // note all commas are encoded here which is wrong - it should be
+ // SIFT=benign,mostly benign,cloudy%2C with meatballs
+ "FER_CAPAN\tUniprot\tPfam\t20\t20\t0.0\t+\t2\tx=y;black=white;"
+ "CSQ=SIFT=benign%2Cmostly benign%2Ccloudy%2C with meatballs,consequence=missense_variant\n"
+ "FER_CAPAN\ts3dm\tGAMMA-TURN\t36\t38\t2.1\t.\t.\n";
sf2.setValue("clin_sig", "Benign");
sf2.setValue("AF", "46");
al.getSequenceAt(0).addSequenceFeature(sf2);
-
+
FeaturesFile featuresFile = new FeaturesFile();
FeatureRenderer fr = af.alignPanel.getFeatureRenderer();
final String gffHeader = "##gff-version 2\n";
sf2.setValue("clin_sig", "Benign");
sf2.setValue("AF", "46");
al.getSequenceAt(0).addSequenceFeature(sf2);
-
+
FeaturesFile featuresFile = new FeaturesFile();
FeatureRenderer fr = af.alignPanel.getFeatureRenderer();
fr.findAllFeatures(true);
-
+
fr.setVisible("METAL");
fr.setColour("METAL", new FeatureColour(Color.PINK));
- String exported = featuresFile.printJalviewFormat(
- al.getSequencesArray(),
- fr, false, false);
+ String exported = featuresFile
+ .printJalviewFormat(al.getSequencesArray(), fr, false, false);
String expected = "METAL\tffafaf\n\nSTARTGROUP\tgrp1\n"
+ "Cath\tFER_CAPAA\t-1\t39\t39\tMETAL\t1.2\n"
+ "ENDGROUP\tgrp1\n\nSTARTGROUP\tgrp2\n"
+ "Cath\tFER_CAPAA\t-1\t41\t41\tMETAL\t0.6\n"
+ "ENDGROUP\tgrp2\n";
assertEquals(expected, exported);
-
+
/*
* now threshold to Score > 1.1 - should exclude sf2
* (and there should be no empty STARTGROUP/ENDGROUP output)
+ "Cath\tFER_CAPAA\t-1\t39\t39\tMETAL\t1.2\n"
+ "ENDGROUP\tgrp1\n";
assertEquals(expected, exported);
-
+
/*
* remove threshold and check sf2 is exported
*/
+ "Cath\tFER_CAPAA\t-1\t41\t41\tMETAL\t0.6\n"
+ "ENDGROUP\tgrp2\n";
assertEquals(expected, exported);
-
+
/*
* filter on (clin_sig contains Benign) - should include sf2 and exclude sf1
*/
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.io;
-import java.util.Locale;
-
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotEquals;
public void testIsIdentifiable()
{
FileFormats formats = FileFormats.getInstance();
- assertTrue(formats
- .isIdentifiable(formats.forName(FileFormat.Fasta.getName())));
- assertTrue(formats
- .isIdentifiable(formats.forName(FileFormat.MMCif.getName())));
- assertTrue(formats
- .isIdentifiable(formats.forName(FileFormat.Jnet.getName())));
- assertTrue(formats
- .isIdentifiable(formats.forName(FileFormat.Jalview.getName())));
- // GenBank/ENA
+ assertTrue(formats.isIdentifiable(formats.forName(FileFormat.Fasta
+ .getName())));
+ assertTrue(formats.isIdentifiable(formats.forName(FileFormat.MMCif
+ .getName())));
+ assertTrue(formats.isIdentifiable(formats.forName(FileFormat.Jnet
+ .getName())));
+ assertTrue(formats.isIdentifiable(formats.forName(FileFormat.Jalview
+ .getName())));
assertFalse(formats.isIdentifiable(null));
/*
@Test(groups = "Functional")
public void testGetWritableFormats()
{
- String expected = "[Fasta, PFAM, Stockholm, PIR, BLC, AMSA, JSON, PileUp, MSF, Clustal, PHYLIP]";
+ String expected = "[Fasta, PFAM, Stockholm, PIR, BLC, AMSA, JSON, PileUp, MSF, Clustal, PHYLIP, HMMER3]";
FileFormats formats = FileFormats.getInstance();
assertEquals(formats.getWritableFormats(true).toString(), expected);
- expected = "[Fasta, PFAM, Stockholm, PIR, BLC, AMSA, JSON, PileUp, MSF, Clustal, PHYLIP, Jalview]";
+ expected = "[Fasta, PFAM, Stockholm, PIR, BLC, AMSA, JSON, PileUp, MSF, Clustal, PHYLIP, Jalview, HMMER3]";
assertEquals(formats.getWritableFormats(false).toString(), expected);
}
@Test(groups = "Functional")
public void testDeregisterFileFormat()
{
- String writable = "[Fasta, PFAM, Stockholm, PIR, BLC, AMSA, JSON, PileUp, MSF, Clustal, PHYLIP]";
- String readable = "[Fasta, PFAM, Stockholm, PIR, BLC, AMSA, HTML, RNAML, JSON, PileUp, MSF, Clustal, PHYLIP, GenBank Flatfile, ENA Flatfile, GFF or Jalview features, PDB, mmCIF, Jalview]";
+ String writable = "[Fasta, PFAM, Stockholm, PIR, BLC, AMSA, JSON, PileUp, MSF, Clustal, PHYLIP, HMMER3]";
+ String readable = "[Fasta, PFAM, Stockholm, PIR, BLC, AMSA, HTML, RNAML, JSON, PileUp, MSF, Clustal, PHYLIP, GenBank Flatfile, ENA Flatfile, GFF or Jalview features, PDB, mmCIF, Jalview, HMMER3, BSML]";
FileFormats formats = FileFormats.getInstance();
+ System.out.println(formats.getReadableFormats().toString());
assertEquals(formats.getWritableFormats(true).toString(), writable);
assertEquals(formats.getReadableFormats().toString(), readable);
formats.deregisterFileFormat(FileFormat.Fasta.getName());
- writable = "[PFAM, Stockholm, PIR, BLC, AMSA, JSON, PileUp, MSF, Clustal, PHYLIP]";
- readable = "[PFAM, Stockholm, PIR, BLC, AMSA, HTML, RNAML, JSON, PileUp, MSF, Clustal, PHYLIP, GenBank Flatfile, ENA Flatfile, GFF or Jalview features, PDB, mmCIF, Jalview]";
+ writable = "[PFAM, Stockholm, PIR, BLC, AMSA, JSON, PileUp, MSF, Clustal, PHYLIP, HMMER3]";
+ readable = "[PFAM, Stockholm, PIR, BLC, AMSA, HTML, RNAML, JSON, PileUp, MSF, Clustal, PHYLIP, GenBank Flatfile, ENA Flatfile, GFF or Jalview features, PDB, mmCIF, Jalview, HMMER3, BSML]";
assertEquals(formats.getWritableFormats(true).toString(), writable);
assertEquals(formats.getReadableFormats().toString(), readable);
* re-register the format: it gets added to the end of the list
*/
formats.registerFileFormat(FileFormat.Fasta);
- writable = "[PFAM, Stockholm, PIR, BLC, AMSA, JSON, PileUp, MSF, Clustal, PHYLIP, Fasta]";
- readable = "[PFAM, Stockholm, PIR, BLC, AMSA, HTML, RNAML, JSON, PileUp, MSF, Clustal, PHYLIP, GenBank Flatfile, ENA Flatfile, GFF or Jalview features, PDB, mmCIF, Jalview, Fasta]";
+ writable = "[PFAM, Stockholm, PIR, BLC, AMSA, JSON, PileUp, MSF, Clustal, PHYLIP, HMMER3, Fasta]";
+ readable = "[PFAM, Stockholm, PIR, BLC, AMSA, HTML, RNAML, JSON, PileUp, MSF, Clustal, PHYLIP, GenBank Flatfile, ENA Flatfile, GFF or Jalview features, PDB, mmCIF, Jalview, HMMER3, BSML, Fasta]";
assertEquals(formats.getWritableFormats(true).toString(), writable);
assertEquals(formats.getReadableFormats().toString(), readable);
}
for (FileFormatI ff : FileFormat.values())
{
assertSame(ff, formats.forName(ff.getName()));
- assertSame(ff, formats.forName(ff.getName().toUpperCase(Locale.ROOT)));
- assertSame(ff, formats.forName(ff.getName().toLowerCase(Locale.ROOT)));
+ assertSame(ff,
+ formats.forName(ff.getName().toUpperCase(Locale.ROOT)));
+ assertSame(ff,
+ formats.forName(ff.getName().toLowerCase(Locale.ROOT)));
}
assertNull(formats.forName(null));
assertNull(formats.forName("rubbish"));
* verify the list of file formats registered matches the enum values
*/
FileFormats instance = FileFormats.getInstance();
- Iterator<FileFormatI> formats = instance.getFormats().iterator();
+ Iterator<FileFormatI> formats = instance.getFormats()
+ .iterator();
FileFormatI[] builtIn = FileFormat.values();
for (FileFormatI ff : builtIn)
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.io;
+import static org.testng.Assert.assertEquals;
+
+import jalview.bin.Cache;
+
import org.junit.Assert;
import org.testng.annotations.Test;
// Data source type expected to be DataSourceType.URL
Assert.assertEquals(DataSourceType.URL, fileLoader.protocol);
}
+
+ @Test(groups = "Functional")
+ public void testUpdateRecentlyOpened()
+ {
+ // ensure properties file is read-only
+ Cache.loadProperties("test/jalview/io/testProps.jvprops");
+
+ String recent = "RECENT_FILE";
+ Cache.removeProperty(recent);
+
+ String prop = FileLoader.updateRecentlyOpened("a/b/c",
+ DataSourceType.FILE);
+ assertEquals(prop, "a/b/c");
+
+ prop = FileLoader.updateRecentlyOpened("d/e/f", DataSourceType.FILE);
+ assertEquals(prop, "d/e/f\ta/b/c");
+
+ // revisiting a file moves it to the top of the list
+ prop = FileLoader.updateRecentlyOpened("a/b/c", DataSourceType.FILE);
+ assertEquals(prop, "a/b/c\td/e/f");
+
+ // history list is limited to the most recent 11 items
+ for (int i = 0; i < 20; i++)
+ {
+ prop = FileLoader.updateRecentlyOpened(String.format("%d.fa", i),
+ DataSourceType.FILE);
+ }
+ assertEquals(prop,
+ "19.fa\t18.fa\t17.fa\t16.fa\t15.fa\t14.fa\t13.fa\t12.fa\t11.fa\t10.fa\t9.fa");
+ }
}
{
try
{
- AlignmentI al = new FormatAdapter().readFile("examples/uniref50.fa",
+ AlignmentI al;
+ if (format == FileFormat.HMMER3)
+ {
+ al = new FormatAdapter().readFile("examples/uniref50.hmm",
+ DataSourceType.FILE, FileFormat.HMMER3);
+ }
+ else
+ {
+ al = new FormatAdapter().readFile("examples/uniref50.fa",
DataSourceType.FILE, FileFormat.Fasta);
+ }
/*
* 'gap' is the gap character used in the alignment data file here,
AlignmentI reloaded = new FormatAdapter().readFile(formatted,
DataSourceType.PASTE, format);
List<SequenceI> reread = reloaded.getSequences();
- assertEquals("Wrong number of reloaded sequences", seqs.length,
- reread.size());
+ assertEquals("Wrong number of reloaded sequences", seqs.length,
+ reread.size());
+
int i = 0;
for (SequenceI seq : reread)
* special case: MSF always uses '.' as gap character
*/
sequenceString = adjustForGapTreatment(sequenceString, gap, format);
- assertEquals(
- String.format("Sequence %d: %s", i, seqs[i].getName()),
+ assertEquals(String.format("Sequence %d: %s", i, seqs[i].getName()),
seqs[i].getSequenceAsString(), sequenceString);
i++;
}
} catch (IOException e)
{
- fail(String
- .format("Format %s failed with %s", format, e.getMessage()));
+ fail(String.format("Format %s failed with %s", format,
+ e.getMessage()));
}
}
@DataProvider(name = "formats")
static Object[][] getFormats()
{
- List<FileFormatI> both = new ArrayList<FileFormatI>();
+ List<FileFormatI> both = new ArrayList<>();
for (FileFormatI format : FileFormats.getInstance().getFormats())
{
if (format.isReadable() && format.isWritable()
* set news feed last read to a future time to ensure no
* 'unread' news item is displayed
*/
- Date oneHourFromNow = new Date(System.currentTimeMillis() + 3600 * 1000);
+ Date oneHourFromNow = new Date(
+ System.currentTimeMillis() + 3600 * 1000);
Cache.setDateProperty("JALVIEW_NEWS_RSS_LASTMODIFIED", oneHourFromNow);
Jalview.main(new String[] {});
@AfterClass(alwaysRun = true)
public static void tearDownAfterClass() throws Exception
{
- jalview.gui.Desktop.instance.closeAll_actionPerformed(null);
+ jalview.gui.Desktop.getInstance().closeAll_actionPerformed(null);
}
@BeforeTest(alwaysRun = true)
public static void clearDesktop()
{
- if (Desktop.instance != null && Desktop.getFrames() != null
+ if (Desktop.getInstance() != null && Desktop.getFrames() != null
&& Desktop.getFrames().length > 0)
{
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
}
}
@BeforeClass(alwaysRun = true)
public static void setUpBeforeClass() throws Exception
{
- jalview.bin.Jalview.main(new String[] { "-props",
- "test/jalview/io/testProps.jvprops" });
+ jalview.bin.Jalview
+ .main(new String[]
+ { "-props", "test/jalview/io/testProps.jvprops" });
}
/**
@AfterClass(alwaysRun = true)
public static void tearDownAfterClass() throws Exception
{
- jalview.gui.Desktop.instance.closeAll_actionPerformed(null);
+ jalview.gui.Desktop.getInstance().closeAll_actionPerformed(null);
}
sg.setStartRes(1);
sg.setEndRes(7);
af.getViewport().setSelectionGroup(sg);
- String fseqs = new FormatAdapter(af.alignPanel).formatSequences(
- FileFormat.Fasta, af.alignPanel, true);
+ String fseqs = new FormatAdapter(af.alignPanel)
+ .formatSequences(FileFormat.Fasta, af.alignPanel, true);
assertTrue("Couldn't find '.' in the exported region\n" + fseqs,
fseqs.indexOf(".") > -1);
}
SequenceAnnotationReport sar = new SequenceAnnotationReport(false);
StringBuilder sb = new StringBuilder();
sb.append("123456");
- SequenceFeature sf = new SequenceFeature("disulfide bond", "desc", 1, 3,
- 1.2f, "group");
+ SequenceFeature sf = new SequenceFeature("disulfide bond", "desc", 1,
+ 3, 1.2f, "group");
// residuePos == 2 does not match start or end of feature, nothing done:
sar.appendFeature(sb, 2, null, sf, null, 0);
assertEquals("123456", sb.toString());
- // residuePos == 1 matches start of feature, text appended (but no <br/>)
+ // residuePos == 1 matches start of feature, text appended (but no <br>)
// feature score is not included
sar.appendFeature(sb, 1, null, sf, null, 0);
assertEquals("123456disulfide bond 1:3", sb.toString());
// residuePos == 3 matches end of feature, text appended
- // <br/> is prefixed once sb.length() > 6
+ // <br> is prefixed once sb.length() > 6
sar.appendFeature(sb, 3, null, sf, null, 0);
- assertEquals("123456disulfide bond 1:3<br/>disulfide bond 1:3",
+ assertEquals("123456disulfide bond 1:3<br>disulfide bond 1:3",
sb.toString());
}
sfl.add(sf);
sfl.add(sf);
sfl.add(sf);
- int n = sar.appendFeatures(sb, 1, sfl, new FeatureRenderer(null), 200); // text
- // should
- // terminate
- // before
- // 200
- // characters
+ int n = sar.appendFeatures(sb, 1, sfl,
+ new FeatureRenderer(null), 200); // text should terminate before 200 characters
String s = sb.toString();
assertTrue(s.length() < 200);
assertEquals(n, 7); // should be 7 features left over
*/
minmax.put("METAL", new float[][] { { 0f, 1f }, null });
sar.appendFeature(sb, 1, fr, sf, null, 0);
- // <br/> is appended to a buffer > 6 in length
- assertEquals("METAL 1 3; Fe2-S<br/>METAL 1 3; Fe2-S Score=1.3",
+ // <br> is appended to a buffer > 6 in length
+ assertEquals("METAL 1 3; Fe2-S<br>METAL 1 3; Fe2-S Score=1.3",
sb.toString());
/*
/*
* positional features are ignored
*/
- seq.addSequenceFeature(new SequenceFeature("Domain", "Ferredoxin", 5,
- 10, 1f, null));
+ seq.addSequenceFeature(
+ new SequenceFeature("Domain", "Ferredoxin", 5, 10, 1f, null));
sar.createSequenceAnnotationReport(sb, seq, true, true, null);
- assertEquals("<i>SeqDesc</i>", sb.toString());
+ assertEquals("<i>SeqDesc\n" + "\n" + "</i>", sb.toString());
/*
* non-positional feature
*/
- seq.addSequenceFeature(new SequenceFeature("Type1", "Nonpos", 0, 0, 1f,
- null));
+ seq.addSequenceFeature(
+ new SequenceFeature("Type1", "Nonpos", 0, 0, 1f, null));
sb.setLength(0);
sar.createSequenceAnnotationReport(sb, seq, true, true, null);
- String expected = "<i>SeqDesc<br>Type1 ; Nonpos Score=1.0</i>";
+ String expected = "<i>SeqDesc\n" + "\n"
+ + "<br/>Type1 ; Nonpos Score=1.0</i>";
assertEquals(expected, sb.toString());
/*
*/
sb.setLength(0);
sar.createSequenceAnnotationReport(sb, seq, true, false, null);
- assertEquals("<i>SeqDesc</i>", sb.toString());
+ assertEquals("<i>SeqDesc\n\n</i>", sb.toString());
/*
* add non-pos feature with score inside min-max range for feature type
* score is only appended for positional features so ignored here!
* minMax are not recorded for non-positional features
*/
- seq.addSequenceFeature(new SequenceFeature("Metal", "Desc", 0, 0, 5f,
- null));
+ seq.addSequenceFeature(
+ new SequenceFeature("Metal", "Desc", 0, 0, 5f, null));
FeatureRendererModel fr = new FeatureRenderer(null);
Map<String, float[][]> minmax = fr.getMinMax();
sb.setLength(0);
sar.createSequenceAnnotationReport(sb, seq, true, true, fr);
- expected = "<i>SeqDesc<br>Metal ; Desc<br>Type1 ; Nonpos</i>";
+ expected = "<i>SeqDesc\n" + "\n"
+ + "<br/>Metal ; Desc<br/>Type1 ; Nonpos</i>";
assertEquals(expected, sb.toString());
-
+
/*
* 'linkonly' features are ignored; this is obsolete, as linkonly
* is only set by DasSequenceFetcher, and DAS is history
* 'clinical_significance' attribute is only included in description
* when used for feature colouring
*/
- SequenceFeature sf2 = new SequenceFeature("Variant", "Havana", 0, 0,
- 5f, null);
+ SequenceFeature sf2 = new SequenceFeature("Variant", "Havana", 0, 0, 5f,
+ null);
sf2.setValue(GffConstants.CLINICAL_SIGNIFICANCE, "benign");
seq.addSequenceFeature(sf2);
sb.setLength(0);
sar.createSequenceAnnotationReport(sb, seq, true, true, fr);
- expected = "<i>SeqDesc<br>Metal ; Desc<br>Type1 ; Nonpos<br>Variant ; Havana</i>";
+ expected = "<i>SeqDesc\n" + "\n"
+ + "<br/>Metal ; Desc<br/>Type1 ; Nonpos<br/>Variant ; Havana</i>";
assertEquals(expected, sb.toString());
/*
fc.setAttributeName("clinical_significance");
fr.setColour("Variant", fc);
sar.createSequenceAnnotationReport(sb, seq, true, true, fr);
- expected = "<i>SeqDesc<br>UNIPROT P30419<br>PDB 3iu1<br>Metal ; Desc<br>"
- + "Type1 ; Nonpos<br>Variant ; Havana; clinical_significance=benign</i>";
+ expected = "<i>SeqDesc\n" + "<br/>\n" + "UNIPROT P30419<br/>\n"
+ + "PDB 3iu1\n"
+ + "<br/>Metal ; Desc<br/>Type1 ; Nonpos<br/>Variant ; Havana; clinical_significance=benign</i>";
assertEquals(expected, sb.toString());
// with showNonPositionalFeatures = false
sb.setLength(0);
sar.createSequenceAnnotationReport(sb, seq, true, false, fr);
- expected = "<i>SeqDesc<br>UNIPROT P30419<br>PDB 3iu1</i>";
+ expected = "<i>SeqDesc\n" + "<br/>\n" + "UNIPROT P30419<br/>\n"
+ + "PDB 3iu1\n" + "</i>";
assertEquals(expected, sb.toString());
/*
sf2.setDescription(
"This is a very long description which should be truncated");
sar.createSequenceAnnotationReport(sb, seq, false, true, fr);
- expected = "<i>SeqDesc<br>Metal ; Desc<br>Type1 ; Nonpos<br>Variant ; This is a very long description which sh...; clinical_significance=benign</i>";
+ expected = "<i>SeqDesc\n" + "\n"
+ + "<br/>Metal ; Desc<br/>Type1 ; Nonpos<br/>Variant ; This is a very long description which sh...; clinical_significance=benign</i>";
assertEquals(expected, sb.toString());
// see other tests for treatment of status and html
{
SequenceAnnotationReport sar = new SequenceAnnotationReport(false);
StringBuilder sb = new StringBuilder();
-
+
SequenceI seq = new Sequence("s1", "ABC");
int maxSources = (int) PA.getValue(sar, "MAX_SOURCES");
{
seq.addDBRef(new DBRefEntry("PDB" + i, "0", "3iu1"));
}
-
+
int maxRefs = (int) PA.getValue(sar, "MAX_REFS_PER_SOURCE");
for (int i = 0; i <= maxRefs; i++)
{
seq.addDBRef(new DBRefEntry("Uniprot", "0", "P3041" + i));
}
-
+
sar.createSequenceAnnotationReport(sb, seq, true, true, null, true);
String report = sb.toString();
- assertTrue(report
- .startsWith(
- "<i><br>UNIPROT P30410, P30411, P30412, P30413,...<br>PDB0 3iu1"));
- assertTrue(report
- .endsWith(
- "<br>PDB7 3iu1<br>PDB8,...<br>(Output Sequence Details to list all database references)</i>"));
+ assertTrue(report.startsWith("<i>\n" + "<br/>\n" + "UNIPROT P30410,\n"
+ + " P30411,\n" + " P30412,\n" + " P30413,...<br/>\n"
+ + "PDB0 3iu1<br/>\n" + "PDB1 3iu1<br/>"));
+ assertTrue(report.endsWith("PDB5 3iu1<br/>\n" + "PDB6 3iu1<br/>\n"
+ + "PDB7 3iu1<br/>\n" + "PDB8,...<br/>\n"
+ + "(Output Sequence Details to list all database references)\n"
+ + "</i>"));
}
/**
* feature at 11-12 on peptide maps to 110-115 on CDS
* here we test for tooltip at 113 (t)
*/
- SequenceFeature sf2 = new SequenceFeature("metal", "Fe", 11, 12,
- 2.3f, "Uniprot");
+ SequenceFeature sf2 = new SequenceFeature("metal", "Fe", 11, 12, 2.3f,
+ "Uniprot");
features.clear();
features.add(sf2);
mapping = new Mapping(peptide, map);
assertTrue(
Pattern.compile(
"^#=GS\\s+FER2_SPIOL(/\\d+-\\d+)?\\s+AC\\s+P00224$",
- Pattern.MULTILINE).matcher(toStockholm)
- .find(),
+ Pattern.MULTILINE).matcher(toStockholm).find(),
"Couldn't locate UNIPROT Accession in generated Stockholm file.");
AlignmentI fromStockholm = af.readFile(toStockholm,
DataSourceType.PASTE, FileFormat.Stockholm);
SequenceI importedSeq = fromStockholm.getSequenceAt(0);
- assertTrue(importedSeq.getDBRefs()
- .size() == 1,
+ assertTrue(importedSeq.getDBRefs().size() == 1,
"Expected just one database reference to be added to sequence.");
assertTrue(
- importedSeq.getDBRefs().get(0).getAccessionId().indexOf(
- " ") == -1,
+ importedSeq.getDBRefs().get(0).getAccessionId()
+ .indexOf(" ") == -1,
"Spaces were found in accession ID.");
List<DBRefEntry> dbrefs = DBRefUtils.searchRefs(importedSeq.getDBRefs(),
"P00224");
* with no dataloss
*
* @param f
- * - source datafile (IdentifyFile.identify()
- * should work with it)
+ * - source datafile (IdentifyFile.identify() should work with it)
* @param ioformat
- * - label for IO class used to write and read
- * back in the data from f
+ * - label for IO class used to write and read back in the data from
+ * f
* @param ignoreFeatures
* @param ignoreRowVisibility
* @param allowNullAnnotations
al.getSequenceAt(i).createDatasetSequence();
}
String outputfile = rf.formatSequences(ioformat, al, true);
- System.out.println("Output file in '" + ioformat + "':\n"
- + outputfile + "\n<<EOF\n");
+ System.out.println("Output file in '" + ioformat + "':\n" + outputfile
+ + "\n<<EOF\n");
// test for consistency in io
AlignmentI al_input = new AppletFormatAdapter().readFile(outputfile,
DataSourceType.PASTE, ioformat);
assertTrue(
"Number of sequence associated annotations wasn't at least "
- + nminseqann, numsqswithali >= nminseqann);
+ + nminseqann,
+ numsqswithali >= nminseqann);
} catch (Exception e)
{
assertNotNull("Original alignment was null", al);
assertNotNull("Generated alignment was null", al_input);
- assertTrue("Alignment dimension mismatch: original: " + al.getHeight()
- + "x" + al.getWidth() + ", generated: " + al_input.getHeight()
- + "x" + al_input.getWidth(),
+ assertTrue(
+ "Alignment dimension mismatch: original: " + al.getHeight()
+ + "x" + al.getWidth() + ", generated: "
+ + al_input.getHeight() + "x" + al_input.getWidth(),
al.getHeight() == al_input.getHeight()
&& al.getWidth() == al_input.getWidth());
// check Alignment annotation
AlignmentAnnotation[] aa_new = al_input.getAlignmentAnnotation();
AlignmentAnnotation[] aa_original = al.getAlignmentAnnotation();
+ boolean expectProteinSS = !al.isNucleotide();
+ assertTrue(
+ "Alignments not both "
+ + (al.isNucleotide() ? "nucleotide" : "protein"),
+ al_input.isNucleotide() == al.isNucleotide());
// note - at moment we do not distinguish between alignment without any
// annotation rows and alignment with no annotation row vector
assertEqualSecondaryStructure(
"Different alignment annotation at position " + i,
aa_original[i], aa_new[i], allowNullAnnotation);
+ if (aa_original[i].hasIcons)
+ {
+ assertTrue(
+ "Secondary structure expected to be "
+ + (expectProteinSS ? "protein" : "nucleotide"),
+ expectProteinSS == !aa_original[i].isRNA());
+ }
// compare graphGroup or graph properties - needed to verify JAL-1299
assertEquals("Graph type not identical.", aa_original[i].graph,
aa_new[i].graph);
if (!ignoreRowVisibility)
{
assertEquals("Visibility not identical.",
- aa_original[i].visible,
- aa_new[i].visible);
+ aa_original[i].visible, aa_new[i].visible);
}
assertEquals("Threshold line not identical.",
aa_original[i].threshold, aa_new[i].threshold);
// check sequences, annotation and features
SequenceI[] seq_original = new SequenceI[al.getSequencesArray().length];
seq_original = al.getSequencesArray();
- SequenceI[] seq_new = new SequenceI[al_input.getSequencesArray().length];
+ SequenceI[] seq_new = new SequenceI[al_input
+ .getSequencesArray().length];
seq_new = al_input.getSequencesArray();
List<SequenceFeature> sequenceFeatures_original;
List<SequenceFeature> sequenceFeatures_new;
String name = seq_original[i].getName();
int start = seq_original[i].getStart();
int end = seq_original[i].getEnd();
- System.out.println("Check sequence: " + name + "/" + start + "-"
- + end);
+ System.out
+ .println("Check sequence: " + name + "/" + start + "-" + end);
// search equal sequence
for (int in = 0; in < al_input.getSequencesArray().length; in++)
"Sequence Features were not equivalent"
+ (ignoreFeatures ? " ignoring." : ""),
ignoreFeatures
- || (seq_original[i].getSequenceFeatures() == null && seq_new[in]
- .getSequenceFeatures() == null)
- || (seq_original[i].getSequenceFeatures() != null && seq_new[in]
- .getSequenceFeatures() != null));
+ || (seq_original[i].getSequenceFeatures() == null
+ && seq_new[in]
+ .getSequenceFeatures() == null)
+ || (seq_original[i].getSequenceFeatures() != null
+ && seq_new[in]
+ .getSequenceFeatures() != null));
// compare sequence features
- if (seq_original[i].getSequenceFeatures() != null
+ if (!ignoreFeatures
+ && seq_original[i].getSequenceFeatures() != null
&& seq_new[in].getSequenceFeatures() != null)
{
- System.out.println("There are feature!!!");
+ System.out.println("Checking feature equivalence.");
sequenceFeatures_original = seq_original[i]
.getSequenceFeatures();
sequenceFeatures_new = seq_new[in].getSequenceFeatures();
- assertEquals("different number of features", seq_original[i]
- .getSequenceFeatures().size(), seq_new[in]
- .getSequenceFeatures().size());
+ assertEquals("different number of features",
+ seq_original[i].getSequenceFeatures().size(),
+ seq_new[in].getSequenceFeatures().size());
for (int feat = 0; feat < seq_original[i].getSequenceFeatures()
.size(); feat++)
if (al.getSequenceAt(i).getAnnotation() != null
&& al_input.getSequenceAt(in).getAnnotation() != null)
{
- for (int j = 0; j < al.getSequenceAt(i).getAnnotation().length; j++)
+ for (int j = 0; j < al.getSequenceAt(i)
+ .getAnnotation().length; j++)
{
- if (al.getSequenceAt(i).getAnnotation()[j] != null
- && al_input.getSequenceAt(in).getAnnotation()[j] != null)
+ if (al.getSequenceAt(i).getAnnotation()[j] != null && al_input
+ .getSequenceAt(in).getAnnotation()[j] != null)
{
annot_original = al.getSequenceAt(i).getAnnotation()[j];
annot_new = al_input.getSequenceAt(in).getAnnotation()[j];
+ annot_new.annotations.length);
}
boolean isRna = annot_or.isRNA();
- assertTrue("Expected " + (isRna ? " valid RNA " : " no RNA ")
- + " secondary structure in the row.",
+ assertTrue(
+ "Expected " + (isRna ? " valid RNA " : " no RNA ")
+ + " secondary structure in the row.",
isRna == annot_new.isRNA());
for (int i = 0; i < annot_or.annotations.length; i++)
{
- Annotation an_or = annot_or.annotations[i], an_new = annot_new.annotations[i];
+ Annotation an_or = annot_or.annotations[i],
+ an_new = annot_new.annotations[i];
if (an_or != null && an_new != null)
{
{
if (an_or.secondaryStructure != an_new.secondaryStructure
|| ((Float.isNaN(an_or.value) != Float
- .isNaN(an_new.value)) || an_or.value != an_new.value))
+ .isNaN(an_new.value))
+ || an_or.value != an_new.value))
{
fail("Different RNA secondary structure at column " + i
+ " expected: [" + annot_or.annotations[i].toString()
{
// not RNA secondary structure, so expect all elements to match...
if ((an_or.isWhitespace() != an_new.isWhitespace())
- || !an_or.displayCharacter.trim().equals(
- an_new.displayCharacter.trim())
- || !("" + an_or.secondaryStructure).trim().equals(
- ("" + an_new.secondaryStructure).trim())
- || (an_or.description != an_new.description && !((an_or.description == null && an_new.description
- .trim().length() == 0)
- || (an_new.description == null && an_or.description
- .trim().length() == 0) || an_or.description
- .trim().equals(an_new.description.trim())))
- || !((Float.isNaN(an_or.value) && Float
- .isNaN(an_new.value)) || an_or.value == an_new.value))
+ || !an_or.displayCharacter.trim()
+ .equals(an_new.displayCharacter.trim())
+ || !("" + an_or.secondaryStructure).trim()
+ .equals(("" + an_new.secondaryStructure).trim())
+ || (an_or.description != an_new.description
+ && !((an_or.description == null
+ && an_new.description.trim()
+ .length() == 0)
+ || (an_new.description == null
+ && an_or.description.trim()
+ .length() == 0)
+ || an_or.description.trim().equals(
+ an_new.description.trim())))
+ || !((Float.isNaN(an_or.value)
+ && Float.isNaN(an_new.value))
+ || an_or.value == an_new.value))
{
fail("Annotation Element Mismatch\nElement " + i
+ " in original: " + annot_or.annotations[i].toString()
}
if (!thrown)
{
- fail("Expected difference for [" + an_orig + "] and [" + an_new + "]");
+ fail("Expected difference for [" + an_orig + "] and [" + an_new
+ + "]");
}
}
+
private AlignmentAnnotation makeAnnot(Annotation ae)
{
- return new AlignmentAnnotation("label", "description", new Annotation[]
- { ae });
+ return new AlignmentAnnotation("label", "description",
+ new Annotation[]
+ { ae });
}
- @Test(groups={"Functional"})
+ @Test(groups = { "Functional" })
public void testAnnotationEquivalence()
{
AlignmentAnnotation one = makeAnnot(new Annotation("", "", ' ', 1));
- AlignmentAnnotation anotherOne = makeAnnot(new Annotation("", "", ' ',
- 1));
- AlignmentAnnotation sheet = makeAnnot(new Annotation("","",'E',0f));
- AlignmentAnnotation anotherSheet = makeAnnot(new Annotation("","",'E',0f));
- AlignmentAnnotation sheetWithLabel = makeAnnot(new Annotation("1", "",
- 'E', 0f));
- AlignmentAnnotation anotherSheetWithLabel = makeAnnot(new Annotation(
- "1", "", 'E', 0f));
- AlignmentAnnotation rnaNoDC = makeAnnot(new Annotation("","",'<',0f));
- AlignmentAnnotation anotherRnaNoDC = makeAnnot(new Annotation("","",'<',0f));
- AlignmentAnnotation rnaWithDC = makeAnnot(new Annotation("B", "", '<',
- 0f));
- AlignmentAnnotation anotherRnaWithDC = makeAnnot(new Annotation("B",
- "", '<', 0f));
-
+ AlignmentAnnotation anotherOne = makeAnnot(
+ new Annotation("", "", ' ', 1));
+ AlignmentAnnotation sheet = makeAnnot(new Annotation("", "", 'E', 0f));
+ AlignmentAnnotation anotherSheet = makeAnnot(
+ new Annotation("", "", 'E', 0f));
+ AlignmentAnnotation sheetWithLabel = makeAnnot(
+ new Annotation("1", "", 'E', 0f));
+ AlignmentAnnotation anotherSheetWithLabel = makeAnnot(
+ new Annotation("1", "", 'E', 0f));
+ AlignmentAnnotation rnaNoDC = makeAnnot(
+ new Annotation("", "", '<', 0f));
+ AlignmentAnnotation anotherRnaNoDC = makeAnnot(
+ new Annotation("", "", '<', 0f));
+ AlignmentAnnotation rnaWithDC = makeAnnot(
+ new Annotation("B", "", '<', 0f));
+ AlignmentAnnotation anotherRnaWithDC = makeAnnot(
+ new Annotation("B", "", '<', 0f));
+
// check self equivalence
for (boolean allowNull : new boolean[] { true, false })
{
if (p != q)
{
assertNotEqualSecondaryStructure("Should be different",
- aaSet.get(p), aaSet.get(q), false);
+ aaSet.get(p), aaSet.get(q), false);
}
else
{
}
String aliFile = ">Dm\nAAACCCUUUUACACACGGGAAAGGG";
+
String annFile = "JALVIEW_ANNOTATION\n# Created: Thu May 04 11:16:52 BST 2017\n\n"
+ "SEQUENCE_REF\tDm\nNO_GRAPH\tsecondary structure\tsecondary structure\t"
+ "(|(|(|(|, .|, .|, .|, .|)|)|)|)|\t0.0\nROWPROPERTIES\t"
+ "SEQUENCE_REF\tDm\nNO_GRAPH\tsecondary structure\tsecondary structure\t"
+ "(|(|(|(||{|{||{|{||)|)|)|)||}|}|}|}|\t0.0\nROWPROPERTIES\t"
+ "secondary structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false";
+
String annFileFullWuss = "JALVIEW_ANNOTATION\n# Created: Thu May 04 11:16:52 BST 2017\n\n"
+ "SEQUENCE_REF\tDm\nNO_GRAPH\tsecondary structure\tsecondary structure\t"
+ "(|(|(|(||{|{||[|[||)|)|)|)||}|}|]|]|\t0.0\nROWPROPERTIES\t"
"Shouldn't recognise '" + ch + "' as a WUSS bracket");
}
}
+
private static void roundTripSSForRNA(String aliFile, String annFile)
throws Exception
{
// this is the single sequence alignment and the SS annotations equivalent to
// the ones in file RnaSSTestFile
- String aliFileRnaSS = ">Test.sequence/1-14\n"
- + "GUACAAAAAAAAAA";
+ String aliFileRnaSS = ">Test.sequence/1-14\n" + "GUACAAAAAAAAAA";
+
String annFileRnaSSAlphaChars = "JALVIEW_ANNOTATION\n"
+ "# Created: Thu Aug 02 14:54:57 BST 2018\n" + "\n"
+ "NO_GRAPH\tSecondary Structure\tSecondary Structure\t<,<|(,(|E,E|H,H|B,B|h,h|e,e|b,b|(,(|E,E|),)|e,e|),)|>,>|\t2.0\n"
+ "\n"
+ "ROWPROPERTIES\tSecondary Structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false\n"
+ "\n" + "\n" + "ALIGNMENT\tID=RNA.SS.TEST\tTP=RNA;";
+
String wrongAnnFileRnaSSAlphaChars = "JALVIEW_ANNOTATION\n"
+ "# Created: Thu Aug 02 14:54:57 BST 2018\n" + "\n"
+ "NO_GRAPH\tSecondary Structure\tSecondary Structure\t<,<|(,(|H,H|E,E|B,B|h,h|e,e|b,b|(,(|E,E|),)|e,e|),)|>,>|\t2.0\n"
+ "\n"
+ "ROWPROPERTIES\tSecondary Structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false\n"
+ "\n" + "\n" + "ALIGNMENT\tID=RNA.SS.TEST\tTP=RNA;";
+
@Test(groups = { "Functional" })
public void stockholmFileRnaSSAlphaChars() throws Exception
{
}
char[] shouldBe = { '<', '(', 'E', 'H', 'B', 'h', 'e', 'b', '(', 'E',
')', 'e', ')', '>' };
- Assert.assertTrue(
- Arrays.equals(As, shouldBe),
- "Annotation is " + new String(As) + " but should be "
- + new String(shouldBe));
+ Assert.assertTrue(Arrays.equals(As, shouldBe), "Annotation is "
+ + new String(As) + " but should be " + new String(shouldBe));
// this should result in the same RNA SS Annotations
- AlignmentI newAl = new AppletFormatAdapter().readFile(
- aliFileRnaSS,
+ AlignmentI newAl = new AppletFormatAdapter().readFile(aliFileRnaSS,
DataSourceType.PASTE, jalview.io.FileFormat.Fasta);
AnnotationFile aaf = new AnnotationFile();
aaf.readAnnotationFile(newAl, annFileRnaSSAlphaChars,
+ "RNA SS A 2:" + newAl.getAlignmentAnnotation()[0]);
// this should NOT result in the same RNA SS Annotations
- newAl = new AppletFormatAdapter().readFile(
- aliFileRnaSS, DataSourceType.PASTE,
- jalview.io.FileFormat.Fasta);
+ newAl = new AppletFormatAdapter().readFile(aliFileRnaSS,
+ DataSourceType.PASTE, jalview.io.FileFormat.Fasta);
aaf = new AnnotationFile();
aaf.readAnnotationFile(newAl, wrongAnnFileRnaSSAlphaChars,
DataSourceType.PASTE);
- boolean mismatch = testRnaSSAnnotationsEquivalent(al.getAlignmentAnnotation()[0],
+ boolean mismatch = testRnaSSAnnotationsEquivalent(
+ al.getAlignmentAnnotation()[0],
newAl.getAlignmentAnnotation()[0]);
Assert.assertFalse(mismatch,
"RNA SS Annotations SHOULD NOT be pair-wise equivalent (but apparently are): \n"
}
private static boolean testRnaSSAnnotationsEquivalent(
- AlignmentAnnotation a1,
- AlignmentAnnotation a2)
+ AlignmentAnnotation a1, AlignmentAnnotation a2)
{
return a1.rnaSecondaryStructureEquivalent(a2);
}
+ "\n"
+ "ROWPROPERTIES\tSecondary Structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false\n"
+ "\n" + "\n" + "ALIGNMENT\tID=RNA.SS.TEST\tTP=RNA;";
+
String annFileRnaSSWithoutSpaceChars = "JALVIEW_ANNOTATION\n"
+ "# Created: Thu Aug 02 14:54:57 BST 2018\n" + "\n"
+ "NO_GRAPH\tSecondary Structure\tSecondary Structure\t<,<|.,.|H,H|.,.|B,B|h,h|.,.|b,b|(,(|E,E|.,.|e,e|),)|>,>|\t2.0\n"
jalview.io.FileFormat.Fasta);
AnnotationFile afWithoutSpaces = new AnnotationFile();
afWithoutSpaces.readAnnotationFile(alWithoutSpaces,
- annFileRnaSSWithoutSpaceChars,
- DataSourceType.PASTE);
+ annFileRnaSSWithoutSpaceChars, DataSourceType.PASTE);
Assert.assertTrue(
testRnaSSAnnotationsEquivalent(
jalview.io.FileFormat.Fasta);
AnnotationFile wrongAfWithoutSpaces = new AnnotationFile();
wrongAfWithoutSpaces.readAnnotationFile(wrongAlWithoutSpaces,
- wrongAnnFileRnaSSWithoutSpaceChars,
- DataSourceType.PASTE);
+ wrongAnnFileRnaSSWithoutSpaceChars, DataSourceType.PASTE);
Assert.assertFalse(
testRnaSSAnnotationsEquivalent(
import org.testng.Assert;
import org.testng.AssertJUnit;
+import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.DBRefEntry;
import jalview.datamodel.GeneLocus;
+import jalview.datamodel.HiddenMarkovModel;
import jalview.datamodel.HiddenSequences;
import jalview.datamodel.Mapping;
import jalview.datamodel.PDBEntry;
import jalview.datamodel.features.FeatureMatcherSet;
import jalview.datamodel.features.FeatureMatcherSetI;
import jalview.gui.AlignFrame;
+ import jalview.gui.AlignViewport;
import jalview.gui.AlignmentPanel;
import jalview.gui.Desktop;
import jalview.gui.JvOptionPane;
import jalview.viewmodel.AlignmentViewport;
import jalview.viewmodel.seqfeatures.FeatureRendererModel;
+import junit.extensions.PA;
@Test(singleThreaded = true)
public class Jalview2xmlTests extends Jalview2xmlBase
{
+ @AfterMethod(alwaysRun = true)
+ public void tearDown()
+ {
+ Desktop.getInstance().closeAll_actionPerformed(null);
+ }
@Override
@BeforeClass(alwaysRun = true)
DataSourceType.FILE);
assertNotNull(af, "Didn't read input file " + inFile);
af.loadJalviewDataFile(inAnnot, DataSourceType.FILE, null, null);
- AlignViewport viewport = af.getViewport();
+ AlignViewportI viewport = af.getViewport();
assertSame(viewport.getGlobalColourScheme().getClass(),
TCoffeeColourScheme.class, "Didn't set T-coffee colourscheme");
assertNotNull(
ColourSchemeProperty.getColourScheme(viewport,
viewport.getAlignment(),
- viewport.getGlobalColourScheme().getSchemeName()),
+ viewport.getGlobalColourScheme()
+ .getSchemeName()),
"Recognise T-Coffee score from string");
af.saveAlignment(tfile, FileFormat.Jalview);
AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
"examples/exampleFile_2_7.jar", DataSourceType.FILE);
assertNotNull(af, "Didn't read in the example file correctly.");
- assertTrue(Desktop.getAlignFrames().length == 1 + origCount,
+ assertEquals(Desktop.getAlignFrames().length,
+ 1 + origCount,
"Didn't gather the views in the example file.");
+
}
/**
@Test(groups = { "Functional" }, enabled = true)
public void testStoreAndRecoverExpandedviews() throws Exception
{
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
"examples/exampleFile_2_7.jar", DataSourceType.FILE);
{
Assert.fail("Didn't save the expanded view state", e);
}
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
if (Desktop.getAlignFrames() != null)
{
Assert.assertEquals(Desktop.getAlignFrames().length, 0);
Assert.assertEquals(Desktop.getAlignFrames().length,
Desktop.getAlignmentPanels(
af.getViewport().getSequenceSetId()).length);
- Assert.assertEquals(Desktop
- .getAlignmentPanels(af.getViewport().getSequenceSetId()).length,
+ Assert.assertEquals(
+ Desktop.getAlignmentPanels(
+ af.getViewport().getSequenceSetId()).length,
oldviews);
}
@Test(groups = { "Functional" })
public void testStoreAndRecoverReferenceSeqSettings() throws Exception
{
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
"examples/exampleFile_2_7.jar", DataSourceType.FILE);
assertNotNull(af, "Didn't read in the example file correctly.");
{
Assert.fail("Didn't save the expanded view state", e);
}
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
if (Desktop.getAlignFrames() != null)
{
Assert.assertEquals(Desktop.getAlignFrames().length, 0);
@Test(groups = { "Functional" })
public void testStoreAndRecoverGroupRepSeqs() throws Exception
{
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
"examples/uniref50.fa", DataSourceType.FILE);
assertNotNull(af, "Didn't read in the example file correctly.");
{
Assert.fail("Didn't save the expanded view state", e);
}
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
if (Desktop.getAlignFrames() != null)
{
Assert.assertEquals(Desktop.getAlignFrames().length, 0);
@Test(groups = { "Functional" })
public void testStoreAndRecoverPDBEntry() throws Exception
{
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
String exampleFile = "examples/3W5V.pdb";
AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(exampleFile,
DataSourceType.FILE);
{
Assert.fail("Didn't save the state", e);
}
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
if (Desktop.getAlignFrames() != null)
{
Assert.assertEquals(Desktop.getAlignFrames().length, 0);
"Mismatch PDBEntry 'Type'");
Assert.assertNotNull(recov.getFile(),
"Recovered PDBEntry should have a non-null file entry");
- Assert.assertEquals(
- recov.getFile().toLowerCase(Locale.ENGLISH)
- .lastIndexOf("pdb"),
- recov.getFile().length() - 3,
- "Recovered PDBEntry file should have PDB suffix");
+ Assert.assertEquals(recov.getFile().toLowerCase(Locale.ENGLISH).lastIndexOf("pdb"),recov.getFile().length()-3, "Recovered PDBEntry file should have PDB suffix");
}
}
@Test(groups = { "Functional" })
public void testStoreAndRecoverColourThresholds() throws IOException
{
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
"examples/uniref50.fa", DataSourceType.FILE);
- AlignViewport av = af.getViewport();
+ AlignViewportI av = af.getViewport();
AlignmentI al = av.getAlignment();
/*
".jvp");
tfile.deleteOnExit();
new Jalview2XML(false).saveState(tfile);
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
DataSourceType.FILE);
Assert.assertNotNull(af, "Failed to reload project");
}
/**
+ * Load an HMM profile to an alignment, and confirm it is correctly restored
+ * when reloaded from project
+ *
+ * @throws IOException
+ */
+ @Test(groups = { "Functional" })
+ public void testStoreAndRecoverHmmProfile() throws IOException
+ {
+ Desktop.getInstance().closeAll_actionPerformed(null);
+ AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
+ "examples/uniref50.fa", DataSourceType.FILE);
+
+ AlignViewportI av = af.getViewport();
+ AlignmentI al = av.getAlignment();
+
+ /*
+ * mimic drag and drop of hmm file on to alignment
+ */
+ AlignFrame af2 = new FileLoader().LoadFileWaitTillLoaded(
+ "examples/uniref50.hmm", DataSourceType.FILE);
+ al.insertSequenceAt(0,
+ af2.getViewport().getAlignment().getSequenceAt(0));
+
+ /*
+ * check it loaded in
+ */
+ SequenceI hmmSeq = al.getSequenceAt(0);
+ assertTrue(hmmSeq.hasHMMProfile());
+ HiddenMarkovModel hmm = hmmSeq.getHMM();
+ assertSame(hmm.getConsensusSequence(), hmmSeq);
+
+ /*
+ * save project, close windows, reload project, verify
+ */
+ File tfile = File.createTempFile("testStoreAndRecoverHmmProfile",
+ ".jvp");
+ tfile.deleteOnExit();
+ new Jalview2XML(false).saveState(tfile);
+ Desktop.getInstance().closeAll_actionPerformed(null);
+ af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
+ DataSourceType.FILE);
+ Assert.assertNotNull(af, "Failed to reload project");
+
+ hmmSeq = al.getSequenceAt(0);
+ assertTrue(hmmSeq.hasHMMProfile());
+ assertSame(hmm.getConsensusSequence(), hmmSeq);
+ Mapping mapToHmmConsensus = (Mapping) PA.getValue(hmm,
+ "mapToHmmConsensus");
+ assertNotNull(mapToHmmConsensus);
+ assertSame(mapToHmmConsensus.getTo(), hmmSeq.getDatasetSequence());
+ }
+
+ /**
* pre 2.11 - jalview 2.10 erroneously created new dataset entries for each
* view (JAL-3171) this test ensures we can import and merge those views
*/
@Test(groups = { "Functional" })
public void testMergeDatasetsforManyViews() throws IOException
{
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
// complex project - one dataset, several views on several alignments
AlignFrame af = new FileLoader(false).LoadFileWaitTillLoaded(
@Test(groups = "Functional")
public void testPcaViewAssociation() throws IOException
{
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
final String PCAVIEWNAME = "With PCA";
// create a new tempfile
File tempfile = File.createTempFile("jvPCAviewAssoc", "jvp");
}
// load again.
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
tempfile.getCanonicalPath(), DataSourceType.FILE);
- JInternalFrame[] frames = Desktop.instance.getAllFrames();
+ JInternalFrame[] frames = Desktop.getInstance().getAllFrames();
// PCA and the tabbed alignment view should be the only two windows on the
// desktop
assertEquals(frames.length, 2,
@Test(groups = { "Functional" })
public void testStoreAndRecoverGeneLocus() throws Exception
{
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
String seqData = ">P30419\nACDE\n>X1235\nGCCTGTGACGAA";
AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(seqData,
DataSourceType.PASTE);
assertNotNull(af, "Didn't read in the example file correctly.");
-
+
AlignmentViewPanel ap = Desktop.getAlignmentPanels(null)[0];
SequenceI pep = ap.getAlignment().getSequenceAt(0);
SequenceI cds = ap.getAlignment().getSequenceAt(1);
{
Assert.fail("Didn't save the state", e);
}
- Desktop.instance.closeAll_actionPerformed(null);
-
+ Desktop.getInstance().closeAll_actionPerformed(null);
+
new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
DataSourceType.FILE);
AlignmentViewPanel rap = Desktop.getAlignmentPanels(null)[0];
import static org.testng.AssertJUnit.assertEquals;
+import jalview.api.AlignViewportI;
import jalview.bin.Cache;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentI;
import jalview.schemes.ColourSchemeI;
import jalview.schemes.UserColourScheme;
import jalview.schemes.ZappoColourScheme;
+
import java.awt.Color;
import java.util.ArrayList;
{
SequenceI seq = new Sequence("name", "MA--TVLGSPRAPAFF");
AlignmentI al = new Alignment(new SequenceI[] { seq });
- final AlignViewport av = new AlignViewport(al);
+ final AlignViewportI av = new AlignViewport(al);
ResidueColourFinder rcf = new OverviewResColourFinder();
// gaps are grey, residues white
assertEquals(Color.white, rcf.getResidueColour(true,
- av.getResidueShading(), null, seq, 0, null));
- assertEquals(Color.lightGray, rcf.getResidueColour(true,
- av.getResidueShading(), null, seq, 2, null));
+ av.getResidueShading(),
+ null, seq, 0, null));
+ assertEquals(Color.lightGray, rcf
+ .getResidueColour(true, av.getResidueShading(), null, seq, 2,
+ null));
// unaffected by showBoxes setting
assertEquals(Color.white, rcf.getResidueColour(false,
SequenceI seq = new Sequence("name", "MAT--GSPRAPAFF"); // FER1_MAIZE... + a
// gap
AlignmentI al = new Alignment(new SequenceI[] { seq });
- final AlignViewport av = new AlignViewport(al);
+ final AlignViewportI av = new AlignViewport(al);
ResidueColourFinder rcf = new OverviewResColourFinder();
av.setGlobalColourScheme(new ZappoColourScheme());
// @see ResidueProperties.zappo
- assertEquals(Color.pink, rcf.getResidueColour(true,
- av.getResidueShading(), null, seq, 0, null)); // M
- assertEquals(Color.green, rcf.getResidueColour(true,
- av.getResidueShading(), null, seq, 2, null)); // T
- assertEquals(Color.magenta, rcf.getResidueColour(true,
- av.getResidueShading(), null, seq, 5, null)); // G
- assertEquals(Color.orange, rcf.getResidueColour(true,
- av.getResidueShading(), null, seq, 12, null)); // F
+ assertEquals(Color.pink,
+ rcf.getResidueColour(true, av.getResidueShading(),
+ null, seq, 0, null)); // M
+ assertEquals(Color.green,
+ rcf.getResidueColour(true, av.getResidueShading(),
+ null, seq, 2, null)); // T
+ assertEquals(Color.magenta,
+ rcf.getResidueColour(true, av.getResidueShading(),
+ null, seq, 5, null)); // G
+ assertEquals(Color.orange,
+ rcf.getResidueColour(true, av.getResidueShading(),
+ null, seq, 12, null)); // F
// gap colour not specified so gaps are lightGray
- assertEquals(Color.lightGray, rcf.getResidueColour(true,
- av.getResidueShading(), null, seq, 3, null));
+ assertEquals(Color.lightGray, rcf
+ .getResidueColour(true, av.getResidueShading(), null, seq, 3,
+ null));
// unaffected by showBoxes setting
assertEquals(Color.pink, rcf.getResidueColour(false,
av.getResidueShading(), null, seq, 12, null)); // F
// gap colour not specified so gaps are lightGray
- assertEquals(Color.lightGray, rcf.getResidueColour(false,
- av.getResidueShading(), null, seq, 3, null));
+ assertEquals(Color.lightGray, rcf
+ .getResidueColour(false, av.getResidueShading(), null, seq, 3,
+ null));
}
SequenceI seq = new Sequence("name", "MAT--GSPRAPAFF"); // FER1_MAIZE... + a
// gap
AlignmentI al = new Alignment(new SequenceI[] { seq });
- final AlignViewport av = new AlignViewport(al);
+ final AlignViewportI av = new AlignViewport(al);
ResidueColourFinder rcf = new OverviewResColourFinder();
Color[] newColours = new Color[24];
av.setGlobalColourScheme(new UserColourScheme(newColours));
// gap colour not specified so gaps are lightGray
- assertEquals(Color.lightGray, rcf.getResidueColour(true,
- av.getResidueShading(), null, seq, 3, null));
+ assertEquals(Color.lightGray, rcf
+ .getResidueColour(true, av.getResidueShading(), null, seq, 3,
+ null));
newColours[23] = Color.pink;
av.setGlobalColourScheme(new UserColourScheme(newColours));
// gap colour specified as pink
assertEquals(Color.pink, rcf.getResidueColour(true,
- av.getResidueShading(), null, seq, 3, null));
+ av.getResidueShading(),
+ null, seq, 3, null));
// unaffected by showBoxes setting
// gap colour not specified so gaps are lightGray
{
SequenceI seq = new Sequence("name", "MA--TVLGSPRAPAFF");
AlignmentI al = new Alignment(new SequenceI[] { seq });
-
+
ColourSchemeI cs = new ZappoColourScheme();
ArrayList<SequenceI> seqlist = new ArrayList<>();
seqlist.add(seq);
al.addGroup(sg);
SequenceGroup[] groups = new SequenceGroup[1];
groups[0] = sg;
-
- final AlignViewport av = new AlignViewport(al);
+
+ final AlignViewportI av = new AlignViewport(al);
ResidueColourFinder rcf = new OverviewResColourFinder();
-
+
// G in group specified as magenta in Zappo
assertEquals(Color.magenta, rcf.getResidueColour(false,
av.getResidueShading(), groups, seq, 7, null));
// use legacy colouring
rcf = new OverviewResColourFinder(true, Color.blue, Color.red);
-
+
// G in group specified as magenta in Zappo
assertEquals(Color.magenta, rcf.getResidueColour(false,
av.getResidueShading(), groups, seq, 7, null));
{
SequenceI seq = new Sequence("name", "MAT--GSPRAPAFF"); // FER1_MAIZE... + a
// gap
- AlignmentI al = new Alignment(new SequenceI[] { seq });
- final AlignViewport av = new AlignViewport(al);
// non-legacy colouring
ResidueColourFinder rcf = new OverviewResColourFinder();
// gaps gap colour
c = rcf.getBoxColour(shader, seq, 3);
- assertEquals(
- jalview.renderer.OverviewResColourFinder.OVERVIEW_DEFAULT_GAP,
- c);
+ assertEquals(OverviewResColourFinder.OVERVIEW_DEFAULT_GAP, c);
// non legacy colouring with colour scheme
rcf = new OverviewResColourFinder(false, Color.blue, Color.red);
import static org.testng.AssertJUnit.assertEquals;
+import jalview.api.AlignViewportI;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.Sequence;
import jalview.gui.JvOptionPane;
import jalview.schemes.UserColourScheme;
import jalview.schemes.ZappoColourScheme;
-
import java.awt.Color;
import org.testng.annotations.BeforeClass;
{
SequenceI seq = new Sequence("name", "MATVLGSPRAPAFF"); // FER1_MAIZE...
AlignmentI al = new Alignment(new SequenceI[] { seq });
- final AlignViewport av = new AlignViewport(al);
+ final AlignViewportI av = new AlignViewport(al);
ResidueColourFinder rcf = new ResidueColourFinder();
av.setGlobalColourScheme(new ZappoColourScheme());
// @see ResidueProperties.zappo
- assertEquals(Color.pink,
- rcf.getResidueColour(true, av.getResidueShading(), null, seq, 0,
- null)); // M
- assertEquals(Color.green,
- rcf.getResidueColour(true, av.getResidueShading(), null, seq, 2,
- null)); // T
- assertEquals(Color.magenta,
- rcf.getResidueColour(true, av.getResidueShading(), null, seq, 5,
- null)); // G
- assertEquals(Color.orange,
- rcf.getResidueColour(true, av.getResidueShading(), null, seq,
- 12,
- null)); // F
+ assertEquals(Color.pink, rcf.getResidueColour(true,
+ av.getResidueShading(), null, seq, 0, null)); // M
+ assertEquals(Color.green, rcf.getResidueColour(true,
+ av.getResidueShading(), null, seq, 2, null)); // T
+ assertEquals(Color.magenta, rcf.getResidueColour(true,
+ av.getResidueShading(), null, seq, 5, null)); // G
+ assertEquals(Color.orange, rcf.getResidueColour(true,
+ av.getResidueShading(), null, seq, 12, null)); // F
// everything is white if showBoxes is false
assertEquals(Color.white, rcf.getResidueColour(false,
{
SequenceI seq = new Sequence("name", "MA--TVLGSPRAPAFF");
AlignmentI al = new Alignment(new SequenceI[] { seq });
- final AlignViewport av = new AlignViewport(al);
+ final AlignViewportI av = new AlignViewport(al);
ResidueColourFinder rcf = new ResidueColourFinder();
- assertEquals(Color.white,
- rcf.getResidueColour(true, av.getResidueShading(),
- null, seq, 0, null));
- assertEquals(Color.white,
- rcf.getResidueColour(true, av.getResidueShading(),
- null, seq, 2, null));
+ assertEquals(Color.white, rcf.getResidueColour(true,
+ av.getResidueShading(), null, seq, 0, null));
+ assertEquals(Color.white, rcf.getResidueColour(true,
+ av.getResidueShading(), null, seq, 2, null));
// no change if showBoxes is false
assertEquals(Color.white, rcf.getResidueColour(false,
SequenceI seq = new Sequence("name", "MAT--GSPRAPAFF"); // FER1_MAIZE... + a
// gap
AlignmentI al = new Alignment(new SequenceI[] { seq });
- final AlignViewport av = new AlignViewport(al);
+ final AlignViewportI av = new AlignViewport(al);
ResidueColourFinder rcf = new ResidueColourFinder();
Color[] newColours = new Color[24];
// gap colour specified as pink
assertEquals(Color.pink, rcf.getResidueColour(true,
- av.getResidueShading(),
- null, seq, 3, null));
+ av.getResidueShading(), null, seq, 3, null));
// everything is white if showBoxes is false
newColours[23] = null;
assertEquals(Color.white, rcf.getResidueColour(false,
- av.getResidueShading(),
- null, seq, 3, null));
+ av.getResidueShading(), null, seq, 3, null));
newColours[23] = Color.pink;
av.setGlobalColourScheme(new UserColourScheme(newColours));
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.renderer;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import jalview.gui.AlignFrame;
import jalview.io.DataSourceType;
import jalview.io.FileLoader;
import jalview.renderer.ScaleRenderer.ScaleMark;
+import jalview.viewmodel.AlignmentViewport;
import java.util.List;
String data = ">Seq/20-45\nABCDEFGHIJKLMNOPQRSTUVWXYS\n";
AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(data,
DataSourceType.PASTE);
- AlignViewport av = af.getViewport();
+ AlignmentViewport av = af.getViewport();
/*
* scale has minor ticks at 5, 15, 25, major at 10 and 20
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.renderer.seqfeatures;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import java.awt.Color;
import java.util.List;
+import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
+ import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import jalview.api.FeatureColourI;
import jalview.datamodel.SequenceFeature;
import jalview.datamodel.SequenceI;
import jalview.gui.AlignFrame;
-import jalview.gui.AlignViewport;
+import jalview.api.AlignViewportI;
import jalview.io.DataSourceType;
import jalview.io.FileLoader;
import jalview.schemes.FeatureColour;
import jalview.viewmodel.seqfeatures.FeatureRendererModel;
import jalview.viewmodel.seqfeatures.FeatureRendererModel.FeatureSettingsBean;
++
/**
* Unit tests for feature colour determination, including but not limited to
* <ul>
*/
public class FeatureColourFinderTest
{
- private AlignViewport av;
+ private AlignViewportI av;
private SequenceI seq;
private FeatureRendererModel fr;
- @BeforeTest(alwaysRun = true)
+ @BeforeClass(alwaysRun = true)
public void setUp()
{
// aligned column 8 is sequence position 6
String s = ">s1\nABCDE---FGHIJKLMNOPQRSTUVWXYZ\n";
- af = new FileLoader().LoadFileWaitTillLoaded(s, DataSourceType.PASTE);
+ af = new FileLoader().LoadFileWaitTillLoaded(s,
+ DataSourceType.PASTE);
av = af.getViewport();
seq = av.getAlignment().getSequenceAt(0);
fr = af.getFeatureRenderer();
@Test(groups = "Functional")
public void testFindFeatureColour_gapPosition()
{
- seq.addSequenceFeature(
- new SequenceFeature("Metal", "Metal", 2, 12, 0f, null));
+ seq.addSequenceFeature(new SequenceFeature("Metal", "Metal", 2, 12, 0f,
+ null));
fr.setColour("Metal", new FeatureColour(Color.red));
fr.featuresAdded();
av.setShowSequenceFeatures(true);
assertNull(c);
}
+ /**
+ * Nested features coloured by label - expect the colour of the enclosed
+ * feature
+ */
+ @Test(groups = "Functional")
+ public void testFindFeatureColour_nestedFeatures()
+ {
+ SequenceFeature sf1 = new SequenceFeature("domain", "peptide", 1, 120, 0f, null);
+ seq.addSequenceFeature(sf1);
+ SequenceFeature sf2 = new SequenceFeature("domain", "binding", 10, 20,
+ 0f, null);
+ seq.addSequenceFeature(sf2);
+ FeatureColourI fc = new FeatureColour(Color.red);
+ fc.setColourByLabel(true);
+ fr.setColour("domain", fc);
+ fr.featuresAdded();
+ av.setShowSequenceFeatures(true);
+ Color c = finder.findFeatureColour(null, seq, 15);
+ assertEquals(c, fr.getColor(sf2, fc));
+ }
-
@Test(groups = "Functional")
public void testFindFeatureColour_multipleFeaturesAtPositionNoTransparency()
{
/*
* currently contact feature == type "Disulphide Bond" or "Disulfide Bond" !!
*/
- seq.addSequenceFeature(new SequenceFeature("Disulphide Bond", "Contact",
- 2, 12, Float.NaN, "Disulphide"));
+ seq.addSequenceFeature(new SequenceFeature("Disulphide Bond",
+ "Contact", 2, 12, Float.NaN, "Disulphide"));
fr.setColour("Disulphide Bond", new FeatureColour(Color.red));
fr.featuresAdded();
av.setShowSequenceFeatures(true);
@Test(groups = "Functional")
public void testFindFeatureColour_graduatedFeatureColour()
{
- seq.addSequenceFeature(new SequenceFeature("kd", "hydrophobicity", 2, 2,
- 0f, "KdGroup"));
- seq.addSequenceFeature(new SequenceFeature("kd", "hydrophobicity", 4, 4,
- 5f, "KdGroup"));
- seq.addSequenceFeature(new SequenceFeature("kd", "hydrophobicity", 7, 7,
- 10f, "KdGroup"));
+ seq.addSequenceFeature(new SequenceFeature("kd", "hydrophobicity", 2,
+ 2, 0f, "KdGroup"));
+ seq.addSequenceFeature(new SequenceFeature("kd", "hydrophobicity", 4,
+ 4, 5f, "KdGroup"));
+ seq.addSequenceFeature(new SequenceFeature("kd", "hydrophobicity", 7,
+ 7, 10f, "KdGroup"));
/*
* graduated colour from 0 to 10
fr.setColour("Metal", red);
fr.featuresAdded();
av.setShowSequenceFeatures(true);
-
+
/*
* the FeatureSettings transparency slider has range 0-70 which
* corresponds to a transparency value of 1 - 0.3
fr.setColour("Domain", green);
fr.featuresAdded();
av.setShowSequenceFeatures(true);
-
+
/*
* Domain (green) rendered above Metal (red) above background (cyan)
* 1) 0.6 * red(255, 0, 0) + 0.4 * cyan(0, 255, 255) = (153, 102, 102)
fr.setTransparency(0.6f);
Color c = finder.findFeatureColour(Color.cyan, seq, 10);
assertEquals(c, new Color(61, 194, 41));
-
+
/*
* now promote Metal above Domain
* - currently no way other than mimicking reordering of
fr.setFeaturePriority(data);
c = finder.findFeatureColour(Color.cyan, seq, 10);
assertEquals(c, new Color(153, 102, 41));
-
+
/*
* ..and turn off display of Metal
* Domain (green) above background (pink)
{
String kdFeature = "kd";
String metalFeature = "Metal";
- seq.addSequenceFeature(new SequenceFeature(kdFeature, "hydrophobicity",
- 2, 2, 0f, "KdGroup"));
- seq.addSequenceFeature(new SequenceFeature(kdFeature, "hydrophobicity",
- 4, 4, 5f, "KdGroup"));
- seq.addSequenceFeature(new SequenceFeature(metalFeature, "Fe", 4, 4, 5f,
- "MetalGroup"));
- seq.addSequenceFeature(new SequenceFeature(kdFeature, "hydrophobicity",
- 7, 7, 10f, "KdGroup"));
-
+ seq.addSequenceFeature(new SequenceFeature(kdFeature, "hydrophobicity", 2,
+ 2, 0f, "KdGroup"));
+ seq.addSequenceFeature(new SequenceFeature(kdFeature, "hydrophobicity", 4,
+ 4, 5f, "KdGroup"));
+ seq.addSequenceFeature(new SequenceFeature(metalFeature, "Fe", 4, 4,
+ 5f, "MetalGroup"));
+ seq.addSequenceFeature(new SequenceFeature(kdFeature, "hydrophobicity", 7,
+ 7, 10f, "KdGroup"));
+
/*
* kd feature has graduated colour from 0 to 10
* above threshold value of 5
fr.setFeaturePriority(data);
av.setShowSequenceFeatures(true);
-
+
/*
* position 2, column 1, score 0 - below threshold - default colour
*/
*/
c = finder.findFeatureColour(Color.blue, seq, 3);
assertEquals(c, Color.green);
-
+
/*
* position 7, column 9, score 10 - maximum colour in range
*/
import static org.testng.Assert.assertSame;
import static org.testng.Assert.assertTrue;
+import java.awt.Color;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.Test;
+
import jalview.analysis.GeneticCodes;
import jalview.api.AlignViewportI;
import jalview.api.FeatureColourI;
import jalview.util.matcher.Condition;
import jalview.viewmodel.seqfeatures.FeatureRendererModel.FeatureSettingsBean;
-import java.awt.Color;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.testng.annotations.Test;
-
public class FeatureRendererTest
{
+ @AfterMethod(alwaysRun = true)
+ public void tearDown()
+ {
+ Desktop.getInstance().closeAll_actionPerformed(null);
+ }
@Test(groups = "Functional")
public void testFindAllFeatures()
gc = new FeatureColour(Color.red, Color.yellow, Color.red, Color.green,
5f, 11f);
fr.getFeatureColours().put("Cath", gc);
- gc.setAutoScaled(false); // this does little other than save a checkbox setting!
+ gc.setAutoScaled(false); // this does little other than save a checkbox
+ // setting!
assertEquals(fr.getColour(sf2), new Color(255, 213, 0));
/*
SequenceFeature sf2 = new SequenceFeature("sequence_variant", "C, CA",
3, 3, "ensembl");
seq1.addSequenceFeature(sf2);
-
+
/*
* 'find' mapped features from the peptide position
* - first with CDS features _not_ shown on peptide alignment
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.schemes;
import static org.testng.Assert.assertEquals;
// TODO more test cases; check if help documentation matches implementation
}
+
+ // @formatter:on
-
+
/**
* Test for colour calculation when the consensus percentage ignores gapped
* sequences
DataSourceType.PASTE);
AlignmentI al = af.getViewport().getAlignment();
ClustalxColourScheme cs = new ClustalxColourScheme(al, null);
-
+
/*
* column 1 is 66% C which is above Clustalx threshold of 60%
*/
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.schemes;
import static org.testng.Assert.assertEquals;
public ColourSchemeI getInstance(AlignViewportI view,
AnnotatedCollectionI sg)
{
- final ColourSchemeI cs1 = ColourSchemes.getInstance()
- .getColourScheme(JalviewColourScheme.Taylor.toString(),
- (AnnotatedCollectionI) null);
- final ColourSchemeI cs2 = ColourSchemes.getInstance()
- .getColourScheme(JalviewColourScheme.Zappo.toString(),
- (AnnotatedCollectionI) null);
+ final ColourSchemeI cs1 = ColourSchemes.getInstance().getColourScheme(
+ JalviewColourScheme.Taylor.toString(),
+ (AnnotatedCollectionI) null);
+ final ColourSchemeI cs2 = ColourSchemes.getInstance().getColourScheme(
+ JalviewColourScheme.Zappo.toString(),
+ (AnnotatedCollectionI) null);
return new Stripy(cs1, cs2);
}
return "stripy";
}
};
-
+
/*
* a colour scheme that is Clustal but using AWT colour equivalents
*/
@AfterClass(alwaysRun = true)
public static void tearDownAfterClass() throws Exception
{
- Desktop.instance.closeAll_actionPerformed(null);
+ Desktop.getInstance().closeAll_actionPerformed(null);
}
@Test(groups = "Functional")
* in the order in which they are declared in the JalviewColourScheme enum
* (this also determines their order in Colour menus)
*/
- Iterator<ColourSchemeI> schemes = ColourSchemes.getInstance().getColourSchemes().iterator();
+ Iterator<ColourSchemeI> schemes = ColourSchemes.getInstance()
+ .getColourSchemes().iterator();
JalviewColourScheme[] jalviewSchemes = JalviewColourScheme.values();
int i = 0;
while (schemes.hasNext() && i < jalviewSchemes.length)
}
af.closeMenuItem_actionPerformed(true);
}
-
+
@Test(groups = "Functional")
public void testRegisterColourScheme()
{
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.schemes;
import static org.testng.Assert.assertEquals;
import jalview.datamodel.SequenceI;
import jalview.gui.AlignFrame;
-import jalview.gui.AlignViewport;
import jalview.io.DataSourceType;
import jalview.io.FileLoader;
+import jalview.viewmodel.AlignmentViewport;
public class PIDColourSchemeTest
{
*/
AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(seqs,
DataSourceType.PASTE);
- AlignViewport viewport = af.getViewport();
+ AlignmentViewport viewport = af.getViewport();
viewport.setIgnoreGapsConsensus(false, af.alignPanel);
do
{
/*
* including gaps, A should be coloured for 50% consensus
*/
- Color c = viewport
- .getResidueShading().findColour('A', 0, seq);
+ Color c = viewport.getResidueShading().findColour('A', 0, seq);
assertEquals(c, over40);
/*
* now choose to ignore gaps; colour should be for 67%
*/
viewport.setIgnoreGapsConsensus(true, af.alignPanel);
- c = viewport
- .getResidueShading().findColour('A', 0, seq);
+ c = viewport.getResidueShading().findColour('A', 0, seq);
assertEquals(c, over60);
}
}
// original numbers taken from
// http://www.ebi.ac.uk/pdbe-srv/view/entry/1qcf/secondary.html
// these are in numbering relative to the subsequence above
- int coils[] = { 266, 275, 278, 287, 289, 298, 302, 316 }, helices[] = new int[]
- { 303, 315 }, sheets[] = new int[] { 267, 268, 269, 270 };
+ int coils[] = { 266, 275, 278, 287, 289, 298, 302, 316 },
+ helices[] = new int[]
+ { 303, 315 }, sheets[] = new int[] { 267, 268, 269, 270 };
- StructureSelectionManager ssm = new jalview.structure.StructureSelectionManager();
+ StructureSelectionManager ssm = StructureSelectionManager
+ .getStructureSelectionManager(null);
StructureFile pmap = ssm.setMapping(true, new SequenceI[] { uprot },
- new String[] { "A" }, "test/jalview/ext/jmol/1QCF.pdb",
+ new String[]
+ { "A" }, "test/jalview/ext/jmol/1QCF.pdb",
DataSourceType.FILE);
assertTrue(pmap != null);
SequenceI protseq = pmap.getSeqsAsArray()[0];
char expected = 'H';
for (int p : helices)
{
- Annotation a = ss.annotations[op = (uprot.findIndex(offset + p) - 1)];
- assertTrue(
- "Expected a helix at position " + p + uprot.getCharAt(op)
- + " but got coil", a != null);
+ Annotation a = ss.annotations[op = (uprot.findIndex(offset + p)
+ - 1)];
+ assertTrue("Expected a helix at position " + p
+ + uprot.getCharAt(op) + " but got coil", a != null);
assertEquals("Expected a helix at position " + p,
a.secondaryStructure, expected);
}
for (int p : sheets)
{
Annotation a = ss.annotations[uprot.findIndex(offset + p) - 1];
- assertTrue(
- "Expected a strand at position " + p + " but got coil",
+ assertTrue("Expected a strand at position " + p + " but got coil",
a != null);
assertEquals("Expected a strand at position " + p,
a.secondaryStructure, expected);
public void testPDBentryMapping() throws Exception
{
Assert.fail("This test intentionally left to fail");
- Sequence sq = new Sequence(
- "1GAQ A subseq 126 to 219",
+ Sequence sq = new Sequence("1GAQ A subseq 126 to 219",
"EIVKGVCSNFLCDLQPGDNVQITGPVGKEMLMPKDPNATIIMLATGTGIAPFRSFLWKMFFEKHDDYKFNGLGWLFLGVPTSSSLLYKEEFGKM");
Sequence sq1 = new Sequence(sq);
String inFile;
- StructureSelectionManager ssm = new jalview.structure.StructureSelectionManager();
+ StructureSelectionManager ssm = StructureSelectionManager
+ .getStructureSelectionManager(null);
// Associate the 1GAQ pdb file with the subsequence 'imported' from another
// source
StructureFile pde = ssm.setMapping(true, new SequenceI[] { sq },
new String[]
- { "A" }, inFile = "examples/1gaq.txt", DataSourceType.FILE);
+ { "A" }, inFile = "examples/1gaq.txt", DataSourceType.FILE);
assertTrue("PDB File couldn't be found", pde != null);
StructureMapping[] mp = ssm.getMapping(inFile);
assertTrue("No mappings made.", mp != null && mp.length > 0);
if (origMap.getSequence() == sq)
{
assertEquals("Mapping was incomplete.", sq.getLength() - 1,
- (origMap.getPDBResNum(sq.getEnd()) - origMap
- .getPDBResNum(sq.getStart())));
+ (origMap.getPDBResNum(sq.getEnd())
+ - origMap.getPDBResNum(sq.getStart())));
// sanity check - if this fails, mapping from first position in sequence
// we want to transfer to is not where we expect
assertEquals(1, origMap.getSeqPos(126));
{
// walk along the pdb chain's jalview sequence
int rseqpos;
- int fpos = origMap.getSeqPos(rseqpos = firstChain
- .findPosition(p));
+ int fpos = origMap
+ .getSeqPos(rseqpos = firstChain.findPosition(p));
// only look at positions where there is a corresponding position in
// mapping
if (fpos < 1)
break;
}
- Annotation a = transfer.annotations[tanpos], b = alan.annotations[p];
- assertEquals("Non-equivalent annotation element at " + p + "("
- + rseqpos + ")" + " expected at " + fpos + " (alIndex "
- + tanpos + ")", a == null ? a : a.toString(),
+ Annotation a = transfer.annotations[tanpos],
+ b = alan.annotations[p];
+ assertEquals(
+ "Non-equivalent annotation element at " + p + "("
+ + rseqpos + ")" + " expected at " + fpos
+ + " (alIndex " + tanpos + ")",
+ a == null ? a : a.toString(),
b == null ? b : b.toString());
System.out.print("(" + a + "|" + b + ")");
}
@Test(groups = { "Functional" })
public void mapFer1From3W5V() throws Exception
{
- AlignFrame seqf = new FileLoader(false)
- .LoadFileWaitTillLoaded(
- ">FER1_MAIZE/1-150 Ferredoxin-1, chloroplast precursor\nMATVLGSPRAPAFFFSSSSLRAAPAPTAVALPAAKVGIMGRSASSRRRLRAQATYNVKLITPEGEVELQVPD\nDVYILDQAEEDGIDLPYSCRAGSCSSCAGKVVSGSVDQSDQSYLDDGQIADGWVLTCHAYPTSDVVIETHKE\nEELTGA",
- DataSourceType.PASTE, FileFormat.Fasta);
+ AlignFrame seqf = new FileLoader(false).LoadFileWaitTillLoaded(
+ ">FER1_MAIZE/1-150 Ferredoxin-1, chloroplast precursor\nMATVLGSPRAPAFFFSSSSLRAAPAPTAVALPAAKVGIMGRSASSRRRLRAQATYNVKLITPEGEVELQVPD\nDVYILDQAEEDGIDLPYSCRAGSCSSCAGKVVSGSVDQSDQSYLDDGQIADGWVLTCHAYPTSDVVIETHKE\nEELTGA",
+ DataSourceType.PASTE, FileFormat.Fasta);
SequenceI newseq = seqf.getViewport().getAlignment().getSequenceAt(0);
- StructureSelectionManager ssm = new jalview.structure.StructureSelectionManager();
+ StructureSelectionManager ssm = StructureSelectionManager
+ .getStructureSelectionManager(null);
StructureFile pmap = ssm.setMapping(true, new SequenceI[] { newseq },
- new String[] { null }, "examples/3W5V.pdb",
- DataSourceType.FILE);
+ new String[]
+ { null }, "examples/3W5V.pdb", DataSourceType.FILE);
if (pmap == null)
{
AssertJUnit.fail("Couldn't make a mapping for 3W5V to FER1_MAIZE");
StructureImportSettings.setProcessSecondaryStructure(true);
StructureImportSettings.setVisibleChainAnnotation(true);
StructureImportSettings.setShowSeqFeatures(true);
- AlignFrame ref = new FileLoader(false)
- .LoadFileWaitTillLoaded("test/jalview/ext/jmol/1QCF.pdb",
- DataSourceType.FILE);
+ AlignFrame ref = new FileLoader(false).LoadFileWaitTillLoaded(
+ "test/jalview/ext/jmol/1QCF.pdb", DataSourceType.FILE);
SequenceI refseq = ref.getViewport().getAlignment().getSequenceAt(0);
SequenceI newseq = new Sequence(refseq.getName() + "Copy",
refseq.getSequenceAsString());
// make it harder by shifting the copy vs the reference
newseq.setStart(refseq.getStart() + 25);
newseq.setEnd(refseq.getLength() + 25 + refseq.getStart());
- StructureSelectionManager ssm = new jalview.structure.StructureSelectionManager();
+ StructureSelectionManager ssm = StructureSelectionManager
+ .getStructureSelectionManager(null);
ssm.setProcessSecondaryStructure(true);
ssm.setAddTempFacAnnot(true);
StructureFile pmap = ssm.setMapping(true, new SequenceI[] { newseq },
- new String[] { null }, "test/jalview/ext/jmol/1QCF.pdb",
+ new String[]
+ { null }, "test/jalview/ext/jmol/1QCF.pdb",
DataSourceType.FILE);
assertTrue(pmap != null);
assertEquals("Original and copied sequence of different lengths.",
{
for (int p = 0, pSize = refseq.getLength(); p < pSize; p++)
{
- Annotation orig = oannot.annotations[p], tran = tannot.annotations[p];
- assertTrue("Mismatch: coil and non coil site " + p, orig == tran
- || orig != null && tran != null);
+ Annotation orig = oannot.annotations[p],
+ tran = tannot.annotations[p];
+ assertTrue("Mismatch: coil and non coil site " + p,
+ orig == tran || orig != null && tran != null);
if (tran != null)
{
assertEquals("Mismatch in secondary structure at site " + p,
import jalview.structure.AtomSpec;
import jalview.structure.AtomSpecModel;
import jalview.structure.StructureCommandI;
+ import jalview.structure.StructureCommandsI.AtomSpecType;
import jalview.structure.StructureMapping;
import jalview.structure.StructureSelectionManager;
import junit.extensions.PA;
// TODO: JAL-2227 - import mmCIF PISA assembly & identify master/copy chains
- @Test(groups= {"Functional"})
+ @Test(groups = { "Functional" })
public void testImportPDBPreservesChainMappings() throws IOException
{
AlignmentI importedAl = new jalview.io.FormatAdapter().readFile(
// ideally, we would match on the actual data for the 'File' handle for
// pasted files,
// see JAL-623 - pasting is still not correctly handled...
- PDBEntry importedPDB = new PDBEntry("3A6S", "", Type.PDB,
- "Paste");
+ PDBEntry importedPDB = new PDBEntry("3A6S", "", Type.PDB, "Paste");
AAStructureBindingModel binder = new AAStructureBindingModel(
- new StructureSelectionManager(), new PDBEntry[]
+ StructureSelectionManager.getStructureSelectionManager(null), new PDBEntry[]
{ importedPDB },
new SequenceI[][]
{ importedAl.getSequencesArray() }, null)
{
-
+
@Override
public void updateColours(Object source)
{
}
-
+
@Override
public void releaseReferences(Object svl)
{
}
-
+
@Override
public String[] getStructureFiles()
{
return null;
}
-
+
@Override
public void highlightAtoms(List<AtomSpec> atoms)
{
}
-
+
@Override
- public SequenceRenderer getSequenceRenderer(AlignmentViewPanel alignment)
+ public SequenceRenderer getSequenceRenderer(
+ AlignmentViewPanel alignment)
{
return null;
}
assertEquals(chains[0][0], "A");
assertEquals(chains[0][1], "B");
}
+
AAStructureBindingModel testee;
AlignmentI al = null;
seqs[0] = new SequenceI[] { seq1a, seq1b };
seqs[1] = new SequenceI[] { seq2 };
seqs[2] = new SequenceI[] { seq3 };
- StructureSelectionManager ssm = new StructureSelectionManager();
+ StructureSelectionManager ssm = StructureSelectionManager.getStructureSelectionManager(null);
ssm.setMapping(new SequenceI[] { seq1a, seq1b }, null, PDB_1,
DataSourceType.PASTE, null);
* @param pdbFiles
* @param seqs
* @param ssm
- * @param alignPanel
+ * @param alignPanel
*/
protected AAStructureBindingModel newBindingModel(PDBEntry[] pdbFiles,
- SequenceI[][] seqs,
- StructureSelectionManager ssm, AlignmentViewPanel avp)
+ SequenceI[][] seqs, StructureSelectionManager ssm,
+ AlignmentViewPanel avp)
{
AAStructureBindingModel model = new AAStructureBindingModel(ssm,
pdbFiles, seqs, null)
}
@Override
- public SequenceRenderer getSequenceRenderer(
- AlignmentViewPanel avp)
+ public SequenceRenderer getSequenceRenderer(AlignmentViewPanel avp)
{
return avp == null ? null
- : new jalview.gui.SequenceRenderer(
- avp.getAlignViewport());
+ : new jalview.gui.SequenceRenderer(avp.getAlignViewport());
}
@Override
/*
* create a data bean to hold data per structure file
*/
- AAStructureBindingModel.SuperposeData[] structs = new AAStructureBindingModel.SuperposeData[testee.getStructureFiles().length];
+ AAStructureBindingModel.SuperposeData[] structs = new AAStructureBindingModel.SuperposeData[testee
+ .getStructureFiles().length];
for (int i = 0; i < structs.length; i++)
{
- structs[i] = new AAStructureBindingModel.SuperposeData(al.getWidth(), "0");
+ structs[i] = new AAStructureBindingModel.SuperposeData(al.getWidth(),
+ "0");
}
/*
* initialise BitSet of 'superposable columns' to true (would be false for
matched.set(i);
}
- int refStructure = testee
- .findSuperposableResidues(al, matched, structs);
+ int refStructure = testee.findSuperposableResidues(al, matched,
+ structs);
assertEquals(refStructure, 0);
@Test(groups = { "Functional" })
public void testFindSuperposableResidues_hiddenColumn()
{
- AAStructureBindingModel.SuperposeData[] structs = new AAStructureBindingModel.SuperposeData[al.getHeight()];
+ AAStructureBindingModel.SuperposeData[] structs = new AAStructureBindingModel.SuperposeData[al
+ .getHeight()];
for (int i = 0; i < structs.length; i++)
{
- structs[i] = new AAStructureBindingModel.SuperposeData(al.getWidth(), "0");
+ structs[i] = new AAStructureBindingModel.SuperposeData(al.getWidth(),
+ "0");
}
/*
* initialise BitSet of 'superposable columns' to true (would be false for
// treat column 5 of the alignment as hidden
matched.clear(4);
- int refStructure = testee
- .findSuperposableResidues(al, matched, structs);
+ int refStructure = testee.findSuperposableResidues(al, matched,
+ structs);
assertEquals(refStructure, 0);
pdbFiles[0] = new PDBEntry("PDB1", "A", Type.PDB, "seq1.pdb");
pdbFiles[1] = new PDBEntry("PDB2", "B", Type.PDB, "seq2.pdb");
StructureSelectionManager ssm = new StructureSelectionManager();
-
+
/*
* map residues 1-10 to residues 21-30 (atoms 105-150) in structures
*/
Map<Object, AtomSpecModel> colours = binding.buildColoursMap(ssm, seqs,
af.alignPanel);
ChimeraCommands helper = new ChimeraCommands();
-
+
/*
* M colour is #82827d (see strand.html help page)
* sequence residue 1 mapped to structure residue 21
Color mColor = new Color(0x82827d);
AtomSpecModel atomSpec = colours.get(mColor);
assertNotNull(atomSpec);
- assertEquals(helper.getAtomSpec(atomSpec, false), "#0:21.A|#1:21.B");
+ assertEquals(helper.getAtomSpec(atomSpec, AtomSpecType.RESIDUE_ONLY),
+ "#0:21.A|#1:21.B");
/*
* H colour is #60609f, seq1.2 mapped to structure 0 residue 22
Color hColor = new Color(0x60609f);
atomSpec = colours.get(hColor);
assertNotNull(atomSpec);
- assertEquals(helper.getAtomSpec(atomSpec, false), "#0:22.A");
+ assertEquals(helper.getAtomSpec(atomSpec, AtomSpecType.RESIDUE_ONLY),
+ "#0:22.A");
/*
* V colour is #ffff00, seq2.2 mapped to structure 1 residue 22
Color vColor = new Color(0xffff00);
atomSpec = colours.get(vColor);
assertNotNull(atomSpec);
- assertEquals(helper.getAtomSpec(atomSpec, false), "#1:22.B");
+ assertEquals(helper.getAtomSpec(atomSpec, AtomSpecType.RESIDUE_ONLY),
+ "#1:22.B");
/*
* hidden columns are Gray (128, 128, 128)
Color gray = new Color(128, 128, 128);
atomSpec = colours.get(gray);
assertNotNull(atomSpec);
- assertEquals(helper.getAtomSpec(atomSpec, false), "#0:23-25.A|#1:23-25.B");
+ assertEquals(helper.getAtomSpec(atomSpec, AtomSpecType.RESIDUE_ONLY),
+ "#0:23-25.A|#1:23-25.B");
/*
* S and G are both coloured #4949b6, structure residues 26-30
Color sgColour = new Color(0x4949b6);
atomSpec = colours.get(sgColour);
assertNotNull(atomSpec);
- assertEquals(helper.getAtomSpec(atomSpec, false),
+ assertEquals(helper.getAtomSpec(atomSpec, AtomSpecType.RESIDUE_ONLY),
"#0:26-30.A|#1:26-30.B");
}
}
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertSame;
-import jalview.gui.JvOptionPane;
+
import java.awt.Color;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
+import jalview.gui.JvOptionPane;
-
public class ColorUtilsTest
{
/*
* value two-thirds of the way between min and max
*/
- col = ColorUtils.getGraduatedColour(30f, 10f, minColour, 40f,
- maxColour);
+ col = ColorUtils
+ .getGraduatedColour(30f, 10f, minColour, 40f, maxColour);
assertEquals(153, col.getRed());
// Color constructor rounds float value to nearest int
assertEquals(167, col.getGreen());
/*
* value = min
*/
- col = ColorUtils.getGraduatedColour(10f, 10f, minColour, 30f,
- maxColour);
+ col = ColorUtils
+ .getGraduatedColour(10f, 10f, minColour, 30f, maxColour);
assertEquals(minColour, col);
/*
* value = max
*/
- col = ColorUtils.getGraduatedColour(30f, 10f, minColour, 30f,
- maxColour);
+ col = ColorUtils
+ .getGraduatedColour(30f, 10f, minColour, 30f, maxColour);
assertEquals(maxColour, col);
/*
/*
* value > max
*/
- col = ColorUtils.getGraduatedColour(40f, 10f, minColour, 30f,
- maxColour);
+ col = ColorUtils
+ .getGraduatedColour(40f, 10f, minColour, 30f, maxColour);
assertEquals(maxColour, col);
/*
* min = max
*/
- col = ColorUtils.getGraduatedColour(40f, 10f, minColour, 10f,
- maxColour);
+ col = ColorUtils
+ .getGraduatedColour(40f, 10f, minColour, 10f, maxColour);
assertEquals(minColour, col);
}
*/
assertNull(ColorUtils.parseColourString(null));
assertNull(ColorUtils.parseColourString("rubbish"));
- assertNull(ColorUtils.parseColourString("-1"));
- assertNull(ColorUtils.parseColourString(String
- .valueOf(Integer.MAX_VALUE)));
++ // from 2.11.2
+ assertEquals(Color.WHITE, ColorUtils.parseColourString("-1"));
+ assertNull(ColorUtils
+ .parseColourString(String.valueOf(Integer.MAX_VALUE)));
assertNull(ColorUtils.parseColourString("100,200,300")); // out of range
assertNull(ColorUtils.parseColourString("100,200")); // too few
assertNull(ColorUtils.parseColourString("100,200,100,200")); // too many
}
@Test(groups = "Functional")
- public void testGetAWTColorFromName()
- {
+ public void testGetAWTColorFromName() {
assertEquals(Color.white, ColorUtils.getAWTColorFromName("white"));
assertEquals(Color.white, ColorUtils.getAWTColorFromName("White"));
assertEquals(Color.white, ColorUtils.getAWTColorFromName("WHITE"));
public void testCreateColourFromName()
{
assertEquals(Color.white, ColorUtils.createColourFromName(null));
- assertEquals(new Color(20, 20, 20),
- ColorUtils.createColourFromName(""));
+ assertEquals(new Color(20, 20, 20), ColorUtils.createColourFromName(""));
assertEquals(new Color(98, 131, 171),
ColorUtils.createColourFromName("None")); // no special treatment!
assertEquals(new Color(123, 211, 122),
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.gui.JvOptionPane;
public class MapListTest
@BeforeClass(alwaysRun = true)
public void setUp()
{
- Cache.initLogger();
+ Console.initLogger();
}
@BeforeClass(alwaysRun = true)
* no overlap
*/
assertNull(ml.locateInFrom(0, 0));
-
+
}
/**
assertEquals("[10, 10, 12, 12, 14, 14]",
Arrays.toString(ml.locateInFrom(3, 3)));
assertEquals("[16, 18]", Arrays.toString(ml.locateInFrom(4, 4)));
-
+
/*
* codons at 11-16, 21-26, 31-36 mapped to peptide positions 1, 3-4, 6-8
*/
}
/**
+ * Tests for method that locates the overlap of the ranges in the 'from' map
+ * for given range in the 'to' map
+ */
+ @Test(groups = { "Functional" })
+ public void testGetOverlapsInFrom_withIntrons()
+ {
+ /*
+ * Exons at positions [2, 3, 5] [6, 7, 9] [10, 12, 14] [16, 17, 18] i.e.
+ * 2-3, 5-7, 9-10, 12-12, 14-14, 16-18
+ */
+ int[] codons = { 2, 3, 5, 7, 9, 10, 12, 12, 14, 14, 16, 18 };
+ int[] protein = { 11, 14 };
+ MapList ml = new MapList(codons, protein, 3, 1);
+
+ assertEquals("[2, 3, 5, 5]",
+ Arrays.toString(ml.getOverlapsInFrom(11, 11)));
+ assertEquals("[2, 3, 5, 7, 9, 9]",
+ Arrays.toString(ml.getOverlapsInFrom(11, 12)));
+ // out of range 5' :
+ assertEquals("[2, 3, 5, 7, 9, 9]",
+ Arrays.toString(ml.getOverlapsInFrom(8, 12)));
+ // out of range 3' :
+ assertEquals("[10, 10, 12, 12, 14, 14, 16, 18]",
+ Arrays.toString(ml.getOverlapsInFrom(13, 16)));
+ // out of range both :
+ assertEquals("[2, 3, 5, 7, 9, 10, 12, 12, 14, 14, 16, 18]",
+ Arrays.toString(ml.getOverlapsInFrom(1, 16)));
+ // no overlap:
+ assertNull(ml.getOverlapsInFrom(20, 25));
+ }
+
+ /**
+ * Tests for method that locates the overlap of the ranges in the 'to' map for
+ * given range in the 'from' map
+ */
+ @Test(groups = { "Functional" })
+ public void testGetOverlapsInTo_withIntrons()
+ {
+ /*
+ * Exons at positions [2, 3, 5] [6, 7, 9] [10, 12, 14] [17, 18, 19] i.e.
+ * 2-3, 5-7, 9-10, 12-12, 14-14, 17-19
+ */
+ int[] codons = { 2, 3, 5, 7, 9, 10, 12, 12, 14, 14, 17, 19 };
+ /*
+ * Mapped proteins at positions 1, 3, 4, 6 in the sequence
+ */
+ int[] protein = { 1, 1, 3, 4, 6, 6 };
+ MapList ml = new MapList(codons, protein, 3, 1);
+
+ /*
+ * Can't map from an unmapped position
+ */
+ assertNull(ml.getOverlapsInTo(1, 1));
+ assertNull(ml.getOverlapsInTo(4, 4));
+ assertNull(ml.getOverlapsInTo(15, 16));
+
+ /*
+ * nor from a range that includes no mapped position (exon)
+ */
+ assertNull(ml.getOverlapsInTo(15, 16));
+
+ // end of codon 1 maps to first peptide
+ assertEquals("[1, 1]", Arrays.toString(ml.getOverlapsInTo(2, 2)));
+ // end of codon 1 and start of codon 2 maps to first 2 peptides
+ assertEquals("[1, 1, 3, 3]", Arrays.toString(ml.getOverlapsInTo(3, 7)));
+
+ // range overlaps 5' end of dna:
+ assertEquals("[1, 1, 3, 3]", Arrays.toString(ml.getOverlapsInTo(1, 6)));
+ assertEquals("[1, 1, 3, 3]", Arrays.toString(ml.getOverlapsInTo(1, 8)));
+
+ // range overlaps 3' end of dna:
+ assertEquals("[6, 6]", Arrays.toString(ml.getOverlapsInTo(17, 24)));
+ assertEquals("[6, 6]", Arrays.toString(ml.getOverlapsInTo(16, 24)));
+
+ // dna positions 8, 11 are intron but include end of exon 2 and start of
+ // exon 3
+ assertEquals("[3, 4]", Arrays.toString(ml.getOverlapsInTo(8, 11)));
+ }
+
+ /**
* Tests for method that locates ranges in the 'to' map for given range in the
* 'from' map.
*/
*/
assertEquals("[1, 4]", Arrays.toString(ml.locateInTo(1, 13)));
assertEquals("[1, 1]", Arrays.toString(ml.locateInTo(-1, 2)));
-
+
/*
* no overlap
*/
assertEquals("[1, 1]", Arrays.toString(ml.locateInTo(1, 2)));
assertEquals("[1, 1]", Arrays.toString(ml.locateInTo(1, 4)));
assertEquals("[1, 1]", Arrays.toString(ml.locateInTo(2, 4)));
-
+
/*
* no overlap
*/
assertEquals("[ [11, 16] ] 1:3 to [ [72, 53] ]", ml.toString());
}
- @Test(groups = "Functional")
- public void testAddRange()
- {
- int[] range = { 1, 5 };
- List<int[]> ranges = new ArrayList<>();
-
- // add to empty list:
- MapList.addRange(range, ranges);
- assertEquals(1, ranges.size());
- assertSame(range, ranges.get(0));
-
- // extend contiguous (same position):
- MapList.addRange(new int[] { 5, 10 }, ranges);
- assertEquals(1, ranges.size());
- assertEquals(1, ranges.get(0)[0]);
- assertEquals(10, ranges.get(0)[1]);
-
- // extend contiguous (next position):
- MapList.addRange(new int[] { 11, 15 }, ranges);
- assertEquals(1, ranges.size());
- assertEquals(1, ranges.get(0)[0]);
- assertEquals(15, ranges.get(0)[1]);
-
- // change direction: range is not merged:
- MapList.addRange(new int[] { 16, 10 }, ranges);
- assertEquals(2, ranges.size());
- assertEquals(16, ranges.get(1)[0]);
- assertEquals(10, ranges.get(1)[1]);
-
- // extend reverse contiguous (same position):
- MapList.addRange(new int[] { 10, 8 }, ranges);
- assertEquals(2, ranges.size());
- assertEquals(16, ranges.get(1)[0]);
- assertEquals(8, ranges.get(1)[1]);
-
- // extend reverse contiguous (next position):
- MapList.addRange(new int[] { 7, 6 }, ranges);
- assertEquals(2, ranges.size());
- assertEquals(16, ranges.get(1)[0]);
- assertEquals(6, ranges.get(1)[1]);
-
- // change direction: range is not merged:
- MapList.addRange(new int[] { 6, 9 }, ranges);
- assertEquals(3, ranges.size());
- assertEquals(6, ranges.get(2)[0]);
- assertEquals(9, ranges.get(2)[1]);
-
- // not contiguous: not merged
- MapList.addRange(new int[] { 11, 12 }, ranges);
- assertEquals(4, ranges.size());
- assertEquals(11, ranges.get(3)[0]);
- assertEquals(12, ranges.get(3)[1]);
- }
-
/**
* Check state after construction
*/
ranges.clear();
ranges.add(new int[] { 10, 30 });
ranges.add(new int[] { 15, 25 });
+
merged = MapList.coalesceRanges(ranges);
assertEquals(2, merged.size());
assertArrayEquals(new int[] { 10, 30 }, merged.get(0));
toRanges = compound.getToRanges();
assertEquals(2, toRanges.size());
assertArrayEquals(new int[] { 931, 901 }, toRanges.get(0));
- assertArrayEquals(new int[] { 600, 582}, toRanges.get(1));
+ assertArrayEquals(new int[] { 600, 582 }, toRanges.get(1));
/*
* 1:1 plus 1:3 should result in 1:3
* no overlap
*/
assertNull(ml.locateInTo(0, 0));
-
+
/*
* partial overlap
*/
ml = new MapList(gene, cds, 1, 1);
assertEquals("[13203, 13204]",
Arrays.toString(ml.locateInTo(13468, 13468)));
-
+
/*
* gene to protein
* the base at 13468 is in the codon for 4401N and also 4402R
public void testAddOffsetPositions()
{
List<int[]> mapped = new ArrayList<>();
- int[] range = new int[] {10, 20};
+ int[] range = new int[] { 10, 20 };
BitSet offsets = new BitSet();
MapList.addOffsetPositions(mapped, 0, range, offsets);
assertArrayEquals(new int[] { 14, 13 }, mapped.get(1));
assertArrayEquals(new int[] { 10, 10 }, mapped.get(2));
}
-
+
@Test(groups = { "Functional" })
public void testGetPositionsForOffsets()
{
BitSet offsets = new BitSet();
List<int[]> mapped = MapList.getPositionsForOffsets(ranges, offsets);
assertTrue(mapped.isEmpty()); // no ranges and no offsets!
-
+
offsets.set(5, 1000);
mapped = MapList.getPositionsForOffsets(ranges, offsets);
assertTrue(mapped.isEmpty()); // no ranges
-
+
/*
* one range with overlap of offsets
*/
- ranges.add(new int[] {15, 25});
+ ranges.add(new int[] { 15, 25 });
mapped = MapList.getPositionsForOffsets(ranges, offsets);
assertEquals(1, mapped.size());
- assertArrayEquals(new int[] {20, 25}, mapped.get(0));
-
+ assertArrayEquals(new int[] { 20, 25 }, mapped.get(0));
+
/*
* two ranges
*/
- ranges.add(new int[] {300, 320});
+ ranges.add(new int[] { 300, 320 });
mapped = MapList.getPositionsForOffsets(ranges, offsets);
assertEquals(2, mapped.size());
- assertArrayEquals(new int[] {20, 25}, mapped.get(0));
- assertArrayEquals(new int[] {300, 320}, mapped.get(1));
-
+ assertArrayEquals(new int[] { 20, 25 }, mapped.get(0));
+ assertArrayEquals(new int[] { 300, 320 }, mapped.get(1));
+
/*
* boundary case - right end of first range overlaps
*/
offsets.set(10);
mapped = MapList.getPositionsForOffsets(ranges, offsets);
assertEquals(1, mapped.size());
- assertArrayEquals(new int[] {25, 25}, mapped.get(0));
-
+ assertArrayEquals(new int[] { 25, 25 }, mapped.get(0));
+
/*
* boundary case - left end of second range overlaps
*/
offsets.set(11);
mapped = MapList.getPositionsForOffsets(ranges, offsets);
assertEquals(2, mapped.size());
- assertArrayEquals(new int[] {25, 25}, mapped.get(0));
- assertArrayEquals(new int[] {300, 300}, mapped.get(1));
-
+ assertArrayEquals(new int[] { 25, 25 }, mapped.get(0));
+ assertArrayEquals(new int[] { 300, 300 }, mapped.get(1));
+
/*
* offsets into a circular range are reported in
* the order in which they are traversed
*/
ranges.clear();
- ranges.add(new int[] {100, 150});
- ranges.add(new int[] {60, 80});
+ ranges.add(new int[] { 100, 150 });
+ ranges.add(new int[] { 60, 80 });
offsets.clear();
offsets.set(45, 55); // sets bits 45 to 54
mapped = MapList.getPositionsForOffsets(ranges, offsets);
assertEquals(2, mapped.size());
- assertArrayEquals(new int[] {145, 150}, mapped.get(0)); // offsets 45-50
- assertArrayEquals(new int[] {60, 63}, mapped.get(1)); // offsets 51-54
+ assertArrayEquals(new int[] { 145, 150 }, mapped.get(0)); // offsets 45-50
+ assertArrayEquals(new int[] { 60, 63 }, mapped.get(1)); // offsets 51-54
/*
* reverse range overlap is reported with start < end
*/
ranges.clear();
- ranges.add(new int[] {4321, 4000});
+ ranges.add(new int[] { 4321, 4000 });
offsets.clear();
offsets.set(20, 22); // sets bits 20 and 21
offsets.set(30);
mapped = MapList.getPositionsForOffsets(ranges, offsets);
assertEquals(2, mapped.size());
- assertArrayEquals(new int[] {4301, 4300}, mapped.get(0));
- assertArrayEquals(new int[] {4291, 4291}, mapped.get(1));
+ assertArrayEquals(new int[] { 4301, 4300 }, mapped.get(0));
+ assertArrayEquals(new int[] { 4291, 4291 }, mapped.get(1));
}
-
+
@Test(groups = { "Functional" })
public void testGetMappedOffsetsForPositions()
{
* start by verifying the examples in the method's Javadoc!
*/
List<int[]> ranges = new ArrayList<>();
- ranges.add(new int[] {10, 20});
- ranges.add(new int[] {31, 40});
- BitSet overlaps = MapList.getMappedOffsetsForPositions(1, 9, ranges, 1, 1);
+ ranges.add(new int[] { 10, 20 });
+ ranges.add(new int[] { 31, 40 });
+ BitSet overlaps = MapList.getMappedOffsetsForPositions(1, 9, ranges, 1,
+ 1);
assertTrue(overlaps.isEmpty());
overlaps = MapList.getMappedOffsetsForPositions(1, 11, ranges, 1, 1);
assertEquals(2, overlaps.cardinality());
assertTrue(overlaps.get(1));
overlaps = MapList.getMappedOffsetsForPositions(15, 35, ranges, 1, 1);
assertEquals(11, overlaps.cardinality());
- for (int i = 5 ; i <= 11 ; i++)
+ for (int i = 5; i <= 11; i++)
{
assertTrue(overlaps.get(i));
}
-
+
ranges.clear();
- ranges.add(new int[] {1, 200});
+ ranges.add(new int[] { 1, 200 });
overlaps = MapList.getMappedOffsetsForPositions(9, 9, ranges, 1, 3);
assertEquals(3, overlaps.cardinality());
assertTrue(overlaps.get(24));
assertTrue(overlaps.get(25));
assertTrue(overlaps.get(26));
-
+
ranges.clear();
- ranges.add(new int[] {101, 150});
- ranges.add(new int[] {171, 180});
+ ranges.add(new int[] { 101, 150 });
+ ranges.add(new int[] { 171, 180 });
overlaps = MapList.getMappedOffsetsForPositions(101, 102, ranges, 3, 1);
assertEquals(1, overlaps.cardinality());
assertTrue(overlaps.get(0));
overlaps = MapList.getMappedOffsetsForPositions(150, 171, ranges, 3, 1);
assertEquals(1, overlaps.cardinality());
assertTrue(overlaps.get(16));
-
+
ranges.clear();
- ranges.add(new int[] {101, 150});
- ranges.add(new int[] {21, 30});
+ ranges.add(new int[] { 101, 150 });
+ ranges.add(new int[] { 21, 30 });
overlaps = MapList.getMappedOffsetsForPositions(24, 40, ranges, 3, 1);
assertEquals(3, overlaps.cardinality());
assertTrue(overlaps.get(17));
assertTrue(overlaps.get(18));
assertTrue(overlaps.get(19));
-
+
/*
* reverse range 1:1 (e.g. reverse strand gene to transcript)
*/
ranges.clear();
- ranges.add(new int[] {20, 10});
+ ranges.add(new int[] { 20, 10 });
overlaps = MapList.getMappedOffsetsForPositions(12, 13, ranges, 1, 1);
assertEquals(2, overlaps.cardinality());
assertTrue(overlaps.get(7));
assertTrue(overlaps.get(8));
-
+
/*
* reverse range 3:1 (e.g. reverse strand gene to peptide)
* from EMBL:J03321 to P0CE20
*/
ranges.clear();
- ranges.add(new int[] {1480, 488});
- overlaps = MapList.getMappedOffsetsForPositions(1460, 1460, ranges, 3, 1);
+ ranges.add(new int[] { 1480, 488 });
+ overlaps = MapList.getMappedOffsetsForPositions(1460, 1460, ranges, 3,
+ 1);
// 1460 is the end of the 7th codon
assertEquals(1, overlaps.cardinality());
assertTrue(overlaps.get(6));
// add one base (part codon)
- overlaps = MapList.getMappedOffsetsForPositions(1459, 1460, ranges, 3, 1);
+ overlaps = MapList.getMappedOffsetsForPositions(1459, 1460, ranges, 3,
+ 1);
assertEquals(2, overlaps.cardinality());
assertTrue(overlaps.get(6));
assertTrue(overlaps.get(7));
// add second base (part codon)
- overlaps = MapList.getMappedOffsetsForPositions(1458, 1460, ranges, 3, 1);
+ overlaps = MapList.getMappedOffsetsForPositions(1458, 1460, ranges, 3,
+ 1);
assertEquals(2, overlaps.cardinality());
assertTrue(overlaps.get(6));
assertTrue(overlaps.get(7));
// add third base (whole codon)
- overlaps = MapList.getMappedOffsetsForPositions(1457, 1460, ranges, 3, 1);
+ overlaps = MapList.getMappedOffsetsForPositions(1457, 1460, ranges, 3,
+ 1);
assertEquals(2, overlaps.cardinality());
assertTrue(overlaps.get(6));
assertTrue(overlaps.get(7));
// add one more base (part codon)
- overlaps = MapList.getMappedOffsetsForPositions(1456, 1460, ranges, 3, 1);
+ overlaps = MapList.getMappedOffsetsForPositions(1456, 1460, ranges, 3,
+ 1);
assertEquals(3, overlaps.cardinality());
assertTrue(overlaps.get(6));
assertTrue(overlaps.get(7));
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
+ import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertSame;
import static org.testng.AssertJUnit.assertTrue;
- import static org.testng.AssertJUnit.fail;
+ import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals;
import java.awt.Color;
import java.io.IOException;
import org.testng.annotations.Test;
import jalview.api.AlignViewportI;
- import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.commands.EditCommand;
import jalview.commands.EditCommand.Action;
import jalview.commands.EditCommand.Edit;
import jalview.io.FileFormatI;
import jalview.io.FormatAdapter;
+
public class MappingUtilsTest
{
@BeforeClass(alwaysRun = true)
public void setUp()
{
- Cache.initLogger();
+ Console.initLogger();
}
@BeforeClass(alwaysRun = true)
protein.setCodonFrames(acfList);
/*
- * Select Seq1 and Seq3 in the protein (startRes=endRes=0)
+ * Select Seq1 and Seq3 in the protein
*/
SequenceGroup sg = new SequenceGroup();
sg.setColourText(true);
sg.setOutlineColour(Color.LIGHT_GRAY);
sg.addSequence(protein.getSequenceAt(0), false);
sg.addSequence(protein.getSequenceAt(2), false);
+ sg.setEndRes(protein.getWidth() - 1);
/*
* Verify the mapped sequence group in dna
assertSame(cdna.getSequenceAt(0), mappedGroup.getSequences().get(0));
assertSame(cdna.getSequenceAt(2), mappedGroup.getSequences().get(1));
assertEquals(0, mappedGroup.getStartRes());
- assertEquals(2, mappedGroup.getEndRes());
+ assertEquals(2, mappedGroup.getEndRes()); // 3 columns (1 codon)
/*
* Verify mapping sequence group from dna to protein
}
@Test(groups = "Functional")
- public void testListToArray()
+ public void testFindOverlap()
{
List<int[]> ranges = new ArrayList<>();
+ ranges.add(new int[] { 4, 8 });
+ ranges.add(new int[] { 10, 12 });
+ ranges.add(new int[] { 16, 19 });
+
+ int[] overlap = MappingUtils.findOverlap(ranges, 5, 13);
+ assertArrayEquals(overlap, new int[] { 5, 12 });
+ overlap = MappingUtils.findOverlap(ranges, -100, 100);
+ assertArrayEquals(overlap, new int[] { 4, 19 });
+ overlap = MappingUtils.findOverlap(ranges, 7, 17);
+ assertArrayEquals(overlap, new int[] { 7, 17 });
+ overlap = MappingUtils.findOverlap(ranges, 13, 15);
+ assertNull(overlap);
+ }
- int[] result = MappingUtils.rangeListToArray(ranges);
- assertEquals(result.length, 0);
- ranges.add(new int[] { 24, 12 });
- result = MappingUtils.rangeListToArray(ranges);
- assertEquals(result.length, 2);
- assertEquals(result[0], 24);
- assertEquals(result[1], 12);
- ranges.add(new int[] { -7, 30 });
- result = MappingUtils.rangeListToArray(ranges);
- assertEquals(result.length, 4);
- assertEquals(result[0], 24);
- assertEquals(result[1], 12);
- assertEquals(result[2], -7);
- assertEquals(result[3], 30);
- try
- {
- MappingUtils.rangeListToArray(null);
- fail("Expected exception");
- } catch (NullPointerException e)
- {
- // expected
- }
+ /**
+ * Test mapping a sequence group where sequences in and outside the group
+ * share a dataset sequence (e.g. alternative CDS for the same gene)
+ * <p>
+ * This scenario doesn't arise after JAL-3763 changes, but test left as still
+ * valid
+ *
+ * @throws IOException
+ */
+ @Test(groups = { "Functional" })
+ public void testMapSequenceGroup_sharedDataset() throws IOException
+ {
+ /*
+ * Set up dna and protein Seq1/2/3 with mappings (held on the protein
+ * viewport). CDS sequences share the same 'gene' dataset sequence.
+ */
+ SequenceI dna = new Sequence("dna", "aaatttgggcccaaatttgggccc");
+ SequenceI cds1 = new Sequence("cds1/1-6", "aaattt");
+ SequenceI cds2 = new Sequence("cds1/4-9", "tttggg");
+ SequenceI cds3 = new Sequence("cds1/19-24", "gggccc");
+
+ cds1.setDatasetSequence(dna);
+ cds2.setDatasetSequence(dna);
+ cds3.setDatasetSequence(dna);
+
+ SequenceI pep1 = new Sequence("pep1", "KF");
+ SequenceI pep2 = new Sequence("pep2", "FG");
+ SequenceI pep3 = new Sequence("pep3", "GP");
+ pep1.createDatasetSequence();
+ pep2.createDatasetSequence();
+ pep3.createDatasetSequence();
+
+ /*
+ * add mappings from coding positions of dna to respective peptides
+ */
+ AlignedCodonFrame acf = new AlignedCodonFrame();
+ acf.addMap(dna, pep1,
+ new MapList(new int[]
+ { 1, 6 }, new int[] { 1, 2 }, 3, 1));
+ acf.addMap(dna, pep2,
+ new MapList(new int[]
+ { 4, 9 }, new int[] { 1, 2 }, 3, 1));
+ acf.addMap(dna, pep3,
+ new MapList(new int[]
+ { 19, 24 }, new int[] { 1, 2 }, 3, 1));
+
+ List<AlignedCodonFrame> acfList = Arrays
+ .asList(new AlignedCodonFrame[]
+ { acf });
+
+ AlignmentI cdna = new Alignment(new SequenceI[] { cds1, cds2, cds3 });
+ AlignmentI protein = new Alignment(
+ new SequenceI[]
+ { pep1, pep2, pep3 });
+ AlignViewportI cdnaView = new AlignViewport(cdna);
+ AlignViewportI peptideView = new AlignViewport(protein);
+ protein.setCodonFrames(acfList);
+
+ /*
+ * Select pep1 and pep3 in the protein alignment
+ */
+ SequenceGroup sg = new SequenceGroup();
+ sg.setColourText(true);
+ sg.setIdColour(Color.GREEN);
+ sg.setOutlineColour(Color.LIGHT_GRAY);
+ sg.addSequence(pep1, false);
+ sg.addSequence(pep3, false);
+ sg.setEndRes(protein.getWidth() - 1);
+
+ /*
+ * Verify the mapped sequence group in dna is cds1 and cds3
+ */
+ SequenceGroup mappedGroup = MappingUtils.mapSequenceGroup(sg,
+ peptideView, cdnaView);
+ assertTrue(mappedGroup.getColourText());
+ assertSame(sg.getIdColour(), mappedGroup.getIdColour());
+ assertSame(sg.getOutlineColour(), mappedGroup.getOutlineColour());
+ assertEquals(2, mappedGroup.getSequences().size());
+ assertSame(cds1, mappedGroup.getSequences().get(0));
+ assertSame(cds3, mappedGroup.getSequences().get(1));
+ // columns 1-6 selected (0-5 base zero)
+ assertEquals(0, mappedGroup.getStartRes());
+ assertEquals(5, mappedGroup.getEndRes());
+
+ /*
+ * Select mapping sequence group from dna to protein
+ */
+ sg.clear();
+ sg.addSequence(cds2, false);
+ sg.addSequence(cds1, false);
+ sg.setStartRes(0);
+ sg.setEndRes(cdna.getWidth() - 1);
+ mappedGroup = MappingUtils.mapSequenceGroup(sg, cdnaView, peptideView);
+ assertTrue(mappedGroup.getColourText());
+ assertSame(sg.getIdColour(), mappedGroup.getIdColour());
+ assertSame(sg.getOutlineColour(), mappedGroup.getOutlineColour());
+ assertEquals(2, mappedGroup.getSequences().size());
+ assertSame(protein.getSequenceAt(1), mappedGroup.getSequences().get(0));
+ assertSame(protein.getSequenceAt(0), mappedGroup.getSequences().get(1));
+ assertEquals(0, mappedGroup.getStartRes());
+ assertEquals(1, mappedGroup.getEndRes()); // two columns
}
+
+ // new for 2.12
+ @Test(groups = "Functional")
+ public void testAddRange()
+ {
+ int[] range = { 1, 5 };
+ List<int[]> ranges = new ArrayList<>();
+
+ // add to empty list:
+ MappingUtils.addRange(range, ranges);
+ assertEquals(1, ranges.size());
+ assertSame(range, ranges.get(0));
+
+ // extend contiguous (same position):
+ MappingUtils.addRange(new int[] { 5, 10 }, ranges);
+ assertEquals(1, ranges.size());
+ assertEquals(1, ranges.get(0)[0]);
+ assertEquals(10, ranges.get(0)[1]);
+
+ // extend contiguous (next position):
+ MappingUtils.addRange(new int[] { 11, 15 }, ranges);
+ assertEquals(1, ranges.size());
+ assertEquals(1, ranges.get(0)[0]);
+ assertEquals(15, ranges.get(0)[1]);
+
+ // change direction: range is not merged:
+ MappingUtils.addRange(new int[] { 16, 10 }, ranges);
+ assertEquals(2, ranges.size());
+ assertEquals(16, ranges.get(1)[0]);
+ assertEquals(10, ranges.get(1)[1]);
+
+ // extend reverse contiguous (same position):
+ MappingUtils.addRange(new int[] { 10, 8 }, ranges);
+ assertEquals(2, ranges.size());
+ assertEquals(16, ranges.get(1)[0]);
+ assertEquals(8, ranges.get(1)[1]);
+
+ // extend reverse contiguous (next position):
+ MappingUtils.addRange(new int[] { 7, 6 }, ranges);
+ assertEquals(2, ranges.size());
+ assertEquals(16, ranges.get(1)[0]);
+ assertEquals(6, ranges.get(1)[1]);
+
+ // change direction: range is not merged:
+ MappingUtils.addRange(new int[] { 6, 9 }, ranges);
+ assertEquals(3, ranges.size());
+ assertEquals(6, ranges.get(2)[0]);
+ assertEquals(9, ranges.get(2)[1]);
+
+ // not contiguous: not merged
+ MappingUtils.addRange(new int[] { 11, 12 }, ranges);
+ assertEquals(4, ranges.size());
+ assertEquals(11, ranges.get(3)[0]);
+ assertEquals(12, ranges.get(3)[1]);
+ }
}
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
+import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
{
assertNull(Platform.escapeBackslashes(null));
assertEquals(Platform.escapeBackslashes("hello world"), "hello world");
- assertEquals(Platform.escapeBackslashes("hello\\world"), "hello\\\\world");
+ assertEquals(Platform.escapeBackslashes("hello\\world"),
+ "hello\\\\world");
}
+
+ @Test(groups = { "Functional" })
+ public void getLeadingIntegerFromString()
+ {
+ Assert.assertEquals(Platform.getLeadingIntegerValue("1234abcd", -1),
+ 1234);
+ Assert.assertEquals(Platform.getLeadingIntegerValue("1234", -1), 1234);
+ Assert.assertEquals(Platform.getLeadingIntegerValue("abcd", -1), -1);
+ Assert.assertEquals(Platform.getLeadingIntegerValue("abcd1234", -1),
+ -1);
+ Assert.assertEquals(Platform.getLeadingIntegerValue("None", -1), -1);
+ Assert.assertEquals(Platform.getLeadingIntegerValue("Null", -1), -1);
+ }
}
char[] c1 = "ABC".toCharArray();
// delete second position
- assertTrue(Arrays.equals(new char[] { 'A', 'C' },
- StringUtils.deleteChars(c1, 1, 2)));
+ assertTrue(
+ Arrays.equals(new char[]
+ { 'A', 'C' }, StringUtils.deleteChars(c1, 1, 2)));
// delete positions 1 and 2
- assertTrue(Arrays.equals(new char[] { 'C' },
- StringUtils.deleteChars(c1, 0, 2)));
+ assertTrue(
+ Arrays.equals(new char[]
+ { 'C' }, StringUtils.deleteChars(c1, 0, 2)));
// delete positions 1-3
assertTrue(Arrays.equals(new char[] {},
StringUtils.deleteChars(c1, 0, 3)));
// delete position 3
- assertTrue(Arrays.equals(new char[] { 'A', 'B' },
- StringUtils.deleteChars(c1, 2, 3)));
+ assertTrue(
+ Arrays.equals(new char[]
+ { 'A', 'B' }, StringUtils.deleteChars(c1, 2, 3)));
// out of range deletion is ignore
assertTrue(Arrays.equals(c1, StringUtils.deleteChars(c1, 3, 4)));
}
@Test(groups = { "Functional" })
- public void testGetLastToken()
- {
- assertNull(StringUtils.getLastToken(null, null));
- assertNull(StringUtils.getLastToken(null, "/"));
- assertEquals("a", StringUtils.getLastToken("a", null));
-
- assertEquals("abc", StringUtils.getLastToken("abc", "/"));
- assertEquals("c", StringUtils.getLastToken("abc", "b"));
- assertEquals("file1.dat", StringUtils.getLastToken(
- "file://localhost:8080/data/examples/file1.dat", "/"));
- }
-
- @Test(groups = { "Functional" })
public void testSeparatorListToArray()
{
String[] result = StringUtils.separatorListToArray(
* String delimited by | containing a quoted | (should not be treated as
* delimiter)
*/
- assertEquals("[abc='|'d, ef, g]", Arrays.toString(StringUtils
- .separatorListToArray("abc='|'d|ef|g", "|")));
+ assertEquals("[abc='|'d, ef, g]", Arrays.toString(
+ StringUtils.separatorListToArray("abc='|'d|ef|g", "|")));
}
@Test(groups = { "Functional" })
assertEquals("*", StringUtils.arrayToSeparatorList(null, "*"));
assertEquals("*",
StringUtils.arrayToSeparatorList(new String[] {}, "*"));
- assertEquals(
- "a*bc*cde",
- StringUtils.arrayToSeparatorList(new String[] { "a", "bc",
- "cde" }, "*"));
- assertEquals(
- "a*cde",
- StringUtils.arrayToSeparatorList(new String[] { "a", null,
- "cde" }, "*"));
- assertEquals("a**cde", StringUtils.arrayToSeparatorList(new String[] {
- "a", "", "cde" }, "*"));
+ assertEquals("a*bc*cde",
+ StringUtils.arrayToSeparatorList(new String[]
+ { "a", "bc", "cde" }, "*"));
+ assertEquals("a*cde",
+ StringUtils.arrayToSeparatorList(new String[]
+ { "a", null, "cde" }, "*"));
+ assertEquals("a**cde",
+ StringUtils.arrayToSeparatorList(new String[]
+ { "a", "", "cde" }, "*"));
// delimiter within token is not (yet) escaped
- assertEquals("a*b*c*cde", StringUtils.arrayToSeparatorList(new String[]
- { "a", "b*c", "cde" }, "*"));
+ assertEquals("a*b*c*cde",
+ StringUtils.arrayToSeparatorList(new String[]
+ { "a", "b*c", "cde" }, "*"));
}
@Test(groups = { "Functional" })
assertEquals("now", StringUtils.listToDelimitedString(list, ";"));
list.add("is");
assertEquals("now;is", StringUtils.listToDelimitedString(list, ";"));
- assertEquals("now ; is", StringUtils.listToDelimitedString(list, " ; "));
+ assertEquals("now ; is",
+ StringUtils.listToDelimitedString(list, " ; "));
list.add("the");
list.add("winter");
list.add("of");
assertEquals(-1, StringUtils.compareVersions("2.8.3", "2.9.2"));
assertEquals(-1, StringUtils.compareVersions("2.8", "2.8.3"));
assertEquals(-1, StringUtils.compareVersions("2.8.3", "2.8.3b1", "b"));
- assertEquals(-1, StringUtils.compareVersions("2.8.3b1", "2.8.3b2", "b"));
+ assertEquals(-1,
+ StringUtils.compareVersions("2.8.3b1", "2.8.3b2", "b"));
assertEquals(-1, StringUtils.compareVersions("2.8", "2.8.0", "b"));
assertEquals(-1, StringUtils.compareVersions("2", "12"));
assertEquals(-1, StringUtils.compareVersions("3.2.4", "3.12.11"));
{
assertNull(StringUtils.stripHtmlTags(null));
assertEquals("", StringUtils.stripHtmlTags(""));
- assertEquals(
- "<a href=\"something\">label</href>",
- StringUtils
- .stripHtmlTags("<html><a href=\"something\">label</href></html>"));
+ assertEquals("<a href=\"something\">label</href>",
+ StringUtils.stripHtmlTags(
+ "<html><a href=\"something\">label</href></html>"));
// if no "<html>" tag, < and > get html-encoded (not sure why)
assertEquals("<a href=\"something\">label</href>",
- StringUtils.stripHtmlTags("<a href=\"something\">label</href>"));
+ StringUtils
+ .stripHtmlTags("<a href=\"something\">label</href>"));
// </body> gets removed but not <body> (is this intentional?)
- assertEquals("<body><p>hello",
- StringUtils.stripHtmlTags("<html><body><p>hello</body></html>"));
+ assertEquals("<body><p>hello", StringUtils
+ .stripHtmlTags("<html><body><p>hello</body></html>"));
assertEquals("kdHydro < 12.53",
StringUtils.stripHtmlTags("kdHydro < 12.53"));
{
Cache.loadProperties("test/jalview/io/testProps.jvprops");
// ensure 'add annotation from structure' is selected
- Cache.applicationProperties.setProperty("STRUCT_FROM_PDB",
+ Cache.setPropertyNoSave("STRUCT_FROM_PDB",
Boolean.TRUE.toString());
- Cache.applicationProperties.setProperty("ADD_SS_ANN",
+ Cache.setPropertyNoSave("ADD_SS_ANN",
Boolean.TRUE.toString());
sf = new SequenceFetcher();
@Test(groups = { "Network" }, enabled = true)
public void testRnaSeqRetrieve() throws Exception
{
- Cache.applicationProperties.setProperty("PDB_DOWNLOAD_FORMAT", "PDB");
+ Cache.setPropertyNoSave("PDB_DOWNLOAD_FORMAT", "PDB");
List<DbSourceProxy> sps = sf.getSourceProxy("PDB");
AlignmentI response = sps.get(0).getSequenceRecords("2GIS");
assertTrue(response != null);
// chains in structure have a mapping to data in the structure
List<SequenceFeature> prev = null;
int lastp = -1;
- for (int col = 1; col <= sq.getLength(); col++)
+ for (int col = 1, ns = sq.getLength(); col <= ns; col++)
{
List<SequenceFeature> sf = sq.findFeatures(col, col, "RESNUM");
if (sf.size() != 1)
{
- errors.append(
- str.id + ": " +
- "Expected one feature at column (position): "
- + (col - 1)
- + " (" + sq.findPosition(col - 1) + ")"
- + ": saw "
- + sf.size());
+ errors.append(str.id + ": "
+ + "Expected one feature at column (position): "
+ + (col - 1) + " (" + sq.findPosition(col - 1) + ")"
+ + ": saw " + sf.size());
errors.append("\n");
if (prev != null)
{
+ /*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.ws.dbsources;
import static org.testng.Assert.assertEquals;
{
Cache.loadProperties("test/jalview/io/testProps.jvprops");
// ensure 'add annotation from structure' is selected
- Cache.applicationProperties.setProperty("STRUCT_FROM_PDB",
+ Cache.setPropertyNoSave("STRUCT_FROM_PDB",
Boolean.TRUE.toString());
- Cache.applicationProperties.setProperty("ADD_SS_ANN",
+ Cache.setPropertyNoSave("ADD_SS_ANN",
Boolean.TRUE.toString());
sf = new SequenceFetcher();
protected Object[][] getAccessions()
{
return new Object[][] { { DBRefSource.UNIPROT, "P30419" },
- { DBRefSource.PDB, "1QIP" }, { DBRefSource.EMBL, "X53828" },
+ { DBRefSource.PDB, "1QIP" },
+ { DBRefSource.EMBL, "X53828" },
{ DBRefSource.EMBLCDS, "CAA37824" },
{ DBRefSource.ENSEMBL, "ENSG00000157764" },
{ new EnsemblGenomes().getDbSource(), "DDB_G0283883" },
wantedFields.add(client.getDataColumnByNameOrCode("organism"));
wantedFields.add(client.getDataColumnByNameOrCode("reviewed")); // Status
wantedFields.add(client.getDataColumnByNameOrCode("length"));
-
+
FTSRestRequest request = new FTSRestRequest();
request.setAllowEmptySeq(false);
request.setResponseSize(100);
request.setFieldToSearchBy("Search All");
request.setSearchTerm("metanephrops"); // lobster!
request.setWantedFields(wantedFields);
-
+
FTSRestResponse response;
response = client.executeRequest(request);
assertTrue(response.getNumberOfItemsFound() > 20);
package jalview.ws.gui;
import java.util.Locale;
+
import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.gui.JvOptionPane;
import jalview.gui.WsJobParameters;
import jalview.util.MessageManager;
+import jalview.ws.api.ServiceWithParameters;
import jalview.ws.jabaws.JalviewJabawsTestUtils;
import jalview.ws.jws2.JabaPreset;
import jalview.ws.jws2.Jws2Discoverer;
import jalview.ws.jws2.jabaws2.Jws2Instance;
+import jalview.ws.params.ArgumentI;
+import jalview.ws.params.ParamDatastoreI;
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
/**
* which services to test
*/
- public static List<String> serviceTests = new ArrayList<String>();
+ public static List<String> serviceTests = new ArrayList<>();
/**
* which presets to test for services
*/
- public static List<String> presetTests = new ArrayList<String>();
+ public static List<String> presetTests = new ArrayList<>();
static
{
serviceTests.add("AAConWS".toLowerCase(Locale.ROOT));
public static void setUpBeforeClass() throws Exception
{
Cache.loadProperties("test/jalview/io/testProps.jvprops");
- Cache.initLogger();
- Console.initLogger();
disc = JalviewJabawsTestUtils.getJabawsDiscoverer();
}
public void testJws2Gui()
{
Iterator<String> presetEnum = presetTests.iterator();
- for (Jws2Instance service : disc.getServices())
+ for (ServiceWithParameters _service : disc.getServices())
{
- if (serviceTests.size() == 0 || serviceTests
- .contains(service.serviceType.toLowerCase(Locale.ROOT)))
+ // This will fail for non-jabaws services
+ Jws2Instance service = (Jws2Instance) _service;
+ if (serviceTests.size() == 0
- || serviceTests.contains(service.serviceType.toLowerCase(Locale.ROOT)))
++ || serviceTests.contains(service.getName().toLowerCase(Locale.ROOT)))
{
List<Preset> prl = null;
Preset pr = null;
}
pr = en.next();
}
- WsJobParameters pgui = new WsJobParameters(service,
- new JabaPreset(service, pr));
+ WsJobParameters pgui = new WsJobParameters((ParamDatastoreI) null,
+ service, new JabaPreset(service, pr),
+ (List<ArgumentI>) null);
JFrame jf = new JFrame(MessageManager
.formatMessage("label.ws_parameters_for", new String[]
{ service.getActionText() }));
package jalview.ws.jabaws;
import java.util.Locale;
-
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertTrue;
import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.AlignmentAnnotation;
import jalview.datamodel.AlignmentI;
import jalview.gui.JvOptionPane;
import jalview.io.FileFormat;
import jalview.io.FormatAdapter;
import jalview.io.StockholmFileTest;
-import jalview.ws.jws2.AADisorderClient;
+import jalview.ws.api.ServiceWithParameters;
import jalview.ws.jws2.Jws2Discoverer;
-import jalview.ws.jws2.jabaws2.Jws2Instance;
+import jalview.ws.jws2.SeqAnnotationServiceCalcWorker;
+import jalview.ws.slivkaws.SlivkaWSDiscoverer;
import java.util.ArrayList;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
+import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/*
public static Jws2Discoverer disc;
- public static List<Jws2Instance> iupreds;
+ public static List<ServiceWithParameters> iupreds;
- jalview.ws.jws2.AADisorderClient disorderClient;
+ jalview.ws.jws2.SeqAnnotationServiceCalcWorker disorderClient;
public static jalview.gui.AlignFrame af = null;
public static void setUpBeforeClass() throws Exception
{
Cache.loadProperties("test/jalview/io/testProps.jvprops");
- Cache.initLogger();
+ Console.initLogger();
disc = JalviewJabawsTestUtils.getJabawsDiscoverer();
while (disc.isRunning())
Thread.sleep(100);
}
- iupreds = new ArrayList<Jws2Instance>();
- for (Jws2Instance svc : disc.getServices())
+ SlivkaWSDiscoverer disc2 = SlivkaWSDiscoverer.getInstance();
+ disc2.startDiscoverer();
+ while (disc2.isRunning())
{
- if (svc.getServiceTypeURI().toLowerCase(Locale.ROOT).contains("iupredws"))
+ if (svc.getServiceTypeURI().toLowerCase(Locale.ROOT)
+ .contains("iupredws"))
{
iupreds.add(svc);
}
assertTrue("Couldn't discover any IUPred services to use to test.",
iupreds.size() > 0);
jalview.io.FileLoader fl = new jalview.io.FileLoader(false);
- af = fl.LoadFileWaitTillLoaded(testseqs, jalview.io.DataSourceType.FILE);
+ af = fl.LoadFileWaitTillLoaded(testseqs,
+ jalview.io.DataSourceType.FILE);
assertNotNull("Couldn't load test data ('" + testseqs + "')", af);
}
af = null;
}
}
+
+ @DataProvider(name="getIuPreds",parallel = false)
+ public static ServiceWithParameters[][] getIuPreds()
+ {
+ ServiceWithParameters[][] services = new ServiceWithParameters[iupreds
+ .size()][1];
+
+ int i = 0;
+ for (ServiceWithParameters iupred : iupreds)
+ {
+ services[i++][0] = iupred;
+ }
+ return services;
+ }
/**
* test for patches to JAL-1294
*/
- @Test(groups = { "External", "Network" })
- public void testDisorderAnnotExport()
+ @Test(groups = { "External", "Network" },dataProvider = "getIuPreds")
+ public void testDisorderAnnotExport(ServiceWithParameters iuPred)
{
- disorderClient = new AADisorderClient(iupreds.get(0), af, null, null);
+ disorderClient = new SeqAnnotationServiceCalcWorker(iuPred, af, null,
+ null);
af.getViewport().getCalcManager().startWorker(disorderClient);
do
{
AlignmentI orig_alig = af.getViewport().getAlignment();
// NOTE: Consensus annotation row cannot be exported and reimported
// faithfully - so we remove them
- List<AlignmentAnnotation> toremove = new ArrayList<AlignmentAnnotation>();
+ List<AlignmentAnnotation> toremove = new ArrayList<>();
for (AlignmentAnnotation aa : orig_alig.getAlignmentAnnotation())
{
if (aa.autoCalculated)
{
try
{
- String aligfileout = FileFormat.Pfam.getWriter(al).print(
- al.getSequencesArray(), true);
+ String aligfileout = FileFormat.Pfam.getWriter(al)
+ .print(al.getSequencesArray(), true);
String anfileout = new AnnotationFile()
.printAnnotationsForAlignment(al);
- assertTrue(
- "Test "
- + testname
- + "\nAlignment annotation file was not regenerated. Null string",
+ assertTrue("Test " + testname
+ + "\nAlignment annotation file was not regenerated. Null string",
anfileout != null);
- assertTrue(
- "Test "
- + testname
- + "\nAlignment annotation file was not regenerated. Empty string",
+ assertTrue("Test " + testname
+ + "\nAlignment annotation file was not regenerated. Empty string",
anfileout.length() > "JALVIEW_ANNOTATION".length());
- System.out.println("Output annotation file:\n" + anfileout
- + "\n<<EOF\n");
+ System.out.println(
+ "Output annotation file:\n" + anfileout + "\n<<EOF\n");
AlignmentI al_new = new FormatAdapter().readFile(aligfileout,
DataSourceType.PASTE, FileFormat.Pfam);
- assertTrue(
- "Test "
- + testname
- + "\nregenerated annotation file did not annotate alignment.",
+ assertTrue("Test " + testname
+ + "\nregenerated annotation file did not annotate alignment.",
new AnnotationFile().readAnnotationFile(al_new, anfileout,
DataSourceType.PASTE));
{
e.printStackTrace();
}
- Assert.fail("Test "
- + testname
+ Assert.fail("Test " + testname
+ "\nCouldn't complete Annotation file roundtrip input/output/input test.");
}
public static Jws2Discoverer getJabawsDiscoverer(boolean localhost)
{
jalview.ws.jws2.Jws2Discoverer disc = jalview.ws.jws2.Jws2Discoverer
- .getDiscoverer();
+ .getInstance();
String svcurls = "";
if (localhost)
{
services.add(url);
}
;
- Jws2Discoverer.getDiscoverer().setServiceUrls(services);
+ Jws2Discoverer.getInstance().setServiceUrls(services);
}
try
{
} catch (Exception e)
{
e.printStackTrace();
- Assert.fail("Aborting. Problem discovering services. Tried "
- + svcurls);
+ Assert.fail(
+ "Aborting. Problem discovering services. Tried " + svcurls);
}
Assert.assertTrue(disc.getServices().size() > 0,
"Failed to discover any services at ");
package jalview.ws.jabaws;
import java.util.Locale;
-
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertTrue;
import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.datamodel.AlignmentAnnotation;
import jalview.datamodel.AlignmentI;
import jalview.gui.JvOptionPane;
import jalview.io.FormatAdapter;
import jalview.io.StockholmFileTest;
import jalview.project.Jalview2XML;
+import jalview.ws.api.ServiceWithParameters;
+import jalview.ws.jws2.JabaParamStore;
import jalview.ws.jws2.Jws2Discoverer;
-import jalview.ws.jws2.RNAalifoldClient;
+import jalview.ws.jws2.SeqAnnotationServiceCalcWorker;
import jalview.ws.jws2.SequenceAnnotationWSClient;
import jalview.ws.jws2.jabaws2.Jws2Instance;
import jalview.ws.params.AutoCalcSetting;
public static Jws2Instance rnaalifoldws;
- jalview.ws.jws2.RNAalifoldClient alifoldClient;
+ SeqAnnotationServiceCalcWorker alifoldClient;
public static jalview.gui.AlignFrame af = null;
public static void setUpBeforeClass() throws Exception
{
Cache.loadProperties("test/jalview/io/testProps.jvprops");
- Cache.initLogger();
+ Console.initLogger();
disc = JalviewJabawsTestUtils.getJabawsDiscoverer(false);
while (disc.isRunning())
Thread.sleep(100);
}
- for (Jws2Instance svc : disc.getServices())
+ for (ServiceWithParameters svc : disc.getServices())
{
- if (svc.getServiceTypeURI().toLowerCase(Locale.ROOT).contains("rnaalifoldws"))
+ if (svc.getServiceTypeURI().toLowerCase(Locale.ROOT)
+ .contains("rnaalifoldws"))
{
- rnaalifoldws = svc;
+ rnaalifoldws = (Jws2Instance) svc;
}
}
jalview.io.FileLoader fl = new jalview.io.FileLoader(false);
- af = fl.LoadFileWaitTillLoaded(testseqs, jalview.io.DataSourceType.FILE);
+ af = fl.LoadFileWaitTillLoaded(testseqs,
+ jalview.io.DataSourceType.FILE);
assertNotNull("Couldn't load test data ('" + testseqs + "')", af);
public void testRNAAliFoldValidStructure()
{
- alifoldClient = new RNAalifoldClient(rnaalifoldws, af, null, null);
+ alifoldClient = new SeqAnnotationServiceCalcWorker(rnaalifoldws, af, null,
+ null);
af.getViewport().getCalcManager().startWorker(alifoldClient);
public void testRNAStructExport()
{
- alifoldClient = new RNAalifoldClient(rnaalifoldws, af, null, null);
+ alifoldClient = new SeqAnnotationServiceCalcWorker(rnaalifoldws, af, null,
+ null);
af.getViewport().getCalcManager().startWorker(alifoldClient);
AlignmentI orig_alig = af.getViewport().getAlignment();
// JBPNote: this assert fails (2.10.2) because the 'Reference Positions'
// annotation is mistakenly recognised as an RNA annotation row when read in
- // as an annotation file.
+ // as an annotation file. bug is JAL-3122
verifyAnnotationFileIO("Testing RNAalifold Annotation IO", orig_alig);
}
try
{
// what format would be appropriate for RNAalifold annotations?
- String aligfileout = FileFormat.Pfam.getWriter(null).print(
- al.getSequencesArray(), true);
+ String aligfileout = FileFormat.Pfam.getWriter(null)
+ .print(al.getSequencesArray(), true);
String anfileout = new AnnotationFile()
.printAnnotationsForAlignment(al);
- assertNotNull(
- "Test "
- + testname
- + "\nAlignment annotation file was not regenerated. Null string",
+ assertNotNull("Test " + testname
+ + "\nAlignment annotation file was not regenerated. Null string",
anfileout);
- assertTrue(
- "Test "
- + testname
- + "\nAlignment annotation file was not regenerated. Empty string",
+ assertTrue("Test " + testname
+ + "\nAlignment annotation file was not regenerated. Empty string",
anfileout.length() > "JALVIEW_ANNOTATION".length());
- System.out.println("Output annotation file:\n" + anfileout
- + "\n<<EOF\n");
+ System.out.println(
+ "Output annotation file:\n" + anfileout + "\n<<EOF\n");
// again what format would be appropriate?
AlignmentI al_new = new FormatAdapter().readFile(aligfileout,
DataSourceType.PASTE, FileFormat.Pfam);
- assertTrue(
- "Test "
- + testname
- + "\nregenerated annotation file did not annotate alignment.",
+ assertTrue("Test " + testname
+ + "\nregenerated annotation file did not annotate alignment.",
new AnnotationFile().readAnnotationFile(al_new, anfileout,
DataSourceType.PASTE));
{
e.printStackTrace();
}
- Assert.fail("Test "
- + testname
+ Assert.fail("Test " + testname
+ "\nCouldn't complete Annotation file roundtrip input/output/input test.");
}
opts.add(rg);
}
}
- alifoldClient = new RNAalifoldClient(rnaalifoldws, af, null, opts);
+ alifoldClient = new SeqAnnotationServiceCalcWorker(rnaalifoldws, af, null,
+ JabaParamStore.getJwsArgsfromJaba(opts));
af.getViewport().getCalcManager().startWorker(alifoldClient);
}
;
} while (af.getViewport().getCalcManager().isWorking());
- AutoCalcSetting oldacs = af.getViewport().getCalcIdSettingsFor(
- alifoldClient.getCalcId());
+ AutoCalcSetting oldacs = af.getViewport()
+ .getCalcIdSettingsFor(alifoldClient.getCalcId());
String oldsettings = oldacs.getWsParamFile();
// write out parameters
jalview.gui.AlignFrame nalf = null;
- assertTrue("Couldn't write out the Jar file",
- new Jalview2XML(false).saveAlignment(af, JAR_FILE_NAME,
- "trial parameter writeout"));
- assertTrue("Couldn't read back the Jar file", (nalf = new Jalview2XML(
- false).loadJalviewAlign(JAR_FILE_NAME)) != null);
+ assertTrue("Couldn't write out the Jar file", new Jalview2XML(false)
+ .saveAlignment(af, JAR_FILE_NAME, "trial parameter writeout"));
+ assertTrue("Couldn't read back the Jar file",
+ (nalf = new Jalview2XML(false)
+ .loadJalviewAlign(JAR_FILE_NAME)) != null);
if (nalf != null)
{
- AutoCalcSetting acs = af.getViewport().getCalcIdSettingsFor(
- alifoldClient.getCalcId());
+ AutoCalcSetting acs = af.getViewport()
+ .getCalcIdSettingsFor(alifoldClient.getCalcId());
assertTrue("Calc ID settings not recovered from viewport stash",
acs.equals(oldacs));
assertTrue(
}
;
}
- AutoCalcSetting acs2 = af.getViewport().getCalcIdSettingsFor(
- alifoldClient.getCalcId());
+ AutoCalcSetting acs2 = af.getViewport()
+ .getCalcIdSettingsFor(alifoldClient.getCalcId());
assertTrue(
"Calc ID settings after recalculation has not been recovered.",
acs2.getWsParamFile().equals(oldsettings));
package jalview.ws.jws2;
import java.util.Locale;
-
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import jalview.bin.Cache;
+ import jalview.bin.Console;
import jalview.gui.JvOptionPane;
+import jalview.ws.api.ServiceWithParameters;
+import jalview.ws.api.UIinfo;
import jalview.ws.jabaws.JalviewJabawsTestUtils;
import jalview.ws.jws2.jabaws2.Jws2Instance;
* To limit tests to specify services, add them to this list; leave list empty
* to test all
*/
- private static List<String> serviceTests = new ArrayList<String>();
+ private static List<String> serviceTests = new ArrayList<>();
private static Jws2Discoverer disc = null;
{
serviceTests.add("AAConWS".toLowerCase(Locale.ROOT));
Cache.loadProperties("test/jalview/io/testProps.jvprops");
- Cache.initLogger();
+ Console.initLogger();
disc = JalviewJabawsTestUtils.getJabawsDiscoverer();
}
@Test(groups = { "Network" })
public void testWriteParameterSet() throws WrongParameterException
{
- for (Jws2Instance service : disc.getServices())
+ for (ServiceWithParameters _service : disc.getServices())
{
- if (isForTesting(service))
+ if (isForTesting(_service))
{
+ Jws2Instance service = (Jws2Instance) _service;
List<Preset> prl = null;
PresetManager prman = service.getPresets();
String on = o.next();
String sn = s.next();
String st = t.next();
- final String errorMsg = "Original was " + on
- + " Phase 1 wrote " + sn + "\tPhase 2 wrote " + st;
+ final String errorMsg = "Original was " + on + " Phase 1 wrote "
+ + sn + "\tPhase 2 wrote " + st;
assertEquals(errorMsg, sn, st);
assertEquals(errorMsg, sn, on);
}
* @param service
* @return
*/
- public boolean isForTesting(Jws2Instance service)
+ public boolean isForTesting(UIinfo service)
{
- return serviceTests.size() == 0
- || serviceTests.contains(service.serviceType.toLowerCase(Locale.ROOT));
+ return serviceTests.size() == 0 || serviceTests
+ .contains(service.serviceType.toLowerCase(Locale.ROOT));
}
@Test(groups = { "Network" })
public void testCopyOption()
{
- for (Jws2Instance service : disc.getServices())
+ for (ServiceWithParameters _service : disc.getServices())
{
- if (isForTesting(service))
+ if (isForTesting(_service))
{
+ Jws2Instance service = (Jws2Instance) _service;
List<Option<?>> options = service.getRunnerConfig().getOptions();
for (Option<?> o : options)
{
@Test(groups = { "Network" })
public void testCopyParameter()
{
- for (Jws2Instance service : disc.getServices())
+ for (ServiceWithParameters _service : disc.getServices())
{
- if (isForTesting(service))
+ if (isForTesting(_service))
{
+ Jws2Instance service = (Jws2Instance) _service;
List<Parameter> parameters = service.getRunnerConfig()
.getParameters();
for (Parameter o : parameters)
import jalview.gui.AlignFrame;
import jalview.gui.JvOptionPane;
+import jalview.ws.rest.clientdefs.ShmrRestClient;
import java.util.Map;
assertTrue(
"Test Rsd Exchange using using default Shmmr service failed.",
testRsdExchange("Test using default Shmmr service",
- RestClient.makeShmmrRestClient().service));
+ ShmrRestClient.makeShmmrRestClient().service));
}
@Test(groups = { "Functional" })
public void testShmmrServiceDataprep() throws Exception
{
- RestClient _rc = RestClient.makeShmmrRestClient();
+ RestClient _rc = ShmrRestClient.makeShmmrRestClient();
assertNotNull(_rc);
AlignFrame alf = new jalview.io.FileLoader(false)
.LoadFileWaitTillLoaded("examples/testdata/smad.fa",
assertTrue(
"Couldn't load the test data's annotation file (should be 5 groups but found "
+ alf.getViewport().getAlignment().getGroups().size()
- + ").", alf.getViewport().getAlignment().getGroups()
- .size() == 5);
+ + ").",
+ alf.getViewport().getAlignment().getGroups().size() == 5);
RestClient rc = new RestClient(_rc.service, alf, true);
assertNotNull("Couldn't creat RestClient job.", rc);
- jalview.bin.Cache.initLogger();
+ jalview.bin.Console.initLogger();
RestJob rjb = new RestJob(0, new RestJobThread(rc),
rc.av.getAlignment(), null);
rjb.setAlignmentForInputs(rc.service.getInputParams().values(),
return testRsdExchange(desc, newService);
} catch (Throwable x)
{
- System.err.println("Failed for service (" + desc + "): "
- + servicestring);
+ System.err.println(
+ "Failed for service (" + desc + "): " + servicestring);
x.printStackTrace();
return false;
}
fromservicetostring);
if (!newService.isValid())
{
- throw new Error("Failed to create service from '"
- + fromservicetostring + "'.\n"
- + newService.getInvalidMessage());
+ throw new Error(
+ "Failed to create service from '" + fromservicetostring
+ + "'.\n" + newService.getInvalidMessage());
}
if (!service.equals(newService))
{
System.err.println("Failed for service (" + desc + ").");
+ if (fromservicetostring.equals(newService.toString()))
+ {
+ System.err.println(
+ "Description strings are equivalent: fault during RestServiceDescription.equals()");
+ return false;
+ }
System.err.println("Original service and parsed service differ.");
System.err.println("Original: " + fromservicetostring);
System.err.println("Parsed : " + newService.toString());
}
} catch (Throwable x)
{
- System.err.println("Failed for service (" + desc + "): "
- + service.toString());
+ System.err.println(
+ "Failed for service (" + desc + "): " + service.toString());
x.printStackTrace();
return false;
}
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
-import jalview.api.DBRefEntryI;
-import jalview.bin.Cache;
-import jalview.datamodel.DBRefEntry;
-import jalview.datamodel.DBRefSource;
-import jalview.datamodel.Sequence;
-import jalview.datamodel.SequenceI;
-import jalview.gui.JvOptionPane;
-import jalview.io.DataSourceType;
-import jalview.structure.StructureMapping;
-import jalview.xml.binding.sifts.Entry.Entity;
+
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
+import jalview.api.DBRefEntryI;
+import jalview.bin.Cache;
+import jalview.datamodel.DBRefEntry;
+import jalview.datamodel.DBRefSource;
+import jalview.datamodel.Sequence;
+import jalview.datamodel.SequenceI;
+import jalview.gui.JvOptionPane;
+import jalview.io.DataSourceType;
+import jalview.structure.StructureMapping;
+import jalview.xml.binding.sifts.Entry.Entity;
import mc_view.Atom;
import mc_view.PDBfile;
}
public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = System
- .getProperty("user.home") + File.separatorChar
+ .getProperty("user.home")
+ + File.separatorChar
+ ".sifts_downloads" + File.separatorChar;
private String testPDBId = "1a70";
private SiftsClient siftsClient = null;
- SequenceI testSeq = new Sequence("P00221",
+ SequenceI testSeq = new Sequence(
+ "P00221",
"MAAT..TTTMMG..MATTFVPKPQAPPMMAALPSNTGR..SLFGLKT.GSR..GGRMTMA"
+ "AYKVTLVTPTGNVEFQCPDDVYILDAAEEEGIDLPYSCRAGSCSSCAGKLKTGSLNQDD"
- + "QSFLDDDQIDEGWVLTCAAYPVSDVTIETHKEEELTA.",
- 1, 147);
+ + "QSFLDDDQIDEGWVLTCAAYPVSDVTIETHKEEELTA.", 1, 147);
int u = SiftsClient.UNASSIGNED;
Cache.loadProperties("test/jalview/io/testProps.jvprops");
// SIFTs entries are updated weekly - so use saved SIFTs file to enforce
// test reproducibility
- new SiftsSettings();
- SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache
- .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
+ SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache.getDefault(
+ "sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
SiftsSettings.setMapWithSifts(true);
SiftsSettings.setCacheThresholdInDays("2");
SiftsSettings.setFailSafePIDThreshold("70");
PDBfile pdbFile;
- pdbFile = new PDBfile(false, false, false,
- "test/jalview/io/" + testPDBId + ".pdb", DataSourceType.FILE);
+ pdbFile = new PDBfile(false, false, false, "test/jalview/io/"
+ + testPDBId + ".pdb", DataSourceType.FILE);
siftsClient = new SiftsClient(pdbFile);
}
try
{
- HashMap<Integer, int[]> actualMapping = siftsClient
- .getGreedyMapping("A", testSeq, null);
+ HashMap<Integer, int[]> actualMapping = siftsClient.getGreedyMapping(
+ "A", testSeq, null);
Assert.assertEquals(testSeq.getStart(), 1);
Assert.assertEquals(testSeq.getEnd(), 147);
// Can't do Assert.assertEquals(actualMapping, expectedMapping);
atom.atomIndex = 7;
atoms.add(atom);
int actualAtomIndex = siftsClient.getAtomIndex(1, atoms);
- Assert.assertEquals(actualAtomIndex, siftsClient.UNASSIGNED);
+ Assert.assertEquals(actualAtomIndex, SiftsClient.UNASSIGNED);
actualAtomIndex = siftsClient.getAtomIndex(43, atoms);
Assert.assertEquals(actualAtomIndex, 7);
}
@Test(
- groups =
- { "Network" },
+ groups = { "Network" },
expectedExceptions = IllegalArgumentException.class)
private void getAtomIndexNullTest()
{
}
- @Test(groups = { "Network" }, expectedExceptions = SiftsException.class)
+ @Test(
+groups = { "Network" },
+ expectedExceptions = SiftsException.class)
private void populateAtomPositionsNullTest1()
throws IllegalArgumentException, SiftsException
{
siftsClient.populateAtomPositions(null, null);
}
- @Test(groups = { "Network" }, expectedExceptions = SiftsException.class)
+ @Test(
+groups = { "Network" },
+ expectedExceptions = SiftsException.class)
private void populateAtomPositionsNullTest2()
throws IllegalArgumentException, SiftsException
{
Assert.assertEquals(actualValidSrcDBRef, expectedDBRef);
}
- @Test(groups = { "Network" }, expectedExceptions = SiftsException.class)
+ @Test(
+groups = { "Network" },
+ expectedExceptions = SiftsException.class)
public void getValidSourceDBRefExceptionTest() throws SiftsException
{
SequenceI invalidTestSeq = new Sequence("testSeq", "ABCDEFGH");
siftsClient.getValidSourceDBRef(invalidTestSeq);
}
- @Test(groups = { "Network" }, expectedExceptions = SiftsException.class)
+ @Test(
+groups = { "Network" },
+ expectedExceptions = SiftsException.class)
public void getValidSourceDBRefExceptionXTest() throws SiftsException
{
SequenceI invalidTestSeq = new Sequence("testSeq", "ABCDEFGH");
public void getSiftsStructureMappingTest() throws SiftsException
{
Assert.assertTrue(SiftsSettings.isMapWithSifts());
- StructureMapping strucMapping = siftsClient
- .getSiftsStructureMapping(testSeq, testPDBId, "A");
+ StructureMapping strucMapping = siftsClient.getSiftsStructureMapping(
+ testSeq, testPDBId, "A");
String expectedMappingOutput = "\nSequence ⟷ Structure mapping details\n"
- + "Method: SIFTS\n\n" + "P00221 : 51 - 147 Maps to \n"
+ + "Method: SIFTS\n\n"
+ + "P00221 : 51 - 147 Maps to \n"
+ "1A70|A : 1 - 97\n\n"
+ "P00221 AAYKVTLVTPTGNVEFQCPDDVYILDAAEEEGIDLPYSCRAGSCSSCAGKLKTGSLNQDDQSFLD\n"
+ " |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\n"
while (it.hasNext())
{
Map.Entry<Integer, int[]> pair = it.next();
- Assert.assertTrue(
- strucMapping.getMapping().containsKey(pair.getKey()));
+ Assert.assertTrue(strucMapping.getMapping()
+ .containsKey(pair.getKey()));
Assert.assertEquals(strucMapping.getMapping().get(pair.getKey()),
pair.getValue());
}
}
@Test(groups = { "Network" })
- public void getEntityByMostOptimalMatchedIdTest1()
- throws IOException, SiftsException
+ public void getEntityByMostOptimalMatchedIdTest1() throws IOException,
+ SiftsException
{
SiftsClient siftsClientX = null;
PDBfile pdbFile;
- pdbFile = new PDBfile(false, false, false,
- "test/jalview/io/2nq2" + ".pdb", DataSourceType.FILE);
+ pdbFile = new PDBfile(false, false, false, "test/jalview/io/2nq2"
+ + ".pdb", DataSourceType.FILE);
siftsClientX = new SiftsClient(pdbFile);
Entity entityA = siftsClientX.getEntityByMostOptimalMatchedId("A");
Assert.assertEquals(entityA.getEntityId(), "A");
}
@Test(groups = { "Network" })
- public void getEntityByMostOptimalMatchedIdTest2()
- throws IOException, SiftsException
+ public void getEntityByMostOptimalMatchedIdTest2() throws IOException,
+ SiftsException
{
// This test is for a SIFTS file in which entity A should map to chain P for
// the given PDB Id. All the other chains shouldn't be mapped as there are
Assert.assertNull(entityP);
}
-
- @Test(groups = { "Network" })
- public void getLeadingIntegerFromString()
- {
- Assert.assertEquals(SiftsClient.getLeadingIntegerValue("1234abcd", -1),
- 1234);
- Assert.assertEquals(SiftsClient.getLeadingIntegerValue("1234", -1),
- 1234);
- Assert.assertEquals(SiftsClient.getLeadingIntegerValue("abcd", -1), -1);
- Assert.assertEquals(SiftsClient.getLeadingIntegerValue("abcd1234", -1),
- -1);
- Assert.assertEquals(SiftsClient.getLeadingIntegerValue("None", -1), -1);
- Assert.assertEquals(SiftsClient.getLeadingIntegerValue("Null", -1), -1);
- }
}
import org.testng.Assert;
import org.testng.annotations.Test;
- public class UrlDownloadClientTest {
+ public class UrlDownloadClientTest
+ {
/**
* Test that url is successfully loaded into download file
public void UrlDownloadTest()
{
UrlDownloadClient client = new UrlDownloadClient();
- String urlstring = "http://identifiers.org/rest/collections/";
+ String urlstring = "http://www.jalview.org/services/identifiers";
+ // was "http://identifiers.org/rest/collections/";
String outfile = "testfile.tmp";
try
// download file has a believable size
// identifiers.org file typically at least 250K
- Assert.assertTrue(f.length() > 250000);
-
+ long n = f.length();
if (f.exists())
{
f.delete();
}
+ // 74589
+ Assert.assertTrue(n > 70000);
+
}
* Test that garbage in results in IOException
*/
@Test(
- groups = { "Network" },
+ groups =
+ { "Network" },
enabled = true,
- expectedExceptions = { IOException.class })
+ expectedExceptions =
+ { IOException.class })
public void DownloadGarbageUrlTest() throws IOException
{
UrlDownloadClient client = new UrlDownloadClient();
assertEquals(0, chainA.seqend); // not set
assertEquals(18, chainA.sequence.getStart());
assertEquals(314, chainA.sequence.getEnd());
- assertTrue(chainA.sequence.getSequenceAsString().startsWith("KCSKKQEE"));
+ assertTrue(
+ chainA.sequence.getSequenceAsString().startsWith("KCSKKQEE"));
assertTrue(chainA.sequence.getSequenceAsString().endsWith("WNVEVY"));
assertEquals("3W5V|A", chainA.sequence.getName());
assertNull(chainA.sequence.getAnnotation());
PDBChain chainC = pf.getChains().get(2);
assertEquals(18, chainC.sequence.getStart());
assertEquals(314, chainC.sequence.getEnd());
- assertTrue(chainC.sequence.getSequenceAsString().startsWith("KCSKKQEE"));
+ assertTrue(
+ chainC.sequence.getSequenceAsString().startsWith("KCSKKQEE"));
assertTrue(chainC.sequence.getSequenceAsString().endsWith("WNVEVY"));
assertEquals("3W5V|C", chainC.sequence.getName());
* @throws IOException
*/
@Test(groups = { "Functional" })
- public void testParse_withJmolAddAlignmentAnnotations()
- throws IOException
+ public void testParse_withJmolAddAlignmentAnnotations() throws IOException
{
PDBfile pf = new PDBfile(true, true, false, "examples/3W5V.pdb",
DataSourceType.FILE);
public void setUp()
{
Cache.loadProperties("test/jalview/io/testProps.jvprops");
- Cache.applicationProperties.setProperty("STRUCT_FROM_PDB",
+ Cache.setPropertyNoSave("STRUCT_FROM_PDB",
Boolean.TRUE.toString());
- Cache.applicationProperties.setProperty("ADD_TEMPFACT_ANN",
+ Cache.setPropertyNoSave("ADD_TEMPFACT_ANN",
Boolean.TRUE.toString());
- Cache.applicationProperties.setProperty("ADD_SS_ANN",
+ Cache.setPropertyNoSave("ADD_SS_ANN",
Boolean.TRUE.toString());
StructureImportSettings.setDefaultStructureFileFormat("PDB");
}