diff --git a/vmfedit/.gitignore b/vmfedit/.gitignore new file mode 100644 index 0000000..3a5b145 --- /dev/null +++ b/vmfedit/.gitignore @@ -0,0 +1,57 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Resources ### + +/node_modules/ +/src/main/resources/eu/mihosoft/vmf/vmfedit/fontawesome-free/ +/src/main/resources/eu/mihosoft/vmf/vmfedit/bootstrap/ +/src/main/resources/json-editor/ + +/package.json +/package-lock.json + + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store + + + + diff --git a/vmfedit/build.gradle b/vmfedit/build.gradle new file mode 100644 index 0000000..272c0ec --- /dev/null +++ b/vmfedit/build.gradle @@ -0,0 +1,123 @@ +plugins { + id 'application' + id 'org.openjfx.javafxplugin' version '0.0.13' + id 'org.beryx.jlink' version '2.25.0' + id 'com.github.node-gradle.node' version '3.3.0' +} + +group 'eu.mihosoft.vmf' +version '1.0.0-SNAPSHOT' + +// installer version (used for jlink/jpackge) +// parse version with three '.' separated numbers from full version string +def installerVersionList = version.tokenize('.') +def majorVersion = installerVersionList[0] +def minorVersion = installerVersionList[1] +// parse leading integer from patch version string (remove the rest) +def patchVersion = ((Number)java.text.NumberFormat.getInstance().parse(installerVersionList[2])).intValue() + +def installerVersionStr = "${majorVersion}.${minorVersion}.${patchVersion}" +def appName = "VMFEdit" + +repositories { + mavenCentral() +} + +ext { + junitVersion = '5.8.2' +} + +sourceCompatibility = '17' +targetCompatibility = '17' + +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' +} + +application { + mainModule = 'eu.mihosoft.vmf.vmfedit' + mainClass = 'eu.mihosoft.vmf.vmfedit.JsonEditorApplication' +} + +javafx { + version = '17.0.2' + modules = ['javafx.controls', 'javafx.fxml', 'javafx.web'] +} + +dependencies { + implementation('org.controlsfx:controlsfx:11.1.1') + + testImplementation("org.junit.jupiter:junit-jupiter-api:${junitVersion}") + testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:${junitVersion}") +} + +test { + useJUnitPlatform() +} + +ext.os = org.gradle.internal.os.OperatingSystem.current() +jlink { + version = installerVersionStr + imageZip = project.file("${buildDir}/distributions/app-${javafx.platform.classifier}.zip") + options = ['--strip-debug', "--compress=zip-6", '--no-header-files', '--no-man-pages'] + launcher { + name = appName + } + jpackage { + if(os.windows) { + installerType = 'msi' + installerOptions = ['--win-per-user-install', '--win-menu'] + } + } +} + + + +jlinkZip { + group = 'distribution' +} + +node { + version = '16.13.1' + download = true +} + +task installJsonEditor(type: NpmTask) { + args = ['install', '@json-editor/json-editor@2.15.1'] +} + +task copyJsonEditorToResources(type: Copy) { + from 'node_modules/@json-editor/json-editor/dist' + into 'src/main/resources/json-editor' + include '**/*' +} + +task installFontAwesome(type: NpmTask) { + args = ['install', '@fortawesome/fontawesome-free@5.15.4'] +} + +task copyFontAwesomeToResources(type: Copy) { + from 'node_modules/@fortawesome/fontawesome-free/' + into 'src/main/resources/eu/mihosoft/vmf/vmfedit/fontawesome-free' + include '**/*' +} + +task installBootStrap(type: NpmTask) { + args = ['install', 'bootstrap@5.3.3'] +} + +task copyBootStrapToResources(type: Copy) { + from 'node_modules/bootstrap/dist' + into 'src/main/resources/eu/mihosoft/vmf/vmfedit/bootstrap' + include '**/*' +} + + +copyJsonEditorToResources.dependsOn installJsonEditor +processResources.dependsOn copyJsonEditorToResources + +copyFontAwesomeToResources.dependsOn installFontAwesome +processResources.dependsOn copyFontAwesomeToResources + +copyBootStrapToResources.dependsOn installBootStrap +processResources.dependsOn copyBootStrapToResources \ No newline at end of file diff --git a/vmfedit/gradle/wrapper/gradle-wrapper.jar b/vmfedit/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/vmfedit/gradle/wrapper/gradle-wrapper.jar differ diff --git a/vmfedit/gradle/wrapper/gradle-wrapper.properties b/vmfedit/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..0d18421 --- /dev/null +++ b/vmfedit/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/vmfedit/gradlew b/vmfedit/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/vmfedit/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/vmfedit/gradlew.bat b/vmfedit/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/vmfedit/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/vmfedit/settings.gradle b/vmfedit/settings.gradle new file mode 100644 index 0000000..02a28c4 --- /dev/null +++ b/vmfedit/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "vmfedit" \ No newline at end of file diff --git a/vmfedit/src/main/java/eu/mihosoft/vmf/vmfedit/JsonEditorApplication.java b/vmfedit/src/main/java/eu/mihosoft/vmf/vmfedit/JsonEditorApplication.java new file mode 100644 index 0000000..1d19451 --- /dev/null +++ b/vmfedit/src/main/java/eu/mihosoft/vmf/vmfedit/JsonEditorApplication.java @@ -0,0 +1,31 @@ +package eu.mihosoft.vmf.vmfedit; + +import javafx.application.Application; +import javafx.fxml.FXMLLoader; +import javafx.scene.Node; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.stage.Stage; + +import java.io.IOException; + +public class JsonEditorApplication extends Application { + @Override + public void start(Stage stage) throws IOException { + FXMLLoader fxmlLoader = new FXMLLoader(JsonEditorApplication.class.getResource("json-editor-view.fxml")); + Parent n = fxmlLoader.load(); + + JsonEditorController controller = fxmlLoader.getController(); + + Scene scene = new Scene(n, 800, 600); + + stage.setTitle("VMF JSON Editor"); + stage.setScene(scene); + stage.show(); + + } + + public static void main(String[] args) { + launch(); + } +} \ No newline at end of file diff --git a/vmfedit/src/main/java/eu/mihosoft/vmf/vmfedit/JsonEditorController.java b/vmfedit/src/main/java/eu/mihosoft/vmf/vmfedit/JsonEditorController.java new file mode 100644 index 0000000..901f11c --- /dev/null +++ b/vmfedit/src/main/java/eu/mihosoft/vmf/vmfedit/JsonEditorController.java @@ -0,0 +1,261 @@ +package eu.mihosoft.vmf.vmfedit; + +import javafx.application.Platform; +import javafx.concurrent.Worker; +import javafx.fxml.FXML; +import javafx.scene.Scene; +import javafx.scene.control.Alert; +import javafx.scene.control.TextField; +import javafx.scene.web.WebEngine; +import javafx.scene.web.WebView; +import javafx.stage.FileChooser; +import javafx.stage.Stage; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.nio.file.Files; +import java.util.concurrent.CompletableFuture; + +public class JsonEditorController { + @FXML + private WebView webView; + @FXML + private TextField schemaField; + + private File currentFile; + + @FXML + public void initialize() { + WebEngine engine = webView.getEngine(); + + engine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> { + if (newValue == Worker.State.SUCCEEDED) { + System.out.println("Page loaded successfully"); + } else if (newValue == Worker.State.FAILED) { + System.out.println("Page failed to load"); + } + }); + + URL url = getClass().getResource("json-editor.html"); + if (url != null) { + System.out.println("Loading URL: " + url); + engine.load(url.toExternalForm()); + } else { + System.out.println("Could not find json-editor.html"); + } + + engine.setOnAlert(event -> System.out.println("JS Alert: " + event.getData())); + engine.setOnError(event -> System.out.println("JS Error: " + event.getMessage())); + + // on schemaField text change update schema + schemaField.textProperty().addListener((observable, oldValue, newValue) -> { + try { + String schema = new String(Files.readAllBytes(new File(newValue).toPath())); + // get current value from editor + String value = (String) webView.getEngine().executeScript("JSON.stringify(getValue())"); + System.out.println("Schema updated: value=" + value); + + // update schema and re-set value + webView.getEngine().executeScript("updateSchema('" + escapeJavaScript(schema) + "')"); + + if (value != null && !value.isEmpty() && !"\"\"".equals(value)) { + Thread.ofVirtual().start(() -> { + for (int i = 0; i < 10; i++) { + // attempt to set value + var future = new CompletableFuture(); + Platform.runLater(() -> { + try { + + // disable stage interaction via blurring the content + var scene = webView.getScene(); + scene.getRoot().setDisable(true); + + webView.getEngine().executeScript( + "setValue('" + escapeJavaScript(value) + "')"); + future.complete(true); + + // enable stage interaction + + } catch (Exception e) { + future.complete(false); + } finally { + var scene = webView.getScene(); + scene.getRoot().setDisable(false); + } + }); + + if(future.join()) { + break; + } else { +// System.out.println("Attempt " + i + " failed"); + } + try { + Thread.sleep(100); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + }); + + } + + } catch (IOException e) { + // showError("Error loading schema", e.getMessage()); + } + }); + + // make sure the WebView content does not keep focus, the JS code needs + // to be notified about focus changes, otherwise some user changes won't be + // applied correctly + webView.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> { + if (!isNowFocused) { + // Execute JavaScript to trigger a blur event inside the WebView + webView.getEngine().executeScript("document.activeElement.blur();"); + } + }); + + } + + @FXML + private void handleLoadDocument() { + FileChooser fileChooser = new FileChooser(); + fileChooser.setTitle("Open JSON Document"); + + if (currentFile != null) { + fileChooser.setInitialDirectory(currentFile.getParentFile()); + } + + FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("JSON files (*.json)", "*.json"); + fileChooser.getExtensionFilters().add(extFilter); + File file = fileChooser.showOpenDialog(webView.getScene().getWindow()); + if (file != null) { + try { + String content = new String(Files.readAllBytes(file.toPath())); + webView.getEngine().executeScript("setValue('" + escapeJavaScript(content) + "')"); + + currentFile = file; + // get stage and set title + Stage stage = (Stage) webView.getScene().getWindow(); + stage.setTitle("VMF JSON Editor - " + currentFile.getName()); + } catch (IOException e) { + showError("Error loading document", e.getMessage()); + } + } + } + + @FXML + private void handleSaveDocument() { + + if(currentFile != null) { + try { + String content = (String) webView.getEngine().executeScript("JSON.stringify(getValue())"); + System.out.println("Saving document: " + content); + Files.write(currentFile.toPath(), content.getBytes()); + + // get stage and set title + Stage stage = (Stage) webView.getScene().getWindow(); + stage.setTitle("VMF JSON Editor - " + currentFile.getName()); + + } catch (IOException e) { + showError("Error saving document", e.getMessage()); + } + return; + } else { + FileChooser fileChooser = new FileChooser(); + FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("JSON files (*.json)", "*.json"); + fileChooser.getExtensionFilters().add(extFilter); + fileChooser.setTitle("Save JSON Document"); + File file = fileChooser.showSaveDialog(webView.getScene().getWindow()); + if (file != null) { + try { + String content = (String) webView.getEngine().executeScript("JSON.stringify(getValue())"); + System.out.println("Saving document: " + content); + Files.write(file.toPath(), content.getBytes()); + + currentFile = file; + // get stage and set title + Stage stage = (Stage) webView.getScene().getWindow(); + stage.setTitle("VMF JSON Editor - " + currentFile.getName()); + + } catch (IOException e) { + showError("Error saving document", e.getMessage()); + } + } + } + } + + @FXML + private void handleSaveAsDocument() { + FileChooser fileChooser = new FileChooser(); + + if (currentFile != null) { + fileChooser.setInitialDirectory(currentFile.getParentFile()); + } + + FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("JSON files (*.json)", "*.json"); + fileChooser.getExtensionFilters().add(extFilter); + fileChooser.setTitle("Save JSON Document as"); + File file = fileChooser.showSaveDialog(webView.getScene().getWindow()); + + if (file != null) { + try { + String content = (String) webView.getEngine().executeScript("JSON.stringify(getValue())"); + System.out.println("Saving document as: " + content); + Files.write(file.toPath(), content.getBytes()); + + currentFile = file; + // get stage and set title + Stage stage = (Stage) webView.getScene().getWindow(); + stage.setTitle("VMF JSON Editor - " + currentFile.getName()); + + } catch (IOException e) { + showError("Error saving document", e.getMessage()); + } + } + } + + @FXML + private void handleQuit() { + System.exit(0); + } + + @FXML + private void handleBrowseSchema() { + + FileChooser fileChooser = new FileChooser(); + + // set current directory from schemaField + File currentDir = new File(schemaField.getText()).getParentFile(); + if (currentDir != null) { + fileChooser.setInitialDirectory(currentDir); + } else { + // + } + + fileChooser.setTitle("Open JSON Schema"); + // set json extension filter + FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("JSON Schema files (*.json)", "*.json"); + fileChooser.getExtensionFilters().add(extFilter); + File file = fileChooser.showOpenDialog(webView.getScene().getWindow()); + if (file != null) { + schemaField.setText(file.getAbsolutePath()); + } + } + + private String escapeJavaScript(String str) { + return str.replace("\\", "\\\\") + .replace("'", "\\'") + .replace("\n", "\\n") + .replace("\r", "\\r") + .replace("\t", "\\t"); + } + + private void showError(String title, String message) { + Alert alert = new Alert(Alert.AlertType.ERROR); + alert.setTitle("Error"); + alert.setHeaderText(title); + alert.setContentText(message); + alert.showAndWait(); + } +} \ No newline at end of file diff --git a/vmfedit/src/main/java/module-info.java b/vmfedit/src/main/java/module-info.java new file mode 100644 index 0000000..dae2244 --- /dev/null +++ b/vmfedit/src/main/java/module-info.java @@ -0,0 +1,8 @@ +module eu.mihosoft.vmf.vmfedit { + requires javafx.controls; + requires javafx.fxml; + requires javafx.web; + + opens eu.mihosoft.vmf.vmfedit to javafx.fxml; + exports eu.mihosoft.vmf.vmfedit; +} \ No newline at end of file diff --git a/vmfedit/src/main/resources/eu/mihosoft/vmf/vmfedit/json-editor-view.fxml b/vmfedit/src/main/resources/eu/mihosoft/vmf/vmfedit/json-editor-view.fxml new file mode 100644 index 0000000..57260d0 --- /dev/null +++ b/vmfedit/src/main/resources/eu/mihosoft/vmf/vmfedit/json-editor-view.fxml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vmfedit/src/main/resources/eu/mihosoft/vmf/vmfedit/json-editor.html b/vmfedit/src/main/resources/eu/mihosoft/vmf/vmfedit/json-editor.html new file mode 100644 index 0000000..1c03766 --- /dev/null +++ b/vmfedit/src/main/resources/eu/mihosoft/vmf/vmfedit/json-editor.html @@ -0,0 +1,102 @@ + + + + + + + + + + + + + + JSON Editor + + + + +
+ + + \ No newline at end of file