This commit is contained in:
helloworldlv
2025-06-16 15:53:37 +08:00
parent 65da66e575
commit 8c228b44cc
77 changed files with 946 additions and 1222 deletions
+1 -1
View File
@@ -5,7 +5,7 @@ OHOS_NDK_CMAKE_TOOLCHAIN_PATH="E:/huawei/IDE/DevEcoStudio/sdk/default/openharmon
#export PATH=${OHOS_NDK_CMAKE_PATH}:$PATH
mkdir build
cd build
${OHOS_NDK_CMAKE_PATH}/cmake.exe -G "Ninja" -DCMAKE_BUILD_TYPE=Release \ -DOHOS_STL=c++_shared -DCMAKE_TOOLCHAIN_FILE=${OHOS_NDK_CMAKE_TOOLCHAIN_PATH} ../conch/proj.ohos
${OHOS_NDK_CMAKE_PATH}/cmake.exe -G "Ninja" -DCMAKE_BUILD_TYPE=Release -DOHOS_STL=c++_shared -DCMAKE_TOOLCHAIN_FILE=${OHOS_NDK_CMAKE_TOOLCHAIN_PATH} ../conch/proj.ohos
${OHOS_NDK_CMAKE_PATH}/cmake.exe --build .
# 如果需要编译静态库则需要设置 cmake 变量 -DBUILD_SHARED_LIBS=OFF
# 可以通过-DCMAKE_INSTALL_PREFIX=xxx 设置库的安装目录
@@ -10,7 +10,6 @@ android {
}
}
compileSdkVersion 28
buildToolsVersion "30.0.3"
useLibrary 'org.apache.http.legacy'
defaultConfig {
@@ -7,7 +7,7 @@ buildscript {
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.1'
classpath 'com.android.tools.build:gradle:7.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
@@ -1,4 +1,4 @@
import proguard.gradle.ProGuardTask
//import proguard.gradle.ProGuardTask
apply plugin: 'com.android.library'
@@ -46,7 +46,7 @@ task deleteBuild(type: Delete) {
delete fromJar
}
/*
task conchUglify(type: ProGuardTask, dependsOn: "build") {
// 未混淆的jar
injars fromJar
@@ -55,7 +55,7 @@ task conchUglify(type: ProGuardTask, dependsOn: "build") {
// 具体需要keep住的类
configuration 'proguard-rules.pro'
}
*/
task conchMakeJar(type: Jar) {
from zipTree(zipFile)
@@ -975,6 +975,8 @@ class Navigator {
return "LayaBox(iPhone; CPU iPhone OS Mac OS X)";
else if (os == "android")
return "LayaBox Android";
else if (os == "OpenHarmony")
return "LayaBox OpenHarmony";
else
return 'LayaBox/2.1';
}
@@ -1624,7 +1626,7 @@ class XMLHttpRequest extends EventTarget {
var onPostError = function (e1, e2) {
var _t = this._t;
_t._readyState = 4;
_t._status = 404;
_t._status = e2;
_t.xhr._changeState(4);
if (_t.onerror) {
var ev = new _lbEvent("error");
@@ -7040,11 +7042,6 @@ var clearTimeout = window.clearTimeout = _window.clearTimeout;
var setInterval = window.setInterval = _window.setInterval;
var setTimeout = window.setTimeout = _window.setTimeout;
Object.defineProperty(window, 'runtime', { get: function () { return true; } });
window.postMessage = function (data, d) {
if (typeof (data) == "object")
data = JSON.stringify(data);
conch.callWebviewJS("window.__getMessemage", encodeURIComponent(data), "");
};
window.postRuntimeMessage = function (d) {
if (typeof (d) == "object")
d = JSON.stringify(d);
@@ -7110,14 +7107,5 @@ window.performance = new Performance();
class AppInfo {
}
;
var appobj = null;
try {
appobj = JSON.parse(conch.readFileFromAsset('app.json', 'utf8'));
if (appobj) {
require(appobj.mainjs);
}
}
catch (e) {
require('index');
}
require('index.js');
})();
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+174 -112
View File
@@ -1,78 +1,129 @@
#!/usr/bin/env sh
#!/bin/sh
#
# Copyright ? 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions ?$var?, ?${var}?, ?${var:-default}?, ?${var+SET}?,
# ?${var#prefix}?, ?${var%suffix}?, and ?$( cmd )?;
# * compound commands having a testable exit status, especially ?case?;
# * various built-in commands including ?command?, ?set?, and ?ulimit?.
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
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
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
MAX_FD=maximum
warn () {
echo "$*"
}
} >&2
die () {
echo
echo "$*"
echo
exit 1
}
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -81,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
@@ -89,84 +140,95 @@ location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
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
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
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`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# 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"
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
# 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")"
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+24 -19
View File
@@ -1,3 +1,19 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@@ -13,15 +29,18 @@ if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@@ -35,7 +54,7 @@ goto fail
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
@@ -45,28 +64,14 @@ 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%
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
@@ -975,6 +975,8 @@ class Navigator {
return "LayaBox(iPhone; CPU iPhone OS Mac OS X)";
else if (os == "android")
return "LayaBox Android";
else if (os == "OpenHarmony")
return "LayaBox OpenHarmony";
else
return 'LayaBox/2.1';
}
@@ -1624,7 +1626,7 @@ class XMLHttpRequest extends EventTarget {
var onPostError = function (e1, e2) {
var _t = this._t;
_t._readyState = 4;
_t._status = 404;
_t._status = e2;
_t.xhr._changeState(4);
if (_t.onerror) {
var ev = new _lbEvent("error");
@@ -7040,11 +7042,6 @@ var clearTimeout = window.clearTimeout = _window.clearTimeout;
var setInterval = window.setInterval = _window.setInterval;
var setTimeout = window.setTimeout = _window.setTimeout;
Object.defineProperty(window, 'runtime', { get: function () { return true; } });
window.postMessage = function (data, d) {
if (typeof (data) == "object")
data = JSON.stringify(data);
conch.callWebviewJS("window.__getMessemage", encodeURIComponent(data), "");
};
window.postRuntimeMessage = function (d) {
if (typeof (d) == "object")
d = JSON.stringify(d);
@@ -7110,14 +7107,5 @@ window.performance = new Performance();
class AppInfo {
}
;
var appobj = null;
try {
appobj = JSON.parse(conch.readFileFromAsset('app.json', 'utf8'));
if (appobj) {
require(appobj.mainjs);
}
}
catch (e) {
require('index');
}
require('index.js');
})();
@@ -89,6 +89,7 @@ set(${PROJECT_NAME}_src
../../../source/napi/render/plugin_render.cpp
../../../source/napi/render/egl_core.cpp
../../../source/napi/modules/TouchesNapi.cpp
../../../source/napi/modules/KeyNapi.cpp
../../../source/napi/modules/VideoPlayerNapi.cpp
)
@@ -54,7 +54,7 @@ namespace laya
{
#define FALSE_RET(v,msg,...) {if(!(v)){ /*LOGE(msg,__VA_ARGS__);*/ return false;}}
#define FALSE_RET0(v,msg) {if(!(v)){ LOGE(msg); return false;}}
#define FALSE_RET0(v,msg) {if(!(v)){ return false;}}
JCServerFileCache::SessionFileCacheType JCServerFileCache::s_bSessionCacheType =
JCServerFileCache::CT_ValidInCurProcess;
+2 -2
View File
@@ -87,7 +87,7 @@ namespace laya
//void *libhandle = dlopen("libGLESv2.so", RTLD_LAZY);
#endif
m_nUrlHistoryPos = -1;
m_sCachePath = gRedistPath + "/appCache";
m_sCachePath = gRedistPath + "appCache";
g_DecThread = new JCWorkerThread(true);
g_DecThread->setThreadName("image decode");
JCDownloadMgr* pdmgr = JCDownloadMgr::getInstance();
@@ -176,7 +176,7 @@ namespace laya
}
void JCConch::onAppStart()
{
m_strLocalStoragePath = gRedistPath + "/localstorage/";
m_strLocalStoragePath = gRedistPath + "localstorage/";
try
{
fs::create_directories(m_strLocalStoragePath);
@@ -42,7 +42,7 @@ namespace laya
m_pSvFileCache = new JCServerFileCache();
m_pSvFileCache->m_pFuncTransUrl = GlobalTransUrl;
m_pSvFileCache->m_pFuncTransUrlData = this;
m_pSvFileCache->setCachePath((gRedistPath + "/appCache").c_str());
m_pSvFileCache->setCachePath((gRedistPath + "appCache").c_str());
if (JCScriptRuntime::s_JSRT->m_pFileResMgr)
{
JCFileResManager* pFileResManager = JCScriptRuntime::s_JSRT->m_pFileResMgr;
@@ -65,7 +65,7 @@ namespace laya
m_pSvFileCache = new JCServerFileCache();
m_pSvFileCache->m_pFuncTransUrl = GlobalTransUrl;
m_pSvFileCache->m_pFuncTransUrlData = this;
m_pSvFileCache->setCachePath((gRedistPath + "/appCache").c_str());
m_pSvFileCache->setCachePath((gRedistPath + "appCache").c_str());
if (JCScriptRuntime::s_JSRT->m_pFileResMgr)
{
JCFileResManager* pFileResManager = JCScriptRuntime::s_JSRT->m_pFileResMgr;
@@ -374,13 +374,13 @@ namespace laya
const char* JSConchConfig::getRuntimeVersion()
{
#ifdef __APPLE__
return "ios-conch6-release-2.13.9";
return "ios-conch6-release-2.13.9.1";
#elif ANDROID
return "android-conch6-release-2.13.9";
return "android-conch6-release-2.13.9.1";
#elif OHOS
return "ohos-conch6-release-2.13.9";
return "ohos-conch6-release-2.13.9.1";
#elif WIN32
return "window-conch6-release-2.13.9";
return "window-conch6-release-2.13.9.1";
#endif
}
const char* JSConchConfig::getAppVersion()
+2
View File
@@ -75,6 +75,8 @@ class Navigator implements NavigatorID, NavigatorOnLine, NavigatorGeolocation {
return "LayaBox(iPhone; CPU iPhone OS Mac OS X)";
else if(os=="android")
return "LayaBox Android";
else if (os == "OpenHarmony")
return "LayaBox OpenHarmony";
else
return 'LayaBox/2.1';
};
+1 -1
View File
@@ -213,7 +213,7 @@ class XMLHttpRequest extends EventTarget{
var onPostError:any=function(e1:number, e2:number){
var _t=this._t;//不用this是因为jsc有泄露
_t._readyState = 4;
_t._status = 404;//e; 目前好像只有200和404
_t._status = e2;
_t.xhr._changeState(4);
if(_t.onerror)
{
+3 -2
View File
@@ -12,7 +12,8 @@
DomJS: string;
mainjs: string;
};
var appobj:AppInfo = null;
require('index.js');
/*var appobj:AppInfo = null;
try {
appobj = <AppInfo>JSON.parse(<string>conch.readFileFromAsset('app.json', 'utf8'));
if(appobj){
@@ -20,5 +21,5 @@
}
} catch (e) {
require('index');
}
}*/
})();
+3 -1
View File
@@ -8,6 +8,8 @@
enum class MessageType {
WM_XCOMPONENT_SURFACE_CREATED = 0,
WM_XCOMPONENT_TOUCH_EVENT,
WM_XCOMPONENT_MOUSE_EVENT,
WM_XCOMPONENT_KEY_EVENT,
WM_XCOMPONENT_SURFACE_CHANGED,
WM_XCOMPONENT_SURFACE_HIDE,
WM_XCOMPONENT_SURFACE_SHOW,
@@ -22,7 +24,7 @@ struct WorkerMessageData {
MessageType type;
void* data;
void* window;
OH_NativeXComponent_TouchEvent* touchEvent;
void* eventData;
};
class WorkerMessageQueue final {
+16 -9
View File
@@ -43,16 +43,23 @@ napi_value registerFunction(napi_env env, napi_callback_info info) {
if (functionType != napi_function) {
napi_throw_type_error(env, NULL, "Wrong arguments");
return nullptr;
}
napi_ref fucRef;
napi_create_reference(env, args[1], 1, &fucRef);
}
char* name = new char[functionName.length() + 1];
strcpy(name, functionName.c_str());
JSFunction* jsFunction = new JSFunction(name, env, fucRef);
JSFunction::addFunction(name, jsFunction);
napi_value workName;
status = napi_create_string_utf8(env, "Thread-safe call from async work", NAPI_AUTO_LENGTH, &workName);
if (status != napi_ok) {
LOGW("registerFunction napi_create_string_utf8 fail,status=%{public}d", status);
}
napi_threadsafe_function save_func;
status = napi_create_threadsafe_function(env, args[1], nullptr, workName, 0, 1, nullptr,
[](napi_env env, void *raw, void *hint) {}, NULL, JSFunction::CallJS, &save_func);
if (status != napi_ok) {
LOGW("registerFunction napi_create_threadsafe_function fail,status=%{public}d", status);
}
JSFunction jsFunction(env, save_func);
JSFunction::addFunction(functionName, jsFunction);
LOGI("begin to return!");
return nullptr;
+7 -83
View File
@@ -14,7 +14,6 @@ struct AsyncCallParam {
const char* methodName;
std::string method;
std::string module_info;
napi_ref executeFuncRef;// 安全函数调用方法的指针
};
class NapiHelper{
@@ -135,97 +134,28 @@ private:
class JSFunction {
public:
napi_ref funcRef;
napi_threadsafe_function save_func = nullptr;
napi_env env;
char* name = nullptr;
public:
static std::unordered_map<std::string, JSFunction> FUNCTION_MAP;
explicit JSFunction(char* name, napi_env env, napi_ref funcRef)
: name(name), env(env), funcRef(funcRef){}
explicit JSFunction(char* name, napi_env env)
: name(name), env(env){}
explicit JSFunction(char* name)
: name(name){}
explicit JSFunction(napi_env env, napi_threadsafe_function save_func)
: env(env), save_func(save_func){}
static JSFunction getFunction(std::string functionName)
{
return FUNCTION_MAP.at(functionName);
}
static void addFunction(std::string name, JSFunction* jsFunction) {
FUNCTION_MAP.emplace(name, *jsFunction);
}
template<typename ReturnType, typename... Args>
typename std::enable_if<!std::is_same<ReturnType, void>::value, ReturnType>::type
invoke(Args... args) {
LOGI("=========cocos-[NApiHelper]=========JSFunction::invoke =========");
napi_value global;
napi_status status = napi_get_global(env, &global);
//if (status != napi_ok) return;
napi_value func;
status = napi_get_reference_value(env, funcRef, &func);
napi_value jsArgs[sizeof...(Args)] = {NapiValueConverter::ToNapiValue(env, args)...};
napi_value return_val;
status = napi_call_function(env, global, func, sizeof...(Args), jsArgs, &return_val);
ReturnType value;
if (!NapiValueConverter::ToCppValue(env, return_val, value)) {
// Handle error here
}
return value;
}
template<typename ReturnType, typename... Args>
typename std::enable_if<std::is_same<ReturnType, void>::value, void>::type
invoke(Args... args) {
LOGI("=========cocos-[NApiHelper]=========JSFunction::invoke =========");
napi_value global;
napi_status status = napi_get_global(env, &global);
if (status != napi_ok) return;
napi_value func;
status = napi_get_reference_value(env, funcRef, &func);
napi_value jsArgs[sizeof...(Args)] = {NapiValueConverter::ToNapiValue(env, args)...};
napi_value return_val;
status = napi_call_function(env, global, func, sizeof...(Args), jsArgs, &return_val);
static void addFunction(std::string name, JSFunction jsFunction) {
FUNCTION_MAP.emplace(name, jsFunction);
}
void invokeAsync(AsyncCallParam *callParam) {
LOGI("=========cocos-[NApiHelper]=========JSFunction::invokeAsync =========");
// 传入执行方法的指针
callParam->executeFuncRef = funcRef;
napi_status status;
napi_value func;
status = napi_get_reference_value(env, funcRef, &func);
if (status != napi_ok) {
LOGW("invokeAsync napi_get_reference_value fail,status=%{public}d", status);
return callParam->cb("napi_error");
}
napi_value workName;
status = napi_create_string_utf8(env, "Thread-safe call from async work", NAPI_AUTO_LENGTH, &workName);
if (status != napi_ok) {
LOGW("invokeAsync napi_create_string_utf8 fail,status=%{public}d", status);
return callParam->cb("napi_error");
}
napi_threadsafe_function save_func;
status = napi_create_threadsafe_function(env, func, nullptr, workName, 0, 1, nullptr,
[](napi_env env, void *raw, void *hint) {}, callParam, CallJS, &save_func);
if (status != napi_ok) {
LOGW("invokeAsync napi_create_threadsafe_function fail,status=%{public}d", status);
return callParam->cb("napi_error");
}
status = napi_acquire_threadsafe_function(save_func);
if (status != napi_ok) {
@@ -233,7 +163,7 @@ public:
return callParam->cb("napi_error");
}
status = napi_call_threadsafe_function(save_func, NULL, napi_tsfn_blocking);
status = napi_call_threadsafe_function(save_func, callParam, napi_tsfn_blocking);
if (status != napi_ok) {
LOGW("invokeAsync napi_call_threadsafe_function fail,status=%{public}d", status);
return callParam->cb("napi_error");
@@ -243,19 +173,13 @@ public:
static void CallJS(napi_env env, napi_value js_cb, void *context, void *data) {
LOGI("napi_call_threadsafe_function CallJS");
AsyncCallParam *callParam = (AsyncCallParam*) (context);
AsyncCallParam *callParam = (AsyncCallParam*) (data);
if (callParam == nullptr) {
LOGW("CallJS AsyncCallParam callParam is null");
return callParam->cb("napi_error");
}
napi_status status;
status = napi_get_reference_value(env, callParam->executeFuncRef, &js_cb);
if (status != napi_ok) {
LOGW("CallJS napi_get_reference_value fail,status=%{public}d", status);
return callParam->cb("napi_error");
}
napi_value result;
status = napi_load_module_with_info(env, callParam->clsPath, callParam->module_info.c_str(), &result);
if (status != napi_ok) {
+92
View File
@@ -0,0 +1,92 @@
#include "KeyNapi.h"
#include <ace/xcomponent/native_xcomponent_key_event.h>
using namespace laya;
extern "C"
{
int ohKeyCodeToLayaKeyCode(OH_NativeXComponent_KeyCode ohKeyCode) {
static const int keyZeroInLaya = 48;
static const int keyF1InLaya = 112;
static const int keyAInLaya = 65;
static std::unordered_map<OH_NativeXComponent_KeyCode, KeyCode> keyCodeMap = {
{KEY_ESCAPE, KeyCode::ESCAPE},
{KEY_GRAVE, KeyCode::GRAVE},
{KEY_MINUS, KeyCode::MINUS},
{KEY_EQUALS, KeyCode::EQUALS},
{KEY_DEL, KeyCode::DEL},
{KEY_TAB, KeyCode::TAB},
{KEY_LEFT_BRACKET, KeyCode::LEFT_BRACKET},
{KEY_RIGHT_BRACKET, KeyCode::RIGHT_BRACKET},
{KEY_BACKSLASH, KeyCode::BACKSLASH},
{KEY_CAPS_LOCK, KeyCode::CAPS_LOCK},
{KEY_SEMICOLON, KeyCode::SEMICOLON},
{KEY_APOSTROPHE, KeyCode::APOSTROPHE},
{KEY_ENTER, KeyCode::ENTER},
{KEY_SHIFT_LEFT, KeyCode::SHIFT_LEFT},
{KEY_COMMA, KeyCode::COMMA},
{KEY_PERIOD, KeyCode::PERIOD},
{KEY_SLASH, KeyCode::SLASH},
{KEY_SHIFT_RIGHT, KeyCode::SHIFT_RIGHT},
{KEY_CTRL_LEFT, KeyCode::CTRL_LEFT},
{KEY_ALT_LEFT, KeyCode::ALT_LEFT},
{KEY_SPACE, KeyCode::SPACE},
{KEY_ALT_RIGHT, KeyCode::ALT_RIGHT},
{KEY_CTRL_RIGHT, KeyCode::CTRL_RIGHT},
{KEY_DPAD_LEFT, KeyCode::DPAD_LEFT},
{KEY_DPAD_RIGHT, KeyCode::DPAD_RIGHT},
{KEY_DPAD_DOWN, KeyCode::DPAD_DOWN},
{KEY_DPAD_UP, KeyCode::DPAD_UP},
{KEY_INSERT, KeyCode::INSERT},
};
if (keyCodeMap.find(ohKeyCode) != keyCodeMap.end()) {
return int(keyCodeMap[ohKeyCode]);
}
if (ohKeyCode >= KEY_0 && ohKeyCode <= KEY_9) {
return keyZeroInLaya + ohKeyCode - KEY_0;
}
if (ohKeyCode >= KEY_A && ohKeyCode <= KEY_Z) {
return keyAInLaya + ohKeyCode - KEY_A;
}
if (ohKeyCode >= KEY_F1 && ohKeyCode <= KEY_F12) {
return keyF1InLaya + ohKeyCode - KEY_F1;
}
return ohKeyCode;
}
void nativeHandleKey(OH_NativeXComponent_KeyAction action, OH_NativeXComponent_KeyCode code)
{
inputEvent e;
if (action == OH_NATIVEXCOMPONENT_KEY_ACTION_DOWN) {
e.nType = E_ONKEYDOWN;
e.keyCode = ohKeyCodeToLayaKeyCode(code);
if (code == KEY_ALT_LEFT || code == KEY_ALT_RIGHT) {
e.bAlt = true;
}
else if (code == KEY_SHIFT_LEFT || code == KEY_SHIFT_RIGHT) {
e.bShift = true;
}
else if (code == KEY_CTRL_LEFT || code == KEY_CTRL_RIGHT) {
e.bCtrl = true;
}
strncpy(e.type, "keydown", 256);
JCScriptRuntime::s_JSRT->dispatchInputEvent(e);
}
else if (action == OH_NATIVEXCOMPONENT_KEY_ACTION_UP) {
e.nType = E_ONKEYUP;
e.keyCode = ohKeyCodeToLayaKeyCode(code);
if (code == KEY_ALT_LEFT || code == KEY_ALT_RIGHT) {
e.bAlt = true;
}
else if (code == KEY_SHIFT_LEFT || code == KEY_SHIFT_RIGHT) {
e.bShift = true;
}
else if (code == KEY_CTRL_LEFT || code == KEY_CTRL_RIGHT) {
e.bCtrl = true;
}
strncpy(e.type, "keyup", 256);
JCScriptRuntime::s_JSRT->dispatchInputEvent(e);
}
else {
// KEY_ACTION_UNKNOWN
}
}
}
+45
View File
@@ -0,0 +1,45 @@
#ifndef _KEYNAPI_H_
#define _KEYNAPI_H_
#include "conch/JCScriptRuntime.h"
#include <ace/xcomponent/native_xcomponent_key_event.h>
enum class KeyCode {
ESCAPE = 27,
GRAVE = 192,
MINUS = 189,
EQUALS = 187,
DEL = 8,
TAB = 9,
LEFT_BRACKET = 219,
RIGHT_BRACKET = 221,
BACKSLASH = 220,
CAPS_LOCK = 20,
SEMICOLON = 186,
APOSTROPHE = 222,
ENTER = 13,
SHIFT_LEFT = 16,
COMMA = 188,
PERIOD = 190,
SLASH = 191,
SHIFT_RIGHT = 20016,
CTRL_LEFT = 17,
ALT_LEFT = 18,
SPACE = 32,
ALT_RIGHT = 20018,
CTRL_RIGHT = 20017,
DPAD_LEFT = 37,
DPAD_RIGHT = 39,
DPAD_DOWN = 40,
DPAD_UP = 38,
INSERT = 45,
};
using namespace laya;
extern "C"
{
void nativeHandleKey(OH_NativeXComponent_KeyAction action, OH_NativeXComponent_KeyCode code);
}
#endif
+39
View File
@@ -17,6 +17,7 @@ enum ContextType
WORKER_INIT,
NATIVE_API,
VIDEOPLAYER_NAPI,
MOUSE_WHEEL_NAPI,
};
JSBIND_ENUM(ContextType)
@@ -26,6 +27,7 @@ JSBIND_ENUM(ContextType)
JSBIND_ENUM_VALUE(WORKER_INIT);
JSBIND_ENUM_VALUE(NATIVE_API);
JSBIND_ENUM_VALUE(VIDEOPLAYER_NAPI);
JSBIND_ENUM_VALUE(MOUSE_WHEEL_NAPI);
}
NapiManager NapiManager::manager_;
@@ -93,6 +95,14 @@ napi_value NapiManager::GetContext(long contextEnum)
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
}
break;
case MOUSE_WHEEL_NAPI:
{
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("onMouseWheel", NapiManager::napiOnMouseWheel),
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
}
break;
default:
LOGI("unknown type");
}
@@ -219,6 +229,35 @@ void NapiManager::OnPageHideNative()
LOGI("NapiManager::OnPageHideNative");
}
napi_value NapiManager::napiOnMouseWheel(napi_env env, napi_callback_info info)
{
size_t argc = 4;
napi_value args[4] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
if (argc != 4)
{
napi_throw_type_error(env, NULL, "Wrong number of arguments");
return nullptr;
}
char buf[256];
size_t length;
napi_get_value_string_utf8(env, args[0], buf, sizeof(buf), &length);
std::string eventType = buf;
double localX;
napi_get_value_double(env, args[1], &localX);
double localY;
napi_get_value_double(env, args[2], &localY);
double offsetY;
napi_get_value_double(env, args[3], &offsetY);
PluginRender::GetInstance()->dispatchMouseWheelCB(eventType, localX, localY, offsetY);
return nullptr;
}
JSBIND_GLOBAL()
{
JSBIND_FUNCTION(NapiManager::GetContext, "getContext");
+2
View File
@@ -43,6 +43,8 @@ public:
static napi_value napiNativeEngineStart(napi_env env, napi_callback_info info);
static napi_value napiWritablePathInit(napi_env env, napi_callback_info info);
static napi_value napiOnMouseWheel(napi_env env, napi_callback_info info);
OH_NativeXComponent* GetNativeXComponent();
void SetNativeXComponent(OH_NativeXComponent* nativeXComponent);
+122 -3
View File
@@ -1,3 +1,4 @@
#include <ace/xcomponent/native_xcomponent_key_event.h>
#include <stdint.h>
#include <unistd.h>
@@ -5,6 +6,7 @@
#include "../../napi/plugin_manager.h"
#include "../modules/TouchesNapi.h"
#include "../../napi/NAPIFun.cpp"
#include "../modules/KeyNapi.h"
#include "native_window/external_window.h"
#include "native_buffer/native_buffer.h"
@@ -84,6 +86,27 @@ void DispatchTouchEventCB(OH_NativeXComponent* component, void* window)
}
}
void dispatchKeyEventCB(OH_NativeXComponent* component, void* window) {
OH_NativeXComponent_KeyEvent* keyEvent;
if (OH_NativeXComponent_GetKeyEvent(component, &keyEvent) >= 0) {
PluginRender::GetInstance()->sendMsgToWorker(MessageType::WM_XCOMPONENT_KEY_EVENT, component, window);
} else {
// OpenHarmonyPlatform::getKeyEventError
}
}
void dispatchMouseEventCB(OH_NativeXComponent* component, void* window) {
OH_NativeXComponent_MouseEvent* mouseEvent = new(std::nothrow) OH_NativeXComponent_MouseEvent();
int32_t ret = OH_NativeXComponent_GetMouseEvent(component, window, mouseEvent);
if (ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
PluginRender::GetInstance()->sendMsgToWorker(MessageType::WM_XCOMPONENT_MOUSE_EVENT, component, window, mouseEvent);
}
}
void dispatchHoverEventCB(OH_NativeXComponent* component, bool isHover) {
// OpenHarmonyPlatform::DispatchHoverEventCB
}
PluginRender::PluginRender() : component_(nullptr)
{
auto renderCallback = PluginRender::GetNXComponentCallback();
@@ -126,7 +149,13 @@ void PluginRender::onMessageCallback(const uv_async_t* /* req */) {
if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_CREATED) {
render->OnSurfaceCreated(nativexcomponet, msgData.window);
} else if (msgData.type == MessageType::WM_XCOMPONENT_TOUCH_EVENT) {
render->DispatchTouchEvent(nativexcomponet, msgData.window, msgData.touchEvent);
OH_NativeXComponent_TouchEvent* touchEvent = reinterpret_cast<OH_NativeXComponent_TouchEvent*>(msgData.eventData);
render->DispatchTouchEvent(nativexcomponet, msgData.window, touchEvent);
} else if (msgData.type == MessageType::WM_XCOMPONENT_KEY_EVENT) {
render->DispatchKeyEvent(nativexcomponet, msgData.window);
} else if (msgData.type == MessageType::WM_XCOMPONENT_MOUSE_EVENT) {
OH_NativeXComponent_MouseEvent* mouseEvent = reinterpret_cast<OH_NativeXComponent_MouseEvent*>(msgData.eventData);
render->DispatchMouseEvent(nativexcomponet, msgData.window, mouseEvent);
} else if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_CHANGED) {
render->OnSurfaceChanged(nativexcomponet, msgData.window);
} else if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_HIDE) {
@@ -177,6 +206,33 @@ void PluginRender::SetNativeXComponent(OH_NativeXComponent* component)
OH_NativeXComponent_RegisterCallback(component_, &PluginRender::callback_);
OH_NativeXComponent_RegisterSurfaceHideCallback(component_, OnSurfaceHideCB);
OH_NativeXComponent_RegisterSurfaceShowCallback(component_, OnSurfaceShowCB);
// register keyEvent
OH_NativeXComponent_RegisterKeyEventCallback(component_, dispatchKeyEventCB);
// register mouseEvent
_mouseCallback.DispatchMouseEvent = dispatchMouseEventCB;
_mouseCallback.DispatchHoverEvent = dispatchHoverEventCB;
OH_NativeXComponent_RegisterMouseEventCallback(component_, &_mouseCallback);
}
void PluginRender::dispatchMouseWheelCB(std::string eventType, float localX, float localY, float offsetY) {
if (PluginRender::GetInstance()->isMouseLeftActive) {
return;
}
if (eventType == "actionUpdate") {
float moveScrollY = offsetY - scrollDistance;
scrollDistance = offsetY;
inputEvent e;
e.nTouchType = e.nType = E_ONMOUSEWHEEL;
strncpy(e.type, "mousewheel", 256);
e.posX = localX;
e.posY = localY;
e.nWheel = moveScrollY;
if (!e.nWheel) return;
JCScriptRuntime::s_JSRT->dispatchInputEvent(e);
} else {
scrollDistance = 0;
}
}
void PluginRender::workerInit(napi_env env, uv_loop_t* loop) {
@@ -196,8 +252,8 @@ void PluginRender::sendMsgToWorker(const MessageType& type, OH_NativeXComponent*
enqueue(data);
}
void PluginRender::sendMsgToWorker(const MessageType& type, OH_NativeXComponent* component, void* window, OH_NativeXComponent_TouchEvent* touchEvent) {
WorkerMessageData data{type, static_cast<void*>(component), window, touchEvent};
void PluginRender::sendMsgToWorker(const MessageType& type, OH_NativeXComponent* component, void* window, void* eventData) {
WorkerMessageData data{type, static_cast<void*>(component), window, eventData};
enqueue(data);
}
@@ -255,6 +311,8 @@ void PluginRender::OnSurfaceChanged(OH_NativeXComponent* component, void* window
void PluginRender::OnSurfaceDestroyed(OH_NativeXComponent* component, void* window)
{
delete eglCore_;
eglCore_ = nullptr;
}
void PluginRender::OnSurfaceHide()
@@ -305,6 +363,67 @@ void PluginRender::DispatchTouchEvent(OH_NativeXComponent* component, void* wind
delete touchEvent;
}
void PluginRender::DispatchKeyEvent(OH_NativeXComponent* component, void* window)
{
OH_NativeXComponent_KeyEvent* keyEvent;
if (OH_NativeXComponent_GetKeyEvent(component, &keyEvent) >= 0) {
static const int keyCodeUnknownInOH = -1;
static const int keyActionUnknownInOH = -1;
OH_NativeXComponent_KeyAction action;
OH_NativeXComponent_GetKeyEventAction(keyEvent, &action);
OH_NativeXComponent_KeyCode code;
OH_NativeXComponent_GetKeyEventCode(keyEvent, &code);
if (code == keyCodeUnknownInOH || action == keyActionUnknownInOH) {
// "unknown code and action dont't callback"
return;
}
nativeHandleKey(action, code);
} else {
// OpenHarmonyPlatform::getKeyEventError
}
}
void PluginRender::DispatchMouseEvent(OH_NativeXComponent* component, void* window, OH_NativeXComponent_MouseEvent* mouseEvent)
{
inputEvent e;
e.posX = mouseEvent->x;
e.posY = mouseEvent->y;
if (mouseEvent->action == OH_NativeXComponent_MouseEventAction::OH_NATIVEXCOMPONENT_MOUSE_PRESS) {
if (mouseEvent->button == OH_NativeXComponent_MouseEventButton::OH_NATIVEXCOMPONENT_LEFT_BUTTON) {
PluginRender::GetInstance()->isMouseLeftActive = true;
e.nTouchType = e.nType = E_ONMOUSEDOWN;
strncpy(e.type, "mousedown", 256);
}
else if(mouseEvent->button == OH_NativeXComponent_MouseEventButton::OH_NATIVEXCOMPONENT_RIGHT_BUTTON) {
e.nTouchType = e.nType = E_ONRIGHTMOUSEDOWN;
strncpy(e.type, "rightmousedown", 256);
}
}
else if (mouseEvent->action == OH_NativeXComponent_MouseEventAction::OH_NATIVEXCOMPONENT_MOUSE_RELEASE) {
if (mouseEvent->button == OH_NativeXComponent_MouseEventButton::OH_NATIVEXCOMPONENT_LEFT_BUTTON) {
PluginRender::GetInstance()->isMouseLeftActive = false;
e.nTouchType = e.nType = E_ONMOUSEUP;
strncpy(e.type, "mouseup", 256);
}
else if(mouseEvent->button == OH_NativeXComponent_MouseEventButton::OH_NATIVEXCOMPONENT_RIGHT_BUTTON) {
e.nTouchType = e.nType = E_ONRIGHTMOUSEUP;
strncpy(e.type, "rightmouseup", 256);
}
}
else if (mouseEvent->action == OH_NativeXComponent_MouseEventAction::OH_NATIVEXCOMPONENT_MOUSE_MOVE) {
e.nTouchType = e.nType = E_ONMOUSEMOVE;
strncpy(e.type, "mousemove", 256);
}
else {
return;
}
e.nWheel = 0;
JCScriptRuntime::s_JSRT->dispatchInputEvent(e);
delete mouseEvent;
}
void PluginRender::OnCreateNative(napi_env env, uv_loop_t* loop) {
LOGI("PluginRender::OnCreateNative");
}
+8 -1
View File
@@ -21,11 +21,13 @@ public:
static void timerCb(uv_timer_t* handle);
void SetNativeXComponent(OH_NativeXComponent* component);
void dispatchMouseWheelCB(std:: string eventType, float localX, float localY, float offsetY);
void workerInit(napi_env env, uv_loop_t* loop);
void sendMsgToWorker(const MessageType& type, OH_NativeXComponent* component, void* window);
void sendMsgToWorker(const MessageType& type, OH_NativeXComponent* component, void* window, OH_NativeXComponent_TouchEvent* touchEvent);
void sendMsgToWorker(const MessageType& type, OH_NativeXComponent* component, void* window, void* eventData);
void enqueue(const WorkerMessageData& data);
bool dequeue(WorkerMessageData* data);
void triggerMessageSignal();
@@ -54,6 +56,8 @@ public:
void OnSurfaceShow(void* window);
void DispatchTouchEvent(OH_NativeXComponent* component, void* window, OH_NativeXComponent_TouchEvent* touchEvent);
void DispatchKeyEvent(OH_NativeXComponent* component, void* window);
void DispatchMouseEvent(OH_NativeXComponent* component, void* window, OH_NativeXComponent_MouseEvent* mouseEvent);
void OnCreateNative(napi_env env, uv_loop_t* loop);
void OnShowNative();
@@ -65,8 +69,10 @@ public:
static OH_NativeXComponent_Callback callback_;
OH_NativeXComponent* component_{nullptr};
OH_NativeXComponent_MouseEvent_Callback _mouseCallback;
uv_timer_t timerHandle_;
bool timerInited_{false};
bool isMouseLeftActive{false};
uv_loop_t* workerLoop_{nullptr};
uv_async_t messageSignal_{};
WorkerMessageQueue messageQueue_;
@@ -77,6 +83,7 @@ public:
double x_;
double y_;
float scrollDistance = 0.0;
static uint64_t animationInterval_;
static uint64_t lastTime;
+4 -16
View File
@@ -975,6 +975,8 @@ class Navigator {
return "LayaBox(iPhone; CPU iPhone OS Mac OS X)";
else if (os == "android")
return "LayaBox Android";
else if (os == "OpenHarmony")
return "LayaBox OpenHarmony";
else
return 'LayaBox/2.1';
}
@@ -1624,7 +1626,7 @@ class XMLHttpRequest extends EventTarget {
var onPostError = function (e1, e2) {
var _t = this._t;
_t._readyState = 4;
_t._status = 404;
_t._status = e2;
_t.xhr._changeState(4);
if (_t.onerror) {
var ev = new _lbEvent("error");
@@ -7040,11 +7042,6 @@ var clearTimeout = window.clearTimeout = _window.clearTimeout;
var setInterval = window.setInterval = _window.setInterval;
var setTimeout = window.setTimeout = _window.setTimeout;
Object.defineProperty(window, 'runtime', { get: function () { return true; } });
window.postMessage = function (data, d) {
if (typeof (data) == "object")
data = JSON.stringify(data);
conch.callWebviewJS("window.__getMessemage", encodeURIComponent(data), "");
};
window.postRuntimeMessage = function (d) {
if (typeof (d) == "object")
d = JSON.stringify(d);
@@ -7110,14 +7107,5 @@ window.performance = new Performance();
class AppInfo {
}
;
var appobj = null;
try {
appobj = JSON.parse(conch.readFileFromAsset('app.json', 'utf8'));
if (appobj) {
require(appobj.mainjs);
}
}
catch (e) {
require('index');
}
require('index.js');
})();
@@ -1,300 +0,0 @@
package layaair.autoupdateversion;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Locale;
import java.util.Random;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.ValueCallback;
import layaair.autoupdateversion.data.VersionData;
import layaair.game.config.config;
public class AutoUpdateAPK {
//static public final String CHECK_VERSION_URL = "http://localhost:80/setuptest_update.xml";
//static public final String APK_DOWNLOAD_PATH = "mnt/sdcard/";
//static public final String DOWNLOAD_APK_NAME = "autoupdate.apk";
static private final int UPDATE_CHECKCOMPLETED = 1;
static private final int UPDATE_DOWNLOADING = 2;
static private final int UPDATE_DOWNLOAD_ERROR = 3;
static private final int UPDATE_DOWNLOAD_COMPLETED = 4;
static private final int UPDATE_DOWNLOAD_CANCELED = 5;
static private AutoUpdateAPK s_instance;
private layaair.autoupdateversion.IUpdateCallback m_callback;
private String m_szDownloadAPKName;// = DOWNLOAD_APK_NAME;
private String m_szDownloadPath;
private int m_iVersionCode = 0;
private int m_iProgressValue = 0;
private Context m_context = null;
private VersionData m_versionData = new VersionData();
private boolean m_hasNewVersion = false;
private boolean m_hasCanceled = false;
private ValueCallback<Integer> m_pCallback;
public AutoUpdateAPK(Context p_context,ValueCallback<Integer> callback)
{
m_pCallback=callback;
s_instance = this;
m_callback = new UpdateCallback();
m_context = p_context;
this.m_szDownloadAPKName = config.GetInstance().getProperty("UpdateAPKFileName");
this.m_szDownloadPath = config.GetInstance().getProperty("UpdateDownloadPath");
setVersionCode(p_context);
downloadVersionXML(config.GetInstance().getProperty("ApkUpdateUrl"));
}
public static void DelInstance()
{
s_instance=null;
}
static public AutoUpdateAPK getInstance() {
return s_instance;
}
public void cancelDownload() {
m_hasCanceled = true;
}
private static class UpdateHandle extends Handler
{
@Override
public void handleMessage(Message msg) {
AutoUpdateAPK that=AutoUpdateAPK.getInstance();
switch (msg.what) {
case UPDATE_CHECKCOMPLETED:
that.m_callback.checkUpdateCompleted(that.getHasNewVersion(),
that.m_versionData.getName() +that.m_versionData.getVersion());
break;
case UPDATE_DOWNLOADING:
that.m_callback.downloadProgressChanged(that.m_iProgressValue);
break;
case UPDATE_DOWNLOAD_ERROR:
onUpdateEnd(1);
that.m_callback.downloadCompleted(false, msg.obj.toString());
break;
case UPDATE_DOWNLOAD_COMPLETED:
onUpdateEnd(0);
that.m_callback.downloadCompleted(true, "");
break;
case UPDATE_DOWNLOAD_CANCELED:
that.m_callback.downloadCanceled();
default:
break;
}
}
}
public static void onUpdateEnd(int ecode)
{
if (ecode == 2 || ecode == 3) {
s_instance.m_pCallback.onReceiveValue(1);
} else {
s_instance.m_pCallback.onReceiveValue(0);
}
}
Handler updateHandler = new UpdateHandle();
public void updateAPK() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.fromFile(new File(m_szDownloadPath, m_szDownloadAPKName)),
"application/vnd.android.package-archive");
m_context.startActivity(intent);
}
public void downloadAPK() {
new Thread() {
public void run() {
try {
URL url = new URL(m_versionData.getDownloasURL());
Log.i("","update apk url:"+url.toString());
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn .setRequestProperty("Accept-Encoding", "identity");
conn.setConnectTimeout(6 * 1000);
conn.connect();
// if (conn.getResponseCode() != 200)
// throw new RuntimeException("请求url失败");
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
File fileAPK = new File(m_szDownloadPath,
m_szDownloadAPKName);
if (fileAPK.exists()) {
if(fileAPK.delete())
{
Log.i("","删除apk成功");
}
else
{
Log.e("","删除apk失败");
}
}
FileOutputStream fos = new FileOutputStream(fileAPK);
int count = 0;
byte buf[] = new byte[512];
int nLastProg=0;
do {
int numread = is.read(buf);
count += numread;
m_iProgressValue = (int) (((float) count / length) * 100);
if(m_iProgressValue!=nLastProg)
{
updateHandler.sendMessage(updateHandler.obtainMessage(UPDATE_DOWNLOADING));
nLastProg = m_iProgressValue;
}
if (numread <= 0) {
updateHandler.sendEmptyMessage(UPDATE_DOWNLOAD_COMPLETED);
break;
}
fos.write(buf, 0, numread);
} while (!m_hasCanceled);
if (m_hasCanceled) {
updateHandler.sendEmptyMessage(UPDATE_DOWNLOAD_CANCELED);
}
fos.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
updateHandler.sendMessage(updateHandler.obtainMessage(UPDATE_DOWNLOAD_ERROR, e.getMessage()));
} catch (IOException e) {
e.printStackTrace();
updateHandler.sendMessage(updateHandler.obtainMessage(UPDATE_DOWNLOAD_ERROR, e.getMessage()));
}
}
}.start();
}
public void setVersionCode(Context p_context) {
try {
m_iVersionCode = p_context.getPackageManager().getPackageInfo(
p_context.getPackageName(), 0).versionCode;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
public void downloadVersionXML(final String p_szURL) {
this.setHasNewVersion(false);
new Thread() {
// ***************************************************************
@Override
public void run() {
try {
Random rnd;
rnd = new Random();
String url=p_szURL+"?r="+rnd.nextInt();
Log.i("","update url="+url);
String verjson = NetHelper
.httpStringGet(url);
parseVersionXMLFromString(verjson);
if (m_versionData.getVersionCode() > m_iVersionCode) {
setHasNewVersion(true);
}
} catch (Exception e) {
Log.e("","自动更新失败,应该是无法连接到"+p_szURL);
}
updateHandler.sendEmptyMessage(UPDATE_CHECKCOMPLETED);
}
}.start();
}
public boolean parseVersionXMLFromString(String p_szContent) {
DocumentBuilder db = null;
Document document = null;
try {
db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
try {
InputStream in = new ByteArrayInputStream(p_szContent.getBytes());
assert db != null;
document = db.parse(in);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Element root = null;
if (document != null) {
root = document.getDocumentElement();
}
// System.out.println("根节点名称:"+root.getTagName()); //根节点名称
return doParseVersionXML(root);
}
@SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi", "NewApi" })
private boolean doParseVersionXML(Element p_root) {
if(p_root==null)return false;
NodeList __ls = p_root.getChildNodes();
Node node;
for (int i = 0; i < __ls.getLength(); i++) {
node = __ls.item(i);
if (node.getNodeName().toLowerCase(Locale.ENGLISH).equals("versioncode")) {
m_versionData.setVersionCode(Integer.parseInt(node
.getTextContent()));
continue;
}
if (node.getNodeName().toLowerCase(Locale.ENGLISH).equals("version")) {
m_versionData.setVersion(node.getTextContent());
continue;
}
if (node.getNodeName().toLowerCase(Locale.ENGLISH).equals("name")) {
m_versionData.setName(node.getTextContent());
continue;
}
if (node.getNodeName().toLowerCase(Locale.ENGLISH).equals("url")) {
m_versionData.setDownloasURL(node.getTextContent());
}
}
//给apk地址加个参数防止服务器的缓存
m_versionData.setDownloasURL(m_versionData.getDownloasURL()+"?vc="+m_versionData.getVersionCode());
return false;
}
public boolean getHasNewVersion() {
return m_hasNewVersion;
}
public void setHasNewVersion(boolean m_hasNewVersion) {
this.m_hasNewVersion = m_hasNewVersion;
}
public Context getContext() {
return this.m_context;
}
}
@@ -1,39 +0,0 @@
package layaair.autoupdateversion;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
public class DialogHelper {
public static void Confirm(Context ctx, CharSequence title, CharSequence message,
CharSequence okText, OnClickListener oklistener, CharSequence cancelText,
OnClickListener cancellistener) {
AlertDialog.Builder builder = createDialog(ctx, title, message);
builder.setPositiveButton(okText, oklistener);
builder.setNegativeButton(cancelText, cancellistener);
AlertDialog dlg = builder.create();
dlg.setCanceledOnTouchOutside(false); //防止点到外面自动关掉对话框
dlg.show();
}
private static AlertDialog.Builder createDialog(Context ctx, CharSequence title,
CharSequence message) {
AlertDialog.Builder builder = new Builder(ctx);
builder.setMessage(message);
if(title!=null)
{
builder.setTitle(title);
}
return builder;
}
@SuppressWarnings("unused")
private static AlertDialog.Builder createDialog(Context ctx,int titleId, int messageId) {
AlertDialog.Builder builder = new Builder(ctx);
builder.setMessage(messageId);
builder.setTitle(titleId);
return builder;
}
}
@@ -1,10 +0,0 @@
package layaair.autoupdateversion;
public interface IUpdateCallback {
void checkUpdateCompleted(Boolean hasUpdate,
CharSequence updateInfo);
void downloadProgressChanged(int progress);
void downloadCanceled();
void downloadCompleted(Boolean sucess, CharSequence errorMsg);
}
@@ -1,55 +0,0 @@
package layaair.autoupdateversion;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class NetHelper {
public static String httpStringGet(String url) throws Exception {
return httpStringGet(url, "utf-8");
}
public static String httpStringGet(String url, String enc) throws Exception {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL u = new URL( url );
connection = (HttpURLConnection) u.openConnection();
connection.setRequestMethod( "GET" );
connection.setConnectTimeout( 5000 );
connection.setReadTimeout( 5000 );
InputStream in = connection.getInputStream();
reader = new BufferedReader( new InputStreamReader( in ) );
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append( line );
}
return String.valueOf( result );
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return "";
}
}
@@ -1,95 +0,0 @@
package layaair.autoupdateversion;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.util.Log;
public class UpdateCallback implements IUpdateCallback {
static private final String DIALOG_DOWNLOAD_ERROR_TITLE = "下载失败";
static private final String DIALOG_DOWNLOAD_ERROR_MSG = "下载更新文件失败";
static private final String DIALOG_DOWNLOAD_BUTTON_TRY = "重试";
static private final String DIALOG_DOWNLOAD_BUTTON_CANCEL= "取消";
static private final String DIALOG_UPDATE_TITLE = "更新";
static private final String DIALOG_UPDATE_MSG = "立刻更新[";
static private final String DIALOG_UPDATE_MSGEND = "]吗?";
static private final String DIALOG_UPDATE_PROGRESS= "更新进度";
static private final String DIALOG_UPDATE_BUTTON_TRY = "开始更新";
static private final String DIALOG_UPDATE_BUTTON_CANCEL= "取消更新";
ProgressDialog updateProgressDialog = null;
public void downloadProgressChanged(int progress) {
if (updateProgressDialog != null
&& updateProgressDialog.isShowing()) {
updateProgressDialog.setProgress(progress);
}
}
public void downloadCompleted(Boolean sucess, CharSequence errorMsg) {
if (updateProgressDialog != null
&& updateProgressDialog.isShowing()) {
updateProgressDialog.dismiss();
}
if (sucess) {
if (AutoUpdateAPK.getInstance() != null)
AutoUpdateAPK.getInstance().updateAPK();
} else {
if (AutoUpdateAPK.getInstance() == null)
return ;
DialogHelper.Confirm(AutoUpdateAPK.getInstance().getContext(),
DIALOG_DOWNLOAD_ERROR_TITLE,
DIALOG_DOWNLOAD_ERROR_MSG,
DIALOG_DOWNLOAD_BUTTON_TRY,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
AutoUpdateAPK.getInstance().downloadAPK();
}
}, DIALOG_DOWNLOAD_BUTTON_CANCEL, null);
}
}
public void downloadCanceled() {
Log.i("", "download canceled");
}
public void checkUpdateCompleted(Boolean hasUpdate, CharSequence updateInfo) {
if (AutoUpdateAPK.getInstance() == null)
return ;
if (hasUpdate)
{
DialogHelper.Confirm(
AutoUpdateAPK.getInstance().getContext(),
DIALOG_UPDATE_TITLE,
DIALOG_UPDATE_MSG + updateInfo+ DIALOG_UPDATE_MSGEND,DIALOG_UPDATE_BUTTON_TRY,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
updateProgressDialog = new ProgressDialog(AutoUpdateAPK.getInstance().getContext());
updateProgressDialog.setMessage(DIALOG_UPDATE_PROGRESS);
updateProgressDialog.setIndeterminate(false);
updateProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
updateProgressDialog.setMax(100);
updateProgressDialog.setProgress(0);
updateProgressDialog.setCancelable(false);
updateProgressDialog.setCanceledOnTouchOutside(false);
updateProgressDialog.show();
AutoUpdateAPK.getInstance().downloadAPK();
}
}, DIALOG_UPDATE_BUTTON_CANCEL,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
AutoUpdateAPK.onUpdateEnd(3);
}
}
);
}else{
AutoUpdateAPK.onUpdateEnd(2);
}
}
}
@@ -1,41 +0,0 @@
package layaair.autoupdateversion.data;
public class VersionData {
private int m_iVersionCode;
private String m_szName;
private String m_szVersion;
private String m_szDownloasURL;
public int getVersionCode() {
return m_iVersionCode;
}
public void setVersionCode(int p_iVersionCode) {
this.m_iVersionCode = p_iVersionCode;
}
public String getName() {
return m_szName;
}
public void setName(String p_szName) {
this.m_szName = p_szName;
}
public String getDownloasURL() {
return m_szDownloasURL;
}
public void setDownloasURL(String p_szDownloasURL) {
this.m_szDownloasURL = p_szDownloasURL;
}
public String getVersion() {
return m_szVersion;
}
public void setVersion(String m_szVersion) {
this.m_szVersion = m_szVersion;
}
}
@@ -0,0 +1,32 @@
{
"DVTSourceControlWorkspaceBlueprintPrimaryRemoteRepositoryKey" : "73A753F6B6B82ECF363DE4C3B91DD4B7F1E9400B",
"DVTSourceControlWorkspaceBlueprintWorkingCopyRepositoryLocationsKey" : {
"89833343-0185-407b-b536-d375878c54a6++6425" : {
}
},
"DVTSourceControlWorkspaceBlueprintWorkingCopyStatesKey" : {
"89833343-0185-407b-b536-d375878c54a6++6425" : 0,
"73A753F6B6B82ECF363DE4C3B91DD4B7F1E9400B" : 9223372036854775807
},
"DVTSourceControlWorkspaceBlueprintIdentifierKey" : "0FCF5F03-5E64-4C6F-A062-20CB36C066F9",
"DVTSourceControlWorkspaceBlueprintWorkingCopyPathsKey" : {
"89833343-0185-407b-b536-d375878c54a6++6425" : "Trunk\/",
"73A753F6B6B82ECF363DE4C3B91DD4B7F1E9400B" : "Conch5Git\/"
},
"DVTSourceControlWorkspaceBlueprintNameKey" : "LayaBox",
"DVTSourceControlWorkspaceBlueprintVersion" : 204,
"DVTSourceControlWorkspaceBlueprintRelativePathToProjectKey" : "IOS-SDK\/LayaBox\/LayaBox.xcodeproj",
"DVTSourceControlWorkspaceBlueprintRemoteRepositoriesKey" : [
{
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey" : "192.168.0.166:\/home\/gituser\/gitrepo\/conch5.git",
"DVTSourceControlWorkspaceBlueprintRemoteRepositorySystemKey" : "com.apple.dt.Xcode.sourcecontrol.Git",
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey" : "73A753F6B6B82ECF363DE4C3B91DD4B7F1E9400B"
},
{
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey" : "http:\/\/192.168.0.166\/svn\/conch5",
"DVTSourceControlWorkspaceBlueprintRemoteRepositorySystemKey" : "com.apple.dt.Xcode.sourcecontrol.Subversion",
"DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey" : "89833343-0185-407b-b536-d375878c54a6++6425"
}
]
}
@@ -975,6 +975,8 @@ class Navigator {
return "LayaBox(iPhone; CPU iPhone OS Mac OS X)";
else if (os == "android")
return "LayaBox Android";
else if (os == "OpenHarmony")
return "LayaBox OpenHarmony";
else
return 'LayaBox/2.1';
}
@@ -1624,7 +1626,7 @@ class XMLHttpRequest extends EventTarget {
var onPostError = function (e1, e2) {
var _t = this._t;
_t._readyState = 4;
_t._status = 404;
_t._status = e2;
_t.xhr._changeState(4);
if (_t.onerror) {
var ev = new _lbEvent("error");
@@ -7040,11 +7042,6 @@ var clearTimeout = window.clearTimeout = _window.clearTimeout;
var setInterval = window.setInterval = _window.setInterval;
var setTimeout = window.setTimeout = _window.setTimeout;
Object.defineProperty(window, 'runtime', { get: function () { return true; } });
window.postMessage = function (data, d) {
if (typeof (data) == "object")
data = JSON.stringify(data);
conch.callWebviewJS("window.__getMessemage", encodeURIComponent(data), "");
};
window.postRuntimeMessage = function (d) {
if (typeof (d) == "object")
d = JSON.stringify(d);
@@ -7110,14 +7107,5 @@ window.performance = new Performance();
class AppInfo {
}
;
var appobj = null;
try {
appobj = JSON.parse(conch.readFileFromAsset('app.json', 'utf8'));
if (appobj) {
require(appobj.mainjs);
}
}
catch (e) {
require('index');
}
require('index.js');
})();
@@ -4,8 +4,7 @@
{
"name": "default",
"signingConfig": "default",
"compatibleSdkVersion": "4.1.0(11)",
"targetSdkVersion": "4.1.0(11)",
"compatibleSdkVersion": "5.0.3(15)",
"runtimeOS": "HarmonyOS"
}
],
@@ -18,6 +18,7 @@ export interface CPPFunctions {
onDurationBack: (viewTag: number, duration: number) => void;
onCurrentTimeBack: (viewTag: number, currentTime: number) => void;
loadedmetadata: (viewTag: number) => void;
onMouseWheel: (type: string, x: number, y: number, offsetY: number) => void;
}
export const getContext: (a: number) => CPPFunctions;
@@ -2,10 +2,10 @@ import window from '@ohos.window';
import UIAbility from '@ohos.app.ability.UIAbility';
import web_webview from '@ohos.web.webview';
import laya from "liblaya.so";
import { ContextType } from "@ohos/libSysCapabilities"
import { BusinessError } from '@ohos.base';
import { GlobalContext, GlobalContextConstants } from "@ohos/libSysCapabilities"
import { GlobalContext, GlobalContextConstants, ContextType } from "@ohos/libSysCapabilities"
import buffer from '@ohos.buffer';
import { Want, AbilityConstant } from '@kit.AbilityKit';
const nativeAppLifecycle: laya.CPPFunctions = laya.getContext(ContextType.APP_LIFECYCLE);
@@ -17,7 +17,7 @@ interface config {
}
export default class MainAbility extends UIAbility {
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
nativeAppLifecycle.onCreate();
GlobalContext.storeGlobalThis(GlobalContextConstants.LAYA_ABILITY_CONTEXT, this.context);
// Initializes the webView kernel of the system. This parameter is optional if it is not used.
@@ -48,7 +48,7 @@ export default class MainAbility extends UIAbility {
let keepScreenOnPromise = windowIns.setWindowKeepScreenOn(true);
Promise.all([systemBarPromise, fullScreenPromise, keepScreenOnPromise]).then(() => {
console.info('Succeeded in setting the window');
}).catch((err) => {
}).catch((err: BusinessError) => {
console.error('Failed to set the window, cause ' + JSON.stringify(err));
});
})
@@ -86,7 +86,7 @@ export default class MainAbility extends UIAbility {
nativeAppLifecycle.onHide();
}
initConfig(fileName): config {
initConfig(fileName: string): config | undefined {
try {
let var1: Uint8Array = this.context.resourceManager.getRawFileContentSync(fileName);
let bf = new Uint8Array(var1).buffer;
@@ -97,6 +97,7 @@ export default class MainAbility extends UIAbility {
let message = (error as BusinessError).message;
console.error(`getRawFileContentSync failed, error code: ${code}, message: ${message}.`);
}
return undefined;
}
initEngine() {
@@ -106,6 +107,9 @@ export default class MainAbility extends UIAbility {
laya.ConchNAPI_SetLocalStoragePath(var1 + "/localstorage");
laya.ConchNAPI_setLocalizable(false);
let config = this.initConfig("config.json");
if (config === undefined) {
return;
}
laya.ConchNAPI_InitDLib(this.context.resourceManager, 3, "cache", var1, config.ThreadMode, config.JSDebugMode, config.JSDebugPort);
}
};
@@ -1,5 +1,4 @@
import { TextInputInfo } from '@ohos/libSysCapabilities/src/main/ets/components/EditBox'
import { Logger } from '@ohos/libSysCapabilities'
import { Logger , TextInputInfo } from '@ohos/libSysCapabilities'
import laya from "liblaya.so";
let log: Logger = new Logger(0x0001, "LayaEditBoxComponent");
@@ -1,9 +1,6 @@
import { WorkerManager } from '../workers/WorkerManager'
import {
VideoPlayerInfo,
VideoEvent
} from '@ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayer';
import worker from '@ohos.worker';
import { VideoPlayerInfo, VideoEvent } from '@ohos/libSysCapabilities';
@Component
export struct LayaVideoPlayer {
@@ -1,7 +1,6 @@
import { WebViewInfo } from "@ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg"
import worker from '@ohos.worker';
import { WorkerManager } from '../workers/WorkerManager';
import { Logger } from '@ohos/libSysCapabilities'
import { Logger, WebViewInfo } from '@ohos/libSysCapabilities'
let log: Logger = new Logger(0x0001, "LayaWebViewComponent");
@Component
@@ -27,5 +26,10 @@ export struct LayaWebview {
.visibility(this.viewInfo.visible ? Visibility.Visible : Visibility.None)
.opacity(this.viewInfo.opacity)
.backgroundColor(this.viewInfo.backgroundColor)
.onControllerAttached(() => {
if (this.viewInfo.url != '') {
this.viewInfo.controller.loadUrl(this.viewInfo.url);
}
})
}
}
@@ -1,24 +1,17 @@
import laya from 'liblaya.so'
import { ContextType } from '@ohos/libSysCapabilities'
import { TextInputInfo } from '@ohos/libSysCapabilities/src/main/ets/components/EditBox'
import { TextInputDialogEntity } from '@ohos/libSysCapabilities'
import { WebViewInfo } from '@ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg'
import { VideoPlayerInfo } from '@ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayer'
import { WorkerMsgUtils } from '@ohos/libSysCapabilities/src/main/ets/utils/WorkerMsgUtils'
import { WorkerManager } from '../workers/WorkerManager'
import { LayaEditBox } from '../components/LayaEditBox'
import { LayaWebview } from '../components/LayaWebview'
import { LayaVideoPlayer } from '../components/LayaVideoPlayer'
import { TextInputDialog } from '../components/TextInputDialog'
import { GlobalContext, GlobalContextConstants } from "@ohos/libSysCapabilities"
import { NapiHelper } from "@ohos/libSysCapabilities/src/main/ets/napi/NapiHelper"
import { Dialog } from "@ohos/libSysCapabilities"
import deviceInfo from '@ohos.deviceInfo';
import { GlobalContext, GlobalContextConstants, TextInputInfo, TextInputDialogEntity, ContextType,
WebViewInfo, VideoPlayerInfo, WorkerMsgUtils, NapiHelper, Dialog } from "@ohos/libSysCapabilities"
import promptAction from '@ohos.promptAction'
import process from '@ohos.process';
const nativePageLifecycle: laya.CPPFunctions = laya.getContext(ContextType.JSPAGE_LIFECYCLE);
const napiContext: laya.CPPFunctions = laya.getContext(ContextType.NATIVE_API);
const mouseWheelNapi: laya.CPPFunctions = laya.getContext(ContextType.MOUSE_WHEEL_NAPI);
NapiHelper.registerUIFunctions(napiContext.registerFunction);
let layaWorker = WorkerManager.getInstance().getWorker();
@@ -88,8 +81,11 @@ struct Index {
return true;
}
onMouseWheel(eventType: string, scrollY: number) {
// layaWorker.postMessage({ type: "onMouseWheel", eventType: eventType, scrollY: scrollY });
onMouseWheel(eventType: string, event: PanGestureEvent) {
if (event.source == SourceType.Mouse) {
const validFinger = event.fingerList?.find(item => item.globalX && item.globalY);
validFinger && mouseWheelNapi.onMouseWheel(eventType, validFinger.localX, validFinger.localY, event.offsetY);
}
}
build() {
@@ -102,18 +98,17 @@ struct Index {
controller: this.xcomponentController
})
.focusable(true)
.defaultFocus(true)
.gesture(
PanGesture(this.panOption)
.onActionStart(() => {
this.onMouseWheel("actionStart", 0);
.onActionStart((event: GestureEvent) => {
this.onMouseWheel("actionStart", event);
})
.onActionUpdate((event: GestureEvent) => {
if (deviceInfo.deviceType === '2in1') {
this.onMouseWheel("actionUpdate", event.offsetY);
}
this.onMouseWheel("actionUpdate", event);
})
.onActionEnd(() => {
this.onMouseWheel("actionEnd", 0);
.onActionEnd((event: GestureEvent) => {
this.onMouseWheel("actionEnd", event);
})
)
.onLoad((context) => {
@@ -1,13 +1,8 @@
import worker, { MessageEvents, ThreadWorkerGlobalScope } from '@ohos.worker';
import laya from "liblaya.so";
import { ContextType } from "@ohos/libSysCapabilities"
import { Dialog } from "@ohos/libSysCapabilities"
import { WebView } from "@ohos/libSysCapabilities"
import { JumpManager } from "@ohos/libSysCapabilities"
import { NapiHelper } from "@ohos/libSysCapabilities/src/main/ets/napi/NapiHelper"
import { GlobalContext, GlobalContextConstants } from "@ohos/libSysCapabilities"
import { WorkerDataEntity } from './WorkerDataEntity';
import { HandleMessageUtils } from "@ohos/libSysCapabilities"
import { HandleMessageUtils, NapiHelper, GlobalContext, GlobalContextConstants, ContextType,
Dialog, WebView, JumpManager } from "@ohos/libSysCapabilities"
const appLifecycle: laya.CPPFunctions = laya.getContext(ContextType.APP_LIFECYCLE);
const workerContext: laya.CPPFunctions = laya.getContext(ContextType.WORKER_INIT);
@@ -32,7 +27,7 @@ workerPort.onmessage = (e: MessageEvents): void => {
laya.ConchNAPI_OnAppStart();
break;
case "abilityContextInit":
GlobalContext.storeGlobalThis(GlobalContextConstants.LAYA_ABILITY_CONTEXT, data.context);
GlobalContext.storeGlobalThis(GlobalContextConstants.LAYA_ABILITY_CONTEXT, data.context!);
break;
case "onVideoCallBack":
videoPlayNapi.onVideoCallBack(data.viewTag, data.event);
@@ -0,0 +1,12 @@
export class WorkerDataEntity {
type?: string;
context?: Object;
viewTag?: number;
text?: string;
eventType?: string;
scrollY?: number;
url?: string;
event?: number;
duration?: number;
currentTime?: number;
}
@@ -1,12 +0,0 @@
export class WorkerDataEntity {
type: string;
context: Object;
viewTag: number;
text: string;
eventType: string;
scrollY: number;
url: string;
event: number;
duration: number;
currentTime: number;
}
@@ -15,7 +15,7 @@
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/MainAbility/MainAbility.ts",
"srcEntry": "./ets/MainAbility/MainAbility.ets",
"description": "$string:MainAbility_desc",
"icon": "$media:icon",
"label": "$string:MainAbility_label",
@@ -1,6 +1,5 @@
'use strict';
require("webglPlus.js");
conch["platCallBack"] = function (ret) {
var objid, m, rs, c, rJSON;
if (ret == null)
@@ -481,11 +480,11 @@ class MouseEvent extends UIEvent {
}
var _lbMouseEvent = window['MouseEvent'] = MouseEvent;
class MouseWheelEvent extends MouseEvent {
initMouseWheelEvent(typeArg, canBubbleArg, cancelableArg, viewArg, detailArg, screenXArg, screenYArg, clientXArg, clientYArg, buttonArg, relatedTargetArg, modifiersListArg, wheelDeltaArg) {
}
constructor() {
super("mousewheel");
}
initMouseWheelEvent(typeArg, canBubbleArg, cancelableArg, viewArg, detailArg, screenXArg, screenYArg, clientXArg, clientYArg, buttonArg, relatedTargetArg, modifiersListArg, wheelDeltaArg) {
}
}
class WheelEvent extends MouseEvent {
constructor(typeArg, eventInitDict) {
@@ -620,7 +619,6 @@ class Storage {
else {
this.fileNamePre = this.storagePath + '/' + url.split('/')[2].replace(':', '_');
}
this.filename = this.fileNamePre + '.txt';
var strdb = readFileSync(this.filename, 'utf8') || '{}';
var db = JSON.parse(strdb);
@@ -964,6 +962,8 @@ var _lbKeyboardEvent = window["KeyboardEvent"] = KeyboardEvent;
});
})(window.document);
class Navigator {
constructor() {
}
get appName() { return 'Netscape'; }
get appVersion() { return this.userAgent; }
;
@@ -994,8 +994,6 @@ class Navigator {
get language() { return 'zh-CN'; }
;
get userLanguage() { return 'zh-CN'; }
constructor() {
}
getGamepads() {
return null;
}
@@ -1628,7 +1626,7 @@ class XMLHttpRequest extends EventTarget {
var onPostError = function (e1, e2) {
var _t = this._t;
_t._readyState = 4;
_t._status = 404;
_t._status = e2;
_t.xhr._changeState(4);
if (_t.onerror) {
var ev = new _lbEvent("error");
@@ -6314,6 +6312,10 @@ class HTMLMediaElement extends HTMLElement {
}
}
class HTMLMetaElement extends HTMLElement {
constructor() {
super();
this.tagName = "META";
}
get httpEquiv() {
return this["http-equiv"];
}
@@ -6325,10 +6327,6 @@ class HTMLMetaElement extends HTMLElement {
get name() {
return this._name;
}
constructor() {
super();
this.tagName = "META";
}
}
class HTMLAudioElement extends HTMLMediaElement {
constructor() {
@@ -6899,9 +6897,6 @@ class _jsXmlAttr {
}
}
class _jsXmlNode extends _jsXmlAttr {
get firstChild() {
return this.childNodes ? this.childNodes[0] : null;
}
constructor() {
super("", "");
this.childNodes = [];
@@ -6910,6 +6905,9 @@ class _jsXmlNode extends _jsXmlAttr {
};
this.attributes = [];
}
get firstChild() {
return this.childNodes ? this.childNodes[0] : null;
}
getElementsByTagName(name) {
var result = [];
if (this.nodeName == name)
@@ -7044,11 +7042,6 @@ var clearTimeout = window.clearTimeout = _window.clearTimeout;
var setInterval = window.setInterval = _window.setInterval;
var setTimeout = window.setTimeout = _window.setTimeout;
Object.defineProperty(window, 'runtime', { get: function () { return true; } });
window.postMessage = function (data, d) {
if (typeof (data) == "object")
data = JSON.stringify(data);
conch.callWebviewJS("window.__getMessemage", encodeURIComponent(data), "");
};
window.postRuntimeMessage = function (d) {
if (typeof (d) == "object")
d = JSON.stringify(d);
@@ -7114,15 +7107,5 @@ window.performance = new Performance();
class AppInfo {
}
;
var appobj = null;
try {
// appobj = JSON.parse(conch.readFileFromAsset('app.json', 'utf8'));
// if (appobj) {
// require(appobj.mainjs);
require('scripts/index.js');
// }
}
catch (e) {
require('index');
}
require('index.js');
})();
@@ -1,9 +1,10 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
@@ -3,6 +3,7 @@ export { GlobalContext,GlobalContextConstants } from './src/main/ets/common/Glob
export { Dialog } from './src/main/ets/components/dialog/DialogWorker'
export { WebView } from './src/main/ets/components/webview/WebView'
export { WebViewInfo } from './src/main/ets/components/webview/WebViewMsg'
export { HandleMessageUtils } from './src/main/ets/Event/HandleMessageUtils'
export { TextInputDialogEntity } from './src/main/ets/entity/TextInputDialogEntity'
@@ -10,4 +11,10 @@ export { TextInputDialogEntity } from './src/main/ets/entity/TextInputDialogEnti
export { JumpManager } from './src/main/ets/system/appJump/JumpManager'
export { DeviceUtils } from './src/main/ets/system/device/DeviceUtils'
export { NetworkUtils } from './src/main/ets/system/device/NetworkUtils'
export { Logger } from './src/main/ets/utils/Logger'
export { Logger } from './src/main/ets/utils/Logger'
export { EditBox, TextInputInfo } from './src/main/ets/components/EditBox'
export { VideoPlayerInfo, VideoEvent } from './src/main/ets/components/videoplayer/VideoPlayer'
export { WorkerMsgUtils } from './src/main/ets/utils/WorkerMsgUtils'
export { NapiHelper } from './src/main/ets/napi/NapiHelper'
@@ -4,7 +4,7 @@
"author": "",
"name": "libsyscapabilities",
"description": "Please describe the basic information.",
"main": "index.ts",
"main": "index.ets",
"version": "1.0.0",
"dependencies": {}
}
@@ -1,15 +1,17 @@
import { GlobalContext, GlobalContextConstants } from "../common/GlobalContext";
import { ThreadWorkerGlobalScope } from "@ohos.worker";
import laya from "liblaya.so";
export class HandleMessageUtils {
private static context = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_ABILITY_CONTEXT);
private static workerPort;
private static workerPort: ThreadWorkerGlobalScope;
static RunJS(data: string): void {
laya.ConchNAPI_RunJS(data);
}
static init(workerPort): void {
static init(workerPort: ThreadWorkerGlobalScope): void {
HandleMessageUtils.workerPort = workerPort;
}
@@ -50,28 +52,25 @@ export class HandleMessageUtils {
*/
static executeNativeMethod(isSyn: boolean, cName: string, mName: string, nativeFunc: Function, paramStr: string): string {
let jParam = JSON.parse(paramStr || "[]");
let jParam: Array<Object> = JSON.parse(paramStr || "[]");
let result = null;
if (isSyn) {
result = nativeFunc && nativeFunc.apply(this, jParam);
result = nativeFunc && nativeFunc(...jParam);
} else {
let paramCb = (call_re: string) => {
let rsJson = {
let rsJson = JSON.stringify({
objId: -1,
cName: cName,
mName: mName,
v: call_re
}
laya.ConchNAPI_RunJS("conch.platCallBack(" + JSON.stringify(rsJson) + ")");
});
laya.ConchNAPI_RunJS("conch.platCallBack(" + rsJson + ")");
};
jParam[jParam.length] = paramCb;
result = nativeFunc && nativeFunc.apply(this, jParam);
result = nativeFunc && nativeFunc(...jParam);
}
let rsJson = {
v: result
}
return JSON.stringify(rsJson);
return JSON.stringify({v: result});
}
}
@@ -4,6 +4,7 @@ export enum ContextType {
WORKER_INIT,
NATIVE_API,
VIDEOPLAYER_NAPI,
MOUSE_WHEEL_NAPI,
}
export class Constants {
@@ -1,10 +1,22 @@
export class GlobalContext {
public static loadGlobalThis(name: string) {
return globalThis[name]
private static instance: GlobalContext;
private propMap = new Map<string, Object>();
private static getInstance(): GlobalContext {
if (!GlobalContext.instance) {
GlobalContext.instance = new GlobalContext();
}
return GlobalContext.instance;
}
public static loadGlobalThis(name: string): Object {
let ins = GlobalContext.getInstance();
return ins.propMap.get(name)!;
}
public static storeGlobalThis(name: string, obj: Object) {
globalThis[name] = obj
let ins = GlobalContext.getInstance();
ins.propMap.set(name, obj);
}
}
@@ -35,125 +35,141 @@ export class EditBox {
static MODULE_NAME : string = 'EditBox';
static create(viewTag: number) : void {
log.debug("call EditBox.create, viewTag: %{public}d", viewTag)
log.debug("call EditBox.create, viewTag: %{public}d", viewTag);
let newTextInputInfo = new TextInputInfo(viewTag);
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_ARRAY).push(newTextInputInfo);
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).set(viewTag, newTextInputInfo);
let arr = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_ARRAY) as TextInputInfo[];
arr.push(newTextInputInfo);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
map.set(viewTag, newTextInputInfo);
}
static remove(viewTag: number) : void {
log.debug("call EditBox.remove, viewTag: %{public}d", viewTag)
log.debug("call EditBox.remove, viewTag: %{public}d", viewTag);
let removeIndex = -1;
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_ARRAY)
.forEach((item: TextInputInfo, index: number) => {
let arr = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_ARRAY) as TextInputInfo[];
arr.forEach((item: TextInputInfo, index: number) => {
if (item.viewTag == viewTag) {
removeIndex = index;
}
});
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_ARRAY).splice(removeIndex, 1);
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).delete(viewTag);
arr.splice(removeIndex, 1);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
map.delete(viewTag);
}
static setPos(viewTag: number, x: number, y: number) : void {
log.debug("call EditBox.setPos, viewTag: %{public}d, x: %{public}d, y: %{public}d", viewTag, x, y)
let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).get(viewTag);
textInputInfo.x = x;
textInputInfo.y = y;
log.debug("call EditBox.setPos, viewTag: %{public}d, x: %{public}d, y: %{public}d", viewTag, x, y);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
let textInputInfo = map.get(viewTag);
textInputInfo!.x = x;
textInputInfo!.y = y;
}
static setSize(viewTag: number, w: number, h: number) : void {
log.debug("call EditBox.setSize, viewTag: %{public}d, w: %{public}d, h: %{public}d", viewTag, w, h)
let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).get(viewTag);
textInputInfo.w = w;
textInputInfo.h = h;
log.debug("call EditBox.setSize, viewTag: %{public}d, w: %{public}d, h: %{public}d", viewTag, w, h);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
let textInputInfo = map.get(viewTag);
textInputInfo!.w = w;
textInputInfo!.h = h;
}
static setOpacity(viewTag: number, opacity: number) : void {
log.debug("call EditBox.setOpacity, viewTag: %{public}d, opacity: %{public}d", viewTag, opacity)
let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).get(viewTag);
textInputInfo.opacity = opacity;
log.debug("call EditBox.setOpacity, viewTag: %{public}d, opacity: %{public}d", viewTag, opacity);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
let textInputInfo = map.get(viewTag);
textInputInfo!.opacity = opacity;
}
static setValue(viewTag: number, value: string) : void {
log.debug("call EditBox.setValue, viewTag: %{public}d, value: %{public}s", viewTag, value)
let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).get(viewTag);
textInputInfo.value = value;
log.debug("call EditBox.setValue, viewTag: %{public}d, value: %{public}s", viewTag, value);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
let textInputInfo = map.get(viewTag);
textInputInfo!.value = value;
}
static getValue(viewTag: number) : string {
let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).get(viewTag);
log.debug("call EditBox.getValue, viewTag: %{public}d, value: %{public}s", viewTag, textInputInfo.value);
return textInputInfo.value;
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
let textInputInfo = map.get(viewTag);
log.debug("call EditBox.getValue, viewTag: %{public}d, value: %{public}s", viewTag, textInputInfo!.value);
return textInputInfo!.value;
}
static setStyle(viewTag: number, style: string) : void {
log.debug("call EditBox.setStyle, viewTag: %{public}d, style: %{public}s", viewTag, style)
let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).get(viewTag);
textInputInfo.style = style;
log.debug("call EditBox.setStyle, viewTag: %{public}d, style: %{public}s", viewTag, style);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
let textInputInfo = map.get(viewTag);
textInputInfo!.style = style;
}
static setVisible(viewTag: number, visible: boolean) : void {
log.debug("call EditBox.setVisible, viewTag: %{public}d, visible: %{public}s", viewTag, visible)
let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).get(viewTag);
textInputInfo.visible = visible;
log.debug("call EditBox.setVisible, viewTag: %{public}d, visible: %{public}s", viewTag, visible);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
let textInputInfo = map.get(viewTag);
textInputInfo!.visible = visible;
}
static focus(viewTag: number) : void {
log.debug("call EditBox.focus, viewTag: %{public}d", viewTag)
let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).get(viewTag);
textInputInfo.visible = true;
textInputInfo.pos = textInputInfo.value.length;
if(textInputInfo.multiAble) {
textInputInfo.textAreaController.caretPosition(textInputInfo.pos);
log.debug("call EditBox.focus, viewTag: %{public}d", viewTag);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
let textInputInfo = map.get(viewTag);
textInputInfo!.visible = true;
textInputInfo!.pos = textInputInfo!.value.length;
if(textInputInfo!.multiAble) {
textInputInfo!.textAreaController.caretPosition(textInputInfo!.pos);
} else {
textInputInfo.textInputController.caretPosition(textInputInfo.pos);
textInputInfo!.textInputController.caretPosition(textInputInfo!.pos);
}
}
static setColor(viewTag: number, color: string) : void {
log.debug("call EditBox.setColor, viewTag: %{public}d, color: %{public}s", viewTag, color)
let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).get(viewTag);
textInputInfo.color = color;
log.debug("call EditBox.setColor, viewTag: %{public}d, color: %{public}s", viewTag, color);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
let textInputInfo = map.get(viewTag);
textInputInfo!.color = color;
}
static setFontSize(viewTag: number, size: number) : void {
log.debug("call EditBox.setFontSize, viewTag: %{public}d, size: %{public}d", viewTag, size)
let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).get(viewTag);
textInputInfo.fontSize = size;
log.debug("call EditBox.setFontSize, viewTag: %{public}d, size: %{public}d", viewTag, size);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
let textInputInfo = map.get(viewTag);
textInputInfo!.fontSize = size;
}
static setCursorPosition(viewTag: number, pos: number) : void {
log.debug("call EditBox.setCursorPosition, viewTag: %{public}d, pos: %{public}d", viewTag, pos)
let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).get(viewTag);
textInputInfo.pos = pos;
if(textInputInfo.multiAble) {
textInputInfo.textAreaController.caretPosition(pos);
log.debug("call EditBox.setCursorPosition, viewTag: %{public}d, pos: %{public}d", viewTag, pos);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
let textInputInfo = map.get(viewTag);
textInputInfo!.pos = pos;
if(textInputInfo!.multiAble) {
textInputInfo!.textAreaController.caretPosition(pos);
} else {
textInputInfo.textInputController.caretPosition(pos);
textInputInfo!.textInputController.caretPosition(pos);
}
}
static setMaxLength(viewTag: number, maxLength: number) : void {
log.debug("call EditBox.setMaxLength, viewTag: %{public}d, maxLength: %{public}d", viewTag, maxLength)
let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).get(viewTag);
textInputInfo.maxLength = maxLength;
log.debug("call EditBox.setMaxLength, viewTag: %{public}d, maxLength: %{public}d", viewTag, maxLength);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
let textInputInfo = map.get(viewTag);
textInputInfo!.maxLength = maxLength;
}
static setType(viewTag: number, type: number) : void {
log.debug("call EditBox.setType, viewTag: %{public}d, type: %{public}d", viewTag, type)
let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).get(viewTag);
log.debug("call EditBox.setType, viewTag: %{public}d, type: %{public}d", viewTag, type);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
let textInputInfo = map.get(viewTag);
switch (type) {
case 0:
textInputInfo.type = InputType.Normal;
textInputInfo!.type = InputType.Normal;
break;
case 1:
textInputInfo.type = InputType.Password;
textInputInfo!.type = InputType.Password;
break;
case 2:
textInputInfo.type = InputType.Number;
textInputInfo!.type = InputType.Number;
break;
case 3:
textInputInfo.type = InputType.NUMBER_PASSWORD;
textInputInfo!.type = InputType.NUMBER_PASSWORD;
break;
default:
log.warn("undefined type value: %{public}", type)
@@ -161,20 +177,23 @@ export class EditBox {
}
static setRegular(viewTag: number, regular: string) : void {
log.debug("call EditBox.setRegular, viewTag: %{public}d, regular: %{public}s", viewTag, regular)
let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).get(viewTag);
textInputInfo.regular = regular;
log.debug("call EditBox.setRegular, viewTag: %{public}d, regular: %{public}s", viewTag, regular);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
let textInputInfo = map.get(viewTag);
textInputInfo!.regular = regular;
}
static setMultiAble(viewTag: number, multiAble: boolean) : void {
log.debug("call EditBox.setMultiAble, viewTag: %{public}d, multiAble: %{public}s", viewTag, multiAble)
let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).get(viewTag);
textInputInfo.multiAble = multiAble;
log.debug("call EditBox.setMultiAble, viewTag: %{public}d, multiAble: %{public}s", viewTag, multiAble);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
let textInputInfo = map.get(viewTag);
textInputInfo!.multiAble = multiAble;
}
static setForbidEdit(viewTag: number, forbidEdit: boolean) : void {
log.debug("call EditBox.setForbidEdit, viewTag: %{public}d, forbidEdit: %{public}s", viewTag, forbidEdit)
let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP).get(viewTag);
textInputInfo.forbidEdit = forbidEdit;
log.debug("call EditBox.setForbidEdit, viewTag: %{public}d, forbidEdit: %{public}s", viewTag, forbidEdit);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_EDIT_BOX_INDEX_MAP) as Map<number, TextInputInfo>;
let textInputInfo = map.get(viewTag);
textInputInfo!.forbidEdit = forbidEdit;
}
}
@@ -16,21 +16,23 @@ export function handleDialogMsg(eventData: DialogMsgEntity): void {
break;
}
case "showTextInputDialog": {
let tempShowMessage: TextInputDialogEntity = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_SHOW_MESSAGE);
let tempShowMessage = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_SHOW_MESSAGE) as TextInputDialogEntity;
tempShowMessage.message = eventData.message;
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_DIALOG_CONTROLLER).open();
let controller = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_DIALOG_CONTROLLER) as CustomDialogController;
controller.open();
break;
}
case "hideTextInputDialog": {
let tempShowMessage: TextInputDialogEntity = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_SHOW_MESSAGE);
let tempShowMessage = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_SHOW_MESSAGE) as TextInputDialogEntity;
tempShowMessage.message = '';
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_DIALOG_CONTROLLER).close();
let controller = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_DIALOG_CONTROLLER) as CustomDialogController;
controller.close();
break;
}
}
}
function showDialog(dialogTitle: string, dialogMessage: string) {
function showDialog(dialogTitle: string | undefined, dialogMessage: string | undefined) {
prompt.showDialog({
title: dialogTitle,
message: dialogMessage,
@@ -40,7 +42,7 @@ function showDialog(dialogTitle: string, dialogMessage: string) {
color: '#000000'
},
],
success: function (data) {
success: (data) => {
log.debug("handling callback, data:%{public}s", data);
}
});
@@ -3,15 +3,15 @@ import { DialogMsgEntity } from '../../entity/WorkerMsgEntity';
export class Dialog {
static MODULE_NAME: string = 'Dialog';
static workerPort;
static workerPort: ThreadWorkerGlobalScope;
static title = "";
static init(workerPort: ThreadWorkerGlobalScope): void {
Dialog.workerPort = workerPort;
}
static setTitle(title:string){
this.title = title;
static setTitle(title:string) {
Dialog.title = title;
}
static showDialog(message: string, title?: string): void {
@@ -61,94 +61,109 @@ export class VideoPlayer{
static createVideoPlayer(viewTag: number) : void {
let newVideoPlayerInfo = new VideoPlayerInfo(0, 0, 0, 0, viewTag);
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_ARRAY).push(newVideoPlayerInfo);
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP).set(viewTag, newVideoPlayerInfo);
let arr = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_ARRAY) as VideoPlayerInfo[];
arr.push(newVideoPlayerInfo);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP) as Map<number, VideoPlayerInfo>;
map.set(viewTag, newVideoPlayerInfo);
}
static removeVideoPlayer(viewTag: number) : void {
let removeIndex = -1;
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_ARRAY).forEach((item:VideoPlayerInfo,index:number) => {
let arr = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_ARRAY) as VideoPlayerInfo[];
arr.forEach((item:VideoPlayerInfo,index:number) => {
if (item.viewTag == viewTag) {
removeIndex = index;
}
});
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP).get(viewTag).controller.requestFullscreen(false); //4.x已修复
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_ARRAY).splice(removeIndex, 1);
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP).delete(viewTag);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP) as Map<number, VideoPlayerInfo>;
map.get(viewTag)!.controller.requestFullscreen(false); //4.x已修复
arr.splice(removeIndex, 1);
map.delete(viewTag);
}
static setURL(viewTag: number, url: string, isUrl: number) : void {
let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP).get(viewTag);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP) as Map<number, VideoPlayerInfo>;
let videoPlayInfo = map.get(viewTag);
if(isUrl == 0) {
videoPlayInfo.isUrl = false;
videoPlayInfo.rawfile = $rawfile(url) ;//$rawfile("video1.mp4");
videoPlayInfo!.isUrl = false;
videoPlayInfo!.rawfile = $rawfile(url) ;//$rawfile("video1.mp4");
} else {
videoPlayInfo.isUrl = true;
videoPlayInfo.url = url;
videoPlayInfo!.isUrl = true;
videoPlayInfo!.url = url;
}
}
static play(viewTag: number) : void {
let videoPlayInfo :VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP).get(viewTag);
videoPlayInfo.controller.start();
videoPlayInfo.isPlay = true;
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP) as Map<number, VideoPlayerInfo>;
let videoPlayInfo = map.get(viewTag);
videoPlayInfo!.controller.start();
videoPlayInfo!.isPlay = true;
}
static pause(viewTag: number) : void {
let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP).get(viewTag);
videoPlayInfo.controller.pause();
videoPlayInfo.isPlay = false;
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP) as Map<number, VideoPlayerInfo>;
let videoPlayInfo = map.get(viewTag);
videoPlayInfo!.controller.pause();
videoPlayInfo!.isPlay = false;
}
static stop(viewTag: number) : void {
let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP).get(viewTag);
videoPlayInfo.controller.stop();
videoPlayInfo.isPlay = false;
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP) as Map<number, VideoPlayerInfo>;
let videoPlayInfo = map.get(viewTag);
videoPlayInfo!.controller.stop();
videoPlayInfo!.isPlay = false;
}
static setLooping(viewTag: number, isLoop: boolean) :void {
let videoPlayInfo: VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP).get(viewTag);
videoPlayInfo.isLoop = isLoop;
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP) as Map<number, VideoPlayerInfo>;
let videoPlayInfo = map.get(viewTag);
videoPlayInfo!.isLoop = isLoop;
}
static setAutoplay(viewTag: number, autoPlay: boolean) :void {
let videoPlayInfo: VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP).get(viewTag);
videoPlayInfo.autoPlay = autoPlay;
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP) as Map<number, VideoPlayerInfo>;
let videoPlayInfo = map.get(viewTag);
videoPlayInfo!.autoPlay = autoPlay;
}
static setX(viewTag: number, val: number) :void {
let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP).get(viewTag);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP) as Map<number, VideoPlayerInfo>;
let videoPlayInfo = map.get(viewTag);
try {
videoPlayInfo.x = val;
videoPlayInfo!.x = val;
} catch (error) {
let e: BusinessError = error as BusinessError;
log.error('videoPlayerInfo ErrorCode: %{public}d, Message: %{public}s', e.code, e.message);
}
}
static setY(viewTag: number, val: number) :void {
let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP).get(viewTag);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP) as Map<number, VideoPlayerInfo>;
let videoPlayInfo = map.get(viewTag);
try {
videoPlayInfo.y = val;
videoPlayInfo!.y = val;
} catch (error) {
let e: BusinessError = error as BusinessError;
log.error('videoPlayerInfo ErrorCode: %{public}d, Message: %{public}s', e.code, e.message);
}
}
static setWidth(viewTag: number, val: number) : void {
let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP).get(viewTag);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP) as Map<number, VideoPlayerInfo>;
let videoPlayInfo = map.get(viewTag);
try {
videoPlayInfo.w = val;
videoPlayInfo!.w = val;
} catch (error) {
let e: BusinessError = error as BusinessError;
log.error('videoPlayerInfo ErrorCode: %{public}d, Message: %{public}s', e.code, e.message);
}
}
static setHeight(viewTag: number, val: number) : void {
let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP).get(viewTag);
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP) as Map<number, VideoPlayerInfo>;
let videoPlayInfo = map.get(viewTag);
try {
videoPlayInfo.h = val;
videoPlayInfo!.h = val;
} catch (error) {
let e: BusinessError = error as BusinessError;
log.error('videoPlayerInfo ErrorCode: %{public}d, Message: %{public}s', e.code, e.message);
}
}
static setCurrentTime(viewTag: number, val: number) : void {
let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP).get(viewTag);
videoPlayInfo.controller.setCurrentTime(val)
let map = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_VIDEO_PLAYER_INDEX_MAP) as Map<number, VideoPlayerInfo>;
let videoPlayInfo = map.get(viewTag);
videoPlayInfo!.controller.setCurrentTime(val)
}
static getVolume(viewTag: number) : number {
let audioManager = audio.getAudioManager();
@@ -1,11 +1,12 @@
import { ViewRect, WebViewMsgEntity } from '../../entity/WorkerMsgEntity';
import type { ThreadWorkerGlobalScope } from '@ohos.worker';
export class WebView {
static MODULE_NAME: string = 'WebView';
private static workerPort;
private static workerPort: ThreadWorkerGlobalScope;
static init(workerPort): void {
static init(workerPort: ThreadWorkerGlobalScope): void {
WebView.workerPort = workerPort;
}
@@ -16,7 +16,7 @@ export class WebViewInfo {
public w: number = 0;
public h: number = 0;
// url
public url: string = '';
public url?: string = '';
public isUrl: boolean = true;
public viewTag: number = 0
public zoomAccess: boolean = true
@@ -46,40 +46,45 @@ export function handleWebViewMsg(eventData: WebViewMsgEntity) {
switch (eventData.function) {
case "createWebview": {
let view = new WebViewInfo(0, 0, 0, 0, 0);
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY).push(view);
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY)[0].url = eventData.url;
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY)[0].isUrl = true;
let arr = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY) as WebViewInfo[];
arr.push(view);
arr[0].url = eventData.url;
arr[0].isUrl = true;
waitUtilControllerAttached().then(() => {
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY)[0].controller.loadUrl(eventData.url);
arr[0].controller.loadUrl(eventData.url);
})
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY)[0].x = px2vp(eventData.viewRect.x);
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY)[0].y = px2vp(eventData.viewRect.y);
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY)[0].w = px2vp(eventData.viewRect.w);
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY)[0].h = px2vp(eventData.viewRect.h);
arr[0].x = px2vp(eventData.viewRect!.x);
arr[0].y = px2vp(eventData.viewRect!.y);
arr[0].w = px2vp(eventData.viewRect!.w);
arr[0].h = px2vp(eventData.viewRect!.h);
break;
}
case "removeWebView": {
if (GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY).length > 0) {
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY).splice(0, 1);
let arr = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY) as WebViewInfo[];
if (arr.length > 0) {
arr.splice(0, 1);
}
break;
}
case "showWebView": {
if (GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY).length > 0) {
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY)[0].visible = true;
let arr = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY) as WebViewInfo[];
if (arr.length > 0) {
arr[0].visible = true;
}
break;
}
case "hideWebView": {
if (GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY).length > 0) {
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY)[0].visible = false;
let arr = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY) as WebViewInfo[];
if (arr.length > 0) {
arr[0].visible = false;
}
break;
}
case "callWebviewJS": {
if (GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY).length > 0) {
GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY)[0]
let arr = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_WEB_VIEW_ARRAY) as WebViewInfo[];
if (arr.length > 0) {
arr[0]
.controller
.runJavaScript(eventData.js, (error: BusinessError, result: string) => {
if (error) {
@@ -0,0 +1,21 @@
interface ResultMsg {
errCode: number;
errMsg: string;
data?: Object;
}
export class Result {
public static success(data?: Object): ResultMsg {
return {
"errCode": 0,
"errMsg": "",
"data": data,
};
}
public static error(errCode: number, errMsg: string): ResultMsg {
return {
"errCode": errCode,
"errMsg": errMsg,
};
}
};
@@ -1,17 +0,0 @@
export class Result {
public static success(data) {
return {
"errCode": 0,
"errMsg": "",
"data": data,
};
}
public static error(errCode, errMsg) {
return {
"errCode": errCode,
"errMsg": errMsg,
};
}
}
;
@@ -1,5 +1,5 @@
export class TextInputDialogEntity {
message: string;
message?: string;
constructor(msg: string) {
this.message = msg;
@@ -38,9 +38,9 @@ export class BaseWorkerMsgEntity {
}
export class DialogMsgEntity extends BaseWorkerMsgEntity {
title: string;
title?: string;
message: string;
message?: string;
type?:number;
@@ -50,26 +50,26 @@ export class DialogMsgEntity extends BaseWorkerMsgEntity {
}
export class WebViewMsgEntity extends BaseWorkerMsgEntity {
viewTag: number
viewTag?: number;
data: string
mimeType: string
encoding: string
baseURL: string
data?: string;
mimeType?: string;
encoding?: string;
baseURL?: string;
url: string
url?: string;
filePath: string
filePath?: string;
viewRect: ViewRect
viewRect?: ViewRect;
visible: boolean
visible?: boolean;
opacity: number
opacity?: number;
js: string
js?: string;
scalesPageToFit: boolean
scalesPageToFit?: boolean;
constructor(module: string, func: string) {
super(module, func);
@@ -77,7 +77,7 @@ export class WebViewMsgEntity extends BaseWorkerMsgEntity {
}
export class JumpMsgEntity extends BaseWorkerMsgEntity {
url: string;
url?: string;
constructor(module: string, func: string) {
super(module, func);
@@ -1,5 +1,4 @@
import { Dialog } from '../components/dialog/DialogWorker'
import { JumpManager } from '../system/appJump/JumpManager'
import { DeviceUtils } from '../system/device/DeviceUtils'
import { NetworkUtils } from '../system/device/NetworkUtils'
import ApplicationManager from '../system/application/ApplicationManager'
@@ -3,6 +3,8 @@ import { GlobalContext, GlobalContextConstants } from '../../common/GlobalContex
import { Result } from "../../entity/Result"
import type { JumpMsgEntity } from '../../entity/WorkerMsgEntity';
import { Logger } from '../../utils/Logger'
import { Want } from '@kit.AbilityKit';
import { BusinessError } from '@ohos.base';
let log: Logger = new Logger(0x0001, "JumpManagerMsg");
@@ -16,16 +18,16 @@ export function handleJumpManagerMsg(eventData: JumpMsgEntity): void {
}
}
function openUrl(url: string): void {
let context: common.UIAbilityContext = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_ABILITY_CONTEXT);
let wantInfo = {
function openUrl(url: string | undefined): void {
let context = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_ABILITY_CONTEXT) as common.UIAbilityContext;
let wantInfo: Want = {
'action': 'ohos.want.action.viewData',
'entities': ['entity.system.browsable'],
'uri': url
}
context.startAbility(wantInfo).then(() => {
log.info('%{public}s', JSON.stringify(Result.success({})));
}).catch((err) => {
log.info('%{public}s', JSON.stringify(Result.success()));
}).catch((err: BusinessError) => {
log.error('openUrl : err : %{public}s', JSON.stringify(Result.error(-1, JSON.stringify(err))) ?? '');
});
}
@@ -4,7 +4,9 @@ import deviceInfo from '@ohos.deviceInfo'
import hidebug from '@ohos.hidebug';
import window from '@ohos.window';
import { GlobalContext, GlobalContextConstants } from '../../common/GlobalContext';
import hilog from '@ohos.hilog'
import hilog from '@ohos.hilog';
import type common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';
export class DeviceUtils {
static MODULE_NAME: string = 'DeviceUtils';
@@ -31,8 +33,8 @@ export class DeviceUtils {
static getDeviceInfo(): string {
// TBD 鸿蒙系统字段和安卓系统字段非一一对应关系,可根据应用业务场景做字段选择,
// 字段可参考:https://docs.openharmony.cn/pages/v4.0/zh-cn/application-dev/reference/apis/js-apis-device-info.md/
var displayObj = display.getDefaultDisplaySync();
const deviceInfoJsonStr: { [key: string]: any } = {
let displayObj = display.getDefaultDisplaySync();
return JSON.stringify({
"dpi":displayObj?.densityDPI,
"resolution":displayObj?.width + "*" + displayObj?.height,
"guid":"",
@@ -41,23 +43,20 @@ export class DeviceUtils {
"os":"OpenHarmony",
"osversion":deviceInfo.sdkApiVersion,
"phonemodel":deviceInfo.softwareModel
};
return JSON.stringify(deviceInfoJsonStr);
});
}
// 获取窗口尺寸
static getScreenInch(cb) {
var displayObj = display.getDefaultDisplaySync();
let windowClass = null;
static getScreenInch(cb: Function) {
let displayObj = display.getDefaultDisplaySync();
try {
let context = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_ABILITY_CONTEXT);
window.getLastWindow(context, (err, data) => { //获取窗口实例
let context = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_ABILITY_CONTEXT) as common.UIAbilityContext;
window.getLastWindow(context, (err, windowClass) => { //获取窗口实例
if (err.code) {
hilog.error(0x0001, "DeviceUtils", 'Failed to obtain last window when initScreenInfo. Cause:%{public}s', JSON.stringify(err));
cb(0);
return;
}
windowClass = data;
let windowProperties: window.WindowProperties = windowClass.getWindowProperties();
let rect: window.Rect = windowProperties.windowRect;
let nWidth = rect.width;
@@ -88,20 +87,18 @@ export class DeviceUtils {
// 设置屏幕常亮
static setKeepScreenOn(value: boolean) {
let windowClass = null;
try {
let context = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_ABILITY_CONTEXT);
window.getLastWindow(context, (err, data) => { //获取窗口实例
let context = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_ABILITY_CONTEXT) as common.UIAbilityContext;
window.getLastWindow(context, (err, windowClass) => { //获取窗口实例
if (err.code) {
hilog.error(0x0001, "DeviceUtils", 'Failed to obtain last window when setKeepScreenOn. Cause:%{public}s', JSON.stringify(err));
return;
}
windowClass = data;
// Sets whether the screen is always on.
let keepScreenOnPromise = windowClass.setWindowKeepScreenOn(value);
Promise.all([keepScreenOnPromise]).then(() => {
hilog.info(0x0001, "DeviceUtils", 'Succeeded in setKeepScreenOn, value:%{public}s', value);
}).catch((err) => {
}).catch((err: BusinessError) => {
hilog.error(0x0001, "DeviceUtils", 'Failed to setKeepScreenOn, cause:%{public}s', JSON.stringify(err));
});
});
@@ -111,15 +108,13 @@ export class DeviceUtils {
}
static setPreferredOrientation(orientatio: number) {
let windowClass = null;
try {
let context = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_ABILITY_CONTEXT);
window.getLastWindow(context, (err, data) => { //获取窗口实例
let context = GlobalContext.loadGlobalThis(GlobalContextConstants.LAYA_ABILITY_CONTEXT) as common.UIAbilityContext;
window.getLastWindow(context, (err, windowClass) => { //获取窗口实例
if (err.code) {
hilog.error(0x0001, "DeviceUtils", 'Failed to obtain last window when setPreferredOrientation. Cause:%{public}s', JSON.stringify(err));
return;
}
windowClass = data;
windowClass.setPreferredOrientation(orientatio, (err) => {
if (err.code) {
hilog.error(0x0001, "DeviceUtils", 'Failed to set window orientation. Cause: ' + JSON.stringify(err));
@@ -1,34 +0,0 @@
import laya from "liblaya.so";
import { ContextType } from "../../common/Constants"
import sensor from '@ohos.sensor';
import display from '@ohos.display';
import { Result } from "../../entity/Result"
import { Logger } from '../../utils/Logger'
let log: Logger = new Logger(0x0001, "AccelerometerUtils");
export default class Accelerometer {
private static instance = new Accelerometer();
static getInstance(): Accelerometer {
return Accelerometer.instance;
}
static enable(): void {
try {
sensor.on(sensor.SensorId.ACCELEROMETER, (data) => {
laya.ConchNAPI_handleDeviceMotionEvent(0, 0, 0, data.x, data.y, data.z, 0, 0, 0, 1);
});
} catch (err) {
log.error('Accelerometer init fail, err: %{public}s', JSON.stringify(Result.error(-1, JSON.stringify(err))) ?? '');
}
}
static disable(): void {
try {
sensor.off(sensor.SensorId.ACCELEROMETER);
} catch (err) {
log.error('Accelerometer off fail, err: %{public}s', JSON.stringify(Result.error(-1, JSON.stringify(err))) ?? '');
}
}
}
@@ -1,32 +0,0 @@
import laya from "liblaya.so";
import sensor from '@ohos.sensor';
import { Result } from "../../entity/Result"
import { Logger } from '../../utils/Logger'
let log: Logger = new Logger(0x0001, "OrientationUtils");
export default class Orientation {
private static instance = new Orientation();
static getInstance(): Orientation {
return Orientation.instance;
}
static enable(): void {
try {
sensor.on(sensor.SensorId.ORIENTATION, (data) => {
laya.ConchNAPI_handleDeviceOrientationEvent(data.alpha, data.beta, data.gamma);
});
} catch (err) {
log.error('Orientation init fail, err: %{public}s', JSON.stringify(Result.error(-1, JSON.stringify(err))) ?? '');
}
}
static disable(): void {
try {
sensor.off(sensor.SensorId.ORIENTATION);
} catch (err) {
log.error('Orientation off fail, err: %{public}s', JSON.stringify(Result.error(-1, JSON.stringify(err))) ?? '');
}
}
}
@@ -2,11 +2,11 @@ import media from '@ohos.multimedia.media';
import fs from '@ohos.file.fs';
import laya from "liblaya.so";
import audio from '@ohos.multimedia.audio';
import { BusinessError } from '@ohos.base';
export default class SoundUtils {
private static avPlayer;
private static mLeftVolume = 0.5;
private static mRightVolume = 0.5;
private static avPlayer: media.AVPlayer;
private static mVolume = 0.5;
private static mPaused = false;
static async playBackgroundMusic(p_sFilePath: string, p_nTimes: number, nCurrentTime: number) {
@@ -33,7 +33,7 @@ export default class SoundUtils {
avPlayer.audioRendererInfo = audioRendererInfo;
avPlayer.prepare().then(() => {
console.info('AVPlayer prepare succeeded.');
}, (err) => {
}, (err: BusinessError) => {
console.error(`Invoke prepare failed, code is ${err.code}, message is ${err.message}`);
});
break;
@@ -41,7 +41,7 @@ export default class SoundUtils {
console.info('AVPlayer state prepared called.');
let bLoop = (p_nTimes == -1);
avPlayer.loop = bLoop;
avPlayer.setVolume(SoundUtils.mLeftVolume, SoundUtils.mRightVolume);
avPlayer.setVolume(SoundUtils.mVolume);
avPlayer.play(); // 调用播放接口开始播放
break;
case 'playing': // play成功调用后触发该状态机上报
@@ -114,9 +114,9 @@ export default class SoundUtils {
if (p_fVolume > 1.0) {
p_fVolume = 1.0;
}
SoundUtils.mLeftVolume = SoundUtils.mRightVolume = p_fVolume;
SoundUtils.mVolume = p_fVolume;
if (SoundUtils.avPlayer != null) {
SoundUtils.avPlayer.setVolume(SoundUtils.mLeftVolume, SoundUtils.mRightVolume);
SoundUtils.avPlayer.setVolume(SoundUtils.mVolume);
}
}
@@ -133,7 +133,7 @@ export default class SoundUtils {
return 0.0;
}
static getDuration() {
static getDuration(): number {
if (SoundUtils.avPlayer != null) {
return SoundUtils.avPlayer.duration;
}
@@ -17,23 +17,23 @@ export class Logger {
this.prefix = prefix
}
debug(format: string, ...args: any[]) {
debug(format: string, ...args: Object[]) {
this.log(LogLevel.DEBUG, format, ...args);
}
info(format: string, ...args: any[]) {
info(format: string, ...args: Object[]) {
this.log(LogLevel.INFO, format, ...args);
}
warn(format: string, ...args: any[]) {
warn(format: string, ...args: Object[]) {
this.log(LogLevel.WARN, format, ...args);
}
error(format: string, ...args: any[]) {
error(format: string, ...args: Object[]) {
this.log(LogLevel.ERROR, format, ...args);
}
log(logLevel: LogLevel, format: string, ...args: any[]) {
log(logLevel: LogLevel, format: string, ...args: Object[]) {
switch (logLevel) {
case LogLevel.DEBUG:
if (this.printLevel > LogLevel.DEBUG) {