jetty-io-9.2.10.v20150310.jar
jetty-server-9.2.10.v20150310.jar
jetty-util-9.2.10.v20150310.jar
-jfreesvg-2.1.jar GPL v3 licensed library from the JFree suite - http://www.jfree.org/jfreesvg/
+jfreesvg-3.4.3.jar GPL v3 licensed library from the JFree suite - last release with Java 1.8 compatibility http://www.jfree.org/jfreesvg/
JGoogleAnalytics_0.3.jar APL 2.0 License - http://code.google.com/p/jgoogleanalytics/
jhall.jar
Jmol-NO_LOG4J-14.31.53.jar GPL/LGPLv2 built manually from commit https://github.com/BobHanson/Jmol-SwingJS/commit/a6a2fb767e3fc2a73e72d926a11fd93a0e4c9f23 (excluded jspecview/application to compile)
regex.jar
saaj.jar
servlet-api-3.1.jar
-slf4j-api-1.7.32.jar MIT license - https://opensource.org/licenses/mit-license.php
+slf4j-api-1.7.36.jar MIT license - https://opensource.org/licenses/mit-license.php - downloaded from https://repo1.maven.org/maven2/org/slf4j/
+slf4j-nop-1.7.36.jar MIT license - https://opensource.org/licenses/mit-license.php - downloaded from https://repo1.maven.org/maven2/org/slf4j/
vamsas-client.jar
VARNAv3-93.jar GPL licenced software by K�vin Darty, Alain Denise and Yann Ponty - http://varna.lri.fr
wsdl4j.jar
info.events = [ TestLogEvent.FAILED ]
}
+ if (OperatingSystem.current().isMacOsX()) {
+ testTask.systemProperty "apple.awt.UIElement", "true"
+ testTask.environment "JAVA_TOOL_OPTIONS", "-Dapple.awt.UIElement=true"
+ }
ignoreFailures = true // Always try to run all tests for all modules
--paematrix=[label=pAE R4-M5]./examples/test_fab41.result/test_fab41_unrelaxed_rank_4_model_5_scores.json
--structure=./examples/test_fab41.result/test_fab41_unrelaxed_rank_5_model_1.pdb
--paematrix=[label=pAE R5-M1]./examples/test_fab41.result/test_fab41_unrelaxed_rank_5_model_1_scores.json
---image=output1.html
+--image=[textrenderer=text]output1.html
--- /dev/null
+--open=./examples/test_fab41.result/sample.a2m
+--colour=gecos:flower
+--gui
+--structure=[structureviewer=none]./examples/test_fab41.result/test_fab41_unrelaxed_rank_1_model_3.pdb
+--paematrix=[label=pAE R1-M3]./examples/test_fab41.result/test_fab41_unrelaxed_rank_1_model_3_scores.json
+--structure=[structureviewer=none]./examples/test_fab41.result/test_fab41_unrelaxed_rank_2_model_4.pdb
+--paematrix=[label=pAE R2-M4]./examples/test_fab41.result/test_fab41_unrelaxed_rank_2_model_4_scores.json
+--structure=[structureviewer=none]./examples/test_fab41.result/test_fab41_unrelaxed_rank_3_model_2.pdb
+--paematrix=[label=pAE R3-M2]./examples/test_fab41.result/test_fab41_unrelaxed_rank_3_model_2_scores.json
+--structure=[structureviewer=none]./examples/test_fab41.result/test_fab41_unrelaxed_rank_4_model_5.pdb
+--paematrix=[label=pAE R4-M5]./examples/test_fab41.result/test_fab41_unrelaxed_rank_4_model_5_scores.json
+--structure=[structureviewer=none]./examples/test_fab41.result/test_fab41_unrelaxed_rank_5_model_1.pdb
+--paematrix=[label=pAE R5-M1]./examples/test_fab41.result/test_fab41_unrelaxed_rank_5_model_1_scores.json
+--image=[textrenderer=text]output1.html
-1.8.3-1.2.14_FJVL
+1.8.3-1.3.0_FJVL
-1.8.3-1.2.14_JVL
+1.8.3-1.3.0_JVL
<parent>
<groupId>com.threerings.getdown</groupId>
<artifactId>getdown</artifactId>
- <version>1.8.3-1.2.14_FJVL</version>
+ <version>1.8.3-1.3.0_FJVL</version>
</parent>
<artifactId>getdown-ant</artifactId>
<parent>
<groupId>com.threerings.getdown</groupId>
<artifactId>getdown</artifactId>
- <version>1.8.3-1.2.14_FJVL</version>
+ <version>1.8.3-1.3.0_FJVL</version>
</parent>
<artifactId>getdown-core</artifactId>
import java.security.MessageDigest;
+import jalview.util.LaunchUtils;
+
import static com.threerings.getdown.Log.log;
/**
return getJVMPath(appdir, false);
}
+ private static String jvmPath = null;
/**
* Reconstructs the path to the JVM used to launch this process.
*
*/
public static String getJVMPath (File appdir, boolean windebug)
{
- // first look in our application directory for an installed VM
- String vmpath = checkJVMPath(new File(appdir, LOCAL_JAVA_DIR).getAbsolutePath(), windebug);
- if (vmpath == null && isMacOS()) {
- vmpath = checkJVMPath(new File(appdir, LOCAL_JAVA_DIR + "/Contents/Home").getAbsolutePath(), windebug);
+ if (jvmPath != null) {
+ return jvmPath;
}
+
+ // first look in our application directory for an installed VM
+ final String appDir = isMacOS() ?
+ (new File(appdir, LOCAL_JAVA_DIR).getAbsolutePath()) + "/Contents/Home"
+ : new File(appdir, LOCAL_JAVA_DIR).getAbsolutePath();
+
+ String javaBin = LaunchUtils.findJavaBin(appDir, windebug, false);
// then fall back to the VM in which we're already running
- if (vmpath == null) {
- vmpath = checkJVMPath(System.getProperty("java.home"), windebug);
+ if (javaBin == null) {
+ javaBin = LaunchUtils.findJavaBin(System.getProperty("java.home"), windebug, false);
}
// then throw up our hands and hope for the best
- if (vmpath == null) {
+ if (javaBin == null) {
+ javaBin = LaunchUtils.findJavaBin(null, windebug, true);
log.warning("Unable to find java [appdir=" + appdir +
", java.home=" + System.getProperty("java.home") + "]!");
- vmpath = "java";
}
// Oddly, the Mac OS X specific java flag -Xdock:name will only work if java is launched
if (isMacOS()) {
try {
File localVM = new File("/usr/bin/java").getCanonicalFile();
- if (localVM.equals(new File(vmpath).getCanonicalFile())) {
- vmpath = "/usr/bin/java";
+ if (localVM.equals(new File(javaBin).getCanonicalFile())) {
+ javaBin = "/usr/bin/java";
}
} catch (IOException ioe) {
log.warning("Failed to check Mac OS canonical VM path.", ioe);
}
}
- return vmpath;
+ jvmPath = javaBin;
+ return jvmPath;
}
private static String _getMD5FileChecksum (File file) {
public class LaunchUtils
{
+ // setting these is LaunchUtils so don't need to import Platform
+ public final static boolean isMac = System.getProperty("os.name")
+ .indexOf("Mac") > -1;
+
+ public final static boolean isWindows = System.getProperty("os.name")
+ .indexOf("Win") > -1;
+
+ private static boolean isJS = /** @j2sNative true || */
+ false;
+
public static void loadChannelProps(File dir)
{
ChannelProperties.loadProps(dir);
public static int getJavaCompileVersion()
{
- if (JAVA_COMPILE_VERSION > 0)
+ if (LaunchUtils.isJS)
+ {
+ return -1;
+ }
+ else if (JAVA_COMPILE_VERSION > 0)
{
return JAVA_COMPILE_VERSION;
}
public static int getJavaVersion()
{
- if (JAVA_VERSION > 0)
+ if (LaunchUtils.isJS)
+ {
+ return -1;
+ }
+ else if (JAVA_VERSION > 0)
{
return JAVA_VERSION;
}
public static boolean checkJavaVersion()
{
+ if (LaunchUtils.isJS)
+ {
+ return true;
+ }
String buildDetails = "jar:".concat(LaunchUtils.class
.getProtectionDomain().getCodeSource().getLocation().toString()
.concat("!" + "/.build_properties"));
return true;
}
+
+ public static String findJavaBin(boolean winConsole)
+ {
+ return findJavaBin(System.getProperty("java.home"), winConsole, true);
+ }
+
+ /*
+ * Returns a string path to the most likely java binary wanted to run this
+ * installation of Jalview.
+ *
+ * @param winConsole whether to use java.exe (console) in preference to javaw.exe
+ * (only affects Windows).
+ * @param javaHome Try this javaHome dir (defaults to the running java.home).
+ * @param generic Return a generic java command if not found.
+ */
+ public static String findJavaBin(String javaHome, boolean winConsole,
+ boolean generic)
+ {
+ String javaBin = null;
+ final String javaExe = winConsole ? "java.exe" : "javaw.exe";
+ final String java = "java";
+
+ if (javaHome != null)
+ {
+ // property "channel.app_name" is set by install4j when launching getdown
+ String propertyAppName = System.getProperty("channel.app_name");
+ final String appName = (propertyAppName != null
+ && propertyAppName.length() > 0) ? propertyAppName
+ : ChannelProperties.getProperty("app_name");
+
+ final String javaBinDir = javaHome + File.separator + "bin"
+ + File.separator;
+
+ // appName and "Jalview" will not point to javaw.exe or java.exe but in
+ // this case that's okay because the taskbar display name problem doesn't
+ // manifest in Windows. See JAL-3820, JAL-4189.
+ for (String name : new String[] { appName, "Jalview", java, javaExe })
+ {
+ if (LaunchUtils.checkJVMSymlink(javaBinDir + name, winConsole))
+ {
+ javaBin = javaBinDir + name;
+ break;
+ }
+ }
+ }
+
+ if (javaBin == null && generic)
+ {
+ javaBin = LaunchUtils.isWindows ? javaExe : java;
+ }
+
+ return javaBin;
+ }
+
+ /*
+ * checkJVMSymlink returns true if the path in testBin *is* a java binary, or
+ * points to a java binary.
+ * @param testBin The binary or symbolic link to check
+ * @param winConsole whether we are in/want a Windows console (only relevant for Windows,
+ * determines whether we use java.exe or javaw.exe)
+ */
+ private static boolean checkJVMSymlink(String testBin, boolean winConsole)
+ {
+ File testBinFile = new File(testBin);
+ if (!testBinFile.exists())
+ {
+ return false;
+ }
+ File targetFile = null;
+ try
+ {
+ targetFile = testBinFile.getCanonicalFile();
+ } catch (IOException e)
+ {
+ return false;
+ }
+ final String javaExe = winConsole ? "java.exe" : "javaw.exe";
+ if (targetFile != null && ("java".equals(targetFile.getName())
+ || javaExe.equals(targetFile.getName())))
+ {
+ return true;
+ }
+ return false;
+ }
}
<parent>
<groupId>com.threerings.getdown</groupId>
<artifactId>getdown</artifactId>
- <version>1.8.3-1.2.14_FJVL</version>
+ <version>1.8.3-1.3.0_FJVL</version>
</parent>
<artifactId>getdown-launcher</artifactId>
if [ x$JVLVERSION != x ]; then
export VERSION=$JVLVERSION
else
- export VERSION=1.8.3-1.2.14_JVL
+ export VERSION=1.8.3-1.3.0_JVL
fi
if [ x${VERSION%_JVL} = x$VERSION ]; then
<groupId>com.threerings.getdown</groupId>
<artifactId>getdown</artifactId>
<packaging>pom</packaging>
- <version>1.8.3-1.2.14_FJVL</version>
+ <version>1.8.3-1.3.0_FJVL</version>
<name>getdown</name>
<description>An application installer and updater.</description>
<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="structureandpaefromfile" url="html/features/structurechooser.html#loadfromfile" />
<mapID target="structuresvia3dbeacons" url="html/features/structurechooser.html#3dbeaconssearch" />
+ <mapID target="workingwithpae" url="html/features/paematrices.html" />
+ <mapID target="paematrixformat" url="html/io/paematrixformat.html" />
<mapID target="selectcolbyannot" url="html/features/columnFilterByAnnotation.html" />
<mapID target="biojsmsa" url="html/features/biojsmsa.html" />
<!-- DO NOT WRAP THESE LINES - help2Website relies on each item being on one line! -->
<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="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" target="jalviewcltool"/>
+ <tocitem text="Latest Release Notes" target="release"/>
+ <tocitem text="Next Generation Command Line Interface" target="clarguments" />
+ <tocitem text="AlphaFold PAE Matrices" target="workingwithpae" />
+ <tocitem text="Nucleotide Ambiguity colours" target="colours.nucleotideambiguity" />
</tocitem>
<tocitem text="Editing Alignments" target="edit" />
<h2><a name="alignmentlinkedids"></a>Alignment linked IDs</h2>
<p>
- Jalview's alignment related arguments are linked together using a <em>linked ID</em>. In all of the basic usage examples this linked ID is assigned using a default formula of <code>JALVIEW:<em>n</em></code> where <em>n</em> starts at 0 and increments every time there is an <code>--open</code>ed file (or a first use of <code>--append</code>) or the <code>--new</code> argument is used.
+ Jalview's alignment related arguments are linked together using a <em>linked ID</em>. In all of the basic usage examples this linked ID is assigned using a default formula of <code>JALVIEW:<em>n</em></code> where <em>n</em> starts at 0 and increments every time there is an <code>‑‑open</code>ed file (or a first use of <code>‑‑append</code>) or the <code>‑‑new</code> argument is used.
</p>
<p>
- When another alignment related argument is used (without a specified linked ID), it is assigned this default linked ID. When the <code>--all</code> argument is used, following alignment related arguments are applied to all of the linked IDs (made so far).
+ When another alignment related argument is used (without a specified linked ID), it is assigned this default linked ID. When the <code>‑‑all</code> argument is used, following alignment related arguments are applied to all of the linked IDs (made so far).
</p>
<p>
</p>
<p>
- A specified linked ID will also take precedence over a wildcard or <code>--all</code> set linked ID. e.g.
+ A specified linked ID will also take precedence over a wildcard or <code>‑‑all</code> set linked ID. e.g.
<pre>
jalview --open[myID] examples/uniref50.fa --all --colour taylor --colour[myID] gecos-blossom
</pre>
</p>
- <h2><a name="moresubstitutions"></a>More substitutions (<code>{n}</code>, <code>{++n}</code>, <code>[*]</code>)</h2>
+ <h2><a name="moresubstitutions"></a>More substitutions (<code>{n}</code>, <code>{++n}</code>, <code>[*]</code>, <code>{m}</code>, <code>{++m}</code>)</h2>
<p>
In the <a href="clarguments-basic.html#substitutions">basic usage document</a> we have a list of special strings that get replaced in output filename values with parts of input filename values.
</p>
<p>
- There is also an incrementor integer value <code>{n}</code> that can be put into both linked IDs and filenames and works across different linked IDs. Whenever you use <code>{n}</code> in a linked ID or filename value it is replaced with the current value of <em>n</em>. The initial value is 0, and it can be incremented by using the argument <code>--npp</code> or <code>--n++</code>, or using a another special substitution <code>{++n}</code> in either a linked ID or filename value which increments the value and is replaced with the new incremented value of <em>n</em>.
+ There is also an incrementor integer value <code>{n}</code> that can be put into both linked IDs and filenames and works across different linked IDs. Whenever you use <code>{n}</code> in a linked ID or filename value it is replaced with the current value of <em>n</em>. The initial value is 0, and it can be incremented by using the argument <code>‑‑npp</code> or <code>‑‑n++</code>, or using a another special substitution <code>{++n}</code> in either a linked ID or filename value which increments the value and is replaced with the new incremented value of <em>n</em>.
</p>
<p>
- In the same way that the <code>--all</code> argument enables (some) following arguments to apply to all opened alignments so far, the special linked ID <code>*</code> will also apply an individual argument to all opened linked IDs (in fact when you use the <code>--all</code> argument it simply changes the default linked ID to <code>*</code>).
+ In the same way that the <code>‑‑all</code> argument enables (some) following arguments to apply to all opened alignments so far, the special linked ID <code>*</code> will also apply an individual argument to all opened linked IDs (in fact when you use the <code>‑‑all</code> argument it simply changes the default linked ID to <code>*</code>).
<pre>
jalview --open[myId1] fileA.fa --open[myId2] fileB.fa --open[myId3] fileC.fa --colour[*] taylor --all --image tmp/image-{++n}.png --headless
</pre>
</pre>
because all of the command line arguments are read and sorted into their linked IDs before starting to be processed, and the <code>[myId3]</code> specified linked ID takes precedence over the <code>[*]</code> wildcard linked ID.
</p>
- </p>
+ <p>
+ All of the substitutions talked about so far are evaluated in the argument parsing process. If in some cases (almost certainly involving structure images!) you find <code>{n}</code> is not incrementing when you think it should, when specifying <code>‑‑structureimage</code> filenames you can also use <code>{m}</code> and <code>{++m}</code>, along with <code>{structuredirname}</code>, <code>{structurebasename}</code> and <code>{structureextension}</code> which are substituted at the point of use. <code>{m}</code> is just a plain counter starting at 0.
+ </p>
<h2><a name="equalsseparatorandfileglobs"></a>Equals separator and Java file globs</h2>
</p>
<p>
- One benefit of this is seen above in the <code>--image</code> argument, the special "alloutput" wildcard filename <code>*.png</code> will not be expanded by the shell, so does not need to be escaped or surrounded with quotation marks.
+ One benefit of this is seen above in the <code>‑‑image</code> argument, the special "alloutput" wildcard filename <code>*.png</code> will not be expanded by the shell, so does not need to be escaped or surrounded with quotation marks.
</p>
<p>
</p>
<p>
- Some arguments (such as <code>--scale=<em>n</em></code>) are used to modify the behaviour of other "primary" arguments (such as <code>--image=filename</code>). These arguments can alternatively be specifed as <em>sub-value modifiers</em> of the values given to the primary argument. If specified as a sub-value modifier, this modifier takes precedence over any following linked argument if given. e.g
+ Some arguments (such as <code>‑‑scale=<em>n</em></code>) are used to modify the behaviour of other "primary" arguments (such as <code>‑‑image=filename</code>). These arguments can alternatively be specifed as <em>sub-value modifiers</em> of the values given to the primary argument. If specified as a sub-value modifier, this modifier takes precedence over any following linked argument if given. e.g
<pre>
jalview --open=[colour=zappo]examples/*.fa
</pre>
</p>
<p>
- You can specify multiple sub-value modifiers separating them with a comma (','). If you wish to specify a "boolean" argument, such as <code>--wrap</code> or <code>--nowrap</code> then simply use the argument name without a value, like this:
+ You can specify multiple sub-value modifiers separating them with a comma (','). If you wish to specify a "boolean" argument, such as <code>‑‑wrap</code> or <code>‑‑nowrap</code> then simply use the argument name without a value, like this:
<pre>
jalview --open=[colour=gecos-flower,wrap,noannotations,features=examples/plantfdx.features]examples/plantfdx.fa
</pre>
</p>
<p>
- Because <code>--argfiles</code> takes a filename argument, and multiple <code>--argfiles</code> can be read on the command line, you can also use file globs to specify multiple <code>--argfile</code> values. If you produce an argument file for each set of alignment files that you wish to associate then you can act on all of them with, e.g.
+ Because <code>‑‑argfiles</code> takes a filename argument, and multiple <code>‑‑argfiles</code> can be read on the command line, you can also use file globs to specify multiple <code>‑‑argfile</code> values. If you produce an argument file for each set of alignment files that you wish to associate then you can act on all of them with, e.g.
<pre>
jalview --argfile=*/argfile.txt --headless
</pre>
<h2><a name="onlyargumentfiles"></a>Only argument files</h2>
<p>
- When you use an <code>--argfile</code> argument, all other non-initialising arguments on the command line <em>will be ignored</em>. Only the initialising arguments and any and all <code>--argfiles</code> arguments on the command line will be used. You can also set initialising arguments in argument files.
+ When you use an <code>‑‑argfile</code> argument, all other non-initialising arguments on the command line <em>will be ignored</em>. Only the initialising arguments and any and all <code>‑‑argfiles</code> arguments on the command line will be used. You can also set initialising arguments in argument files.
</p>
<li><a href="#alloutputwildcard">The all output wildcard</a></li>
</ul>
- <h2><a name="openingalignments"></a>Opening alignments (<code>--open</code>, <code>--append</code>, <code>--new</code>)</h2>
+ <h2><a name="openingalignments"></a>Opening alignments (<code>‑‑open</code>, <code>‑‑append</code>, <code>‑‑new</code>)</h2>
<p>
- To simply open one or more alignment files in different windows just put the filenames as the first arguments:
+ To simply open one or more alignment files in different alignment windows just put the filenames as the first arguments:
<pre>
jalview filename1 filename2 ...
</pre>
</p>
<p>
- (Using initial filenames is the same as using the <code>--open</code> argument, and further arguments can be used
+ (Using initial filenames is the same as using the <code>‑‑open</code> argument, and further arguments can be used
after the initial filenames.)
</p>
- <h3><a name="open"></a><code>--open</code></h3>
+ <h3><a name="open"></a><code>‑‑open</code></h3>
<p>
- Use the <code>--open</code> argument to open alignment files each in their own window.
+ Use the <code>‑‑open</code> argument to open alignment files each in their own window.
</p>
<p>
</pre>
</p>
- <h3><a name="append"></a><code>--append</code></h3>
+ <h3><a name="append"></a><code>‑‑append</code></h3>
<p>
To append several alignment files together use:
<pre>
jalview --open filename1.fa --append filename2.fa filename3.fa
</pre>
- or, if you haven't previously used <code>--open</code> then you can use --append to open one new window and keep appending each set of alignments:
+ or, if you haven't previously used <code>‑‑open</code> then you can use --append to open one new window and keep appending each set of alignments:
<pre>
jalview --append these/filename*.fa --append more/filename*.fa
</p>
<p>
- <strong>Note</strong> that whilst you can include a Jalview Project File (<code>.jvp</code>) as an <code>--append</code> value, the items in the file will always open in their original windows and not append to another.
+ <strong>Note</strong> that whilst you can include a Jalview Project File (<code>.jvp</code>) as an <code>‑‑append</code> value, the items in the file will always open in their original windows and not append to another.
</p>
- <h3><a name="new"></a><code>--new</code></h3>
+ <h3><a name="new"></a><code>‑‑new</code></h3>
<p>
- To append different sets of alignment files in different windows, use <code>--new</code> to move on to a new alignment window:
+ To append different sets of alignment files in different windows, use <code>‑‑new</code> to move on to a new alignment window:
<pre>
jalview --append these/filename*.fa --new --append other/filename*.fa
</pre>
</p>
<p>
- <code>--open</code> is like using <code>--new --append</code> applied to every filename/URL given to <code>--open</code>
+ <code>‑‑open</code> is like using <code>‑‑new --append</code> applied to every filename/URL given to <code>‑‑open</code>
</p>
- <h2><a name="alignmentoptions"></a>Alignment options (<code>--colour</code>, <code>--wrap</code>, <code>--showannotations</code>, <code>--title</code>)</h2>
+ <h2><a name="alignmentoptions"></a>Alignment options (<code>‑‑colour</code>, <code>‑‑wrap</code>, <code>‑‑showannotations</code>, <code>‑‑title</code>)</h2>
- <h3><a name="colour"></a><code>--colour</code></h3>
+ <p>
+ An opened alignment window (or set of opened alignment windows) can be modified in its appearance using the following arguments before the next <code>‑‑open</code> argument. These modifying arguments apply to the one or more files that were opened with the preceding <code>‑‑open</code> argument. E.g. <code>‑‑open file.fa --colour gecos-flower</code> will colour the one alignment window with <code>file.fa</code>. However, <code>‑‑open *.fa --colour gecos-flower</code> will colour every alignment window matching <code>file*.fa</code>, and <code> --open file1.fa file2.fa --colour gecos-flower</code>
+ will colour both opened alignment windows.
+ </p>
+
+ <h3><a name="colour"></a><code>‑‑colour</code></h3>
<p>
- You can specify a residue/base colouring for the alignment using the <code>--colour</code> option (note spelling -- Jalview is made in Scotland!):
+ You can specify a residue/base colouring for the alignment using the <code>‑‑colour</code> option (note spelling -- Jalview is made in Scotland!):
<pre>
jalview --open examples/uniref50.fa --colour gecos-flower
</pre>
<code>sequence-id</code>
</p>
- <h3><a name="wrap"></a><code>--wrap</code></h3>
+ <h3><a name="wrap"></a><code>‑‑wrap</code></h3>
<p>
- An alignment should open with your usual preferences stored in the <code>.jalview_properties</code> file. To open an alignment with the sequences (definitely) wrapped, following your <code>--open</code> (or first <code>--append</code>) argument use the argument <code>--wrap</code>:
+ An alignment should open with your usual preferences stored in the <code>.jalview_properties</code> file. To open an alignment with the sequences (definitely) wrapped, following your <code>‑‑open</code> (or first <code>‑‑append</code>) argument use the argument <code>‑‑wrap</code>:
<pre>
jalview --open examples/uniref50.fa --wrap
</pre>
- To ensure an alignment is not wrapped use <code>--nowrap</code>:
+ To ensure an alignment is not wrapped use <code>‑‑nowrap</code>:
<pre>
jalview --open examples/uniref50.fa --nowrap
</pre>
</p>
- <h3><a name="showannotations"></a><code>--showannotations</code> / <code>--noshowannotations</code></h3>
+ <h3><a name="showannotations"></a><code>‑‑showannotations</code> / <code>‑‑noshowannotations</code></h3>
<p>
- You can specify whether the currently opened alignment window should show alignment annotations (e.g. Conservation, Quality, Consensus...) or not with either <code>--showannotations</code> or <code>--noshowannotations</code>. If you don't specify then your saved preference will be used.
+ You can specify whether the currently opened alignment window should show alignment annotations (e.g. Conservation, Quality, Consensus...) or not with either <code>‑‑showannotations</code> or <code>‑‑noshowannotations</code>. If you don't specify then your saved preference will be used.
<pre>
jalview --open examples/uniref50.fa --noshowannotations
</pre>
</p>
- <h3><a name="title"></a><code>--title</code></h3>
+ <h3><a name="title"></a><code>‑‑title</code></h3>
<p>
- If you would like to give the alignment window a specific title you can do so with the <code>--title</code> option:
+ If you would like to give the alignment window a specific title you can do so with the <code>‑‑title</code> option:
<pre>
jalview --open examples/uniref50.fa --title "My example alignment"
</pre>
- <h2><a name="adding3dstructures"></a>Adding 3D structures (<code>--structure</code>, <code>--seqid</code>, <code>--structureviewer</code>, <code>--paematrix</code>, <code>--tempfac</code>, <code>--showssannotations</code>)</h2>
+ <h2><a name="adding3dstructures"></a>Adding 3D structures (<code>‑‑structure</code>, <code>‑‑seqid</code>, <code>‑‑structureviewer</code>, <code>‑‑paematrix</code>, <code>‑‑tempfac</code>, <code>‑‑showssannotations</code>)</h2>
<p>
</p>
- <h3><a name="structure"></a><code>--structure</code></h3>
+ <h3><a name="structure"></a><code>‑‑structure</code></h3>
<p>
- You can add a 3D structure file to a sequence in the current alignment window with the <code>--structure</code> option:
+ You can add a 3D structure file to a sequence in the current alignment window with the <code>‑‑structure</code> option:
<pre>
jalview --open examples/uniref50.fa --structure examples/AlphaFold/AF-P00221-F1-model_v4.pdb
</pre>
By default this attaches to the first sequence in the alignment but most likely you will want to attach it to a specific sequence.
</p>
- <h3><a name="seqid"></a><code>--seqid</code></h3>
+ <h3><a name="seqid"></a><code>‑‑seqid</code></h3>
<p>
- The easiest way to specify a sequence ID for your structure is to follow the <code>--structure</code> argument with a <code>--seqid</code> argument with a value of a sequence ID in the alignment. This does of course require some knowledge of the sequences in the alignment files
+ The easiest way to specify a sequence ID for your structure is to follow the <code>‑‑structure</code> argument with a <code>‑‑seqid</code> argument with a value of a sequence ID in the alignment. This does of course require some knowledge of the sequences in the alignment files
that have been opened.
<br/>
- Alternatively you can specify a <em>sub-value</em> with the <code>--structure</code> argument value. You do this by preceding the value with square brackets and <code>seqid=SequenceId</code>,
+ Alternatively you can specify a <em>sub-value</em> with the <code>‑‑structure</code> argument value. You do this by preceding the value with square brackets and <code>seqid=SequenceId</code>,
like this:
<pre>
jalview --open examples/uniref50.fa --structure [seqid=FER1_SPIOL]examples/AlphaFold/AF-P00221-F1-model_v4.pdb
</p>
<p>
- The sub-value <code>seqid=FER1_SPIOL</code> takes precedence over the following argument <code>--seqid FER1_SPIOL</code> if you accidentally specify both (in which case the argument will probably be completely unused).
+ The sub-value <code>seqid=FER1_SPIOL</code> takes precedence over the following argument <code>‑‑seqid FER1_SPIOL</code> if you accidentally specify both (in which case the argument will probably be completely unused).
</p>
<p>
Remember that you might need to escape any spaces in the sequence ID or enclose the ID in quotation marks.
</p>
- <h3><a name="structureviewer"></a><code>--structureviewer</code></h3>
+ <h3><a name="structureviewer"></a><code>‑‑structureviewer</code></h3>
<p>
- You can specify which structure viewer (or none) to use to open the structure using either the <code>--structureviewer</code> argument or the <code>structureviewer</code> sub-value. Multiple sub-values can be specified together, separated by a comma ','. Possible values for the <code>structureviewer</code> are:
+ You can specify which structure viewer (or none) to use to open the structure using either the <code>‑‑structureviewer</code> argument or the <code>structureviewer</code> sub-value. Multiple sub-values can be specified together, separated by a comma ','. Possible values for the <code>structureviewer</code> are:
<br/>
<code>none</code>,
<br/>
</pre>
</p>
- <h3><a name="paematrix"></a><code>--paematrix</code></h3>
+ <h3><a name="paematrix"></a><code>‑‑paematrix</code></h3>
<p>
- If you are opening a structure file that has a PAE matrix (provided as a JSON file), such as from an AlphaFold model or an nf-core pipeline, you can add the PAE matrix as an annotation by following the <code>--structure</code> argument with a <code>--paematrix</code> argument with the filename. You can also specify a <code>paematrix=filename</code> sub-value.
+ If you are opening a structure file that has a PAE matrix (provided as a JSON file), such as from an AlphaFold model or an nf-core pipeline, you can add the PAE matrix as an annotation by following the <code>‑‑structure</code> argument with a <code>‑‑paematrix</code> argument with the filename. You can also specify a <code>paematrix=filename</code> sub-value.
<pre>
jalview --open examples/uniref50.fa --structure [seqid=FER1+SPIOL,structureviewer=pymol]examples/AlphaFold/AF-P00221-F1-model_v4.pdb --paematrix examples/AlphaFold/AF-P00221-F1-predicted_aligned_error_v4.json
</pre>
</p>
- <h3><a name="tempfac"></a><code>--tempfac</code></h3>
+ <h3><a name="tempfac"></a><code>‑‑tempfac</code></h3>
<p>
- Structure files may have a temperature factor associated with the structure component positions. If the temperature factor is a pLDDT confidence score, such as with an AlphaFold model, you can specify this by using a following argument of <code>--tempfac</code> with a value of <code>plddt</code>. This will enable standard pLDDT colouring of the temperature factor annotation. Valid values are:
+ Structure files may have a temperature factor associated with the structure component positions. If the temperature factor is a pLDDT confidence score, such as with an AlphaFold model, you can specify this by using a following argument of <code>‑‑tempfac</code> with a value of <code>plddt</code>. This will enable standard pLDDT colouring of the temperature factor annotation. Valid values are:
<code>default</code>,
<code>plddt</code>.
More types of temperature factor may be added in future releases of Jalview.
<!-- notempfac not yet working. undocumented until then -->
- <h3><a name="showssannotations"></a><code>--showssannotations</code> / <code>--noshowssannotations</code></h3>
+ <h3><a name="showssannotations"></a><code>‑‑showssannotations</code> / <code>‑‑noshowssannotations</code></h3>
<p>
- You can specify whether the currently opened alignment window should show secondary structure annotations or not with either <code>--showssannotations</code> or <code>--noshowssannotations</code>. If you don't specify then your saved preference will be used.
+ You can specify whether the currently opened alignment window should show secondary structure annotations or not with either <code>‑‑showssannotations</code> or <code>‑‑noshowssannotations</code>. If you don't specify then your saved preference will be used.
<pre>
jalview --open examples/uniref50.fa --structure examples/AlphaFold/AF-P00221-F1-model_v4.pdb --noshowssannotations
</pre>
</pre>
</p>
- <h2><a name="outputtingalignmentfiles"></a>Outputting/converting alignment files and images (<code>--output</code>, <code>--format</code>, <code>--image</code>, <code>--type</code>, <code>--textrenderer</code>, <code>--scale</code>, <code>--backups</code>, <code>--overwrite</code>)</h2>
+ <h2><a name="outputtingalignmentfiles"></a>Outputting/converting alignment files and images (<code>‑‑output</code>, <code>‑‑format</code>, <code>‑‑image</code>, <code>‑‑structureimage</code>, <code>‑‑type</code>, <code>‑‑scale</code>, <code>‑‑width</code>, <code>‑‑height</code>, <code>‑‑imagecolour</code>, <code>‑‑bgcolour</code>, <code>‑‑textrenderer</code>, <code>‑‑overwrite</code>, <code>‑‑backups</code>, <code>‑‑mkdirs</code>)</h2>
<p>
You can save an alignment as an alignment file, or exported as an image, in different formats. Jalview's alignment output formats are:
In bitmap formats (currently only PNG, but what else would you want?!) you can specify a scaling factor to improve the resolution of the output image.
</p>
- <h3><a name="output"></a><code>--output</code></h3>
+ <h3><a name="output"></a><code>‑‑output</code></h3>
<p>
- To save the open alignment in a new alignment file use <code>--output filename</code>. The format for the file can be found from the extension of <code>filename</code>, or if you are using a non-standard extension you can use a following <code>--format</code> argument, or specify it as a sub-value modifier.
+ To save the open alignment in a new alignment file use <code>‑‑output filename</code>. The format for the file can be found from the extension of <code>filename</code>, or if you are using a non-standard extension you can use a following <code>‑‑format</code> argument, or specify it as a sub-value modifier.
</p>
<p>
Recognised formats and their recognised extensions are:
<code>phylip</code> (<code>phy</code>),
<br/>
<code>jalview</code> (<code>jvp, jar</code>).
+ </p>
<p>
For example, to open a FASTA file, append another FASTA file and then save the concatenation as a Stockholm file, do
<pre>
</p>
<p>
- <em>Important!</em> If you use <code>--output</code> or any other argument that outputs a file, then it will be assumed you want to run Jalview in headless mode (as if you had specified <code>--headless</code>). To use Jalview with <code>--output</code> and not assume headless mode, use the <code>--gui</code> or <code>--noheadless</code> argument (the order doesn't matter).
+ <em>Important!</em> If you use <code>‑‑output</code> or any other argument that outputs a file, then it will be assumed you want to run Jalview in headless mode (as if you had specified <code>‑‑headless</code>). To use Jalview with <code>‑‑output</code> and not assume headless mode, use the <code>‑‑gui</code> argument (the order doesn't matter).
</p>
- <h3><a name="format"></a><code>--format</code></h3>
+ <p>
+ If you would like to output an alignment file directly to standard output (often referred to as STDOUT), then use the filename <code>-</code> (a single hyphen). In this case any messages that would normally appear on STDOUT will be diverted to STDERR to avoid invalidating the output file.
+ </p>
+ <p>
+ For example, to open a Stockholm file and pipe it to another command as a Block file, do
+ <pre>
+ jalview --open alignment1.stk --output - --format blc | another_command
+ </pre>
+ or equivalently
+ <pre>
+ jalview alignment1.stk --output=[format=blc]- | another_command
+ </pre>
+ </p>
+
+ <h3><a name="format"></a><code>‑‑format</code></h3>
<p>
- To specify the format of the output file (if using an unrecognised file extension) use the <code>--format</code> argument to specify a value (see above). A sub-value modifier on the <code>--output</code> value can also be used.
+ To specify the format of the output file (if using an unrecognised file extension) use the <code>‑‑format</code> argument to specify a value (see above). A sub-value modifier on the <code>‑‑output</code> value can also be used.
+ </p>
+
+ <h3><a name="image"></a><code>‑‑image</code></h3>
+ <p>
+ To export the open alignment window as an image, use the <code>‑‑image</code> argument, which will give an image of the alignment and annotations as it appears (or would appear if not in <code>‑‑headless</code> mode) in the alignment window if it was large enough for the whole alignment, including colour scheme and features.
+ </p>
+ <p>
+ <pre>
+ jalview --open examples/plantfdx.fa --colour gecos-blossom --features examples/plantfdx.features --annotations examples/plantfdx.annotations --image plantfdx.png --headless
+ </pre>
</p>
- <h3><a name="image"></a><code>--image</code></h3>
- To export the open alignment window as an image, use the <code>--image</code> argument, which will give an image of the alignment and annotations as it appears (or would appear if not in <code>--headless</code> mode) in the alignment window if it was large enough for the whole alignment, including colour choice and features.
+ <h3><a name="structureimage"></a><code>‑‑structureimage</code></h3>
+ <p>
+ To export an open structure as an image, use the <code>‑‑structureimage</code> argument, which will give an image of the structure as it appears (or would appear if not in <code>‑‑headless</code> mode) in a Jmol window including colour scheme. <code>‑‑structureimage</code> can currently only be used with structures opened with the <code>jmol</code> structureviewer (the default viewer).
+ </p>
<p>
<pre>
jalview --open examples/plantfdx.fa --colour gecos-blossom --features examples/plantfdx.features --annotations examples/plantfdx.annotations --image plantfdx.png --headless
</p>
<p>
- This by default produces a PNG image of screen or webpage resolution, which you may want to improve upon. There are two ways of doing this with Jalview: increasing the scale of the PNG image, or using a vector based image format (EPS, SVG, HTML).
+ These by default produce a PNG image of screen or webpage resolution, which you will probably want to improve upon. There are two ways of doing this with Jalview: increasing the scale of the PNG image, or using a vector based image format (EPS, SVG, HTML).
<p>
+ <h3><a name="type"></a><code>‑‑type</code></h3>
+
+ <p>
+ To specify the type of image file to write (if using an unrecognised file extension) use the <code>‑‑type</code> argument to specify a value (see above). A sub-value modifier on the <code>‑‑image</code> and <code>‑‑structureimage</code> value can also be used. Valid values are:
+ <br/>
+ <code>png</code> - A Portable Network Graphics image (bitmap, default),
+ <br/>
+ <code>svg</code> - A Scalable Vector Graphics image (vector),
+ <br/>
+ <code>eps</code> - An Encapsulated PostScript file (vector),
+ <br/>
+ <code>html</code> - An HTML rendition of the alignment with embedded source data (vector/web browser),
+ <br/>
+ <code>biojs</code> - An HTML rendition of the alignment with interactive MSA viewer <a href="biojsmsa.html">BioJS-MSA</a> (vector).
+ </p>
+
<h3><a name="bitmap"></a>Bitmap image types (<code>png</code>)</h3>
<p>
Let's increase the resolution of the PNG image:
</p>
- <h3><a name="scale"></a><code>--scale</code></h3>
+ <h3><a name="scale"></a><code>‑‑scale</code></h3>
<p>
- We can increase the size of the PNG image by a factor of <em>S</em> by following the <code>--image</code> argument with a <code>--scale <em>S</em></code> argument and value. The value doesn't have to be an integer and should be given as an integer or floating point formatted number, e.g.
+ We can increase the size of the PNG image by a factor of <em>S</em> by following the <code>‑‑image</code> or <code>‑‑structureimage</code> argument with a <code>‑‑scale <em>S</em></code> argument and value. The value doesn't have to be an integer and should be given as an integer or floating point formatted number, e.g.
<pre>
jalview --open examples/uniref50.fa --colour gecos-ocean --image mypic.png --scale 5.5 --headless
</pre>
- which will produce a PNG image 5.5 times larger (and more detailed) than without the <code>--scale</code> argument.
+ which will produce a PNG image 5.5 times larger (and more detailed) than without the <code>‑‑scale</code> argument.
</p>
<p>
However, since you won't necessarily already know the size of an alignment's exported image you can specify either an exact width or height (in pixels) with either one of the
- <code>--width</code> and <code>--height</code> arguments:
+ <code>‑‑width</code> and <code>‑‑height</code> arguments:
- <h3><a name="width"></a><code>--width</code></h3>
+ <h3><a name="width"></a><code>‑‑width</code></h3>
<p>
- Specify an exact width of an exported PNG image with <code>--width</code>:
+ Specify an exact width of an exported PNG image with <code>‑‑width</code>:
<pre>
jalview --headless --open https://www.ebi.ac.uk/interpro/api/entry/pfam/PF03760/?annotation=alignment%3Aseed --noshowannotations --colour gecos-sunset --image wallpaper.png --width 3840
</pre>
</p>
- <h3><a name="height"></a><code>--height</code></h3>
+ <h3><a name="height"></a><code>‑‑height</code></h3>
<p>
- Alternatively specify an exact height with the <code>--height</code> argument:
+ Alternatively specify an exact height with the <code>‑‑height</code> argument:
<pre>
jalview --headless --open https://www.ebi.ac.uk/interpro/api/entry/pfam/PF03760/?annotation=alignment%3Aseed --noshowannotations --colour gecos-ocean --image wallpaper.png --height 2160
</pre>
</p>
<p>
- You can specify two or all of <code>--scale</code>, <code>--width</code> and <code>--height</code> as limits to the size of the image (think of one or two bounding boxes) and the one which produces the smallest scale of image is used. You can also specify each of these as sub-value modifiers to the <code>--image</code> value:
+ You can specify two or all of <code>‑‑scale</code>, <code>‑‑width</code> and <code>‑‑height</code> as limits to the size of the image (think of one or two bounding boxes) and the one which produces the smallest scale of image is used. You can also specify each of these as sub-value modifiers to the <code>‑‑image</code> or <code>‑‑structureimage</code> value:
<pre>
jalview --headless --open https://www.ebi.ac.uk/interpro/api/entry/pfam/PF03760/?annotation=alignment%3Aseed --noshowannotations --colour gecos-flower --image [scale=0.25,width=320,height=240]thumbnail.png
</pre>
</p>
+ <h3><a name="imagecolour"></a><code>‑‑imagecolour</code></h3>
+
+ <p>
+ Specify a colour scheme to use just for this image using the <code>‑‑imagecolour</code> argument:
+ <pre>
+ jalview --open examples/uniref50.fa --colour gecos-flower --image uniref50-residues.png --height 2160 --image uniref50-helix.png --imagecolour helix-propensity --width 800 --image uniref50-turn.png --imagecolour turn-propensity --width 800
+ </pre>
+ </p>
+
+ <h3><a name="bgcolour"></a><code>‑‑bgcolour</code></h3>
+
+ <p>
+ <strong>Only applies to <code>‑‑structureimage</code>.</strong> Specify a background colour for a structure image. The colour can be specified as a named colour recognised by Java (e.g. <code>"white"</code>, <code>"cyan"</code>) or as a RRGGBB 6 digit hex string (e.g. <code>ffffff</code>, <code>00ffff</code>).
+ </p>
+ <p>
+ E.g.
+ <pre>
+ jalview --open examples/uniref50.fa --colour gecos-sunset --structure examples/AF-P00221-F1-model_v4.pdb --seqid FER1_SPIOL --structureimage temp.png --bgcolour magenta
+ </pre>
+ </p>
+
<p>
Next we look at vector image formats, which maintain detail at all resolutions.
</p>
- <h3><a name="vector"></a>Vector image export</h3>
+ <h3><a name="vector"></a>Vector image export (<code>svg</code>, <code>eps</code>, <code>html</code>, <code>biojs</code>)</h3>
<p>
- Jalview can export an alignment in Encapsulated PostScript (<code>eps</code>), Scalable Vector Graphics (<code>svg</code>), HTML (<code>html</code>) or BioJSON -- another HTML format (<code>biojs</code>), by using, e.g.
+ Jalview can export an alignment in Encapsulated PostScript (<code>eps</code>), Scalable Vector Graphics (<code>svg</code>), HTML (<code>html</code>) or <a href="biojsmsa.html">BioJSON</a> -- another HTML format with an interactive MSA viewer (<code>biojs</code>), by using, e.g.
<pre>
jalview --open examples/uniref50.fa --colour gecos-flower --image printable.eps
</pre>
- The image format can be specified with the <code>--type</code> argument or as a sub-value modifier on the <code>--image</code> value. If neither is used the <code>type</code> will be guessed from the image file extension. The following three examples should produce the same contents:
+ The image format can be specified with the <code>‑‑type</code> argument or as a sub-value modifier on the <code>‑‑image</code> value. If neither is used the <code>type</code> will be guessed from the image file extension. The following three examples should produce the same contents:
<pre>
jalview --open examples/uniref50.fa --colour gecos-flower --image printable.eps
jalview --open examples/uniref50.fa --colour gecos-flower --image printable.postscript --type eps
jalview --open examples/uniref50.fa --colour gecos-flower --image [type=eps]printable.postscript
+ jalview --open examples/uniref50.fa --colour gecos-flower --image [type=biojs]printable.html
</pre>
</p>
- <h3><a name="textrenderer"></a><code>--textrenderer</code></h3>
+ <h3><a name="textrenderer"></a><code>‑‑textrenderer</code></h3>
<p>
- In a vector format any text that appears on the page (including residue/base labels) can be saved in the image file either as <code>text</code> or as <code>lineart</code> using the <code>--textrenderer</code> argument. This is only available for <code>eps</code>, <code>svg</code> and <code>html</code> formats.
+ In a vector format any text that appears on the page (including residue/base labels) can be saved in the image file either as <code>text</code> or as <code>lineart</code> using the <code>‑‑textrenderer</code> argument. This is only available for <code>eps</code>, <code>svg</code> and <code>html</code> formats.
</p>
<p>
</p>
<p>
- The type of <code>--textrenderer</code> can be specified with an argument following <code>--image</code> or as a sub-value modifier:
+ The type of <code>‑‑textrenderer</code> can be specified with an argument following <code>‑‑image</code> or as a sub-value modifier:
<pre>
jalview --open examples/uniref50.fa --colour gecos-flower --image printable.html --type biojs
jalview --open examples/uniref50.fa --colour gecos-flower --image [type=eps,textrenderer=lineart]printable.ps
</pre>
</p>
+ <h3><a name="outputbehaviour"></a>Output behaviour</h3>
- <h2><a name="filenamesubstitutionsandbatchprocessing"></a>Filename substitutions and batch processing (<code>--substitutions</code>, <code>--close</code>, <code>--all</code>)</h2>
+ <h3><a name="overwrite"></a><code>‑‑overwrite</code></h3>
+
+ <p>
+ By default, Jalview will refuse to overwrite an output file (alignment or image) unless backups are in operation (alignment files only). To force overwriting files, use the <code>‑‑overwrite</code> argument.
+ </p>
+
+ <h3><a name="backups"></a><code>‑‑backups / --nobackups</code></h3>
+
+ <p>
+ Jalview should honour your preferences for backup files of output alignment files. Using <code>‑‑backups</code> or <code>‑‑nobackups</code> forces the behaviour. With no backups set, you will need to use <code>‑‑overwrite</code> to overwrite an existing file. Note that Jalview does not make backup files of exported images.
+ </p>
+
+ <h3><a name="mkdirs"></a><code>‑‑mkdirs</code></h3>
+
+ <p>
+ If you want to output a file into a folder that doesn't yet exist (this might happen particularly when using <code>{dirname}</code> substitutions -- see below), then Jalview will fail to write the file since the parent directory doesn't exist. You can use <code>‑‑mkdirs</code> to tell Jalview to make the new directory (or directories, it will create several nested directories if necessary) before writing the file. <code>‑‑mkdirs</code> is cautious and will generally refuse to make a new directory using a relative path with <code>..</code> in.
+ </p>
+
+ <h2><a name="filenamesubstitutionsandbatchprocessing"></a>Filename substitutions and batch processing (<code>‑‑substitutions</code>, <code>‑‑close</code>, <code>‑‑all</code>)</h2>
<p>
One of the more powerful aspects of Jalview's command line operations is that stores all of the different opened alignment arguments (before opening them) and can apply some arguments to <em>all</em> of the alignments as they are opened. This includes display and output arguments.
</p>
<p>
+ Specifically for <code>‑‑structureimage</code> output, you can also use substitutions using parts of the structure filename:
+ <ul>
+ <li><code>{structuredirname}</code> -- is replaced by the directory path to the opened structure file.</li>
+ <li><code>{structurebasename}</code> -- is replaced by the base of the filename of the opened structure file. This is without the path or file extension (if there is one).</li>
+ <li><code>{structureextension}</code> -- is replaced by the extension of the filename of the opened structure file.</li>
+ </ul>
+ </p>
+
+ <p>
These filename substitutions are on by default, but if for whatever reason you wish to disable the substitutions, they can be turned off (or back on again) through the list of arguments with:
</p>
- <h3><a name="substitutions"></a><code>--substitutions / --nosubstitutions</code></h3>
+ <h3><a name="substitutions"></a><code>‑‑substitutions / --nosubstitutions</code></h3>
<p>
Enable (or disable) filename substitutions in the following argument values and sub-value modifier values.
</p>
<p>
- For opening single files this is less useful, since you could obviously just type the output filename, but for multiple opened alignments you can also use these substituted values and they will be replaced by the relevant part of the filename given for each opened alignment window. Normally an <code>--output</code> or <code>--image</code> argument will only be applied to the latest opened alignment window, but you can tell Jalview to apply some arguments to all alignments that have been opened (so far) by using the <code>--all</code> argument.
+ For opening single files this is less useful, since you could obviously just type the output filename, but for multiple opened alignments you can also use these substituted values and they will be replaced by the relevant part of the filename given for each opened alignment window. Normally an <code>‑‑output</code> or <code>‑‑image</code> argument will only be applied to the latest opened alignment window, but you can tell Jalview to apply some arguments to all alignments that have been opened (so far) by using the <code>‑‑all</code> argument.
</p>
- <h3><a name="all"></a><code>--all / -noall</code></h3>
+ <h3><a name="all"></a><code>‑‑all / -noall</code></h3>
<p>
- When using the <code>--all</code> argument, following arguments will apply to all of the previously opened alignment windows. You can turn this behaviour off again for following arguments using the <code>--noall</code> argument. The arguments that can apply to all previously opened alignments are:
+ When using the <code>‑‑all</code> argument, following arguments will apply to all of the previously opened alignment windows. You can turn this behaviour off again for following arguments using the <code>‑‑noall</code> argument. The arguments that can apply to all previously opened alignments are:
<br/>
- <code>--colour</code>
+ <code>‑‑colour</code>
<br/>
- <code>--sortbytree</code>
+ <code>‑‑sortbytree</code>
<br/>
- <code>--showannotations</code>
+ <code>‑‑showannotations</code>
<br/>
- <code>--wrap</code>
+ <code>‑‑wrap</code>
<br/>
- <code>--nostructure</code>
+ <code>‑‑nostructure</code>
<br/>
- <code>--notempfac</code>
+ <code>‑‑notempfac</code>
<br/>
- <code>--showssannotations</code>
+ <code>‑‑showssannotations</code>
<br/>
- <code>--image</code>
+ <code>‑‑image</code>
<br/>
- <code>--type</code>
+ <code>‑‑type</code>
<br/>
- <code>--textrenderer</code>
+ <code>‑‑textrenderer</code>
<br/>
- <code>--scale</code>
+ <code>‑‑scale</code>
<br/>
- <code>--width</code>
+ <code>‑‑width</code>
<br/>
- <code>--height</code>
+ <code>‑‑height</code>
<br/>
- <code>--output</code>
+ <code>‑‑output</code>
<br/>
- <code>--format</code>
+ <code>‑‑format</code>
<br/>
- <code>--groovy</code>
+ <code>‑‑groovy</code>
<br/>
- <code>--backups</code>
+ <code>‑‑backups</code>
<br/>
- <code>--overwrite</code>
+ <code>‑‑overwrite</code>
<br/>
- <code>--close</code>
+ <code>‑‑close</code>
</p>
<p>
- In particular, for our example above, we can use <code>-all</code> and <code>--output</code> like this (<code>--close</code> will be explained in a moment):
+ In particular, for our example above, we can use <code>-all</code> and <code>‑‑output</code> like this (<code>‑‑close</code> will be explained in a moment):
<pre>
jalview --open all_my_fasta_files/*.fa --all --output all_my_converted_stockholm_files/{basename}.stk --close --headless
</pre>
</pre>
</p>
- <h3><a name="close"></a><code>--close</code></h3>
+ <h3><a name="close"></a><code>‑‑close</code></h3>
<p>
- The <code>--close</code> tag is used to close an alignment window after all output files or image exports are performed. This reduces memory use, especially if an <code>--open</code> value is set to open many files. These will be opened, formatted and output sequentially so since they are closed before the next one is opened memory use will not build up over a large number of alignments.
+ The <code>‑‑close</code> tag is used to close an alignment window after all output files or image exports are performed. This reduces memory use, especially if an <code>‑‑open</code> value is set to open many files. These will be opened, formatted and output sequentially so since they are closed before the next one is opened memory use will not build up over a large number of alignments.
<pre>
</pre>
</p>
- <h2><a name="alloutputwildcard"></a>The all output wildcard: <code>--output "*.ext"</code>, <code>--image "*.ext"</code></h2>
+ <h2><a name="alloutputwildcard"></a>The all output wildcard: <code>‑‑output "*/*.ext"</code>, <code>‑‑image "*/*.ext"</code></h2>
+
+ <p>
+ Purely as an intuitive syntactic sweetener, you can use the <code>‑‑output</code> wildcard <code>*</code> in two places as part of an output path and filename.
+ </p>
+
+ <p>
+ Using an asterisk (<code>*</code>) as a filename before an extension, e.g. <code>‑‑image "tmp/*.png"</code> will result in that asterisk being treated as a <code>{basename}</code> substitution.
+ </p>
+
+ <p>
+ Using an asterisk (<code>*</code>) before a file separator (usually </code>/</code>), e.g. <code>‑‑image "tmp/*/file1.png"</code> will result in that asterisk being treated as a <code>{dirname}</code> substitution.
+ </p>
+
+ <p>
+ You can combine these, using an asterisk (<code>*</code>) before and after the last file separator, e.g. <code>‑‑image "tmp/*/*.png"</code> will result in being substituted like <code>tmp/{dirname}/{basename}.png</code>.
+ </p>
<p>
- Purely as an intuitive syntactic sweetener, you can use the <code>--output</code> wildcard <code>*</code> <em>at the beginning of the output filename</em> as shorthand for <code>--all --output {dirname}/{basename}</code> followed by whatever you put after the '<code>*</code>'. For example, to achieve the same as the thumbnails example above, you could use
+ For example, to achieve the same as the thumbnails example above, you could use
<pre>
- jalview --open */*.fa --image "*.png" --colour gecos-flower --width 256 --height 256 --close --headless
+ jalview --open */*.fa --image "*/*.png" --colour gecos-flower --width 256 --height 256 --close --headless
</pre>
- Here we move the <code>--colour</code> argument after the <code>--output</code> argument (it will still be applied before the image export or file output) so that it is included after the implied <code>--all</code> argument. The thumbnails will be placed in the same directory as the alignment file with the same filename except for a different extension of <code>.png</code>.
+ Here we move the <code>‑‑colour</code> argument after the <code>‑‑output</code> argument (it will still be applied before the image export or file output) so that it is included after the implied <code>‑‑all</code> argument. The thumbnails will be placed in the same directory as the alignment file with the same filename except for a different extension of <code>.png</code>.
</p>
<p>
</p>
<p>
- An alternative is to use an equals sign ('=') with no spaces between the argument and the value, <code>--output=*.ext</code>, which Jalview will interpret the same, but the shell will not automatically expand before it is sent to Jalview, e.g.
+ An alternative is to use an equals sign ('=') with no spaces between the argument and the value, <code>‑‑output=*.ext</code>, which Jalview will interpret the same, but the shell will not automatically expand before it is sent to Jalview, e.g.
<pre>
jalview --open all_my_fasta_files/*.fa --output=*.stk --close --headless
</pre>
<li><a href="#processingalignments">Processing alignments</a></li>
<li><a href="#outputtingalignmentfiles">Outputting alignment files</a></li>
<li><a href="#exportingimagefiles">Exporting image files</a></li>
- <li><a href="#exporting3dstructureimagefiles">Exporting 3D structure image files</a></li>
<li><a href="#controllingflowofarguments">Controlling flow of arguments</a></li>
</ul>
<tr valign="top"><td><code>‑‑help‑all</code></td><td>Help for all arguments</td></tr>
<tr valign="top">
- <td><code>‑‑headless / ‑‑noheadless</code></td>
- <td>Run Jalview in headless (/ or not in headless) mode. In headless mode, no GUI interface will be created and Jalview will quit after all arguments have been processed.
+ <td><code>‑‑headless</code></td>
+ <td>Run Jalview in headless mode. In headless mode, no GUI interface will be created and Jalview will quit after all arguments have been processed.
<br/>
- If you use a command line argument to specify an output file of some kind (<code>--output</code>, <code>--image</code> or <code>--structureimage</code>) then <strong>headless mode will be assumed</strong>. If you don't want this behaviour use <code>--noheadless</code> or <code>--gui</code>.
+ If you use a command line argument to specify an output file of some kind (<code>‑‑output</code>, <code>‑‑image</code> or <code>‑‑structureimage</code>) then <strong>headless mode will be assumed</strong>. If you don't want this behaviour use <code>‑‑gui</code>.
</td>
</tr>
<tr valign="top">
<td><code>‑‑gui</code></td>
- <td>Force Jalview to run in graphical mode. This can be used to counter the assumption of headless mode when an argument that creates an output file is used. <code>--gui</code> takes precedence over <code>--headless</code>.</td>
+ <td>Force Jalview to run in graphical mode. This can be used to counter the assumption of headless mode when an argument that creates an output file is used. <code>‑‑gui</code> takes precedence over <code>‑‑headless</code>.</td>
</tr>
<tr valign="top">
<code>phylip</code> (<code>phy</code>),
<br/>
<code>jalview</code> (<code>jvp, jar</code>).
+ <br/>
+ To output directly to STDOUT (console output) use the filename <code>-</code> (a single hyphen). In this case all STDOUT messages will instead go to STDERR. If no <code>format</code> is supplied then Fasta will be assumed.
</td>
<td><code>format=<em>name</em></code></td>
<td align="center">✓</td>
<td align="center">✓</td>
</tr>
+ <tr valign="top">
+ <td><code>‑‑mkdirs</code></td>
+ <td>Enable automatic creation of new directories and parent directories for filenames given, or created through substitutions, in <code>‑‑output</code>, <code>‑‑image</code> or <code>‑‑structureimage</code> arguments.
+ <td></td>
+ <td align="center">✓</td>
+ </tr>
+
+
+
+Automatically create directories when outputting a file to a new directory
</table>
<code>biojs</code>.
</td>
<td>
- <code>type=<em>name</em>,
- <code>textrenderer=<em>name</em>,
- <code>scale=<em>number</em>,
- <code>width=<em>number</em>,
- <code>height=<em>number</em>
+ <code>
+ type=<em>name</em>,
+ <br/>
+ textrenderer=<em>name</em>,
+ <br/>
+ scale=<em>number</em>,
+ <br/>
+ width=<em>number</em>,
+ <br/>
+ height=<em>number</em>,
+ <br/>
+ imagecolour=<em>name</em>
+ </code>
+ </td>
+ <td align="center">✓</td>
+ </tr>
+
+ <tr valign="top">
+ <td><code>‑‑structureimage <em>filename</em></code></td>
+ <td>Export an image of a 3D structure opened in JMOL (currently jmol only). Each <code>‑‑structureimage</code> filename will output a file for each <code>‑‑structureimage</code> that has been applied to the open alignment window. In this situation, to avoid overwriting the same file with each structure, additional substitutions <code>{structuredirname}</code>, <code>{structurebasename}</code> and <code>{structureextname}</code> are available being substituted with the directory path, file basename and file extension of each structure file. Image formats can be:
+ <br/>
+ <code>svg</code>,
+ <br/>
+ <code>png</code>,
+ <br/>
+ <code>eps</code>.
+ </td>
+ <td>
+ <code>
+ type=<em>name</em>,
+ <br/>
+ textrenderer=<em>name</em>,
+ <br/>
+ scale=<em>number</em>,
+ <br/>
+ width=<em>number</em>,
+ <br/>
+ height=<em>number</em>,
+ <br/>
+ imagecolour=<em>name</em>
+ <br/>
+ bgcolour=<em>name</em>
+ </code>
</td>
<td align="center">✓</td>
</tr>
<tr valign="top">
<td><code>‑‑type <em>name</em></code></td>
- <td>Set the image format for the preceding <code>‑‑image</code> to <em>name</em>. Valid values for <em>name</em> are:
+ <td>Set the image format for the preceding <code>‑‑image</code> or <code>‑‑structureimage</code> to <em>name</em>. Valid values for <em>name</em> are:
<br/>
<code>svg</code>,
<br/>
<tr valign="top">
<td><code>‑‑textrenderer <em>name</em></code></td>
- <td>Sets whether text in a vector image format (SVG, HTML, EPS) should be rendered as text or vector line-art. Valid values for <em>name</em> are:
+ <td>Sets whether text in a vector image format (SVG, HTML, EPS) should be rendered as text or vector line-art. Applies to the preceding <code>‑‑image</code> or <code>‑‑structureimage</code>. Valid values for <em>name</em> are:
<br/>
<code>text</code>,
<br/>
<tr valign="top">
<td><code>‑‑scale <em>number</em></code></td>
- <td>Sets a scaling for bitmap image format (PNG). Should be given as a floating point number. This can also be set as a sub-value modifier to the <code>--image</code> value. If used in conjunction with <code>--width</code> and <code>--height</code> then the smallest scaling will be used (<code>scale</code>, <code>width</code> and <code>height</code> provide bounds for the image).
+ <td>Sets a scaling for bitmap image format (PNG). Should be given as a floating point number. Applies to the preceding <code>‑‑image</code> or <code>‑‑structureimage</code>. This can also be set as a sub-value modifier to the <code>‑‑image</code> or <code>‑‑structureimage</code> value. If used in conjunction with <code>‑‑width</code> and <code>‑‑height</code> then the smallest size will be used (<code>scale</code>, <code>width</code> and <code>height</code> provide bounds for the image).
</td>
<td></td>
<td align="center">✓</td>
<tr valign="top">
<td><code>‑‑width <em>number</em></code></td>
- <td>Sets a width for bitmap image format (PNG) with the height maintaining the aspect ratio. Should be given as a positive integer. This can also be set as a sub-value modifier to the <code>--image</code> value. If used in conjunction with <code>--scale</code> and <code>--height</code> then the smallest scaling will be used (<code>scale</code>, <code>width</code> and <code>height</code> provide bounds for the image).
+ <td>Sets a width for bitmap image format (PNG) with the height maintaining the aspect ratio. Applies to the preceding <code>‑‑image</code> or <code>‑‑structureimage</code>. Should be given as a positive integer. This can also be set as a sub-value modifier to the <code>‑‑image</code> or <code>‑‑structureimage</code> value. If used in conjunction with <code>‑‑scale</code> and <code>‑‑height</code> then the smallest size will be used (<code>scale</code>, <code>width</code> and <code>height</code> provide bounds for the image).
</td>
<td></td>
<td align="center">✓</td>
<tr valign="top">
<td><code>‑‑height <em>number</em></code></td>
- <td>Sets a height for bitmap image format (PNG) with the width maintaining the aspect ratio. Should be given as a positive integer. This can also be set as a sub-value modifier to the <code>--image</code> value. If used in conjunction with <code>--scale</code> and <code>--width</code> then the smallest scaling will be used (<code>scale</code>, <code>width</code> and <code>height</code> provide bounds for the image).</td>
- <td></td>
- <td align="center">✓</td>
- </tr>
-
- <tr valign="top">
- <td><code>‑‑groovy <em>filename</em></code></td>
- <td>Process a groovy script in the file for the open alignment.</td>
- <td></td>
- <td align="center">✓</td>
- </tr>
-
- </table>
-
-
- <h2><a name="exporting3dstructureimagefiles"></a>Exporting 3D structure image files (<code>jmol</code> only)</h2>
-
- <table border="1" cellpadding="3">
- <tr valign="top">
- <td><strong>argument</strong></td>
- <td><strong>action</strong></td>
- <td><strong>sub-value modifiers</strong> (optional)</td>
- <td><strong>linked</strong> (optional)</td>
- </tr>
-
- <tr valign="top">
- <td><code>‑‑structureimage <em>filename</em></code></td>
- <td>Export an image of a 3D structure opened in JMOL. Image formats can be:
- <br/>
- <code>svg</code>,
- <br/>
- <code>png</code>,
- <br/>
- <code>eps</code>.
- </td>
- <td>
- <code>structureimagetype=<em>name</em>,
- <code>structureimagetextrenderer=<em>name</em>,
- <code>structureimagescale=<em>number</em>,
- <code>structureimagewidth=<em>number</em>,
- <code>structureimageheight=<em>number</em>
- </td>
- <td align="center">✓</td>
- </tr>
-
- <tr valign="top">
- <td><code>‑‑structureimagetype <em>name</em></code></td>
- <td>Set the structure image format for the preceding --structureimage. Valid values are:
- <br/>
- <code>svg</code>,
- <br/>
- <code>png</code>,
- <br/>
- <code>eps</code>.
- </td>
- <td></td>
- <td align="center">✓</td>
- </tr>
-
- <tr valign="top">
- <td><code>‑‑structureimagetextrenderer <em>name</em></code></td>
- <td>Sets whether text in a vector structure image format (SVG, EPS) should be rendered as text or vector line-art. Possible values are:
- <br/>
- <code>text</code>,
- <br/>
- <code>lineart</code>.
- </td>
+ <td>Sets a height for bitmap image format (PNG) with the width maintaining the aspect ratio. Applies to the preceding <code>‑‑image</code> or <code>‑‑structureimage</code>. Should be given as a positive integer. This can also be set as a sub-value modifier to the <code>‑‑image</code> or <code>‑‑structureimage</code> value. If used in conjunction with <code>‑‑scale</code> and <code>‑‑width</code> then the smallest size will be used (<code>scale</code>, <code>width</code> and <code>height</code> provide bounds for the image).</td>
<td></td>
<td align="center">✓</td>
</tr>
<tr valign="top">
- <td><code>‑‑structureimagescale <em>number</em></code></td>
- <td>Sets a scaling for bitmap structure image format (PNG). Should be given as a floating point number. If used in conjunction with --structureimagewidth and --structureimageheight then the smallest scaling will be used (structureimagescale, structureimagewidth and structureimageheight provide bounds for the structure image).
- </td>
+ <td><code>‑‑bgcolour <em>name</em></code></td>
+ <td>Only applies to structure images (opened with <code>jmol</code> structure viewer). Sets the background colour of the preceding <code>‑‑structureimage</code>. <em>name</em> should be either a named colour (e.g. <code>white</code>, <code>cyan</code>) known to Jmol, or can be given as a six digit RGB hex string (e.g. <code>ffffff</code>, <code>00ffff</code>). This can also be set as a sub-value modifier to the <code>‑‑structureimage</code> value.</td>
<td></td>
<td align="center">✓</td>
</tr>
<tr valign="top">
- <td><code>‑‑structureimagewidth <em>number</em></code></td>
- <td>Sets a width for bitmap structure image format (PNG) with the height maintaining the aspect ratio. Should be given as a positive integer. If used in conjunction with --structureimagescale and --structureimageheight then the smallest scaling will be used (structureimagescale, structureimagewidth and structureimageheight provide bounds for the structure image).
- </td>
- <td></td>
- <td align="center">✓</td>
- </tr>
-
- <tr valign="top">
- <td><code>‑‑structureimageheight <em>number</em></code></td>
- <td>Sets a height for bitmap structure image format (PNG) with the width maintaining the aspect ratio. Should be given as a positive integer. If used in conjunction with --structureimagescale and --structureimagewidth then the smallest scaling will be used (structureimagescale, structureimagewidth and structureimageheight provide bounds for the structure image).
- </td>
+ <td><code>‑‑groovy <em>filename</em></code></td>
+ <td>Process a groovy script in the file for the open alignment.</td>
<td></td>
<td align="center">✓</td>
</tr>
<td>
Move on to a new alignment window. This will ensure <code>‑‑append</code> will start a new alignment window and other linked arguments will apply to the new alignment window.
<br/>
- <em>Note</em> that <code>--open</code> already starts a new alignment window for each file it opens.
+ <em>Note</em> that <code>‑‑open</code> already starts a new alignment window for each file it opens.
</td>
</tr>
<tr valign="top">
<td><code>‑‑substitutions / ‑‑nosubstitutions</code></td>
<td>The following argument values allow (or don't allow) subsituting filename parts. This is initially true. Valid substitutions are
+ <br/>
<code>{basename}</code> - the filename-without-extension of the currently <code>‑‑open</code>ed file (or first <code>‑‑append</code>ed file),
<br/>
<code>{dirname}</code>, - the directory (folder) name of the currently <code>‑‑open</code>ed file (or first <code>‑‑append</code>ed file),
+ <code>{extension}</code>, - the extension of the filename of the currently <code>‑‑open</code>ed file (or first <code>‑‑append</code>ed file),
<br/>
<code>{argfilebasename}</code> - the filename-without-extension of the current <code>‑‑argfile</code>,
<br/>
<code>{argfiledirname}</code> - the directory (folder) name of the current <code>‑‑argfile</code>,
<br/>
+ <code>{structurebasename}</code> - the filename-without-extension of the <code>‑‑structure</code> file. Only available to <code>‑‑structureimage</code> .
+ <br/>
+ <code>{structuredirname}</code>, - the directory (folder) name of the <code>‑‑structure</code> file. Only available to <code>‑‑structureimage</code> .
+ <br/>
+ <code>{structureextension}</code>, - the extension of the filename of the <code>‑‑structure</code> file. Only available to <code>‑‑structureimage</code> .
+ <br/>
<code>{n}</code> - the value of the index counter (starting at 0).
<br/>
- <code>{++n}</code> - increase and substitute the value of the index counter,
+ <code>{++n}</code> - increase and substitute the value of the index counter.
+ <br/>
+ <code>{m}</code> - the value of the on-the-fly counter (starting at 0). Only available to <code>‑‑structureimage</code> .
+ <br/>
+ <code>{++m}</code> - increase and substitute the (incremented) value of the on-the-fly counter. Only available to <code>‑‑structureimage</code> .
<br/>
<code>{}</code> - the value of the current alignment window <em>default</em> index.
</td>
<tr valign="top">
<td><code>‑‑allstructures / ‑‑noallstructures</code></td>
<td>
- Apply (or stop applying) the following 3D structure formatting arguments to all structures <em>within the current open alignment</em>. Whilst <code>--allstructures</code> will continue to operate for a <code>--new</code> alignment, the structure formatting arguments must be set again for each new alignment.
+ Apply (or stop applying) the following 3D structure formatting arguments to all structures <em>within the current open alignment</em>. Whilst <code>‑‑allstructures</code> will continue to operate for a <code>‑‑new</code> alignment, the structure formatting arguments must be set again for each new alignment.
</td>
</tr>
</p>
<p>
- These new arguments are all accessed with a <code>--doubledash</code> form of
+ These new arguments are all accessed with a <code>‑‑doubledash</code> form of
command line argument (with the one exception where simply opening one or more
files can be performed without any arguments other than the filenames).
</p>
<p>
However, you cannot mix old and new style arguments, so if you use any
<code>-singledash</code> arguments (with the exception of <code>-help</code> or <code>-h</code>), they will all be interpreted as
- old style arguments with the new <code>--doubledash</code>
+ old style arguments with the new <code>‑‑doubledash</code>
arguments being ignored. If you have a script
that uses the old arguments without any dashes, and uses the bare-word
<code>open</code> then these will also be interpreted as old style arguments.
<li>
For arguments that require a value, the value can be given after an equals-sign ('=') or a space (' ').
<br/>
- <code>--arg value</code>
+ <code>‑‑arg value</code>
<br/>
- <code>--arg=value</code>
+ <code>‑‑arg=value</code>
</li>
<li>
For arguments that can take multiple values (these will be filenames), the multiple filenames should appear after a space. If you use a filename wildcard you can put this after a space (which will be expanded by the shell unto multiple filenames before they reach Jalview), or you can put it after an equals-sign, which will be used by Jalview to find a list of files. You cannot use an equals-sign and value followed by further values.
<br/>
- <code>--arg file1.fa otherfile.stk</code>
+ <code>‑‑arg file1.fa otherfile.stk</code>
<br/>
- <code>--arg filename*.fa</code> <em>(filenames expanded by shell)</em>
+ <code>‑‑arg filename*.fa</code> <em>(filenames expanded by shell)</em>
<br/>
- <code>--arg=filename*.fa</code> <em>(filenames expanded by Jalview)</em>
+ <code>‑‑arg=filename*.fa</code> <em>(filenames expanded by Jalview)</em>
</li>
<li>
For arguments that act as a switch, most can be negated by preceding the argument name with <code>no</code>.
<br/>
- <code>--switch</code>
+ <code>‑‑switch</code>
<br/>
- <code>--noswitch</code>
+ <code>‑‑noswitch</code>
</li>
<li>
- Some values can be modified, or may need additional information (for instance an <code>--image</code> output can be modified with a <code>--scale=number</code> factor, or a <code>--structure</code> can refer to a sequence with a <code>--seqid=ID</code>). This additional information can be added in a number of different ways.
+ Some values can be modified, or may need additional information (for instance an <code>‑‑image</code> output can be modified with a <code>‑‑scale=number</code> factor, or a <code>‑‑structure</code> can refer to a sequence with a <code>‑‑seqid=ID</code>). This additional information can be added in a number of different ways.
<ul>
<li>
An argument immediately following the main argument.
<br/>
- <code>--image output.png --scale 2.5</code>
+ <code>‑‑image output.png --scale 2.5</code>
</li>
<li>
A <em>sub-value modifier</em>, which is where one or more (comma-separated) values are added to the start of the main value, placed in square brackets.
<br/>
- <code>--open=[nowrap,colour=gecos-blossom]uniref50.fa</code>
+ <code>‑‑open=[nowrap,colour=gecos-blossom]uniref50.fa</code>
<br/>
Sub-value modifiers with a value must use an equals-sign separator, and those that act as a switch can simply be included without an equals-sign or value, and can be preceded with <code>no</code> to negate the value, as with the argument name.
</li>
<li>
Another argument with the same <em>linked ID</em>. A linked ID is an optional identifier for a particular open alignment, placed in square brackets immediately following the argument name (before the equals-sign or space). If linked IDs are specified they do not need to be near to each other.
<br/>
- <code>--image[MYID]=output.png --other --args --scale[MYID]=2.5</code>
+ <code>‑‑image[MYID]=output.png --other --args --scale[MYID]=2.5</code>
</li>
<li>
An argument that is designated as applying to <em>all linked IDs</em>
<br/>
- <code>--image=output.png --other --args --all --scale=2.5</code>
+ <code>‑‑image=output.png --other --args --all --scale=2.5</code>
<br/>
- <code>--image=output.png --other --args --scale[*]=2.5</code>
+ <code>‑‑image=output.png --other --args --scale[*]=2.5</code>
</li>
</ul>
</li>
<h2><a name="headlessmode"></a>Headless mode</h2>
<p>
- Jalview can be run in headless mode, i.e. without the usual graphical user interface (GUI), by specifying the <code>--headless</code> argument. With command line arguments you can specify operations for Jalview to perform on one or more files and then stop running. Most likely you will want to output another file, either an alignment for image file.
+ Jalview can be run in headless mode, i.e. without the usual graphical user interface (GUI), by specifying the <code>‑‑headless</code> argument. With command line arguments you can specify operations for Jalview to perform on one or more files and then stop running. Most likely you will want to output another file, either an alignment for image file.
</p>
<p>
- <strong>If you specify an argument for an output file</strong> (one or more of <code>--output</code>, <code>--image</code> or <code>--structureimage</code>) then it will be assumed that you wish to <strong>run in headless mode</strong>.
+ <strong>If you specify an argument for an output file</strong> (one or more of <code>‑‑output</code>, <code>‑‑image</code> or <code>‑‑structureimage</code>) then it will be assumed that you wish to <strong>run in headless mode</strong>.
</p>
<p>
- You can force Jalview to run in graphical mode using the <code>--gui</code> or <code>--noheadless</code> arguments.
+ You can force Jalview to run in graphical mode using the <code>‑‑gui</code> argument.
</p>
<p>
--- /dev/null
+<html>
+<!--
+ * 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.
+ -->
+<head>
+<title>Working with PAE Matrices in Jalview</title>
+</head>
+
+<body>
+ <p>
+ <strong>Working with Predicted Alignment Error Matrices in
+ Jalview</strong>
+ </p>
+
+ <p>Predicted Alignment Error matrices are produced by deep-learning
+ based 3D-structure prediction pipelines such as AlphaFold.</p>
+ <p>
+ Jalview retrieves PAE matrices when importing predicted 3D structures
+ from the EBI-AlphaFold database via <a
+ href="../features/structurechooser.html">Jalview's structure
+ chooser</a> GUI.
+ </p>
+ <p>
+ If you have produced your own models using a pipeline such as
+ ColabFold, then you can load it via the 'Add PAE matrix file' button
+ in the <a href="../features/structurechooser.html#loadpdbfile">Load
+ PDB File</a> dropdown menu in the 3D structure chooser, providing it is
+ in a <a href="../io/paematrixformat.html">supported PAE format</a>. ,
+ or the <a href="../features/clarguments-basic.html">Command Line
+ Interface</a>. See <a href="../features/paematrices.html">Working
+ with PAE Matrices</a> for information on how they are visualised and
+ analysed in Jalview.
+ </p>
+ </p>
+ <p>
+ An additional <em>Predicted Alignment Error</em> file can also be
+ provided when importing 3D structure data. Jalview supports import of
+ PAE Matrices provided as <a href="../io/paematrixformat.html">AlphaFold
+ format JSON files</a> - which are also produced by ColabFold. See <a
+ href="paematrices.html">Working with PAE Matrices</a> for details on
+ what Jalview allows you to do with associated PAE matrix data.
+ </p>
+ <p>
+ <em>The Structure Chooser interface was introduced in Jalview
+ 2.9. </em>
+ </p>
+</body>
+</html>
style="width: 464px; height: 173px;"> <br /> <strong>Manual
selection/association of PDB files with Sequences</strong>
</p>
- <p>To manually associate PDB files with a sequence, select 'From
- File', or 'Enter PDB Id' from the drop-down menu:
- <ul>
- <li><strong>From File</strong> - allows you to load a PDB file
- from the local machine or network and associate it with the
- selected sequence. PDB files associated in this way will also be
- saved in the <a href="jalarchive.html">Jalview Archive file</a>.<br></li>
- <li><strong>Enter PDB Id</strong> - allows you specify a PDB ID
- for your sequence. The PDB Rest API, provided by EMBL-EBI, is used
- to validate and fetch structure data.<br></li>
- </ul>
-
- <p>
- <em>The Structure Chooser interface was introduced in Jalview
- 2.9. </em>
- </p>
+ <p>
+ <strong>Manual Association of PDBe accessions with sequences</strong>
+ </p>
+ <p>If for some reason the PDBe and 3D beacons search fail to
+ automatically the PDB structure or model you wish to import, you can
+ select 'Enter PDB Id' from the drop-down menu to manually specify PDB
+ identifiers for one or more selected sequences. The PDB Rest API,
+ provided by EMBL-EBI, is used to validate accessions exist, and fetch
+ structure data.</p>
+ <p>
+ <strong><a name="loadpdbfromfile">Import structure models
+ and metadata from file</a></strong>
+ </p>
+ <p>
+ Selecting the <strong>From File</strong> option from the drop down
+ menu allows 3D structure data to be imported from your own computer.
+ PDB or mmCIF files associated in this way are also saved in <a
+ href="jalarchive.html">Jalview Projects</a>. <br /> <img
+ src="local-pdb-import.png" style="width: 496px; height: 482px;"><br />
+ The 'From File' dialog provides a drop down menu which allows you to
+ specify how the Temperature Factor metadata for each residue in the 3D
+ structure data file is interpreted:
+
+ <ul>
+ <li>Default - Jalview will try to automatically determine whether
+ to show as 'Temperature Factor', 'AlphaFold Reliability' or 'Model
+ Quality'</li>
+ <li>PLDDT - Model has PLDDT scores in the temperature factor
+ column.</li>
+ </ul>
+ <p>
+ An additional <em>Predicted Alignment Error</em> file can also be
+ provided when importing 3D structure data. Jalview supports import of
+ PAE Matrices provided as <a href="../io/paematrixformat.html">AlphaFold
+ format JSON files</a> - which are also produced by ColabFold. See <a
+ href="paematrices.html">Working with PAE Matrices</a> for details on
+ what Jalview allows you to do with associated PAE matrix data.
+ </p>
+ <p>
+ <em>The Structure Chooser interface was introduced in Jalview
+ 2.9. </em>
+ </p>
</body>
</html>
</li>
</ul>
- <a name="htmlexport" />
<p>
+ <strong>PNG Export Options</strong>
+
+ <p>
+ <em>Since Jalview 2.11.3</em> it is possible to specify options when <a
+ href="../features/clarguments-reference.html#exportingimagefiles">exporting
+ figures via the command line</a> to increase the resolution of the
+ exported PNG, and configure maximum width and height settings.
+
+ <p>You can also configure default export settings by adding the
+ following lines to
+
+ <pre>.jalview_properties</pre>
+ <pre>BITMAP_SCALE=<Scale factor multiplied by 10>
+ BITMAP_WIDTH=Width of export in pixels
+ BITMAP_HEIGHT=Height of figure export in pixels
+ </pre>
+ When scale is not set, the figure will be scaled to fit in the smallest
+ specified dimension. Scale will be ignored if it results in an image
+ dimension greater than the smallest specified dimension.
+ <p>
+ <a name="htmlexport" /><p>
<strong>Exporting alignments as Web Pages</strong>
<p>
In Jalview 2.9, new HTML exporting options were introduced. The
--- /dev/null
+<html>
+<!--
+ * 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.
+ -->
+<head>
+<title>Supported Formats for Predicted Alignment Error Matrices</title>
+</head>
+
+<body>
+ <p>
+ <strong>Supported Formats for Predicted Alignment Error
+ Matrices</strong>
+ </p>
+ <p>
+ Predicted Alignment Error matrices are square matrices produced as
+ part of deep-learning based 3D-structure prediction pipelines such as
+ AlphaFold. They can be imported via <a
+ href="../features/structurechooser.html">Jalview's structure
+ chooser</a> GUI and the <a href="../features/clarguments-basic.html">Command
+ Line Interface</a>. See <a href="../features/paematrices.html">Working
+ with PAE Matrices</a> for information on how they are visualised and
+ analysed in Jalview.
+ </p>
+ <p>
+ <strong>Supported Formats</strong>
+ </p>
+ <p>Jalview supports import of PAE matrix data as provided by the
+ EBI-AlphaFold database. This resource provides PAE matrices as a JSON
+ files structured in one of the following ways:</p>
+ <pre>
+ # Version 1 format PAE file - deprecated 28th July 2022
+ {
+ residue1:[1,1,... total number of residues]
+ residue2:[1,2,... total number of residues]
+ distance:[0.1,0.3,... list of PAE matrix elements as doubles]
+ }
+ </pre>
+ <pre>
+ # Version 2 format PAE file - see https://alphafold.ebi.ac.uk/faq
+ {
+ max_predicted_alignment_error: 4.0, # may also be max_pae
+ predicted_alignment_error: [[1,2,0,0,3,...],...] # may also be pae
+ }
+ </pre>
+ <p>
+ Variants of the version 2 format include using 'pae' instead of
+ 'predicted_alignment_error' in the names of keys. Jalview copes both.<br />
+ Once imported, Jalview stores PAE matrices as float arrays along with
+ any associated tree and partition set resultant from clustering the
+ matrix. <br/><br/><em>PAE Matrix import support was added in Jalview 2.11.3
+ </em>
+ </p>
+</body>
+</html>
- <!-- JAL-4064 --> Native M1 build for macOS using Adoptium JRE 11 macos-aarch64
- <!-- JAL-4054 --> Installers built with install4j10
- <!-- JAL-3676 --> Allow log level configuration via Jalview's Java Console, and a Copy to Clipboard button
-- <!-- JAL-3416 --> FlatLAF default look and feel on Linux, OSX and everywhere else ?
+- <!-- JAL-3416 --> FlatLAF default look and feel on Linux, OSX and everywhere else
- <!-- JAL-4019 --> Ambiguous Base Colourscheme
- <!-- JAL-4061 --> Find can search sequence features' type and description
- <!-- JAL-4086 --> Highlight aligned positions on all associated structures when mousing over a column
- <!-- JAL-4221 --> sequence descriptions are updated from database reference sources if not already defined
+- <!-- JAL-4273 --> Visible adjuster marks to grab and adjust annotation panel height and id width
+- <!-- JAL-4260 --> Adjustable ID margin when alignment is wrapped
+- <!-- JAL-4274 --> Command line options and configurable bitmap export preferences for height, width and scale factor
### Improved support for working with computationally determined models
### Jalview on the command line
-- <!-- JAL-4160,JAL-629 --> New command line argument framework allowing flexible batch processing, figure generation, and import of structures, pae matrices and other sequence associated data
+- <!-- JAL-4160,JAL-629,JAL-4262,JAL-4265, --> New command line argument framework allowing flexible batch processing, import of structures, pae matrices and other sequence associated data, and alignment and structure figure generation.
- <!-- JAL-4121 --> Assume --headless when jalview is run with a command line argument that generates output
+- <!-- JAL-244 --> Automatically adjust Left margin on import to avoid cropping of annotation labels & sequence IDs
+- <!-- JAL-901 --> Specify alignment title on import via --title argument
### Other improvements
+
+- <!-- JAL-4250 --> Secondary structure annotation glyphs are rendered anti-aliasing when enabled
+- <!-- JAL-325 --> Helix and Sheet glyphs vertically centered with respect to grey coil secondary structure annotation track
+- <!-- JAL-4253 --> Lower line of the sequence group border does not align with vertical and background residue box
+- <!-- JAL-4250 --> Updated JFreeSVG (https://www.jfree.org/jfreesvg) from 2.1 to 3.4.3
- <!-- JAL-3119 --> Name of alignment and view included in overview window's title
- <!-- JAL-4213 --> "add reference annotation" add all positions in reference annotation tracks, not just positions in the currently highlighted columns/selection range
- <!-- JAL-4119 --> EMBL-EBI SIFTS file downloads now use split directories
- <!-- JAL-3830 --> Command-line wrapper script for macOS bundle, linux and Windows installations (bash, powershell and .bat wrappers)
- <!-- JAL-3820 --> In Linux desktops' task-managers, the grouped Jalview windows get a generic name
+- <!-- JAL-4206 --> Improved file chooser's 'recent files' view and added filter for 'All known alignment files'
+- <!-- JAL-4206 --> Relative files added to recent files list via import from command line are selected when Jalview opened from same location
+
+
## Still in progress (delete on release)
- <!-- JAL-2382 --> Import and display sequence-associated contact predictions in CASP-RR format
### Development and Deployment
- <!-- JAL-4167 --> Create separate gradle test task for some tests
+- <!-- JAL-4212 --> Prevent gradle test on macOS continuously grabbing focus
- <!-- JAL-4111 --> Allow gradle build to create suffixed DEVELOP-... builds with channel appbase
- <!-- JAL-4243 --> Jalview bio.tools description maintained under jalview's git repo and bundled with source release
- <!-- JAL-4150 --> Sequences copied to clipboard from within Jalview cannot be pasted via the desktop's popup menu to a new alignment window
- <!-- JAL-2528, JAL-1713 --> Overview window is saved in project file, and state of 'show hidden regions' is preserved.
- <!-- JAL-4153 --> JvCacheableInputBoxTest flaky on build server
+- <!-- JAL-4255 --> SLF4J produces an error to STDERR at Jalview startup due to missing class
+- <!-- JAL-4189 --> macOS Dock and KDE taskbar names Jalview icon "java" when running
+- <!-- JAL-2910 --> HeadlessException in console in headless mode (actually fixed in 2.11.{0,1,2))
+
## New Known defects
- <!-- JAL-4178 --> Cannot cancel structure view open action once it has been started via the structure chooser dialog
- <!-- JAL-4142 --> Example project's multiple views do not open in distinct locations when eXpand views is used to show them all separately
- <!-- JAL-4165 --> Missing last letter when copying consensus sequence from alignment if first column is hidden
+- <!-- JAL-4261 --> Last sequence ID in alignment not shown and annotation labels are misaligned in HTML export
+- <!-- JAL-3024 --> Files opened via command line with a relative path are added as relative paths to Recent files list (since 2.0.x)
-The 2.11.3 series includes support for in-depth exploration of predicted alignment error matrices from AlphaFold in the context of multiple alignments, along with support for standard colourschemes for shading models according to their pLDDT.
+The 2.11.3 Jalview release features a new and more powerful command line interface, support for in-depth exploration of predicted alignment error (PAE) matrices from AlphaFold in the context of multiple alignments, AlphaFold's standard Blue-Orange-Red confidence colourscheme, and a host of minor improvements and bug fixes.
-We're launching this release at ISMB 2023 - come find us !
+**Interactive exploration of AlphaFold Predicted Alignment Error Matrices**
-It also introduces new support for native ARM-based OSX architectures, and a few other goodies!
+Predicted alignment error (PAE) matrices are JSON files produced by AlphaFold and other 3D structure prediction tools, which reflect how well any two positions in a predicted structure are positioned correctly relative to each other. Jalview automatically imports PAE matrices when retrieving protein structures from the EBI-AlphaFold database. A PAE matrix file can also be provided when manually importing 3D structure data.
+Once imported, PAE matrices are shown in annotation tracks as a heat map shaded pale to dark green, where darker shades indicate higher confidence in relative positioning. Right-clicking a PAE Matrix's annotation label provides the option to cluster the columns of the matrix, producing a tree where regions of well arranged structure are grouped together, allowing columns containing those regions to be selected and manipulated further.
+
+**Jalview's Next Generation Command Line Interface**
+
+Jalview 2's original command line interface (CLI) allowed alignments to be imported, annotated and overlaid with sequence features, coloured, associated with trees, and exported either as figures (EPS, PNG, SVG, HTML SVG or an interactive BioJS page) or with one of Jalview's supported alignment export file formats. The new command line interface provides all this, as well as a range of additional functionality previously only available via the GUI:
+
+ * 3D structures can be associated with sequences in alignments and shown in Jmol or external viewers
+ * Secondary structure, Model Reliability and Temperature factor can be shown and used to colour alignments
+ * PAE Matrices can be imported and shown as annotation
+ * 3D structure data shown in Jmol can be exported as PNG
+ * Scale factors and dimensions can be specified, allowing high resolution image exports
+
+In addition to these new functionality, next generation CLI operations can be applied to a range of files and directories through the use of wild-cards. This allows faster and more efficient processing of large numbers of alignments. It also facilitates modularisation of operations through the use of ['command-line argument files'](../features/clarguments-argfiles.html).
+
+All new CLI parameters are preceded by '--', as opposed to an optional single '-' which was used in Jalview's old CLI. Old style arguments can still be used, so existing scripts will still work as before, but old-style operations cannot be mixed with new operations in the same CLI call. Use of old command line operations will also raise a warning, and we plan to completely remove support in Jalview's next major release (2.12).
+
+As usual, please let us via [Jalview's Discussion forum](https://discourse.jalview.org) of any issues you encounter using the new CLI, and of course any requests for improvement or new functionality !
label.successfully_loaded_file = Successfully loaded file {0}
label.successfully_loaded_matrix = Successfully loaded score matrix {0}
label.successfully_saved_to_file_in_format = Successfully saved to file: {0} in {1} format.
+label.successfully_printed_to_stdout_in_format = Successfully printed to STDOUT in {0} format.
label.copied_sequences_to_clipboard = Copied {0} sequences to clipboard.
label.check_file_matches_sequence_ids_alignment = Check that the file matches sequence IDs in the alignment.
label.problem_reading_tcoffee_score_file = Problem reading T-COFFEE score file
action.cluster_matrix = Cluster matrix
action.clustering_matrix_for = Calculating tree for matrix {0} and clustering at {1}
action.cluster_matrix_tooltip = Computes an average distance tree for the matrix and displays it
-
+label.all_known_alignment_files = All known alignment files
+label.command_line_arguments = Command Line Arguments
+warning.using_old_command_line_arguments = It looks like you are using old command line arguments. These are now deprecated and will be removed in a future release of Jalview.\nFind out about the new command line arguments at\n
+warning.using_mixed_command_line_arguments = Jalview cannot use both old (-arg) and new (--arg) command line arguments. Please check your command line arguments.\ne.g. {0} and {1}
+warning.the_following_errors = The following errors and warnings occurred whilst processing files:
label.successfully_loaded_file = Fichero cargado exitosamente {0}
label.successfully_loaded_matrix = Matriz cargada exitosamente {0}
label.successfully_saved_to_file_in_format = Guardado exitosamente en el fichero: {0} en formato {1}.
+label.successfully_printed_to_stdout_in_format = Impresso exitosamente al STDOUT en formato {0}.
label.copied_sequences_to_clipboard = Copiadas {0} secuencias en el portapapeles.
label.check_file_matches_sequence_ids_alignment = Comprobar que el fichero coincide con el ID de la secuencia en el alineamiento.
label.problem_reading_tcoffee_score_file = Problema de lectura del fichero de puntuaciones T-COFFEE
label.nothing_selected = Nada seleccionado
prompt.analytics_title = Jalview EstadÃsticas de Uso
prompt.analytics = ¿Quiere ayudar a mejorar Jalview habilitando la recopilación de estadÃsticas de uso con análisis Plausible?\nPuede habilitar o deshabilitar el seguimiento de uso en las preferencias.
+label.all_known_alignment_files = Todos los archivos de alineación conocidos
+label.command_line_arguments = Argumentos de lÃnea de comando
+warning.using_old_command_line_arguments = Parece que estás utilizando argumentos antiguos de lÃnea de comando. Estos ahora están en desuso y se eliminarán en una versión futura de Jalview.\nObtenga más información sobre los nuevos argumentos de la lÃnea de comando en\n
+warning.using_mixed_command_line_arguments = Jalview no puede utilizar argumentos de lÃnea de comando antiguos (-arg) y nuevos (--arg). Verifique los argumentos de su lÃnea de comando.\ne.g. {0} y {1}
+warning.the_following_errors = Se produjeron los siguientes errores y advertencias al procesar archivos:
{
if (sequences[row] == null)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"WARNING: Consensus skipping null sequence - possible race condition.");
continue;
}
}
return new Profiles(result);
// long elapsed = System.currentTimeMillis() - now;
- // System.out.println(elapsed);
+ // jalview.bin.Console.outPrintln(elapsed);
}
/**
' ', value);
}
// long elapsed = System.currentTimeMillis() - now;
- // System.out.println(-elapsed);
+ // jalview.bin.Console.outPrintln(-elapsed);
}
/**
}
}
- System.out.println(max + " " + min);
+ jalview.bin.Console.outPrintln(max + " " + min);
for (int i = 0; i < n; i++)
{
int x = psize * i;
int y = psize * j;
- // System.out.println(mat[i][j]);
+ // jalview.bin.Console.outPrintln(mat[i][j]);
float score = (float) (mat[i][j] - min) / (float) (max - min);
g.setColor(new Color(score, 0, 0));
g.fillRect(x, y, psize, psize);
- // System.out.println(x + " " + y + " " + score);
+ // jalview.bin.Console.outPrintln(x + " " + y + " " + score);
}
}
}
bestm = msq;
}
}
- // System.out.println("Best Score for " + (matches.size() + 1) + " :"
+ // jalview.bin.Console.outPrintln("Best Score for " + (matches.size() + 1) + " :"
// + bestscore);
matches.add(bestm);
aligns.add(bestaseq);
if (tmp.size() != nSeq)
{
- System.err.println("WARNING: tmp.size()=" + tmp.size() + " != nseq="
+ jalview.bin.Console.errPrintln("WARNING: tmp.size()=" + tmp.size() + " != nseq="
+ nSeq
+ " in getOrderByTree - tree contains sequences not in alignment");
}
String msg = String.format(
"Implementation Error - sortByFeature method must be either '%s' or '%s'",
FEATURE_SCORE, FEATURE_DENSITY);
- System.err.println(msg);
+ jalview.bin.Console.errPrintln(msg);
return;
}
{
// int nf = (feats[i] == null) ? 0
// : ((SequenceFeature[]) feats[i]).length;
- // // System.err.println("Sorting on Score: seq " +
+ // // jalview.bin.Console.errPrintln("Sorting on Score: seq " +
// seqs[i].getName()
// + " Feats: " + nf + " Score : " + scores[i]);
}
int featureCount = feats[i] == null ? 0
: ((SequenceFeature[]) feats[i]).length;
scores[i] = featureCount;
- // System.err.println("Sorting on Density: seq "+seqs[i].getName()+
+ // jalview.bin.Console.errPrintln("Sorting on Density: seq "+seqs[i].getName()+
// " Feats: "+featureCount+" Score : "+scores[i]);
}
QuickSort.sortByDouble(scores, seqs, sortByFeatureAscending);
if (translated == null || !(aaRes == translated.charAt(0)))
{
// debug
- // System.out.println(("Mismatch at " + i + "/" + aaResidue + ": "
+ // jalview.bin.Console.outPrintln(("Mismatch at " + i + "/" + aaResidue + ": "
// + codon + "(" + translated + ") != " + aaRes));
return false;
}
* unmapped position; treat like a gap
*/
sourceGapMappedLength += ratio;
- // System.err.println("Can't align: no codon mapping to residue "
+ // jalview.bin.Console.errPrintln("Can't align: no codon mapping to residue "
// + sourceDsPos + "(" + sourceChar + ")");
// return;
continue;
{
if (protein.isNucleotide() || !dna.isNucleotide())
{
- System.err.println("Wrong alignment type in alignProteinAsDna");
+ jalview.bin.Console.errPrintln("Wrong alignment type in alignProteinAsDna");
return 0;
}
List<SequenceI> unmappedProtein = new ArrayList<>();
{
if (protein.isNucleotide() || !dna.isNucleotide())
{
- System.err.println("Wrong alignment type in alignProteinAsDna");
+ jalview.bin.Console.errPrintln("Wrong alignment type in alignProteinAsDna");
return 0;
}
// todo: implement this
.getLength() == mappedFromLength - 1);
if (cdsLength != mappedToLength && !addStopCodon)
{
- System.err.println(String.format(
+ jalview.bin.Console.errPrintln(String.format(
"Can't align cds as protein (length mismatch %d/%d): %s",
cdsLength, mappedToLength, cdsSeq.getName()));
}
AlignedCodon codon = sequenceCodon.getValue();
if (codon.peptideCol > 1)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Problem mapping protein with >1 unmapped start positions: "
+ seq.getName());
}
fromRange[i + 1]);
if (range == null)
{
- System.err.println("Error in mapping " + seqMap + " from "
+ jalview.bin.Console.errPrintln("Error in mapping " + seqMap + " from "
+ fromSeq.getName());
return false;
}
}
else
{
- System.out.println("SEQUENCE HAS BEEN DELETED!!!");
+ jalview.bin.Console.outPrintln("SEQUENCE HAS BEEN DELETED!!!");
}
}
else
{
// JBPNote INFO level debug
- System.err.println(
+ jalview.bin.Console.errPrintln(
"ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
}
}
// tmp = ((max - tmp) * (size - cons2[j][23])) / size;
tmp = ((max - tmp) * (size - cons2GapCounts[j])) / size;
- // System.out.println(tmp+ " " + j);
+ // jalview.bin.Console.outPrintln(tmp+ " " + j);
quality.setElementAt(Double.valueOf(tmp), j);
if (tmp > newmax)
if (matchInDataset != null && xref.getMap().getTo() != null
&& matchInDataset != xref.getMap().getTo())
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Implementation problem (reopen JAL-2154): CrossRef.findInDataset seems to have recovered a different sequence than the one explicitly mapped for xref."
+ "Found:" + matchInDataset + "\nExpected:"
+ xref.getMap().getTo() + "\nFor xref:"
retrieved = sftch.getSequences(sourceRefs, !fromDna);
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Problem whilst retrieving cross references for Sequence : "
+ seq.getName());
e.printStackTrace();
String msg = "Mapping updated from " + ms.getName()
+ " to retrieved crossreference "
+ matched.getName();
- System.out.println(msg);
+ jalview.bin.Console.outPrintln(msg);
List<DBRefEntry> toRefs = map.getTo().getDBRefs();
if (toRefs != null)
cf.addMap(retrievedSequence, map.getTo(), map.getMap());
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Exception when consolidating Mapped sequence set...");
e.printStackTrace(System.err);
}
}
if (dataset.getSequences() == null)
{
- System.err.println("Empty dataset sequence set - NO VECTOR");
+ jalview.bin.Console.errPrintln("Empty dataset sequence set - NO VECTOR");
return false;
}
List<SequenceI> ds = dataset.getSequences();
{
if (nxt.getDatasetSequence() != null)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Implementation warning: CrossRef initialised with a dataset alignment with non-dataset sequences in it! ("
+ nxt.getDisplayId(true) + " has ds reference "
+ nxt.getDatasetSequence().getDisplayId(true)
if (rf != 0)
{
final String errMsg = "trimming contigs for incomplete terminal codon.";
- System.err.println(errMsg);
+ jalview.bin.Console.errPrintln(errMsg);
// map and trim contigs to ORF region
vc = scontigs.length - 1;
lastnpos = vismapping.shift(lastnpos); // place npos in context of
InputStream is = getClass().getResourceAsStream(fileName);
if (is == null)
{
- System.err.println("Resource file not found: " + fileName);
+ jalview.bin.Console.errPrintln("Resource file not found: " + fileName);
return;
}
BufferedReader dataIn = new BufferedReader(new InputStreamReader(is));
}
if (codeTables.isEmpty())
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"No genetic code tables loaded, check format of file "
+ fileName);
}
InputStream is = getClass().getResourceAsStream(fileName);
if (is == null)
{
- System.err.println("Resource file not found: " + fileName);
+ jalview.bin.Console.errPrintln("Resource file not found: " + fileName);
return;
}
BufferedReader dataIn = new BufferedReader(new InputStreamReader(is));
}
else
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Unexpected data in " + fileName + ": " + line);
}
}
* seqs.length) { for (int i = 0; i < seqs.length; i++) { if (!hasScore[i])
* { scores[i] = (max + i); } else { int nf=(feats[i]==null) ? 0
* :((SequenceFeature[]) feats[i]).length;
- * System.err.println("Sorting on Score: seq "+seqs[i].getName()+
+ * jalview.bin.Console.errPrintln("Sorting on Score: seq "+seqs[i].getName()+
* " Feats: "+nf+" Score : "+scores[i]); } } }
*
* jalview.util.QuickSort.sort(scores, seqs); } else if
* (int i=0;i<seqs.length; i++) { double nf; scores[i] =
* (0.05+fr*i)+(nf=((feats[i]==null) ? 0.0 :1.0*((SequenceFeature[])
* feats[i]).length));
- * System.err.println("Sorting on Density: seq "+seqs[i].getName()+
+ * jalview.bin.Console.errPrintln("Sorting on Density: seq "+seqs[i].getName()+
* " Feats: "+nf+" Score : "+scores[i]); }
* jalview.util.QuickSort.sort(scores, seqs); } else { if
* (method==FEATURE_LABEL) { throw new Error("Not yet implemented."); } } if
ScoreNames[cols] + ((reps > 0) ? "_" + reps : ""),
ScoreDescriptions[cols], null);
an.setScore(score);
- System.out.println(seqs[i].getName() + " score: '"
+ jalview.bin.Console.outPrintln(seqs[i].getName() + " score: '"
+ ScoreNames[cols] + "' = " + score); // DEBUG
an.setSequenceRef(seqs[i]);
seqs[i].addAlignmentAnnotation(an);
final int open = basePair.getBP5();
final int close = basePair.getBP3();
- // System.out.println("open " + open + " close " + close);
- // System.out.println("lastclose " + lastclose + " lastopen " + lastopen);
+ // jalview.bin.Console.outPrintln("open " + open + " close " + close);
+ // jalview.bin.Console.outPrintln("lastclose " + lastclose + " lastopen " + lastopen);
// we're moving from right to left based on closing pair
/*
{
int popen = bps.get(j).getBP5();
- // System.out.println("j " + j + " popen " + popen + " lastopen "
+ // jalview.bin.Console.outPrintln("j " + j + " popen " + popen + " lastopen "
// +lastopen + " open " + open);
if ((popen < lastopen) && (popen > open))
{
{
if (sfeatures != null)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Implementation error: setting dataset sequence for a sequence which has sequence features.\n\tDataset sequence features will not be visible.");
}
sq.setDatasetSequence(seqds);
{
if (!quiet)
{
- System.err.println("Can't find '" + ((String) key)
+ jalview.bin.Console.errPrintln("Can't find '" + ((String) key)
+ "' in uniquified alignment");
}
}
}
if (unmatched.size() > 0 && !quiet)
{
- System.err.println("Did not find matches for :");
+ jalview.bin.Console.errPrintln("Did not find matches for :");
for (Enumeration i = unmatched.elements(); i
.hasMoreElements(); System.out
.println(((SequenceI) i.nextElement()).getName()))
{
if (sequences[j] == null)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"WARNING: Consensus skipping null sequence - possible race condition.");
continue;
}
{
// if (_lycount<_lylimit)
// {
- // System.err.println("Warning: depth of _recount greater than number of
+ // jalview.bin.Console.errPrintln("Warning: depth of _recount greater than number of
// nodes.");
// }
if (nd == null)
if ((nd.left() == null) && (nd.right() == null))
{
- System.out.println("Leaf = " + ((SequenceI) nd.element()).getName());
- System.out.println("Dist " + nd.dist);
- System.out.println("Boot " + nd.getBootstrap());
+ jalview.bin.Console.outPrintln("Leaf = " + ((SequenceI) nd.element()).getName());
+ jalview.bin.Console.outPrintln("Dist " + nd.dist);
+ jalview.bin.Console.outPrintln("Boot " + nd.getBootstrap());
}
else
{
- System.out.println("Dist " + nd.dist);
+ jalview.bin.Console.outPrintln("Dist " + nd.dist);
printNode((BinaryNode) nd.left());
printNode((BinaryNode) nd.right());
}
}
else
{
- System.out.println(" name = " + ((SequenceI) nd.element()).getName());
+ jalview.bin.Console.outPrintln(" name = " + ((SequenceI) nd.element()).getName());
}
- System.out.println(
+ jalview.bin.Console.outPrintln(
" dist = " + nd.dist + " " + nd.count + " " + nd.height);
}
{
// if (_lycount<_lylimit)
// {
- // System.err.println("Warning: depth of _recount greater than number of
+ // jalview.bin.Console.errPrintln("Warning: depth of _recount greater than number of
// nodes.");
// }
if (nd == null)
return instance;
} catch (InstantiationException | IllegalAccessException e)
{
- System.err.println("Error in " + getClass().getName()
+ jalview.bin.Console.errPrintln("Error in " + getClass().getName()
+ ".getInstance(): " + e.getMessage());
return null;
} catch (ReflectiveOperationException roe)
{
if (c >= symbolIndex.length)
{
- System.err.println(String.format(BAD_ASCII_ERROR, c));
+ jalview.bin.Console.errPrintln(String.format(BAD_ASCII_ERROR, c));
return 0;
}
if (d >= symbolIndex.length)
{
- System.err.println(String.format(BAD_ASCII_ERROR, d));
+ jalview.bin.Console.errPrintln(String.format(BAD_ASCII_ERROR, d));
return 0;
}
return sm;
} catch (IOException e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Error reading " + resourcePath + ": " + e.getMessage());
}
return null;
ScoreModelI sm2 = models.get(sm.getName());
if (sm2 != null)
{
- System.err.println("Warning: replacing score model " + sm2.getName());
+ jalview.bin.Console.errPrintln("Warning: replacing score model " + sm2.getName());
}
models.put(sm.getName(), sm);
}
*/
package jalview.api;
+import jalview.datamodel.SequenceGroup;
import jalview.datamodel.SequenceI;
import jalview.renderer.seqfeatures.FeatureColourFinder;
import java.awt.Color;
+import java.awt.Graphics;
public interface SequenceRenderer
{
Color getResidueColour(SequenceI seq, int position,
FeatureColourFinder finder);
+ /**
+ * Configure the Graphics canvas and render options for the renderer
+ * @param g - the canvas to render to
+ * @param renderGaps - when true, gap characters will be included when rendered
+ *
+ */
+ void prepare(Graphics g, boolean renderGaps);
+
+ void drawSequence(SequenceI nextSeq, SequenceGroup[] findAllGroups,
+ int startRes, int endRes, int i);
+
+ void drawHighlightedText(SequenceI nextSeq, int i, int j, int k, int l);
+
+ void drawCursor(Graphics g, char s, int i, int j);
+
}
*/
package jalview.api.structures;
+import java.io.File;
+
import jalview.api.AlignmentViewPanel;
import jalview.datamodel.PDBEntry;
import jalview.datamodel.SequenceI;
+import jalview.gui.AlignmentPanel;
+import jalview.gui.StructureViewer;
import jalview.structures.models.AAStructureBindingModel;
public interface JalviewStructureDisplayI
*/
boolean hasViewerActionsMenu();
+ String getViewId();
+
+ StructureViewer.ViewerType getViewerType();
+
+ boolean isUsedforaligment(AlignmentViewPanel ap);
+
+ boolean isColouredByViewer();
+
+ int getHeight();
+
+ int getWidth();
+
+ int getY();
+
+ File saveSession();
+
}
urlLink = new UrlLink(link);
} catch (Exception foo)
{
- System.err.println("Exception for URLLink '" + link + "': "
+ jalview.bin.Console.errPrintln("Exception for URLLink '" + link + "': "
+ foo.getMessage());
continue;
}
if (!urlLink.isValid())
{
- System.err.println(urlLink.getInvalidMessage());
+ jalview.bin.Console.errPrintln(urlLink.getInvalidMessage());
continue;
}
/*
* When we finally deprecate 1.1 compatibility, we can start to use
* URLEncoder.encode(url,"UTF-8") and then we'll need this catch: catch
- * (UnsupportedEncodingException ex) { System.err.println("WARNING -
+ * (UnsupportedEncodingException ex) { jalview.bin.Console.errPrintln("WARNING -
* IMPLEMENTATION ERROR - UNSUPPORTED ENCODING EXCEPTION FOR "+url);
* ex.printStackTrace(); }
*/
url = viewport.applet.getCodeBase() + url;
} catch (UnsupportedEncodingException ex)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"WARNING = IMPLEMENTATION ERROR - UNSUPPORTED ENCODING EXCEPTION FOR "
+ url);
ex.printStackTrace();
SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
if (viewport.applet.debug)
{
- System.err.println("Sorting " + alorder.getOrder().size()
+ jalview.bin.Console.errPrintln("Sorting " + alorder.getOrder().size()
+ " in alignment '" + getTitle() + "'");
}
AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
{
if (viewport.applet == null)
{
- System.out.println("Not running as applet - no browser available.");
+ jalview.bin.Console.outPrintln("Not running as applet - no browser available.");
}
else
{
viewer = (Viewer) jmolviewer;
} catch (ClassCastException ex)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Unsupported viewer object :" + jmolviewer.getClass());
}
if (viewer == null)
{
- System.err.println("Can't use this object as a structure viewer:"
+ jalview.bin.Console.errPrintln("Can't use this object as a structure viewer:"
+ jmolviewer.getClass());
return null;
}
chains = (String[]) sqch[1];
if (seqs == null || seqs.length == 0)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"JalviewLite.AlignFrame:newStructureView: No sequence to bind structure to.");
}
if (protocol == null)
}
if (protocol == null)
{
- System.err.println("Couldn't work out protocol to open structure: "
+ jalview.bin.Console.errPrintln("Couldn't work out protocol to open structure: "
+ pdb.getId());
return;
}
.setMapping(seqs, chains, pdb.getFile(), protocol,
null) == null)
{
- System.err.println("Failed to map " + pdb.getFile() + " ("
+ jalview.bin.Console.errPrintln("Failed to map " + pdb.getFile() + " ("
+ protocol + ") to any sequences");
}
return;
}
if (ajm != null)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Incremental adding and aligning structure to existing Jmol view not yet implemented.");
// try and add the pdb structure
// ajm.addS
SequenceI[][] seqs, String[][] chains, String[] protocols)
{
// TODO Auto-generated method stub
- System.err.println("Aligned Structure View: Not yet implemented.");
+ jalview.bin.Console.errPrintln("Aligned Structure View: Not yet implemented.");
}
/**
if (!file.isValid())
{
// TODO: raise dialog for gui
- System.err.println("Problems parsing T-Coffee scores: "
+ jalview.bin.Console.errPrintln("Problems parsing T-Coffee scores: "
+ file.getWarningMessage());
- System.err.println("Origin was:\n" + source);
+ jalview.bin.Console.errPrintln("Origin was:\n" + source);
return false;
}
|| aln.getWidth() != file.getWidth()))
{
// TODO: raise a dialog box here rather than bomb out.
- System.err.println(
+ jalview.bin.Console.errPrintln(
"The scores matrix does not match the alignment dimensions");
}
}
else
{
- System.err.println("Problems resolving T-Coffee scores:");
+ jalview.bin.Console.errPrintln("Problems resolving T-Coffee scores:");
if (file.getWarningMessage() != null)
{
- System.err.println(file.getWarningMessage());
+ jalview.bin.Console.errPrintln(file.getWarningMessage());
}
}
return false;
}
if (widthScale <= 1.0)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Invalid alignment character width scaling factor ("
+ widthScale + "). Ignoring.");
widthScale = 1;
}
if (JalviewLite.debug)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Alignment character width scaling factor is now "
+ widthScale);
}
}
if (heightScale <= 1.0)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Invalid alignment character height scaling factor ("
+ heightScale + "). Ignoring.");
heightScale = 1;
}
if (JalviewLite.debug)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Alignment character height scaling factor is now "
+ heightScale);
}
{
if (JalviewLite.debug)
{// DEBUG
- System.out.println(
+ jalview.bin.Console.outPrintln(
"DEBUG: scroll didn't happen - results not within alignment : "
+ seq.getStart() + "," + seq.getEnd());
}
{
// DEBUG
/*
- * System.out.println("DEBUG: scroll: start=" + r[0] +
+ * jalview.bin.Console.outPrintln("DEBUG: scroll: start=" + r[0] +
* " av.getStartRes()=" + av.getStartRes() + " end=" + r[1] +
* " seq.end=" + seq.getEnd() + " av.getEndRes()=" + av.getEndRes() +
* " hextent=" + hextent);
// this is called after loading new annotation onto alignment
if (alignFrame.getSize().height == 0)
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"adjustAnnotationHeight frame size zero NEEDS FIXING");
}
fontChanged();
if ((hextent + x) > width)
{
- System.err.println("hextent was " + hextent + " and x was " + x);
+ jalview.bin.Console.errPrintln("hextent was " + hextent + " and x was " + x);
x = width - hextent;
}
if (x < 0)
{
- System.err.println("x was " + x);
+ jalview.bin.Console.errPrintln("x was " + x);
x = 0;
}
public void raiseOOMWarning(String string, OutOfMemoryError error)
{
// TODO: JAL-960
- System.err.println("Out of memory whilst '" + string + "'");
+ jalview.bin.Console.errPrintln("Out of memory whilst '" + string + "'");
error.printStackTrace();
}
"-applet", scriptWindow, null);
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Couldn't create a jmol viewer. Args to allocate viewer were:\nDocumentBase="
+ ap.av.applet.getDocumentBase() + "\nCodebase="
+ ap.av.applet.getCodeBase());
{
if (jalview.bin.JalviewLite.debug)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"AppletJmol:Trying to reuse existing PDBfile IO parser.");
}
// re-use the one we opened earlier
{
if (jalview.bin.JalviewLite.debug)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"AppletJmol:Creating new PDBfile IO parser.");
}
FileParse fp = new FileParse(pdbentry.getFile(), protocol);
} catch (Exception e)
{
// give up!
- System.err.println("Couldn't access pdbentry id="
+ jalview.bin.Console.errPrintln("Couldn't access pdbentry id="
+ pdbentry.getId() + " and file=" + pdbentry.getFile()
+ " using protocol=" + protocol);
e.printStackTrace();
} catch (OutOfMemoryError ex)
{
frame.dispose();
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Out of memory when trying to create dialog box with sequence-structure mapping.");
return;
}
{
// This never gets called because we haven't overriden the associated Jmol's
// console
- System.err.println(
+ jalview.bin.Console.errPrintln(
"WARNING: unexpected call to ExtJmol's showConsole method. (showConsole="
+ show);
}
top = pcaModel.getTop();
} catch (OutOfMemoryError x)
{
- System.err.println("Out of memory when calculating PCA.");
+ jalview.bin.Console.errPrintln("Out of memory when calculating PCA.");
return;
}
calcSettings.setEnabled(true);
if (count > 2)
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Pairwise alignment scaled similarity score matrix\n");
for (int i = 0; i < count; i++)
("" + i) + " " + seqs[i].getName());
}
- System.out.println("\n");
+ jalview.bin.Console.outPrintln("\n");
for (int i = 0; i < count; i++)
{
}
}
- System.out.println("\n");
+ jalview.bin.Console.outPrintln("\n");
}
}
validate();
sliderValueChanged();
- // System.out.println("blob done "+ (System.currentTimeMillis()-start));
+ // jalview.bin.Console.outPrintln("blob done "+ (System.currentTimeMillis()-start));
}
void sliderValueChanged()
scale = findScale();
- // System.out.println("Scale factor = " + scale);
+ // jalview.bin.Console.outPrintln("Scale factor = " + scale);
addMouseListener(this);
addKeyListener(this);
scale = findScale();
- // System.out.println("New scale = " + scale);
+ // jalview.bin.Console.outPrintln("New scale = " + scale);
img = createImage(getSize().width, getSize().height);
ig = img.getGraphics();
}
else if (evt.getKeyChar() == 's')
{
- System.err.println("DEBUG: Rectangle selection"); // log.debug
+ jalview.bin.Console.errPrintln("DEBUG: Rectangle selection"); // log.debug
if (rectx2 != -1 && recty2 != -1)
{
rectSelect(rectx1, recty1, rectx2, recty2);
if (av.cursorMode && cursorY == i && cursorX >= startRes
&& cursorX <= endRes)
{
- sr.drawCursor(nextSeq, cursorX, (cursorX - startRes) * avcharWidth,
+ char s = nextSeq.getCharAt(cursorX);
+
+ sr.drawCursor(g,s, (cursorX - startRes) * avcharWidth,
offset + ((i - startSeq) * avcharHeight));
}
}
@Override
public void updateColours(SequenceI seq, int index)
{
- System.out.println("update the seqPanel colours");
+ jalview.bin.Console.outPrintln("update the seqPanel colours");
// repaint();
}
{
if (av.getAlignment() == null)
{
- System.out.println("Selection message: alignviewport av SeqSetId="
+ jalview.bin.Console.outPrintln("Selection message: alignviewport av SeqSetId="
+ av.getSequenceSetId() + " ViewId=" + av.getViewId()
+ " 's alignment is NULL! returning immediatly.");
return;
if (copycolsel && av.hasHiddenColumns()
&& (av.getColumnSelection() == null))
{
- System.err.println("Bad things");
+ jalview.bin.Console.errPrintln("Bad things");
}
if (repaint)
{
}
}
- public void drawCursor(SequenceI seq, int res, int x1, int y1)
+ public void drawCursor(Graphics graphics, char s, int x1, int y1)
{
int pady = av.getCharHeight() / 5;
int charOffset = 0;
graphics.setColor(Color.white);
- char s = seq.getCharAt(res);
if (av.validCharWidth)
{
}
else
{
- System.out.println("Original Tree Data not available");
+ jalview.bin.Console.outPrintln("Original Tree Data not available");
}
}
* <li>WRAP_ALIGNMENT</li>
* <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
* style check</li>
+ * <li>BITMAP_SCALE - scale factor for PNG export - default 0.0 - native
+ * resolution</li>
+ * <li>BITMAP_HEIGHT - height bound for PNG export or 0 for unbound</li>
+ * <li>BITMAP_WIDTH - width bound for PNG export or 0 for unbound</li>
* <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
* <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
* $SEQUENCE_ID$</li>
fis = new URL(propertiesFile).openStream();
if (!Jalview.quiet())
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Loading jalview properties from : " + propertiesFile);
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Disabling Jalview writing to user's local properties file.");
}
propsAreReadOnly = true;
} catch (Exception ex)
{
if (!Jalview.quiet())
- System.out.println("Error reading properties file: " + ex);
+ jalview.bin.Console
+ .outPrintln("Error reading properties file: " + ex);
}
}
} catch (Exception ex)
{
if (!Jalview.quiet())
- System.out.println("Error reading author details: " + ex);
+ jalview.bin.Console
+ .outPrintln("Error reading author details: " + ex);
authorDetails = null;
}
if (authorDetails == null)
{
if (!Jalview.quiet())
{
- System.out.println(
+ jalview.bin.Console.errPrintln(
"Non-fatal exception when checking version at "
+ remoteBuildPropertiesUrl + ":");
- System.out.println(ex);
+ jalview.bin.Console.printStackTrace(ex);
}
remoteVersion = getProperty("VERSION");
}
url = Cache.class.getResource(resourcePath).toString();
} catch (Exception ex)
{
- System.err.println("Failed to resolve resource " + resourcePath
- + ": " + ex.getMessage());
+ jalview.bin.Console.errPrintln("Failed to resolve resource "
+ + resourcePath + ": " + ex.getMessage());
}
}
else
} catch (Exception ex)
{
if (!Jalview.quiet())
- System.out.println("Error reading build details: " + ex);
+ jalview.bin.Console
+ .outPrintln("Error reading build details: " + ex);
applicationProperties.remove("VERSION");
}
String codeVersion = getProperty("VERSION");
new BuildDetails(codeVersion, null, codeInstallation);
if (printVersion && reportVersion)
{
- System.out.println(ChannelProperties.getProperty("app_name")
- + " version: " + codeVersion + codeInstallation);
+ jalview.bin.Console
+ .outPrintln(ChannelProperties.getProperty("app_name")
+ + " version: " + codeVersion + codeInstallation);
}
}
} catch (NumberFormatException e)
{
if (!Jalview.quiet())
- System.out.println("Error parsing int property '" + property
- + "' with value '" + string + "'");
+ jalview.bin.Console.errPrintln("Error parsing int property '"
+ + property + "' with value '" + string + "'");
+ }
+ }
+
+ return def;
+ }
+
+ public static float getDefault(String property, float def)
+ {
+ String string = getProperty(property);
+ if (string != null)
+ {
+ try
+ {
+ def = Float.parseFloat(string);
+ } catch (NumberFormatException e)
+ {
+ if (!Jalview.quiet())
+ jalview.bin.Console.errPrintln("Error parsing float property '"
+ + property + "' with value '" + string + "'");
}
}
} catch (Exception ex)
{
if (!Jalview.quiet())
- System.out.println(
+ jalview.bin.Console.errPrintln(
"Error setting property: " + key + " " + obj + "\n" + ex);
}
return oldValue;
} catch (Exception ex)
{
if (!Jalview.quiet())
- System.out.println("Error saving properties: " + ex);
+ jalview.bin.Console.errPrintln("Error saving properties: " + ex);
}
}
}
return date_format.parse(val);
} catch (Exception ex)
{
- System.err.println("Invalid or corrupt date in property '"
- + propertyName + "' : value was '" + val + "'");
+ jalview.bin.Console
+ .errPrintln("Invalid or corrupt date in property '"
+ + propertyName + "' : value was '" + val + "'");
}
}
return null;
return Integer.valueOf(val);
} catch (NumberFormatException x)
{
- System.err.println("Invalid integer in property '" + property
- + "' (value was '" + val + "')");
+ jalview.bin.Console.errPrintln("Invalid integer in property '"
+ + property + "' (value was '" + val + "')");
}
}
return null;
} catch (Exception ex)
{
if (!Jalview.quiet())
- System.out.println("Error loading User ColourFile\n" + ex);
+ jalview.bin.Console
+ .outPrintln("Error loading User ColourFile\n" + ex);
}
}
if (!files.equals(coloursFound.toString()))
return null;
if (!file.exists())
{
- System.err.println("Could not load bootstrap preferences file '"
- + filename + "'");
+ jalview.bin.Console
+ .errPrintln("Could not load bootstrap preferences file '"
+ + filename + "'");
return null;
}
}
} catch (FileNotFoundException e)
{
- System.err.println("Could not find bootstrap preferences file '"
- + file.getAbsolutePath() + "'");
+ jalview.bin.Console
+ .errPrintln("Could not find bootstrap preferences file '"
+ + file.getAbsolutePath() + "'");
} catch (IOException e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"IOException when loading bootstrap preferences file '"
+ file.getAbsolutePath() + "'");
}
package jalview.bin;
+import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
-import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import jalview.analysis.AlignmentUtils;
import jalview.api.structures.JalviewStructureDisplayI;
+import jalview.bin.Jalview.ExitCode;
import jalview.bin.argparser.Arg;
import jalview.bin.argparser.ArgParser;
-import jalview.bin.argparser.ArgParser.Position;
import jalview.bin.argparser.ArgValue;
import jalview.bin.argparser.ArgValuesMap;
import jalview.bin.argparser.SubVals;
import jalview.io.exceptions.ImageOutputException;
import jalview.schemes.ColourSchemeI;
import jalview.schemes.ColourSchemeProperty;
+import jalview.structure.StructureCommandI;
import jalview.structure.StructureImportSettings.TFType;
import jalview.structure.StructureSelectionManager;
+import jalview.util.ColorUtils;
import jalview.util.FileUtils;
import jalview.util.HttpUtils;
import jalview.util.ImageMaker;
import jalview.util.ImageMaker.TYPE;
import jalview.util.MessageManager;
import jalview.util.Platform;
+import jalview.util.StringUtils;
import jalview.util.imagemaker.BitmapImageSizing;
public class Commands
private Map<String, AlignFrame> afMap;
+ private Map<String, List<StructureViewer>> svMap;
+
private boolean commandArgsProvided = false;
private boolean argsWereParsed = false;
+ private List<String> errors = new ArrayList<>();
+
public Commands(ArgParser argparser, boolean headless)
{
this(Desktop.instance, argparser, headless);
headless = h;
desktop = d;
afMap = new HashMap<>();
- if (argparser != null)
- {
- processArgs(argparser, headless);
- }
}
- private boolean processArgs(ArgParser argparser, boolean h)
+ protected boolean processArgs()
{
- argParser = argparser;
- headless = h;
+ if (argParser == null)
+ {
+ return true;
+ }
+
boolean theseArgsWereParsed = false;
if (argParser != null && argParser.getLinkedIds() != null)
{
ArgValuesMap avm = argParser.getLinkedArgs(id);
theseArgsWereParsed = true;
- theseArgsWereParsed &= processLinked(id);
+ boolean processLinkedOkay = processLinked(id);
+ theseArgsWereParsed &= processLinkedOkay;
+
processGroovyScript(id);
- boolean processLinkedOkay = theseArgsWereParsed;
-
+
// wait around until alignFrame isn't busy
- AlignFrame af=afMap.get(id);
- while (af!=null && af.getViewport().isCalcInProgress())
+ AlignFrame af = afMap.get(id);
+ while (af != null && af.getViewport().isCalcInProgress())
{
- try {
+ try
+ {
Thread.sleep(25);
- } catch (Exception q) {};
+ } catch (Exception q)
+ {
+ }
+ ;
}
-
+
theseArgsWereParsed &= processImages(id);
+
if (processLinkedOkay)
+ {
theseArgsWereParsed &= processOutput(id);
+ }
// close ap
if (avm.getBoolean(Arg.CLOSE))
}
}
+
+ // report errors - if any
+ String errorsRaised = errorsToString();
+ if (errorsRaised.trim().length() > 0)
+ {
+ Console.warn(
+ "The following errors and warnings occurred whilst processing files:\n"
+ + errorsRaised);
+ }
+ // gui errors reported in Jalview
+
if (argParser.getBoolean(Arg.QUIT))
{
- Jalview.getInstance().quit();
+ Jalview.getInstance().exit(
+ "Exiting due to " + Arg.QUIT.argString() + " argument.",
+ ExitCode.OK);
return true;
}
// carry on with jalview.bin.Jalview
return argsWereParsed;
}
- protected boolean processUnlinked(String id)
- {
- return processLinked(id);
- }
-
protected boolean processLinked(String id)
{
boolean theseArgsWereParsed = false;
ArgValuesMap avm = argParser.getLinkedArgs(id);
if (avm == null)
+ {
return true;
+ }
+
+ Boolean isError = Boolean.valueOf(false);
+
+ // set wrap scope here so it can be applied after structures are opened
+ boolean wrap = false;
- /*
- * // script to execute after all loading is completed one way or another String
- * groovyscript = m.get(Arg.GROOVY) == null ? null :
- * m.get(Arg.GROOVY).getValue(); String file = m.get(Arg.OPEN) == null ? null :
- * m.get(Arg.OPEN).getValue(); String data = null; FileFormatI format = null;
- * DataSourceType protocol = null;
- */
if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
{
commandArgsProvided = true;
{
if (!(new File(openFile)).exists())
{
- Console.warn("Can't find file '" + openFile + "'");
+ addError("Can't find file '" + openFile + "'");
+ isError = true;
+ continue;
}
}
}
format = new IdentifyFile().identify(openFile, protocol);
} catch (FileFormatException e1)
{
- Console.error("Unknown file format for '" + openFile + "'");
+ addError("Unknown file format for '" + openFile + "'");
+ isError = true;
+ continue;
}
af = afMap.get(id);
Console.debug(
"Opening '" + openFile + "' in new alignment frame");
FileLoader fileLoader = new FileLoader(!headless);
-
- af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
- format);
-
- // wrap alignment?
- boolean wrap = ArgParser.getFromSubValArgOrPref(avm, Arg.WRAP, sv,
- null, "WRAP_ALIGNMENT", false);
- af.getCurrentView().setWrapAlignment(wrap);
-
- // colour alignment?
- String colour = ArgParser.getFromSubValArgOrPref(avm, av,
- Arg.COLOUR, sv, null, "DEFAULT_COLOUR_PROT", "");
- if ("" != colour)
+ boolean xception = false;
+ try
+ {
+ af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
+ format);
+ } catch (Throwable thr)
+ {
+ xception = true;
+ addError("Couldn't open '" + openFile + "' as " + format + " "
+ + thr.getLocalizedMessage()
+ + " (Enable debug for full stack trace)");
+ isError = true;
+ Console.debug("Exception when opening '" + openFile + "'", thr);
+ } finally
{
- ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
- af.getViewport(), af.getViewport().getAlignment(), colour);
-
- if (cs==null && !"None".equals(colour))
+ if (af == null && !xception)
{
- Console.warn("Couldn't parse '"+colour+"' as a colourscheme.");
- } else {
- af.changeColour(cs);
+ addInfo("Ignoring '" + openFile
+ + "' - no alignment data found.");
+ continue;
}
- Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
}
+ // colour alignment
+ String colour = avm.getFromSubValArgOrPref(av, Arg.COLOUR, sv,
+ null, "DEFAULT_COLOUR_PROT", "");
+ this.colourAlignFrame(af, colour);
+
// Change alignment frame title
- String title = ArgParser.getFromSubValArgOrPref(avm, av,
- Arg.TITLE, sv, null, null, null);
+ String title = avm.getFromSubValArgOrPref(av, Arg.TITLE, sv, null,
+ null, null);
if (title != null)
{
af.setTitle(title);
}
// Add features
- String featuresfile = ArgParser.getValueFromSubValOrArg(avm, av,
+ String featuresfile = avm.getValueFromSubValOrArg(av,
Arg.FEATURES, sv);
if (featuresfile != null)
{
}
// Add annotations from file
- String annotationsfile = ArgParser.getValueFromSubValOrArg(avm,
- av, Arg.ANNOTATIONS, sv);
+ String annotationsfile = avm.getValueFromSubValOrArg(av,
+ Arg.ANNOTATIONS, sv);
if (annotationsfile != null)
{
af.loadJalviewDataFile(annotationsfile, null, null, null);
}
// Set or clear the sortbytree flag
- boolean sortbytree = ArgParser.getBoolFromSubValOrArg(avm,
- Arg.SORTBYTREE, sv);
+ boolean sortbytree = avm.getBoolFromSubValOrArg(Arg.SORTBYTREE,
+ sv);
if (sortbytree)
{
af.getViewport().setSortByTree(true);
}
// Load tree from file
- String treefile = ArgParser.getValueFromSubValOrArg(avm, av,
- Arg.TREE, sv);
+ String treefile = avm.getValueFromSubValOrArg(av, Arg.TREE, sv);
if (treefile != null)
{
try
"examples/testdata/uniref50_test_tree", treefile);
} catch (IOException e)
{
- Console.warn("Couldn't add tree " + treefile, e);
+ addError("Couldn't add tree " + treefile, e);
+ isError = true;
}
}
// Show secondary structure annotations?
- boolean showSSAnnotations = ArgParser.getFromSubValArgOrPref(avm,
+ boolean showSSAnnotations = avm.getFromSubValArgOrPref(
Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
"STRUCT_FROM_PDB", true);
af.setAnnotationsVisibility(showSSAnnotations, true, false);
// Show sequence annotations?
- boolean showAnnotations = ArgParser.getFromSubValArgOrPref(avm,
+ boolean showAnnotations = avm.getFromSubValArgOrPref(
Arg.SHOWANNOTATIONS, av.getSubVals(), null,
"SHOW_ANNOTATIONS", true);
af.setAnnotationsVisibility(showAnnotations, false, true);
false, false);
}
+ // wrap alignment? do this last for formatting reasons
+ wrap = avm.getFromSubValArgOrPref(Arg.WRAP, sv, null,
+ "WRAP_ALIGNMENT", false);
+ // af.setWrapFormat(wrap) is applied after structures are opened for
+ // annotation reasons
+
// store the AlignFrame for this id
afMap.put(id, af);
{
if (headless)
{
- Jalview.exit("Could not open any files in headless mode", 1);
+ Jalview.exit("Could not open any files in headless mode",
+ ExitCode.NO_FILES);
}
else
{
- Console.warn("No more files to open");
+ Console.info("No more files to open");
}
}
if (progressBarSet && desktop != null)
commandArgsProvided = true;
for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
{
+ argParser.setStructureFilename(null);
String val = av.getValue();
SubVals subVals = av.getSubVals();
+ int argIndex = av.getArgIndex();
SequenceI seq = getSpecifiedSequence(af, avm, av);
if (seq == null)
{
if (seq == null)
{
- Console.warn("Could not find sequence for argument "
+ addWarn("Could not find sequence for argument "
+ Arg.STRUCTURE.argString() + "=" + val);
- // you probably want to continue here, not break
- // break;
continue;
}
+ String structureFilename = null;
File structureFile = null;
if (subVals.getContent() != null
&& subVals.getContent().length() != 0)
{
- structureFile = new File(subVals.getContent());
+ structureFilename = subVals.getContent();
Console.debug("Using structure file (from argument) '"
- + structureFile.getAbsolutePath() + "'");
- }
- // TRY THIS
- /*
- * PDBEntry fileEntry = new AssociatePdbFileWithSeq()
- * .associatePdbWithSeq(selectedPdbFileName, DataSourceType.FILE,
- * selectedSequence, true, Desktop.instance);
- *
- * sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap, new
- * SequenceI[] { selectedSequence });
- *
- */
+ + structureFilename + "'");
+ structureFile = new File(structureFilename);
+ }
/* THIS DOESN'T WORK */
else if (seq.getAllPDBEntries() != null
&& seq.getAllPDBEntries().size() > 0)
{
structureFile = new File(
seq.getAllPDBEntries().elementAt(0).getFile());
- Console.debug("Using structure file (from sequence) '"
- + structureFile.getAbsolutePath() + "'");
+ if (structureFile != null)
+ {
+ Console.debug("Using structure file (from sequence) '"
+ + structureFile.getAbsolutePath() + "'");
+ }
+ structureFilename = structureFile.getAbsolutePath();
}
- if (structureFile == null)
+ if (structureFilename == null || structureFile == null)
{
- Console.warn("Not provided structure file with '" + val + "'");
+ addWarn("Not provided structure file with '" + val + "'");
continue;
}
if (!structureFile.exists())
{
- Console.warn("Structure file '"
- + structureFile.getAbsoluteFile() + "' not found.");
+ addWarn("Structure file '" + structureFile.getAbsoluteFile()
+ + "' not found.");
continue;
}
Console.debug("Using structure file "
+ structureFile.getAbsolutePath());
+ argParser.setStructureFilename(structureFilename);
+
// open structure view
AlignmentPanel ap = af.alignPanel;
if (headless)
String structureFilepath = structureFile.getAbsolutePath();
// get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
- String paeFilepath = ArgParser
- .getFromSubValArgOrPrefWithSubstitutions(argParser, avm,
- Arg.PAEMATRIX, Position.AFTER, av, subVals, null,
- null, null);
+ String paeFilepath = avm.getFromSubValArgOrPrefWithSubstitutions(
+ argParser, Arg.PAEMATRIX, ArgValuesMap.Position.AFTER, av,
+ subVals, null, null, null);
if (paeFilepath != null)
{
File paeFile = new File(paeFilepath);
} catch (IOException e)
{
paeFilepath = paeFile.getAbsolutePath();
- Console.warn("Problem with the PAE file path: '"
+ addWarn("Problem with the PAE file path: '"
+ paeFile.getPath() + "'");
}
}
// showing annotations from structure file or not
- boolean ssFromStructure = ArgParser.getFromSubValArgOrPref(avm,
+ boolean ssFromStructure = avm.getFromSubValArgOrPref(
Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
true);
// get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
// reference annotations
- String tftString = ArgParser
- .getFromSubValArgOrPrefWithSubstitutions(argParser, avm,
- Arg.TEMPFAC, Position.AFTER, av, subVals, null,
- null, null);
- boolean notempfac = ArgParser.getFromSubValArgOrPref(avm,
- Arg.NOTEMPFAC, subVals, null, "ADD_TEMPFACT_ANN", false,
- true);
+ String tftString = avm.getFromSubValArgOrPrefWithSubstitutions(
+ argParser, Arg.TEMPFAC, ArgValuesMap.Position.AFTER, av,
+ subVals, null, null, null);
+ boolean notempfac = avm.getFromSubValArgOrPref(Arg.NOTEMPFAC,
+ subVals, null, "ADD_TEMPFACT_ANN", false, true);
TFType tft = notempfac ? null : TFType.DEFAULT;
if (tftString != null && !notempfac)
{
if (it.hasNext())
sb.append(", ");
}
- Console.warn(sb.toString());
+ addWarn(sb.toString());
}
}
- String sViewer = ArgParser.getFromSubValArgOrPref(avm,
- Arg.STRUCTUREVIEWER, Position.AFTER, av, subVals, null,
- null, "jmol");
- ViewerType viewerType = null;
- if (!"none".equals(sViewer))
- {
- for (ViewerType v : EnumSet.allOf(ViewerType.class))
- {
- String name = v.name().toLowerCase(Locale.ROOT)
- .replaceAll(" ", "");
- if (sViewer.equals(name))
- {
- viewerType = v;
- break;
- }
- }
- }
+ String sViewerName = avm.getFromSubValArgOrPref(
+ Arg.STRUCTUREVIEWER, ArgValuesMap.Position.AFTER, av,
+ subVals, null, null, "jmol");
+ ViewerType viewerType = ViewerType.getFromString(sViewerName);
// TODO use ssFromStructure
- StructureViewer sv = StructureChooser
+ StructureViewer structureViewer = StructureChooser
.openStructureFileForSequence(null, null, ap, seq, false,
structureFilepath, tft, paeFilepath, false,
ssFromStructure, false, viewerType);
- if (sv==null)
+ if (structureViewer == null)
{
- Console.error("Failed to import and open structure view.");
+ if (!StringUtils.equalsIgnoreCase(sViewerName, "none"))
+ {
+ addError("Failed to import and open structure view for file '"
+ + structureFile + "'.");
+ }
continue;
}
try
{
- long tries=1000;
- while (sv.isBusy() && tries>0)
+ long tries = 1000;
+ while (structureViewer.isBusy() && tries > 0)
{
Thread.sleep(25);
- if (sv.isBusy())
+ if (structureViewer.isBusy())
{
tries--;
Console.debug(
"Waiting for viewer for " + structureFilepath);
}
}
- if (tries==0 && sv.isBusy())
+ if (tries == 0 && structureViewer.isBusy())
{
- Console.warn("Gave up waiting for structure viewer to load. Something may have gone wrong.");
+ addWarn("Gave up waiting for structure viewer to load file '"
+ + structureFile
+ + "'. Something may have gone wrong.");
}
} catch (Exception x)
{
- Console.warn("Exception whilst waiting for structure viewer "+structureFilepath,x);
+ addError("Exception whilst waiting for structure viewer "
+ + structureFilepath, x);
+ isError = true;
+ }
+
+ // add StructureViewer to svMap list
+ if (svMap == null)
+ {
+ svMap = new HashMap<>();
}
- Console.debug("Successfully opened viewer for "+structureFilepath);
- String structureImageFilename = ArgParser.getValueFromSubValOrArg(
- avm, av, Arg.STRUCTUREIMAGE, subVals);
- if (sv != null && structureImageFilename != null)
+ if (svMap.get(id) == null)
{
- ArgValue siAv = avm.getClosestNextArgValueOfArg(av,
- Arg.STRUCTUREIMAGE);
- SubVals sisv = null;
- if (structureImageFilename.equals(siAv.getValue()))
- {
- sisv = siAv.getSubVals();
- }
- File structureImageFile = new File(structureImageFilename);
- String width = ArgParser.getValueFromSubValOrArg(avm, av,
- Arg.STRUCTUREIMAGEWIDTH, sisv);
- String height = ArgParser.getValueFromSubValOrArg(avm, av,
- Arg.STRUCTUREIMAGEHEIGHT, sisv);
- String scale = ArgParser.getValueFromSubValOrArg(avm, av,
- Arg.STRUCTUREIMAGESCALE, sisv);
- String renderer = ArgParser.getValueFromSubValOrArg(avm, av,
- Arg.STRUCTUREIMAGETEXTRENDERER, sisv);
- String typeS = ArgParser.getValueFromSubValOrArg(avm, av,
- Arg.STRUCTUREIMAGETYPE, sisv);
- if (typeS == null || typeS.length() == 0)
- {
- typeS = FileUtils.getExtension(structureImageFile);
- }
- TYPE imageType;
- try
- {
- imageType = Enum.valueOf(TYPE.class,
- typeS.toUpperCase(Locale.ROOT));
- } catch (IllegalArgumentException e)
- {
- Console.warn("Do not know image format '" + typeS
- + "', using PNG");
- imageType = TYPE.PNG;
- }
- BitmapImageSizing userBis = ImageMaker
- .parseScaleWidthHeightStrings(scale, width, height);
- // TODO MAKE THIS VIEWER INDEPENDENT!!
- switch (StructureViewer.getViewerType())
+ svMap.put(id, new ArrayList<>());
+ }
+ svMap.get(id).add(structureViewer);
+
+ Console.debug(
+ "Successfully opened viewer for " + structureFilepath);
+
+ if (avm.containsArg(Arg.STRUCTUREIMAGE))
+ {
+ for (ArgValue structureImageArgValue : avm
+ .getArgValueList(Arg.STRUCTUREIMAGE))
{
- case JMOL:
- try
+ String structureImageFilename = argParser.makeSubstitutions(
+ structureImageArgValue.getValue(), id, true);
+ if (structureViewer != null && structureImageFilename != null)
{
- Thread.sleep(1000); // WHY ???
- } catch (InterruptedException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- JalviewStructureDisplayI sview = sv
- .getJalviewStructureDisplay();
- if (sview instanceof AppJmol)
- {
- AppJmol jmol = (AppJmol) sview;
- try {
- Console.debug("Rendering image to "+structureImageFile);
- jmol.makePDBImage(structureImageFile, imageType, renderer,
- userBis);
- Console.debug("Finished Rendering image to "+structureImageFile);
+ SubVals structureImageSubVals = null;
+ structureImageSubVals = structureImageArgValue.getSubVals();
+ File structureImageFile = new File(structureImageFilename);
+ String width = avm.getValueFromSubValOrArg(
+ structureImageArgValue, Arg.WIDTH,
+ structureImageSubVals);
+ String height = avm.getValueFromSubValOrArg(
+ structureImageArgValue, Arg.HEIGHT,
+ structureImageSubVals);
+ String scale = avm.getValueFromSubValOrArg(
+ structureImageArgValue, Arg.SCALE,
+ structureImageSubVals);
+ String renderer = avm.getValueFromSubValOrArg(
+ structureImageArgValue, Arg.TEXTRENDERER,
+ structureImageSubVals);
+ String typeS = avm.getValueFromSubValOrArg(
+ structureImageArgValue, Arg.TYPE,
+ structureImageSubVals);
+ if (typeS == null || typeS.length() == 0)
+ {
+ typeS = FileUtils.getExtension(structureImageFile);
+ }
+ TYPE imageType;
+ try
+ {
+ imageType = Enum.valueOf(TYPE.class,
+ typeS.toUpperCase(Locale.ROOT));
+ } catch (IllegalArgumentException e)
+ {
+ addWarn("Do not know image format '" + typeS
+ + "', using PNG");
+ imageType = TYPE.PNG;
+ }
+ BitmapImageSizing userBis = ImageMaker
+ .parseScaleWidthHeightStrings(scale, width, height);
+ /////
+ // DON'T TRY TO EXPORT IF VIEWER IS UNSUPPORTED
+ if (viewerType != ViewerType.JMOL)
+ {
+ addWarn("Cannot export image for structure viewer "
+ + viewerType.name() + " yet");
+ continue;
}
- catch (ImageOutputException ioexc)
+
+ /////
+ // Apply the temporary colourscheme to the linked alignment
+ // TODO: enhance for multiple linked alignments.
+
+ String imageColour = avm.getValueFromSubValOrArg(
+ structureImageArgValue, Arg.IMAGECOLOUR,
+ structureImageSubVals);
+ ColourSchemeI originalColourScheme = this
+ .getColourScheme(af);
+ this.colourAlignFrame(af, imageColour);
+
+ /////
+ // custom image background colour
+
+ String bgcolourstring = avm.getValueFromSubValOrArg(
+ structureImageArgValue, Arg.BGCOLOUR,
+ structureImageSubVals);
+ Color bgcolour = null;
+ if (bgcolourstring != null && bgcolourstring.length() > 0)
{
- Console.warn("Unexpected error whilst exporting image to "+structureImageFile,ioexc);
+ bgcolour = ColorUtils.parseColourString(bgcolourstring);
+ if (bgcolour == null)
+ {
+ Console.warn(
+ "Background colour string '" + bgcolourstring
+ + "' not recognised -- using default");
+ }
}
+ JalviewStructureDisplayI sview = structureViewer
+ .getJalviewStructureDisplay();
+
+ File sessionToRestore = null;
+
+ List<StructureCommandI> extraCommands = new ArrayList<>();
+
+ if (extraCommands.size() > 0 || bgcolour != null)
+ {
+ try
+ {
+ sessionToRestore = sview.saveSession();
+ } catch (Throwable t)
+ {
+ Console.warn(
+ "Unable to save temporary session file before custom structure view export operation.");
+ }
+ }
+
+ ////
+ // Do temporary ops
+
+ if (bgcolour != null)
+ {
+ sview.getBinding().setBackgroundColour(bgcolour);
+ }
+
+ sview.getBinding().executeCommands(extraCommands, false,
+ "Executing Custom Commands");
+
+ // and export the view as an image
+ boolean success = this.checksBeforeWritingToFile(avm,
+ subVals, false, structureImageFilename,
+ "structure image", isError);
+
+ if (!success)
+ {
+ continue;
+ }
+ Console.debug("Rendering image to " + structureImageFile);
+ //
+ // TODO - extend StructureViewer / Binding with makePDBImage so
+ // we can do this with every viewer
+ //
+
+ try
+ {
+ // We don't expect class cast exception
+ AppJmol jmol = (AppJmol) sview;
+ jmol.makePDBImage(structureImageFile, imageType, renderer,
+ userBis);
+ Console.debug("Finished Rendering image to "
+ + structureImageFile);
+
+ // RESTORE SESSION AFTER EXPORT IF NEED BE
+ if (sessionToRestore != null)
+ {
+ Console.debug("Restoring session from "
+ + sessionToRestore);
+
+ sview.getBinding().restoreSession(sessionToRestore.getAbsolutePath());
+
+ }
+ } catch (ImageOutputException ioexec)
+ {
+ addError(
+ "Unexpected error when restoring structure viewer session after custom view operations.");
+ isError = true;
+ continue;
+ } finally
+ {
+ try {
+ this.colourAlignFrame(af, originalColourScheme);
+ } catch (Exception t)
+ {
+ addError("Unexpected error when restoring colourscheme to alignment after temporary change for export.",t);
+ }
+ }
}
- break;
- default:
- Console.warn("Cannot export image for structure viewer "
- + sv.getViewerType() + " yet");
- break;
}
}
+ argParser.setStructureFilename(null);
}
}
}
+ if (wrap)
+ {
+ AlignFrame af = afMap.get(id);
+ if (af != null)
+ {
+ af.setWrapFormat(wrap, true);
+ }
+ }
+
/*
boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
if (doShading)
}
*/
- return theseArgsWereParsed;
+ return theseArgsWereParsed && !isError;
}
protected void processGroovyScript(String id)
if (af == null)
{
- Console.warn("Did not have an alignment window for id=" + id);
+ addWarn("Did not have an alignment window for id=" + id);
return;
}
if (af == null)
{
- Console.warn("Did not have an alignment window for id=" + id);
+ addWarn("Did not have an alignment window for id=" + id);
return false;
}
+ Boolean isError = Boolean.valueOf(false);
if (avm.containsArg(Arg.IMAGE))
{
- for (ArgValue av : avm.getArgValueList(Arg.IMAGE))
+ for (ArgValue imageAv : avm.getArgValueList(Arg.IMAGE))
{
- String val = av.getValue();
- SubVals subVal = av.getSubVals();
- String fileName = subVal.getContent();
+ String val = imageAv.getValue();
+ SubVals imageSubVals = imageAv.getSubVals();
+ String fileName = imageSubVals.getContent();
File file = new File(fileName);
String name = af.getName();
- String renderer = ArgParser.getValueFromSubValOrArg(avm, av,
- Arg.TEXTRENDERER, subVal);
+ String renderer = avm.getValueFromSubValOrArg(imageAv,
+ Arg.TEXTRENDERER, imageSubVals);
if (renderer == null)
renderer = "text";
String type = "png"; // default
- String scale = ArgParser.getValueFromSubValOrArg(avm, av, Arg.SCALE,
- subVal);
- String width = ArgParser.getValueFromSubValOrArg(avm, av, Arg.WIDTH,
- subVal);
- String height = ArgParser.getValueFromSubValOrArg(avm, av,
- Arg.HEIGHT, subVal);
+ String scale = avm.getValueFromSubValOrArg(imageAv, Arg.SCALE,
+ imageSubVals);
+ String width = avm.getValueFromSubValOrArg(imageAv, Arg.WIDTH,
+ imageSubVals);
+ String height = avm.getValueFromSubValOrArg(imageAv, Arg.HEIGHT,
+ imageSubVals);
BitmapImageSizing userBis = ImageMaker
.parseScaleWidthHeightStrings(scale, width, height);
- type = ArgParser.getValueFromSubValOrArg(avm, av, Arg.TYPE, subVal);
+ type = avm.getValueFromSubValOrArg(imageAv, Arg.TYPE, imageSubVals);
if (type == null && fileName != null)
{
for (String ext : new String[] { "svg", "png", "html", "eps" })
Cache.setPropsAreReadOnly(true);
Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
- Console.info("Writing " + file);
- try {
- switch (type)
- {
-
- case "svg":
- Console.debug("Outputting type '" + type + "' to " + fileName);
- af.createSVG(file, renderer);
- break;
+ String imageColour = avm.getValueFromSubValOrArg(imageAv,
+ Arg.IMAGECOLOUR, imageSubVals);
+ ColourSchemeI originalColourScheme = this.getColourScheme(af);
+ this.colourAlignFrame(af, imageColour);
- case "png":
- Console.debug("Outputting type '" + type + "' to " + fileName);
- af.createPNG(file, null, userBis);
- break;
+ Console.info("Writing " + file);
- case "html":
- Console.debug("Outputting type '" + type + "' to " + fileName);
- HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
- htmlSVG.exportHTML(fileName, renderer);
- break;
+ boolean success = checksBeforeWritingToFile(avm, imageSubVals,
+ false, fileName, "image", isError);
+ if (!success)
+ {
+ continue;
+ }
- case "biojs":
- Console.debug("Creating BioJS MSA Viwer HTML file: " + fileName);
- try
- {
- BioJsHTMLOutput.refreshVersionInfo(
- BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
- } catch (URISyntaxException e)
+ try
+ {
+ switch (type)
{
- e.printStackTrace();
- }
- BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
- bjs.exportHTML(fileName);
- break;
- case "eps":
- Console.debug("Creating EPS file: " + fileName);
- af.createEPS(file, name);
- break;
-
- case "imagemap":
- Console.debug("Creating ImageMap file: " + fileName);
- af.createImageMap(file, name);
- break;
-
- default:
- Console.warn(Arg.IMAGE.argString() + " type '" + type
- + "' not known. Ignoring");
- break;
- }
- } catch (Exception ioex) {
- Console.warn("Unexpected error during export",ioex);
+ case "svg":
+ Console.debug("Outputting type '" + type + "' to " + fileName);
+ af.createSVG(file, renderer);
+ break;
+
+ case "png":
+ Console.debug("Outputting type '" + type + "' to " + fileName);
+ af.createPNG(file, null, userBis);
+ break;
+
+ case "html":
+ Console.debug("Outputting type '" + type + "' to " + fileName);
+ HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
+ htmlSVG.exportHTML(fileName, renderer);
+ break;
+
+ case "biojs":
+ Console.debug(
+ "Outputting BioJS MSA Viwer HTML file: " + fileName);
+ try
+ {
+ BioJsHTMLOutput.refreshVersionInfo(
+ BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
+ } catch (URISyntaxException e)
+ {
+ e.printStackTrace();
+ }
+ BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
+ bjs.exportHTML(fileName);
+ break;
+
+ case "eps":
+ Console.debug("Outputting EPS file: " + fileName);
+ af.createEPS(file, renderer);
+ break;
+
+ case "imagemap":
+ Console.debug("Outputting ImageMap file: " + fileName);
+ af.createImageMap(file, name);
+ break;
+
+ default:
+ addWarn(Arg.IMAGE.argString() + " type '" + type
+ + "' not known. Ignoring");
+ break;
+ }
+ } catch (Exception ioex)
+ {
+ addError("Unexpected error during export to '" + fileName + "'",
+ ioex);
+ isError = true;
}
+
+ this.colourAlignFrame(af, originalColourScheme);
}
}
- return true;
+ return !isError;
}
protected boolean processOutput(String id)
if (af == null)
{
- Console.warn("Did not have an alignment window for id=" + id);
+ addWarn("Did not have an alignment window for id=" + id);
return false;
}
+ Boolean isError = Boolean.valueOf(false);
+
if (avm.containsArg(Arg.OUTPUT))
{
for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
String val = av.getValue();
SubVals subVals = av.getSubVals();
String fileName = subVals.getContent();
+ boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
File file = new File(fileName);
- boolean overwrite = ArgParser.getFromSubValArgOrPref(avm,
- Arg.OVERWRITE, subVals, null, "OVERWRITE_OUTPUT", false);
- // backups. Use the Arg.BACKUPS or subval "backups" setting first,
- // otherwise if headless assume false, if not headless use the user
- // preference with default true.
- boolean backups = ArgParser.getFromSubValArgOrPref(avm, Arg.BACKUPS,
- subVals, null,
- Platform.isHeadless() ? null : BackupFiles.ENABLED,
- !Platform.isHeadless());
-
- // if backups is not true then --overwrite must be specified
- if (file.exists() && !(overwrite || backups))
- {
- Console.error("Won't overwrite file '" + fileName + "' without "
- + Arg.OVERWRITE.argString() + " or "
- + Arg.BACKUPS.argString() + " set");
- return false;
- }
String name = af.getName();
- String format = ArgParser.getValueFromSubValOrArg(avm, av,
- Arg.FORMAT, subVals);
+ String format = avm.getValueFromSubValOrArg(av, Arg.FORMAT,
+ subVals);
FileFormats ffs = FileFormats.getInstance();
List<String> validFormats = ffs.getWritableFormats(false);
}
if (ff == null)
{
- StringBuilder validSB = new StringBuilder();
- for (String f : validFormats)
- {
- if (validSB.length() > 0)
- validSB.append(", ");
- validSB.append(f);
- FileFormatI tff = ffs.forName(f);
- validSB.append(" (");
- validSB.append(tff.getExtensions());
- validSB.append(")");
- }
-
- Jalview.exit("No valid format specified for "
- + Arg.OUTPUT.argString() + ". Valid formats are "
- + validSB.toString() + ".", 1);
- // this return really shouldn't happen
- return false;
+ if (stdout)
+ {
+ ff = FileFormat.Fasta;
+ }
+ else
+ {
+ StringBuilder validSB = new StringBuilder();
+ for (String f : validFormats)
+ {
+ if (validSB.length() > 0)
+ validSB.append(", ");
+ validSB.append(f);
+ FileFormatI tff = ffs.forName(f);
+ validSB.append(" (");
+ validSB.append(tff.getExtensions());
+ validSB.append(")");
+ }
+
+ addError("No valid format specified for "
+ + Arg.OUTPUT.argString() + ". Valid formats are "
+ + validSB.toString() + ".");
+ continue;
+ }
}
- String savedBackupsPreference = Cache
- .getDefault(BackupFiles.ENABLED, null);
- Console.debug("Setting backups to " + backups);
- Cache.applicationProperties.put(BackupFiles.ENABLED,
- Boolean.toString(backups));
+ boolean success = checksBeforeWritingToFile(avm, subVals, true,
+ fileName, ff.getName(), isError);
+ if (!success)
+ {
+ continue;
+ }
+
+ boolean backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVals,
+ null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
+ !Platform.isHeadless());
Console.info("Writing " + fileName);
- af.saveAlignment(fileName, ff);
- Console.debug("Returning backups to " + savedBackupsPreference);
- if (savedBackupsPreference != null)
- Cache.applicationProperties.put(BackupFiles.ENABLED,
- savedBackupsPreference);
+ af.saveAlignment(fileName, ff, stdout, backups);
if (af.isSaveAlignmentSuccessful())
{
Console.debug("Written alignment '" + name + "' in "
- + ff.getName() + " format to " + file);
+ + ff.getName() + " format to '" + file + "'");
}
else
{
- Console.warn("Error writing file " + file + " in " + ff.getName()
+ addError("Error writing file '" + file + "' in " + ff.getName()
+ " format!");
+ isError = true;
+ continue;
}
}
}
- return true;
+ return !isError;
}
private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
ArgValue av)
{
SubVals subVals = av.getSubVals();
- ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID);
+ ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID, true);
SequenceI seq = null;
if (subVals == null && idAv == null)
return null;
seq = al.getSequenceAt(subVals.getIndex());
}
}
- else if (idAv != null)
+ if (seq == null && idAv != null)
{
seq = al.findName(idAv.getValue());
}
return seq;
}
+
+ public AlignFrame[] getAlignFrames()
+ {
+ AlignFrame[] afs = null;
+ if (afMap != null)
+ {
+ afs = (AlignFrame[]) afMap.values().toArray();
+ }
+
+ return afs;
+ }
+
+ public List<StructureViewer> getStructureViewers()
+ {
+ List<StructureViewer> svs = null;
+ if (svMap != null)
+ {
+ for (List<StructureViewer> svList : svMap.values())
+ {
+ if (svs == null)
+ {
+ svs = new ArrayList<>();
+ }
+ svs.addAll(svList);
+ }
+ }
+ return svs;
+ }
+
+ private void colourAlignFrame(AlignFrame af, String colour)
+ {
+ // use string "none" to remove colour scheme
+ if (colour != null && "" != colour)
+ {
+ ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
+ af.getViewport(), af.getViewport().getAlignment(), colour);
+ if (cs == null && !StringUtils.equalsIgnoreCase(colour, "none"))
+ {
+ addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
+ }
+ else
+ {
+ Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
+ colourAlignFrame(af, cs);
+ }
+ }
+ }
+
+ private void colourAlignFrame(AlignFrame af, ColourSchemeI cs)
+ {
+ // Note that cs == null removes colour scheme from af
+ af.changeColour(cs);
+ }
+
+ private ColourSchemeI getColourScheme(AlignFrame af)
+ {
+ return af.getViewport().getGlobalColourScheme();
+ }
+
+ private void addInfo(String errorMessage)
+ {
+ Console.info(errorMessage);
+ errors.add(errorMessage);
+ }
+
+ private void addWarn(String errorMessage)
+ {
+ Console.warn(errorMessage);
+ errors.add(errorMessage);
+ }
+
+ private void addError(String errorMessage)
+ {
+ addError(errorMessage, null);
+ }
+
+ private void addError(String errorMessage, Exception e)
+ {
+ Console.error(errorMessage, e);
+ errors.add(errorMessage);
+ }
+
+ private boolean checksBeforeWritingToFile(ArgValuesMap avm,
+ SubVals subVal, boolean includeBackups, String filename,
+ String adjective, Boolean isError)
+ {
+ File file = new File(filename);
+
+ boolean overwrite = avm.getFromSubValArgOrPref(Arg.OVERWRITE, subVal,
+ null, "OVERWRITE_OUTPUT", false);
+ boolean stdout = false;
+ boolean backups = false;
+ if (includeBackups)
+ {
+ stdout = ArgParser.STDOUTFILENAME.equals(filename);
+ // backups. Use the Arg.BACKUPS or subval "backups" setting first,
+ // otherwise if headless assume false, if not headless use the user
+ // preference with default true.
+ backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVal, null,
+ Platform.isHeadless() ? null : BackupFiles.ENABLED,
+ !Platform.isHeadless());
+ }
+
+ if (file.exists() && !(overwrite || backups || stdout))
+ {
+ addWarn("Won't overwrite file '" + filename + "' without "
+ + Arg.OVERWRITE.argString()
+ + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
+ + " set");
+ return false;
+ }
+
+ boolean mkdirs = avm.getFromSubValArgOrPref(Arg.MKDIRS, subVal, null,
+ "MKDIRS_OUTPUT", false);
+
+ if (!FileUtils.checkParentDir(file, mkdirs))
+ {
+ addError("Directory '"
+ + FileUtils.getParentDir(file).getAbsolutePath()
+ + "' does not exist for " + adjective + " file '" + filename
+ + "'."
+ + (mkdirs ? "" : " Try using " + Arg.MKDIRS.argString()));
+ isError = true;
+ return false;
+ }
+
+ return true;
+ }
+
+ public List<String> getErrors()
+ {
+ return errors;
+ }
+
+ public String errorsToString()
+ {
+ StringBuilder sb = new StringBuilder();
+ for (String error : errors)
+ {
+ if (sb.length() > 0)
+ sb.append("\n");
+ sb.append("- " + error);
+ }
+ return sb.toString();
+ }
}
*/
package jalview.bin;
+import java.io.PrintStream;
import java.util.Locale;
import jalview.log.JLogger;
}
else
{
- System.out.println(message);
- t.printStackTrace();
+ outPrintln(message);
+ Console.printStackTrace(t);
}
}
}
else
{
- System.out.println(message);
+ outPrintln(message);
}
}
}
else
{
- System.out.println(message);
- t.printStackTrace();
+ outPrintln(message);
+ Console.printStackTrace(t);
}
}
}
else
{
- System.out.println(message);
+ outPrintln(message);
}
}
}
else
{
- System.out.println(message);
- t.printStackTrace();
+ outPrintln(message);
+ Console.printStackTrace(t);
}
}
}
else
{
- System.out.println(message);
+ outPrintln(message);
}
}
}
else
{
- System.out.println(message);
+ outPrintln(message);
}
}
}
else
{
- System.out.println(message);
- t.printStackTrace();
+ outPrintln(message);
+ Console.printStackTrace(t);
}
}
}
else
{
- System.err.println(message);
+ jalview.bin.Console.errPrintln(message);
}
}
}
else
{
- System.err.println(message);
- t.printStackTrace(System.err);
+ jalview.bin.Console.errPrintln(message);
+ Console.printStackTrace(t);
}
}
}
else
{
- System.err.println(message);
+ jalview.bin.Console.errPrintln(message);
}
}
}
else
{
- System.err.println(message);
- t.printStackTrace(System.err);
+ jalview.bin.Console.errPrintln(message);
+ Console.printStackTrace(t);
}
}
{
if (!Jalview.quiet())
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Setting initial log level to " + logLevel.name());
}
Log4j.init(logLevel);
log = JLoggerLog4j.getLogger(Cache.JALVIEW_LOGGER_NAME, logLevel);
} catch (NoClassDefFoundError e)
{
- System.err.println("Could not initialise the logger framework");
- e.printStackTrace();
+ jalview.bin.Console
+ .errPrintln("Could not initialise the logger framework");
+ Console.printStackTrace(e);
}
// Test message
}
}
+ public static void outPrint()
+ {
+ outPrint("");
+ }
+
+ public static void outPrintln()
+ {
+ outPrintln("");
+ }
+
+ public static void outPrint(Object message)
+ {
+ outPrintMessage(message, false, false);
+ }
+
+ public static void outPrint(Object message, boolean forceStdout)
+ {
+ outPrintMessage(message, false, forceStdout);
+ }
+
+ public static void outPrintln(Object message)
+ {
+ outPrintMessage(message, true, false);
+ }
+
+ public static PrintStream outputStream(boolean forceStdout)
+ {
+ // send message to stderr if an output file to stdout is expected
+ if (!forceStdout && Jalview.getInstance() != null
+ && Jalview.getInstance().getBootstrapArgs() != null
+ && Jalview.getInstance().getBootstrapArgs().outputToStdout())
+ {
+ return System.err;
+ }
+ else
+ {
+ return System.out;
+ }
+ }
+
+ public static void outPrintMessage(Object message, boolean newline,
+ boolean forceStdout)
+ {
+ PrintStream ps = outputStream(forceStdout);
+ if (newline)
+ {
+ ps.println(message);
+ }
+ else
+ {
+ ps.print(message);
+ }
+ }
+
+ public static void errPrint()
+ {
+ errPrint("");
+ }
+
+ public static void errPrintln()
+ {
+ errPrintln("");
+ }
+
+ public static void errPrint(Object message)
+ {
+ System.err.print(message);
+ }
+
+ public static void errPrintln(Object message)
+ {
+ System.err.println(message);
+ }
+
+ public static void debugPrintStackTrace(Throwable t)
+ {
+ if (!isDebugEnabled())
+ {
+ return;
+ }
+ // send message to stderr if output to stdout is expected
+ printStackTrace(t);
+ }
+
+ public static void printStackTrace(Throwable t)
+ {
+ // send message to stderr if output to stdout is expected
+ t.printStackTrace(System.err);
+ }
+
public final static String LOGGING_TEST_MESSAGE = "Logging to STDERR";
-}
+}
\ No newline at end of file
} catch (NoClassDefFoundError e)
{
// com.sun.management.OperatingSystemMXBean doesn't exist in this JVM
- System.err.println(
+ jalview.bin.Console.errPrintln(
"No com.sun.management.OperatingSystemMXBean: cannot get total physical memory size");
}
*/
package jalview.bin;
-import java.util.Locale;
-
import java.awt.HeadlessException;
+import java.util.Locale;
public class HiDPISetting
{
}
} catch (NumberFormatException e)
{
- System.err.println(setHiDPIScalePropertyName + " property give ("
- + setHiDPIScaleProperty + ") but not parseable as integer");
+ jalview.bin.Console.errPrintln(setHiDPIScalePropertyName
+ + " property give (" + setHiDPIScaleProperty
+ + ") but not parseable as integer");
}
}
if (setHiDPI && setHiDPIScale > 0)
try
{
int existingPropertyVal = Integer.parseInt(existingProperty);
- System.out.println("Existing " + scalePropertyName + " is "
- + existingPropertyVal);
+ jalview.bin.Console.outPrintln("Existing " + scalePropertyName
+ + " is " + existingPropertyVal);
if (existingPropertyVal > 1)
{
setHiDPIScale(existingPropertyVal);
}
} catch (NumberFormatException e)
{
- System.out.println("Could not convert property " + scalePropertyName
- + " vale '" + existingProperty + "' to number");
+ jalview.bin.Console.outPrintln(
+ "Could not convert property " + scalePropertyName
+ + " vale '" + existingProperty + "' to number");
}
}
dpi = screenInfo.getScreenResolution();
} catch (HeadlessException e)
{
- System.err.println("Cannot get screen resolution: " + e.getMessage());
+ if (isLinux)
+ {
+ jalview.bin.Console.errPrintln(
+ "Cannot get screen resolution: " + e.getMessage());
+ }
}
// try and get screen size height and width
mindimension = Math.min(height, width);
} catch (HeadlessException e)
{
- System.err.println(
- "Cannot get screen size height and width:" + e.getMessage());
+ if (isLinux)
+ {
+ jalview.bin.Console
+ .errPrintln("Cannot get screen size height and width:"
+ + e.getMessage());
+ }
}
// attempt at a formula for scaling based on screen dpi and mindimension.
import jalview.ext.so.SequenceOntology;
import jalview.gui.AlignFrame;
import jalview.gui.Desktop;
+import jalview.gui.JvOptionPane;
import jalview.gui.PromptUserConfig;
import jalview.gui.QuitHandler;
import jalview.gui.QuitHandler.QResponse;
public static AlignFrame currentAlignFrame;
- public ArgParser argparser = null;
+ private ArgParser argparser = null;
- public BootstrapArgs bootstrapArgs = null;
+ private BootstrapArgs bootstrapArgs = null;
private boolean QUIET = false;
*
*/
{
- System.out.println("not in js");
+ Console.outPrintln("not in js");
}
// BH - for event debugging in JavaScript (Java mode only)
}.start();
}
- if (!quiet() || bootstrapArgs.contains(Arg.VERSION))
+ if (!quiet() || !bootstrapArgs.outputToStdout()
+ || bootstrapArgs.contains(Arg.VERSION))
{
- System.out.println(
+ Console.outPrintln(
"Java version: " + System.getProperty("java.version"));
- System.out.println("Java home: " + System.getProperty("java.home"));
- System.out.println("Java arch: " + System.getProperty("os.arch") + " "
+ Console.outPrintln("Java home: " + System.getProperty("java.home"));
+ Console.outPrintln("Java arch: " + System.getProperty("os.arch") + " "
+ System.getProperty("os.name") + " "
+ System.getProperty("os.version"));
String val = System.getProperty("sys.install4jVersion");
if (val != null)
{
- System.out.println("Install4j version: " + val);
+ Console.outPrintln("Install4j version: " + val);
}
val = System.getProperty("installer_template_version");
if (val != null)
{
- System.out.println("Install4j template version: " + val);
+ Console.outPrintln("Install4j template version: " + val);
}
val = System.getProperty("launcher_version");
if (val != null)
{
- System.out.println("Launcher version: " + val);
+ Console.outPrintln("Launcher version: " + val);
}
}
// stop now if only after --version
if (bootstrapArgs.contains(Arg.VERSION))
{
- Jalview.exit(null, 0);
+ Jalview.exit(null, ExitCode.OK);
}
// old ArgsParser
error.printStackTrace();
String message = "\nEssential logging libraries not found."
+ "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview";
- Jalview.exit(message, 0);
+ Jalview.exit(message, ExitCode.OK);
}
// register SIGTERM listener
Runtime.getRuntime().addShutdownHook(new Thread()
{
+ @Override
public void run()
{
Console.debug("Running shutdown hook");
Cache.loadProperties(usrPropsFile);
if (usrPropsFile != null)
{
- System.out.println(
+ Console.outPrintln(
"CMD [-props " + usrPropsFile + "] executed successfully!");
testoutput(bootstrapArgs, Arg.PROPS,
"test/jalview/bin/testProps.jvprops", usrPropsFile);
{
List<Map.Entry<Type, String>> helpArgs = bootstrapArgs
.getList(Arg.HELP);
- System.out.println(Arg.usage(helpArgs.stream().map(e -> e.getKey())
+ Console.outPrintln(Arg.usage(helpArgs.stream().map(e -> e.getKey())
.collect(Collectors.toList())));
- Jalview.exit(null, 0);
+ Jalview.exit(null, ExitCode.OK);
}
if (aparser.contains("help") || aparser.contains("h"))
{
* Now using new usage statement.
showUsage();
*/
- System.out.println(Arg.usage());
- Jalview.exit(null, 0);
+ Console.outPrintln(Arg.usage());
+ Jalview.exit(null, ExitCode.OK);
}
// new CLI
try
{
Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
- System.out.println(
+ Console.outPrintln(
"CMD [-jabaws " + jabawsUrl + "] executed successfully!");
testoutput(bootstrapArgs, Arg.JABAWS,
"http://www.compbio.dundee.ac.uk/jabaws", jabawsUrl);
} catch (MalformedURLException e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Invalid jabaws parameter: " + jabawsUrl + " ignored");
}
}
}
else
{
- System.out.println("Executing setprop argument: " + setprop);
+ jalview.bin.Console
+ .errPrintln("Executing setprop argument: " + setprop);
if (Platform.isJS())
{
Cache.setProperty(setprop.substring(0, p),
error.printStackTrace();
String message = "\nEssential logging libraries not found."
+ "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview";
- Jalview.exit(message, 0);
+ Jalview.exit(message, ExitCode.OK);
}
desktop = null;
desktop = new Desktop();
desktop.setInBatchMode(true); // indicate we are starting up
+ mixedCliWarning();
+
try
{
JalviewTaskbar.setTaskbar(this);
}
else
{
- System.out.println("CMD [-nousagestats] executed successfully!");
+ Console.outPrintln("CMD [-nousagestats] executed successfully!");
testoutput(argparser, Arg.NOUSAGESTATS);
}
// questionnaire
Console.debug("Starting questionnaire url at " + url);
desktop.checkForQuestionnaire(url);
- System.out.println("CMD questionnaire[-" + url
+ Console.outPrintln("CMD questionnaire[-" + url
+ "] executed successfully!");
}
else
}
else
{
- System.out
- .println("CMD [-noquestionnaire] executed successfully!");
+ Console.outPrintln(
+ "CMD [-noquestionnaire] executed successfully!");
testoutput(argparser, Arg.QUESTIONNAIRE);
}
}
}
}
+ else
+ {
+
+ if (getArgParser().isMixedStyle())
+ {
+ String warning = MessageManager.formatMessage(
+ "warning.using_mixed_command_line_arguments",
+ getArgParser().getMixedExamples());
+ Console.warn(warning);
+ Jalview.exit(
+ "Exiting due to mixed old and new command line arguments",
+ ExitCode.INVALID_ARGUMENT);
+ }
+ if (getArgParser().isOldStyle())
+ {
+ String warning = MessageManager
+ .getString("warning.using_old_command_line_arguments")
+ .replace("\n", " ")
+ + "https://www.jalview.org/help/html/features/commandline.html";
+ Console.warn(warning);
+ }
+
+ }
+
// Run Commands from cli
cmds = new Commands(argparser, headlessArg);
+ cmds.processArgs();
boolean commandsSuccess = cmds.argsWereParsed();
if (commandsSuccess)
else
{
Jalview.exit("Successfully completed commands in headless mode",
- 0);
+ ExitCode.OK);
}
}
Console.info("Successfully completed commands");
{
if (headlessArg)
{
- Jalview.exit("Error when running Commands in headless mode", 1);
+ Jalview.exit("Error when running Commands in headless mode",
+ ExitCode.ERROR_RUNNING_COMMANDS);
}
Console.warn("Error when running commands");
}
if (file == null && desktop == null && !commandsSuccess)
{
- Jalview.exit("No files to open!", 1);
+ Jalview.exit("No files to open!", ExitCode.NO_FILES);
}
long progress = -1;
.getString("status.processing_commandline_args"),
progress = System.currentTimeMillis());
}
- System.out.println("CMD [-open " + file + "] executed successfully!");
+ Console.outPrintln("CMD [-open " + file + "] executed successfully!");
if (!Platform.isJS())
/**
if (headless)
{
Jalview.exit(
- "Can't find file '" + file + "' in headless mode", 1);
+ "Can't find file '" + file + "' in headless mode",
+ ExitCode.FILE_NOT_FOUND);
}
Console.warn("Can't find file'" + file + "'");
}
format);
if (af == null)
{
- System.out.println("error");
+ Console.outPrintln("error");
}
else
{
if (cs != null)
{
- System.out.println(
+ Console.outPrintln(
"CMD [-colour " + data + "] executed successfully!");
}
af.changeColour(cs);
{
af.parseFeaturesFile(data,
AppletFormatAdapter.checkProtocol(data));
- // System.out.println("Added " + data);
- System.out.println(
+ // Console.outPrintln("Added " + data);
+ Console.outPrintln(
"CMD groups[-" + data + "] executed successfully!");
}
data = aparser.getValue("features", true);
{
af.parseFeaturesFile(data,
AppletFormatAdapter.checkProtocol(data));
- // System.out.println("Added " + data);
- System.out.println(
+ // Console.outPrintln("Added " + data);
+ Console.outPrintln(
"CMD [-features " + data + "] executed successfully!");
}
if (data != null)
{
af.loadJalviewDataFile(data, null, null, null);
- // System.out.println("Added " + data);
- System.out.println(
+ // Console.outPrintln("Added " + data);
+ Console.outPrintln(
"CMD [-annotations " + data + "] executed successfully!");
}
// set or clear the sortbytree flag.
af.getViewport().setSortByTree(true);
if (af.getViewport().getSortByTree())
{
- System.out.println("CMD [-sortbytree] executed successfully!");
+ Console.outPrintln("CMD [-sortbytree] executed successfully!");
}
}
if (aparser.contains("no-annotation"))
af.getViewport().setShowAnnotation(false);
if (!af.getViewport().isShowAnnotation())
{
- System.out.println("CMD no-annotation executed successfully!");
+ Console.outPrintln("CMD no-annotation executed successfully!");
}
}
if (aparser.contains("nosortbytree"))
af.getViewport().setSortByTree(false);
if (!af.getViewport().getSortByTree())
{
- System.out
- .println("CMD [-nosortbytree] executed successfully!");
+ Console.outPrintln(
+ "CMD [-nosortbytree] executed successfully!");
}
}
data = aparser.getValue("tree", true);
{
try
{
- System.out.println(
+ Console.outPrintln(
"CMD [-tree " + data + "] executed successfully!");
NewickFile nf = new NewickFile(data,
AppletFormatAdapter.checkProtocol(data));
.setCurrentTree(af.showNewickTree(nf, data).getTree());
} catch (IOException ex)
{
- System.err.println("Couldn't add tree " + data);
+ jalview.bin.Console.errPrintln("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);
+ Console.outPrintln("Executing script " + groovyscript);
executeGroovyScript(groovyscript, af);
- System.out.println("CMD groovy[" + groovyscript
+ Console.outPrintln("CMD groovy[" + groovyscript
+ "] executed successfully!");
groovyscript = null;
}
if (outputFormat.equalsIgnoreCase("png"))
{
- System.out.println("Creating PNG image: " + file);
+ Console.outPrintln("Creating PNG image: " + file);
af.createPNG(new File(file));
imageName = (new File(file)).getName();
continue;
}
else if (outputFormat.equalsIgnoreCase("svg"))
{
- System.out.println("Creating SVG image: " + file);
+ Console.outPrintln("Creating SVG image: " + file);
File imageFile = new File(file);
imageName = imageFile.getName();
af.createSVG(imageFile);
imageName = imageFile.getName();
HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
- System.out.println("Creating HTML image: " + file);
+ Console.outPrintln("Creating HTML image: " + file);
htmlSVG.exportHTML(file);
continue;
}
{
if (file == null)
{
- System.err.println("The output html file must not be null");
+ jalview.bin.Console.errPrintln(
+ "The output html file must not be null");
return;
}
try
e.printStackTrace();
}
BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
- System.out.println(
+ Console.outPrintln(
"Creating BioJS MSA Viwer HTML file: " + file);
bjs.exportHTML(file);
continue;
}
else if (outputFormat.equalsIgnoreCase("imgMap"))
{
- System.out.println("Creating image map: " + file);
+ Console.outPrintln("Creating image map: " + file);
af.createImageMap(new File(file), imageName);
continue;
}
else if (outputFormat.equalsIgnoreCase("eps"))
{
File outputFile = new File(file);
- System.out.println(
+ Console.outPrintln(
"Creating EPS file: " + outputFile.getAbsolutePath());
af.createEPS(outputFile);
continue;
outFormat = FileFormats.getInstance().forName(outputFormat);
} catch (Exception formatP)
{
- System.out.println("Couldn't parse " + outFormat
+ Console.outPrintln("Couldn't parse " + outFormat
+ " as a valid Jalview format string.");
}
if (outFormat != null)
{
if (!outFormat.isWritable())
{
- System.out.println(
+ Console.outPrintln(
"This version of Jalview does not support alignment export as "
+ outputFormat);
}
af.saveAlignment(file, outFormat);
if (af.isSaveAlignmentSuccessful())
{
- System.out.println("Written alignment in "
+ Console.outPrintln("Written alignment in "
+ outFormat.getName() + " format to " + file);
}
else
{
- System.out.println("Error writing file " + file + " in "
+ Console.outPrintln("Error writing file " + file + " in "
+ outFormat.getName() + " format!!");
}
}
}
} catch (ImageOutputException ioexc)
{
- System.out.println(
+ Console.outPrintln(
"Unexpected error whilst exporting image to " + file);
ioexc.printStackTrace();
}
while (aparser.getSize() > 0)
{
- System.out.println("Unknown arg: " + aparser.nextValue());
+ Console.outPrintln("Unknown arg: " + aparser.nextValue());
}
}
}
{
if (Cache.groovyJarsPresent())
{
- System.out.println("Executing script " + groovyscript);
+ Console.outPrintln("Executing script " + groovyscript);
executeGroovyScript(groovyscript, startUpAlframe);
}
else
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Sorry. Groovy Support is not available, so ignoring the provided groovy script "
+ groovyscript);
}
}
desktop.setInBatchMode(false);
}
+
+ cliWarning();
}
private static void setLookAndFeel()
UIManager.put("TabbedPane.tabType", "card");
UIManager.put("TabbedPane.showTabSeparators", true);
UIManager.put("TabbedPane.showContentSeparator", true);
- UIManager.put("TabbedPane.tabSeparatorsFullHeight", true);
+ // UIManager.put("TabbedPane.tabSeparatorsFullHeight", true);
UIManager.put("TabbedPane.tabsOverlapBorder", true);
UIManager.put("TabbedPane.hasFullBorder", true);
UIManager.put("TabbedPane.tabLayoutPolicy", "scroll");
/*
private static void showUsage()
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
+ "-nodisplay\tRun Jalview without User Interface.\n"
+ "-props FILE\tUse the given Jalview properties file instead of users default.\n"
*/
PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
"USAGESTATS",
- MessageManager.getString("prompt.plausible_analytics_title"),
- MessageManager.getString("prompt.plausible_analytics"),
+ MessageManager.getString("prompt.analytics_title"),
+ MessageManager.getString("prompt.analytics"),
new Runnable()
{
@Override
} catch (Exception ex)
{
- System.err.println("Failed to read from STDIN into tempfile "
- + ((tfile == null) ? "(tempfile wasn't created)"
- : tfile.toString()));
+ jalview.bin.Console
+ .errPrintln("Failed to read from STDIN into tempfile "
+ + ((tfile == null) ? "(tempfile wasn't created)"
+ : tfile.toString()));
ex.printStackTrace();
return;
}
sfile = tfile.toURI().toURL();
} catch (Exception x)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Unexpected Malformed URL Exception for temporary file created from STDIN: "
+ tfile.toURI());
x.printStackTrace();
tfile = new File(groovyscript);
if (!tfile.exists())
{
- System.err.println("File '" + groovyscript + "' does not exist.");
+ jalview.bin.Console.errPrintln(
+ "File '" + groovyscript + "' does not exist.");
return;
}
if (!tfile.canRead())
{
- System.err.println("File '" + groovyscript + "' cannot be read.");
+ jalview.bin.Console.errPrintln(
+ "File '" + groovyscript + "' cannot be read.");
return;
}
if (tfile.length() < 1)
{
- System.err.println("File '" + groovyscript + "' is empty.");
+ jalview.bin.Console
+ .errPrintln("File '" + groovyscript + "' is empty.");
return;
}
try
sfile = tfile.getAbsoluteFile().toURI().toURL();
} catch (Exception ex)
{
- System.err.println("Failed to create a file URL for "
+ jalview.bin.Console.errPrintln("Failed to create a file URL for "
+ tfile.getAbsoluteFile());
return;
}
}
} catch (Exception e)
{
- System.err.println("Exception Whilst trying to execute file " + sfile
- + " as a groovy script.");
+ jalview.bin.Console
+ .errPrintln("Exception Whilst trying to execute file " + sfile
+ + " as a groovy script.");
e.printStackTrace(System.err);
}
public void quit()
{
// System.exit will run the shutdownHook first
- Jalview.exit("Quitting now. Bye!", 0);
+ Jalview.exit("Quitting now. Bye!", ExitCode.OK);
}
public static AlignFrame getCurrentAlignFrame()
Jalview.currentAlignFrame = currentAlignFrame;
}
- protected Commands getCommands()
+ public Commands getCommands()
{
return cmds;
}
- public static void exit(String message, int exitcode)
+ public static void exit(String message, ExitCode ec)
{
+ int exitcode = ec == ExitCode.OK ? 0 : ec.ordinal() + 1;
if (Console.log == null)
{
// Don't start the logger just to exit!
{
if (exitcode == 0)
{
- System.out.println(message);
+ Console.outPrintln(message);
}
else
{
- System.err.println(message);
+ jalview.bin.Console.errPrintln(message);
}
}
}
}
}
+ public enum ExitCode
+ {
+ // only add new ones to the end of the list (to preserve ordinal values)
+ OK, FILE_NOT_FOUND, FILE_NOT_READABLE, NO_FILES, INVALID_FORMAT,
+ INVALID_ARGUMENT, INVALID_VALUE, MIXED_CLI_ARGUMENTS,
+ ERROR_RUNNING_COMMANDS;
+ }
+
/******************************
*
* TEST OUTPUT METHODS
*
+ * these operate only when Arg.TESTOUTPUT has been passed, and variously check
+ * if an expected value / arg was set and report it to the test framework.
+ *
******************************/
/**
- * method for reporting string values parsed/processed during tests
+ * report string values parsed/processed during tests When the Bootstrap
+ * argument Arg.TESTOUTPUT is present - reports on debug if given s1 is not
+ * null and not equals s2, warns if given argument is not set, and calls
+ * testoutput(true,a,s1,s2) to report processing progress.
*
+ * @param ap
+ * - ArgParser handling parsing
+ * @param a
+ * - Arg currently being processed
+ * @param s1
+ * - expected
+ * @param s2
*/
protected static void testoutput(ArgParser ap, Arg a, String s1,
String s2)
}
/**
- * method for reporting string values parsed/processed during tests
+ * report values passed via bootstrap arguments
+ *
+ * TODO: significant code duplication with testouput(Argparser...) - move it
*/
protected static void testoutput(BootstrapArgs bsa, Arg a, String s1,
}
/**
- * report value set for string values parsed/processed during tests
+ * conditionally (on @param yes) report that expected value s1 was set during
+ * CommandsTest tests
*/
private static void testoutput(boolean yes, Arg a, String s1, String s2)
{
if (yes && ((s1 == null && s2 == null)
|| (s1 != null && s1.equals(s2))))
{
- System.out.println("[TESTOUTPUT] arg " + a.argString() + "='" + s1
+ Console.outPrintln("[TESTOUTPUT] arg " + a.argString() + "='" + s1
+ "' was set");
}
}
{
message = a.argString() + (yes ? " was set" : " was not set");
}
- System.out.println("[TESTOUTPUT] arg " + message);
+ Console.outPrintln("[TESTOUTPUT] arg " + message);
+ }
+
+ public ArgParser getArgParser()
+ {
+ return argparser;
+ }
+
+ public BootstrapArgs getBootstrapArgs()
+ {
+ return bootstrapArgs;
+ }
+
+ public static boolean isBatchMode()
+ {
+ return getInstance() != null && (getInstance().desktop == null
+ || getInstance().desktop.isInBatchMode());
+ }
+
+ /**
+ * Warning about old or mixed command line arguments
+ */
+ private void mixedCliWarning()
+ {
+ Jalview j = Jalview.getInstance();
+ boolean mixedStyle = j.getArgParser() != null
+ && j.getArgParser().isMixedStyle();
+ String title = MessageManager.getString("label.command_line_arguments");
+ if (mixedStyle)
+ {
+ String warning = MessageManager.formatMessage(
+ "warning.using_mixed_command_line_arguments",
+ j.getArgParser().getMixedExamples());
+ String quit = MessageManager.getString("action.quit");
+
+ Desktop.instance.nonBlockingDialog(title, warning, quit,
+ JvOptionPane.WARNING_MESSAGE, false, true);
+
+ Jalview.exit(
+ "Exiting due to mixed old and new command line arguments.",
+ ExitCode.MIXED_CLI_ARGUMENTS);
+ }
}
+
+ private void cliWarning()
+ {
+ Jalview j = Jalview.getInstance();
+ Commands c = j.getCommands();
+ boolean oldStyle = j.getArgParser() != null
+ && j.getArgParser().isOldStyle();
+ String title = MessageManager.getString("label.command_line_arguments");
+ if (oldStyle)
+ {
+ String warning = MessageManager
+ .getString("warning.using_old_command_line_arguments");
+ String url = "<a href=\"https://www.jalview.org/help/html/features/commandline.html\">https://www.jalview.org/help/html/features/commandline.html</a>";
+ if (Desktop.instance != null)
+ {
+ String cont = MessageManager.getString("label.continue");
+
+ Desktop.instance.nonBlockingDialog(32, 2, title, warning, url, cont,
+ JvOptionPane.WARNING_MESSAGE, false, true, true);
+ }
+ }
+ if (j.getCommands() != null && j.getCommands().getErrors().size() > 0)
+ {
+ if (Desktop.instance != null)
+ {
+ String message = MessageManager
+ .getString("warning.the_following_errors");
+ String ok = MessageManager.getString("action.ok");
+ int shortest = 60;
+ List<String> errors = j.getCommands().getErrors();
+ for (int i = 0; i < errors.size(); i++)
+ {
+ shortest = Math.min(shortest, errors.get(i).length());
+ }
+ Desktop.instance.nonBlockingDialog(
+ Math.max(message.length(), Math.min(60, shortest)),
+ Math.min(errors.size(), 20), title, message,
+ j.getCommands().errorsToString(), ok,
+ JvOptionPane.WARNING_MESSAGE, true, false, true);
+ }
+ }
+ }
+
}
{
if (debug)
{
- System.err.println("Selecting region using separator string '"
+ jalview.bin.Console.errPrintln("Selecting region using separator string '"
+ separator + "'");
}
}
from--;
} catch (NumberFormatException ex)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"ERROR: Couldn't parse first integer in range element column selection string '"
+ cl + "' - format is 'from-to'");
return;
to--;
} catch (NumberFormatException ex)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"ERROR: Couldn't parse second integer in range element column selection string '"
+ cl + "' - format is 'from-to'");
return;
}
if (debug)
{
- System.err.println("Range '" + cl + "' deparsed as [" + from
+ jalview.bin.Console.errPrintln("Range '" + cl + "' deparsed as [" + from
+ "," + to + "]");
}
}
else
{
- System.err.println("ERROR: Invalid Range '" + cl
+ jalview.bin.Console.errPrintln("ERROR: Invalid Range '" + cl
+ "' deparsed as [" + from + "," + to + "]");
}
}
}
else
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"ERROR: Couldn't parse integer from point selection element of column selection string '"
+ cl + "'");
return;
csel.addElement(r);
if (debug)
{
- System.err.println("Point selection '" + cl
+ jalview.bin.Console.errPrintln("Point selection '" + cl
+ "' deparsed as [" + r + "]");
}
}
else
{
- System.err.println("ERROR: Invalid Point selection '" + cl
+ jalview.bin.Console.errPrintln("ERROR: Invalid Point selection '" + cl
+ "' deparsed as [" + r + "]");
}
}
listener = listener.trim();
if (listener.length() == 0)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"jalview Javascript error: Ignoring empty function for mouseover listener.");
return;
}
.addStructureViewerListener(mol);
if (debug)
{
- System.err.println("Added a mouseover listener for "
+ jalview.bin.Console.errPrintln("Added a mouseover listener for "
+ ((af == null) ? "All frames"
: "Just views for "
+ af.getAlignViewport().getSequenceSetId()));
- System.err.println("There are now " + javascriptListeners.size()
+ jalview.bin.Console.errPrintln("There are now " + javascriptListeners.size()
+ " listeners in total.");
}
}
listener = listener.trim();
if (listener.length() == 0)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"jalview Javascript error: Ignoring empty function for selection listener.");
return;
}
.addSelectionListener(mol);
if (debug)
{
- System.err.println("Added a selection listener for "
+ jalview.bin.Console.errPrintln("Added a selection listener for "
+ ((af == null) ? "All frames"
: "Just views for "
+ af.getAlignViewport().getSequenceSetId()));
- System.err.println("There are now " + javascriptListeners.size()
+ jalview.bin.Console.errPrintln("There are now " + javascriptListeners.size()
+ " listeners in total.");
}
}
listener = listener.trim();
if (listener.length() == 0)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"jalview Javascript error: Ignoring empty function for selection listener.");
return;
}
.addStructureViewerListener(mol);
if (debug)
{
- System.err.println("Added a javascript structure viewer listener '"
+ jalview.bin.Console.errPrintln("Added a javascript structure viewer listener '"
+ listener + "'");
- System.err.println("There are now " + javascriptListeners.size()
+ jalview.bin.Console.errPrintln("There are now " + javascriptListeners.size()
+ " listeners in total.");
}
}
rprt = debug;
if (debug)
{
- System.err.println("Removed listener '" + listener + "'");
+ jalview.bin.Console.errPrintln("Removed listener '" + listener + "'");
}
}
else
}
if (rprt)
{
- System.err.println("There are now " + javascriptListeners.size()
+ jalview.bin.Console.errPrintln("There are now " + javascriptListeners.size()
+ " listeners in total.");
}
}
@Override
public void stop()
{
- System.err.println("Applet " + getName() + " stop().");
+ jalview.bin.Console.errPrintln("Applet " + getName() + " stop().");
tidyUp();
}
@Override
public void destroy()
{
- System.err.println("Applet " + getName() + " destroy().");
+ jalview.bin.Console.errPrintln("Applet " + getName() + " destroy().");
tidyUp();
}
}
} catch (NumberFormatException e)
{
- System.err.println("Ignoring invalid residue number string '"
+ jalview.bin.Console.errPrintln("Ignoring invalid residue number string '"
+ pdbResNum + "'");
}
} catch (Exception ex)
{
- System.err.println("Couldn't parse integer arguments (topRow='"
+ jalview.bin.Console.errPrintln("Couldn't parse integer arguments (topRow='"
+ topRow + "' and leftHandColumn='" + leftHandColumn
+ "')");
ex.printStackTrace();
} catch (Exception ex)
{
- System.err.println("Couldn't parse integer arguments (topRow='"
+ jalview.bin.Console.errPrintln("Couldn't parse integer arguments (topRow='"
+ topRow + "')");
ex.printStackTrace();
}
} catch (Exception ex)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Couldn't parse integer arguments (leftHandColumn='"
+ leftHandColumn + "')");
ex.printStackTrace();
{
if (debug)
{
- System.err.println("Applet context is '"
+ jalview.bin.Console.errPrintln("Applet context is '"
+ getAppletContext().getClass().toString() + "'");
}
JSObject scriptObject = JSObject.getWindow(this);
if (debug && scriptObject != null)
{
- System.err.println("Applet has Javascript callback support.");
+ jalview.bin.Console.errPrintln("Applet has Javascript callback support.");
}
} catch (Exception ex)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Warning: No JalviewLite javascript callbacks available.");
if (debug)
{
if (debug)
{
- System.err.println("JalviewLite Version " + getVersion());
- System.err.println("Build Date : " + getBuildDate());
- System.err.println("Installation : " + getInstallation());
+ jalview.bin.Console.errPrintln("JalviewLite Version " + getVersion());
+ jalview.bin.Console.errPrintln("Build Date : " + getBuildDate());
+ jalview.bin.Console.errPrintln("Installation : " + getInstallation());
}
String externalsviewer = getParameter("externalstructureviewer");
if (externalsviewer != null)
separator = sep;
if (debug)
{
- System.err.println("Separator set to '" + separator + "'");
+ jalview.bin.Console.errPrintln("Separator set to '" + separator + "'");
}
}
else
{
if (tries > 0)
{
- System.err.println("LiveConnect request thread going to sleep.");
+ jalview.bin.Console.errPrintln("LiveConnect request thread going to sleep.");
}
try
{
;
if (tries++ > 0)
{
- System.err.println("LiveConnect request thread woken up.");
+ jalview.bin.Console.errPrintln("LiveConnect request thread woken up.");
}
try
{
}
} catch (Exception jsex)
{
- System.err.println("Attempt " + tries
+ jalview.bin.Console.errPrintln("Attempt " + tries
+ " to access LiveConnect javascript failed.");
}
}
"Calling oninit callback '" + initjscallback + "'.");
} catch (Exception e)
{
- System.err.println("Exception when executing _oninit callback '"
+ jalview.bin.Console.errPrintln("Exception when executing _oninit callback '"
+ initjscallback + "'.");
e.printStackTrace();
}
}
else
{
- System.err.println("Not executing _oninit callback '"
+ jalview.bin.Console.errPrintln("Not executing _oninit callback '"
+ initjscallback + "' - no scripting allowed.");
}
}
((AlignFrame) frame).viewport.applet.currentAlignFrame = (AlignFrame) frame;
if (debug)
{
- System.err.println("Activated window " + frame);
+ jalview.bin.Console.errPrintln("Activated window " + frame);
}
}
// be good.
*
* public void windowDeactivated(WindowEvent e) { if (currentAlignFrame ==
* frame) { currentAlignFrame = null; if (debug) {
- * System.err.println("Deactivated window "+frame); } }
+ * jalview.bin.Console.errPrintln("Deactivated window "+frame); } }
* super.windowDeactivated(e); }
*/
});
}
if (!jmolAvailable)
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Jmol not available - Using mc_view for structures");
}
} catch (java.lang.ClassNotFoundException ex)
jmolAvailable = false;
if (debug)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Skipping Jmol check. Will use mc_view (probably)");
}
}
{
if (JalviewLite.debug)
{
- System.err.println(msg);
+ jalview.bin.Console.errPrintln(msg);
}
}
{
if (debug)
{
- System.err.println("Prepended document base '" + documentBase
+ jalview.bin.Console.errPrintln("Prepended document base '" + documentBase
+ "' to make: '" + withDocBase + "'");
}
protocol = DataSourceType.URL;
protocol = DataSourceType.URL;
if (debug)
{
- System.err.println("Prepended codebase '" + codeBase
+ jalview.bin.Console.errPrintln("Prepended codebase '" + codeBase
+ "' to make: '" + withCodeBase + "'");
}
return withCodeBase;
+ " as "
+ (al1.isNucleotide() ? "protein product" : "cDNA")
+ " for " + af.getTitle();
- System.err.println(msg);
+ jalview.bin.Console.errPrintln(msg);
}
}
dbgMsg(">>>Dump finished.");
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Exception when trying to dump the content of the file parameter.");
e.printStackTrace();
}
{
// this may not really be a problem but we give a warning
// anyway
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
+ i + ")");
}
}
else
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Annotations were not added from annotation file '"
+ param + "'");
}
{
if (debug)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Attempting to load T-COFFEE score file from the scoreFile parameter");
}
result = alignFrame.loadScoreFile(sScoreFile);
if (!result)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Failed to parse T-COFFEE parameter as a valid score file ('"
+ sScoreFile + "')");
}
boolean rtn = (getClass().getResourceAsStream("/" + f) != null);
if (debug)
{
- System.err.println("Resource '" + f + "' was "
+ jalview.bin.Console.errPrintln("Resource '" + f + "' was "
+ (rtn ? "" : "not ") + "located by classloader.");
}
return rtn;
} catch (Exception ex)
{
- System.out.println("Exception checking resources: " + f + " " + ex);
+ jalview.bin.Console.outPrintln("Exception checking resources: " + f + " " + ex);
return false;
}
}
{
return initialAlignFrame;
}
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
return null;
}
jv.removeAllElements();
if (debug)
{
- System.err.println("Array from '" + separator
+ jalview.bin.Console.errPrintln("Array from '" + separator
+ "' separated List:\n" + v.length);
for (int i = 0; i < v.length; i++)
{
- System.err.println("item " + i + " '" + v[i] + "'");
+ jalview.bin.Console.errPrintln("item " + i + " '" + v[i] + "'");
}
}
return v;
}
if (debug)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Empty Array from '" + separator + "' separated List");
}
return null;
{
System.err
.println("Returning '" + separator + "' separated List:\n");
- System.err.println(v);
+ jalview.bin.Console.errPrintln(v);
}
return v.toString();
}
if (debug)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Returning empty '" + separator + "' separated List\n");
}
return "" + separator;
this.separator = separator;
if (debug)
{
- System.err.println("Default Separator now: '" + separator + "'");
+ jalview.bin.Console.errPrintln("Default Separator now: '" + separator + "'");
}
}
Color col = ColorUtils.parseColourString(colprop);
if (col == null)
{
- System.err.println("Couldn't parse '" + colprop + "' as a colour for "
+ jalview.bin.Console.errPrintln("Couldn't parse '" + colprop + "' as a colour for "
+ colparam);
}
return (col == null) ? defcolour : col;
}
if (debug)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"resolveUrlForLocalOrAbsolute returning " + resolvedPath);
}
return resolvedPath;
: getDocumentBase());
if (debug)
{
- System.err.println("Show url (prepended " + prepend
+ jalview.bin.Console.errPrintln("Show url (prepended " + prepend
+ " - toggle resolvetocodebase if code/docbase resolution is wrong): "
+ url);
}
{
if (debug)
{
- System.err.println("Show url: " + url);
+ jalview.bin.Console.errPrintln("Show url: " + url);
}
}
if (url.indexOf("javascript:") == 0)
DataSourceType protocol = null;
try
{
- System.out.println("Loading thread started with:\n>>file\n" + file
+ jalview.bin.Console.outPrintln("Loading thread started with:\n>>file\n" + file
+ ">>endfile");
// This might throw a security exception in certain browsers
// Netscape Communicator for instance.
rtn = true;
is.close();
}
- System.err.println("Resource '" + file + "' was "
+ jalview.bin.Console.errPrintln("Resource '" + file + "' was "
+ (rtn ? "" : "not") + " located by classloader.");
if (rtn)
{
} catch (Exception ex)
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Exception checking resources: " + file + " " + ex);
}
if (file.indexOf("://") > -1)
protocol = DataSourceType.FILE;
}
- System.out.println("Trying to get contents of resource:");
+ jalview.bin.Console.outPrintln("Trying to get contents of resource:");
FileParse fp = new FileParse(file, protocol);
if (fp.isValid())
{
}
else
{
- System.out.println("Resource at " + file
+ jalview.bin.Console.outPrintln("Resource at " + file
+ " cannot be read with protocol==" + protocol);
return;
}
if (format == null)
{
format = new IdentifyFile().identify(file, protocol);
- System.out.println("Format is " + format);
+ jalview.bin.Console.outPrintln("Format is " + format);
}
else
{
- System.out.println("User specified Format is " + format);
+ jalview.bin.Console.outPrintln("User specified Format is " + format);
}
AlignmentI al = null;
try
al = new AppletFormatAdapter().readFile(file, protocol, format);
} catch (java.io.IOException ex)
{
- System.err.println("Failed to open the file.");
+ jalview.bin.Console.errPrintln("Failed to open the file.");
ex.printStackTrace();
}
if (al != null)
{
- System.out.println(new AppletFormatAdapter()
+ jalview.bin.Console.outPrintln(new AppletFormatAdapter()
.formatSequences(FileFormat.Fasta, al, false));
}
} catch (Exception e)
{
- System.err.println("bailing out : Unexpected exception:");
+ jalview.bin.Console.errPrintln("bailing out : Unexpected exception:");
e.printStackTrace();
}
}
}
else
{
- System.out.println("Unable to setIconImage()");
+ Console.outPrintln("Unable to setIconImage()");
}
}
}
{
private final static String startClass = "jalview.bin.Jalview";
- private static boolean checkJVMSymlink(String testBin)
- {
- File testBinFile = new File(testBin);
- if (!testBinFile.exists())
- {
- return false;
- }
- File targetFile = null;
- try
- {
- targetFile = testBinFile.getCanonicalFile();
- } catch (IOException e)
- {
- return false;
- }
- if (targetFile != null && ("java".equals(targetFile.getName())
- || "java.exe".equals(targetFile.getName())))
- {
- return true;
- }
- return false;
- }
+ private final static String headlessProperty = "java.awt.headless";
/**
* main method for jalview.bin.Launcher. This restarts the same JRE's JVM with
{
if (!LaunchUtils.checkJavaVersion())
{
- System.err.println("WARNING - The Java version being used (Java "
- + LaunchUtils.getJavaVersion()
- + ") may lead to problems. This installation of Jalview should be used with Java "
- + LaunchUtils.getJavaCompileVersion() + ".");
- }
- final String appName = ChannelProperties.getProperty("app_name");
- final String javaBinDir = System.getProperty("java.home")
- + File.separator + "bin" + File.separator;
- String javaBin = null;
- if (javaBin == null && checkJVMSymlink(javaBinDir + appName))
- {
- javaBin = javaBinDir + appName;
- }
- if (javaBin == null && checkJVMSymlink(javaBinDir + "Jalview"))
- {
- javaBin = javaBinDir + "Jalview";
- }
- if (javaBin == null)
- {
- javaBin = "java";
- }
-
- List<String> command = new ArrayList<>();
- command.add(javaBin);
-
- String memSetting = null;
-
- boolean isAMac = System.getProperty("os.name").indexOf("Mac") > -1;
-
- for (String jvmArg : ManagementFactory.getRuntimeMXBean()
- .getInputArguments())
- {
- command.add(jvmArg);
+ jalview.bin.Console
+ .errPrintln("WARNING - The Java version being used (Java "
+ + LaunchUtils.getJavaVersion()
+ + ") may lead to problems. This installation of Jalview should be used with Java "
+ + LaunchUtils.getJavaCompileVersion() + ".");
}
- command.add("-cp");
- command.add(ManagementFactory.getRuntimeMXBean().getClassPath());
String jvmmempc = null;
String jvmmemmax = null;
boolean debug = false;
boolean wait = true;
boolean quiet = false;
+ boolean headless = false;
+ boolean gui = false;
+ boolean stdout = false;
// must set --debug before --launcher...
boolean launcherstop = false;
boolean launcherprint = false;
boolean launcherwait = false;
ArrayList<String> arguments = new ArrayList<>();
+ String previousArg = null;
for (String arg : args)
{
if (arg.equals("--debug"))
{
quiet = true;
}
+ if (arg.equals("--headless"))
+ {
+ headless = true;
+ }
+ if (arg.equals("--gui"))
+ {
+ gui = true;
+ }
+ if (arg.equals("--output=-")
+ || (arg.equals("-") && "--output".equals(previousArg)))
+ {
+ stdout = true;
+ }
if (debug && arg.equals("--launcherprint"))
{
launcherprint = true;
{
wait = false;
}
+ previousArg = arg;
// Don't add the --launcher... args to Jalview launch
if (arg.startsWith("--launcher"))
{
arguments.add(arg);
}
}
+ if (gui)
+ {
+ // --gui takes precedence over --headless
+ headless = false;
+ }
+
+ final String appName = ChannelProperties.getProperty("app_name");
+
+ // if we're using jalview.bin.Launcher we always assume a console is in use
+ final String javaBin = LaunchUtils.findJavaBin(true);
+
+ List<String> command = new ArrayList<>();
+ command.add(javaBin);
+
+ String memSetting = null;
+
+ for (String jvmArg : ManagementFactory.getRuntimeMXBean()
+ .getInputArguments())
+ {
+ command.add(jvmArg);
+ }
+ command.add("-cp");
+ command.add(ManagementFactory.getRuntimeMXBean().getClassPath());
// use saved preferences if no cmdline args
boolean useCustomisedSettings = LaunchUtils
boolean memSet = false;
boolean dockIcon = false;
boolean dockName = false;
+ boolean headlessProp = false;
for (int i = 0; i < command.size(); i++)
{
String arg = command.get(i);
{
dockName = true;
}
+ else if (arg.startsWith("-D" + headlessProperty + "="))
+ {
+ headlessProp = true;
+ }
}
if (!memSet)
}
}
- if (isAMac)
+ if (LaunchUtils.isMac)
{
if (!dockIcon)
{
+ appName);
}
}
+ if (headless && !headlessProp)
+ {
+ System.setProperty(headlessProperty, "true");
+ command.add("-D" + headlessProperty + "=true");
+ }
String scalePropertyArg = HiDPISetting.getScalePropertyArg();
if (scalePropertyArg != null)
{
- sysout(debug, quiet, "Running " + startClass + " with scale setting "
+ syserr(debug, quiet, "Running " + startClass + " with scale setting "
+ scalePropertyArg);
command.add(scalePropertyArg);
}
if ((Boolean.parseBoolean(System.getProperty("launcherprint", "false"))
|| launcherprint))
{
- sysout(debug, quiet,
+ syserr(debug, quiet,
"LAUNCHER COMMAND: " + String.join(" ", builder.command()));
}
- sysout(debug, quiet,
+ syserr(debug, quiet,
"Running " + startClass + " with "
+ (memSetting == null ? "no memory setting"
: ("memory setting " + memSetting)));
if (Boolean.parseBoolean(System.getProperty("launcherstop", "false"))
|| (debug && launcherstop))
{
- sysout(debug, quiet,
+ syserr(debug, quiet,
"System property 'launcherstop' is set and not 'false'. Exiting.");
System.exit(0);
}
Process process = builder.start();
if (wait || launcherwait)
{
- sysout(debug, quiet, "Launching application process");
+ syserr(debug, quiet, "Launching application process");
process.waitFor();
}
else
{
int waitInt = 0;
- sysout(debug, quiet,
+ syserr(debug, quiet,
"Wait time for application process is " + waitInt + "ms");
process.waitFor(waitInt, TimeUnit.MILLISECONDS);
}
- sysout(debug, quiet, "Launcher process ending");
+ syserr(debug, quiet, "Launcher process ending");
} catch (IOException e)
{
if (e.getMessage().toLowerCase(Locale.ROOT).contains("memory"))
{
- System.err.println("Caught a memory exception: " + e.getMessage());
+ jalview.bin.Console
+ .errPrintln("Caught a memory exception: " + e.getMessage());
// Probably the "Cannot allocate memory" error, try without the memory
// setting
ArrayList<String> commandNoMem = new ArrayList<>();
}
final ProcessBuilder builderNoMem = new ProcessBuilder(
commandNoMem);
- System.err.println("Command without memory setting: "
+ jalview.bin.Console.errPrintln("Command without memory setting: "
+ String.join(" ", builderNoMem.command()));
try
{
}
}
- private static void sysout(boolean debug, boolean quiet, String message)
+ private static void syserr(boolean debug, boolean quiet, String message)
{
if (debug && !quiet)
{
- System.out.println("LAUNCHERDEBUG - " + message);
+ jalview.bin.Console.errPrintln("LAUNCHERDEBUG - " + message);
}
}
else
{
// number too big for a Long. Limit to Long.MAX_VALUE
- System.out.println("Memory parsing of '" + memString
+ jalview.bin.Console.outPrintln("Memory parsing of '" + memString
+ "' produces number too big. Limiting to Long.MAX_VALUE="
+ Long.MAX_VALUE);
return Long.MAX_VALUE;
ADJUSTMENT_MESSAGE = reason;
if (!quiet)
{
- System.out.println(reason);
+ jalview.bin.Console.outPrintln(reason);
}
}
// Initialising arguments (BOOTSTRAP)
HELP(Type.HELP, "h", "Display basic help", Opt.UNARY, Opt.BOOTSTRAP,
- Opt.HASTYPE, Opt.MULTI),
+ Opt.HASTYPE, Opt.MULTIVALUE),
/*
* Other --help-type Args will be added by the static block.
*/
Opt.UNARY, Opt.BOOTSTRAP),
HEADLESS(Type.CONFIG,
"Run Jalview in headless mode. No GUI interface will be created and Jalview will quit after all arguments have been processed. "
- + "Headless mode is assumed if an output file is to be generated, this can be overridden with --noheadless or --gui.",
- Opt.BOOLEAN, Opt.BOOTSTRAP),
+ + "Headless mode is assumed if an output file is to be generated, this can be overridden with --gui.",
+ Opt.UNARY, Opt.BOOTSTRAP),
GUI(Type.CONFIG,
"Do not run Jalview in headless mode. This overrides the assumption of headless mode when an output file is to be generated.",
Opt.UNARY, Opt.BOOTSTRAP),
Opt.BOOTSTRAP, Opt.SECRET),
QUIET(Type.CONFIG, "q",
"Stop all output to STDOUT (after the Java Virtual Machine has started). Use ‑‑quiet a second time to stop all output to STDERR.",
- Opt.UNARY, Opt.MULTI, Opt.BOOTSTRAP),
+ Opt.UNARY, Opt.MULTIVALUE, Opt.BOOTSTRAP),
INITSUBSTITUTIONS(Type.CONFIG,
"Set ‑‑substitutions to be initially enabled (or initially disabled).",
true, Opt.BOOLEAN, Opt.BOOTSTRAP, Opt.NOACTION, Opt.SECRET),
P(Type.CONFIG, "Set a Jalview preference value for this session.",
Opt.PREFIXKEV, Opt.PRESERVECASE, Opt.STRING, Opt.BOOTSTRAP,
- Opt.MULTI, Opt.NOACTION, Opt.SECRET), // keep this secret for now.
+ Opt.MULTIVALUE, Opt.NOACTION, Opt.SECRET), // keep this secret for
+ // now.
// Opening an alignment
OPEN(Type.OPENING,
"Opens one or more alignment files or URLs in new alignment windows.",
- Opt.STRING, Opt.LINKED, Opt.INCREMENTDEFAULTCOUNTER, Opt.MULTI,
- Opt.GLOB, Opt.ALLOWSUBSTITUTIONS, Opt.INPUT, Opt.STORED,
- Opt.PRIMARY),
+ Opt.STRING, Opt.LINKED, Opt.INCREMENTDEFAULTCOUNTER,
+ Opt.MULTIVALUE, Opt.GLOB, Opt.ALLOWSUBSTITUTIONS, Opt.INPUT,
+ Opt.STORED, Opt.PRIMARY),
APPEND(Type.OPENING,
"Appends one or more alignment files or URLs to the open alignment window (or opens a new alignment if none already open).",
- Opt.STRING, Opt.LINKED, Opt.MULTI, Opt.GLOB,
+ Opt.STRING, Opt.LINKED, Opt.MULTIVALUE, Opt.GLOB,
Opt.ALLOWSUBSTITUTIONS, Opt.INPUT, Opt.PRIMARY),
TITLE(Type.OPENING,
"Specifies the title for the open alignment window as string.",
- Opt.STRING, Opt.LINKED),
+ Opt.STRING, Opt.LINKED, Opt.ALLOWMULTIID),
COLOUR(Type.OPENING, "color", // being a bit soft on the Americans!
"Applies the colour scheme to the open alignment window. Valid values include:\n"
+ "clustal,\n" + "blosum62,\n" + "pc-identity,\n"
+ "turn-propensity,\n" + "buried-index,\n"
+ "nucleotide,\n" + "nucleotide-ambiguity,\n"
+ "purine-pyrimidine,\n" + "rna-helices,\n"
- + "t-coffee-scores,\n" + "sequence-id.\n"
- +"\n"
+ + "t-coffee-scores,\n" + "sequence-id.\n" + "\n"
+ "Names of user defined colourschemes will also work,\n"
- +"and jalview colourscheme specifications like\n"
- +"--colour=\"D,E=red; K,R,H=0022FF; C,c=yellow\"",
- Opt.STRING, Opt.LINKED, Opt.ALLOWALL),
+ + "and jalview colourscheme specifications like\n"
+ + "--colour=\"D,E=red; K,R,H=0022FF; C,c=yellow\"",
+ Opt.STRING, Opt.LINKED, Opt.ALLOWMULTIID),
FEATURES(Type.OPENING, "Add a feature file or URL to the open alignment.",
- Opt.STRING, Opt.LINKED, Opt.MULTI, Opt.ALLOWSUBSTITUTIONS),
+ Opt.STRING, Opt.LINKED, Opt.MULTIVALUE, Opt.ALLOWSUBSTITUTIONS,
+ Opt.ALLOWMULTIID),
TREE(Type.OPENING, "Add a tree file or URL to the open alignment.",
- Opt.STRING, Opt.LINKED, Opt.MULTI, Opt.ALLOWSUBSTITUTIONS),
+ Opt.STRING, Opt.LINKED, Opt.MULTIVALUE, Opt.ALLOWSUBSTITUTIONS,
+ Opt.ALLOWMULTIID),
SORTBYTREE(Type.OPENING,
"Enforces sorting (or not sorting) the open alignment in the order of an attached phylogenetic tree.",
- true, Opt.LINKED, Opt.BOOLEAN, Opt.ALLOWALL),
+ true, Opt.LINKED, Opt.BOOLEAN, Opt.ALLOWMULTIID),
ANNOTATIONS(Type.OPENING,
"Add an annotations file or URL to the open alignment.",
- Opt.STRING, Opt.LINKED, Opt.MULTI, Opt.ALLOWSUBSTITUTIONS),
+ Opt.STRING, Opt.LINKED, Opt.MULTIVALUE, Opt.ALLOWSUBSTITUTIONS,
+ Opt.ALLOWMULTIID),
SHOWANNOTATIONS(Type.OPENING,
"Enforces showing (or not showing) alignment annotations.",
- Opt.BOOLEAN, Opt.LINKED, Opt.ALLOWALL),
+ Opt.BOOLEAN, Opt.LINKED, Opt.ALLOWMULTIID, Opt.ALLOWMULTIID),
WRAP(Type.OPENING,
"Enforces wrapped (or not wrapped) alignment formatting.",
- Opt.BOOLEAN, Opt.LINKED, Opt.ALLOWALL),
+ Opt.BOOLEAN, Opt.LINKED, Opt.ALLOWMULTIID, Opt.ALLOWMULTIID),
NOSTRUCTURE(Type.OPENING,
"Do not open or process any 3D structure in the ‑‑open or ‑‑append files.",
- Opt.UNARY, Opt.LINKED, Opt.ALLOWALL),
+ Opt.UNARY, Opt.LINKED, Opt.ALLOWMULTIID, Opt.ALLOWMULTIID),
// Adding a 3D structure
STRUCTURE(Type.STRUCTURE,
"Load a structure file or URL associated with a sequence in the open alignment.\n"
+ "The sequence to be associated with can be specified with a following --seqid argument, or the subval modifier seqid=ID can be used. A subval INDEX can also be used to specify the INDEX-th sequence in the open alignment.",
- Opt.STRING, Opt.LINKED, Opt.MULTI, Opt.ALLOWSUBSTITUTIONS,
- Opt.PRIMARY),
+ Opt.STRING, Opt.LINKED, Opt.MULTIVALUE, Opt.ALLOWSUBSTITUTIONS,
+ Opt.PRIMARY, Opt.ALLOWMULTIID),
SEQID(Type.STRUCTURE,
"Specify the sequence name for the preceding --structure to be associated with.",
- Opt.STRING, Opt.LINKED, Opt.MULTI, Opt.ALLOWSUBSTITUTIONS),
+ Opt.STRING, Opt.LINKED, Opt.MULTIVALUE, Opt.ALLOWSUBSTITUTIONS,
+ Opt.ALLOWMULTIID),
PAEMATRIX(Type.STRUCTURE,
"Add a PAE json matrix file to the preceding --structure.",
- Opt.STRING, Opt.LINKED, Opt.MULTI, Opt.ALLOWSUBSTITUTIONS),
+ Opt.STRING, Opt.LINKED, Opt.MULTIVALUE, Opt.ALLOWSUBSTITUTIONS,
+ Opt.ALLOWMULTIID),
TEMPFAC(Type.STRUCTURE,
"Set the type of temperature factor. Possible values are:\n"
+ "default,\n" + "plddt.",
- Opt.STRING, Opt.LINKED),
+ Opt.STRING, Opt.LINKED, Opt.MULTIVALUE, Opt.ALLOWMULTIID),
STRUCTUREVIEWER(Type.STRUCTURE,
"Set the structure viewer to use to open the 3D structure file specified in previous --structure to name. Possible values of name are:\n"
+ "none,\n" + "jmol,\n" + "chimera,\n" + "chimerax,\n"
+ "pymol.",
- Opt.STRING, Opt.LINKED, Opt.MULTI),
+ Opt.STRING, Opt.LINKED, Opt.MULTIVALUE, Opt.ALLOWMULTIID),
NOTEMPFAC(Type.STRUCTURE,
"Do not show the temperature factor annotation for the preceding --structure.",
- Opt.UNARY, Opt.LINKED, Opt.ALLOWALL, Opt.SECRET), // keep this secret
- // until it works!
+ Opt.UNARY, Opt.LINKED, Opt.ALLOWMULTIID, Opt.SECRET), // keep this
+ // secret until
+ // it works!
SHOWSSANNOTATIONS(Type.STRUCTURE, null, Opt.BOOLEAN, Opt.LINKED,
- Opt.ALLOWALL),
+ Opt.ALLOWMULTIID),
// Outputting files
IMAGE(Type.IMAGE,
"Output an image of the open alignment window. Format is specified by the subval modifier, a following --type argument or guessed from the file extension. Valid formats/extensions are:\n"
+ "svg,\n" + "png,\n" + "eps,\n" + "html,\n" + "biojs.",
- Opt.STRING, Opt.LINKED, Opt.ALLOWSUBSTITUTIONS, Opt.ALLOWALL,
- Opt.REQUIREINPUT, Opt.OUTPUTFILE, Opt.PRIMARY),
+ Opt.STRING, Opt.LINKED, Opt.ALLOWSUBSTITUTIONS, Opt.MULTIVALUE,
+ Opt.ALLOWMULTIID, Opt.REQUIREINPUT, Opt.OUTPUTFILE, Opt.PRIMARY),
+ STRUCTUREIMAGE(Type.IMAGE,
+ "Export an image of a 3D structure opened in JMOL", Opt.STRING,
+ Opt.LINKED, Opt.MULTIVALUE, Opt.OUTPUTFILE, Opt.ALLOWMULTIID,
+ Opt.PRIMARY),
TYPE(Type.IMAGE,
- "Set the image format for the preceding --image. Valid values are:\n"
- + "svg,\n" + "png,\n" + "eps,\n" + "html,\n" + "biojs.",
- Opt.STRING, Opt.LINKED, Opt.ALLOWALL),
+ "Set the image format for the preceding " + Arg.IMAGE.argString()
+ + " or " + Arg.STRUCTUREIMAGE.argString()
+ + ". Valid values are:\n" + "svg,\n" + "png,\n" + "eps,\n"
+ + "html,\n" + "biojs.",
+ Opt.STRING, Opt.LINKED, Opt.MULTIVALUE, Opt.ALLOWMULTIID),
TEXTRENDERER(Type.IMAGE,
"Sets whether text in a vector image format (SVG, HTML, EPS) should be rendered as text or vector line-art. Possible values are:\n"
+ "text,\n" + "lineart.",
- Opt.STRING, Opt.LINKED, Opt.ALLOWALL),
+ Opt.STRING, Opt.LINKED, Opt.MULTIVALUE, Opt.ALLOWMULTIID),
SCALE(Type.IMAGE,
"Sets a scaling for bitmap image format (PNG). Should be given as a floating point number. If used in conjunction with --width and --height then the smallest scaling will be used (scale, width and height provide bounds for the image).",
- Opt.STRING, Opt.LINKED, Opt.ALLOWALL),
+ Opt.STRING, Opt.LINKED, Opt.MULTIVALUE, Opt.ALLOWMULTIID),
WIDTH(Type.IMAGE,
"Sets a width for bitmap image format (PNG) with the height maintaining the aspect ratio. Should be given as a positive integer. If used in conjunction with --scale and --height then the smallest scaling will be used (scale, width and height provide bounds for the image).",
- Opt.STRING, Opt.LINKED, Opt.ALLOWALL),
+ Opt.STRING, Opt.LINKED, Opt.MULTIVALUE, Opt.ALLOWMULTIID),
HEIGHT(Type.IMAGE,
"Sets a height for bitmap image format (PNG) with the width maintaining the aspect ratio. Should be given as a positive integer. If used in conjunction with --scale and --width then the smallest scaling will be used (scale, width and height provide bounds for the image).",
- Opt.STRING, Opt.LINKED, Opt.ALLOWALL),
- STRUCTUREIMAGE(Type.STRUCTUREIMAGE,
- "Export an image of a 3D structure opened in JMOL", Opt.STRING,
- Opt.LINKED, Opt.MULTI, Opt.OUTPUTFILE),
- STRUCTUREIMAGETYPE(Type.STRUCTUREIMAGE,
+ Opt.STRING, Opt.LINKED, Opt.MULTIVALUE, Opt.ALLOWMULTIID),
+ IMAGECOLOUR(Type.IMAGE, "imagecolor", // being a bit soft on the Americans!
+ "Applies the colour scheme to the open alignment window for this image, otherwise the value of "
+ + Arg.COLOUR.argString()
+ + " (or none) will apply. Valid values are the same as "
+ + Arg.COLOUR.argString() + ".",
+ Opt.STRING, Opt.LINKED, Opt.MULTIVALUE, Opt.ALLOWMULTIID),
+ BGCOLOUR(Type.IMAGE, "bgcolor", // being a bit soft on the Americans!
+ "Applies a background colour to the structure image. Valid values are named colours known to Java or RRGGBB 6 digit hex-string.",
+ Opt.STRING, Opt.LINKED, Opt.MULTIVALUE, Opt.ALLOWMULTIID),
+ /*
+ STRUCTUREIMAGETYPE(Type.IMAGE,
"Set the structure image format for the preceding --structureimage. Valid values are:\n"
+ "svg,\n" + "png,\n" + "eps,\n" + "html,\n" + "biojs.",
- Opt.STRING, Opt.LINKED, Opt.ALLOWALL),
- STRUCTUREIMAGETEXTRENDERER(Type.STRUCTUREIMAGE,
+ Opt.STRING, Opt.LINKED, Opt.ALLOWMULTIID),
+ STRUCTUREIMAGETEXTRENDERER(Type.IMAGE,
"Sets whether text in a vector structure image format (SVG, EPS) should be rendered as text or vector line-art. Possible values are:\n"
+ "text,\n" + "lineart.",
- Opt.STRING, Opt.LINKED, Opt.ALLOWALL),
- STRUCTUREIMAGESCALE(Type.STRUCTUREIMAGE,
+ Opt.STRING, Opt.LINKED, Opt.ALLOWMULTIID),
+ STRUCTUREIMAGESCALE(Type.IMAGE,
"Sets a scaling for bitmap structure image format (PNG). Should be given as a floating point number. If used in conjunction with --structureimagewidth and --structureimageheight then the smallest scaling will be used (structureimagescale, structureimagewidth and structureimageheight provide bounds for the structure image).",
- Opt.STRING, Opt.LINKED, Opt.ALLOWALL),
- STRUCTUREIMAGEWIDTH(Type.STRUCTUREIMAGE,
+ Opt.STRING, Opt.LINKED, Opt.ALLOWMULTIID),
+ STRUCTUREIMAGEWIDTH(Type.IMAGE,
"Sets a width for bitmap structure image format (PNG) with the height maintaining the aspect ratio. Should be given as a positive integer. If used in conjunction with --structureimagescale and --structureimageheight then the smallest scaling will be used (structureimagescale, structureimagewidth and structureimageheight provide bounds for the structure image).",
- Opt.STRING, Opt.LINKED, Opt.ALLOWALL),
- STRUCTUREIMAGEHEIGHT(Type.STRUCTUREIMAGE,
+ Opt.STRING, Opt.LINKED, Opt.ALLOWMULTIID),
+ STRUCTUREIMAGEHEIGHT(Type.IMAGE,
"Sets a height for bitmap structure image format (PNG) with the width maintaining the aspect ratio. Should be given as a positive integer. If used in conjunction with --structureimagescale and --structureimagewidth then the smallest scaling will be used (structureimagescale, structureimagewidth and structureimageheight provide bounds for the structure image).",
- Opt.STRING, Opt.LINKED, Opt.ALLOWALL),
+ Opt.STRING, Opt.LINKED, Opt.ALLOWMULTIID),
+ */
OUTPUT(Type.OUTPUT,
"Export the open alignment to file filename. The format name is specified by the subval modifier format=name, a following --format name argument or guessed from the file extension. Valid format names (and file extensions) are:\n"
+ "pileup (pileup),\n" + "msf (msf),\n"
+ "clustal (aln),\n" + "phylip (phy),\n"
+ "jalview (jvp, jar).",
- Opt.STRING, Opt.LINKED, Opt.ALLOWSUBSTITUTIONS, Opt.ALLOWALL,
- Opt.REQUIREINPUT, Opt.OUTPUTFILE, Opt.PRIMARY),
+ Opt.STRING, Opt.LINKED, Opt.ALLOWSUBSTITUTIONS, Opt.ALLOWMULTIID,
+ Opt.REQUIREINPUT, Opt.OUTPUTFILE, Opt.STDOUT, Opt.PRIMARY),
FORMAT(Type.OUTPUT,
"Sets the format for the preceding --output file. Valid formats are:\n"
+ "fasta,\n" + "pfam,\n" + "stockholm,\n" + "pir,\n"
+ "blc,\n" + "amsa,\n" + "json,\n" + "pileup,\n"
+ "msf,\n" + "clustal,\n" + "phylip,\n" + "jalview.",
- Opt.STRING, Opt.LINKED, Opt.ALLOWALL),
+ Opt.STRING, Opt.LINKED, Opt.ALLOWMULTIID),
GROOVY(Type.PROCESS,
"Process a groovy script in the file for the open alignment.",
- Opt.STRING, Opt.LINKED, Opt.MULTI, Opt.ALLOWSUBSTITUTIONS,
- Opt.ALLOWALL),
+ Opt.STRING, Opt.LINKED, Opt.MULTIVALUE, Opt.ALLOWSUBSTITUTIONS,
+ Opt.ALLOWMULTIID),
BACKUPS(Type.OUTPUT,
"Enable (or disable) writing backup files when saving an ‑‑output file. This applies to the current open alignment. To apply to all ‑‑output and ‑‑image files, use after ‑‑all.",
- true, Opt.BOOLEAN, Opt.LINKED, Opt.ALLOWALL),
+ true, Opt.BOOLEAN, Opt.LINKED, Opt.ALLOWMULTIID),
OVERWRITE(Type.OUTPUT,
"Enable (or disable) overwriting of output files without backups enabled. This applies to the current open alignment. To apply to all ‑‑output and ‑‑image files, use after ‑‑all.",
- Opt.BOOLEAN, Opt.LINKED, Opt.ALLOWALL),
+ Opt.BOOLEAN, Opt.LINKED, Opt.ALLOWMULTIID),
CLOSE(Type.OPENING,
"Close the current open alignment window. This occurs after other output arguments. This applies to the current open alignment. To apply to all ‑‑output and ‑‑image files, use after ‑‑all.",
- Opt.UNARY, Opt.LINKED, Opt.ALLOWALL),
+ Opt.UNARY, Opt.LINKED, Opt.ALLOWMULTIID),
+ MKDIRS(Type.OUTPUT,
+ "Automatically create directories when outputting a file to a new directory.",
+ Opt.UNARY, Opt.LINKED, Opt.ALLOWMULTIID),
// controlling flow of arguments
NEW(Type.FLOW,
"Move on to a new alignment window. This will ensure --append will start a new alignment window and other linked arguments will apply to the new alignment window.",
- Opt.UNARY, Opt.MULTI, Opt.NOACTION, Opt.INCREMENTDEFAULTCOUNTER),
+ Opt.UNARY, Opt.MULTIVALUE, Opt.NOACTION,
+ Opt.INCREMENTDEFAULTCOUNTER),
SUBSTITUTIONS(Type.FLOW,
"The following argument values allow (or don't allow) subsituting filename parts. This is initially true. Valid substitutions are:\n"
+ "{basename} - the filename-without-extension of the currently --opened file (or first --appended file),\n"
+ "{n} - the value of the index counter (starting at 0).\n"
+ "{++n} - increase and substitute the value of the index counter,\n"
+ "{} - the value of the current alignment window default index.",
- true, Opt.BOOLEAN, Opt.MULTI, Opt.NOACTION),
+ true, Opt.BOOLEAN, Opt.MULTIVALUE, Opt.NOACTION),
ARGFILE(Type.FLOW,
"Open one or more files filename and read, line-by-line, as arguments to Jalview.\n"
+ "Values in an argfile should be given with an equals sign (\"=\") separator with no spaces.\n"
+ "Note that if you use one or more --argfile arguments then all other non-initialising arguments will be ignored.",
- Opt.STRING, Opt.MULTI, Opt.BOOTSTRAP, Opt.GLOB,
+ Opt.STRING, Opt.MULTIVALUE, Opt.BOOTSTRAP, Opt.GLOB,
Opt.ALLOWSUBSTITUTIONS),
NPP(Type.FLOW, "n++",
"Increase the index counter used in argument value substitutions.",
- Opt.UNARY, Opt.MULTI, Opt.NOACTION),
+ Opt.UNARY, Opt.MULTIVALUE, Opt.NOACTION),
ALL(Type.FLOW,
"Apply the following output arguments to all sets of linked arguments.",
- Opt.BOOLEAN, Opt.MULTI, Opt.NOACTION),
+ Opt.BOOLEAN, Opt.MULTIVALUE, Opt.NOACTION),
OPENED(Type.FLOW,
"Apply the following output arguments to all of the last --open'ed set of linked arguments.",
- Opt.BOOLEAN, Opt.MULTI, Opt.NOACTION),
+ Opt.BOOLEAN, Opt.MULTIVALUE, Opt.NOACTION),
QUIT(Type.FLOW,
"After all files have been opened, appended and output, quit Jalview. In ‑‑headless mode this already happens.",
Opt.UNARY),
Opt.UNARY, Opt.SECRET),
ALLSTRUCTURES(Type.FLOW,
"Apply the following 3D structure formatting arguments to all structures within the open alignment.",
- Opt.BOOLEAN, Opt.MULTI, Opt.NOACTION),
+ Opt.BOOLEAN, Opt.MULTIVALUE, Opt.NOACTION),
// secret options
TESTOUTPUT(Type.CONFIG,
"Allow specific stdout information. For testing purposes only.",
Opt.UNARY, Opt.BOOTSTRAP, Opt.SECRET), // do not show this to the user
SETPROP(Type.CONFIG, "Set an individual Java System property.",
- Opt.STRING, Opt.MULTI, Opt.BOOTSTRAP, Opt.SECRET), // not in use yet
+ Opt.STRING, Opt.MULTIVALUE, Opt.BOOTSTRAP, Opt.SECRET), // not in use
+ // yet
NIL(Type.FLOW,
"This argument does nothing on its own, but can be used with linkedIds.",
- Opt.UNARY, Opt.LINKED, Opt.MULTI, Opt.NOACTION, Opt.SECRET),
+ Opt.UNARY, Opt.LINKED, Opt.MULTIVALUE, Opt.NOACTION, Opt.SECRET),
// private options (inserted during arg processing)
SETARGFILE(Type.FLOW,
"Sets the current value of the argfilename. Inserted before argfilecontents.",
- Opt.UNARY, Opt.LINKED, Opt.STRING, Opt.MULTI, Opt.PRIVATE,
+ Opt.UNARY, Opt.LINKED, Opt.STRING, Opt.MULTIVALUE, Opt.PRIVATE,
Opt.NOACTION),
UNSETARGFILE(Type.FLOW,
"Unsets the current value of the argfilename. Inserted after argfile contents.",
- Opt.UNARY, Opt.LINKED, Opt.MULTI, Opt.PRIVATE, Opt.NOACTION),
+ Opt.UNARY, Opt.LINKED, Opt.MULTIVALUE, Opt.PRIVATE, Opt.NOACTION),
// these last two have no purpose in the normal Jalview application but are
// used by jalview.bin.Launcher to set memory settings. They are not used by
* A MULTI Arg can be specified multiple times.
* Multiple values are stored in the ArgValuesMap (along with their positional index) for each linkedId.
*/
- MULTI("can be specified multiple times"),
+ MULTIVALUE("can be specified multiple times"),
/*
* A Linked Arg can be linked to others through a --arg[linkedId] or --arg[linkedId]=value.
* If no linkedId is specified then the current default linkedId will be used.
/*
* An ALLOWALL Arg can use the '*' linkedId to apply to all known linkedIds
*/
- ALLOWALL("can be used with " + ArgParser.DOUBLEDASH + "all"),
+ ALLOWMULTIID("can be used with " + ArgParser.DOUBLEDASH + "all"),
/*
* If an Arg has the INCREMENTDEFAULTCOUNTER option and the default linkedId is used,
* the defaultLinkedIdCounter is incremented *first*.
*/
OUTPUTFILE("output file --headless will be assumed unless --gui used"),
/*
+ * A STDOUT Arg can take an output filename that can be '-' to mean print to STDOUT.
+ */
+ STDOUT("allows the output filename '" + ArgParser.STDOUTFILENAME
+ + "' to mean output to STDOUT"),
+ /*
* A STORED Arg resets and creates a new set of "opened" linkedIds
*/
STORED(null),
STRUCTURE("arguments used to add and format 3D structure data"),
PROCESS("arguments used to process an alignment once opened"),
OUTPUT("arguments used to save data from a processed alignment"),
- IMAGE("arguments used to export an image of an alignment"),
- STRUCTUREIMAGE("arguments used to export an image of an structure"),
+ IMAGE("arguments used to export an image of an alignment or structure"),
+ // IMAGE("arguments used to export an image of an alignment"),
+ // STRUCTUREIMAGE("arguments used to export an image of an structure"),
FLOW("arguments that control processing of the other arguments"), //
ALL("all arguments"), // mostly just a place-holder for --help-all
NONE, // mostly a place-holder for --help
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
-import java.util.Locale;
import java.util.Map;
-import jalview.bin.Cache;
import jalview.bin.Console;
import jalview.bin.Jalview;
+import jalview.bin.Jalview.ExitCode;
import jalview.bin.argparser.Arg.Opt;
import jalview.bin.argparser.Arg.Type;
import jalview.util.FileUtils;
public static final char EQUALS = '=';
+ public static final String STDOUTFILENAME = "-";
+
protected static final String NEGATESTRING = "no";
/**
private static final String LINKEDIDDIRNAME = "{dirname}";
/**
+ * On-the-fly substitution (not made at argument parsing time)! the current
+ * structure filename extension
+ */
+ private static final String STRUCTUREEXTENSION = "{structureextension}";
+
+ /**
+ * On-the-fly substitution (not made at argument parsing time)! the current
+ * structure filename base
+ */
+ private static final String STRUCTUREBASENAME = "{structurebasename}";
+
+ /**
+ * On-the-fly substitution (not made at argument parsing time)! the current
+ * structure filename dir path
+ */
+ private static final String STRUCTUREDIRNAME = "{structuredirname}";
+
+ /**
+ * On-the-fly substitution (not made at argument parsing time)! increment the
+ * on-the-fly counter and substitute the incremented value
+ */
+ private static final String INCREMENTONTHEFLYCOUNTER = "{++m}";
+
+ /**
+ * On-the-fly substitution (not made at argument parsing time)! the current
+ * substitute with the on-the-fly counter
+ */
+ private static final String ONTHEFLYCOUNTER = "{m}";
+
+ /**
+ * the string used for on-the-fly structure filename substitutions
+ */
+ private String currentStructureFilename = null;
+
+ /**
+ * the counter used for on-the-fly {m} substitutions
+ */
+ private int ontheflyCounter = 0;
+
+ /**
* the current argfile
*/
private String argFile = null;
private boolean allLinkedIds = false;
/**
- * flag to say whether the default linkedId is the current default linked id
- * or OPENED linkedIds
- */
- private boolean openedLinkedIds = false;
-
- /**
* flag to say whether the structure arguments should be applied to all
* structures with this linked id
*/
private BootstrapArgs bootstrapArgs = null;
+ private boolean oldArguments = false;
+
+ private boolean mixedArguments = false;
+
+ /**
+ * saved examples of mixed arguments
+ */
+ private String[] mixedExamples = new String[] { null, null };
+
static
{
argMap = new HashMap<>();
public ArgParser(String[] args, boolean initsubstitutions,
BootstrapArgs bsa)
{
- // Make a mutable new ArrayList so that shell globbing parser works.
- // (When shell file globbing is used, there are a sequence of non-Arg
- // arguments (which are the expanded globbed filenames) that need to be
- // consumed by the --append/--argfile/etc Arg which is most easily done by
- // removing these filenames from the list one at a time. This can't be done
- // with an ArrayList made with only Arrays.asList(String[] args). )
+ /*
+ * Make a mutable new ArrayList so that shell globbing parser works.
+ * (When shell file globbing is used, there are a sequence of non-Arg
+ * arguments (which are the expanded globbed filenames) that need to be
+ * consumed by the --append/--argfile/etc Arg which is most easily done
+ * by removing these filenames from the list one at a time. This can't be
+ * done with an ArrayList made with only Arrays.asList(String[] args) as
+ * that is not mutable. )
+ */
this(new ArrayList<>(Arrays.asList(args)), initsubstitutions, false,
bsa);
}
if (arg.startsWith(DOUBLEDASH))
{
dd = true;
- break;
+ if (mixedExamples[1] == null)
+ {
+ mixedExamples[1] = arg;
+ }
}
- else if (arg.startsWith("-") || arg.equals("open"))
+ else if ((arg.startsWith("-") && !arg.equals(STDOUTFILENAME))
+ || arg.equals("open"))
{
d = true;
+ if (mixedExamples[0] == null)
+ {
+ mixedExamples[0] = arg;
+ }
}
}
- if (d && !dd)
+ if (d)
+ {
+ if (dd)
+ {
+ mixedArguments = true;
+ }
+ else
+ {
+ oldArguments = true;
+ }
+ }
+
+ if (oldArguments || mixedArguments)
{
// leave it to the old style -- parse an empty list
parse(new ArrayList<String>(), false, false);
return;
}
+
if (bsa != null)
this.bootstrapArgs = bsa;
else
boolean allowPrivate)
{
this.substitutions = initsubstitutions;
- boolean openEachInitialFilenames = true;
- for (int i = 0; i < args.size(); i++)
- {
- String arg = args.get(i);
- // If the first arguments do not start with "--" or "-" or is not "open"
- // and` is a filename that exists it is probably a file/list of files to
- // open so we fake an Arg.OPEN argument and when adding files only add the
- // single arg[i] and increment the defaultLinkedIdCounter so that each of
- // these files is opened separately.
- if (openEachInitialFilenames && !arg.startsWith(DOUBLEDASH)
- && !arg.startsWith("-") && !arg.equals("open")
- && (new File(arg).exists()
- || HttpUtils.startsWithHttpOrHttps(arg)))
- {
- arg = Arg.OPEN.argString();
- }
- else
+ /*
+ * If the first argument does not start with "--" or "-" or is not "open",
+ * and is a filename that exists or a URL, it is probably a file/list of
+ * files to open so we insert an Arg.OPEN argument before it. This will
+ * mean the list of files at the start of the arguments are all opened
+ * separately.
+ */
+ if (args.size() > 0)
+ {
+ String arg0 = args.get(0);
+ if (arg0 != null
+ && (!arg0.startsWith(DOUBLEDASH) && !arg0.startsWith("-")
+ && !arg0.equals("open") && (new File(arg0).exists()
+ || HttpUtils.startsWithHttpOrHttps(arg0))))
{
- openEachInitialFilenames = false;
+ // insert "--open" at the start
+ args.add(0, Arg.OPEN.argString());
}
+ }
+
+ for (int i = 0; i < args.size(); i++)
+ {
+ String arg = args.get(i);
// look for double-dash, e.g. --arg
if (arg.startsWith(DOUBLEDASH))
{
// arg not found
Console.error("Argument '" + arg + "' not recognised. Exiting.");
- Jalview.exit("Invalid argument used." + System.lineSeparator()
- + "Use" + System.lineSeparator() + "jalview "
- + Arg.HELP.argString() + System.lineSeparator()
- + "for a usage statement.", 13);
+ Jalview.exit(
+ "Invalid argument used." + System.lineSeparator() + "Use"
+ + System.lineSeparator() + "jalview "
+ + Arg.HELP.argString() + System.lineSeparator()
+ + "for a usage statement.",
+ ExitCode.INVALID_ARGUMENT);
continue;
}
if (a.hasOption(Opt.PRIVATE) && !allowPrivate)
{
// There is no "=" so value is next arg or args (possibly shell
// glob-expanded)
- if ((openEachInitialFilenames ? i : i + 1) >= args.size())
+ if (i + 1 >= args.size())
{
// no value to take for arg, which wants a value
Console.error("Argument '" + a.getName()
{
// if this is the first argument with a file list at the start of
// the args we add filenames from index i instead of i+1
- globVals = getShellGlobbedFilenameValues(a, args,
- openEachInitialFilenames ? i : i + 1);
+ globVals = getShellGlobbedFilenameValues(a, args, i + 1);
}
else
{
else if (a == Arg.ALL)
{
allLinkedIds = !negated;
- openedLinkedIds = false;
- }
- else if (a == Arg.OPENED)
- {
- openedLinkedIds = !negated;
- allLinkedIds = false;
}
else if (a == Arg.ALLSTRUCTURES)
{
{
if (linkedId == null)
{
- if (a.hasOption(Opt.OUTPUTFILE) && a.hasOption(Opt.ALLOWALL)
- && val.startsWith(MATCHALLLINKEDIDS))
+ if (a.hasOption(Opt.OUTPUTFILE) && a.hasOption(Opt.ALLOWMULTIID)
+ && val.contains(MATCHALLLINKEDIDS))
{
- // --output=*.ext is shorthand for --all --output {basename}.ext
+ // --output=*.ext is shorthand for --output {basename}.ext
+ // --output=*/*.ext is shorthand for
+ // --output {dirname}/{basename}.ext
// (or --image=*.ext)
- allLinkedIds = true;
- openedLinkedIds = false;
- linkedId = MATCHALLLINKEDIDS;
- val = LINKEDIDDIRNAME + File.separator + LINKEDIDBASENAME
- + val.substring(MATCHALLLINKEDIDS.length());
- }
- else if (a.hasOption(Opt.OUTPUTFILE)
- && a.hasOption(Opt.ALLOWALL)
- && val.startsWith(MATCHOPENEDLINKEDIDS))
- {
- // --output=open*.ext is shorthand for --opened --output
- // {basename}.ext
- // (or --image=open*.ext)
- openedLinkedIds = true;
- allLinkedIds = false;
- linkedId = MATCHOPENEDLINKEDIDS;
- val = LINKEDIDDIRNAME + File.separator + LINKEDIDBASENAME
- + val.substring(MATCHOPENEDLINKEDIDS.length());
+ linkedId = allLinkedIds ? MATCHALLLINKEDIDS
+ : MATCHOPENEDLINKEDIDS;
+ val = FileUtils.convertWildcardsToPath(val, MATCHALLLINKEDIDS,
+ LINKEDIDDIRNAME, LINKEDIDBASENAME);
}
- else if (allLinkedIds && a.hasOption(Opt.ALLOWALL))
+ else if (allLinkedIds && a.hasOption(Opt.ALLOWMULTIID))
{
linkedId = MATCHALLLINKEDIDS;
}
- else if (openedLinkedIds && a.hasOption(Opt.ALLOWALL))
+ else if (a.hasOption(Opt.ALLOWMULTIID)
+ && this.storedLinkedIds != null
+ && this.storedLinkedIds.size() > 0)
{
linkedId = MATCHOPENEDLINKEDIDS;
}
// set allstructures to all non-primary structure options in this linked
// id if --allstructures has been set
- if (allStructures
- && (a.getType() == Type.STRUCTURE
- || a.getType() == Type.STRUCTUREIMAGE)
- && !a.hasOption(Opt.PRIMARY))
+ if (allStructures && (a.getType() == Type.STRUCTURE
+ // || a.getType() == Type.STRUCTUREIMAGE)
+ ) && !a.hasOption(Opt.PRIMARY))
{
if (!subvals.has(Arg.ALLSTRUCTURES.getName()))
// && !subvals.has("structureid"))
// remove the '*' or 'open*' linkedId that should be empty if it was
// created
if ((MATCHALLLINKEDIDS.equals(linkedId)
+ || MATCHOPENEDLINKEDIDS.equals(linkedId))
&& linkedArgs.containsKey(linkedId))
- || (MATCHOPENEDLINKEDIDS.equals(linkedId)
- && linkedArgs.containsKey(linkedId)))
{
linkedArgs.remove(linkedId);
}
public String makeSubstitutions(String val, String linkedId)
{
+ return makeSubstitutions(val, linkedId, false);
+ }
+
+ public String makeSubstitutions(String val, String linkedId,
+ boolean onthefly)
+ {
if (!this.substitutions || val == null)
return val;
rest = val;
}
if (rest.contains(LINKEDIDAUTOCOUNTER))
+ {
rest = rest.replace(LINKEDIDAUTOCOUNTER,
String.valueOf(linkedIdAutoCounter));
+ }
if (rest.contains(INCREMENTLINKEDIDAUTOCOUNTER))
+ {
rest = rest.replace(INCREMENTLINKEDIDAUTOCOUNTER,
String.valueOf(++linkedIdAutoCounter));
+ }
if (rest.contains(DEFAULTLINKEDIDCOUNTER))
+ {
rest = rest.replace(DEFAULTLINKEDIDCOUNTER,
String.valueOf(defaultLinkedIdCounter));
+ }
ArgValuesMap avm = linkedArgs.get(linkedId);
if (avm != null)
{
FileUtils.getDirname(new File(argFile)));
}
}
+ if (onthefly)
+ {
+ if (rest.contains(ONTHEFLYCOUNTER))
+ {
+ rest = rest.replace(ONTHEFLYCOUNTER,
+ String.valueOf(ontheflyCounter));
+ }
+ if (rest.contains(INCREMENTONTHEFLYCOUNTER))
+ {
+ rest = rest.replace(INCREMENTONTHEFLYCOUNTER,
+ String.valueOf(++ontheflyCounter));
+ }
+ if (currentStructureFilename != null)
+ {
+ if (rest.contains(STRUCTUREBASENAME))
+ {
+ rest = rest.replace(STRUCTUREBASENAME, FileUtils
+ .getBasename(new File(currentStructureFilename)));
+ }
+ if (rest.contains(STRUCTUREDIRNAME))
+ {
+ rest = rest.replace(STRUCTUREDIRNAME,
+ FileUtils.getDirname(new File(currentStructureFilename)));
+ }
+ }
+ }
return new StringBuilder(subvals).append(rest).toString();
}
{
String message = Arg.ARGFILE.argString() + EQUALS + "\""
+ argFile.getPath() + "\": File does not exist.";
- Jalview.exit(message, 2);
+ Jalview.exit(message, ExitCode.FILE_NOT_FOUND);
}
try
{
{
String message = Arg.ARGFILE.argString() + "=\"" + argFile.getPath()
+ "\": File could not be read.";
- Jalview.exit(message, 3);
+ Jalview.exit(message, ExitCode.FILE_NOT_READABLE);
}
}
// Third param "true" uses Opt.PRIVATE args --setargile=argfile and
String message = Arg.ARGFILE.argString() + "=\"" + argFile.getPath()
+ "\": File could not be read.";
Console.debug(message, e);
- Jalview.exit(message, 3);
+ Jalview.exit(message, ExitCode.FILE_NOT_READABLE);
}
}
return args;
}
- public static enum Position
- {
- FIRST, BEFORE, AFTER
- }
-
- /**
- * get from following Arg of type a or subval of same name (lowercase)
- */
- public static String getValueFromSubValOrArg(ArgValuesMap avm,
- ArgValue av, Arg a, SubVals sv)
- {
- return getFromSubValArgOrPref(avm, av, a, sv, null, null, null);
- }
-
- /**
- * get from following Arg of type a or subval key or preference pref or
- * default def
- */
- public static String getFromSubValArgOrPref(ArgValuesMap avm, ArgValue av,
- Arg a, SubVals sv, String key, String pref, String def)
- {
- return getFromSubValArgOrPref(avm, a, Position.AFTER, av, sv, key, pref,
- def);
- }
-
- /**
- * get from following(AFTER), first occurence of (FIRST) or previous (BEFORE)
- * Arg of type a or subval key or preference pref or default def
- */
- public static String getFromSubValArgOrPref(ArgValuesMap avm, Arg a,
- Position pos, ArgValue av, SubVals sv, String key, String pref,
- String def)
- {
- return getFromSubValArgOrPrefWithSubstitutions(null, avm, a, pos, av,
- sv, key, pref, def);
- }
-
- public static String getFromSubValArgOrPrefWithSubstitutions(ArgParser ap,
- ArgValuesMap avm, Arg a, Position pos, ArgValue av, SubVals sv,
- String key, String pref, String def)
- {
- if (key == null)
- key = a.getName();
- String value = null;
- if (sv != null && sv.has(key) && sv.get(key) != null)
- {
- value = ap == null ? sv.get(key)
- : sv.getWithSubstitutions(ap, avm.getLinkedId(), key);
- }
- else if (avm != null && avm.containsArg(a))
- {
- if (pos == Position.FIRST && avm.getValue(a) != null)
- value = avm.getValue(a);
- else if (pos == Position.BEFORE
- && avm.getClosestPreviousArgValueOfArg(av, a) != null)
- value = avm.getClosestPreviousArgValueOfArg(av, a).getValue();
- else if (pos == Position.AFTER
- && avm.getClosestNextArgValueOfArg(av, a) != null)
- value = avm.getClosestNextArgValueOfArg(av, a).getValue();
-
- // look for allstructures subval for Type.STRUCTURE*
- Arg arg = av.getArg();
- if (value == null && arg.hasOption(Opt.PRIMARY)
- && arg.getType() == Type.STRUCTURE
- && !a.hasOption(Opt.PRIMARY) && (a.getType() == Type.STRUCTURE
- || a.getType() == Type.STRUCTUREIMAGE))
- {
- ArgValue av2 = avm.getArgValueOfArgWithSubValKey(a,
- Arg.ALLSTRUCTURES.getName());
- if (av2 != null)
- {
- value = av2.getValue();
- }
- }
- }
- if (value == null)
- {
- value = pref != null ? Cache.getDefault(pref, def) : def;
- }
- return value;
- }
-
- public static boolean getBoolFromSubValOrArg(ArgValuesMap avm, Arg a,
- SubVals sv)
- {
- return getFromSubValArgOrPref(avm, a, sv, null, null, false);
- }
-
- public static boolean getFromSubValArgOrPref(ArgValuesMap avm, Arg a,
- SubVals sv, String key, String pref, boolean def)
- {
- return getFromSubValArgOrPref(avm, a, sv, key, pref, def, false);
- }
-
- public static boolean getFromSubValArgOrPref(ArgValuesMap avm, Arg a,
- SubVals sv, String key, String pref, boolean def,
- boolean invertPref)
- {
- if ((key == null && a == null) || (sv == null && a == null))
- return false;
-
- boolean usingArgKey = false;
- if (key == null)
- {
- key = a.getName();
- usingArgKey = true;
- }
-
- String nokey = ArgParser.NEGATESTRING + key;
-
- // look for key or nokey in subvals first (if using Arg check options)
- if (sv != null)
- {
- // check for true boolean
- if (sv.has(key) && sv.get(key) != null)
- {
- if (usingArgKey)
- {
- if (!(a.hasOption(Opt.BOOLEAN) || a.hasOption(Opt.UNARY)))
- {
- Console.debug(
- "Looking for boolean in subval from non-boolean/non-unary Arg "
- + a.getName());
- return false;
- }
- }
- return sv.get(key).toLowerCase(Locale.ROOT).equals("true");
- }
-
- // check for negative boolean (subval "no..." will be "true")
- if (sv.has(nokey) && sv.get(nokey) != null)
- {
- if (usingArgKey)
- {
- if (!(a.hasOption(Opt.BOOLEAN)))
- {
- Console.debug(
- "Looking for negative boolean in subval from non-boolean Arg "
- + a.getName());
- return false;
- }
- }
- return !sv.get(nokey).toLowerCase(Locale.ROOT).equals("true");
- }
- }
-
- // check argvalues
- if (avm != null && avm.containsArg(a))
- return avm.getBoolean(a);
-
- // return preference or default
- boolean prefVal = pref != null ? Cache.getDefault(pref, def) : false;
- return pref != null ? (invertPref ? !prefVal : prefVal) : def;
- }
-
// the following methods look for the "*" linkedId and add the argvalue to all
// linkedId ArgValues if it does.
/**
argIndex, doSubs);
}
- private void addValue(String linkedId, Type type, ArgValues avs, String v,
- int argIndex, boolean doSubs)
- {
- this.argValueOperation(Op.ADDVALUE, linkedId, type, avs, null, v, false,
- argIndex, doSubs);
- }
-
private void setBoolean(String linkedId, Type type, ArgValues avs,
boolean b, int argIndex)
{
Arg a = avs.arg();
List<String> wildcardLinkedIds = null;
- if (a.hasOption(Opt.ALLOWALL))
+ if (a.hasOption(Opt.ALLOWMULTIID))
{
switch (linkedId)
{
// skip incorrectly stored wildcard ids!
if (id == null || MATCHALLLINKEDIDS.equals(id)
|| MATCHOPENEDLINKEDIDS.equals(id))
+ {
continue;
+ }
ArgValuesMap avm = linkedArgs.get(id);
// don't set an output if there isn't an input
if (a.hasOption(Opt.REQUIREINPUT)
return linkedArgs.get(linkedId);
}
+ public boolean isOldStyle()
+ {
+ return oldArguments;
+ }
+
+ public boolean isMixedStyle()
+ {
+ return mixedArguments;
+ }
+
+ public String[] getMixedExamples()
+ {
+ return mixedExamples;
+ }
+
+ public void setStructureFilename(String s)
+ {
+ this.currentStructureFilename = s;
+ }
+
}
\ No newline at end of file
protected void addArgValue(ArgValue av, boolean beingSetByWildcard)
{
// allow a non-wildcard value to overwrite a wildcard set single value
- boolean overwrite = !arg.hasOption(Opt.MULTI) && setByWildcard
+ boolean overwrite = !arg.hasOption(Opt.MULTIVALUE) && setByWildcard
&& !beingSetByWildcard;
- if ((!arg.hasOption(Opt.MULTI) && argValueList.size() > 0)
+ if ((!arg.hasOption(Opt.MULTIVALUE) && argValueList.size() > 0)
&& !overwrite)
return;
if (arg.hasOption(Opt.NODUPLICATEVALUES)
protected ArgValue getArgValue()
{
- if (arg.hasOption(Opt.MULTI))
+ if (arg.hasOption(Opt.MULTIVALUE))
Console.warn("Requesting single value for multi value argument");
return argValueList.size() > 0 ? argValueList.get(0) : null;
}
import java.io.File;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Set;
+import jalview.bin.Cache;
+import jalview.bin.Console;
import jalview.bin.argparser.Arg.Opt;
+import jalview.bin.argparser.Arg.Type;
import jalview.util.FileUtils;
/**
*/
public class ArgValuesMap
{
+ private List<ArgInfo> argInfoList = new ArrayList<>();
+
protected Map<Arg, ArgValues> m;
private String linkedId;
return closestAv;
}
- public ArgValue getClosestNextArgValueOfArg(ArgValue thisAv, Arg a)
+ public ArgValue getClosestNextArgValueOfArg(ArgValue thisAv, Arg a,
+ boolean withinType)
{
// this looks for the *next* arg that *might* be referring back to
// a thisAv. Such an arg would have no subValues (if it does it should
closestAv = av;
}
}
+
+ // check if withinType this closestAv doesn't belong to the next primary arg
+ // of this type
+ if (withinType && closestAv != null)
+ {
+ int nextPrimaryArgOfSameTypeIndex = Integer.MAX_VALUE;
+ for (Arg tmpA : this.getArgKeys())
+ {
+ // interested in Opt.PRIMARY args of the same type
+ if (tmpA.getType() == a.getType() && tmpA.hasOption(Opt.PRIMARY))
+ {
+ for (ArgValue tmpAv : getArgValueList(tmpA))
+ {
+ int tmpArgIndex = tmpAv.getArgIndex();
+ if (tmpArgIndex > thisArgIndex
+ && tmpArgIndex < nextPrimaryArgOfSameTypeIndex)
+ {
+ nextPrimaryArgOfSameTypeIndex = tmpArgIndex;
+ }
+ }
+ }
+ }
+ if (nextPrimaryArgOfSameTypeIndex < closestAv.getArgIndex())
+ {
+ // looks licke closestAv actually belongs to a different primary Arg
+ return null;
+ }
+ }
+
return closestAv;
}
*/
public String getBasename()
{
- return getDirBasenameOrExtension(false, false);
+ return getDirBasenameOrExtension(false, false, false);
}
/*
*/
public String getExtension()
{
- return getDirBasenameOrExtension(false, true);
+ return getDirBasenameOrExtension(false, true, false);
}
/*
*/
public String getDirname()
{
- return getDirBasenameOrExtension(true, false);
+ return getDirBasenameOrExtension(true, false, false);
}
public String getDirBasenameOrExtension(boolean dirname,
- boolean extension)
+ boolean extension, boolean absoluteDirname)
{
String filename = null;
String appendVal = getValue(Arg.APPEND);
}
return false;
}
+
+ /*
+ * ArgInfo is a more straightforward list of arguments and their info
+ */
+
+ public void addArgInfo(Arg arg, String value, SubVals subVals,
+ int argIndex)
+ {
+ argInfoList.add(new ArgInfo(arg, value, subVals, argIndex));
+ }
+
+ public List<ArgInfo> getArgInfoList()
+ {
+ Collections.sort(argInfoList);
+ return argInfoList;
+ }
+
+ /**
+ * get from following Arg of type a or subval of same name (lowercase)
+ */
+ public String getValueFromSubValOrArg(ArgValue av, Arg a, SubVals sv)
+ {
+ return getFromSubValArgOrPref(av, a, sv, null, null, null);
+ }
+
+ /**
+ * get from following Arg of type a or subval key or preference pref or
+ * default def
+ */
+ public String getFromSubValArgOrPref(ArgValue av, Arg a, SubVals sv,
+ String key, String pref, String def)
+ {
+ return getFromSubValArgOrPref(a, ArgValuesMap.Position.AFTER, av, sv,
+ key, pref, def);
+ }
+
+ /**
+ * get from following(AFTER), first occurence of (FIRST) or previous (BEFORE)
+ * Arg of type a or subval key or preference pref or default def
+ */
+ public String getFromSubValArgOrPref(Arg a, ArgValuesMap.Position pos,
+ ArgValue av, SubVals sv, String key, String pref, String def)
+ {
+ return getFromSubValArgOrPrefWithSubstitutions(null, a, pos, av, sv,
+ key, pref, def);
+ }
+
+ public String getFromSubValArgOrPrefWithSubstitutions(ArgParser ap, Arg a,
+ ArgValuesMap.Position pos, ArgValue av, SubVals sv, String key,
+ String pref, String def)
+ {
+ return getFromSubValArgOrPrefWithSubstitutionsWithinType(ap, a, pos, av,
+ sv, key, pref, def, true);
+ }
+
+ public String getFromSubValArgOrPrefWithSubstitutionsWithinType(
+ ArgParser ap, Arg a, ArgValuesMap.Position pos, ArgValue av,
+ SubVals sv, String key, String pref, String def,
+ boolean withinType)
+ {
+ if (key == null)
+ key = a.getName();
+ String value = null;
+ if (sv != null && sv.has(key) && sv.get(key) != null)
+ {
+ value = ap == null ? sv.get(key)
+ : sv.getWithSubstitutions(ap, getLinkedId(), key);
+ }
+ else if (containsArg(a))
+ {
+ if (pos == ArgValuesMap.Position.FIRST && getValue(a) != null)
+ value = getValue(a);
+ else if (pos == ArgValuesMap.Position.BEFORE
+ && getClosestPreviousArgValueOfArg(av, a) != null)
+ value = getClosestPreviousArgValueOfArg(av, a).getValue();
+ else if (pos == ArgValuesMap.Position.AFTER
+ && getClosestNextArgValueOfArg(av, a, withinType) != null)
+ value = getClosestNextArgValueOfArg(av, a, withinType).getValue();
+
+ // look for allstructures subval for Type.STRUCTURE
+ Arg arg = av.getArg();
+ if (value == null && arg.hasOption(Opt.PRIMARY)
+ && arg.getType() == Type.STRUCTURE
+ && !a.hasOption(Opt.PRIMARY) && (a.getType() == Type.STRUCTURE
+ // || a.getType() == Type.STRUCTUREIMAGE))
+ ))
+ {
+ ArgValue av2 = getArgValueOfArgWithSubValKey(a,
+ Arg.ALLSTRUCTURES.getName());
+ if (av2 != null)
+ {
+ value = av2.getValue();
+ }
+ }
+ }
+ if (value == null)
+ {
+ value = pref != null ? Cache.getDefault(pref, def) : def;
+ }
+ return value;
+ }
+
+ public boolean getBoolFromSubValOrArg(Arg a, SubVals sv)
+ {
+ return getFromSubValArgOrPref(a, sv, null, null, false);
+ }
+
+ public boolean getFromSubValArgOrPref(Arg a, SubVals sv, String key,
+ String pref, boolean def)
+ {
+ return getFromSubValArgOrPref(a, sv, key, pref, def, false);
+ }
+
+ public boolean getFromSubValArgOrPref(Arg a, SubVals sv, String key,
+ String pref, boolean def, boolean invertPref)
+ {
+ if ((key == null && a == null) || (sv == null && a == null))
+ return false;
+
+ boolean usingArgKey = false;
+ if (key == null)
+ {
+ key = a.getName();
+ usingArgKey = true;
+ }
+
+ String nokey = ArgParser.NEGATESTRING + key;
+
+ // look for key or nokey in subvals first (if using Arg check options)
+ if (sv != null)
+ {
+ // check for true boolean
+ if (sv.has(key) && sv.get(key) != null)
+ {
+ if (usingArgKey)
+ {
+ if (!(a.hasOption(Opt.BOOLEAN) || a.hasOption(Opt.UNARY)))
+ {
+ Console.debug(
+ "Looking for boolean in subval from non-boolean/non-unary Arg "
+ + a.getName());
+ return false;
+ }
+ }
+ return sv.get(key).toLowerCase(Locale.ROOT).equals("true");
+ }
+
+ // check for negative boolean (subval "no..." will be "true")
+ if (sv.has(nokey) && sv.get(nokey) != null)
+ {
+ if (usingArgKey)
+ {
+ if (!(a.hasOption(Opt.BOOLEAN)))
+ {
+ Console.debug(
+ "Looking for negative boolean in subval from non-boolean Arg "
+ + a.getName());
+ return false;
+ }
+ }
+ return !sv.get(nokey).toLowerCase(Locale.ROOT).equals("true");
+ }
+ }
+
+ // check argvalues
+ if (containsArg(a))
+ return getBoolean(a);
+
+ // return preference or default
+ boolean prefVal = pref != null ? Cache.getDefault(pref, def) : false;
+ return pref != null ? (invertPref ? !prefVal : prefVal) : def;
+ }
+
+ public class ArgInfo implements Comparable<ArgInfo>
+ {
+ private Arg arg;
+
+ private String value;
+
+ private SubVals subVals;
+
+ private int argIndex;
+
+ public ArgInfo(Arg arg, String value, SubVals subVals, int argIndex)
+ {
+ this.arg = arg;
+ this.value = value;
+ this.subVals = subVals;
+ this.argIndex = argIndex;
+ }
+
+ public Arg arg()
+ {
+ return arg;
+ }
+
+ public String value()
+ {
+ return value;
+ }
+
+ public SubVals subVals()
+ {
+ return subVals;
+ }
+
+ public int argIndex()
+ {
+ return argIndex;
+ }
+
+ @Override
+ public int compareTo(ArgInfo ai2)
+ {
+ return Integer.compare(this.argIndex(), ai2.argIndex());
+ }
+ }
+
+ public static enum Position
+ {
+ FIRST, BEFORE, AFTER
+ }
}
private Set<Type> argsTypes = new HashSet<>();
+ private boolean outputToStdout = false;
+
public static BootstrapArgs getBootstrapArgs(String[] args)
{
List<String> argList = new ArrayList<>(Arrays.asList(args));
{
if (argFiles.contains(inArgFile))
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Looped argfiles detected: '" + inArgFile.getPath() + "'");
return;
}
}
}
- if (ArgParser.argMap.containsKey(argName) && val == null)
- {
- val = "true";
- }
-
Arg a = ArgParser.argMap.get(argName);
if (a != null)
if (a == null || !a.hasOption(Opt.BOOTSTRAP))
{
- // not a valid bootstrap arg
+ // not a bootstrap arg
+
+ // make a check for an output going to stdout
+ if (a != null && a.hasOption(Opt.OUTPUTFILE)
+ && a.hasOption(Opt.STDOUT))
+ {
+ if (val == null && i + 1 < args.size())
+ {
+ val = args.get(i + 1);
+ }
+ if (val.startsWith("[") && val.indexOf(']') > 0)
+ {
+ val = val.substring(val.indexOf(']') + 1);
+ }
+
+ if (ArgParser.STDOUTFILENAME.equals(val))
+ {
+ this.outputToStdout = true;
+ }
+ }
+
continue;
}
}
else
{
+ if (val == null)
+ {
+ val = "true";
+ }
+
add(a, type, val);
}
}
private void add(Arg a, Type t, String s)
{
List<Map.Entry<Type, String>> l = getOrCreateList(a);
- if (a.hasOption(Opt.MULTI) || l.size() == 0)
+ if (a.hasOption(Opt.MULTIVALUE) || l.size() == 0)
{
l.add(entry(t, s));
}
private void addAll(Arg a, Type t, List<String> al)
{
List<Map.Entry<Type, String>> l = getOrCreateList(a);
- if (a.hasOption(Opt.MULTI))
+ if (a.hasOption(Opt.MULTIVALUE))
{
for (String s : al)
{
}
else if (this.contains(Arg.HEADLESS))
{
- // --headless, --noheadless specified => use value
+ // --headless has been specified on the command line => headless
isHeadless = this.getBoolean(Arg.HEADLESS);
}
else if (this.argsHaveOption(Opt.OUTPUTFILE))
}
return isHeadless;
}
+
+ public boolean outputToStdout()
+ {
+ return this.outputToStdout;
+ }
}
{
command.seqs[s].insertCharAt(command.position, command.number,
command.gapChar);
- // System.out.println("pos: "+command.position+" number:
+ // jalview.bin.Console.outPrintln("pos: "+command.position+" number:
// "+command.number);
}
//
// for (int s = 0; s < command.seqs.length; s++)
// {
- // System.out.println("pos: "+command.position+" number: "+command.number);
+ // jalview.bin.Console.outPrintln("pos: "+command.position+" number: "+command.number);
// command.seqs[s].insertCharAt(command.position, command.number,'A');
// }
//
}
else
{
- System.err.println("Can't undo edit action " + action);
+ jalview.bin.Console.errPrintln("Can't undo edit action " + action);
// throw new IllegalStateException("Can't undo edit action " +
// action);
}
ds.setSequenceFeatures(dna.getSequenceFeatures());
// dnaSeqs[i] = ds;
ssm.fromSeq = ds;
- System.out.println("Realised mapped sequence " + ds.getName());
+ jalview.bin.Console.outPrintln("Realised mapped sequence " + ds.getName());
}
}
}
invalidrnastruc = -1;
} catch (WUSSParseException px)
{
- // DEBUG System.out.println(px);
+ // DEBUG jalview.bin.Console.outPrintln(px);
invalidrnastruc = px.getProblemPos();
}
if (invalidrnastruc > -1)
scaleColLabel = true;
_markRnaHelices();
}
- // System.out.println("featuregroup " + _rnasecstr[0].getFeatureGroup());
+ // jalview.bin.Console.outPrintln("featuregroup " + _rnasecstr[0].getFeatureGroup());
}
{
/*
- * System.out.println(this.annotation._rnasecstr[x] + " Begin" +
+ * jalview.bin.Console.outPrintln(this.annotation._rnasecstr[x] + " Begin" +
* this.annotation._rnasecstr[x].getBegin());
*/
- // System.out.println(this.annotation._rnasecstr[x].getFeatureGroup());
+ // jalview.bin.Console.outPrintln(this.annotation._rnasecstr[x].getFeatureGroup());
int val = 0;
try
{
char firstChar = 0;
for (int i = 0; i < annotations.length; i++)
{
- // DEBUG System.out.println(i + ": " + annotations[i]);
+ // DEBUG jalview.bin.Console.outPrintln(i + ": " + annotations[i]);
if (annotations[i] == null)
{
continue;
if (annotations[i].secondaryStructure == 'H'
|| annotations[i].secondaryStructure == 'E')
{
- // DEBUG System.out.println( "/H|E/ '" +
+ // DEBUG jalview.bin.Console.outPrintln( "/H|E/ '" +
// annotations[i].secondaryStructure + "'");
hasIcons |= true;
}
else
// Check for RNA secondary structure
{
- // DEBUG System.out.println( "/else/ '" +
+ // DEBUG jalview.bin.Console.outPrintln( "/else/ '" +
// annotations[i].secondaryStructure + "'");
// TODO: 2.8.2 should this ss symbol validation check be a function in
// RNA/ResidueProperties ?
}
}
- // System.out.println("displaychar " + annotations[i].displayCharacter);
+ // jalview.bin.Console.outPrintln("displaychar " + annotations[i].displayCharacter);
if (annotations[i].displayCharacter == null
|| annotations[i].displayCharacter.length() == 0)
public static void testSelectionViews(AlignmentI alignment,
HiddenColumns hidden, SequenceGroup selection)
{
- System.out.println("Testing standard view creation:\n");
+ jalview.bin.Console.outPrintln("Testing standard view creation:\n");
AlignmentView view = null;
try
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"View with no hidden columns, no limit to selection, no groups to be collected:");
view = new AlignmentView(alignment, hidden, selection, false, false,
false);
} catch (Exception e)
{
e.printStackTrace();
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Failed to generate alignment with selection but no groups marked.");
}
try
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"View with no hidden columns, no limit to selection, and all groups to be collected:");
view = new AlignmentView(alignment, hidden, selection, false, false,
true);
} catch (Exception e)
{
e.printStackTrace();
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Failed to generate alignment with selection marked but no groups marked.");
}
try
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"View with no hidden columns, limited to selection and no groups to be collected:");
view = new AlignmentView(alignment, hidden, selection, false, true,
false);
} catch (Exception e)
{
e.printStackTrace();
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Failed to generate alignment with selection restricted but no groups marked.");
}
try
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"View with no hidden columns, limited to selection, and all groups to be collected:");
view = new AlignmentView(alignment, hidden, selection, false, true,
true);
} catch (Exception e)
{
e.printStackTrace();
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Failed to generate alignment with selection restricted and groups marked.");
}
try
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"View *with* hidden columns, no limit to selection, no groups to be collected:");
view = new AlignmentView(alignment, hidden, selection, true, false,
false);
} catch (Exception e)
{
e.printStackTrace();
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Failed to generate alignment with selection but no groups marked.");
}
try
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"View *with* hidden columns, no limit to selection, and all groups to be collected:");
view = new AlignmentView(alignment, hidden, selection, true, false,
true);
} catch (Exception e)
{
e.printStackTrace();
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Failed to generate alignment with selection marked but no groups marked.");
}
try
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"View *with* hidden columns, limited to selection and no groups to be collected:");
view = new AlignmentView(alignment, hidden, selection, true, true,
false);
} catch (Exception e)
{
e.printStackTrace();
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Failed to generate alignment with selection restricted but no groups marked.");
}
try
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"View *with* hidden columns, limited to selection, and all groups to be collected:");
view = new AlignmentView(alignment, hidden, selection, true, true,
true);
} catch (Exception e)
{
e.printStackTrace();
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Failed to generate alignment with selection restricted and groups marked.");
}
if (alignmentIndex < 0 || hiddenSequences[alignmentIndex] != null)
{
- System.out.println("ERROR!!!!!!!!!!!");
+ jalview.bin.Console.outPrintln("ERROR!!!!!!!!!!!");
return;
}
}
else
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
seq.getName() + " has been deleted whilst hidden");
}
}
else
{
// debug
- // System.err.println("Outwith bounds!" + matchStart+">"+end +" or "
+ // jalview.bin.Console.errPrintln("Outwith bounds!" + matchStart+">"+end +" or "
// + matchEnd+"<"+start);
}
}
{
if (name == null)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
name = "";
}
{
if (sf.getType() == null)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"SequenceFeature type may not be null: " + sf.toString());
return false;
}
} catch (java.lang.OutOfMemoryError err)
{
// TODO: catch OOM
- System.out.println("Out of memory loading groups: " + err);
+ jalview.bin.Console.outPrintln("Out of memory loading groups: " + err);
}
return upd;
}
int nextQuotePos = descriptor.indexOf(QUOTE, 1);
if (nextQuotePos == -1)
{
- System.err.println(invalidFormat);
+ jalview.bin.Console.errPrintln(invalidFormat);
return null;
}
firstField = descriptor.substring(1, nextQuotePos);
int nextSpacePos = descriptor.indexOf(SPACE);
if (nextSpacePos == -1)
{
- System.err.println(invalidFormat);
+ jalview.bin.Console.errPrintln(invalidFormat);
return null;
}
firstField = descriptor.substring(0, nextSpacePos);
cond = Condition.fromString(leftToParse);
if (cond == null || cond.needsAPattern())
{
- System.err.println(invalidFormat);
+ jalview.bin.Console.errPrintln(invalidFormat);
return null;
}
}
else
{
// unbalanced quote
- System.err.println(invalidFormat);
+ jalview.bin.Console.errPrintln(invalidFormat);
return null;
}
}
if (spacePos == -1)
{
// trailing junk after a match condition
- System.err.println(invalid);
+ jalview.bin.Console.errPrintln(invalid);
return null;
}
String conjunction = leftToParse.substring(0, spacePos);
else
{
// not an AND or an OR - invalid
- System.err.println(invalid);
+ jalview.bin.Console.errPrintln(invalid);
return null;
}
}
int closePos = leftToParse.indexOf(CLOSE_BRACKET);
if (closePos == -1)
{
- System.err.println(invalid);
+ jalview.bin.Console.errPrintln(invalid);
return null;
}
nextCondition = leftToParse.substring(1, closePos);
FeatureMatcher fm = FeatureMatcher.fromString(nextCondition);
if (fm == null)
{
- System.err.println(invalid);
+ jalview.bin.Console.errPrintln(invalid);
return null;
}
try
} catch (IllegalStateException e)
{
// thrown if OR and AND are mixed
- System.err.println(invalid);
+ jalview.bin.Console.errPrintln(invalid);
return null;
}
SequenceFeature sf = contactFeatureEnds.get(index);
if (!sf.isContactFeature())
{
- System.err.println("Error! non-contact feature type " + sf.getType()
+ jalview.bin.Console.errPrintln("Error! non-contact feature type " + sf.getType()
+ " in contact features list");
index++;
continue;
SequenceFeature sf = contactFeatureStarts.get(index);
if (!sf.isContactFeature())
{
- System.err.println("Error! non-contact feature " + sf.toString()
+ jalview.bin.Console.errPrintln("Error! non-contact feature " + sf.toString()
+ " in contact features list");
index++;
continue;
String type = sf.getType();
if (type == null)
{
- System.err.println("Feature type may not be null: " + sf.toString());
+ jalview.bin.Console.errPrintln("Feature type may not be null: " + sf.toString());
return false;
}
return true;
} catch (NumberFormatException e)
{
- System.err.println("Bad integers in description " + description);
+ jalview.bin.Console.errPrintln("Bad integers in description " + description);
}
}
return false;
ids, -1, MODE_MAP, null);
} catch (IOException | ParseException e)
{
- System.err.println("Error parsing " + identifier + " lookup response "
+ jalview.bin.Console.errPrintln("Error parsing " + identifier + " lookup response "
+ e.getMessage());
return null;
}
return (parseAssemblyMappingResponse(url));
} catch (Throwable t)
{
- System.out.println("Error calling " + url + ": " + t.getMessage());
+ jalview.bin.Console.outPrintln("Error calling " + url + ": " + t.getMessage());
return null;
}
}
return null;
} catch (Throwable t)
{
- System.out.println("Error calling " + url + ": " + t.getMessage());
+ jalview.bin.Console.outPrintln("Error calling " + url + ": " + t.getMessage());
return null;
}
}
String ass = mapped.get("assembly_name").toString();
if (assembly != null && !assembly.equals(ass))
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"EnsemblMap found multiple assemblies - can't resolve");
return null;
}
String chr = mapped.get("seq_region_name").toString();
if (chromosome != null && !chromosome.equals(chr))
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"EnsemblMap found multiple chromosomes - can't resolve");
return null;
}
return pingString != null;
} catch (Throwable t)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Error connecting to " + pingUrl + ": " + t.getMessage());
} finally
{
* note: a GET request for an invalid id returns an error code e.g. 415
* but POST request returns 200 and an empty Fasta response
*/
- System.err.println("Response code " + responseCode);// + " for " + url);
+ jalview.bin.Console.errPrintln("Response code " + responseCode);// + " for " + url);
return null;
}
protected HttpURLConnection tryConnection(URL url, List<String> ids,
int readTimeout) throws IOException, ProtocolException
{
- // System.out.println(System.currentTimeMillis() + " " + url);
+ // jalview.bin.Console.outPrintln(System.currentTimeMillis() + " " + url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int retrySecs = Integer.valueOf(retryDelay);
if (retrySecs > 0 && retrySecs < 10)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Ensembl REST service rate limit exceeded, waiting "
+ retryDelay + " seconds before retrying");
Thread.sleep(1000 * retrySecs);
}
} catch (NumberFormatException | InterruptedException e)
{
- System.err.println("Error handling Retry-After: " + e.getMessage());
+ jalview.bin.Console.errPrintln("Error handling Retry-After: " + e.getMessage());
}
}
}
}
} catch (NumberFormatException e)
{
- System.err.println("Error in REST version: " + e.toString());
+ jalview.bin.Console.errPrintln("Error in REST version: " + e.toString());
}
/*
expected) == 1;
if (laterVersion)
{
- System.err.println(String.format(
+ jalview.bin.Console.errPrintln(String.format(
"EnsemblRestClient expected %s REST version %s but found %s, see %s",
getDbSource(), expected, version, REST_CHANGE_LOG));
}
info.restVersion = version;
} catch (Throwable t)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Error checking Ensembl REST version: " + t.getMessage());
}
}
domainData.get(getDomain()).dataVersion = versions.get(0).toString();
} catch (Throwable e)
{// could be IOException | ParseException e) {
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Error checking Ensembl data version: " + e.getMessage());
}
}
String msg = "Aborting ID retrieval after " + v
+ " chunks. Unexpected problem (" + r.getLocalizedMessage()
+ ")";
- System.err.println(msg);
+ jalview.bin.Console.errPrintln(msg);
r.printStackTrace();
break;
}
}
} catch (IOException e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Error transferring Ensembl features: " + e.getMessage());
}
// Platform.timeCheck("ESP.addfeat done", Platform.TIME_MARK);
String accId = querySeq.getName();
try
{
- System.out.println("Adding protein product for " + accId);
+ jalview.bin.Console.outPrintln("Adding protein product for " + accId);
AlignmentI protein = new EnsemblProtein(getDomain())
.getSequenceRecords(accId);
if (protein == null || protein.getHeight() == 0)
{
- System.out.println("No protein product found for " + accId);
+ jalview.bin.Console.outPrintln("No protein product found for " + accId);
return;
}
SequenceI proteinSeq = protein.getSequenceAt(0);
seq.addDBRef(xrefs.get(i));
}
- // System.out.println("primaries are " + seq.getPrimaryDBRefs().toString());
+ // jalview.bin.Console.outPrintln("primaries are " + seq.getPrimaryDBRefs().toString());
/*
* and add a reference to itself
*/
if (seqs.size() != ids.size())
{
- System.out.println(String.format(
+ jalview.bin.Console.outPrintln(String.format(
"Only retrieved %d sequences for %d query strings",
seqs.size(), ids.size()));
}
result.add(sequence);
} catch (ParseException | IOException e)
{
- System.err.println("Error processing JSON response: " + e.toString());
+ jalview.bin.Console.errPrintln("Error processing JSON response: " + e.toString());
// ignore
}
// Platform.timeCheck("ENS seqproxy2", Platform.TIME_MARK);
if (regions.isEmpty())
{
- System.out.println("Failed to identify target sequence for " + accId
+ jalview.bin.Console.outPrintln("Failed to identify target sequence for " + accId
+ " from genomic features");
return null;
}
boolean result = transferFeatures(sfs, targetSequence, mapping,
accessionId);
- // System.out.println("transferFeatures (" + (sfs.size()) + " --> "
+ // jalview.bin.Console.outPrintln("transferFeatures (" + (sfs.size()) + " --> "
// + targetSequence.getFeatures().getFeatureCount(true) + ") to "
// + targetSequence.getName() + " took "
// + (System.currentTimeMillis() - start) + "ms");
{
if (!isValid() || !refFile.isIndexed())
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Cannot read contig as file is invalid or not indexed");
return null;
}
public void createImage(String file, String type, int quality)
{
- System.out.println("JMOL CREATE IMAGE");
+ jalview.bin.Console.outPrintln("JMOL CREATE IMAGE");
}
@Override
public String createImage(String fileName, String type,
Object textOrBytes, int quality)
{
- System.out.println("JMOL CREATE IMAGE");
+ jalview.bin.Console.outPrintln("JMOL CREATE IMAGE");
return null;
}
@Override
public String eval(String strEval)
{
- // System.out.println(strEval);
+ // jalview.bin.Console.outPrintln(strEval);
// "# 'eval' is implemented only for the applet.";
return null;
}
lastMessage = strInfo;
if (data != null)
{
- System.err.println("Ignoring additional hover info: " + data
+ jalview.bin.Console.errPrintln("Ignoring additional hover info: " + data
+ " (other info: '" + strInfo + "' pos " + atomIndex + ")");
}
mouseOverStructure(atomIndex, strInfo);
*/
if (strData != null)
{
- System.err.println("Ignoring additional pick data string " + strData);
+ jalview.bin.Console.errPrintln("Ignoring additional pick data string " + strData);
}
int chainSeparator = strInfo.indexOf(":");
int p = 0;
(data == null) ? ((String) null) : (String) data[1]);
break;
case ERROR:
- // System.err.println("Ignoring error callback.");
+ // jalview.bin.Console.errPrintln("Ignoring error callback.");
break;
case SYNC:
case RESIZE:
case CLICK:
default:
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Unhandled callback " + type + " " + data[1].toString());
break;
}
} catch (Exception e)
{
- System.err.println("Squashed Jmol callback handler error:");
+ jalview.bin.Console.errPrintln("Squashed Jmol callback handler error:");
e.printStackTrace();
}
}
public void setCallbackFunction(String callbackType,
String callbackFunction)
{
- System.err.println("Ignoring set-callback request to associate "
+ jalview.bin.Console.errPrintln("Ignoring set-callback request to associate "
+ callbackType + " with function " + callbackFunction);
}
String buttonsToShow)
{
- System.err.println("Allocating Jmol Viewer: " + commandOptions);
+ jalview.bin.Console.errPrintln("Allocating Jmol Viewer: " + commandOptions);
if (commandOptions == null)
{
console = createJmolConsole(consolePanel, buttonsToShow);
} catch (Throwable e)
{
- System.err.println("Could not create Jmol application console. "
+ jalview.bin.Console.errPrintln("Could not create Jmol application console. "
+ e.getMessage());
e.printStackTrace();
}
return new StructureCommand(
"load FILES \"" + Platform.escapeBackslashes(file) + "\"");
}
+ @Override
+ public StructureCommandI restoreSession(String filePath)
+ {
+ return new StructureCommand(
+ "restore STATE \"" + Platform.escapeBackslashes(filePath) + "\"");
+ }
/**
* Obsolete method, only referenced from
}
} catch (OutOfMemoryError er)
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"OUT OF MEMORY LOADING TRANSFORMING JMOL MODEL TO JALVIEW MODEL");
throw new IOException(MessageManager
.getString("exception.outofmemory_loading_mmcif_file"));
org.jmol.modelset.Atom prevAtom,
HashMap<String, org.jmol.modelset.Atom> chainTerMap)
{
- // System.out.println("Atom: " + curAtom.getAtomNumber()
+ // jalview.bin.Console.outPrintln("Atom: " + curAtom.getAtomNumber()
// + " Last atom index " + curAtom.group.lastAtomIndex);
if (chainTerMap == null || prevAtom == null)
{
if (sval == null)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"DEVELOPER WARNING: Annotate3d didn't return a '2D' tag in its response. Consider checking output of server. Response was :"
+ val.toString());
boolean getReply)
{
String postBody = getPostRequest(command);
- // System.out.println(postBody);// debug
+ // jalview.bin.Console.outPrintln(postBody);// debug
String rpcUrl = "http://127.0.0.1:" + this.pymolXmlRpcPort;
PrintWriter out = null;
BufferedReader in = null;
}
else if (message.startsWith(MODEL_CHANGED))
{
- System.err.println(message);
+ jalview.bin.Console.errPrintln(message);
processModelChanged(message.substring(MODEL_CHANGED.length()));
}
else
{
- System.err.println("Unexpected chimeraNotification: " + message);
+ jalview.bin.Console.errPrintln("Unexpected chimeraNotification: " + message);
}
}
}
*/
protected void processModelChanged(String message)
{
- // System.out.println(message + " (not implemented in Jalview)");
+ // jalview.bin.Console.outPrintln(message + " (not implemented in Jalview)");
}
/**
startListening(chimeraListener.getUri());
} catch (BindException e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Failed to start Chimera listener: " + e.getMessage());
}
}
private void log(String message)
{
- System.err.println("## Chimera log: " + message);
+ jalview.bin.Console.errPrintln("## Chimera log: " + message);
}
/**
executeCommand(false, null, command);
} catch (IOException e)
{
- System.err.println("Sending commands to Chimera via file failed with "
+ jalview.bin.Console.errPrintln("Sending commands to Chimera via file failed with "
+ e.getMessage());
}
}
int x = 0;
for (FTSDataColumnI field : allFTSDataColumns)
{
- // System.out.println("allFTSDataColumns==" + allFTSDataColumns);
+ // jalview.bin.Console.outPrintln("allFTSDataColumns==" + allFTSDataColumns);
if (field.getName().equalsIgnoreCase("all"))
{
continue;
data[x++] = new Object[] { ftsRestClient
.getAllDefaultDisplayedFTSDataColumns().contains(field),
field.getName(), field.getGroup() };
- // System.out.println(" PUIS " + field.getName() + " ET AUSSI " +
+ // jalview.bin.Console.outPrintln(" PUIS " + field.getName() + " ET AUSSI " +
// field.getGroup() + "X = " + x);
break;
case STRUCTURE_CHOOSER:
} catch (Exception e)
{
e.printStackTrace();
- System.out.println("offending value:" + fieldData);
+ jalview.bin.Console.outPrintln("offending value:" + fieldData);
}
}
}
URI uri = webResource.getURI();
- System.out.println(uri);
+ jalview.bin.Console.outPrintln(uri);
ClientResponse clientResponse = null;
int responseStatus = -1;
// Get the JSON string from the response object or directly from the
Map<String, Object> jsonObj = null;
String responseString = null;
- System.out.println("query >>>>>>> " + pdbRestRequest.toString());
+ jalview.bin.Console.outPrintln("query >>>>>>> " + pdbRestRequest.toString());
if (!isMocked())
{
for (FTSDataColumnI field : diplayFields)
{
- // System.out.println("Field " + field);
+ // jalview.bin.Console.outPrintln("Field " + field);
String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
: pdbJsonDoc.get(field.getCode()).toString();
- // System.out.println("Field Data : " + fieldData);
+ // jalview.bin.Console.outPrintln("Field Data : " + fieldData);
if (field.isPrimaryKeyColumn())
{
primaryKey = fieldData;
} catch (Exception e)
{
e.printStackTrace();
- System.out.println("offending value:" + fieldData);
+ jalview.bin.Console.outPrintln("offending value:" + fieldData);
}
}
}
@Override
protected void showHelp()
{
- System.out.println("No help implemented yet.");
+ jalview.bin.Console.outPrintln("No help implemented yet.");
}
webResource = client.resource(DEFAULT_THREEDBEACONS_DOMAIN + query);
URI uri = webResource.getURI();
- System.out.println(uri.toString());
+ jalview.bin.Console.outPrintln(uri.toString());
// Execute the REST request
ClientResponse clientResponse;
String fieldData = (tdbJsonStructure.get(field.getCode()) == null)
? " "
: tdbJsonStructure.get(field.getCode()).toString();
- // System.out.println("Field : " + field + " Data : " + fieldData);
+ // jalview.bin.Console.outPrintln("Field : " + field + " Data : " + fieldData);
if (field.isPrimaryKeyColumn())
{
primaryKey = fieldData;
} catch (Exception e)
{
// e.printStackTrace();
- System.out.println("offending value:" + fieldData + fieldData);
+ jalview.bin.Console.outPrintln("offending value:" + fieldData + fieldData);
}
}
}
.getEntity(String.class);
// Make redundant objects eligible for garbage collection to conserve
// memory
- // System.out.println(">>>>> response : "
+ // jalview.bin.Console.outPrintln(">>>>> response : "
// + uniProtTabDelimittedResponseString);
if (clientResponse.getStatus() != 200)
{
firstRow = false;
continue;
}
- // System.out.println(dataRow);
+ // jalview.bin.Console.outPrintln(dataRow);
result.add(getFTSData(dataRow, uniprotRestRequest));
}
searchResult.setNumberOfItemsFound(xTotalResults);
} catch (Exception e)
{
e.printStackTrace();
- System.out.println("offending value:" + fieldData);
+ jalview.bin.Console.outPrintln("offending value:" + fieldData);
}
}
} catch (Exception e)
import jalview.api.AlignExportSettingsI;
import jalview.api.AlignViewportI;
+import jalview.bin.Jalview;
import jalview.io.FileFormatI;
import jalview.util.MessageManager;
public static boolean isNeeded(AlignViewportI viewport,
FileFormatI format)
{
- if (viewport.hasHiddenColumns() || viewport.hasHiddenRows()
- || format.isComplexAlignFile())
- {
- return true;
- }
- return false;
+ return !Jalview.getInstance().isHeadlessMode()
+ && (viewport.hasHiddenColumns() || viewport.hasHiddenRows()
+ || format.isComplexAlignFile());
}
/**
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
+import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import jalview.viewmodel.ViewportRanges;
import jalview.ws.DBRefFetcher;
import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
-import jalview.ws.datamodel.alphafold.PAEContactMatrix;
import jalview.ws.jws1.Discoverer;
import jalview.ws.jws2.Jws2Discoverer;
import jalview.ws.jws2.jabaws2.Jws2Instance;
// if (viewport.cursorMode)
// {
// alignPanel.seqPanel.insertNucAtCursor(false,"A");
- // //System.out.println("A");
+ // //jalview.bin.Console.outPrintln("A");
// }
// break;
/*
* case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
- * System.out.println("closing bracket"); } break;
+ * jalview.bin.Console.outPrintln("closing bracket"); } break;
*/
case KeyEvent.VK_DELETE:
case KeyEvent.VK_BACK_SPACE:
@Override
public void propertyChange(PropertyChangeEvent evt)
{
- // // System.out.println("Discoverer property change.");
+ // // jalview.bin.Console.outPrintln("Discoverer property
+ // change.");
// if (evt.getPropertyName().equals("services"))
{
SwingUtilities.invokeLater(new Runnable()
@Override
public void run()
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Rebuild WS Menu for service change");
BuildWebServiceMenu();
}
public void internalFrameClosed(
javax.swing.event.InternalFrameEvent evt)
{
- // System.out.println("deregistering discoverer listener");
+ // jalview.bin.Console.outPrintln("deregistering discoverer listener");
Desktop.instance.removeJalviewPropertyChangeListener("services",
thisListener);
closeMenuItem_actionPerformed(true);
*/
public void saveAlignment(String file, FileFormatI format)
{
+ saveAlignment(file, format, false, false);
+ }
+
+ public void saveAlignment(String file, FileFormatI format, boolean stdout,
+ boolean forceBackup)
+ {
lastSaveSuccessful = true;
- lastFilenameSaved = file;
+ if (!stdout)
+ {
+ lastFilenameSaved = file;
+ }
lastFormatSaved = format;
if (FileFormat.Jalview.equals(format))
shortName = shortName
.substring(shortName.lastIndexOf(File.separatorChar) + 1);
}
+ // TODO deal with stdout=true
lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
shortName);
else
{
// create backupfiles object and get new temp filename destination
- boolean doBackup = BackupFiles.getEnabled();
+ boolean doBackup = forceBackup
+ || (BackupFiles.getEnabled() && !stdout);
BackupFiles backupfiles = null;
if (doBackup)
{
String tempFilePath = doBackup ? backupfiles.getTempFilePath()
: file;
Console.trace("ALIGNFRAME setting PrintWriter");
- PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
+ PrintWriter out = stdout
+ ? new PrintWriter(new OutputStreamWriter(System.out))
+ : new PrintWriter(new FileWriter(tempFilePath));
if (backupfiles != null)
{
}
out.print(output);
- Console.trace("ALIGNFRAME about to close file");
- out.close();
- Console.trace("ALIGNFRAME closed file");
- AlignFrame.this.setTitle(file);
- statusBar.setText(MessageManager.formatMessage(
- "label.successfully_saved_to_file_in_format", new Object[]
- { fileName, format.getName() }));
+ out.flush();
+ if (!stdout)
+ {
+ Console.trace("ALIGNFRAME about to close file");
+ out.close();
+ Console.trace("ALIGNFRAME closed file");
+ }
+ AlignFrame.this.setTitle(stdout ? "STDOUT" : file);
+ if (stdout)
+ {
+ statusBar.setText(MessageManager.formatMessage(
+ "label.successfully_printed_to_stdout_in_format",
+ new Object[]
+ { format.getName() }));
+ }
+ else
+ {
+ statusBar.setText(MessageManager.formatMessage(
+ "label.successfully_saved_to_file_in_format",
+ new Object[]
+ { fileName, format.getName() }));
+ }
lastSaveSuccessful = true;
} catch (IOException e)
{
protected void htmlMenuItem_actionPerformed(ActionEvent e)
{
HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
- try {
+ try
+ {
htmlSVG.exportHTML(null);
- } catch (ImageOutputException x) {
+ } catch (ImageOutputException x)
+ {
// report problem to console and raise dialog
}
}
public void bioJSMenuItem_actionPerformed(ActionEvent e)
{
BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
- try {
- bjs.exportHTML(null);
- } catch (ImageOutputException x) {
- // report problem to console and raise dialog
- }
+ try
+ {
+ bjs.exportHTML(null);
+ } catch (ImageOutputException x)
+ {
+ // report problem to console and raise dialog
+ }
}
public void createImageMap(File file, String image)
{
- try {
- alignPanel.makePNGImageMap(file, image);
- } catch (ImageOutputException x) {
+ try
+ {
+ alignPanel.makePNGImageMap(file, image);
+ } catch (ImageOutputException x)
+ {
// report problem to console and raise dialog
}
}
@Override
- public void createPNG_actionPerformed(ActionEvent e) {
- try{
+ public void createPNG_actionPerformed(ActionEvent e)
+ {
+ try
+ {
createPNG(null);
} catch (ImageOutputException ioex)
{
// raise dialog, and report via console
}
}
+
@Override
- public void createEPS_actionPerformed(ActionEvent e) {
- try{
+ public void createEPS_actionPerformed(ActionEvent e)
+ {
+ try
+ {
createEPS(null);
} catch (ImageOutputException ioex)
{
// raise dialog, and report via console
}
-
+
}
+
@Override
- public void createSVG_actionPerformed(ActionEvent e) {
- try{
+ public void createSVG_actionPerformed(ActionEvent e)
+ {
+ try
+ {
createSVG(null);
} catch (ImageOutputException ioex)
{
// raise dialog, and report via console
}
-
+
}
+
/**
* Creates a PNG image of the alignment and writes it to the given file. If
* the file is null, the user is prompted to choose a file.
*/
public void createPNG(File f) throws ImageOutputException
{
- createPNG(f, null, BitmapImageSizing.nullBitmapImageSizing());
+ createPNG(f, null, BitmapImageSizing.defaultBitmapImageSizing());
}
- public void createPNG(File f, String renderer, BitmapImageSizing userBis) throws ImageOutputException
+ public void createPNG(File f, String renderer, BitmapImageSizing userBis)
+ throws ImageOutputException
{
alignPanel.makeAlignmentImage(TYPE.PNG, f, renderer, userBis);
}
*
* @param f
*/
- public void createEPS(File f) throws ImageOutputException
+ public void createEPS(File f) throws ImageOutputException
{
createEPS(f, null);
}
*
* @param f
*/
- public void createSVG(File f) throws ImageOutputException
+ public void createSVG(File f) throws ImageOutputException
{
createSVG(f, null);
}
closeAllTabs = true;
}
+ Desktop.closeModal(this);
+
try
{
if (alignPanels != null)
featureSettings.close();
featureSettings = null;
}
+
/*
* this will raise an INTERNAL_FRAME_CLOSED event and this method will
* be called recursively, with the frame now in 'closed' state
*
* @return alignment objects for all views
*/
- AlignmentI[] getViewAlignments()
+ public AlignmentI[] getViewAlignments()
{
if (alignPanels != null)
{
// annotation was duplicated earlier
alignment.addAnnotation(sequences[i].getAnnotation()[a]);
// take care of contact matrix too
- ContactMatrixI cm=sequences[i].getContactMatrixFor(sequences[i].getAnnotation()[a]);
- if (cm!=null)
+ ContactMatrixI cm = sequences[i]
+ .getContactMatrixFor(sequences[i].getAnnotation()[a]);
+ if (cm != null)
{
- alignment.addContactListFor(sequences[i].getAnnotation()[a], cm);
+ alignment.addContactListFor(sequences[i].getAnnotation()[a],
+ cm);
}
-
+
alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
a);
}
} catch (Exception ex)
{
ex.printStackTrace();
- System.out.println("Exception whilst pasting: " + ex);
+ jalview.bin.Console.outPrintln("Exception whilst pasting: " + ex);
// could be anything being pasted in here
}
} catch (Exception ex)
{
ex.printStackTrace();
- System.out.println("Exception whilst pasting: " + ex);
+ jalview.bin.Console.outPrintln("Exception whilst pasting: " + ex);
// could be anything being pasted in here
} catch (OutOfMemoryError oom)
{
@Override
public void wrapMenuItem_actionPerformed(ActionEvent e)
{
- scaleAbove.setVisible(wrapMenuItem.isSelected());
- scaleLeft.setVisible(wrapMenuItem.isSelected());
- scaleRight.setVisible(wrapMenuItem.isSelected());
- viewport.setWrapAlignment(wrapMenuItem.isSelected());
+ setWrapFormat(wrapMenuItem.isSelected(), false);
+ }
+
+ public void setWrapFormat(boolean b, boolean setMenuItem)
+ {
+ scaleAbove.setVisible(b);
+ scaleLeft.setVisible(b);
+ scaleRight.setVisible(b);
+ viewport.setWrapAlignment(b);
alignPanel.updateLayout();
+ if (setMenuItem)
+ {
+ wrapMenuItem.setSelected(b);
+ }
}
@Override
}
JInternalFrame frame = new JInternalFrame();
-
+ frame.setFrameIcon(null);
frame.getContentPane().add(new JScrollPane(pane));
Desktop.addInternalFrame(frame, MessageManager
return alignPanel.overviewPanel;
}
JInternalFrame frame = new JInternalFrame();
+ frame.setFrameIcon(null);
final OverviewPanel overview = new OverviewPanel(alignPanel, frame,
showHidden);
frame.setContentPane(overview);
Desktop.addInternalFrame(frame, "", true, frame.getWidth(),
frame.getHeight(), true, true);
- frame.setFrameIcon(null);
frame.pack();
frame.setLayer(JLayeredPane.PALETTE_LAYER);
final AlignmentPanel thePanel = this.alignPanel;
else
{
JInternalFrame frame = new JInternalFrame();
+ frame.setFrameIcon(null);
frame.setContentPane(new PairwiseAlignPanel(viewport));
Desktop.addInternalFrame(frame,
MessageManager.getString("action.pairwise_alignment"), 600,
return tp;
}
- public void showContactMapTree(AlignmentAnnotation aa,
- ContactMatrixI cm)
+ public void showContactMapTree(AlignmentAnnotation aa, ContactMatrixI cm)
{
int x = 4, y = 5;
int w = 400, h = 500;
{
NewickFile fin = new NewickFile(
new FileParse(cm.getNewick(), DataSourceType.PASTE));
- String title = aa.label + " "
- + cm.getTreeMethod() + " tree" + (aa.sequenceRef != null
+ String title = aa.label + " " + cm.getTreeMethod() + " tree"
+ + (aa.sequenceRef != null
? (" for " + aa.sequenceRef.getDisplayId(false))
: "");
{
try
{
- System.err.println("Waiting for building menu to finish.");
+ jalview.bin.Console
+ .errPrintln("Waiting for building menu to finish.");
Thread.sleep(10);
} catch (Exception e)
{
final List<JMenuItem> legacyItems = new ArrayList<>();
try
{
- // System.err.println("Building ws menu again "
+ // jalview.bin.Console.errPrintln("Building ws menu again "
// + Thread.currentThread());
// TODO: add support for context dependent disabling of services based
// on
Desktop.instance);
if (pe != null)
{
- System.err.println("Associated file : "
+ jalview.bin.Console.errPrintln("Associated file : "
+ (fm[0].toString()) + " with "
+ toassoc.getDisplayId(true));
assocfiles++;
viewport.getAlignment()));
} catch (Exception ex)
{
- System.err.println(ex.getMessage());
+ jalview.bin.Console.errPrintln(ex.getMessage());
return;
}
}
console.runScript();
} catch (Exception ex)
{
- System.err.println((ex.toString()));
+ jalview.bin.Console.errPrintln((ex.toString()));
JvOptionPane.showInternalMessageDialog(Desktop.desktop,
MessageManager.getString("label.couldnt_run_groovy_script"),
MessageManager.getString("label.groovy_support_failed"),
}
else
{
- System.err.println("Can't run Groovy script as console not found");
+ jalview.bin.Console
+ .errPrintln("Can't run Groovy script as console not found");
}
}
import jalview.commands.CommandI;
import jalview.datamodel.AlignedCodonFrame;
import jalview.datamodel.Alignment;
-import jalview.datamodel.AlignmentAnnotation;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.ColumnSelection;
import jalview.datamodel.ContactMatrixI;
import jalview.bin.Cache;
import jalview.bin.Console;
import jalview.bin.Jalview;
+import jalview.datamodel.AlignmentAnnotation;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.HiddenColumns;
import jalview.datamodel.SearchResultsI;
Dimension r = 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);
+ r = calculateDefaultAlignmentIdWidth();
av.setIdWidth(r.width);
}
else
return r;
}
+ public Dimension calculateDefaultAlignmentIdWidth()
+ {
+ 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);
+ return calculateIdWidth(-1, false, false);
+ }
+
/**
* Calculate the width of the alignment labels based on the displayed names
* and any bounds on label width set in preferences.
*/
protected Dimension calculateIdWidth(int maxwidth)
{
+ return calculateIdWidth(maxwidth, true, false);
+ }
+
+ public Dimension calculateIdWidth(int maxwidth,
+ boolean includeAnnotations, boolean visibleOnly)
+ {
Container c = new Container();
FontMetrics fm = c.getFontMetrics(
}
// Also check annotation label widths
- i = 0;
-
- if (al.getAlignmentAnnotation() != null)
+ if (includeAnnotations && al.getAlignmentAnnotation() != null)
{
- fm = c.getFontMetrics(getAlabels().getFont());
-
- while (i < al.getAlignmentAnnotation().length)
+ if (Jalview.isHeadlessMode())
{
- String label = al.getAlignmentAnnotation()[i].label;
- int stringWidth = fm.stringWidth(label);
+ AnnotationLabels aal = getAlabels();
+ int stringWidth = aal.drawLabels(null, false, idWidth, false, false,
+ fm);
idWidth = Math.max(idWidth, stringWidth);
- i++;
+ }
+ else
+ {
+ fm = c.getFontMetrics(getAlabels().getFont());
+
+ for (i = 0; i < al.getAlignmentAnnotation().length; i++)
+ {
+ AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
+ if (visibleOnly && !aa.visible)
+ {
+ continue;
+ }
+ String label = aa.label;
+ int stringWidth = fm.stringWidth(label);
+ idWidth = Math.max(idWidth, stringWidth);
+ }
}
}
// this is called after loading new annotation onto alignment
if (alignFrame.getHeight() == 0)
{
- System.out.println("NEEDS FIXING");
+ jalview.bin.Console.outPrintln("NEEDS FIXING");
}
validateAnnotationDimensions(true);
addNotify();
// 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);
+ AnnotationPanel ap = getAnnotationPanel();
+ int annotationHeight = ap.adjustPanelHeight();
+ annotationHeight = ap.adjustForAlignFrame(adjustPanelHeight,
+ annotationHeight);
hscroll.addNotify();
- annotationScroller.setPreferredSize(
- new Dimension(annotationScroller.getWidth(), annotationHeight));
-
Dimension e = idPanel.getSize();
- alabels.setSize(new Dimension(e.width, annotationHeight));
+ int idWidth = e.width;
+ boolean manuallyAdjusted = this.getIdPanel().getIdCanvas()
+ .manuallyAdjusted();
+ annotationScroller.setPreferredSize(new Dimension(
+ manuallyAdjusted ? idWidth : annotationScroller.getWidth(),
+ annotationHeight));
+
+ alabels.setPreferredSize(new Dimension(idWidth, annotationHeight));
annotationSpaceFillerHolder.setPreferredSize(new Dimension(
- annotationSpaceFillerHolder.getWidth(), annotationHeight));
+ manuallyAdjusted ? idWidth
+ : annotationSpaceFillerHolder.getWidth(),
+ annotationHeight));
annotationScroller.validate();
annotationScroller.addNotify();
+ ap.validate();
}
/**
boolean wrap = av.getWrapAlignment();
ViewportRanges ranges = av.getRanges();
ranges.setStartSeq(0);
- scalePanelHolder.setVisible(!wrap);
+ // scalePanelHolder.setVisible(!wrap);
hscroll.setVisible(!wrap);
- idwidthAdjuster.setVisible(!wrap);
+ // Allow idPanel width adjustment in wrap mode
+ idwidthAdjuster.setVisible(true);
if (wrap)
{
}
}
- idSpaceFillerPanel1.setVisible(!wrap);
+ // idSpaceFillerPanel1.setVisible(!wrap);
repaint();
}
public void paintComponent(Graphics g)
{
invalidate(); // needed so that the id width adjuster works correctly
-
Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
- idPanelHolder.setPreferredSize(d);
- hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
+ int idWidth = d.width;
+
+ // check wrapped alignment as at least 1 residue width
+ if (av.getWrapAlignment())
+ {
+ SeqCanvas sc = this.getSeqPanel().seqCanvas;
+ if (sc != null && sc.getWidth() < sc.getMinimumWrappedCanvasWidth())
+ {
+ // need to make some adjustments
+ idWidth -= (sc.getMinimumWrappedCanvasWidth() - sc.getWidth());
+ av.setIdWidth(idWidth);
+ av.getAlignPanel().getIdPanel().getIdCanvas()
+ .setManuallyAdjusted(true);
+
+ validateAnnotationDimensions(false);
+ }
+ }
+
+ idPanelHolder.setPreferredSize(new Dimension(idWidth, d.height));
+ hscrollFillerPanel.setPreferredSize(new Dimension(idWidth, 12));
validate(); // needed so that the id width adjuster works correctly
List<SequenceI> selection = av.getSelectionGroup() == null ? null
: av.getSelectionGroup().getSequences(null);
idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
- selection);
+ selection, false);
idGraphics.setFont(av.getFont());
idGraphics.translate(0, -scaleHeight);
int offset = getAlabels().getScrollOffset();
idGraphics.translate(0, -offset);
idGraphics.translate(0, alignmentDrawnHeight);
- getAlabels().drawComponent(idGraphics, idWidth);
+ getAlabels().drawComponentNotGUI(idGraphics, idWidth);
idGraphics.translate(0, -alignmentDrawnHeight);
/*
* draw sequence ids and annotation labels (if shown)
*/
IdCanvas idCanvas = getIdPanel().getIdCanvas();
- idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
+ idCanvas.drawIdsWrappedNoGUI((Graphics2D) g, av, 0, totalHeight);
g.translate(idWidth, 0);
}
int w = getIdPanel().getWidth();
+ w = this.calculateIdWidth(-1, true, true).width;
return (w > 0 ? w : calculateIdWidth().width);
}
- void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer) throws ImageOutputException
+ void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer)
+ throws ImageOutputException
{
makeAlignmentImage(type, file, renderer,
- BitmapImageSizing.nullBitmapImageSizing());
+ BitmapImageSizing.defaultBitmapImageSizing());
}
/**
final int borderBottomOffset = 5;
AlignmentDimension aDimension = getAlignmentDimension();
+
// todo use a lambda function in place of callback here?
ImageWriterI writer = new ImageWriterI()
{
}
- public void makePNGImageMap(File imgMapFile, String imageName) throws ImageOutputException
+ public void makePNGImageMap(File imgMapFile, String imageName)
+ throws ImageOutputException
{
// /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
// ////////////////////////////////////////////
} catch (Exception ex)
{
- throw new ImageOutputException("couldn't write ImageMap due to unexpected error",ex);
+ throw new ImageOutputException(
+ "couldn't write ImageMap due to unexpected error", ex);
}
} // /////////END OF IMAGE MAP
{
int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
- if (System.getProperty("java.awt.headless") != null
- && System.getProperty("java.awt.headless").equals("true"))
+ if (Jalview.isHeadlessMode())
{
seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
- vscroll.getPreferredSize().width
*/
package jalview.gui;
+import java.awt.Canvas;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import jalview.analysis.AlignSeq;
import jalview.analysis.AlignmentUtils;
+import jalview.bin.Cache;
+import jalview.bin.Jalview;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentAnnotation;
import jalview.datamodel.Annotation;
/**
* height in pixels for allowing height adjuster to be active
*/
- private static int HEIGHT_ADJUSTER_HEIGHT = 10;
+ public static int HEIGHT_ADJUSTER_HEIGHT = 10;
private static final Font font = new Font("Arial", Font.PLAIN, 11);
private static final String COPYCONS_SEQ = MessageManager
.getString("label.copy_consensus_sequence");
+ private static final String ADJUST_ANNOTATION_LABELS_WIDTH_PREF = "ADJUST_ANNOTATION_LABELS_WIDTH";
+
private final boolean debugRedraw = false;
private AlignmentPanel ap;
private boolean resizePanel = false;
+ private int annotationIdWidth = -1;
+
+ public static final String RESIZE_MARGINS_MARK_PREF = "RESIZE_MARGINS_MARK";
+
/**
* Creates a new AnnotationLabels object
*
*/
public AnnotationLabels(AlignmentPanel ap)
{
-
this.ap = ap;
av = ap.av;
ToolTipManager.sharedInstance().registerComponent(this);
pop.add(consclipbrd);
}
- addColourOrFilterByOptions(ap,aa[selectedRow],pop);
-
+ addColourOrFilterByOptions(ap, aa[selectedRow], pop);
+
if (aa[selectedRow].graph == AlignmentAnnotation.CONTACT_MAP)
{
- addContactMatrixOptions(ap,aa[selectedRow],pop);
- // Set/adjust threshold for grouping ?
- // colour alignment by this [type]
- // select/hide columns by this row
-
- }
+ addContactMatrixOptions(ap, aa[selectedRow], pop);
+ // Set/adjust threshold for grouping ?
+ // colour alignment by this [type]
+ // select/hide columns by this row
+
}
-
+ }
+
pop.show(this, evt.getX(), evt.getY());
}
static void addColourOrFilterByOptions(final AlignmentPanel ap,
- final AlignmentAnnotation alignmentAnnotation, final JPopupMenu pop)
+ final AlignmentAnnotation alignmentAnnotation,
+ final JPopupMenu pop)
{
JMenuItem item;
- item = new JMenuItem(MessageManager.getString("label.colour_by_annotation"));
+ item = new JMenuItem(
+ MessageManager.getString("label.colour_by_annotation"));
item.addActionListener(new ActionListener()
{
-
+
@Override
public void actionPerformed(ActionEvent e)
{
- AnnotationColourChooser.displayFor(ap.av, ap,alignmentAnnotation,false);
+ AnnotationColourChooser.displayFor(ap.av, ap, alignmentAnnotation,
+ false);
};
});
pop.add(item);
- if (alignmentAnnotation.sequenceRef!=null)
+ if (alignmentAnnotation.sequenceRef != null)
{
- item = new JMenuItem(MessageManager.getString("label.colour_by_annotation")+" ("+MessageManager.getString("label.per_seq")+")");
+ item = new JMenuItem(
+ MessageManager.getString("label.colour_by_annotation") + " ("
+ + MessageManager.getString("label.per_seq") + ")");
item.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
- AnnotationColourChooser.displayFor(ap.av, ap,alignmentAnnotation,true);
+ AnnotationColourChooser.displayFor(ap.av, ap, alignmentAnnotation,
+ true);
};
});
pop.add(item);
}
- item = new JMenuItem(MessageManager.getString("action.select_by_annotation"));
+ item = new JMenuItem(
+ MessageManager.getString("action.select_by_annotation"));
item.addActionListener(new ActionListener()
{
-
+
@Override
public void actionPerformed(ActionEvent e)
{
- AnnotationColumnChooser.displayFor(ap.av,ap,alignmentAnnotation);
+ AnnotationColumnChooser.displayFor(ap.av, ap, alignmentAnnotation);
};
});
pop.add(item);
}
+
static void addContactMatrixOptions(final AlignmentPanel ap,
- final AlignmentAnnotation alignmentAnnotation, final JPopupMenu pop)
+ final AlignmentAnnotation alignmentAnnotation,
+ final JPopupMenu pop)
{
-
+
final ContactMatrixI cm = ap.av.getContactMatrix(alignmentAnnotation);
JMenuItem item;
if (cm != null)
if (cm.hasGroups())
{
- JCheckBoxMenuItem chitem = new JCheckBoxMenuItem(MessageManager.getString("action.show_groups_on_matrix"));
- chitem.setToolTipText(MessageManager.getString("action.show_groups_on_matrix_tooltip"));
- boolean showGroups = alignmentAnnotation.isShowGroupsForContactMatrix();
- final AlignmentAnnotation sel_row=alignmentAnnotation;
+ JCheckBoxMenuItem chitem = new JCheckBoxMenuItem(
+ MessageManager.getString("action.show_groups_on_matrix"));
+ chitem.setToolTipText(MessageManager
+ .getString("action.show_groups_on_matrix_tooltip"));
+ boolean showGroups = alignmentAnnotation
+ .isShowGroupsForContactMatrix();
+ final AlignmentAnnotation sel_row = alignmentAnnotation;
chitem.setState(showGroups);
chitem.addActionListener(new ActionListener()
{
}
if (cm.hasTree())
{
- item = new JMenuItem(MessageManager.getString("action.show_tree_for_matrix"));
- item.setToolTipText(MessageManager.getString("action.show_tree_for_matrix_tooltip"));
+ item = new JMenuItem(
+ MessageManager.getString("action.show_tree_for_matrix"));
+ item.setToolTipText(MessageManager
+ .getString("action.show_tree_for_matrix_tooltip"));
item.addActionListener(new ActionListener()
{
}
else
{
- item = new JMenuItem(MessageManager.getString("action.cluster_matrix"));
- item.setToolTipText(MessageManager.getString("action.cluster_matrix_tooltip"));
+ item = new JMenuItem(
+ MessageManager.getString("action.cluster_matrix"));
+ item.setToolTipText(
+ MessageManager.getString("action.cluster_matrix_tooltip"));
item.addActionListener(new ActionListener()
{
@Override
public void run()
{
final long progBar;
- ap.alignFrame.setProgressBar(MessageManager.formatMessage("action.clustering_matrix_for",cm.getAnnotDescr(),5f), progBar = System.currentTimeMillis());
+ ap.alignFrame.setProgressBar(
+ MessageManager.formatMessage(
+ "action.clustering_matrix_for",
+ cm.getAnnotDescr(), 5f),
+ progBar = System.currentTimeMillis());
cm.setGroupSet(GroupSet.makeGroups(cm, true));
cm.randomlyReColourGroups();
cm.transferGroupColorsTo(alignmentAnnotation);
RenderingHints.VALUE_ANTIALIAS_ON);
}
- drawComponent(g2, true, width);
-
+ drawComponent(g2, true, width, true);
}
/**
*/
public void drawComponent(Graphics g, int width)
{
- drawComponent(g, false, width);
+ drawComponent(g, false, width, true);
}
/**
* @param width
* Width for scaling labels
*/
- public void drawComponent(Graphics g, boolean clip, int width)
+ public void drawComponent(Graphics g, boolean clip, int givenWidth, boolean forGUI)
{
- if (av.getFont().getSize() < 10)
+ int width = givenWidth;
+ IdwidthAdjuster iwa = null;
+ if (ap != null)
{
- g.setFont(font);
+ iwa = ap.idwidthAdjuster;
+ if ((Cache.getDefault(ADJUST_ANNOTATION_LABELS_WIDTH_PREF, true)
+ || Jalview.isHeadlessMode()))
+ {
+ Graphics2D g2d = (Graphics2D) g;
+ Graphics dummy = g2d.create();
+ int newAnnotationIdWidth = drawLabels(dummy, clip, width, false, forGUI,
+ null);
+ dummy.dispose();
+ Dimension d = ap.calculateDefaultAlignmentIdWidth();
+ int alignmentIdWidth = d.width;
+ if (iwa != null && !iwa.manuallyAdjusted())
+ {
+ // If no manual adjustment to ID column with has been made then adjust
+ // width match widest of alignment or annotation id widths
+ boolean allowShrink = Cache.getDefault("ALLOW_SHRINK_ID_WIDTH",
+ false);
+ width = Math.max(alignmentIdWidth, newAnnotationIdWidth);
+ if (clip && width < givenWidth && !allowShrink)
+ {
+ width = givenWidth;
+ }
+ }
+ else if (newAnnotationIdWidth != annotationIdWidth
+ && newAnnotationIdWidth > givenWidth
+ && newAnnotationIdWidth > alignmentIdWidth)
+ {
+ // otherwise if the annotation id width has become larger than the
+ // current id width, increase
+ width = newAnnotationIdWidth;
+ annotationIdWidth = newAnnotationIdWidth;
+ }
+ // set the width if it's changed
+ if (width != ap.av.getIdWidth())
+ {
+ iwa.setWidth(width);
+ }
+ }
}
else
{
- g.setFont(av.getFont());
+ int newAnnotationIdWidth = drawLabels(g, clip, width, false, forGUI, null);
+ width = Math.max(newAnnotationIdWidth, givenWidth);
+ }
+ drawLabels(g, clip, width, true, forGUI, null);
+ }
+
+ /**
+ * Render the full set of annotation Labels for the alignment at the given
+ * cursor. If actuallyDraw is false or g is null then no actual drawing will
+ * occur, but the widest label width will be returned. If g is null then
+ * fmetrics must be supplied.
+ *
+ * Returns the width of the annotation labels.
+ *
+ * @param g
+ * Graphics2D instance (used for rendering and font scaling if no fmetrics supplied)
+ * @param clip
+ * - true indicates that only current visible area needs to be
+ * rendered
+ * @param width
+ * Width for scaling labels
+ * @param actuallyDraw - when false, no graphics are rendered to g0
+ * @param forGUI - when false, GUI relevant marks like indicators for dragging annotation panel height are not rendered
+ * @param fmetrics
+ * FontMetrics if Graphics object g is null
+ */
+ public int drawLabels(Graphics g0, boolean clip, int width,
+ boolean actuallyDraw, boolean forGUI, FontMetrics fmetrics)
+ {
+ if (clip)
+ {
+ clip = Cache.getDefault("MOVE_SEQUENCE_ID_WITH_VISIBLE_ANNOTATIONS",
+ true);
+ }
+ Graphics g = null;
+ // create a dummy Graphics object if not drawing and one is supplied
+ if (g0 != null)
+ {
+ if (!actuallyDraw)
+ {
+ Graphics2D g2d = (Graphics2D) g0;
+ g = g2d.create();
+ }
+ else
+ {
+ g = g0;
+ }
+ }
+ int actualWidth = 0;
+ if (g != null)
+ {
+ if (av.getFont().getSize() < 10)
+ {
+ g.setFont(font);
+ }
+ else
+ {
+ g.setFont(av.getFont());
+ }
}
- FontMetrics fm = g.getFontMetrics(g.getFont());
- g.setColor(Color.white);
- g.fillRect(0, 0, getWidth(), getHeight());
+ FontMetrics fm = fmetrics == null ? g.getFontMetrics(g.getFont())
+ : fmetrics;
+ if (actuallyDraw)
+ {
+ g.setColor(Color.white);
+ g.fillRect(0, 0, getWidth(), getHeight());
+
+ if (!Cache.getDefault(RESIZE_MARGINS_MARK_PREF, false)
+ && !av.getWrapAlignment() && forGUI)
+ {
+ g.setColor(Color.LIGHT_GRAY);
+ g.drawLine(0, HEIGHT_ADJUSTER_HEIGHT / 4, HEIGHT_ADJUSTER_WIDTH / 4,
+ HEIGHT_ADJUSTER_HEIGHT / 4);
+ g.drawLine(0, 3 * HEIGHT_ADJUSTER_HEIGHT / 4,
+ HEIGHT_ADJUSTER_WIDTH / 4, 3 * HEIGHT_ADJUSTER_HEIGHT / 4);
+
+ }
+ }
- g.translate(0, getScrollOffset());
- g.setColor(Color.black);
+ if (actuallyDraw)
+ {
+ g.translate(0, getScrollOffset());
+ g.setColor(Color.black);
+ }
SequenceI lastSeqRef = null;
String lastLabel = null;
AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
- int fontHeight = g.getFont().getSize();
+ int fontHeight = g != null ? g.getFont().getSize()
+ : fm.getFont().getSize();
int y = 0;
int x = 0;
int graphExtras = 0;
int offset = 0;
- Font baseFont = g.getFont();
+ Font baseFont = g != null ? g.getFont() : fm.getFont();
FontMetrics baseMetrics = fm;
int ofontH = fontHeight;
int sOffset = 0;
{
if (debugRedraw)
{
- System.out.println("before vis: " + i);
+ jalview.bin.Console.outPrintln("before vis: " + i);
}
before = true;
}
{
if (debugRedraw)
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Scroll offset: " + sOffset + " after vis: " + i);
}
after = true;
continue;
}
}
- g.setColor(Color.black);
-
+ if (actuallyDraw && g != null)
+ {
+ g.setColor(Color.black);
+ }
offset = -aa[i].height / 2;
if (aa[i].hasText)
vertBar = true;
}
}
- x = width - fm.stringWidth(label) - 3;
+
+ int labelWidth = fm.stringWidth(label) + 3;
+ x = width - labelWidth;
if (aa[i].graphGroup > -1)
{
s = ((float) fontHeight) / (float) ofontH;
Font f = baseFont
.deriveFont(AffineTransform.getScaleInstance(s, s));
- g.setFont(f);
- fm = g.getFontMetrics();
- graphExtras = (aa[i].height - (groupSize * (fontHeight + 8)))
- / 2;
+ Canvas c = new Canvas();
+ fm = c.getFontMetrics(f);
+ if (actuallyDraw && g != null)
+ {
+ g.setFont(f);
+ // fm = g.getFontMetrics();
+ graphExtras = (aa[i].height
+ - (groupSize * (fontHeight + 8))) / 2;
+ }
}
}
if (visible)
{
if (aa[gg].graphGroup == aa[i].graphGroup)
{
- x = width - fm.stringWidth(aa[gg].label) - 3;
- g.drawString(aa[gg].label, x, y - graphExtras);
-
- if (aa[gg]._linecolour != null)
+ labelWidth = fm.stringWidth(aa[gg].label) + 3;
+ x = width - labelWidth;
+ if (actuallyDraw && g != null)
{
+ g.drawString(aa[gg].label, x, y - graphExtras);
- g.setColor(aa[gg]._linecolour);
- g.drawLine(x, y - graphExtras + 3,
- x + fm.stringWidth(aa[gg].label),
- y - graphExtras + 3);
- }
+ if (aa[gg]._linecolour != null)
+ {
+
+ g.setColor(aa[gg]._linecolour);
+ g.drawLine(x, y - graphExtras + 3,
+ x + fm.stringWidth(aa[gg].label),
+ y - graphExtras + 3);
+ }
- g.setColor(Color.black);
+ g.setColor(Color.black);
+ }
graphExtras += fontHeight + 8;
}
}
}
- g.setFont(baseFont);
+ if (actuallyDraw && g != null)
+ {
+ g.setFont(baseFont);
+ }
fm = baseMetrics;
fontHeight = ofontH;
}
else
{
- if (vertBar)
+ if (actuallyDraw && g != null)
{
- g.drawLine(width - 3, y + offset - fontHeight, width - 3,
- (int) (y - 1.5 * aa[i].height - offset - fontHeight));
- // g.drawLine(20, y + offset, x - 20, y + offset);
+ if (vertBar)
+ {
+ g.drawLine(width - 3, y + offset - fontHeight, width - 3,
+ (int) (y - 1.5 * aa[i].height - offset - fontHeight));
+ // g.drawLine(20, y + offset, x - 20, y + offset);
+ }
+ g.drawString(label, x, y + offset);
}
- g.drawString(label, x, y + offset);
}
lastSeqRef = aa[i].sequenceRef;
+
+ if (labelWidth > actualWidth)
+ {
+ actualWidth = labelWidth;
+ }
}
}
if (!resizePanel && dragEvent != null && aa != null)
{
- g.setColor(Color.lightGray);
- g.drawString(
- (aa[selectedRow].sequenceRef == null ? ""
- : aa[selectedRow].sequenceRef.getName())
- + aa[selectedRow].label,
- dragEvent.getX(), dragEvent.getY() - getScrollOffset());
+ if (actuallyDraw && g != null)
+ {
+ g.setColor(Color.lightGray);
+ g.drawString(
+ (aa[selectedRow].sequenceRef == null ? ""
+ : aa[selectedRow].sequenceRef.getName())
+ + aa[selectedRow].label,
+ dragEvent.getX(), dragEvent.getY() - getScrollOffset());
+ }
}
if (!av.getWrapAlignment() && ((aa == null) || (aa.length < 1)))
{
- g.drawString(MessageManager.getString("label.right_click"), 2, 8);
- g.drawString(MessageManager.getString("label.to_add_annotation"), 2,
- 18);
+ if (actuallyDraw && g != null)
+ {
+ g.drawString(MessageManager.getString("label.right_click"), 2, 8);
+ g.drawString(MessageManager.getString("label.to_add_annotation"), 2,
+ 18);
+ }
}
+
+ return actualWidth;
}
public int getScrollOffset()
public void mouseEntered(MouseEvent e)
{
}
+
+ public void drawComponentNotGUI(Graphics idGraphics, int idWidth)
+ {
+ drawComponent(idGraphics, false, idWidth, false);
+ }
}
tried = true;
} catch (IllegalArgumentException exc)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Serious issue with viewport geometry imgWidth requested was "
+ imgWidth);
return;
&& (fadedImage == null || fadedImage.getWidth() != imgWidth
|| fadedImage.getHeight() != image.getHeight()))
{
- // System.err.println("redraw faded image ("+(fadedImage==null ?
+ // jalview.bin.Console.errPrintln("redraw faded image ("+(fadedImage==null ?
// "null image" : "") + " lastGood="+lastImageGood+")");
fadedImage = new BufferedImage(imgWidth, image.getHeight(),
BufferedImage.TYPE_INT_RGB);
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.io.File;
-import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.FutureTask;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
}
jmb.executeCommand(new StructureCommand(command), false);
jmb.executeCommand(new StructureCommand("set hoverDelay=0.1"), false);
+ jmb.executeCommand(new StructureCommand("set antialiasdisplay on"),
+ false);
jmb.setFinishedInit(true);
}
}
if (waitTotal > waitMax)
{
- System.err.println("Timed out waiting for Jmol to load files after "
- + waitTotal + "ms");
- // System.err.println("finished: " + jmb.isFinishedInit()
+ jalview.bin.Console.errPrintln(
+ "Timed out waiting for Jmol to load files after "
+ + waitTotal + "ms");
+ // jalview.bin.Console.errPrintln("finished: " + jmb.isFinishedInit()
// + "; loaded: " + Arrays.toString(jmb.getPdbFile())
// + "; files: " + files.toString());
jmb.getStructureFiles();
@Override
public void makePDBImage(ImageMaker.TYPE type)
{
- try {
- makePDBImage(null, type, null,
- BitmapImageSizing.nullBitmapImageSizing());
- } catch (ImageOutputException ioex) {
- Console.error("Unexpected error whilst writing "+type.toString(),ioex);
+ try
+ {
+ makePDBImage(null, type, null,
+ BitmapImageSizing.defaultBitmapImageSizing());
+ } catch (ImageOutputException ioex)
+ {
+ Console.error("Unexpected error whilst writing " + type.toString(),
+ ioex);
}
}
BitmapImageSizing bis = ImageMaker.getScaleWidthHeight(width, height,
userBis);
- float usescale = bis.scale;
- int usewidth = bis.width;
- int useheight = bis.height;
+ float usescale = bis.scale();
+ int usewidth = bis.width();
+ int useheight = bis.height();
ImageWriterI writer = new ImageWriterI()
{
}
}
- jmb.jmolViewer.antialiased = true;
jmb.jmolViewer.requestRepaintAndWait("image export");
jmb.jmolViewer.renderScreenImage(ig2, usewidth, useheight);
}
.toLowerCase(Locale.ROOT);
final ImageExporter exporter = new ImageExporter(writer,
getProgressIndicator(), type, getTitle());
-
+
final Throwable[] exceptions = new Throwable[1];
exceptions[0] = null;
final AppJmol us = this;
try
{
- Thread runner = Executors.defaultThreadFactory().newThread(new Runnable()
- {
- @Override
- public void run()
- {
- try
- {
- exporter.doExport(file, us, width, height, view, renderer,
- userBis);
- } catch (Throwable t)
- {
- exceptions[0] = t;
- }
- }
- });
+ Thread runner = Executors.defaultThreadFactory()
+ .newThread(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ try
+ {
+ exporter.doExport(file, us, width, height, view,
+ renderer, userBis);
+ } catch (Throwable t)
+ {
+ exceptions[0] = t;
+ }
+ }
+ });
runner.start();
- do { Thread.sleep(25); } while (runner.isAlive());
+ do
+ {
+ Thread.sleep(25);
+ } while (runner.isAlive());
} catch (Throwable e)
{
throw new ImageOutputException(
.openURL("http://wiki.jmol.org");// http://jmol.sourceforge.net/docs/JmolUserGuide/");
} catch (Exception ex)
{
- System.err.println("Show Jmol help failed with: " + ex.getMessage());
+ jalview.bin.Console
+ .errPrintln("Show Jmol help failed with: " + ex.getMessage());
}
}
import jalview.api.AlignmentViewPanel;
import jalview.api.structures.JalviewStructureDisplayI;
import jalview.bin.Console;
-import jalview.datamodel.AlignmentI;
+import jalview.bin.Jalview;
import jalview.datamodel.PDBEntry;
import jalview.datamodel.SequenceI;
import jalview.ext.jmol.JalviewJmolBinding;
import jalview.structure.StructureSelectionManager;
import jalview.util.MessageManager;
import jalview.util.Platform;
-import jalview.ws.dbsources.EBIAlfaFold;
-import jalview.ws.dbsources.Pdb;
-import jalview.ws.utils.UrlDownloadClient;
import javajs.util.BS;
public class AppJmolBinding extends JalviewJmolBinding
{
jmolViewer.setJmolCallbackListener(this);
// BH comment: can't do this yet [for JS only, or generally?]
- return Platform.isJS() ? null
+ return Platform.isJS() || Jalview.isHeadlessMode() ? null
: new AppConsole(jmolViewer, consolePanel, buttonsToShow);
}
if (shift != null)
{
int i = shift.shift(newBase.getIndex());
- // System.err.println("shifted "+(arg1.getIndex())+" to "+i);
+ // jalview.bin.Console.errPrintln("shifted "+(arg1.getIndex())+" to "+i);
ssm.mouseOverVamsasSequence(seq, i, this);
}
else
} catch (ExceptionNAViewAlgorithm e)
{
// only throwable for draw mode = 3 NAView
- System.err.println("Error drawing RNA: " + e.getMessage());
+ jalview.bin.Console.errPrintln("Error drawing RNA: " + e.getMessage());
}
}
}
String formattedDate = Cache.setDateProperty(
"JALVIEW_NEWS_RSS_LASTMODIFIED", lastread.getTime());
BlogReader me = new BlogReader();
- System.out.println("Set last date to " + formattedDate);
+ jalview.bin.Console.outPrintln("Set last date to " + formattedDate);
if (me.isNewsNew())
{
Console.debug("There is news to read.");
boolean opened = jmb.openSession(chimeraSessionFile);
if (!opened)
{
- System.err.println("An error occurred opening Chimera session file "
+ jalview.bin.Console.errPrintln("An error occurred opening Chimera session file "
+ chimeraSessionFile);
}
}
}
} catch (Exception ex)
{
- System.out.println("Error loading User ColourFile\n" + ex);
+ jalview.bin.Console.outPrintln("Error loading User ColourFile\n" + ex);
}
}
// you may omit this part for your application
//
- System.out.println("Hello World 2");
- System.out.println("All fonts available to Graphic2D:\n");
+ jalview.bin.Console.outPrintln("Hello World 2");
+ jalview.bin.Console.outPrintln("All fonts available to Graphic2D:\n");
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
String[] fontNames = ge.getAvailableFontFamilyNames();
for (int n = 0; n < fontNames.length; n++)
{
- System.out.println(fontNames[n]);
+ jalview.bin.Console.outPrintln(fontNames[n]);
}
// Testing part: simple an error thrown anywhere in this JVM will be printed
// on the Console
// We do it with a seperate Thread becasue we don't wan't to break a Thread
// used by the Console.
- System.out.println("\nLets throw an error on this console");
+ jalview.bin.Console.outPrintln("\nLets throw an error on this console");
errorThrower = new Thread(this);
errorThrower.setDaemon(true);
errorThrower.start();
MessageManager.getString("label.cant_map_cds"),
MessageManager.getString("label.operation_failed"),
JvOptionPane.OK_OPTION);
- System.err.println("Failed to make CDS alignment");
+ jalview.bin.Console.errPrintln("Failed to make CDS alignment");
return null;
}
if (copyAlignment.getHeight() <= 0)
{
- System.err.println("No Sequences generated for xRef type " + source);
+ jalview.bin.Console.errPrintln("No Sequences generated for xRef type " + source);
return null;
}
import java.awt.BorderLayout;
import java.awt.Color;
+import java.awt.Component;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.geom.AffineTransform;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
+import java.beans.PropertyVetoException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
+import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
+import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
+import javax.swing.JScrollPane;
+import javax.swing.JTextArea;
import javax.swing.JTextField;
+import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.HyperlinkEvent.EventType;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
+import javax.swing.text.JTextComponent;
import org.stackoverflowusers.file.WindowsShortcut;
import jalview.api.structures.JalviewStructureDisplayI;
import jalview.bin.Cache;
import jalview.bin.Jalview;
+import jalview.bin.Jalview.ExitCode;
import jalview.datamodel.Alignment;
import jalview.datamodel.HiddenColumns;
import jalview.datamodel.Sequence;
* Send this message to stderr as the warning that follows (due to
* reflection) also goes to stderr.
*/
- System.err.println(
+ jalview.bin.Console.errPrintln(
"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.");
}
final String awtAppClassName = "awtAppClassName";
}
// Thread off a new instance of the file chooser - this reduces the time
- // it
- // takes to open it later on.
+ // it takes to open it later on.
new Thread(new Runnable()
{
@Override
public void run()
{
jalview.bin.Console.debug("Filechooser init thread started.");
- String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
+ String fileFormat = FileLoader.getUseDefaultFileFormat()
+ ? Cache.getProperty("DEFAULT_FILE_FORMAT")
+ : null;
JalviewFileChooser.forRead(Cache.getProperty("LAST_DIRECTORY"),
fileFormat);
jalview.bin.Console.debug("Filechooser init thread finished.");
// used for jalviewjsTest
jalview.bin.Console.info("JALVIEWJS: CREATED DESKTOP");
}
+
}
/**
}
} catch (Exception ex)
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Unable to paste alignment from system clipboard:\n" + ex);
}
}
setKeyBindings(frame);
- // Since the latest FlatLaf patch, we occasionally have problems showing structureViewer frames...
- int tries=3;
- boolean shown=false;
- Exception last=null;
+ // Since the latest FlatLaf patch, we occasionally have problems showing
+ // structureViewer frames...
+ int tries = 3;
+ boolean shown = false;
+ Exception last = null;
do
{
try
{
desktop.add(frame);
- shown=true;
+ shown = true;
} catch (IllegalArgumentException iaex)
{
- last=iaex;
+ last = iaex;
tries--;
- jalview.bin.Console.info(
- "Squashed IllegalArgument Exception (" + tries + " left) for "+frame.getTitle(),
- iaex);
+ jalview.bin.Console.info("Squashed IllegalArgument Exception ("
+ + tries + " left) for " + frame.getTitle(), iaex);
try
{
Thread.sleep(5);
} while (!shown && tries > 0);
if (!shown)
{
- jalview.bin.Console.error("Serious Problem whilst showing window "+frame.getTitle(),last);
+ jalview.bin.Console.error(
+ "Serious Problem whilst showing window " + frame.getTitle(),
+ last);
}
windowMenu.add(menuItem);
@Override
public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
{
- String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
+ String fileFormat = FileLoader.getUseDefaultFileFormat()
+ ? Cache.getProperty("DEFAULT_FILE_FORMAT")
+ : null;
JalviewFileChooser chooser = JalviewFileChooser.forRead(
Cache.getProperty("LAST_DIRECTORY"), fileFormat,
BackupFiles.getEnabled());
// this will run the shutdownHook but QuitHandler.getQuitResponse() should
// not run a second time if gotQuitResponse flag has been set (i.e. user
// confirmed quit of some kind).
- Jalview.exit("Desktop exiting.", 0);
+ Jalview.exit("Desktop exiting.", ExitCode.OK);
}
private void storeLastKnownDimensions(String string, Rectangle jc)
}
} catch (Exception ex)
{
- System.err.println("Error opening help: " + ex.getMessage());
+ jalview.bin.Console
+ .errPrintln("Error opening help: " + ex.getMessage());
}
}
boolean autoSave = projectFile != null && !saveAs
&& BackupFiles.getEnabled();
- // System.out.println("autoSave="+autoSave+", projectFile='"+projectFile+"',
+ // jalview.bin.Console.outPrintln("autoSave="+autoSave+",
+ // projectFile='"+projectFile+"',
// saveAs="+saveAs+", Backups
// "+(BackupFiles.getEnabled()?"enabled":"disabled"));
{
if (Platform.isAMacAndNotJS())
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Please ignore plist error - occurs due to problem with java 8 on OSX");
}
}
Desktop us = Desktop.instance;
Desktop.instance = null;
// call dispose in a separate thread - try to avoid indirect deadlocks
- new Thread(new Runnable() {
+ new Thread(new Runnable()
+ {
@Override
public void run()
{
ExecutorService dex = us.dialogExecutor;
- if (dex!=null) {
+ if (dex != null)
+ {
dex.shutdownNow();
- us.dialogExecutor=null;
+ us.dialogExecutor = null;
us.block.drainPermits();
}
us.dispose();
}
/**
- * checks if any progress bars are being displayed in any of the windows managed by the desktop
+ * checks if any progress bars are being displayed in any of the windows
+ * managed by the desktop
+ *
* @return
*/
public boolean operationsAreInProgress()
{
JInternalFrame[] frames = getAllFrames();
- for (JInternalFrame frame:frames)
+ for (JInternalFrame frame : frames)
{
if (frame instanceof IProgressIndicator)
{
- if (((IProgressIndicator)frame).operationInProgress())
+ if (((IProgressIndicator) frame).operationInProgress())
{
return true;
}
}
return operationInProgress();
}
+
+ /**
+ * keep track of modal JvOptionPanes open as modal dialogs for AlignFrames.
+ * The way the modal JInternalFrame is made means it cannot be a child of an
+ * AlignFrame, so closing the AlignFrame might leave the modal open :(
+ */
+ private static Map<AlignFrame, JInternalFrame> alignFrameModalMap = new HashMap<>();
+
+ protected static void addModal(AlignFrame af, JInternalFrame jif)
+ {
+ alignFrameModalMap.put(af, jif);
+ }
+
+ protected static void closeModal(AlignFrame af)
+ {
+ if (!alignFrameModalMap.containsKey(af))
+ {
+ return;
+ }
+ JInternalFrame jif = alignFrameModalMap.get(af);
+ if (jif != null)
+ {
+ try
+ {
+ jif.setClosed(true);
+ } catch (PropertyVetoException e)
+ {
+ e.printStackTrace();
+ }
+ }
+ alignFrameModalMap.remove(af);
+ }
+
+ public void nonBlockingDialog(String title, String message, String button,
+ int type, boolean scrollable, boolean modal)
+ {
+ nonBlockingDialog(32, 2, title, message, null, button, type, scrollable,
+ false, modal);
+ }
+
+ public void nonBlockingDialog(int width, int height, String title,
+ String message, String boxtext, String button, int type,
+ boolean scrollable, boolean html, boolean modal)
+ {
+ if (type < 0)
+ {
+ type = JvOptionPane.WARNING_MESSAGE;
+ }
+ JLabel jl = new JLabel(message);
+
+ JTextComponent jtc = null;
+ if (html)
+ {
+ JTextPane jtp = new JTextPane();
+ jtp.setContentType("text/html");
+ jtp.setEditable(false);
+ jtp.setAutoscrolls(true);
+ jtp.setText(boxtext);
+
+ jtc = jtp;
+ }
+ else
+ {
+ JTextArea jta = new JTextArea(height, width);
+ // jta.setLineWrap(true);
+ jta.setEditable(false);
+ jta.setWrapStyleWord(true);
+ jta.setAutoscrolls(true);
+ jta.setText(boxtext);
+
+ jtc = jta;
+ }
+
+ JScrollPane jsp = scrollable
+ ? new JScrollPane(jtc, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
+ JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
+ : null;
+
+ JvOptionPane jvp = JvOptionPane.newOptionDialog(this);
+
+ JPanel jp = new JPanel();
+ jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS));
+
+ if (message != null)
+ {
+ jl.setAlignmentX(Component.LEFT_ALIGNMENT);
+ jp.add(jl);
+ }
+ if (boxtext != null)
+ {
+ if (scrollable)
+ {
+ jsp.setAlignmentX(Component.LEFT_ALIGNMENT);
+ jp.add(jsp);
+ }
+ else
+ {
+ jtc.setAlignmentX(Component.LEFT_ALIGNMENT);
+ jp.add(jtc);
+ }
+ }
+
+ jvp.setResponseHandler(JOptionPane.YES_OPTION, () -> {
+ });
+ jvp.showDialogOnTopAsync(this, jp, title, JOptionPane.YES_OPTION, type,
+ null, new Object[]
+ { button }, button, modal, null, false);
+ }
+
}
JvOptionPane.frameDialog(panel, title, JvOptionPane.PLAIN_MESSAGE,
options, ok, actions, false);
- */
+ */
}
}
}
} catch (Exception ex)
{
- System.out.println("Error loading User Colour File\n" + ex);
+ jalview.bin.Console.outPrintln("Error loading User Colour File\n" + ex);
}
}
{
Color newColor = gcol.getMaxColour();
comp.setBackground(newColor);
- // System.err.println("Width is " + w / 2);
+ // jalview.bin.Console.errPrintln("Width is " + w / 2);
Icon ficon = new FeatureIcon(gcol, comp.getBackground(), w, h, thr);
comp.setIcon(ficon);
// tt+="RGB value: Max (" + newColor.getRed() + ", "
{
if (featureSettings != null)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"IMPLEMENTATION ISSUE: overwriting action listener for FeatureColourChooser");
}
featureSettings = listener;
hb.setCurrentID(id.getId());
} catch (BadIDException bad)
{
- System.out.println("Bad help link: " + id.getId()
+ jalview.bin.Console.outPrintln("Bad help link: " + id.getId()
+ ": must match a target in help.jhm");
throw bad;
}
import java.awt.BorderLayout;
import java.awt.Color;
+import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
gg.translate(0, transY);
- drawIds(gg, av, ss, es, searchResults);
+ drawIds(gg, av, ss, es, searchResults,true);
gg.translate(0, -transY);
gg.fillRect(0, 0, getWidth(), imgHeight);
drawIds(gg, av, av.getRanges().getStartSeq(),
- av.getRanges().getEndSeq(), searchResults);
+ av.getRanges().getEndSeq(), searchResults,true);
gg.dispose();
* @param selection
*/
void drawIds(Graphics2D g, AlignViewport alignViewport,
- final int startSeq, final int endSeq, List<SequenceI> selection)
+ final int startSeq, final int endSeq, List<SequenceI> selection, boolean forGUI)
{
Font font = alignViewport.getFont();
if (alignViewport.isSeqNameItalics())
void drawIdsWrapped(Graphics2D g, AlignViewport alignViewport,
int startSeq, int pageHeight)
{
+ drawIdsWrapped(g, alignViewport, startSeq, pageHeight, -1, true);
+ }
+
+ /**
+ * render sequence IDs and annotation labels when wrapped - without GUI junk
+ * @param g
+ * @param av2
+ * @param i
+ * @param totalHeight
+ */
+ public void drawIdsWrappedNoGUI(Graphics2D g, AlignViewport av2, int i,
+ int totalHeight)
+ {
+ drawIdsWrapped(g, av2, totalHeight, totalHeight, i,false);
+ }
+
+ void drawIdsWrapped(Graphics2D g, AlignViewport alignViewport,
+ int startSeq, int pageHeight, int idWidth, boolean forGUI)
+ {
int alignmentWidth = alignViewport.getAlignment().getWidth();
final int alheight = alignViewport.getAlignment().getHeight();
if (labels != null && alignViewport.isShowAnnotation())
{
+ int getWidth = getWidth();
+ int thisIdWidth = getWidth;
g.translate(0, ypos + (alheight * charHeight));
- labels.drawComponent(g, getWidth());
+ if (!manuallyAdjusted())
+ {
+ int getAnnotationsIdWidth = labels.drawLabels(g, false, -1, false,forGUI,
+ null);
+ thisIdWidth = idWidth < 0 ? getAnnotationsIdWidth : idWidth;
+ if (thisIdWidth > getWidth)
+ {
+ this.setPreferredSize(
+ new Dimension(thisIdWidth, this.getHeight()));
+ this.repaint();
+ alignViewport.setIdWidth(thisIdWidth);
+ }
+ }
+ labels.drawComponent(g, false, thisIdWidth, forGUI);
g.translate(0, -ypos - (alheight * charHeight));
}
repaint();
}
}
+
+ private boolean manuallyAdjusted = false;
+
+ public boolean manuallyAdjusted()
+ {
+ return manuallyAdjusted;
+ }
+
+ public void setManuallyAdjusted(boolean b)
+ {
+ manuallyAdjusted = b;
+ }
+
}
*/
package jalview.gui;
-import jalview.api.AlignViewportI;
-
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import javax.swing.JPanel;
+import jalview.api.AlignViewportI;
+import jalview.bin.Cache;
+
/**
* DOCUMENT ME!
*
return;
}
+ /*
+ * don't allow residue width to be < 1 in wrapped format
+ */
+ if (viewport.getWrapAlignment())
+ {
+ SeqCanvas sc = ap.getSeqPanel().seqCanvas;
+ if (sc != null && sc.getWrappedCanvasWidth(sc.getWidth() - dif) < 1)
+ {
+ return;
+ }
+ }
+
oldX = evt.getX();
/*
{
return;
}
+
+ // TODO JAL-4260 - work out how to trigger recomputation of wrapped pages !
+ int curCol = viewport.getRanges().getStartRes()
+ + viewport.getRanges().getViewportWidth();
+
+ viewport.setIdWidth(newWidth);
+
+ ap.validateAnnotationDimensions(false);
+ if (viewport.getWrapAlignment())
+ {
+ viewport.getRanges().scrollToWrappedVisible(
+ curCol - viewport.getRanges().getViewportWidth());
+ }
+ ap.paintAlignment(true, false);
+
+ ap.getIdPanel().getIdCanvas().setManuallyAdjusted(true);
+ }
+
+ public void setWidth(int newWidth)
+ {
+ if (newWidth < MIN_ID_WIDTH
+ || ap.getIdPanel().getIdCanvas().manuallyAdjusted())
+ {
+ return;
+ }
+ final AlignViewportI viewport = ap.getAlignViewport();
viewport.setIdWidth(newWidth);
ap.paintAlignment(true, false);
}
+ public boolean manuallyAdjusted()
+ {
+ return ap.getIdPanel().getIdCanvas().manuallyAdjusted();
+ }
+
@Override
public void mouseMoved(MouseEvent evt)
{
@Override
public void paintComponent(Graphics g)
{
+ int width = getWidth();
+ int height = getHeight();
g.setColor(Color.white);
- g.fillRect(0, 0, getWidth(), getHeight());
+ g.fillRect(0, 0, width, height);
+
+ if (!Cache.getDefault(AnnotationLabels.RESIZE_MARGINS_MARK_PREF, false))
+ // && !ap.getAlignViewport().getWrapAlignment()) // now allowing adjustment
+ // in wrap mode
+ {
+ int spacer = Math.max(2, AnnotationLabels.HEIGHT_ADJUSTER_HEIGHT / 4);
+ g.setColor(Color.LIGHT_GRAY);
+ g.drawLine(width - 3 * spacer, 0, width - 3 * spacer, height / 2);
+ g.drawLine(width - spacer, 0, width - spacer, height / 2);
+ }
+
setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR));
}
}
import jalview.util.ImageMaker.TYPE;
import jalview.util.MessageManager;
import jalview.util.Platform;
+import jalview.util.StringUtils;
import jalview.util.imagemaker.BitmapImageSizing;
/**
String imageSource) throws ImageOutputException
{
doExport(file, parent, width, height, imageSource, null,
- BitmapImageSizing.nullBitmapImageSizing());
+ BitmapImageSizing.defaultBitmapImageSizing());
}
public void doExport(File file, Component parent, int width, int height,
- String imageSource, String renderer, BitmapImageSizing userBis) throws ImageOutputException
+ String imageSource, String renderer, BitmapImageSizing userBis)
+ throws ImageOutputException
{
final long messageId = System.currentTimeMillis();
setStatus(
{
if (Desktop.instance.isInBatchMode())
{
- // defensive error report - we could wait for user input.. I guess ?
- throw(new ImageOutputException("Need an output file to render to when exporting images in batch mode!"));
+ // defensive error report - we could wait for user input.. I guess ?
+ throw (new ImageOutputException(
+ "Need an output file to render to when exporting images in batch mode!"));
}
JalviewFileChooser chooser = imageType.getFileChooser();
chooser.setFileView(new JalviewFileView());
renderStyle = "Text";
}
AtomicBoolean textSelected = new AtomicBoolean(
- !"Lineart".equals(renderStyle));
- if ((imageType == TYPE.EPS || imageType == TYPE.SVG)
- && LineartOptions.PROMPT_EACH_TIME.equals(renderStyle)
+ !StringUtils.equalsIgnoreCase("lineart", renderStyle));
+ if ((imageType == TYPE.EPS || imageType == TYPE.SVG) && StringUtils
+ .equalsIgnoreCase(LineartOptions.PROMPT_EACH_TIME, renderStyle)
&& !Jalview.isHeadlessMode())
{
final File chosenFile = file;
else
{
/*
- * character rendering not required, or preference already set
- * - just do the export
+ * character rendering not required, or preference already set
+ * or we're in headless mode - just do the export
*/
exportImage(file, !textSelected.get(), width, height, messageId,
userBis);
messageId);
} catch (Exception e)
{
- jalview.bin.Console.error(String.format("Error creating %s file: %s", type,
- e.toString()),e);
+ jalview.bin.Console.error(String.format("Error creating %s file: %s",
+ type, e.toString()), e);
setStatus(MessageManager.formatMessage("info.error_creating_file",
type), messageId);
}
}
else
{
- System.err.println("dupe ig for : " + dbs[i] + " \t"
+ jalview.bin.Console.errPrintln("dupe ig for : " + dbs[i] + " \t"
+ dbp.getDbName() + " (" + dbp.getDbSource() + ")");
source.remove(tn);
}
@Override
public void setVisible(boolean arg0)
{
- System.out.println("setVisible: " + arg0);
+ jalview.bin.Console.outPrintln("setVisible: " + arg0);
super.setVisible(arg0);
}
}
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
+import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionAdapter;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
+import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLayeredPane;
+import javax.swing.JMenu;
+import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
+import javax.swing.JRootPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.InternalFrameEvent;
private static void outputMessage(Object message)
{
- System.out.println(">>> JOption Message : " + message.toString());
+ jalview.bin.Console
+ .outPrintln(">>> JOption Message : " + message.toString());
}
public static Object getMockResponse()
if (parentComponent != this
&& !(parentComponent == null && Desktop.instance == null))
{
+ // note the parent goes back to a JRootPane so is probably
+ // Desktop.getDesktop()
JInternalFrame jif = this.createInternalFrame(
parentComponent != null ? parentComponent : Desktop.instance,
title);
+ // connect to the alignFrame using a map in Desktop
+ if (parentComponent instanceof AlignFrame)
+ {
+ Desktop.addModal((AlignFrame) parentComponent, jif);
+ }
jif.setFrameIcon(null);
jif.addInternalFrameListener(new InternalFrameListener()
{
private void internalDialogHandleResponse()
{
- String responseString = (String) this.getValue();
+ Object value = this.getValue();
+ if (value == null
+ || (value instanceof Integer && (Integer) value == -1))
+ {
+ return;
+ }
+ String responseString = value.toString();
int response = ourOptions.indexOf(responseString);
if (!Platform.isJS())
int JOPTIONPANE_MESSAGETYPE, Icon icon, Object[] options,
Object initialValue, boolean modal, JButton[] buttons)
{
+ showDialogOnTopAsync(dialogParent, label, actionString,
+ JOPTIONPANE_OPTION, JOPTIONPANE_MESSAGETYPE, icon, options,
+ initialValue, modal, buttons, true);
+ }
+
+ public void showDialogOnTopAsync(JFrame dialogParent, Object label,
+ String actionString, int JOPTIONPANE_OPTION,
+ int JOPTIONPANE_MESSAGETYPE, Icon icon, Object[] options,
+ Object initialValue, boolean modal, JButton[] buttons,
+ boolean dispose)
+ {
if (!isInteractiveMode())
{
handleResponse(getMockResponse());
JOPTIONPANE_MESSAGETYPE, icon, options, initialValue, modal,
buttons);
- dialogParent.setAlwaysOnTop(false);
- dialogParent.dispose();
+ if (dispose)
+ {
+ dialogParent.setAlwaysOnTop(false);
+ dialogParent.dispose();
+ }
}
/**
lp.add(modalInterceptor);
f.toFront();
+ // disable the main menu bar if in Linux
+ JMenuBar menubar = null;
+ if (Platform.isLinux())
+ {
+ JRootPane rootpane = Desktop.getDesktop().getRootPane();
+ menubar = rootpane.getJMenuBar();
+ }
+
// We need to explicitly dispatch events when we are blocking the event
// dispatch thread.
EventQueue queue = Toolkit.getDefaultToolkit().getSystemEventQueue();
try
{
+ if (menubar != null)
+ {
+ // don't allow clicks on main menu on linux due to a hanging bug.
+ // see JAL-4214.
+ setMenusEnabled(menubar, false);
+ }
+
while (!f.isClosed())
{
if (EventQueue.isDispatchThread())
// EventQueue.dispatchEvent() directly, because it is
// protected, unfortunately.
if (ev instanceof ActiveEvent)
+ {
((ActiveEvent) ev).dispatch();
- else if (ev.getSource() instanceof Component)
+ }
+ else if (ev instanceof KeyEvent && ((KeyEvent) ev).isControlDown()
+ && menubar != null)
+ {
+ // temporarily enable menus to send Ctrl+? KeyEvents
+ setMenusEnabled(menubar, true);
((Component) ev.getSource()).dispatchEvent(ev);
+ setMenusEnabled(menubar, false);
+ }
else if (ev.getSource() instanceof MenuComponent)
+ {
((MenuComponent) ev.getSource()).dispatchEvent(ev);
+ }
+ else if (ev.getSource() instanceof Component)
+ {
+ ((Component) ev.getSource()).dispatchEvent(ev);
+ }
// Other events are ignored as per spec in
// EventQueue.dispatchEvent
}
// If we get interrupted, then leave the modal state.
} finally
{
+ // re-enable the main menu bar
+ if (menubar != null)
+ {
+ setMenusEnabled(menubar, true);
+ }
+
// Clean up the modal interceptor.
lp.remove(modalInterceptor);
+ // unpaint the frame
+ f.setVisible(false);
+
+ // close the frame
+ try
+ {
+ f.setClosed(true);
+ } catch (PropertyVetoException e)
+ {
+ f.doDefaultCloseAction();
+ }
+
// Remove the internal frame from its parent, so it is no longer
// lurking around and clogging memory.
Container parent = f.getParent();
if (parent != null)
+ {
parent.remove(f);
+ }
}
}
return jvop;
}
+
+ private static void setMenusEnabled(JMenuBar menubar, boolean b)
+ {
+ for (int i = 0; i < menubar.getMenuCount(); i++)
+ {
+ JMenu menu = menubar.getMenu(i);
+ menu.setEnabled(b);
+ }
+ }
+
}
}
} catch (NumberFormatException e)
{
- System.err.println(e.toString());
+ jalview.bin.Console.errPrintln(e.toString());
}
if (minValue != null || maxValue != null)
{
}
} catch (NumberFormatException e)
{
- System.err.println(e.toString());
+ jalview.bin.Console.errPrintln(e.toString());
}
if (minValue != null && maxValue != null)
{
{
// raise an implementation warning here - not sure if this situation
// will ever occur
- System.err.println(
+ jalview.bin.Console.errPrintln(
"IMPLEMENTATION PROBLEM: DATASET out of sync due to an insert whilst calling PaintRefresher.validateSequences(AlignmentI, ALignmentI)");
}
List<SequenceI> alsq = comp.getSequences();
if (!first)
{
- System.out.println(DASHES);
+ jalview.bin.Console.outPrintln(DASHES);
textarea.append(DASHES);
}
first = false;
for (int i = 0; i < seqs.length; i++)
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
String.format("%3d %s", i + 1, seqs[i].getDisplayId(true)));
}
{
System.out.print(String.format("%7d", i + 1));
}
- System.out.println();
+ jalview.bin.Console.outPrintln();
for (int i = 0; i < seqs.length; i++)
{
*/
System.out.print(String.format("%7.3f", scores[i][j] / totscore));
}
- System.out.println();
+ jalview.bin.Console.outPrintln();
}
- System.out.println("\n");
+ jalview.bin.Console.outPrintln("\n");
}
/**
if (Platform.isJS())
{
details = new JInternalFrame();
+ details.setFrameIcon(null);
JPanel panel = new JPanel(new BorderLayout());
panel.setOpaque(true);
panel.setBackground(Color.white);
pane.setBackground(Color.WHITE);
pane.add(textLabel, BorderLayout.NORTH);
frame = new JInternalFrame();
+ frame.setFrameIcon(null);
frame.getContentPane().add(new JScrollPane(pane));
}
else
String[] omitHidden = null;
- System.out.println("PROMPT USER HERE"); // TODO: decide if a prompt happens
+ jalview.bin.Console.outPrintln("PROMPT USER HERE"); // TODO: decide if a prompt happens
// or we simply trust the user wants
// wysiwig behaviour
final JPanel progressPanel = progressBars.get(id);
if (progressPanel == null)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"call setProgressBar before registering the progress bar's handler.");
return;
}
protected List<String> executeCommand(StructureCommandI command,
boolean getReply)
{
- // System.out.println(command.toString()); // debug
+ // jalview.bin.Console.outPrintln(command.toString()); // debug
return pymolManager.sendCommand(command, getReply);
}
validate();
sliderValueChanged();
- // System.out.println((System.currentTimeMillis()-start));
+ // jalview.bin.Console.outPrintln((System.currentTimeMillis()-start));
}
void sliderValueChanged()
.newInstance());
} catch (Throwable x)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Unexpected exception when instantiating rest input type.");
x.printStackTrace();
}
updated = true;
} catch (InvalidArgumentException ex)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"IMPLEMENTATION ERROR: Invalid argument for type : "
+ typeList.getSelectedValue() + "\n");
ex.printStackTrace();
types.add(jtype.getURLtokenPrefix());
} catch (Throwable x)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Unexpected exception when instantiating rest input type.");
x.printStackTrace();
}
mtch.group(2) + ":" + mtch.group(3), mtch.group(1),
mtch.group(2), mtch.group(3), inputTypes, warnings))
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"IMPLEMENTATION PROBLEM: Cannot parse RestService input parameter string '"
+ its + "'" + "\n" + warnings);
}
} catch (Throwable x)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"IMPLEMENTATION PROBLEM: Cannot parse RestService output parameter string '"
+ its + "'" + "\n" + warnings);
}
}
else
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"IMPLEMENTATION PROBLEM: Restservice generated from GUI is invalid\n"
+ warnings);
import javax.swing.JPanel;
+import jalview.api.SequenceRenderer;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.HiddenColumns;
import jalview.datamodel.SearchResultsI;
{
this.av = ap.av;
fr = new FeatureRenderer(ap);
- seqRdr = new SequenceRenderer(av);
+ seqRdr = new jalview.gui.SequenceRenderer(av);
setLayout(new BorderLayout());
PaintRefresher.Register(this, av.getSequenceSetId());
setBackground(Color.white);
}
}
- // System.err.println(">>> FastPaint to " + transX + " " + transY + " "
+ // jalview.bin.Console.errPrintln(">>> FastPaint to " + transX + " " + transY + " "
// + horizontal + " " + vertical + " " + startRes + " " + endRes
// + " " + startSeq + " " + endSeq);
/** @j2sNative xxi = this.img */
gg.translate(transX, transY);
- drawPanel(gg, startRes, endRes, startSeq, endSeq, 0);
+ drawPanel(seqRdr, gg, startRes, endRes, startSeq, endSeq, 0);
gg.translate(-transX, -transY);
gg.dispose();
// 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...");
+ // jalview.bin.Console.outPrintln("SeqCanvas fastPaint() repaint() request...");
av.getAlignPanel().repaint();
} finally
{
if (av.getWrapAlignment())
{
- drawWrappedPanel(gg, getWidth(), getHeight(), ranges.getStartRes());
+ drawWrappedPanel(seqRdr, gg, getWidth(), getHeight(), ranges.getStartRes());
}
else
{
- drawPanel(gg, startRes, endRes, startSeq, endSeq, 0);
+ drawPanel(seqRdr,gg, startRes, endRes, startSeq, endSeq, 0);
}
drawSelectionGroup(gg, startRes, endRes, startSeq, endSeq);
public void drawPanelForPrinting(Graphics g1, int startRes, int endRes,
int startSeq, int endSeq)
{
- drawPanel(g1, startRes, endRes, startSeq, endSeq, 0);
+ SequenceRenderer localSeqR = new jalview.gui.SequenceRenderer(av);
+ drawPanel(localSeqR,g1, startRes, endRes, startSeq, endSeq, 0);
drawSelectionGroup((Graphics2D) g1, startRes, endRes, startSeq, endSeq);
}
public void drawWrappedPanelForPrinting(Graphics g, int canvasWidth,
int canvasHeight, int startRes)
{
- drawWrappedPanel(g, canvasWidth, canvasHeight, startRes);
+ SequenceRenderer localSeqR = new jalview.gui.SequenceRenderer(av);
+ drawWrappedPanel(localSeqR, g, canvasWidth, canvasHeight, startRes);
SequenceGroup group = av.getSelectionGroup();
if (group != null)
return (canvasWidth - labelWidthEast - labelWidthWest) / charWidth;
}
+ public int getMinimumWrappedCanvasWidth()
+ {
+ int charWidth = av.getCharWidth();
+ FontMetrics fm = getFontMetrics(av.getFont());
+ int labelWidth = 0;
+ if (av.getScaleRightWrapped() || av.getScaleLeftWrapped())
+ {
+ labelWidth = getLabelWidth(fm);
+ }
+ labelWidthEast = av.getScaleRightWrapped() ? labelWidth : 0;
+ labelWidthWest = av.getScaleLeftWrapped() ? labelWidth : 0;
+ return labelWidthEast + labelWidthWest + charWidth;
+ }
+
/**
* Returns a pixel width sufficient to show the largest sequence coordinate
* (end position) in the alignment, calculated as the FontMetrics width of
* @param startColumn
* the first column (0...) of the alignment to draw
*/
- public void drawWrappedPanel(Graphics g, int canvasWidth,
+ public void drawWrappedPanel(SequenceRenderer seqRdr, Graphics g, int canvasWidth,
int canvasHeight, final int startColumn)
{
int wrappedWidthInResidues = calculateWrappedGeometry(canvasWidth,
{
int endColumn = Math.min(maxWidth,
start + wrappedWidthInResidues - 1);
- drawWrappedWidth(g, ypos, start, endColumn, canvasHeight);
+ drawWrappedWidth(seqRdr, g, ypos, start, endColumn, canvasHeight);
ypos += wrappedRepeatHeightPx;
start += wrappedWidthInResidues;
currentWidth++;
* @param endColumn
* @param canvasHeight
*/
- protected void drawWrappedWidth(Graphics g, final int ypos,
+ protected void drawWrappedWidth(SequenceRenderer seqRdr, Graphics g, final int ypos,
final int startColumn, final int endColumn,
final int canvasHeight)
{
g.fillRect(0, ypos, (endx - startColumn + 1) * charWidth,
wrappedRepeatHeightPx);
- drawPanel(g, startColumn, endx, 0, av.getAlignment().getHeight() - 1,
+ drawPanel(seqRdr, g, startColumn, endx, 0, av.getAlignment().getHeight() - 1,
ypos);
int cHeight = av.getAlignment().getHeight() * av.getCharHeight();
* are hidden column markers in the visible region, then each sub-region
* between the markers is drawn separately, followed by the hidden column
* marker.
+ * @param localSeqR - sequence renderer implementation - when null, uses the one used for rendering interactive GUI
*
* @param g1
* the graphics context, positioned at the first residue to be drawn
* @param yOffset
* vertical offset at which to draw (for wrapped alignments)
*/
- public void drawPanel(Graphics g1, final int startRes, final int endRes,
+ public void drawPanel(SequenceRenderer localSeqR, Graphics g1, final int startRes, final int endRes,
final int startSeq, final int endSeq, final int yOffset)
{
int charHeight = av.getCharHeight();
int charWidth = av.getCharWidth();
+ if (localSeqR==null)
+ {
+ localSeqR = seqRdr;
+ }
if (!av.hasHiddenColumns())
{
- draw(g1, startRes, endRes, startSeq, endSeq, yOffset);
+ draw(localSeqR, g1, startRes, endRes, startSeq, endSeq, yOffset);
}
else
{
*/
g1.translate(screenY * charWidth, 0);
- draw(g1, blockStart, blockEnd, startSeq, endSeq, yOffset);
+ draw(localSeqR, g1, blockStart, blockEnd, startSeq, endSeq, yOffset);
/*
* draw the downline of the hidden column marker (ScalePanel draws the
/**
* Draws a region of the visible alignment
+ * @param seqRdr
*
* @param g1
* @param startRes
* @param yOffset
* vertical offset at which to draw (for wrapped alignments)
*/
- private void draw(Graphics g, int startRes, int endRes, int startSeq,
+ private void draw(SequenceRenderer seqRdr, Graphics g, int startRes, int endRes, int startSeq,
int endSeq, int offset)
{
int charHeight = av.getCharHeight();
}
else if (inGroup)
{
- drawVerticals(g, sx, xwidth, visWidth, oldY, sy);
- drawHorizontals(g, sx, xwidth, visWidth, top, bottom);
+ drawVerticals(g, sx, xwidth, visWidth, oldY, bottom);
+ drawHorizontals(g, sx, xwidth, visWidth, top, bottom+1);
// reset top and bottom
top = -1;
if (inGroup)
{
sy = verticalOffset + ((i - startSeq) * charHeight);
- drawVerticals(g, sx, xwidth, visWidth, oldY, sy);
- drawHorizontals(g, sx, xwidth, visWidth, top, bottom);
+ drawVerticals(g, sx, xwidth, visWidth, oldY, bottom);
+ drawHorizontals(g, sx, xwidth, visWidth, top, bottom+1);
}
}
}
int transY = (firstSeq - ranges.getStartSeq()) * av.getCharHeight();
Graphics gg = img.getGraphics();
gg.translate(transX, transY);
- drawPanel(gg, firstCol, lastCol, firstSeq, lastSeq, 0);
+ drawPanel(seqRdr, gg, firstCol, lastCol, firstSeq, lastSeq, 0);
gg.translate(-transX, -transY);
gg.dispose();
}
public void propertyChange(PropertyChangeEvent evt)
{
String eventName = evt.getPropertyName();
- // System.err.println(">>SeqCanvas propertyChange " + eventName);
+ // jalview.bin.Console.errPrintln(">>SeqCanvas propertyChange " + eventName);
if (eventName.equals(SequenceGroup.SEQ_GROUP_CHANGED))
{
fastPaint = true;
else if (eventName.equals(ViewportRanges.MOVE_VIEWPORT))
{
fastPaint = false;
- // System.err.println("!!!! fastPaint false from MOVE_VIEWPORT");
+ // jalview.bin.Console.errPrintln("!!!! fastPaint false from MOVE_VIEWPORT");
repaint();
return;
}
if (scrollX < 0)
{
int startRes = ranges.getStartRes();
- drawWrappedWidth(gg, wrappedSpaceAboveAlignment, startRes,
+ drawWrappedWidth(seqRdr,gg, wrappedSpaceAboveAlignment, startRes,
startRes - scrollX - 1, getHeight());
}
else
wrappedRepeatHeightPx);
gg.translate(-xOffset, 0);
- drawWrappedWidth(gg, ypos, startRes, endRes, canvasHeight);
+ drawWrappedWidth(seqRdr, gg, ypos, startRes, endRes, canvasHeight);
}
if (startRes < ranges.getVisibleAlignmentWidth())
{
- drawWrappedWidth(gg, ypos, startRes, endRes, canvasHeight);
+ drawWrappedWidth(seqRdr, gg, ypos, startRes, endRes, canvasHeight);
}
/*
{
matchFound = true;
gg.translate(transX, transY);
- drawPanel(gg, displayColumn, displayColumn, seqNo, seqNo,
+ drawPanel(seqRdr,gg, displayColumn, displayColumn, seqNo, seqNo,
yOffset);
gg.translate(-transX, -transY);
}
} catch (OutOfMemoryError er)
{
System.gc();
- System.err.println("SeqCanvas OutOfMemory Redraw Error.\n" + er);
+ jalview.bin.Console.errPrintln("SeqCanvas OutOfMemory Redraw Error.\n" + er);
new OOMWarning("Creating alignment image for display", er);
return;
MousePos o = (MousePos) obj;
boolean b = (column == o.column && seqIndex == o.seqIndex
&& annotationIndex == o.annotationIndex);
- // System.out.println(obj + (b ? "= " : "!= ") + this);
+ // jalview.bin.Console.outPrintln(obj + (b ? "= " : "!= ") + this);
return b;
}
if (lastMessage == null || !lastMessage.equals(tmp))
{
- // System.err.println("mouseOver Sequence: "+tmp);
+ // jalview.bin.Console.errPrintln("mouseOver Sequence: "+tmp);
ssm.mouseOverSequence(sequence, index, pos, av);
}
lastMessage = tmp;
@Override
public void updateColours(SequenceI seq, int index)
{
- System.out.println("update the seqPanel colours");
+ jalview.bin.Console.outPrintln("update the seqPanel colours");
// repaint();
}
if (copycolsel && av.hasHiddenColumns()
&& (av.getAlignment().getHiddenColumns() == null))
{
- System.err.println("Bad things");
+ jalview.bin.Console.errPrintln("Bad things");
}
if (repaint) // always true!
{
+ ((StringPair) database.getSelectedItem()).getDisplay());
// error
// +="Couldn't retrieve sequences from "+database.getSelectedItem();
- System.err.println("Retrieval failed for source ='"
+ jalview.bin.Console.errPrintln("Retrieval failed for source ='"
+ ((StringPair) database.getSelectedItem()).getDisplay()
+ "' and query\n'" + textArea.getText() + "'\n");
e.printStackTrace();
* @param b
* DOCUMENT ME!
*/
+ @Override
public void prepare(Graphics g, boolean renderGaps)
{
graphics = g;
}
if (mt.isErrorAny())
{
- System.err.println("Error when loading images!");
+ jalview.bin.Console.errPrintln("Error when loading images!");
}
} while (!mt.checkAll());
Desktop.instance.setIconImages(ChannelProperties.getIconList());
protected boolean refreshText()
{
String newtext = Desktop.instance.getAboutMessage();
- // System.err.println("Text found: \n"+newtext+"\nEnd of newtext.");
+ // jalview.bin.Console.errPrintln("Text found: \n"+newtext+"\nEnd of newtext.");
if (oldTextLength != newtext.length())
{
iframe.setVisible(false);
});
featureSettingsUI = new JInternalFrame(MessageManager.getString(
"label.sequence_feature_settings_for_CDS_and_Protein"));
+ featureSettingsUI.setFrameIcon(null);
featureSettingsPanels.setOpaque(true);
JPanel dialog = new JPanel();
import jalview.gui.structurechooser.StructureChooserQuerySource;
import jalview.gui.structurechooser.ThreeDBStructureChooserQuerySource;
import jalview.io.DataSourceType;
-import jalview.io.FileFormatException;
import jalview.io.JalviewFileChooser;
import jalview.io.JalviewFileView;
import jalview.jbgui.FilterOption;
import jalview.ws.DBRefFetcher;
import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
import jalview.ws.datamodel.alphafold.PAEContactMatrix;
-import jalview.ws.dbsources.EBIAlfaFold;
import jalview.ws.seqfetcher.DbSourceProxy;
import jalview.ws.sifts.SiftsSettings;
List<SequenceI> seqsWithoutSourceDBRef = null;
private boolean showChooserGUI = true;
+ /**
+ * when true, queries to external services are supressed (no SIFTs, no PDBe, no 3D-Beacons, etc)
+ */
+ private boolean dontQueryServices = false;
private static StructureViewer lastTargetedView = null;
public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
AlignmentPanel ap, boolean showGUI)
{
+ this(selectedSeqs, selectedSeq, ap, showGUI, false);
+ }
+
+ public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
+ AlignmentPanel ap, boolean showGUI, boolean dontQueryServices)
+ {
+
// which FTS engine to use
data = StructureChooserQuerySource.getQuerySourceFor(selectedSeqs);
initDialog();
this.selectedSequences = selectedSeqs;
this.progressIndicator = (ap == null) ? null : ap.alignFrame;
this.showChooserGUI = showGUI;
+ this.dontQueryServices = dontQueryServices;
init();
}
}
});
- Executors.defaultThreadFactory().newThread(new Runnable()
+ if (!dontQueryServices)
{
- @Override
- public void run()
+ Executors.defaultThreadFactory().newThread(new Runnable()
{
- populateSeqsWithoutSourceDBRef();
- initialStructureDiscovery();
- }
-
- }).start();
+ @Override
+ public void run()
+ {
+ populateSeqsWithoutSourceDBRef();
+ initialStructureDiscovery();
+ }
+ }).start();
+ } else {
+ Console.debug("Structure chooser not querying services to discover metadata.");
+ }
}
// called by init
}
} catch (Exception e)
{
- e.printStackTrace();
+ Console.printStackTrace(e);
errors.add(e.getMessage());
continue;
}
{
errorMsg.append(error).append("\n");
}
- JvOptionPane.showMessageDialog(this, errorMsg.toString(),
- MessageManager.getString("label.pdb_web-service_error"),
- JvOptionPane.ERROR_MESSAGE);
+ if (!Jalview.isHeadlessMode())
+ {
+ JvOptionPane.showMessageDialog(this, errorMsg.toString(),
+ MessageManager.getString("label.pdb_web-service_error"),
+ JvOptionPane.ERROR_MESSAGE);
+ }
+ else
+ {
+ Console.error(
+ MessageManager.getString("label.pdb_web-service_error"));
+ Console.debug(errorMsg.toString());
+ }
}
}
}
} catch (Exception e)
{
- e.printStackTrace();
+ Console.debugPrintStackTrace(e);
errors.add(e.getMessage());
continue;
}
boolean superimpose = chk_superpose.isSelected();
theViewer.setSuperpose(superimpose);
+ // if we're running in --headless mode make this viewer synchronous
+ if (Jalview.isHeadlessMode())
+ {
+ theViewer.setAsync(false);
+ }
+
/*
* remember user's choice of superimpose or not
*/
// for moment, it will work fine as is because it is self-contained
String searchTerm = text.toLowerCase(Locale.ROOT);
searchTerm = searchTerm.split(":")[0];
- // System.out.println(">>>>> search term : " + searchTerm);
+ // jalview.bin.Console.outPrintln(">>>>> search term : " +
+ // searchTerm);
List<FTSDataColumnI> wantedFields = new ArrayList<>();
FTSRestRequest pdbRequest = new FTSRestRequest();
pdbRequest.setAllowEmptySeq(false);
{
// headless = true;
prompt = false;
- sc = new StructureChooser(new SequenceI[] { seq }, seq, ap, false);
+ // suppress structure viewer's external service queries
+ sc = new StructureChooser(new SequenceI[] { seq }, seq, ap, false,true);
}
if (ssm == null)
{
sc.mainFrame.dispose();
if (showRefAnnotations)
+ {
showReferenceAnnotationsForSequence(ap.alignFrame, seq);
+ }
return sv;
}
package jalview.gui;
import java.util.ArrayList;
+import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
public enum ViewerType
{
- JMOL, CHIMERA, CHIMERAX, PYMOL
+ JMOL, CHIMERA, CHIMERAX, PYMOL;
+
+ public static ViewerType getFromString(String viewerString)
+ {
+ ViewerType viewerType = null;
+ if (!"none".equals(viewerString))
+ {
+ for (ViewerType v : EnumSet.allOf(ViewerType.class))
+ {
+ String name = v.name().toLowerCase(Locale.ROOT).replaceAll(" ",
+ "");
+ if (viewerString.equals(name))
+ {
+ viewerType = v;
+ break;
+ }
+ }
+ }
+ return viewerType;
+ }
+
};
/**
import javax.swing.event.MenuListener;
import jalview.api.AlignmentViewPanel;
+import jalview.api.structures.JalviewStructureDisplayI;
import jalview.bin.Cache;
import jalview.bin.Console;
import jalview.datamodel.AlignmentI;
}
/**
+ * Singleton list of all (open) instances of structureViewerBase
+ * TODO: JAL-3362 - review and adopt the swingJS-safe singleton pattern so each structure viewer base instance is kept to its own JalviewJS parent
+ */
+ private static List<JalviewStructureDisplayI> svbs = new ArrayList<>();
+
+ /**
+ *
+ * @return list with all existing StructureViewers instance
+ */
+ public static List<JalviewStructureDisplayI> getAllStructureViewerBases()
+ {
+ List<JalviewStructureDisplayI> goodSvbs = new ArrayList<>();
+ for (JalviewStructureDisplayI s : svbs)
+ {
+ if (s != null && !goodSvbs.contains(s))
+ {
+ goodSvbs.add(s);
+ }
+ }
+ return goodSvbs;
+ }
+
+ /**
* list of sequenceSet ids associated with the view
*/
protected List<String> _aps = new ArrayList<>();
{
super();
setFrameIcon(null);
+ svbs.add(this);
}
/**
return _aps.contains(ap2.av.getSequenceSetId());
}
+ @Override
public boolean isUsedforaligment(AlignmentViewPanel ap2)
{
}
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Error retrieving PDB id " + pdbid + ": " + e.getMessage());
} finally
{
// TODO: check for memory leaks where instance isn't finalised because jmb
// holds a reference to the window
// jmb = null;
+
+ try {
+ svbs.remove(this);
+ } catch (Throwable t)
+ {
+ Console.info("Unexpected exception when deregistering structure viewer",t);
+ }
dispose();
}
{
if (tree == null)
{
- System.out.println("tree is null");
+ jalview.bin.Console.outPrintln("tree is null");
// TODO: deal with case when a change event is received whilst a
// tree is still being calculated - should save reference for
// processing message later.
}
if (evt.getNewValue() == null)
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"new alignment sequences vector value is null");
}
pg.close();
} catch (Exception ex)
{
- System.err.println("Error writing tree as EPS");
+ jalview.bin.Console.errPrintln("Error writing tree as EPS");
ex.printStackTrace();
}
}
cdoc = null;
} catch (Exception ee)
{
- System.err.println("Exception whilst updating :");
+ jalview.bin.Console.errPrintln("Exception whilst updating :");
ee.printStackTrace(System.err);
// recover object map backup, since its probably corrupted with references
// to Vobjects that don't exist anymore.
// we only care about AlignmentSequence selections
SelectionMessage sm = (SelectionMessage) message;
sm.validate();
- System.err.println("Received\n" + sm.getRawMessage());
+ jalview.bin.Console.errPrintln("Received\n" + sm.getRawMessage());
Object[] jvobjs = sm.getVorbaIDs() == null ? null
: new Object[sm.getVorbaIDs().length];
if (jvobjs == null)
@Override
public void internalFrameClosed(InternalFrameEvent evt)
{
- // System.out.println("Shutting down webservice client");
+ // jalview.bin.Console.outPrintln("Shutting down webservice client");
WSClientI service = thisinfo.getthisService();
if (service != null && service.isCancellable())
{
else
{
// TODO: show warning
- System.err.println("Invalid name. Not saved.");
+ jalview.bin.Console.errPrintln("Invalid name. Not saved.");
}
}
}
else
{
- System.err.println("Ignoring unknown service argument type "
+ jalview.bin.Console.errPrintln("Ignoring unknown service argument type "
+ myarg.getClass().getName());
}
}
{
if (arg instanceof OptionI)
{
- // System.out.println("Setting option "
+ // jalview.bin.Console.outPrintln("Setting option "
// + System.identityHashCode(arg) + ":" + arg.getName()
// + " with " + arg.getDefaultValue());
opanp.selectOption((OptionI) arg, arg.getValue());
if (cw + 120 > panewidth)
{
jobOptions.add(pbox, "wrap");
- // System.out.println("Wrap on "+pbox.option.getName());
+ // jalview.bin.Console.outPrintln("Wrap on "+pbox.option.getName());
cw = hgap + pbox.getSize().width;
fh = true;
}
}
// TODO: waste some time trying to eliminate any unnecessary .validate calls
// here
- // System.out.println("Size will be : "+w+","+os);
+ // jalview.bin.Console.outPrintln("Size will be : "+w+","+os);
// optsAndparams.setPreferredSize(null);
// paramPane.getViewport().setView(optsAndparams);
paramPane.getViewport().setAutoscrolls(true);
disc.run();
} catch (Exception e)
{
- System.err.println("Aborting. Problem discovering services.");
+ jalview.bin.Console.errPrintln("Aborting. Problem discovering services.");
e.printStackTrace();
return;
}
pr = en.next();
}
{
- System.out.println("Testing opts dupes for "
+ jalview.bin.Console.outPrintln("Testing opts dupes for "
+ lastserv.getUri() + " : " + lastserv.getActionText()
+ ":" + pr.getName());
List<Option> rg = lastserv.getRunnerConfig().getOptions();
Option cpy = jalview.ws.jws2.ParameterUtils.copyOption(o);
} catch (Exception e)
{
- System.err.println("Failed to copy " + o.getName());
+ jalview.bin.Console.errPrintln("Failed to copy " + o.getName());
e.printStackTrace();
} catch (Error e)
{
- System.err.println("Failed to copy " + o.getName());
+ jalview.bin.Console.errPrintln("Failed to copy " + o.getName());
e.printStackTrace();
}
}
}
{
- System.out.println("Testing param dupes:");
+ jalview.bin.Console.outPrintln("Testing param dupes:");
List<Parameter> rg = lastserv.getRunnerConfig()
.getParameters();
for (Parameter o : rg)
.copyParameter(o);
} catch (Exception e)
{
- System.err.println("Failed to copy " + o.getName());
+ jalview.bin.Console.errPrintln("Failed to copy " + o.getName());
e.printStackTrace();
} catch (Error e)
{
- System.err.println("Failed to copy " + o.getName());
+ jalview.bin.Console.errPrintln("Failed to copy " + o.getName());
e.printStackTrace();
}
}
}
{
- System.out.println("Testing param write:");
+ jalview.bin.Console.outPrintln("Testing param write:");
List<String> writeparam = null, readparam = null;
try
{
.writeParameterSet(
pr.getArguments(lastserv.getRunnerConfig()),
" ");
- System.out.println("Testing param read :");
+ jalview.bin.Console.outPrintln("Testing param read :");
List<Option> pset = jalview.ws.jws2.ParameterUtils
.processParameters(writeparam,
lastserv.getRunnerConfig(), " ");
String on = o.next(), sn = s.next(), st = t.next();
if (!sn.equals(st))
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Original was " + on + " Phase 1 wrote " + sn
+ "\tPhase 2 wrote " + st);
failed = true;
}
if (failed)
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Original parameters:\n" + pr.getOptions());
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Wrote parameters in first set:\n" + writeparam);
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Wrote parameters in second set:\n" + readparam);
}
* + storeSetName + ": ", jobParams); }
*
* private void writeParam(String nm, List<ArgumentI> params) { for (ArgumentI
- * p : params) { System.out.println(nm + ":" + System.identityHashCode(p) +
+ * p : params) { jalview.bin.Console.outPrintln(nm + ":" + System.identityHashCode(p) +
* " Name: " + p.getName() + " Value: " + p.getDefaultValue()); } }
*
* private Object[] _getUserPreset(String setName) { Object[] pset =
return;
}
settingDialog = true;
- System.out.println("Prompting to save " + lsetname);
+ jalview.bin.Console.outPrintln("Prompting to save " + lsetname);
if (JvOptionPane.showConfirmDialog(this, "Parameter set '" + lsetname
+ "' is modifed, and your changes will be lost.\nReally change preset ?",
"Warning: Unsaved Changes",
settingDialog = false;
// and leave.
return;
- // System.out.println("Saving for " + lsetname);
+ // jalview.bin.Console.outPrintln("Saving for " + lsetname);
// _storeCurrentPreset(lsetname);
}
return;
}
curSetName = newname;
- System.err.println("New name for user setting " + curSetName
+ jalview.bin.Console.errPrintln("New name for user setting " + curSetName
+ " (was " + setName.getSelectedItem() + ")");
if (curSetName.equals(setName.getSelectedItem()))
{
String[] names = seqName.toLowerCase(Locale.ROOT).split("\\|");
for (String name : names)
{
- // System.out.println("Found name : " + name);
+ // jalview.bin.Console.outPrintln("Found name : " + name);
name.trim();
if (isValidSeqName(name))
{
*/
static boolean isValidSeqName(String seqName)
{
- // System.out.println("seqName : " + seqName);
+ // jalview.bin.Console.outPrintln("seqName : " + seqName);
String ignoreList = "pdb,uniprot,swiss-prot";
if (seqName.length() < 3)
{
*/
static boolean isValidSeqName(String seqName)
{
- // System.out.println("seqName : " + seqName);
+ // jalview.bin.Console.outPrintln("seqName : " + seqName);
String ignoreList = "pdb,uniprot,swiss-prot";
if (seqName.length() < 3)
{
int idx = EXP_CATEGORIES.indexOf(upper_cat);
if (idx == -1)
{
- System.out.println("Unknown category: '" + cat + "'");
+ jalview.bin.Console.outPrintln("Unknown category: '" + cat + "'");
EXP_CATEGORIES.add(upper_cat);
idx = EXP_CATEGORIES.size() - 1;
}
{
if (!hasPdbResp)
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Warning: seems like we couldn't get to the PDBe search interface.");
}
else
/*
* Set server error status on response
*/
- System.err.println("Exception handling request "
+ jalview.bin.Console.errPrintln("Exception handling request "
+ request.getRequestURI() + " : " + t.getMessage());
if (response.isCommitted())
{
/*
* Can't write an HTTP header once any response content has been written
*/
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Unable to return HTTP 500 as response already committed");
}
else
*/
protected void dumpRequest(HttpServletRequest request)
{
- System.out.println(request.getMethod());
- System.out.println(request.getRequestURL());
+ jalview.bin.Console.outPrintln(request.getMethod());
+ jalview.bin.Console.outPrintln(request.getRequestURL());
for (String hdr : Collections.list(request.getHeaderNames()))
{
for (String val : Collections.list(request.getHeaders(hdr)))
{
- System.out.println(hdr + ": " + val);
+ jalview.bin.Console.outPrintln(hdr + ": " + val);
}
}
for (String param : Collections.list(request.getParameterNames()))
{
for (String val : request.getParameterValues(param))
{
- System.out.println(param + "=" + val);
+ jalview.bin.Console.outPrintln(param + "=" + val);
}
}
}
stop();
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Error stopping " + getName() + ": " + e.getMessage());
}
}
contextHandlers = new HandlerCollection(true);
server.setHandler(contextHandlers);
server.start();
- // System.out.println(String.format(
+ // jalview.bin.Console.outPrintln(String.format(
// "HttpServer started with %d threads", server.getThreadPool()
// .getThreads()));
contextRoot = server.getURI();
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Error trying to start HttpServer: " + e.getMessage());
try
{
{
for (String val : Collections.list(request.getHeaders(hdr)))
{
- System.out.println(hdr + ": " + val);
+ jalview.bin.Console.outPrintln(hdr + ": " + val);
}
}
for (String param : Collections.list(request.getParameterNames()))
{
for (String val : request.getParameterValues(param))
{
- System.out.println(param + "=" + val);
+ jalview.bin.Console.outPrintln(param + "=" + val);
}
}
}
server.stop();
} catch (Exception e)
{
- System.err.println("Error stopping Http Server on "
+ jalview.bin.Console.errPrintln("Error stopping Http Server on "
+ server.getURI() + ": " + e.getMessage());
}
}
ch.start();
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Error starting handler for " + path + ": " + e.getMessage());
}
handler.setUri(this.contextRoot + ch.getContextPath().substring(1));
- System.out.println("Jalview " + handler.getName()
+ jalview.bin.Console.outPrintln("Jalview " + handler.getName()
+ " handler started on " + handler.getUri());
}
{
contextHandlers.removeHandler(ch);
myHandlers.remove(handler);
- System.out.println("Stopped Jalview " + handler.getName()
+ jalview.bin.Console.outPrintln("Stopped Jalview " + handler.getName()
+ " handler on " + handler.getUri());
}
}
}
else
{
- // System.err.println("Skipping NaN - not valid value.");
+ // jalview.bin.Console.errPrintln("Skipping NaN - not valid value.");
text.append(comma + 0f);// row.annotations[j].value);
}
comma = ",";
} catch (Exception ex)
{
ex.printStackTrace();
- System.out.println("Problem reading annotation file: " + ex);
+ jalview.bin.Console.outPrintln("Problem reading annotation file: " + ex);
if (nlinesread > 0)
{
- System.out.println("Last read line " + nlinesread + ": '" + lastread
+ jalview.bin.Console.outPrintln("Last read line " + nlinesread + ": '" + lastread
+ "' (first 80 chars) ...");
}
return false;
if (refSeqIndex < 1)
{
refSeqIndex = 1;
- System.out.println(
+ jalview.bin.Console.outPrintln(
"WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
}
} catch (Exception ex)
{
if (hidden == null)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
+ line);
}
{
// TODO: specify and implement duplication of alignment annotation
// for multiple group references.
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Ignoring 1:many group reference mappings for group name '"
+ groupRef + "'");
}
}
else
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Couldn't combine annotations. None are added to alignment yet!");
}
}
value = Float.valueOf(nextToken);
} catch (NumberFormatException e)
{
- System.err.println("line " + nlinesread + ": Threshold '" + nextToken
+ jalview.bin.Console.errPrintln("line " + nlinesread + ": Threshold '" + nextToken
+ "' invalid, setting to zero");
}
String label = st.hasMoreTokens() ? st.nextToken() : null;
}
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
+ rng + "' - assuming alignment width for group.");
// assume group is full width
} catch (Exception e)
{
e.printStackTrace();
- System.err.println("Failed to read alignment using the '" + fileFormat
+ jalview.bin.Console.errPrintln("Failed to read alignment using the '" + fileFormat
+ "' reader.\n" + e);
if (e.getMessage() != null
} catch (Exception e)
{
e.printStackTrace();
- System.err.println("Failed to read alignment using the '" + format
+ jalview.bin.Console.errPrintln("Failed to read alignment using the '" + format
+ "' reader.\n" + e);
if (e.getMessage() != null
String afileresp = afile.print(seqs, jvsuffix);
if (afile.hasWarningMessage())
{
- System.err.println("Warning raised when writing as " + format
+ jalview.bin.Console.errPrintln("Warning raised when writing as " + format
+ " : " + afile.getWarningMessage());
}
return afileresp;
} catch (Exception e)
{
- System.err.println("Failed to write alignment as a '"
+ jalview.bin.Console.errPrintln("Failed to write alignment as a '"
+ format.getName() + "' file\n");
e.printStackTrace();
}
{
try
{
- System.out.println("Reading file: " + f);
+ jalview.bin.Console.outPrintln("Reading file: " + f);
AppletFormatAdapter afa = new AppletFormatAdapter();
Runtime r = Runtime.getRuntime();
System.gc();
memf += r.totalMemory() - r.freeMemory();
if (al != null)
{
- System.out.println("Alignment contains " + al.getHeight()
+ jalview.bin.Console.outPrintln("Alignment contains " + al.getHeight()
+ " sequences and " + al.getWidth() + " columns.");
try
{
- System.out.println(new AppletFormatAdapter()
+ jalview.bin.Console.outPrintln(new AppletFormatAdapter()
.formatSequences(FileFormat.Fasta, al, true));
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Couln't format the alignment for output as a FASTA file.");
e.printStackTrace(System.err);
}
}
else
{
- System.out.println("Couldn't read alignment");
+ jalview.bin.Console.outPrintln("Couldn't read alignment");
}
- System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
- System.out.println(
+ jalview.bin.Console.outPrintln("Read took " + (t1 / 1000.0) + " seconds.");
+ jalview.bin.Console.outPrintln(
"Difference between free memory now and before is "
+ (memf / (1024.0 * 1024.0) * 1.0) + " MB");
} catch (Exception e)
{
- System.err.println("Exception when dealing with " + i
+ jalview.bin.Console.errPrintln("Exception when dealing with " + i
+ "'th argument: " + args[i] + "\n" + e);
}
}
else
{
- System.err.println("Ignoring argument '" + args[i] + "' (" + i
+ jalview.bin.Console.errPrintln("Ignoring argument '" + args[i] + "' (" + i
+ "'th)- not a readable file.");
}
i++;
DataSourceType protocol = null;
if (debug)
{
- System.out.println("resolving datasource started with:\n>>file\n"
+ jalview.bin.Console.outPrintln("resolving datasource started with:\n>>file\n"
+ file + ">>endfile");
}
}
if (debug)
{
- System.err.println("Resource '" + file + "' was "
+ jalview.bin.Console.errPrintln("Resource '" + file + "' was "
+ (rtn ? "" : "not") + " located by classloader.");
}
if (rtn)
{
if (debug)
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Trying to get contents of resource as " + protocol + ":");
}
fp = new FileParse(file, protocol);
{
if (debug)
{
- System.out.println("Successful.");
+ jalview.bin.Console.outPrintln("Successful.");
}
}
} catch (Exception e)
{
if (debug)
{
- System.err.println("Exception when accessing content: " + e);
+ jalview.bin.Console.errPrintln("Exception when accessing content: " + e);
}
fp = null;
}
{
if (debug)
{
- System.out.println("Accessing as paste.");
+ jalview.bin.Console.outPrintln("Accessing as paste.");
}
protocol = DataSourceType.PASTE;
fp = null;
}
} catch (Exception e)
{
- System.err.println("Failed to access content as paste!");
+ jalview.bin.Console.errPrintln("Failed to access content as paste!");
e.printStackTrace();
fp = null;
}
{
if (debug)
{
- System.out.println("Format not identified. Inaccessible file.");
+ jalview.bin.Console.outPrintln("Format not identified. Inaccessible file.");
}
return null;
}
if (debug)
{
- System.out.println("Format identified as " + idformat
+ jalview.bin.Console.outPrintln("Format identified as " + idformat
+ "and expected as " + format);
}
if (idformat.equals(format))
{
if (debug)
{
- System.out.println("Protocol identified as " + protocol);
+ jalview.bin.Console.outPrintln("Protocol identified as " + protocol);
}
return protocol;
}
{
if (debug)
{
- System.err.println("File deemed not accessible via " + protocol);
+ jalview.bin.Console.errPrintln("File deemed not accessible via " + protocol);
e.printStackTrace();
}
}
}
} catch (IOException e)
{
- System.out.println("IOException when checking file '" + filename
+ jalview.bin.Console.outPrintln("IOException when checking file '" + filename
+ "' is a backupfile");
}
{
if (!biojsDirectory.mkdirs())
{
- System.out.println("Couldn't create local directory : "
+ jalview.bin.Console.outPrintln("Couldn't create local directory : "
+ BJS_TEMPLATES_LOCAL_DIRECTORY);
return;
}
} catch (OutOfMemoryError err)
{
- System.out.println("########################\n" + "OUT OF MEMORY "
+ jalview.bin.Console.outPrintln("########################\n" + "OUT OF MEMORY "
+ generatedFile + "\n" + "########################");
new OOMWarning("Creating Image for " + generatedFile, err);
} catch (Exception e)
}
} catch (IOException e)
{
- System.err.println("Exception parsing clustal file " + e);
+ jalview.bin.Console.errPrintln("Exception parsing clustal file " + e);
e.printStackTrace();
}
}
else
{
- System.err.println("Clustal File Reader: Can't find sequence for "
+ jalview.bin.Console.errPrintln("Clustal File Reader: Can't find sequence for "
+ headers.elementAt(i));
}
}
// should report somewhere useful for UI if necessary
warningMessage = ((warningMessage == null) ? "" : warningMessage)
+ "Parsing error at\n" + line;
- System.out.println("Error parsing feature file: " + ex + "\n" + line);
+ jalview.bin.Console.outPrintln("Error parsing feature file: " + ex + "\n" + line);
ex.printStackTrace(System.err);
resetMatcher();
return false;
String[] tokens = line.split(TAB_REGEX);
if (tokens.length != 2)
{
- System.err.println(String.format("Invalid token count %d for %d",
+ jalview.bin.Console.errPrintln(String.format("Invalid token count %d for %d",
tokens.length, line));
}
else
*/
if (gffColumns.length < 6)
{
- System.err.println("Ignoring feature line '" + line
+ jalview.bin.Console.errPrintln("Ignoring feature line '" + line
+ "' with too few columns (" + gffColumns.length + ")");
return false;
}
seq = alignment.getSequenceAt(idx);
} catch (NumberFormatException ex)
{
- System.err.println("Invalid sequence index: " + seqIndex);
+ jalview.bin.Console.errPrintln("Invalid sequence index: " + seqIndex);
}
}
if (seq == null)
{
- System.out.println("Sequence not found: " + line);
+ jalview.bin.Console.outPrintln("Sequence not found: " + line);
return false;
}
@Override
public String print(SequenceI[] sqs, boolean jvsuffix)
{
- System.out.println("Use printGffFormat() or printJalviewFormat()");
+ jalview.bin.Console.outPrintln("Use printGffFormat() or printJalviewFormat()");
return null;
}
*/
if (gffColumns.length < 5)
{
- System.err.println("Ignoring GFF feature line with too few columns ("
+ jalview.bin.Console.errPrintln("Ignoring GFF feature line with too few columns ("
+ gffColumns.length + ")");
return null;
}
}
} catch (IOException e)
{
- System.err.println("GFF parsing failed with: " + e.getMessage());
+ jalview.bin.Console.errPrintln("GFF parsing failed with: " + e.getMessage());
return null;
}
}
}
else
{
- System.err.println("Ignoring unknown pragma: " + line);
+ jalview.bin.Console.errPrintln("Ignoring unknown pragma: " + line);
}
}
}
String name = format.getName().toUpperCase(Locale.ROOT);
if (formats.containsKey(name))
{
- System.err.println("Overwriting file format: " + format.getName());
+ jalview.bin.Console.errPrintln("Overwriting file format: " + format.getName());
}
formats.put(name, format);
if (isIdentifiable)
private File selectedFile;
+ private static boolean useDefaultFileFormat = false;
+
/**
* default constructor always raised errors in GUI dialog boxes
*/
if (format == null)
{
Desktop.instance.stopLoading();
- System.err.println("The input file \"" + file
+ jalview.bin.Console.errPrintln("The input file \"" + file
+ "\" has null or unidentifiable data content!");
- if (!Jalview.isHeadlessMode())
+ if (!Jalview.isHeadlessMode() && !Jalview.isBatchMode())
{
JvOptionPane.showInternalMessageDialog(Desktop.desktop,
MessageManager.getString("label.couldnt_read_data")
if (source != null)
{
// Tell the user (developer?) that this is going to cause a problem
- System.err.println(
+ jalview.bin.Console.errPrintln(
"IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
// We read the data anyway - it might make sense.
}
// BH 2018 switch to File object here instead of filename
- alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(
+ alignFrame = new Jalview2XML(raiseGUI && !Jalview.isBatchMode()).loadJalviewAlign(
selectedFile == null ? file : selectedFile);
}
else
"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 && !Jalview.isBatchMode() && Desktop.desktop != null)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
}
else
{
- System.err.println(errorMessage);
+ jalview.bin.Console.errPrintln(errorMessage);
}
}
}
} catch (Exception er)
{
- System.err.println("Exception whilst opening file '" + file);
+ jalview.bin.Console.errPrintln("Exception whilst opening file '" + file);
er.printStackTrace();
- if (raiseGUI)
+ if (raiseGUI && !Jalview.isBatchMode())
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
er.printStackTrace();
alignFrame = null;
- if (raiseGUI)
+ if (raiseGUI && !Jalview.isBatchMode())
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
}
});
}
- System.err.println("Out of memory loading file " + file + "!!");
+ jalview.bin.Console.errPrintln("Out of memory loading file " + file + "!!");
}
loadtime += System.currentTimeMillis();
{
AlignmentI al = alignFrame.getViewport().getAlignment();
- System.out.println("Loaded '" + title + "' in "
+ jalview.bin.Console.outPrintln("Loaded '" + title + "' in "
+ (loadtime / 1000.0) + "s, took an additional "
+ (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
+ al.getHeight() + " seqs by " + al.getWidth() + " cols)");
{
// report that we didn't load anything probably due to an out of memory
// error
- System.out.println("Failed to load '" + title + "' in "
+ jalview.bin.Console.outPrintln("Failed to load '" + title + "' in "
+ (loadtime / 1000.0) + "s, took an additional "
+ (1.0 * memused / (1024.0 * 1024.0))
+ " MB (alignment is null)");
}
this.setShouldBeSaved();
+ // after first file loaded we revert to assuming a default file format
+ useDefaultFileFormat = true;
}
/**
QuitHandler.Message.UNSAVED_ALIGNMENTS);
}
+ public static boolean getUseDefaultFileFormat()
+ {
+ return useDefaultFileFormat;
+ }
+
}
if (sfpos > -1 && sfpos < fileStr.length() - 1)
{
suffix = fileStr.substring(sfpos + 1);
- // System.err.println("DEBUG: Found Suffix:"+suffix);
+ // jalview.bin.Console.errPrintln("DEBUG: Found Suffix:"+suffix);
return fileStr.substring(0, sfpos);
}
return null;
{
if (bytesRead >= READAHEAD_LIMIT)
{
- System.err.println(String.format(
+ jalview.bin.Console.errPrintln(String.format(
"File reset error: read %d bytes but reset limit is %d",
bytesRead, READAHEAD_LIMIT));
}
}
else
{
- System.out.println(message);
+ jalview.bin.Console.outPrintln(message);
}
}
}
} catch (OutOfMemoryError err)
{
- System.out.println("########################\n" + "OUT OF MEMORY "
+ jalview.bin.Console.outPrintln("########################\n" + "OUT OF MEMORY "
+ generatedFile + "\n" + "########################");
new OOMWarning("Creating Image for " + generatedFile, err);
} catch (Exception e)
@Override
public void parse() throws IOException
{
- // JBPNote log.System.out.println("all read in ");
+ // JBPNote log.jalview.bin.Console.outPrintln("all read in ");
String line;
QuerySeqPosition = -1;
noSeqs = 0;
}
else if (id.equals("jnetconf"))
{
- // log.debug System.out.println("here");
+ // log.debug jalview.bin.Console.outPrintln("here");
id = "Prediction Confidence";
this.conf = new Vector(numSymbols);
for (int i = 0; i < jpred.seqs.size(); i++)
{
- System.out.println(((Sequence) jpred.seqs.elementAt(i)).getName()
+ jalview.bin.Console.outPrintln(((Sequence) jpred.seqs.elementAt(i)).getName()
+ "\n"
+ ((Sequence) jpred.seqs.elementAt(i)).getSequenceAsString()
+ "\n");
}
} catch (java.io.IOException e)
{
- System.err.println("Exception " + e);
+ jalview.bin.Console.errPrintln("Exception " + e);
// e.printStackTrace(); not java 1.1 compatible!
}
}
* out = BLCFile.print(s);
*
* AlignFrame af = new AlignFrame(null, s); af.resize(700, 500); af.show();
- * System.out.println(out); } catch (java.io.IOException e) {
- * System.out.println("Exception " + e); } } }
+ * jalview.bin.Console.outPrintln(out); } catch (java.io.IOException e) {
+ * jalview.bin.Console.outPrintln("Exception " + e); } } }
*/
.setSecondaryStructure(annotation.secondaryStructure);
String displayChar = annotation.displayCharacter == null ? null
: annotation.displayCharacter;
- // System.out.println("--------------------->[" + displayChar + "]");
+ // jalview.bin.Console.outPrintln("--------------------->[" + displayChar + "]");
annotationPojo.setDisplayCharacter(displayChar);
if (annotation.colour != null)
{
import java.util.Vector;
import javax.swing.BoxLayout;
-import javax.swing.DefaultListCellRenderer;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
+import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
+import javax.swing.ListCellRenderer;
import javax.swing.SpringLayout;
+import javax.swing.SwingConstants;
+import javax.swing.SwingUtilities;
+import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileFilter;
import javax.swing.plaf.basic.BasicFileChooserUI;
}
else
{
- System.err.println("JalviewFileChooser arguments mismatch: "
+ jalview.bin.Console.errPrintln("JalviewFileChooser arguments mismatch: "
+ extensions + ", " + descs);
}
}
// file filters to fix bug on Mac OSX
setAcceptAllFileFilterUsed(acceptAny);
+ // add a "All known alignment files" option
+ List<String> allExtensions = new ArrayList<>();
+ for (String[] format : formats)
+ {
+ String[] extensions = format[0].split(",");
+ for (String ext : extensions)
+ {
+ if (!allExtensions.contains(ext))
+ {
+ allExtensions.add(ext);
+ }
+ }
+ }
+ allExtensions.sort(null);
+ JalviewFileFilter alljvf = new JalviewFileFilter(
+ allExtensions.toArray(new String[] {}),
+ MessageManager.getString("label.all_known_alignment_files"));
+ alljvf.setExtensionListInDescription(false);
+ addChoosableFileFilter(alljvf);
+
+ if (selected == null)
+ {
+ chosen = alljvf;
+ }
+
for (String[] format : formats)
{
JalviewFileFilter jvf = new JalviewFileFilter(format[0], format[1]);
return FileFormats.getInstance().forName(format);
} catch (IllegalArgumentException e)
{
- System.err.println("Unexpected format: " + format);
+ jalview.bin.Console.errPrintln("Unexpected format: " + format);
}
}
return null;
}
} catch (Throwable x)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Unexpected exception when trying to get filename.");
x.printStackTrace();
}
}
}
+ if (!file.isAbsolute() && file.exists())
+ {
+ file = file.getAbsoluteFile();
+ }
+
setSelectedFile(file);
}
}
}
list = new JList<>(recent);
-
- DefaultListCellRenderer dlcr = new DefaultListCellRenderer();
- dlcr.setHorizontalAlignment(DefaultListCellRenderer.RIGHT);
- list.setCellRenderer(dlcr);
+ list.setCellRenderer(new recentlyOpenedCellRenderer());
list.addMouseListener(new MouseAdapter()
{
}
});
- this.setBorder(new javax.swing.border.TitledBorder(
- MessageManager.getString("label.recently_opened")));
+ TitledBorder recentlyOpenedBorder = new TitledBorder(
+ MessageManager.getString("label.recently_opened"));
+ recentlyOpenedBorder.setTitleFont(
+ recentlyOpenedBorder.getTitleFont().deriveFont(10f));
+ this.setBorder(recentlyOpenedBorder);
final JScrollPane scroller = new JScrollPane(list);
layout.putConstraint(SpringLayout.NORTH, scroller, 5,
SpringLayout.NORTH, this);
- if (Platform.isAMacAndNotJS())
- {
- scroller.setPreferredSize(new Dimension(500, 100));
- }
- else
- {
- scroller.setPreferredSize(new Dimension(530, 200));
- }
-
+ // one size okay for all
+ scroller.setPreferredSize(new Dimension(280, 105));
this.add(scroller);
- javax.swing.SwingUtilities.invokeLater(new Runnable()
+ SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
}
+ class recentlyOpenedCellRenderer extends JLabel
+ implements ListCellRenderer<String>
+ {
+ private final static int maxChars = 46;
+
+ private final static String ellipsis = "...";
+
+ @Override
+ public Component getListCellRendererComponent(
+ JList<? extends String> list, String value, int index,
+ boolean isSelected, boolean cellHasFocus)
+ {
+ String filename = value.toString();
+ String displayFilename;
+ if (filename.length() > maxChars)
+ {
+ StringBuilder displayFileSB = new StringBuilder();
+ File file = new File(filename);
+ displayFileSB.append(file.getName());
+ if (file.getParent() != null)
+ {
+ File parent = file;
+ boolean spaceleft = true;
+ while (spaceleft && parent.getParent() != null)
+ {
+ parent = parent.getParentFile();
+ String name = parent.getName();
+ displayFileSB.insert(0, File.separator);
+ if (displayFileSB.length() + name.length() < maxChars - 1)
+ {
+ displayFileSB.insert(0, name);
+ }
+ else
+ {
+ displayFileSB.insert(0, ellipsis);
+ spaceleft = false;
+ }
+ }
+ if (spaceleft && filename.startsWith(File.separator)
+ && !(displayFileSB.charAt(0) == File.separatorChar))
+ {
+ displayFileSB.insert(0, File.separator);
+ }
+ }
+ displayFilename = displayFileSB.toString();
+ }
+ else
+ {
+ displayFilename = filename;
+ }
+ this.setText(displayFilename.toString());
+ this.setToolTipText(filename);
+ if (isSelected)
+ {
+ setBackground(list.getSelectionBackground());
+ setForeground(list.getSelectionForeground());
+ }
+ else
+ {
+ setBackground(list.getBackground());
+ setForeground(list.getForeground());
+ }
+ this.setHorizontalAlignment(SwingConstants.TRAILING);
+ this.setEnabled(list.isEnabled());
+ this.setFont(list.getFont().deriveFont(12f));
+ this.setOpaque(true);
+ return this;
+ }
+
+ }
+
/*
@Override
public JalviewFileChooser setResponseHandler(Object response,
*/
package jalview.io;
-import java.util.Locale;
-
import java.io.File;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
+import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
while (extensions.hasNext())
{
- fullDescription += (", " + extensions.next());
+ fullDescription += (", ." + extensions.next());
}
}
}
else
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"JalviewFileView.createImageIcon: Couldn't find file: "
+ filePath);
}
}
} catch (IOException e)
{
- System.err.println("Exception parsing MSFFile " + e);
+ jalview.bin.Console.errPrintln("Exception parsing MSFFile " + e);
e.printStackTrace();
}
}
else
{
- System.err.println("MSFFile Parser: Can't find sequence for "
+ jalview.bin.Console.errPrintln("MSFFile Parser: Can't find sequence for "
+ headers.get(i));
}
}
}
} catch (Exception e)
{
- System.err.println("Exception during MSF Checksum calculation");
+ jalview.bin.Console.errPrintln("Exception during MSF Checksum calculation");
e.printStackTrace();
}
}
import com.stevesoft.pat.Regex;
import jalview.bin.Jalview;
+import jalview.bin.Jalview.ExitCode;
import jalview.datamodel.BinaryNode;
import jalview.datamodel.SequenceNode;
import jalview.util.MessageManager;
{
c.setRight(new SequenceNode(null, c, null, DefDistance,
DefBootstrap, false));
- c = (BinaryNode) c.right();
+ c = c.right();
}
else
{
c.setLeft(new SequenceNode(null, c, null, DefDistance,
DefBootstrap, false));
- c = (BinaryNode) c.left();
+ c = c.left();
}
if (realroot == null)
// node string contains Comment or structured/extended NH format info
/*
* if ((fcp-cp>1 && nf.substring(cp,fcp).trim().length()>1)) { // will
- * process in remains System.err.println("skipped text:
+ * process in remains jalview.bin.Console.errPrintln("skipped text:
* '"+nf.substring(cp,fcp)+"'"); }
*/
// verify termination.
// Just advance focus, if we need to
if ((c.left() != null) && (!c.left().isLeaf()))
{
- c = (BinaryNode) c.left();
+ c = c.left();
}
}
}
}
// THe next line is failing for topali trees - not sure why yet. if
// (root.right()!=null && root.isDummy())
- root = (SequenceNode) root.right().detach(); // remove the imaginary root.
+ root = root.right().detach(); // remove the imaginary root.
if (!RootHasDistance)
{
// more codes here.
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Couldn't parse code '" + code + "' = '" + value + "'");
e.printStackTrace(System.err);
}
if (args == null || args.length != 1)
{
Jalview.exit(
- "Takes one argument - file name of a newick tree file.", 0);
+ "Takes one argument - file name of a newick tree file.",
+ ExitCode.INVALID_ARGUMENT);
}
File fn = new File(args[0]);
}
treefile.close();
- System.out.println("Read file :\n");
+ jalview.bin.Console.outPrintln("Read file :\n");
NewickFile trf = new NewickFile(args[0], DataSourceType.FILE);
trf.parse();
- System.out.println("Original file :\n");
+ jalview.bin.Console.outPrintln("Original file :\n");
Regex nonl = new Regex("\n+", "");
- System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
-
- System.out.println("Parsed file.\n");
- System.out.println("Default output type for original input.\n");
- System.out.println(trf.print());
- System.out.println("Without bootstraps.\n");
- System.out.println(trf.print(false));
- System.out.println("Without distances.\n");
- System.out.println(trf.print(true, false));
- System.out.println("Without bootstraps but with distanecs.\n");
- System.out.println(trf.print(false, true));
- System.out.println("Without bootstraps or distanecs.\n");
- System.out.println(trf.print(false, false));
- System.out.println("With bootstraps and with distances.\n");
- System.out.println(trf.print(true, true));
+ jalview.bin.Console
+ .outPrintln(nonl.replaceAll(newickfile.toString()) + "\n");
+
+ jalview.bin.Console.outPrintln("Parsed file.\n");
+ jalview.bin.Console
+ .outPrintln("Default output type for original input.\n");
+ jalview.bin.Console.outPrintln(trf.print());
+ jalview.bin.Console.outPrintln("Without bootstraps.\n");
+ jalview.bin.Console.outPrintln(trf.print(false));
+ jalview.bin.Console.outPrintln("Without distances.\n");
+ jalview.bin.Console.outPrintln(trf.print(true, false));
+ jalview.bin.Console
+ .outPrintln("Without bootstraps but with distanecs.\n");
+ jalview.bin.Console.outPrintln(trf.print(false, true));
+ jalview.bin.Console.outPrintln("Without bootstraps or distanecs.\n");
+ jalview.bin.Console.outPrintln(trf.print(false, false));
+ jalview.bin.Console
+ .outPrintln("With bootstraps and with distances.\n");
+ jalview.bin.Console.outPrintln(trf.print(true, true));
} catch (java.io.IOException e)
{
- System.err.println("Exception\n" + e);
+ jalview.bin.Console.errPrintln("Exception\n" + e);
e.printStackTrace();
}
}
{
if (line.length() == 0)
{
- // System.out.println("blank line");
+ // jalview.bin.Console.outPrintln("blank line");
continue;
}
if (line.indexOf("C;") == 0 || line.indexOf("#") == 0)
}
else
{
- System.err.println("PFAM File reader: Can't find sequence for "
+ jalview.bin.Console.errPrintln("PFAM File reader: Can't find sequence for "
+ headers.get(i));
}
}
} catch (IOException e)
{
- System.err.println("Exception parsing PHYLIP file " + e);
+ jalview.bin.Console.errPrintln("Exception parsing PHYLIP file " + e);
e.printStackTrace(System.err);
throw e;
}
// public static void main(String[] args) {
// Pattern p= Pattern.compile("(.+)[.][^.]+");
// Matcher m = p.matcher("toto.xml.zip");
- // System.out.println(m.matches());
- // System.out.println(m.group(1));
+ // jalview.bin.Console.outPrintln(m.matches());
+ // jalview.bin.Console.outPrintln(m.group(1));
// }
/**
* make a friendly ID string.
}
} catch (Exception x)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"problem when creating links from " + urlstring);
x.printStackTrace();
}
UrlLink urlLink = new UrlLink(link);
if (!urlLink.isValid())
{
- System.err.println(urlLink.getInvalidMessage());
+ jalview.bin.Console.errPrintln(urlLink.getInvalidMessage());
return null;
}
rstart = Long.parseLong(stindx);
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Couldn't parse '" + stindx + "' as start of row");
// inAlignments = false;
// warn for this line
rend = Long.parseLong(endindx);
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Couldn't parse '" + endindx + "' as end of row");
// inAlignments = false;
+ umcp.getMessage() + ")";
throw new IOException(umcp);
}
- // DEBUG System.out.println("this is the secondary scructure:"
+ // DEBUG jalview.bin.Console.outPrintln("this is the secondary scructure:"
// +result.size());
SequenceI[] seqs = new SequenceI[result.size()];
String id = null;
for (int i = 0; i < result.size(); i++)
{
- // DEBUG System.err.println("Processing i'th sequence in Stockholm file")
+ // DEBUG jalview.bin.Console.errPrintln("Processing i'th sequence in Stockholm file")
RNA current = result.get(i);
String seq = current.getSeq();
String rna = current.getStructDBN(true);
- // DEBUG System.out.println(seq);
- // DEBUG System.err.println(rna);
+ // DEBUG jalview.bin.Console.outPrintln(seq);
+ // DEBUG jalview.bin.Console.errPrintln(rna);
int begin = 0;
int end = seq.length() - 1;
id = safeName(getDataName());
}
else if (!r.search(line))
{
- // System.err.println("Found sequence line: " + line);
+ // jalview.bin.Console.errPrintln("Found sequence line: " + line);
// Split sequence in sequence and accession parts
if (!x.search(line))
String annType = r.stringMatched(1);
String annContent = r.stringMatched(2);
- // System.err.println("type:" + annType + " content: " + annContent);
+ // jalview.bin.Console.errPrintln("type:" + annType + " content: " + annContent);
if (annType.equals("GF"))
{
else
{
// throw new IOException("Error parsing " + line);
- System.err.println(">> missing annotation: " + line);
+ jalview.bin.Console.errPrintln(">> missing annotation: " + line);
}
}
else if (annType.equals("GC"))
// }
else
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Warning - couldn't parse sequence annotation row line:\n"
+ line);
// throw new IOException("Error parsing " + line);
annot.annotations.length);
System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
annot.annotations = anns;
- // System.out.println("else: ");
+ // jalview.bin.Console.outPrintln("else: ");
}
return annot;
}
{
return (String) typeIds.get(id);
}
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Warning : Unknown Stockholm annotation type code " + id);
return id;
}
{
return key;
}
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Warning : Unknown Stockholm annotation type: " + type);
return key;
}
protected void processPdbFileWithAnnotate3d(List<SequenceI> rna)
throws Exception
{
- // System.out.println("this is a PDB format and RNA sequence");
+ // jalview.bin.Console.outPrintln("this is a PDB format and RNA sequence");
// note: we use reflection here so that the applet can compile and run
// without the HTTPClient bits and pieces needed for accessing Annotate3D
// web service
processPdbFileWithAnnotate3d(rnaSequences);
} catch (Exception x)
{
- System.err.println("Exceptions when dealing with RNA in pdb file");
+ jalview.bin.Console.errPrintln("Exceptions when dealing with RNA in pdb file");
x.printStackTrace();
}
processWithJmolParser(proteinSequences, true);
} catch (Exception x)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Exceptions from Jmol when processing data in pdb file");
x.printStackTrace();
}
annotations[j] = null;
if (val > 0)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Warning: non-zero value for positional T-COFFEE score for gap at "
+ j + " in sequence " + s.getName());
}
{
// removeValignmentSequences(alignment, docseqs);
docseqs.removeAllElements();
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Sequence deletion from alignment is not implemented.");
}
}
if (alismod)
{
- System.out.println("update alignment in document.");
+ jalview.bin.Console.outPrintln("update alignment in document.");
}
else
{
- System.out.println("alignment in document left unchanged.");
+ jalview.bin.Console.outPrintln("alignment in document left unchanged.");
}
}
else
// unbind alignment from view.
// create new binding and new alignment.
// mark trail on new alignment as being derived from old ?
- System.out.println(
+ jalview.bin.Console.outPrintln(
"update edited alignment to new alignment in document.");
}
}
// METHODS)
{
// verify existing alignment sequence annotation is up to date
- System.out.println("update dataset sequence annotation.");
+ jalview.bin.Console.outPrintln("update dataset sequence annotation.");
}
else
{
// verify existing alignment sequence annotation is up to date
- System.out.println(
+ jalview.bin.Console.outPrintln(
"make new alignment dataset sequence annotation if modification has happened.");
}
}
// METHODS)
{
// verify existing alignment sequence annotation is up to date
- System.out.println("update alignment sequence annotation.");
+ jalview.bin.Console.outPrintln("update alignment sequence annotation.");
}
else
{
// verify existing alignment sequence annotation is up to date
- System.out.println(
+ jalview.bin.Console.outPrintln(
"make new alignment sequence annotation if modification has happened.");
}
}
for (int i = 0; i < ids.size(); i++)
{
Sequence sequence = (Sequence) ids.get(i);
- System.out.println(sequence.getName());
+ jalview.bin.Console.outPrintln(sequence.getName());
BlastThread thread = new BlastThread(sequence);
thread.start();
BlastThread(Sequence sequence)
{
- System.out.println("blasting for: " + sequence.getName());
+ jalview.bin.Console.outPrintln("blasting for: " + sequence.getName());
this.sequence = sequence;
}
else
{
Thread.sleep(10000);
- System.out.println("WSWuBlastClient: I'm alive "
+ jalview.bin.Console.outPrintln("WSWuBlastClient: I'm alive "
+ sequence.getName() + " " + jobid); // log.debug
}
} catch (Exception ex)
{
jobComplete = true;
jobsRunning--;
- System.err.println("WSWUBlastClient error:\n" + exp.toString());
+ jalview.bin.Console.errPrintln("WSWUBlastClient error:\n" + exp.toString());
exp.printStackTrace();
}
}
@Override
public void actionPerformed(ActionEvent e)
{
- // System.out.println(">>>>> Clear cache items");
+ // jalview.bin.Console.outPrintln(">>>>> Clear cache items");
setSelectedItem("");
appCache.deleteCacheItems(cacheKey);
updateCache();
relaxedIdMatching);
} catch (IOException ivfe)
{
- System.err.println(ivfe);
+ jalview.bin.Console.errPrintln(ivfe);
}
/*
}
else if (!"+".equals(strand))
{
- System.err.println("Strand must be specified for alignment");
+ jalview.bin.Console.errPrintln("Strand must be specified for alignment");
return;
}
String[] tokens = region.split(" ");
if (tokens.length != 3)
{
- System.err.println("Malformed Align descriptor: " + region);
+ jalview.bin.Console.errPrintln("Malformed Align descriptor: " + region);
return null;
}
alignCount = Integer.parseInt(tokens[2]);
} catch (NumberFormatException nfe)
{
- System.err.println(nfe.toString());
+ jalview.bin.Console.errPrintln(nfe.toString());
return null;
}
return true;
}
}
- System.err.println("Sorry, I don't handle exonerate model " + model);
+ jalview.bin.Console.errPrintln("Sorry, I don't handle exonerate model " + model);
return false;
}
*/
if ("-".equals(strand))
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Skipping mapping from reverse complement as not yet supported");
return null;
}
List<String> targets = attributes.get(TARGET);
if (targets == null)
{
- System.err.println("'Target' missing in GFF");
+ jalview.bin.Console.errPrintln("'Target' missing in GFF");
return null;
}
String[] tokens = target.split(" ");
if (tokens.length < 3)
{
- System.err.println("Incomplete Target: " + target);
+ jalview.bin.Console.errPrintln("Incomplete Target: " + target);
continue;
}
}
} catch (NumberFormatException nfe)
{
- System.err.println("Invalid start or end in Target " + target);
+ jalview.bin.Console.errPrintln("Invalid start or end in Target " + target);
}
}
*/
if (!trimMapping(from, to, fromRatio, toRatio))
{
- System.err.println("Ignoring mapping from " + Arrays.toString(from)
+ jalview.bin.Console.errPrintln("Ignoring mapping from " + Arrays.toString(from)
+ " to " + Arrays.toString(to) + " as counts don't match!");
return null;
}
{
from[1] += fromOverlap / toRatio;
}
- System.err.println(Arrays.toString(from));
+ jalview.bin.Console.errPrintln(Arrays.toString(from));
return true;
}
else if (fromOverlap < 0 && fromOverlap % fromRatio == 0)
{
to[1] += fromOverlap / fromRatio;
}
- System.err.println(Arrays.toString(to));
+ jalview.bin.Console.errPrintln(Arrays.toString(to));
return true;
}
return sf;
} catch (NumberFormatException nfe)
{
- System.err.println("Invalid number in gff: " + nfe.getMessage());
+ jalview.bin.Console.errPrintln("Invalid number in gff: " + nfe.getMessage());
return null;
}
}
if (!valid)
{
- System.err.println(INVALID_GFF_ATTRIBUTE_FORMAT + s);
+ jalview.bin.Console.errPrintln(INVALID_GFF_ATTRIBUTE_FORMAT + s);
return map;
}
theKey = theKey.trim();
if (theKey.isEmpty())
{
- System.err.println(INVALID_GFF_ATTRIBUTE_FORMAT + s);
+ jalview.bin.Console.errPrintln(INVALID_GFF_ATTRIBUTE_FORMAT + s);
map.clear();
return map;
}
{
// suppress logging here as it reports Uniprot sequence features
// (which do not use SO terms) when auto-configuring feature colours
- // System.out.println("SO term " + term
+ // jalview.bin.Console.outPrintln("SO term " + term
// + " not known - add to model if needed in "
// + getClass().getName());
termsNotFound.add(term);
AlignmentSet last = getLastAlignmentSet();
if (last != null)
{
- System.err.println("Deuniquifying last alignment set.");
+ jalview.bin.Console.errPrintln("Deuniquifying last alignment set.");
last.deuniquifyAlignment();
}
al.add(new AlignmentSet(newal));
fp = new FileParse(file, AppletFormatAdapter.checkProtocol(file));
} catch (Exception e)
{
- System.err.println("Couldn't handle datasource of type " + jtype
+ jalview.bin.Console.errPrintln("Couldn't handle datasource of type " + jtype
+ " using URI " + file);
e.printStackTrace();
return;
}
else
{
- System.out.println("Couldn't parse source type token '"
+ jalview.bin.Console.outPrintln("Couldn't parse source type token '"
+ type.toUpperCase(Locale.ROOT) + "'");
}
}
System.out.print("\n");
}
- System.out.println("Now trying to parse set:");
+ jalview.bin.Console.outPrintln("Now trying to parse set:");
JalviewDataset context;
Object[] newdm;
ParsePackedSet pps;
.getAlignment(context = new JalviewDataset(), dp);
} catch (Exception e)
{
- System.out.println("Test failed for these arguments.\n");
+ jalview.bin.Console.outPrintln("Test failed for these arguments.\n");
e.printStackTrace(System.out);
return;
}
{
for (Object o : newdm)
{
- System.out.println("Will need to create an " + o.getClass());
+ jalview.bin.Console.outPrintln("Will need to create an " + o.getClass());
}
// now test uniquify/deuniquify stuff
{
if (context.getLastAlignmentSet().isModified())
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Initial alignment set was modified and any associated views should be updated.");
}
}
private void conflict(Mapping mjvmapping, SequenceMapping sequenceMapping)
{
- System.err.println("Conflict in update of sequenceMapping "
+ jalview.bin.Console.errPrintln("Conflict in update of sequenceMapping "
+ sequenceMapping.getVorbaId());
}
}
else
{
- System.err.println("WARNING: Unassociated treeNode "
+ jalview.bin.Console.errPrintln("WARNING: Unassociated treeNode "
+ tnode.element().toString() + " "
+ ((tnode.getName() != null)
? " label " + tnode.getName()
occurence = Integer.valueOf(oval).intValue();
} catch (Exception e)
{
- System.err.println("Invalid nodespec '" + nodespec + "'");
+ jalview.bin.Console.errPrintln("Invalid nodespec '" + nodespec + "'");
return null;
}
jalview.datamodel.BinaryNode bn = null;
initialise(vcfFile);
} catch (IOException e)
{
- System.err.println("Error opening VCF file: " + e.getMessage());
+ jalview.bin.Console.errPrintln("Error opening VCF file: " + e.getMessage());
}
// map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
}
} catch (Throwable e)
{
- System.err.println("Error processing VCF: " + e.getMessage());
+ jalview.bin.Console.errPrintln("Error processing VCF: " + e.getMessage());
e.printStackTrace();
if (gui != null)
{
patterns.add(Pattern.compile(token.toUpperCase(Locale.ROOT)));
} catch (PatternSyntaxException e)
{
- System.err.println("Invalid pattern ignored: " + token);
+ jalview.bin.Console.errPrintln("Invalid pattern ignored: " + token);
}
}
return patterns;
{
if (jvlite.debug && dbgMsg != null)
{
- System.err.println(dbgMsg);
+ jalview.bin.Console.errPrintln(dbgMsg);
}
scriptObject.call(_listener, objects);
}
{
if (jvlite.debug)
{
- System.err.println(jex);
+ jalview.bin.Console.errPrintln(jex);
}
if (jex instanceof netscape.javascript.JSException
&& jvlite.jsfallbackEnabled)
jsex[0] = jex;
if (jvlite.debug)
{
- System.err.println("Falling back to javascript: url call");
+ jalview.bin.Console.errPrintln("Falling back to javascript: url call");
}
StringBuffer sb = new StringBuffer(
"javascript:" + _listener + "(");
sb.append(")");
if (jvlite.debug)
{
- System.err.println(sb.toString());
+ jalview.bin.Console.errPrintln(sb.toString());
}
// alternate
URL url = null;
public void selection(SequenceGroup seqsel, ColumnSelection colsel,
HiddenColumns hidden, SelectionSource source)
{
- // System.err.println("Testing selection event relay to
+ // jalview.bin.Console.errPrintln("Testing selection event relay to
// jsfunction:"+_listener);
try
{
;
}
- System.err.println("Relaying selection to jsfunction:" + _listener);
+ jalview.bin.Console.errPrintln("Relaying selection to jsfunction:" + _listener);
executeJavascriptFunction(_listener,
new Object[]
{ src, setid, jvlite.arrayToSeparatorList(seqs),
jvlite.arrayToSeparatorList(cols) });
} catch (Exception ex)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Jalview Javascript exec error: Couldn't send selection message using function '"
+ _listener + "'");
ex.printStackTrace();
if (ex instanceof netscape.javascript.JSException)
{
- System.err.println("Javascript Exception: "
+ jalview.bin.Console.errPrintln("Javascript Exception: "
+ ((netscape.javascript.JSException) ex).getCause()
.toString());
}
} catch (Exception ex)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"JalviewLite javascript error: Couldn't send mouseOver with handler '"
+ _listener + "'");
if (ex instanceof netscape.javascript.JSException)
{
- System.err.println("Javascript Exception: "
+ jalview.bin.Console.errPrintln("Javascript Exception: "
+ ((netscape.javascript.JSException) ex).getMessage());
}
ex.printStackTrace();
"" + (atom.getPdbResNum()), "" + atom.getAtomIndex() });
} catch (Exception ex)
{
- System.err.println("Couldn't execute callback with " + _listenerfn
+ jalview.bin.Console.errPrintln("Couldn't execute callback with " + _listenerfn
+ " for atomSpec: " + atom);
ex.printStackTrace();
}
if (JalviewLite.debug)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
this.getClass().getName() + " modelSet[0]: " + modelSet[0]);
ssm.reportMapping();
}
}
// if (jvlite.debug)
// {
- // System.err.println("Mapped '" + modelSet[m] + "' to "
+ // jalview.bin.Console.errPrintln("Mapped '" + modelSet[m] + "' to "
// + sequence[m].length + " sequences.");
// }
}
executeJavascriptFunction(true, _listenerfn, st);
} catch (Exception ex)
{
- System.err.println("Couldn't execute callback with " + _listenerfn
+ jalview.bin.Console.errPrintln("Couldn't execute callback with " + _listenerfn
+ " using args { " + st[0] + ", " + st[1] + ", " + st[2]
+ "," + st[3] + "}"); // + ","+st[4]+"\n");
ex.printStackTrace();
* executeJavascriptFunction( false, _listenerfn, st = new String[] {
* "colourstruct", "" + ((jalview.appletgui.AlignmentPanel) source).av
* .getViewId(), handle, "" }); } catch (Exception ex) {
- * System.err.println("Couldn't execute callback with " + _listenerfn +
+ * jalview.bin.Console.errPrintln("Couldn't execute callback with " + _listenerfn +
* " using args { " + st[0] + ", " + st[1] + ", " + st[2] + "," + st[3] +
* "\n"); ex.printStackTrace();
*
import jalview.gui.JvSwingUtils;
import jalview.gui.Preferences;
import jalview.io.FileFormats;
-import jalview.io.exceptions.ImageOutputException;
import jalview.schemes.ResidueColourScheme;
import jalview.util.MessageManager;
import jalview.util.Platform;
{
try
{
+ setFrameIcon(null);
// for Web-page embedding using id=align-frame-div
setName("jalview-alignment");
}
} catch (Exception e)
{
- System.err.println(e.toString());
+ jalview.bin.Console.errPrintln(e.toString());
}
if (Platform.allowMnemonics()) // was "not mac and not JS"
protected void createPNG_actionPerformed(ActionEvent object)
{
// TODO Auto-generated method stub
-
+
}
protected void createEPS_actionPerformed(ActionEvent object)
{
// TODO Auto-generated method stub
-
+
}
protected void createSVG_actionPerformed(ActionEvent object)
{
// TODO Auto-generated method stub
-
+
}
protected void copyHighlightedColumns_actionPerformed(
{
}
-
protected void font_actionPerformed(ActionEvent e)
{
}
}
-
protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
{
protected JPanel scalePanelHolder = newJPanel();
- protected JPanel idPanelHolder = newJPanel();
+ public JPanel idPanelHolder = newJPanel();
protected JPanel idSpaceFillerPanel1 = newJPanel();
APQHandlers.setAPQHandlers((Desktop) this);
} catch (Exception e)
{
- System.out.println("Cannot set APQHandlers");
+ jalview.bin.Console.outPrintln("Cannot set APQHandlers");
// e.printStackTrace();
} catch (Throwable t)
{
inputURLMenuItem_actionPerformed(null);
} catch (FileFormatException e1)
{
- System.err.println("Error loading from URL: " + e1.getMessage());
+ jalview.bin.Console.errPrintln("Error loading from URL: " + e1.getMessage());
}
}
});
*/
protected void quit()
{
- // System.out.println("********** GDesktop.quit()");
+ // jalview.bin.Console.outPrintln("********** GDesktop.quit()");
}
/**
mainFrame.pack();
} catch (Exception e)
{
- System.out.println(e); // for JavaScript TypeError
+ jalview.bin.Console.outPrintln(e); // for JavaScript TypeError
e.printStackTrace();
}
}
protected void closeAction(int preferredHeight)
{
- // System.out.println(">>>>>>>>>> closing internal frame!!!");
- // System.out.println("width : " + mainFrame.getWidth());
- // System.out.println("heigh : " + mainFrame.getHeight());
- // System.out.println("x : " + mainFrame.getX());
- // System.out.println("y : " + mainFrame.getY());
+ // jalview.bin.Console.outPrintln(">>>>>>>>>> closing internal frame!!!");
+ // jalview.bin.Console.outPrintln("width : " + mainFrame.getWidth());
+ // jalview.bin.Console.outPrintln("heigh : " + mainFrame.getHeight());
+ // jalview.bin.Console.outPrintln("x : " + mainFrame.getX());
+ // jalview.bin.Console.outPrintln("y : " + mainFrame.getY());
tempUserPrefs.put("structureChooser.width", pnl_filter.getWidth());
tempUserPrefs.put("structureChooser.height", preferredHeight);
tempUserPrefs.put("structureChooser.x", mainFrame.getX());
{
String logLine = String.format("%s: %s", loglevel.toString(),
message);
- System.out.println(logLine);
+ jalview.bin.Console.outPrintln(logLine);
if (t != null)
{
if (loglevel.compareTo(LogLevel.DEBUG) <= 0)
t.printStackTrace(System.err);
else
- System.err.println(t.getMessage());
+ jalview.bin.Console.errPrintln(t.getMessage());
}
return false;
}
}
else
{
- // System.out.println("Iteration " + iter);
+ // jalview.bin.Console.outPrintln("Iteration " + iter);
}
g = (d[l] - d[l - 1]) / (2.0 * e[l - 1]);
}
else
{
- // System.out.println("Iteration " + iter);
+ // jalview.bin.Console.outPrintln("Iteration " + iter);
}
g = (d[l] - d[l - 1]) / (2.0 * e[l - 1]);
Float floatValue = Float.valueOf(degrees);
if (cachedRotations.get(axis).containsKey(floatValue))
{
- // System.out.println("getRotation from cache: " + (int) degrees);
+ // jalview.bin.Console.outPrintln("getRotation from cache: " + (int) degrees);
return cachedRotations.get(axis).get(floatValue);
}
import java.awt.Color;
import java.awt.Font;
-import java.awt.FontMetrics;
import java.awt.Rectangle;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import jalview.api.structures.JalviewStructureDisplayI;
import jalview.bin.Cache;
import jalview.bin.Console;
+import jalview.bin.Jalview;
import jalview.datamodel.AlignedCodonFrame;
import jalview.datamodel.Alignment;
import jalview.datamodel.AlignmentAnnotation;
}
} catch (Exception x)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"IMPLEMENTATION ERROR: Failed to resolve forward reference for sequence "
+ ref.getSref());
x.printStackTrace();
}
if (unresolved > 0)
{
- System.err.println("Jalview Project Import: There were " + unresolved
+ jalview.bin.Console.errPrintln("Jalview Project Import: There were "
+ + unresolved
+ " forward references left unresolved on the stack.");
}
if (failedtoresolve > 0)
{
- System.err.println("SERIOUS! " + failedtoresolve
+ jalview.bin.Console.errPrintln("SERIOUS! " + failedtoresolve
+ " resolvable forward references failed to resolve.");
}
if (incompleteSeqs != null && incompleteSeqs.size() > 0)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"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());
+ jalview.bin.Console.errPrintln(s.toString());
}
}
else
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Too many to report. Skipping output of incomplete sequences.");
}
}
object.setCreationDate(now);
} catch (DatatypeConfigurationException e)
{
- System.err.println("error writing date: " + e.toString());
+ jalview.bin.Console.errPrintln("error writing date: " + e.toString());
}
object.setVersion(Cache.getDefault("VERSION", "Development Build"));
// 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()+"
+ // jalview.bin.Console.errPrintln("vamsasSeq backref: "+id+"");
+ // jalview.bin.Console.errPrintln(jds.getName()+"
// "+jds.getStart()+"-"+jds.getEnd()+" "+jds.getSequenceAsString());
- // System.err.println("Hashcode: "+seqHash(jds));
+ // jalview.bin.Console.errPrintln("Hashcode: "+seqHash(jds));
// SequenceI rsq = (SequenceI) seqRefIds.get(id + "");
- // System.err.println(rsq.getName()+"
+ // jalview.bin.Console.errPrintln(rsq.getName()+"
// "+rsq.getStart()+"-"+rsq.getEnd()+" "+rsq.getSequenceAsString());
- // System.err.println("Hashcode: "+seqHash(rsq));
+ // jalview.bin.Console.errPrintln("Hashcode: "+seqHash(rsq));
}
else
{
* 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--)
+ List<JalviewStructureDisplayI> viewFrames = new ArrayList<>();
+ if (Desktop.desktop != null)
{
- if (frames[f] instanceof StructureViewerBase)
+ JInternalFrame[] jifs = Desktop.desktop.getAllFrames();
+ if (jifs != null)
{
- 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))
+ for (JInternalFrame jif : jifs)
{
- viewIds.add(viewId);
- File viewerState = viewFrame.saveSession();
- if (viewerState != null)
- {
- copyFileToJar(jout, viewerState.getPath(),
- getViewerJarEntryName(viewId), viewerType);
- }
- else
+ if (jif instanceof JalviewStructureDisplayI)
{
- Console.error(
- "Failed to save viewer state for " + viewerType);
+ viewFrames.add((JalviewStructureDisplayI) jif);
}
}
}
}
+ else if (Jalview.isHeadlessMode()
+ && Jalview.getInstance().getCommands() != null)
+ {
+ viewFrames.addAll(
+ StructureViewerBase.getAllStructureViewerBases());
+ }
+
+ String matchedFile = null;
+ for (JalviewStructureDisplayI viewFrame : viewFrames)
+ {
+ 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)
{
try
{
fileName = fileName.replace('\\', '/');
- System.out.println("Writing jar entry " + fileName);
+ jalview.bin.Console.outPrintln("Writing jar entry " + fileName);
JarEntry entry = new JarEntry(fileName);
jout.putNextEntry(entry);
PrintWriter pout = new PrintWriter(
} catch (Exception ex)
{
// TODO: raise error in GUI if marshalling failed.
- System.err.println("Error writing Jalview project");
+ jalview.bin.Console.errPrintln("Error writing Jalview project");
ex.printStackTrace();
}
}
File file = new File(infilePath);
if (file.exists() && jout != null)
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Writing jar entry " + jarEntryName + " (" + msg + ")");
jout.putNextEntry(new JarEntry(jarEntryName));
copyAll(is, jout);
*/
protected String saveStructureViewer(AlignmentPanel ap, SequenceI jds,
Pdbids pdb, PDBEntry entry, List<String> viewIds,
- String matchedFile, StructureViewerBase viewFrame)
+ String matchedFile, JalviewStructureDisplayI viewFrame)
{
final AAStructureBindingModel bindingModel = viewFrame.getBinding();
{
StructureState state = new StructureState();
state.setVisible(true);
- state.setXpos(viewFrame.getX());
+ state.setXpos(viewFrame.getY());
state.setYpos(viewFrame.getY());
state.setWidth(viewFrame.getWidth());
state.setHeight(viewFrame.getHeight());
return BitSet.valueOf(newlongvals);
}
+
private CalcIdParam createCalcIdParam(String calcId, AlignViewport av)
{
AutoCalcSetting settings = av.getCalcIdSettingsFor(calcId);
});
} catch (Exception x)
{
- System.err.println("Error loading alignment: " + x.getMessage());
+ jalview.bin.Console
+ .errPrintln("Error loading alignment: " + x.getMessage());
}
}
return af;
{
if (bytes != null)
{
- // System.out.println("Jalview2XML: opening byte jarInputStream for
+ // jalview.bin.Console.outPrintln("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 "
+ // jalview.bin.Console.outPrintln("Jalview2XML: opening url
+ // jarInputStream for "
// + _url);
return new JarInputStream(_url.openStream());
}
else
{
- // System.out.println("Jalview2XML: opening file jarInputStream for
+ // jalview.bin.Console.outPrintln("Jalview2XML: opening file
+ // jarInputStream for
// " + file);
return new JarInputStream(new FileInputStream(file));
}
{
ex.printStackTrace();
errorMessage = "Couldn't locate Jalview XML file : " + file;
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Exception whilst loading jalview XML file : " + ex + "\n");
} catch (Exception ex)
{
- System.err.println("Parsing as Jalview Version 2 file failed.");
+ jalview.bin.Console
+ .errPrintln("Parsing as Jalview Version 2 file failed.");
ex.printStackTrace(System.err);
if (attemptversion1parse)
{
}
if (af != null)
{
- System.out.println("Successfully loaded archive file");
+ jalview.bin.Console.outPrintln("Successfully loaded archive file");
return af;
}
ex.printStackTrace();
- System.err.println(
+ jalview.bin.Console.errPrintln(
"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");
+ jalview.bin.Console
+ .errPrintln("Out of memory whilst loading jalview XML file");
e.printStackTrace();
}
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");
+ jalview.bin.Console.errPrintln("Failed to restore view "
+ + view.getTitle() + " to split frame");
}
}
}
else
{
- System.err.println("Problem loading Jalview file: " + errorMessage);
+ jalview.bin.Console.errPrintln(
+ "Problem loading Jalview file: " + errorMessage);
}
}
errorMessage = null;
if (tmpSeq.getStart() != jseq.getStart()
|| tmpSeq.getEnd() != jseq.getEnd())
{
- System.err.println(String.format(
+ jalview.bin.Console.errPrintln(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()));
// XML.
// and then recover its containing af to allow the settings to be applied.
// TODO: fix for vamsas demo
- System.err.println(
+ jalview.bin.Console.errPrintln(
"About to recover a viewport for existing alignment: Sequence set ID is "
+ uniqueSeqSetId);
Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
if (seqsetobj instanceof String)
{
uniqueSeqSetId = (String) seqsetobj;
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
+ uniqueSeqSetId);
}
else
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Warning : Collision between sequence set ID string and existing jalview object mapping.");
}
{
if (tree.isColumnWise())
{
- AlignmentAnnotation aa = (AlignmentAnnotation) annotationIds
+ AlignmentAnnotation aa = annotationIds
.get(tree.getColumnReference());
if (aa == null)
{
createOrLinkStructureViewer(entry, af, ap, jprovider);
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Error loading structure viewer: " + e.getMessage());
// failed - try the next one
}
|| version.equalsIgnoreCase("Test")
|| version.equalsIgnoreCase("AUTOMATED BUILD"))
{
- System.err.println("Assuming project file with "
+ jalview.bin.Console.errPrintln("Assuming project file with "
+ (version == null ? "null" : version)
+ " is compatible with Jalview version " + supported);
return true;
//
// @Override
// protected void processKeyEvent(java.awt.event.KeyEvent e) {
- // System.out.println("Jalview2XML AF " + e);
+ // jalview.bin.Console.outPrintln("Jalview2XML AF " + e);
// super.processKeyEvent(e);
//
// }
}
if (matchedAnnotation == null)
{
- System.err.println("Failed to match annotation colour scheme for "
- + annotationId);
+ jalview.bin.Console
+ .errPrintln("Failed to match annotation colour scheme for "
+ + annotationId);
return null;
}
// belt-and-braces create a threshold line if the
}
// TODO: merges will never happen if we 'know' we have the real dataset
// sequence - this should be detected when id==dssid
- System.err.println(
+ jalview.bin.Console.errPrintln(
"DEBUG Notice: Merged dataset sequence (if you see this often, post at http://issues.jalview.org/browse/JAL-1474)"); // ("
// + (pre ? "prepended" : "") + " "
// + (post ? "appended" : ""));
}
else
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Warning - making up dataset sequence id for DbRef sequence map reference");
sqid = ((Object) ms).toString(); // make up a new hascode for
// undefined dataset sequence hash
} catch (IllegalStateException e)
{
// mixing AND and OR conditions perhaps
- System.err.println(
+ jalview.bin.Console.errPrintln(
String.format("Error reading filter conditions for '%s': %s",
featureType, e.getMessage()));
// return as much as was parsed up to the error
}
else
{
- System.err.println("Malformed compound filter condition");
+ jalview.bin.Console
+ .errPrintln("Malformed compound filter condition");
}
}
}
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
+import java.awt.RenderingHints;
+import java.awt.Stroke;
import java.awt.geom.AffineTransform;
import java.awt.image.ImageObserver;
import java.util.BitSet;
import java.util.Hashtable;
+import org.jfree.graphics2d.svg.SVGGraphics2D;
+import org.jibble.epsgraphics.EpsGraphics2D;
+
import jalview.analysis.AAFrequency;
import jalview.analysis.CodingUtils;
import jalview.analysis.Rna;
import jalview.analysis.StructureFrequency;
import jalview.api.AlignViewportI;
+import jalview.bin.Cache;
+import jalview.bin.Console;
import jalview.datamodel.AlignmentAnnotation;
import jalview.datamodel.Annotation;
import jalview.datamodel.ColumnSelection;
private boolean av_ignoreGapsConsensus;
+ private boolean vectorRendition = false;
+
+ private boolean glyphLineDrawn = false;
+
/**
* attributes set from AwtRenderPanelI
*/
int x, int y, int iconOffset, int startRes, int column,
boolean validRes, boolean validEnd)
{
- g.setColor(STEM_COLOUR);
int sCol = (lastSSX / charWidth)
+ hiddenColumns.visibleToAbsoluteColumn(startRes);
int x1 = lastSSX;
|| row_annotations[column] == null
|| dc != row_annotations[column].secondaryStructure;
+ if (diffupstream || diffdownstream)
+ {
+ // draw glyphline under arrow
+ drawGlyphLine(g, lastSSX, x, y, iconOffset);
+ }
+ g.setColor(STEM_COLOUR);
+
if (column > 0 && Rna.isClosingParenthesis(dc))
{
if (diffupstream)
* if new annotation with a closing base pair half of the stem,
* display a backward arrow
*/
- g.fillPolygon(new int[] { lastSSX + 5, lastSSX + 5, lastSSX },
+ fillPolygon(g, new int[] { lastSSX + 5, lastSSX + 5, lastSSX },
new int[]
- { y + iconOffset, y + 14 + iconOffset, y + 8 + iconOffset },
+ { y + iconOffset + 1, y + 13 + iconOffset,
+ y + 7 + iconOffset },
3);
x1 += 5;
}
* if annotation ending with an opeing base pair half of the stem,
* display a forward arrow
*/
- g.fillPolygon(new int[] { x2 - 5, x2 - 5, x2 },
+ fillPolygon(g, new int[] { x2 - 6, x2 - 6, x2 - 1 },
new int[]
- { y + iconOffset, y + 14 + iconOffset, y + 8 + iconOffset },
+ { y + iconOffset + 1, y + 13 + iconOffset,
+ y + 7 + iconOffset },
3);
x2 -= 5;
}
}
}
// draw arrow body
- g.fillRect(x1, y + 4 + iconOffset, x2 - x1, 7);
+ unsetAntialias(g);
+ fillRect(g, x1, y + 4 + iconOffset, x2 - x1, 6);
}
void drawNotCanonicalAnnot(Graphics g, Color nonCanColor,
int iconOffset, int startRes, int column, boolean validRes,
boolean validEnd)
{
- // System.out.println(nonCanColor);
+ // Console.info(nonCanColor);
- g.setColor(nonCanColor);
int sCol = (lastSSX / charWidth)
+ hiddenColumns.visibleToAbsoluteColumn(startRes);
int x1 = lastSSX;
boolean diffdownstream = !validRes || !validEnd
|| row_annotations[column] == null
|| !dc.equals(row_annotations[column].displayCharacter);
- // System.out.println("Column "+column+" diff up: "+diffupstream+"
+ // Console.info("Column "+column+" diff up:
+ // "+diffupstream+"
// down:"+diffdownstream);
// If a closing base pair half of the stem, display a backward arrow
+ if (diffupstream || diffdownstream)
+ {
+ // draw glyphline under arrow
+ drawGlyphLine(g, lastSSX, x, y, iconOffset);
+ }
+ g.setColor(nonCanColor);
if (column > 0 && Rna.isClosingParenthesis(dc))
{
// if (validRes && column>1 && row_annotations[column-2]!=null &&
// dc.equals(row_annotations[column-2].displayCharacter))
{
- g.fillPolygon(new int[] { lastSSX + 5, lastSSX + 5, lastSSX },
+ fillPolygon(g, new int[] { lastSSX + 5, lastSSX + 5, lastSSX },
new int[]
- { y + iconOffset, y + 14 + iconOffset, y + 8 + iconOffset },
+ { y + iconOffset + 1, y + 13 + iconOffset,
+ y + 7 + iconOffset },
3);
x1 += 5;
}
// display a forward arrow
if (diffdownstream)
{
- g.fillPolygon(new int[] { x2 - 5, x2 - 5, x2 },
+ fillPolygon(g, new int[] { x2 - 6, x2 - 6, x2 - 1 },
new int[]
- { y + iconOffset, y + 14 + iconOffset, y + 8 + iconOffset },
+ { y + iconOffset + 1, y + 13 + iconOffset,
+ y + 7 + iconOffset },
3);
x2 -= 5;
}
}
}
// draw arrow body
- g.fillRect(x1, y + 4 + iconOffset, x2 - x1, 7);
+ unsetAntialias(g);
+ fillRect(g, x1, y + 4 + iconOffset, x2 - x1, 6);
}
// public void updateFromAnnotationPanel(FontMetrics annotFM, AlignViewportI
AlignViewportI av, Graphics g, int activeRow, int startRes,
int endRes)
{
+ if (g instanceof EpsGraphics2D || g instanceof SVGGraphics2D)
+ {
+ this.setVectorRendition(true);
+ }
+ Graphics2D g2d = (Graphics2D) g;
+
long stime = System.currentTimeMillis();
boolean usedFaded = false;
// NOTES:
*
* continue; }
*/
+
// first pass sets up state for drawing continuation from left-hand
// column
// of startRes
+
+ // flag used for vector rendition
+ this.glyphLineDrawn = false;
x = (startRes == 0) ? 0 : -1;
while (x < endRes - startRes)
{
: null;
if (x > -1)
{
+ unsetAntialias(g);
if (activeRow == i)
{
g.setColor(Color.red);
{
if (columnSelection.contains(column))
{
- g.fillRect(x * charWidth, y, charWidth, charHeight);
+ fillRect(g, x * charWidth, y, charWidth, charHeight);
}
}
}
if (row.getInvalidStrucPos() > x)
{
g.setColor(Color.orange);
- g.fillRect(x * charWidth, y, charWidth, charHeight);
+ fillRect(g, x * charWidth, y, charWidth, charHeight);
}
else if (row.getInvalidStrucPos() == x)
{
g.setColor(Color.orange.darker());
- g.fillRect(x * charWidth, y, charWidth, charHeight);
+ fillRect(g, x * charWidth, y, charWidth, charHeight);
}
if (validCharWidth && validRes && displayChar != null
&& (displayChar.length() > 0))
{
- Graphics2D gg = ((Graphics2D) g);
+ // Graphics2D gg = (g);
float fmWidth = fm.charsWidth(displayChar.toCharArray(), 0,
displayChar.length());
if (row_annotations[column].colour == null)
{
- gg.setColor(Color.black);
+ g2d.setColor(Color.black);
}
else
{
- gg.setColor(row_annotations[column].colour);
+ g2d.setColor(row_annotations[column].colour);
}
/*
/*
* translate to drawing position _before_ applying any scaling
*/
- gg.translate(xPos, yPos);
+ g2d.translate(xPos, yPos);
if (scaledToFit)
{
/*
* use a scaling transform to make the label narrower
* (JalviewJS doesn't have Font.deriveFont(AffineTransform))
*/
- gg.transform(
+ g2d.transform(
AffineTransform.getScaleInstance(fmScaling, 1.0));
}
+ setAntialias(g);
if (column == 0 || row.graph > 0)
{
- gg.drawString(displayChar, 0, 0);
+ g2d.drawString(displayChar, 0, 0);
}
else if (row_annotations[column - 1] == null || (labelAllCols
|| !displayChar.equals(
|| (displayChar.length() < 2
&& row_annotations[column].secondaryStructure == ' ')))
{
- gg.drawString(displayChar, 0, 0);
+ g2d.drawString(displayChar, 0, 0);
}
if (scaledToFit)
{
* undo scaling before translating back
* (restoring saved transform does NOT work in JS PDFGraphics!)
*/
- gg.transform(AffineTransform
+ g2d.transform(AffineTransform
.getScaleInstance(1D / fmScaling, 1.0));
}
- gg.translate(-xPos, -yPos);
+ g2d.translate(-xPos, -yPos);
}
}
if (row.hasIcons)
{
// int nb_annot = x - temp;
- // System.out.println("\t type :"+lastSS+"\t x :"+x+"\t nbre
+ // Console.info("\t type :"+lastSS+"\t x
+ // :"+x+"\t nbre
// annot :"+nb_annot);
switch (lastSS)
{
// temp = x;
break;
default:
- g.setColor(Color.gray);
- g.fillRect(lastSSX, y + 6 + iconOffset,
- (x * charWidth) - lastSSX, 2);
- // temp = x;
+ if (isVectorRendition())
+ {
+ // draw single full width glyphline
+ drawGlyphLine(g, lastSSX, endRes - x, y, iconOffset);
+ // disable more glyph lines
+ this.glyphLineDrawn = true;
+ }
+ else
+ {
+ drawGlyphLine(g, lastSSX, x, y, iconOffset);
+ }
break;
}
}
case 'y':
case 'Z':
case 'z':
- // System.out.println(lastSS);
+ // Console.info(lastSS);
Color nonCanColor = getNotCanonicalColor(lastSS);
drawNotCanonicalAnnot(g, nonCanColor, row_annotations, lastSSX,
x, y, iconOffset, startRes, column, validRes, validEnd);
break;
default:
- drawGlyphLine(g, row_annotations, lastSSX, x, y, iconOffset,
- startRes, column, validRes, validEnd);
+ if (isVectorRendition())
+ {
+ // draw single full width glyphline
+ drawGlyphLine(g, lastSSX, endRes - x, y, iconOffset);
+ // disable more glyph lines
+ this.glyphLineDrawn = true;
+ }
+ else
+ {
+ drawGlyphLine(g, lastSSX, x, y, iconOffset);
+ }
break;
}
}
}
else
{
- System.err.println(
+ Console.warn(
"rendered with " + renderer.getClass().toString());
}
}
{
if (clipst)
{
- System.err.println(
- "Start clip at : " + yfrom + " (index " + f_i + ")");
+ Console.warn("Start clip at : " + yfrom + " (index " + f_i + ")");
}
if (clipend)
{
- System.err.println(
- "End clip at : " + yto + " (index " + f_to + ")");
+ Console.warn("End clip at : " + yto + " (index " + f_to + ")");
}
}
;
- System.err.println("Annotation Rendering time:"
+ Console.warn("Annotation Rendering time:"
+ (System.currentTimeMillis() - stime));
}
;
// private Color sdNOTCANONICAL_COLOUR;
- void drawGlyphLine(Graphics g, Annotation[] row, int lastSSX, int x,
- int y, int iconOffset, int startRes, int column, boolean validRes,
- boolean validEnd)
+ void drawGlyphLine(Graphics g, int lastSSX, int x, int y, int iconOffset)
{
+ if (glyphLineDrawn)
+ {
+ // if we've drawn a single long glyphline for an export, don't draw the
+ // bits
+ return;
+ }
+ unsetAntialias(g);
g.setColor(GLYPHLINE_COLOR);
g.fillRect(lastSSX, y + 6 + iconOffset, (x * charWidth) - lastSSX, 2);
}
int lastSSX, int x, int y, int iconOffset, int startRes,
int column, boolean validRes, boolean validEnd)
{
- g.setColor(SHEET_COLOUR);
-
if (!validEnd || !validRes || row == null || row[column] == null
|| row[column].secondaryStructure != 'E')
{
- g.fillRect(lastSSX, y + 4 + iconOffset, (x * charWidth) - lastSSX - 4,
- 7);
- g.fillPolygon(
+ // draw the glyphline underneath
+ drawGlyphLine(g, lastSSX, x, y, iconOffset);
+
+ g.setColor(SHEET_COLOUR);
+ fillRect(g, lastSSX, y + 4 + iconOffset,
+ (x * charWidth) - lastSSX - 4, 6);
+ fillPolygon(g,
new int[]
- { (x * charWidth) - 4, (x * charWidth) - 4, (x * charWidth) },
+ { (x * charWidth) - 6, (x * charWidth) - 6,
+ (x * charWidth - 1) },
new int[]
- { y + iconOffset, y + 14 + iconOffset, y + 7 + iconOffset },
+ { y + iconOffset + 1, y + 13 + iconOffset,
+ y + 7 + iconOffset },
3);
}
else
{
- g.fillRect(lastSSX, y + 4 + iconOffset, (x + 1) * charWidth - lastSSX,
- 7);
+ g.setColor(SHEET_COLOUR);
+ fillRect(g, lastSSX, y + 4 + iconOffset, (x * charWidth) - lastSSX,
+ 6);
}
-
}
void drawHelixAnnot(Graphics g, Annotation[] row, int lastSSX, int x,
int y, int iconOffset, int startRes, int column, boolean validRes,
boolean validEnd)
{
- g.setColor(HELIX_COLOUR);
-
int sCol = (lastSSX / charWidth)
+ hiddenColumns.visibleToAbsoluteColumn(startRes);
int x1 = lastSSX;
int x2 = (x * charWidth);
- if (USE_FILL_ROUND_RECT)
+ if (USE_FILL_ROUND_RECT || isVectorRendition())
{
+ // draw glyph line behind helix (visible in EPS or SVG output)
+ drawGlyphLine(g, lastSSX, x, y, iconOffset);
+
+ g.setColor(HELIX_COLOUR);
+ setAntialias(g);
int ofs = charWidth / 2;
// Off by 1 offset when drawing rects and ovals
// to offscreen image on the MAC
- g.fillRoundRect(lastSSX, y + 4 + iconOffset, x2 - x1, 8, 8, 8);
+ fillRoundRect(g, lastSSX, y + 3 + iconOffset, x2 - x1 - 1, 8, 8, 8);
if (sCol == 0 || row[sCol - 1] == null
|| row[sCol - 1].secondaryStructure != 'H')
{
}
else
{
- // g.setColor(Color.orange);
- g.fillRoundRect(lastSSX, y + 4 + iconOffset, x2 - x1 - ofs + 1, 8,
- 0, 0);
+ fillRoundRect(g, lastSSX, y + 3 + iconOffset, x2 - x1 - ofs, 8, 0,
+ 0);
}
if (!validRes || row[column] == null
|| row[column].secondaryStructure != 'H')
}
else
{
- // g.setColor(Color.magenta);
- g.fillRoundRect(lastSSX + ofs, y + 4 + iconOffset,
- x2 - x1 - ofs + 1, 8, 0, 0);
-
+ fillRoundRect(g, lastSSX + ofs, y + 3 + iconOffset, x2 - x1 - ofs,
+ 8, 0, 0);
}
return;
}
- if (sCol == 0 || row[sCol - 1] == null
- || row[sCol - 1].secondaryStructure != 'H')
+ boolean leftEnd = sCol == 0 || row[sCol - 1] == null
+ || row[sCol - 1].secondaryStructure != 'H';
+ boolean rightEnd = !validRes || row[column] == null
+ || row[column].secondaryStructure != 'H';
+
+ if (leftEnd || rightEnd)
+ {
+ drawGlyphLine(g, lastSSX, x, y, iconOffset);
+ }
+ g.setColor(HELIX_COLOUR);
+
+ if (leftEnd)
{
- g.fillArc(lastSSX, y + 4 + iconOffset, charWidth, 8, 90, 180);
+ fillArc(g, lastSSX, y + 3 + iconOffset, charWidth, 8, 90, 180);
x1 += charWidth / 2;
}
- if (!validRes || row[column] == null
- || row[column].secondaryStructure != 'H')
+ if (rightEnd)
{
- g.fillArc((x * charWidth) - charWidth, y + 4 + iconOffset, charWidth,
- 8, 270, 180);
+ fillArc(g, ((x - 1) * charWidth), y + 3 + iconOffset, charWidth, 8,
+ 270, 180);
x2 -= charWidth / 2;
}
- g.fillRect(x1, y + 4 + iconOffset, x2 - x1, 8);
+ fillRect(g, x1, y + 3 + iconOffset, x2 - x1, 8);
}
void drawLineGraph(Graphics g, AlignmentAnnotation _aa,
{
return;
}
+ Stroke roundStroke = new BasicStroke(1, BasicStroke.CAP_ROUND,
+ BasicStroke.JOIN_ROUND);
+ Stroke squareStroke = new BasicStroke(1, BasicStroke.CAP_SQUARE,
+ BasicStroke.JOIN_MITER);
+ Graphics2D g2d = (Graphics2D) g;
+ Stroke prevStroke = g2d.getStroke();
+ g2d.setStroke(roundStroke);
int x = 0;
}
g.setColor(Color.gray);
- g.drawLine(x - charWidth, y2, (eRes - sRes + 1) * charWidth, y2);
+ drawLine(g, squareStroke, x * charWidth - charWidth, y2,
+ (eRes - sRes) * charWidth, y2);
eRes = Math.min(eRes, aa_annotations.length);
// standalone value
y1 = y - (int) (((aa_annotations[column].value - min) / range)
* graphHeight);
- g.drawLine(x * charWidth + charWidth / 4, y1,
+ drawLine(g, x * charWidth + charWidth / 4, y1,
x * charWidth + 3 * charWidth / 4, y1);
x++;
continue;
y2 = y - (int) (((aa_annotations[column].value - min) / range)
* graphHeight);
- g.drawLine(x * charWidth - charWidth / 2, y1,
+ drawLine(g, (x - 1) * charWidth + charWidth / 2, y1,
x * charWidth + charWidth / 2, y2);
x++;
}
{
g.setColor(_aa.threshold.colour);
Graphics2D g2 = (Graphics2D) g;
- g2.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE,
+ Stroke s = new BasicStroke(1, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_ROUND, 3f, new float[]
- { 5f, 3f }, 0f));
+ { 5f, 3f }, 0f);
y2 = (int) (y - ((_aa.threshold.value - min) / range) * graphHeight);
- g.drawLine(0, y2, (eRes - sRes) * charWidth, y2);
- g2.setStroke(new BasicStroke());
+ drawLine(g, s, 0, y2, (eRes - sRes) * charWidth, y2);
}
+ g2d.setStroke(prevStroke);
}
@SuppressWarnings("unused")
g.setColor(Color.gray);
- g.drawLine(x, y2, (eRes - sRes) * charWidth, y2);
+ drawLine(g, x, y2, (eRes - sRes) * charWidth, y2);
int column;
int aaMax = aa_annotations.length - 1;
{
if (y1 - y2 > 0)
{
- g.fillRect(x * charWidth, y2, charWidth, y1 - y2);
+ fillRect(g, x * charWidth, y2, charWidth, y1 - y2);
}
else
{
- g.fillRect(x * charWidth, y1, charWidth, y2 - y1);
+ fillRect(g, x * charWidth, y1, charWidth, y2 - y1);
}
}
// draw profile if available
// lm is not necessary - we can just use fm - could be off by no more
// than 0.5 px
// LineMetrics lm = g.getFontMetrics(ofont).getLineMetrics("Q", g);
- // System.out.println(asc + " " + dec + " " + (asc - lm.getAscent())
+ // Console.info(asc + " " + dec + " " + (asc -
+ // lm.getAscent())
// + " " + (dec - lm.getDescent()));
double asc = fm.getAscent();
if (_aa.threshold != null)
{
g.setColor(_aa.threshold.colour);
- Graphics2D g2 = (Graphics2D) g;
- g2.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE,
+ Stroke s = new BasicStroke(1, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_ROUND, 3f, new float[]
- { 5f, 3f }, 0f));
+ { 5f, 3f }, 0f);
y2 = (int) (y
- ((_aa.threshold.value - min) / range) * _aa.graphHeight);
- g.drawLine(0, y2, (eRes - sRes) * charWidth, y2);
- g2.setStroke(new BasicStroke());
+ drawLine(g, s, 0, y2, (eRes - sRes) * charWidth, y2);
}
}
{
eRes = Math.min(eRes, aa_annotations.length);
g.setColor(Color.white);
- g.fillRect(0, 0, width, y);
+ fillRect(g, 0, 0, width, y);
g.setColor(new Color(0, 0, 180));
int x = 0, height;
height = y;
}
- g.fillRect(x, y - height, charWidth, height);
+ fillRect(g, x, y - height, charWidth, height);
}
x += charWidth;
}
return new Color(0, 80, 255);
default:
- System.out.println("This is not a interaction : " + lastss);
+ Console.info("This is not a interaction : " + lastss);
return null;
}
}
+
+ private void fillPolygon(Graphics g, int[] xpoints, int[] ypoints, int n)
+ {
+ setAntialias(g);
+ g.fillPolygon(xpoints, ypoints, n);
+ }
+
+ /*
+ private void fillRect(Graphics g, int a, int b, int c, int d)
+ {
+ fillRect(g, false, a, b, c, d);
+ }*/
+
+ private void fillRect(Graphics g, int a, int b, int c, int d)
+ {
+ unsetAntialias(g);
+ g.fillRect(a, b, c, d);
+ }
+
+ private void fillRoundRect(Graphics g, int a, int b, int c, int d, int e,
+ int f)
+ {
+ setAntialias(g);
+ g.fillRoundRect(a, b, c, d, e, f);
+ }
+
+ private void fillArc(Graphics g, int a, int b, int c, int d, int e, int f)
+ {
+ setAntialias(g);
+ g.fillArc(a, b, c, d, e, f);
+ }
+
+ private void drawLine(Graphics g, Stroke s, int a, int b, int c, int d)
+ {
+ Graphics2D g2d = (Graphics2D) g;
+ Stroke p = g2d.getStroke();
+ g2d.setStroke(s);
+ drawLine(g, a, b, c, d);
+ g2d.setStroke(p);
+ }
+
+ private void drawLine(Graphics g, int a, int b, int c, int d)
+ {
+ setAntialias(g);
+ g.drawLine(a, b, c, d);
+ }
+
+ private void setAntialias(Graphics g)
+ {
+ if (isVectorRendition())
+ {
+ // no need to antialias vector drawings
+ return;
+ }
+ if (Cache.getDefault("ANTI_ALIAS", true))
+ {
+ Graphics2D g2d = (Graphics2D) g;
+ g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+ RenderingHints.VALUE_ANTIALIAS_ON);
+ }
+ }
+
+ private void unsetAntialias(Graphics g)
+ {
+ if (isVectorRendition())
+ {
+ // no need to antialias vector drawings
+ return;
+ }
+ Graphics2D g2d = (Graphics2D) g;
+ g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+ RenderingHints.VALUE_ANTIALIAS_OFF);
+ }
+
+ public void setVectorRendition(boolean b)
+ {
+ vectorRendition = b;
+ }
+
+ public boolean isVectorRendition()
+ {
+ return vectorRendition;
+ }
}
final String reply = "REST not yet implemented; received "
+ request.getMethod() + ": " + request.getRequestURL()
+ (queryString == null ? "" : "?" + queryString);
- System.out.println(reply);
+ jalview.bin.Console.outPrintln(reply);
response.setHeader("Cache-Control", "no-cache/no-store");
response.setHeader("Content-type", "text/plain");
} catch (Exception ex)
{
// used to try to parse a V1 Castor generated colours file
- System.err.println("Failed to read colour scheme from " + filePath
+ jalview.bin.Console.errPrintln("Failed to read colour scheme from " + filePath
+ " : " + ex.toString());
}
cs.getSchemeClass().getDeclaredConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException e)
{
- System.err.println("Error instantiating colour scheme for "
+ jalview.bin.Console.errPrintln("Error instantiating colour scheme for "
+ cs.toString() + " " + e.getMessage());
e.printStackTrace();
} catch (ReflectiveOperationException roe)
String name = cs.getSchemeName();
if (name == null)
{
- System.err.println("ColourScheme name may not be null");
+ jalview.bin.Console.errPrintln("ColourScheme name may not be null");
return;
}
this.mask = setNums(s);
// for (int i=0; i < mask.length; i++) {
- // System.out.println(mask[i] + " " + ResidueProperties.aa[mask[i]]);
+ // jalview.bin.Console.outPrintln(mask[i] + " " + ResidueProperties.aa[mask[i]]);
// }
}
@Deprecated
public boolean isConserved(int[][] cons2, int col, int size)
{
- System.out.println("DEPRECATED!!!!");
+ jalview.bin.Console.outPrintln("DEPRECATED!!!!");
return isConserved(cons2, col, size, true);
}
if (tot > ((threshold * size) / 100))
{
- // System.out.println("True conserved "+tot+" from "+threshold+" out of
+ // jalview.bin.Console.outPrintln("True conserved "+tot+" from "+threshold+" out of
// "+size+" : "+maskstr);
return true;
}
for (int x = 0; x < this.annotation._rnasecstr.length; x++)
{
- // System.out.println(this.annotation._rnasecstr[x] + " Begin" +
+ // jalview.bin.Console.outPrintln(this.annotation._rnasecstr[x] + " Begin" +
// this.annotation._rnasecstr[x].getBegin());
- // System.out.println(this.annotation._rnasecstr[x].getFeatureGroup());
+ // jalview.bin.Console.outPrintln(this.annotation._rnasecstr[x].getFeatureGroup());
// pairs.put(this.annotation._rnasecstr[x].getBegin(),
// this.annotation._rnasecstr[x].getEnd());
@Override
public Color findColour(char c)
{
- // System.out.println("called"); log.debug
+ // jalview.bin.Console.outPrintln("called"); log.debug
// Generate a random pastel color
return ResidueProperties.purinepyrimidine[ResidueProperties.purinepyrimidineIndex[c]];// jalview.util.ColorUtils.generateRandomColor(Color.white);
{
Color currentColour = Color.white;
String currentHelix = null;
- // System.out.println(c + " " + j);
+ // jalview.bin.Console.outPrintln(c + " " + j);
currentHelix = positionsToHelix.get(j);
- // System.out.println(positionsToHelix.get(j));
+ // jalview.bin.Console.outPrintln(positionsToHelix.get(j));
if (currentHelix != null)
{
currentColour = helixcolorhash.get(currentHelix);
}
- // System.out.println(c + " " + j + " helix " + currentHelix + " " +
+ // jalview.bin.Console.outPrintln(c + " " + j + " helix " + currentHelix + " " +
// currentColour);
return currentColour;
}
{
if (!ttype.toLowerCase(Locale.ROOT).startsWith("no"))
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Ignoring unrecognised threshold type : " + ttype);
}
}
featureColour.setThreshold(Float.valueOf(tval).floatValue());
} catch (Exception e)
{
- System.err.println("Couldn't parse threshold value as a float: ("
+ jalview.bin.Console.errPrintln("Couldn't parse threshold value as a float: ("
+ tval + ")");
}
}
if (gcol.hasMoreTokens())
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Ignoring additional tokens in parameters in graduated colour specification\n");
while (gcol.hasMoreTokens())
{
- System.err.println(BAR + gcol.nextToken());
+ jalview.bin.Console.errPrintln(BAR + gcol.nextToken());
}
- System.err.println("\n");
+ jalview.bin.Console.errPrintln("\n");
}
return featureColour;
} catch (Exception e)
{
/*
- * System.out.println(this.annotation._rnasecstr[x] + " Begin" +
+ * jalview.bin.Console.outPrintln(this.annotation._rnasecstr[x] + " Begin" +
* this.annotation._rnasecstr[x].getBegin());
*/
- // System.out.println(this.annotation._rnasecstr[x].getFeatureGroup());
+ // jalview.bin.Console.outPrintln(this.annotation._rnasecstr[x].getFeatureGroup());
positionsToHelix.put(this.annotation._rnasecstr[x].getBegin(),
this.annotation._rnasecstr[x].getFeatureGroup());
public static void main(String[] args)
{
Hashtable<String, Vector<String>> aaProps = new Hashtable<>();
- System.out.println("my %aa = {");
+ jalview.bin.Console.outPrintln("my %aa = {");
// invert property hashes
for (String pname : propHash.keySet())
{
System.out.print("'" + props.nextElement() + "'");
if (props.hasMoreElements())
{
- System.out.println(", ");
+ jalview.bin.Console.outPrintln(", ");
}
}
- System.out.println("]" + (res.hasMoreElements() ? "," : ""));
+ jalview.bin.Console.outPrintln("]" + (res.hasMoreElements() ? "," : ""));
}
- System.out.println("};");
+ jalview.bin.Console.outPrintln("};");
}
// to here
if (col == null)
{
- System.out.println("Making colour from name: " + colour);
+ jalview.bin.Console.outPrintln("Making colour from name: " + colour);
col = ColorUtils.createColourFromName(colour);
}
}
} catch (Exception ex)
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Error parsing userDefinedColours:\n" + token + "\n" + ex);
}
import java.util.Map;
import java.util.Map.Entry;
+import jalview.bin.Console;
+
/**
* A base class holding methods useful to all classes that implement commands
* for structure viewers
{
return null;
}
+
+ @Override
+ public StructureCommandI restoreSession(String filePath)
+ {
+ return loadFile(filePath);
+ }
}
* @return
*/
StructureCommandI openSession(String filepath);
+
+ /**
+ * Returns command to restore a previously saved version of an existing structure viewer session file.
+ * Default implementation calls 'openSession'
+ * @param filePath
+ * @return
+ */
+ StructureCommandI restoreSession(String filePath);
+
/**
* Returns a command to ask the viewer to close down
{
if (mappings.isEmpty())
{
- System.err.println("reportMapping: No PDB/Sequence mappings.");
+ jalview.bin.Console.errPrintln("reportMapping: No PDB/Sequence mappings.");
}
else
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"reportMapping: There are " + mappings.size() + " mappings.");
int i = 0;
for (StructureMapping sm : mappings)
{
- System.err.println("mapping " + i++ + " : " + sm.pdbfile);
+ jalview.bin.Console.errPrintln("mapping " + i++ + " : " + sm.pdbfile);
}
}
}
pdbFile, sourceType, tft, paeFilename, true);
}
+
+ /**
+ * create sequence structure mappings between each sequence and the given
+ * pdbFile (retrieved via the given protocol). Either constructs a mapping
+ * using NW alignment or derives one from any available SIFTS mapping data.
+ *
+ * @param forStructureView
+ * when true, record the mapping for use in mouseOvers
+ *
+ * @param sequenceArray
+ * - one or more sequences to be mapped to pdbFile
+ * @param targetChainIds
+ * - optional chain specification for mapping each sequence to pdb
+ * (may be nill, individual elements may be nill) - JBPNote: JAL-2693
+ * - this should be List<List<String>>, empty lists indicate no
+ * predefined mappings
+ * @param pdbFile
+ * - structure data resource
+ * @param sourceType
+ * - how to resolve data from resource
+ * @param tft - specify how to interpret the temperature factor column in the atom data
+ * @param paeFilename - when not null, specifies a filename containing a matrix formatted in JSON using one of the known PAE formats
+ * @param doXferSettings - when true, transfer annotation to mapped sequences in sequenceArray
+ * @return null or the structure data parsed as a pdb file
+ */
synchronized public StructureFile setMapping(boolean forStructureView,
SequenceI[] sequenceArray, String[] targetChainIds,
String pdbFile, DataSourceType sourceType, TFType tft,
chain.transferResidueAnnotation(siftsMapping, null);
} catch (SiftsException e)
{
- System.err.println(e.getMessage());
+ jalview.bin.Console.errPrintln(e.getMessage());
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Unexpected exception during SIFTS mapping - falling back to NW for this sequence/structure pair");
- System.err.println(e.getMessage());
+ jalview.bin.Console.errPrintln(e.getMessage());
}
}
if (!foundSiftsMappings.isEmpty())
*
* if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
* && mappings[j].pdbfile.equals(sl.getPdbFile())) {
- * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
+ * jalview.bin.Console.outPrintln(pdbid+" "+mappings[j].getPdbId() +"
* "+mappings[j].pdbfile);
*
* java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
boolean removed = seqmappings.remove(acf);
if (removed && seqmappings.isEmpty())
{ // debug
- System.out.println("All mappings removed");
+ jalview.bin.Console.outPrintln("All mappings removed");
}
}
}
if (waiting)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Timed out waiting for structure viewer to load file "
+ notLoaded);
return false;
* @param getReply
* @param msg
*/
- protected List<String> executeCommands(List<StructureCommandI> commands,
+ public List<String> executeCommands(List<StructureCommandI> commands,
boolean getReply, String msg)
{
return executeCommand(getReply, msg,
return f;
}
+
+ /**
+ * Use restoreSession when you want to restore a previously saved sesssion to
+ * the running viewer instance.
+ *
+ * @param absolutePath
+ */
+ public void restoreSession(String absolutePath)
+ {
+ String prefix = getViewerType().toString();
+ try {
+
+ StructureCommandI cmd = commandGenerator.restoreSession(absolutePath);
+ if (cmd != null)
+ {
+ executeCommand(cmd, false);
+ }
+ } catch (Throwable e)
+ {
+ Console.error(String.format("Error restoring %s session: %s", prefix,
+ e.toString()));
+ }
+
+ }
+
/**
* Saves the structure viewer session to the given file
*
}
else
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Unexpected key returned from identifiers jalview service");
return idData;
}
// BH 2018 -- added more valuable report
if (errorMessage != null)
{
- System.err.println("IdentifiersUrlProvider: cannot read " + idFileName
+ jalview.bin.Console.errPrintln("IdentifiersUrlProvider: cannot read " + idFileName
+ ": " + errorMessage);
}
return idData;
}
}
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Error initialising UrlProvider - no custom url provider");
return null;
}
import java.io.PrintStream;
import jalview.bin.Jalview;
+import jalview.bin.Jalview.ExitCode;
public class AWTConsole extends WindowAdapter
implements WindowListener, ActionListener, Runnable
// testing part
// you may omit this part for your application
//
- System.out.println("Hello World 2");
- System.out.println("All fonts available to Graphic2D:\n");
+ jalview.bin.Console.outPrintln("Hello World 2");
+ jalview.bin.Console.outPrintln("All fonts available to Graphic2D:\n");
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
String[] fontNames = ge.getAvailableFontFamilyNames();
for (int n = 0; n < fontNames.length; n++)
{
- System.out.println(fontNames[n]);
+ jalview.bin.Console.outPrintln(fontNames[n]);
}
// Testing part: simple an error thrown anywhere in this JVM will be printed
// on the Console
// We do it with a seperate Thread becasue we don't wan't to break a Thread
// used by the Console.
- System.out.println("\nLets throw an error on this console");
+ jalview.bin.Console.outPrintln("\nLets throw an error on this console");
errorThrower = new Thread(this);
errorThrower.setDaemon(true);
errorThrower.start();
} catch (Exception e)
{
}
- Jalview.exit("Window closing. Bye!", 0);
+ Jalview.exit("Window closing. Bye!", ExitCode.OK);
}
@Override
if (channelPropsURL == null)
{
// complete failure of channel_properties, set all properties to defaults
- System.err.println("Failed to find '/" + CHANNEL_PROPERTIES_FILENAME
+ jalview.bin.Console.errPrintln("Failed to find '/" + CHANNEL_PROPERTIES_FILENAME
+ "' file at '"
+ (channelPropsURL == null ? "null"
: channelPropsURL.toString())
channelPropsIS.close();
} catch (IOException e)
{
- System.err.println(e.getMessage());
+ jalview.bin.Console.errPrintln(e.getMessage());
// return false;
}
}
channelProps.load(is);
} catch (FileNotFoundException e)
{
- System.err.println(e.getMessage());
+ jalview.bin.Console.errPrintln(e.getMessage());
} catch (IOException e)
{
- System.err.println(e.getMessage());
+ jalview.bin.Console.errPrintln(e.getMessage());
}
}
}
}
else
{
- System.err.println("Failed to get channel property '" + key + "'");
+ jalview.bin.Console.errPrintln("Failed to get channel property '" + key + "'");
}
}
return null;
img = imgIcon == null ? null : imgIcon.getImage();
if (img == null)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Failed to load channel image " + key + "=" + path);
if (!useClassDefaultImage)
{
{
return urlMap().getOrDefault(key, null);
}
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Do not use getImageURL(key) before using getImage(key...)");
}
return null;
}
else
{
- System.err.println("Malformed PDB DR line:" + acn);
+ jalview.bin.Console.errPrintln("Malformed PDB DR line:" + acn);
}
}
else
boolean allowSingleFilenameThatDoesNotExist)
{
pattern = substituteHomeDir(pattern);
+ String relativePattern = pattern.startsWith(File.separator) ? null
+ : pattern;
List<File> files = new ArrayList<>();
/*
* For efficiency of the Files.walkFileTree(), let's find the longest path that doesn't need globbing.
{
String pS = pattern.substring(0, lastFS + 1);
String rest = pattern.substring(lastFS + 1);
- Path parentDir = Paths.get(pS).toAbsolutePath();
+ if ("".equals(pS))
+ {
+ pS = ".";
+ }
+ Path parentDir = Paths.get(pS);
if (parentDir.toFile().exists())
{
try
return null;
String dirname = null;
- try
- {
- File p = file.getParentFile();
- File d = new File(substituteHomeDir(p.getPath()));
- dirname = d.getCanonicalPath();
- } catch (IOException e)
+ File p = file.getParentFile();
+ if (p == null)
{
- Console.debug(
- "Exception when getting dirname of '" + file.getPath() + "'",
- e);
- dirname = "";
+ p = new File(".");
}
+ File d = new File(substituteHomeDir(p.getPath()));
+ dirname = d.getPath();
return dirname;
}
+
+ public static String convertWildcardsToPath(String value, String wildcard,
+ String dirname, String basename)
+ {
+ if (value == null)
+ {
+ return null;
+ }
+ StringBuilder path = new StringBuilder();
+ int lastFileSeparatorIndex = value.lastIndexOf(File.separatorChar);
+ int wildcardBeforeIndex = value.indexOf(wildcard);
+ if (lastFileSeparatorIndex > wildcard.length() - 1
+ && wildcardBeforeIndex < lastFileSeparatorIndex)
+ {
+ path.append(value.substring(0, wildcardBeforeIndex));
+ path.append(dirname);
+ path.append(value.substring(wildcardBeforeIndex + wildcard.length(),
+ lastFileSeparatorIndex + 1));
+ }
+ else
+ {
+ path.append(value.substring(0, lastFileSeparatorIndex + 1));
+ }
+ int wildcardAfterIndex = value.indexOf(wildcard,
+ lastFileSeparatorIndex);
+ if (wildcardAfterIndex > lastFileSeparatorIndex)
+ {
+ path.append(value.substring(lastFileSeparatorIndex + 1,
+ wildcardAfterIndex));
+ path.append(basename);
+ path.append(value.substring(wildcardAfterIndex + wildcard.length()));
+ }
+ else
+ {
+ path.append(value.substring(lastFileSeparatorIndex + 1));
+ }
+ return path.toString();
+ }
+
+ public static File getParentDir(File file)
+ {
+ if (file == null)
+ {
+ return null;
+ }
+ File parentDir = file.getAbsoluteFile().getParentFile();
+ return parentDir;
+ }
+
+ public static boolean checkParentDir(File file, boolean mkdirs)
+ {
+ if (file == null)
+ {
+ return false;
+ }
+ File parentDir = getParentDir(file);
+ if (parentDir.exists())
+ {
+ // already exists, nothing to do so nothing to worry about!
+ return true;
+ }
+
+ if (!mkdirs)
+ {
+ return false;
+ }
+
+ Path path = file.toPath();
+ for (int i = 0; i < path.getNameCount(); i++)
+ {
+ Path p = path.getName(i);
+ if ("..".equals(p.toString()))
+ {
+ Console.warn("Cautiously not running mkdirs on " + file.toString()
+ + " because the path to be made contains '..'");
+ return false;
+ }
+ }
+
+ return parentDir.mkdirs();
+ }
}
// debug
/*
* for (int s = 0; s <= rg.numSubs(); s++) {
- * System.err.println("Sub " + s + " : " + rg.matchedFrom(s) +
+ * jalview.bin.Console.errPrintln("Sub " + s + " : " + rg.matchedFrom(s) +
* " : " + rg.matchedTo(s) + " : '" + rg.stringMatched(s) + "'");
* }
*/
if (url == null)
{
- System.out.println("Created NO urls.");
+ jalview.bin.Console.outPrintln("Created NO urls.");
}
else
{
- System.out.println("Created a url from " + ((int[]) url[0])[0]
+ jalview.bin.Console.outPrintln("Created a url from " + ((int[]) url[0])[0]
+ "out of " + idstring[0].length + " sequences.");
- System.out.println("Sequences that did not match:");
+ jalview.bin.Console.outPrintln("Sequences that did not match:");
for (int sq = 0; sq < idstring[0].length; sq++)
{
if (!((boolean[]) url[1])[sq])
{
- System.out.println("Seq " + sq + ": " + idstring[0][sq] + "\t: "
+ jalview.bin.Console.outPrintln("Seq " + sq + ": " + idstring[0][sq] + "\t: "
+ idstring[1][sq]);
}
}
- System.out.println("Sequences that DID match:");
+ jalview.bin.Console.outPrintln("Sequences that DID match:");
for (int sq = 0; sq < idstring[0].length; sq++)
{
if (((boolean[]) url[1])[sq])
{
- System.out.println("Seq " + sq + ": " + idstring[0][sq] + "\t: "
+ jalview.bin.Console.outPrintln("Seq " + sq + ": " + idstring[0][sq] + "\t: "
+ idstring[1][sq]);
}
}
- System.out.println("The generated URL:");
- System.out.println(((String[]) url[3])[0]);
+ jalview.bin.Console.outPrintln("The generated URL:");
+ jalview.bin.Console.outPrintln(((String[]) url[3])[0]);
}
}
GroupUrlLink ul = new GroupUrlLink(links[i]);
if (ul.isValid())
{
- System.out.println("\n\n\n");
- System.out.println(
+ jalview.bin.Console.outPrintln("\n\n\n");
+ jalview.bin.Console.outPrintln(
"Link " + i + " " + links[i] + " : " + ul.toString());
- System.out.println(" pref : " + ul.getUrl_prefix());
- System.out.println(" IdReplace : " + ul.getIDRegexReplace());
- System.out.println(" SeqReplace : " + ul.getSeqRegexReplace());
- System.out.println(" Suffixes : " + ul.getUrl_suffix());
+ jalview.bin.Console.outPrintln(" pref : " + ul.getUrl_prefix());
+ jalview.bin.Console.outPrintln(" IdReplace : " + ul.getIDRegexReplace());
+ jalview.bin.Console.outPrintln(" SeqReplace : " + ul.getSeqRegexReplace());
+ jalview.bin.Console.outPrintln(" Suffixes : " + ul.getUrl_suffix());
- System.out.println(
+ jalview.bin.Console.outPrintln(
"<insert input id and sequence strings here> Without onlyIfMatches:");
Object[] urls;
try
testUrls(ul, seqsandids, urls);
} catch (UrlStringTooLongException ex)
{
- System.out.println("too long exception " + ex);
+ jalview.bin.Console.outPrintln("too long exception " + ex);
}
- System.out.println(
+ jalview.bin.Console.outPrintln(
"<insert input id and sequence strings here> With onlyIfMatches set:");
try
{
testUrls(ul, seqsandids, urls);
} catch (UrlStringTooLongException ex)
{
- System.out.println("too long exception " + ex);
+ jalview.bin.Console.outPrintln("too long exception " + ex);
}
}
else
{
- System.err.println("Invalid URLLink : " + links[i] + " : "
+ jalview.bin.Console.errPrintln("Invalid URLLink : " + links[i] + " : "
+ ul.getInvalidMessage());
}
}
public static boolean checkUrlAvailable(URL url, int readTimeout)
throws IOException, ProtocolException
{
- // System.out.println(System.currentTimeMillis() + " " + url);
+ // jalview.bin.Console.outPrintln(System.currentTimeMillis() + " " + url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BitmapImageSizing bis = ImageMaker.getScaleWidthHeight(width, height,
userBis);
- float usescale = bis.scale;
- int usewidth = bis.width;
- int useheight = bis.height;
+ float usescale = bis.scale();
+ int usewidth = bis.width();
+ int useheight = bis.height();
bi = new BufferedImage(usewidth, useheight, BufferedImage.TYPE_INT_RGB);
graphics = bi.getGraphics();
}
/**
- * Takes suggested float scale, int width, int height and create a bounding
- * box returned as a BitmapImageSizing object with consistent scale, width,
- * height fields.
+ * Takes initial width and height, and suggested float scale, int width, int
+ * height and create a bounding box returned as a BitmapImageSizing object
+ * with consistent scale, width, height fields.
*
+ * @param width
+ * The unscaled image width
+ * @param height
+ * The unscaled image height
* @param scale
+ * The suggested scaling
* @param bitmapwidth
+ * The suggested width
* @param bitmapheight
- * @return BitmapImageSizing
+ * The suggested height
+ * @return BitmapImageSizing A consistent scale,width and height for the final
+ * image
*/
public static BitmapImageSizing getScaleWidthHeight(int width, int height,
float scale, int bitmapwidth, int bitmapheight)
int usewidth = width;
int useheight = height;
+ if ((width == 0 && bitmapwidth > 0)
+ || (height == 0 && bitmapheight > 0))
+ {
+ // original image is zero sized! Avoid dividing by zero!
+ return BitmapImageSizing.nullBitmapImageSizing();
+ }
+
// use the smallest positive scale (i.e. fit in the box)
if (scale > 0.0f)
{
useheight = bitmapheight;
}
}
- return new BitmapImageSizing(usescale, usewidth, useheight);
+ return new BitmapImageSizing(usescale, usewidth, useheight, false);
}
/**
public static BitmapImageSizing getScaleWidthHeight(int width, int height,
BitmapImageSizing bis)
{
- return ImageMaker.getScaleWidthHeight(width, height, bis.scale,
- bis.width, bis.height);
+ return ImageMaker.getScaleWidthHeight(width, height, bis.scale(),
+ bis.width(), bis.height());
}
/**
public static BitmapImageSizing parseScaleWidthHeightStrings(
String scaleS, String widthS, String heightS)
{
+ if (scaleS == null && widthS == null && heightS == null)
+ {
+ // if all items are null (i.e. not provided) we use the dynamic
+ // preferences set BIS
+ return BitmapImageSizing.defaultBitmapImageSizing();
+ }
+
float scale = 0.0f;
int width = 0;
int height = 0;
}
}
- return new BitmapImageSizing(scale, width, height);
+ return new BitmapImageSizing(scale, width, height, false);
}
}
import java.net.URL;
import java.util.Properties;
+import jalview.bin.Console;
+
public class LaunchUtils
{
+ // setting these is LaunchUtils so don't need to import Platform
+ public final static boolean isMac = System.getProperty("os.name")
+ .indexOf("Mac") > -1;
+
+ public final static boolean isWindows = System.getProperty("os.name")
+ .indexOf("Win") > -1;
+
+ private static boolean isJS = /** @j2sNative true || */
+ false;
+
public static void loadChannelProps(File dir)
{
ChannelProperties.loadProps(dir);
return null;
} catch (IOException e)
{
- System.err.println(e.getMessage());
+ jalview.bin.Console.errPrintln(e.getMessage());
return null;
}
}
public static int getJavaCompileVersion()
{
- if (Platform.isJS())
+ if (LaunchUtils.isJS)
{
return -1;
}
null);
if (JCV == null)
{
- System.out.println(
+ Console.errPrintln(
"Could not obtain JAVA_COMPILE_VERSION for comparison");
return -2;
}
JAVA_COMPILE_VERSION = Integer.parseInt(JCV);
} catch (MalformedURLException e)
{
- System.err.println("Could not find " + buildDetails);
+ jalview.bin.Console.errPrintln("Could not find " + buildDetails);
return -3;
} catch (IOException e)
{
- System.err.println("Could not load " + buildDetails);
+ jalview.bin.Console.errPrintln("Could not load " + buildDetails);
return -4;
} catch (NumberFormatException e)
{
- System.err.println("Could not parse JAVA_COMPILE_VERSION");
+ jalview.bin.Console.errPrintln("Could not parse JAVA_COMPILE_VERSION");
return -5;
}
public static int getJavaVersion()
{
- if (Platform.isJS())
+ if (LaunchUtils.isJS)
{
return -1;
}
String JV = System.getProperty("java.version");
if (JV == null)
{
- System.out.println("Could not obtain java.version for comparison");
+ Console.errPrintln("Could not obtain java.version for comparison");
return -2;
}
if (JV.startsWith("1."))
: Integer.parseInt(JV.substring(0, JV.indexOf(".")));
} catch (NumberFormatException e)
{
- System.err.println("Could not parse java.version");
+ jalview.bin.Console.errPrintln("Could not parse java.version");
return -3;
}
return JAVA_VERSION;
public static boolean checkJavaVersion()
{
- if (Platform.isJS())
+ if (LaunchUtils.isJS)
{
return true;
}
if (java_compile_version <= 0 || java_version <= 0)
{
- System.out.println("Could not make Java version check");
+ Console.errPrintln("Could not make Java version check");
return true;
}
// Warn if these java.version and JAVA_COMPILE_VERSION conditions exist
return true;
}
+
+ public static String findJavaBin(boolean winConsole)
+ {
+ return findJavaBin(System.getProperty("java.home"), winConsole, true);
+ }
+
+ /*
+ * Returns a string path to the most likely java binary wanted to run this
+ * installation of Jalview.
+ *
+ * @param winConsole whether to use java.exe (console) in preference to javaw.exe
+ * (only affects Windows).
+ * @param javaHome Try this javaHome dir (defaults to the running java.home).
+ * @param generic Return a generic java command if not found.
+ */
+ public static String findJavaBin(String javaHome, boolean winConsole,
+ boolean generic)
+ {
+ String javaBin = null;
+ final String javaExe = winConsole ? "java.exe" : "javaw.exe";
+ final String java = "java";
+
+ if (javaHome != null)
+ {
+ // property "channel.app_name" is set by install4j when launching getdown
+ String propertyAppName = System.getProperty("channel.app_name");
+ final String appName = (propertyAppName != null
+ && propertyAppName.length() > 0) ? propertyAppName
+ : ChannelProperties.getProperty("app_name");
+
+ final String javaBinDir = javaHome + File.separator + "bin"
+ + File.separator;
+
+ // appName and "Jalview" will not point to javaw.exe or java.exe but in
+ // this case that's okay because the taskbar display name problem doesn't
+ // manifest in Windows. See JAL-3820, JAL-4189.
+ for (String name : new String[] { appName, "Jalview", java, javaExe })
+ {
+ if (LaunchUtils.checkJVMSymlink(javaBinDir + name, winConsole))
+ {
+ javaBin = javaBinDir + name;
+ break;
+ }
+ }
+ }
+
+ if (javaBin == null && generic)
+ {
+ javaBin = LaunchUtils.isWindows ? javaExe : java;
+ }
+
+ return javaBin;
+ }
+
+ /*
+ * checkJVMSymlink returns true if the path in testBin *is* a java binary, or
+ * points to a java binary.
+ * @param testBin The binary or symbolic link to check
+ * @param winConsole whether we are in/want a Windows console (only relevant for Windows,
+ * determines whether we use java.exe or javaw.exe)
+ */
+ private static boolean checkJVMSymlink(String testBin, boolean winConsole)
+ {
+ File testBinFile = new File(testBin);
+ if (!testBinFile.exists())
+ {
+ return false;
+ }
+ File targetFile = null;
+ try
+ {
+ targetFile = testBinFile.getCanonicalFile();
+ } catch (IOException e)
+ {
+ return false;
+ }
+ final String javaExe = winConsole ? "java.exe" : "javaw.exe";
+ if (targetFile != null && ("java".equals(targetFile.getName())
+ || javaExe.equals(targetFile.getName())))
+ {
+ return true;
+ }
+ return false;
+ }
}
init = true;
} catch (Exception e)
{
- System.err.println("Problems initializing the log4j system\n");
+ jalview.bin.Console.errPrintln("Problems initializing the log4j system\n");
e.printStackTrace(System.err);
}
}
public class MapUtils
{
- /*
- * Return the value of the first key that exists in the map
+ /**
+ * Return the value of the first key that exists in the map and has a non-null
+ * value
*/
public static <K, V> V getFirst(Map<K, V> map, K... keys)
{
return getFirst(false, map, keys);
}
+ /**
+ * Return the value of the first key that exists in the map - optionally
+ * limiting to only returning non-null values for first extant key encountered
+ */
public static <K, V> V getFirst(boolean nonNull, Map<K, V> map, K... keys)
{
for (K key : keys)
return null;
}
+ /**
+ * peeks in to the map and returns true if one of a bunch of keys is contained
+ * in it
+ *
+ * @param <K>
+ * @param map
+ * @param keys
+ * @return
+ */
public static <K> boolean containsAKey(Map<K, ?> map, K... keys)
{
for (K key : keys)
time = mark = t;
if (msg != null)
{
- System.err.println("Platform: timer reset\t\t\t" + msg);
+ jalview.bin.Console.errPrintln("Platform: timer reset\t\t\t" + msg);
}
break;
case TIME_MARK:
}
if (msg != null)
{
- System.err.println("Platform: timer mark\t" + ((t - time) / 1000f)
+ jalview.bin.Console.errPrintln("Platform: timer mark\t" + ((t - time) / 1000f)
+ "\t" + ((t - mark) / 1000f) + "\t" + msg);
}
mark = t;
case TIME_GET:
if (msg != null)
{
- System.err.println("Platform: timer dur\t" + ((t - time) / 1000f)
+ jalview.bin.Console.errPrintln("Platform: timer dur\t" + ((t - time) / 1000f)
+ "\t" + ((duration) / 1000f) + "\t" + msg);
}
set = 0;
* info[key];
*/
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Platform id=" + id + " reading Info." + key + " = " + value);
p.put(id + "_" + key, value);
if (isJS())
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Platform adding known access-control-allow-origin * for domain "
+ domain);
/**
* @j2sNative var a =
* decodeURI((document.location.href.replace("&","?").split("?j2s")[0]
* + "?").split("?")[1].split("#")[0]); a &&
- * (System.out.println("URL arguments detected were "+a)) &&
+ * (jalview.bin.Console.outPrintln("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
+ * (J2S.thisApplet.__Info.args = a) && (jalview.bin.Console.outPrintln("URL
* arguments were passed to J2S main."));
*/
} catch (Throwable t)
jv.clear();
if (DEBUG)
{
- System.err.println("Array from '" + delimiter
+ jalview.bin.Console.errPrintln("Array from '" + delimiter
+ "' separated List:\n" + v.length);
for (int i = 0; i < v.length; i++)
{
- System.err.println("item " + i + " '" + v[i] + "'");
+ jalview.bin.Console.errPrintln("item " + i + " '" + v[i] + "'");
}
}
return v;
}
if (DEBUG)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Empty Array from '" + delimiter + "' separated List");
}
return null;
{
System.err
.println("Returning '" + separator + "' separated List:\n");
- System.err.println(v);
+ jalview.bin.Console.errPrintln(v);
}
return v.toString();
}
if (DEBUG)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Returning empty '" + separator + "' separated List\n");
}
return "" + separator;
return min < text.length() + 1 ? min : -1;
}
+ public static boolean equalsIgnoreCase(String s1, String s2)
+ {
+ if (s1 == null || s2 == null)
+ {
+ return s1 == s2;
+ }
+ return s1.toLowerCase(Locale.ROOT).equals(s2.toLowerCase(Locale.ROOT));
+ }
+
public static int indexOfFirstWhitespace(String text)
{
int index = -1;
// debug
for (int s = 0; s <= rg.numSubs(); s++)
{
- System.err.println("Sub " + s + " : " + rg.matchedFrom(s)
+ jalview.bin.Console.errPrintln("Sub " + s + " : " + rg.matchedFrom(s)
+ " : " + rg.matchedTo(s) + " : '"
+ rg.stringMatched(s) + "'");
}
package jalview.util.imagemaker;
+import jalview.bin.Cache;
+
public class BitmapImageSizing
{
- public final float scale;
+ private final float scale;
+
+ private final int width;
- public final int width;
+ private final int height;
- public final int height;
+ private boolean isDefault = false;
- public BitmapImageSizing(float scale, int width, int height)
+ public BitmapImageSizing(float scale, int width, int height,
+ boolean isDefault)
{
this.scale = scale;
this.width = width;
this.height = height;
+ this.isDefault = isDefault;
+ }
+
+ public boolean isNull()
+ {
+ return scale == 0.0f && width == 0 && height == 0;
}
public static BitmapImageSizing nullBitmapImageSizing()
{
- return new BitmapImageSizing(0.0f, 0, 0);
+ return new BitmapImageSizing(0.0f, 0, 0, false);
+ }
+
+ public static final String BITMAP_SCALE = "BITMAP_SCALE";
+
+ public static final String BITMAP_HEIGHT = "BITMAP_HEIGHT";
+
+ public static final String BITMAP_WIDTH = "BITMAP_WIDTH";
+
+ /**
+ *
+ * @return bean configured from Cache keys
+ */
+ public static BitmapImageSizing defaultBitmapImageSizing()
+ {
+ return new BitmapImageSizing(0f, 0, 0, true);
+ }
+
+ private float defaultScale()
+ {
+ return Cache.getDefault(BITMAP_SCALE, 0f);
+ }
+
+ private int defaultWidth()
+ {
+ return Cache.getDefault(BITMAP_WIDTH, 0);
+ }
+
+ private int defaultHeight()
+ {
+ return Cache.getDefault(BITMAP_HEIGHT, 0);
+ }
+
+ public float scale()
+ {
+ return isDefault() ? defaultScale() : scale;
+ }
+
+ public int width()
+ {
+ return isDefault() ? defaultWidth() : width;
+ }
+
+ public int height()
+ {
+ return isDefault() ? defaultHeight() : height;
+ }
+
+ public boolean isDefault()
+ {
+ return isDefault;
}
}
}
if (calculator.workingInvolvedWith(alignmentAnnotation))
{
- // System.err.println("grey out ("+alignmentAnnotation.label+")");
+ // jalview.bin.Console.errPrintln("grey out ("+alignmentAnnotation.label+")");
return true;
}
return false;
{
if (sequenceSetID != null)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Warning - overwriting a sequenceSetId for a viewport!");
}
sequenceSetID = new String(newid);
{
if (aa == null)
{
- System.err.println("Null annotation row: ignoring.");
+ jalview.bin.Console.errPrintln("Null annotation row: ignoring.");
continue;
}
if (!aa.visible)
{
if (this == av)
{
- System.err.println("Ignoring recursive setCodingComplement request");
+ jalview.bin.Console.errPrintln("Ignoring recursive setCodingComplement request");
}
else
{
*/
public void setStartEndSeq(int start, int end)
{
- // System.out.println("ViewportRange setStartEndSeq " + start + " " + end);
+ // jalview.bin.Console.outPrintln("ViewportRange setStartEndSeq " + start + " " + end);
int[] oldvalues = updateStartEndSeq(start, end);
int oldstartseq = oldvalues[0];
int oldendseq = oldvalues[1];
{
vpstart = visHeight - h;
}
- // System.out.println("ViewportRanges setviewportStartAndHeight " + vpstart
+ // jalview.bin.Console.outPrintln("ViewportRanges setviewportStartAndHeight " + vpstart
// + " " + start + " " + h + " " + getVisibleAlignmentHeight());
setStartEndSeq(vpstart, vpstart + h - 1);
*/
package jalview.viewmodel.styles;
-import jalview.api.ViewStyleI;
-
import java.awt.Color;
+import jalview.api.ViewStyleI;
+
/**
* A container for holding alignment view properties. View properties are
* data-independent, which means they can be safely copied between views
{
synchronized (inProgress)
{
- // System.err.println("Worker " + worker + " marked as complete.");
+ // jalview.bin.Console.errPrintln("Worker " + worker + " marked as complete.");
inProgress.remove(worker);
List<AlignCalcWorkerI> upd = updating.get(worker.getClass());
if (upd != null)
public boolean isWorking(AlignCalcWorkerI worker)
{
synchronized (inProgress)
- {// System.err.println("isWorking : worker "+(worker!=null ?
+ {// jalview.bin.Console.errPrintln("isWorking : worker "+(worker!=null ?
// worker.getClass():"null")+ " "+hashCode());
return worker != null && inProgress.contains(worker);
}
boolean working=false;
synchronized (inProgress)
{
- // System.err.println("isWorking "+hashCode());
+ // jalview.bin.Console.errPrintln("isWorking "+hashCode());
working |= inProgress.size() > 0;
}
synchronized (updating)
* {
*
* if (isPending(worker)) { worker.abortAndDestroy(); startWorker(worker); }
- * else { System.err.println("Pending exists for " + workerClass); } }
+ * else { jalview.bin.Console.errPrintln("Pending exists for " + workerClass); } }
*/
}
.getCurrentAlignFrame().alignPanel;
if (currentAlignFrame == null)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Can't register calculator as no alignment window has focus");
return;
}
}
else
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Can't register calculator as no alignment window has focus");
}
}
}
while (!calcMan.notifyWorking(this))
{
- // System.err.println("Thread
+ // jalview.bin.Console.errPrintln("Thread
// (Consensus"+Thread.currentThread().getName()+") Waiting around.");
try
{
{
Console.debug("Interrupted sleep waiting for next job poll.", e);
}
- // System.out.println("I'm alive "+alTitle);
+ // jalview.bin.Console.outPrintln("I'm alive "+alTitle);
}
}
if (jobComplete && jobs != null)
}
} catch (Exception e)
{
- System.err.println("Couldn't locate PICR service instance.\n");
+ jalview.bin.Console.errPrintln("Couldn't locate PICR service instance.\n");
e.printStackTrace();
}
while (sdataset.size() > 0 && db < dbSources.length)
{
int maxqlen = 1; // default number of queries made at one time
- System.out.println("Verifying against " + dbSources[db].getDbName());
+ jalview.bin.Console.outPrintln("Verifying against " + dbSources[db].getDbName());
// iterate through db for each remaining un-verified sequence
SequenceI[] currSeqs = new SequenceI[sdataset.size()];
true);
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Exception with Picr for '" + token + "'\n");
e.printStackTrace();
}
// present, and do a transferReferences
// otherwise transfer non sequence x-references directly.
}
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Validated ID against PICR... (for what its worth):"
+ token);
addSeqId(sequence, token);
else
{
// if ()
- // System.out.println("Not querying source with
+ // jalview.bin.Console.outPrintln("Not querying source with
// token="+token+"\n");
addSeqId(sequence, token);
queries.addElement(token.toUpperCase(Locale.ROOT));
DbSourceProxy dbSourceProxy, AlignmentI retrievedAl,
boolean trimDatasetSeqs, List<String> warningMessages)
{
- // System.out.println("trimming ? " + trimDatasetSeqs);
+ // jalview.bin.Console.outPrintln("trimming ? " + trimDatasetSeqs);
if (retrievedAl == null || retrievedAl.getHeight() == 0)
{
return false;
}
}
- System.out.println("Adding dbrefs to " + sequence.getName()
+ jalview.bin.Console.outPrintln("Adding dbrefs to " + sequence.getName()
+ " from " + dbSource + " sequence : "
+ retrievedSeq.getName());
sequence.transferAnnotation(retrievedSeq, mp);
}
// } catch (OutOfMemoryError e)
// {
- // System.err.println("Out of memory when displaying status. Squashing
+ // jalview.bin.Console.errPrintln("Out of memory when displaying status. Squashing
// error.");
// wsInfo.appendProgressText(j.jobnum,
// "..\n(Out of memory when displaying status)\n");
addDBRefSourceImpl(PfamFull.class);
addDBRefSourceImpl(PfamSeed.class);
addDBRefSourceImpl(RfamSeed.class);
- addDBRefSourceImpl(EBIAlfaFold.class);
+ // Technically not a database cross reference we fetch directly
+ // Useful for AlphaFold debugging
+ // addDBRefSourceImpl(EBIAlfaFold.class);
}
/**
if (!isValidReference(id))
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"(AFClient) Ignoring invalid alphafold query: '" + id + "'");
stopQuery();
return null;
}
} catch (Exception e)
{
- System.err.println("Warning: problems reading temp file " + file);
+ jalview.bin.Console.errPrintln("Warning: problems reading temp file " + file);
return null;
}
return bf;
}
else
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"No record found for '" + emprefx + ":" + query + "'");
}
}
}
} catch (Exception e)
{
- System.err.println("EMBL Record Features parsing error!");
+ jalview.bin.Console.errPrintln("EMBL Record Features parsing error!");
System.err
.println("Please report the following to help@jalview.org :");
- System.err.println("EMBL Record " + accession);
- System.err.println("Resulted in exception: " + e.getMessage());
+ jalview.bin.Console.errPrintln("EMBL Record " + accession);
+ jalview.bin.Console.errPrintln("Resulted in exception: " + e.getMessage());
e.printStackTrace(System.err);
}
codonStart = Integer.parseInt(value.trim());
} catch (NumberFormatException e)
{
- System.err.println("Invalid codon_start in XML for "
+ jalview.bin.Console.errPrintln("Invalid codon_start in XML for "
+ entry.getAccession() + ": " + e.getMessage());
}
}
* workaround until we handle dna location for CDS sequence
* e.g. location="X53828.1:60..1058" correctly
*/
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Implementation Notice: EMBLCDS records not properly supported yet - Making up the CDNA region of this sequence... may be incorrect ("
+ sourceDb + ":" + entry.getAccession() + ")");
int dnaLength = dna.getLength();
if (translationLength * 3 == (1 - codonStart + dnaLength))
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Not allowing for additional stop codon at end of cDNA fragment... !");
// this might occur for CDS sequences where no features are marked
exons = new int[] { dna.getStart() + (codonStart - 1),
}
if ((translationLength + 1) * 3 == (1 - codonStart + dnaLength))
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Allowing for additional stop codon at end of cDNA fragment... will probably cause an error in VAMSAs!");
exons = new int[] { dna.getStart() + (codonStart - 1),
dna.getEnd() - 3 };
if (!isValidReference(id))
{
- System.err.println("Ignoring invalid pdb query: '" + id + "'");
+ jalview.bin.Console.errPrintln("Ignoring invalid pdb query: '" + id + "'");
stopQuery();
return null;
}
String database = parseIds(ids, querystring);
if (database == null)
{
- System.err.println("Invalid Query string : '" + ids + "'");
- System.err.println("Should be of form 'dbname:q1;q2;q3;q4'");
+ jalview.bin.Console.errPrintln("Invalid Query string : '" + ids + "'");
+ jalview.bin.Console.errPrintln("Should be of form 'dbname:q1;q2;q3;q4'");
return null;
}
}
return (String[]) arl.toArray();
}
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Warning: response code " + responseCode + " for " + url);
} catch (OutOfMemoryError er)
{
- System.out.println("OUT OF MEMORY DOWNLOADING QUERY FROM " + database
+ jalview.bin.Console.outPrintln("OUT OF MEMORY DOWNLOADING QUERY FROM " + database
+ ":\n" + ids);
throw er;
} catch (Exception ex)
if (!ex.getMessage().startsWith(
"uk.ac.ebi.jdbfetch.exceptions.DbfNoEntryFoundException"))
{
- System.err.println("Unexpected exception when retrieving from "
+ jalview.bin.Console.errPrintln("Unexpected exception when retrieving from "
+ database + "\nQuery was : '" + ids + "'");
ex.printStackTrace(System.err);
}
public Annotate3D()
{
- System.out.println("Annotate3D");
+ jalview.bin.Console.outPrintln("Annotate3D");
// try {
// Create a URL for the desired page
// String id = "1HR2";
// OutputStream out1 = null;
// out = new BufferedWriter(new OutputStreamWriter(out1, "temp.rnaml"));
// while ((str = in.readLine()) != null) {
- // System.out.println(str);
+ // jalview.bin.Console.outPrintln(str);
// out.write(str);
// }
// in.close();
public Annotate3D(String path) throws InterruptedException
{
- System.out.println("Annotate3D");
+ jalview.bin.Console.outPrintln("Annotate3D");
try
{
// //URL url = new
// URL("http://paradise-ibmc.u-strasbg.fr/webservices/annotate3d?data="+inFile);
- // System.out.println("Step1");
+ // jalview.bin.Console.outPrintln("Step1");
// FileReader r = new FileReader(inFile);
// BufferedReader in = new BufferedReader(r);
// StringBuffer content = new StringBuffer();
- // System.out.println("Step2");
+ // jalview.bin.Console.outPrintln("Step2");
// while(in.readLine()!=null){
// content.append(in.readLine());
- // //System.out.println("Step3"+in.readLine());
+ // //jalview.bin.Console.outPrintln("Step3"+in.readLine());
// }
//
// String data = URLEncoder.encode("data", "UTF-8") + "=" +
// FileReader r = new FileReader(path);
// BufferedReader in = new BufferedReader(r);
// StringBuffer content = new StringBuffer();
- // System.out.println("Step1");
+ // jalview.bin.Console.outPrintln("Step1");
// while(in.readLine()!=null){
// content.append(in.readLine());
//
// }
- // System.out.println("Step2");
+ // jalview.bin.Console.outPrintln("Step2");
// String data = URLEncoder.encode("data", "UTF-8") + "=" +
// URLEncoder.encode(content.toString(), "UTF-8");
- // System.out.println("Step2");
+ // jalview.bin.Console.outPrintln("Step2");
// URL url = new
// URL("http://paradise-ibmc.u-strasbg.fr/webservices/annotate3d?data="+data);
// DataInputStream is = new DataInputStream(url.openStream());
// String str;
// while ((str = is.readLine()) != null) {
- // System.out.println(str);
+ // jalview.bin.Console.outPrintln(str);
// //out.write(str);
// }
FileReader r = new FileReader(path);
while ((str = in.readLine()) != null)
{
- // System.out.println(str);
+ // jalview.bin.Console.outPrintln(str);
content = content + str;
}
- System.out.println("pdbfile=" + content.toString());
- System.out.println("capacité=" + content.length());
+ jalview.bin.Console.outPrintln("pdbfile=" + content.toString());
+ jalview.bin.Console.outPrintln("capacité=" + content.length());
String paramfile = URLEncoder.encode(content.toString(), "UTF-8");
- System.out.println("param=" + paramfile);
+ jalview.bin.Console.outPrintln("param=" + paramfile);
URL url = new URL(
"http://paradise-ibmc.u-strasbg.fr/webservices/annotate3d?data="
+ content);
String str4;
while ((str4 = is.readLine()) != null)
{
- System.out.println(str4);
+ jalview.bin.Console.outPrintln(str4);
// out.write(str);
}
in.close();
// BufferedReader in1 = new BufferedReader(is);
// OutputStream out1 = null;
- // System.out.println("Step3");
+ // jalview.bin.Console.outPrintln("Step3");
// BufferedWriter out = new BufferedWriter(new OutputStreamWriter(out1,
// "temp.rnaml"));
//
// return;
- // System.out.println(data.length());
- // System.out.println("step2");
+ // jalview.bin.Console.outPrintln(data.length());
+ // jalview.bin.Console.outPrintln("step2");
// URL url = new
// URL("http://paradise-ibmc.u-strasbg.fr/webservices/annotate3d?data="+data);
- // System.out.println("step3");
+ // jalview.bin.Console.outPrintln("step3");
// URLConnection conn = url.openConnection();
// conn.setDoOutput(true);
// OutputStreamWriter writer = new
// //String line;
// while ((line = reader.readLine()) != null) {
// answer.append(line);
- // System.out.println(line);
+ // jalview.bin.Console.outPrintln(line);
// }
// writer.close();
// reader.close();
// out = new BufferedWriter(new FileWriter("temp.rnaml"));
// while ((str = in.readLine()) != null) {
- // System.out.println(str);
+ // jalview.bin.Console.outPrintln(str);
// out.write(str);
- // System.out.println(str);
+ // jalview.bin.Console.outPrintln(str);
// in.close();
// out.close();
// public BufferedWriter getReader()
// {
- // System.out.println("The buffer");
+ // jalview.bin.Console.outPrintln("The buffer");
// return out;
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"jalview.rootRegistry is not a proper url!\nWas set to "
+ RootServiceURL + "\n" + e);
}
WS1Client instance = serviceClientBindings.get(sh.getAbstractName());
if (instance == null)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"WARNING - POSSIBLE IMPLEMENTATION ERROR - cannot find WSClient implementation for "
+ sh.getAbstractName());
}
wsInfo.setProgressText(j.getJobnum(),
"Failed to submit the prediction. (Just close the window)\n"
+ "It is most likely that there is a problem with the server.\n");
- System.err.println(
+ jalview.bin.Console.errPrintln(
"JPredWS Client: Failed to submit the prediction. Quite possibly because of a server error - see below)\n"
+ e.getMessage() + "\n");
j.setJobId(jobsubmit.getJobId());
j.setSubmitted(true);
j.setSubjobComplete(false);
- // System.out.println(WsURL + " Job Id '" + jobId + "'");
+ // jalview.bin.Console.outPrintln(WsURL + " Job Id '" + jobId + "'");
}
else
{
{
// TODO: JBPNote catch timeout or other fault types explicitly
// For unexpected errors
- System.err.println(WebServiceName
+ jalview.bin.Console.errPrintln(WebServiceName
+ "Client: Failed to submit the sequences for alignment (probably a server side problem)\n"
+ "When contacting Server:" + WsUrl + "\n" + e.toString()
+ "\n");
results++;
// if (Cache.isDebugEnabled())
// {
- // System.out.println("Job lob for job
+ // jalview.bin.Console.outPrintln("Job lob for job
// "+jobs[j].getJobId()+":"+jobs[j].getJobnum());
- // System.out.println(jobs[j].getStatus());
+ // jalview.bin.Console.outPrintln(jobs[j].getStatus());
// }
vamsas.objects.simple.Alignment valign = ((MsaResult) ((MsaWSJob) jobs[j]).result)
}
else
{
- System.out.println("MERGE WITH OLD FRAME");
+ jalview.bin.Console.outPrintln("MERGE WITH OLD FRAME");
// TODO: modify alignment in original frame, replacing old for new
// alignment using the commands.EditCommand model to ensure the update can
// be undone
}
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Failed to parse the annotation file associated with the alignment.");
- System.err.println(">>>EOF" + inFile + "\n<<<EOF\n");
+ jalview.bin.Console.errPrintln(">>>EOF" + inFile + "\n<<<EOF\n");
e.printStackTrace(System.err);
}
}
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Failed to parse the Features file associated with the alignment.");
- System.err.println(">>>EOF" + inFile + "\n<<<EOF\n");
+ jalview.bin.Console.errPrintln(">>>EOF" + inFile + "\n<<<EOF\n");
e.printStackTrace(System.err);
}
jalview.io.NewickFile nf = null;
}
} catch (Exception e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Failed to parse the treeFile associated with the alignment.");
- System.err.println(">>>EOF" + inFile + "\n<<<EOF\n");
+ jalview.bin.Console.errPrintln(">>>EOF" + inFile + "\n<<<EOF\n");
e.printStackTrace(System.err);
}
j.setJobId(jobsubmit.getJobId());
j.setSubmitted(true);
j.setSubjobComplete(false);
- // System.out.println(WsURL + " Job Id '" + jobId + "'");
+ // jalview.bin.Console.outPrintln(WsURL + " Job Id '" + jobId + "'");
}
else
{
{
// TODO: JBPNote catch timeout or other fault types explicitly
// For unexpected errors
- System.err.println(WebServiceName
+ jalview.bin.Console.errPrintln(WebServiceName
+ "Client: Failed to submit the sequences for alignment (probably a server side problem)\n"
+ "When contacting Server:" + WsUrl + "\n" + e.toString()
+ "\n");
{
if (!newFrame)
{
- System.err.println("MERGE WITH OLD FRAME NOT IMPLEMENTED");
+ jalview.bin.Console.errPrintln("MERGE WITH OLD FRAME NOT IMPLEMENTED");
return;
}
// each subjob is an independent alignment for the moment
{
if (cancelJob(rslt))
{
- System.err.println("Cancelled AACon job: " + rslt);
+ jalview.bin.Console.errPrintln("Cancelled AACon job: " + rslt);
}
else
{
- System.err.println("FAILED TO CANCEL AACon job: " + rslt);
+ jalview.bin.Console.errPrintln("FAILED TO CANCEL AACon job: " + rslt);
}
} catch (Exception x)
catch (JobSubmissionException x)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"submission error with " + getServiceActionText() + " :");
x.printStackTrace();
calcMan.disableWorker(this);
} catch (ResultNotAvailableException x)
{
- System.err.println("collection error:\nJob ID: " + rslt);
+ jalview.bin.Console.errPrintln("collection error:\nJob ID: " + rslt);
x.printStackTrace();
calcMan.disableWorker(this);
String id = rslt;
if (cancelJob(rslt))
{
- System.err.println("Cancelled job " + id);
+ jalview.bin.Console.errPrintln("Cancelled job " + id);
}
else
{
- System.err.println("Job " + id + " couldn't be cancelled.");
+ jalview.bin.Console.errPrintln("Job " + id + " couldn't be cancelled.");
}
} catch (Exception q)
{
}
else
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Warning: Ignoring parameter set instance of type "
+ paramset.getClass()
+ " : Bound but not applicable for service at "
registry = Jws2Client.connectToRegistry(jwsserver);
if (registry != null)
{
- // System.err.println("Test Services Output\n"
+ // jalview.bin.Console.errPrintln("Test Services Output\n"
// + registry.testAllServices());
// TODO: enumerate services and test those that haven't been tested
// in the last n-days/hours/etc.
srv_set = registry.getSupportedServices();
// dan test
- System.out.println(
+ jalview.bin.Console.outPrintln(
"registry.getSupportedServices: " + srv_set.toString());
svccategories = registry.getServiceCategories();
// dan test
- // System.out.println("registry.getServiceCategories: " +
+ // jalview.bin.Console.outPrintln("registry.getServiceCategories: " +
// svccategories.toString());
}
} catch (Exception ex)
{
- System.err.println("Exception whilst trying to get at registry:");
+ jalview.bin.Console.errPrintln("Exception whilst trying to get at registry:");
ex.printStackTrace();
// if that failed, then we are probably working with a JABAWS1 server.
// in that case, look for each service endpoint
- System.err.println("JWS2 Discoverer: " + jwsserver
+ jalview.bin.Console.errPrintln("JWS2 Discoverer: " + jwsserver
+ " is a JABAWS1 server. Using hardwired list.");
for (Services srv : JABAWS1SERVERS)
{
service = Jws2Client.connect(jwsserver, srv);
} catch (Exception e)
{
- System.err.println("Jws2 Discoverer: Problem on " + jwsserver
+ jalview.bin.Console.errPrintln("Jws2 Discoverer: Problem on " + jwsserver
+ " with service " + srv + ":\n" + e.getMessage());
if (!(e instanceof javax.xml.ws.WebServiceException))
{
result = true;
} catch (MalformedURLException e)
{
- System.err.println("Invalid server URL: " + server);
+ jalview.bin.Console.errPrintln("Invalid server URL: " + server);
result = false;
} catch (IOException e)
{
- System.err.println("Error connecting to server: " + server + ": "
+ jalview.bin.Console.errPrintln("Error connecting to server: " + server + ": "
+ e.toString());
result = false;
}
List<AlignmentAnnotation> ourAnnot, String typeName,
String calcId, SequenceI dseq, int base, Score scr)
{
- System.out.println("Creating annotation on dseq:" + dseq.getStart()
+ jalview.bin.Console.outPrintln("Creating annotation on dseq:" + dseq.getStart()
+ " base is " + base + " and length=" + dseq.getLength()
+ " == " + scr.getScores().size());
// AlignmentAnnotation annotation = new AlignmentAnnotation(
List<AlignmentAnnotation> ourAnnot, String typeName,
String calcId, SequenceI dseq, int base, Score scr)
{
- System.out.println("Creating annotation on dseq:" + dseq.getStart()
+ jalview.bin.Console.outPrintln("Creating annotation on dseq:" + dseq.getStart()
+ " base is " + base + " and length=" + dseq.getLength()
+ " == " + scr.getScores().size());
// AlignmentAnnotation annotation = new AlignmentAnnotation(
.loadClass("compbio.ws.client.Jws2Client");
} catch (ClassNotFoundException e)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Not enabling JABA Webservices : client jar is not available."
+ "\nPlease check that your webstart JNLP file is up to date!");
running = false;
{
services = new Vector<>();
}
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Discovered service: " + jwsservers + " " + service.toString());
// Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
// service2);
{
if (getDiscoverer().services != null)
{
- System.out.println("Changesupport: There are now "
+ jalview.bin.Console.outPrintln("Changesupport: There are now "
+ getDiscoverer().services.size() + " services");
int i = 1;
for (Jws2Instance instance : getDiscoverer().services)
{
- System.out.println("Service " + i++ + " "
+ jalview.bin.Console.outPrintln("Service " + i++ + " "
+ instance.getClass() + "@" + instance.getHost()
+ ": " + instance.getActionText());
}
{
j.setSubmitted(true);
j.setSubjobComplete(false);
- // System.out.println(WsURL + " Job Id '" + jobId + "'");
+ // jalview.bin.Console.outPrintln(WsURL + " Job Id '" + jobId + "'");
return;
}
else
} catch (Error e)
{
// For unexpected errors
- System.err.println(WebServiceName
+ jalview.bin.Console.errPrintln(WebServiceName
+ "Client: Failed to submit the sequences for alignment (probably a server side problem)\n"
+ "When contacting Server:" + WsUrl + "\n");
e.printStackTrace(System.err);
} catch (Exception e)
{
// For unexpected errors
- System.err.println(WebServiceName
+ jalview.bin.Console.errPrintln(WebServiceName
+ "Client: Failed to submit the sequences for alignment (probably a server side problem)\n"
+ "When contacting Server:" + WsUrl + "\n");
e.printStackTrace(System.err);
if (Console.isDebugEnabled())
{
- System.out.println("Job Execution file for job: "
+ jalview.bin.Console.outPrintln("Job Execution file for job: "
+ msjob.getJobId() + " on server " + WsUrl);
- System.out.println(msjob.getStatus());
- System.out.println("*** End of status");
+ jalview.bin.Console.outPrintln(msjob.getStatus());
+ jalview.bin.Console.outPrintln("*** End of status");
}
try
else
{
// TODO 2.9.x feature
- System.out.println("MERGE WITH OLD FRAME");
+ jalview.bin.Console.outPrintln("MERGE WITH OLD FRAME");
// TODO: modify alignment in original frame, replacing old for new
// alignment using the commands.EditCommand model to ensure the update can
// be undone
Option o = options.getArgumentByOptionName(oname);
if (o == null)
{
- System.out.println("WARN ignoring unsuppoted parameter: " + oname);
+ jalview.bin.Console.outPrintln("WARN ignoring unsuppoted parameter: " + oname);
continue;
}
if (o instanceof Parameter)
: param);
} catch (WrongParameterException e)
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Problem setting value for the parameter: " + param);
e.printStackTrace();
}
}
} catch (Exception ex)
{
- System.err.println("Exception when retrieving presets for service "
+ jalview.bin.Console.errPrintln("Exception when retrieving presets for service "
+ serviceType + " at " + hosturl);
}
}
* try { URL serviceurl = new URL(hosturl); if (serviceurl.getPort()!=80) {
* return serviceurl.getHost()+":"+serviceurl.getPort(); } return
* serviceurl.getHost(); } catch (Exception e) {
- * System.err.println("Failed to parse service URL '" + hosturl +
+ * jalview.bin.Console.errPrintln("Failed to parse service URL '" + hosturl +
* "' as a valid URL!"); } return null;
*/
}
: null));
} catch (Exception ex)
{
- System.err.println("Unexpected exception creating JabaParamStore.");
+ jalview.bin.Console.errPrintln("Unexpected exception creating JabaParamStore.");
ex.printStackTrace();
}
}
} catch (Exception ex)
{
- System.err.println("Couldn't transform string\n" + content
+ jalview.bin.Console.errPrintln("Couldn't transform string\n" + content
+ "\nException was :");
ex.printStackTrace(System.err);
}
@Override
public void cancelJob()
{
- System.err.println("Cannot cancel this job type: " + service);
+ jalview.bin.Console.errPrintln("Cannot cancel this job type: " + service);
}
@Override
}
} catch (Exception ex)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Serious - RSBS descriptions in user preferences are corrupt!");
ex.printStackTrace();
}
public void pollJob(AWsJob job) throws Exception
{
assert (job instanceof RestJob);
- System.err.println("Debug RestJob: Polling Job");
+ jalview.bin.Console.errPrintln("Debug RestJob: Polling Job");
doPoll((RestJob) job);
}
assert (job instanceof RestJob);
try
{
- System.err.println("Debug RestJob: Posting Job");
+ jalview.bin.Console.errPrintln("Debug RestJob: Posting Job");
doPost((RestJob) job);
} catch (NoValidInputDataException erex)
{
if (!rj.hasValidInput())
{
// invalid input for this job
- System.err.println("Job " + rj.getJobnum()
+ jalview.bin.Console.errPrintln("Job " + rj.getJobnum()
+ " has invalid input. ( " + rj.getStatus() + ")");
if (rj.hasStatus() && !_warnings.contains(rj.getStatus()))
{
seqset = fetcher.getSequenceRecords(qsb.toString());
} catch (Exception ex)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Failed to retrieve the following from " + db);
- System.err.println(qsb);
+ jalview.bin.Console.errPrintln(qsb);
ex.printStackTrace(System.err);
}
// TODO: Merge alignment together - perhaps
{
if (fetcher.getRawRecords() != null)
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"# Retrieved from " + db + ":" + qsb.toString());
StringBuffer rrb = fetcher.getRawRecords();
/*
/*
* } else { hdr = "# part "+rr; }
*/
- System.out.println(hdr);
+ jalview.bin.Console.outPrintln(hdr);
if (rrb != null)
{
- System.out.println(rrb);
+ jalview.bin.Console.outPrintln(rrb);
}
- System.out.println("# end of " + hdr);
+ jalview.bin.Console.outPrintln("# end of " + hdr);
}
}
}
if (queriesMade.size() > 0)
{
- System.out.println("# Adding " + queriesMade.size()
+ jalview.bin.Console.outPrintln("# Adding " + queriesMade.size()
+ " ids back to queries list for searching again (" + db
+ ")");
queriesLeft.addAll(queriesMade);
Exception ex)
{
- System.err.println(
+ jalview.bin.Console.errPrintln(
"Failed to retrieve the following references from " + db);
int n = 0;
for (String qv : queriesMade)
System.err.print(" " + qv + ";");
if (n++ > 10)
{
- System.err.println();
+ jalview.bin.Console.errPrintln();
n = 0;
}
}
- System.err.println();
+ jalview.bin.Console.errPrintln();
ex.printStackTrace();
}
try (InputStream in = new FileInputStream(siftFile);
GZIPInputStream gzis = new GZIPInputStream(in);)
{
- // System.out.println("File : " + siftFile.getAbsolutePath());
+ // jalview.bin.Console.outPrintln("File : " + siftFile.getAbsolutePath());
JAXBContext jc = JAXBContext.newInstance("jalview.xml.binding.sifts");
XMLStreamReader streamReader = XMLInputFactory.newInstance()
.createXMLStreamReader(gzis);
if (siftsFile.exists())
{
// The line below is required for unit testing... don't comment it out!!!
- System.out.println(">>> SIFTS File already downloaded for " + pdbId);
+ jalview.bin.Console.outPrintln(">>> SIFTS File already downloaded for " + pdbId);
if (isFileOlderThanThreshold(siftsFile,
SiftsSettings.getCacheThresholdInDays()))
diffInDays = (int) ((new Date().getTime()
- attr.lastModifiedTime().toMillis())
/ (1000 * 60 * 60 * 24));
- // System.out.println("Diff in days : " + diffInDays);
+ // jalview.bin.Console.outPrintln("Diff in days : " + diffInDays);
} catch (IOException e)
{
e.printStackTrace();
}
}
- // System.out.println(">> Download ftp url : " + siftsFileFTPURL);
+ // jalview.bin.Console.outPrintln(">> Download ftp url : " + siftsFileFTPURL);
// long now = System.currentTimeMillis();
URL url = new URL(siftsFileFTPURL);
URLConnection conn = url.openConnection();
}
outputStream.close();
inputStream.close();
- // System.out.println(">>> File downloaded : " + downloadedSiftsFile
+ // jalview.bin.Console.outPrintln(">>> File downloaded : " + downloadedSiftsFile
// + " took " + (System.currentTimeMillis() - now) + "ms");
return downloadTo;
}
seq = seq.getDatasetSequence();
}
structId = (chain == null) ? pdbId : pdbId + "|" + chain;
- System.out.println("Getting SIFTS mapping for " + structId + ": seq "
+ jalview.bin.Console.outPrintln("Getting SIFTS mapping for " + structId + ": seq "
+ seq.getName());
final StringBuilder mappingDetails = new StringBuilder(128);
{
List<Integer> omitNonObserved = new ArrayList<>();
int nonObservedShiftIndex = 0, pdbeNonObserved = 0;
- // System.out.println("Generating mappings for : " + entityId);
+ // jalview.bin.Console.outPrintln("Generating mappings for : " + entityId);
Entity entity = null;
entity = getEntityById(entityId);
String originalSeq = AlignSeq.extractGaps(
int firstPDBResNum = UNASSIGNED;
for (Segment segment : segments)
{
- // System.out.println("Mapping segments : " + segment.getSegId() + "\\"s
+ // jalview.bin.Console.outPrintln("Mapping segments : " + segment.getSegId() + "\\"s
// + segStartEnd);
List<Residue> residues = segment.getListResidue().getResidue();
for (Residue residue : residues)
// Arrays.sort(keys);
int firstIndex = keys[0];
int lastIndex = keys[keys.length - 1];
- // System.out.println("Min value " + firstIndex);
- // System.out.println("Max value " + lastIndex);
+ // jalview.bin.Console.outPrintln("Min value " + firstIndex);
+ // jalview.bin.Console.outPrintln("Max value " + lastIndex);
for (int x = firstIndex; x <= lastIndex; x++)
{
if (!resNumMap.containsKey(x) && !omitNonObserved.contains(x))
*/
public Entity getEntityByMostOptimalMatchedId(String chainId)
{
- // System.out.println("---> advanced greedy entityId matching block
+ // jalview.bin.Console.outPrintln("---> advanced greedy entityId matching block
// entered..");
List<Entity> entities = siftsEntry.getEntity();
SiftsEntitySortPojo[] sPojo = new SiftsEntitySortPojo[entities.size()];
++count;
}
Arrays.sort(sPojo, Collections.reverseOrder());
- // System.out.println("highest matched entity : " + sPojo[0].entityId);
- // System.out.println("highest matched pid : " + sPojo[0].pid);
+ // jalview.bin.Console.outPrintln("highest matched entity : " + sPojo[0].entityId);
+ // jalview.bin.Console.outPrintln("highest matched pid : " + sPojo[0].pid);
if (sPojo[0].entityId != null)
{
}
} catch (IOException e)
{
- System.out.println(
+ jalview.bin.Console.outPrintln(
"Exception while closing download file output stream: "
+ e.getMessage());
}
}
} catch (IOException e)
{
- System.out.println("Exception while closing download channel: "
+ jalview.bin.Console.outPrintln("Exception while closing download channel: "
+ e.getMessage());
}
try
}
} catch (IOException e)
{
- System.out.println("Exception while deleting download temp file: "
+ jalview.bin.Console.outPrintln("Exception while deleting download temp file: "
+ e.getMessage());
}
}
--- /dev/null
+>101
+P.I...A..Q..I.....H.....I........L.......E........G.......R.......S....D.......E.......Q.....K....E.
+T..LI....RE...V.S.E...A...I......S.......R...S.......L........D....A.....P......L...................
+..........T......S.......V.......R......V...I....I.......T......E.....M........A....K.........G.....
+.H..........F..........G........I..........G........G......E........L....A...SK
+>UPI
+P.Hye.V..S..V.....T.....M........P.......T........G.......Wl......N....T.......V.......R.....K....Q.
+G..MI....DA...V.T.R...A...L......L.......E...A.......I........A....T.....P......F...................
+..........D......Essrfr..V.......R......C...L....I.......P......E.....I........P....D.........G.....
+.N..........W..........G........S..........G........Gya....L........P....L...S-
+>SRR
+P.H...V..A..V.....K.....L........Y.......P........G.......R.......T....E.......Q.......Q.....K....E.
+Q..LA....RA...I.A.D...D...V......M.......R...I.......L........G....S.....S......E...................
+..........A......S.......V.......S......V...S....I.......E......E.....V........D....A.........A.....
+.D..........W..........A........EkvyrplivegG........G......T........L....Y...KK
+>SRR
+P.H...V..I..V.....K.....L........W.......P........G.......R.......S....E.......P.......Q.....K....Q.
+K..LV....ES...V.T.K...A...V......T.......T...S.......L........G....Y.....S......D...................
+..........E......A.......V.......S......V...S....L.......Q......E.....V........P....S.........D.....
+.Q..........WtekvyrpdilG........T..........A........G......R........L....Y...KK
+>MGY
+P.I...V..R..I.....T.....M........F.......E........G.......R.......T....K.......E.......Q.....K....Q.
+E..LA....RV...I.T.E...A...V......V.......N...I.......A........K....T.....T......P...................
+..........D......A.......T.......E......VkdqI....L.......Q......K.....VllvrslrlP....PppasrrqvsG.....
+.A..........W..........S........A..........D........G......K........P....T...SE
+>446
+P.H...V..I..V.....K.....L........W.......P........G.......K.......S....E.......R.......E.....E....T.
+Q..LA....EA...I.T.K...S...V......T.......E...T.......L........N....F.....G......P...................
+..........E......S.......V.......S......V...A....F.......E......E.....I........P....A.........K.....
+.D..........W..........AskvyhadiI..........Gne......G......K........L....Y...KK
+>SRR
+P.L...V..R..I.....T.....Y........P.......R........Ga......L.......S....P.......E.......H.....K....T.
+R..IA....RA...L.T.E...I...V......L.......D...Vevdaa..T........D....A.....G......R...................
+..........M......V.......T.......V......V...H....F.......N......E.....A........A....P.........D.....
+.D..........W..........A........V..........G........G......Eirs.....T....A...AE
+>SRR
+P.L...V..R..I.....T.....Y........P.......R........Ga......L.......S....P.......D.......H.....K....R.
+R..IA....RE...L.T.E...I...V......L.......D...Vevdaa..T........D....A.....G......R...................
+..........M......V.......T.......V......I...H....F.......N......E.....A........A....A.........D.....
+.D..........W..........A........V..........G........G......Eirs.....T....A...AE
+>SRR
+P.R...Y..R..Vip...T.....V........P.......E........G.......Qy......S....N.......E.......S.....R....K.
+A..LV....KD...V.T.E...A...V......V.......R...A.......D........G....G.....K......Y...................
+..........E......Dvapr...V.......W......V...F....P.......T......E.....I........P....D.........G.....
+.Q..........W..........G........S..........R........Gvi....R........P....L...PE
+>SRR
+P.R...Y..R..Iip...T.....V........P.......E........G.......Qy......S....N.......E.......S.....R....K.
+A..LV....KD...V.T.E...A...V......V.......R...A.......D........G....G.....K......Y...................
+..........E......Dvapr...V.......W......V...F....P.......T......E.....I........P....D.........G.....
+.Q..........W..........G........S..........R........Gvi....R........P....L...PE
+>SRR
+P.V...I..E..M.....F.....V........P.......E........G.......La......D....A.......E.......A.....K....R.
+A..LH....DR...V.S.R...Q...V......L.......E...V.......E........G....AtydesP......L...................
+..........A......Qsi.....T.......W......M...L....I.......Q......E.....V........L....E.........C.....
+.G..........W..........S........V..........G........S......K........Avw..A...SE
+>SRR
+P.I...I..E..M.....H.....V........Q.......E........Gv......L.......D....E.......E.......T.....K....R.
+T..LH....ER...V.G.R...Q...V......L.......E...I.......E........G....Any...D......E...................
+..........N......D.......Varllt..F......M...F....I.......R......E.....H........P....E.........G.....
+.G..........F..........S........I..........G........G......E........M....It..SE
+>SRR
+P.Lyr.V..D..V.....T.....V........P.......E........Gsmihg..Q.......G....Pwal....S.......R.....R....R.
+A..IV....RE...V.T.E...I...V......L.......E...A.......E........G....S.....D......P...................
+..........Slgeaw.R.......V.......W......V...V....L.......R......E.....V........G....D.........A.....
+.F..........W..........G........A..........A........G......E........L....-...--
+>SRR
+P.Lyr.V..Q..I.....T.....V........P.......E........Gsmlhg..Q.......G....Pwai....E.......R.....R....R.
+E..LV....RA...V.S.K...A...V......L.......D...A.......E........G....Teyn..P......A...................
+..........Saw....R.......V.......W......V...L....M.......S......E.....I........S....E.........T.....
+.H..........W..........G........A..........A........G......E........-....-...--
+>SRR
+P.L...V..E..M.....S.....F........P.......V........Gv......L.......T....L.......D.......Q.....K....A.
+A..MI....KS...V.T.D...V...V......R.......G...A.......M........K....L.....P......P...................
+..........Dpar...K.......L.......F......V...E....I.......F......E.....T........P....G.........G.....
+.G..........F..........G........Vtakvvvvp..G........Gky....R........P....A...P-
+>SRR
+P.L...V..E..I.....D.....L........L.......E........A.......W.......A....P.......D.......Q.....I....D.
+A..IA....DA...I.H.E...A...M......V.......E...T.......L........G....V.....P......Eraagrdsatkqhfysrfaa
+llaeratvqsA......D.......L.......T......A...V....L.......V......E.....N........S....R.........D.....
+.D..........W..........S........F..........Gm.......G......Q........-....-...--
--- /dev/null
+--nonews
+--nosplash
+--open=./test/files/annotation_label_width/sample.a2m
+--colour=gecos:flower
+--gui
+--structure=[structureviewer=none]./examples/test_fab41.result/test_fab41_unrelaxed_rank_1_model_3.pdb
+--paematrix=./examples/test_fab41.result/test_fab41_unrelaxed_rank_1_model_3_scores.json
+--structure=[structureviewer=none]./examples/test_fab41.result/test_fab41_unrelaxed_rank_2_model_4.pdb
+--paematrix=./examples/test_fab41.result/test_fab41_unrelaxed_rank_2_model_4_scores.json
+--structure=[structureviewer=none]./examples/test_fab41.result/test_fab41_unrelaxed_rank_3_model_2.pdb
+--paematrix=./examples/test_fab41.result/test_fab41_unrelaxed_rank_3_model_2_scores.json
+--structure=[structureviewer=none]./examples/test_fab41.result/test_fab41_unrelaxed_rank_4_model_5.pdb
+--paematrix=./examples/test_fab41.result/test_fab41_unrelaxed_rank_4_model_5_scores.json
+--structure=[structureviewer=none]./examples/test_fab41.result/test_fab41_unrelaxed_rank_5_model_1.pdb
+--paematrix=./examples/test_fab41.result/test_fab41_unrelaxed_rank_5_model_1_scores.json
String ln = null;
while ((ln = worker.getOutputReader().readLine()) != null)
{
- System.out.println(ln);
+ System.out.println("STDOUT: " + ln);
successfulCMDs.add(ln);
}
while ((ln = worker.getErrorReader().readLine()) != null)
{
- System.err.println(ln);
+ System.err.println("STDERR: " + ln);
+ successfulCMDs.add(ln);
}
}
// number of lines expected on STDERR when Jalview starts up normally
// may need to adjust this if Jalview is excessively noisy ?
+ final int STDOUT_SETUPLINES = 50;
final int STDERR_SETUPLINES = 50;
// thread monitors stderr - bails after SETUP_TIMEOUT or when
public void run()
{
String ln = null;
- int count = 0;
+ int stdoutcount = 0;
+ int stderrcount = 0;
try
{
while ((ln = worker.getOutputReader().readLine()) != null)
{
System.out.println(ln);
successfulCMDs.add(ln);
- if (++count > STDERR_SETUPLINES)
+ if (++stdoutcount > STDOUT_SETUPLINES)
+ {
+ break;
+ }
+ }
+ while ((ln = worker.getErrorReader().readLine()) != null)
+ {
+ System.err.println(ln);
+ successfulCMDs.add(ln);
+ if (++stderrcount > STDERR_SETUPLINES)
{
break;
}
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
+import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
private Worker getJalviewDesktopRunner(boolean withAwt, String cmd,
int timeout)
{
+ return getJalviewDesktopRunner(withAwt, cmd, timeout, true);
+ }
+
+ private Worker getJalviewDesktopRunner(boolean withAwt, String cmd,
+ int timeout, boolean testoutput)
+ {
/*
boolean win = System.getProperty("os.name").indexOf("Win") >= 0;
String pwd = "";
Worker worker = null;
try
{
- cmd = " --testoutput " + cmd;
+ cmd = cmd + (testoutput ? " --testoutput " : "");
System.out.println("Running '" + _cmd + cmd + "'");
ls2_proc = Runtime.getRuntime().exec(_cmd + cmd);
} catch (Throwable e1)
file.delete();
}
+ @Test(
+ groups =
+ { "Functional", "testTask1" },
+ dataProvider = "headlessModeOutputToStdout")
+ public void testHeadlessModeOutputToStdout(String args,
+ String comparisonFile, int timeout)
+ {
+ String cmd = args;
+ File file = new File(comparisonFile);
+ Worker worker = getJalviewDesktopRunner(true, cmd, timeout, false);
+ int b = -1;
+ StringBuilder sb = new StringBuilder();
+ try
+ {
+ while ((b = worker.getOutputReader().read()) != -1)
+ {
+ sb.append(Character.toChars(b));
+ }
+ } catch (IOException e)
+ {
+ Assert.fail("IOException whilst trying to read from jalview process");
+ }
+
+ String comparisonContent = null;
+ try
+ {
+ comparisonContent = new String(Files.readAllBytes(file.toPath()));
+ } catch (IOException e)
+ {
+ Assert.fail("IOException whilst trying to read comparison file");
+ }
+
+ Assert.assertEquals(sb.toString(), comparisonContent,
+ "STDOUT from jalview command did not match the comparison file");
+ }
+
@DataProvider(name = "allInputOperationsData")
public Object[][] getHeadlessModeInputParams()
{
//
};
}
+
+ @DataProvider(name = "headlessModeOutputToStdout")
+ public static Object[][] getHeadlessModeOutputToStdout()
+ {
+ // JBPNote: I'm not clear why need to specify full path for output file
+ // when running tests on build server, but we will keep this patch for now
+ // since it works.
+ // https://issues.jalview.org/browse/JAL-1889?focusedCommentId=21609&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-21609
+ String workingDir = "test/jalview/bin";
+ return new Object[][] {
+ //
+ { "--open=examples/uniref50.fa --output=-",
+ workingDir + "/uniref50-output.fa", TEST_TIMEOUT },
+ { "--open examples/uniref50.fa --output -",
+ workingDir + "/uniref50-output.fa", TEST_TIMEOUT },
+ { "--open examples/uniref50.fa --output=[format=blc]-",
+ workingDir + "/uniref50-output.blc", TEST_TIMEOUT },
+ { "--open examples/uniref50.fa --output - --format blc",
+ workingDir + "/uniref50-output.blc", TEST_TIMEOUT },
+ { "./examples/uniref50.fa --output=-",
+ workingDir + "/uniref50-output.fa", TEST_TIMEOUT },
+ { "./examples/uniref50.fa --output - --format blc",
+ workingDir + "/uniref50-output.blc", TEST_TIMEOUT },
+ // remember you can't use shell wildcards for filenames in a test
+ { "./test/jalview/bin/argparser/testfiles/test1.fa ./test/jalview/bin/argparser/testfiles/test2.fa ./test/jalview/bin/argparser/testfiles/test3.fa --all --output -",
+ workingDir + "/test1-3.fa", TEST_TIMEOUT },
+ // but you can use java wildcards when using an equals sign
+ { "--open=./test/jalview/bin/argparser/testfiles/test*.fa --all --output -",
+ workingDir + "/test1-3.fa", TEST_TIMEOUT },
+ //
+ };
+ }
}
import java.io.File;
import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
+import javax.swing.SwingUtilities;
+
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
}
@AfterMethod(alwaysRun = true)
- public void tearDown()
+ public void tearDown()
{
- Desktop.closeDesktop();
+ try
+ {
+ // occasionally we are blocked by Jmol redraws
+ SwingUtilities.invokeAndWait(new Runnable()
+ {
+
+ @Override
+ public void run()
+ {
+ Desktop.closeDesktop();
+ }
+ });
+ } catch (Exception foo)
+ {
+ System.err.println("Failed during teardown with exception");
+ foo.printStackTrace();
+ }
+
}
-
- public static void callJalviewMain(String[] args) {
- if (Jalview.getInstance()!=null) {
+
+ public static void callJalviewMain(String[] args)
+ {
+ if (Jalview.getInstance() != null)
+ {
Jalview.getInstance().doMain(args);
- } else {
+ }
+ else
+ {
Jalview.main(args);
}
}
}
}
- @Test(groups = {"Functional","testTask1"}, dataProvider = "structureImageOutputFiles")
+ @Test(
+ groups =
+ { "Functional", "testTask1" },
+ dataProvider = "structureImageOutputFiles")
public void structureImageOutputTest(String cmdLine, String[] filenames)
throws IOException
{
{
cleanupFiles(filenames);
String[] args = (cmdLine + " --gui").split("\\s+");
- try {
- callJalviewMain(args);
- Commands cmds = Jalview.getInstance().getCommands();
- Assert.assertNotNull(cmds);
- File lastFile = null;
- for (String filename : filenames)
+ try
{
- File file = new File(filename);
- Assert.assertTrue(file.exists(), "File '" + filename
- + "' was not created by '" + cmdLine + "'");
- Assert.assertTrue(file.isFile(), "File '" + filename
- + "' is not a file from '" + cmdLine + "'");
- Assert.assertTrue(Files.size(file.toPath()) > 0, "File '" + filename
- + "' has no content from '" + cmdLine + "'");
- // make sure the successive output files get bigger!
- if (lastFile != null)
- Assert.assertTrue(
- Files.size(file.toPath()) > Files.size(lastFile.toPath()));
- }
+ callJalviewMain(args);
+ Commands cmds = Jalview.getInstance().getCommands();
+ Assert.assertNotNull(cmds);
+ File lastFile = null;
+ for (String filename : filenames)
+ {
+ File file = new File(filename);
+ Assert.assertTrue(file.exists(), "File '" + filename
+ + "' was not created by '" + cmdLine + "'");
+ Assert.assertTrue(file.isFile(), "File '" + filename
+ + "' is not a file from '" + cmdLine + "'");
+ Assert.assertTrue(Files.size(file.toPath()) > 0, "File '" + filename
+ + "' has no content from '" + cmdLine + "'");
+ // make sure the successive output files get bigger!
+ if (lastFile != null)
+ Assert.assertTrue(Files.size(file.toPath()) > Files
+ .size(lastFile.toPath()));
+ }
} catch (Exception x)
{
- Assert.fail("Unexpected exception during argFilesGlobAndSubstitutions",
+ Assert.fail(
+ "Unexpected exception during argFilesGlobAndSubstitutions",
x);
} finally
{
+ "--open=./examples/test_fab41.result/sample.a2m "
+ "--structure=./examples/test_fab41.result/test_fab41_unrelaxed_rank_1_model_3.pdb "
+ "--structureimage=" + testfiles
- + "/structureimage2.png --structureimagescale=1.5"
+ + "/structureimage2.png --scale=1.5 "
+ "--open=./examples/test_fab41.result/sample.a2m "
+ "--structure=./examples/test_fab41.result/test_fab41_unrelaxed_rank_1_model_3.pdb "
+ "--structureimage=" + testfiles
- + "/structureimage3.png --structureimagescale=2.0",
+ + "/structureimage3.png --scale=2.0 ",
new String[]
{ testfiles + "/structureimage1.png",
testfiles + "/structureimage2.png",
testfiles + "/structureimage3.png" } },
- /*
{ "--headless --noquit --open=./examples/test_fab41.result/sample.a2m "
+ "--structure=./examples/test_fab41.result/test_fab41_unrelaxed_rank_1_model_3.pdb "
+ "--structureimage=" + testfiles + "/structureimage1.png "
+ "--open=./examples/test_fab41.result/sample.a2m "
+ "--structure=./examples/test_fab41.result/test_fab41_unrelaxed_rank_1_model_3.pdb "
+ "--structureimage=" + testfiles
- + "/structureimage2.png --structureimagescale=1.5"
+ + "/structureimage2.png --scale=1.5 "
+ "--open=./examples/test_fab41.result/sample.a2m "
+ "--structure=./examples/test_fab41.result/test_fab41_unrelaxed_rank_1_model_3.pdb "
+ "--structureimage=" + testfiles
- + "/structureimage3.png --structureimagescale=2.0",
+ + "/structureimage3.png --scale=2.0 ",
new String[]
{ testfiles + "/structureimage1.png",
testfiles + "/structureimage2.png",
testfiles + "/structureimage3.png" } },
+ /*
*/
//
};
}
}
+ private final String deleteDir = "test/deleteAfter";
+
@Test(
groups = "Functional",
dataProvider = "allLinkedIdsData",
"File " + nonfilename + " exists when it shouldn't!");
}
}
+
+ File deleteDirF = new File(deleteDir);
+ if (deleteDirF.exists())
+ {
+ deleteDirF.delete();
+ }
}
@DataProvider(name = "allLinkedIdsData")
{
return new Object[][] {
//
- /*
- */
{ "--gui --open=test/jalview/bin/argparser/testfiles/*.fa --substitutions --all --output={dirname}/{basename}.stk --close",
new String[]
{ "test/jalview/bin/argparser/testfiles/test1.stk",
"test/jalview/bin/argparser/testfiles/dir3/subdir/test2.stk",
"test/jalview/bin/argparser/testfiles/dir3/subdir/test3.stk", },
null },
- { "--gui --open=test/jalview/bin/argparser/**/*.fa --output=*.stk --close",
+ { "--gui --open=test/jalview/bin/argparser/**/*.fa --output=*/*.stk --close",
new String[]
{ "test/jalview/bin/argparser/testfiles/test1.stk",
"test/jalview/bin/argparser/testfiles/test2.stk",
"test/jalview/bin/argparser/testfiles/dir3/subdir/test2.stk",
"test/jalview/bin/argparser/testfiles/dir3/subdir/test3.stk", },
null },
- { "--gui --open=test/jalview/bin/argparser/testfiles/dir1/*.fa --open=test/jalview/bin/argparser/testfiles/dir2/*.fa --output=*.stk --close",
+ { "--gui --open=test/jalview/bin/argparser/testfiles/dir1/*.fa --open=test/jalview/bin/argparser/testfiles/dir2/*.fa --all --output=*/*.stk --close",
new String[]
{ "test/jalview/bin/argparser/testfiles/dir1/test1.stk",
"test/jalview/bin/argparser/testfiles/dir1/test2.stk",
"test/jalview/bin/argparser/testfiles/dir3/subdir/test1.stk",
"test/jalview/bin/argparser/testfiles/dir3/subdir/test2.stk",
"test/jalview/bin/argparser/testfiles/dir3/subdir/test3.stk", }, },
- { "--gui --open=test/jalview/bin/argparser/testfiles/dir1/*.fa --open=test/jalview/bin/argparser/testfiles/dir2/*.fa --output=open*.stk --close",
+ { "--gui --open=test/jalview/bin/argparser/testfiles/dir1/*.fa --open=test/jalview/bin/argparser/testfiles/dir2/*.fa --output=*/*.stk --close",
+ new String[]
+ { "test/jalview/bin/argparser/testfiles/dir2/test1.stk",
+ "test/jalview/bin/argparser/testfiles/dir2/test2.stk",
+ "test/jalview/bin/argparser/testfiles/dir2/test3.stk", },
+ new String[]
+ { "test/jalview/bin/argparser/testfiles/test1.stk",
+ "test/jalview/bin/argparser/testfiles/test2.stk",
+ "test/jalview/bin/argparser/testfiles/test3.stk",
+ "test/jalview/bin/argparser/testfiles/dir3/subdir/test0.stk",
+ "test/jalview/bin/argparser/testfiles/dir3/subdir/test1.stk",
+ "test/jalview/bin/argparser/testfiles/dir3/subdir/test2.stk",
+ "test/jalview/bin/argparser/testfiles/dir3/subdir/test3.stk", }, },
+ { "--gui --open=test/jalview/bin/argparser/testfiles/dir1/*.fa --open=test/jalview/bin/argparser/testfiles/dir2/*.fa --output={dirname}/{basename}.stk --close",
new String[]
{ "test/jalview/bin/argparser/testfiles/dir2/test1.stk",
"test/jalview/bin/argparser/testfiles/dir2/test2.stk",
"test/jalview/bin/argparser/testfiles/dir3/subdir/test1.stk",
"test/jalview/bin/argparser/testfiles/dir3/subdir/test2.stk",
"test/jalview/bin/argparser/testfiles/dir3/subdir/test3.stk", }, },
- { "--gui --open=test/jalview/bin/argparser/testfiles/dir1/*.fa --open=test/jalview/bin/argparser/testfiles/dir2/*.fa --opened --output={dirname}/{basename}.stk --close",
+ { "--gui --open=test/jalview/bin/argparser/testfiles/dir1/*.fa --open=test/jalview/bin/argparser/testfiles/dir2/*.fa --output={dirname}/{basename}.stk --close",
new String[]
{ "test/jalview/bin/argparser/testfiles/dir2/test1.stk",
"test/jalview/bin/argparser/testfiles/dir2/test2.stk",
"test/jalview/bin/argparser/testfiles/dir3/subdir/test1.stk",
"test/jalview/bin/argparser/testfiles/dir3/subdir/test2.stk",
"test/jalview/bin/argparser/testfiles/dir3/subdir/test3.stk", }, },
- { "--gui --open=test/jalview/bin/argparser/testfiles/dir1/*.fa --output open*.stk --open=test/jalview/bin/argparser/testfiles/dir2/*.fa --output=open*.aln --close",
+ { "--gui --open=test/jalview/bin/argparser/testfiles/dir1/*.fa --output {dirname}/{basename}.stk --open=test/jalview/bin/argparser/testfiles/dir2/*.fa --output={dirname}/{basename}.aln --close",
new String[]
{ "test/jalview/bin/argparser/testfiles/dir1/test1.stk",
"test/jalview/bin/argparser/testfiles/dir1/test2.stk",
"test/jalview/bin/argparser/testfiles/dir3/subdir/test1.aln",
"test/jalview/bin/argparser/testfiles/dir3/subdir/test2.aln",
"test/jalview/bin/argparser/testfiles/dir3/subdir/test3.aln", }, },
+ // --mkdirs
+ { "--headless --open=test/jalview/bin/argparser/testfiles/dir1/*.fa --output "
+ + deleteDir
+ + "/{dirname}/{basename}.stk --open=test/jalview/bin/argparser/testfiles/dir2/*.fa --output="
+ + deleteDir
+ + "/{dirname}/{basename}.aln --close --all --mkdirs",
+ new String[]
+ { deleteDir
+ + "/test/jalview/bin/argparser/testfiles/dir1/test1.stk",
+ deleteDir
+ + "/test/jalview/bin/argparser/testfiles/dir1/test2.stk",
+ deleteDir
+ + "/test/jalview/bin/argparser/testfiles/dir2/test1.aln",
+ deleteDir
+ + "/test/jalview/bin/argparser/testfiles/dir2/test2.aln",
+ deleteDir
+ + "/test/jalview/bin/argparser/testfiles/dir2/test3.aln", },
+ new String[]
+ { "test/jalview/bin/argparser/testfiles/test1.stk",
+ "test/jalview/bin/argparser/testfiles/test2.stk",
+ "test/jalview/bin/argparser/testfiles/test3.stk",
+ "test/jalview/bin/argparser/testfiles/dir2/test1.stk",
+ "test/jalview/bin/argparser/testfiles/dir2/test2.stk",
+ "test/jalview/bin/argparser/testfiles/dir2/test3.stk",
+ "test/jalview/bin/argparser/testfiles/dir3/subdir/test0.stk",
+ "test/jalview/bin/argparser/testfiles/dir3/subdir/test1.stk",
+ "test/jalview/bin/argparser/testfiles/dir3/subdir/test2.stk",
+ "test/jalview/bin/argparser/testfiles/dir3/subdir/test3.stk",
+ "test/jalview/bin/argparser/testfiles/test1.aln",
+ "test/jalview/bin/argparser/testfiles/test2.aln",
+ "test/jalview/bin/argparser/testfiles/test3.aln",
+ "test/jalview/bin/argparser/testfiles/dir1/test1.aln",
+ "test/jalview/bin/argparser/testfiles/dir1/test2.aln",
+ "test/jalview/bin/argparser/testfiles/dir3/subdir/test0.aln",
+ "test/jalview/bin/argparser/testfiles/dir3/subdir/test1.aln",
+ "test/jalview/bin/argparser/testfiles/dir3/subdir/test2.aln",
+ "test/jalview/bin/argparser/testfiles/dir3/subdir/test3.aln",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/test1.stk",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/test2.stk",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/test3.stk",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/dir2/test1.stk",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/dir2/test2.stk",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/dir2/test3.stk",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/dir3/subdir/test0.stk",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/dir3/subdir/test1.stk",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/dir3/subdir/test2.stk",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/dir3/subdir/test3.stk",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/test1.aln",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/test2.aln",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/test3.aln",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/dir1/test1.aln",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/dir1/test2.aln",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/dir3/subdir/test0.aln",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/dir3/subdir/test1.aln",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/dir3/subdir/test2.aln",
+ deleteDir
+ + "test/jalview/bin/argparser/testfiles/dir3/subdir/test3.aln", }, },
//
};
}
String[] args = cmdLine.split("\\s+");
CommandsTest.callJalviewMain(args);
- while (Desktop.instance!=null && Desktop.instance.operationsAreInProgress())
+ while (Desktop.instance != null
+ && Desktop.instance.operationsAreInProgress())
{
try
{
String jvmArgs = HiDPISetting.getScalePropertyArg(scale);
- String appArgs = " -open examples/uniref50.fa -nosplash -nonews -noquestionnaire -nousagestats -nowebservicediscovery";
+ String appArgs = " --open examples/uniref50.fa --nosplash --nonews --noquestionnaire --nousagestats --nowebservicediscovery";
Worker worker = getJalviewDesktopRunner(jvmArgs, appArgs);
assertNotNull(worker, "worker is null");
{
while ((ln = worker.getErrorReader().readLine()) != null)
{
- if (++count > 100)
+ if (++count > 150)
{
break;
}
}
@Test(groups = "Functional", dataProvider = "allLinkedIdsData")
- public void allLinkedIdsTest(String commandLineArgs, Arg a,
+ public void allLinkedIdsTest(String pwd, String commandLineArgs, Arg a,
String[] values, String[] nonvalues)
{
+ String userDir = System.getProperty("user.dir");
+ if (pwd != null)
+ {
+ File pwdFile = new File(pwd);
+ System.setProperty("user.dir", pwdFile.getAbsolutePath());
+ }
String[] args = commandLineArgs.split("\\s+");
ArgParser argparser = new ArgParser(args);
ArgValues avs = avm.getArgValues(a);
ArgValue av = avs.getArgValue();
String v = av.getValue();
- value = new File(value).getAbsolutePath();
+ value = new File(value).getPath();
Assert.assertEquals(v, value, "Arg value for " + a.argString()
+ " not applied correctly to linkedId '" + linkedId + "'");
}
}
+ System.setProperty("user.dir", userDir);
}
@DataProvider(name = "allLinkedIdsData")
//
/*
*/
- { "--open=test/jalview/bin/argparser/testfiles/*.fa --substitutions --all --image={dirname}/{basename}.png --close",
+ { null,
+ "--open=test/jalview/bin/argparser/testfiles/*.fa --substitutions --all --image={dirname}/{basename}.png --close",
Arg.CLOSE, new String[]
{ null, null, null },
null },
- { "--open=test/jalview/bin/argparser/testfiles/*.fa --substitutions --all --output={dirname}/{basename}.stk --close",
+ { null,
+ "--open=test/jalview/bin/argparser/testfiles/*.fa --substitutions --all --output={dirname}/{basename}.stk --close",
Arg.OUTPUT, new String[]
{ "test/jalview/bin/argparser/testfiles/test1.stk",
"test/jalview/bin/argparser/testfiles/test2.stk",
"test/jalview/bin/argparser/testfiles/test3.stk", },
null },
- { "--open=test/jalview/bin/argparser/testfiles/*.fa --substitutions --all --image={dirname}/{basename}.png --close",
+ { null,
+ "--open=test/jalview/bin/argparser/testfiles/*.fa --substitutions --all --image={dirname}/{basename}.png --close",
Arg.IMAGE, new String[]
{ "test/jalview/bin/argparser/testfiles/test1.png",
"test/jalview/bin/argparser/testfiles/test2.png",
"test/jalview/bin/argparser/testfiles/test3.png", },
null },
+ /*
+ * Find a way to change pwd reliably -- need to match "*.fa" against some files!
+ { "test/jalview/bin/argparser/testfiles",
+
+ "--open=*.fa --image={dirname}/{basename}.png --close",
+ Arg.IMAGE, new String[]
+ { "./test1.png", "./test2.png", "./test3.png", }, null },
+ */
//
};
}
};
}
-}
+}
\ No newline at end of file
---substitutions
--append=examples/test_fab41.result/sample.a2m
--showannotations
--showssannotations
--colour=gecos-flower
---structure=[viewer=jmol,tempfac=plddt,paematrix={dirname}/test_fab41_unrelaxed_rank_1_model_3_scores.json]{dirname}/test_fab41_unrelaxed_rank_1_model_3.pdb
+--structure=[structureviewer=jmol,tempfac=plddt,paematrix={dirname}/test_fab41_unrelaxed_rank_1_model_3_scores.json]{dirname}/test_fab41_unrelaxed_rank_1_model_3.pdb
--structure={dirname}/test_fab41_unrelaxed_rank_2_model_4.pdb
--structureviewer=jmol
--paematrix={dirname}/test_fab41_unrelaxed_rank_2_model_4_scores.json
--structureviewer=jmol
--paematrix={dirname}/test_fab41_unrelaxed_rank_3_model_2_scores.json
--tempfac=plddt
---structure=[viewer=none]{dirname}/test_fab41_unrelaxed_rank_4_model_5.pdb
+--structure=[structureviewer=none]{dirname}/test_fab41_unrelaxed_rank_4_model_5.pdb
--paematrix={dirname}/test_fab41_unrelaxed_rank_4_model_5_scores.json
--tempfac=plddt
--structure={dirname}/test_fab41_unrelaxed_rank_5_model_1.pdb
--- /dev/null
+>TEST1/1-4
+AAAA
+>TEST2/1-4
+LLLL
+>TEST3/1-5
+AAARG
--- /dev/null
+>FER_CAPAA/1-97 Ferredoxin
+>FER_CAPAN/1-144 Ferredoxin, chloroplast precursor
+>FER1_SOLLC/1-144 Ferredoxin-1, chloroplast precursor
+>Q93XJ9_SOLTU/1-144 Ferredoxin I precursor
+>FER1_PEA/1-149 Ferredoxin-1, chloroplast precursor
+>Q7XA98_TRIPR/1-152 Ferredoxin I
+>FER1_MESCR/1-148 Ferredoxin-1, chloroplast precursor
+>FER1_SPIOL/1-147 Ferredoxin-1, chloroplast precursor
+>FER3_RAPSA/1-96 Ferredoxin, leaf L-A
+>FER2_ARATH/1-148 Ferredoxin-2, chloroplast precursor
+>FER_BRANA/1-96 Ferredoxin
+>FER1_ARATH/1-148 Ferredoxin-1, chloroplast precursor
+>Q93Z60_ARATH/1-118 At1g10960/T19D16_12
+>FER1_MAIZE/1-150 Ferredoxin-1, chloroplast precursor
+>O80429_MAIZE/1-140 Ferredoxin
+* iteration 1
+-MMMMMMM-M-MMMM
+-AAAAAAA-A-AAAA
+----TTAA-S-SSTA
+----TTTT-T-TTVT
+-------------L-
+-------------G-
+------TT-----S-
+----PPAT-----P-
+-SSSAAAT-A-AAR-
+-VIILLLM-L-LLA-
+-SSSYYSM-S-SSP-
+-AGGGGGG-S-SSA-
+-TTTTTA--A-AAF-
+-MMMAAT--I-IIFA
+-IIIVVMM-V-VVFL
+-SSSSSSA-G-SSSS
+-TTTTTTT-T-TTSM
+-SSSSSAT-S-SSSS
+-FFFFFFF-F-FFSI
+-MLLLMAV-I-LLLL
+-PPPRRPP-R-RRRR
+-RRRTRKK-R-RRA-
+-KKKQQ-P-S-QQA-
+-PPPPP-Q-P-QQP-
+-AAVMVTA-A-TTAA
+-VVVPPPP-P-PPPP
+-TTTMMPP-I-IITP
+-SSSSSMM-S-SSAP
+-LLLVVTM-L-LLVC
+------AA-R-RR-F
+-KKKTAAA-S-SS-S
+-PAATTLL-L-LLAS
+-IIITTPP-P-PPLP
+-PSSKTTS-S-FFPL
+-NNNATNN-A-AAAR
+-VVVFTVT-N-NNAL
+-GGGSKGG-T-TTKR
+-EEENARR-Q-QQVV
+-----F---------
+-----P---------
+-AAAGSAS-S-SSGA
+-LLLFGLL-L-LLIV
+-FFFLFFF-F-FFMA
+-GGGGGGG-G-GGGK
+-LLLLLLL-L-LLRP
+-KKKKKKK-K-KKSL
+-SSSTSST-S-SSAA
+-----V---------
+-AGGSSSG-G-SSSA
+----LTAS-T-TTSP
+----KKSR-A-AARM
+-NRRRRR--R-RRRR
+-GNNGG---G-GG-R
+-GGGDDGG-G-GG-Q
+-KRRLLRG-R-RRRL
+-VIIAAVR-V-VVLL
+-TTTVVTM-T-TTRR
+-CCCAAAT-A-AAAA
+-MMMMMMM-M-MMQQ
+AAAAAAAAAAAAAAA
+SSSSSTAATTTTTTT
+YYYYYYYYYYYYYYY
+KKKKKKKKKKKKKNN
+VVVVVVVVVVVVVVV
+KKKKKKTTKKKKKKK
+LLLLLLLLFFFFFLL
+IIIIVIVVIIIIIII
+TTTTTTTTTTTTTTT
+PPPPPPPPPPPPPPP
+DDEDDEETEEEEEEE
+GGGGGGGGGGGGGGG
+PPPPTPKNEEEEEEE
+IIIIQQQVQLQQQVV
+EEEEEEEEEEEEEEE
+FFFFFFLFVVVVVLL
+DDEEEDEQEEEEEQQ
+CCCCCCCCCCCCCVV
+PPPPPPPPDDDEEPP
+DDDDSDDDDDDEEDD
+DNDDDDDDDDDDDDD
+VVVVVVVVVVVVVVV
+YYYYYYYYYYYYYYY
+IIIIIIIIVVVVVII
+LLLLLLLLLLLLLLL
+DDDDDDDDDDDDDDD
+QQQQHHAAAAAAAQF
+AAAAAAAAAAAAAAA
+EEEEEEEEEEEEEEE
+EEEEEEEEEEEEEEE
+AAEEVVAEAAAAADE
+GGGGGGGGGGGGGGG
+HHHHIIIIIIILLII
+DDDDDEDDDDDDDDD
+LLLLLLLLLLLLLLL
+PPPPPPPPPPPPPPP
+YYYYYYYYYYYYYYF
+SSSSSSSSSSSSSSS
+CCCCCCCCCCCCCCC
+RRRRRRRRRRRRRRR
+AAAAAAAAAAAAAAA
+GGGGGGGGGGGGGGG
+SSSSSSSSSSSSSSS
+CCCCCCCCCCCCCCC
+SSSSSSSSSSSSSSS
+SSSSSSSSSSSSSSS
+CCCCCCCCCCCCCCC
+AAAAAAAAAAAAAAA
+GGGGGGGGGGGGGGG
+KKKKKKKKKKKKKKK
+IIVVVVVLVVVVVVV
+AATTVVTKVVVVVVV
+GGAAGNSTSSSSSSS
+GGGGGGGGGGGGGGG
+AASTENSSSSFSSSS
+VVVVVVVLVVVIIVV
+DDDDDNNNDDDDDDD
+QQQQQQQQQQQQQQQ
+TTSSSEDDSSSSSSS
+DDDDDDDDDDDDDDD
+GGGGGGGQQQEQQQQ
+NNNKSSSSSSSSSSS
+FFFFFFFFFFFFFYF
+LLLLLLLLLLLLLLL
+DDDDDDDDDDDDDDN
+DDEDDDDDDDDDDDD
+DDDDEEDDDEDE-GN
+QQQQQQQQQQQQ-QQ
+LLEEIIIIIIIM-IV
+EEAAEEKDAGAS-AA
+EEAAAGEEEEEE-DD
+GGGGGGGGGGGG-GG
+WWFFFWWWFFFY-WW
+VVVVVVVVVVVV-VV
+LLLLLLLLLLLL-LL
+TTTTTTTTTTTT-TT
+CCCCCCCCCCCC-CC
+VVVVVVVAAAAV-HA
+AAAAAAAAAAAA-AA
+YYYYYFYYYYYY-YY
+PPPPPPPPPPPP-PP
+QQKKTTTVTTTT-TT
+SSGCSSGSSSSS-SS
+DDDDDDDDDDDD-DD
+VVVVVVVVVVVV-VV
+TTTTVTTTTTTV-VV
+IIIIIIIIIIII-II
+EEEEEEEEEEEE-EE
+TTTTTTTTTTTT-TT
+HHHHHHHHHHHH-HH
+KKKKKKKKRKKK-KK
+EEEEEEEEEEEE-EE
+AAEEEEEEEEEE-ED
+EEEEDEEEDDEA-ED
+LLLLLLLLMILI-LL
+VVTTTTTTVVVM-TL
+GGAAAAAA-----G-
+-------------A-
+*
--- /dev/null
+>FER_CAPAA/1-97 Ferredoxin
+-----------------------------------------------------------ASYKVKLITPDGP
+IEFDCPDDVYILDQAEEAGHDLPYSCRAGSCSSCAGKIAGGAVDQTDGNFLDDDQLEEGWVLTCVAYPQSDV
+TIETHKEAELVG-
+>FER_CAPAN/1-144 Ferredoxin, chloroplast precursor
+MA------SVSATMISTSFMPRKPAVTSL-KPIPNVGE--ALFGLKS-A--NGGKVTCMASYKVKLITPDGP
+IEFDCPDNVYILDQAEEAGHDLPYSCRAGSCSSCAGKIAGGAVDQTDGNFLDDDQLEEGWVLTCVAYPQSDV
+TIETHKEAELVG-
+>FER1_SOLLC/1-144 Ferredoxin-1, chloroplast precursor
+MA------SISGTMISTSFLPRKPAVTSL-KAISNVGE--ALFGLKS-G--RNGRITCMASYKVKLITPEGP
+IEFECPDDVYILDQAEEEGHDLPYSCRAGSCSSCAGKVTAGSVDQSDGNFLDEDQEAAGFVLTCVAYPKGDV
+TIETHKEEELTA-
+>Q93XJ9_SOLTU/1-144 Ferredoxin I precursor
+MA------SISGTMISTSFLPRKPVVTSL-KAISNVGE--ALFGLKS-G--RNGRITCMASYKVKLITPDGP
+IEFECPDDVYILDQAEEEGHDLPYSCRAGSCSSCAGKVTAGTVDQSDGKFLDDDQEAAGFVLTCVAYPKCDV
+TIETHKEEELTA-
+>FER1_PEA/1-149 Ferredoxin-1, chloroplast precursor
+MATT---PALYGTAVSTSFLRTQPMPMSV-TTTKAFSN--GFLGLKT-SLKRGDLAVAMASYKVKLVTPDGT
+QEFECPSDVYILDHAEEVGIDLPYSCRAGSCSSCAGKVVGGEVDQSDGSFLDDEQIEAGFVLTCVAYPTSDV
+VIETHKEEDLTA-
+>Q7XA98_TRIPR/1-152 Ferredoxin I
+MATT---PALYGTAVSTSFMRRQPVPMSV-ATTTTTKAFPSGFGLKSVSTKRGDLAVAMATYKVKLITPEGP
+QEFDCPDDVYILDHAEEVGIELPYSCRAGSCSSCAGKVVNGNVNQEDGSFLDDEQIEGGWVLTCVAFPTSDV
+TIETHKEEELTA-
+>FER1_MESCR/1-148 Ferredoxin-1, chloroplast precursor
+MAAT--TAALSGATMSTAFAPK--TPPMTAALPTNVGR--ALFGLKS-SASR-GRVTAMAAYKVTLVTPEGK
+QELECPDDVYILDAAEEAGIDLPYSCRAGSCSSCAGKVTSGSVNQDDGSFLDDDQIKEGWVLTCVAYPTGDV
+TIETHKEEELTA-
+>FER1_SPIOL/1-147 Ferredoxin-1, chloroplast precursor
+MAAT--TTTMMG--MATTFVPKPQAPPMMAALPSNTGR--SLFGLKT-GSR--GGRMTMAAYKVTLVTPTGN
+VEFQCPDDVYILDAAEEEGIDLPYSCRAGSCSSCAGKLKTGSLNQDDQSFLDDDQIDEGWVLTCAAYPVSDV
+TIETHKEEELTA-
+>FER3_RAPSA/1-96 Ferredoxin, leaf L-A
+-----------------------------------------------------------ATYKVKFITPEGE
+QEVECDDDVYVLDAAEEAGIDLPYSCRAGSCSSCAGKVVSGSVDQSDQSFLDDDQIAEGFVLTCAAYPTSDV
+TIETHREEDMV--
+>FER2_ARATH/1-148 Ferredoxin-2, chloroplast precursor
+MAST----ALSSAIVGTSFIRRSPAPISLRSLPSANTQ--SLFGLKS-GTARGGRVTAMATYKVKFITPEGE
+LEVECDDDVYVLDAAEEAGIDLPYSCRAGSCSSCAGKVVSGSVDQSDQSFLDDEQIGEGFVLTCAAYPTSDV
+TIETHKEEDIV--
+>FER_BRANA/1-96 Ferredoxin
+-----------------------------------------------------------ATYKVKFITPEGE
+QEVECDDDVYVLDAAEEAGIDLPYSCRAGSCSSCAGKVVSGFVDQSDESFLDDDQIAEGFVLTCAAYPTSDV
+TIETHKEEELV--
+>FER1_ARATH/1-148 Ferredoxin-1, chloroplast precursor
+MAST----ALSSAIVSTSFLRRQQTPISLRSLPFANTQ--SLFGLKS-STARGGRVTAMATYKVKFITPEGE
+QEVECEEDVYVLDAAEEAGLDLPYSCRAGSCSSCAGKVVSGSIDQSDQSFLDDEQMSEGYVLTCVAYPTSDV
+VIETHKEEAIM--
+>Q93Z60_ARATH/1-118 At1g10960/T19D16_12
+MAST----ALSSAIVSTSFLRRQQTPISLRSLPFANTQ--SLFGLKS-STARGGRVTAMATYKVKFITPEGE
+QEVECEEDVYVLDAAEEAGLDLPYSCRAGSCSSCAGKVVSGSIDQSDQSFLDD-------------------
+-------------
+>FER1_MAIZE/1-150 Ferredoxin-1, chloroplast precursor
+MATVLGSPRAPAFFFSSSSLRAAPAPTAV--ALPAAKV--GIMGRSA-SSRR--RLRAQATYNVKLITPEGE
+VELQVPDDVYILDQAEEDGIDLPYSCRAGSCSSCAGKVVSGSVDQSDQSYLDDGQIADGWVLTCHAYPTSDV
+VIETHKEEELTGA
+>O80429_MAIZE/1-140 Ferredoxin
+MAAT---------ALSMSILR---APPPCFSSPLRLRV--AVAKPLA-APMRRQLLRAQATYNVKLITPEGE
+VELQVPDDVYILDFAEEEGIDLPFSCRAGSCSSCAGKVVSGSVDQSDQSFLNDNQVADGWVLTCAAYPTSDV
+VIETHKEDDLL--
--- /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.gui;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+
+import java.io.File;
+
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import jalview.bin.Cache;
+import jalview.bin.Jalview;
+import jalview.datamodel.AlignmentI;
+import jalview.datamodel.SequenceI;
+import jalview.gui.StructureViewer.ViewerType;
+import jalview.io.DataSourceType;
+import jalview.io.FileLoader;
+import jalview.structure.StructureImportSettings.TFType;
+
+public class AnnotationLabelsTest2
+{
+ @BeforeClass(alwaysRun = true)
+ public static void setUpBeforeClass() throws Exception
+ {
+ if (Desktop.instance != null)
+ Desktop.instance.closeAll_actionPerformed(null);
+
+ setUpJvOptionPane();
+ /*
+ * use read-only test properties file
+ */
+ Cache.loadProperties("test/jalview/io/testProps.jvprops");
+ Jalview.main(new String[] { "--nonews", "--nosplash", });
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown()
+ {
+ if (Desktop.instance != null)
+ Desktop.instance.closeAll_actionPerformed(null);
+ }
+
+ /**
+ * 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",
+ Boolean.TRUE.toString());
+
+ }
+
+ public static void setUpJvOptionPane()
+ {
+ JvOptionPane.setInteractiveMode(false);
+ JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
+ }
+
+ @Test(
+ groups =
+ { "Functional", "testTask1" },
+ dataProvider = "openFilesWithIdWidthChanges")
+ public void testIdWidthChanges(String alignmentFilename, boolean wrap,
+ int idWidth1min, int idWidth1max, int manualWidth,
+ String structureFilename, String paeFilename,
+ boolean secondaryStructureView, TFType temperatureFactorType,
+ ViewerType viewerType, int idWidth2min, int idWidth2max)
+ {
+ AlignFrame af = new FileLoader()
+ .LoadFileWaitTillLoaded(alignmentFilename, DataSourceType.FILE);
+ try
+ {
+ Thread.sleep(200); // to allow alignment annotations to open
+ } catch (InterruptedException e)
+ {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ AlignViewport av = af.getCurrentView();
+
+ int idWidth = 0;
+
+ idWidth = av.getIdWidth();
+ assertTrue(idWidth > idWidth1min,
+ "idWidth (" + idWidth + ") is not greater than " + idWidth1min);
+ assertTrue(idWidth < idWidth1max,
+ "idWidth (" + idWidth + ") is not narrower than" + idWidth1max);
+
+ // set wrap
+ if (wrap)
+ {
+ af.setWrapFormat(true, false);
+ idWidth = av.getIdWidth();
+ assertTrue(idWidth > idWidth1min, "After wrap idWidth (" + idWidth
+ + ") is not greater than " + idWidth1min);
+ assertTrue(idWidth < idWidth1max, "After wrap idWidth (" + idWidth
+ + ") is not narrower than" + idWidth1max);
+ }
+
+ AlignmentI al = av.getAlignment();
+ SequenceI s = al.getSequenceAt(0);
+ AlignmentPanel ap = af.alignPanel;
+
+ File structureFile = new File(structureFilename);
+ File paeFile = new File(paeFilename);
+
+ StructureViewer sv = StructureChooser.openStructureFileForSequence(null,
+ null, ap, s, false, structureFile.getAbsolutePath(),
+ temperatureFactorType, paeFile.getAbsolutePath(), true,
+ secondaryStructureView, false, viewerType);
+ // give time for annotations to open
+ try
+ {
+ Thread.sleep(200); // to allow alignment annotations to open
+ } catch (InterruptedException e)
+ {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ // idWidth = ap.getIdPanel().getWidth();
+ idWidth = av.getIdWidth();
+ assertTrue(idWidth > idWidth2min,
+ "idWidth (" + idWidth + ") is not greater than " + idWidth2min);
+ assertTrue(idWidth < idWidth2max,
+ "idWidth (" + idWidth + ") is not narrower than" + idWidth2max);
+ }
+
+ @Test(
+ groups =
+ { "Functional", "testTask1" },
+ dataProvider = "openFilesWithIdWidthChanges")
+ public void testIdWidthNoChanges(String alignmentFilename, boolean wrap,
+ int idWidth1min, int idWidth1max, int manualWidth,
+ String structureFilename, String paeFilename,
+ boolean secondaryStructureView, TFType temperatureFactorType,
+ ViewerType viewerType, int idWidth2min, int idWidth2max)
+ {
+ AlignFrame af = new FileLoader()
+ .LoadFileWaitTillLoaded(alignmentFilename, DataSourceType.FILE);
+ try
+ {
+ Thread.sleep(200); // to allow alignment annotations to open
+ } catch (InterruptedException e)
+ {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ AlignViewport av = af.getCurrentView();
+
+ int idWidth = 0;
+
+ idWidth = av.getIdWidth();
+ assertTrue(idWidth > idWidth1min,
+ "idWidth (" + idWidth + ") is not greater than " + idWidth1min);
+ assertTrue(idWidth < idWidth1max,
+ "idWidth (" + idWidth + ") is not narrower than" + idWidth1max);
+
+ AlignmentI al = av.getAlignment();
+ SequenceI s = al.getSequenceAt(0);
+ AlignmentPanel ap = af.alignPanel;
+
+ // set width manually
+ av.setIdWidth(manualWidth);
+ ap.validateAnnotationDimensions(false);
+ ap.paintAlignment(true, false);
+ ap.getIdPanel().getIdCanvas().setManuallyAdjusted(true);
+
+ idWidth = av.getIdWidth();
+ assertEquals(idWidth, manualWidth,
+ "idWidth is not set to the manually set width " + manualWidth);
+
+ File structureFile = new File(structureFilename);
+ File paeFile = new File(paeFilename);
+
+ StructureViewer sv = StructureChooser.openStructureFileForSequence(null,
+ null, ap, s, false, structureFile.getAbsolutePath(),
+ temperatureFactorType, paeFile.getAbsolutePath(), false,
+ secondaryStructureView, false, viewerType);
+
+ idWidth = ap.getIdPanel().getWidth();// av.getIdWidth();
+ idWidth = av.getIdWidth();
+ assertEquals(idWidth, manualWidth,
+ "idWidth is not set to the manually set width " + manualWidth
+ + " after adding structure annotations");
+ assertFalse(idWidth > idWidth2min,
+ "idWidth (" + idWidth + ") is greater than " + idWidth2min);
+ }
+
+ @DataProvider(name = "openFilesWithIdWidthChanges")
+ public Object[][] openFilesWithIdWidthChanges()
+ {
+ /*
+ String alignmentFilename,
+ boolean wrap,
+ int idWidth1min,
+ int idWidth1max,
+ int manualWidth, // ignored by testIdWidthChanges()
+ String structureFilename,
+ String paeFilename,
+ boolean secondaryStructureView,
+ TFType temperatureFactorType,
+ ViewerType viewerType,
+ int idWidth2min,
+ int idWidth2max,
+ */
+ return new Object[][] {
+ //
+ /*
+ */
+ { "./test/files/annotation_label_width/sample.a2m", false, 50, 70,
+ 100,
+ "./examples/test_fab41.result/test_fab41_unrelaxed_rank_1_model_3.pdb",
+ "./examples/test_fab41.result/test_fab41_unrelaxed_rank_1_model_3_scores.json",
+ true, TFType.PLDDT, null, 115, 130 },
+ { "./test/files/annotation_label_width/sample.a2m", true, 50, 70,
+ 100,
+ "./examples/test_fab41.result/test_fab41_unrelaxed_rank_1_model_3.pdb",
+ "./examples/test_fab41.result/test_fab41_unrelaxed_rank_1_model_3_scores.json",
+ true, TFType.PLDDT, null, 115, 130 },
+ /*
+ */
+ };
+ }
+
+}
package jalview.util;
import java.io.File;
-import java.io.IOException;
import java.util.List;
import org.testng.Assert;
}
@Test(groups = "Functional", dataProvider = "dirnamesAndBasenames")
- public void testDirnamesAndBasenames(String filename, int where,
- String dirname, String basename, String notInDirname)
+ public void testDirnamesAndBasenames(String filename, String dirname,
+ String endsWith, String basename, String notInDirname)
{
File file = new File(filename);
String d = FileUtils.getDirname(file);
String b = FileUtils.getBasename(file);
Assert.assertEquals(b, basename);
- if (where == 0)
- Assert.assertEquals(d, dirname);
- else if (where < 0)
- Assert.assertTrue(d.startsWith(dirname),
- "getDirname(" + file.getPath() + ")=" + d
- + " didn't start with '" + dirname + "'");
- else if (where > 0)
- Assert.assertTrue(d.endsWith(dirname), "getDirname(" + file.getPath()
- + ")=" + d + " didn't end with '" + d + "'");
+ Assert.assertTrue(d.startsWith(dirname), "getDirname(" + file.getPath()
+ + ")=" + d + " didn't start with '" + dirname + "'");
+ Assert.assertTrue(d.endsWith(endsWith), "getDirname(" + file.getPath()
+ + ")=" + d + " didn't end with '" + endsWith + "'");
// ensure dirname doesn't end with basename (which means you can't use same
// filename as dir in tests!)
- Assert.assertFalse(d.endsWith(b));
+ Assert.assertFalse(d.endsWith(b), "Processed dirname '" + d
+ + "' ends with '" + b + "' when it shouldn't");
if (notInDirname != null)
- Assert.assertFalse(d.contains(notInDirname));
+ Assert.assertFalse(d.contains(notInDirname), "Processed directory '"
+ + d + "' contains '" + notInDirname + "' when it shouldn't");
}
@DataProvider(name = "patternsAndMinNumFiles")
@DataProvider(name = "dirnamesAndBasenames")
public Object[][] dirnamesAndBasenames()
{
- String homeDir = null;
- try
- {
- homeDir = new File(System.getProperty("user.home"))
- .getCanonicalPath();
- } catch (IOException e)
- {
- System.err.println("Problem getting canonical home dir");
- e.printStackTrace();
- }
+ String homeDir = new File(System.getProperty("user.home")).getPath();
return new Object[][] { // -1=startsWith, 0=equals, 1=endsWith
- { "~/hello/sailor", -1, homeDir, "sailor", "~" }, //
- { "~/hello/sailor", 1, "/hello", "sailor", "~" }, //
- { "./examples/uniref50.fa", -1, "/", "uniref50", "." }, //
- { "./examples/uniref50.fa", 1, "/examples", "uniref50", "." }, //
- { "examples/uniref50.fa", 1, "/examples", "uniref50", ".fa" }, //
+ { "~/hello/sailor", homeDir, "/hello", "sailor", "~" }, //
+ { "./examples/uniref50.fa", "./", "examples", "uniref50", "Users" }, //
+ { "./examples/uniref50.1.fa", "./", "examples", "uniref50.1",
+ "Users" }, //
+ { "examples/uniref50.fa", "examples", "examples", "uniref50",
+ ".fa" }, //
};
}
+
+ @Test(groups = "Functional", dataProvider = "convertWildcardsToPathData")
+ public void convertWildcardsToPathTest(String value, String wildcard,
+ String dirname, String basename, String path)
+ {
+
+ Assert.assertEquals(
+ FileUtils.convertWildcardsToPath(value, wildcard, dirname,
+ basename),
+ path, "Conversion of wildcard output path is not right.");
+
+ }
+
+ @DataProvider(name = "convertWildcardsToPathData")
+ public Object[][] convertWildcardsToPathData()
+ {
+ return new Object[][] {
+ /*
+ * cmdline args
+ * Arg (null if only testing headless)
+ * String value if there is one (null otherwise)
+ * boolean value if String value is null
+ * expected value of isHeadless()
+ */
+ /*
+ */
+ { "*/*", "*", "{dirname}", "{basename}", "{dirname}/{basename}" },
+ { "*/", "*", "{dirname}", "{basename}", "{dirname}/" },
+ { "/*", "*", "{dirname}", "{basename}", "/{basename}" },
+ { "*", "*", "{dirname}", "{basename}", "{basename}" },
+ { "tmp/output/*/file-*.stk", "*", "{dirname}", "{basename}",
+ "tmp/output/{dirname}/file-{basename}.stk" },
+ { "/*.file", "*", "{dirname}", "{basename}", "/{basename}.file" },
+ { "*/file.stk", "*", "{dirname}", "{basename}",
+ "{dirname}/file.stk" },
+ { "tmp/abc*def/file.stk", "*", "{dirname}", "{basename}",
+ "tmp/abc{dirname}def/file.stk" },
+ { "a*b/c*d", "*", "{dirname}", "{basename}",
+ "a{dirname}b/c{basename}d" },
+ { "a*b/c", "*", "{dirname}", "{basename}", "a{dirname}b/c" },
+ { "a/b*c", "*", "{dirname}", "{basename}", "a/b{basename}c" },
+ { "a*b", "*", "{dirname}", "{basename}", "a{basename}b" },
+ { "aSTARb/cSTARd", "STAR", "BEFORE", "AFTER", "aBEFOREb/cAFTERd" },
+ { "aSTARb/c", "STAR", "BEFORE", "AFTER", "aBEFOREb/c" },
+ { "a/bSTARc", "STAR", "BEFORE", "AFTER", "a/bAFTERc" },
+ { "aSTARb", "STAR", "BEFORE", "AFTER", "aAFTERb" },
+ //
+ };
+ }
+
}
--- /dev/null
+package jalview.util;
+
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import jalview.bin.Cache;
+import jalview.util.imagemaker.BitmapImageSizing;
+
+public class ImageMakerTest
+{
+ @Test(groups = { "Functional" })
+ public void testParseScaleWidthHeightStrings()
+ {
+ Cache.setPropsAreReadOnly(true);
+ Cache.loadProperties("test/jalview/bin/testProps.jvprops");
+
+ Cache.removeProperty(BitmapImageSizing.BITMAP_SCALE);
+ Cache.removeProperty(BitmapImageSizing.BITMAP_HEIGHT);
+ Cache.removeProperty(BitmapImageSizing.BITMAP_WIDTH);
+
+ BitmapImageSizing bis = null;
+
+ // No defaults set, 3 values given. Should be the 3 values.
+ bis = ImageMaker.parseScaleWidthHeightStrings("1.2", "3", "4");
+ Assert.assertEquals(bis.scale(), 1.2f,
+ "scale not parsed and set to value given");
+ Assert.assertEquals(bis.width(), 3,
+ "width not parsed and set to value given");
+ Assert.assertEquals(bis.height(), 4,
+ "height not parsed and set to value given");
+
+ // No defaults set, 1 value given. Should be the 1 value and 2 0s.
+ bis = ImageMaker.parseScaleWidthHeightStrings("1.2", null, null);
+ Assert.assertEquals(bis.scale(), 1.2f,
+ "scale not parsed and set to value given");
+ Assert.assertEquals(bis.width(), 0, "width not parsed and set to 0");
+ Assert.assertEquals(bis.height(), 0, "height not parsed and set to 0");
+
+ // No defaults set, 1 value given. Should be the 1 value and 2 0s. (checking
+ // the other value)
+ bis = ImageMaker.parseScaleWidthHeightStrings(null, "1", null);
+ Assert.assertEquals(bis.scale(), 0f, "scale not parsed and set to 0f");
+ Assert.assertEquals(bis.width(), 1,
+ "width not parsed and set to value given");
+ Assert.assertEquals(bis.height(), 0, "height not parsed and set to 0");
+
+ // No defaults set, no values given, these should first look at defaults and
+ // then set all to 0
+ bis = ImageMaker.parseScaleWidthHeightStrings(null, null, null);
+ Assert.assertEquals(bis.scale(), 0f,
+ "scale not parsed and set to undefined default 0f");
+ Assert.assertEquals(bis.width(), 0,
+ "width not parsed and set to undefined default 0");
+ Assert.assertEquals(bis.height(), 0,
+ "height not parsed and set to undefined default 0");
+
+ Cache.setProperty(BitmapImageSizing.BITMAP_HEIGHT, "1");
+ // 1 default set, bis should detect this
+ Assert.assertEquals(bis.scale(), 0f,
+ "scale not parsed and set to undefined default 0f");
+ Assert.assertEquals(bis.width(), 0,
+ "width not parsed and set to undefined default 0");
+ Assert.assertEquals(bis.height(), 1,
+ "height not parsed and set to default 1");
+
+ Cache.setProperty(BitmapImageSizing.BITMAP_SCALE, "3.4");
+ Cache.setProperty(BitmapImageSizing.BITMAP_WIDTH, "2");
+ // Now all 3 defaults set, bis should detect this
+ Assert.assertEquals(bis.scale(), 3.4f,
+ "scale not parsed and set to undefined default 3.2f");
+ Assert.assertEquals(bis.width(), 2,
+ "width not parsed and set to undefined default 2");
+ Assert.assertEquals(bis.height(), 1,
+ "height not parsed and set to default 1");
+
+ // 3 defaults set, and 3 values given, should use the 3 values
+ bis = ImageMaker.parseScaleWidthHeightStrings("1.2", "3", "4");
+ Assert.assertEquals(bis.scale(), 1.2f,
+ "scale not parsed and set to value given");
+ Assert.assertEquals(bis.width(), 3,
+ "width not parsed and set to value given");
+ Assert.assertEquals(bis.height(), 4,
+ "height not parsed and set to value given");
+
+ // 3 defaults set, and 1 value given, should use the 1 value and 2 0s
+ bis = ImageMaker.parseScaleWidthHeightStrings("1.2", null, null);
+ Assert.assertEquals(bis.scale(), 1.2f,
+ "scale not parsed and set to value given");
+ Assert.assertEquals(bis.width(), 0,
+ "width not parsed and set to undefined 0");
+ Assert.assertEquals(bis.height(), 0,
+ "height not parsed and set to undefined 0");
+
+ // 3 defaults set, and 1 value given, should use the 1 value and 2 0s
+ bis = ImageMaker.parseScaleWidthHeightStrings(null, null, "5");
+ Assert.assertEquals(bis.scale(), 0f,
+ "scale not parsed and set to undefined 0f");
+ Assert.assertEquals(bis.width(), 0,
+ "width not parsed and set to undefined 0");
+ Assert.assertEquals(bis.height(), 5,
+ "height not parsed and set to value given");
+
+ // 3 defaults set, and no values given, should use the 3 default values
+ bis = ImageMaker.parseScaleWidthHeightStrings(null, null, null);
+ Assert.assertEquals(bis.scale(), 3.4f,
+ "scale not parsed and set to undefined default 3.4f");
+ Assert.assertEquals(bis.width(), 2,
+ "width not parsed and set to undefined default 2");
+ Assert.assertEquals(bis.height(), 1,
+ "height not parsed and set to default 1");
+ }
+}
--- /dev/null
+package jalview.util.imagemaker;
+
+import static org.testng.Assert.assertEquals;
+
+import org.testng.annotations.Test;
+
+import jalview.bin.Cache;
+
+public class BitmapImageSizeTest
+{
+ @Test(groups = { "Functional" })
+ public void testCacheSettingsRecovery()
+ {
+ Cache.setPropsAreReadOnly(true);
+ Cache.loadProperties("test/jalview/bin/testProps.jvprops");
+
+ Cache.removeProperty(BitmapImageSizing.BITMAP_HEIGHT);
+ Cache.removeProperty(BitmapImageSizing.BITMAP_SCALE);
+ Cache.removeProperty(BitmapImageSizing.BITMAP_WIDTH);
+
+ BitmapImageSizing def = BitmapImageSizing.defaultBitmapImageSizing();
+ BitmapImageSizing zero = BitmapImageSizing.nullBitmapImageSizing();
+
+ assertEquals(def.height(), zero.height());
+ assertEquals(def.width(), zero.width());
+ assertEquals(def.scale(), zero.scale());
+
+ Cache.setProperty(BitmapImageSizing.BITMAP_HEIGHT, "120");
+ Cache.setProperty(BitmapImageSizing.BITMAP_SCALE, "24");
+ Cache.setProperty(BitmapImageSizing.BITMAP_WIDTH, "360");
+
+ // default now updates dynamically
+ // def = BitmapImageSizing.defaultBitmapImageSizing();
+
+ assertEquals(def.height(), 120);
+ assertEquals(def.width(), 360);
+ assertEquals(def.scale(), 24f);
+
+ Cache.removeProperty(BitmapImageSizing.BITMAP_WIDTH);
+
+ // def = BitmapImageSizing.defaultBitmapImageSizing();
+ assertEquals(def.height(), 120);
+ assertEquals(def.width(), zero.width());
+ assertEquals(def.scale(), 24f);
+ }
+}
--- /dev/null
+#!/usr/bin/env bash
+
+###############################
+# Wrapper for Jalview
+#
+# 2023-08-16 Jalview 2.11.3.0 has new command line arguments
+# Old command line arguments are currently detected and actioned
+# but are no longer supported and will be removed at a later date.
+#
+# See
+# Jalview -> Help -> Documentation -> Command Line -> introduction and reference
+# or
+# https://www.jalview.org/help/html/features/clarguments.html
+# for details of the new command line arguments.
+#
+# Note, in order to run commandline-only calls use
+# --headless
+#
+# By default, this wrapper executes java -version to determine the JRE version
+# Set JALVIEW_JRE=j1.8 or JALVIEW_JRE=j11 to skip the version check.
+#
+# By default, this wrapper does NOT restrict the memory consumption of Jalview.
+# Set eg. JALVIEW_MAXMEM=1g to set the maximal memory of Jalview's VM
+#
+# This script is maintained in the Jalview repository in utils/conda/jalview.sh
+###############################
+
+declare -a ARGS=("${@}")
+ARG1=$1
+
+# this function is because there's no readlink -f in Darwin/macOS
+function readlinkf() {
+ FINDFILE="$1"
+ FILE="${FINDFILE}"
+ PREVFILE=""
+ C=0
+ MAX=100 # just in case we end up in a loop
+ FOUND=0
+ while [ "${C}" -lt "${MAX}" -a "${FILE}" != "${PREVFILE}" -a "${FOUND}" -ne 1 ]; do
+ PREVFILE="${FILE}"
+ FILE="$(readlink "${FILE}")"
+ if [ -z "${FILE}" ]; then
+ # the readlink is empty means we've arrived at the script, let's canonicalize with pwd
+ FILE="$(cd "$(dirname "${PREVFILE}")" &> /dev/null && pwd -P)"/"$(basename "${PREVFILE}")"
+ FOUND=1
+ elif [ "${FILE#/}" = "${FILE}" ]; then
+ # FILE is not an absolute path link, we need to add the relative path to the previous dir
+ FILE="$(dirname "${PREVFILE}")/${FILE}"
+ fi
+ C=$((C+1))
+ done
+ if [ "${FOUND}" -ne 1 ]; then
+ echo "Could not determine path to actual file '$(basename "${FINDFILE}")'" >&2
+ exit 1
+ fi
+ echo "${FILE}"
+}
+
+ISMACOS=0
+if [ "$( uname -s )" = "Darwin" ]; then
+ ISMACOS=1
+fi
+
+# check for headless mode
+HEADLESS=0
+GUI=0
+HELP=0
+DEBUG=0
+for RAWARG in "${@}"; do
+ ARG="${RAWARG%%=*}"
+ case "${ARG}" in
+ --headless|--output|--image|--structureimage)
+ HEADLESS=1
+ ;;
+ --help|--help-*|--version)
+ HELP=1
+ ;;
+ --gui)
+ GUI=1
+ ;;
+ --debug)
+ DEBUG=1
+ ;;
+ esac
+
+ if [ "${HELP}" = 1 ]; then
+ # --help takes precedence
+ HEADLESS=1
+ GUI=0
+ elif [ "${GUI}" = 1 ]; then
+ # --gui takes precedence over --headless
+ HEADLESS=0
+ fi
+done
+
+declare -a JVMARGS=()
+
+# set vars for being inside the macos App Bundle
+if [ "${ISMACOS}" = 1 ]; then
+# MACOS ONLY
+ DIR="$(dirname "$(readlinkf "$0")")"
+ JVMARGS=( "${JVMARGS[@]}" "-Xdock:icon=${DIR}/jalview_logo.png" )
+else
+# NOT MACOS
+ DIR="$(dirname "$(readlink -f "$0")")"
+fi
+
+if [ "${HEADLESS}" = 1 ]; then
+ # this suppresses the Java icon appearing in the macOS Dock and maybe other things in other OSes
+ JVMARGS=( "${JVMARGS[@]}" "-Djava.awt.headless=true" )
+fi
+
+JAVA=java
+
+# decide which jalview jar to launch - either 'j11' or 'j1.8'
+if [[ "$JALVIEW_JRE" != "j11" && "$JALVIEW_JRE" != "j1.8" ]]; then
+ JALVIEW_JRE="j11"
+ # if java 8 is installed we pick the j1.8 build
+ if [[ $( "${JAVA}" -version 2>&1 | grep '"1.8' ) != "" ]]; then
+ JALVIEW_JRE="j1.8"
+ fi
+fi
+
+JARPATH="${DIR}/jalview-all-${JALVIEW_JRE}.jar"
+
+# check if memory maximum is set and if so forward to java-based jalview call
+if [ \! -z "$JALVIEW_MAXMEM" ]; then
+ JVMARGS=( "${JVMARGS[@]}" "-Xmx${JALVIEW_MAXMEM}" )
+fi
+
+# WINDOWS ONLY (Cygwin or WSL)
+# change paths for Cygwin or Windows Subsystem for Linux (WSL)
+if [ "${ISMACOS}" != 1 ]; then # older macos doesn't like uname -o, best to avoid
+ if [ "$(uname -o)" = "Cygwin" ]; then
+ # CYGWIN
+ JARPATH="$(cygpath -pw "${JARPATH}")"
+ # now for some arg paths fun. only translating paths starting with './', '../', '/' or '~'
+ ARGS=()
+ for ARG in "${@}"; do
+ if [ "${ARG}" != "${ARG#@(/|./|../|~)}" ]; then
+ ARGS=( "${ARGS[@]}" "$(cygpath -aw "${ARG}")" )
+ else
+ ARGS=( "${ARGS[@]}" "${ARG}" )
+ fi
+ done
+ elif uname -r | grep -i microsoft | grep -i wsl >/dev/null; then
+ # WSL
+ JARPATH="$(wslpath -aw "${JARPATH}")"
+ ARGS=()
+ for ARG in "${@}"; do
+ if [ "${ARG}" != "${ARG#@(/|./|../|~)}" ]; then
+ # annoyingly wslpath does not work if the file doesn't exist!
+ ARGBASENAME="$(basename "${ARG}")"
+ ARGDIRNAME="$(dirname "${ARG}")"
+ ARGS=( "${ARGS[@]}" "$(wslpath -aw "${ARGDIRNAME}")\\${ARGBASENAME}" )
+ else
+ ARGS=( "${ARGS[@]}" "${ARG}" )
+ fi
+ done
+ JAVA="${JAVA}.exe"
+ fi
+fi
+
+# get console width -- three ways to try, just in case
+if command -v tput 2>&1 >/dev/null; then
+ COLUMNS=$(tput cols) 2>/dev/null
+elif command -v stty 2>&1 >/dev/null; then
+ COLUMNS=$(stty size | cut -d" " -f2) 2>/dev/null
+elif command -v resize 2>&1 >/dev/null; then
+ COLUMNS=$(resize -u | grep COLUMNS= | sed -e 's/.*=//;s/;//') 2>/dev/null
+fi
+JVMARGS=( "${JVMARGS[@]}" "-DCONSOLEWIDTH=${COLUMNS}" )
+
+if [ "${DEBUG}" = 1 ]; then
+ echo Shell running: "${JAVA}" "${JVMARGS[@]}" -jar \""${JARPATH}"\" "${ARGS[@]}"
+fi
+
+"${JAVA}" "${JVMARGS[@]}" -jar "${JARPATH}" "${ARGS[@]}"
ISMACOS=1
fi
+# check for headless mode
+HEADLESS=0
+GUI=0
+HELP=0
+DEBUG=0
+for RAWARG in "${@}"; do
+ ARG="${RAWARG%%=*}"
+ case "${ARG}" in
+ --headless|--output|--image|--structureimage)
+ HEADLESS=1
+ ;;
+ --help|--help-*|--version|-h)
+ HELP=1
+ ;;
+ --gui)
+ GUI=1
+ ;;
+ --debug)
+ DEBUG=1
+ ;;
+ esac
+
+ if [ "${HELP}" = 1 ]; then
+ # --help takes precedence
+ HEADLESS=1
+ GUI=0
+ elif [ "${GUI}" = 1 ]; then
+ # --gui takes precedence over --headless
+ HEADLESS=0
+ fi
+done
+
declare -a JVMARGS=()
# set vars for being inside the macos App Bundle
if [ "${ISMACOS}" = 1 ]; then
# MACOS ONLY
DIR="$(dirname "$(readlinkf "$0")")"
- APP="${DIR%.app/Contents/*}".app
- if [ "${APP}" = "${APP%.app}" ]; then
- echo "Could not find Jalview.app" >&2
- exit 2
- fi
- APPDIR="${APP}/Contents/Resources/app"
+ APPDIR="${DIR%/bin}"
JAVA="${APPDIR}/jre/Contents/Home/bin/java"
JVMARGS=( "${JVMARGS[@]}" "-Xdock:icon=${APPDIR}/resource/jalview_logo.png" )
else
JAVA="${APPDIR}/jre/bin/java"
fi
+if [ "${HEADLESS}" = 1 ]; then
+ # this suppresses the Java icon appearing in the macOS Dock and maybe other things in other OSes
+ JVMARGS=( "${JVMARGS[@]}" "-Djava.awt.headless=true" )
+fi
+
SYSJAVA=java
GETDOWNTXT="${APPDIR}/getdown.txt"
echo "Cannot find bundled java, using system ${JAVA} and hoping for the best!" >&2
fi
+if [ "${DEBUG}" = 1 ]; then
+ echo Shell running: \""${JAVA}"\" \""${JVMARGS[@]}"\" -cp \""${CLASSPATH}"\" jalview.bin.Launcher "${ARGS[@]}"
+fi
+
"${JAVA}" "${JVMARGS[@]}" -cp "${CLASSPATH}" jalview.bin.Launcher "${ARGS[@]}"
<?xml version="1.0" encoding="UTF-8"?>
-<install4j version="10.0.5" transformSequenceNumber="10">
+<install4j version="10.0.6" transformSequenceNumber="10">
<directoryPresets config="bin/Jalview" />
<application name="${compiler:JALVIEW_APPLICATION_NAME}" applicationId="${compiler:WINDOWS_APPLICATION_ID}" mediaDir="${compiler:BUILD_DIR}" lzmaCompression="true" shortName="${compiler:INTERNAL_ID}" publisher="University of Dundee" publisherWeb="https://www.jalview.org/" version="${compiler:JALVIEW_VERSION}" allPathsRelative="true" macVolumeId="5aac4968c304f65" javaMinVersion="${compiler:JAVA_MIN_VERSION}" javaMaxVersion="${compiler:JAVA_MAX_VERSION}" allowBetaVM="true" jdkMode="jdk" jdkName="JDK 11.0">
<searchSequence>
</exclude>
<jreBundle jreBundleSource="preCreated" includedJre="${compiler:WINDOWS_X64_JAVA_VM_TGZ}" manualJreEntry="true" />
</windows>
- <macosArchive name="macOS x64 Disk Image" id="878" customizedId="MACOS-X64-DMG" mediaFileName="${compiler:APPLICATION_FOLDER}-${compiler:JALVIEW_VERSION}-${compiler:sys.platform}-x64-java_${compiler:JAVA_INTEGER_VERSION}" volumeName="${compiler:INSTALLER_NAME}" launcherId="737" setupAppId="2746">
+ <macosArchive name="macOS x64 (intel) Disk Image" id="878" customizedId="MACOS-X64-DMG" mediaFileName="${compiler:APPLICATION_FOLDER}-${compiler:JALVIEW_VERSION}-${compiler:sys.platform}-x64-java_${compiler:JAVA_INTEGER_VERSION}" volumeName="${compiler:INSTALLER_NAME}" launcherId="737" setupAppId="2746">
<exclude>
<entry defaultFileset="true" />
<entry filesetId="2803" />
<symlink name="${compiler:JALVIEW_APPLICATION_NAME}.app/Contents/Resources/app/jre/Contents/Home/bin/${compiler:JALVIEW_NAME}" target="java" />
</topLevelFiles>
</macosArchive>
- <macosArchive name="macOS aarch64 Disk Image" id="2796" customizedId="MACOS-AARCH64-DMG" mediaFileName="${compiler:APPLICATION_FOLDER}-${compiler:JALVIEW_VERSION}-${compiler:sys.platform}-aarch64-java_${compiler:JAVA_INTEGER_VERSION}" volumeName="${compiler:INSTALLER_NAME}" architecture="aarch64" launcherId="737" setupAppId="2746">
+ <macosArchive name="macOS aarch64 (Apple Silicon) Disk Image" id="2796" customizedId="MACOS-AARCH64-DMG" mediaFileName="${compiler:APPLICATION_FOLDER}-${compiler:JALVIEW_VERSION}-${compiler:sys.platform}-aarch64-java_${compiler:JAVA_INTEGER_VERSION}" volumeName="${compiler:INSTALLER_NAME}" architecture="aarch64" launcherId="737" setupAppId="2746">
<exclude>
<entry defaultFileset="true" />
<entry filesetId="2801" />