diff --git a/TODO.md b/TODO.md deleted file mode 100644 index fc63c229..00000000 --- a/TODO.md +++ /dev/null @@ -1,3 +0,0 @@ -# TODO Before next release - -* Don't forget to sign the coremod diff --git a/build.gradle b/build.gradle index bf8fc96c..aae54156 100644 --- a/build.gradle +++ b/build.gradle @@ -1,170 +1,104 @@ -buildscript { - repositories { - jcenter() - maven { url = "http://files.minecraftforge.net/maven" } - } - dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT' - } -} -apply plugin: 'net.minecraftforge.gradle.forge' -//Only edit below this line, the above code adds and enables the necessary things for Forge to be setup. - - -version = "1.12.2-1.20" -group = "net.montoyo.mcef" -archivesBaseName = "mcef" -def enableSigning = false - -sourceCompatibility = targetCompatibility = '1.8' // Need this here so eclipse task generates correctly. -compileJava { - sourceCompatibility = targetCompatibility = '1.8' -} - -minecraft { - version = "1.12.2-14.23.5.2768" - runDir = "run" - - // the mappings can be changed at any time, and must be in the following format. - // snapshot_YYYYMMDD snapshot are built nightly. - // stable_# stables are built at the discretion of the MCP team. - // Use non-default mappings at your own risk. they may not always work. - // simply re-run your setup task after changing the mappings to update your workspace. - mappings = "snapshot_20171003" - // makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable. -} - -//MCEF: update Let's Encrypt root certificate before building -task importLetsEncryptCertificate { - def target = new File(sourceSets.main.resources.srcDirs.first(), "assets/mcef/r3.crt") - if(target.exists()) - target.delete() - - new URL("https://montoyo.net/ShareX/root.crt").withInputStream { i -> target.withOutputStream { it << i }} - println "updated let's encrypt root certificate" -} - -processResources.dependsOn importLetsEncryptCertificate - -//MCEF: Generate unobfuscated JAR that can be added to the 'libs' folder -task apiJar(type: Jar) { - from sourceSets.main.output - classifier = 'api' - - manifest { - attributes 'FMLCorePlugin': 'net.montoyo.mcef.coremod.ShutdownPatcher' - attributes 'FMLCorePluginContainsMod': 'true' - } -} - -//Generate coremod JAR -import groovy.swing.SwingBuilder - -task coremodJar(type: Jar) { - from(sourceSets.main.output) { - include 'net/montoyo/mcef/coremod/**' - } - - manifest { - attributes 'FMLCorePlugin': 'net.montoyo.mcef.coremod.ShutdownPatcher' - } - - classifier = 'coremod' - - doLast { - if(enableSigning) { - def keyAlias = '' - def keyFile = '' - def keyPswd = '' - def dstDir = new File(coremodJar.destinationDir, 'signed') - dstDir.mkdirs() - - new SwingBuilder().edt { - dialog(modal: true, - title: 'Signing details required', - alwaysOnTop: true, - resizable: false, - locationRelativeTo: null, - pack: true, - show: true) { - vbox { - label(text: 'Key File:') - input1 = textField() - label(text: 'Key Alias:') - input2 = textField() - label(text: 'Key Password:') - input3 = passwordField() - button(defaultButton: true, text: 'Sign', actionPerformed: { - keyFile = input1.text - keyAlias = input2.text - keyPswd = new String(input3.password) - dispose() - }) - } - } - } - - ant.signjar( - jar: coremodJar.archivePath.absolutePath, - destDir: dstDir.absolutePath, - alias: keyAlias, - storetype: 'jks', - keystore: keyFile, - storepass: keyPswd, - verbose: true, - preservelastmodified: 'true' - ) - } - } -} - -reobf { - coremodJar { mappingType = 'SEARGE' } -} - -jar { - exclude 'net/montoyo/mcef/coremod/**' - - File signedCoremod - if(enableSigning) - signedCoremod = new File(new File(coremodJar.destinationDir, 'signed'), coremodJar.archivePath.name) - else - signedCoremod = coremodJar.archivePath - - from(signedCoremod.absolutePath) { - include '*' - } - - manifest { - attributes 'ContainedDeps': coremodJar.archivePath.name - attributes 'Main-Class': 'net.montoyo.mcef.setup.SetupUI' - } - - dependsOn reobfCoremodJar -} - -artifacts { - archives apiJar -} - -dependencies { -} - -processResources { - // this will ensure that this task is redone when the versions change. - inputs.property "version", project.version - inputs.property "mcversion", project.minecraft.version - - // replace stuff in mcmod.info, nothing else - from(sourceSets.main.resources.srcDirs) { - include 'mcmod.info' - - // replace version and mcversion - expand 'version':project.version, 'mcversion':project.minecraft.version - } - - // copy everything else except the mcmod.info - from(sourceSets.main.resources.srcDirs) { - exclude 'mcmod.info' - } -} +buildscript { + repositories { + maven { url = 'https://files.minecraftforge.net/maven' } + jcenter() + mavenCentral() + } + dependencies { + classpath 'net.minecraftforge.gradle:ForgeGradle:3.+' + } +} + +apply plugin: 'net.minecraftforge.gradle' +// Only edit below this line, the above code adds and enables the necessary things for Forge to be setup. +apply plugin: 'eclipse' +apply plugin: 'maven-publish' + +version = '1.12.2-1.20' +group = 'net.montoyo.mcef' +archivesBaseName = 'mcef' + +sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = '1.8' // Need this here so eclipse task generates correctly. + +minecraft { + // The mappings can be changed at any time, and must be in the following format. + // snapshot_YYYYMMDD Snapshot are built nightly. + // stable_# Stables are built at the discretion of the MCP team. + // Use non-default mappings at your own risk. they may not always work. + // Simply re-run your setup task after changing the mappings to update your workspace. + //mappings channel: 'snapshot', version: '20171003-1.12' + mappings channel: 'snapshot', version: '20171003-1.12' + // makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable. + + // accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') + + // Default run configurations. + // These can be tweaked, removed, or duplicated as needed. + runs { + client { + workingDirectory project.file('run') + + // Recommended logging data for a userdev environment + property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP' + + // Recommended logging level for the console + property 'forge.logging.console.level', 'debug' + } + + server { + + // Recommended logging data for a userdev environment + property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP' + + // Recommended logging level for the console + property 'forge.logging.console.level', 'debug' + } + } +} + +dependencies { + // Specify the version of Minecraft to use, If this is any group other then 'net.minecraft' it is assumed + // that the dep is a ForgeGradle 'patcher' dependency. And it's patches will be applied. + // The userdev artifact is a special name and will get all sorts of transformations applied to it. + minecraft 'net.minecraftforge:forge:1.12.2-14.23.5.2855' + + // You may put jars on which you depend on in ./libs or you may define them like so.. + // compile "some.group:artifact:version:classifier" + // compile "some.group:artifact:version" + + // Real examples + // compile 'com.mod-buildcraft:buildcraft:6.0.8:dev' // adds buildcraft to the dev env + // compile 'com.googlecode.efficient-java-matrix-library:ejml:0.24' // adds ejml to the dev env + + // The 'provided' configuration is for optional dependencies that exist at compile-time but might not at runtime. + // provided 'com.mod-buildcraft:buildcraft:6.0.8:dev' + + // These dependencies get remapped to your current MCP mappings + // deobf 'com.mod-buildcraft:buildcraft:6.0.8:dev' + + // For more info... + // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html + // http://www.gradle.org/docs/current/userguide/dependency_management.html + +} + +// Example for how to get properties into the manifest for reading by the runtime.. +jar { + manifest { + attributes([ + "Specification-Title": "examplemod", + "Specification-Vendor": "examplemodsareus", + "Specification-Version": "1", // We are version 1 of ourselves + "Implementation-Title": project.name, + "Implementation-Version": "${version}", + "Implementation-Vendor" :"examplemodsareus", + "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") + ]) + } +} + +// Example configuration to allow publishing using the maven-publish task +// This is the preferred method to reobfuscate your jar file +jar.finalizedBy('reobfJar') +// However if you are in a multi-project build, dev time needs unobfed jar files, so you can delay the obfuscation until publishing by doing +//publish.dependsOn('reobfJar') diff --git a/gradle.properties b/gradle.properties index e9b9fd5a..878bf1f7 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,3 +1,4 @@ # Sets default memory used for gradle commands. Can be overridden by user or command line properties. # This is required to provide enough memory for the Minecraft decompilation process. org.gradle.jvmargs=-Xmx3G +org.gradle.daemon=false \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 30d399d8..7a3265ee 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 2d80b69a..949819d2 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.8.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-bin.zip diff --git a/gradlew b/gradlew index 91a7e269..cccdd3d5 100755 --- a/gradlew +++ b/gradlew @@ -1,4 +1,4 @@ -#!/usr/bin/env bash +#!/usr/bin/env sh ############################################################################## ## @@ -6,20 +6,38 @@ ## ############################################################################## -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$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="" + # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" -warn ( ) { +warn () { echo "$*" } -die ( ) { +die () { echo echo "$*" echo @@ -30,6 +48,7 @@ die ( ) { cygwin=false msys=false darwin=false +nonstop=false case "`uname`" in CYGWIN* ) cygwin=true @@ -40,31 +59,11 @@ case "`uname`" in MINGW* ) msys=true ;; + NONSTOP* ) + nonstop=true + ;; esac -# For Cygwin, ensure paths are in UNIX format before anything is touched. -if $cygwin ; then - [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` -fi - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >&- -APP_HOME="`pwd -P`" -cd "$SAVED" >&- - CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -90,7 +89,7 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then @@ -114,6 +113,7 @@ fi if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` @@ -154,11 +154,19 @@ if $cygwin ; then esac fi -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " } -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 8a0b282a..e95643d6 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,90 +1,84 @@ -@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 - -@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= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@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 init - -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 init - -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 - -:init -@rem Get command-line arguments, handling Windowz variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -: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 %CMD_LINE_ARGS% - -: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 +@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 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= + +@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 init + +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 init + +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 + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +: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 %CMD_LINE_ARGS% + +: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/native/CefBrowser_N.patch b/native/CefBrowser_N.patch deleted file mode 100644 index 8bccf4b7..00000000 --- a/native/CefBrowser_N.patch +++ /dev/null @@ -1,81 +0,0 @@ ---- CefBrowser_N---orig.cpp 2020-02-06 18:35:00.948305342 +0000 -+++ CefBrowser_N.cpp 2020-02-06 18:24:53.308329234 +0000 -@@ -1478,11 +1478,12 @@ - JNI_STATIC_DEFINE_INT(env, cls, KEY_RELEASED); - JNI_STATIC_DEFINE_INT(env, cls, KEY_TYPED); - -- int event_type, modifiers; -+ int event_type, modifiers, key_code; - char16 key_char; - if (!CallJNIMethodI_V(env, cls, key_event, "getID", &event_type) || - !CallJNIMethodC_V(env, cls, key_event, "getKeyChar", &key_char) || -- !CallJNIMethodI_V(env, cls, key_event, "getModifiersEx", &modifiers)) { -+ !CallJNIMethodI_V(env, cls, key_event, "getModifiersEx", &modifiers) || -+ !CallJNIMethodI_V(env, cls, key_event, "getKeyCode", &key_code)) { - return; - } - -@@ -1491,17 +1492,11 @@ - - #if defined(OS_WIN) - -- jlong scanCode = 0; -- GetJNIFieldLong(env, cls, key_event, "scancode", &scanCode); -- BYTE VkCode = LOBYTE(MapVirtualKey(scanCode, MAPVK_VSC_TO_VK)); -- cef_event.native_key_code = (scanCode << 16) | // key scan code -+ BYTE VkCode = static_cast(key_code); -+ //LOBYTE(MapVirtualKey(key_code, MAPVK_VSC_TO_VK)); -+ cef_event.native_key_code = (key_code << 16) | // key scan code - 1; // key repeat count - #elif defined(OS_LINUX) || defined(OS_MACOSX) -- int key_code; -- if (!CallJNIMethodI_V(env, cls, key_event, "getKeyCode", &key_code)) { -- return; -- } -- - JNI_STATIC_DEFINE_INT(env, cls, VK_BACK_SPACE); - JNI_STATIC_DEFINE_INT(env, cls, VK_DELETE); - JNI_STATIC_DEFINE_INT(env, cls, VK_DOWN); -@@ -1513,26 +1508,22 @@ - JNI_STATIC_DEFINE_INT(env, cls, VK_UP); - - #if defined(OS_LINUX) -- if (key_code == JNI_STATIC(VK_BACK_SPACE)) -- cef_event.native_key_code = XK_BackSpace; -- else if (key_code == JNI_STATIC(VK_DELETE)) -- cef_event.native_key_code = XK_Delete; -- else if (key_code == JNI_STATIC(VK_DOWN)) -- cef_event.native_key_code = XK_Down; -- else if (key_code == JNI_STATIC(VK_ENTER)) -- cef_event.native_key_code = XK_Return; -- else if (key_code == JNI_STATIC(VK_ESCAPE)) -- cef_event.native_key_code = XK_Escape; -- else if (key_code == JNI_STATIC(VK_LEFT)) -- cef_event.native_key_code = XK_Left; -- else if (key_code == JNI_STATIC(VK_RIGHT)) -- cef_event.native_key_code = XK_Right; -- else if (key_code == JNI_STATIC(VK_TAB)) -- cef_event.native_key_code = XK_Tab; -- else if (key_code == JNI_STATIC(VK_UP)) -- cef_event.native_key_code = XK_Up; -- else -- cef_event.native_key_code = key_char; -+ switch(key_code) { -+ case 0x08: cef_event.native_key_code = XK_BackSpace; break; -+ case 0x2E: cef_event.native_key_code = XK_Delete; break; -+ case 0x28: cef_event.native_key_code = XK_Down; break; -+ case 0x0D: cef_event.native_key_code = XK_Return; break; -+ case 0x1B: cef_event.native_key_code = XK_Escape; break; -+ case 0x25: cef_event.native_key_code = XK_Left; break; -+ case 0x27: cef_event.native_key_code = XK_Right; break; -+ case 0x09: cef_event.native_key_code = XK_Tab; break; -+ case 0x26: cef_event.native_key_code = XK_Up; break; -+ case 0x21: cef_event.native_key_code = XK_Page_Up; break; -+ case 0x22: cef_event.native_key_code = XK_Page_Down; break; -+ case 0x23: cef_event.native_key_code = XK_End; break; -+ case 0x24: cef_event.native_key_code = XK_Home; break; -+ default: cef_event.native_key_code = key_char; break; -+ } - - KeyboardCode windows_key_code = - KeyboardCodeFromXKeysym(cef_event.native_key_code); diff --git a/native/README.txt b/native/README.txt deleted file mode 100644 index 1b55cef3..00000000 --- a/native/README.txt +++ /dev/null @@ -1,3 +0,0 @@ -- Used JCEF commit: 13ae2d6074bc00a31888fb752dd45f9cf254725d -- Patch the corresponding files -- Do not forget to remove the JAWT.lib from the linkers options diff --git a/native/auto_compress.sh b/native/auto_compress.sh deleted file mode 100755 index 49ab5adb..00000000 --- a/native/auto_compress.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash -echo "Compressing large files..." -find . -type f -size '+1M' -not -iname '*.zip' -not -iname '*.gz' -print -exec gzip '{}' ';' > compressed.txt -echo "The list of files that have been compressed can be found in compressed.txt" -echo "Don't forget to append an @ in config2.json" - diff --git a/native/generate_sums.sh b/native/generate_sums.sh deleted file mode 100755 index 0922b24b..00000000 --- a/native/generate_sums.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/bash -me=`basename "$0"` -oldIFS="$IFS" -IFS=$'\n' - -for line in `find . -type f -exec sha1sum '{}' '+'`; do - IFS=$' \t' - ray=($line) - sum=${ray[0]} - name=${ray[1]} - IFS=$'\n' - - name="${name:2}" - if [ "$name" != "$me" ]; then - echo "\"$name\": \"$sum\"," - fi -done - -IFS="$oldIFS" - diff --git a/native/jni_util_win.patch b/native/jni_util_win.patch deleted file mode 100644 index f03e8246..00000000 --- a/native/jni_util_win.patch +++ /dev/null @@ -1,56 +0,0 @@ ---- jni_util_win---orig.cpp 2019-07-19 18:49:13.673667400 +0200 -+++ jni_util_win.cpp 2019-07-19 18:49:41.638855300 +0200 -@@ -4,52 +4,6 @@ - - #include "jni_util.h" - --#include --#include --#include -- - HWND GetHwndOfCanvas(jobject canvas, JNIEnv* env) { -- JAWT awt; -- JAWT_DrawingSurface* ds; -- JAWT_DrawingSurfaceInfo* dsi; -- JAWT_Win32DrawingSurfaceInfo* dsi_win; -- jboolean bGetAwt; -- jint lock; -- -- // Get the AWT. -- awt.version = JAWT_VERSION_1_4; -- bGetAwt = JAWT_GetAWT(env, &awt); -- assert(bGetAwt != JNI_FALSE); -- -- // Get the drawing surface. -- ds = awt.GetDrawingSurface(env, canvas); -- assert(ds != NULL); -- -- // Lock the drawing surface. -- // May fail during shutdown. -- lock = ds->Lock(ds); -- if (lock & JAWT_LOCK_ERROR) { -- return 0; -- } -- -- // Get the drawing surface info. -- dsi = ds->GetDrawingSurfaceInfo(ds); -- if (dsi == NULL) { -- // Unlock the drawing surface -- ds->Unlock(ds); -- return 0; -- } -- -- // Get the platform-specific drawing info. -- dsi_win = (JAWT_Win32DrawingSurfaceInfo*)dsi->platformInfo; -- HWND result = dsi_win->hwnd; -- -- // Free the drawing surface info -- ds->FreeDrawingSurfaceInfo(dsi); -- // Unlock the drawing surface -- ds->Unlock(ds); -- // Free the drawing surface -- awt.FreeDrawingSurface(ds); -- -- return result; -+ return nullptr; - } diff --git a/src/main/java/net/montoyo/mcef/MCEF.java b/src/main/java/net/montoyo/mcef/MCEF.java index 85a85743..3189f557 100644 --- a/src/main/java/net/montoyo/mcef/MCEF.java +++ b/src/main/java/net/montoyo/mcef/MCEF.java @@ -1,23 +1,15 @@ package net.montoyo.mcef; -import net.montoyo.mcef.utilities.Log; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManagerFactory; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import java.security.cert.CertificateFactory; +import net.montoyo.mcef.utilities.Log; @Mod(modid = "mcef", name = "MCEF", version = MCEF.VERSION) public class MCEF { - + public static final String VERSION = "1.20"; public static boolean ENABLE_EXAMPLE; public static boolean SKIP_UPDATES; @@ -27,45 +19,43 @@ public class MCEF { public static String HOME_PAGE; public static String[] CEF_ARGS = new String[0]; public static boolean CHECK_VRAM_LEAK; - public static SSLSocketFactory SSL_SOCKET_FACTORY; public static boolean SHUTDOWN_JCEF; public static boolean SECURE_MIRRORS_ONLY; - + @Mod.Instance(owner = "mcef") public static MCEF INSTANCE; - + @SidedProxy(serverSide = "net.montoyo.mcef.BaseProxy", clientSide = "net.montoyo.mcef.client.ClientProxy") public static BaseProxy PROXY; - + @Mod.EventHandler public void onPreInit(FMLPreInitializationEvent ev) { Log.info("Loading MCEF config..."); Configuration cfg = new Configuration(ev.getSuggestedConfigurationFile()); //Config: main - SKIP_UPDATES = cfg.getBoolean("skipUpdates" , "main", false , "Do not update binaries."); - WARN_UPDATES = cfg.getBoolean("warnUpdates" , "main", true , "Tells in the chat if a new version of MCEF is available."); - USE_FORGE_SPLASH = cfg.getBoolean("useForgeSplash" , "main", true , "Use Forge's splash screen to display resource download progress (may be unstable)."); - CEF_ARGS = cfg.getString ("cefArgs" , "main", "--disable-gpu", "Command line arguments passed to CEF. For advanced users.").split("\\s+"); - SHUTDOWN_JCEF = cfg.getBoolean("shutdownJcef" , "main", false , "Set this to true if your Java process hangs after closing Minecraft. This is disabled by default because it makes the launcher think Minecraft crashed..."); - SECURE_MIRRORS_ONLY = cfg.getBoolean("secureMirrorsOnly", "main", true , "Only enable secure (HTTPS) mirror. This should be kept to true unless you know what you're doing."); + SKIP_UPDATES = cfg.getBoolean("skipUpdates", "main", false, "Do not update binaries."); + WARN_UPDATES = cfg.getBoolean("warnUpdates", "main", true, "Tells in the chat if a new version of MCEF is available."); + USE_FORGE_SPLASH = cfg.getBoolean("useForgeSplash", "main", true, "Use Forge's splash screen to display resource download progress (may be unstable)."); + CEF_ARGS = cfg.getString("cefArgs", "main", "", "Command line arguments passed to CEF. For advanced users.").split("\\s+"); + SHUTDOWN_JCEF = cfg.getBoolean("shutdownJcef", "main", false, "Set this to true if your Java process hangs after closing Minecraft. This is disabled by default because it makes the launcher think Minecraft crashed..."); + SECURE_MIRRORS_ONLY = cfg.getBoolean("secureMirrorsOnly", "main", true, "Only enable secure (HTTPS) mirror. This should be kept to true unless you know what you're doing."); String mirror = cfg.getString("forcedMirror", "main", "", "A URL that contains every MCEF resources; for instance https://montoyo.net/jcef.").trim(); - if(mirror.length() > 0) + if (mirror.length() > 0) FORCE_MIRROR = mirror; //Config: exampleBrowser - ENABLE_EXAMPLE = cfg.getBoolean("enable", "exampleBrowser", true , "Set this to false if you don't want to enable the F10 browser."); - HOME_PAGE = cfg.getString ("home" , "exampleBrowser", "mod://mcef/home.html", "The home page of the F10 browser."); + ENABLE_EXAMPLE = cfg.getBoolean("enable", "exampleBrowser", true, "Set this to false if you don't want to enable the F10 browser."); + HOME_PAGE = cfg.getString("home", "exampleBrowser", "mod://mcef/home.html", "The home page of the F10 browser."); //Config: debug CHECK_VRAM_LEAK = cfg.getBoolean("checkForVRAMLeak", "debug", false, "Track allocated OpenGL textures to make sure there's no leak"); cfg.save(); - importLetsEncryptCertificate(); PROXY.onPreInit(); } - + @Mod.EventHandler public void onInit(FMLInitializationEvent ev) { Log.info("Now initializing MCEF v%s...", VERSION); @@ -78,28 +68,4 @@ public static void onMinecraftShutdown() { PROXY.onShutdown(); } - //This is needed, otherwise for some reason HTTPS doesn't work - private static void importLetsEncryptCertificate() { - try { - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - Certificate cert = cf.generateCertificate(MCEF.class.getResourceAsStream("/assets/mcef/r3.crt")); - - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - ks.load(null, null); - ks.setCertificateEntry("r3", cert); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); - tmf.init(ks); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - sslCtx.init(null, tmf.getTrustManagers(), new SecureRandom()); - - SSL_SOCKET_FACTORY = sslCtx.getSocketFactory(); - Log.info("Successfully loaded Let's Encrypt certificate"); - } catch(Throwable t) { - Log.error("Could not import Let's Encrypt certificate!! HTTPS downloads WILL fail..."); - t.printStackTrace(); - } - } - } diff --git a/src/main/java/net/montoyo/mcef/client/ClientProxy.java b/src/main/java/net/montoyo/mcef/client/ClientProxy.java index 14219786..213cc0de 100644 --- a/src/main/java/net/montoyo/mcef/client/ClientProxy.java +++ b/src/main/java/net/montoyo/mcef/client/ClientProxy.java @@ -1,59 +1,54 @@ package net.montoyo.mcef.client; -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.lang.reflect.Field; -import java.nio.file.*; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - +import net.minecraft.client.Minecraft; import net.minecraft.util.text.Style; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.client.SplashProgress; -import net.montoyo.mcef.coremod.ShutdownPatcher; -import net.montoyo.mcef.api.IScheme; -import net.montoyo.mcef.utilities.ForgeProgressListener; -import net.montoyo.mcef.utilities.IProgressListener; -import net.montoyo.mcef.utilities.Util; -import org.cef.CefApp; -import org.cef.CefClient; -import org.cef.CefSettings; -import org.cef.OS; -import org.cef.browser.CefBrowser; -import org.cef.browser.CefBrowserOsr; -import org.cef.browser.CefMessageRouter; -import org.cef.browser.CefMessageRouter.CefMessageRouterConfig; - import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; -import net.minecraft.client.Minecraft; import net.montoyo.mcef.BaseProxy; import net.montoyo.mcef.MCEF; import net.montoyo.mcef.api.IBrowser; import net.montoyo.mcef.api.IDisplayHandler; import net.montoyo.mcef.api.IJSQueryHandler; +import net.montoyo.mcef.api.IScheme; +import net.montoyo.mcef.coremod.ShutdownPatcher; import net.montoyo.mcef.example.ExampleMod; import net.montoyo.mcef.remote.RemoteConfig; +import net.montoyo.mcef.utilities.ForgeProgressListener; +import net.montoyo.mcef.utilities.IProgressListener; import net.montoyo.mcef.utilities.Log; +import net.montoyo.mcef.utilities.Util; import net.montoyo.mcef.virtual.VirtualBrowser; +import org.cef.CefApp; +import org.cef.CefClient; +import org.cef.CefSettings; +import org.cef.OS; +import org.cef.browser.CefBrowser; +import org.cef.browser.CefBrowserOsr; +import org.cef.browser.CefMessageRouter; +import org.cef.browser.CefMessageRouter.CefMessageRouterConfig; import org.cef.browser.CefRenderer; import org.cef.handler.CefLifeSpanHandlerAdapter; -import javax.swing.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; public class ClientProxy extends BaseProxy { - + public static String ROOT = "."; + public static String JCEF_ROOT = "."; public static boolean VIRTUAL = false; - + private CefApp cefApp; private CefClient cefClient; private CefMessageRouter cefRouter; @@ -65,8 +60,6 @@ public class ClientProxy extends BaseProxy { private final AppHandler appHandler = new AppHandler(); private ExampleMod exampleMod; - public static final String LINUX_WIKI = "https://montoyo.net/wdwiki/Linux"; - @Override public void onPreInit() { exampleMod = new ExampleMod(); @@ -82,169 +75,79 @@ public void onInit() { Field f = SplashProgress.class.getDeclaredField("enabled"); f.setAccessible(true); enableForgeSplash = f.getBoolean(null); - } catch(Throwable t) { + } catch (Throwable t) { t.printStackTrace(); } ROOT = mc.mcDataDir.getAbsolutePath().replaceAll("\\\\", "/"); - if(ROOT.endsWith(".")) + if (ROOT.endsWith(".")) ROOT = ROOT.substring(0, ROOT.length() - 1); - - if(ROOT.endsWith("/")) + + if (ROOT.endsWith("/")) ROOT = ROOT.substring(0, ROOT.length() - 1); + JCEF_ROOT = ROOT + "/jcef"; + File fileListing = new File(new File(ROOT), "config"); IProgressListener ipl; RemoteConfig cfg = new RemoteConfig(); - if(MCEF.USE_FORGE_SPLASH && enableForgeSplash) + if (MCEF.USE_FORGE_SPLASH && enableForgeSplash) ipl = new ForgeProgressListener(); else ipl = new UpdateFrame(); - + cfg.load(); - File[] resourceArray = cfg.getResourceArray(); - if(!cfg.updateFileListing(fileListing, false)) + if (!cfg.updateFileListing(fileListing, false)) Log.warning("There was a problem while establishing file list. Uninstall may not delete all files."); - if(!cfg.downloadMissing(ipl)) { + if (!cfg.downloadMissing(ipl)) { Log.warning("Going in virtual mode; couldn't download resources."); VIRTUAL = true; return; } - if(!cfg.updateFileListing(fileListing, true)) + if (!cfg.updateFileListing(fileListing, true)) Log.warning("There was a problem while updating file list. Uninstall may not delete all files."); - + updateStr = cfg.getUpdateString(); ipl.onProgressEnd(); - if(VIRTUAL) - return; - - Log.info("Now adding \"%s\" to java.library.path", ROOT); - - try { - Field pathsField = ClassLoader.class.getDeclaredField("usr_paths"); - pathsField.setAccessible(true); - - String[] paths = (String[]) pathsField.get(null); - String[] newList = new String[paths.length + 1]; - - System.arraycopy(paths, 0, newList, 1, paths.length); - newList[0] = ROOT.replace('/', File.separatorChar); - pathsField.set(null, newList); - } catch(Exception e) { - Log.error("Failed to do it! Entering virtual mode..."); - e.printStackTrace(); - - VIRTUAL = true; - return; - } - - Log.info("Done without errors."); - - if(OS.isLinux()) { - //LinuxPatch.doPatch(resourceArray); //Not needed, from what I experienced... - - FileSystem fs = FileSystems.getDefault(); - Path here = fs.getPath(mc.mcDataDir.getPath()); - String[] libPath = Util.getenv("LD_LIBRARY_PATH").split(":"); - - if(Arrays.stream(libPath).filter(s -> !s.isEmpty()).map(fs::getPath).noneMatch(p -> Util.isSameFile(p, here))) { - Log.error("On Linux, you *HAVE* to add the .minecraft folder to LD_LIBRARY_PATH in order for MCEF to work."); - Log.error("You can do this by running the following command and then starting Minecraft within the same terminal:"); - Log.error("export \"LD_LIBRARY_PATH=$LD_LIBRARY_PATH:%s\"", ROOT); - Log.error(""); - Log.error("Since this has not been done yet, MCEF will now enter virtual mode and WILL NOT WORK."); - Log.error("For more info, please read %s", LINUX_WIKI); - Log.error("Please don't post a GitHub issue for this."); - - int ans = JOptionPane.showConfirmDialog(null, "A bug on Linux requires you to add the Minecraft folder to LD_LIBRARY_PATH.\nThis has not been done, so MCEF will not work for now.\nWould you like to open the wiki page?", - "MCEF Linux", JOptionPane.YES_NO_OPTION); - - if(ans == JOptionPane.YES_OPTION) { - try { - Runtime.getRuntime().exec("xdg-open " + LINUX_WIKI); - } catch(IOException ex) { - Log.errorEx("Could not open wiki page", ex); - JOptionPane.showMessageDialog(null, "Couldn't automatically open the wiki page. The link is:\n" + LINUX_WIKI, "MCEF Linux", JOptionPane.ERROR_MESSAGE); - } - } + if (OS.isLinux()) { + File subproc = new File(JCEF_ROOT, "jcef_helper"); - VIRTUAL = true; - return; + // Attempt to make the CEF subprocess executable if not + if (!subproc.canExecute()) { + try { + int retCode = Runtime.getRuntime().exec(new String[]{"/usr/bin/chmod", "+x", subproc.getAbsolutePath()}).waitFor(); + + if (retCode != 0) + throw new RuntimeException("chmod exited with code " + retCode); + } catch (Throwable t) { + Log.errorEx("Error while giving execution rights to jcef_helper. MCEF will enter virtual mode. You can fix this by chmoding jcef_helper manually.", t); + VIRTUAL = true; + } } } - String exeSuffix; - if(OS.isWindows()) - exeSuffix = ".exe"; - else - exeSuffix = ""; - - File subproc = new File(ROOT, "jcef_helper" + exeSuffix); - if(OS.isLinux() && !subproc.canExecute()) { - try { - int retCode = Runtime.getRuntime().exec(new String[] { "/usr/bin/chmod", "+x", subproc.getAbsolutePath() }).waitFor(); + if (VIRTUAL) + return; - if(retCode != 0) - throw new RuntimeException("chmod exited with code " + retCode); - } catch(Throwable t) { - Log.errorEx("Error while giving execution rights to jcef_helper. MCEF will probably enter virtual mode. You can fix this by chmoding jcef_helper manually.", t); - } - } - CefSettings settings = new CefSettings(); settings.windowless_rendering_enabled = true; settings.background_color = settings.new ColorType(0, 255, 255, 255); - settings.locales_dir_path = (new File(ROOT, "MCEFLocales")).getAbsolutePath(); - settings.cache_path = (new File(ROOT, "MCEFCache")).getAbsolutePath(); - settings.browser_subprocess_path = subproc.getAbsolutePath(); - //settings.log_severity = CefSettings.LogSeverity.LOGSEVERITY_VERBOSE; - - try { - ArrayList libs = new ArrayList<>(); - - if(OS.isWindows()) { - libs.add("d3dcompiler_47.dll"); - libs.add("libGLESv2.dll"); - libs.add("libEGL.dll"); - libs.add("chrome_elf.dll"); - libs.add("libcef.dll"); - libs.add("jcef.dll"); - } else { - libs.add("libcef.so"); - libs.add("libjcef.so"); - } + settings.cache_path = (new File(JCEF_ROOT, "cache")).getAbsolutePath(); + settings.ignore_certificate_errors = true; - for(String lib: libs) { - File f = new File(ROOT, lib); - try { - f = f.getCanonicalFile(); - } catch(IOException ex) { - f = f.getAbsoluteFile(); - } + CefApp.startup(null); // TODO: pass CEF switches + cefApp = CefApp.getInstance(settings); + CefApp.addAppHandler(appHandler); - System.load(f.getPath()); - } + loadMimeTypeMapping(); - CefApp.startup(); - cefApp = CefApp.getInstance(settings); - //cefApp.myLoc = ROOT.replace('/', File.separatorChar); + cefClient = cefApp.createClient(); - loadMimeTypeMapping(); - CefApp.addAppHandler(appHandler); - cefClient = cefApp.createClient(); - } catch(Throwable t) { - Log.error("Going in virtual mode; couldn't initialize CEF."); - t.printStackTrace(); - - VIRTUAL = true; - return; - } - Log.info(cefApp.getVersion().toString()); cefRouter = CefMessageRouter.create(new CefMessageRouterConfig("mcefQuery", "mcefCancel")); cefClient.addMessageRouter(cefRouter); @@ -257,27 +160,27 @@ public boolean doClose(CefBrowser browser) { } }); - if(!ShutdownPatcher.didPatchSucceed()) { + if (!ShutdownPatcher.didPatchSucceed()) { Log.warning("ShutdownPatcher failed to patch Minecraft.run() method; starting ShutdownThread..."); (new ShutdownThread()).start(); } MinecraftForge.EVENT_BUS.register(this); - if(MCEF.ENABLE_EXAMPLE) + if (MCEF.ENABLE_EXAMPLE) exampleMod.onInit(); - + Log.info("MCEF loaded successfuly."); } - + public CefApp getCefApp() { return cefApp; } - + @Override public IBrowser createBrowser(String url, boolean transp) { - if(VIRTUAL) + if (VIRTUAL) return new VirtualBrowser(); - + CefBrowserOsr ret = (CefBrowserOsr) cefClient.createBrowser(url, true, transp); ret.setCloseAllowed(); ret.createImmediately(); @@ -285,26 +188,26 @@ public IBrowser createBrowser(String url, boolean transp) { browsers.add(ret); return ret; } - + @Override public void registerDisplayHandler(IDisplayHandler idh) { displayHandler.addHandler(idh); } - + @Override public boolean isVirtual() { return VIRTUAL; } - + @Override public void openExampleBrowser(String url) { - if(MCEF.ENABLE_EXAMPLE) + if (MCEF.ENABLE_EXAMPLE) exampleMod.showScreen(url); } - + @Override public void registerJSQueryHandler(IJSQueryHandler iqh) { - if(!VIRTUAL) + if (!VIRTUAL) cefRouter.addHandler(new MessageRouter(iqh), false); } @@ -320,34 +223,34 @@ public boolean isSchemeRegistered(String name) { @SubscribeEvent public void onTick(TickEvent.RenderTickEvent ev) { - if(ev.phase == TickEvent.Phase.START) { + if (ev.phase == TickEvent.Phase.START) { mc.mcProfiler.startSection("MCEF"); - if(cefApp != null) + if (cefApp != null) cefApp.N_DoMessageLoopWork(); - for(CefBrowserOsr b: browsers) + for (CefBrowserOsr b : browsers) b.mcefUpdate(); displayHandler.update(); mc.mcProfiler.endSection(); } } - + @SubscribeEvent public void onLogin(PlayerEvent.PlayerLoggedInEvent ev) { - if(updateStr == null || !MCEF.WARN_UPDATES) + if (updateStr == null || !MCEF.WARN_UPDATES) return; - + Style cs = new Style(); cs.setColor(TextFormatting.LIGHT_PURPLE); - + TextComponentString cct = new TextComponentString(updateStr); cct.setStyle(cs); - + ev.player.sendMessage(cct); } - + public void removeBrowser(CefBrowserOsr b) { browsers.remove(b); } @@ -362,30 +265,30 @@ private void runMessageLoopFor(long ms) { do { cefApp.N_DoMessageLoopWork(); - } while(System.currentTimeMillis() - start < ms); + } while (System.currentTimeMillis() - start < ms); } @Override public void onShutdown() { - if(VIRTUAL) + if (VIRTUAL) return; Log.info("Shutting down JCEF..."); CefBrowserOsr.CLEANUP = false; //Workaround - for(CefBrowserOsr b: browsers) + for (CefBrowserOsr b : browsers) b.close(); browsers.clear(); - if(MCEF.CHECK_VRAM_LEAK) + if (MCEF.CHECK_VRAM_LEAK) CefRenderer.dumpVRAMLeak(); runMessageLoopFor(100); CefApp.forceShutdownState(); cefClient.dispose(); - if(MCEF.SHUTDOWN_JCEF) + if (MCEF.SHUTDOWN_JCEF) cefApp.N_Shutdown(); } @@ -398,30 +301,30 @@ public void loadMimeTypeMapping() { try { BufferedReader br = new BufferedReader(new InputStreamReader(ClientProxy.class.getResourceAsStream("/assets/mcef/mime.types"))); - while(true) { + while (true) { cLine++; line = br.readLine(); - if(line == null) + if (line == null) break; line = line.trim(); - if(!line.startsWith("#")) { + if (!line.startsWith("#")) { Matcher m = p.matcher(line); - if(!m.matches()) + if (!m.matches()) continue; mimeTypeMap.put(m.group(2), m.group(1)); - if(m.groupCount() >= 4 && !m.group(3).isEmpty()) { + if (m.groupCount() >= 4 && !m.group(3).isEmpty()) { mimeTypeMap.put(m.group(3), m.group(1)); - if(m.groupCount() >= 5 && !m.group(4).isEmpty()) + if (m.groupCount() >= 5 && !m.group(4).isEmpty()) mimeTypeMap.put(m.group(4), m.group(1)); } } } Util.close(br); - } catch(Throwable e) { + } catch (Throwable e) { Log.error("[Mime Types] Error while parsing \"%s\" at line %d:", line, cLine); e.printStackTrace(); } @@ -433,11 +336,11 @@ public void loadMimeTypeMapping() { public String mimeTypeFromExtension(String ext) { ext = ext.toLowerCase(); String ret = mimeTypeMap.get(ext); - if(ret != null) + if (ret != null) return ret; //If the mimeTypeMap couldn't be loaded, fall back to common things - switch(ext) { + switch (ext) { case "htm": case "html": return "text/html"; diff --git a/src/main/java/net/montoyo/mcef/client/DisplayHandler.java b/src/main/java/net/montoyo/mcef/client/DisplayHandler.java index c6819a6a..2d3653c3 100644 --- a/src/main/java/net/montoyo/mcef/client/DisplayHandler.java +++ b/src/main/java/net/montoyo/mcef/client/DisplayHandler.java @@ -93,6 +93,11 @@ public boolean onConsoleMessage(CefBrowser browser, CefSettings.LogSeverity leve return false; } + @Override + public boolean onCursorChange(CefBrowser browser, int cursorType) { + return false; + } + public void addHandler(IDisplayHandler h) { list.add(h); } diff --git a/src/main/java/net/montoyo/mcef/client/LinuxPatch.java b/src/main/java/net/montoyo/mcef/client/LinuxPatch.java deleted file mode 100644 index 221e4436..00000000 --- a/src/main/java/net/montoyo/mcef/client/LinuxPatch.java +++ /dev/null @@ -1,148 +0,0 @@ -package net.montoyo.mcef.client; - -import net.montoyo.mcef.utilities.Log; -import net.montoyo.mcef.utilities.Util; - -import javax.swing.*; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; - -/* - * I'm keeping this code but I don't think it's required anymore... - */ -@Deprecated -public class LinuxPatch { - - private static String[] getBinDirs() { - return new String[] { "/bin", "/usr/bin", "/usr/sbin", "/usr/local/bin", "/usr/local/sbin" }; - } - - private static String[] getPatchFiles() { - return new String[] { "icudtl.dat", "natives_blob.bin", "snapshot_blob.bin", "v8_context_snapshot.bin" }; - } - - private static String getExeLocation(String exe) { - String[] bins = getBinDirs(); - for(String b: bins) { - File f = new File(b, exe); - - if(f.exists()) - return f.getAbsolutePath(); - } - - return null; - } - - private static String getGksudoLocation() { - String ret = getExeLocation("gksudo"); - return (ret == null) ? getExeLocation("gksu") : ret; - } - - public static File getScriptFile() { - return new File(ClientProxy.ROOT, "mcefLinuxPatch.sh"); - } - - public static void generateScript() throws Throwable { - String[] files = getPatchFiles(); - BufferedWriter bw = new BufferedWriter(new FileWriter(getScriptFile())); - - bw.write("#!/bin/sh\n"); - bw.write("MCEF_ROOT=\"" + ClientProxy.ROOT + "\"\n"); - bw.write("JAVA_ROOT=\"" + System.getProperty("java.home") + "/bin\"\n\n"); - - for(String f: files) - bw.write("rm -f \"$JAVA_ROOT/" + f + "\"\n"); - - bw.write("\n\n"); - - for(String f: files) - bw.write("ln -s \"$MCEF_ROOT/" + f + "\" \"$JAVA_ROOT/" + f + "\"\n"); - - bw.write("\n\n"); - Util.close(bw); - } - - public static boolean chmodX(File p) { - try { - return Runtime.getRuntime().exec(new String[] { "chmod", "+x", p.getAbsolutePath() }).waitFor() == 0; - } catch(IOException | InterruptedException ex) { - return false; - } - } - - public static boolean runScript() { - String cmd = getGksudoLocation(); - if(cmd == null) - return false; - - try { - if(!chmodX(getScriptFile())) { - Log.error("chmod failed!"); - return false; - } - - if(Runtime.getRuntime().exec(new String[] { cmd, getScriptFile().getAbsolutePath() }).waitFor() != 0) { - Log.error("gksudo failed!"); - return false; - } - - for(int i = 0; i < 6; i++) { - if(isPatched()) - break; - - try { - Thread.sleep(1000); - } catch(Throwable t) { - } - } - - return true; - } catch(IOException | InterruptedException e) { - e.printStackTrace(); - return false; - } - } - - private static boolean isPatched() { - File root = new File(System.getProperty("java.home"), "bin"); - String[] files = getPatchFiles(); - - for(String f: files) { - if(!(new File(root, f)).exists()) - return false; - } - - return true; - } - - public static boolean doPatch(File[] resourceArray) { - for(File f: resourceArray) { - if(f.exists() && !chmodX(f)) - Log.warning("Couldn't give execution access to %s", f.getAbsolutePath()); - } - - if(isPatched()) - return true; - - try { - generateScript(); - } catch(Throwable t) { - Log.error("Could not apply linux patch:"); - t.printStackTrace(); - return false; - } - - int ans = JOptionPane.showConfirmDialog(null, "An existing bug in JCEF requires some files to be copied\ninto the Java home directory in order to make MCEF working.\nThis operations requires root privileges.\nDo you want MCEF to try to do it automatically?", - "MCEF Linux", JOptionPane.YES_NO_OPTION); - - if(ans != JOptionPane.YES_OPTION) { - JOptionPane.showMessageDialog(null, "MCEF will enter virtual mode.\nA script containing the patch was generated here:\n" + getScriptFile().getAbsolutePath(), "MCEF Linux", JOptionPane.INFORMATION_MESSAGE); - return false; - } - - return runScript(); - } - -} diff --git a/src/main/java/net/montoyo/mcef/remote/Mirror.java b/src/main/java/net/montoyo/mcef/remote/Mirror.java index 2b3338de..16b97bf5 100644 --- a/src/main/java/net/montoyo/mcef/remote/Mirror.java +++ b/src/main/java/net/montoyo/mcef/remote/Mirror.java @@ -18,11 +18,6 @@ public final class Mirror { */ public static final int FLAG_SECURE = 1; - /** - * Whether the embedded Let's Encrypt certificate should be used to establish a secure connection to this host - */ - public static final int FLAG_LETSENCRYPT = 2; - /** * Whether this mirror has been forced by the user in the MCEF configuration file */ @@ -74,14 +69,6 @@ public boolean isSecure() { return (flags & FLAG_SECURE) != 0; } - /** - * @return Whether the Let's Encrypt flag is set - * @see #FLAG_LETSENCRYPT - */ - public boolean usesLetsEncryptCertificate() { - return (flags & FLAG_LETSENCRYPT) != 0; - } - /** * @return Whether this mirror has been forced by the user * @see #FLAG_FORCED diff --git a/src/main/java/net/montoyo/mcef/remote/MirrorManager.java b/src/main/java/net/montoyo/mcef/remote/MirrorManager.java index f94a4f5a..a4a877d3 100644 --- a/src/main/java/net/montoyo/mcef/remote/MirrorManager.java +++ b/src/main/java/net/montoyo/mcef/remote/MirrorManager.java @@ -16,8 +16,7 @@ public class MirrorManager { private static final Mirror[] defaultMirrors = new Mirror[] { - new Mirror("montoyo.net (over HTTPS)", "https://montoyo.net/jcef", Mirror.FLAG_SECURE | Mirror.FLAG_LETSENCRYPT), - new Mirror("montoyo.net (non-secure)", "http://montoyo.net/jcef", 0) + new Mirror("Ruinscraft MCEF Mirror", "https://storage.googleapis.com/ruinscraft-mcef-mirror", Mirror.FLAG_SECURE) }; /** diff --git a/src/main/java/net/montoyo/mcef/remote/RemoteConfig.java b/src/main/java/net/montoyo/mcef/remote/RemoteConfig.java index 95d3ae5e..c3722195 100644 --- a/src/main/java/net/montoyo/mcef/remote/RemoteConfig.java +++ b/src/main/java/net/montoyo/mcef/remote/RemoteConfig.java @@ -24,6 +24,8 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import static net.montoyo.mcef.client.ClientProxy.JCEF_ROOT; + /** * A class for updating and parsing the remote configuration file. * @author montoyo @@ -68,8 +70,8 @@ private JsonObject readConfig(File f) { * @return The parsed configuration file. */ private JsonObject readConfig() { - File newCfg = new File(ClientProxy.ROOT, "mcef2.new"); - File cfgFle = new File(ClientProxy.ROOT, "mcef2.json"); + File newCfg = new File(JCEF_ROOT, "mcef2.new"); + File cfgFle = new File(JCEF_ROOT, "mcef2.json"); boolean ok = Util.download("config2.json", newCfg, null); @@ -116,7 +118,7 @@ else if(OS.isLinux()) } String arch = System.getProperty("sun.arch.data.model"); - if(!arch.equals("32") && !arch.equals("64")) { + if(!arch.equals("64")) { //Shouldn't happen. Log.error("Your CPU arch isn't supported by MCEF. Entering virtual mode."); ClientProxy.VIRTUAL = true; @@ -266,7 +268,7 @@ public boolean updateFileListing(File configDir, boolean zipOnly) { if(!zipOnly) { for(Resource r: resources) - fl.addFile(r.getFileName()); + fl.addFile(JCEF_ROOT + "/" + r.getFileName()); } boolean allOk = true; diff --git a/src/main/java/net/montoyo/mcef/remote/Resource.java b/src/main/java/net/montoyo/mcef/remote/Resource.java index ca2fb5a9..5bf85617 100644 --- a/src/main/java/net/montoyo/mcef/remote/Resource.java +++ b/src/main/java/net/montoyo/mcef/remote/Resource.java @@ -40,7 +40,7 @@ public Resource(String name, String sum, String platform) { * @return true if (and only if) the file exists and the checksum matches the {@link #sum} field. */ public boolean exists() { - File f = new File(ClientProxy.ROOT, name); + File f = new File(ClientProxy.JCEF_ROOT, name); if(!f.exists()) return false; @@ -64,7 +64,7 @@ public boolean download(IProgressListener ipl) { if(shouldExtract) end += ".gz"; - File dst = new File(ClientProxy.ROOT, name); + File dst = new File(ClientProxy.JCEF_ROOT, name); File parent = dst.getParentFile(); //ClientProxy.ROOT exists, but this.name might contain some subdirectories that we need to create... @@ -82,7 +82,7 @@ public boolean download(IProgressListener ipl) { */ public boolean extract(IProgressListener ipl) { Util.secure(ipl).onTaskChanged("Extracting " + name); - return Util.extract(new File(ClientProxy.ROOT, name), new File(ClientProxy.ROOT)); + return Util.extract(new File(ClientProxy.JCEF_ROOT, name), new File(ClientProxy.JCEF_ROOT)); } /** @@ -108,7 +108,7 @@ public String getFileName() { * @return The File containing the location of the specified resource. */ public static File getLocationOf(String resName) { - return new File(ClientProxy.ROOT, resName); + return new File(ClientProxy.JCEF_ROOT, resName); } } diff --git a/src/main/java/net/montoyo/mcef/utilities/Util.java b/src/main/java/net/montoyo/mcef/utilities/Util.java index d1836242..7dafd4f6 100644 --- a/src/main/java/net/montoyo/mcef/utilities/Util.java +++ b/src/main/java/net/montoyo/mcef/utilities/Util.java @@ -315,9 +315,6 @@ public static SizedInputStream openStream(String res, String err) { try { Mirror m = MirrorManager.INSTANCE.getCurrent(); conn = m.getResource(res); - - if(conn instanceof HttpsURLConnection && m.usesLetsEncryptCertificate() && MCEF.SSL_SOCKET_FACTORY != null) - ((HttpsURLConnection) conn).setSSLSocketFactory(MCEF.SSL_SOCKET_FACTORY); } catch(MalformedURLException e) { Log.error("%s Is the mirror list broken?", err); e.printStackTrace(); diff --git a/src/main/java/org/cef/CefApp.java b/src/main/java/org/cef/CefApp.java index acefdd04..4f94745f 100644 --- a/src/main/java/org/cef/CefApp.java +++ b/src/main/java/org/cef/CefApp.java @@ -4,19 +4,17 @@ package org.cef; +import org.cef.callback.CefSchemeHandlerFactory; +import org.cef.handler.CefAppHandler; +import org.cef.handler.CefAppHandlerAdapter; + +import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; -import java.io.FilenameFilter; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; -import javax.swing.SwingUtilities; -import javax.swing.Timer; - -import org.cef.callback.CefSchemeHandlerFactory; -import org.cef.handler.CefAppHandler; -import org.cef.handler.CefAppHandlerAdapter; /** * Exposes static methods for managing the global CEF context. @@ -36,7 +34,7 @@ public final class CefVersion { public final int CHROME_VERSION_PATCH; private CefVersion(int jcefCommitNo, int cefMajor, int cefMinor, int cefPatch, - int cefCommitNo, int chrMajor, int chrMin, int chrBuild, int chrPatch) { + int cefCommitNo, int chrMajor, int chrMin, int chrBuild, int chrPatch) { JCEF_COMMIT_NUMBER = jcefCommitNo; CEF_VERSION_MAJOR = cefMajor; @@ -51,8 +49,8 @@ private CefVersion(int jcefCommitNo, int cefMajor, int cefMinor, int cefPatch, } public String getJcefVersion() { - return CEF_VERSION_MAJOR + "." + CEF_VERSION_MINOR + "." + CEF_VERSION_PATCH - + "." + JCEF_COMMIT_NUMBER; + return CEF_VERSION_MAJOR + "." + CEF_VERSION_MINOR + "." + CEF_VERSION_PATCH + "." + + JCEF_COMMIT_NUMBER; } public String getCefVersion() { @@ -130,7 +128,7 @@ public enum CefAppState { /** * To get an instance of this class, use the method * getInstance() instead of this CTOR. - * + *

