diff --git a/attachment/repos/dart.patch4 b/attachment/repos/dart.patch4 new file mode 100644 index 0000000000000000000000000000000000000000..382f7c882885be5556fe92f204e368be058862ec --- /dev/null +++ b/attachment/repos/dart.patch4 @@ -0,0 +1,68 @@ +diff --git a/runtime/vm/flag_list.h b/runtime/vm/flag_list.h +index 2f448049ef0..01eef6deb62 100644 +--- a/runtime/vm/flag_list.h ++++ b/runtime/vm/flag_list.h +@@ -156,7 +156,7 @@ constexpr bool FLAG_support_il_printer = false; + "Maximum number of polymorphic checks in equality operator,") \ + P(new_gen_semi_max_size, int, kDefaultNewGenSemiMaxSize, \ + "Max size of new gen semi space in MB") \ +- P(new_gen_semi_initial_size, int, (kWordSize <= 4) ? 1 : 2, \ ++ P(new_gen_semi_initial_size, int, (kWordSize <= 4) ? 1 : 32, \ + "Initial size of new gen semi space in MB") \ + P(optimization_counter_threshold, int, kDefaultOptimizationCounterThreshold, \ + "Function's usage-counter value before it is optimized, -1 means never") \ +diff --git a/runtime/vm/globals.h b/runtime/vm/globals.h +index 13db280340a..0e70edeea8f 100644 +--- a/runtime/vm/globals.h ++++ b/runtime/vm/globals.h +@@ -60,7 +60,7 @@ const intptr_t kBytesPerBigIntDigit = 4; + // Set the VM limit below the OS limit to increase the likelihood of failing + // gracefully with a Dart OutOfMemory exception instead of SIGABORT. + const intptr_t kDefaultMaxOldGenHeapSize = (kWordSize <= 4) ? 1536 : 30720; +-const intptr_t kDefaultNewGenSemiMaxSize = (kWordSize <= 4) ? 8 : 16; ++const intptr_t kDefaultNewGenSemiMaxSize = (kWordSize <= 4) ? 8 : 256; + + #define kPosInfinity bit_cast(DART_UINT64_C(0x7ff0000000000000)) + #define kNegInfinity bit_cast(DART_UINT64_C(0xfff0000000000000)) +diff --git a/runtime/vm/heap/page.h b/runtime/vm/heap/page.h +index 13e31d6a68a..d981485efe3 100644 +--- a/runtime/vm/heap/page.h ++++ b/runtime/vm/heap/page.h +@@ -24,7 +24,7 @@ class Thread; + // can be computed by masking the object with kPageMask. This does not apply to + // image pages, whose address is choosen by the system loader rather than the + // Dart VM. +-static constexpr intptr_t kPageSize = 512 * KB; ++static constexpr intptr_t kPageSize = 1024 * KB; + static constexpr intptr_t kPageSizeInWords = kPageSize / kWordSize; + static constexpr intptr_t kPageMask = ~(kPageSize - 1); + +diff --git a/runtime/vm/heap/scavenger.h b/runtime/vm/heap/scavenger.h +index 9f04c8e21a4..3814ccb1e19 100644 +--- a/runtime/vm/heap/scavenger.h ++++ b/runtime/vm/heap/scavenger.h +@@ -118,7 +118,7 @@ class ScavengeStats { + + class Scavenger { + private: +- static const intptr_t kTLABSize = 512 * KB; ++ static const intptr_t kTLABSize = 1024 * KB; + + public: + Scavenger(Heap* heap, intptr_t max_semi_capacity_in_words); +diff --git a/runtime/vm/flag_list.h b/runtime/vm/flag_list.h +index 01eef6deb62..d7b8ddb8230 100644 +--- a/runtime/vm/flag_list.h ++++ b/runtime/vm/flag_list.h +@@ -130,7 +130,7 @@ constexpr bool FLAG_support_il_printer = false; + P(huge_method_cutoff_in_ast_nodes, int, 10000, \ + "Huge method cutoff in AST nodes: Disables optimizations for huge " \ + "methods.") \ +- P(idle_timeout_micros, int, 1000 * kMicrosecondsPerMillisecond, \ ++ P(idle_timeout_micros, int, 61 * kMicrosecondsPerSecond, \ + "Consider thread pool isolates for idle tasks after this long.") \ + P(idle_duration_micros, int, 500 * kMicrosecondsPerMillisecond, \ + "Allow idle tasks to run for this long.") \ +-- +2.39.3 (Apple Git-146) + diff --git a/attachment/repos/skia.patch b/attachment/repos/skia.patch index d993bdffa7bae8ef54f07c45fbb2824284ef191c..5cda561c5ab20196024fec35d2a6ba78b4dc48fe 100644 --- a/attachment/repos/skia.patch +++ b/attachment/repos/skia.patch @@ -3726,3 +3726,17 @@ index 0000000000..ec225a188e + } + ] +} +diff --git a/src/sksl/codegen/SkSLGLSLCodeGenerator.cpp b/src/sksl/codegen/SkSLGLSLCodeGenerator.cpp +index fca2f34ded..65955a7041 100644 +--- a/src/sksl/codegen/SkSLGLSLCodeGenerator.cpp ++++ b/src/sksl/codegen/SkSLGLSLCodeGenerator.cpp +@@ -1687,6 +1687,9 @@ void GLSLCodeGenerator::writeInputVars() { + + bool GLSLCodeGenerator::generateCode() { + this->writeHeader(); ++ // Tell driver this shader generated by skia ++ this->writeLine("// GL_EXTENSION_SKIA_CACHE"); ++ + OutputStream* rawOut = fOut; + StringStream body; + fOut = &body; diff --git a/attachment/scripts/config.json b/attachment/scripts/config.json index 848689d9fa261275f634cc758a5713627d017b85..9092b1a9391fc583a49e8d2837226597c069ae72 100644 --- a/attachment/scripts/config.json +++ b/attachment/scripts/config.json @@ -29,6 +29,12 @@ "type": "patch", "file_path": "flutter/attachment/repos/dart.patch3" }, + { + "name": "dart4", + "target": "third_party/dart", + "type": "patch", + "file_path": "flutter/attachment/repos/dart.patch4" + }, { "name": "skia", "target": "third_party/skia", diff --git a/attachment/scripts/config_pre.json b/attachment/scripts/config_pre.json index 848689d9fa261275f634cc758a5713627d017b85..9092b1a9391fc583a49e8d2837226597c069ae72 100644 --- a/attachment/scripts/config_pre.json +++ b/attachment/scripts/config_pre.json @@ -29,6 +29,12 @@ "type": "patch", "file_path": "flutter/attachment/repos/dart.patch3" }, + { + "name": "dart4", + "target": "third_party/dart", + "type": "patch", + "file_path": "flutter/attachment/repos/dart.patch4" + }, { "name": "skia", "target": "third_party/skia", diff --git a/attachment/scripts/ohos_create_flutter_har.py b/attachment/scripts/ohos_create_flutter_har.py index d33cda8c885bae4320bee71b3f08f0a1d2bfb9c0..bf21568bdfe8b10c5f4c6e61513f67daccb386c3 100644 --- a/attachment/scripts/ohos_create_flutter_har.py +++ b/attachment/scripts/ohos_create_flutter_har.py @@ -16,7 +16,6 @@ """Create a HAR incorporating all the components required to build a Flutter application""" import argparse -import datetime import logging import os import re @@ -69,6 +68,12 @@ HVIGOR_CONFIG = """ """ +def runGitCommand(command): + result = subprocess.run(command, capture_output=True, text=True, shell=True) + if result.returncode != 0: + raise Exception(f"Git command failed: {result.stderr}") + return result.stdout.strip() + # 更新har的配置文件,指定编译使用的api版本 def updateConfig(buildDir, apiInt): apiVersionMap = { @@ -93,6 +98,8 @@ def updateConfig(buildDir, apiInt): # 自动更新flutter.har的版本号,把日期加到末尾。如: 1.0.0-20240731 def updateVersion(buildDir): filePath = os.path.join(buildDir, "flutter", "oh-package.json5") + currentDir = os.path.dirname(__file__) + latestCommit = runGitCommand(f'git -C {currentDir} rev-parse --short HEAD') with open(filePath, "r") as sources: lines = sources.readlines() @@ -106,9 +113,7 @@ def updateVersion(buildDir): if matches and len(matches) > 0: result = ''.join(matches[0]) versionArr = result.split("-") - today = datetime.date.today() - dateStr = today.strftime("%Y%m%d") - list = [versionArr[0], dateStr] + list = [versionArr[0], latestCommit] versionStr = "-".join(list) print(f'versionStr = {versionStr}') sources.write(re.sub(pattern, versionStr, line)) diff --git a/common/graphics/persistent_cache.cc b/common/graphics/persistent_cache.cc index 50d09bb8fcbc6d4c93d654004085d1cd8d1884ea..514451fc56aeff9675503627c14faf65852af29e 100644 --- a/common/graphics/persistent_cache.cc +++ b/common/graphics/persistent_cache.cc @@ -250,7 +250,7 @@ std::vector PersistentCache::LoadSkSLs() const { mapping = asset_manager_->GetAsMapping(kAssetFileName); } if (mapping == nullptr) { - FML_LOG(INFO) << "No sksl asset found."; + FML_LOG(ERROR) << "No sksl asset found."; } else { FML_LOG(INFO) << "Found sksl asset. Loading SkSLs from it..."; rapidjson::Document json_doc; diff --git a/fml/log_level.h b/fml/log_level.h index 79316f86b657a66114aab8ff2a926335912f97f7..65f26f4b76609f1b335048d36244775a37a7e8b4 100644 --- a/fml/log_level.h +++ b/fml/log_level.h @@ -15,7 +15,7 @@ constexpr LogSeverity LOG_WARNING = 1; constexpr LogSeverity LOG_ERROR = 2; constexpr LogSeverity LOG_FATAL = 3; constexpr LogSeverity LOG_NUM_SEVERITIES = 4; -constexpr LogSeverity LOG_DEBUG= 4; +constexpr LogSeverity LOG_DEBUG = 0; // One of the Windows headers defines ERROR to 0. This makes the token // concatenation in FML_LOG(ERROR) to resolve to LOG_0. We define this back to diff --git a/fml/trace_event.h b/fml/trace_event.h index 505ad2e89a155f4f0dd481cfdc2c0b33bf9f769b..ce7bcf359509c91041b99a7225ac9c490356fd0c 100644 --- a/fml/trace_event.h +++ b/fml/trace_event.h @@ -48,7 +48,6 @@ class OHFlutterTrace { public: explicit OHFlutterTrace(const char *fmt, ...) { -//#if !defined(_WIN32) && !defined(_APPLE) char title[1000] = "OHFlutterTrace"; const char *title_ = title; if (fmt != nullptr) { @@ -63,53 +62,30 @@ public: } } OH_HiTrace_StartTrace(title_); -//#endif } ~OHFlutterTrace() { -//#if !defined(_WIN32) && !defined(_APPLE) OH_HiTrace_FinishTrace(); -//#endif } }; #define TRACE_NAME(x, y) x##y - -#define TRACE_DURATION_LINE(l, a, args...) OHFlutterTrace TRACE_NAME(trace, l)(a, args) - -#define TRACE_DURATION(a, args...) TRACE_DURATION_LINE(__LINE__, a, args) - - -#define FML_TRACE_EVENT(a, b, args...) -#define FML_TRACE_COUNTER(a, b, c, arg1, ...) - -#define TRACE_FLOW_BEGIN(category, name, id) OH_HiTrace_StartAsyncTrace(category#name, id) - -#define TRACE_FLOW_STEP(category, name, id) - -#define TRACE_FLOW_END(category, name, id) OH_HiTrace_FinishAsyncTrace(category#name, id) +#define TRACE_DURATION_LINE(line, fmt, args...) OHFlutterTrace TRACE_NAME(__OH_trace_, line)(fmt, args) +#define TRACE_DURATION(fmt, args...) TRACE_DURATION_LINE(__LINE__, fmt, args) #define TRACE_FMT "%s:%s " -#define TRACE_EVENT0(a, b) TRACE_DURATION(TRACE_FMT, a, b) -#define TRACE_EVENT1(a, b, c, d) TRACE_DURATION(TRACE_FMT TRACE_FMT, a, b, c, d) -#define TRACE_EVENT2(a, b, c, d, e, f) TRACE_DURATION(TRACE_FMT TRACE_FMT TRACE_FMT TRACE_FMT, a, b, c, d, e, f) +#define OH_TRACE_DURATION(a, b) TRACE_DURATION(TRACE_FMT, a, b) -#define TRACE_EVENT_ASYNC_BEGIN0(a, b, c) OH_HiTrace_StartAsyncTrace(a#b, c) -#define TRACE_EVENT_ASYNC_END0(a, b, c) OH_HiTrace_FinishAsyncTrace(a#b, c) +#define OH_TRACE_ASYNC_BEGIN(category, name, id) OH_HiTrace_StartAsyncTrace(category#name, id) +#define OH_TRACE_ASYNC_END(category, name, id) OH_HiTrace_FinishAsyncTrace(category#name, id) -#define TRACE_EVENT_ASYNC_BEGIN1(a, b, c, d, e) -#define TRACE_EVENT_ASYNC_END1(a, b, c, d, e) - -#define TRACE_INSTANT(category_literal, name_literal, scope, args...) - -#define TRACE_EVENT_INSTANT0(a, b) TRACE_INSTANT(a, b, TRACE_SCOPE_THREAD) -#define TRACE_EVENT_INSTANT1(a, b, k1, v1) \ - TRACE_INSTANT(a, b, TRACE_SCOPE_THREAD, k1, v1) -#define TRACE_EVENT_INSTANT2(a, b, k1, v1, k2, v2) \ - TRACE_INSTANT(a, b, TRACE_SCOPE_THREAD, k1, v1, k2, v2) +#else -#endif // defined(FML_OS_OHOS) +#define OH_TRACE_DURATION(a, b) +#define OH_TRACE_ASYNC_BEGIN(category, name, id) +#define OH_TRACE_ASYNC_END(category, name, id) +#endif // defined(FML_OS_OHOS) #include #include @@ -121,28 +97,28 @@ public: #include "flutter/fml/time/time_point.h" #include "third_party/dart/runtime/include/dart_tools_api.h" -#if (FLUTTER_RELEASE && !defined(OS_FUCHSIA) && !defined(FML_OS_ANDROID)) +#if (FLUTTER_RELEASE && !defined(OS_FUCHSIA) && !defined(FML_OS_ANDROID) && !defined(FML_OS_OHOS)) #define FLUTTER_TIMELINE_ENABLED 0 #else #define FLUTTER_TIMELINE_ENABLED 1 #endif -#if !defined(OS_FUCHSIA) && !defined(FML_OS_OHOS) +#if !defined(OS_FUCHSIA) #ifndef TRACE_EVENT_HIDE_MACROS #define __FML__TOKEN_CAT__(x, y) x##y #define __FML__TOKEN_CAT__2(x, y) __FML__TOKEN_CAT__(x, y) -#define __FML__AUTO_TRACE_END(name) \ - ::fml::tracing::ScopedInstantEnd __FML__TOKEN_CAT__2(__trace_end_, \ - __LINE__)(name); +#define __FML__AUTO_TRACE_END(name) \ + ::fml::tracing::ScopedInstantEnd __FML__TOKEN_CAT__2(__trace_end_, \ + __LINE__)(name) // This macro has the FML_ prefix so that it does not collide with the macros // from lib/trace/event.h on Fuchsia. // // TODO(chinmaygarde): All macros here should have the FML prefix. -#define FML_TRACE_COUNTER(category_group, name, counter_id, arg1, ...) \ - ::fml::tracing::TraceCounter((category_group), (name), (counter_id), (arg1), \ - __VA_ARGS__); +#define FML_TRACE_COUNTER(category_group, name, counter_id, arg1, ...) \ + ::fml::tracing::TraceCounter((category_group), (name), (counter_id), (arg1), \ + __VA_ARGS__) // Avoid using the same `name` and `argX_name` for nested traces, which can // lead to double free errors. E.g. the following code should be avoided: @@ -157,58 +133,71 @@ public: // ``` // // Instead, either use different `name` or `arg1` parameter names. -#define FML_TRACE_EVENT(category_group, name, ...) \ - ::fml::tracing::TraceEvent((category_group), (name), __VA_ARGS__); \ - __FML__AUTO_TRACE_END(name) - -#define TRACE_EVENT0(category_group, name) \ - ::fml::tracing::TraceEvent0(category_group, name); \ - __FML__AUTO_TRACE_END(name) - -#define TRACE_EVENT1(category_group, name, arg1_name, arg1_val) \ - ::fml::tracing::TraceEvent1(category_group, name, arg1_name, arg1_val); \ - __FML__AUTO_TRACE_END(name) - -#define TRACE_EVENT2(category_group, name, arg1_name, arg1_val, arg2_name, \ - arg2_val) \ - ::fml::tracing::TraceEvent2(category_group, name, arg1_name, arg1_val, \ - arg2_name, arg2_val); \ - __FML__AUTO_TRACE_END(name) - -#define TRACE_EVENT_ASYNC_BEGIN0(category_group, name, id) \ - ::fml::tracing::TraceEventAsyncBegin0(category_group, name, id); - -#define TRACE_EVENT_ASYNC_END0(category_group, name, id) \ - ::fml::tracing::TraceEventAsyncEnd0(category_group, name, id); - -#define TRACE_EVENT_ASYNC_BEGIN1(category_group, name, id, arg1_name, \ - arg1_val) \ - ::fml::tracing::TraceEventAsyncBegin1(category_group, name, id, arg1_name, \ - arg1_val); - -#define TRACE_EVENT_ASYNC_END1(category_group, name, id, arg1_name, arg1_val) \ - ::fml::tracing::TraceEventAsyncEnd1(category_group, name, id, arg1_name, \ - arg1_val); - -#define TRACE_EVENT_INSTANT0(category_group, name) \ - ::fml::tracing::TraceEventInstant0(category_group, name); - -#define TRACE_EVENT_INSTANT1(category_group, name, arg1_name, arg1_val) \ - ::fml::tracing::TraceEventInstant1(category_group, name, arg1_name, arg1_val); - -#define TRACE_EVENT_INSTANT2(category_group, name, arg1_name, arg1_val, \ - arg2_name, arg2_val) \ - ::fml::tracing::TraceEventInstant2(category_group, name, arg1_name, \ - arg1_val, arg2_name, arg2_val); - -#define TRACE_FLOW_BEGIN(category, name, id) \ - ::fml::tracing::TraceEventFlowBegin0(category, name, id); - -#define TRACE_FLOW_STEP(category, name, id) \ - ::fml::tracing::TraceEventFlowStep0(category, name, id); - -#define TRACE_FLOW_END(category, name, id) \ - ::fml::tracing::TraceEventFlowEnd0(category, name, id); +#define FML_TRACE_EVENT(category_group, name, ...) \ + ::fml::tracing::TraceEvent((category_group), (name), __VA_ARGS__); \ + __FML__AUTO_TRACE_END(name); \ + OH_TRACE_DURATION((category_group), (name)) + +#define TRACE_EVENT0(category_group, name) \ + ::fml::tracing::TraceEvent0(category_group, name); \ + __FML__AUTO_TRACE_END(name); \ + OH_TRACE_DURATION((category_group), (name)) + +#define TRACE_EVENT1(category_group, name, arg1_name, arg1_val) \ + ::fml::tracing::TraceEvent1(category_group, name, arg1_name, arg1_val); \ + __FML__AUTO_TRACE_END(name); \ + OH_TRACE_DURATION((category_group), (name)) + +#define TRACE_EVENT2(category_group, name, arg1_name, arg1_val, arg2_name, \ + arg2_val) \ + ::fml::tracing::TraceEvent2(category_group, name, arg1_name, arg1_val, \ + arg2_name, arg2_val); \ + __FML__AUTO_TRACE_END(name); \ + OH_TRACE_DURATION((category_group), (name)) + +#define TRACE_EVENT_ASYNC_BEGIN0(category_group, name, id) \ + ::fml::tracing::TraceEventAsyncBegin0(category_group, name, id); \ + OH_TRACE_ASYNC_BEGIN(category_group, name, (id)) + +#define TRACE_EVENT_ASYNC_END0(category_group, name, id) \ + ::fml::tracing::TraceEventAsyncEnd0(category_group, name, id); \ + OH_TRACE_ASYNC_END(category_group, name, (id)) + +#define TRACE_EVENT_ASYNC_BEGIN1(category_group, name, id, arg1_name, \ + arg1_val) \ + ::fml::tracing::TraceEventAsyncBegin1(category_group, name, id, arg1_name, \ + arg1_val); \ + OH_TRACE_ASYNC_BEGIN(category_group, name, (id)) + +#define TRACE_EVENT_ASYNC_END1(category_group, name, id, arg1_name, arg1_val) \ + ::fml::tracing::TraceEventAsyncEnd1(category_group, name, id, arg1_name, \ + arg1_val); \ + OH_TRACE_ASYNC_END(category_group, name, (id)) + +#define TRACE_EVENT_INSTANT0(category_group, name) \ + ::fml::tracing::TraceEventInstant0(category_group, name); \ + OH_TRACE_DURATION((category_group), (name)) + +#define TRACE_EVENT_INSTANT1(category_group, name, arg1_name, arg1_val) \ + ::fml::tracing::TraceEventInstant1(category_group, name, arg1_name, arg1_val); \ + OH_TRACE_DURATION((category_group), (name)) + +#define TRACE_EVENT_INSTANT2(category_group, name, arg1_name, arg1_val, \ + arg2_name, arg2_val) \ + ::fml::tracing::TraceEventInstant2(category_group, name, arg1_name, \ + arg1_val, arg2_name, arg2_val); \ + OH_TRACE_DURATION((category_group), (name)) + +#define TRACE_FLOW_BEGIN(category, name, id) \ + ::fml::tracing::TraceEventFlowBegin0(category, name, id); \ + OH_TRACE_ASYNC_BEGIN(category, name, (id)) + +#define TRACE_FLOW_STEP(category, name, id) \ + ::fml::tracing::TraceEventFlowStep0(category, name, id) + +#define TRACE_FLOW_END(category, name, id) \ + ::fml::tracing::TraceEventFlowEnd0(category, name, id); \ + OH_TRACE_ASYNC_END(category, name, (id)) #endif // TRACE_EVENT_HIDE_MACROS #endif // !defined(OS_FUCHSIA) diff --git a/runtime/dart_vm_initializer.cc b/runtime/dart_vm_initializer.cc index 521b26d04eb8efcf4f3a48df10d88e734c8d20b4..ce0f67c591d45c8b77382cec69e3929264a5885f 100644 --- a/runtime/dart_vm_initializer.cc +++ b/runtime/dart_vm_initializer.cc @@ -38,8 +38,8 @@ void LogUnhandledException(Dart_Handle exception_handle, // Either the exception handler was not set or it could not handle the // error, just log the exception. - FML_LOG(ERROR) << "Unhandled Exception: " << error << std::endl - << stack_trace; + // FML_LOG(ERROR) << "Unhandled Exception: " << error << std::endl + // << stack_trace; } void ReportUnhandledException(Dart_Handle exception_handle, diff --git a/shell/common/shell.cc b/shell/common/shell.cc index b0bf51ae5d5cc87e53aeb2f9544b01fc6a8e5bd0..bdaf8c234d889328cd00e64a223024d12589585d 100644 --- a/shell/common/shell.cc +++ b/shell/common/shell.cc @@ -77,12 +77,12 @@ std::unique_ptr CreateEngine( // that cause shell initialization failures will still lead to some of their // settings being applied. void PerformInitializationTasks(Settings& settings) { -/* { + { fml::LogSettings log_settings; log_settings.min_log_level = - settings.verbose_logging ? fml::LOG_INFO : fml::LOG_ERROR; + settings.verbose_logging ? fml::LOG_INFO : fml::LOG_WARNING; fml::SetLogSettings(log_settings); - } */ + } static std::once_flag gShellSettingsInitialization = {}; std::call_once(gShellSettingsInitialization, [&settings] { tonic::SetLogHandler( diff --git a/shell/platform/ohos/BUILD.gn b/shell/platform/ohos/BUILD.gn index cc00ad30fb137ac38c212d04b7a16fc4fa0238c7..689f5015c2a163805cc04cd776451815973c7ac3 100644 --- a/shell/platform/ohos/BUILD.gn +++ b/shell/platform/ohos/BUILD.gn @@ -83,6 +83,7 @@ source_set("flutter_ohos_sources") { "ohos_environment_gl.h", "ohos_surface_gl_skia.h", "types.h", + "ohos_logging.h", ] #configs += [ "//flutter/shell/platform/ohos/config:gtk" ] @@ -146,8 +147,6 @@ source_set("flutter_ohos_sources") { #"//flutter/vulkan", "//third_party/skia", "//flutter/shell/gpu:gpu_surface_gl", - - ] } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ets index f88f0688f8493af61fe5a3e16b141212bab2237e..142a41da70a76ff0041b3fe90af893569c2331fe 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ets @@ -123,4 +123,6 @@ export const nativeUnregisterTexture: (nativeShellHolderId: number, textureId: n export const nativeRegisterPixelMap: (nativeShellHolderId: number, textureId: number, pixelMap: PixelMap) => void; +export const nativeSetTextureBackGroundPixelMap: (nativeShellHolderId: number, textureId: number, pixelMap: PixelMap) => void; + export const nativeRegisterTexture: (nativeShellHolderId: number, textureId: number) => number; diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineConnectionRegistry.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineConnectionRegistry.ets index b864a5b3fa64102f84526247b05076e2640c8312..bdcddb159e110ea3daace7a4983306835b333a46 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineConnectionRegistry.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineConnectionRegistry.ets @@ -73,7 +73,7 @@ export default class FlutterEngineConnectionRegistry implements PluginRegistry, return; } - Log.w(TAG, "Adding plugin: " + plugin); + Log.w(TAG, "Adding plugin: " + plugin.getUniqueClassName()); // Add the plugin to our generic set of plugins and notify the plugin // that is has been attached to an engine. this.plugins.set(plugin.getUniqueClassName(), plugin); diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterNapi.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterNapi.ets index 7aad81c196de16ca4681e5c1dc7686a659badec5..6fcf4a574fde2c3b46e070c6159b36ec3b14597b 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterNapi.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterNapi.ets @@ -72,8 +72,8 @@ export default class FlutterNapi { Log.e(TAG, "the engine has init"); return; } - Log.i(TAG, "HAR_VERSION=" + BuildProfile.HAR_VERSION); - Log.w(TAG, JSON.stringify({ + Log.w(TAG, "HAR_VERSION=" + BuildProfile.HAR_VERSION); + Log.d(TAG, JSON.stringify({ "name": "init, initTimeMillis=" + initTimeMillis, "bundlePath": bundlePath, "appStoragePath": appStoragePath, @@ -83,7 +83,7 @@ export default class FlutterNapi { let code: number | null = flutter.nativeInit(context, args, bundlePath, appStoragePath, engineCachesPath, initTimeMillis, deviceInfo.productModel); FlutterNapi.hasInit = code == 0; - Log.i(TAG, "init code=" + code + ", FlutterNapi.hasInit" + FlutterNapi.hasInit); + Log.d(TAG, "init code=" + code + ", FlutterNapi.hasInit" + FlutterNapi.hasInit); } static prefetchDefaultFontManager(): void { @@ -96,7 +96,7 @@ export default class FlutterNapi { return; } this.nativeShellHolderId = flutter.nativeAttach(this); - Log.w(TAG, "nativeShellHolderId=" + this.nativeShellHolderId); + Log.d(TAG, "nativeShellHolderId=" + this.nativeShellHolderId); } runBundleAndSnapshotFromLibrary( @@ -109,7 +109,11 @@ export default class FlutterNapi { Log.e(TAG, "runBundleAndSnapshotFromLibrary fail, FlutterNapi.hasInit=" + FlutterNapi.hasInit); return; } - Log.w(TAG, "init: bundlePath=" + bundlePath + " entrypointFunctionName=" + entrypointFunctionName + " pathToEntrypointFunction=" + pathToEntrypointFunction + " entrypointArgs=" + JSON.stringify(entrypointArgs)) + Log.d(TAG, "init: bundlePath=" + bundlePath + " entrypointFunctionName=" + entrypointFunctionName + " pathToEntrypointFunction=" + pathToEntrypointFunction + " entrypointArgs=" + JSON.stringify(entrypointArgs)) + if (!this.isAttached()) { + Log.e(TAG, "runBundleAndSnapshotFromLibrary this.nativeShellHolderId:" + this.nativeShellHolderId) + return; + } flutter.nativeRunBundleAndSnapshotFromLibrary(this.nativeShellHolderId!, bundlePath, entrypointFunctionName, pathToEntrypointFunction, assetManager, entrypointArgs); }; @@ -129,13 +133,6 @@ export default class FlutterNapi { this.platformMessageHandler = platformMessageHandler; } - private ensureAttachedToNative(): void { - if (this.nativeShellHolderId == null) { - throw new Error( - "Cannot execute operation because FlutterNapi is not attached to native."); - } - } - private nativeNotifyLowMemoryWarning(nativeShellHolderId: number): void { } @@ -146,7 +143,10 @@ export default class FlutterNapi { notifyLowMemoryWarning(): void { this.ensureRunningOnMainThread(); - this.ensureAttachedToNative(); + if (!this.isAttached()) { + Log.e(TAG, "notifyLowMemoryWarning this.nativeShellHolderId:" + this.nativeShellHolderId) + return; + } this.nativeNotifyLowMemoryWarning(this.nativeShellHolderId!); } @@ -257,7 +257,7 @@ export default class FlutterNapi { //Called by native to respond to a platform message that we sent. handlePlatformMessageResponse(replyId: number, reply: ArrayBuffer): void { - Log.w(TAG, "called handlePlatformMessageResponse Response ID: " + replyId); + Log.d(TAG, "called handlePlatformMessageResponse Response ID: " + replyId); if (this.platformMessageHandler != null) { this.platformMessageHandler.handlePlatformMessageResponse(replyId, reply); } @@ -265,7 +265,7 @@ export default class FlutterNapi { // Called by native on any thread. handlePlatformMessage(channel: string, message: ArrayBuffer, replyId: number, messageData: number): void { - Log.w(TAG, "called handlePlatformMessage Channel: " + channel + ". Response ID: " + replyId); + Log.d(TAG, "called handlePlatformMessage Channel: " + channel + ". Response ID: " + replyId); if (this.platformMessageHandler != null) { this.platformMessageHandler.handleMessageFromDart(channel, message, replyId, messageData); } @@ -381,6 +381,10 @@ export default class FlutterNapi { for (index = 0; index < systemLanguages.length; index++) { Log.d(TAG, "systemlanguages "+ index + ":" + systemLanguages[index]); } + if (!this.isAttached()) { + Log.e(TAG, "getSystemLanguages this.nativeShellHolderId:" + this.nativeShellHolderId) + return; + } flutter.nativeGetSystemLanguages(this.nativeShellHolderId!, systemLanguages); } @@ -428,32 +432,60 @@ export default class FlutterNapi { } detachFromNativeAndReleaseResources() { - flutter.nativeDestroy(this.nativeShellHolderId!!); + if (!this.isAttached()) { + Log.e(TAG, "detachFromNativeAndReleaseResources this.nativeShellHolderId:" + this.nativeShellHolderId) + return; + } + flutter.nativeDestroy(this.nativeShellHolderId!); + this.nativeShellHolderId = null; } initNativeImage(textureId: number, aImage: image.Image) { Log.d(TAG, "called initNativeImage "); + if (!this.isAttached()) { + Log.e(TAG, "initNativeImage this.nativeShellHolderId:" + this.nativeShellHolderId) + return; + } flutter.nativeInitNativeImage(this.nativeShellHolderId!, textureId, aImage); } unregisterTexture(textureId: number): void { Log.d(TAG, "called unregisterTexture "); + if (!this.isAttached()) { + Log.e(TAG, "unregisterTexture this.nativeShellHolderId:" + this.nativeShellHolderId) + return; + } flutter.nativeUnregisterTexture(this.nativeShellHolderId!, textureId); } registerPixelMap(textureId: number, pixelMap: PixelMap): void { Log.d(TAG, "called registerPixelMap "); + if (!this.isAttached()) { + Log.e(TAG, "registerPixelMap this.nativeShellHolderId:" + this.nativeShellHolderId) + return; + } flutter.nativeRegisterPixelMap(this.nativeShellHolderId!, textureId, pixelMap); } + setTextureBackGroundPixelMap(textureId: number, pixelMap: PixelMap): void { + Log.d(TAG, "called setTextureBackGroundPixelMap "); + flutter.nativeSetTextureBackGroundPixelMap(this.nativeShellHolderId!, textureId, pixelMap); + } + registerTexture(textureId: number): number { Log.d(TAG, "called registerTexture "); + if (!this.isAttached()) { + Log.e(TAG, "registerTexture this.nativeShellHolderId:" + this.nativeShellHolderId) + return 0; + } return flutter.nativeRegisterTexture(this.nativeShellHolderId!, textureId); } /** Dispatch Touch Event */ onTouchEvent(strings: Array): void { - TouchEventProcessor.getInstance().postTouchEvent(strings); + if (this.isAttached()) { + TouchEventProcessor.getInstance().postTouchEvent(strings); + } } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartExecutor.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartExecutor.ets index 5ccbeb7407a5ef3a8724ed1f07decc782b970ce9..2c41446b2a710cbd3cf11aa7431b0ef8f5fdfac1 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartExecutor.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartExecutor.ets @@ -109,7 +109,7 @@ export default class DartExecutor implements BinaryMessenger { return; } - TraceSection.begin("DartExecutor#executeDartEntrypoint"); + let traceId: number = TraceSection.begin("DartExecutor#executeDartEntrypoint"); try { Log.d(TAG, "Executing Dart entrypoint: " + dartEntrypoint); this.flutterNapi.runBundleAndSnapshotFromLibrary( @@ -121,7 +121,7 @@ export default class DartExecutor implements BinaryMessenger { this.isApplicationRunning = true; } finally { - TraceSection.end("DartExecutor#executeDartEntrypoint"); + TraceSection.endWithId("DartExecutor#executeDartEntrypoint", traceId); } } @@ -138,7 +138,7 @@ export default class DartExecutor implements BinaryMessenger { return; } - TraceSection.begin("DartExecutor#executeDartCallback"); + let traceId: number = TraceSection.begin("DartExecutor#executeDartCallback"); try { Log.d(TAG, "Executing Dart callback: " + dartCallback); this.flutterNapi.runBundleAndSnapshotFromLibrary( @@ -150,7 +150,7 @@ export default class DartExecutor implements BinaryMessenger { this.isApplicationRunning = true; } finally { - TraceSection.end("DartExecutor#executeDartCallback"); + TraceSection.endWithId("DartExecutor#executeDartCallback", traceId); } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartMessenger.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartMessenger.ets index 2b1178097d32f9a5decacf8d277f60a9a7a07437..d2894ebcca73e04dc907e9034a3f251a45d0c825 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartMessenger.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartMessenger.ets @@ -82,7 +82,7 @@ export class DartMessenger implements BinaryMessenger, PlatformMessageHandler { send(channel: String, message: ArrayBuffer, callback?: BinaryReply): void { Log.d(TAG, "Sending message over channel '" + channel + "'"); - TraceSection.begin("DartMessenger#send on " + channel); + let traceId: number = TraceSection.begin("DartMessenger#send on " + channel); try { Log.d(TAG, "Sending message with callback over channel '" + channel + "'"); let replyId: number = this.nextReplyId++; @@ -95,7 +95,7 @@ export class DartMessenger implements BinaryMessenger, PlatformMessageHandler { this.flutterNapi.dispatchPlatformMessage(channel, message, message.byteLength, replyId); } } finally { - TraceSection.end("DartMessenger#send on " + channel); + TraceSection.endWithId("DartMessenger#send on " + channel, traceId); } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/FlutterLoader.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/FlutterLoader.ets index abf6e96a3ee1ce06d12097d2f13fa64fda18f752..aaeb579a61b3b2415babfe5eeae14c7dd218616f 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/FlutterLoader.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/FlutterLoader.ets @@ -180,6 +180,7 @@ export default class FlutterLoader { shellArgs.push( "--" + ISOLATE_SNAPSHOT_DATA_KEY + "=" + this.flutterApplicationInfo!.isolateSnapshotData); shellArgs.push('--enable-checked-mode') + shellArgs.push('--verbose-logging') } else { shellArgs.push( "--" + AOT_SHARED_LIBRARY_NAME + "=" + this.flutterApplicationInfo!.aotSharedLibraryName); diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityAware.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityAware.ets index bd68f68aee68859e0c13b696743c8d9d280b7500..b3d9b9df83522545bef2893d26b02dc297c8b908 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityAware.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityAware.ets @@ -20,7 +20,7 @@ */ import { AbilityPluginBinding } from './AbilityPluginBinding'; -export default interface AbilityAware { +export default interface AbilityAware { /** * This {@code AbilityAware} {@link io.flutter.embedding.engine.plugins.FlutterPlugin} is now * associated with an {@link ohos.app.ability.UIAbility}. diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/renderer/FlutterRenderer.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/renderer/FlutterRenderer.ets index f1624aaa4d9ef4b4cbcee420e3d0d6645ad4365a..5d9fe37697523931f8099d7ff7d5bc9304abffbd 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/renderer/FlutterRenderer.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/renderer/FlutterRenderer.ets @@ -62,6 +62,10 @@ export class FlutterRenderer implements TextureRegistry { return this.nextTextureId; } + setTextureBackGroundPixelMap(textureId: number, pixelMap: PixelMap): void { + this.flutterNapi.setTextureBackGroundPixelMap(textureId, pixelMap); + } + unregisterTexture(textureId: number): void { this.flutterNapi.unregisterTexture(textureId); } @@ -72,9 +76,9 @@ export class FlutterRenderer implements TextureRegistry { private getImageReceiver(): image.ImageReceiver { let receiver: image.ImageReceiver = image.createImageReceiver(640, 480, 4, 8); if (receiver !== undefined) { - console.info('[camera test] ImageReceiver is ok'); + Log.i(TAG, '[camera test] ImageReceiver is ok'); } else { - console.info('[camera test] ImageReceiver is not ok'); + Log.i(TAG, '[camera test] ImageReceiver is not ok'); } return receiver; } @@ -86,12 +90,12 @@ export class FlutterRenderer implements TextureRegistry { return; } this.flutterNapi.initNativeImage(textureId, nextImage); - console.log("[camera test] format: " + nextImage.format); + Log.i(TAG, "[camera test] format: " + nextImage.format); nextImage.release((err : BusinessError) =>{ if (err != undefined) { - console.log('Failed to release the image source instance.'); + Log.i(TAG, 'Failed to release the image source instance.'); } else { - console.log('Succeeded in releasing the image source instance.'); + Log.i(TAG, 'Succeeded in releasing the image source instance.'); } }); }) diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/KeyEventChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/KeyEventChannel.ets index f1ef9043ac6683be379a0cfcc507d7b967dfb3bc..4c863bc8bd38df145d113ebc57b01f41bcc40d7d 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/KeyEventChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/KeyEventChannel.ets @@ -51,9 +51,10 @@ export default class KeyEventChannel { message.set("keymap", "ohos"); message.set("keyCode", keyEvent.event.keyCode); message.set("deviceId", keyEvent.event.deviceId); - message.set("character", keyEvent.event.keyText); + message.set("flags", keyEvent.event.keyText); message.set("metaState", keyEvent.event.metaKey); - message.set("source", keyEvent.event.metaKey); + message.set("source", keyEvent.event.keySource); + message.set("intentionCode", keyEvent.event.intentionCode) return message; } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformChannel.ets index 239ce035500de51c68c568f7654bf80522a349da..8afbc9222396e8c7c3437818b36f7c05469fb9cd 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformChannel.ets @@ -59,10 +59,10 @@ export default class PlatformChannel { requestedOrientation |= 0x04; break; case DeviceOrientation.LANDSCAPE_LEFT: - requestedOrientation |= 0x02; + requestedOrientation |= 0x08; break; case DeviceOrientation.LANDSCAPE_RIGHT: - requestedOrientation |= 0x08; + requestedOrientation |= 0x02; break; } if (firstRequestedOrientation == 0x00) { @@ -105,6 +105,7 @@ export default class PlatformChannel { return bundleManager.DisplayOrientation.LANDSCAPE; } case 0x0f: + return window.Orientation.AUTO_ROTATION_RESTRICTED; } return bundleManager.DisplayOrientation.PORTRAIT; } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SettingsChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SettingsChannel.ets index dcb7e2fd91c1bee627b39184cb45393ad8adb2ea..6756b9032c035a13b4797168c32ec5cf42e9db3e 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SettingsChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SettingsChannel.ets @@ -76,7 +76,7 @@ class MessageBuilder { } send(): void { - Log.i(TAG, "Sending message: \n" + Log.i(TAG, "Sending message: " + TEXT_SCALE_FACTOR + " : " + this.settingsMessage.getTextScaleFactor() + ", " + NATIVE_SPELL_CHECK_SERVICE_DEFINED + " : " diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/EmbeddingNodeController.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/EmbeddingNodeController.ets index 2ad660b2a8ec7a911c8732031e041285be04c2a8..a58b9685ee7a4595d6022bbac038181fee8652c9 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/EmbeddingNodeController.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/EmbeddingNodeController.ets @@ -77,6 +77,7 @@ export class EmbeddingNodeController extends NodeController { setDestroy(isDestroy : boolean) : void { this.isDestroy = isDestroy; if (this.isDestroy) { + this.rootNode?.dispose() this.rootNode = null; } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbility.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbility.ets index 37e532808dddf506e4d43c02e2a58c1c0d45ba45..8ba4463178e5737bd4e4e4d4f27aa6457c67ef83 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbility.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbility.ets @@ -30,7 +30,6 @@ import { PlatformBrightness } from '../engine/systemchannels/SettingsChannel'; import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; import { Configuration } from '@ohos.app.ability.Configuration'; -import List from '@ohos.util.List'; import ExclusiveAppComponent from './ExclusiveAppComponent'; import errorManager from '@ohos.app.ability.errorManager'; import appRecovery from '@ohos.app.ability.appRecovery'; @@ -69,6 +68,9 @@ export class FlutterAbility extends UIAbility implements Host { * 4. setContentView() noNeed */ async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + // 冷启动通过上下文环境获取到系统当前文字大小,并进行键值存储 + AppStorage.setOrCreate('fontSizeScale', this.context.config.fontSizeScale); + Log.i(TAG, "bundleCodeDir=" + this.context.bundleCodeDir); FlutterManager.getInstance().pushUIAbility(this) @@ -86,7 +88,7 @@ export class FlutterAbility extends UIAbility implements Host { this?.delegate?.onWindowStageCreate(); } - console.log('MyAbility onCreate'); + Log.i(TAG, 'MyAbility onCreate'); this.context.eventHub.on(EVENT_BACK_PRESS, () => { this.delegate?.flutterEngine?.getNavigationChannel()?.popRoute(); @@ -94,7 +96,7 @@ export class FlutterAbility extends UIAbility implements Host { }); let observer:errorManager.ErrorObserver = { onUnhandledException(errorMsg) { - console.log("onUnhandledException, errorMsg:", errorMsg); + Log.e(TAG, "onUnhandledException, errorMsg:", errorMsg); appRecovery.saveAppState(); appRecovery.restartApp(); } @@ -163,7 +165,7 @@ export class FlutterAbility extends UIAbility implements Host { }); this.flutterView = this.delegate!!.createView(this.context) - Log.e(TAG, 'onWindowStageCreate:' + this.flutterView!!.getId()); + Log.w(TAG, 'onWindowStageCreate:' + this.flutterView!!.getId()); let storage: LocalStorage = new LocalStorage(); storage.setOrCreate("viewId", this.flutterView!!.getId()) windowStage.loadContent(this.pagePath(), storage, (err, data) => { @@ -367,9 +369,13 @@ export class FlutterAbility extends UIAbility implements Host { onConfigurationUpdated(config: Configuration){ Log.i(TAG, 'onConfigurationUpdated config:' + JSON.stringify(config)); this?.delegate?.flutterEngine?.getSettingsChannel()?.startMessage() + .setNativeSpellCheckServiceDefined(false) + .setBrieflyShowPassword(false) .setAlwaysUse24HourFormat(I18n.System.is24HourClock()) .setPlatformBrightness(config.colorMode != ConfigurationConstant.ColorMode.COLOR_MODE_DARK - ? PlatformBrightness.LIGHT : PlatformBrightness.DARK); + ? PlatformBrightness.LIGHT : PlatformBrightness.DARK) + .setTextScaleFactor(config.fontSizeScale == undefined? 1.0 : config.fontSizeScale) + .send(); //热启动生命周期内,实时监听系统设置环境改变并实时发送相应信息 if (config.language != '') { this.getFlutterEngine()?.getLocalizationPlugin()?.sendLocaleToFlutter(); diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterEntry.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterEntry.ets index 88e714f241bbf8b4981af55f00608e21042d8ab7..f6462e5cf3c649f86ae95c91c542a20f71564b3e 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterEntry.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterEntry.ets @@ -245,7 +245,7 @@ export default class FlutterEntry implements Host { } popSystemNavigator(): boolean { - return true; + return false; } addPlugin(plugin: FlutterPlugin): void { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterManager.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterManager.ets index 80896cf99e11d134ffc63bd435fafc8c8609d261..8cac73b0dc5fb3f1909f0a4b8e8200d1e1bc574a 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterManager.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterManager.ets @@ -17,6 +17,9 @@ import { FlutterView } from '../../view/FlutterView'; import UIAbility from '@ohos.app.ability.UIAbility'; import window from '@ohos.window'; +import Log from '../../util/Log'; + +const TAG = "FlutterManager" export default class FlutterManager { private static instance: FlutterManager; @@ -136,10 +139,12 @@ export class DefaultFullScreenListener implements FullScreenListener { let window = FlutterManager.getInstance() .getWindowStage(FlutterManager.getInstance().getUIAbility(getContext(this))); window.getMainWindowSync().setWindowLayoutFullScreen(useFullScreen); + Log.i(TAG, "WindowLayoutFullScreen is on") } onScreenStateChanged(data: window.WindowStatusType): void { if (this.skipCheck) { + Log.i(TAG, "onScreenStateChanged: skipCheck is on, WindowStatusType = " + data) return; } switch (data) { @@ -148,9 +153,11 @@ export class DefaultFullScreenListener implements FullScreenListener { case window.WindowStatusType.FLOATING: case window.WindowStatusType.MAXIMIZE: this.fullScreen = true; + Log.i(TAG, "onScreenStateChanged: fullScreen = true") break; default: this.fullScreen = false; + Log.i(TAG, "onScreenStateChanged: fullScreen = false") break; } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterPage.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterPage.ets index 3c7c84be0866443ff12b5be576751059a31faabe..1634db5f6fdfad4be355fa193fb052a83844f491 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterPage.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterPage.ets @@ -15,11 +15,11 @@ import Log from '../../util/Log'; import { FlutterView } from '../../view/FlutterView'; -import { EmbeddingNodeController } from './EmbeddingNodeController'; import FlutterManager from './FlutterManager'; import { DVModel, DVModelChildren, DynamicView } from '../../view/DynamicView/dynamicView'; const TAG = "FlutterPage"; +export const OHOS_FLUTTER_PAGE_UPDATE = "ohos_flutter_page_update"; /** * 基础page组件,承载XComponent组件 @@ -31,43 +31,60 @@ export struct FlutterPage { @Builder doNothingBuilder() {} @BuilderParam splashScreenView: () => void = this.doNothingBuilder; - @State showSplashScreen: boolean = true; - - @State checkFullScreen: boolean = true; - @State checkKeyboard: boolean = true; - @State checkGesture: boolean = true; - - @StorageLink('nodeWidth') storageLinkWidth: number = 0; - @StorageLink('nodeHeight') storageLinkHeight: number = 0; - - @State rootDvModel: DVModelChildren | undefined = undefined - - - private flutterView?: FlutterView | null - private lastArea?: Area; - private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down }); - - aboutToAppear() { - this.flutterView = FlutterManager.getInstance().getFlutterView(this.viewId); - this.flutterView?.addFirstFrameListener(this) - - this.flutterView?.setCheckFullScreen(this.checkFullScreen) - this.flutterView?.setCheckKeyboard(this.checkKeyboard) - this.flutterView?.setCheckGesture(this.checkGesture) + @Builder defaultPage() { + Stack() { + ForEach(this.rootDvModel!!, (child: ESObject) => { + DynamicView({ + model: child as DVModel, + params: child.params, + events: child.events, + children: child.children, + customBuilder: child.builder + }) + }, (child: ESObject) => `${child.id_}`) - this.rootDvModel = this.flutterView!!.getDVModel().children - } + Text('') + .id('emptyFocusText' + this.viewId) + .size({ width: 0, height: 0 }) + .opacity(0) + .focusable(true) - aboutToDisappear() { - this.flutterView?.removeFirstFrameListener(this); - } + XComponent({ id: this.viewId, type: this.xComponentType, libraryname: 'flutter' }) + .id(this.viewId) + .focusable(true) + .onLoad((context) => { + this.flutterView?.onSurfaceCreated() + Log.d(TAG, "XComponent onLoad "); + }) + .onDestroy(() => { + Log.d(TAG, "XComponent onDestroy "); + this.flutterView?.onSurfaceDestroyed() + }) + .backgroundColor(Color.Transparent) - onFirstFrame() { - this.showSplashScreen = false; + if (this.showSplashScreen) { + this.splashScreenView(); + } + } + .defaultFocus(true) + .onAreaChange((oldValue: Area, newValue: Area) => { + if (this.isNeedUpdate || !this.lastArea || oldValue.width != newValue.width + || oldValue.height != newValue.height) { + Log.d(TAG, "onAreaChange, old=" + JSON.stringify(oldValue)); + Log.d(TAG, "onAreaChange, new=" + JSON.stringify(newValue)); + this.lastArea = newValue; + this.flutterView?.onAreaChange(newValue) + this.isNeedUpdate = false; + } + }) + .onKeyPreIme((event: KeyEvent) => { + Log.d(TAG, "onKeyEvent " + event.type); + this.flutterView?.onKeyEvent(event); + return false; + }) } - - build() { + @Builder mouseWheelPage() { Stack() { ForEach(this.rootDvModel!!, (child: ESObject) => { DynamicView({ @@ -77,7 +94,6 @@ export struct FlutterPage { children: child.children, customBuilder: child.builder }) - .position({x: (child.params as Record)['left'] as number, y: (child.params as Record)['top'] as number}) }, (child: ESObject) => `${child.id_}`) @@ -88,6 +104,7 @@ export struct FlutterPage { .focusable(true) XComponent({ id: this.viewId, type: this.xComponentType, libraryname: 'flutter' }) + .id(this.viewId) .focusable(true) .onLoad((context) => { this.flutterView?.onSurfaceCreated() @@ -103,18 +120,21 @@ export struct FlutterPage { this.splashScreenView(); } } + .defaultFocus(true) .onAreaChange((oldValue: Area, newValue: Area) => { - if (!this.lastArea || oldValue.width != newValue.width + if (this.isNeedUpdate || !this.lastArea || oldValue.width != newValue.width || oldValue.height != newValue.height) { Log.d(TAG, "onAreaChange, old=" + JSON.stringify(oldValue)); Log.d(TAG, "onAreaChange, new=" + JSON.stringify(newValue)); this.lastArea = newValue; this.flutterView?.onAreaChange(newValue) + this.isNeedUpdate = false; } }) - .onKeyEvent((event: KeyEvent) => { + .onKeyPreIme((event: KeyEvent) => { Log.d(TAG, "onKeyEvent " + event.type); - this.flutterView?.onKeyEvent(event) + this.flutterView?.onKeyEvent(event); + return false; }) .gesture( PanGesture(this.panOption) @@ -129,4 +149,52 @@ export struct FlutterPage { }) ) } + @State showSplashScreen: boolean = true; + + @State checkFullScreen: boolean = true; + @State checkKeyboard: boolean = true; + @State checkGesture: boolean = true; + @State checkMouseWheel: boolean = true; + + @StorageLink('nodeWidth') storageLinkWidth: number = 0; + @StorageLink('nodeHeight') storageLinkHeight: number = 0; + + @State rootDvModel: DVModelChildren | undefined = undefined + + @State isNeedUpdate: boolean = false; + + private flutterView?: FlutterView | null + private lastArea?: Area; + private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down }); + + aboutToAppear() { + this.flutterView = FlutterManager.getInstance().getFlutterView(this.viewId); + this.flutterView?.addFirstFrameListener(this) + + this.flutterView?.setCheckFullScreen(this.checkFullScreen) + this.flutterView?.setCheckKeyboard(this.checkKeyboard) + this.flutterView?.setCheckGesture(this.checkGesture) + + this.rootDvModel = this.flutterView!!.getDVModel().children + getContext().eventHub.on(OHOS_FLUTTER_PAGE_UPDATE, () => { + this.isNeedUpdate = true; + }) + } + + aboutToDisappear() { + this.flutterView?.removeFirstFrameListener(this); + getContext().eventHub.off(OHOS_FLUTTER_PAGE_UPDATE) + } + + onFirstFrame() { + this.showSplashScreen = false; + } + + build() { + if (this.checkMouseWheel) { + this.mouseWheelPage(); + } else { + this.defaultPage(); + } + } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/Settings.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/Settings.ets index f90df8cf28a98f50e69520497b09e088e713d2a4..637e99815ea5142d25d5c33ed138a97ae41f558c 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/Settings.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/Settings.ets @@ -30,14 +30,14 @@ export default class Settings { sendSettings(mediaQuery: MediaQuery): void { this.settingsChannel?.startMessage() .setAlwaysUse24HourFormat(I18n.System.is24HourClock()) - .setTextScaleFactor(1.0) .setNativeSpellCheckServiceDefined(false) .setBrieflyShowPassword(false) - .setPlatformBrightness(this.getDarkMode(mediaQuery)) + .setPlatformBrightness(this.getThemeMode(mediaQuery)) + .setTextScaleFactor(this.getTextScaleFactor()) .send(); } - getDarkMode(mediaQuery: MediaQuery): PlatformBrightness { + getThemeMode(mediaQuery: MediaQuery): PlatformBrightness { let listener = mediaQuery.matchMediaSync('(dark-mode: true)'); if (listener.matches) { @@ -48,4 +48,15 @@ export default class Settings { return PlatformBrightness.LIGHT; } } + + getTextScaleFactor() : number { + let sysTextScaleFactor = AppStorage.get('fontSizeScale'); + if(sysTextScaleFactor == undefined) { + sysTextScaleFactor = 1.0; + Log.e(TAG, 'get textScaleFactor error, it is assigned to ' + JSON.stringify(sysTextScaleFactor)); + } + Log.i(TAG, "return textScaleFactor = " + JSON.stringify(sysTextScaleFactor)) + return sysTextScaleFactor; + } + } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/TouchEventProcessor.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/TouchEventProcessor.ets index 00fab960360e3b7e7a143df134bfff4219c1b5e7..e6100e08335ae582e9a048471e017163ba749c3a 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/TouchEventProcessor.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/TouchEventProcessor.ets @@ -258,7 +258,7 @@ export default class TouchEventProcessor { let touchEvent = TouchEventProcessor.getInstance().constureCustomTouchEvent(strings, top, left); let nodeController = params['nodeController'] as EmbeddingNodeController; nodeController.postEvent(touchEvent) - } else if (strings[6] == '0' && !down) { + } else { //如果触摸事件为OH_NATIVEXCOMPONENT_DOWN=0,且只有一个手指,说明是下一次点击了,这时候需要清空上一次的数据 if (strings[6] == '0' && strings[0] == '1') { params['touchEvent'] = undefined diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/PlatformPlugin.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/PlatformPlugin.ets index c2e129244bc803f97324bf5057c47ad68d42d06f..e9ef8faa7daa76f2e504e57f44790e45336dbc86 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/PlatformPlugin.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/PlatformPlugin.ets @@ -199,12 +199,9 @@ export class PlatformPluginCallback implements PlatformMessageHandler { popSystemNavigator() { if (this.platformPluginDelegate != null && this.platformPluginDelegate?.popSystemNavigator()) { - router.back(); return; } - if (this.uiAbilityContext != null) { - this.uiAbilityContext.terminateSelf(); - } + router.back(); } getClipboardData(result: MethodResult): void { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/JSONMessageCodec.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/JSONMessageCodec.ets index 4f0e7ab2bd8f68a0587cc16e1b10d5a1ac61c63b..d30f817fb3c6ce49d1ccdd5cae6a774098e8ca2e 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/JSONMessageCodec.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/JSONMessageCodec.ets @@ -72,7 +72,7 @@ export default class JSONMessageCodec implements MessageCodec { toBaseData(message: Any): Any { if (message == null || message == undefined) { - return ""; + return null; } else if (message instanceof List || message instanceof LinkedList) { return this.toBaseData(message.convertToArray()); } else if (message instanceof Map || message instanceof HashMap || message instanceof TreeMap diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/SendableStandardMessageCodec.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/SendableStandardMessageCodec.ets index dac0917a1fc7e110e98e4f62603e6dc886e5bc75..af405327733303d134942a5fa849b3975f7094f5 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/SendableStandardMessageCodec.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/SendableStandardMessageCodec.ets @@ -211,13 +211,13 @@ export default class SendableStandardMessageCodec implements SendableMessageCode writeSize(stream: ByteBuffer, value: number) { if (value < 254) { - stream.writeInt8(value); + stream.writeUint8(value); } else if (value <= 0xffff) { - stream.writeInt8(254); - stream.writeInt16(value, true); + stream.writeUint8(254); + stream.writeUint16(value, true); } else { - stream.writeInt8(255); - stream.writeInt32(value, true); + stream.writeUint8(255); + stream.writeUint32(value, true); } } @@ -227,13 +227,13 @@ export default class SendableStandardMessageCodec implements SendableMessageCode } readSize(buffer: ByteBuffer) { - let value = buffer.readInt8() & 0xff; + let value = buffer.readUint8() & 0xff; if (value < 254) { return value; } else if (value == 254) { return buffer.readUint16(true); } else { - return buffer.readInt32(true); + return buffer.readUint32(true); } } @@ -251,10 +251,9 @@ export default class SendableStandardMessageCodec implements SendableMessageCode readBytes(buffer: ByteBuffer): Uint8Array { let length = this.readSize(buffer); - let bytes = new Uint8Array(length) - for (let i = 0; i < length; i++) { - bytes[i] = buffer.readUint8() - } + let bytesBuffer = new ArrayBuffer(length); + let bytes = new Uint8Array(bytesBuffer); + bytes.set(buffer.readUint8Array(length)); return bytes; } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StandardMessageCodec.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StandardMessageCodec.ets index 33ad31db904f7f1a00c5c3984a12785effc31689..d9df49cee8388c6adebc1dfffbf8ce1c0bd85d50 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StandardMessageCodec.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StandardMessageCodec.ets @@ -217,13 +217,13 @@ export default class StandardMessageCodec implements MessageCodec { writeSize(stream: ByteBuffer, value: number) { if (value < 254) { - stream.writeInt8(value); + stream.writeUint8(value); } else if (value <= 0xffff) { - stream.writeInt8(254); - stream.writeInt16(value, true); + stream.writeUint8(254); + stream.writeUint16(value, true); } else { - stream.writeInt8(255); - stream.writeInt32(value, true); + stream.writeUint8(255); + stream.writeUint32(value, true); } } @@ -233,13 +233,13 @@ export default class StandardMessageCodec implements MessageCodec { } readSize(buffer: ByteBuffer) { - let value = buffer.readInt8() & 0xff; + let value = buffer.readUint8() & 0xff; if (value < 254) { return value; } else if (value == 254) { return buffer.readUint16(true); } else { - return buffer.readInt32(true); + return buffer.readUint32(true); } } @@ -257,10 +257,9 @@ export default class StandardMessageCodec implements MessageCodec { readBytes(buffer: ByteBuffer): Uint8Array { let length = this.readSize(buffer); - let bytes = new Uint8Array(length) - for (let i = 0; i < length; i++) { - bytes[i] = buffer.readUint8() - } + let bytesBuffer = new ArrayBuffer(length); + let bytes = new Uint8Array(bytesBuffer); + bytes.set(buffer.readUint8Array(length)); return bytes; } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextInputPlugin.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextInputPlugin.ets index 2cd92fd9786b13e27315dcd6f70db08c446e70ec..01a79f36f1815d093cd1a9b45c668a7116d5ad3f 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextInputPlugin.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextInputPlugin.ets @@ -23,6 +23,9 @@ import inputMethod from '@ohos.inputMethod'; import Log from '../../util/Log'; import { EditingStateWatcher, ListenableEditingState } from './ListenableEditingState'; import Any from '../common/Any'; +import { window } from '@kit.ArkUI'; +import FlutterManager from '../../embedding/ohos/FlutterManager'; +import { IntentionCode } from '@ohos.multimodalInput.intentionCode'; /// 临时规避缺少newline对应枚举问题 const NEWLINE_KEY_TYPE: number = 8; @@ -50,8 +53,8 @@ export default class TextInputPlugin implements EditingStateWatcher { let editable = this.mTextInputHandler.mEditable; let inputTarget = this.mTextInputHandler.inputTarget; let configuration = this.mTextInputHandler.configuration; - if (configuration!= null && configuration.enableDeltaModel) { - this.textInputChannel.updateEditingStateWithDeltas(inputTarget.id,editable.extractBatchTextEditingDeltas()); + if (configuration != null && configuration.enableDeltaModel) { + this.textInputChannel.updateEditingStateWithDeltas(inputTarget.id, editable.extractBatchTextEditingDeltas()); editable.clearBatchDeltas(); } else { this.textInputChannel.updateEditingState(inputTarget.id, editable.getStringCache(), @@ -80,17 +83,20 @@ class TextInputMethodHandlerImpl implements TextInputMethodHandler { private mRestartInputPending: boolean = false; private plugin: EditingStateWatcher | Any; private imcFlag: boolean = false; + private showType: keyboardType = keyboardType.ENTRY constructor(plugin: TextInputPlugin | Any) { this.textConfig = { inputAttribute: { textInputType: 0, enterKeyType: 1 - } }; + } + }; this.plugin = plugin; this.mEditable = new ListenableEditingState(null, 0); this.inputMethodController = inputMethod.getController(); this.inputTarget = new InputTarget(Type.NO_TARGET, 0); + this.listenShowKeyboardHeight(); } show(): void { @@ -123,8 +129,10 @@ class TextInputMethodHandlerImpl implements TextInputMethodHandler { } setEditingState(editingState: TextEditState): void { - Log.d(TextInputMethodHandlerImpl.TAG, "text:" + editingState.text + " selectionStart:" + editingState.selectionStart + " selectionEnd:" - + editingState.selectionEnd + " composingStart:" + editingState.composingStart + " composingEnd" + editingState.composingEnd); + Log.d(TextInputMethodHandlerImpl.TAG, + "text:" + editingState.text + " selectionStart:" + editingState.selectionStart + " selectionEnd:" + + editingState.selectionEnd + " composingStart:" + editingState.composingStart + " composingEnd" + + editingState.composingEnd); this.mEditable.updateTextInputState(editingState); } @@ -133,6 +141,31 @@ class TextInputMethodHandlerImpl implements TextInputMethodHandler { } private async showTextInput(): Promise { + /// 暂时规避方案 + /// NONE是打开软键盘,正常输入模式 + /// ENTRY是未弹出软键盘时的输入模式 + /// TRANSFER负责切换同一个页面内的TextField时重置键盘 + /// DONE是解决点击Entry时submitted回调使用弹窗而无法正常收起软键盘 + switch (this.showType) { + case keyboardType.NONE: + break; + case keyboardType.ENTRY: + this.showKeyboard(); + break; + case keyboardType.TRANSFER: + this.showKeyboard(); + break; + case keyboardType.DONE: + this.hideTextInput(); + break; + default: + break; + } + } + + async showKeyboard() { + /// 添加软键盘弹出收起监听方法 + this.listenShowKeyboardHeight(); await this.attach(true); if (this.imcFlag != true) { this.listenKeyBoardEvent(); @@ -142,6 +175,35 @@ class TextInputMethodHandlerImpl implements TextInputMethodHandler { }).catch((err: Any) => { Log.e(TextInputMethodHandlerImpl.TAG, "Failed to show softKeyboard:" + JSON.stringify(err)); }); + this.showType = keyboardType.NONE; + } + + listenShowKeyboardHeight() { + window.getLastWindow(getContext(this)).then(currentWindow => { + try { + currentWindow.on('keyboardHeightChange', (data) => { + console.info('Succeeded in enabling the listener for keyboard height changes. Data: ' + JSON.stringify(data)); + if (data == 0) { + this.showType = keyboardType.ENTRY + } else { + this.showType = keyboardType.NONE + } + }); + } catch (exception) { + console.error(`Failed to enable the listener for keyboard height changes. Cause code: ${exception.code}, message: ${exception.message}`); + } + }) + } + + /// 软键盘收起时关闭监听方法 + listenHideKeyboardHeight() { + window.getLastWindow(getContext(this)).then(currentWindow => { + try { + currentWindow.off('keyboardHeightChange'); + } catch (exception) { + console.error(`Failed to enable the listener for keyboard height changes. Cause code: ${exception.code}, message: ${exception.message}`); + } + }) } private async hideTextInput(): Promise { @@ -150,6 +212,8 @@ class TextInputMethodHandlerImpl implements TextInputMethodHandler { }).catch((err: Any) => { Log.e(TextInputMethodHandlerImpl.TAG, "Failed to hide softKeyboard:" + JSON.stringify(err)); }) + this.showType = keyboardType.ENTRY + this.listenHideKeyboardHeight() } async attach(showKeyboard: boolean): Promise { @@ -166,7 +230,7 @@ class TextInputMethodHandlerImpl implements TextInputMethodHandler { inputAttribute: { textInputType: 0, enterKeyType: 1 - } + } }; await this.inputMethodController.attach(false, textConfig); } catch (err) { @@ -175,7 +239,8 @@ class TextInputMethodHandlerImpl implements TextInputMethodHandler { } setTextInputClient(client: number, configuration: Configuration | null): void { - const INPUT_TYPE_NAME = ['NONE', 'TEXT', 'MULTILINE', 'NUMBER', 'PHONE', 'DATETIME', 'EMAIL_ADDRESS', 'URL', 'VISIBLE_PASSWORD'] + const INPUT_TYPE_NAME = + ['NONE', 'TEXT', 'MULTILINE', 'NUMBER', 'PHONE', 'DATETIME', 'EMAIL_ADDRESS', 'URL', 'VISIBLE_PASSWORD'] if (configuration) { this.configuration = configuration; if (configuration.inputType) { @@ -217,6 +282,26 @@ class TextInputMethodHandlerImpl implements TextInputMethodHandler { try { this.inputMethodController.on('deleteLeft', (length) => { + /// 暂时规避方案 + /// OS机制与Android不一致,需要去监听软键盘事件才能发送KeyEvent事件 + /// keyCode是从dart侧获取的,因为是使用删除按钮,此处暂时这样写死;其他地方如果需要键盘发送事件,再去找对应的keyCode + if (length == 1) { + let event: KeyEvent = { + type: KeyType.Down, + /// dart侧keyboard_maps.g.dart中LogicalKeyboardKey.backspace设置为这个参 + keyCode: 2055, + keyText: '', + keySource: KeySource.Keyboard, + deviceId: 0, + metaKey: 0, + timestamp: 0, + stopPropagation: (): void => { + throw new Error('Function not implemented.'); + }, + intentionCode: IntentionCode.INTENTION_BACK + } + this.sendKeyboardEvent(event) + } this.mEditable.handleDeleteEvent(false, length); }) } catch (err) { @@ -238,8 +323,10 @@ class TextInputMethodHandlerImpl implements TextInputMethodHandler { try { this.inputMethodController.on('sendFunctionKey', (functionKey) => { /// 临时规避缺少newline对应枚举类型问题 - if(functionKey.enterKeyType == NEWLINE_KEY_TYPE) { + if (functionKey.enterKeyType == NEWLINE_KEY_TYPE) { this.mEditable.handleNewlineEvent(); + } else { + this.showType = keyboardType.DONE } this.mEditable.handleFunctionKey(functionKey); }) @@ -253,7 +340,11 @@ class TextInputMethodHandlerImpl implements TextInputMethodHandler { this.inputMethodController.on('sendKeyboardStatus', (state) => { if (state == inputMethod.KeyboardStatus.HIDE) { this.plugin.textInputChannel.onConnectionClosed(this.inputTarget.id); - this.resetAttach(); + if (this.showType != keyboardType.DONE) { + this.showType = keyboardType.TRANSFER + } + this.hideTextInput() + this.cancelListenKeyBoardEvent() } }) } catch (err) { @@ -275,6 +366,12 @@ class TextInputMethodHandlerImpl implements TextInputMethodHandler { this.imcFlag = true; } + sendKeyboardEvent(event: KeyEvent): void { + FlutterManager.getInstance().getFlutterViewList().forEach((value) => { + value.onKeyEvent(event) + }) + } + cancelListenKeyBoardEvent(): void { this.inputMethodController.off('insertText'); this.inputMethodController.off('deleteLeft'); @@ -292,6 +389,9 @@ class TextInputMethodHandlerImpl implements TextInputMethodHandler { this.mEditable.removeEditingStateListener(this.plugin); this.configuration = null; this.inputTarget = new InputTarget(Type.NO_TARGET, 0); + if (this.showType != keyboardType.DONE) { + this.showType = keyboardType.TRANSFER + } this.resetAttach(); } } @@ -306,6 +406,13 @@ enum Type { PHYSICAL_DISPLAY_PLATFORM_VIEW, } +enum keyboardType { + NONE, + ENTRY, + TRANSFER, + DONE +} + export class InputTarget { type: Type; id: number; diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/localization/LocalizationPlugin.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/localization/LocalizationPlugin.ets index 93ce6e6d25e3b34055586a43cc64d24b9eac6212..05421fc41e6c74003556ed92dffc9018314b7926 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/localization/LocalizationPlugin.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/localization/LocalizationPlugin.ets @@ -13,20 +13,23 @@ * limitations under the License. */ -import LocalizationChannel, { LocalizationMessageHandler } from '../../embedding/engine/systemchannels/LocalizationChannel' +import LocalizationChannel, { + LocalizationMessageHandler +} from '../../embedding/engine/systemchannels/LocalizationChannel' import common from '@ohos.app.ability.common'; import intl from '@ohos.intl'; import Log from '../../util/Log'; import i18n from '@ohos.i18n'; -const TAG = "LocalizationPlugin"; +const TAG = "LocalizationPlugin"; + export default class LocalizationPlugin { - private localizationChannel:LocalizationChannel; + private localizationChannel: LocalizationChannel; private context: common.Context; localeFromString(localeString: string): intl.Locale { - localeString = localeString.replace('_','-'); - let parts: string[] = localeString.split('-',-1); + localeString = localeString.replace('_', '-'); + let parts: string[] = localeString.split('-', -1); let languageCode = parts[0]; let scriptCode = ""; let countryCode = ""; @@ -41,13 +44,36 @@ export default class LocalizationPlugin { countryCode = parts[index]; index++; } - return new intl.Locale(languageCode+'-'+ countryCode +'-' + scriptCode); + return new intl.Locale(languageCode + '-' + countryCode + '-' + scriptCode); } - private localizationMessageHandler: LocalizationMessageHandler =new enterGetStringResource(()=>{ - Log.i(TAG, "getResource enter"); - return "" - }) + private localizationMessageHandler: LocalizationMessageHandler = + new enterGetStringResource((key: string, localeString: string | null) => { + + Log.i(TAG, "getStringResource,key: " + key + ",localeString: " + localeString); + let localContext: common.Context = this.context; + let stringToReturn: string | null = null; + // 获取资源管理器 + let resMgr = localContext.resourceManager; + + try { + // 如果localeString不为空,则更新为指定地区的资源管理器 + if (localeString) { + let overrideConfig = resMgr.getOverrideConfiguration(); + overrideConfig.locale = localeString; + let overrideResMgr = resMgr.getOverrideResourceManager(overrideConfig); + stringToReturn = overrideResMgr.getStringByNameSync(key); + } else { + stringToReturn = resMgr.getStringByNameSync(key); + } + } catch (e) { + Log.e(TAG, e); + return null; + } + + return stringToReturn; + }) + constructor(context: common.Context, localizationChannel: LocalizationChannel) { this.context = context; this.localizationChannel = localizationChannel; @@ -61,10 +87,11 @@ export default class LocalizationPlugin { this.localizationChannel.sendLocales(data); } } -class enterGetStringResource{ - getStringResource : (key: string, localeString: string)=>string - constructor(getStringResource: (key: string, localeString: string)=>string) { +class enterGetStringResource { + getStringResource: (key: string, localeString: string | null) => string | null + + constructor(getStringResource: (key: string, localeString: string | null) => string | null) { this.getStringResource = getStringResource } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformView.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformView.ets index 320e5e973d4e0b4452856a676f20c8b1156aa9a0..1628ddd672c078a94b7624996e20878110eaaf58 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformView.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformView.ets @@ -21,7 +21,12 @@ export declare class Params { } /** A handle to an DynamicView to be embedded in the Flutter hierarchy. */ -export default abstract class PlatformView { +export default abstract class PlatformView { + + getType(): string { + return 'default'; + } + /** Returns the DynamicView to be embedded in the Flutter hierarchy. */ abstract getView(): WrappedBuilder<[Params]>; /** diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsController.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsController.ets index 5f56d928120ecc3e1523d41d3d0c2b94070678ec..7d3e311fc612c67c45341c7a70210fab83ca09c1 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsController.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsController.ets @@ -88,6 +88,8 @@ export default class PlatformViewsController implements PlatformViewsAccessibili private currentFrameUsedPlatformViewIds: HashSet; private platformViewParent: Map; private nodeControllers: Stack; + private viewPhysicalInfo: Map = new Map(); + private dValue: number = 3; constructor() { this.registry = new PlatformViewRegistryImpl(); @@ -136,6 +138,9 @@ export default class PlatformViewsController implements PlatformViewsAccessibili return; } this.platformViews.delete(viewId); + if (this.viewPhysicalInfo.has(viewId)) { + this.viewPhysicalInfo.delete(viewId); + } let textureId = this.viewIdWithTextureId.get(viewId); if (textureId != undefined) { @@ -150,6 +155,7 @@ export default class PlatformViewsController implements PlatformViewsAccessibili let viewWrapper: PlatformViewWrapper | null = this.viewWrappers.get(viewId) || null; if (viewWrapper != null) { + this.viewIdWithNodeController.get(viewId)?.setDestroy(true) if (this.flutterView) { let index = this.flutterView.getDVModel().children.indexOf(viewWrapper.getDvModel()!); this.flutterView.getDVModel().children.splice(index, 1); @@ -163,6 +169,11 @@ export default class PlatformViewsController implements PlatformViewsAccessibili params2[key] =element; } + getParams: (params: DVModelParameters, key: string) => number = (params: DVModelParameters, key: string): number => { + let params2 = params as Record; + return params2[key]; + } + resize(request: PlatformViewResizeRequest, onComplete: PlatformViewBufferResized): void { let physicalWidth: number = this.toPhysicalPixels(request.newLogicalWidth); let physicalHeight: number = this.toPhysicalPixels(request.newLogicalHeight); @@ -171,7 +182,23 @@ export default class PlatformViewsController implements PlatformViewsAccessibili let viewWrapper = this.viewWrappers.get(request.viewId) let params: DVModelParameters | undefined = viewWrapper?.getDvModel()!.params + + const platformView = this.platformViews.get(request.viewId); + if (platformView?.getType() === 'web') { + let oldPhysicalHeight: number = 0; + if (this.viewPhysicalInfo.has(viewId)) { + oldPhysicalHeight = this.viewPhysicalInfo.get(viewId) as number; + //高度变化小于3,不做刷新处理,减少闪烁 + if (physicalHeight - oldPhysicalHeight < this.dValue) { + onComplete.run(new PlatformViewBufferSize(physicalWidth, oldPhysicalHeight)); + return; + } + } + } + //保存组件最高位置,解决webview上下滑动带来的组件高度变化而引起的页面闪烁 + this.viewPhysicalInfo.set(viewId, physicalHeight); + this.setParams(params!, "width", physicalWidth); this.setParams(params!, "height", physicalHeight); @@ -433,6 +460,9 @@ export default class PlatformViewsController implements PlatformViewsAccessibili private diposeAllViews(): void { + for (let viewId of this.platformViews.keys()) { + this.dispose(viewId); + } } private initializeRootImageViewIfNeeded(): void { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ByteBuffer.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ByteBuffer.ets index 57193e339a90805271c4bb24f091ee4d379331f9..e7cc1d3ac24f31d8f32bd64190819fee1ae57817 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ByteBuffer.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ByteBuffer.ets @@ -116,7 +116,11 @@ export class ByteBuffer { */ checkWriteCapacity(slen: number): void { if (this.mByteOffset + slen > this.dataView!.byteLength) { - let newBuffer = new ArrayBuffer(this.dataView!.byteLength + slen + 512); + let newCapacity = this.dataView!.byteLength + (this.dataView!.byteLength >> 1); + if (newCapacity < this.dataView!.byteLength + slen + 512) { + newCapacity = this.dataView!.byteLength + slen + 512; + } + let newBuffer = new ArrayBuffer(newCapacity); let newDataView = new DataView(newBuffer); let oldUint8Array = new Uint8Array(this.dataView!.buffer); let newUint8Array = new Uint8Array(newBuffer); diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/Log.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/Log.ets index 503515c6471c48e1a73210465adaa1486e4f8085..12a50ce3202a5f3cf2db0a0d2b3f7d140b98ced3 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/Log.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/Log.ets @@ -14,6 +14,7 @@ */ import HiLog from '@ohos.hilog'; +import BuildProfile from '../../../../BuildProfile'; const DOMAIN: number = 0x00FF; const TAG = "Flutter"; @@ -39,6 +40,17 @@ const SYMBOL = " --> "; * Basic log class */ export default class Log { + private static _logLevel = HiLog.LogLevel.WARN; + + /** + * Set log level. + * + * @param level Indecated the log level. + */ + public static setLogLevel(level: HiLog.LogLevel) { + Log._logLevel = level; + } + /** * Outputs debug-level logs. * @@ -123,6 +135,10 @@ export default class Log { * @since 7 */ private static isLoggable(level: HiLog.LogLevel): boolean { + let buildModeName: string = BuildProfile.BUILD_MODE_NAME.toLowerCase(); + if (buildModeName == 'release' || buildModeName == 'profile') { + return level >= Log._logLevel && HiLog.isLoggable(DOMAIN, TAG, level); + } return HiLog.isLoggable(DOMAIN, TAG, level); } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/StringUtils.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/StringUtils.ets index a9344782075002c1968da4b8b23c982b9553b944..62c730aa6b35d907934f4035b38802681224a6fd 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/StringUtils.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/StringUtils.ets @@ -19,28 +19,28 @@ import util from '@ohos.util' * 默认字符串工具 */ export default class StringUtils { + static TEXT_ENCODER = new util.TextEncoder("utf-8"); + static TEXT_DECODER = util.TextDecoder.create('utf-8', { ignoreBOM : true }); + static stringToArrayBuffer(str: string): ArrayBuffer { if(str.length == 0){ return new ArrayBuffer(0); } - let textEncoder = new util.TextEncoder("utf-8"); - return textEncoder.encodeInto(str).buffer; + return StringUtils.TEXT_ENCODER.encodeInto(str).buffer; } static arrayBufferToString(buffer: ArrayBuffer): string { if (buffer.byteLength <= 0) { return ""; } - let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM : true }) - return textDecoder.decode(new Uint8Array(buffer)); + return StringUtils.TEXT_DECODER.decodeWithStream(new Uint8Array(buffer)); } static uint8ArrayToString(buffer: Uint8Array): string { if (buffer.length <= 0) { return ""; } - let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM : true }) - return textDecoder.decodeWithStream(buffer); + return StringUtils.TEXT_DECODER.decodeWithStream(buffer); } static isNotEmpty(str: string): boolean { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/TraceSection.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/TraceSection.ets index 3caaadea7aa0cb84be3542be9c4595139cd25af4..e74cbcce5f63e638a9cbac1e9cd59c693ca2b7a6 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/TraceSection.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/TraceSection.ets @@ -17,7 +17,7 @@ import hiTraceMeter from '@ohos.hiTraceMeter' export class TraceSection { - static taskId: number = 1; + static taskId: number = 0; private static cropSectionName(sectionName: string): string { return sectionName.length < 124 ? sectionName : sectionName.substring(0, 124) + "..."; @@ -28,12 +28,18 @@ export class TraceSection { * * @param sectionName The string to display as the section name in the trace. */ - public static begin(sectionName: string): void { - hiTraceMeter.startTrace(TraceSection.cropSectionName(sectionName), TraceSection.taskId++); + public static begin(sectionName: string): number { + TraceSection.taskId++; + hiTraceMeter.startTrace(TraceSection.cropSectionName(sectionName), TraceSection.taskId); + return TraceSection.taskId; } /** Wraps Trace.endSection. */ public static end(sectionName: string): void { hiTraceMeter.finishTrace(TraceSection.cropSectionName(sectionName), TraceSection.taskId); } + + public static endWithId(sectionName: string, id: number): void { + hiTraceMeter.finishTrace(TraceSection.cropSectionName(sectionName), id); + } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicView.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicView.ets index 63af526e5a30562a07806bc88117dda1d75a8fc2..89b999d7f0fb013c61d75c64ec5d6ecb05c50287 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicView.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicView.ets @@ -242,6 +242,10 @@ export struct DynamicView { @Builder buildNodeContainer() { NodeContainer(this.getParams(this.params, "nodeController")) .common_attrs() + .position({ + x: (this.params as Record)['left'] as number, + y: (this.params as Record)['top'] as number + }) } @Builder diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicViewJson.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicViewJson.ets index 1b332830cee9ffa620dd246ad92d4374c65039d0..28721b37056ed68bd92ad4d2c9b45a24e97a9569 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicViewJson.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicViewJson.ets @@ -15,6 +15,8 @@ import Any from '../../plugin/common/Any'; import { DVModel, DVModelParameters, DVModelEvents, DVModelChildren } from "./dynamicView"; +import Log from '../../util/Log'; +const TAG = "dynamicViewJson"; export function createDVModelFromJson(json: Object): DVModel { @@ -54,7 +56,7 @@ export function createDVModelFromJson(json: Object): DVModel { } if (typeof json !== 'object') { - console.error("createDVModelFromJson: input is not JSON"); + Log.e(TAG, "createDVModelFromJson: input is not JSON"); return new DVModel("", "", "", createChildrenFrom([])); } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/FlutterView.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/FlutterView.ets index 3f23984aeed09048c5851df89d4745b72d2cd97e..03bdbc5b0845e3347894977acf72f17f61b2a3ef 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/FlutterView.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/FlutterView.ets @@ -25,10 +25,11 @@ import Settings from '../embedding/ohos/Settings'; import ArrayList from '@ohos.util.ArrayList'; import { EmbeddingNodeController } from '../embedding/ohos/EmbeddingNodeController'; import PlatformView, { Params } from '../plugin/platform/PlatformView'; +import { JSON } from '@kit.ArkTS'; -const TAG = "FlutterView"; +const TAG = "FlutterViewTag"; -class ViewportMetrics { +export class ViewportMetrics { devicePixelRatio: number = 1.0; physicalWidth: number = 0; physicalHeight: number = 0; @@ -44,7 +45,7 @@ class ViewportMetrics { systemGestureInsetRight: number = 0; systemGestureInsetBottom: number = 0; systemGestureInsetLeft: number = 0; - physicalTouchSlop = -1; + physicalTouchSlop: number = -1; } export class PlatformViewParas { @@ -68,6 +69,7 @@ export class PlatformViewParas { } export class FlutterView { + private flutterEngine: FlutterEngine | null = null private id: string = "" private dVModel: DVModel = new DVModel("Stack", new DVModelParameters(), new DVModelEvents(), new DVModelChildren(), null); @@ -77,7 +79,7 @@ export class FlutterView { private viewportMetrics = new ViewportMetrics(); private displayInfo?: display.Display; private keyboardManager: KeyboardManager | null = null; - private mainWindow: window.Window + private mainWindow: window.Window | null = null; private mouseCursorPlugin?: MouseCursorPlugin; private uiContext?: UIContext | undefined; private settings?: Settings; @@ -93,7 +95,9 @@ export class FlutterView { constructor(viewId: string, context: Context) { this.id = viewId this.displayInfo = display.getDefaultDisplaySync(); - this.viewportMetrics.devicePixelRatio = this.displayInfo?.densityPixels + this.viewportMetrics.devicePixelRatio = this.displayInfo?.densityPixels; + this.viewportMetrics.physicalTouchSlop = 1.0 * this.displayInfo?.densityPixels; + this.mainWindow = FlutterManager.getInstance() .getWindowStage(FlutterManager.getInstance().getUIAbility(context)) .getMainWindowSync(); @@ -101,27 +105,30 @@ export class FlutterView { this.mainWindow?.on('windowSizeChange', this.windowSizeChangeCallback); this.mainWindow?.on('avoidAreaChange', this.avoidAreaChangeCallback); - this.mainWindow?.on('keyboardHeightChange', this.keyboardHeightChangeCallback); - this.mainWindow?.on('windowStatusChange', (data: window.WindowStatusType) => { - Log.i(TAG, "windowStatusChangeCallback " + JSON.stringify(data)); - FlutterManager.getInstance().getFullScreenListener().onScreenStateChanged(data); - this.onAreaChange(null); - }); + this.mainWindow?.on('windowStatusChange', this.windowStatusChangeCallback); } - private windowSizeChangeCallback= (data: window.Size) => { - Log.i(TAG, "windowSizeChangeCallback"); - this.onAreaChange(null); - } - private avoidAreaChangeCallback = (data: Any) => { - Log.i(TAG, "avoidAreaChangeCallback"); - this.onAreaChange(null); + private windowSizeChangeCallback = (data: window.Size) => { + Log.i(TAG, "windowSizeChangeCallback w:" + data.width + ", h:" + data.height); + if (this.isAttachedToFlutterEngine()) { + this.onAreaChange(null); + } } - private keyboardHeightChangeCallback = (data: number) => { - Log.i(TAG, "keyboardHeightChangeCallback"); - this.onAreaChange(null); + + private avoidAreaChangeCallback = (data: window.AvoidAreaOptions) => { + Log.i(TAG, "avoidAreaChangeCallback, type=" + data.type); + if (this.isAttachedToFlutterEngine()) { + this.onAreaChange(null); + } } + private windowStatusChangeCallback = (data: window.WindowStatusType) => { + Log.i(TAG, "windowStatusChangeCallback " + data); + if (this.isAttachedToFlutterEngine()) { + FlutterManager.getInstance().getFullScreenListener().onScreenStateChanged(data); + } + }; + getId(): string { return this.id } @@ -166,10 +173,11 @@ export class FlutterView { try { this.mainWindow?.off('windowSizeChange', this.windowSizeChangeCallback); this.mainWindow?.off('avoidAreaChange', this.avoidAreaChangeCallback); - this.mainWindow?.off('keyboardHeightChange', this.keyboardHeightChangeCallback); - this.mainWindow?.off('windowStatusChange'); + this.mainWindow?.off('windowStatusChange', this.windowStatusChangeCallback); } catch (e) { + Log.e(TAG, "mainWindow off error: " + JSON.stringify(e)); } + this.mainWindow = null; } attachToFlutterEngine(flutterEngine: FlutterEngine): void { @@ -194,7 +202,7 @@ export class FlutterView { this.flutterEngine?.getFlutterNapi()?.updateRefreshRate(this.displayInfo!.refreshRate) flutterEngine.getPlatformViewsController()?.attachToView(this); this.updateViewportMetrics() - let windowId = this.mainWindow?.getWindowProperties()?.id + let windowId = this.mainWindow?.getWindowProperties()?.id ?? 0 this.mouseCursorPlugin = new MouseCursorPlugin(windowId, this.flutterEngine?.getMouseCursorChannel()!); this.settings = new Settings(this.flutterEngine.getSettingsChannel()!); this.sendSettings(); @@ -206,6 +214,7 @@ export class FlutterView { detachFromFlutterEngine(): void { Log.i(TAG, "detachFromFlutterEngine"); + if (!this.isAttachedToFlutterEngine()) { Log.d(TAG, "FlutterView not attached to an engine. Not detaching."); return; @@ -257,17 +266,18 @@ export class FlutterView { this.viewportMetrics.physicalHeight = vp2px(newArea.height as number); } - // 根据是否全屏显示,设置标题栏高度 + // 根据是否全屏显示,设置标题栏高度(若全屏,则及时规避) if (this.checkFullScreen && FlutterManager.getInstance().getFullScreenListener().useFullScreen()) { // 全屏显示 - this.viewportMetrics.physicalViewPaddingTop = systemAvoidArea!.topRect.height - this.viewportMetrics.physicalViewPaddingBottom = navigationAvoidArea!.bottomRect.height - } else { // 非全屏显示 + this.viewportMetrics.physicalViewPaddingTop = systemAvoidArea?.topRect.height ?? 0; + this.viewportMetrics.physicalViewPaddingBottom = navigationAvoidArea?.bottomRect.height ?? 0; + } else { // 非全屏显示(保持规避效果) + // 顶部状态栏和底部导航栏规避为0,无平滑过渡效果 this.viewportMetrics.physicalViewPaddingTop = 0; this.viewportMetrics.physicalViewPaddingBottom = 0; } - this.viewportMetrics.physicalViewPaddingLeft = systemAvoidArea!.leftRect.width - this.viewportMetrics.physicalViewPaddingRight = systemAvoidArea!.rightRect.width + this.viewportMetrics.physicalViewPaddingLeft = systemAvoidArea?.leftRect.width ?? 0; + this.viewportMetrics.physicalViewPaddingRight = systemAvoidArea?.rightRect.width ?? 0; this.onKeyboardAreaChange() this.onGestureAreaChange() @@ -277,10 +287,10 @@ export class FlutterView { private onKeyboardAreaChange() { if (this.checkKeyboard) { let keyboardAvoidArea = this.mainWindow?.getWindowAvoidArea(window.AvoidAreaType.TYPE_KEYBOARD); - this.viewportMetrics.physicalViewInsetTop = keyboardAvoidArea!.topRect.height - this.viewportMetrics.physicalViewInsetLeft = keyboardAvoidArea!.leftRect.width - this.viewportMetrics.physicalViewInsetBottom = keyboardAvoidArea!.bottomRect.height - this.viewportMetrics.physicalViewInsetRight = keyboardAvoidArea!.rightRect.width + this.viewportMetrics.physicalViewInsetTop = keyboardAvoidArea?.topRect.height ?? 0 + this.viewportMetrics.physicalViewInsetLeft = keyboardAvoidArea?.leftRect.width ?? 0 + this.viewportMetrics.physicalViewInsetBottom = keyboardAvoidArea?.bottomRect.height ?? 0 + this.viewportMetrics.physicalViewInsetRight = keyboardAvoidArea?.rightRect.width ?? 0 } else { this.viewportMetrics.physicalViewInsetTop = 0 this.viewportMetrics.physicalViewInsetLeft = 0 @@ -292,10 +302,10 @@ export class FlutterView { private onGestureAreaChange() { if (this.checkGesture) { let gestureAvoidArea = this.mainWindow?.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM_GESTURE); - this.viewportMetrics.systemGestureInsetTop = gestureAvoidArea!.topRect.height - this.viewportMetrics.systemGestureInsetLeft = gestureAvoidArea!.leftRect.width - this.viewportMetrics.systemGestureInsetBottom = gestureAvoidArea!.bottomRect.height - this.viewportMetrics.systemGestureInsetRight = gestureAvoidArea!.rightRect.width + this.viewportMetrics.systemGestureInsetTop = gestureAvoidArea?.topRect.height ?? 0 + this.viewportMetrics.systemGestureInsetLeft = gestureAvoidArea?.leftRect.width ?? 0 + this.viewportMetrics.systemGestureInsetBottom = gestureAvoidArea?.bottomRect.height ?? 0 + this.viewportMetrics.systemGestureInsetRight = gestureAvoidArea?.rightRect.width ?? 0 } else { this.viewportMetrics.systemGestureInsetTop = 0 this.viewportMetrics.systemGestureInsetLeft = 0 @@ -370,6 +380,7 @@ export class FlutterView { setCheckGesture(check: boolean) { this.checkGesture = check } + } export interface FirstFrameListener { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/TextureRegistry.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/TextureRegistry.ets index fa79eb238c0781f3f23b690e00d08101a0969830..8568b03568fc13477531b401252ac1464973c265 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/TextureRegistry.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/TextureRegistry.ets @@ -21,6 +21,7 @@ export interface TextureRegistry { registerTexture(textureId: number): SurfaceTextureEntry; registerSurfaceTexture(receiver: image.ImageReceiver): SurfaceTextureEntry; registerPixelMap(pixelMap: PixelMap): number; + setTextureBackGroundPixelMap(textureId: number, pixelMap: PixelMap): void; unregisterTexture(textureId: number): void; onTrimMemory(level: number) : void; } diff --git a/shell/platform/ohos/library_loader.cpp b/shell/platform/ohos/library_loader.cpp index 231723d337abab42a477ee2cedee1e0113ba67f8..c6289c3017aec01345d07e934c572a1814774483 100644 --- a/shell/platform/ohos/library_loader.cpp +++ b/shell/platform/ohos/library_loader.cpp @@ -18,6 +18,7 @@ #include "napi/native_api.h" #include "napi_common.h" #include "ohos_xcomponent_adapter.h" +#include "ohos_logging.h" // namespace flutter { @@ -125,6 +126,9 @@ static napi_value Init(napi_env env, napi_value exports) { DECLARE_NAPI_FUNCTION( "nativeRegisterPixelMap", flutter::PlatformViewOHOSNapi::nativeRegisterPixelMap), + DECLARE_NAPI_FUNCTION( + "nativeSetTextureBackGroundPixelMap", + flutter::PlatformViewOHOSNapi::nativeSetTextureBackGroundPixelMap), }; @@ -132,7 +136,7 @@ static napi_value Init(napi_env env, napi_value exports) { napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); bool ret = flutter::XComponentAdapter::GetInstance()->Export(env, exports); if (!ret) { - LOGE("Init NAPI Failed."); + FML_DLOG(ERROR) << "Init NAPI Failed."; } else { FML_DLOG(INFO) << "Init NAPI Succeed."; } diff --git a/shell/platform/ohos/napi/platform_view_ohos_napi.cpp b/shell/platform/ohos/napi/platform_view_ohos_napi.cpp index 52fa7d7b52cbdc6b63ac15b12535ee833e078a1b..a3a3110cb0058c3af8301eb6e14a25b50ce8fbb7 100644 --- a/shell/platform/ohos/napi/platform_view_ohos_napi.cpp +++ b/shell/platform/ohos/napi/platform_view_ohos_napi.cpp @@ -31,6 +31,7 @@ #include "flutter/shell/platform/ohos/types.h" #include "unicode/uchar.h" #include "flutter/shell/platform/ohos/ohos_xcomponent_adapter.h" +#include "flutter/shell/platform/ohos/ohos_logging.h" #define OHOS_SHELL_HOLDER (reinterpret_cast(shell_holder)) namespace flutter { @@ -899,13 +900,13 @@ napi_value PlatformViewOHOSNapi::nativeSetViewportMetrics( LOGD("nativeSetViewportMetrics::systemGestureInsetLeft : %{public}ld", systemGestureInsetLeft); - int64_t physicalTouchSlop; - ret = napi_get_value_int64(env, args[16], &physicalTouchSlop); + double physicalTouchSlop; + ret = napi_get_value_double(env, args[16], &physicalTouchSlop); if (ret != napi_ok) { - LOGE("nativeSetViewportMetrics napi_get_value_int64 error"); + LOGE("nativeSetViewportMetrics napi_get_value_double error"); return nullptr; } - LOGD("nativeSetViewportMetrics::physicalTouchSlop : %{public}ld", + LOGD("nativeSetViewportMetrics::physicalTouchSlop : %{public}lf", physicalTouchSlop); std::vector displayFeaturesBounds; @@ -1528,6 +1529,23 @@ napi_value PlatformViewOHOSNapi::nativeRegisterPixelMap( return nullptr; } +napi_value PlatformViewOHOSNapi::nativeSetTextureBackGroundPixelMap( + napi_env env, + napi_callback_info info) +{ + FML_DLOG(INFO)<<"PlatformViewOHOSNapi::nativeSetTextureBackGroundPixelMap"; + size_t argc = 3; + napi_value args[3] = {nullptr}; + int64_t shell_holder; + int64_t textureId; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + NAPI_CALL(env, napi_get_value_int64(env, args[0], &shell_holder)); + NAPI_CALL(env, napi_get_value_int64(env, args[1], &textureId)); + NativePixelMap *nativePixelMap = OH_PixelMap_InitNativePixelMap(env, args[2]); + OHOS_SHELL_HOLDER->GetPlatformView()->SetExternalTextureBackGroundPixelMap(textureId, nativePixelMap); + return nullptr; +} + void PlatformViewOHOSNapi::SurfaceCreated(int64_t shell_holder, void* window) { auto native_window = fml::MakeRefCounted( static_cast(window)); diff --git a/shell/platform/ohos/napi/platform_view_ohos_napi.h b/shell/platform/ohos/napi/platform_view_ohos_napi.h index b91367ae88f7442984bbe5db6e3fedfbb91401e6..09d3424d9e08e0d65aae7bc51ead27b4ea34f542 100644 --- a/shell/platform/ohos/napi/platform_view_ohos_napi.h +++ b/shell/platform/ohos/napi/platform_view_ohos_napi.h @@ -171,6 +171,10 @@ class PlatformViewOHOSNapi { napi_env env, napi_callback_info info); + static napi_value nativeSetTextureBackGroundPixelMap( + napi_env env, + napi_callback_info info); + static napi_value nativeRegisterTexture( napi_env env, napi_callback_info info); diff --git a/shell/platform/ohos/napi_common.h b/shell/platform/ohos/napi_common.h index 43b2b3cbef7ebbd12ede9ccaf7509bc208e12d96..9837fa09eb23b31224af63fdde9789c509624ed2 100644 --- a/shell/platform/ohos/napi_common.h +++ b/shell/platform/ohos/napi_common.h @@ -22,22 +22,6 @@ #ifndef XComponentDemo_native_common_H #define XComponentDemo_native_common_H -#include -#define APP_LOG_DOMAIN 0x0000 -#define APP_LOG_TAG "XComFlutterOHOS_Native" -#define LOGI(...) \ - ((void)OH_LOG_Print(LOG_APP, LOG_INFO, APP_LOG_DOMAIN, APP_LOG_TAG, \ - __VA_ARGS__)) -#define LOGD(...) \ - ((void)OH_LOG_Print(LOG_APP, LOG_INFO, APP_LOG_DOMAIN, APP_LOG_TAG, \ - __VA_ARGS__)) -#define LOGW(...) \ - ((void)OH_LOG_Print(LOG_APP, LOG_WARN, APP_LOG_DOMAIN, APP_LOG_TAG, \ - __VA_ARGS__)) -#define LOGE(...) \ - ((void)OH_LOG_Print(LOG_APP, LOG_ERROR, APP_LOG_DOMAIN, APP_LOG_TAG, \ - __VA_ARGS__)) - #define NAPI_RETVAL_NOTHING #define GET_AND_THROW_LAST_ERROR(env) \ diff --git a/shell/platform/ohos/ohos_asset_provider.cpp b/shell/platform/ohos/ohos_asset_provider.cpp index 8cabce185ea2bd5b0ca89114493b473a11160a06..c7b60e2b15ed437b80beacd2bf842ebf6723b4df 100755 --- a/shell/platform/ohos/ohos_asset_provider.cpp +++ b/shell/platform/ohos/ohos_asset_provider.cpp @@ -17,6 +17,7 @@ #include #include #include "napi_common.h" +#include "ohos_logging.h" namespace flutter { @@ -127,12 +128,12 @@ std::unique_ptr OHOSAssetProvider::GetAsMapping( } std::string relativePath = dir_ + "/" + asset_name; - LOGE("GetAsMapping=%{public}s->%{public}s", asset_name.c_str(), + LOGD("GetAsMapping=%{public}s->%{public}s", asset_name.c_str(), relativePath.c_str()); RawFile* fileHandle = OH_ResourceManager_OpenRawFile(nativeResMgr, relativePath.c_str()); - LOGE("GetAsMapping=%{public}s->%{public}p", relativePath.c_str(), fileHandle); + LOGD("GetAsMapping=%{public}s->%{public}p", relativePath.c_str(), fileHandle); if (fileHandle == nullptr) { fileHandle = @@ -140,7 +141,7 @@ std::unique_ptr OHOSAssetProvider::GetAsMapping( LOGE("GetAsMapping2 ..fallback:%{public}s->%{public}p", asset_name.c_str(), fileHandle); } - LOGE("GetAsMappingend:%{public}p", fileHandle); + LOGD("GetAsMappingend:%{public}p", fileHandle); return fileHandle == nullptr ? nullptr : (std::make_unique(fileHandle)); diff --git a/shell/platform/ohos/ohos_external_texture_gl.cpp b/shell/platform/ohos/ohos_external_texture_gl.cpp index 4b41c9ede0ad045cce4c3b512645e1c388176d8d..59d505b4a6e3c13df83b498f09e330c69afe0e11 100755 --- a/shell/platform/ohos/ohos_external_texture_gl.cpp +++ b/shell/platform/ohos/ohos_external_texture_gl.cpp @@ -42,6 +42,7 @@ constexpr const char *EGL_GET_PLATFORM_DISPLAY_EXT = "eglGetPlatformDisplayEXT"; OHOSExternalTextureGL::OHOSExternalTextureGL(int64_t id, const std::shared_ptr& ohos_surface) : Texture(id), ohos_surface_(std::move(ohos_surface)), transform(SkMatrix::I()) { + state_ = AttachmentState::uninitialized; nativeImage_ = nullptr; backGroundNativeImage_ = nullptr; nativeWindow_ = nullptr; @@ -51,46 +52,72 @@ OHOSExternalTextureGL::OHOSExternalTextureGL(int64_t id, const std::shared_ptrGLContextMakeCurrent(); if (result->GetResult()) { FML_DLOG(INFO)<<"ResourceContextMakeCurrent successed"; glGenTextures(1, &texture_name_); - FML_DLOG(INFO) << "OHOSExternalTextureGL::Paint, glGenTextures texture_name_=" << texture_name_; + FML_DLOG(INFO) << "OHOSExternalTextureGL::Paint, glGenTextures texture_name_=" << texture_name_ << ", Id()=" << Id(); if (nativeImage_ == nullptr) { nativeImage_ = OH_NativeImage_Create(texture_name_, GL_TEXTURE_EXTERNAL_OES); if (nativeImage_ == nullptr) { - FML_DLOG(ERROR) << "Error with OH_NativeImage_Create"; + FML_LOG(ERROR) << "Error with OH_NativeImage_Create"; return; } nativeWindow_ = OH_NativeImage_AcquireNativeWindow(nativeImage_); if (nativeWindow_ == nullptr) { - FML_DLOG(ERROR) << "Error with OH_NativeImage_AcquireNativeWindow"; + FML_LOG(ERROR) << "Error with OH_NativeImage_AcquireNativeWindow"; return; } } int32_t ret = OH_NativeImage_AttachContext(nativeImage_, texture_name_); if (ret != 0) { - FML_DLOG(FATAL)<<"OHOSExternalTextureGL OH_NativeImage_AttachContext err code:"<< ret; + FML_LOG(ERROR) << "OHOSExternalTextureGL OH_NativeImage_AttachContext err code:" << ret; } state_ = AttachmentState::attached; } else { - FML_DLOG(FATAL)<<"ResourceContextMakeCurrent failed"; + FML_LOG(ERROR) << "ResourceContextMakeCurrent failed"; } } @@ -100,7 +127,7 @@ void OHOSExternalTextureGL::Paint(PaintContext& context, const SkSamplingOptions& sampling) { if (state_ == AttachmentState::detached) { - FML_DLOG(ERROR) << "OHOSExternalTextureGL::Paint"; + FML_LOG(ERROR) << "OHOSExternalTextureGL::Paint, the current status is detached"; return; } if (state_ == AttachmentState::uninitialized) { @@ -108,7 +135,7 @@ void OHOSExternalTextureGL::Paint(PaintContext& context, if (!freeze && new_frame_ready_ && pixelMap_ != nullptr) { ProducePixelMapToNativeImage(); Update(); - } + } new_frame_ready_ = false; } @@ -170,46 +197,77 @@ void OHOSExternalTextureGL::OnGrContextDestroyed() glDeleteTextures(1, &texture_name_); } state_ = AttachmentState::detached; + if (backGroundTextureName_ != 0) { + glDeleteTextures(1, &backGroundTextureName_); + } } void OHOSExternalTextureGL::MarkNewFrameAvailable() { FML_DLOG(INFO)<<" OHOSExternalTextureGL::MarkNewFrameAvailable"; new_frame_ready_ = true; - Update(); + if (pixelMap_ == nullptr) { + Update(); + } else { + FML_DLOG(INFO) << "pixelMap_ is nullptr, texture_name_=" << texture_name_; + } } void OHOSExternalTextureGL::OnTextureUnregistered() { - FML_DLOG(INFO)<<" OHOSExternalTextureGL::OnTextureUnregistered"; + FML_DLOG(INFO) << " OHOSExternalTextureGL::OnTextureUnregistered, texture_name_=" << texture_name_ + << ", Id()=" << Id() + << ", nativeImage_=" << nativeImage_ + << ", backGroundNativeImage_=" << backGroundNativeImage_; first_update_ = false; - OH_NativeImage_UnsetOnFrameAvailableListener(nativeImage_); - OH_NativeImage_Destroy(&nativeImage_); + if (nativeImage_ != nullptr) { + OH_NativeImage_UnsetOnFrameAvailableListener(nativeImage_); + OH_NativeImage_Destroy(&nativeImage_); + nativeImage_ = nullptr; + } + if (backGroundNativeImage_ != nullptr) { + OH_NativeImage_Destroy(&backGroundNativeImage_); + backGroundNativeImage_ = nullptr; + } } void OHOSExternalTextureGL::Update() { + FML_DLOG(INFO) << "OHOSExternalTextureGL::Update, texture_name_=" << texture_name_; + if (nativeImage_ == nullptr) { + FML_LOG(ERROR) << "Update, nativeImage_ is nullptr, texture_name_=" << texture_name_; + return; + } int32_t ret = OH_NativeImage_UpdateSurfaceImage(nativeImage_); if (ret != 0) { - FML_DLOG(FATAL)<<"OHOSExternalTextureGL OH_NativeImage_UpdateSurfaceImage err code:"<< ret; + FML_LOG(ERROR) << "OHOSExternalTextureGL OH_NativeImage_UpdateSurfaceImage err code:" << ret; return; } first_update_ = true; - UpdateTransform(); + UpdateTransform(nativeImage_); } void OHOSExternalTextureGL::Detach() { + FML_LOG(INFO) << "OHOSExternalTextureGL::Detach, texture_name_=" << texture_name_; + if (state_ != AttachmentState::attached) { + FML_LOG(ERROR) << "OHOSExternalTextureGL::Detach, the current status is not attached"; + return; + } OH_NativeImage_DetachContext(nativeImage_); + OH_NativeImage_DetachContext(backGroundNativeImage_); OH_NativeWindow_DestroyNativeWindow(nativeWindow_); + OH_NativeWindow_DestroyNativeWindow(backGroundNativeWindow_); + nativeWindow_ = nullptr; + backGroundNativeWindow_ = nullptr; } -void OHOSExternalTextureGL::UpdateTransform() +void OHOSExternalTextureGL::UpdateTransform(OH_NativeImage *image) { float m[16] = { 0.0f }; - int32_t ret = OH_NativeImage_GetTransformMatrixV2(nativeImage_, m); + int32_t ret = OH_NativeImage_GetTransformMatrixV2(image, m); if (ret != 0) { - FML_DLOG(FATAL)<<"OHOSExternalTextureGL OH_NativeImage_GetTransformMatrixV2 err code:"<< ret; + FML_LOG(ERROR) << "OHOSExternalTextureGL OH_NativeImage_GetTransformMatrixV2 err code:" << ret; } // transform ohos 4x4 matrix to skia 3x3 matrix SkScalar matrix3[] = { @@ -220,7 +278,7 @@ void OHOSExternalTextureGL::UpdateTransform() transform.set9(matrix3); SkMatrix inverted; if (!transform.invert(&inverted)) { - FML_LOG(FATAL) << "OHOSExternalTextureGL Invalid SurfaceTexture transformation matrix"; + FML_LOG(ERROR) << "OHOSExternalTextureGL Invalid SurfaceTexture transformation matrix"; } transform = inverted; } @@ -247,43 +305,56 @@ void OHOSExternalTextureGL::setBackground(int32_t width, int32_t height) if (backGroundNativeImage_ == nullptr) { backGroundNativeImage_ = OH_NativeImage_Create(backGroundTextureName_, GL_TEXTURE_EXTERNAL_OES); if (backGroundNativeImage_ == nullptr) { - FML_DLOG(ERROR) << "Error with OH_NativeImage_Create"; + FML_LOG(ERROR) << "Error with OH_NativeImage_Create"; return; } backGroundNativeWindow_ = OH_NativeImage_AcquireNativeWindow(backGroundNativeImage_); if (backGroundNativeWindow_ == nullptr) { - FML_DLOG(ERROR) << "Error with OH_NativeImage_AcquireNativeWindow"; + FML_LOG(ERROR) << "Error with OH_NativeImage_AcquireNativeWindow"; return; } } + int32_t ret = OH_NativeImage_AttachContext(backGroundNativeImage_, backGroundTextureName_); + if (ret != 0) { + FML_LOG(ERROR) << "OHOSExternalTextureGL::setBackground OH_NativeImage_AttachContext err code:" << ret; + } } else { - FML_DLOG(FATAL)<<"ResourceContextMakeCurrent failed"; + FML_LOG(ERROR) << "ResourceContextMakeCurrent failed"; } + if (backGroundPixelMap_ != nullptr) { + ProducePixelMapToBackGroundImage(); + } else { + ProduceColorToBackGroundImage(width, height); + } +} +void OHOSExternalTextureGL::ProduceColorToBackGroundImage(int32_t width, int32_t height) +{ + FML_DLOG(INFO) << "OHOSExternalTextureGL::ProduceColorToBackGroundImage"; int code = SET_BUFFER_GEOMETRY; int32_t ret = OH_NativeWindow_NativeWindowHandleOpt(backGroundNativeWindow_, code, width, height); if (ret != 0) { - FML_DLOG(ERROR) << "OHOSExternalTextureGL::setBackground OH_NativeWindow_NativeWindowHandleOpt err:" << ret; + FML_LOG(ERROR) << "OHOSExternalTextureGL::setBackground OH_NativeWindow_NativeWindowHandleOpt err:" << ret; return; } ret = OH_NativeWindow_NativeWindowRequestBuffer(backGroundNativeWindow_, &backGroundBuffer_, &backGroundFenceFd); if (ret != 0) { - FML_DLOG(ERROR) << "OHOSExternalTextureGL::setBackground OH_NativeWindow_NativeWindowRequestBuffer err:" << ret; + FML_LOG(ERROR) << "OHOSExternalTextureGL::setBackground OH_NativeWindow_NativeWindowRequestBuffer err:" << ret; return; } BufferHandle *handle = OH_NativeWindow_GetBufferHandleFromNative(backGroundBuffer_); void *mappedAddr = mmap(handle->virAddr, handle->size, PROT_READ | PROT_WRITE, MAP_SHARED, handle->fd, 0); if (mappedAddr == MAP_FAILED) { - FML_DLOG(FATAL)<<"OHOSExternalTextureGL::setBackground mmap failed"; + FML_LOG(ERROR)<<"OHOSExternalTextureGL::setBackground mmap failed"; return; } uint32_t* destAddr = static_cast(mappedAddr); uint32_t value = 0xFFFFFFFF; - for(int32_t x = 0; x < handle->width; x++) { + for (int32_t x = 0; x < handle->width; x++) { for (int32_t y = 0; y < handle->height; y++) { *destAddr++ = value; } @@ -292,38 +363,105 @@ void OHOSExternalTextureGL::setBackground(int32_t width, int32_t height) // munmap after use ret = munmap(mappedAddr, handle->size); if (ret == -1) { - FML_DLOG(FATAL)<<"OHOSExternalTextureGL in setBackground munmap failed"; + FML_LOG(ERROR)<<"OHOSExternalTextureGL in setBackground munmap failed"; return; } Region region{nullptr, 0}; ret = OH_NativeWindow_NativeWindowFlushBuffer(backGroundNativeWindow_, backGroundBuffer_, backGroundFenceFd, region); if (ret != 0) { - FML_DLOG(FATAL)<<"OHOSExternalTextureGL::setBackground OH_NativeWindow_NativeWindowFlushBuffer err:"<< ret; + FML_LOG(ERROR)<<"OHOSExternalTextureGL::setBackground OH_NativeWindow_NativeWindowFlushBuffer err:"<< ret; } + ret = OH_NativeImage_UpdateSurfaceImage(backGroundNativeImage_); + if (ret != 0) { + FML_LOG(ERROR)<<"OHOSExternalTextureGL::setBackground OH_NativeImage_UpdateSurfaceImage err code:"<< ret; + return; + } +} +void OHOSExternalTextureGL::ProducePixelMapToBackGroundImage() +{ + FML_DLOG(INFO) << "OHOSExternalTextureGL::ProducePixelMapToBackGroundImage"; + if (backGroundPixelMap_ == nullptr) { + FML_LOG(ERROR) << "backGroundPixelMap_ is nullptr"; + return; + } + int32_t ret = -1; + ret = OH_PixelMap_GetImageInfo(backGroundPixelMap_, &pixelMapInfo); + if (ret != 0) { + FML_LOG(ERROR) + << "OHOSExternalTextureGL::ProducePixelMapToBackGroundImage " + "OH_PixelMap_GetImageInfo err:" + << ret; + return; + } + int code = SET_BUFFER_GEOMETRY; + ret = OH_NativeWindow_NativeWindowHandleOpt(backGroundNativeWindow_, code, pixelMapInfo.width, pixelMapInfo.height); + if (ret != 0) { + FML_LOG(ERROR) + << "OHOSExternalTextureGL::ProducePixelMapToBackGroundImage " + "OH_NativeWindow_NativeWindowHandleOpt err:" + << ret; + return; + } + + int32_t usage = 0; + OH_NativeWindow_NativeWindowHandleOpt(backGroundNativeWindow_, GET_USAGE, &usage); + usage |= NATIVEBUFFER_USAGE_CPU_READ; + OH_NativeWindow_NativeWindowHandleOpt(backGroundNativeWindow_, SET_USAGE, usage); + + if (backGroundBuffer_ != nullptr) { + OH_NativeWindow_NativeWindowAbortBuffer(backGroundNativeWindow_, backGroundBuffer_); + backGroundBuffer_ = nullptr; + } + ret = OH_NativeWindow_NativeWindowRequestBuffer(backGroundNativeWindow_, &backGroundBuffer_, &backGroundFenceFd); + if (ret != 0) { + FML_LOG(ERROR) + << "OHOSExternalTextureGL::ProducePixelMapToBackGroundImage " + "OH_NativeWindow_NativeWindowRequestBuffer err:" + << ret; + return; + } + HandlePixelMapBuffer(backGroundPixelMap_, backGroundBuffer_); + Region region{nullptr, 0}; + ret = OH_NativeWindow_NativeWindowFlushBuffer(backGroundNativeWindow_, backGroundBuffer_, backGroundFenceFd, region); + if (ret != 0) { + FML_LOG(ERROR) + << "OHOSExternalTextureGL::ProducePixelMapToBackGroundImage " + "OH_NativeWindow_NativeWindowFlushBuffer err:" + << ret; + } ret = OH_NativeImage_UpdateSurfaceImage(backGroundNativeImage_); if (ret != 0) { - FML_DLOG(FATAL)<<"OHOSExternalTextureGL::setBackground OH_NativeImage_UpdateSurfaceImage err code:"<< ret; + FML_LOG(ERROR) + << "OHOSExternalTextureGL::ProducePixelMapToBackGroundImage " + "OH_NativeImage_UpdateSurfaceImage err code:" + << ret; + return; } + UpdateTransform(backGroundNativeImage_); } -void OHOSExternalTextureGL::HandlePixelMapBuffer() +void OHOSExternalTextureGL::HandlePixelMapBuffer(NativePixelMap* pixelMap, OHNativeWindowBuffer* buffer) { - BufferHandle *handle = OH_NativeWindow_GetBufferHandleFromNative(buffer_); + BufferHandle *handle = OH_NativeWindow_GetBufferHandleFromNative(buffer); + if (handle == nullptr) { + FML_LOG(ERROR) << "OHOSExternalTextureGL::HandlePixelMapBuffer, handle is nullptr."; + return; + } // get virAddr of bufferHandl by mmap sys interface uint32_t stride = handle->stride; FML_DLOG(INFO) << "OHOSExternalTextureGL stride:" << stride; void *mappedAddr = mmap(handle->virAddr, handle->size, PROT_READ | PROT_WRITE, MAP_SHARED, handle->fd, 0); if (mappedAddr == MAP_FAILED) { - FML_DLOG(FATAL)<<"OHOSExternalTextureGL mmap failed"; + FML_LOG(ERROR)<<"OHOSExternalTextureGL mmap failed"; return; } void *pixelAddr = nullptr; - int64_t ret = OH_PixelMap_AccessPixels(pixelMap_, &pixelAddr); + int64_t ret = OH_PixelMap_AccessPixels(pixelMap, &pixelAddr); if (ret != IMAGE_RESULT_SUCCESS) { - FML_DLOG(FATAL)<<"OHOSExternalTextureGL OH_PixelMap_AccessPixels err:"<< ret; + FML_LOG(ERROR)<<"OHOSExternalTextureGL OH_PixelMap_AccessPixels err:"<< ret; return; } @@ -347,31 +485,38 @@ void OHOSExternalTextureGL::HandlePixelMapBuffer() pixel += pixelMapInfo.width; } } - OH_PixelMap_UnAccessPixels(pixelMap_); + OH_PixelMap_UnAccessPixels(pixelMap); // munmap after use ret = munmap(mappedAddr, handle->size); if (ret == -1) { - FML_DLOG(FATAL)<<"OHOSExternalTextureGL munmap failed"; + FML_LOG(ERROR)<<"OHOSExternalTextureGL munmap failed"; return; } } void OHOSExternalTextureGL::ProducePixelMapToNativeImage() { + FML_DLOG(INFO) << "OHOSExternalTextureGL::ProducePixelMapToNativeImage, pixelMap_=" << pixelMap_; if (state_ == AttachmentState::detached) { - FML_DLOG(ERROR) << "OHOSExternalTextureGL AttachmentState err"; + FML_LOG(ERROR) << "OHOSExternalTextureGL AttachmentState err"; + return; + } + if (pixelMap_ == nullptr) { + FML_LOG(ERROR) << "pixelMap_ is nullptr"; return; } int32_t ret = -1; ret = OH_PixelMap_GetImageInfo(pixelMap_, &pixelMapInfo); if (ret != 0) { - FML_DLOG(ERROR) << "OHOSExternalTextureGL OH_PixelMap_GetImageInfo err:" << ret; + FML_LOG(ERROR) << "OHOSExternalTextureGL OH_PixelMap_GetImageInfo err:" << ret; + return; } int code = SET_BUFFER_GEOMETRY; ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, code, pixelMapInfo.width, pixelMapInfo.height); if (ret != 0) { - FML_DLOG(ERROR) << "OHOSExternalTextureGL OH_NativeWindow_NativeWindowHandleOpt err:" << ret; + FML_LOG(ERROR) << "OHOSExternalTextureGL OH_NativeWindow_NativeWindowHandleOpt err:" << ret; + return; } int32_t usage = 0; @@ -385,13 +530,14 @@ void OHOSExternalTextureGL::ProducePixelMapToNativeImage() } ret = OH_NativeWindow_NativeWindowRequestBuffer(nativeWindow_, &buffer_, &fenceFd); if (ret != 0) { - FML_DLOG(ERROR) << "OHOSExternalTextureGL OH_NativeWindow_NativeWindowRequestBuffer err:" << ret; + FML_LOG(ERROR) << "OHOSExternalTextureGL OH_NativeWindow_NativeWindowRequestBuffer err:" << ret; + return; } - HandlePixelMapBuffer(); + HandlePixelMapBuffer(pixelMap_, buffer_); Region region{nullptr, 0}; ret = OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow_, buffer_, fenceFd, region); if (ret != 0) { - FML_DLOG(FATAL)<<"OHOSExternalTextureGL OH_NativeWindow_NativeWindowFlushBuffer err:"<< ret; + FML_LOG(ERROR) << "OHOSExternalTextureGL OH_NativeWindow_NativeWindowFlushBuffer err:" << ret; } } @@ -442,4 +588,11 @@ void OHOSExternalTextureGL::DispatchPixelMap(NativePixelMap* pixelMap) } } +void OHOSExternalTextureGL::DispatchBackGroundPixelMap(NativePixelMap* pixelMap) +{ + if (pixelMap != nullptr) { + backGroundPixelMap_ = pixelMap; + } +} + } // namespace flutter \ No newline at end of file diff --git a/shell/platform/ohos/ohos_external_texture_gl.h b/shell/platform/ohos/ohos_external_texture_gl.h index fe9625514ea3c7299e72570a23a1ec2523efbf76..29d2e3eb9fb20a4aaaf54da90d992511ef7a3d80 100755 --- a/shell/platform/ohos/ohos_external_texture_gl.h +++ b/shell/platform/ohos/ohos_external_texture_gl.h @@ -65,6 +65,8 @@ class OHOSExternalTextureGL : public flutter::Texture { void DispatchPixelMap(NativePixelMap* pixelMap); + void DispatchBackGroundPixelMap(NativePixelMap* pixelMap); + private: void Attach(); @@ -72,19 +74,23 @@ class OHOSExternalTextureGL : public flutter::Texture { void Detach(); - void UpdateTransform(); + void UpdateTransform(OH_NativeImage *image); EGLDisplay GetPlatformEglDisplay(EGLenum platform, void *native_display, const EGLint *attrib_list); bool CheckEglExtension(const char *extensions, const char *extension); - void HandlePixelMapBuffer(); + void HandlePixelMapBuffer(NativePixelMap* pixelMap, OHNativeWindowBuffer* buffer); void ProducePixelMapToNativeImage(); + void ProduceColorToBackGroundImage(int32_t width, int32_t height); + + void ProducePixelMapToBackGroundImage(); + enum class AttachmentState { uninitialized, attached, detached }; - AttachmentState state_ = AttachmentState::uninitialized; + AttachmentState state_; bool new_frame_ready_ = false; @@ -104,6 +110,8 @@ class OHOSExternalTextureGL : public flutter::Texture { OHNativeWindowBuffer *backGroundBuffer_; + NativePixelMap* backGroundPixelMap_; + NativePixelMap* pixelMap_; ImageNative* lastImage_; diff --git a/shell/platform/ohos/ohos_image_generator.cpp b/shell/platform/ohos/ohos_image_generator.cpp index 8962dd80b80f1540a926398a478ffb8f2bd26ff8..2256ca2a237876f7312f5557eb6bd13843533b10 100755 --- a/shell/platform/ohos/ohos_image_generator.cpp +++ b/shell/platform/ohos/ohos_image_generator.cpp @@ -20,6 +20,7 @@ #include #include "third_party/skia/include/codec/SkCodecAnimation.h" +#include "ohos_logging.h" namespace flutter { diff --git a/shell/platform/ohos/ohos_logging.h b/shell/platform/ohos/ohos_logging.h new file mode 100644 index 0000000000000000000000000000000000000000..d1d275f04a939b99fb890f679828ddc7b03a978e --- /dev/null +++ b/shell/platform/ohos/ohos_logging.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * 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 + * + * http://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. + */ + +#ifndef OHOS_LOGGING_H +#define OHOS_LOGGING_H + +#include +#define APP_LOG_DOMAIN 0x0000 +#define APP_LOG_TAG "XComFlutterOHOS_Native" + +#define LOGD(...) \ + ((void)OH_LOG_Print(LOG_APP, LOG_DEBUG, APP_LOG_DOMAIN, APP_LOG_TAG, __VA_ARGS__)) + +#define LOGI(...) \ + ((void)OH_LOG_Print(LOG_APP, !(FML_LOG_IS_ON(INFO)) ? LOG_DEBUG : LOG_INFO, \ + APP_LOG_DOMAIN, APP_LOG_TAG, __VA_ARGS__)) + +#define LOGW(...) \ + ((void)OH_LOG_Print(LOG_APP, LOG_WARN, APP_LOG_DOMAIN, APP_LOG_TAG, __VA_ARGS__)) + +#define LOGE(...) \ + ((void)OH_LOG_Print(LOG_APP, LOG_ERROR, APP_LOG_DOMAIN, APP_LOG_TAG, __VA_ARGS__)) + +#endif // OHOS_LOGGING_H diff --git a/shell/platform/ohos/ohos_main.cpp b/shell/platform/ohos/ohos_main.cpp index 246dc4a778a9529e90a3d84cebfaf5f7ccb6c173..90b66207292d98d9c785b9fb4aa7ec73dd77e761 100644 --- a/shell/platform/ohos/ohos_main.cpp +++ b/shell/platform/ohos/ohos_main.cpp @@ -17,7 +17,6 @@ #include "flutter/fml/command_line.h" #include "flutter/fml/file.h" -#include "flutter/fml/logging.h" #include "flutter/fml/macros.h" #include "flutter/fml/message_loop.h" #include "flutter/fml/native_library.h" @@ -32,6 +31,7 @@ #include "flutter/shell/common/switches.h" #include "third_party/dart/runtime/include/dart_tools_api.h" #include "third_party/skia/include/core/SkFontMgr.h" +#include "ohos_logging.h" namespace flutter { @@ -145,7 +145,8 @@ napi_value OhosMain::Init(napi_env env, napi_callback_info info) { }; settings.log_message_callback = [](const std::string& tag, const std::string& message) { - LOGI("%{public}s %{public}s", tag.c_str(), message.c_str()); + // The logs output here are very important for The Dart VM and cannot be deleted or blocked. + LOGW("%{public}s settings log message: %{public}s", tag.c_str(), message.c_str()); }; if (!EnableTracingIfNecessary(settings)) { @@ -159,7 +160,7 @@ napi_value OhosMain::Init(napi_env env, napi_callback_info info) { g_flutter_main.reset(new OhosMain(settings)); // TODO : g_flutter_main->SetupObservatoryUriCallback(env); - LOGI("OhosMain::Init finished."); + LOGD("OhosMain::Init finished."); napi_value result; napi_create_int64(env, 0, &result); return result; diff --git a/shell/platform/ohos/ohos_shell_holder.cpp b/shell/platform/ohos/ohos_shell_holder.cpp index b70310845d4b1f6ec213ddba0f35cb7b694721c5..2cb763fc04889ce0342e708451dc485f04bfc023 100644 --- a/shell/platform/ohos/ohos_shell_holder.cpp +++ b/shell/platform/ohos/ohos_shell_holder.cpp @@ -20,7 +20,7 @@ #include "flutter/shell/common/thread_host.h" #include "flutter/shell/platform/ohos/ohos_display.h" -#include "flutter/fml/logging.h" +#include "flutter/shell/platform/ohos/ohos_logging.h" #include #include @@ -175,7 +175,6 @@ OHOSShellHolder::OHOSShellHolder( platform_view_ = weak_platform_view; FML_DCHECK(platform_view_); - is_valid_ = shell_ != nullptr; } OHOSShellHolder::OHOSShellHolder( @@ -196,17 +195,17 @@ OHOSShellHolder::OHOSShellHolder( FML_DCHECK(shell_->IsSetup()); FML_DCHECK(platform_view_); FML_DCHECK(thread_host_); - is_valid_ = shell_ != nullptr; } OHOSShellHolder::~OHOSShellHolder() { FML_LOG(INFO) << "MHN enter ~OHOSShellHolder()"; shell_.reset(); thread_host_.reset(); + shell_ = nullptr; } bool OHOSShellHolder::IsValid() const { - return is_valid_; + return shell_ != nullptr; } const flutter::Settings& OHOSShellHolder::GetSettings() const { @@ -219,9 +218,11 @@ std::unique_ptr OHOSShellHolder::Spawn( const std::string& libraryUrl, const std::string& initial_route, const std::vector& entrypoint_args) const { - FML_DCHECK(shell_ && shell_->IsSetup()) - << "A new Shell can only be spawned " + if (!IsValid()) { + FML_LOG(ERROR) << "A new Shell can only be spawned " "if the current Shell is properly constructed"; + return nullptr; + } fml::WeakPtr weak_platform_view; PlatformViewOHOS* ohos_platform_view = platform_view_.get(); @@ -269,7 +270,10 @@ fml::WeakPtr OHOSShellHolder::GetPlatformView() { } void OHOSShellHolder::NotifyLowMemoryWarning() { - FML_DCHECK(shell_); + if (!IsValid()) { + FML_LOG(ERROR) << "NotifyLowMemoryWarning, Is Not Valid"; + return; + } shell_->NotifyLowMemoryWarning(); } @@ -281,7 +285,7 @@ void OHOSShellHolder::Launch( FML_DLOG(INFO) << "Launch ...entrypoint<<" << entrypoint << ",libraryUrl:" << libraryUrl; if (!IsValid()) { - FML_DLOG(ERROR) << "Is Not Valid"; + FML_LOG(ERROR) << "Launch, Is Not Valid"; return; } diff --git a/shell/platform/ohos/ohos_shell_holder.h b/shell/platform/ohos/ohos_shell_holder.h index a1d83ab44db5c253960832fa061e4bf4219847be..4a87730862c4ded233a6f08ace2154ae3eba29cb 100644 --- a/shell/platform/ohos/ohos_shell_holder.h +++ b/shell/platform/ohos/ohos_shell_holder.h @@ -65,7 +65,6 @@ class OHOSShellHolder { const std::shared_ptr& GetPlatformMessageHandler() const { - LOGI("GetPlatformMessageHandler LOGI"); return shell_->GetPlatformMessageHandler(); } @@ -79,7 +78,6 @@ class OHOSShellHolder { fml::WeakPtr platform_view_; std::shared_ptr thread_host_; std::unique_ptr shell_; - bool is_valid_ = false; uint64_t next_pointer_flow_id_ = 0; std::unique_ptr assetProvider_; diff --git a/shell/platform/ohos/ohos_surface_software.cpp b/shell/platform/ohos/ohos_surface_software.cpp index b5c9271596b959574ed4d01d1d78df0d6e5d03a7..5a3fb5ca3e1f367a0e87294015e09a0854e88ce5 100644 --- a/shell/platform/ohos/ohos_surface_software.cpp +++ b/shell/platform/ohos/ohos_surface_software.cpp @@ -16,10 +16,10 @@ #include "flutter/shell/platform/ohos/ohos_surface_software.h" #include #include -#include "flutter/fml/logging.h" #include "napi_common.h" #include "third_party/skia/include/core/SkImage.h" #include "types.h" +#include "ohos_logging.h" namespace flutter { diff --git a/shell/platform/ohos/ohos_xcomponent_adapter.cpp b/shell/platform/ohos/ohos_xcomponent_adapter.cpp index 4fa9afc7ab967f70c16377ca8170c5942d6c222c..d1b62dcd70290cd31a49024b51ec846a1bed569d 100644 --- a/shell/platform/ohos/ohos_xcomponent_adapter.cpp +++ b/shell/platform/ohos/ohos_xcomponent_adapter.cpp @@ -16,7 +16,9 @@ #include "ohos_xcomponent_adapter.h" #include "flutter/shell/platform/ohos/napi/platform_view_ohos_napi.h" #include "types.h" +#include "ohos_logging.h" #include + namespace flutter { bool g_isMouseLeftActive = false; diff --git a/shell/platform/ohos/platform_view_ohos.cpp b/shell/platform/ohos/platform_view_ohos.cpp index b6a03a0d5156e979a9217dd7d6442e74a2a9ad78..34c6193685561fe188732da54c4ac73dbff8a5b6 100644 --- a/shell/platform/ohos/platform_view_ohos.cpp +++ b/shell/platform/ohos/platform_view_ohos.cpp @@ -14,7 +14,6 @@ */ #include "flutter/shell/platform/ohos/platform_view_ohos.h" -#include "flutter/fml/logging.h" #include "flutter/fml/make_copyable.h" #include "flutter/lib/ui/window/viewport_metrics.h" #include "flutter/shell/common/shell_io_manager.h" @@ -23,6 +22,7 @@ #include "flutter/shell/platform/ohos/ohos_surface_software.h" #include "flutter/shell/platform/ohos/platform_message_response_ohos.h" #include "napi_common.h" +#include "ohos_logging.h" #include "ohos_external_texture_gl.h" #include @@ -439,6 +439,12 @@ void PlatformViewOHOS::RegisterExternalTextureByImage( } } +PointerDataDispatcherMaker PlatformViewOHOS::GetDispatcherMaker() { + return [](DefaultPointerDataDispatcher::Delegate& delegate) { + return std::make_unique(delegate); + }; +} + uint64_t PlatformViewOHOS::RegisterExternalTexture(int64_t texture_id) { uint64_t surface_id = 0; @@ -467,6 +473,7 @@ uint64_t PlatformViewOHOS::RegisterExternalTexture(int64_t texture_id) FML_DLOG(ERROR) << "Error with OH_NativeImage_GetSurfaceId"; return surface_id; } + external_texture_gl_[texture_id] = ohos_external_gl; RegisterTexture(ohos_external_gl); } return surface_id; @@ -502,6 +509,7 @@ void PlatformViewOHOS::OnNativeImageFrameAvailable(void *data) void PlatformViewOHOS::UnRegisterExternalTexture(int64_t texture_id) { + FML_DLOG(INFO) << "PlatformViewOHOS::UnRegisterExternalTexture, texture_id=" << texture_id; external_texture_gl_.erase(texture_id); UnregisterTexture(texture_id); std::map::iterator it = contextDatas_.find(texture_id); @@ -537,6 +545,16 @@ void PlatformViewOHOS::RegisterExternalTextureByPixelMap(int64_t texture_id, Nat } } +void PlatformViewOHOS::SetExternalTextureBackGroundPixelMap(int64_t texture_id, NativePixelMap* pixelMap) +{ + if (ohos_context_->RenderingApi() == OHOSRenderingAPI::kOpenGLES) { + auto iter = external_texture_gl_.find(texture_id); + if (iter != external_texture_gl_.end()) { + iter->second->DispatchBackGroundPixelMap(pixelMap); + } + } +} + void PlatformViewOHOS::OnTouchEvent(const std::shared_ptr touchPacketString, int size) { return napi_facade_->FlutterViewOnTouchEvent(touchPacketString, size); diff --git a/shell/platform/ohos/platform_view_ohos.h b/shell/platform/ohos/platform_view_ohos.h index 8e070854afc2f19e8d798ea575c64f66d24ab025..cccbc048466eca73b9c5dd5ec496d5b7d36fb6fa 100644 --- a/shell/platform/ohos/platform_view_ohos.h +++ b/shell/platform/ohos/platform_view_ohos.h @@ -95,9 +95,14 @@ class PlatformViewOHOS final : public PlatformView { uint64_t RegisterExternalTexture(int64_t texture_id); void RegisterExternalTextureByPixelMap(int64_t texture_id, NativePixelMap* pixelMap); + + void SetExternalTextureBackGroundPixelMap(int64_t texture_id, NativePixelMap* pixelMap); void UnRegisterExternalTexture(int64_t texture_id); + // |PlatformView| + PointerDataDispatcherMaker GetDispatcherMaker() override; + // |PlatformView| void LoadDartDeferredLibrary( intptr_t loading_unit_id, diff --git a/shell/platform/ohos/vsync_waiter_ohos.cpp b/shell/platform/ohos/vsync_waiter_ohos.cpp index 595b4273a4f4db60d7da31b1362394669854bc9f..c181b283348660b62e9756368a088ac30e2a8294 100644 --- a/shell/platform/ohos/vsync_waiter_ohos.cpp +++ b/shell/platform/ohos/vsync_waiter_ohos.cpp @@ -14,8 +14,9 @@ */ #include "flutter/shell/platform/ohos/vsync_waiter_ohos.h" -#include "flutter/fml/logging.h" #include "napi_common.h" +#include "ohos_logging.h" +#include namespace flutter { @@ -23,6 +24,8 @@ static std::atomic_uint g_refresh_rate_ = 60; const char* flutterSyncName = "flutter_connect"; +thread_local bool VsyncWaiterOHOS::firstCall = true; + VsyncWaiterOHOS::VsyncWaiterOHOS(const flutter::TaskRunners& task_runners) : VsyncWaiter(task_runners) { vsyncHandle = @@ -53,6 +56,11 @@ void VsyncWaiterOHOS::AwaitVSync() { } void VsyncWaiterOHOS::OnVsyncFromOHOS(long long timestamp, void* data) { + if (VsyncWaiterOHOS::firstCall) { + int ret = OH_QoS_SetThreadQoS(QoS_Level::QOS_USER_INTERACTIVE); + FML_DLOG(INFO) << "qos set VsyncWaiterOHOS result:" << ret << ",tid:" << gettid(); + VsyncWaiterOHOS::firstCall = false; + } int64_t frame_nanos = static_cast(timestamp); auto frame_time = fml::TimePoint::FromEpochDelta( fml::TimeDelta::FromNanoseconds(frame_nanos)); diff --git a/shell/platform/ohos/vsync_waiter_ohos.h b/shell/platform/ohos/vsync_waiter_ohos.h index 5650a7f64cf11421e001a119f322af57291a9255..e9aac66c852b888b7495c27d0843fe777e3af169 100644 --- a/shell/platform/ohos/vsync_waiter_ohos.h +++ b/shell/platform/ohos/vsync_waiter_ohos.h @@ -31,6 +31,7 @@ class VsyncWaiterOHOS final : public VsyncWaiter { ~VsyncWaiterOHOS() override; private: + thread_local static bool firstCall; // |VsyncWaiter| void AwaitVSync() override;