diff --git a/.gitignore b/.gitignore
index 40f20e32..1b6985c0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,166 +1,5 @@
-#################
-## Eclipse
-#################
+# Ignore Gradle project-specific cache directory
+.gradle
-*.pydevproject
-.project
-.metadata
-bin/
-tmp/
-*.tmp
-*.bak
-*.swp
-*~.nib
-local.properties
-.classpath
-.settings/
-.loadpath
-
-# External tool builders
-.externalToolBuilders/
-
-# Locally stored "Eclipse launch configurations"
-*.launch
-
-# CDT-specific
-.cproject
-
-# PDT-specific
-.buildpath
-
-
-#################
-## Visual Studio
-#################
-
-## Ignore Visual Studio temporary files, build results, and
-## files generated by popular Visual Studio add-ons.
-
-# User-specific files
-*.suo
-*.user
-*.sln.docstates
-
-# Build results
-[Dd]ebug/
-[Rr]elease/
-*_i.c
-*_p.c
-*.ilk
-*.meta
-*.obj
-*.pch
-*.pdb
-*.pgc
-*.pgd
-*.rsp
-*.sbr
-*.tlb
-*.tli
-*.tlh
-*.tmp
-*.vspscc
-.builds
-*.dotCover
-
-## TODO: If you have NuGet Package Restore enabled, uncomment this
-#packages/
-
-# Visual C++ cache files
-ipch/
-*.aps
-*.ncb
-*.opensdf
-*.sdf
-
-# Visual Studio profiler
-*.psess
-*.vsp
-
-# ReSharper is a .NET coding add-in
-_ReSharper*
-
-# Installshield output folder
-[Ee]xpress
-
-# DocProject is a documentation generator add-in
-DocProject/buildhelp/
-DocProject/Help/*.HxT
-DocProject/Help/*.HxC
-DocProject/Help/*.hhc
-DocProject/Help/*.hhk
-DocProject/Help/*.hhp
-DocProject/Help/Html2
-DocProject/Help/html
-
-# Click-Once directory
-publish
-
-# Others
-[Bb]in
-[Oo]bj
-sql
-TestResults
-*.Cache
-ClientBin
-stylecop.*
-~$*
-*.dbmdl
-Generated_Code #added for RIA/Silverlight projects
-
-# Backup & report files from converting an old project file to a newer
-# Visual Studio version. Backup files are not needed, because we have git ;-)
-_UpgradeReport_Files/
-Backup*/
-UpgradeLog*.XML
-
-
-
-############
-## Windows
-############
-
-# Windows image file caches
-Thumbs.db
-
-# Folder config file
-Desktop.ini
-
-
-#############
-## Python
-#############
-
-*.py[co]
-
-# Packages
-*.egg
-*.egg-info
-dist
+# Ignore Gradle build output directory
build
-eggs
-parts
-bin
-var
-sdist
-develop-eggs
-.installed.cfg
-
-# Installer logs
-pip-log.txt
-
-# Unit test / coverage reports
-.coverage
-.tox
-
-#Translations
-*.mo
-
-#Mr Developer
-.mr.developer.cfg
-
-# Mac crap
-.DS_Store
-
-# svn
-.svn*
\ No newline at end of file
diff --git a/3rd-party-jars/JoSQL-2.2.jar b/3rd-party-jars/JoSQL-2.2.jar
deleted file mode 100644
index 08fcd6f5..00000000
Binary files a/3rd-party-jars/JoSQL-2.2.jar and /dev/null differ
diff --git a/3rd-party-jars/gentlyWEB-properties-1.2.jar b/3rd-party-jars/gentlyWEB-properties-1.2.jar
deleted file mode 100644
index 931b8d1f..00000000
Binary files a/3rd-party-jars/gentlyWEB-properties-1.2.jar and /dev/null differ
diff --git a/3rd-party-jars/gentlyweb-properties-3.jar b/3rd-party-jars/gentlyweb-properties-3.jar
new file mode 100644
index 00000000..65b21295
Binary files /dev/null and b/3rd-party-jars/gentlyweb-properties-3.jar differ
diff --git a/3rd-party-jars/josql-2.3.jar b/3rd-party-jars/josql-2.3.jar
new file mode 100644
index 00000000..416c8714
Binary files /dev/null and b/3rd-party-jars/josql-2.3.jar differ
diff --git a/build.gradle b/build.gradle
new file mode 100644
index 00000000..811c7454
--- /dev/null
+++ b/build.gradle
@@ -0,0 +1,265 @@
+/*
+ * This file was generated by the Gradle 'init' task.
+ *
+ * This generated file contains a sample Java project to get you started.
+ * For more details take a look at the Java Quickstart chapter in the Gradle
+ * User Manual available at https://docs.gradle.org/5.2.1/userguide/tutorial_java_projects.html
+ */
+
+plugins {
+ // Apply the java plugin to add support for Java
+ id 'java'
+
+ // Apply the application plugin to add support for building an application
+ id 'application'
+
+ //id 'org.openjfx.javafxplugin' version '0.0.9'
+}
+
+version '3.0.1'
+//version '3.0.0'
+
+sourceSets {
+ main {
+ }
+}
+/*
+javafx {
+ version = '12'
+ modules = [ 'javafx.swing', 'javafx.controls', 'javafx.media', 'javafx.web' ]
+ configuration = 'compileOnly'
+}
+*/
+repositories {
+ // Use jcenter for resolving your dependencies.
+ // You can declare any Maven/Ivy/file repository here.
+ //jcenter()
+ mavenCentral()
+
+ // Needed for the EPUB lib artifact.
+/*
+ maven {
+ url 'http://maven.openkm.com/'
+ }
+*/
+
+ maven {
+ //id 'psiegman-repo'
+ url 'https://github.com/psiegman/mvn-repo/raw/master/releases'
+ }
+
+ maven {
+ url 'https://oss.sonatype.org/content/repositories/snapshots/'
+ }
+
+}
+
+dependencies {
+
+ implementation fileTree('3rd-party-jars') {
+ //include 'jdom-1.0.jar'
+ //include 'jgoodies-forms-1.8.0.jar'
+ //include 'JoSQL-2.2.jar'
+ include 'josql-2.3.jar'
+ //include 'gentlyWEB-utils-1.1.jar'
+ //include 'gentlyWEB-xml-1.1.jar'
+ //include 'gentlyWEB-properties-1.2.jar'
+ //include 'gentlyWEB-logging-1.0.jar'
+ include 'gentlyweb-properties-3.jar'
+ include 'javadiff.jar'
+
+ // Spellchecker
+ include 'suggester-1.1.2.jar'
+
+ // TODO Investigate using maven?
+ include 'jazzy-core.jar'
+
+ include 'suggester-1.1.2.jar'
+ include 'GWordCram-0.1.jar'
+
+ // TODO Remove when no longer using Swing/AWT
+ include 'jcalendar-1.4.jar'
+
+ include 'h2mig_pagestore_addon.jar'
+
+ }
+
+ //compile 'org.jsoup:jsoup:1.11.3'
+ implementation 'org.jsoup:jsoup:1.11.3'
+
+ // Use JUnit test framework
+ testImplementation 'junit:junit:4.12'
+
+ // XML Parser
+ implementation 'pull-parser:pull-parser:2.1.10'
+
+ // Docx4J
+ implementation 'org.docx4j:docx4j-JAXB-ReferenceImpl:11.1.8'
+
+ // Bouncy castle crypto
+ implementation 'org.bouncycastle:bcprov-jdk15on:1.62'
+ implementation 'org.bouncycastle:bcpg-jdk15on:1.62'
+
+ // TODO This is probably not needed now since we can scale images via JavaFX.
+ implementation 'org.imgscalr:imgscalr-lib:4.2'
+
+ // DBCP implementation (Apache)
+ implementation 'org.apache.commons:commons-dbcp2:2.6.0'
+
+ // Apache Commons IO
+ implementation 'commons-io:commons-io:2.11.0'
+
+ // H2 DB
+ implementation 'com.h2database:h2:1.3.175'
+
+ // EPUB lib
+ implementation 'nl.siegmann.epublib:epublib-core:3.1'
+
+ // POI hwpf (.doc file reading)
+ //implementation 'org.apache.poi:poi-scratchpad:4.1.0'
+
+ // JFreeChart
+ implementation 'org.jfree:jfreechart:1.5.0'
+
+ // JFreeChart-FX
+ implementation 'org.jfree:jfreechart-fx:1.0.1'
+
+ // Smack
+ implementation 'org.igniterealtime.smack:smack-core:4.4.4'
+ implementation 'org.igniterealtime.smack:smack-extensions:4.4.4'
+ implementation 'org.igniterealtime.smack:smack-tcp:4.4.4'
+ implementation 'org.igniterealtime.smack:smack-im:4.4.4'
+ implementation 'org.igniterealtime.smack:smack-java8:4.4.4'
+
+ // RichtextFX
+ implementation 'org.fxmisc.richtext:richtextfx:0.11.0'
+ //implementation 'org.fxmisc.richtext:richtextfx:0.10.9'
+ //implementation 'org.fxmisc.richtext:richtextfx:1.0.0-SNAPSHOT'
+
+ // This is temporary for testing changes to a local version of richtextfx. Ignore.
+ // TEMP ADD RICHTEXTFX JARS AND DEPS
+/*
+ implementation fileTree('d:/reference/java/afester-richtextfx/RichTextFX/richtextfx/build/libs/') {
+ //include 'richtextfx-1.0.0-SNAPSHOT.jar'
+ include 'richtextfx-0.10.8-rc1.jar'
+ include 'flowless-0.6.7.jar'
+ include 'reactfx-2.0-M5.jar'
+ include 'undofx-2.1.1.jar'
+ include 'wellbehavedfx-0.3.3.jar'
+ }
+*/
+ // Flying Saucer (can be removed when no longer using Swing)
+ implementation 'org.xhtmlrenderer:flying-saucer-core:9.1.18'
+
+ // JGoodies (remove when no longer using Swing)
+ implementation 'com.jgoodies:jgoodies-looks:2.7.0'
+ implementation 'com.jgoodies:jgoodies-forms:1.9.0'
+
+ // AnimateFX (test)
+ //implementation 'io.github.typhon0:AnimateFX:1.2.1'
+
+ // SVG support
+ //implementation 'de.codecentric.centerdevice:javafxsvg:1.3.0'
+
+ // PDF support
+ //implementation 'org.apache.pdfbox:pdfbox:2.0.20'
+
+ // DOM4J
+ implementation 'org.dom4j:dom4j:2.1.3'
+
+}
+
+compileJava {
+
+ options.incremental = true
+
+ options.compilerArgs =
+ [
+ '--add-modules',
+ 'java.base,javafx.swing,javafx.controls,javafx.media,javafx.web,java.instrument,jdk.attach',
+ '--add-exports',
+ 'javafx.graphics/com.sun.javafx.iio=ALL-UNNAMED',
+ '--add-exports',
+ 'javafx.graphics/com.sun.javafx.iio.common=ALL-UNNAMED',
+ '--add-exports',
+ 'javafx.web/com.sun.javafx.webkit=ALL-UNNAMED',
+ '--add-exports',
+ 'javafx.web/com.sun.webkit=ALL-UNNAMED',
+ '--module-path',
+ // This is a property that should be defined (usually) in gradle.prpoerties, i.e. module_path=/usr/share/lib/javafx-sdk-12/lib
+ module_path,
+ '-Xmaxerrs',
+ '1000'
+ ]
+}
+
+jar {
+ doFirst {
+ file("${sourceSets.main.output.resourcesDir}/data/version.txt").text = "$version"
+ }
+}
+
+javadoc {
+ doFirst {
+ options.addStringOption ('-module-path', module_path)
+ options.addStringOption ('-add-modules', 'javafx.controls,javafx.swing,javafx.media,javafx.web,java.instrument,jdk.attach')
+ }
+}
+
+application {
+ applicationDefaultJvmArgs =
+ [
+ '-Djava.locale.providers=COMPAT',
+ '--module-path',
+ // This is a property that should be defined (usually) in gradle.prpoerties, i.e. module_path=/usr/share/lib/javafx-sdk-12/lib
+ module_path,
+ '--add-modules=javafx.controls,javafx.swing,javafx.media,javafx.web,java.instrument,jdk.attach',
+ '--add-exports',
+ 'javafx.graphics/com.sun.javafx.iio=ALL-UNNAMED',
+ '--add-exports',
+ 'javafx.graphics/com.sun.javafx.iio.common=ALL-UNNAMED',
+ '--add-exports',
+ 'javafx.graphics/com.sun.javafx.scene.text=ALL-UNNAMED',
+ '--add-exports',
+ 'javafx.graphics/com.sun.javafx.geom=ALL-UNNAMED',
+ '--add-opens',
+ 'javafx.graphics/javafx.scene.text=ALL-UNNAMED',
+ '--add-opens',
+ 'javafx.graphics/com.sun.javafx.text=ALL-UNNAMED',
+ '--add-exports',
+ 'javafx.graphics/com.sun.javafx.geom=ALL-UNNAMED',
+ '--add-exports',
+ 'javafx.graphics/com.sun.javafx.scene.text=ALL-UNNAMED',
+ '--add-exports',
+ 'javafx.graphics/com.sun.javafx.tk=ALL-UNNAMED',
+ '--add-exports',
+ 'javafx.web/com.sun.javafx.webkit=ALL-UNNAMED',
+ '--add-exports',
+ 'javafx.web/com.sun.webkit=ALL-UNNAMED'
+ ]
+
+ // Define the main class for the application
+ mainClassName 'com.quollwriter.Startup'
+
+}
+
+run {
+ dependsOn jar
+}
+
+task copyToLib(type: Copy) {
+ delete "$buildDir/libs"
+ into "$buildDir/libs"
+ from configurations.runtimeClasspath
+}
+
+configurations.all {
+ resolutionStrategy {
+ //failOnVersionConflict()
+ // This is to try and fix some of the dependency conflicts between siegmann and dom4j.
+ force 'commons-codec:commons-codec:1.15',
+ 'commons-io:commons-io:2.11.0',
+ 'org.slf4j:slf4j-api:1.8.0-beta4',
+ 'pull-parser:pull-parser:2.1.10'
+ }
+}
diff --git a/build.xml b/build.xml
deleted file mode 100644
index 44359b6a..00000000
--- a/build.xml
+++ /dev/null
@@ -1,581 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- ${currVersion}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/data/project-info-schema-version.txt b/data/project-info-schema-version.txt
deleted file mode 100644
index e440e5c8..00000000
--- a/data/project-info-schema-version.txt
+++ /dev/null
@@ -1 +0,0 @@
-3
\ No newline at end of file
diff --git a/data/prompts/5148672f441b.txt b/data/prompts/5148672f441b.txt
deleted file mode 100644
index ae081571..00000000
--- a/data/prompts/5148672f441b.txt
+++ /dev/null
@@ -1 +0,0 @@
-Louisa M. AlcottA Garland for Girlshttp://www.gutenberg.org/dirs/etext04/grlnd11.txtMuch is not expected of a girl of eighteen, I know; but oh! there were heaps of kind little things I MIGHT have done if I hadn't thought only of myself.
\ No newline at end of file
diff --git a/data/prompts/e4671c821dcc.txt b/data/prompts/e4671c821dcc.txt
deleted file mode 100644
index b969abe9..00000000
--- a/data/prompts/e4671c821dcc.txt
+++ /dev/null
@@ -1 +0,0 @@
-L. Frank BaumDorothy and the Wizard of Ozhttp://www.gutenberg.org/files/420/420-h/420-h.htmThe buggy seemed almost new, for it had a shiny top and side curtains. Getting around in front, so that she could look inside, the girl saw a boy curled up on the seat, fast asleep.
\ No newline at end of file
diff --git a/data/version.txt b/data/version.txt
deleted file mode 100644
index d5724cd4..00000000
--- a/data/version.txt
+++ /dev/null
@@ -1 +0,0 @@
-2.6.2
\ No newline at end of file
diff --git a/settings.gradle b/settings.gradle
new file mode 100644
index 00000000..9634be09
--- /dev/null
+++ b/settings.gradle
@@ -0,0 +1,10 @@
+/*
+ * This file was generated by the Gradle 'init' task.
+ *
+ * The settings file is used to specify which projects to include in your build.
+ *
+ * Detailed information about configuring a multi-project build in Gradle can be found
+ * in the user manual at https://docs.gradle.org/5.2.1/userguide/multi_project_builds.html
+ */
+
+rootProject.name = 'QuollWriter'
diff --git a/src/com/quollwriter/ByteArrayDataSource.java b/src/com/quollwriter/ByteArrayDataSource.java
deleted file mode 100644
index 57d4a643..00000000
--- a/src/com/quollwriter/ByteArrayDataSource.java
+++ /dev/null
@@ -1,49 +0,0 @@
-package com.quollwriter;
-
-import java.io.*;
-
-import javax.activation.*;
-
-public class ByteArrayDataSource implements DataSource
-{
-
- private byte[] bytes = null;
-
- public ByteArrayDataSource (byte[] bytes)
- {
-
- this.bytes = bytes;
-
- }
-
- public InputStream getInputStream ()
- throws IOException
- {
-
- return new ByteArrayInputStream (this.bytes);
-
- }
-
- public OutputStream getOutputStream ()
- throws IOException
- {
-
- throw new UnsupportedOperationException ("Write is not supported.");
-
- }
-
- public String getName ()
- {
-
- return null;
-
- }
-
- public String getContentType ()
- {
-
- return "application/octet-stream";
-
- }
-
-}
\ No newline at end of file
diff --git a/src/com/quollwriter/DictionaryProvider.java b/src/com/quollwriter/DictionaryProvider.java
deleted file mode 100644
index f8a88f7e..00000000
--- a/src/com/quollwriter/DictionaryProvider.java
+++ /dev/null
@@ -1,556 +0,0 @@
-package com.quollwriter;
-
-import java.io.*;
-
-import java.util.*;
-
-import com.quollwriter.ui.events.*;
-
-import com.quollwriter.ui.components.*;
-import com.quollwriter.text.*;
-
-import com.softcorporation.suggester.util.Constants;
-import com.softcorporation.suggester.util.SpellCheckConfiguration;
-import com.softcorporation.suggester.Suggestion;
-import com.softcorporation.suggester.dictionary.BasicDictionary;
-import com.softcorporation.suggester.BasicSuggester;
-
-public class DictionaryProvider
-{
-
- private List listeners = new ArrayList ();
- //private List dicts = new ArrayList ();
- private QWSpellDictionaryHashMap projDict = null;
- private SpellChecker checker = null;
- private com.swabunga.spell.event.SpellChecker projectSpellChecker = null;
-
- private static File userDictFile = null;
- private static QWSpellDictionaryHashMap userDict = null;
- private static com.swabunga.spell.event.SpellChecker userSpellChecker = null;
- private String language = null;
-
- public DictionaryProvider (String lang,
- List projWords)
- throws Exception
- {
-
- this.language = lang;
-
- File dictFile = Environment.getDictionaryFile (lang);
-
- if (!dictFile.exists ())
- {
-
- throw new GeneralException ("Unable to find dictionary file: " +
- dictFile);
-
- }
-
- BasicDictionary dict = new BasicDictionary ("file://" + dictFile.getPath ());
-
- SpellCheckConfiguration config = new SpellCheckConfiguration ("/com/softcorporation/suggester/spellCheck.config");
-
- final BasicSuggester suggester = new BasicSuggester (config);
- suggester.attach (dict);
-
- final DictionaryProvider _this = this;
-
- this.checker = new SpellChecker ()
- {
-
- public synchronized boolean isCorrect (Word word)
- {
-
- if (word.isPunctuation ())
- {
-
- return true;
-
- }
-
- String w = word.getText ();
-
- // See if the word is a number.
- try
- {
-
- Double.parseDouble (w);
-
- return true;
-
- } catch (Exception e) {
-
- // Not a number.
-
- }
-
- if (this.isIgnored (word))
- {
-
- return true;
-
- }
-
- try
- {
-
- if (_this.projectSpellChecker.isCorrect (w))
- {
-
- return true;
-
- }
-
- if (DictionaryProvider.userSpellChecker.isCorrect (w))
- {
-
- return true;
-
- }
-
- if (suggester.hasExactWord (w))
- {
-
- return true;
-
- }
-
- int result = suggester.hasWord (w);
- if (result == Constants.RESULT_ID_MATCH ||
- result == Constants.RESULT_ID_MATCH_EXACT)
- {
- return true;
- }
-
- }catch (Exception e) {
-
- Environment.logError ("Unable to check word: " +
- word,
- e);
-
- }
-
- return false;
-
- }
-
- public synchronized boolean isIgnored (Word word)
- {
-
- return false;
-
- }
-
- public synchronized List getSuggestions (Word word)
- {
-
- List ret = new ArrayList ();
-
- if (word == null)
- {
-
- return null;
-
- }
-
- if (this.isCorrect (word))
- {
-
- return null;
-
- }
-
- String wt = word.getText ();
-
- List suggestions = null;
-
- List jsuggestions = _this.projectSpellChecker.getSuggestions (wt,
- 1);
-
- if (jsuggestions != null)
- {
-
- for (int i = 0; i < jsuggestions.size (); i++)
- {
-
- ret.add (((com.swabunga.spell.engine.Word) jsuggestions.get (i)).getWord ());
-
- }
-
- }
-
- jsuggestions = DictionaryProvider.userSpellChecker.getSuggestions (wt,
- 1);
-
- if (jsuggestions != null)
- {
-
- for (int i = 0; i < jsuggestions.size (); i++)
- {
-
- ret.add (((com.swabunga.spell.engine.Word) jsuggestions.get (i)).getWord ());
-
- }
-
- }
-
- try
- {
-
- suggestions = suggester.getSuggestions (wt, 20);
-
- } catch (Exception e) {
-
- e.printStackTrace ();
-
- }
-
- if (suggestions != null)
- {
-
- for (int i = 0; i < suggestions.size (); i++)
- {
-
- Suggestion s = (Suggestion) suggestions.get (i);
-
- ret.add (s.word);
-
- }
-
- }
-
- if (Character.isUpperCase (wt.charAt (0)))
- {
-
- for (int i = 0; i < ret.size (); i++)
- {
-
- String w = ret.get (i);
-
- ret.set (i,
- Character.toUpperCase (w.charAt (0)) + w.substring (1));
-
- }
-
- }
-
- return ret;
-
- }
-
- };
-
- this.projectSpellChecker = new com.swabunga.spell.event.SpellChecker ();
-
- if (projWords != null)
- {
-
- StringBuilder b = new StringBuilder ();
-
- for (String i : projWords)
- {
-
- b.append (i);
- b.append ('\n');
-
- }
-
- this.projDict = new QWSpellDictionaryHashMap (new StringReader (b.toString ()));
-
- this.projectSpellChecker.addDictionary (this.projDict);
-
- //this.dicts.add (this.projDict);
-
- }
-
- if (DictionaryProvider.userDict == null)
- {
-
- File userDictFile = Environment.getUserDictionaryFile ();
-
- if (!userDictFile.exists ())
- {
-
- userDictFile.createNewFile ();
-
- }
-
- DictionaryProvider.userDict = new QWSpellDictionaryHashMap (userDictFile);
-
- DictionaryProvider.userDictFile = userDictFile;
-
- DictionaryProvider.userSpellChecker = new com.swabunga.spell.event.SpellChecker ();
-
- DictionaryProvider.userSpellChecker.setUserDictionary (DictionaryProvider.userDict);
-
- }
-
- }
-
- public String getLanguage ()
- {
-
- return this.language;
-
- }
-
- public static boolean isLanguageInstalled (String lang)
- {
-
- File f = Environment.getDictionaryFile (lang);
-
- if ((f != null)
- &&
- (f.exists ())
- )
- {
-
- return true;
-
- }
-
- return false;
-
- }
-
- /**
- * Checks to see if the directory is an indexed dictionary directory which means:
- * - It contains a db directory
- * - It contains a words directory
- * - It contains a contents file
- *
- * @param dir The directory to check.
- * @return If the checks pass.
- */
- private boolean isIndexedDictionaryDirectory (File dir)
- {
-
- if (!dir.exists ())
- {
-
- return false;
-
- }
-
- File dbDir = new File (dir, "db");
-
- if ((!dbDir.exists ())
- ||
- (dbDir.isFile ())
- )
- {
-
- return false;
-
- }
-
- File wordsDir = new File (dir, "words");
-
- if ((!wordsDir.exists ())
- ||
- (wordsDir.isFile ())
- )
- {
-
- return false;
-
- }
-
- return true;
-
- }
-
- public void addDictionaryChangedListener (DictionaryChangedListener l)
- {
-
- if (this.listeners.contains (l))
- {
-
- return;
-
- }
-
- this.listeners.add (l);
-
- }
-
- public void removeDictionaryChangedListener (DictionaryChangedListener l)
- {
-
- this.listeners.remove (l);
-
- }
-
- protected void fireDictionaryEvent (DictionaryChangedEvent ev)
- {
-
- for (int i = 0; i < this.listeners.size (); i++)
- {
-
- DictionaryChangedListener dcl = (DictionaryChangedListener) this.listeners.get (i);
-
- dcl.dictionaryChanged (ev);
-
- }
-
- }
-
- public SpellChecker getSpellChecker ()
- {
-
- return this.checker;
-
- }
-
- public static void addUserWord (String word)
- {
-
- if (!DictionaryProvider.userDict.isCorrect (word))
- {
-
- DictionaryProvider.userDict.addWord (word);
-/*
- this.fireDictionaryEvent (new DictionaryChangedEvent (this,
- DictionaryChangedEvent.WORD_ADDED,
- word));
-*/
- }
-
- }
-
- public static void removeUserWord (String word)
- {
-
- if (DictionaryProvider.userDict != null)
- {
-
- DictionaryProvider.userDict.removeWord (word);
-
- try
- {
-
- DictionaryProvider.userDict.saveDictionaryToFile (DictionaryProvider.userDictFile);
-
- } catch (Exception e)
- {
-
- Environment.logError ("Unable to save user dictionary file",
- e);
-
- }
-
- /*
- this.fireDictionaryEvent (new DictionaryChangedEvent (this,
- DictionaryChangedEvent.WORD_REMOVED,
- word));
-*/
- }
-
- }
-
- public void removeWord (String word,
- String type)
- {
-
- if (type.equals ("project"))
- {
-
- if (this.projDict != null)
- {
-
- this.projDict.removeWord (word);
-
- this.fireDictionaryEvent (new DictionaryChangedEvent (this,
- DictionaryChangedEvent.WORD_REMOVED,
- word));
-
- }
-
- }
-
- if (type.equals ("user"))
- {
-
- if (DictionaryProvider.userDict != null)
- {
-
- DictionaryProvider.userDict.removeWord (word);
-
- try
- {
-
- DictionaryProvider.userDict.saveDictionaryToFile (DictionaryProvider.userDictFile);
-
- } catch (Exception e)
- {
-
- Environment.logError ("Unable to save user dictionary file",
- e);
-
- }
-
- this.fireDictionaryEvent (new DictionaryChangedEvent (this,
- DictionaryChangedEvent.WORD_REMOVED,
- word));
-
- }
-
- }
-
- }
-
- public void addWord (String word,
- String type)
- {
-
- if (type.equals ("project"))
- {
-
- if (this.projDict == null)
- {
-
- try
- {
-
- this.projDict = new QWSpellDictionaryHashMap (new StringReader (""));
-
- } catch (Exception e)
- {
-
- Environment.logError ("Unable to create project dictionary for word: " +
- word,
- e);
-
- return;
-
- }
-
- }
-
- this.projDict.addWord (word);
-
- this.fireDictionaryEvent (new DictionaryChangedEvent (this,
- DictionaryChangedEvent.WORD_ADDED,
- word));
-
- }
-
- if (type.equals ("user"))
- {
-
- if (!DictionaryProvider.userDict.isCorrect (word))
- {
-
- DictionaryProvider.userDict.addWord (word);
-
- this.fireDictionaryEvent (new DictionaryChangedEvent (this,
- DictionaryChangedEvent.WORD_ADDED,
- word));
-
- }
-
- }
-
- }
-
-}
diff --git a/src/com/quollwriter/Environment.java b/src/com/quollwriter/Environment.java
deleted file mode 100644
index 2396748e..00000000
--- a/src/com/quollwriter/Environment.java
+++ /dev/null
@@ -1,8211 +0,0 @@
-package com.quollwriter;
-
-import java.awt.Color;
-import java.awt.Component;
-import java.awt.Dimension;
-import java.awt.Image;
-import java.awt.Insets;
-import java.awt.Font;
-import java.awt.KeyboardFocusManager;
-import java.awt.image.*;
-import java.awt.event.*;
-
-import java.nio.channels.*;
-
-import java.beans.*;
-
-import java.io.*;
-import java.nio.charset.*;
-
-import java.net.*;
-
-import java.security.*;
-
-import java.text.*;
-
-import java.util.*;
-import java.util.jar.*;
-import java.util.logging.*;
-import java.util.prefs.*;
-import java.util.concurrent.*;
-
-import javax.swing.*;
-import javax.swing.border.*;
-import javax.swing.plaf.*;
-
-import javax.imageio.*;
-
-import javax.sound.sampled.*;
-
-import com.gentlyweb.logging.Logger;
-
-import com.gentlyweb.properties.*;
-
-import com.gentlyweb.utils.*;
-
-import com.gentlyweb.xml.*;
-
-import com.jgoodies.looks.*;
-import com.jgoodies.looks.windows.*;
-
-import com.quollwriter.data.*;
-import com.quollwriter.editors.*;
-import com.quollwriter.data.editors.*;
-import com.quollwriter.data.comparators.*;
-
-import com.quollwriter.text.*;
-
-import com.quollwriter.events.*;
-
-import com.quollwriter.importer.*;
-
-import com.quollwriter.synonyms.*;
-
-import com.quollwriter.text.rules.*;
-
-import com.quollwriter.db.*;
-
-import com.quollwriter.ui.*;
-import com.quollwriter.ui.components.ActionAdapter;
-import com.quollwriter.ui.components.GradientPanel;
-import com.quollwriter.ui.components.Header;
-import com.quollwriter.ui.components.IconProvider;
-import com.quollwriter.ui.components.Runner;
-
-import com.quollwriter.achievements.*;
-import com.quollwriter.achievements.rules.*;
-
-import com.quollwriter.editors.ui.*;
-
-import static com.quollwriter.LanguageStrings.*;
-
-import org.jdom.*;
-
-public class Environment
-{
-
- public static String GZIP_EXTENSION = ".gz";
-
- private static Landing landingViewer = null;
- private static Map openProjects = new HashMap<> ();
- private static Set openViewers = new HashSet<> ();
-
- public static Map defaultObjectProperties = new HashMap ();
-
- //public static com.gentlyweb.properties.Properties userProperties = new com.gentlyweb.properties.Properties ();
- public static PrintStream out = null;
-
- private static Logger generalLog = null;
- private static Logger errorLog = null;
- private static Logger sqlLog = null;
-
- // Get rid of this value once bug reporting is via the web.
- public static boolean seenReportBugMessage = false;
-
- private static Version appVersion = null;
- //private static String appVersion = null;
- //private static boolean betaVersion = false;
- private static int schemaVersion = 0;
- private static int projectInfoSchemaVersion = 0;
-
- private static SimpleDateFormat dateFormatter = null;
- private static SimpleDateFormat timeFormatter = null;
-
- private static boolean debugMode = false;
- private static boolean doneVersionCheck = false;
- public static boolean isWindows = false;
- public static boolean isMac = false;
- public static boolean isLinux = false;
- private static boolean isFirstUse = false;
-
- private static List installJarFilesToDelete = new ArrayList ();
-
- private static Map userPropertyHandlers = new HashMap ();
-
- private static DecimalFormat numFormat = new DecimalFormat ("###,###");
- private static DecimalFormat floatNumFormat = new DecimalFormat ("###,###.#");
-
- private static Map backgroundImages = new HashMap ();
-
- private static AchievementsManager achievementsManager = null;
-
- private static Map objectTypeNamesSingular = new HashMap ();
- private static Map objectTypeNamesPlural = new HashMap ();
-
- private static Map synonymProviders = new WeakHashMap ();
- //private static DictionaryProvider defaultDictProv = null;
-
- private static List startupProgressListeners = new ArrayList ();
- private static int startupProgress = 0;
-
- private static FileLock lock = null;
-
- private static ProjectInfoObjectManager projectInfoManager = null;
-
- private static Map projectInfoChangedListeners = null;
-
- private static Map userProjectEventListeners = null;
-
- // Just used in the maps above as a placeholder for the listeners.
- private static final Object listenerFillObj = new Object ();
-
- private static boolean playSoundOnKeyStroke = false;
- private static Clip keyStrokeSound = null;
-
- private static UserSession userSession = null;
- private static TargetsData targets = null;
-
- private static ScheduledThreadPoolExecutor generalTimer = null;
-
- private static ProjectTextProperties projectTextProps = null;
- private static FullScreenTextProperties fullScreenTextProps = null;
-
- private static List doOnShutdown = new ArrayList ();
-
- private static Set userConfigObjTypes = new HashSet ();
-
- private static PropertyChangedListener userConfigurableObjectTypeNameListener = null;
-
- private static Set tags = null;
-
- private static LanguageStrings uiLanguageStrings = null;
- private static LanguageStrings defaultUILanguageStrings = null;
-
- static
- {
-
- // We use a synchronized weak hash map here so that we don't have to worry about all the
- // references since they will be transient compared to the potential length of the service
- // running.
-
- // Where possible listeners should de-register as normal but this just ensure that objects
- // that don't have a controlled pre-defined lifecycle (as opposed say to AbstractSideBar)
- // won't leak.
- Environment.projectInfoChangedListeners = Collections.synchronizedMap (new WeakHashMap ());
-
- Environment.userProjectEventListeners = Collections.synchronizedMap (new WeakHashMap ());
-
- try
- {
-
- // Put a wrapper around System.out to ensure that non ascii characters show up correctly when debugging.
- Environment.out = new java.io.PrintStream (System.out, true, "utf-8");
-
- } catch (Exception e) {
-
- Environment.out = System.out;
-
- }
-
- }
-
- public class XMLConstants
- {
-
- public static final String projects = "projects";
- public static final String type = "type";
- public static final String name = "name";
- public static final String object = "object";
- public static final String singular = "singular";
- public static final String plural = "plural";
- public static final String file = "file";
- public static final String files = "files";
- public static final String stats = "stats";
- public static final String stat = "stat";
- public static final String id = "id";
-
- }
-
- public static void fireProjectInfoChangedEvent (final ProjectInfo proj,
- final String changeType)
- {
-
- UIUtils.doActionLater (new ActionListener ()
- {
-
- public void actionPerformed (ActionEvent aev)
- {
-
- ProjectInfoChangedEvent ev = new ProjectInfoChangedEvent (proj,
- changeType);
-
- Set ls = null;
-
- // Get a copy of the current valid listeners.
- synchronized (Environment.projectInfoChangedListeners)
- {
-
- ls = new LinkedHashSet (Environment.projectInfoChangedListeners.keySet ());
-
- }
-
- for (ProjectInfoChangedListener l : ls)
- {
-
- l.projectInfoChanged (ev);
-
- }
-
- }
-
- });
-
- }
-
- public static void unregisterViewer (AbstractViewer v,
- ActionListener afterUnregister)
- {
-
- Environment.openViewers.remove (v);
-
- if (v == Environment.landingViewer)
- {
-
- Environment.landingViewer = null;
-
- }
-
- if (afterUnregister != null)
- {
-
- UIUtils.doLater (afterUnregister);
-
- return;
-
- }
-
- if (Environment.openViewers.size () == 0)
- {
-
- Environment.closeDown ();
-
- }
-
- }
-
- public static void registerViewer (AbstractViewer v)
- {
-
- Environment.openViewers.add (v);
-
- }
-
- public static void removeProjectInfoChangedListener (ProjectInfoChangedListener l)
- {
-
- Environment.projectInfoChangedListeners.remove (l);
-
- }
-
- public static void addProjectInfoChangedListener (ProjectInfoChangedListener l)
- {
-
- Environment.projectInfoChangedListeners.put (l,
- Environment.listenerFillObj);
-
- }
-
- public static void addStartupProgressListener (PropertyChangedListener l)
- {
-
- Environment.startupProgressListeners.add (l);
-
- }
-
- private static void fireStartupProgressEvent ()
- {
-
- PropertyChangedEvent ev = new PropertyChangedEvent (new Object (),
- "progress",
- 0,
- Environment.startupProgress);
-
- for (PropertyChangedListener l : Environment.startupProgressListeners)
- {
-
- l.propertyChanged (ev);
-
- }
-
- }
-
- public static void incrStartupProgress ()
- {
-
- if (Environment.isStartupComplete ())
- {
-
- return;
-
- }
-
- Environment.startupProgress += 9;
-
- Environment.fireStartupProgressEvent ();
-
- }
-
- public static void startupComplete ()
- {
-
- if (Environment.isStartupComplete ())
- {
-
- return;
-
- }
-
- Environment.startupProgress = 100;
-
- Environment.fireStartupProgressEvent ();
-
- }
-
- public static boolean isStartupComplete ()
- {
-
- return Environment.startupProgress == 100;
-
- }
-
- public static boolean isDistractionFreeModeEnabled ()
- {
-
- for (AbstractProjectViewer pv : Environment.openProjects.values ())
- {
-
- if (pv.isDistractionFreeModeEnabled ())
- {
-
- return true;
-
- }
-
- }
-
- return false;
-
- }
-
- public static AbstractViewer getFocusedViewer ()
- {
-
- if (Environment.landingViewer != null)
- {
-
- if (Environment.landingViewer.isFocused ())
- {
-
- return Environment.landingViewer;
-
- }
-
- }
-
- if (Environment.openViewers.size () == 0)
- {
-
- return null;
-
- }
-
- for (AbstractViewer viewer : Environment.openViewers)
- {
-
- if (viewer.isFocused ())
- {
-
- return viewer;
-
- }
-
- }
-
- // Return the first viewer that is showing.
- for (AbstractViewer viewer : Environment.openViewers)
- {
-
- if (viewer.isShowing ())
- {
-
- return viewer;
-
- }
-
- }
-
- // What the derp... Return the first.
- return Environment.openViewers.iterator ().next ();
-
- }
-
- public static String getUrlFileAsString (URL url)
- throws Exception
- {
-
- URLConnection c = url.openConnection ();
-
- InputStream bin = c.getInputStream ();
-
- return Utils.getStreamAsString (bin,
- StandardCharsets.UTF_8);
-
- }
-
- public static AbstractProjectViewer getProjectViewer (ProjectInfo p)
- {
-
- return Environment.openProjects.get (p);
-
- }
-
- public static AbstractProjectViewer getProjectViewer (Project p)
- {
-
- return Environment.openProjects.get (Environment.getProjectInfo (p));
-
- }
-
- public static void removeSideBarFromAllProjectViewers (String id)
- {
-
- for (AbstractProjectViewer pv : Environment.openProjects.values ())
- {
-
- pv.removeSideBar (pv.getSideBar (id));
-
- }
-
- }
-
- public static Book createTestBook ()
- throws Exception
- {
-
- Element root = JDOMUtils.getStringAsElement (Environment.getResourceFileAsString (Constants.TEST_BOOK_FILE));
-
- String name = JDOMUtils.getAttributeValue (root,
- XMLConstants.name);
-
- Book b = new Book ();
-
- b.setName (name);
-
- List chEls = JDOMUtils.getChildElements (root,
- Chapter.OBJECT_TYPE,
- false);
-
- for (int i = 0; i < chEls.size (); i++)
- {
-
- Element el = (Element) chEls.get (i);
-
- name = JDOMUtils.getAttributeValue (el,
- XMLConstants.name);
-
- Chapter ch = new Chapter ();
- ch.setName (name);
-
- String text = JDOMUtils.getChildContent (el);
-
- ch.setText (new StringWithMarkup (text));
-
- b.addChapter (ch);
-
- }
-
- return b;
-
- }
-
- public static boolean areDifferent (Comparable o,
- Comparable n)
- {
-
- if ((o == null) &&
- (n == null))
- {
-
- return false;
-
- }
-
- if ((o != null) &&
- (n == null))
- {
-
- return true;
-
- }
-
- if ((o == null) &&
- (n != null))
- {
-
- return true;
-
- }
-
- return o.compareTo (n) != 0;
-
- }
-
- public static void addInstallJarToDelete (File oldFile,
- File newFile)
- {
-
- Environment.installJarFilesToDelete.add (oldFile);
-
- }
-
- public static Date zeroTimeFieldsForDate (Date d)
- {
-
- GregorianCalendar gc = new GregorianCalendar ();
- gc.setTime (d);
-
- Environment.zeroTimeFields (gc);
-
- return gc.getTime ();
-
- }
-
- public static void zeroTimeFields (GregorianCalendar gc)
- {
-
- // Zero-out the non date fields.
- gc.set (Calendar.HOUR_OF_DAY,
- 0);
- gc.set (Calendar.MINUTE,
- 0);
- gc.set (Calendar.SECOND,
- 0);
- gc.set (Calendar.MILLISECOND,
- 0);
-
- }
-
- public static void updateUserObjectTypeNames (Map singular,
- Map plural)
- throws Exception
- {
-
- //Map newSingular = new HashMap ();
- //newSingular.putAll (Environment.objectTypeNamesSingular);
-
- //newSingular.putAll (singular);
-
- //Map newPlural = new HashMap ();
- //newPlural.putAll (Environment.objectTypeNamesPlural);
-
- //newPlural.putAll (plural);
-
- UserConfigurableObjectType type = Environment.getUserConfigurableObjectType (Chapter.OBJECT_TYPE);
-
- // TODO: Fix this nonsense...
- if (singular.containsKey (Chapter.OBJECT_TYPE))
- {
-
- type.setObjectTypeName (singular.get (Chapter.OBJECT_TYPE));
-
- }
-
- if (plural.containsKey (Chapter.OBJECT_TYPE))
- {
-
- type.setObjectTypeNamePlural (plural.get (Chapter.OBJECT_TYPE));
-
- }
-
- Environment.updateUserConfigurableObjectType (type);
-
- Environment.setUserObjectTypeNames (singular,
- plural);
-
-
- }
-
- public static void setUserObjectTypeNames (Map singular,
- Map plural)
- throws Exception
- {
-
- Map> t = new HashMap ();
-
- t.put (LanguageStrings.singular,
- singular);
- t.put (LanguageStrings.plural,
- plural);
-
- IOUtils.writeStringToFile (Environment.getUserObjectTypeNamesFile (),
- JSONEncoder.encode (t),
- false);
-
- Environment.loadUserObjectTypeNames ();
-
- /*
- Element root = new Element ("object-names");
-
- Map els = new HashMap ();
-
- for (String ot : singular.keySet ())
- {
-
- ot = ot.toLowerCase ();
-
- String s = singular.get (ot);
-
- Element el = els.get (ot);
-
- if (el == null)
- {
-
- el = new Element (XMLConstants.object);
-
- el.setAttribute (XMLConstants.type,
- ot);
-
- els.put (ot,
- el);
-
- root.addContent (el);
-
- }
-
- Element sel = new Element (XMLConstants.singular);
-
- CDATA cd = new CDATA (s);
-
- sel.addContent (cd);
-
- el.addContent (sel);
-
- }
-
- for (String ot : plural.keySet ())
- {
-
- ot = ot.toLowerCase ();
-
- String p = plural.get (ot);
-
- Element el = els.get (ot);
-
- if (el == null)
- {
-
- el = new Element (XMLConstants.object);
-
- el.setAttribute (XMLConstants.type,
- ot);
-
- els.put (ot,
- el);
-
- root.addContent (el);
-
- }
-
- Element pel = new Element (XMLConstants.plural);
-
- CDATA cd = new CDATA (p);
-
- pel.addContent (cd);
-
- el.addContent (pel);
-
- }
-
- JDOMUtils.writeElementToFile (root,
- Environment.getUserObjectTypeNamesFile (),
- true);
-
- // Now force a reload.
- Environment.loadObjectTypeNames (root);
-*/
- }
-
- public static Map getObjectTypeNamePlurals ()
- {
-
- return new HashMap (Environment.objectTypeNamesPlural);
-
- }
-
- public static Map getObjectTypeNames ()
- {
-
- return new HashMap (Environment.objectTypeNamesSingular);
-
- }
-
- public static String getObjectTypeName (DataObject t)
- {
-
- if (t == null)
- {
-
- return null;
-
- }
-
- if (t instanceof UserConfigurableObject)
- {
-
- UserConfigurableObject ut = (UserConfigurableObject) t;
-
- return ut.getObjectTypeName ();
-
- }
-
- if (t instanceof Note)
- {
-
- Note n = (Note) t;
-
- if (n.isEditNeeded ())
- {
-
- return Environment.getObjectTypeName ("editneeded" + t.getObjectType ());
-
- }
-
- }
-
- return Environment.getObjectTypeName (t.getObjectType ());
-
- }
-
- public static String getObjectTypeName (String t)
- {
-
- if (t == null)
- {
-
- return null;
-
- }
-
- t = t.toLowerCase ();
-
- if (t.equals ("qw"))
- {
-
- return Constants.QUOLL_WRITER_NAME;
-
- }
-
- String v = Environment.objectTypeNamesSingular.get (t);
-
- if (v == null)
- {
-
- v = Environment.getUIString (LanguageStrings.objectnames,
- LanguageStrings.singular,
- t);
-
- }
-
- return v;
-
- }
-
- public static int getPercent (float t,
- float b)
- {
-
- return (int) ((t / b) * 100);
-
- }
-
- public static String getObjectTypeNamePlural (DataObject t)
- {
-
- if (t == null)
- {
-
- return null;
-
- }
-
- if (t instanceof UserConfigurableObjectType)
- {
-
- UserConfigurableObjectType ut = (UserConfigurableObjectType) t;
-
- if (ut.isLegacyObjectType ())
- {
-
- return Environment.getObjectTypeNamePlural (ut.getUserObjectType ());
-
- }
-
- return ut.getObjectTypeNamePlural ();
-
- }
-
- if ((t instanceof UserConfigurableObject)
- &&
- (!(t instanceof LegacyUserConfigurableObject))
- )
- {
-
- UserConfigurableObject ut = (UserConfigurableObject) t;
-
- return ut.getObjectTypePluralName ();
-
- }
-
- if (t instanceof Note)
- {
-
- Note n = (Note) t;
-
- if (n.isEditNeeded ())
- {
-
- return Environment.getObjectTypeNamePlural ("editneeded" + t.getObjectType ());
-
- }
-
- }
-
- return Environment.getObjectTypeNamePlural (t.getObjectType ());
-
- }
-
- public static String getObjectTypeNamePlural (String t)
- {
-
- if (t == null)
- {
-
- return null;
-
- }
-
- t = t.toLowerCase ();
-
- String v = Environment.objectTypeNamesPlural.get (t);
-
- if (v == null)
- {
-
- v = Environment.getUIString (LanguageStrings.objectnames,
- LanguageStrings.plural,
- t);
-
- }
-
- return v;
-
- //return Environment.objectTypeNamesPlural.get (t);
-
- }
-/*
- public static String getObjectTypeName (NamedObject n)
- {
-
- if (n == null)
- {
-
- return null;
-
- }
-
- return Environment.getObjectTypeName (n.getObjectType ());
-
- }
-
- public static String getObjectTypeNamePlural (NamedObject n)
- {
-
- if (n == null)
- {
-
- return null;
-
- }
-
- return Environment.getObjectTypeNamePlural (n.getObjectType ());
-
- }
-*/
- public static Map getOpenProjects ()
- {
-
- return new HashMap (Environment.openProjects);
-
- }
-
- public static boolean projectsEqual (Project p1,
- Project p2)
- {
-
- if ((p1 == null) ||
- (p2 == null))
- {
-
- return false;
-
- }
-
- if ((p1.getId () != null)
- &&
- (p2.getId () != null)
- )
- {
-
- return p1.equals (p2);
-
- }
-
- if (p1.getName ().equalsIgnoreCase (p2.getName ()))
- {
-
- return true;
-
- }
-
- return false;
-
- }
-
- public static void deleteProject (Project p,
- ActionListener onDelete)
- {
-
- ProjectInfo pi = Environment.getProjectInfo (p.getId (),
- p.getType ());
-
- if (pi == null)
- {
-
- return;
-
- }
-
- Environment.deleteProject (pi,
- onDelete);
-
- }
-
- public static void deleteProject (final ProjectInfo pr,
- final ActionListener onDelete)
- {
-
- AbstractProjectViewer viewer = Environment.openProjects.get (pr);
-
- ActionListener onClose = new ActionListener ()
- {
-
- @Override
- public void actionPerformed (ActionEvent ev)
- {
-
- // There is probably now (because of h2) a "projectdb.lobs.db" directory.
- // Add a can delete file to it.
- try
- {
-
- Utils.createQuollWriterDirFile (new File (pr.getProjectDirectory ().getPath () + "/projectdb.lobs.db"));
-
- } catch (Exception e)
- {
-
- // Ignore for now.
- Environment.logError ("Unable to add can delete dir file to: " +
- pr.getProjectDirectory ().getPath () + "/projectdb.lobs.db",
- e);
-
- }
-
- // Delete the backup directory.
- Utils.deleteDir (pr.getBackupDirectory ());
-
- // Delete the files directory.
- Utils.deleteDir (pr.getFilesDirectory ());
-
- // Delete the directory.
- Utils.deleteDir (pr.getProjectDirectory ());
-
- // Remove the project from the list.
- try
- {
-
- Environment.projectInfoManager.deleteObject (pr,
- false,
- null);
-
- } catch (Exception e)
- {
-
- Environment.logError ("Unable to delete project: " +
- pr,
- e);
-
- }
-
- Environment.fireProjectInfoChangedEvent (pr,
- ProjectInfoChangedEvent.DELETED);
-
- if (onDelete != null)
- {
-
- onDelete.actionPerformed (new ActionEvent (pr, 1, "deleted"));
-
- } else {
-
- Environment.showLandingIfNoOpenProjects ();
-
- }
-
- }
-
-
- };
-
- if (viewer != null)
- {
-
- viewer.close (true,
- onClose);
-
- } else {
-
- UIUtils.doLater (onClose);
-
- }
-
- }
-
- public static void deleteProject (Project pr)
- {
-
- if (pr == null)
- {
-
- return;
-
- }
-
- ProjectInfo p = Environment.getProjectInfo (pr);
-
- if (p == null)
- {
-
- return;
-
- }
-
- Environment.deleteProject (p,
- null);
-
- }
-
- public static ProjectInfo getProjectInfo (Project p)
- {
-
- ProjectInfo pi = Environment.getProjectInfo (p.getId (),
- p.getType ());
-
- if (pi != null)
- {
-
- pi.setFilePassword (p.getFilePassword ());
-
- }
-
- return pi;
-
- }
-
- public static ProjectInfo getProjectInfo (String id,
- String type)
- {
-
- try
- {
-
- for (ProjectInfo p : Environment.getAllProjectInfos ())
- {
-
- if (p.getId ().equals (id))
- {
-
- if (type == null)
- {
-
- return p;
-
- }
-
- if (type.equals (p.getType ()))
- {
-
- return p;
-
- }
-
- }
-
- }
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to get all project infos to check for project: " +
- id +
- ", type: " +
- type,
- e);
-
- }
-
- return null;
-
- }
-
- public static void showLandingIfNoOpenProjects ()
- {
-
- // Show the welcome screen if there are no projects open.
- if (Environment.getOpenProjects ().size () == 0)
- {
-
- Environment.showLanding ();
-
- }
-
- }
-
- public static File getQuollWriterJarsDir ()
- {
-
- String userDir = System.getProperty ("user.dir");
-
- if (!userDir.endsWith ("jars"))
- {
-
- userDir += "/jars";
-
- }
-
- File dir = null;
-
- try
- {
-
- dir = new File (userDir).getCanonicalFile ();
-
- } catch (Exception e) {
-
- return null;
-
- }
-
- if ((!dir.exists ())
- ||
- (dir.isFile ())
- )
- {
-
- return null;
-
- }
-
- return dir;
-
- }
-
- public static void closeDown ()
- {
-
- if (Environment.openViewers.size () > 0)
- {
-
- throw new IllegalStateException ("Cannot closedown when there are open viewers.");
-
- }
-
- Environment.generalTimer.shutdown ();
-
- // Go offline from the editors service (if logged in).
- EditorsEnvironment.closeDown ();
-
- Environment.userSession.end (new Date ());
-
- try
- {
-
- Environment.projectInfoManager.addSession (Environment.userSession);
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to add session",
- e);
-
- }
-
- Environment.projectInfoManager.closeConnectionPool ();
-
- if (Environment.doOnShutdown.size () > 0)
- {
-
- for (Runnable r : Environment.doOnShutdown)
- {
-
- try
- {
-
- r.run ();
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to run on shutdown.",
- e);
-
- }
-
- }
-
- }
-
- System.exit (0);
-
- }
-
- /**
- * Inform the environment about a project closing.
- *
- * If onClose is provided then it is assumed that the caller
- * is doing something after the project has been deregistered with the
- * environment, for example opening another project or window.
- *
- * If onClose is not provided (null) then a check is made to see if
- * the projects window should be shown or should shutdown occur because
- * there are no projects open.
- *
- * @param pv The project viewer being closed.
- * @param onClose The action to take once the project is deregistered.
- * @throws Exception If something goes wrong (the list is long).
- */
- public static void projectClosed (AbstractProjectViewer pv,
- boolean tryShowLanding)
- throws Exception
- {
-
- Project proj = pv.getProject ();
-
- ProjectInfo p = Environment.getProjectInfo (pv.getProject ().getId (),
- pv.getProject ().getType ());
-
- if (p != null)
- {
-
- Object r = Environment.openProjects.remove (p);
-
- }
-
- Environment.userSession.updateCurrentSessionWordCount (pv.getSessionWordCount ());
-
- if ((tryShowLanding)
- &&
- (UserProperties.getAsBoolean (Constants.SHOW_PROJECTS_WINDOW_WHEN_NO_OPEN_PROJECTS_PROPERTY_NAME))
- )
- {
-
- Environment.showLandingIfNoOpenProjects ();
-
- }
-
- }
-
- public static void addOpenedProject (AbstractProjectViewer pv)
- throws Exception
- {
-
- final Project proj = pv.getProject ();
-
- ProjectInfo p = Environment.getProjectInfo (proj.getId (),
- proj.getType ());
-
- if (p == null)
- {
-
- // We don't have this project, so add it.
- p = new ProjectInfo (proj);
-
- try
- {
-
- Environment.projectInfoManager.saveObject (p,
- null);
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to add new project info for project: " +
- proj,
- e);
-
- }
-
- } else {
-
- p.setProject (proj);
-
- }
-
- Environment.openProjects.put (p,
- pv);
-
- }
-
- public static void updateProjectInfo (ProjectInfo pi)
- throws GeneralException
- {
-
- Environment.projectInfoManager.saveObject (pi,
- null);
-
- Environment.fireProjectInfoChangedEvent (pi,
- ProjectInfoChangedEvent.CHANGED);
-
- }
-
- public static void updateProjectInfos (List pis)
- throws GeneralException
- {
-
- Environment.projectInfoManager.saveObjects (pis,
- null);
-
- for (ProjectInfo pi : pis)
- {
-
- Environment.fireProjectInfoChangedEvent (pi,
- ProjectInfoChangedEvent.CHANGED);
-
- }
-
- }
-
- public static String replaceObjectNames (String t)
- {
-
- if (t == null)
- {
-
- return t;
-
- }
-
- StringBuilder b = new StringBuilder (t);
-
- int start = b.indexOf ("{");
-
- while (start > -1)
- {
-
- int end = b.indexOf ("}",
- start);
-
- if (end > -1)
- {
-
- String ot = b.substring (start + 1,
- end);
-
- String newot = ot.toLowerCase ();
-
- if (newot.equals ("qw"))
- {
-
- newot = Constants.QUOLL_WRITER_NAME;
-
- }
-
-/*
- boolean an = newot.startsWith ("an ");
-
- if (an)
- {
-
- newot = newot.substring (3);
-
- }
-
- if (newot.endsWith ("s"))
- {
-
- newot = Environment.getObjectTypeNamePlural (newot.substring (0,
- newot.length () - 1));
-
- } else
- {
-
- newot = Environment.getObjectTypeName (newot);
-
- }
-
- if (newot == null)
- {
-
- newot = ot;
-
- } else
- {
-
- if (Character.isUpperCase (ot.charAt (0)))
- {
-
- newot = Character.toUpperCase (newot.charAt (0)) + newot.substring (1);
-
- } else
- {
-
- newot = newot.toLowerCase ();
-
- }
-
- }
-
- if (an)
- {
-
- if (TextUtilities.isVowel (newot.toLowerCase ().charAt (0)))
- {
-
- newot = "an " + newot;
-
- } else {
-
- newot = "a " + newot;
-
- }
-
- }
-*/
- b.replace (start,
- end + 1,
- newot);
-
- start += newot.length ();
-
- } else {
-
- start++;
-
- }
-
- start = b.indexOf ("{",
- start);
-
- }
-
- return b.toString ();
-
- }
-
- public static String canOpenProject (Project p)
- {
-
- java.util.List prefix = new ArrayList ();
- prefix.add (LanguageStrings.project);
- prefix.add (LanguageStrings.actions);
- prefix.add (LanguageStrings.openproject);
- prefix.add (LanguageStrings.openerrors);
-
- if (p == null)
- {
-
- return Environment.getUIString (prefix,
- LanguageStrings.projectnotexist);
- //"{Project} does not exist.";
-
- }
-
- if (!p.getProjectDirectory ().exists ())
- {
-
- return String.format (Environment.getUIString (prefix,
- LanguageStrings.projectdirnotexist),
- p.getProjectDirectory ());
- //"Cannot find {project} directory " + p.getProjectDirectory () + ".";
-
- }
-
- if (!p.getProjectDirectory ().isDirectory ())
- {
-
- return String.format (Environment.getUIString (prefix,
- LanguageStrings.projectdirisfile),
- p.getProjectDirectory ());
- //"Path to {project} " + p.getProjectDirectory () + " is a file, but a directory is expected.";
-
- }
-
- if (!Utils.getQuollWriterDirFile (p.getProjectDirectory ()).exists ())
- {
-
- return String.format (Environment.getUIString (prefix,
- LanguageStrings.invalidprojectdir),
- p.getProjectDirectory ());
- //"{Project} directory " + p.getProjectDirectory () + " doesn't appear to be a valid Quoll Writer {project}.";
-
- }
-
- if ((p.isEditorProject ())
- &&
- (EditorsEnvironment.getEditorByEmail (p.getForEditor ().getEmail ()) == null)
- )
- {
-
- return String.format (Environment.getUIString (prefix,
- LanguageStrings.cantfindeditor),
- //"Unable to find {contact}: %s you are editing the {project} for.",
- p.getForEditor ().getEmail ());
-
- }
-
- return null;
-
- }
-
- public static String canOpenProject (ProjectInfo p)
- {
-
- java.util.List prefix = new ArrayList<> ();
- prefix.add (LanguageStrings.project);
- prefix.add (LanguageStrings.actions);
- prefix.add (LanguageStrings.openproject);
- prefix.add (LanguageStrings.openerrors);
-
- if (p == null)
- {
-
- return Environment.getUIString (prefix,
- LanguageStrings.projectnotexist);
- //return "{Project} does not exist.";
-
- }
-
- if (!p.getProjectDirectory ().exists ())
- {
-
- return String.format (Environment.getUIString (prefix,
- LanguageStrings.projectdirnotexist),
- p.getProjectDirectory ());
- //return "Cannot find {project} directory " + p.getProjectDirectory () + ".";
-
- }
-
- if (!p.getProjectDirectory ().isDirectory ())
- {
-
- return String.format (Environment.getUIString (prefix,
- LanguageStrings.projectdirisfile),
- p.getProjectDirectory ());
- //return "Path to {project} " + p.getProjectDirectory () + " is a file, but a directory is expected.";
-
- }
-
- if (!Utils.getQuollWriterDirFile (p.getProjectDirectory ()).exists ())
- {
-
- return String.format (Environment.getUIString (prefix,
- LanguageStrings.invalidprojectdir),
- p.getProjectDirectory ());
- //return "{Project} directory " + p.getProjectDirectory () + " doesn't appear to be a valid Quoll Writer {project}.";
-
- }
-
- if ((p.isEditorProject ())
- &&
- (p.getForEditor () != null)
- &&
- (EditorsEnvironment.getEditorByEmail (p.getForEditor ().getEmail ()) == null)
- )
- {
-
- return String.format (Environment.getUIString (prefix,
- LanguageStrings.cantfindeditor),
- //"Unable to find {contact}: %s you are editing the {project} for.",
- p.getForEditor ().getEmail ());
-
- }
-
- return null;
-
- }
-
- public static boolean isFirstUse ()
- {
-
- return Environment.isFirstUse;
-
- }
-
- public static boolean checkCanOpenProject (ProjectInfo p,
- boolean showLanding)
- {
-
- String r = Environment.canOpenProject (p);
-
- if (r != null)
- {
-
- // Do this first to ensure the error shows above it.
- if (showLanding)
- {
-
- Environment.showLanding ();
-
- }
-
- UIUtils.showErrorMessage (null,
- String.format (Environment.getUIString (LanguageStrings.project,
- LanguageStrings.actions,
- LanguageStrings.openproject,
- LanguageStrings.openerrors,
- LanguageStrings.general),
- p.getName (),
- r));
- //"Unable to open {project} " + p.getName () + ", reason:
" + r);
-
- return false;
-
- }
-
- return true;
-
- }
-
- public static boolean openLastEditedProject ()
- throws Exception
- {
-
- List projs = new ArrayList (Environment.getAllProjectInfos ());
-
- Collections.sort (projs,
- new ProjectInfoSorter ());
-
- ProjectInfo p = null;
-
- if (projs.size () > 0)
- {
-
- p = projs.get (0);
-
- }
-
- if (p != null)
- {
-
- // Check to see if the project directory exists.
- if (!Environment.checkCanOpenProject (p,
- true))
- {
-
- // We return true here since we don't want further errors to be displayed or the find/open.
- return true;
-
- }
-
- try
- {
-
- // Get the first.
- Environment.openProject (p,
- null);
-
- } catch (Exception e)
- {
-
- Environment.logError ("Unable to open project: " +
- p,
- e);
-
- return false;
-
- }
-
- return true;
-
- }
-
- return false;
-
- }
-
- public static ProjectInfo getProjectById (String id,
- String projType)
- throws Exception
- {
-
- if (id == null)
- {
-
- return null;
-
- }
-
- Set projs = Environment.getAllProjectInfos ();
-
- for (ProjectInfo p : projs)
- {
-
- String pid = p.getId ();
-
- if (pid == null)
- {
-
- continue;
-
- }
-
- if (projType != null)
- {
-
- if (!p.getType ().equals (projType))
- {
-
- continue;
-
- }
-
- }
-
- if (pid.equals (id))
- {
-
- return p;
-
- }
-
- }
-
- return null;
-
- }
-
- public static ProjectInfo getProjectByDirectory (File dir)
- throws Exception
- {
-
- if (dir == null)
- {
-
- return null;
-
- }
-
- Set projs = Environment.getAllProjectInfos ();
-
- for (ProjectInfo p : projs)
- {
-
- if (p.getProjectDirectory ().equals (dir))
- {
-
- return p;
-
- }
-
- }
-
- return null;
-
- }
-
- /** For a given project, get the project version object by its id.
- *
- * @param p The project.
- * @param id The project version id.
- * @param filePassword The password for the project file if it is encrypted.
- * @return The project version, if it can be found.
- * @throws Exception If something goes wrong.
- * TODO: Move the filepassword into the project and expect it there instead.
- */
- public static ProjectVersion getProjectVersionById (ProjectInfo p,
- String id,
- String filePassword)
- throws Exception
- {
-
- AbstractProjectViewer pv = Environment.getProjectViewer (p);
-
- ObjectManager om = null;
-
- if (pv != null)
- {
-
- // Load up the chapters.
- om = pv.getObjectManager ();
-
- } else {
-
- // Open the project.
- om = Environment.getProjectObjectManager (p,
- filePassword);
-
- om.getProject ();
-
- }
-
- ProjectVersionDataHandler pdh = (ProjectVersionDataHandler) om.getHandler (ProjectVersion.class);
-
- return pdh.getById (id);
-
- }
-
- /**
- * For a given project get the text/data for the versions of the chapters passed in. This assumes that the
- * text is not already available in the chapter object, for example when you only know the id and version.
- *
- * @param p The project.
- * @param chaps The chapters to look up.
- * @param filePassword The password for the project file if it is encrypted.
- * @return The set of versioned chapters.
- * @throws If something goes wrong.
- * TODO: Move the filepassword into the project and expect it there instead.
- */
- public static Set getVersionedChapters (ProjectInfo p,
- Collection chaps,
- String filePassword)
- throws Exception
- {
-
- AbstractProjectViewer pv = Environment.getProjectViewer (p);
-
- ObjectManager om = null;
-
- if (pv != null)
- {
-
- // Load up the chapters.
- om = pv.getObjectManager ();
-
- } else {
-
- // Open the project.
- om = Environment.getProjectObjectManager (p,
- filePassword);
-
- om.getProject ();
-
- }
-
- ChapterDataHandler cdh = (ChapterDataHandler) om.getHandler (Chapter.class);
-
- return cdh.getVersionedChapters (chaps);
-
- }
-
- /**
- * Update the chapters to the versions provided. This creates new chapter objects with new keys but
- * keeps the id/version in the chapter.
- *
- * @param p The project.
- * @param projVer The new project version to update to.
- * @param chaps The chapters to update.
- * @param filePassword The password for the project file if it is encrypted.
- * @return The set of versioned chapters.
- * @throws If something goes wrong.
- * TODO: Move the filepassword into the project and expect it there instead.
- */
- public static Set updateToNewVersions (ProjectInfo p,
- ProjectVersion projVer,
- Collection chaps,
- String filePassword)
- throws Exception
- {
-
- boolean closePool = false;
-
- AbstractProjectViewer pv = Environment.getProjectViewer (p);
-
- ObjectManager om = null;
-
- if (pv != null)
- {
-
- // Load up the chapters.
- om = pv.getObjectManager ();
-
- } else {
-
- // Open the project.
- om = Environment.getProjectObjectManager (p,
- filePassword);
-
- om.getProject ();
-
- closePool = true;
-
- }
-
- try
- {
-
- ChapterDataHandler cdh = (ChapterDataHandler) om.getHandler (Chapter.class);
-
- // Check to see if we already have a version with the specified id.
- ProjectVersionDataHandler pvdh = (ProjectVersionDataHandler) om.getHandler (ProjectVersion.class);
-
- if (pvdh.getById (projVer.getId ()) != null)
- {
-
- // Already have this version.
- return cdh.getChaptersForVersion (projVer,
- om.getProject ().getBook (0),
- null,
- true);
-
- }
-
- return cdh.updateToNewVersions (projVer,
- chaps);
-
- } finally {
-
- if (closePool)
- {
-
- if (om != null)
- {
-
- om.closeConnectionPool ();
-
- }
-
- }
-
- }
-
- }
-
- public static void restoreBackupForProject (ProjectInfo p,
- File restoreFile)
- throws Exception
- {
-
- // Get the project db file.
-
- File dbFile = new File (p.getProjectDirectory (),
- Constants.PROJECT_DB_FILE_NAME_PREFIX + Constants.H2_DB_FILE_SUFFIX);
-
- if (!dbFile.exists ())
- {
-
- throw new GeneralException ("No project database file found at: " +
- dbFile +
- ", for project: " +
- p);
-
- }
-
- File oldDBFile = new File (dbFile.getPath () + ".old");
-
- // Rename to .old
- // TODO: Investigate using java.nio.file.Files.move instead.
- if (!dbFile.renameTo (oldDBFile))
- {
-
- throw new GeneralException ("Unable to rename project database file to: " +
- dbFile.getPath () + ".old" +
- ", for project: " +
- p);
-
- }
-
- try
- {
-
- Utils.extractZipFile (restoreFile,
- p.getProjectDirectory ());
-
- // See if there is a project db file in there now.
- if (!dbFile.exists ())
- {
-
- throw new GeneralException ("Backup file does not contain a valid project db file");
-
- }
-
- oldDBFile.delete ();
-
- } catch (Exception e) {
-
- // Try and rename back.
- oldDBFile.renameTo (dbFile);
-
- throw e;
-
- }
-
- }
-
- public static File createBackupForProject (Project p,
- boolean noPrune)
- throws Exception
- {
-
- return Environment.createBackupForProject (Environment.getProjectInfo (p),
- noPrune);
-
- }
-
- public static File createBackupForProject (ProjectInfo p,
- boolean noPrune)
- throws Exception
- {
-
- boolean closePool = false;
-
- AbstractProjectViewer pv = Environment.getProjectViewer (p);
-
- ObjectManager om = null;
- Project proj = null;
-
- if (pv != null)
- {
-
- // Load up the chapters.
- om = pv.getObjectManager ();
-
- proj = pv.getProject ();
-
- } else {
-
- if ((p.isEncrypted ())
- &&
- (p.getFilePassword () == null)
- )
- {
-
- throw new IllegalArgumentException ("The file password must be specified for encrypted projects when the project is not already open.");
-
- }
-
- // Open the project.
- try
- {
-
- om = Environment.getProjectObjectManager (p,
- p.getFilePassword ());
-
- proj = om.getProject ();
-
- } catch (Exception e) {
-
- // Can't open the project.
- if (om != null)
- {
-
- om.closeConnectionPool ();
-
- }
-
- throw e;
-
- }
-
- proj.setBackupDirectory (p.getBackupDirectory ());
-
- closePool = true;
-
- }
-
- String backupCount = proj.getProperty (Constants.BACKUPS_TO_KEEP_COUNT_PROPERTY_NAME);
-
- int count = -1;
-
- if ((backupCount != null)
- &&
- // Legacy, pre 2.6.5
- (!backupCount.equals ("All"))
- )
- {
-
- try
- {
-
- count = Integer.parseInt (backupCount);
-
- } catch (Exception e) {}
-
- }
-
- try
- {
-
- File f = om.createBackup (proj,
- (noPrune ? -1 : count));
-
- Environment.fireUserProjectEvent (proj,
- ProjectEvent.BACKUPS,
- ProjectEvent.NEW,
- proj);
-
- return f;
-
- } finally {
-
- if (closePool)
- {
-
- if (om != null)
- {
-
- om.closeConnectionPool ();
-
- }
-
- }
-
- }
-
- }
-
- /**
- * Get an object manager for the specified project and init it.
- *
- * @param p The project.
- * @param filePassword Optional, the password for the project if it is encrypted.
- * @returns The object manager for the project.
- * @throws An exception if the object manager cannot be inited.
- * TODO: Move the filepassword into the project and expect it there instead.
- */
- public static ObjectManager getProjectObjectManager (ProjectInfo p,
- String filePassword)
- throws GeneralException
- {
-
- // Get the username and password.
- String username = Environment.getProperty (Constants.DB_USERNAME_PROPERTY_NAME);
- String password = Environment.getProperty (Constants.DB_PASSWORD_PROPERTY_NAME);
-
- if (p.isNoCredentials ())
- {
-
- username = null;
- password = null;
-
- }
-
- ObjectManager dBMan = new ObjectManager ();
- dBMan.init (new File (p.getProjectDirectory ().getPath (), Constants.PROJECT_DB_FILE_NAME_PREFIX),
- username,
- password,
- filePassword,
- Environment.getSchemaVersion ());
-
- try
- {
-
- dBMan.getProject ();
-
- } catch (Exception e) {
-
- dBMan.closeConnectionPool ();
-
- throw e;
-
- }
-
- return dBMan;
-
- }
-
- /**
- * Creates a completely new project with the specified name at the saveDir/name location.
- * If the project is to be encrypted then a filePassword should be supplied. The schema will be created.
- *
- * @param saveDir The directory to save the project to.
- * @param name The name of the project.
- * @param filePassword Optional, provide if the project is to be encrypted.
- * @returns The new project object created.
- * @throws An exception if the schema cannot be created or if the save location already exists.
- */
- public static Project createNewProject (File saveDir,
- String name,
- String filePassword)
- throws Exception
- {
-
- File projDir = new File (saveDir,
- Utils.sanitizeForFilename (name));
-
- if (projDir.exists ())
- {
-
- throw new IllegalArgumentException ("A project with name: " +
- name +
- " already exists at: " +
- projDir);
-
- }
-
- Project p = new Project ();
- p.setName (name);
-
- // Get the username and password.
- String username = Environment.getProperty (Constants.DB_USERNAME_PROPERTY_NAME);
- String password = Environment.getProperty (Constants.DB_PASSWORD_PROPERTY_NAME);
-
- ObjectManager dBMan = new ObjectManager ();
- dBMan.init (new File (projDir.getPath (), Constants.PROJECT_DB_FILE_NAME_PREFIX),
- username,
- password,
- filePassword,
- 0);
-
- // Create a file that indicates that the directory can be deleted.
- Utils.createQuollWriterDirFile (projDir);
-
- p.setProjectDirectory (projDir);
- p.setEncrypted (filePassword != null);
-
- Book b = new Book (p,
- p.getName ());
-
- p.addBook (b);
-
- dBMan.saveObject (p,
- null);
-
- dBMan.closeConnectionPool ();
-
- ProjectInfo pi = new ProjectInfo (p);
-
- Environment.fireProjectInfoChangedEvent (pi,
- ProjectInfoChangedEvent.ADDED);
-
- return p;
-
- }
-
- /**
- * Creates the specified project (containing the relevant information) at the saveDir/p.getName () location.
- * If the project is to be encrypted then a filePassword should be supplied. The schema will be created.
- *
- * @param saveDir The directory to save the project to.
- * @param p The project.
- * @param filePassword Optional, provide if the project is to be encrypted.
- * @throws An exception if the schema cannot be created or if a project already exists at the save location.
- */
- public static ObjectManager createProject (File saveDir,
- Project p,
- String filePassword)
- throws Exception
- {
-
- File projDir = new File (saveDir,
- Utils.sanitizeForFilename (p.getName ()));
-
- if (projDir.exists ())
- {
-
- throw new IllegalArgumentException ("A project with name: " +
- p.getName () +
- " already exists at: " +
- projDir);
-
- }
-
- // Get the username and password.
- String username = Environment.getProperty (Constants.DB_USERNAME_PROPERTY_NAME);
- String password = Environment.getProperty (Constants.DB_PASSWORD_PROPERTY_NAME);
-
- ObjectManager dBMan = new ObjectManager ();
- dBMan.init (new File (projDir.getPath (), Constants.PROJECT_DB_FILE_NAME_PREFIX),
- username,
- password,
- filePassword,
- 0);
-
- // Create a file that indicates that the directory can be deleted.
- Utils.createQuollWriterDirFile (projDir);
-
- p.setProjectDirectory (projDir);
- p.setEncrypted (filePassword != null);
-
- dBMan.setProject (p);
-
- dBMan.saveObject (p,
- null);
-
- ProjectInfo pi = new ProjectInfo (p);
-
- Environment.projectInfoManager.saveObject (pi,
- null);
-
- Environment.fireProjectInfoChangedEvent (pi,
- ProjectInfoChangedEvent.ADDED);
-
- return dBMan;
-
- }
-
- public static void openObjectInProject (final ProjectInfo proj,
- final DataObject obj)
- throws Exception
- {
-
- Environment.openProject (proj,
- new ActionListener ()
- {
-
- public void actionPerformed (ActionEvent ev)
- {
-
- // View the object.
- AbstractProjectViewer viewer = Environment.getProjectViewer (proj);
-
- viewer.viewObject (obj);
-
- }
-
- });
-
- }
-
- public static void openObjectInProject (final Project proj,
- final DataObject obj)
- throws Exception
- {
-
- final DataObject dobj = obj;
-
- ProjectInfo p = null;
-
- try
- {
-
- p = Environment.getProjectInfo (proj);
-
- } catch (Exception e) {
-
- throw new GeneralException ("Unable to get project info for project id: " +
- proj.getId (),
- e);
-
- }
-
- if (p == null)
- {
-
- throw new GeneralException ("Unable to get project info for project id: " +
- proj.getId ());
-
- }
-
- Environment.openObjectInProject (p,
- obj);
-
- }
-
- public static void openProjectWithId (String projId,
- String projType)
- throws Exception
- {
-
- Environment.openProject (projId,
- projType,
- null);
-
- }
-
- public static void openProject (Project p)
- throws Exception
- {
-
- Environment.openProject (p,
- null);
-
- }
-
- public static void openProject (Project p,
- ActionListener onProjectOpen)
- throws Exception
- {
-
- if (p == null)
- {
-
- return;
-
- }
-
- Environment.openProject (p.getId (),
- p.getType (),
- onProjectOpen);
-
- }
-
- public static void openProject (final String projId,
- final String projType,
- final ActionListener onProjectOpen)
- throws Exception
- {
-
- ProjectInfo p = Environment.getProjectInfo (projId,
- projType);
-
- if (p != null)
- {
-
- Environment.openProject (p,
- onProjectOpen);
-
- }
-
- }
-
- public static void openProject (final ProjectInfo p)
- throws Exception
- {
-
- Environment.openProject (p,
- null);
-
- }
-
- public static void openProject (final ProjectInfo p,
- final ActionListener onProjectOpen)
- throws Exception
- {
-
- if (p == null)
- {
-
- return;
-
- }
-
- if (p.isOpening ())
- {
-
- return;
-
- }
-
- AbstractProjectViewer pv = (AbstractProjectViewer) Environment.openProjects.get (p);
-
- if (pv != null)
- {
-
- p.setOpening (false);
-
- pv.setVisible (true);
- pv.setState (java.awt.Frame.NORMAL);
- pv.toFront ();
-
- if (onProjectOpen != null)
- {
-
- onProjectOpen.actionPerformed (new ActionEvent ("open", 1, "open"));
-
- }
-
- } else
- {
-
- try
- {
-
- pv = Environment.getProjectViewerForType (p);
-
- } catch (Exception e)
- {
-
- throw new GeneralException ("Unable to open project: " +
- p,
- e);
-
- }
-
- if (pv == null)
- {
-
- throw new GeneralException ("Unable to open project: " +
- p);
-
- }
-
- final AbstractProjectViewer fpv = pv;
- /*
- if (onProjectOpen != null)
- {
-
- pv.addProjectEventListener (new ProjectEventListener ()
- {
-
- @Override
- public void eventOccurred (ProjectEvent ev)
- {
-
- if ((ev.getType ().equals (Project.OBJECT_TYPE))
- &&
- (ev.getAction ().equals (ProjectEvent.OPEN))
- )
- {
-
- try
- {
-
- onProjectOpen.actionPerformed (new ActionEvent (fpv, 1, "open"));
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to perform action after project open",
- e);
-
- }
-
- }
-
- }
-
- });
-
- }
- */
- Environment.incrStartupProgress ();
-
- java.util.List prefix = new ArrayList ();
- prefix.add (LanguageStrings.project);
- prefix.add (LanguageStrings.actions);
- prefix.add (LanguageStrings.openproject);
- prefix.add (LanguageStrings.enterpasswordpopup);
-
- if (p.isEncrypted ())
- {
-
- Environment.startupComplete ();
-
- PasswordInputWindow.create (Environment.getUIString (prefix,
- LanguageStrings.title),
- //"Enter password",
- "lock",
- String.format (Environment.getUIString (prefix,
- LanguageStrings.text),
- p.getName ()),
- //"{Project}: " + p.getName () + " is encrypted, please enter the password.",
- Environment.getUIString (prefix,
- LanguageStrings.buttons,
- LanguageStrings.open),
- //"Open",
- new ValueValidator ()
- {
-
- public String isValid (String v)
- {
-
- if ((v == null)
- ||
- (v.trim ().equals (""))
- )
- {
-
- return Environment.getUIString (prefix,
- LanguageStrings.errors,
- LanguageStrings.novalue);
- //"Please enter the password.";
-
- }
-
- try
- {
-
- fpv.openProject (p,
- v,
- onProjectOpen);
- /*
- Environment.openProjects.put (p,
- fpv);
- */
- } catch (Exception e) {
-
- if (ObjectManager.isDatabaseAlreadyInUseException (e))
- {
-
- return Environment.getUIString (prefix,
- LanguageStrings.errors,
- LanguageStrings.projectalreadyopen);
- //"Sorry, the {project} appears to already be open in Quoll Writer. Please close all other instances of Quoll Writer first before trying to open the {project}.";
-
- }
-
- if (ObjectManager.isEncryptionException (e))
- {
-
- return Environment.getUIString (prefix,
- LanguageStrings.errors,
- LanguageStrings.invalidpassword);
- //return "Password is not valid.";
-
- }
-
- Environment.logError ("Cant open project: " +
- p,
- e);
-
- UIUtils.showErrorMessage (null,
- Environment.getUIString (prefix,
- LanguageStrings.errors,
- LanguageStrings.general));
- //"Sorry, the {project} can't be opened. Please contact Quoll Writer support for assistance.");
-
- return null;
-
- } finally {
-
- p.setOpening (false);
-
- }
-
- return null;
-
- }
-
- },
- new ActionAdapter ()
- {
-
- public void actionPerformed (ActionEvent ev)
- {
-
- // All handled by the validator.
-
- }
-
- },
- new ActionAdapter ()
- {
-
- public void actionPerformed (ActionEvent ev)
- {
-
- Environment.showLanding ();
-
- }
-
- }).resize ();
-
- return;
-
- }
-
- try
- {
-
- pv.openProject (p,
- null,
- onProjectOpen);
-
- } catch (Exception e) {
-
- pv.close (false,
- null);
-
- if (ObjectManager.isDatabaseAlreadyInUseException (e))
- {
-
- UIUtils.showErrorMessage (null,
- Environment.getUIString (prefix,
- LanguageStrings.errors,
- LanguageStrings.projectalreadyopen));
- //"Sorry, the {project} appears to already be open in Quoll Writer. Please close all other instances of Quoll Writer first before trying to open the {project}.");
-
- return;
-
- }
-
- throw e;
-
- } finally {
-
- p.setOpening (false);
-
- }
-
- Environment.startupComplete ();
- /*
- Environment.openProjects.put (p,
- pv);
-*/
- }
-
- //return pv;
-
- }
-
- public static void addToAchievementsManager (AbstractProjectViewer viewer)
- {
-
- try
- {
-
- Environment.achievementsManager.addProjectViewer (viewer);
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to init achievements for viewer: " +
- viewer,
- e);
-
- }
-
- }
-
- public static void removeFromAchievementsManager (AbstractViewer viewer)
- {
-
- try
- {
-
- Environment.achievementsManager.removeViewer (viewer);
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to remove from achievements: " +
- viewer,
- e);
-
- }
-
- }
-
- public static boolean isDebugModeEnabled ()
- {
-
- return Environment.debugMode;
-
- }
-
- public static void setDebugModeEnabled (boolean v)
- {
-
- Environment.debugMode = v;
-
- // TODO: Maybe have an EnvironmentEvent?
-
- }
-
- public static void logDebugMessage (String m)
- {
-
- if (Environment.isDebugModeEnabled ())
- {
-
- Environment.logMessage (m);
-
- }
-
- }
-
- public static void logMessage (String m)
- {
-
- if (Environment.isDebugModeEnabled ())
- {
-
- //System.out.println (m);
-
- }
-
- Environment.generalLog.logInformationMessage (m);
-
- }
-
- public static void logError (String m)
- {
-
- if (Environment.errorLog == null)
- {
-
- return;
-
- }
-
- Environment.logError (m,
- null);
-
- }
-
- public static void logSQLStatement (String s,
- List params)
- {
-
- if (!Environment.isDebugModeEnabled ())
- {
-
- return;
-
- }
-
- Environment.sqlLog.logInformationMessage ("SQL:=============================\n" + s + "\nPARAMS:\n" + params);
-
- }
-
- public static void logError (String m,
- Exception ex)
- {
-
- if (Environment.errorLog == null)
- {
-
- return;
-
- }
-
- Environment.errorLog.logError (m,
- ex,
- null);
-
- if ((!Environment.isDebugModeEnabled ())
- &&
- (UserProperties.getAsBoolean (Constants.AUTO_SEND_ERRORS_TO_SUPPORT_PROPERTY_NAME))
- )
- {
-
- Map details = new HashMap ();
-/*
- try
- {
-
- details.put ("errorLog",
- IOUtils.getFile (Environment.getErrorLogFile ()));
- details.put ("generalLog",
- IOUtils.getFile (Environment.getGeneralLogFile ()));
-
- } catch (Exception e) {
-
- // NOt much we can do here!
-
- }
-*/
- details.put ("reason",
- m);
-
- if (ex != null)
- {
-
- details.put ("stackTrace",
- Utils.getStackTrace (ex));
-
- }
-
- try
- {
-
- Environment.sendMessageToSupport ("error",
- details,
- null);
-
- } catch (Exception e) {
-
- // Nothing we can do.
-
- }
-
- }
-
- }
-
- public static com.gentlyweb.properties.Properties getDefaultProperties (String objType)
- {
-
- com.gentlyweb.properties.Properties props = (com.gentlyweb.properties.Properties) Environment.defaultObjectProperties.get (objType);
-
- if (props == null)
- {
-
- // Create some new blank properties.
- props = new com.gentlyweb.properties.Properties ();
-
- Environment.defaultObjectProperties.put (objType,
- props);
-
- }
-
- if (props.getId () == null)
- {
-
- props.setId ("default-" + objType);
-
- }
-
- if (props.getParentProperties () == null)
- {
-
- props.setParentProperties (UserProperties.getProperties ());
-
- }
-
- return props;
-
- }
-
- private static void initProjectId (Project envProj,
- Project realProj)
- {
-
- if ((envProj.getId () == null)
- &&
- (realProj.getId () != null)
- )
- {
-
- envProj.setId (realProj.getId ());
-
- }
-
- }
-
- public static void setUILanguage (String id)
- throws Exception
- {
-
- LanguageStrings ls = null;
-
- ls = Environment.getUILanguageStrings (id);
-
- if (ls == null)
- {
-
- throw new GeneralException ("No language strings found for id: " +
- id);
-
- }
-
- Environment.uiLanguageStrings = ls;
-
- UserProperties.set (Constants.USER_UI_LANGUAGE_PROPERTY_NAME, id);
-
- Environment.loadUserObjectTypeNames ();
-
- }
-
- private static File getUILanguageStringsDir ()
- {
-
- File d = new File (Environment.getUserQuollWriterDir (),
- Constants.UI_LANGUAGES_DIR_NAME);
-
- if (!d.exists ())
- {
-
- d.mkdirs ();
-
- }
-
- return d;
-
- }
-
- private static File getUserUILanguageStringsDir (Version v)
- {
-
- File d = new File (Environment.getUserQuollWriterDir (),
- Constants.USER_UI_LANGUAGES_DIR_NAME + "/" + v.toString ());
-
- if (!d.exists ())
- {
-
- d.mkdirs ();
-
- }
-
- return d;
-
- }
-
- public static LanguageStrings getUserUILanguageStrings (Version v,
- String id)
- throws Exception
- {
-
- File f = Environment.getUserUILanguageStringsFile (v,
- id);
-
- if (f.exists ())
- {
-
- LanguageStrings ls = new LanguageStrings (f);
- ls.setUser (true);
-
- return ls;
-
- }
-
- return null;
-
- }
-
- private static void deleteUserUILanguageStrings (final LanguageStrings ls)
- {
-
- ActionListener remFile = new ActionListener ()
- {
-
- @Override
- public void actionPerformed (ActionEvent ev)
- {
-
- File f = Environment.getUserUILanguageStringsFile (ls.getQuollWriterVersion (),
- ls.getId ());
-
- if (f.exists ())
- {
-
- f.delete ();
-
- }
-
- }
-
- };
-
- Set viewers = new HashSet<> (Environment.openViewers);
-
- for (AbstractViewer v : viewers)
- {
-
- if (v instanceof LanguageStringsEditor)
- {
-
- LanguageStringsEditor lse = (LanguageStringsEditor) v;
-
- if ((lse.getUserLanguageStrings ().getId ().equals (ls.getId ()))
- &&
- (lse.getUserLanguageStrings ().getQuollWriterVersion ().equals (ls.getQuollWriterVersion ()))
- )
- {
-
- lse.close (false,
- remFile);
-
- return;
-
- }
-
- }
-
- }
-
- remFile.actionPerformed (new ActionEvent (ls, 0, "do"));
-
- if (UserProperties.get (Constants.USER_UI_LANGUAGE_PROPERTY_NAME).equals ("user-" + ls.getId ()))
- {
-
- try
- {
-
- // Need to set the language back to English.
- Environment.setUILanguage (LanguageStrings.ENGLISH_ID);
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to set UI strings.",
- e);
-
- UIUtils.showErrorMessage (null,
- "Unable to reset user interface language to " + Constants.ENGLISH);
-
- return;
-
- }
-
- UIUtils.showMessage ((Component) null,
- "Restart recommended",
- "The user interface language has been reset to " + Constants.ENGLISH + ", a restart is recommended.");
-
- }
-
- }
-
- public static void deleteUserUILanguageStrings (LanguageStrings ls,
- boolean allVersions)
- throws Exception
- {
-
- if (!ls.isUser ())
- {
-
- throw new IllegalArgumentException ("Can only delete user language strings.");
-
- }
-
- if (allVersions)
- {
-
- Set allLs = Environment.getAllUserLanguageStrings ();
-
- for (LanguageStrings _ls : allLs)
- {
-
- if (_ls.getId ().equals (ls.getId ()))
- {
-
- Environment.deleteUserUILanguageStrings (_ls);
-
- }
-
- }
-
- } else {
-
- Environment.deleteUserUILanguageStrings (ls);
-
- }
-
- }
-
- public static LanguageStrings getUserUIEnglishLanguageStrings (Version v)
- throws Exception
- {
-
- // If the version is the same as the QW version the user is running then
- if (v.equals (Environment.getQuollWriterVersion ()))
- {
-
- LanguageStrings def = Environment.getDefaultUILanguageStrings ();
-
- Environment.saveUserUILanguageStrings (def);
-
- return def;
-
- //return Environment.getUserUIEnglishLanguageStrings (v);
-
- }
-
- // See if there is a user strings file.
- File f = Environment.getUserUILanguageStringsFile (v,
- LanguageStrings.ENGLISH_ID);
-
- if (f.exists ())
- {
-
- return new LanguageStrings (f);
-
- }
-
- return null;
-
- }
-
- public static LanguageStrings getDefaultUILanguageStrings ()
- {
-
- return Environment.defaultUILanguageStrings;
-
- }
-
- public static LanguageStrings getCurrentUILanguageStrings ()
- {
-
- return Environment.uiLanguageStrings;
-
- }
-
- public static LanguageStrings getUILanguageStrings (String id)
- throws Exception
- {
-
- if (id.startsWith ("user-"))
- {
-
- id = id.substring ("user-".length ());
-
- return Environment.getUserUILanguageStrings (Environment.getQuollWriterVersion (),
- id);
-
- }
-
- if (id.equals (LanguageStrings.ENGLISH_ID))
- {
-
- return Environment.getDefaultUILanguageStrings ();
-
- }
-
- File f = Environment.getUILanguageStringsFile (id);
-
- if (!f.exists ())
- {
-
- return null;
-
- }
-
- String data = Utils.getFileAsString (f,
- StandardCharsets.UTF_8);
-
- LanguageStrings s = new LanguageStrings (data);
-
- return s;
-
- }
-
- public static Set getAllUserLanguageStrings (Version qwVer)
- throws GeneralException
- {
-
- Set ret = new LinkedHashSet<> ();
-
- for (LanguageStrings ls : Environment.getAllUserLanguageStrings ())
- {
-
- if (ls.getQuollWriterVersion ().equals (qwVer))
- {
-
- ret.add (ls);
-
- }
-
- }
-
- return ret;
-
- }
-
- public static Set getAllUserLanguageStrings ()
- throws GeneralException
- {
-
- Set s = new TreeSet<> ();
-
- File d = new File (Environment.getUserQuollWriterDir (),
- Constants.USER_UI_LANGUAGES_DIR_NAME);
-
- File[] files = d.listFiles ();
-
- if (files != null)
- {
-
- for (int i = 0; i < files.length; i++)
- {
-
- File fd = files[i];
-
- File[] dfiles = fd.listFiles ();
-
- if (dfiles != null)
- {
-
- for (int j = 0; j < dfiles.length; j++)
- {
-
- LanguageStrings ls = new LanguageStrings (dfiles[j]);
-
- if (ls.isEnglish ())
- {
-
- continue;
-
- }
-
- s.add (ls);
-
- }
-
- }
-
- }
-
- }
-
- return s;
-
- }
-
- public static void saveUserUILanguageStrings (LanguageStrings ls)
- throws Exception
- {
-
- File f = Environment.getUserUILanguageStringsFile (ls);
-
- f.getParentFile ().mkdirs ();
-
- String json = JSONEncoder.encode (ls.getAsJSON ());
-
- Writer out = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (f),
- "utf-8"));
-
- char[] chars = json.toCharArray ();
-
- out.write (chars, 0, chars.length);
- out.flush ();
- out.close ();
-
- }
-
- public static void downloadUILanguageFile (final String id,
- final ActionListener onComplete,
- final ActionListener onError)
- {
-
- Environment.schedule (new Runnable ()
- {
-
- @Override
- public void run ()
- {
-
- String lastMod = "";
-
- LanguageStrings ls = null;
-
- try
- {
-
- ls = Environment.getUILanguageStrings (id);
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to get language strings: " + id,
- e);
-
- onError.actionPerformed (new ActionEvent (getUIString (uilanguage,download,actionerror), 0, "error"));
-
- return;
-
- }
-
- if (ls != null)
- {
-
- Date d = ls.getLastModified ();
-
- if (d == null)
- {
-
- d = ls.getDateCreated ();
-
- }
-
- lastMod = d.getTime () + "";
-
- }
-
- String url = Environment.getProperty (Constants.QUOLL_WRITER_GET_UI_LANGUAGE_STRINGS_URL_PROPERTY_NAME);
-
- url = StringUtils.replaceString (url,
- Constants.VERSION_TAG,
- Environment.getQuollWriterVersion ().toString ());
-
- url = StringUtils.replaceString (url,
- Constants.ID_TAG,
- id);
-
- url = StringUtils.replaceString (url,
- Constants.LAST_MOD_TAG,
- lastMod);
-
- try
- {
-
- String data = Environment.getUrlFileAsString (new URL (Environment.getQuollWriterWebsite () + "/" + url));
-
- if (data.startsWith (Constants.JSON_RETURN_PREFIX))
- {
-
- data = data.substring (Constants.JSON_RETURN_PREFIX.length ());
-
- }
-
- if (data.trim ().length () == 0)
- {
-
- Environment.logError ("No language strings data available for: " + id + ", " + Environment.getQuollWriterVersion ());
-
- onError.actionPerformed (new ActionEvent (getUIString (uilanguage,download,actionerror), 0, "error"));
-
- return;
-
- }
-
- // Will be a collection.
- Collection col = null;
-
- try
- {
-
- col = (Collection) JSONDecoder.decode (data);
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to decode language strings data for id: " + id + ", " + Environment.getQuollWriterVersion (),
- e);
-
- onError.actionPerformed (new ActionEvent (getUIString (uilanguage,download,actionerror), 0, "error"));
-
- return;
-
- }
-
- Iterator iter = col.iterator ();
-
- int updated = 0;
-
- while (iter.hasNext ())
- {
-
- Map m = (Map) iter.next ();
-
- String id = (String) m.get (":id");
-
- if (id == null)
- {
-
- throw new GeneralException ("No id found.");
-
- }
-
- updated++;
-
- File f = Environment.getUILanguageStringsFile (id);
-
- Writer out = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (f),
- StandardCharsets.UTF_8));
-
- char[] chars = JSONEncoder.encode (m).toCharArray ();
-
- out.write (chars, 0, chars.length);
- out.flush ();
- out.close ();
-
- }
-
- onComplete.actionPerformed (new ActionEvent (this, updated, "success"));
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to get user interface files for: " + id + ", " + Environment.getQuollWriterVersion (),
- e);
-
- onError.actionPerformed (new ActionEvent (getUIString (uilanguage,download,actionerror), 0, "error"));
-
- }
-
- }
-
- },
- 1 * Constants.SEC_IN_MILLIS,
- -1);
-
- }
-
- public static Set getAllUILanguageStrings ()
- {
-
- return Environment.getAllUILanguageStrings (null);
-
- }
-
- public static Set getAllUILanguageStrings (Version ver)
- {
-
- Set ret = new LinkedHashSet<> ();
-
- File[] files = Environment.getUILanguageStringsDir ().listFiles ();
-
- if (files == null)
- {
-
- return ret;
-
- }
-
- for (int i = 0; i < files.length; i++)
- {
-
- File f = files[i];
-
- if (f.isFile ())
- {
-
- try
- {
-
- LanguageStrings ls = new LanguageStrings (f);
-
- if (ver != null)
- {
-
- if (!ls.getQuollWriterVersion ().equals (ver))
- {
-
- continue;
-
- }
-
- }
-
- ret.add (ls);
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to create strings from: " + f,
- e);
-
- // Delete the file.
- f.delete ();
-
- }
-
- }
-
- }
-
- return ret;
-
- }
-
- public static File getUILanguageStringsFile (String id)
- {
-
- return new File (Environment.getUILanguageStringsDir (),
- id);
-
- }
-
- public static File getUserUILanguageStringsFile (Version qwVersion,
- String id)
- {
-
- if (id.equals (LanguageStrings.ENGLISH_ID))
- {
-
- id = id.substring (1);
-
- }
-
- return new File (Environment.getUserUILanguageStringsDir (qwVersion),
- id);
-
- }
-
- public static File getUserUILanguageStringsFile (LanguageStrings ls)
- {
-
- return Environment.getUserUILanguageStringsFile (ls.getQuollWriterVersion (),
- ls.getId ());
-
- }
-
- private static File getUserDefaultProjectPropertiesFile ()
- {
-
- return new File (Environment.getUserQuollWriterDir () + "/" + Constants.DEFAULT_PROJECT_PROPERTIES_FILE_NAME);
-
- }
-
- public static AbstractProjectViewer getProjectViewerForType (Project p)
- throws Exception
- {
-
- AbstractProjectViewer v = null;
-
- if (p.getType ().equals (Project.NORMAL_PROJECT_TYPE))
- {
-
- v = new ProjectViewer ();
-
- }
-
- if (p.getType ().equals (Project.EDITOR_PROJECT_TYPE))
- {
-
- v = new EditorProjectViewer ();
-
- }
-
- if (p.getType ().equals (Project.WARMUPS_PROJECT_TYPE))
- {
-
- v = new WarmupsViewer ();
-
- }
-
- if (v == null)
- {
-
- throw new GeneralException ("Project type: " +
- p.getType () +
- " is not supported.");
-
- }
-
- v.init ();
-
- return v;
-
- }
-
- public static AbstractProjectViewer getProjectViewerForType (ProjectInfo p)
- throws Exception
- {
-
- AbstractProjectViewer v = null;
-
- if (p.getType ().equals (Project.NORMAL_PROJECT_TYPE))
- {
-
- v = new ProjectViewer ();
-
- }
-
- if (p.getType ().equals (Project.EDITOR_PROJECT_TYPE))
- {
-
- v = new EditorProjectViewer ();
-
- }
-
- if (p.getType ().equals (Project.WARMUPS_PROJECT_TYPE))
- {
-
- v = new WarmupsViewer ();
-
- }
-
- if (v == null)
- {
-
- throw new GeneralException ("Project type: " +
- p.getType () +
- " is not supported.");
-
- }
-
- v.init ();
-
- return v;
-
- }
-
- public static String getButtonLabel (String preferredValue,
- String id)
- {
-
- if (preferredValue != null)
- {
-
- return preferredValue;
-
- }
-
- return Environment.getButtonLabel (id);
-
- }
-
- public static String getButtonLabel (String id)
- {
-
- if (!id.startsWith (Constants.BUTTON_LABEL_ID_PREFIX))
- {
-
- return id;
-
- }
-
-
- return Environment.getUIString (LanguageStrings.buttons,
- id);
-
- }
-
- private static void initProjectsDBFromProjectsFile ()
- throws Exception
- {
-
- File f = new File (Environment.getUserQuollWriterDir () + "/" + Constants.PROJECTS_FILE_NAME);
-
- if (!f.exists ())
- {
-
- return;
-
- }
-
- // Get the projects file.
- Element root = JDOMUtils.getFileAsElement (f,
- Environment.GZIP_EXTENSION);
-
- List pels = JDOMUtils.getChildElements (root,
- Project.OBJECT_TYPE,
- false);
-
- for (int i = 0; i < pels.size (); i++)
- {
-
- Element pEl = (Element) pels.get (i);
-
- Project p = null;
-
- try
- {
-
- p = new Project (pEl);
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to convert element: " +
- JDOMUtils.getPath (pEl) +
- " to a project",
- e);
-
- continue;
-
- }
-
- ProjectInfo pi = null;
-
- // Try and load the project.
- try
- {
-
- pi = new ProjectInfo (p);
-
- ObjectManager om = Environment.getProjectObjectManager (pi,
- null);
-
- // Now deal with the real project.
- pi = new ProjectInfo (om.getProject ());
-
- pi.setEncrypted (p.isEncrypted ());
- pi.setNoCredentials (p.isNoCredentials ());
-
- om.closeConnectionPool ();
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to load project: " +
- p,
- e);
-
- }
-
- if (pi == null)
- {
-
- try
- {
-
- pi = new ProjectInfo (p);
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to convert project: " +
- p +
- " to a project info",
- e);
-
- continue;
-
- }
-
- }
-
- try
- {
-
- Environment.projectInfoManager.saveObject (pi,
- null);
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to load project: " +
- p +
- ", path: " +
- JDOMUtils.getPath (pEl) +
- " into the project db",
- e);
-
- }
-
- }
-
- // Remove the projects file (rename for now).
- f.renameTo (new File (f.getParentFile (), f.getName () + ".old"));
-
- }
-
- public static Set getAllProjectInfos (String limitToType)
- throws Exception
- {
-
- Set all = new LinkedHashSet (Environment.projectInfoManager.getObjects (ProjectInfo.class,
- null,
- null,
- true));
-
- if (limitToType != null)
- {
-
- Set pis = new LinkedHashSet ();
-
- for (ProjectInfo p : all)
- {
-
- if (p.getType ().equals (limitToType))
- {
-
- pis.add (p);
-
- }
-
- }
-
- all = pis;
-
- }
-
- return all;
-
- }
-
- public static Set getAllProjectInfos ()
- throws Exception
- {
-
- return Environment.getAllProjectInfos (null);
-
- }
-
- public static ProjectInfo getWarmupsProject ()
- throws Exception
- {
-
- Set projs = Environment.getAllProjectInfos ();
-
- for (ProjectInfo pi : projs)
- {
-
- if (pi.isWarmupsProject ())
- {
-
- return pi;
-
- }
-
- }
-
- return null;
-
- }
-
- public static boolean getPropertyAsBoolean (String name)
- {
-
- return UserProperties.getAsBoolean (name);
- //return Environment.userProperties.getPropertyAsBoolean (name);
-
- }
-
- public static String getProperty (String name)
- {
-
- return UserProperties.get (name);
- //return Environment.userProperties.getProperty (name);
-
- }
-
- public static File getUserQuollWriterDir ()
- {
-
- File d = new File (System.getProperty ("user.home") + "/" + Constants.QUOLL_WRITER_DIR_NAME + "/");
-
- d.mkdirs ();
-
- return d;
-
- }
-/*
- public static File getDictionaryDirectory (String lang)
- {
-
- return new File (Environment.getUserQuollWriterDir ().getPath () + Constants.DICTIONARIES_DIR + lang);
-
- }
- */
- public static File getDictionaryFile (String lang)
- {
-
- return Environment.getUserFile (Constants.DICTIONARIES_DIR + lang + ".zip");
-
- }
-
- public static boolean hasSynonymsDirectory (String lang)
- {
-
- File f = Environment.getUserFile (Constants.THESAURUS_DIR + lang);
-
- return (f.exists () && f.isDirectory ());
-
- }
-
- public static File getLogDir ()
- {
-
- File d = Environment.getUserFile (Constants.LOGS_DIR);
-
- d.mkdirs ();
-
- return d;
-
- }
-
- public static File getUserFile (String name)
- {
-
- return new File (Environment.getUserQuollWriterDir ().getPath (), name);
-
- }
-
- public static File getUserObjectTypeNamesFile ()
- {
-
- return Environment.getUserFile (Constants.OBJECT_TYPE_NAMES_FILE_NAME);
-
- }
-
- /**
- * No longer used, since properties now stored in projects db.
- * This is only used for legacy versions that need to port the properties over
- * to the new storage method.
- */
- private static File getUserPropertiesFile ()
- {
-
- return Environment.getUserFile (Constants.PROPERTIES_FILE_NAME);
-
- }
-
- public static void saveUserProperties ()
- throws Exception
- {
-
- Environment.projectInfoManager.setUserProperties (UserProperties.getProperties ());//Environment.userProperties);
-
- }
-
- public static void saveDefaultProperties (String objType,
- com.gentlyweb.properties.Properties props)
- throws Exception
- {
-
- File f = new File (Environment.getUserQuollWriterDir ().getPath () + "/default-" + objType + "-properties.xml");
-
- JDOMUtils.writeElementToFile (props.getAsJDOMElement (),
- f,
- true);
-
- }
-
- public static Date parseDate (String d)
- {
-
- if (d == null)
- {
-
- return null;
-
- }
-
- try
- {
-
- return Environment.dateFormatter.parse (d);
-
- } catch (Exception e) {
-
- // Bugger
- Environment.logError ("Unable to parse date: " +
- d,
- e);
-
- }
-
- return null;
-
- }
-
- public static String formatDateTime (Date d)
- {
-
- return Environment.formatDate (d) + " " + Environment.formatTime (d);
-
- }
-
- public static String formatDate (Date d)
- {
-
- return Environment.dateFormatter.format (d);
-
- }
-
- public static String formatTime (Date d)
- {
-
- return Environment.timeFormatter.format (d);
-
- }
-
- public static void init ()
- throws Exception
- {
-
- // Start the timer, it is done here so that any other code that needs it can start running things
- // straightaway.
- Environment.generalTimer = new ScheduledThreadPoolExecutor (5,
- new ThreadFactory ()
- {
-
- @Override
- public Thread newThread (Runnable r)
- {
-
- Thread t = new Thread (r);
-
- t.setDaemon (true);
- t.setPriority (Thread.MIN_PRIORITY);
- t.setName ("Environment-general-" + t.getId ());
-
- return t;
-
- }
-
- });
-
- File f = Environment.getErrorLogFile ();
-
- f.delete ();
-
- Environment.errorLog = new Logger ();
- Environment.errorLog.initLogFile (f);
-
- f = Environment.getGeneralLogFile ();
-
- f.delete ();
-
- Environment.generalLog = new Logger ();
- Environment.generalLog.initLogFile (f);
-
- f = Environment.getSQLLogFile ();
-
- f.delete ();
-
- Environment.sqlLog = new Logger ();
- Environment.sqlLog.initLogFile (f);
-
- Environment.incrStartupProgress ();
-
- Header.defaultPaintLeftColor = UIUtils.getComponentColor (); //UIUtils.getColor ("#516CA3");
- GradientPanel.defaultPaintLeftColor = UIUtils.getComponentColor (); //UIUtils.getColor ("#516CA3");
- Header.defaultPaintRightColor = UIUtils.getComponentColor (); //UIUtils.getColor ("#516CA3");
- GradientPanel.defaultPaintRightColor = UIUtils.getComponentColor (); //UIUtils.getColor ("#516CA3");
- Header.defaultTitleColor = UIUtils.getTitleColor ();
-
- Environment.isWindows = System.getProperty ("os.name").startsWith ("Windows");
-
- Environment.isMac = System.getProperty ("os.name").startsWith ("Mac");
-
- Environment.isLinux = System.getProperty ("os.name").startsWith ("Linux");
-
- //System.setErr (Environment.nullOut);
- //System.setOut (Environment.nullOut);
-
- // Setup our stream handler for the objectref protocol.
- URL.setURLStreamHandlerFactory (new ObjectRefURLStreamHandlerFactory ());
-
- Environment.dateFormatter = new SimpleDateFormat ("d MMM yyyy");
- Environment.timeFormatter = new SimpleDateFormat ("HH:mm");
-
- UIManager.put("SplitPane.background", UIUtils.getComponentColor ());
- UIManager.put("TabbedPane.contentBorderInsets", new Insets(0, 0, 1, 0));
- //UIManager.put("TabbedPane.tabInsets", new Insets(0, 5, 0, 0));
- UIManager.put("Tree.selectionBackground", UIUtils.getColor ("#aaaaaa"));//UIUtils.getTitleColor ());
- UIManager.put("SplitPane.shadow", UIUtils.getColor ("#aaaaaa"));
- UIManager.put("Tree.textForeground", UIUtils.getTitleColor ());
- UIManager.put("Tree.rowHeight", 0);
- UIManager.put("Tree.leftChildIndent", 6);
- UIManager.put("ProgressBar.cellSpacing", 0);
- UIManager.put("PopupMenu.background", UIUtils.getComponentColor ());
- UIManager.put("PopupMenu.foreground", UIUtils.getTitleColor ());
-
- if (Environment.isWindows)
- {
-
- try
- {
-
- com.jgoodies.looks.Options.setUseSystemFonts (true);
-
- UIManager.setLookAndFeel (new WindowsLookAndFeel ());
-
- } catch (Exception e)
- {
-
- Environment.logError ("Unable to set laf to: " +
- WindowsLookAndFeel.class.getName (),
- e);
-
- }
-
- }
-
- System.setProperty ("swing.aatext",
- "true");
-
- System.setProperty ("aawt.useSystemAAFontSettings",
- "true");
-
- // Remove border around splitpane divider.
- UIManager.put ("SplitPaneDivider.border",
- BorderFactory.createEmptyBorder ());
-
- UIManager.put ("Button.margin",
- new java.awt.Insets (3,
- 3,
- 3,
- 3));
-
- // Try and get a lock on the file.
- File l = new File (Environment.getUserQuollWriterDir (),
- "___quollwriter_lock.lock");
-
- FileChannel ch = new RandomAccessFile (l, "rw").getChannel ();
-
- FileLock lock = ch.tryLock ();
-
- if (lock == null)
- {
-
- throw new OverlappingFileLockException ();
-
- }
-
- Environment.lock = lock;
-
- l.deleteOnExit ();
-
- Environment.appVersion = new Version (Environment.getResourceFileAsString (Constants.VERSION_FILE).trim ());
-
- try
- {
-
- Environment.schemaVersion = Integer.parseInt (Environment.getResourceFileAsString (Constants.SCHEMA_VERSION_FILE).trim ());
-
- } catch (Exception e)
- {
-
- // Ignore.
-
- }
-
- try
- {
-
- Environment.projectInfoSchemaVersion = Integer.parseInt (Environment.getResourceFileAsString (Constants.PROJECT_INFO_SCHEMA_VERSION_FILE).trim ());
-
- } catch (Exception e)
- {
-
- // Ignore.
-
- }
-
- com.gentlyweb.properties.Properties sysProps = new com.gentlyweb.properties.Properties (Environment.class.getResourceAsStream (Constants.DEFAULT_PROPERTIES_FILE),
- null);
-
- sysProps.setId ("system");
-
- // Temporarily set the user properties to the system properties.
- UserProperties.init (sysProps);
- //Environment.userProperties = sysProps;
-
- com.gentlyweb.properties.Properties userProps = sysProps;
-
- Environment.incrStartupProgress ();
-
- Environment.defaultUILanguageStrings = new LanguageStrings (Environment.getResourceFileAsString (Constants.DEFAULT_UI_LANGUAGE_STRINGS_FILE));
-/*
- Map> errs = Environment.defaultUILanguageStrings.getErrors ();
-
- for (LanguageStrings.Value v : errs.keySet ())
- {
-
- System.out.println (v);
- System.out.println (errs.get (v));
- System.out.println ();
- }
-*/
- Environment.uiLanguageStrings = Environment.defaultUILanguageStrings;
-
- // Load the default object type names.
- // Object type names may be needed when initing the legacy object types.
- /*
- try
- {
-
- Environment.loadObjectTypeNames (JDOMUtils.getStringAsElement (Environment.getResourceFileAsString (Constants.DEFAULT_OBJECT_TYPE_NAMES_FILE)));
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to load default object type names from resource file: " +
- Constants.DEFAULT_OBJECT_TYPE_NAMES_FILE);
-
- }
-*/
- // See if this is first use.
- Environment.isFirstUse = (Environment.getProjectInfoSchemaVersion () == 0);
-
- // Get the username and password.
- String username = Environment.getProperty (Constants.DB_USERNAME_PROPERTY_NAME);
- String password = Environment.getProperty (Constants.DB_PASSWORD_PROPERTY_NAME);
-
- Environment.projectInfoManager = new ProjectInfoObjectManager ();
-
- Environment.projectInfoManager.init (Environment.getProjectInfoDBFile (),
- username,
- password,
- null,
- Environment.getProjectInfoSchemaVersion ());
-
- try
- {
-
- userProps = Environment.projectInfoManager.getUserProperties ();
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to load user properties",
- e);
-
- }
-
- if (userProps == null)
- {
-
- // Check for legacy properties.xml. Pre v2.5.
- File pf = Environment.getUserPropertiesFile ();
-
- if (pf.exists ())
- {
-
- try
- {
-
- userProps = new com.gentlyweb.properties.Properties (pf,
- Environment.GZIP_EXTENSION);
-
- } catch (Exception e)
- {
-
- Environment.logError ("Unable to load user properties from file: " +
- pf,
- e);
-
- }
-
- pf.delete ();
-
- }
-
- }
-
- if (userProps == null)
- {
-
- userProps = new com.gentlyweb.properties.Properties ();
-
- }
-
- if (userProps != sysProps)
- {
-
- userProps.setId ("user");
-
- userProps.setParentProperties (sysProps);
-
- }
-
- if (userProps == null)
- {
-
- // If this is legacy and we can't load the properties file (is corrupted) then
- // use the system properties as the properties.
- userProps = sysProps;
-
- }
-
- UserProperties.init (userProps);
-
- // Do a save here so that if we are loading for the first time they will be saved.
- try
- {
-
- Environment.saveUserProperties ();
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to save user properties",
- e);
-
- }
-
- // Load the user default, if appropriate.
- final String uilangid = UserProperties.get (Constants.USER_UI_LANGUAGE_PROPERTY_NAME);
-
- if (uilangid != null)
- {
-
- if (!LanguageStrings.isEnglish (uilangid))
- {
-
- LanguageStrings ls = Environment.getUILanguageStrings (uilangid);
-
- if ((ls == null)
- ||
- // Have we updated QW and need to get newer versions?
- ((ls != null)
- &&
- (ls.getQuollWriterVersion ().isNewer (Environment.getQuollWriterVersion ()))
- )
- )
- {
-
- // Something has gone wrong, try and download again.
- Environment.downloadUILanguageFile (uilangid,
- new ActionListener ()
- {
-
- @Override
- public void actionPerformed (ActionEvent ev)
- {
-
- try
- {
-
- Environment.setUILanguage (uilangid);
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to set ui language to: " + uilangid,
- e);
-
- UIUtils.showErrorMessage (null,
- getUIString (uilanguage,set,downloading,errors,download));
- //"Warning! Quoll Writer has been unable to re-download the User Interface strings for your selected language. There may be multiple reasons for this, such as a connection error to the internet or that the Quoll Writer server is unavailable.
It is recommended that you either restart Quoll Writer to try again or try downloading the strings from the Options panel.
In the interim Quoll Writer has fallen back to using English.");
-
- }
-
- UIUtils.showMessage (null,
- getUIString (uilanguage,set,downloading,redownload,confirmpopup,title),
- //"Language strings re-downloaded",
- getUIString (uilanguage,set,downloading,redownload,confirmpopup,text),
- //"Quoll Writer has re-downloaded the User Interface language strings you are using because they were missing from your local system. In the interim the User Interface has fallen back to using English.
To return to using your selected language Quoll Writer must be restarted.",
- null,
- null);
-
- }
-
- },
- // On error.
- new ActionListener ()
- {
-
- @Override
- public void actionPerformed (ActionEvent ev)
- {
-
- UIUtils.showErrorMessage (null,
- getUIString (uilanguage,set,downloading,redownload,actionerror));
- //"Warning! Quoll Writer has been unable to re-download the User Interface strings for your selected language. There may be multiple reasons for this, such as a connection error to the internet or that the Quoll Writer server is unavailable.
It is recommended that you either restart Quoll Writer to try again or try downloading the strings from the Options panel.
In the interim Quoll Writer has fallen back to using English.");
-
- }
-
- });
-
- } else {
-
- Environment.uiLanguageStrings = ls;
-
- if (!ls.isUser ())
- {
-
- // See if there is an update to the strings.
- Environment.downloadUILanguageFile (uilangid,
- new ActionListener ()
- {
-
- @Override
- public void actionPerformed (ActionEvent ev)
- {
-
- if (ev.getID () > 0)
- {
-
- try
- {
-
- Environment.setUILanguage (uilangid);
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to set ui language to: " + uilangid,
- e);
-
- UIUtils.showErrorMessage (null,
- getUIString (uilanguage,set,downloading,update,actionerror));
- //"Warning! Quoll Writer has been unable to update the User Interface strings for your selected language. There may be multiple reasons for this, such as a connection error to the internet or that the Quoll Writer server is unavailable.
It is recommended that you either restart Quoll Writer to try again or try downloading the strings from the Options panel.
In the interim Quoll Writer has fallen back to using English.");
-
- }
-
- UIUtils.showMessage (null,
- getUIString (uilanguage,set,downloading,update,confirmpopup,title),
- //"Language strings updated",
- getUIString (uilanguage,set,downloading,update,confirmpopup,text),
- //"Quoll Writer has updated the User Interface language strings you are using because a new version was available.
To make full use of the updated strings Quoll Writer must be restarted.",
- null,
- null);
-
- }
-
- }
-
- },
- // On error.
- new ActionListener ()
- {
-
- @Override
- public void actionPerformed (ActionEvent ev)
- {
-
- }
-
- });
-
- }
-
- }
-
- }
-
- }
-
- try
- {
-
- Environment.loadUserObjectTypeNames ();
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to load user object type names.",
- e);
-
- }
-
- // Add a property listener for name changes to user config object types.
- Environment.userConfigurableObjectTypeNameListener = new PropertyChangedListener ()
- {
-
- @Override
- public void propertyChanged (PropertyChangedEvent ev)
- {
-
- UserConfigurableObjectType type = (UserConfigurableObjectType) ev.getSource ();
-
- String id = type.getObjectTypeId ();
-
- Environment.objectTypeNamesSingular.put (id,
- type.getObjectTypeName ());
-
- Environment.objectTypeNamesPlural.put (id,
- type.getObjectTypeNamePlural ());
-
- }
-
- };
-
- // Init our legacy object types, if needed.
- Environment.projectInfoManager.initLegacyObjectTypes ();
-
- // The user session needs the properties.
- Environment.userSession = new UserSession ();
-
- // Override the debug mode.
- /*
- if (UserProperties.get (Constants.DEBUG_MODE_PROPERTY_NAME) != null)
- {
-
- Environment.setDebugModeEnabled (UserProperties.getAsBoolean (Constants.DEBUG_MODE_PROPERTY_NAME));
-
- }
-*/
-
- // Get the system default project properties.
- com.gentlyweb.properties.Properties sysDefProjProps = new com.gentlyweb.properties.Properties (Environment.class.getResourceAsStream (Constants.DEFAULT_PROJECT_PROPERTIES_FILE),
- UserProperties.getProperties ());
-
- File defUserPropsFile = Environment.getUserDefaultProjectPropertiesFile ();
-
- if (defUserPropsFile.exists ())
- {
-
- com.gentlyweb.properties.Properties userDefProjProps = new com.gentlyweb.properties.Properties (defUserPropsFile,
- Environment.GZIP_EXTENSION);
-
- userDefProjProps.setParentProperties (sysDefProjProps);
-
- sysDefProjProps = userDefProjProps;
-
- }
-
- // Load the default project properties.
- Environment.defaultObjectProperties.put (Project.OBJECT_TYPE,
- sysDefProjProps);
-
- // Create the text properties, they are derived from the user properties so need to be done after
- // the user props are inited.
- Environment.projectTextProps = new ProjectTextProperties ();
-
- Environment.fullScreenTextProps = new FullScreenTextProperties ();
-
- Environment.playSoundOnKeyStroke = UserProperties.getAsBoolean (Constants.PLAY_SOUND_ON_KEY_STROKE_PROPERTY_NAME);
-
- String sf = UserProperties.get (Constants.KEY_STROKE_SOUND_FILE_PROPERTY_NAME);
-
- try
- {
-
- File ksf = null;
-
- if (sf != null)
- {
-
- ksf = new File (sf);
-
- }
-
- Environment.setKeyStrokeSoundFile (ksf);
-
- } catch (Exception e)
- {
-
- Environment.logError ("Unable to get sound file to play on key stroke using file: " + sf,
- e);
-
- }
-
- Environment.incrStartupProgress ();
-
-/*
- Environment.userPropertyHandlers.put (Constants.OBJECT_TYPES_PROPERTY_NAME,
- new UserPropertyHandler (Constants.OBJECT_TYPES_PROPERTY_NAME,
- null));
-*/
- Environment.userPropertyHandlers.put (Constants.NOTE_TYPES_PROPERTY_NAME,
- new UserPropertyHandler (Constants.NOTE_TYPES_PROPERTY_NAME,
- null,
- notetypes,defaulttypes));
- Environment.userPropertyHandlers.put (Constants.PROJECT_STATUSES_PROPERTY_NAME,
- new UserPropertyHandler (Constants.PROJECT_STATUSES_PROPERTY_NAME,
- null,
- allprojects,defaultstatuses));
- Environment.userPropertyHandlers.put (Constants.TAGS_PROPERTY_NAME,
- new UserPropertyHandler (Constants.TAGS_PROPERTY_NAME,
- null,
- // Prevents the compiler whining...
- (String[]) null));
-
- try
- {
-
- Prompts.init ();
-
- } catch (Exception e)
- {
-
- Environment.logError ("Unable to init prompts",
- e);
-
- }
-
- try
- {
-
- RuleFactory.init ();
-
- } catch (Exception e)
- {
-
- Environment.logError ("Unable to init rule factory",
- e);
-
- }
-
- try
- {
-
- Environment.achievementsManager = new AchievementsManager ();
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to init achievements manager",
- e);
-
- }
-
- Environment.schedule (new Runnable ()
- {
-
- @Override
- public void run ()
- {
-
- try
- {
-
- Importer.init ();
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to init importer",
- e);
-
- }
-
- }
-
- },
- 1 * Constants.SEC_IN_MILLIS,
- -1);
-
- Environment.incrStartupProgress ();
-
- KeyboardFocusManager.getCurrentKeyboardFocusManager ().addKeyEventPostProcessor (new java.awt.KeyEventPostProcessor ()
- {
-
- public boolean postProcessKeyEvent (KeyEvent ev)
- {
-
- if (!(ev.getSource () instanceof JComponent))
- {
-
- return true;
-
- }
-
- final JComponent focused = (JComponent) ev.getSource ();
-
- Environment.scrollIntoView (focused);
-
- return true;
-
- }
- });
-
- try
- {
-
- // Get the user editor properties.
- com.gentlyweb.properties.Properties eprops = new com.gentlyweb.properties.Properties ();
-
- File edPropsFile = Environment.getUserEditorsPropertiesFile ();
-
- if (edPropsFile.exists ())
- {
-
- eprops = new com.gentlyweb.properties.Properties (edPropsFile,
- Environment.GZIP_EXTENSION);
-
- }
-
- eprops.setParentProperties (UserProperties.getProperties ());
-
- EditorsEnvironment.init (eprops);
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to init editors environment",
- e);
-
- }
-
- // Pre 2.4.
- // See if there is a projects.xml file, if so load the db.
- try
- {
-
- Environment.initProjectsDBFromProjectsFile ();
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to init project info from projects file",
- e);
-
- }
-
- if (Environment.isFirstUse)
- {
-
- Environment.isFirstUse = (Environment.getAllProjectInfos ().size () == 0);
-
- }
-
- Environment.targets = new TargetsData (UserProperties.getProperties ());
-
- Environment.addStartupProgressListener (new PropertyChangedListener ()
- {
-
- public void propertyChanged (PropertyChangedEvent ev)
- {
-
- if (Environment.isStartupComplete ())
- {
-
- Environment.userSession.start (new Date ());
-
- // See if we should be doing a warmup exercise.
- if (UserProperties.getAsBoolean (Constants.DO_WARMUP_ON_STARTUP_PROPERTY_NAME))
- {
-
- UIUtils.doLater (new ActionListener ()
- {
-
- public void actionPerformed (ActionEvent ev)
- {
-
- AbstractViewer viewer = Environment.getFocusedViewer ();
-
- if (viewer != null)
- {
-
- viewer.showWarmupPromptSelect ();
-
- viewer.fireProjectEvent (Warmup.OBJECT_TYPE,
- ProjectEvent.WARMUP_ON_STARTUP);
-
- }
-
- }
-
- });
-
- }
-
- Date d = new Date (System.currentTimeMillis () + (Constants.DAY_IN_MILLIS));
-
- d = Utils.zeroTimeFields (d);
-
- Environment.schedule (new Runnable ()
- {
-
- @Override
- public void run ()
- {
-
- try
- {
-
- Environment.projectInfoManager.addSession (Environment.userSession.createSnapshot ());
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to take session snapshot",
- e);
-
- }
-
- }
-
- },
- d.getTime (),
- // Run every 24 hours. It will drift over the days but not by much.
- Constants.DAY_IN_MILLIS);
-
- Environment.schedule (new Runnable ()
- {
-
- @Override
- public void run ()
- {
-
- java.util.List prefix = new ArrayList ();
- prefix.add (LanguageStrings.targets);
- prefix.add (LanguageStrings.types);
-
- Set met = new LinkedHashSet ();
- int sessWC = 0;
-
- try
- {
-
- if (!Environment.targets.isShowMessageWhenSessionTargetReached ())
- {
-
- return;
-
- }
-
- sessWC = Environment.userSession.getCurrentSessionWordCount ();
-
- // See if the user session has exceeded the session count.
- if ((sessWC >= Environment.targets.getMySessionWriting ())
- &&
- (Environment.userSession.shouldShowSessionTargetReachedPopup ())
- )
- {
-
- met.add (Environment.getUIString (prefix,
- LanguageStrings.session));
- //"Session");
-
- Environment.userSession.shownSessionTargetReachedPopup ();
-
- }
-
- } catch (Exception e) {
-
- Environment.logError ("Unable show session target reached popup",
- e);
-
- }
-
- // Check for the daily count.
- // Get all sessions for today.
- try
- {
-
- // The order is important here, the userSession check is cheaper
- // than the past sessions check since it doesn't require a db lookup.
- if ((Environment.userSession.shouldShowDailyTargetReachedPopup ())
- &&
- (Environment.getPastSessionsWordCount (0) >= Environment.targets.getMyDailyWriting ())
- )
- {
-
- met.add (Environment.getUIString (prefix,
- LanguageStrings.daily));
- //"Daily");
-
- Environment.userSession.shownDailyTargetReachedPopup ();
-
- }
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to get past session word counts",
- e);
-
- }
-
- // Get all sessions for this week.
- try
- {
-
- // We perform the cheap check here since it will prevent the extra work
- // with the calendar and db from having to be performed.
- if (Environment.userSession.shouldShowWeeklyTargetReachedPopup ())
- {
-
- GregorianCalendar gc = new GregorianCalendar ();
-
- int fd = gc.getFirstDayOfWeek ();
-
- int cd = gc.get (Calendar.DAY_OF_WEEK);
-
- int diff = cd - fd;
-
- if (diff < 0)
- {
-
- diff += 7;
-
- }
-
- if (Environment.getPastSessionsWordCount (diff) >= Environment.targets.getMyWeeklyWriting ())
- {
-
- met.add (Environment.getUIString (prefix,
- LanguageStrings.weekly));
- //"Weekly");
-
- Environment.userSession.shownWeeklyTargetReachedPopup ();
-
- }
-
- }
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to get past session word counts",
- e);
-
- }
-
- // Get all sessions for this month.
- try
- {
-
- // As above, do the cheap check first to prevent the extra work from
- // being done.
- if (Environment.userSession.shouldShowMonthlyTargetReachedPopup ())
- {
-
- GregorianCalendar gc = new GregorianCalendar ();
-
- int fd = gc.getFirstDayOfWeek ();
-
- int cd = gc.get (Calendar.DAY_OF_MONTH);
-
- int diff = cd - fd;
-
- if (Environment.getPastSessionsWordCount (diff) >= Environment.targets.getMyMonthlyWriting ())
- {
-
- AbstractViewer viewer = Environment.getFocusedViewer ();
-
- met.add (Environment.getUIString (prefix,
- LanguageStrings.monthly));
- //"Monthly");
-
- Environment.userSession.shownMonthlyTargetReachedPopup ();
-
- }
-
- }
-
- } catch (Exception e) {
-
- Environment.logError ("Unable to get past session word counts",
- e);
-
- }
-
- try
- {
-
- if (met.size () > 0)
- {
-
- StringBuilder b = new StringBuilder ();
-
- for (String m : met)
- {
-
- b.append (String.format ("