* The CTOR is called by getInstance() as needed and * loads all required JCEF libraries. * @@ -140,56 +138,23 @@ private CefApp(String[] args, CefSettings settings) throws UnsatisfiedLinkError super(args); if (settings != null) settings_ = settings.clone(); - //montoyo: Modified for MCEF - /* - if (OS.isWindows()) { - System.loadLibrary("jawt"); - System.loadLibrary("chrome_elf"); - System.loadLibrary("libcef"); - - // Other platforms load this library in CefApp.startup(). - System.loadLibrary("jcef"); - } else if (OS.isLinux()) { - System.loadLibrary("cef"); - } - */ - if (appHandler_ == null) { appHandler_ = this; } - // Execute on the AWT event dispatching thread. - try { - Runnable r = new Runnable() { - @Override - public void run() { - // Perform native pre-initialization. - if (!N_PreInitialize()) - throw new IllegalStateException("Failed to pre-initialize native code"); - } - }; - - //montoyo: Modified for MCEF - /* - if (SwingUtilities.isEventDispatchThread()) - r.run(); - else - SwingUtilities.invokeAndWait(r);*/ - r.run(); - } catch (Exception e) { - e.printStackTrace(); - } + if (!N_PreInitialize()) + throw new IllegalStateException("Failed to pre-initialize native code"); } /** * Assign an AppHandler to CefApp. The AppHandler can be used to evaluate * application arguments, to register your own schemes and to hook into the * shutdown sequence. See CefAppHandler for more details. - * + *

* This method must be called before CefApp is initialized. CefApp will be * initialized automatically if you call createClient() the first time. - * @param appHandler An instance of CefAppHandler. * + * @param appHandler An instance of CefAppHandler. * @throws IllegalStateException in case of CefApp is already initialized */ public static void addAppHandler(CefAppHandler appHandler) throws IllegalStateException { @@ -200,6 +165,7 @@ public static void addAppHandler(CefAppHandler appHandler) throws IllegalStateEx /** * Get an instance of this class. + * * @return an instance of this class * @throws UnsatisfiedLinkError */ @@ -250,6 +216,7 @@ public final CefVersion getVersion() { /** * Returns the current state of CefApp. + * * @return current state. */ public final static CefAppState getState() { @@ -262,15 +229,7 @@ private static final void setState(final CefAppState state) { synchronized (state_) { state_ = state; } - - //montoyo: Modified for MCEF - // Execute on the AWT event dispatching thread. - /*SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() {*/ - if (appHandler_ != null) appHandler_.stateHasChanged(state); - /*} - });*/ + if (appHandler_ != null) appHandler_.stateHasChanged(state); } //montoyo: Added for MCEF @@ -323,6 +282,7 @@ public synchronized final void dispose() { * Creates a new client instance and returns it to the caller. * One client instance is responsible for one to many browser * instances + * * @return a new client instance */ public synchronized CefClient createClient() { @@ -330,7 +290,7 @@ public synchronized CefClient createClient() { case NEW: setState(CefAppState.INITIALIZING); initialize(); - // FALL THRU + // FALL THRU case INITIALIZING: case INITIALIZED: @@ -383,6 +343,7 @@ public boolean clearSchemeHandlerFactories() { * This method is called by a CefClient if it was disposed. This causes * CefApp to clean up its list of available client instances. If all clients * are disposed, CefApp will be shutdown. + * * @param client the disposed client. */ protected final synchronized void clientWasDisposed(CefClient client) { @@ -395,56 +356,38 @@ protected final synchronized void clientWasDisposed(CefClient client) { /** * Initialize the context. + * * @return true on success. */ private final void initialize() { - // Execute on the AWT event dispatching thread. - try { - Runnable r = new Runnable() { - @Override - public void run() { - String library_path = getJcefLibPath(); - System.out.println("initialize on " + Thread.currentThread() - + " with library path " + library_path); - - CefSettings settings = settings_ != null ? settings_ : new CefSettings(); - - // Avoid to override user values by testing on NULL - if (OS.isMacintosh()) { - if (settings.browser_subprocess_path == null) { - Path path = Paths.get(library_path, - "../Frameworks/jcef Helper.app/Contents/MacOS/jcef Helper"); - settings.browser_subprocess_path = - path.normalize().toAbsolutePath().toString(); - } - } else if (OS.isWindows()) { - if (settings.browser_subprocess_path == null) { - settings.browser_subprocess_path = library_path + "\\jcef_helper.exe"; - } - } else if (OS.isLinux()) { - if (settings.browser_subprocess_path == null) - settings.browser_subprocess_path = library_path + "/jcef_helper"; - if (settings.resources_dir_path == null) - settings.resources_dir_path = library_path; - if (settings.locales_dir_path == null) - settings.locales_dir_path = library_path + "/locales"; - } + String jcefPath = getJcefLibPath(); + System.out.println("initialize on " + Thread.currentThread() + " with library path " + jcefPath); - if (N_Initialize(library_path, appHandler_, settings)) - setState(CefAppState.INITIALIZED); - } - }; - - //montoyo: Modified for MCEF - /* - if (SwingUtilities.isEventDispatchThread()) - r.run(); - else - SwingUtilities.invokeAndWait(r);*/ - r.run(); - } catch (Exception e) { - e.printStackTrace(); + CefSettings settings = settings_ != null ? settings_ : new CefSettings(); + + if (OS.isWindows()) { + Path jcefHelperPath = Paths.get(jcefPath, "jcef_helper.exe"); + settings.browser_subprocess_path = jcefHelperPath.normalize().toAbsolutePath().toString(); + } else if (OS.isMacintosh()) { + String basePath = Paths.get(jcefPath).getParent().getParent().toString(); + settings.main_bundle_path = basePath; + settings.framework_dir_path = basePath + + "/Contents/Frameworks/Chromium Embedded Framework.framework"; + settings.locales_dir_path = basePath + + "/Contents/Frameworks/Chromium Embedded Framework.framework/Resources"; + settings.resources_dir_path = basePath + + "/Contents/Frameworks/Chromium Embedded Framework.framework/Resources"; + settings.browser_subprocess_path = basePath + + "/Contents/Frameworks/jcef Helper.app/Contents/MacOS/jcef Helper"; + } else if (OS.isLinux()) { + settings.resources_dir_path = jcefPath; + Path jcefHelperPath = Paths.get(jcefPath, "jcef_helper"); + settings.browser_subprocess_path = jcefHelperPath.normalize().toAbsolutePath().toString(); + Path localesPath = Paths.get(jcefPath, "locales"); + settings.locales_dir_path = localesPath.normalize().toAbsolutePath().toString(); } + + if (N_Initialize(appHandler_, settings)) setState(CefAppState.INITIALIZED); } /** @@ -453,32 +396,22 @@ public void run() { */ protected final void handleBeforeTerminate() { System.out.println("Cmd+Q termination request."); - - //montoyo: Modified for MCEF - // Execute on the AWT event dispatching thread. Always call asynchronously - // so the call stack has a chance to unwind. - /*SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() {*/ - CefAppHandler handler = - (CefAppHandler) ((appHandler_ == null) ? this : appHandler_); - if (!handler.onBeforeTerminate()) dispose(); - /*} - });*/ + CefAppHandler handler = + (CefAppHandler) ((appHandler_ == null) ? this : appHandler_); + if (!handler.onBeforeTerminate()) dispose(); } /** * Shut down the context. */ - //montoyo: modified for MCEF private final void shutdown() { - System.out.println("shutdown on " + Thread.currentThread()); + System.out.println("shutdown on " + Thread.currentThread()); - // Shutdown native CEF. - //N_Shutdown(); + // Shutdown native CEF. + N_Shutdown(); - setState(CefAppState.TERMINATED); - CefApp.self = null; + setState(CefAppState.TERMINATED); + CefApp.self = null; } /** @@ -535,49 +468,72 @@ public void actionPerformed(ActionEvent evt) { * This method must be called at the beginning of the main() method to perform platform- * specific startup initialization. On Linux this initializes Xlib multithreading and on * macOS this dynamically loads the CEF framework. + * + * @param args Command-line arguments massed to main(). + * @return True on successful startup. */ - public static final boolean startup() { - if (OS.isLinux() || OS.isMacintosh()) { - //Modified by montoyo for MCEF - //System.loadLibrary("jcef"); - return N_Startup(); + public static final boolean startup(String[] args) { + String jcefPath = getJcefLibPath(); + + if (OS.isWindows()) { + System.load(jcefPath + "\\d3dcompiler_47.dll"); + System.load(jcefPath + "\\libGLESv2.dll"); + System.load(jcefPath + "\\libEGL.dll"); + System.load(jcefPath + "\\chrome_elf.dll"); + System.load(jcefPath + "\\libcef.dll"); + System.load(jcefPath + "\\jcef.dll"); + return true; + } else if (OS.isMacintosh()) { + System.load(jcefPath + "/libjcef.dylib"); + return N_Startup(getCefFrameworkPath(args)); + } else if (OS.isLinux()) { + System.load(jcefPath + "/libcef.so"); + System.load(jcefPath + "/libjcef.so"); + return N_Startup(null); } - return true; + + return false; + } + + private static final String getJcefLibPath() { + Path runtimeDir = Paths.get(""); + Path jcefPath = runtimeDir.resolve("jcef"); + return jcefPath.toAbsolutePath().toString(); } /** - * Get the path which contains the jcef library - * @return The path to the jcef library + * Get the path that contains the CEF Framework on macOS. + * + * @return The path to the CEF Framework. */ - private final String getJcefLibPath() { - String library_path = System.getProperty("java.library.path"); - String[] paths = library_path.split(System.getProperty("path.separator")); - for (String path : paths) { - File dir = new File(path); - String[] found = dir.list(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return (name.equalsIgnoreCase("libjcef.dylib") - || name.equalsIgnoreCase("libjcef.so") - || name.equalsIgnoreCase("jcef.dll")); - } - }); - if (found != null && found.length != 0) return path; + private static final String getCefFrameworkPath(String[] args) { + // Check for the path on the command-line. + String switchPrefix = "--framework-dir-path="; + for (String arg : args) { + if (arg.startsWith(switchPrefix)) { + return new File(arg.substring(switchPrefix.length())).getAbsolutePath(); + } } - return library_path; + + // Determine the path relative to the JCEF lib location in the app bundle. + return new File(getJcefLibPath() + "/../Frameworks/Chromium Embedded Framework.framework") + .getAbsolutePath(); } - private final static native boolean N_Startup(); + private final static native boolean N_Startup(String pathToCefFramework); + private final native boolean N_PreInitialize(); - private final native boolean N_Initialize( - String pathToJavaDLL, CefAppHandler appHandler, CefSettings settings); - //montoyo: modified for MCEF + private final native boolean N_Initialize(CefAppHandler appHandler, CefSettings settings); + public final native void N_Shutdown(); + public final native void N_DoMessageLoopWork(); private final native CefVersion N_GetVersion(); + private final native boolean N_RegisterSchemeHandlerFactory( String schemeName, String domainName, CefSchemeHandlerFactory factory); + private final native boolean N_ClearSchemeHandlerFactories(); } diff --git a/src/main/java/org/cef/CefClient.java b/src/main/java/org/cef/CefClient.java index ce7c728a..15aca12b 100644 --- a/src/main/java/org/cef/CefClient.java +++ b/src/main/java/org/cef/CefClient.java @@ -34,6 +34,7 @@ import org.cef.handler.CefRequestHandler; import org.cef.handler.CefResourceHandler; import org.cef.handler.CefResourceRequestHandler; +import org.cef.handler.CefScreenInfo; import org.cef.handler.CefWindowHandler; import org.cef.misc.BoolRef; import org.cef.misc.StringRef; @@ -319,6 +320,24 @@ public boolean onConsoleMessage(CefBrowser browser, CefSettings.LogSeverity leve return false; } + @Override + public boolean onCursorChange(CefBrowser browser, int cursorType) { + if (browser == null) { + return false; + } + + if (displayHandler_ != null && displayHandler_.onCursorChange(browser, cursorType)) { + return true; + } + + CefRenderHandler realHandler = browser.getRenderHandler(); + if (realHandler != null) { + return realHandler.onCursorChange(browser, cursorType); + } + + return false; + } + // CefDownloadHandler public CefClient addDownloadHandler(CefDownloadHandler handler) { @@ -673,14 +692,6 @@ public void onPaint(CefBrowser browser, boolean popup, Rectangle[] dirtyRects, realHandler.onPaint(browser, popup, dirtyRects, buffer, width, height); } - @Override - public void onCursorChange(CefBrowser browser, int cursorType) { - if (browser == null) return; - - CefRenderHandler realHandler = browser.getRenderHandler(); - if (realHandler != null) realHandler.onCursorChange(browser, cursorType); - } - @Override public boolean startDragging(CefBrowser browser, CefDragData dragData, int mask, int x, int y) { if (browser == null) return false; @@ -718,6 +729,15 @@ public boolean onBeforeBrowse(CefBrowser browser, CefFrame frame, CefRequest req return false; } + @Override + public boolean onOpenURLFromTab( + CefBrowser browser, CefFrame frame, String target_url, boolean user_gesture) { + if (isDisposed_) return true; + if (requestHandler_ != null && browser != null) + return requestHandler_.onOpenURLFromTab(browser, frame, target_url, user_gesture); + return false; + } + @Override public CefResourceRequestHandler getResourceRequestHandler(CefBrowser browser, CefFrame frame, CefRequest request, boolean isNavigation, boolean isDownload, String requestInitiator, @@ -730,11 +750,11 @@ public CefResourceRequestHandler getResourceRequestHandler(CefBrowser browser, C } @Override - public boolean getAuthCredentials(CefBrowser browser, CefFrame frame, boolean isProxy, + public boolean getAuthCredentials(CefBrowser browser, String origin_url, boolean isProxy, String host, int port, String realm, String scheme, CefAuthCallback callback) { if (requestHandler_ != null && browser != null) return requestHandler_.getAuthCredentials( - browser, frame, isProxy, host, port, realm, scheme, callback); + browser, origin_url, isProxy, host, port, realm, scheme, callback); return false; } @@ -784,4 +804,9 @@ public void onMouseEvent( if (realHandler != null) realHandler.onMouseEvent(browser, event, screenX, screenY, modifier, button); } + + @Override + public boolean getScreenInfo(CefBrowser arg0, CefScreenInfo arg1) { + return false; + } } diff --git a/src/main/java/org/cef/CefSettings.java b/src/main/java/org/cef/CefSettings.java index 511b65be..78a5a0df 100644 --- a/src/main/java/org/cef/CefSettings.java +++ b/src/main/java/org/cef/CefSettings.java @@ -75,6 +75,10 @@ public ColorType clone() { } } + // MacOS specific settings + public String framework_dir_path = null; + public String main_bundle_path = null; + /** * The path to a separate executable that will be launched for sub-processes. * By default the browser process executable is used. See the comments on diff --git a/src/main/java/org/cef/DummyComponent.java b/src/main/java/org/cef/DummyComponent.java deleted file mode 100644 index c3620535..00000000 --- a/src/main/java/org/cef/DummyComponent.java +++ /dev/null @@ -1,15 +0,0 @@ -//Created by montoyo for MCEF - -package org.cef; - -import java.awt.Component; -import java.awt.Point; - -public class DummyComponent extends Component { - - @Override - public Point getLocationOnScreen() { - return new Point(0, 0); - } - -} diff --git a/src/main/java/org/cef/SystemBootstrap.java b/src/main/java/org/cef/SystemBootstrap.java new file mode 100644 index 00000000..0a217ac4 --- /dev/null +++ b/src/main/java/org/cef/SystemBootstrap.java @@ -0,0 +1,38 @@ +// Copyright (c) 2020 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +package org.cef; + +/** + * To allow customization of System.load() calls by supplying a different + * implementation. You'll want to call setLoader with your custom + * implementation before calling into any other CEF classes which then in turn + * will start triggering libraries to be loaded at runtime. + */ +public class SystemBootstrap { + /** + * Simple interface for how a library by name should be loaded. + */ + static public interface Loader { public void loadLibrary(String libname); } + + /** + * Default implementation is to call System.loadLibrary + */ + static private Loader loader_ = new Loader() { + @Override + public void loadLibrary(String libname) { + System.loadLibrary(libname); + } + }; + + static public void setLoader(Loader loader) { + if (loader == null) { + throw new NullPointerException("Loader cannot be null"); + } + loader_ = loader; + } + + static public void loadLibrary(String libname) { + loader_.loadLibrary(libname); + } +} \ No newline at end of file diff --git a/src/main/java/org/cef/browser/CefBrowser.java b/src/main/java/org/cef/browser/CefBrowser.java index 0842176a..b1a9e8b5 100644 --- a/src/main/java/org/cef/browser/CefBrowser.java +++ b/src/main/java/org/cef/browser/CefBrowser.java @@ -4,10 +4,6 @@ package org.cef.browser; -import java.awt.Component; -import java.awt.Point; -import java.util.Vector; - import org.cef.CefClient; import org.cef.callback.CefPdfPrintCallback; import org.cef.callback.CefRunFileDialogCallback; @@ -18,6 +14,12 @@ import org.cef.misc.CefPdfPrintSettings; import org.cef.network.CefRequest; +import java.awt.Component; +import java.awt.Point; +import java.awt.image.BufferedImage; +import java.util.Vector; +import java.util.concurrent.CompletableFuture; + /** * Interface representing a browser. */ @@ -202,17 +204,6 @@ public interface CefBrowser { */ public void loadURL(String url); - /** - * Load the contents of val with the specified dummy url. - * url should have a standard scheme (for example, http scheme) or - * behaviors like link clicks and web security restrictions may not - * behave as expected. - * - * @param val Content to be displayed. - * @param url dummy url to be used for. - */ - public void loadString(String val, String url); - /** * Execute a string of JavaScript code in this frame. The url * parameter is the URL where the script in question can be found, if any. @@ -368,4 +359,27 @@ public void find(int identifier, String searchText, boolean forward, boolean mat * @param word replace selected word with this word. */ public void replaceMisspelling(String word); + + /** + * Captures a screenshot-like image of the currently displayed content and returns it. + *

+ * If executed on the AWT Event Thread, this returns an immediately resolved {@link + * java.util.concurrent.CompletableFuture}. If executed from another thread, the {@link + * java.util.concurrent.CompletableFuture} returned is resolved as soon as the screenshot + * has been taken (which must happen on the event thread). + *

+ * The generated screenshot can either be returned as-is, containing all natively-rendered + * pixels, or it can be scaled to match the logical width and height of the window. + * This distinction is only relevant in case of differing logical and physical resolutions + * (for example with HiDPI/Retina displays, which have a scaling factor of for example 2 + * between the logical width of a window (ex. 400px) and the actual number of pixels in + * each row (ex. 800px with a scaling factor of 2)). + * + * @param nativeResolution whether to return an image at full native resolution (true) + * or a scaled-down version whose width and height are equal to the logical size + * of the screenshotted browser window + * @return the screenshot image + * @throws UnsupportedOperationException if not supported + */ + public CompletableFuture createScreenshot(boolean nativeResolution); } diff --git a/src/main/java/org/cef/browser/CefBrowserOsr.java b/src/main/java/org/cef/browser/CefBrowserOsr.java index 4d47ac4f..423480ca 100644 --- a/src/main/java/org/cef/browser/CefBrowserOsr.java +++ b/src/main/java/org/cef/browser/CefBrowserOsr.java @@ -2,8 +2,6 @@ // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. -// Modified by montoyo for MCEF - package org.cef.browser; import net.montoyo.mcef.MCEF; @@ -12,22 +10,23 @@ import net.montoyo.mcef.client.ClientProxy; import net.montoyo.mcef.client.StringVisitor; import net.montoyo.mcef.utilities.Log; +import org.apache.commons.lang3.NotImplementedException; import org.cef.CefClient; -import org.cef.DummyComponent; -import org.cef.OS; import org.cef.callback.CefDragData; import org.cef.handler.CefRenderHandler; +import org.cef.handler.CefScreenInfo; import org.lwjgl.BufferUtils; import org.lwjgl.input.Keyboard; -import java.awt.Component; -import java.awt.Point; -import java.awt.Rectangle; +import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; +import java.awt.image.BufferedImage; import java.nio.ByteBuffer; import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CompletableFuture; /** * This class represents an off-screen rendered browser. @@ -36,12 +35,21 @@ */ public class CefBrowserOsr extends CefBrowser_N implements CefRenderHandler, IBrowser { private CefRenderer renderer_; + private long window_handle_ = 0; + private boolean justCreated_ = false; private Rectangle browser_rect_ = new Rectangle(0, 0, 1, 1); // Work around CEF issue #1437. private Point screenPoint_ = new Point(0, 0); + private double scaleFactor_ = 1.0; + private int depth = 32; + private int depth_per_component = 8; private boolean isTransparent_; - private final DummyComponent dc_ = new DummyComponent(); + private final Component dc_ = new Component() { + @Override + public Point getLocationOnScreen() { + return new Point(0, 0); + } + }; private MouseEvent lastMouseEvent = new MouseEvent(dc_, MouseEvent.MOUSE_MOVED, 0, 0, 0, 0, 0, false); - public static boolean CLEANUP = true; CefBrowserOsr(CefClient client, String url, boolean transparent, CefRequestContext context) { @@ -49,7 +57,7 @@ public class CefBrowserOsr extends CefBrowser_N implements CefRenderHandler, IBr } private CefBrowserOsr(CefClient client, String url, boolean transparent, - CefRequestContext context, CefBrowserOsr parent, Point inspectAt) { + CefRequestContext context, CefBrowserOsr parent, Point inspectAt) { super(client, url, context, parent, inspectAt); isTransparent_ = transparent; renderer_ = new CefRenderer(transparent); @@ -57,6 +65,7 @@ private CefBrowserOsr(CefClient client, String url, boolean transparent, @Override public void createImmediately() { + justCreated_ = true; // Create the browser immediately. createBrowserIfRequired(false); } @@ -73,7 +82,7 @@ public CefRenderHandler getRenderHandler() { @Override protected CefBrowser_N createDevToolsBrowser(CefClient client, String url, - CefRequestContext context, CefBrowser_N parent, Point inspectAt) { + CefRequestContext context, CefBrowser_N parent, Point inspectAt) { return new CefBrowserOsr( client, url, isTransparent_, context, (CefBrowserOsr) this, inspectAt); } @@ -103,97 +112,9 @@ public void onPopupSize(CefBrowser browser, Rectangle size) { renderer_.onPopupSize(size); } - private static class PaintData { - private ByteBuffer buffer; - private int width; - private int height; - private Rectangle[] dirtyRects; - private boolean hasFrame; - private boolean fullReRender; - } - - private final PaintData paintData = new PaintData(); - - @Override - public void onPaint(CefBrowser browser, boolean popup, Rectangle[] dirtyRects, - ByteBuffer buffer, int width, int height) { - if(popup) - return; - - final int size = (width * height) << 2; - - synchronized(paintData) { - if(buffer.limit() > size) - Log.warning("Skipping MCEF browser frame, data is too heavy"); //TODO: Don't spam - else { - if(paintData.hasFrame) //The previous frame was not uploaded to GL texture, so we skip it and render this on instead - paintData.fullReRender = true; - - if(paintData.buffer == null || size != paintData.buffer.capacity()) //This only happens when the browser gets resized - paintData.buffer = BufferUtils.createByteBuffer(size); - - paintData.buffer.position(0); - paintData.buffer.limit(buffer.limit()); - buffer.position(0); - paintData.buffer.put(buffer); - paintData.buffer.position(0); - - paintData.width = width; - paintData.height = height; - paintData.dirtyRects = dirtyRects; - paintData.hasFrame = true; - } - } - } - - public void mcefUpdate() { - synchronized(paintData) { - if(paintData.hasFrame) { - renderer_.onPaint(false, paintData.dirtyRects, paintData.buffer, paintData.width, paintData.height, paintData.fullReRender); - paintData.hasFrame = false; - paintData.fullReRender = false; - } - } - - //So sadly this is the only way I could get around the "youtube not rendering video if the mouse doesn't move bug" - //Even the test browser from the original JCEF library doesn't fix this... - //What I hope, however, is that it doesn't redraw the entire browser... otherwise I could just call "invalidate" - sendMouseEvent(lastMouseEvent); - } - - @Override - public void onCursorChange(CefBrowser browser, final int cursorType) { - } - - @Override - public boolean startDragging(CefBrowser browser, CefDragData dragData, int mask, int x, int y) { - // TODO(JCEF) Prepared for DnD support using OSR mode. - return false; - } - - @Override - public void updateDragCursor(CefBrowser browser, int operation) { - // TODO(JCEF) Prepared for DnD support using OSR mode. - } - - private void createBrowserIfRequired(boolean hasParent) { - if (getNativeRef("CefBrowser") == 0) { - if (getParentBrowser() != null) { - createDevTools(getParentBrowser(), getClient(), 0, true, isTransparent_, - null, getInspectAt()); - } else { - createBrowser(getClient(), 0, getUrl(), true, isTransparent_, null, - getRequestContext()); - } - } else { - // OSR windows cannot be reparented after creation. - setFocus(true); - } - } - @Override public void close() { - if(CLEANUP) { + if (CLEANUP) { ((ClientProxy) MCEF.PROXY).removeBrowser(this); renderer_.cleanup(); } @@ -241,31 +162,43 @@ public void injectKeyTyped(char c, int mods) { } public static int remapKeycode(int kc, char c) { - switch(kc) { - case Keyboard.KEY_BACK: return 0x08; - case Keyboard.KEY_DELETE: return 0x2E; - case Keyboard.KEY_DOWN: return 0x28; - case Keyboard.KEY_RETURN: return 0x0D; - case Keyboard.KEY_ESCAPE: return 0x1B; - case Keyboard.KEY_LEFT: return 0x25; - case Keyboard.KEY_RIGHT: return 0x27; - case Keyboard.KEY_TAB: return 0x09; - case Keyboard.KEY_UP: return 0x26; - case Keyboard.KEY_PRIOR: return 0x21; - case Keyboard.KEY_NEXT: return 0x22; - case Keyboard.KEY_END: return 0x23; - case Keyboard.KEY_HOME: return 0x24; - - default: return (int) c; + switch (kc) { + case Keyboard.KEY_BACK: + return 0x08; + case Keyboard.KEY_DELETE: + return 0x2E; + case Keyboard.KEY_DOWN: + return 0x28; + case Keyboard.KEY_RETURN: + return 0x0D; + case Keyboard.KEY_ESCAPE: + return 0x1B; + case Keyboard.KEY_LEFT: + return 0x25; + case Keyboard.KEY_RIGHT: + return 0x27; + case Keyboard.KEY_TAB: + return 0x09; + case Keyboard.KEY_UP: + return 0x26; + case Keyboard.KEY_PRIOR: + return 0x21; + case Keyboard.KEY_NEXT: + return 0x22; + case Keyboard.KEY_END: + return 0x23; + case Keyboard.KEY_HOME: + return 0x24; + + default: + return c; } } - private static final HashMap WORST_HACK = new HashMap<>(); - @Override public void injectKeyPressedByKeyCode(int keyCode, char c, int mods) { - if(c != '\0') { - synchronized(WORST_HACK) { + if (c != '\0') { + synchronized (WORST_HACK) { WORST_HACK.put(keyCode, c); } } @@ -274,10 +207,12 @@ public void injectKeyPressedByKeyCode(int keyCode, char c, int mods) { sendKeyEvent(ev); } + private static final Map WORST_HACK = new HashMap<>(); + @Override public void injectKeyReleasedByKeyCode(int keyCode, char c, int mods) { - if(c == '\0') { - synchronized(WORST_HACK) { + if (c == '\0') { + synchronized (WORST_HACK) { c = WORST_HACK.getOrDefault(keyCode, '\0'); } } @@ -306,4 +241,107 @@ public void visitSource(IStringVisitor isv) { public boolean isPageLoading() { return isLoading(); } + + private static class PaintData { + private ByteBuffer buffer; + private int width; + private int height; + private Rectangle[] dirtyRects; + private boolean hasFrame; + private boolean fullReRender; + } + + private final PaintData paintData = new PaintData(); + + @Override + public void onPaint(CefBrowser browser, boolean popup, Rectangle[] dirtyRects, + ByteBuffer buffer, int width, int height) { + if (popup) { + return; + } + + final int size = (width * height) << 2; + + synchronized (paintData) { + if (buffer.limit() > size) + Log.warning("Skipping MCEF browser frame, data is too heavy"); //TODO: Don't spam + else { + if (paintData.hasFrame) //The previous frame was not uploaded to GL texture, so we skip it and render this on instead + paintData.fullReRender = true; + + if (paintData.buffer == null || size != paintData.buffer.capacity()) //This only happens when the browser gets resized + paintData.buffer = BufferUtils.createByteBuffer(size); + + paintData.buffer.position(0); + paintData.buffer.limit(buffer.limit()); + buffer.position(0); + paintData.buffer.put(buffer); + paintData.buffer.position(0); + + paintData.width = width; + paintData.height = height; + paintData.dirtyRects = dirtyRects; + paintData.hasFrame = true; + } + } + } + + public void mcefUpdate() { + synchronized (paintData) { + if (paintData.hasFrame) { + renderer_.onPaint(false, paintData.dirtyRects, paintData.buffer, paintData.width, paintData.height, paintData.fullReRender); + paintData.hasFrame = false; + paintData.fullReRender = false; + } + } + + //So sadly this is the only way I could get around the "youtube not rendering video if the mouse doesn't move bug" + //Even the test browser from the original JCEF library doesn't fix this... + //What I hope, however, is that it doesn't redraw the entire browser... otherwise I could just call "invalidate" + sendMouseEvent(lastMouseEvent); + } + + @Override + public boolean onCursorChange(CefBrowser browser, final int cursorType) { + return true; + } + + @Override + public boolean startDragging(CefBrowser browser, CefDragData dragData, int mask, int x, int y) { + // TODO(JCEF) Prepared for DnD support using OSR mode. + return false; + } + + @Override + public void updateDragCursor(CefBrowser browser, int operation) { + // TODO(JCEF) Prepared for DnD support using OSR mode. + } + + private void createBrowserIfRequired(boolean hasParent) { + if (getNativeRef("CefBrowser") == 0) { + if (getParentBrowser() != null) { + createDevTools(getParentBrowser(), getClient(), 0, true, isTransparent_, + null, getInspectAt()); + } else { + createBrowser(getClient(), 0, getUrl(), true, isTransparent_, null, + getRequestContext()); + } + } else { + // OSR windows cannot be reparented after creation. + setFocus(true); + } + } + + @Override + public boolean getScreenInfo(CefBrowser browser, CefScreenInfo screenInfo) { + screenInfo.Set(scaleFactor_, depth, depth_per_component, false, browser_rect_.getBounds(), + browser_rect_.getBounds()); + + return true; + } + + @Override + public CompletableFuture createScreenshot(boolean nativeResolution) { + throw new NotImplementedException("createScreenshot not implemented on MCEF"); + } } diff --git a/src/main/java/org/cef/browser/CefBrowserWr.java b/src/main/java/org/cef/browser/CefBrowserWr.java index 0185d148..b142bc5c 100644 --- a/src/main/java/org/cef/browser/CefBrowserWr.java +++ b/src/main/java/org/cef/browser/CefBrowserWr.java @@ -4,12 +4,18 @@ package org.cef.browser; +import org.cef.CefClient; +import org.cef.OS; +import org.cef.handler.CefWindowHandler; +import org.cef.handler.CefWindowHandlerAdapter; + import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; +import java.awt.Graphics2D; import java.awt.MouseInfo; import java.awt.Point; import java.awt.Rectangle; @@ -24,7 +30,9 @@ import java.awt.event.HierarchyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; +import java.awt.image.BufferedImage; import java.util.Date; +import java.util.concurrent.CompletableFuture; import javax.swing.JPanel; import javax.swing.JPopupMenu; @@ -33,11 +41,6 @@ import javax.swing.Timer; import javax.swing.ToolTipManager; -import org.cef.CefClient; -import org.cef.OS; -import org.cef.handler.CefWindowHandler; -import org.cef.handler.CefWindowHandlerAdapter; - /** * This class represents a windowed rendered browser. * The visibility of this class is "package". To create a new @@ -49,14 +52,14 @@ class CefBrowserWr extends CefBrowser_N { private Rectangle content_rect_ = new Rectangle(0, 0, 0, 0); private long window_handle_ = 0; private boolean justCreated_ = false; + private double scaleFactor_ = 1.0; private Timer delayedUpdate_ = new Timer(100, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { - if (isClosed()) - return; + if (isClosed()) return; boolean hasCreatedUI = createBrowserIfRequired(true); @@ -149,7 +152,7 @@ public int getClickCount(int event, int button) { if (currTime > nextClick[idx]) { nextClick[idx] = currTime + (Integer) Toolkit.getDefaultToolkit().getDesktopProperty( - "awt.multiClickInterval"); + "awt.multiClickInterval"); clickCnt[idx] = 1; } else { clickCnt[idx]++; @@ -186,7 +189,7 @@ private CefBrowserWr(CefClient client, String url, CefRequestContext context, @Override public void setBounds(int x, int y, int width, int height) { super.setBounds(x, y, width, height); - wasResized(width, height); + wasResized((int) (width * scaleFactor_), (int) (height * scaleFactor_)); } @Override @@ -197,7 +200,7 @@ public void setBounds(Rectangle r) { @Override public void setSize(int width, int height) { super.setSize(width, height); - wasResized(width, height); + wasResized((int) (width * scaleFactor_), (int) (height * scaleFactor_)); } @Override @@ -215,6 +218,9 @@ public void paint(Graphics g) { // we're setting up a delayedUpdate timer which is reset each time // paint is called. This prevents the us of sending the UI update too // often. + if (g instanceof Graphics2D) { + scaleFactor_ = ((Graphics2D) g).getTransform().getScaleX(); + } doUpdate(); delayedUpdate_.restart(); } @@ -344,7 +350,10 @@ private static long getWindowHandle(Component component) { private void doUpdate() { if (isClosed()) return; - Rectangle clipping = ((JPanel) component_).getVisibleRect(); + Rectangle vr = ((JPanel) component_).getVisibleRect(); + Rectangle clipping = new Rectangle((int) (vr.getX() * scaleFactor_), + (int) (vr.getY() * scaleFactor_), (int) (vr.getWidth() * scaleFactor_), + (int) (vr.getHeight() * scaleFactor_)); if (OS.isMacintosh()) { Container parent = component_.getParent(); @@ -369,7 +378,11 @@ private void doUpdate() { } } else { synchronized (content_rect_) { - content_rect_ = component_.getBounds(); + Rectangle bounds = component_.getBounds(); + content_rect_ = new Rectangle((int) (bounds.getX() * scaleFactor_), + (int) (bounds.getY() * scaleFactor_), + (int) (bounds.getWidth() * scaleFactor_), + (int) (bounds.getHeight() * scaleFactor_)); updateUI(clipping, content_rect_); } } @@ -403,4 +416,9 @@ private boolean createBrowserIfRequired(boolean hasParent) { return false; } + + @Override + public CompletableFuture createScreenshot(boolean nativeResolution) { + throw new UnsupportedOperationException("Unsupported for windowed rendering"); + } } diff --git a/src/main/java/org/cef/browser/CefBrowser_N.java b/src/main/java/org/cef/browser/CefBrowser_N.java index ba65fdb5..03116535 100644 --- a/src/main/java/org/cef/browser/CefBrowser_N.java +++ b/src/main/java/org/cef/browser/CefBrowser_N.java @@ -4,19 +4,6 @@ package org.cef.browser; -import java.awt.event.KeyEvent; -import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; -import java.awt.Canvas; -import java.awt.Component; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.Window; -import java.awt.event.WindowEvent; -import java.util.Vector; - -import javax.swing.SwingUtilities; - import org.cef.CefClient; import org.cef.browser.CefRequestContext; import org.cef.callback.CefDragData; @@ -25,12 +12,25 @@ import org.cef.callback.CefRunFileDialogCallback; import org.cef.callback.CefStringVisitor; import org.cef.handler.CefClientHandler; -import org.cef.handler.CefRenderHandler; import org.cef.handler.CefDialogHandler.FileDialogMode; +import org.cef.handler.CefRenderHandler; import org.cef.handler.CefWindowHandler; import org.cef.misc.CefPdfPrintSettings; import org.cef.network.CefRequest; +import java.awt.Canvas; +import java.awt.Component; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Window; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.awt.event.MouseWheelEvent; +import java.awt.event.WindowEvent; +import java.util.Vector; + +import javax.swing.SwingUtilities; + /** * This class represents all methods which are connected to the * native counterpart CEF. @@ -38,15 +38,16 @@ * CefBrowser instance, please use CefBrowserFactory. */ abstract class CefBrowser_N extends CefNativeAdapter implements CefBrowser { - private boolean isPending_ = false; - private CefClient client_; - private String url_; - private CefRequestContext request_context_; - private CefBrowser_N parent_ = null; - private Point inspectAt_ = null; - private CefBrowser_N devTools_ = null; + private volatile boolean isPending_ = false; + private final CefClient client_; + private final String url_; + private final CefRequestContext request_context_; + private volatile CefBrowser_N parent_ = null; + private volatile Point inspectAt_ = null; + private volatile CefBrowser_N devTools_ = null; private boolean closeAllowed_ = false; - private boolean isClosed_ = false; + private volatile boolean isClosed_ = false; + private volatile boolean isClosing_ = false; protected CefBrowser_N(CefClient client, String url, CefRequestContext context, CefBrowser_N parent, Point inspectAt) { @@ -154,7 +155,7 @@ protected void createBrowser(CefClientHandler clientHandler, long windowHandle, boolean osr, boolean transparent, Component canvas, CefRequestContext context) { if (getNativeRef("CefBrowser") == 0 && !isPending_) { try { - isPending_ = N_CreateBrowser( + N_CreateBrowser( clientHandler, windowHandle, url, osr, transparent, canvas, context); } catch (UnsatisfiedLinkError err) { err.printStackTrace(); @@ -162,6 +163,13 @@ protected void createBrowser(CefClientHandler clientHandler, long windowHandle, } } + /** + * Called async from the (native) main UI thread. + */ + private void notifyBrowserCreated() { + isPending_ = true; + } + /** * Create a new browser as dev tools */ @@ -413,15 +421,6 @@ public void loadURL(String url) { } } - @Override - public void loadString(String val, String url) { - try { - N_LoadString(val, url); - } catch (UnsatisfiedLinkError ule) { - ule.printStackTrace(); - } - } - @Override public void executeJavaScript(String code, String url, int line) { try { @@ -443,6 +442,9 @@ public String getURL() { @Override public void close(boolean force) { + if (isClosing_ || isClosed_) return; + if (force) isClosing_ = true; + try { N_Close(force); } catch (UnsatisfiedLinkError ule) { @@ -729,6 +731,8 @@ protected final void updateUI(Rectangle contentRect, Rectangle browserRect) { } protected final void setParent(long windowHandle, Component canvas) { + if (isClosing_ || isClosed_) return; + try { N_SetParent(windowHandle, canvas); } catch (UnsatisfiedLinkError ule) { @@ -777,7 +781,6 @@ private final native boolean N_CreateDevTools(CefBrowser parent, CefClientHandle private final native void N_GetText(CefStringVisitor visitor); private final native void N_LoadRequest(CefRequest request); private final native void N_LoadURL(String url); - private final native void N_LoadString(String val, String url); private final native void N_ExecuteJavaScript(String code, String url, int line); private final native String N_GetURL(); private final native void N_Close(boolean force); diff --git a/src/main/java/org/cef/browser/CefDropTargetListenerOsr.java b/src/main/java/org/cef/browser/CefDropTargetListener.java similarity index 90% rename from src/main/java/org/cef/browser/CefDropTargetListenerOsr.java rename to src/main/java/org/cef/browser/CefDropTargetListener.java index 792d9fda..e5e0be03 100644 --- a/src/main/java/org/cef/browser/CefDropTargetListenerOsr.java +++ b/src/main/java/org/cef/browser/CefDropTargetListener.java @@ -18,14 +18,14 @@ import java.io.File; import java.util.List; -class CefDropTargetListenerOsr implements DropTargetListener { - private CefBrowserOsr browser_; +class CefDropTargetListener implements DropTargetListener { + private CefBrowser_N browser_; private CefDragData dragData_ = null; private int dragOperations_ = CefDragData.DragOperations.DRAG_OPERATION_COPY; private int dragModifiers_ = EventFlags.EVENTFLAG_NONE; private int acceptOperations_ = DnDConstants.ACTION_COPY; - CefDropTargetListenerOsr(CefBrowserOsr browser) { + CefDropTargetListener(CefBrowser_N browser) { browser_ = browser; } @@ -106,8 +106,11 @@ private static CefDragData createDragData(DropTargetDragEvent event) { DataFlavor[] flavors = transferable.getTransferDataFlavors(); for (DataFlavor flavor : flavors) { try { - // TODO(JCEF): Add support for other flavor types. - if (flavor.isFlavorJavaFileListType()) { + if (flavor.isFlavorTextType()) { + Object ob = transferable.getTransferData(flavor); + if (!(ob instanceof String)) continue; + dragData.setFragmentText((String) ob); + } else if (flavor.isFlavorJavaFileListType()) { List files = (List) transferable.getTransferData(flavor); for (File file : files) { dragData.addFile(file.getPath(), file.getName()); diff --git a/src/main/java/org/cef/browser/CefFrame.java b/src/main/java/org/cef/browser/CefFrame.java index c308f660..3a2393fb 100644 --- a/src/main/java/org/cef/browser/CefFrame.java +++ b/src/main/java/org/cef/browser/CefFrame.java @@ -8,6 +8,11 @@ * Interface representing a frame. */ public interface CefFrame { + /** + * Removes the native reference from an unused object. + */ + void dispose(); + /** * Returns the globally unique identifier for this frame or < 0 if the * underlying frame does not yet exist. @@ -68,4 +73,29 @@ public interface CefFrame { * @param line The base line number to use for error reporting. */ public void executeJavaScript(String code, String url, int line); + + /** + * Execute undo in this frame. + */ + public void undo(); + + /** + * Execute redo in this frame. + */ + public void redo(); + + /** + * Execute cut in this frame. + */ + public void cut(); + + /** + * Execute copy in this frame. + */ + public void copy(); + + /** + * Execute paste in this frame. + */ + public void paste(); } \ No newline at end of file diff --git a/src/main/java/org/cef/browser/CefFrame_N.java b/src/main/java/org/cef/browser/CefFrame_N.java index 30f0f073..8e129f1a 100644 --- a/src/main/java/org/cef/browser/CefFrame_N.java +++ b/src/main/java/org/cef/browser/CefFrame_N.java @@ -12,21 +12,27 @@ * The visibility of this class is "package". */ class CefFrame_N extends CefNativeAdapter implements CefFrame { + CefFrame_N() {} + @Override protected void finalize() throws Throwable { + dispose(); + super.finalize(); + } + + @Override + public void dispose() { try { - N_CefFrame_DTOR(); + N_Dispose(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); - } finally { - super.finalize(); } } @Override public long getIdentifier() { try { - return N_GetIdentifier(); + return N_GetIdentifier(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); return -1; @@ -36,7 +42,7 @@ public long getIdentifier() { @Override public String getURL() { try { - return N_GetURL(); + return N_GetURL(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); return null; @@ -46,7 +52,7 @@ public String getURL() { @Override public String getName() { try { - return N_GetName(); + return N_GetName(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); return null; @@ -56,7 +62,7 @@ public String getName() { @Override public boolean isMain() { try { - return N_IsMain(); + return N_IsMain(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); return false; @@ -66,7 +72,7 @@ public boolean isMain() { @Override public boolean isValid() { try { - return N_IsValid(); + return N_IsValid(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); return false; @@ -76,7 +82,7 @@ public boolean isValid() { @Override public boolean isFocused() { try { - return N_IsFocused(); + return N_IsFocused(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); return false; @@ -86,7 +92,7 @@ public boolean isFocused() { @Override public CefFrame getParent() { try { - return N_GetParent(); + return N_GetParent(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); return null; @@ -96,19 +102,64 @@ public CefFrame getParent() { @Override public void executeJavaScript(String code, String url, int line) { try { - N_ExecuteJavaScript(code, url, line); + N_ExecuteJavaScript(getNativeRef(null), code, url, line); + } catch (UnsatisfiedLinkError ule) { + ule.printStackTrace(); + } + } + + public void undo() { + try { + N_Undo(getNativeRef(null)); + } catch (UnsatisfiedLinkError ule) { + ule.printStackTrace(); + } + } + + public void redo() { + try { + N_Redo(getNativeRef(null)); + } catch (UnsatisfiedLinkError ule) { + ule.printStackTrace(); + } + } + + public void cut() { + try { + N_Cut(getNativeRef(null)); + } catch (UnsatisfiedLinkError ule) { + ule.printStackTrace(); + } + } + + public void copy() { + try { + N_Copy(getNativeRef(null)); + } catch (UnsatisfiedLinkError ule) { + ule.printStackTrace(); + } + } + + public void paste() { + try { + N_Paste(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } } - private final native void N_CefFrame_DTOR(); - private final native int N_GetIdentifier(); - private final native String N_GetURL(); - private final native String N_GetName(); - private final native boolean N_IsMain(); - private final native boolean N_IsValid(); - private final native boolean N_IsFocused(); - private final native CefFrame N_GetParent(); - private final native void N_ExecuteJavaScript(String code, String url, int line); -} \ No newline at end of file + private final native void N_Dispose(long self); + private final native long N_GetIdentifier(long self); + private final native String N_GetURL(long self); + private final native String N_GetName(long self); + private final native boolean N_IsMain(long self); + private final native boolean N_IsValid(long self); + private final native boolean N_IsFocused(long self); + private final native CefFrame N_GetParent(long self); + private final native void N_ExecuteJavaScript(long self, String code, String url, int line); + private final native void N_Undo(long self); + private final native void N_Redo(long self); + private final native void N_Cut(long self); + private final native void N_Copy(long self); + private final native void N_Paste(long self); +} diff --git a/src/main/java/org/cef/browser/CefMessageRouter.java b/src/main/java/org/cef/browser/CefMessageRouter.java index 66c08dfe..1fdfd690 100644 --- a/src/main/java/org/cef/browser/CefMessageRouter.java +++ b/src/main/java/org/cef/browser/CefMessageRouter.java @@ -142,7 +142,7 @@ * 6. Notice that the success callback is executed in JavaScript. */ public abstract class CefMessageRouter { - private final CefMessageRouterConfig routerConfig_; + private CefMessageRouterConfig routerConfig_ = null; /** * Used to configure the query router. If using multiple router pairs make @@ -172,28 +172,40 @@ public CefMessageRouterConfig(String queryFunction, String cancelFunction) { } // This CTOR can't be called directly. Call method create() instead. - CefMessageRouter(CefMessageRouterConfig routerConfig) { - routerConfig_ = routerConfig; + CefMessageRouter() {} + + @Override + protected void finalize() throws Throwable { + dispose(); + super.finalize(); } /** - * Create a new router with the specified configuration. - * - * @param config router configuration - * @return + * Create a new router with the default configuration. The addHandler() method should be called + * to add a handler. */ public static final CefMessageRouter create() { return CefMessageRouter.create(null, null); } + /** + * Create a new router with the specified configuration. The addHandler() method should be + * called to add a handler. + */ public static final CefMessageRouter create(CefMessageRouterConfig config) { return CefMessageRouter.create(config, null); } + /** + * Create a new router with the specified handler and default configuration. + */ public static final CefMessageRouter create(CefMessageRouterHandler handler) { return CefMessageRouter.create(null, handler); } + /** + * Create a new router with the specified handler and configuration. + */ public static final CefMessageRouter create( CefMessageRouterConfig config, CefMessageRouterHandler handler) { CefMessageRouter router = CefMessageRouter_N.createNative(config); @@ -202,60 +214,48 @@ public static final CefMessageRouter create( } /** - * Must be called if the CefMessageRouter instance isn't used any more + * Must be called if the CefMessageRouter instance isn't used any more. */ public abstract void dispose(); + // Called from native code during handling of createNative(). + void setMessageRouterConfig(CefMessageRouterConfig config) { + routerConfig_ = config; + } + + // Called from native code during handling of CefClientHandler.[add|remove]MessageRouter(). public final CefMessageRouterConfig getMessageRouterConfig() { return routerConfig_; } /** - * Add a new query handler. If |first| is true it will be added as the first - * handler, otherwise it will be added as the last handler. Returns true if - * the handler is added successfully or false if the handler has already been - * added. Must be called on the browser process UI thread. The Handler object - * must either outlive the router or be removed before deletion. + * Add a new query handler. * - * @param handler the according handler to be added - * @param first if If set to true it will be added as the first handler - * @return true if the handler is added successfully + * @param handler The handler to be added. + * @param first If true the handler will be added as the first handler, otherwise it will be + * added as the last handler. + * @return True if the handler is added successfully. */ public abstract boolean addHandler(CefMessageRouterHandler handler, boolean first); /** - * Remove an existing query handler. Any pending queries associated with the - * handler will be canceled. Handler.OnQueryCanceled will be called and the - * associated JavaScript onFailure callback will be executed with an error - * code of -1. Returns true if the handler is removed successfully or false - * if the handler is not found. Must be called on the browser process UI - * thread. + * Remove an existing query handler. Any pending queries associated with the handler will be + * canceled. onQueryCanceled will be called and the associated JavaScript onFailure callback + * will be executed with an error code of -1. * - * @param handler the according handler to be removed - * @return true if the handler is removed successfully + * @param handler The handler to be removed. + * @return True if the handler is removed successfully. */ public abstract boolean removeHandler(CefMessageRouterHandler handler); /** - * Cancel all pending queries associated with either |browser| or |handler|. - * If both |browser| and |handler| are NULL all pending queries will be - * canceled. Handler::OnQueryCanceled will be called and the associated - * JavaScript onFailure callback will be executed in all cases with an error + * Cancel all pending queries associated with either |browser| or |handler|. If both |browser| + * and |handler| are NULL all pending queries will be canceled. onQueryCanceled will be called + * and the associated JavaScript onFailure callback will be executed in all cases with an error * code of -1. * - * @param browser may be empty - * @param handler may be empty + * @param browser The associated browser, or null. + * @param handler The associated handler, or null. */ public abstract void cancelPending(CefBrowser browser, CefMessageRouterHandler handler); - - /** - * Returns the number of queries currently pending for the specified |browser| - * and/or |handler|. Either or both values may be empty. Must be called on the - * browser process UI thread. - * - * @param browser may be empty - * @param handler may be empty - * @return the number of queries currently pending - */ - public abstract int getPendingCount(CefBrowser browser, CefMessageRouterHandler handler); } diff --git a/src/main/java/org/cef/browser/CefMessageRouter_N.java b/src/main/java/org/cef/browser/CefMessageRouter_N.java index 16809fb1..5f8fefde 100644 --- a/src/main/java/org/cef/browser/CefMessageRouter_N.java +++ b/src/main/java/org/cef/browser/CefMessageRouter_N.java @@ -21,26 +21,23 @@ public long getNativeRef(String identifer) { return N_CefHandle; } - private CefMessageRouter_N(CefMessageRouterConfig config) { - super(config); + private CefMessageRouter_N() { + super(); } public static final CefMessageRouter createNative(CefMessageRouterConfig config) { - // keep a reference to the request and client objects. - CefMessageRouter_N result = new CefMessageRouter_N(config); try { - result.N_Create(config); + return CefMessageRouter_N.N_Create(config); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); + return null; } - if (result.N_CefHandle == 0) return null; - return result; } @Override public void dispose() { try { - N_Dispose(); + N_Dispose(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -49,7 +46,7 @@ public void dispose() { @Override public boolean addHandler(CefMessageRouterHandler handler, boolean first) { try { - return N_AddHandler(handler, first); + return N_AddHandler(N_CefHandle, handler, first); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); return false; @@ -59,7 +56,7 @@ public boolean addHandler(CefMessageRouterHandler handler, boolean first) { @Override public boolean removeHandler(CefMessageRouterHandler handler) { try { - return N_RemoveHandler(handler); + return N_RemoveHandler(N_CefHandle, handler); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); return false; @@ -69,26 +66,17 @@ public boolean removeHandler(CefMessageRouterHandler handler) { @Override public void cancelPending(CefBrowser browser, CefMessageRouterHandler handler) { try { - N_CancelPending(browser, handler); + N_CancelPending(N_CefHandle, browser, handler); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } } - @Override - public int getPendingCount(CefBrowser browser, CefMessageRouterHandler handler) { - try { - return N_GetPendingCount(browser, handler); - } catch (UnsatisfiedLinkError ule) { - ule.printStackTrace(); - return 0; - } - } - - private final native void N_Create(CefMessageRouterConfig config); - private final native void N_Dispose(); - private final native boolean N_AddHandler(CefMessageRouterHandler handler, boolean first); - private final native boolean N_RemoveHandler(CefMessageRouterHandler handler); - private final native void N_CancelPending(CefBrowser browser, CefMessageRouterHandler handler); - private final native int N_GetPendingCount(CefBrowser browser, CefMessageRouterHandler handler); + private final native static CefMessageRouter_N N_Create(CefMessageRouterConfig config); + private final native void N_Dispose(long self); + private final native boolean N_AddHandler( + long self, CefMessageRouterHandler handler, boolean first); + private final native boolean N_RemoveHandler(long self, CefMessageRouterHandler handler); + private final native void N_CancelPending( + long self, CefBrowser browser, CefMessageRouterHandler handler); } diff --git a/src/main/java/org/cef/browser/CefRenderer.java b/src/main/java/org/cef/browser/CefRenderer.java index b281d062..d453eba7 100644 --- a/src/main/java/org/cef/browser/CefRenderer.java +++ b/src/main/java/org/cef/browser/CefRenderer.java @@ -2,29 +2,28 @@ // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. -// Modified by montoyo for MCEF - package org.cef.browser; -import java.awt.Rectangle; -import java.nio.ByteBuffer; -import java.util.ArrayList; - import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; - import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.montoyo.mcef.MCEF; import net.montoyo.mcef.utilities.Log; import org.lwjgl.opengl.EXTBgra; +import java.awt.*; +import java.nio.ByteBuffer; +import java.util.ArrayList; + import static org.lwjgl.opengl.GL11.*; public class CefRenderer { + //montoyo: debug tool //montoyo: debug tool private static final ArrayList GL_TEXTURES = new ArrayList<>(); + public static void dumpVRAMLeak() { Log.info(">>>>> MCEF: Beginning VRAM leak report"); GL_TEXTURES.forEach(tex -> Log.warning(">>>>> MCEF: This texture has not been freed: " + tex)); @@ -35,8 +34,11 @@ public static void dumpVRAMLeak() { public int[] texture_id_ = new int[1]; private int view_width_ = 0; private int view_height_ = 0; + private float spin_x_ = 0f; + private float spin_y_ = 0f; private Rectangle popup_rect_ = new Rectangle(0, 0, 0, 0); private Rectangle original_popup_rect_ = new Rectangle(0, 0, 0, 0); + private boolean use_draw_pixels_ = false; protected CefRenderer(boolean transparent) { transparent_ = transparent; @@ -47,12 +49,15 @@ protected boolean isTransparent() { return transparent_; } - @SuppressWarnings("static-access") + protected int getTextureID() { + return texture_id_[0]; + } + protected void initialize() { GlStateManager.enableTexture2D(); texture_id_[0] = glGenTextures(); - if(MCEF.CHECK_VRAM_LEAK) + if (MCEF.CHECK_VRAM_LEAK) GL_TEXTURES.add(texture_id_[0]); GlStateManager.bindTexture(texture_id_[0]); @@ -63,16 +68,16 @@ protected void initialize() { } protected void cleanup() { - if(texture_id_[0] != 0) { - if(MCEF.CHECK_VRAM_LEAK) + if (texture_id_[0] != 0) { + if (MCEF.CHECK_VRAM_LEAK) GL_TEXTURES.remove((Object) texture_id_[0]); glDeleteTextures(texture_id_[0]); } } - public void render(double x1, double y1, double x2, double y2) { - if(view_width_ == 0 || view_height_ == 0) + protected void render(double x1, double y1, double x2, double y2) { + if (view_width_ == 0 || view_height_ == 0) return; Tessellator t = Tessellator.getInstance(); @@ -89,28 +94,26 @@ public void render(double x1, double y1, double x2, double y2) { } protected void onPopupSize(Rectangle rect) { - if(rect.width <= 0 || rect.height <= 0) - return; + if (rect.width <= 0 || rect.height <= 0) return; original_popup_rect_ = rect; popup_rect_ = getPopupRectInWebView(original_popup_rect_); } - protected Rectangle getPopupRectInWebView(Rectangle rc) { + protected Rectangle getPopupRect() { + return (Rectangle) popup_rect_.clone(); + } + + protected Rectangle getPopupRectInWebView(Rectangle original_rect) { + Rectangle rc = original_rect; // if x or y are negative, move them to 0. - if(rc.x < 0) - rc.x = 0; - if(rc.y < 0) - rc.y = 0; + if (rc.x < 0) rc.x = 0; + if (rc.y < 0) rc.y = 0; // if popup goes outside the view, try to reposition origin - if(rc.x + rc.width > view_width_) - rc.x = view_width_ - rc.width; - if(rc.y + rc.height > view_height_) - rc.y = view_height_ - rc.height; + if (rc.x + rc.width > view_width_) rc.x = view_width_ - rc.width; + if (rc.y + rc.height > view_height_) rc.y = view_height_ - rc.height; // if x or y became negative, move them to 0 again. - if(rc.x < 0) - rc.x = 0; - if(rc.y < 0) - rc.y = 0; + if (rc.x < 0) rc.x = 0; + if (rc.y < 0) rc.y = 0; return rc; } @@ -120,11 +123,11 @@ protected void clearPopupRects() { } protected void onPaint(boolean popup, Rectangle[] dirtyRects, ByteBuffer buffer, int width, int height, boolean completeReRender) { - if(transparent_) // Enable alpha blending. + if (transparent_) // Enable alpha blending. GlStateManager.enableBlend(); final int size = (width * height) << 2; - if(size > buffer.limit()) { + if (size > buffer.limit()) { Log.warning("Bad data passed to CefRenderer.onPaint() triggered safe guards... (1)"); return; } @@ -136,8 +139,8 @@ protected void onPaint(boolean popup, Rectangle[] dirtyRects, ByteBuffer buffer, int oldAlignement = glGetInteger(GL_UNPACK_ALIGNMENT); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - if(!popup) { - if(completeReRender || width != view_width_ || height != view_height_) { + if (!popup) { + if (completeReRender || width != view_width_ || height != view_height_) { // Update/resize the whole texture. view_width_ = width; view_height_ = height; @@ -146,8 +149,8 @@ protected void onPaint(boolean popup, Rectangle[] dirtyRects, ByteBuffer buffer, glPixelStorei(GL_UNPACK_ROW_LENGTH, view_width_); // Update just the dirty rectangles. - for(Rectangle rect: dirtyRects) { - if(rect.x < 0 || rect.y < 0 || rect.x + rect.width > view_width_ || rect.y + rect.height > view_height_) + for (Rectangle rect : dirtyRects) { + if (rect.x < 0 || rect.y < 0 || rect.x + rect.width > view_width_ || rect.y + rect.height > view_height_) Log.warning("Bad data passed to CefRenderer.onPaint() triggered safe guards... (2)"); else { glPixelStorei(GL_UNPACK_SKIP_PIXELS, rect.x); @@ -160,24 +163,24 @@ protected void onPaint(boolean popup, Rectangle[] dirtyRects, ByteBuffer buffer, glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); } - } else if(popup_rect_.width > 0 && popup_rect_.height > 0) { + } else if (popup_rect_.width > 0 && popup_rect_.height > 0) { int skip_pixels = 0, x = popup_rect_.x; int skip_rows = 0, y = popup_rect_.y; int w = width; int h = height; // Adjust the popup to fit inside the view. - if(x < 0) { + if (x < 0) { skip_pixels = -x; x = 0; } - if(y < 0) { + if (y < 0) { skip_rows = -y; y = 0; } - if(x + w > view_width_) + if (x + w > view_width_) w -= x + w - view_width_; - if(y + h > view_height_) + if (y + h > view_height_) h -= y + h - view_height_; // Update the popup rectangle. @@ -194,12 +197,13 @@ protected void onPaint(boolean popup, Rectangle[] dirtyRects, ByteBuffer buffer, GlStateManager.bindTexture(0); } - public int getViewWidth() { - return view_width_; + protected void setSpin(float spinX, float spinY) { + spin_x_ = spinX; + spin_y_ = spinY; } - public int getViewHeight() { - return view_height_; + protected void incrementSpin(float spinDX, float spinDY) { + spin_x_ -= spinDX; + spin_y_ -= spinDY; } - } diff --git a/src/main/java/org/cef/browser/mac/CefBrowserWindowMac.java b/src/main/java/org/cef/browser/mac/CefBrowserWindowMac.java index 6aabc1eb..e2d9b0d2 100644 --- a/src/main/java/org/cef/browser/mac/CefBrowserWindowMac.java +++ b/src/main/java/org/cef/browser/mac/CefBrowserWindowMac.java @@ -4,15 +4,13 @@ package org.cef.browser.mac; -import java.awt.Component; - import org.cef.browser.CefBrowserWindow; -public class CefBrowserWindowMac implements CefBrowserWindow { +import java.awt.*; +public class CefBrowserWindowMac implements CefBrowserWindow { @Override public long getWindowHandle(Component comp) { - return 0; + return 0L; } - } diff --git a/src/main/java/org/cef/callback/CefBeforeDownloadCallback_N.java b/src/main/java/org/cef/callback/CefBeforeDownloadCallback_N.java index 4e53d9d1..93a14f24 100644 --- a/src/main/java/org/cef/callback/CefBeforeDownloadCallback_N.java +++ b/src/main/java/org/cef/callback/CefBeforeDownloadCallback_N.java @@ -7,14 +7,20 @@ class CefBeforeDownloadCallback_N extends CefNativeAdapter implements CefBeforeDownloadCallback { CefBeforeDownloadCallback_N() {} + @Override + protected void finalize() throws Throwable { + Continue("", false); + super.finalize(); + } + @Override public void Continue(String downloadPath, boolean showDialog) { try { - N_Continue(downloadPath, showDialog); + N_Continue(getNativeRef(null), downloadPath, showDialog); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } } - private final native void N_Continue(String downloadPath, boolean showDialog); + private final native void N_Continue(long self, String downloadPath, boolean showDialog); } diff --git a/src/main/java/org/cef/callback/CefCommandLine.java b/src/main/java/org/cef/callback/CefCommandLine.java index 65a553b9..1daeba4b 100644 --- a/src/main/java/org/cef/callback/CefCommandLine.java +++ b/src/main/java/org/cef/callback/CefCommandLine.java @@ -22,26 +22,31 @@ public interface CefCommandLine { * component unchanged. */ public void reset(); + /** * Get the program part of the command line string (the first item). */ public String getProgram(); + /** * Set the program part of the command line string (the first item). * @param program Name of the program. */ public void setProgram(String program); + /** * Checks if the command line has switches. * @return true if the command line has switches. */ public boolean hasSwitches(); + /** * Checks if the command line has a specific switches. * @param name A switch name to test for. * @return true if the command line contains the given switch. */ public boolean hasSwitch(String name); + /** * Returns the value associated with the given switch. If the switch has no * value or isn't present this method returns the empty string. @@ -49,33 +54,39 @@ public interface CefCommandLine { * @return the value of the switch. */ public String getSwitchValue(String name); + /** * Returns the map of switch names and values. If a switch has no value an * empty string is returned. * @return Map of switches and each value. */ public Map getSwitches(); + /** * Add a switch with an empty value to the end of the command line. * @param name name of the switch. */ public void appendSwitch(String name); + /** * Add a switch with the specified value to the end of the command line. * @param name name of the switch. * @param value value for the switch. */ public void appendSwitchWithValue(String name, String value); + /** * Tests if there are remaining command line arguments. * @return True if there are remaining command line arguments. */ public boolean hasArguments(); + /** * Get the remaining command line arguments. * @return Vector of command line arguments. */ public Vector getArguments(); + /** * Add an argument to the end of the command line. * @param argument name of the argument. diff --git a/src/main/java/org/cef/callback/CefCommandLine_N.java b/src/main/java/org/cef/callback/CefCommandLine_N.java index 5566c447..27881fc0 100644 --- a/src/main/java/org/cef/callback/CefCommandLine_N.java +++ b/src/main/java/org/cef/callback/CefCommandLine_N.java @@ -8,10 +8,12 @@ import java.util.Vector; class CefCommandLine_N extends CefNativeAdapter implements CefCommandLine { + CefCommandLine_N() {} + @Override public void reset() { try { - N_reset(); + N_Reset(getNativeRef(null)); } catch (UnsatisfiedLinkError err) { err.printStackTrace(); } @@ -20,7 +22,7 @@ public void reset() { @Override public String getProgram() { try { - return N_getProgram(); + return N_GetProgram(getNativeRef(null)); } catch (UnsatisfiedLinkError err) { err.printStackTrace(); } @@ -30,7 +32,7 @@ public String getProgram() { @Override public void setProgram(String program) { try { - N_setProgram(program); + N_SetProgram(getNativeRef(null), program); } catch (UnsatisfiedLinkError err) { err.printStackTrace(); } @@ -39,7 +41,7 @@ public void setProgram(String program) { @Override public boolean hasSwitches() { try { - return N_hasSwitches(); + return N_HasSwitches(getNativeRef(null)); } catch (UnsatisfiedLinkError err) { err.printStackTrace(); } @@ -49,7 +51,7 @@ public boolean hasSwitches() { @Override public boolean hasSwitch(String name) { try { - return N_hasSwitch(name); + return N_HasSwitch(getNativeRef(null), name); } catch (UnsatisfiedLinkError err) { err.printStackTrace(); } @@ -59,7 +61,7 @@ public boolean hasSwitch(String name) { @Override public String getSwitchValue(String name) { try { - return N_getSwitchValue(name); + return N_GetSwitchValue(getNativeRef(null), name); } catch (UnsatisfiedLinkError err) { err.printStackTrace(); } @@ -69,7 +71,7 @@ public String getSwitchValue(String name) { @Override public Map getSwitches() { try { - return N_getSwitches(); + return N_GetSwitches(getNativeRef(null)); } catch (UnsatisfiedLinkError err) { err.printStackTrace(); } @@ -79,7 +81,7 @@ public Map getSwitches() { @Override public void appendSwitch(String name) { try { - N_appendSwitch(name); + N_AppendSwitch(getNativeRef(null), name); } catch (UnsatisfiedLinkError err) { err.printStackTrace(); } @@ -88,7 +90,7 @@ public void appendSwitch(String name) { @Override public void appendSwitchWithValue(String name, String value) { try { - N_appendSwitchWithValue(name, value); + N_AppendSwitchWithValue(getNativeRef(null), name, value); } catch (UnsatisfiedLinkError err) { err.printStackTrace(); } @@ -97,7 +99,7 @@ public void appendSwitchWithValue(String name, String value) { @Override public boolean hasArguments() { try { - return N_hasArguments(); + return N_HasArguments(getNativeRef(null)); } catch (UnsatisfiedLinkError err) { err.printStackTrace(); } @@ -107,7 +109,7 @@ public boolean hasArguments() { @Override public Vector getArguments() { try { - return N_getArguments(); + return N_GetArguments(getNativeRef(null)); } catch (UnsatisfiedLinkError err) { err.printStackTrace(); } @@ -117,7 +119,7 @@ public Vector getArguments() { @Override public void appendArgument(String argument) { try { - N_appendArgument(argument); + N_AppendArgument(getNativeRef(null), argument); } catch (UnsatisfiedLinkError err) { err.printStackTrace(); } @@ -137,16 +139,16 @@ public String toString() { return result + "]"; } - private final native void N_reset(); - private final native String N_getProgram(); - private final native void N_setProgram(String program); - private final native boolean N_hasSwitches(); - private final native boolean N_hasSwitch(String name); - private final native String N_getSwitchValue(String name); - private final native Map N_getSwitches(); - private final native void N_appendSwitch(String name); - private final native void N_appendSwitchWithValue(String name, String value); - private final native boolean N_hasArguments(); - private final native Vector N_getArguments(); - private final native void N_appendArgument(String argument); + private final native void N_Reset(long self); + private final native String N_GetProgram(long self); + private final native void N_SetProgram(long self, String program); + private final native boolean N_HasSwitches(long self); + private final native boolean N_HasSwitch(long self, String name); + private final native String N_GetSwitchValue(long self, String name); + private final native Map N_GetSwitches(long self); + private final native void N_AppendSwitch(long self, String name); + private final native void N_AppendSwitchWithValue(long self, String name, String value); + private final native boolean N_HasArguments(long self); + private final native Vector N_GetArguments(long self); + private final native void N_AppendArgument(long self, String argument); } diff --git a/src/main/java/org/cef/callback/CefDownloadItemCallback.java b/src/main/java/org/cef/callback/CefDownloadItemCallback.java index e5ed8cdd..1e2fc347 100644 --- a/src/main/java/org/cef/callback/CefDownloadItemCallback.java +++ b/src/main/java/org/cef/callback/CefDownloadItemCallback.java @@ -5,11 +5,21 @@ package org.cef.callback; /** - * Callback interface used to asynchronously cancel a download. + * Callback interface used to asynchronously modify download status. */ public interface CefDownloadItemCallback { /** * Call to cancel the download. */ public void cancel(); + + /** + * Call to pause the download. + */ + public void pause(); + + /** + * Call to resume the download. + */ + public void resume(); } diff --git a/src/main/java/org/cef/callback/CefDownloadItemCallback_N.java b/src/main/java/org/cef/callback/CefDownloadItemCallback_N.java index 11109e51..46aace1f 100644 --- a/src/main/java/org/cef/callback/CefDownloadItemCallback_N.java +++ b/src/main/java/org/cef/callback/CefDownloadItemCallback_N.java @@ -7,14 +7,45 @@ class CefDownloadItemCallback_N extends CefNativeAdapter implements CefDownloadItemCallback { CefDownloadItemCallback_N() {} + @Override + protected void finalize() throws Throwable { + try { + N_Dispose(getNativeRef(null)); + } catch (UnsatisfiedLinkError ule) { + ule.printStackTrace(); + } + super.finalize(); + } + @Override public void cancel() { try { - N_Cancel(); + N_Cancel(getNativeRef(null)); + } catch (UnsatisfiedLinkError ule) { + ule.printStackTrace(); + } + } + + @Override + public void pause() { + try { + N_Pause(getNativeRef(null)); + } catch (UnsatisfiedLinkError ule) { + ule.printStackTrace(); + } + } + + @Override + public void resume() { + try { + N_Resume(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } } - private final native void N_Cancel(); + private final native void N_Dispose(long self); + private final native void N_Cancel(long self); + private final native void N_Pause(long self); + private final native void N_Resume(long self); } diff --git a/src/main/java/org/cef/callback/CefDownloadItem_N.java b/src/main/java/org/cef/callback/CefDownloadItem_N.java index c7dbc24f..114c4af6 100644 --- a/src/main/java/org/cef/callback/CefDownloadItem_N.java +++ b/src/main/java/org/cef/callback/CefDownloadItem_N.java @@ -7,16 +7,12 @@ import java.util.Date; class CefDownloadItem_N extends CefNativeAdapter implements CefDownloadItem { - protected void finalize() throws Throwable { - super.finalize(); - } - CefDownloadItem_N() {} @Override public boolean isValid() { try { - return N_IsValid(); + return N_IsValid(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -26,7 +22,7 @@ public boolean isValid() { @Override public boolean isInProgress() { try { - return N_IsInProgress(); + return N_IsInProgress(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -36,7 +32,7 @@ public boolean isInProgress() { @Override public boolean isComplete() { try { - return N_IsComplete(); + return N_IsComplete(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -46,7 +42,7 @@ public boolean isComplete() { @Override public boolean isCanceled() { try { - return N_IsCanceled(); + return N_IsCanceled(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -56,7 +52,7 @@ public boolean isCanceled() { @Override public long getCurrentSpeed() { try { - return N_GetCurrentSpeed(); + return N_GetCurrentSpeed(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -66,7 +62,7 @@ public long getCurrentSpeed() { @Override public int getPercentComplete() { try { - return N_GetPercentComplete(); + return N_GetPercentComplete(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -76,7 +72,7 @@ public int getPercentComplete() { @Override public long getTotalBytes() { try { - return N_GetTotalBytes(); + return N_GetTotalBytes(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -86,7 +82,7 @@ public long getTotalBytes() { @Override public long getReceivedBytes() { try { - return N_GetReceivedBytes(); + return N_GetReceivedBytes(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -96,7 +92,7 @@ public long getReceivedBytes() { @Override public Date getStartTime() { try { - return N_GetStartTime(); + return N_GetStartTime(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -106,7 +102,7 @@ public Date getStartTime() { @Override public Date getEndTime() { try { - return N_GetEndTime(); + return N_GetEndTime(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -116,7 +112,7 @@ public Date getEndTime() { @Override public String getFullPath() { try { - return N_GetFullPath(); + return N_GetFullPath(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -126,7 +122,7 @@ public String getFullPath() { @Override public int getId() { try { - return N_GetId(); + return N_GetId(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -136,7 +132,7 @@ public int getId() { @Override public String getURL() { try { - return N_GetURL(); + return N_GetURL(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -146,7 +142,7 @@ public String getURL() { @Override public String getSuggestedFileName() { try { - return N_GetSuggestedFileName(); + return N_GetSuggestedFileName(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -156,7 +152,7 @@ public String getSuggestedFileName() { @Override public String getContentDisposition() { try { - return N_GetContentDisposition(); + return N_GetContentDisposition(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -166,27 +162,27 @@ public String getContentDisposition() { @Override public String getMimeType() { try { - return N_GetMimeType(); + return N_GetMimeType(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } return null; } - private final native boolean N_IsValid(); - private final native boolean N_IsInProgress(); - private final native boolean N_IsComplete(); - private final native boolean N_IsCanceled(); - private final native long N_GetCurrentSpeed(); - private final native int N_GetPercentComplete(); - private final native long N_GetTotalBytes(); - private final native long N_GetReceivedBytes(); - private final native Date N_GetStartTime(); - private final native Date N_GetEndTime(); - private final native String N_GetFullPath(); - private final native int N_GetId(); - private final native String N_GetURL(); - private final native String N_GetSuggestedFileName(); - private final native String N_GetContentDisposition(); - private final native String N_GetMimeType(); + private final native boolean N_IsValid(long self); + private final native boolean N_IsInProgress(long self); + private final native boolean N_IsComplete(long self); + private final native boolean N_IsCanceled(long self); + private final native long N_GetCurrentSpeed(long self); + private final native int N_GetPercentComplete(long self); + private final native long N_GetTotalBytes(long self); + private final native long N_GetReceivedBytes(long self); + private final native Date N_GetStartTime(long self); + private final native Date N_GetEndTime(long self); + private final native String N_GetFullPath(long self); + private final native int N_GetId(long self); + private final native String N_GetURL(long self); + private final native String N_GetSuggestedFileName(long self); + private final native String N_GetContentDisposition(long self); + private final native String N_GetMimeType(long self); } diff --git a/src/main/java/org/cef/callback/CefFileDialogCallback_N.java b/src/main/java/org/cef/callback/CefFileDialogCallback_N.java index 200ff5d8..de3d5410 100644 --- a/src/main/java/org/cef/callback/CefFileDialogCallback_N.java +++ b/src/main/java/org/cef/callback/CefFileDialogCallback_N.java @@ -9,10 +9,16 @@ class CefFileDialogCallback_N extends CefNativeAdapter implements CefFileDialogCallback { CefFileDialogCallback_N() {} + @Override + protected void finalize() throws Throwable { + Cancel(); + super.finalize(); + } + @Override public void Continue(int selectedAcceptFilter, Vector filePaths) { try { - N_Continue(selectedAcceptFilter, filePaths); + N_Continue(getNativeRef(null), selectedAcceptFilter, filePaths); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -21,12 +27,13 @@ public void Continue(int selectedAcceptFilter, Vector filePaths) { @Override public void Cancel() { try { - N_Cancel(); + N_Cancel(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } } - private final native void N_Continue(int selectedAcceptFilter, Vector filePaths); - private final native void N_Cancel(); + private final native void N_Continue( + long self, int selectedAcceptFilter, Vector filePaths); + private final native void N_Cancel(long self); } diff --git a/src/main/java/org/cef/callback/CefJSDialogCallback_N.java b/src/main/java/org/cef/callback/CefJSDialogCallback_N.java index a99fd5df..6256d3de 100644 --- a/src/main/java/org/cef/callback/CefJSDialogCallback_N.java +++ b/src/main/java/org/cef/callback/CefJSDialogCallback_N.java @@ -7,14 +7,20 @@ class CefJSDialogCallback_N extends CefNativeAdapter implements CefJSDialogCallback { CefJSDialogCallback_N() {} + @Override + protected void finalize() throws Throwable { + Continue(false, ""); + super.finalize(); + } + @Override public void Continue(boolean success, String user_input) { try { - N_Continue(success, user_input); + N_Continue(getNativeRef(null), success, user_input); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } } - private final native void N_Continue(boolean success, String user_input); + private final native void N_Continue(long self, boolean success, String user_input); } diff --git a/src/main/java/org/cef/callback/CefPrintDialogCallback_N.java b/src/main/java/org/cef/callback/CefPrintDialogCallback_N.java index 63e35d43..8883906b 100644 --- a/src/main/java/org/cef/callback/CefPrintDialogCallback_N.java +++ b/src/main/java/org/cef/callback/CefPrintDialogCallback_N.java @@ -9,10 +9,16 @@ class CefPrintDialogCallback_N extends CefNativeAdapter implements CefPrintDialogCallback { CefPrintDialogCallback_N() {} + @Override + protected void finalize() throws Throwable { + cancel(); + super.finalize(); + } + @Override public void Continue(CefPrintSettings settings) { try { - N_Continue(settings); + N_Continue(getNativeRef(null), settings); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -21,12 +27,12 @@ public void Continue(CefPrintSettings settings) { @Override public void cancel() { try { - N_Cancel(); + N_Cancel(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } } - private final native void N_Continue(CefPrintSettings settings); - private final native void N_Cancel(); + private final native void N_Continue(long self, CefPrintSettings settings); + private final native void N_Cancel(long self); } diff --git a/src/main/java/org/cef/callback/CefPrintJobCallback_N.java b/src/main/java/org/cef/callback/CefPrintJobCallback_N.java index 6e9f1d1f..18e319cb 100644 --- a/src/main/java/org/cef/callback/CefPrintJobCallback_N.java +++ b/src/main/java/org/cef/callback/CefPrintJobCallback_N.java @@ -7,14 +7,20 @@ class CefPrintJobCallback_N extends CefNativeAdapter implements CefPrintJobCallback { CefPrintJobCallback_N() {} + @Override + protected void finalize() throws Throwable { + Continue(); + super.finalize(); + } + @Override public void Continue() { try { - N_Continue(); + N_Continue(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } } - private final native void N_Continue(); + private final native void N_Continue(long self); } diff --git a/src/main/java/org/cef/callback/CefQueryCallback_N.java b/src/main/java/org/cef/callback/CefQueryCallback_N.java index 7d526e91..14b32e3a 100644 --- a/src/main/java/org/cef/callback/CefQueryCallback_N.java +++ b/src/main/java/org/cef/callback/CefQueryCallback_N.java @@ -5,13 +5,18 @@ package org.cef.callback; class CefQueryCallback_N extends CefNativeAdapter implements CefQueryCallback { - // Constructor is called by native code. CefQueryCallback_N() {} + @Override + protected void finalize() throws Throwable { + failure(-1, "Unexpected call to CefQueryCallback_N::finalize()"); + super.finalize(); + } + @Override public void success(String response) { try { - N_Success(response); + N_Success(getNativeRef(null), response); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -20,12 +25,12 @@ public void success(String response) { @Override public void failure(int error_code, String error_message) { try { - N_Failure(error_code, error_message); + N_Failure(getNativeRef(null), error_code, error_message); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } } - private final native void N_Success(String response); - private final native void N_Failure(int error_code, String error_message); + private final native void N_Success(long self, String response); + private final native void N_Failure(long self, int error_code, String error_message); } diff --git a/src/main/java/org/cef/callback/CefSchemeHandlerFactory.java b/src/main/java/org/cef/callback/CefSchemeHandlerFactory.java index 32701e50..bb2546a5 100644 --- a/src/main/java/org/cef/callback/CefSchemeHandlerFactory.java +++ b/src/main/java/org/cef/callback/CefSchemeHandlerFactory.java @@ -15,12 +15,17 @@ */ public interface CefSchemeHandlerFactory { /** - * Return a new resource handler instance to handle the request or an empty - * reference to allow default handling of the request. |browser| and |frame| - * will be the browser window and frame respectively that originated the - * request or NULL if the request did not originate from a browser window - * (for example, if the request came from CefURLRequest). The |request| object - * passed to this method will not contain cookie data. + * Return a new resource handler instance to handle the request or NULL to allow default + * handling of the request. + * + * @param browser The corresponding browser, or NULL if the request did not originate from a + * browser window (for example, if the request came from CefURLRequest). + * @param frame The frame generating the event, or NULL if the request did not originate from a + * browser window (for example, if the request came from CefURLRequest). Instance only + * valid within the scope of this method. + * @param schemeName Name of the scheme being created. + * @param request The request itself. Cannot be modified in this callback. Instance only valid + * within the scope of this method. */ public CefResourceHandler create( CefBrowser browser, CefFrame frame, String schemeName, CefRequest request); diff --git a/src/main/java/org/cef/callback/CefWebPluginInfoVisitor.java b/src/main/java/org/cef/callback/CefWebPluginInfoVisitor.java index c73abf57..79a9837f 100644 --- a/src/main/java/org/cef/callback/CefWebPluginInfoVisitor.java +++ b/src/main/java/org/cef/callback/CefWebPluginInfoVisitor.java @@ -7,15 +7,19 @@ import org.cef.network.CefWebPluginInfo; /** - * Interface to implement for visiting web plugin information. The methods of - * this class will be called on the browser process UI thread. + * Interface to implement for visiting web plugin information. The methods of this class will be + * called on the browser process UI thread. */ public interface CefWebPluginInfoVisitor { /** - * Method that will be called once for each plugin. |count| is the 0-based - * index for the current plugin. |total| is the total number of plugins. - * Return false to stop visiting plugins. This method may never be called if - * no plugins are found. + * Method that will be called once for each plugin. This method may never be called if no + * plugins are found. + * + * @param info Information for the current plugin. Instance only valid within the scope of this + * method. + * @param count The 0-based index for the current plugin. + * @param total The total number of plugins. + * @return True to continue visiting plugins or false to stop. */ public boolean visit(CefWebPluginInfo info, int count, int total); } diff --git a/src/main/java/org/cef/callback/CefWebPluginUnstableCallback.java b/src/main/java/org/cef/callback/CefWebPluginUnstableCallback.java index c358ff98..9fb6d65a 100644 --- a/src/main/java/org/cef/callback/CefWebPluginUnstableCallback.java +++ b/src/main/java/org/cef/callback/CefWebPluginUnstableCallback.java @@ -5,14 +5,16 @@ package org.cef.callback; /** - * Interface to implement for receiving unstable plugin information. The methods - * of this class will be called on the browser process IO thread. + * Interface to implement for receiving unstable plugin information. The methods of this class will + * be called on the browser process IO thread. */ public interface CefWebPluginUnstableCallback { /** - * Method that will be called for the requested plugin. |unstable| will be - * true if the plugin has reached the crash count threshold of 3 times in 120 - * seconds. + * Method that will be called for the requested plugin. + * + * @param path Plugin file path (DLL/bundle/library). + * @param unstable True if the plugin has reached the crash count threshold of 3 times in 120 + * seconds. */ public void isUnstable(String path, boolean unstable); } diff --git a/src/main/java/org/cef/handler/CefAppHandlerAdapter.java b/src/main/java/org/cef/handler/CefAppHandlerAdapter.java index 1a0cf2c4..6ebed8ef 100644 --- a/src/main/java/org/cef/handler/CefAppHandlerAdapter.java +++ b/src/main/java/org/cef/handler/CefAppHandlerAdapter.java @@ -99,5 +99,4 @@ public void onScheduleMessagePumpWork(long delay_ms) { public void setArgs(String[] args) { this.args_ = args; } - } diff --git a/src/main/java/org/cef/handler/CefDisplayHandler.java b/src/main/java/org/cef/handler/CefDisplayHandler.java index 0a14229b..0affefc5 100644 --- a/src/main/java/org/cef/handler/CefDisplayHandler.java +++ b/src/main/java/org/cef/handler/CefDisplayHandler.java @@ -4,9 +4,9 @@ package org.cef.handler; +import org.cef.CefSettings; import org.cef.browser.CefBrowser; import org.cef.browser.CefFrame; -import org.cef.CefSettings; /** * Implement this interface to handle events related to browser display state. @@ -14,7 +14,7 @@ */ public interface CefDisplayHandler { /** - * Handle address changes. + * Browser address changed. * @param browser The browser generating the event. * @param frame The frame generating the event. * @param url The new address. @@ -22,32 +22,29 @@ public interface CefDisplayHandler { public void onAddressChange(CefBrowser browser, CefFrame frame, String url); /** - * Handle title changes. + * Browser title changed. * @param browser The browser generating the event. * @param title The new title. */ public void onTitleChange(CefBrowser browser, String title); /** - * Called when the browser is about to display a tooltip. - * + * About to display a tooltip. * @param browser The browser generating the event. * @param text Contains the text that will be displayed in the tooltip. - * @return To handle the display of the tooltip yourself return true. + * @return true to handle the tooltip display yourself. */ public boolean onTooltip(CefBrowser browser, String text); /** - * Called when the browser receives a status message. - * + * Received a status message. * @param browser The browser generating the event. * @param value Contains the text that will be displayed in the status message. */ public void onStatusMessage(CefBrowser browser, String value); /** - * Called to display a console message. - * + * Display a console message. * @param browser The browser generating the event. * @param level * @param message @@ -57,4 +54,12 @@ public interface CefDisplayHandler { */ public boolean onConsoleMessage(CefBrowser browser, CefSettings.LogSeverity level, String message, String source, int line); + + /** + * Handle cursor changes. + * @param browser The browser generating the event. + * @param cursorType The new cursor type. + * @return true if the cursor change was handled. + */ + public boolean onCursorChange(CefBrowser browser, int cursorType); } diff --git a/src/main/java/org/cef/handler/CefDisplayHandlerAdapter.java b/src/main/java/org/cef/handler/CefDisplayHandlerAdapter.java index 88de5392..80ab96b6 100644 --- a/src/main/java/org/cef/handler/CefDisplayHandlerAdapter.java +++ b/src/main/java/org/cef/handler/CefDisplayHandlerAdapter.java @@ -4,9 +4,9 @@ package org.cef.handler; +import org.cef.CefSettings; import org.cef.browser.CefBrowser; import org.cef.browser.CefFrame; -import org.cef.CefSettings; /** * An abstract adapter class for receiving display events. @@ -39,4 +39,9 @@ public boolean onConsoleMessage(CefBrowser browser, CefSettings.LogSeverity leve String message, String source, int line) { return false; } + + @Override + public boolean onCursorChange(CefBrowser browser, int cursorType) { + return false; + } } diff --git a/src/main/java/org/cef/handler/CefLoadHandler.java b/src/main/java/org/cef/handler/CefLoadHandler.java index bfdb5f15..b1803713 100644 --- a/src/main/java/org/cef/handler/CefLoadHandler.java +++ b/src/main/java/org/cef/handler/CefLoadHandler.java @@ -4,18 +4,20 @@ package org.cef.handler; -import java.util.HashMap; -import java.util.Map; import org.cef.browser.CefBrowser; import org.cef.browser.CefFrame; import org.cef.network.CefRequest.TransitionType; +import java.util.HashMap; +import java.util.Map; + /** * Implement this interface to handle events related to browser load status. */ public interface CefLoadHandler { enum ErrorCode { ERR_NONE(0), + ERR_IO_PENDING(-1), ERR_FAILED(-2), ERR_ABORTED(-3), ERR_INVALID_ARGUMENT(-4), @@ -26,6 +28,23 @@ enum ErrorCode { ERR_UNEXPECTED(-9), ERR_ACCESS_DENIED(-10), ERR_NOT_IMPLEMENTED(-11), + ERR_INSUFFICIENT_RESOURCES(-12), + ERR_OUT_OF_MEMORY(-13), + ERR_UPLOAD_FILE_CHANGED(-14), + ERR_SOCKET_NOT_CONNECTED(-15), + ERR_FILE_EXISTS(-16), + ERR_FILE_PATH_TOO_LONG(-17), + ERR_FILE_NO_SPACE(-18), + ERR_FILE_VIRUS_INFECTED(-19), + ERR_BLOCKED_BY_CLIENT(-20), + ERR_NETWORK_CHANGED(-21), + ERR_BLOCKED_BY_ADMINISTRATOR(-22), + ERR_SOCKET_IS_CONNECTED(-23), + ERR_BLOCKED_ENROLLMENT_CHECK_PENDING(-24), + ERR_UPLOAD_STREAM_REWIND_NOT_SUPPORTED(-25), + ERR_CONTEXT_SHUT_DOWN(-26), + ERR_BLOCKED_BY_RESPONSE(-27), + ERR_CLEARTEXT_NOT_PERMITTED(-29), ERR_CONNECTION_CLOSED(-100), ERR_CONNECTION_RESET(-101), ERR_CONNECTION_REFUSED(-102), @@ -41,8 +60,62 @@ enum ErrorCode { ERR_NO_SSL_VERSIONS_ENABLED(-112), ERR_SSL_VERSION_OR_CIPHER_MISMATCH(-113), ERR_SSL_RENEGOTIATION_REQUESTED(-114), + ERR_PROXY_AUTH_UNSUPPORTED(-115), + ERR_CERT_ERROR_IN_SSL_RENEGOTIATION(-116), + ERR_BAD_SSL_CLIENT_AUTH_CERT(-117), + ERR_CONNECTION_TIMED_OUT(-118), + ERR_HOST_RESOLVER_QUEUE_TOO_LARGE(-119), + ERR_SOCKS_CONNECTION_FAILED(-120), + ERR_SOCKS_CONNECTION_HOST_UNREACHABLE(-121), + ERR_ALPN_NEGOTIATION_FAILED(-122), + ERR_SSL_NO_RENEGOTIATION(-123), + ERR_WINSOCK_UNEXPECTED_WRITTEN_BYTES(-124), + ERR_SSL_DECOMPRESSION_FAILURE_ALERT(-125), + ERR_SSL_BAD_RECORD_MAC_ALERT(-126), + ERR_PROXY_AUTH_REQUESTED(-127), + ERR_PROXY_CONNECTION_FAILED(-130), + ERR_MANDATORY_PROXY_CONFIGURATION_FAILED(-131), + ERR_PRECONNECT_MAX_SOCKET_LIMIT(-133), + ERR_SSL_CLIENT_AUTH_PRIVATE_KEY_ACCESS_DENIED(-134), + ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY(-135), + ERR_PROXY_CERTIFICATE_INVALID(-136), + ERR_NAME_RESOLUTION_FAILED(-137), + ERR_NETWORK_ACCESS_DENIED(-138), + ERR_TEMPORARILY_THROTTLED(-139), + ERR_HTTPS_PROXY_TUNNEL_RESPONSE_REDIRECT(-140), + ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED(-141), + ERR_MSG_TOO_BIG(-142), + ERR_WS_PROTOCOL_ERROR(-145), + ERR_ADDRESS_IN_USE(-147), + ERR_SSL_HANDSHAKE_NOT_COMPLETED(-148), + ERR_SSL_BAD_PEER_PUBLIC_KEY(-149), + ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN(-150), + ERR_CLIENT_AUTH_CERT_TYPE_UNSUPPORTED(-151), + ERR_SSL_DECRYPT_ERROR_ALERT(-153), + ERR_WS_THROTTLE_QUEUE_TOO_LARGE(-154), + ERR_SSL_SERVER_CERT_CHANGED(-156), + ERR_SSL_UNRECOGNIZED_NAME_ALERT(-159), + ERR_SOCKET_SET_RECEIVE_BUFFER_SIZE_ERROR(-160), + ERR_SOCKET_SET_SEND_BUFFER_SIZE_ERROR(-161), + ERR_SOCKET_RECEIVE_BUFFER_SIZE_UNCHANGEABLE(-162), + ERR_SOCKET_SEND_BUFFER_SIZE_UNCHANGEABLE(-163), + ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT(-164), + ERR_ICANN_NAME_COLLISION(-166), + ERR_SSL_SERVER_CERT_BAD_FORMAT(-167), + ERR_CT_STH_PARSING_FAILED(-168), + ERR_CT_STH_INCOMPLETE(-169), + ERR_UNABLE_TO_REUSE_CONNECTION_FOR_PROXY_AUTH(-170), + ERR_CT_CONSISTENCY_PROOF_PARSING_FAILED(-171), + ERR_SSL_OBSOLETE_CIPHER(-172), + ERR_WS_UPGRADE(-173), + ERR_READ_IF_READY_NOT_IMPLEMENTED(-174), + ERR_NO_BUFFER_SPACE(-176), + ERR_SSL_CLIENT_AUTH_NO_COMMON_ALGORITHMS(-177), + ERR_EARLY_DATA_REJECTED(-178), + ERR_WRONG_VERSION_ON_EARLY_DATA(-179), + ERR_TLS13_DOWNGRADE_DETECTED(-180), + ERR_SSL_KEY_USAGE_INCOMPATIBLE(-181), ERR_CERT_COMMON_NAME_INVALID(-200), - ERR_CERT_BEGIN(-200), // same as ERR_CERT_COMMON_NAME_INVALID ERR_CERT_DATE_INVALID(-201), ERR_CERT_AUTHORITY_INVALID(-202), ERR_CERT_CONTAINS_ERRORS(-203), @@ -51,15 +124,19 @@ enum ErrorCode { ERR_CERT_REVOKED(-206), ERR_CERT_INVALID(-207), ERR_CERT_WEAK_SIGNATURE_ALGORITHM(-208), - // -209 is available: was ERR_CERT_NOT_IN_DNS. ERR_CERT_NON_UNIQUE_NAME(-210), ERR_CERT_WEAK_KEY(-211), ERR_CERT_NAME_CONSTRAINT_VIOLATION(-212), ERR_CERT_VALIDITY_TOO_LONG(-213), - ERR_CERT_END(-213), // same as ERR_CERT_VALIDITY_TOO_LONG + ERR_CERTIFICATE_TRANSPARENCY_REQUIRED(-214), + ERR_CERT_SYMANTEC_LEGACY(-215), + ERR_CERT_KNOWN_INTERCEPTION_BLOCKED(-217), + ERR_SSL_OBSOLETE_VERSION(-218), + ERR_CERT_END(-219), ERR_INVALID_URL(-300), ERR_DISALLOWED_URL_SCHEME(-301), ERR_UNKNOWN_URL_SCHEME(-302), + ERR_INVALID_REDIRECT(-303), ERR_TOO_MANY_REDIRECTS(-310), ERR_UNSAFE_REDIRECT(-311), ERR_UNSAFE_PORT(-312), @@ -69,8 +146,102 @@ enum ErrorCode { ERR_UNEXPECTED_PROXY_AUTH(-323), ERR_EMPTY_RESPONSE(-324), ERR_RESPONSE_HEADERS_TOO_BIG(-325), + ERR_PAC_SCRIPT_FAILED(-327), + ERR_REQUEST_RANGE_NOT_SATISFIABLE(-328), + ERR_MALFORMED_IDENTITY(-329), + ERR_CONTENT_DECODING_FAILED(-330), + ERR_NETWORK_IO_SUSPENDED(-331), + ERR_SYN_REPLY_NOT_RECEIVED(-332), + ERR_ENCODING_CONVERSION_FAILED(-333), + ERR_UNRECOGNIZED_FTP_DIRECTORY_LISTING_FORMAT(-334), + ERR_NO_SUPPORTED_PROXIES(-336), + ERR_HTTP2_PROTOCOL_ERROR(-337), + ERR_INVALID_AUTH_CREDENTIALS(-338), + ERR_UNSUPPORTED_AUTH_SCHEME(-339), + ERR_ENCODING_DETECTION_FAILED(-340), + ERR_MISSING_AUTH_CREDENTIALS(-341), + ERR_UNEXPECTED_SECURITY_LIBRARY_STATUS(-342), + ERR_MISCONFIGURED_AUTH_ENVIRONMENT(-343), + ERR_UNDOCUMENTED_SECURITY_LIBRARY_STATUS(-344), + ERR_RESPONSE_BODY_TOO_BIG_TO_DRAIN(-345), + ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH(-346), + ERR_INCOMPLETE_HTTP2_HEADERS(-347), + ERR_PAC_NOT_IN_DHCP(-348), + ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION(-349), + ERR_RESPONSE_HEADERS_MULTIPLE_LOCATION(-350), + ERR_HTTP2_SERVER_REFUSED_STREAM(-351), + ERR_HTTP2_PING_FAILED(-352), + ERR_CONTENT_LENGTH_MISMATCH(-354), + ERR_INCOMPLETE_CHUNKED_ENCODING(-355), + ERR_QUIC_PROTOCOL_ERROR(-356), + ERR_RESPONSE_HEADERS_TRUNCATED(-357), + ERR_QUIC_HANDSHAKE_FAILED(-358), + ERR_HTTP2_INADEQUATE_TRANSPORT_SECURITY(-360), + ERR_HTTP2_FLOW_CONTROL_ERROR(-361), + ERR_HTTP2_FRAME_SIZE_ERROR(-362), + ERR_HTTP2_COMPRESSION_ERROR(-363), + ERR_PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION(-364), + ERR_HTTP_1_1_REQUIRED(-365), + ERR_PROXY_HTTP_1_1_REQUIRED(-366), + ERR_PAC_SCRIPT_TERMINATED(-367), + ERR_INVALID_HTTP_RESPONSE(-370), + ERR_CONTENT_DECODING_INIT_FAILED(-371), + ERR_HTTP2_RST_STREAM_NO_ERROR_RECEIVED(-372), + ERR_HTTP2_PUSHED_STREAM_NOT_AVAILABLE(-373), + ERR_HTTP2_CLAIMED_PUSHED_STREAM_RESET_BY_SERVER(-374), + ERR_TOO_MANY_RETRIES(-375), + ERR_HTTP2_STREAM_CLOSED(-376), + ERR_HTTP2_CLIENT_REFUSED_STREAM(-377), + ERR_HTTP2_PUSHED_RESPONSE_DOES_NOT_MATCH(-378), + ERR_HTTP_RESPONSE_CODE_FAILURE(-379), + ERR_QUIC_CERT_ROOT_NOT_KNOWN(-380), ERR_CACHE_MISS(-400), - ERR_INSECURE_RESPONSE(-501); + ERR_CACHE_READ_FAILURE(-401), + ERR_CACHE_WRITE_FAILURE(-402), + ERR_CACHE_OPERATION_NOT_SUPPORTED(-403), + ERR_CACHE_OPEN_FAILURE(-404), + ERR_CACHE_CREATE_FAILURE(-405), + ERR_CACHE_RACE(-406), + ERR_CACHE_CHECKSUM_READ_FAILURE(-407), + ERR_CACHE_CHECKSUM_MISMATCH(-408), + ERR_CACHE_LOCK_TIMEOUT(-409), + ERR_CACHE_AUTH_FAILURE_AFTER_READ(-410), + ERR_CACHE_ENTRY_NOT_SUITABLE(-411), + ERR_CACHE_DOOM_FAILURE(-412), + ERR_CACHE_OPEN_OR_CREATE_FAILURE(-413), + ERR_INSECURE_RESPONSE(-501), + ERR_NO_PRIVATE_KEY_FOR_CERT(-502), + ERR_ADD_USER_CERT_FAILED(-503), + ERR_INVALID_SIGNED_EXCHANGE(-504), + ERR_INVALID_WEB_BUNDLE(-505), + ERR_FTP_FAILED(-601), + ERR_FTP_SERVICE_UNAVAILABLE(-602), + ERR_FTP_TRANSFER_ABORTED(-603), + ERR_FTP_FILE_BUSY(-604), + ERR_FTP_SYNTAX_ERROR(-605), + ERR_FTP_COMMAND_NOT_SUPPORTED(-606), + ERR_FTP_BAD_COMMAND_SEQUENCE(-607), + ERR_PKCS12_IMPORT_BAD_PASSWORD(-701), + ERR_PKCS12_IMPORT_FAILED(-702), + ERR_IMPORT_CA_CERT_NOT_CA(-703), + ERR_IMPORT_CERT_ALREADY_EXISTS(-704), + ERR_IMPORT_CA_CERT_FAILED(-705), + ERR_IMPORT_SERVER_CERT_FAILED(-706), + ERR_PKCS12_IMPORT_INVALID_MAC(-707), + ERR_PKCS12_IMPORT_INVALID_FILE(-708), + ERR_PKCS12_IMPORT_UNSUPPORTED(-709), + ERR_KEY_GENERATION_FAILED(-710), + ERR_PRIVATE_KEY_EXPORT_FAILED(-712), + ERR_SELF_SIGNED_CERT_GENERATION_FAILED(-713), + ERR_CERT_DATABASE_CHANGED(-714), + ERR_DNS_MALFORMED_RESPONSE(-800), + ERR_DNS_SERVER_REQUIRES_TCP(-801), + ERR_DNS_SERVER_FAILED(-802), + ERR_DNS_TIMED_OUT(-803), + ERR_DNS_CACHE_MISS(-804), + ERR_DNS_SEARCH_EMPTY(-805), + ERR_DNS_SORT_ERROR(-806), + ERR_DNS_SECURE_RESOLVER_HOSTNAME_RESOLUTION_FAILED(-808); static private final Map CODES = new HashMap<>(); static { @@ -92,7 +263,7 @@ enum ErrorCode { /** * Gets the underlying native chrome embedded framework error code value * as an integer. - * @return The error code as an integer + * @return The error code as an integer. */ public int getCode() { return code; @@ -101,8 +272,8 @@ public int getCode() { /** * Finds the ErrorCode by the native chrome embedded framework integer-based * error code value. - * @param code The integer-based raw error code - * @return The Java enum mapped to that error code or null if none was found + * @param code The integer-based raw error code. + * @return The Java enum mapped to that error code or null if none was found. */ static public ErrorCode findByCode(int code) { return CODES.get(code); @@ -110,12 +281,11 @@ static public ErrorCode findByCode(int code) { } /** - * Called when the loading state has changed. This callback will be executed - * twice -- once when loading is initiated either programmatically or by user - * action, and once when loading is terminated due to completion, cancellation - * of failure. + * Called when the loading state has changed. This callback will be executed twice -- once when + * loading is initiated either programmatically or by user action, and once when loading is + * terminated due to completion, cancellation of failure. * - * @param browser The affected browser. + * @param browser The corresponding browser. * @param isLoading true if it is loading. * @param canGoBack true if you can navigate back. * @param canGoForward true if you can navigate forward. @@ -124,28 +294,28 @@ public void onLoadingStateChange( CefBrowser browser, boolean isLoading, boolean canGoBack, boolean canGoForward); /** - * Called when the browser begins loading a frame. The frameIdentifer value will - * never be empty. Multiple frames may be loading at the same time. Sub-frames may - * start or continue loading after the main frame load has ended. This method - * may not be called for a particular frame if the load request for that frame - * fails. For notification of overall browser load status use - * OnLoadingStateChange instead. + * Called when the browser begins loading a frame. The frameIdentifer value will never be empty. + * Multiple frames may be loading at the same time. Sub-frames may start or continue loading + * after the main frame load has ended. This method may not be called for a particular frame if + * the load request for that frame fails. For notification of overall browser load status use + * onLoadingStateChange instead. * - * @param browser The affected browser. - * @param frame The loading frame. - * @param transitionType The transition type + * @param browser The corresponding browser. + * @param frame The frame generating the event. Instance only valid within the scope of this + * method. + * @param transitionType The transition type. */ public void onLoadStart(CefBrowser browser, CefFrame frame, TransitionType transitionType); /** - * Called when the browser is done loading a frame. The frameIdentifer value will - * never be empty. Multiple frames may be loading at the same time. Sub-frames may - * start or continue loading after the main frame load has ended. This method - * will always be called for all frames irrespective of whether the request - * completes successfully. + * Called when the browser is done loading a frame. The frameIdentifer value will never be + * empty. Multiple frames may be loading at the same time. Sub-frames may start or continue + * loading after the main frame load has ended. This method will always be called for all frames + * irrespective of whether the request completes successfully. * - * @param browser The affected browser. - * @param frame The loading frame. + * @param browser The corresponding browser. + * @param frame The frame generating the event. Instance only valid within the scope of this + * method. * @param httpStatusCode The status code of the load. */ public void onLoadEnd(CefBrowser browser, CefFrame frame, int httpStatusCode); @@ -153,8 +323,9 @@ public void onLoadingStateChange( /** * Called when the resource load for a navigation fails or is canceled. * - * @param browser The affected browser. - * @param frame The loading frame. + * @param browser The corresponding browser. + * @param frame The frame generating the event. Instance only valid within the scope of this + * method. * @param errorCode The error code number. * @param errorText The error text. * @param failedUrl The URL that failed to load. diff --git a/src/main/java/org/cef/handler/CefMessageRouterHandler.java b/src/main/java/org/cef/handler/CefMessageRouterHandler.java index e0c0b253..4827a476 100644 --- a/src/main/java/org/cef/handler/CefMessageRouterHandler.java +++ b/src/main/java/org/cef/handler/CefMessageRouterHandler.java @@ -10,31 +10,34 @@ import org.cef.callback.CefQueryCallback; /** - * Implement this interface to handle queries. All methods will be executed on - * the browser process UI thread. + * Implement this interface to handle queries. All methods will be executed on the browser process + * UI thread. */ public interface CefMessageRouterHandler extends CefNative { /** * Called when the browser receives a JavaScript query. - * @param browser The browser generating the event. - * @param frame The frame generating the event. - * @param query_id The unique ID for the query. + * + * @param browser The corresponding browser. + * @param frame The frame generating the event. Instance only valid within the scope of this + * method. + * @param queryId The unique ID for the query. * @param persistent True if the query is persistent. * @param callback Object used to continue or cancel the query asynchronously. - * - * @return true to handle the query or false to propagate the query to other - * registered handlers, if any. If no handlers return true from this method - * then the query will be automatically canceled with an error code of -1 - * delivered to the JavaScript onFailure callback. + * @return True to handle the query or false to propagate the query to other registered + * handlers, if any. If no handlers return true from this method then the query will be + * automatically canceled with an error code of -1 delivered to the JavaScript onFailure + * callback. */ - public boolean onQuery(CefBrowser browser, CefFrame frame, long query_id, String request, + public boolean onQuery(CefBrowser browser, CefFrame frame, long queryId, String request, boolean persistent, CefQueryCallback callback); /** * Called when a pending JavaScript query is canceled. - * @param browser The browser generating the event. - * @param frame The frame generating the event. - * @param query_id The unique ID for the query. + * + * @param browser The corresponding browser. + * @param frame The frame generating the event. Instance only valid within the scope of this + * method. + * @param queryId The unique ID for the query. */ - public void onQueryCanceled(CefBrowser browser, CefFrame frame, long query_id); + public void onQueryCanceled(CefBrowser browser, CefFrame frame, long queryId); } diff --git a/src/main/java/org/cef/handler/CefMessageRouterHandlerAdapter.java b/src/main/java/org/cef/handler/CefMessageRouterHandlerAdapter.java index 044b83fe..c924dbfe 100644 --- a/src/main/java/org/cef/handler/CefMessageRouterHandlerAdapter.java +++ b/src/main/java/org/cef/handler/CefMessageRouterHandlerAdapter.java @@ -17,13 +17,13 @@ public abstract class CefMessageRouterHandlerAdapter extends CefNativeAdapter implements CefMessageRouterHandler { @Override - public boolean onQuery(CefBrowser browser, CefFrame frame, long query_id, String request, + public boolean onQuery(CefBrowser browser, CefFrame frame, long queryId, String request, boolean persistent, CefQueryCallback callback) { return false; } @Override - public void onQueryCanceled(CefBrowser browser, CefFrame frame, long query_id) { + public void onQueryCanceled(CefBrowser browser, CefFrame frame, long queryId) { return; } } diff --git a/src/main/java/org/cef/handler/CefPrintHandler.java b/src/main/java/org/cef/handler/CefPrintHandler.java index 089be24a..6f87d0c9 100644 --- a/src/main/java/org/cef/handler/CefPrintHandler.java +++ b/src/main/java/org/cef/handler/CefPrintHandler.java @@ -4,60 +4,73 @@ package org.cef.handler; -import java.awt.Dimension; import org.cef.browser.CefBrowser; import org.cef.callback.CefNative; import org.cef.callback.CefPrintDialogCallback; import org.cef.callback.CefPrintJobCallback; import org.cef.misc.CefPrintSettings; +import java.awt.Dimension; + /** - * Implement this interface to handle printing on Linux. The methods of this - * class will be called on the browser process UI thread. + * Implement this interface to handle printing on Linux. The methods of this class will be called on + * the browser process UI thread. */ public interface CefPrintHandler extends CefNative { /** - * Called when printing has started for the specified |browser|. This method - * will be called before the other onPrint*() methods and irrespective of how - * printing was initiated (e.g. CefBrowser::print(), JavaScript window.print() - * or PDF extension print button). + * Called when printing has started. This method will be called before the other onPrint*() + * methods and irrespective of how printing was initiated (e.g. CefBrowser::print(), JavaScript + * window.print() or PDF extension print button). + * + * @param browser The corresponding browser. */ void onPrintStart(CefBrowser browser); /** - * Synchronize |settings| with client state. If |get_defaults| is true then - * populate |settings| with the default print settings. Do not keep a - * reference to |settings| outside of this callback. + * Called to get print settings. + * + * @param browser The corresponding browser. + * @param settings Populate with the desired print settings. Do not keep a reference to this + * object outside of this callback. + * @param getDefaults If true |settings| should be populated with the default print settings. */ - void onPrintSettings(CefPrintSettings settings, boolean get_defaults); + void onPrintSettings(CefBrowser browser, CefPrintSettings settings, boolean getDefaults); /** - * Show the print dialog. Execute |callback| once the dialog is dismissed. - * Return true if the dialog will be displayed or false to cancel the - * printing immediately. + * Called to show the print dialog. * + * @param browser The corresponding browser. + * @param hasSelection True if the user has selected a region of the page to print. + * @param callback Callback to execute after the dialog is dismissed. + * @return True if the dialog will be displayed or false to cancel the printing immediately. */ - boolean onPrintDialog(boolean has_selection, CefPrintDialogCallback callback); + boolean onPrintDialog( + CefBrowser browser, boolean hasSelection, CefPrintDialogCallback callback); /** - * Send the print job to the printer. Execute |callback| once the job is - * completed. Return true if the job will proceed or false to cancel the job - * immediately. + * Called to send the print job to the printer. + * + * @param browser The corresponding browser. + * @param documentName Name of the document that is printing. + * @param pdfFilePath Path to the PDF file that contains the document contents. + * @param callback Callback to execute after the print job has completed. + * @return True if the job will proceed or false to cancel the printing immediately. */ - boolean onPrintJob(String document_name, String pdf_file_path, CefPrintJobCallback callback); + boolean onPrintJob(CefBrowser browser, String documentName, String pdfFilePath, + CefPrintJobCallback callback); /** - * Reset client state related to printing. + * Called to reset client state related to printing. + * + * @param browser The corresponding browser. */ - void onPrintReset(); - + void onPrintReset(CefBrowser browser); + /** - * Called when PrintToPDF is requested for a browser. Returns the page size - * (as measured in microns) to use. - * @param deviceUnitsPerInch The DPI of the print. Use this to calculate - * the page size to use. - * @return The page size + * Called to retrieve the page size when printToPDF is requested for a browser. + * + * @param deviceUnitsPerInch The DPI of the print. Use this to calculate the page size to use. + * @return The page size in microns. */ Dimension getPdfPaperSize(int deviceUnitsPerInch); - } diff --git a/src/main/java/org/cef/handler/CefPrintHandlerAdapter.java b/src/main/java/org/cef/handler/CefPrintHandlerAdapter.java index 8decd857..25c0afdc 100644 --- a/src/main/java/org/cef/handler/CefPrintHandlerAdapter.java +++ b/src/main/java/org/cef/handler/CefPrintHandlerAdapter.java @@ -4,13 +4,14 @@ package org.cef.handler; -import java.awt.Dimension; import org.cef.browser.CefBrowser; import org.cef.callback.CefNativeAdapter; import org.cef.callback.CefPrintDialogCallback; import org.cef.callback.CefPrintJobCallback; import org.cef.misc.CefPrintSettings; +import java.awt.Dimension; + /** * An abstract adapter class for receiving print events on Linux. * The methods in this class are empty. @@ -23,35 +24,37 @@ public void onPrintStart(CefBrowser browser) { } @Override - public void onPrintSettings(CefPrintSettings settings, boolean get_defaults) { + public void onPrintSettings( + CefBrowser browser, CefPrintSettings settings, boolean getDefaults) { // The default implementation does nothing } @Override - public boolean onPrintDialog(boolean has_selection, CefPrintDialogCallback callback) { + public boolean onPrintDialog( + CefBrowser browser, boolean hasSelection, CefPrintDialogCallback callback) { // The default implementation does nothing return false; } @Override - public boolean onPrintJob( - String document_name, String pdf_file_path, CefPrintJobCallback callback) { + public boolean onPrintJob(CefBrowser browser, String documentName, String pdfFilePath, + CefPrintJobCallback callback) { // The default implementation does nothing return false; } @Override - public void onPrintReset() { + public void onPrintReset(CefBrowser browser) { // The default implementation does nothing } - + @Override public Dimension getPdfPaperSize(int deviceUnitsPerInch) { // default implementation is A4 letter size // @ 300 DPI, A4 is 2480 x 3508 // @ 150 DPI, A4 is 1240 x 1754 - int adjustedWidth = (int)(((double)deviceUnitsPerInch/300d)*2480d); - int adjustedHeight = (int)(((double)deviceUnitsPerInch/300d)*3508d); + int adjustedWidth = (int) (((double) deviceUnitsPerInch / 300d) * 2480d); + int adjustedHeight = (int) (((double) deviceUnitsPerInch / 300d) * 3508d); return new Dimension(adjustedWidth, adjustedHeight); } } diff --git a/src/main/java/org/cef/handler/CefRenderHandler.java b/src/main/java/org/cef/handler/CefRenderHandler.java index 5f7657a8..0a94bb2f 100644 --- a/src/main/java/org/cef/handler/CefRenderHandler.java +++ b/src/main/java/org/cef/handler/CefRenderHandler.java @@ -4,13 +4,13 @@ package org.cef.handler; +import org.cef.browser.CefBrowser; +import org.cef.callback.CefDragData; + import java.awt.Point; import java.awt.Rectangle; import java.nio.ByteBuffer; -import org.cef.browser.CefBrowser; -import org.cef.callback.CefDragData; - /** * Implement this interface to handle events when window rendering is disabled. * The methods of this class will be called on the UI thread. @@ -22,6 +22,15 @@ public interface CefRenderHandler { * @return The view rectangle. */ public Rectangle getViewRect(CefBrowser browser); + + /** + * Retrieve the screen info. + * @param browser The browser generating the event. + * @param screenInfo The screenInfo + * @return True if this callback was handled. False to fallback to defaults. + */ + public boolean getScreenInfo(CefBrowser browser, CefScreenInfo screenInfo); + /** * Retrieve the screen point for the specified view point. * @param browser The browser generating the event. @@ -59,9 +68,10 @@ public void onPaint(CefBrowser browser, boolean popup, Rectangle[] dirtyRects, /** * Handle cursor changes. * @param browser The browser generating the event. - * @param cursor The new cursor. + * @param cursorType The new cursor type. + * @return true if the cursor change was handled. */ - public void onCursorChange(CefBrowser browser, int cursor); + public boolean onCursorChange(CefBrowser browser, int cursorType); /** * Called when the user starts dragging content in the web view. Contextual diff --git a/src/main/java/org/cef/handler/CefRenderHandlerAdapter.java b/src/main/java/org/cef/handler/CefRenderHandlerAdapter.java index 4df55dc4..ea782830 100644 --- a/src/main/java/org/cef/handler/CefRenderHandlerAdapter.java +++ b/src/main/java/org/cef/handler/CefRenderHandlerAdapter.java @@ -4,13 +4,13 @@ package org.cef.handler; +import org.cef.browser.CefBrowser; +import org.cef.callback.CefDragData; + import java.awt.Point; import java.awt.Rectangle; import java.nio.ByteBuffer; -import org.cef.browser.CefBrowser; -import org.cef.callback.CefDragData; - /** * An abstract adapter class for receiving render events. * The methods in this class are empty. @@ -18,13 +18,13 @@ */ public abstract class CefRenderHandlerAdapter implements CefRenderHandler { @Override - public void onCursorChange(CefBrowser browser, int cursorIdentifer) { - return; + public Rectangle getViewRect(CefBrowser browser) { + return new Rectangle(0, 0, 0, 0); } @Override - public Rectangle getViewRect(CefBrowser browser) { - return new Rectangle(0, 0, 0, 0); + public boolean getScreenInfo(CefBrowser browser, CefScreenInfo screenInfo) { + return false; } @Override @@ -42,6 +42,11 @@ public void onPopupSize(CefBrowser browser, Rectangle size) {} public void onPaint(CefBrowser browser, boolean popup, Rectangle[] dirtyRects, ByteBuffer buffer, int width, int height) {} + @Override + public boolean onCursorChange(CefBrowser browser, int cursorType) { + return false; + } + @Override public boolean startDragging(CefBrowser browser, CefDragData dragData, int mask, int x, int y) { return false; diff --git a/src/main/java/org/cef/handler/CefRequestHandler.java b/src/main/java/org/cef/handler/CefRequestHandler.java index c818864f..33789815 100644 --- a/src/main/java/org/cef/handler/CefRequestHandler.java +++ b/src/main/java/org/cef/handler/CefRequestHandler.java @@ -47,6 +47,23 @@ enum TerminationStatus { boolean onBeforeBrowse(CefBrowser browser, CefFrame frame, CefRequest request, boolean user_gesture, boolean is_redirect); + /** + * Called on the UI thread before OnBeforeBrowse in certain limited cases + * where navigating a new or different browser might be desirable. This + * includes user-initiated navigation that might open in a special way (e.g. + * links clicked via middle-click or ctrl + left-click) and certain types of + * cross-origin navigation initiated from the renderer process (e.g. + * navigating the top-level frame to/from a file URL). + * + * @param browser The corresponding browser. + * @param frame The frame generating the event. Instance only valid within the scope of this + * method + * @param user_gesture True if the request was initiated by a user gesture. + * @return True to cancel navigation or false to continue + */ + boolean onOpenURLFromTab(CefBrowser browser, CefFrame frame, String target_url, + boolean user_gesture); + /** * Called on the IO thread before a resource request is initiated. The |browser| and |frame| * values represent the source of the request. If this callback returns null the same method @@ -73,8 +90,7 @@ CefResourceRequestHandler getResourceRequestHandler(CefBrowser browser, CefFrame * Called on the IO thread when the browser needs credentials from the user. * * @param browser The corresponding browser. - * @param frame The frame generating the event. Instance only valid within the scope of this - * method. + * @param origin_url The origin making this authentication request. * @param isProxy True if the host is a proxy server. * @param host Hostname. * @param port Port number. @@ -84,7 +100,7 @@ CefResourceRequestHandler getResourceRequestHandler(CefBrowser browser, CefFrame * available. * @return True to continue the request (callback must be executed) or false to cancel. */ - boolean getAuthCredentials(CefBrowser browser, CefFrame frame, boolean isProxy, String host, + boolean getAuthCredentials(CefBrowser browser, String origin_url, boolean isProxy, String host, int port, String realm, String scheme, CefAuthCallback callback); /** diff --git a/src/main/java/org/cef/handler/CefRequestHandlerAdapter.java b/src/main/java/org/cef/handler/CefRequestHandlerAdapter.java index bc350089..a5231d04 100644 --- a/src/main/java/org/cef/handler/CefRequestHandlerAdapter.java +++ b/src/main/java/org/cef/handler/CefRequestHandlerAdapter.java @@ -25,6 +25,12 @@ public boolean onBeforeBrowse(CefBrowser browser, CefFrame frame, CefRequest req return false; } + @Override + public boolean onOpenURLFromTab(CefBrowser browser, CefFrame frame, String target_url, + boolean user_gesture) { + return false; + } + @Override public CefResourceRequestHandler getResourceRequestHandler(CefBrowser browser, CefFrame frame, CefRequest request, boolean isNavigation, boolean isDownload, String requestInitiator, @@ -33,7 +39,7 @@ public CefResourceRequestHandler getResourceRequestHandler(CefBrowser browser, C } @Override - public boolean getAuthCredentials(CefBrowser browser, CefFrame frame, boolean isProxy, + public boolean getAuthCredentials(CefBrowser browser, String origin_url, boolean isProxy, String host, int port, String realm, String scheme, CefAuthCallback callback) { return false; } diff --git a/src/main/java/org/cef/handler/CefResourceHandler.java b/src/main/java/org/cef/handler/CefResourceHandler.java index 2f35bc9d..72f9f30d 100644 --- a/src/main/java/org/cef/handler/CefResourceHandler.java +++ b/src/main/java/org/cef/handler/CefResourceHandler.java @@ -5,7 +5,6 @@ package org.cef.handler; import org.cef.callback.CefCallback; -import org.cef.callback.CefNative; import org.cef.misc.IntRef; import org.cef.misc.StringRef; import org.cef.network.CefCookie; @@ -16,7 +15,7 @@ * Implement this interface to handle custom resource requests. The methods of * this class will always be called on the IO thread. */ -public interface CefResourceHandler extends CefNative { +public interface CefResourceHandler { /** * Begin processing the request. * @param request The request itself. Cannot be modified in this callback. Instance only valid diff --git a/src/main/java/org/cef/handler/CefResourceHandlerAdapter.java b/src/main/java/org/cef/handler/CefResourceHandlerAdapter.java index d645252f..9458bb2b 100644 --- a/src/main/java/org/cef/handler/CefResourceHandlerAdapter.java +++ b/src/main/java/org/cef/handler/CefResourceHandlerAdapter.java @@ -5,7 +5,6 @@ package org.cef.handler; import org.cef.callback.CefCallback; -import org.cef.callback.CefNativeAdapter; import org.cef.misc.IntRef; import org.cef.misc.StringRef; import org.cef.network.CefCookie; @@ -17,8 +16,7 @@ * The methods in this class are empty. * This class exists as convenience for creating handler objects. */ -public abstract class CefResourceHandlerAdapter - extends CefNativeAdapter implements CefResourceHandler { +public abstract class CefResourceHandlerAdapter implements CefResourceHandler { @Override public boolean processRequest(CefRequest request, CefCallback callback) { return false; diff --git a/src/main/java/org/cef/handler/CefScreenInfo.java b/src/main/java/org/cef/handler/CefScreenInfo.java new file mode 100644 index 00000000..8a8cd4a9 --- /dev/null +++ b/src/main/java/org/cef/handler/CefScreenInfo.java @@ -0,0 +1,36 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +package org.cef.handler; + +import java.awt.Rectangle; + +/** + * + * @author shannah + */ +public class CefScreenInfo { + public double device_scale_factor; + public int depth; + public int depth_per_component; + public boolean is_monochrome; + public int x, y, width, height; + public int available_x, available_y, available_width, available_height; + + public void Set(double device_scale_factor, int depth, int depth_per_component, + boolean is_monochrome, Rectangle rect, Rectangle availableRect) { + this.device_scale_factor = device_scale_factor; + this.depth = depth; + this.depth_per_component = depth_per_component; + this.is_monochrome = is_monochrome; + this.x = rect.x; + this.y = rect.y; + this.width = rect.width; + this.height = rect.height; + this.available_x = availableRect.x; + this.available_y = availableRect.y; + this.available_width = availableRect.width; + this.available_height = availableRect.height; + } +} diff --git a/src/main/java/org/cef/handler/CefWindowHandler.java b/src/main/java/org/cef/handler/CefWindowHandler.java index 5ecc9604..eeda8dac 100644 --- a/src/main/java/org/cef/handler/CefWindowHandler.java +++ b/src/main/java/org/cef/handler/CefWindowHandler.java @@ -1,42 +1,42 @@ -// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights -// reserved. Use of this source code is governed by a BSD-style license that -// can be found in the LICENSE file. - -package org.cef.handler; - -import java.awt.Rectangle; - -import org.cef.browser.CefBrowser; - -/** - * Implement this interface to handle events if window rendering is enabled. - * - */ -public interface CefWindowHandler { - /** - * Retrieve the view rectangle. - * @param browser The browser generating the event. - * @return The view rectangle. - */ - public Rectangle getRect(CefBrowser browser); - - /** - * Implement this method to handle mouse events on Windows. - * - * The method is called in case of the following events: - * MOUSE_MOVED, MOUSE_PRESSED, MOUSE_RELEASED and MOUSE_WHEEL for a - * horizontal wheel movement. - * - * @param browser The browser generating the event. - * @param event A mouse event like MouseEvent.MOUSE_MOVED. - * @param screenX The absolute X position on the screen. - * @param screenY The absolute Y position on the screen. - * @param modifier The modifier keys down during event (e.g. Shift, Ctrl). - * @param button An integer indicating which mouse button state changed. - * If parameter event is set to MouseEvent.MOUSE_WHEEL, the value of this - * parameter specifies the rotation indicator (negative value for left scroll - * and positive value for right scroll). - */ - public void onMouseEvent( - CefBrowser browser, int event, int screenX, int screenY, int modifier, int button); -} +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +package org.cef.handler; + +import java.awt.Rectangle; + +import org.cef.browser.CefBrowser; + +/** + * Implement this interface to handle events if window rendering is enabled. + * + */ +public interface CefWindowHandler { + /** + * Retrieve the view rectangle. + * @param browser The browser generating the event. + * @return The view rectangle. + */ + public Rectangle getRect(CefBrowser browser); + + /** + * Implement this method to handle mouse events on Windows. + * + * The method is called in case of the following events: + * MOUSE_MOVED, MOUSE_PRESSED, MOUSE_RELEASED and MOUSE_WHEEL for a + * horizontal wheel movement. + * + * @param browser The browser generating the event. + * @param event A mouse event like MouseEvent.MOUSE_MOVED. + * @param screenX The absolute X position on the screen. + * @param screenY The absolute Y position on the screen. + * @param modifier The modifier keys down during event (e.g. Shift, Ctrl). + * @param button An integer indicating which mouse button state changed. + * If parameter event is set to MouseEvent.MOUSE_WHEEL, the value of this + * parameter specifies the rotation indicator (negative value for left scroll + * and positive value for right scroll). + */ + public void onMouseEvent( + CefBrowser browser, int event, int screenX, int screenY, int modifier, int button); +} diff --git a/src/main/java/org/cef/handler/CefWindowHandlerAdapter.java b/src/main/java/org/cef/handler/CefWindowHandlerAdapter.java index 327cd422..1e6ad6bd 100644 --- a/src/main/java/org/cef/handler/CefWindowHandlerAdapter.java +++ b/src/main/java/org/cef/handler/CefWindowHandlerAdapter.java @@ -1,25 +1,25 @@ -// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights -// reserved. Use of this source code is governed by a BSD-style license that -// can be found in the LICENSE file. - -package org.cef.handler; - -import java.awt.Rectangle; - -import org.cef.browser.CefBrowser; - -/** - * An abstract adapter class for receiving windowed render events. - * The methods in this class are empty. - * This class exists as convenience for creating handler objects. - */ -public abstract class CefWindowHandlerAdapter implements CefWindowHandler { - @Override - public Rectangle getRect(CefBrowser browser) { - return new Rectangle(0, 0, 0, 0); - } - - @Override - public void onMouseEvent( - CefBrowser browser, int event, int screenX, int screenY, int modifier, int button) {} -} +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +package org.cef.handler; + +import java.awt.Rectangle; + +import org.cef.browser.CefBrowser; + +/** + * An abstract adapter class for receiving windowed render events. + * The methods in this class are empty. + * This class exists as convenience for creating handler objects. + */ +public abstract class CefWindowHandlerAdapter implements CefWindowHandler { + @Override + public Rectangle getRect(CefBrowser browser) { + return new Rectangle(0, 0, 0, 0); + } + + @Override + public void onMouseEvent( + CefBrowser browser, int event, int screenX, int screenY, int modifier, int button) {} +} diff --git a/src/main/java/org/cef/misc/CefPdfPrintSettings.java b/src/main/java/org/cef/misc/CefPdfPrintSettings.java index e4866f17..554c2925 100644 --- a/src/main/java/org/cef/misc/CefPdfPrintSettings.java +++ b/src/main/java/org/cef/misc/CefPdfPrintSettings.java @@ -8,7 +8,6 @@ * PDF print settings for browser.printToPDF() */ public class CefPdfPrintSettings { - public enum MarginType { // Default margins. DEFAULT, @@ -22,13 +21,13 @@ public enum MarginType { // Custom margins using the values from CefPdfPrintSettings CUSTOM } - + /** * Set to true to print headers and footers or false to not print * headers and footers. */ public boolean header_footer_enabled; - + /** * Page title to display in the header. Only used if header_footer_enabled * is set to true. @@ -51,43 +50,43 @@ public enum MarginType { * background graphics. */ public boolean backgrounds_enabled; - + /** * Output page size in microns (1 millimeter = 1000 microns). If either of these * values is less than or equal to zero then the default paper size will be - * used as returned by the print_handler. A4 is 210 × 297 mm which would - * be 210000 x 297000 microns. US Letter is 215.9 × 279.4 mm which would + * used as returned by the print_handler. A4 is 210 x 297 mm which would + * be 210000 x 297000 microns. US Letter is 215.9 x 279.4 mm which would * be 215900 x 279400 microns. */ public int page_width; public int page_height; - + /** * Set to true to print the selection only or false to print all. */ public boolean selection_only; - + /** * The percentage to scale the PDF by before printing (e.g. 50 is 50%). * If this value is less than or equal to zero the default value of 100 * will be used. */ public int scale_factor; - + /** - * Margins in millimeters. Only used if |margin_type| is set to + * Margins in points. Only used if |margin_type| is set to * PDF_PRINT_MARGIN_CUSTOM. */ - public double margin_top; - public double margin_right; - public double margin_bottom; - public double margin_left; + public int margin_top; + public int margin_right; + public int margin_bottom; + public int margin_left; /** * Margin type. */ public MarginType margin_type; - + public CefPdfPrintSettings() {} @Override diff --git a/src/main/java/org/cef/misc/CefPrintSettings.java b/src/main/java/org/cef/misc/CefPrintSettings.java index 0ffa03f3..6dc56fef 100644 --- a/src/main/java/org/cef/misc/CefPrintSettings.java +++ b/src/main/java/org/cef/misc/CefPrintSettings.java @@ -52,6 +52,12 @@ public enum DuplexMode { // This CTOR can't be called directly. Call method create() instead. CefPrintSettings() {} + @Override + protected void finalize() throws Throwable { + dispose(); + super.finalize(); + } + /** * Create a new CefPrintSettings object. */ @@ -59,6 +65,11 @@ public static final CefPrintSettings create() { return CefPrintSettings_N.createNative(); } + /** + * Removes the native reference from an unused object. + */ + public abstract void dispose(); + /** * Returns true if this object is valid. Do not call any other methods if this * function returns false. @@ -71,11 +82,6 @@ public static final CefPrintSettings create() { */ public abstract boolean isReadOnly(); - /** - * Returns a writable copy of this object. - */ - public abstract CefPrintSettings copy(); - /** * Set the page orientation. */ diff --git a/src/main/java/org/cef/misc/CefPrintSettings_N.java b/src/main/java/org/cef/misc/CefPrintSettings_N.java index 47a653c6..bc0f83a0 100644 --- a/src/main/java/org/cef/misc/CefPrintSettings_N.java +++ b/src/main/java/org/cef/misc/CefPrintSettings_N.java @@ -4,12 +4,12 @@ package org.cef.misc; +import org.cef.callback.CefNative; + import java.awt.Dimension; import java.awt.Rectangle; import java.util.Vector; -import org.cef.callback.CefNative; - class CefPrintSettings_N extends CefPrintSettings implements CefNative { // Used internally to store a pointer to the CEF object. private long N_CefHandle = 0; @@ -28,32 +28,28 @@ public long getNativeRef(String identifer) { super(); } - public static final CefPrintSettings createNative() { - CefPrintSettings_N result = new CefPrintSettings_N(); + public static CefPrintSettings createNative() { try { - result.N_CefPrintSettings_CTOR(); + return CefPrintSettings_N.N_Create(); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); + return null; } - if (result.N_CefHandle == 0) return null; - return result; } @Override - protected void finalize() throws Throwable { + public void dispose() { try { - N_CefPrintSettings_DTOR(); + N_Dispose(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); - } finally { - super.finalize(); } } @Override public boolean isValid() { try { - return N_IsValid(); + return N_IsValid(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -63,27 +59,17 @@ public boolean isValid() { @Override public boolean isReadOnly() { try { - return N_IsReadOnly(); + return N_IsReadOnly(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } return false; } - @Override - public CefPrintSettings copy() { - try { - return N_Copy(); - } catch (UnsatisfiedLinkError ule) { - ule.printStackTrace(); - } - return null; - } - @Override public void setOrientation(boolean landscape) { try { - N_SetOrientation(landscape); + N_SetOrientation(N_CefHandle, landscape); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -92,7 +78,7 @@ public void setOrientation(boolean landscape) { @Override public boolean isLandscape() { try { - return N_IsLandscape(); + return N_IsLandscape(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -103,8 +89,8 @@ public boolean isLandscape() { public void setPrinterPrintableArea(Dimension physical_size_device_units, Rectangle printable_area_device_units, boolean landscape_needs_flip) { try { - N_SetPrinterPrintableArea( - physical_size_device_units, printable_area_device_units, landscape_needs_flip); + N_SetPrinterPrintableArea(N_CefHandle, physical_size_device_units, + printable_area_device_units, landscape_needs_flip); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -113,7 +99,7 @@ public void setPrinterPrintableArea(Dimension physical_size_device_units, @Override public void setDeviceName(String name) { try { - N_SetDeviceName(name); + N_SetDeviceName(N_CefHandle, name); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -122,7 +108,7 @@ public void setDeviceName(String name) { @Override public String getDeviceName() { try { - return N_GetDeviceName(); + return N_GetDeviceName(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -132,7 +118,7 @@ public String getDeviceName() { @Override public void setDPI(int dpi) { try { - N_SetDPI(dpi); + N_SetDPI(N_CefHandle, dpi); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -141,7 +127,7 @@ public void setDPI(int dpi) { @Override public int getDPI() { try { - return N_GetDPI(); + return N_GetDPI(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -151,7 +137,7 @@ public int getDPI() { @Override public void setPageRanges(Vector ranges) { try { - N_SetPageRanges(ranges); + N_SetPageRanges(N_CefHandle, ranges); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -160,7 +146,7 @@ public void setPageRanges(Vector ranges) { @Override public int getPageRangesCount() { try { - return N_GetPageRangesCount(); + return N_GetPageRangesCount(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -170,7 +156,7 @@ public int getPageRangesCount() { @Override public void getPageRanges(Vector ranges) { try { - N_GetPageRanges(ranges); + N_GetPageRanges(N_CefHandle, ranges); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -179,7 +165,7 @@ public void getPageRanges(Vector ranges) { @Override public void setSelectionOnly(boolean selection_only) { try { - N_SetSelectionOnly(selection_only); + N_SetSelectionOnly(N_CefHandle, selection_only); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -188,7 +174,7 @@ public void setSelectionOnly(boolean selection_only) { @Override public boolean isSelectionOnly() { try { - return N_IsSelectionOnly(); + return N_IsSelectionOnly(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -198,7 +184,7 @@ public boolean isSelectionOnly() { @Override public void setCollate(boolean collate) { try { - N_SetCollate(collate); + N_SetCollate(N_CefHandle, collate); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -207,7 +193,7 @@ public void setCollate(boolean collate) { @Override public boolean willCollate() { try { - return N_WillCollate(); + return N_WillCollate(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -217,7 +203,7 @@ public boolean willCollate() { @Override public void setColorModel(ColorModel model) { try { - N_SetColorModel(model); + N_SetColorModel(N_CefHandle, model); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -226,7 +212,7 @@ public void setColorModel(ColorModel model) { @Override public ColorModel getColorModel() { try { - return N_GetColorModel(); + return N_GetColorModel(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -236,7 +222,7 @@ public ColorModel getColorModel() { @Override public void setCopies(int copies) { try { - N_SetCopies(copies); + N_SetCopies(N_CefHandle, copies); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -245,7 +231,7 @@ public void setCopies(int copies) { @Override public int getCopies() { try { - return N_GetCopies(); + return N_GetCopies(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -255,7 +241,7 @@ public int getCopies() { @Override public void setDuplexMode(DuplexMode mode) { try { - N_SetDuplexMode(mode); + N_SetDuplexMode(N_CefHandle, mode); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -264,37 +250,37 @@ public void setDuplexMode(DuplexMode mode) { @Override public DuplexMode getDuplexMode() { try { - return N_GetDuplexMode(); + return N_GetDuplexMode(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } return null; } - private final native void N_CefPrintSettings_CTOR(); - private final native boolean N_IsValid(); - private final native boolean N_IsReadOnly(); - private final native CefPrintSettings N_Copy(); - private final native void N_SetOrientation(boolean landscape); - private final native boolean N_IsLandscape(); - private final native void N_SetPrinterPrintableArea(Dimension physical_size_device_units, - Rectangle printable_area_device_units, boolean landscape_needs_flip); - private final native void N_SetDeviceName(String name); - private final native String N_GetDeviceName(); - private final native void N_SetDPI(int dpi); - private final native int N_GetDPI(); - private final native void N_SetPageRanges(Vector ranges); - private final native int N_GetPageRangesCount(); - private final native void N_GetPageRanges(Vector ranges); - private final native void N_SetSelectionOnly(boolean selection_only); - private final native boolean N_IsSelectionOnly(); - private final native void N_SetCollate(boolean collate); - private final native boolean N_WillCollate(); - private final native void N_SetColorModel(ColorModel model); - private final native ColorModel N_GetColorModel(); - private final native void N_SetCopies(int copies); - private final native int N_GetCopies(); - private final native void N_SetDuplexMode(DuplexMode mode); - private final native DuplexMode N_GetDuplexMode(); - private final native void N_CefPrintSettings_DTOR(); + private final native static CefPrintSettings_N N_Create(); + private final native void N_Dispose(long self); + private final native boolean N_IsValid(long self); + private final native boolean N_IsReadOnly(long self); + private final native void N_SetOrientation(long self, boolean landscape); + private final native boolean N_IsLandscape(long self); + private final native void N_SetPrinterPrintableArea(long self, + Dimension physical_size_device_units, Rectangle printable_area_device_units, + boolean landscape_needs_flip); + private final native void N_SetDeviceName(long self, String name); + private final native String N_GetDeviceName(long self); + private final native void N_SetDPI(long self, int dpi); + private final native int N_GetDPI(long self); + private final native void N_SetPageRanges(long self, Vector ranges); + private final native int N_GetPageRangesCount(long self); + private final native void N_GetPageRanges(long self, Vector ranges); + private final native void N_SetSelectionOnly(long self, boolean selection_only); + private final native boolean N_IsSelectionOnly(long self); + private final native void N_SetCollate(long self, boolean collate); + private final native boolean N_WillCollate(long self); + private final native void N_SetColorModel(long self, ColorModel model); + private final native ColorModel N_GetColorModel(long self); + private final native void N_SetCopies(long self, int copies); + private final native int N_GetCopies(long self); + private final native void N_SetDuplexMode(long self, DuplexMode mode); + private final native DuplexMode N_GetDuplexMode(long self); } diff --git a/src/main/java/org/cef/network/CefPostData.java b/src/main/java/org/cef/network/CefPostData.java index 00d97507..85ba6f91 100644 --- a/src/main/java/org/cef/network/CefPostData.java +++ b/src/main/java/org/cef/network/CefPostData.java @@ -14,6 +14,12 @@ public abstract class CefPostData { // This CTOR can't be called directly. Call method create() instead. CefPostData() {} + @Override + protected void finalize() throws Throwable { + dispose(); + super.finalize(); + } + /** * Create a new CefPostData object. */ @@ -21,6 +27,11 @@ public static final CefPostData create() { return CefPostData_N.createNative(); } + /** + * Removes the native reference from an unused object. + */ + public abstract void dispose(); + /** * Returns true if this object is read-only. */ diff --git a/src/main/java/org/cef/network/CefPostDataElement.java b/src/main/java/org/cef/network/CefPostDataElement.java index 8f9c2eb3..f8a209b3 100644 --- a/src/main/java/org/cef/network/CefPostDataElement.java +++ b/src/main/java/org/cef/network/CefPostDataElement.java @@ -21,6 +21,12 @@ public static enum Type { // This CTOR can't be called directly. Call method create() instead. CefPostDataElement() {} + @Override + protected void finalize() throws Throwable { + dispose(); + super.finalize(); + } + /** * Create a new CefPostDataElement object. */ @@ -28,6 +34,11 @@ public static final CefPostDataElement create() { return CefPostDataElement_N.createNative(); } + /** + * Removes the native reference from an unused object. + */ + public abstract void dispose(); + /** * Returns true if this object is read-only. */ diff --git a/src/main/java/org/cef/network/CefPostDataElement_N.java b/src/main/java/org/cef/network/CefPostDataElement_N.java index 595cf502..6d3fdddb 100644 --- a/src/main/java/org/cef/network/CefPostDataElement_N.java +++ b/src/main/java/org/cef/network/CefPostDataElement_N.java @@ -24,32 +24,28 @@ public long getNativeRef(String identifer) { super(); } - public static final CefPostDataElement createNative() { - CefPostDataElement_N result = new CefPostDataElement_N(); + public static CefPostDataElement createNative() { try { - result.N_CefPostDataElement_CTOR(); + return CefPostDataElement_N.N_Create(); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); + return null; } - if (result.N_CefHandle == 0) return null; - return result; } @Override - protected void finalize() throws Throwable { + public void dispose() { try { - N_CefPostDataElement_DTOR(); + N_Dispose(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); - } finally { - super.finalize(); } } @Override public boolean isReadOnly() { try { - return N_IsReadOnly(); + return N_IsReadOnly(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -59,7 +55,7 @@ public boolean isReadOnly() { @Override public void setToEmpty() { try { - N_SetToEmpty(); + N_SetToEmpty(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -68,7 +64,7 @@ public void setToEmpty() { @Override public void setToFile(String fileName) { try { - N_SetToFile(fileName); + N_SetToFile(N_CefHandle, fileName); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -77,7 +73,7 @@ public void setToFile(String fileName) { @Override public void setToBytes(int size, byte[] bytes) { try { - N_SetToBytes(size, bytes); + N_SetToBytes(N_CefHandle, size, bytes); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -86,7 +82,7 @@ public void setToBytes(int size, byte[] bytes) { @Override public Type getType() { try { - return N_GetType(); + return N_GetType(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -96,7 +92,7 @@ public Type getType() { @Override public String getFile() { try { - return N_GetFile(); + return N_GetFile(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -106,7 +102,7 @@ public String getFile() { @Override public int getBytesCount() { try { - return N_GetBytesCount(); + return N_GetBytesCount(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -116,21 +112,21 @@ public int getBytesCount() { @Override public int getBytes(int size, byte[] bytes) { try { - return N_GetBytes(size, bytes); + return N_GetBytes(N_CefHandle, size, bytes); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } return 0; } - private final native void N_CefPostDataElement_CTOR(); - private final native boolean N_IsReadOnly(); - private final native void N_SetToEmpty(); - private final native void N_SetToFile(String fileName); - private final native void N_SetToBytes(int size, byte[] bytes); - private final native Type N_GetType(); - private final native String N_GetFile(); - private final native int N_GetBytesCount(); - private final native int N_GetBytes(int size, byte[] bytes); - private final native void N_CefPostDataElement_DTOR(); + private final native static CefPostDataElement_N N_Create(); + private final native void N_Dispose(long self); + private final native boolean N_IsReadOnly(long self); + private final native void N_SetToEmpty(long self); + private final native void N_SetToFile(long self, String fileName); + private final native void N_SetToBytes(long self, int size, byte[] bytes); + private final native Type N_GetType(long self); + private final native String N_GetFile(long self); + private final native int N_GetBytesCount(long self); + private final native int N_GetBytes(long self, int size, byte[] bytes); } diff --git a/src/main/java/org/cef/network/CefPostData_N.java b/src/main/java/org/cef/network/CefPostData_N.java index c8470987..3b79cf53 100644 --- a/src/main/java/org/cef/network/CefPostData_N.java +++ b/src/main/java/org/cef/network/CefPostData_N.java @@ -4,9 +4,10 @@ package org.cef.network; -import java.util.Vector; import org.cef.callback.CefNative; +import java.util.Vector; + /** * */ @@ -28,32 +29,28 @@ public long getNativeRef(String identifer) { super(); } - public static final CefPostData createNative() { - CefPostData_N result = new CefPostData_N(); + public static CefPostData createNative() { try { - result.N_CefPostData_CTOR(); + return CefPostData_N.N_Create(); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); + return null; } - if (result.N_CefHandle == 0) return null; - return result; } @Override - protected void finalize() throws Throwable { + public void dispose() { try { - N_CefPostData_DTOR(); + N_Dispose(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); - } finally { - super.finalize(); } } @Override public boolean isReadOnly() { try { - return N_IsReadOnly(); + return N_IsReadOnly(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -63,7 +60,7 @@ public boolean isReadOnly() { @Override public int getElementCount() { try { - return N_GetElementCount(); + return N_GetElementCount(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -73,7 +70,7 @@ public int getElementCount() { @Override public void getElements(Vector elements) { try { - N_GetElements(elements); + N_GetElements(N_CefHandle, elements); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -82,7 +79,7 @@ public void getElements(Vector elements) { @Override public boolean removeElement(CefPostDataElement element) { try { - return N_RemoveElement(element); + return N_RemoveElement(N_CefHandle, element); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -92,7 +89,7 @@ public boolean removeElement(CefPostDataElement element) { @Override public boolean addElement(CefPostDataElement element) { try { - return N_AddElement(element); + return N_AddElement(N_CefHandle, element); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -102,18 +99,18 @@ public boolean addElement(CefPostDataElement element) { @Override public void removeElements() { try { - N_RemoveElements(); + N_RemoveElements(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } } - private final native void N_CefPostData_CTOR(); - private final native boolean N_IsReadOnly(); - private final native int N_GetElementCount(); - private final native void N_GetElements(Vector elements); - private final native boolean N_RemoveElement(CefPostDataElement element); - private final native boolean N_AddElement(CefPostDataElement element); - private final native void N_RemoveElements(); - private final native void N_CefPostData_DTOR(); + private final native static CefPostData_N N_Create(); + private final native void N_Dispose(long self); + private final native boolean N_IsReadOnly(long self); + private final native int N_GetElementCount(long self); + private final native void N_GetElements(long self, Vector elements); + private final native boolean N_RemoveElement(long self, CefPostDataElement element); + private final native boolean N_AddElement(long self, CefPostDataElement element); + private final native void N_RemoveElements(long self); } diff --git a/src/main/java/org/cef/network/CefRequest.java b/src/main/java/org/cef/network/CefRequest.java index eb5d4c81..2ba608c0 100644 --- a/src/main/java/org/cef/network/CefRequest.java +++ b/src/main/java/org/cef/network/CefRequest.java @@ -35,7 +35,9 @@ public enum ResourceType { RT_FAVICON, //!< Favicon. RT_XHR, //!< XMLHttpRequest. RT_PING, //!< A request for a - RT_SERVICE_WORKER //!< Main resource of a service worker. + RT_SERVICE_WORKER, //!< Main resource of a service worker. + RT_CSP_REPORT, //!< A report of Content Security Policy violations. + RT_PLUGIN_RESOURCE, //!< A resource that a plugin requested. } /** @@ -318,6 +320,12 @@ public enum ReferrerPolicy { // This CTOR can't be called directly. Call method create() instead. CefRequest() {} + @Override + protected void finalize() throws Throwable { + dispose(); + super.finalize(); + } + /** * Create a new CefRequest object. */ @@ -325,6 +333,11 @@ public static final CefRequest create() { return CefRequest_N.createNative(); } + /** + * Removes the native reference from an unused object. + */ + public abstract void dispose(); + /** * Returns the globally unique identifier for this request or 0 if not * specified. Can be used by CefRequestHandler implementations in the browser @@ -385,6 +398,24 @@ public static final CefRequest create() { */ public abstract void setPostData(CefPostData postData); + /** + * Get the value for the specified response header field. The Referer value cannot be retrieved + * using this method. Use getHeaderMap instead if there might be multiple values. + * @param name The header name. + * @return The header value. + */ + public abstract String getHeaderByName(String name); + + /** + * Set the value for the specified response header field. The Referer value cannot be set using + * this method. + * @param name The header name. + * @param value The header value. + * @param overwrite If true any existing values will be replaced with the new value. If false + * any existing values will not be overwritten. + */ + public abstract void setHeaderByName(String name, String value, boolean overwrite); + /** * Get the header values. */ diff --git a/src/main/java/org/cef/network/CefRequest_N.java b/src/main/java/org/cef/network/CefRequest_N.java index ab1c735f..71bdf00b 100644 --- a/src/main/java/org/cef/network/CefRequest_N.java +++ b/src/main/java/org/cef/network/CefRequest_N.java @@ -4,9 +4,10 @@ package org.cef.network; -import java.util.Map; import org.cef.callback.CefNative; +import java.util.Map; + class CefRequest_N extends CefRequest implements CefNative { // Used internally to store a pointer to the CEF object. private long N_CefHandle = 0; @@ -25,32 +26,28 @@ public long getNativeRef(String identifer) { super(); } - public static final CefRequest createNative() { - CefRequest_N result = new CefRequest_N(); + public static CefRequest createNative() { try { - result.N_CefRequest_CTOR(); + return CefRequest_N.N_Create(); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); + return null; } - if (result.N_CefHandle == 0) return null; - return result; } @Override - protected void finalize() throws Throwable { + public void dispose() { try { - N_CefRequest_DTOR(); + N_Dispose(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); - } finally { - super.finalize(); } } @Override public long getIdentifier() { try { - return N_GetIdentifier(); + return N_GetIdentifier(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -60,7 +57,7 @@ public long getIdentifier() { @Override public boolean isReadOnly() { try { - return N_IsReadOnly(); + return N_IsReadOnly(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -70,7 +67,7 @@ public boolean isReadOnly() { @Override public String getURL() { try { - return N_GetURL(); + return N_GetURL(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -80,7 +77,7 @@ public String getURL() { @Override public void setURL(String url) { try { - N_SetURL(url); + N_SetURL(N_CefHandle, url); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -89,7 +86,7 @@ public void setURL(String url) { @Override public String getMethod() { try { - return N_GetMethod(); + return N_GetMethod(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -99,7 +96,7 @@ public String getMethod() { @Override public void setMethod(String string) { try { - N_SetMethod(string); + N_SetMethod(N_CefHandle, string); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -108,7 +105,7 @@ public void setMethod(String string) { @Override public void setReferrer(String url, ReferrerPolicy policy) { try { - N_SetReferrer(url, policy); + N_SetReferrer(N_CefHandle, url, policy); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -117,7 +114,7 @@ public void setReferrer(String url, ReferrerPolicy policy) { @Override public String getReferrerURL() { try { - return N_GetReferrerURL(); + return N_GetReferrerURL(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -127,7 +124,7 @@ public String getReferrerURL() { @Override public ReferrerPolicy getReferrerPolicy() { try { - return N_GetReferrerPolicy(); + return N_GetReferrerPolicy(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -137,7 +134,7 @@ public ReferrerPolicy getReferrerPolicy() { @Override public CefPostData getPostData() { try { - return N_GetPostData(); + return N_GetPostData(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -147,7 +144,26 @@ public CefPostData getPostData() { @Override public void setPostData(CefPostData postData) { try { - N_SetPostData(postData); + N_SetPostData(N_CefHandle, postData); + } catch (UnsatisfiedLinkError ule) { + ule.printStackTrace(); + } + } + + @Override + public String getHeaderByName(String name) { + try { + return N_GetHeaderByName(N_CefHandle, name); + } catch (UnsatisfiedLinkError ule) { + ule.printStackTrace(); + } + return null; + } + + @Override + public void setHeaderByName(String name, String value, boolean overwrite) { + try { + N_SetHeaderByName(N_CefHandle, name, value, overwrite); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -156,7 +172,7 @@ public void setPostData(CefPostData postData) { @Override public void getHeaderMap(Map headerMap) { try { - N_GetHeaderMap(headerMap); + N_GetHeaderMap(N_CefHandle, headerMap); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -165,7 +181,7 @@ public void getHeaderMap(Map headerMap) { @Override public void setHeaderMap(Map headerMap) { try { - N_SetHeaderMap(headerMap); + N_SetHeaderMap(N_CefHandle, headerMap); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -175,7 +191,7 @@ public void setHeaderMap(Map headerMap) { public void set( String url, String method, CefPostData postData, Map headerMap) { try { - N_Set(url, method, postData, headerMap); + N_Set(N_CefHandle, url, method, postData, headerMap); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -184,7 +200,7 @@ public void set( @Override public int getFlags() { try { - return N_GetFlags(); + return N_GetFlags(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -194,7 +210,7 @@ public int getFlags() { @Override public void setFlags(int flags) { try { - N_SetFlags(flags); + N_SetFlags(N_CefHandle, flags); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -203,7 +219,7 @@ public void setFlags(int flags) { @Override public String getFirstPartyForCookies() { try { - return N_GetFirstPartyForCookies(); + return N_GetFirstPartyForCookies(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -213,7 +229,7 @@ public String getFirstPartyForCookies() { @Override public void setFirstPartyForCookies(String url) { try { - N_SetFirstPartyForCookies(url); + N_SetFirstPartyForCookies(N_CefHandle, url); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -222,7 +238,7 @@ public void setFirstPartyForCookies(String url) { @Override public ResourceType getResourceType() { try { - return N_GetResourceType(); + return N_GetResourceType(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -232,34 +248,37 @@ public ResourceType getResourceType() { @Override public TransitionType getTransitionType() { try { - return N_GetTransitionType(); + return N_GetTransitionType(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } return TransitionType.TT_AUTO_SUBFRAME; } - private final native void N_CefRequest_CTOR(); - private final native long N_GetIdentifier(); - private final native boolean N_IsReadOnly(); - private final native String N_GetURL(); - private final native void N_SetURL(String url); - private final native String N_GetMethod(); - private final native void N_SetMethod(String method); - private final native void N_SetReferrer(String url, ReferrerPolicy policy); - private final native String N_GetReferrerURL(); - private final native ReferrerPolicy N_GetReferrerPolicy(); - private final native CefPostData N_GetPostData(); - private final native void N_SetPostData(CefPostData postData); - private final native void N_GetHeaderMap(Map headerMap); - private final native void N_SetHeaderMap(Map headerMap); - private final native void N_Set( - String url, String method, CefPostData postData, Map headerMap); - private final native int N_GetFlags(); - private final native void N_SetFlags(int flags); - private final native String N_GetFirstPartyForCookies(); - private final native void N_SetFirstPartyForCookies(String url); - private final native ResourceType N_GetResourceType(); - private final native TransitionType N_GetTransitionType(); - private final native void N_CefRequest_DTOR(); + private final native static CefRequest_N N_Create(); + private final native void N_Dispose(long self); + private final native long N_GetIdentifier(long self); + private final native boolean N_IsReadOnly(long self); + private final native String N_GetURL(long self); + private final native void N_SetURL(long self, String url); + private final native String N_GetMethod(long self); + private final native void N_SetMethod(long self, String method); + private final native void N_SetReferrer(long self, String url, ReferrerPolicy policy); + private final native String N_GetReferrerURL(long self); + private final native ReferrerPolicy N_GetReferrerPolicy(long self); + private final native CefPostData N_GetPostData(long self); + private final native void N_SetPostData(long self, CefPostData postData); + private final native String N_GetHeaderByName(long self, String name); + private final native void N_SetHeaderByName( + long self, String name, String value, boolean overwrite); + private final native void N_GetHeaderMap(long self, Map headerMap); + private final native void N_SetHeaderMap(long self, Map headerMap); + private final native void N_Set(long self, String url, String method, CefPostData postData, + Map headerMap); + private final native int N_GetFlags(long self); + private final native void N_SetFlags(long self, int flags); + private final native String N_GetFirstPartyForCookies(long self); + private final native void N_SetFirstPartyForCookies(long self, String url); + private final native ResourceType N_GetResourceType(long self); + private final native TransitionType N_GetTransitionType(long self); } diff --git a/src/main/java/org/cef/network/CefResponse.java b/src/main/java/org/cef/network/CefResponse.java index fa06383f..fe705ba1 100644 --- a/src/main/java/org/cef/network/CefResponse.java +++ b/src/main/java/org/cef/network/CefResponse.java @@ -4,11 +4,12 @@ package org.cef.network; +import org.cef.handler.CefLoadHandler.ErrorCode; + import java.util.HashMap; import java.util.Map; -import java.util.Set; import java.util.Map.Entry; -import org.cef.handler.CefLoadHandler.ErrorCode; +import java.util.Set; /** * Class used to represent a web response. The methods of this class may be @@ -18,6 +19,12 @@ public abstract class CefResponse { // This CTOR can't be called directly. Call method create() instead. CefResponse() {} + @Override + protected void finalize() throws Throwable { + dispose(); + super.finalize(); + } + /** * Create a new CefRequest object. */ @@ -25,6 +32,11 @@ public static final CefResponse create() { return CefResponse_N.createNative(); } + /** + * Removes the native reference from an unused object. + */ + public abstract void dispose(); + /** * Returns true if this object is read-only. */ @@ -71,9 +83,21 @@ public static final CefResponse create() { public abstract void setMimeType(String mimeType); /** - * Get the value for the specified response header field. + * Get the value for the specified response header field. Use getHeaderMap instead if there + * might be multiple values. + * @param name The header name. + * @return The header value. + */ + public abstract String getHeaderByName(String name); + + /** + * Set the value for the specified response header field. + * @param name The header name. + * @param value The header value. + * @param overwrite If true any existing values will be replaced with the new value. If false + * any existing values will not be overwritten. */ - public abstract String getHeader(String name); + public abstract void setHeaderByName(String name, String value, boolean overwrite); /** * Get all response header fields. diff --git a/src/main/java/org/cef/network/CefResponse_N.java b/src/main/java/org/cef/network/CefResponse_N.java index a68472d0..60e25256 100644 --- a/src/main/java/org/cef/network/CefResponse_N.java +++ b/src/main/java/org/cef/network/CefResponse_N.java @@ -4,10 +4,11 @@ package org.cef.network; -import java.util.Map; import org.cef.callback.CefNative; import org.cef.handler.CefLoadHandler.ErrorCode; +import java.util.Map; + class CefResponse_N extends CefResponse implements CefNative { // Used internally to store a pointer to the CEF object. private long N_CefHandle = 0; @@ -26,32 +27,28 @@ public long getNativeRef(String identifer) { super(); } - public static final CefResponse createNative() { - CefResponse_N result = new CefResponse_N(); + public static CefResponse createNative() { try { - result.N_CefResponse_CTOR(); + return CefResponse_N.N_Create(); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); + return null; } - if (result.N_CefHandle == 0) return null; - return result; } @Override - protected void finalize() throws Throwable { + public void dispose() { try { - N_CefResponse_DTOR(); + N_Dispose(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); - } finally { - super.finalize(); } } @Override public boolean isReadOnly() { try { - return N_IsReadOnly(); + return N_IsReadOnly(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -61,7 +58,7 @@ public boolean isReadOnly() { @Override public ErrorCode getError() { try { - return N_GetError(); + return N_GetError(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -71,7 +68,7 @@ public ErrorCode getError() { @Override public void setError(ErrorCode errorCode) { try { - N_SetError(errorCode); + N_SetError(N_CefHandle, errorCode); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -80,7 +77,7 @@ public void setError(ErrorCode errorCode) { @Override public int getStatus() { try { - return N_GetStatus(); + return N_GetStatus(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -90,7 +87,7 @@ public int getStatus() { @Override public void setStatus(int status) { try { - N_SetStatus(status); + N_SetStatus(N_CefHandle, status); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -99,7 +96,7 @@ public void setStatus(int status) { @Override public String getStatusText() { try { - return N_GetStatusText(); + return N_GetStatusText(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -109,7 +106,7 @@ public String getStatusText() { @Override public void setStatusText(String statusText) { try { - N_SetStatusText(statusText); + N_SetStatusText(N_CefHandle, statusText); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -118,7 +115,7 @@ public void setStatusText(String statusText) { @Override public String getMimeType() { try { - return N_GetMimeType(); + return N_GetMimeType(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -128,26 +125,35 @@ public String getMimeType() { @Override public void setMimeType(String mimeType) { try { - N_SetMimeType(mimeType); + N_SetMimeType(N_CefHandle, mimeType); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } } @Override - public String getHeader(String name) { + public String getHeaderByName(String name) { try { - return N_GetHeader(name); + return N_GetHeaderByName(N_CefHandle, name); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } return null; } + @Override + public void setHeaderByName(String name, String value, boolean overwrite) { + try { + N_SetHeaderByName(N_CefHandle, name, value, overwrite); + } catch (UnsatisfiedLinkError ule) { + ule.printStackTrace(); + } + } + @Override public void getHeaderMap(Map headerMap) { try { - N_GetHeaderMap(headerMap); + N_GetHeaderMap(N_CefHandle, headerMap); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -156,24 +162,26 @@ public void getHeaderMap(Map headerMap) { @Override public void setHeaderMap(Map headerMap) { try { - N_SetHeaderMap(headerMap); + N_SetHeaderMap(N_CefHandle, headerMap); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } } - private final native void N_CefResponse_CTOR(); - private final native boolean N_IsReadOnly(); - private final native ErrorCode N_GetError(); - private final native void N_SetError(ErrorCode errorCode); - private final native int N_GetStatus(); - private final native void N_SetStatus(int status); - private final native String N_GetStatusText(); - private final native void N_SetStatusText(String statusText); - private final native String N_GetMimeType(); - private final native void N_SetMimeType(String mimeType); - private final native String N_GetHeader(String name); - private final native void N_GetHeaderMap(Map headerMap); - private final native void N_SetHeaderMap(Map headerMap); - private final native void N_CefResponse_DTOR(); + private final native static CefResponse_N N_Create(); + private final native void N_Dispose(long self); + private final native boolean N_IsReadOnly(long self); + private final native ErrorCode N_GetError(long self); + private final native void N_SetError(long self, ErrorCode errorCode); + private final native int N_GetStatus(long self); + private final native void N_SetStatus(long self, int status); + private final native String N_GetStatusText(long self); + private final native void N_SetStatusText(long self, String statusText); + private final native String N_GetMimeType(long self); + private final native void N_SetMimeType(long self, String mimeType); + private final native String N_GetHeaderByName(long self, String name); + private final native void N_SetHeaderByName( + long self, String name, String value, boolean overwrite); + private final native void N_GetHeaderMap(long self, Map headerMap); + private final native void N_SetHeaderMap(long self, Map headerMap); } diff --git a/src/main/java/org/cef/network/CefURLRequest.java b/src/main/java/org/cef/network/CefURLRequest.java index 53802a73..2327cd4d 100644 --- a/src/main/java/org/cef/network/CefURLRequest.java +++ b/src/main/java/org/cef/network/CefURLRequest.java @@ -26,6 +26,12 @@ public static enum Status { // This CTOR can't be called directly. Call method create() instead. CefURLRequest() {} + @Override + protected void finalize() throws Throwable { + dispose(); + super.finalize(); + } + /** * Create a new URL request. Only GET, POST, HEAD, DELETE and PUT request * methods are supported. Multiple post data elements are not supported and @@ -42,7 +48,10 @@ public static final CefURLRequest create(CefRequest request, CefURLRequestClient return CefURLRequest_N.createNative(request, client); } - public abstract void finalize(); + /** + * Removes the native reference from an unused object. + */ + public abstract void dispose(); /** * Returns the request object used to create this URL request. The returned diff --git a/src/main/java/org/cef/network/CefURLRequest_N.java b/src/main/java/org/cef/network/CefURLRequest_N.java index d75bc68a..e5a73aba 100644 --- a/src/main/java/org/cef/network/CefURLRequest_N.java +++ b/src/main/java/org/cef/network/CefURLRequest_N.java @@ -4,8 +4,8 @@ package org.cef.network; -import org.cef.callback.CefURLRequestClient; import org.cef.callback.CefNative; +import org.cef.callback.CefURLRequestClient; import org.cef.handler.CefLoadHandler.ErrorCode; class CefURLRequest_N extends CefURLRequest implements CefNative { @@ -34,7 +34,7 @@ public static final CefURLRequest createNative(CefRequest request, CefURLRequest // keep a reference to the request and client objects. CefURLRequest_N result = new CefURLRequest_N(request, client); try { - result.N_CefURLRequest_CTOR(request, client); + result.N_Create(request, client); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -43,9 +43,9 @@ public static final CefURLRequest createNative(CefRequest request, CefURLRequest } @Override - public void finalize() { + public void dispose() { try { - N_CefURLRequest_DTOR(); + N_Dispose(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -64,7 +64,7 @@ public CefURLRequestClient getClient() { @Override public Status getRequestStatus() { try { - return N_GetRequestStatus(); + return N_GetRequestStatus(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -74,7 +74,7 @@ public Status getRequestStatus() { @Override public ErrorCode getRequestError() { try { - return N_GetRequestError(); + return N_GetRequestError(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -84,7 +84,7 @@ public ErrorCode getRequestError() { @Override public CefResponse getResponse() { try { - return N_GetResponse(); + return N_GetResponse(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -94,16 +94,16 @@ public CefResponse getResponse() { @Override public void cancel() { try { - N_Cancel(); + N_Cancel(N_CefHandle); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } } - private final native void N_CefURLRequest_CTOR(CefRequest request, CefURLRequestClient client); - private final native Status N_GetRequestStatus(); - private final native ErrorCode N_GetRequestError(); - private final native CefResponse N_GetResponse(); - private final native void N_Cancel(); - private final native void N_CefURLRequest_DTOR(); + private final native void N_Create(CefRequest request, CefURLRequestClient client); + private final native void N_Dispose(long self); + private final native Status N_GetRequestStatus(long self); + private final native ErrorCode N_GetRequestError(long self); + private final native CefResponse N_GetResponse(long self); + private final native void N_Cancel(long self); } diff --git a/src/main/java/org/cef/network/CefWebPluginInfo_N.java b/src/main/java/org/cef/network/CefWebPluginInfo_N.java index fe4f3ce8..00dce8c1 100644 --- a/src/main/java/org/cef/network/CefWebPluginInfo_N.java +++ b/src/main/java/org/cef/network/CefWebPluginInfo_N.java @@ -7,10 +7,12 @@ import org.cef.callback.CefNativeAdapter; class CefWebPluginInfo_N extends CefNativeAdapter implements CefWebPluginInfo { + CefWebPluginInfo_N() {} + @Override public String getName() { try { - return N_GetName(); + return N_GetName(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -20,7 +22,7 @@ public String getName() { @Override public String getPath() { try { - return N_GetPath(); + return N_GetPath(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -30,7 +32,7 @@ public String getPath() { @Override public String getVersion() { try { - return N_GetVersion(); + return N_GetVersion(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } @@ -40,15 +42,15 @@ public String getVersion() { @Override public String getDescription() { try { - return N_GetDescription(); + return N_GetDescription(getNativeRef(null)); } catch (UnsatisfiedLinkError ule) { ule.printStackTrace(); } return null; } - private final native String N_GetName(); - private final native String N_GetPath(); - private final native String N_GetVersion(); - private final native String N_GetDescription(); + private final native String N_GetName(long self); + private final native String N_GetPath(long self); + private final native String N_GetVersion(long self); + private final native String N_GetDescription(long self); } diff --git a/src/main/java/org/cef/network/CefWebPluginManager.java b/src/main/java/org/cef/network/CefWebPluginManager.java index 9a4c7490..fb3e653e 100644 --- a/src/main/java/org/cef/network/CefWebPluginManager.java +++ b/src/main/java/org/cef/network/CefWebPluginManager.java @@ -11,7 +11,7 @@ * Class used to manage web plugins. */ public abstract class CefWebPluginManager { - // This CTOR can't be called directly. Call method create() instead. + // This CTOR can't be called directly. Call method getGlobalManager() instead. CefWebPluginManager() {} /** @@ -22,35 +22,39 @@ public static final CefWebPluginManager getGlobalManager() { } /** - * Visit web plugin information. Can be called on any thread in the browser - * process. + * Visit web plugin information. Can be called on any thread in the browser process. + * * @param visitor Called with plugin information when available. */ public abstract void visitPlugins(CefWebPluginInfoVisitor visitor); /** - * Cause the plugin list to refresh the next time it is accessed regardless - * of whether it has already been loaded. Can be called on any thread in the - * browser process. + * Cause the plugin list to refresh the next time it is accessed regardless of whether it has + * already been loaded. Can be called on any thread in the browser process. */ public abstract void refreshPlugins(); /** - * Unregister an internal plugin. This may be undone the next time - * CefRefreshWebPlugins() is called. Can be called on any thread in the browser - * process. + * Unregister an internal plugin. This may be undone the next time refreshPlugins() is called. + * Can be called on any thread in the browser process. + * + * @param path Plugin file path (DLL/bundle/library). */ public abstract void unregisterInternalPlugin(String path); /** - * Register a plugin crash. Can be called on any thread in the browser process - * but will be executed on the IO thread. + * Register a plugin crash. Can be called on any thread in the browser process but will be + * executed on the IO thread. + * + * @param path Plugin file path (DLL/bundle/library). */ public abstract void registerPluginCrash(String path); /** - * Query if a plugin is unstable. Can be called on any thread in the browser - * process. + * Query if a plugin is unstable. Can be called on any thread in the browser process. + * + * @param path Plugin file path (DLL/bundle/library). + * @param callback Called when plugin information is available. */ public abstract void isWebPluginUnstable(String path, CefWebPluginUnstableCallback callback); } diff --git a/src/main/java/org/cef/network/CefWebPluginManager_N.java b/src/main/java/org/cef/network/CefWebPluginManager_N.java index 592e020b..c9217047 100644 --- a/src/main/java/org/cef/network/CefWebPluginManager_N.java +++ b/src/main/java/org/cef/network/CefWebPluginManager_N.java @@ -8,21 +8,9 @@ import org.cef.callback.CefWebPluginInfoVisitor; import org.cef.callback.CefWebPluginUnstableCallback; -class CefWebPluginManager_N extends CefWebPluginManager implements CefNative { - // Used internally to store a pointer to the CEF object. - private long N_CefHandle = 0; +class CefWebPluginManager_N extends CefWebPluginManager { private static CefWebPluginManager_N instance = null; - @Override - public void setNativeRef(String identifer, long nativeRef) { - N_CefHandle = nativeRef; - } - - @Override - public long getNativeRef(String identifer) { - return N_CefHandle; - } - CefWebPluginManager_N() { super(); }