diff --git a/.github/workflows/code_linter.yml b/.github/workflows/code_linter.yml index 0e82ba0c6c..160049f328 100644 --- a/.github/workflows/code_linter.yml +++ b/.github/workflows/code_linter.yml @@ -46,8 +46,8 @@ jobs: inplace: True - uses: EndBug/add-and-commit@v4 with: - author_name: openkraken-bot - author_email: openkraken@list.alibaba-inc.com + author_name: openwebf-bot + author_email: openwebf@openwebf.com message: 'Committing clang-format changes' env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/example_build.yml b/.github/workflows/example_build.yml index 78d5a372a3..625de0835a 100644 --- a/.github/workflows/example_build.yml +++ b/.github/workflows/example_build.yml @@ -10,7 +10,7 @@ on: env: nodeVersion: "16" cmakeVersion: "3.22.x" - flutterVersion: "2.8.1" + flutterVersion: "3.0.4" jobs: build_android-app_in_macos: @@ -35,7 +35,7 @@ jobs: - name: android app build run: | - cd kraken/ + cd webf/ flutter pub get cd example/ flutter build apk --release @@ -60,7 +60,7 @@ jobs: - name: ios app build run: | - cd kraken/ + cd webf/ flutter pub get cd example/ flutter build ios --release --no-codesign @@ -86,7 +86,7 @@ jobs: - name: macos app build run: | - cd kraken/ + cd webf/ flutter pub get cd example/ flutter build macos --release @@ -115,7 +115,7 @@ jobs: - run: flutter doctor -v - name: linux app build run: | - cd kraken/ + cd webf/ flutter pub get cd example/ flutter build linux --release diff --git a/.github/workflows/integration_test_flutter.yml b/.github/workflows/integration_test_flutter.yml index c9cc6def3e..652781f7b4 100644 --- a/.github/workflows/integration_test_flutter.yml +++ b/.github/workflows/integration_test_flutter.yml @@ -5,12 +5,12 @@ on: [workflow_dispatch, pull_request] env: nodeVersion: "16" cmakeVersion: "3.22.x" - flutterVersion: "2.8.1" + flutterVersion: "3.0.4" # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: setup: - runs-on: macos-latest + runs-on: macos-12 outputs: matrix: ${{ steps.matrix.outputs.value }} steps: @@ -20,7 +20,7 @@ jobs: JSON=$(node -e "console.log(JSON.stringify(require('./integration_tests/spec_group.json').map(j=>j.name)))") echo "::set-output name=value::$(echo $JSON)" build_bridge: - runs-on: macos-latest + runs-on: macos-12 steps: - uses: actions/checkout@v2 - uses: actions/setup-node@v2 @@ -35,8 +35,34 @@ jobs: with: name: macos_bridge_binary path: bridge/build/macos/ + + bridge_unit_test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v2 + with: + node-version: ${{ env.nodeVersion }} + - uses: jwlawson/actions-setup-cmake@v1.11 + with: + cmake-version: ${{ env.cmakeVersion }} + - run: npm i + - run: ENABLE_ASAN=true npm run build:bridge:linux + - run: node scripts/run_bridge_unit_test.js + + webf_unit_test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: subosito/flutter-action@v2 + with: + flutter-version: ${{ env.flutterVersion }} + - run: flutter config --enable-macos-desktop + - run: flutter doctor -v + - run: cd webf && flutter test + integration_test: - runs-on: macos-latest + runs-on: macos-12 needs: [ setup, build_bridge ] strategy: fail-fast: false @@ -69,7 +95,7 @@ jobs: if: steps.test.outcome != 'success' run: exit 1 plugin_test: - runs-on: macos-latest + runs-on: macos-12 needs: [ build_bridge ] steps: - uses: actions/checkout@v2 diff --git a/.github/workflows/publish_to_dart_dev.yml b/.github/workflows/publish_to_dart_dev.yml index 7eb84e3ecd..76f766607c 100644 --- a/.github/workflows/publish_to_dart_dev.yml +++ b/.github/workflows/publish_to_dart_dev.yml @@ -1,4 +1,4 @@ -name: Publish Kraken To pub.dev +name: Publish WebF To pub.dev on: release: @@ -66,7 +66,7 @@ jobs: name: ios_binary path: bridge/build/ios/ build_android_binary: - runs-on: ubuntu-latest + runs-on: macos-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-node@v2 @@ -99,8 +99,6 @@ jobs: flutter-version: ${{ env.flutterVersion }} - name: NPM INSTALL run: npm install - - name: Set up nightly version - run: node scripts/set_up_nightly_release.js - uses: actions/download-artifact@v2 with: name: linux_binary @@ -118,7 +116,7 @@ jobs: name: android_binary path: bridge/build/android/ - name: Prepare distribute binaries - run: node scripts/pre_publish_kraken.js + run: node scripts/pre_publish_webf.js - name: Publish uses: k-paxian/dart-package-publisher@master with: @@ -126,5 +124,5 @@ jobs: force: true flutter: true skipTests: true - relativePath: ./kraken + relativePath: ./webf diff --git a/.github/workflows/publish_to_dart_dev_nightly.yml b/.github/workflows/publish_to_dart_dev_nightly.yml index 11ad4d90eb..4123d4cf7b 100644 --- a/.github/workflows/publish_to_dart_dev_nightly.yml +++ b/.github/workflows/publish_to_dart_dev_nightly.yml @@ -1,4 +1,4 @@ -name: Publish Kraken To pub.dev Nightly +name: Publish WebF To pub.dev Nightly on: schedule: diff --git a/.github/workflows/sync_to_release.yml b/.github/workflows/sync_to_release.yml deleted file mode 100644 index 1aa6d86b5a..0000000000 --- a/.github/workflows/sync_to_release.yml +++ /dev/null @@ -1,22 +0,0 @@ -name: Sync main code to release branch - -on: - push: - branches: - - main - -# Sync main code to release/flutter-2.2.x branch. -jobs: - flutter_2_5_x: - runs-on: ubuntu-latest - timeout-minutes: 30 - steps: - - uses: actions/checkout@v2 - with: - ref: 'release/flutter-2.5.x' - - name: Opening pull request - uses: tretuna/sync-branches@1.2.0 - with: - GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} - FROM_BRANCH: 'main' - TO_BRANCH: 'release/flutter-2.5.x' diff --git a/bridge/CMakeLists.txt b/bridge/CMakeLists.txt index 554f66eb8f..278f27be01 100644 --- a/bridge/CMakeLists.txt +++ b/bridge/CMakeLists.txt @@ -49,8 +49,8 @@ execute_process( ) string(REGEX REPLACE "\n$" "" DART_SDK "${DART_SDK}") -list(APPEND KRAKEN_PUBLIC_HEADERS - ${CMAKE_CURRENT_SOURCE_DIR}/include/kraken_bridge.h +list(APPEND WEBF_PUBLIC_HEADERS + ${CMAKE_CURRENT_SOURCE_DIR}/include/webf_bridge.h ) set(QUICKJS_PUBLIC_HEADERS @@ -81,9 +81,9 @@ if (DEFINED PLATFORM) endif() list(APPEND BRIDGE_SOURCE - kraken_bridge.cc - ${CMAKE_CURRENT_SOURCE_DIR}/include/kraken_bridge.h - ${CMAKE_CURRENT_SOURCE_DIR}/include/kraken_foundation.h + webf_bridge.cc + ${CMAKE_CURRENT_SOURCE_DIR}/include/webf_bridge.h + ${CMAKE_CURRENT_SOURCE_DIR}/include/webf_foundation.h ${CMAKE_CURRENT_SOURCE_DIR}/include/dart_methods.h foundation/logging.cc foundation/logging.h @@ -152,7 +152,7 @@ list(APPEND BRIDGE_INCLUDE set(BINDING_DIR ${CMAKE_CURRENT_LIST_DIR}/bindings) if ($ENV{WEBF_JS_ENGINE} MATCHES "quickjs") - add_compile_options(-DKRAKEN_QUICK_JS_ENGINE=1) + add_compile_options(-DWEBF_QUICK_JS_ENGINE=1) execute_process( COMMAND cat ${CMAKE_CURRENT_SOURCE_DIR}/third_party/quickjs/VERSION @@ -296,7 +296,7 @@ if ($ENV{WEBF_JS_ENGINE} MATCHES "quickjs") endif () list(APPEND PUBLIC_HEADER - include/kraken_bridge.h + include/webf_bridge.h ) add_library(webf SHARED ${BRIDGE_SOURCE}) @@ -335,7 +335,7 @@ if ($ENV{WEBF_JS_ENGINE} MATCHES "quickjs") endif () endif () -### KrakenStatic +### webfStatic target_include_directories(webf_static PRIVATE ${BRIDGE_INCLUDE} ${CMAKE_CURRENT_SOURCE_DIR} PUBLIC ./include) @@ -389,7 +389,7 @@ if (${CMAKE_SYSTEM_NAME} MATCHES "iOS") MACOSX_FRAMEWORK_IDENTIFIER com.openwebf.webf-bridge MACOSX_FRAMEWORK_BUNDLE_VERSION 1.0 MACOSX_FRAMEWORK_SHORT_VERSION_STRING 1.0 - PUBLIC_HEADER ${KRAKEN_PUBLIC_HEADERS} + PUBLIC_HEADER ${WEBF_PUBLIC_HEADERS} ) # If quickjs is static, there will be no quickjs.framework any more. diff --git a/bridge/bindings/qjs/bom/blob.cc b/bridge/bindings/qjs/bom/blob.cc index 65f6a28fb6..0ce5f76329 100644 --- a/bridge/bindings/qjs/bom/blob.cc +++ b/bridge/bindings/qjs/bom/blob.cc @@ -1,11 +1,12 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "blob.h" #include "dart_methods.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { std::once_flag kBlobInitOnceFlag; @@ -277,4 +278,4 @@ int32_t BlobInstance::size() { uint8_t* BlobInstance::bytes() { return _data.data(); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/bom/blob.h b/bridge/bindings/qjs/bom/blob.h index 360364b6dd..8387d8021b 100644 --- a/bridge/bindings/qjs/bom/blob.h +++ b/bridge/bindings/qjs/bom/blob.h @@ -1,13 +1,14 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_BLOB_H -#define KRAKENBRIDGE_BLOB_H +#ifndef BRIDGE_BLOB_H +#define BRIDGE_BLOB_H #include "bindings/qjs/host_class.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { class BlobBuilder; class BlobInstance; @@ -73,6 +74,6 @@ class BlobBuilder { std::vector _data; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_BLOB_H +#endif // BRIDGE_BLOB_H diff --git a/bridge/bindings/qjs/bom/console.cc b/bridge/bindings/qjs/bom/console.cc index 8fdc02f4b6..35c13fab18 100644 --- a/bridge/bindings/qjs/bom/console.cc +++ b/bridge/bindings/qjs/bom/console.cc @@ -1,11 +1,12 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "console.h" #include "foundation/logging.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { JSValue print(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) { std::stringstream stream; @@ -31,7 +32,7 @@ JSValue print(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* arg } void bindConsole(ExecutionContext* context) { - QJS_GLOBAL_BINDING_FUNCTION(context, print, "__kraken_print__", 2); + QJS_GLOBAL_BINDING_FUNCTION(context, print, "__webf_print__", 2); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/bom/console.h b/bridge/bindings/qjs/bom/console.h index 433189ccaa..60cc7feff7 100644 --- a/bridge/bindings/qjs/bom/console.h +++ b/bridge/bindings/qjs/bom/console.h @@ -1,16 +1,17 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_CONSOLE_H -#define KRAKENBRIDGE_CONSOLE_H +#ifndef BRIDGE_CONSOLE_H +#define BRIDGE_CONSOLE_H #include "bindings/qjs/executing_context.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindConsole(ExecutionContext* context); } -#endif // KRAKENBRIDGE_CONSOLE_H +#endif // BRIDGE_CONSOLE_H diff --git a/bridge/bindings/qjs/bom/console_test.cc b/bridge/bindings/qjs/bom/console_test.cc index b3fcceec18..e20b14114c 100644 --- a/bridge/bindings/qjs/bom/console_test.cc +++ b/bridge/bindings/qjs/bom/console_test.cc @@ -1,34 +1,35 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "console.h" #include "gtest/gtest.h" -#include "kraken_test_env.h" #include "page.h" +#include "webf_test_env.h" std::once_flag kGlobalClassIdFlag; TEST(Console, rawPrintShouldWork) { static bool logExecuted = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logExecuted = true; EXPECT_STREQ(message.c_str(), "1234"); }; auto bridge = TEST_init(); - const char* code = "__kraken_print__('1234', 'info')"; + const char* code = "__webf_print__('1234', 'info')"; bridge->evaluateScript(code, strlen(code), "vm://", 0); EXPECT_EQ(logExecuted, true); } TEST(Console, log) { static bool logExecuted = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { - KRAKEN_LOG(VERBOSE) << message; + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + WEBF_LOG(VERBOSE) << message; logExecuted = true; }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; exit(1); }); const char* code = "console.log(1234);"; diff --git a/bridge/bindings/qjs/bom/dom_timer_coordinator.cc b/bridge/bindings/qjs/bom/dom_timer_coordinator.cc index 6623d046e0..e3a9e2a8d3 100644 --- a/bridge/bindings/qjs/bom/dom_timer_coordinator.cc +++ b/bridge/bindings/qjs/bom/dom_timer_coordinator.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "dom_timer_coordinator.h" @@ -7,10 +8,10 @@ #include "timer.h" #if UNIT_TEST -#include "kraken_test_env.h" +#include "webf_test_env.h" #endif -namespace kraken::binding::qjs { +namespace webf::binding::qjs { static void handleTimerCallback(DOMTimer* timer, const char* errmsg) { auto* context = static_cast(JS_GetContextOpaque(timer->ctx())); @@ -79,4 +80,4 @@ void DOMTimerCoordinator::trace(JSRuntime* rt, JSValue val, JS_MarkFunc* mark_fu } } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/bom/dom_timer_coordinator.h b/bridge/bindings/qjs/bom/dom_timer_coordinator.h index c8229620f3..6e48491331 100644 --- a/bridge/bindings/qjs/bom/dom_timer_coordinator.h +++ b/bridge/bindings/qjs/bom/dom_timer_coordinator.h @@ -1,15 +1,16 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_BINDINGS_QJS_BOM_DOM_TIMER_COORDINATOR_H_ -#define KRAKENBRIDGE_BINDINGS_QJS_BOM_DOM_TIMER_COORDINATOR_H_ +#ifndef BRIDGE_BINDINGS_QJS_BOM_DOM_TIMER_COORDINATOR_H_ +#define BRIDGE_BINDINGS_QJS_BOM_DOM_TIMER_COORDINATOR_H_ #include #include #include -namespace kraken::binding::qjs { +namespace webf::binding::qjs { class ExecutionContext; class DOMTimer; @@ -36,6 +37,6 @@ class DOMTimerCoordinator { std::vector m_abandonedTimers; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_BINDINGS_QJS_BOM_DOM_TIMER_COORDINATOR_H_ +#endif // BRIDGE_BINDINGS_QJS_BOM_DOM_TIMER_COORDINATOR_H_ diff --git a/bridge/bindings/qjs/bom/location.cc b/bridge/bindings/qjs/bom/location.cc index 7d253a10eb..3d779868d6 100644 --- a/bridge/bindings/qjs/bom/location.cc +++ b/bridge/bindings/qjs/bom/location.cc @@ -1,12 +1,13 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "location.h" #include #include "dart_methods.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { JSValue Location::reload(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) { auto* location = static_cast(JS_GetOpaque(this_val, ExecutionContext::kHostObjectClassId)); @@ -20,4 +21,4 @@ JSValue Location::reload(JSContext* ctx, JSValue this_val, int argc, JSValue* ar return JS_NULL; } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/bom/location.h b/bridge/bindings/qjs/bom/location.h index e21a26b73d..dbc0a26d71 100644 --- a/bridge/bindings/qjs/bom/location.h +++ b/bridge/bindings/qjs/bom/location.h @@ -1,14 +1,15 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_LOCATION_H -#define KRAKENBRIDGE_LOCATION_H +#ifndef BRIDGE_LOCATION_H +#define BRIDGE_LOCATION_H #include "bindings/qjs/executing_context.h" #include "bindings/qjs/host_object.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { class Location : public HostObject { public: @@ -21,6 +22,6 @@ class Location : public HostObject { DEFINE_FUNCTION(reload, 0); }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_LOCATION_H +#endif // BRIDGE_LOCATION_H diff --git a/bridge/bindings/qjs/bom/performance.cc b/bridge/bindings/qjs/bom/performance.cc index ef32ba004a..de7eaf6350 100644 --- a/bridge/bindings/qjs/bom/performance.cc +++ b/bridge/bindings/qjs/bom/performance.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "performance.h" @@ -8,7 +9,7 @@ #define PERFORMANCE_ENTRY_NONE_UNIQUE_ID -1024 -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindPerformance(ExecutionContext* context) { auto* performance = Performance::instance(context); @@ -410,7 +411,7 @@ double getMeasureTotalDuration(const std::vector& measu return duration / 1000; } -JSValue Performance::__kraken_navigation_summary__(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) { +JSValue Performance::__webf_navigation_summary__(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) { auto* performance = static_cast(JS_GetOpaque(this_val, ExecutionContext::kHostObjectClassId)); JSValue exception = JS_NULL; performance->measureSummary(&exception); @@ -579,4 +580,4 @@ Rendering: %.*fms #endif -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/bom/performance.h b/bridge/bindings/qjs/bom/performance.h index 0e7c9ab870..5cfe46b92a 100644 --- a/bridge/bindings/qjs/bom/performance.h +++ b/bridge/bindings/qjs/bom/performance.h @@ -1,9 +1,10 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_PERFORMANCE_H -#define KRAKENBRIDGE_PERFORMANCE_H +#ifndef BRIDGE_PERFORMANCE_H +#define BRIDGE_PERFORMANCE_H #if ENABLE_PROFILE #define PERF_WIDGET_CREATION_COST "widget_creation_cost" @@ -122,7 +123,7 @@ #include "bindings/qjs/host_object.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindPerformance(ExecutionContext* context); @@ -193,7 +194,7 @@ class Performance : public HostObject { static JSValue measure(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv); #if ENABLE_PROFILE - static JSValue __kraken_navigation_summary__(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv); + static JSValue __webf_navigation_summary__(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv); void measureSummary(JSValue* exception); #endif @@ -217,10 +218,10 @@ class Performance : public HostObject { DEFINE_FUNCTION(measure, 4); #if ENABLE_PROFILE - DEFINE_FUNCTION(__kraken_navigation_summary__, 0); + DEFINE_FUNCTION(__webf_navigation_summary__, 0); #endif }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_PERFORMANCE_H +#endif // BRIDGE_PERFORMANCE_H diff --git a/bridge/bindings/qjs/bom/screen.cc b/bridge/bindings/qjs/bom/screen.cc index b8ac2ce642..5a31b108a0 100644 --- a/bridge/bindings/qjs/bom/screen.cc +++ b/bridge/bindings/qjs/bom/screen.cc @@ -1,10 +1,11 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "screen.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindScreen(ExecutionContext* context) { auto* screen = new Screen(context); @@ -53,4 +54,4 @@ IMPL_PROPERTY_GETTER(Screen, availHeight)(JSContext* ctx, JSValue this_val, int return JS_NewFloat64(ctx, screen->height); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/bom/screen.h b/bridge/bindings/qjs/bom/screen.h index b454f94727..b302f545bf 100644 --- a/bridge/bindings/qjs/bom/screen.h +++ b/bridge/bindings/qjs/bom/screen.h @@ -1,15 +1,16 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_SCREEN_H -#define KRAKENBRIDGE_SCREEN_H +#ifndef BRIDGE_SCREEN_H +#define BRIDGE_SCREEN_H #include "bindings/qjs/executing_context.h" #include "bindings/qjs/host_object.h" #include "dart_methods.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { class Screen : public HostObject { public: @@ -24,8 +25,8 @@ class Screen : public HostObject { void bindScreen(ExecutionContext* context); -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs class screen {}; -#endif // KRAKENBRIDGE_SCREEN_H +#endif // BRIDGE_SCREEN_H diff --git a/bridge/bindings/qjs/bom/timer.cc b/bridge/bindings/qjs/bom/timer.cc index 88a3e73d31..db99071355 100644 --- a/bridge/bindings/qjs/bom/timer.cc +++ b/bridge/bindings/qjs/bom/timer.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "timer.h" @@ -8,10 +9,10 @@ #include "dart_methods.h" #if UNIT_TEST -#include "kraken_test_env.h" +#include "webf_test_env.h" #endif -namespace kraken::binding::qjs { +namespace webf::binding::qjs { DOMTimer::DOMTimer(JSValue callback) : m_callback(callback) {} @@ -224,4 +225,4 @@ void bindTimer(ExecutionContext* context) { QJS_GLOBAL_BINDING_FUNCTION(context, clearTimeout, "clearTimeout", 1); QJS_GLOBAL_BINDING_FUNCTION(context, clearTimeout, "clearInterval", 1); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/bom/timer.h b/bridge/bindings/qjs/bom/timer.h index 23cb6a9b98..07691f8662 100644 --- a/bridge/bindings/qjs/bom/timer.h +++ b/bridge/bindings/qjs/bom/timer.h @@ -1,15 +1,16 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_TIMER_H -#define KRAKENBRIDGE_TIMER_H +#ifndef BRIDGE_TIMER_H +#define BRIDGE_TIMER_H #include "bindings/qjs/executing_context.h" #include "bindings/qjs/garbage_collected.h" #include "dom_timer_coordinator.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { class DOMTimer : public GarbageCollected { public: @@ -35,6 +36,6 @@ class DOMTimer : public GarbageCollected { void bindTimer(ExecutionContext* context); -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_TIMER_H +#endif // BRIDGE_TIMER_H diff --git a/bridge/bindings/qjs/bom/timer_test.cc b/bridge/bindings/qjs/bom/timer_test.cc index 7261b2f4e7..4aa9550225 100644 --- a/bridge/bindings/qjs/bom/timer_test.cc +++ b/bridge/bindings/qjs/bom/timer_test.cc @@ -1,16 +1,17 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "gtest/gtest.h" -#include "kraken_bridge.h" -#include "kraken_test_env.h" #include "page.h" +#include "webf_bridge.h" +#include "webf_test_env.h" TEST(Timer, setTimeout) { auto bridge = TEST_init(); - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { static int logIdx = 0; switch (logIdx) { case 0: @@ -43,7 +44,7 @@ console.log('1234'); TEST(Timer, clearTimeout) { auto bridge = TEST_init(); - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) {}; + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) {}; std::string code = R"( function getCachedData() { diff --git a/bridge/bindings/qjs/bom/window.cc b/bridge/bindings/qjs/bom/window.cc index dabc8addd7..23deab65a2 100644 --- a/bridge/bindings/qjs/bom/window.cc +++ b/bridge/bindings/qjs/bom/window.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "window.h" @@ -9,7 +10,7 @@ #include "bindings/qjs/qjs_patch.h" #include "dart_methods.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { std::once_flag kWindowInitOnceFlag; @@ -118,7 +119,7 @@ JSValue Window::requestAnimationFrame(JSContext* ctx, JSValue this_val, int argc // Flutter backend implements check #if FLUTTER_BACKEND if (getDartMethod()->flushUICommand == nullptr) { - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_flush_ui_command__': dart method (flushUICommand) is not registered."); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_flush_ui_command__': dart method (flushUICommand) is not registered."); } // Flush all pending ui messages. getDartMethod()->flushUICommand(); @@ -258,4 +259,4 @@ DocumentInstance* WindowInstance::document() { return m_context->m_document; } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/bom/window.h b/bridge/bindings/qjs/bom/window.h index 9d796e002f..67656a08bc 100644 --- a/bridge/bindings/qjs/bom/window.h +++ b/bridge/bindings/qjs/bom/window.h @@ -1,15 +1,16 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_WINDOW_H -#define KRAKENBRIDGE_WINDOW_H +#ifndef BRIDGE_WINDOW_H +#define BRIDGE_WINDOW_H #include "bindings/qjs/bom/location.h" #include "bindings/qjs/dom/event_target.h" #include "bindings/qjs/executing_context.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindWindow(ExecutionContext* context); @@ -80,6 +81,6 @@ class WindowInstance : public EventTargetInstance { friend ExecutionContext; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_WINDOW_H +#endif // BRIDGE_WINDOW_H diff --git a/bridge/bindings/qjs/bom/window_test.cc b/bridge/bindings/qjs/bom/window_test.cc index cbc25fdf00..a3d3d7d707 100644 --- a/bridge/bindings/qjs/bom/window_test.cc +++ b/bridge/bindings/qjs/bom/window_test.cc @@ -1,21 +1,22 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "window.h" #include "gtest/gtest.h" -#include "kraken_test_env.h" #include "page.h" +#include "webf_test_env.h" TEST(Window, instanceofEventTarget) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "true"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -29,7 +30,7 @@ TEST(Window, instanceofEventTarget) { TEST(Window, requestAnimationFrame) { auto bridge = TEST_init(); - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { EXPECT_STREQ(message.c_str(), "456"); }; + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { EXPECT_STREQ(message.c_str(), "456"); }; std::string code = R"( requestAnimationFrame(() => { @@ -44,7 +45,7 @@ requestAnimationFrame(() => { TEST(Window, cancelAnimationFrame) { auto bridge = TEST_init(); - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { abort(); }; + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { abort(); }; std::string code = R"( let id = requestAnimationFrame(() => { @@ -61,7 +62,7 @@ TEST(Window, postMessage) { { auto bridge = TEST_init(); static bool logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "{\"data\":1234} "); }; @@ -84,7 +85,7 @@ window.postMessage({ TEST(Window, location) { auto bridge = TEST_init(); static bool logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "true true"); }; diff --git a/bridge/bindings/qjs/dom/all_collection.cc b/bridge/bindings/qjs/dom/all_collection.cc index dcb1891c6b..bca4d6c89b 100644 --- a/bridge/bindings/qjs/dom/all_collection.cc +++ b/bridge/bindings/qjs/dom/all_collection.cc @@ -1,10 +1,11 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "all_collection.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { JSValue AllCollection::item(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) { if (argc < 1) { @@ -75,4 +76,4 @@ IMPL_PROPERTY_GETTER(AllCollection, length)(JSContext* ctx, JSValue this_val, in return JS_NewUint32(ctx, collection->m_nodes.size()); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/all_collection.h b/bridge/bindings/qjs/dom/all_collection.h index 1a6374334b..0eb5d28d15 100644 --- a/bridge/bindings/qjs/dom/all_collection.h +++ b/bridge/bindings/qjs/dom/all_collection.h @@ -1,14 +1,15 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_ALL_COLLECTION_H -#define KRAKENBRIDGE_ALL_COLLECTION_H +#ifndef BRIDGE_ALL_COLLECTION_H +#define BRIDGE_ALL_COLLECTION_H #include "bindings/qjs/host_object.h" #include "node.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { class AllCollection : public HostObject { public: @@ -26,6 +27,6 @@ class AllCollection : public HostObject { std::vector m_nodes; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_ALL_COLLECTION_H +#endif // BRIDGE_ALL_COLLECTION_H diff --git a/bridge/bindings/qjs/dom/comment_node.cc b/bridge/bindings/qjs/dom/comment_node.cc index 62274c1ed6..d66731722c 100644 --- a/bridge/bindings/qjs/dom/comment_node.cc +++ b/bridge/bindings/qjs/dom/comment_node.cc @@ -1,12 +1,13 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "comment_node.h" #include "document.h" -#include "kraken_bridge.h" +#include "webf_bridge.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { std::once_flag kCommentInitFlag; @@ -46,4 +47,4 @@ CommentInstance::CommentInstance(Comment* comment) : NodeInstance(comment, NodeT m_context->uiCommandBuffer()->addCommand(m_eventTargetId, UICommand::createComment, nativeEventTarget); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/comment_node.h b/bridge/bindings/qjs/dom/comment_node.h index 42d35329c7..cdda4520c1 100644 --- a/bridge/bindings/qjs/dom/comment_node.h +++ b/bridge/bindings/qjs/dom/comment_node.h @@ -1,13 +1,14 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_COMMENT_NODE_H -#define KRAKENBRIDGE_COMMENT_NODE_H +#ifndef BRIDGE_COMMENT_NODE_H +#define BRIDGE_COMMENT_NODE_H #include "node.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindCommentNode(ExecutionContext* context); @@ -41,6 +42,6 @@ class CommentInstance : public NodeInstance { friend Comment; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_COMMENT_NODE_H +#endif // BRIDGE_COMMENT_NODE_H diff --git a/bridge/bindings/qjs/dom/css_property_list.h b/bridge/bindings/qjs/dom/css_property_list.h index a4cf27faf3..646ebb3135 100644 --- a/bridge/bindings/qjs/dom/css_property_list.h +++ b/bridge/bindings/qjs/dom/css_property_list.h @@ -1,14 +1,15 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_BINDINGS_QJS_DOM_CSS_PROPERTY_LIST_H_ -#define KRAKENBRIDGE_BINDINGS_QJS_DOM_CSS_PROPERTY_LIST_H_ +#ifndef BRIDGE_BINDINGS_QJS_DOM_CSS_PROPERTY_LIST_H_ +#define BRIDGE_BINDINGS_QJS_DOM_CSS_PROPERTY_LIST_H_ #include #include -namespace kraken { +namespace webf { std::unordered_map cssPropertyList{{"accentColor", true}, {"additiveSymbols", true}, @@ -430,6 +431,6 @@ std::unordered_map cssPropertyList{{"accentColor", true}, {"zIndex", true}, {"zoom", true}}; -} // namespace kraken +} // namespace webf -#endif // KRAKENBRIDGE_BINDINGS_QJS_DOM_CSS_PROPERTY_LIST_H_ +#endif // BRIDGE_BINDINGS_QJS_DOM_CSS_PROPERTY_LIST_H_ diff --git a/bridge/bindings/qjs/dom/custom_event.cc b/bridge/bindings/qjs/dom/custom_event.cc index 2fa39bc93b..e0b319d4d8 100644 --- a/bridge/bindings/qjs/dom/custom_event.cc +++ b/bridge/bindings/qjs/dom/custom_event.cc @@ -1,14 +1,15 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "custom_event.h" #include "bindings/qjs/qjs_patch.h" -#include "kraken_bridge.h" +#include "webf_bridge.h" #include -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindCustomEvent(ExecutionContext* context) { auto* constructor = CustomEvent::instance(context); @@ -88,4 +89,4 @@ CustomEventInstance::CustomEventInstance(CustomEvent* jsCustomEvent, NativeCusto m_detail.value(newDetail); JS_FreeValue(m_ctx, newDetail); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/custom_event.h b/bridge/bindings/qjs/dom/custom_event.h index 80a1b09ce5..56f9f0f14a 100644 --- a/bridge/bindings/qjs/dom/custom_event.h +++ b/bridge/bindings/qjs/dom/custom_event.h @@ -1,13 +1,14 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_CUSTOM_EVENT_H -#define KRAKENBRIDGE_CUSTOM_EVENT_H +#ifndef BRIDGE_CUSTOM_EVENT_H +#define BRIDGE_CUSTOM_EVENT_H #include "event.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindCustomEvent(ExecutionContext* context); @@ -45,6 +46,6 @@ class CustomEventInstance : public EventInstance { friend CustomEvent; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_CUSTOM_EVENT_H +#endif // BRIDGE_CUSTOM_EVENT_H diff --git a/bridge/bindings/qjs/dom/custom_event_test.cc b/bridge/bindings/qjs/dom/custom_event_test.cc index 1f9825483a..fe92a6d4c8 100644 --- a/bridge/bindings/qjs/dom/custom_event_test.cc +++ b/bridge/bindings/qjs/dom/custom_event_test.cc @@ -1,21 +1,22 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "event_target.h" #include "gtest/gtest.h" -#include "kraken_test_env.h" #include "page.h" +#include "webf_test_env.h" TEST(CustomEvent, instanceofEvent) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "true"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); diff --git a/bridge/bindings/qjs/dom/document.cc b/bridge/bindings/qjs/dom/document.cc index 459029c9b9..88a799495a 100644 --- a/bridge/bindings/qjs/dom/document.cc +++ b/bridge/bindings/qjs/dom/document.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "document.h" @@ -32,7 +33,7 @@ #include "events/.gen/popstate_event.h" #include "events/touch_event.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void traverseNode(NodeInstance* node, TraverseHandler handler) { bool shouldExit = handler(node); @@ -609,4 +610,4 @@ void DocumentInstance::trace(JSRuntime* rt, JSValue val, JS_MarkFunc* mark_func) } } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/document.h b/bridge/bindings/qjs/dom/document.h index 3555adecd0..b6cff01d3a 100644 --- a/bridge/bindings/qjs/dom/document.h +++ b/bridge/bindings/qjs/dom/document.h @@ -1,16 +1,17 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_DOCUMENT_H -#define KRAKENBRIDGE_DOCUMENT_H +#ifndef BRIDGE_DOCUMENT_H +#define BRIDGE_DOCUMENT_H #include "element.h" #include "frame_request_callback_collection.h" #include "node.h" #include "script_animation_controller.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindDocument(ExecutionContext* context); @@ -108,6 +109,6 @@ class DocumentInstance : public NodeInstance { friend ExecutionContext; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_DOCUMENT_H +#endif // BRIDGE_DOCUMENT_H diff --git a/bridge/bindings/qjs/dom/document_fragment.cc b/bridge/bindings/qjs/dom/document_fragment.cc index 6979a12b7d..6d898a91ac 100644 --- a/bridge/bindings/qjs/dom/document_fragment.cc +++ b/bridge/bindings/qjs/dom/document_fragment.cc @@ -1,12 +1,13 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "document_fragment.h" #include "document.h" -#include "kraken_bridge.h" +#include "webf_bridge.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindDocumentFragment(ExecutionContext* context) { auto* constructor = DocumentFragment::instance(context); @@ -34,4 +35,4 @@ DocumentFragmentInstance::DocumentFragmentInstance(DocumentFragment* fragment) : setNodeFlag(DocumentFragmentInstance::NodeFlag::IsDocumentFragment); m_context->uiCommandBuffer()->addCommand(m_eventTargetId, UICommand::createDocumentFragment, nativeEventTarget); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/document_fragment.h b/bridge/bindings/qjs/dom/document_fragment.h index 5b0e3c40a7..5356000546 100644 --- a/bridge/bindings/qjs/dom/document_fragment.h +++ b/bridge/bindings/qjs/dom/document_fragment.h @@ -1,13 +1,14 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_DOCUMENT_FRAGMENT_H -#define KRAKENBRIDGE_DOCUMENT_FRAGMENT_H +#ifndef BRIDGE_DOCUMENT_FRAGMENT_H +#define BRIDGE_DOCUMENT_FRAGMENT_H #include "node.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindDocumentFragment(ExecutionContext* context); @@ -30,6 +31,6 @@ class DocumentFragmentInstance : public NodeInstance { DocumentFragmentInstance(DocumentFragment* fragment); }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_DOCUMENT_FRAGMENT_H +#endif // BRIDGE_DOCUMENT_FRAGMENT_H diff --git a/bridge/bindings/qjs/dom/document_test.cc b/bridge/bindings/qjs/dom/document_test.cc index a6bc30f0ac..841c12deaa 100644 --- a/bridge/bindings/qjs/dom/document_test.cc +++ b/bridge/bindings/qjs/dom/document_test.cc @@ -1,21 +1,22 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "event_target.h" #include "gtest/gtest.h" -#include "kraken_test_env.h" #include "page.h" +#include "webf_test_env.h" TEST(Document, createTextNode) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "
"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -34,12 +35,12 @@ TEST(Document, createTextNode) { TEST(Document, instanceofNode) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "true true true"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -50,9 +51,9 @@ TEST(Document, instanceofNode) { } TEST(Document, createElementShouldWorkWithMultipleContext) { - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) {}; + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) {}; - kraken::KrakenPage* bridge1; + webf::WebFPage* bridge1; const char* code = "(() => { let img = document.createElement('img'); document.body.appendChild(img); })();"; diff --git a/bridge/bindings/qjs/dom/element.cc b/bridge/bindings/qjs/dom/element.cc index 662739f1e5..cf3533d354 100644 --- a/bridge/bindings/qjs/dom/element.cc +++ b/bridge/bindings/qjs/dom/element.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "element.h" @@ -11,10 +12,10 @@ #include "text_node.h" #if UNIT_TEST -#include "kraken_test_env.h" +#include "webf_test_env.h" #endif -namespace kraken::binding::qjs { +namespace webf::binding::qjs { std::once_flag kElementInitOnceFlag; @@ -30,7 +31,7 @@ bool isJavaScriptExtensionElementInstance(ExecutionContext* context, JSValue ins auto* elementInstance = static_cast(JS_GetOpaque(instance, Element::classId())); std::string tagName = elementInstance->getRegisteredTagName(); - // Special case for kraken official plugins. + // Special case for webf official plugins. if (tagName == "video" || tagName == "iframe") return true; @@ -897,4 +898,4 @@ IMPL_PROPERTY_GETTER(BoundingClientRect, left)(JSContext* ctx, JSValue this_val, return JS_NewFloat64(ctx, boundingClientRect->m_nativeBoundingClientRect->left); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/element.h b/bridge/bindings/qjs/dom/element.h index 0e3d64ab82..cb7c64a9c7 100644 --- a/bridge/bindings/qjs/dom/element.h +++ b/bridge/bindings/qjs/dom/element.h @@ -1,9 +1,10 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_ELEMENT_H -#define KRAKENBRIDGE_ELEMENT_H +#ifndef BRIDGE_ELEMENT_H +#define BRIDGE_ELEMENT_H #include #include "bindings/qjs/garbage_collected.h" @@ -11,7 +12,7 @@ #include "node.h" #include "style_declaration.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindElement(ExecutionContext* context); @@ -195,6 +196,6 @@ class BoundingClientRect : public HostObject { NativeBoundingClientRect* m_nativeBoundingClientRect{nullptr}; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_ELEMENT_H +#endif // BRIDGE_ELEMENT_H diff --git a/bridge/bindings/qjs/dom/element_test.cc b/bridge/bindings/qjs/dom/element_test.cc index 5a6040d6a2..17a7d87f8a 100644 --- a/bridge/bindings/qjs/dom/element_test.cc +++ b/bridge/bindings/qjs/dom/element_test.cc @@ -1,21 +1,22 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "event_target.h" #include "gtest/gtest.h" -#include "kraken_test_env.h" #include "page.h" +#include "webf_test_env.h" TEST(Element, setAttribute) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "1234"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -32,12 +33,12 @@ TEST(Element, setAttribute) { TEST(Element, getAttribute) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "helloworld"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -60,9 +61,9 @@ TEST(Element, getAttribute) { TEST(Element, setAttributeWithHTML) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; }; + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -76,12 +77,12 @@ TEST(Element, setAttributeWithHTML) { TEST(Element, style) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "true false"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -93,12 +94,12 @@ TEST(Element, style) { TEST(Element, instanceofNode) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "true"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -114,12 +115,12 @@ TEST(Element, instanceofNode) { TEST(Element, instanceofEventTarget) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "true"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -133,16 +134,16 @@ TEST(Element, instanceofEventTarget) { } TEST(Element, stringifyBoundingClientRect) { - using namespace kraken::binding::qjs; + using namespace webf::binding::qjs; bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "{\"x\":10,\"y\":20,\"width\":30,\"height\":40,\"top\":10,\"right\":20,\"bottom\":30,\"left\":40}"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); diff --git a/bridge/bindings/qjs/dom/elements/image_element.cc b/bridge/bindings/qjs/dom/elements/image_element.cc index 99f9aa9c4e..16ac11a664 100644 --- a/bridge/bindings/qjs/dom/elements/image_element.cc +++ b/bridge/bindings/qjs/dom/elements/image_element.cc @@ -1,12 +1,13 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "image_element.h" #include "bindings/qjs/qjs_patch.h" #include "page.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { ImageElement::ImageElement(ExecutionContext* context) : Element(context) { JS_SetPrototype(m_ctx, m_prototypeObject, Element::instance(m_context)->prototype()); @@ -117,4 +118,4 @@ bool ImageElementInstance::dispatchEvent(EventInstance* event) { return result; } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/elements/image_element.h b/bridge/bindings/qjs/dom/elements/image_element.h index 469e9383bb..4a3f0130c3 100644 --- a/bridge/bindings/qjs/dom/elements/image_element.h +++ b/bridge/bindings/qjs/dom/elements/image_element.h @@ -1,13 +1,14 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_IMAGE_ELEMENT_H -#define KRAKENBRIDGE_IMAGE_ELEMENT_H +#ifndef BRIDGE_IMAGE_ELEMENT_H +#define BRIDGE_IMAGE_ELEMENT_H #include "bindings/qjs/dom/element.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindImageElement(ExecutionContext* context); @@ -43,6 +44,6 @@ class ImageElementInstance : public ElementInstance { friend ImageElement; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_IMAGE_ELEMENTT_H +#endif // BRIDGE_IMAGE_ELEMENTT_H diff --git a/bridge/bindings/qjs/dom/elements/template_element.cc b/bridge/bindings/qjs/dom/elements/template_element.cc index 6194249641..0fab56dae8 100644 --- a/bridge/bindings/qjs/dom/elements/template_element.cc +++ b/bridge/bindings/qjs/dom/elements/template_element.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "template_element.h" @@ -7,7 +8,7 @@ #include "bindings/qjs/qjs_patch.h" #include "page.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { TemplateElement::TemplateElement(ExecutionContext* context) : Element(context) { JS_SetPrototype(m_ctx, m_prototypeObject, Element::instance(m_context)->prototype()); @@ -37,4 +38,4 @@ void TemplateElementInstance::trace(JSRuntime* rt, JSValue val, JS_MarkFunc* mar ElementInstance::trace(rt, val, mark_func); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/elements/template_element.h b/bridge/bindings/qjs/dom/elements/template_element.h index c22558fa5d..8bc4bacce1 100644 --- a/bridge/bindings/qjs/dom/elements/template_element.h +++ b/bridge/bindings/qjs/dom/elements/template_element.h @@ -1,14 +1,15 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_TEMPLATE_ELEMENT_H -#define KRAKENBRIDGE_TEMPLATE_ELEMENT_H +#ifndef BRIDGE_TEMPLATE_ELEMENT_H +#define BRIDGE_TEMPLATE_ELEMENT_H #include "bindings/qjs/dom/document_fragment.h" #include "bindings/qjs/dom/element.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindTemplateElement(ExecutionContext* context); class TemplateElementInstance; @@ -41,6 +42,6 @@ class TemplateElementInstance : public ElementInstance { friend TemplateElement; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_TEMPLATE_ELEMENTT_H +#endif // BRIDGE_TEMPLATE_ELEMENTT_H diff --git a/bridge/bindings/qjs/dom/event.cc b/bridge/bindings/qjs/dom/event.cc index cc5d3b0805..db2a70212d 100644 --- a/bridge/bindings/qjs/dom/event.cc +++ b/bridge/bindings/qjs/dom/event.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "event.h" @@ -7,9 +8,9 @@ #include "bindings/qjs/qjs_patch.h" #include "custom_event.h" #include "event_target.h" -#include "kraken_bridge.h" +#include "webf_bridge.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { std::once_flag kEventInitOnceFlag; @@ -246,4 +247,4 @@ void EventInstance::finalizer(JSRuntime* rt, JSValue val) { delete event; } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/event.h b/bridge/bindings/qjs/dom/event.h index 334d422171..cab749cc2c 100644 --- a/bridge/bindings/qjs/dom/event.h +++ b/bridge/bindings/qjs/dom/event.h @@ -1,13 +1,14 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_EVENT_H -#define KRAKENBRIDGE_EVENT_H +#ifndef BRIDGE_EVENT_H +#define BRIDGE_EVENT_H #include "bindings/qjs/host_class.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { #define EVENT_CLICK "click" #define EVENT_INPUT "input" @@ -167,6 +168,6 @@ class EventInstance : public Instance { friend Event; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_EVENT_H +#endif // BRIDGE_EVENT_H diff --git a/bridge/bindings/qjs/dom/event_listener_map.cc b/bridge/bindings/qjs/dom/event_listener_map.cc index 55cac80bfa..ba77834667 100644 --- a/bridge/bindings/qjs/dom/event_listener_map.cc +++ b/bridge/bindings/qjs/dom/event_listener_map.cc @@ -1,10 +1,11 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "event_listener_map.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { static bool addListenerToVector(EventListenerVector* vector, JSValue callback) { if (std::find_if(vector->begin(), vector->end(), [&callback](JSValue fn) { return JS_VALUE_GET_PTR(fn) == JS_VALUE_GET_PTR(callback); }) != vector->end()) { @@ -94,4 +95,4 @@ EventListenerMap::~EventListenerMap() { } } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/event_listener_map.h b/bridge/bindings/qjs/dom/event_listener_map.h index 7a0be8604c..d04901873d 100644 --- a/bridge/bindings/qjs/dom/event_listener_map.h +++ b/bridge/bindings/qjs/dom/event_listener_map.h @@ -1,15 +1,16 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_BINDINGS_QJS_DOM_EVENT_LISTENER_MAP_H_ -#define KRAKENBRIDGE_BINDINGS_QJS_DOM_EVENT_LISTENER_MAP_H_ +#ifndef BRIDGE_BINDINGS_QJS_DOM_EVENT_LISTENER_MAP_H_ +#define BRIDGE_BINDINGS_QJS_DOM_EVENT_LISTENER_MAP_H_ #include #include -#include "include/kraken_foundation.h" +#include "include/webf_foundation.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { using EventListenerVector = std::vector; @@ -38,6 +39,6 @@ class EventListenerMap final { JSRuntime* m_runtime; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_BINDINGS_QJS_DOM_EVENT_LISTENER_MAP_H_ +#endif // BRIDGE_BINDINGS_QJS_DOM_EVENT_LISTENER_MAP_H_ diff --git a/bridge/bindings/qjs/dom/event_target.cc b/bridge/bindings/qjs/dom/event_target.cc index 05931e6777..5c81192bd8 100644 --- a/bridge/bindings/qjs/dom/event_target.cc +++ b/bridge/bindings/qjs/dom/event_target.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "event_target.h" @@ -11,16 +12,16 @@ #include "document.h" #include "element.h" #include "event.h" -#include "kraken_bridge.h" +#include "webf_bridge.h" #define PROPAGATION_STOPPED 1 #define PROPAGATION_CONTINUE 0 #if UNIT_TEST -#include "kraken_test_env.h" +#include "webf_test_env.h" #endif -namespace kraken::binding::qjs { +namespace webf::binding::qjs { static std::atomic globalEventTargetId{0}; std::once_flag kEventTargetInitFlag; @@ -525,4 +526,4 @@ int32_t NativeEventTarget::dispatchEventImpl(int32_t contextId, NativeEventTarge return propagationStopped ? PROPAGATION_STOPPED : PROPAGATION_CONTINUE; } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/event_target.h b/bridge/bindings/qjs/dom/event_target.h index 9248bc8e5a..7a24691de2 100644 --- a/bridge/bindings/qjs/dom/event_target.h +++ b/bridge/bindings/qjs/dom/event_target.h @@ -1,9 +1,10 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_EVENT_TARGET_H -#define KRAKENBRIDGE_EVENT_TARGET_H +#ifndef BRIDGE_EVENT_TARGET_H +#define BRIDGE_EVENT_TARGET_H #include "bindings/qjs/dom/event.h" #include "bindings/qjs/executing_context.h" @@ -22,7 +23,7 @@ void TEST_invokeBindingMethod(void* nativePtr, void* returnValue, void* method, #define GetPropertyMagic "%g" #define SetPropertyMagic "%s" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { class EventTargetInstance; class NativeEventTarget; @@ -136,6 +137,6 @@ class EventTargetInstance : public Instance { friend StyleDeclarationInstance; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_EVENT_TARGET_H +#endif // BRIDGE_EVENT_TARGET_H diff --git a/bridge/bindings/qjs/dom/event_target_test.cc b/bridge/bindings/qjs/dom/event_target_test.cc index 2b51b82fb5..1316fa8b0b 100644 --- a/bridge/bindings/qjs/dom/event_target_test.cc +++ b/bridge/bindings/qjs/dom/event_target_test.cc @@ -1,21 +1,22 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "event_target.h" #include "gtest/gtest.h" -#include "kraken_test_env.h" #include "page.h" +#include "webf_test_env.h" TEST(EventTarget, addEventListener) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { EXPECT_STREQ(message.c_str(), "1234"); logCalled = true; }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -28,9 +29,9 @@ TEST(EventTarget, addEventListener) { TEST(EventTarget, removeEventListener) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; }; + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -44,12 +45,12 @@ TEST(EventTarget, removeEventListener) { TEST(EventTarget, setNoEventTargetProperties) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "{name: 1}"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); @@ -62,12 +63,12 @@ TEST(EventTarget, setNoEventTargetProperties) { TEST(EventTarget, propertyEventHandler) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "ƒ () 1234"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -85,12 +86,12 @@ TEST(EventTarget, propertyEventHandler) { TEST(EventTarget, attributeEventHandlerShouldExit) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "true"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -105,9 +106,9 @@ TEST(EventTarget, attributeEventHandlerShouldExit) { TEST(EventTarget, setUnExpectedAttributeEventHandler) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = false; }; + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = false; }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -125,12 +126,12 @@ TEST(EventTarget, setUnExpectedAttributeEventHandler) { TEST(EventTarget, propertyEventOnWindow) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "1234"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -145,12 +146,12 @@ TEST(EventTarget, propertyEventOnWindow) { TEST(EventTarget, asyncFunctionCallback) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "done"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -158,7 +159,7 @@ TEST(EventTarget, asyncFunctionCallback) { const img = document.createElement('img'); img.style.width = '100px'; img.style.height = '100px'; - img.src = "assets/kraken.png"; + img.src = "assets/webf.png"; document.body.appendChild(img); const img2 = img.cloneNode(false); document.body.appendChild(img2); @@ -187,12 +188,12 @@ TEST(EventTarget, asyncFunctionCallback) { TEST(EventTarget, ClassInheritEventTarget) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "ƒ () ƒ ()"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -221,11 +222,11 @@ TEST(EventTarget, wontLeakWithStringProperty) { } TEST(EventTarget, dispatchEventOnGC) { - using namespace kraken::binding::qjs; + using namespace webf::binding::qjs; bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "1234"); }; @@ -265,7 +266,7 @@ setTimeout(() => {}); TEST(EventTarget, globalBindListener) { bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "clicked"); }; @@ -278,7 +279,7 @@ TEST(EventTarget, globalBindListener) { TEST(EventTarget, shouldKeepAtom) { auto bridge = TEST_init(); bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "2"); }; diff --git a/bridge/bindings/qjs/dom/event_test.cc b/bridge/bindings/qjs/dom/event_test.cc index ab3ad19193..e5df41d3e6 100644 --- a/bridge/bindings/qjs/dom/event_test.cc +++ b/bridge/bindings/qjs/dom/event_test.cc @@ -1,16 +1,17 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "event_target.h" #include "gtest/gtest.h" -#include "kraken_test_env.h" #include "page.h" +#include "webf_test_env.h" TEST(MouseEvent, init) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { EXPECT_STREQ(message.c_str(), "10"); logCalled = true; }; diff --git a/bridge/bindings/qjs/dom/event_type_names.cc b/bridge/bindings/qjs/dom/event_type_names.cc index 1d70053d97..7d9e099e30 100644 --- a/bridge/bindings/qjs/dom/event_type_names.cc +++ b/bridge/bindings/qjs/dom/event_type_names.cc @@ -1,12 +1,13 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "event_type_names.h" #include #include -namespace kraken::binding::qjs { +namespace webf::binding::qjs { static std::vector eventTypeNames{ "onabort", @@ -59,4 +60,4 @@ bool qjs::EventTypeNames::isEventTypeName(const std::string& name) { return std::find(eventTypeNames.begin(), eventTypeNames.end(), name) != eventTypeNames.end(); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/event_type_names.h b/bridge/bindings/qjs/dom/event_type_names.h index c30a5c1dd7..9a55ebb9f2 100644 --- a/bridge/bindings/qjs/dom/event_type_names.h +++ b/bridge/bindings/qjs/dom/event_type_names.h @@ -1,19 +1,20 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_BINDINGS_QJS_DOM_EVENT_TYPE_NAMES_H_ -#define KRAKENBRIDGE_BINDINGS_QJS_DOM_EVENT_TYPE_NAMES_H_ +#ifndef BRIDGE_BINDINGS_QJS_DOM_EVENT_TYPE_NAMES_H_ +#define BRIDGE_BINDINGS_QJS_DOM_EVENT_TYPE_NAMES_H_ #include #include -namespace kraken::binding::qjs { +namespace webf::binding::qjs { class EventTypeNames { public: static bool isEventTypeName(const std::string& name); }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_BINDINGS_QJS_DOM_EVENT_TYPE_NAMES_H_ +#endif // BRIDGE_BINDINGS_QJS_DOM_EVENT_TYPE_NAMES_H_ diff --git a/bridge/bindings/qjs/dom/events/touch_event.cc b/bridge/bindings/qjs/dom/events/touch_event.cc index 7e46737de1..247fcd0596 100644 --- a/bridge/bindings/qjs/dom/events/touch_event.cc +++ b/bridge/bindings/qjs/dom/events/touch_event.cc @@ -1,12 +1,13 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "touch_event.h" #include "bindings/qjs/qjs_patch.h" #include "page.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindTouchEvent(ExecutionContext* context) { auto* constructor = TouchEvent::instance(context); @@ -255,4 +256,4 @@ IMPL_PROPERTY_GETTER(TouchEvent, shiftKey)(JSContext* ctx, JSValue this_val, int TouchEventInstance::TouchEventInstance(TouchEvent* event, NativeEvent* nativeEvent) : EventInstance(event, nativeEvent) {} -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/events/touch_event.h b/bridge/bindings/qjs/dom/events/touch_event.h index 56f3c19196..92ded406c1 100644 --- a/bridge/bindings/qjs/dom/events/touch_event.h +++ b/bridge/bindings/qjs/dom/events/touch_event.h @@ -1,13 +1,14 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_TOUCH_EVENT_H -#define KRAKENBRIDGE_TOUCH_EVENT_H +#ifndef BRIDGE_TOUCH_EVENT_H +#define BRIDGE_TOUCH_EVENT_H #include "bindings/qjs/dom/element.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindTouchEvent(ExecutionContext* context); @@ -112,6 +113,6 @@ class TouchEventInstance : public EventInstance { friend TouchEvent; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_TOUCH_EVENTT_H +#endif // BRIDGE_TOUCH_EVENTT_H diff --git a/bridge/bindings/qjs/dom/frame_request_callback_collection.cc b/bridge/bindings/qjs/dom/frame_request_callback_collection.cc index 372fc38279..e7cc6b1d10 100644 --- a/bridge/bindings/qjs/dom/frame_request_callback_collection.cc +++ b/bridge/bindings/qjs/dom/frame_request_callback_collection.cc @@ -1,10 +1,11 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "frame_request_callback_collection.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { JSClassID FrameCallback::classId{0}; FrameCallback::FrameCallback(JSValue callback) : m_callback(callback) {} @@ -70,4 +71,4 @@ void FrameRequestCallbackCollection::trace(JSRuntime* rt, JSValue val, JS_MarkFu } } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/frame_request_callback_collection.h b/bridge/bindings/qjs/dom/frame_request_callback_collection.h index 5839069758..46aa42bc00 100644 --- a/bridge/bindings/qjs/dom/frame_request_callback_collection.h +++ b/bridge/bindings/qjs/dom/frame_request_callback_collection.h @@ -1,13 +1,14 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_BINDINGS_QJS_BOM_FRAME_REQUEST_CALLBACK_COLLECTION_H_ -#define KRAKENBRIDGE_BINDINGS_QJS_BOM_FRAME_REQUEST_CALLBACK_COLLECTION_H_ +#ifndef BRIDGE_BINDINGS_QJS_BOM_FRAME_REQUEST_CALLBACK_COLLECTION_H_ +#define BRIDGE_BINDINGS_QJS_BOM_FRAME_REQUEST_CALLBACK_COLLECTION_H_ #include "bindings/qjs/executing_context.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { // |FrameCallback| is an interface type which generalizes callbacks which are // invoked when a script-based animation needs to be resampled. @@ -40,8 +41,8 @@ class FrameRequestCallbackCollection final { std::vector m_abandonedCallbacks; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs class frame_request_callback_collection {}; -#endif // KRAKENBRIDGE_BINDINGS_QJS_BOM_FRAME_REQUEST_CALLBACK_COLLECTION_H_ +#endif // BRIDGE_BINDINGS_QJS_BOM_FRAME_REQUEST_CALLBACK_COLLECTION_H_ diff --git a/bridge/bindings/qjs/dom/node.cc b/bridge/bindings/qjs/dom/node.cc index 883d88e667..d043f0c35f 100644 --- a/bridge/bindings/qjs/dom/node.cc +++ b/bridge/bindings/qjs/dom/node.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "node.h" @@ -8,10 +9,10 @@ #include "document.h" #include "document_fragment.h" #include "element.h" -#include "kraken_bridge.h" #include "text_node.h" +#include "webf_bridge.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindNode(ExecutionContext* context) { auto* constructor = Node::instance(context); @@ -573,4 +574,4 @@ void NodeInstance::trace(JSRuntime* rt, JSValue val, JS_MarkFunc* mark_func) { JS_MarkValue(rt, parentNode, mark_func); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/node.h b/bridge/bindings/qjs/dom/node.h index 32e9d26337..d8b96dea5f 100644 --- a/bridge/bindings/qjs/dom/node.h +++ b/bridge/bindings/qjs/dom/node.h @@ -1,16 +1,17 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_NODE_H -#define KRAKENBRIDGE_NODE_H +#ifndef BRIDGE_NODE_H +#define BRIDGE_NODE_H #include #include #include "event_target.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { void bindNode(ExecutionContext* context); @@ -128,6 +129,6 @@ class NodeInstance : public EventTargetInstance { friend ElementInstance; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_NODE_H +#endif // BRIDGE_NODE_H diff --git a/bridge/bindings/qjs/dom/node_test.cc b/bridge/bindings/qjs/dom/node_test.cc index 8244e74d20..bda58b29be 100644 --- a/bridge/bindings/qjs/dom/node_test.cc +++ b/bridge/bindings/qjs/dom/node_test.cc @@ -1,16 +1,17 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "event_target.h" #include "gtest/gtest.h" -#include "kraken_test_env.h" #include "page.h" +#include "webf_test_env.h" TEST(Node, appendChild) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { EXPECT_STREQ(message.c_str(), "true true true"); logCalled = true; }; @@ -29,7 +30,7 @@ TEST(Node, appendChild) { TEST(Node, childNodes) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { EXPECT_STREQ(message.c_str(), "true true true true"); logCalled = true; }; @@ -54,7 +55,7 @@ TEST(Node, childNodes) { TEST(Node, textContent) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { EXPECT_STREQ(message.c_str(), "1234helloworld"); logCalled = true; }; @@ -76,7 +77,7 @@ TEST(Node, textContent) { TEST(Node, setTextContent) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { EXPECT_STREQ(message.c_str(), "1234"); logCalled = true; }; @@ -95,7 +96,7 @@ TEST(Node, setTextContent) { TEST(Node, ensureDetached) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { EXPECT_STREQ(message.c_str(), "true true"); logCalled = true; }; @@ -117,9 +118,9 @@ TEST(Node, ensureDetached) { TEST(Node, replaceBody) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; }; + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -149,12 +150,12 @@ console.log(div.style.width == div2.style.height, div.getAttribute('id') == '123 bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "true true true"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -197,12 +198,12 @@ console.log( bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "true true true"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); diff --git a/bridge/bindings/qjs/dom/script_animation_controller.cc b/bridge/bindings/qjs/dom/script_animation_controller.cc index 1e7581d800..25e1c259bb 100644 --- a/bridge/bindings/qjs/dom/script_animation_controller.cc +++ b/bridge/bindings/qjs/dom/script_animation_controller.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "script_animation_controller.h" @@ -7,10 +8,10 @@ #include "frame_request_callback_collection.h" #if UNIT_TEST -#include "kraken_test_env.h" +#include "webf_test_env.h" #endif -namespace kraken::binding::qjs { +namespace webf::binding::qjs { JSClassID ScriptAnimationController::classId{0}; @@ -61,4 +62,4 @@ void ScriptAnimationController::cancelFrameCallback(uint32_t callbackId) { m_frameRequestCallbackCollection.cancelFrameCallback(callbackId); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/script_animation_controller.h b/bridge/bindings/qjs/dom/script_animation_controller.h index 5939bea7bf..19b37b9c6c 100644 --- a/bridge/bindings/qjs/dom/script_animation_controller.h +++ b/bridge/bindings/qjs/dom/script_animation_controller.h @@ -1,14 +1,15 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_BINDINGS_QJS_BOM_SCRIPT_ANIMATION_CONTROLLER_H_ -#define KRAKENBRIDGE_BINDINGS_QJS_BOM_SCRIPT_ANIMATION_CONTROLLER_H_ +#ifndef BRIDGE_BINDINGS_QJS_BOM_SCRIPT_ANIMATION_CONTROLLER_H_ +#define BRIDGE_BINDINGS_QJS_BOM_SCRIPT_ANIMATION_CONTROLLER_H_ #include "bindings/qjs/garbage_collected.h" #include "frame_request_callback_collection.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { class ScriptAnimationController : public GarbageCollected { public: @@ -29,6 +30,6 @@ class ScriptAnimationController : public GarbageCollectedjsObject, mark_func); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/style_declaration.h b/bridge/bindings/qjs/dom/style_declaration.h index f1f5a3fc58..1e2b5f36cc 100644 --- a/bridge/bindings/qjs/dom/style_declaration.h +++ b/bridge/bindings/qjs/dom/style_declaration.h @@ -1,13 +1,14 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_STYLE_DECLARATION_H -#define KRAKENBRIDGE_STYLE_DECLARATION_H +#ifndef BRIDGE_STYLE_DECLARATION_H +#define BRIDGE_STYLE_DECLARATION_H #include "bindings/qjs/host_class.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { class EventTargetInstance; void bindCSSStyleDeclaration(ExecutionContext* context); @@ -76,6 +77,6 @@ class StyleDeclarationInstance : public Instance { friend EventTargetInstance; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_STYLE_DECLARATION_H +#endif // BRIDGE_STYLE_DECLARATION_H diff --git a/bridge/bindings/qjs/dom/text_node.cc b/bridge/bindings/qjs/dom/text_node.cc index 37be3f38c4..777f866ad7 100644 --- a/bridge/bindings/qjs/dom/text_node.cc +++ b/bridge/bindings/qjs/dom/text_node.cc @@ -1,12 +1,13 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "text_node.h" #include "document.h" -#include "kraken_bridge.h" +#include "webf_bridge.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { std::once_flag kTextNodeInitFlag; @@ -82,4 +83,4 @@ void TextNodeInstance::internalSetTextContent(JSValue content) { std::unique_ptr args_02 = jsValueToNativeString(m_ctx, content); m_context->uiCommandBuffer()->addCommand(m_eventTargetId, UICommand::setAttribute, *args_01, *args_02, nullptr); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/dom/text_node.h b/bridge/bindings/qjs/dom/text_node.h index d9c293f719..ca94284d79 100644 --- a/bridge/bindings/qjs/dom/text_node.h +++ b/bridge/bindings/qjs/dom/text_node.h @@ -1,13 +1,14 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_TEXT_NODE_H -#define KRAKENBRIDGE_TEXT_NODE_H +#ifndef BRIDGE_TEXT_NODE_H +#define BRIDGE_TEXT_NODE_H #include "node.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { class TextNodeInstance; @@ -49,6 +50,6 @@ class TextNodeInstance : public NodeInstance { std::string m_data; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_TEXT_NODE_H +#endif // BRIDGE_TEXT_NODE_H diff --git a/bridge/bindings/qjs/dom/text_node_test.cc b/bridge/bindings/qjs/dom/text_node_test.cc index d7552d3b71..8fe76b30a3 100644 --- a/bridge/bindings/qjs/dom/text_node_test.cc +++ b/bridge/bindings/qjs/dom/text_node_test.cc @@ -1,21 +1,22 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "event_target.h" #include "gtest/gtest.h" -#include "kraken_test_env.h" #include "page.h" +#include "webf_test_env.h" TEST(TextNode, instanceofNode) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "true true"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); diff --git a/bridge/bindings/qjs/executing_context.cc b/bridge/bindings/qjs/executing_context.cc index 5c6af7802f..33a3f95008 100644 --- a/bridge/bindings/qjs/executing_context.cc +++ b/bridge/bindings/qjs/executing_context.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "executing_context.h" @@ -9,10 +10,10 @@ #include "bindings/qjs/module_manager.h" #include "bom/dom_timer_coordinator.h" #include "garbage_collected.h" -#include "kraken_bridge.h" #include "qjs_patch.h" +#include "webf_bridge.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { static std::atomic context_unique_id{0}; @@ -557,4 +558,4 @@ void ExecutionContext::trace(JSRuntime* rt, JSValue val, JS_MarkFunc* mark_func) m_timers.trace(rt, JS_NULL, mark_func); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/executing_context.h b/bridge/bindings/qjs/executing_context.h index 601e534253..bfc5fba894 100644 --- a/bridge/bindings/qjs/executing_context.h +++ b/bridge/bindings/qjs/executing_context.h @@ -1,9 +1,10 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_JS_CONTEXT_H -#define KRAKENBRIDGE_JS_CONTEXT_H +#ifndef BRIDGE_JS_CONTEXT_H +#define BRIDGE_JS_CONTEXT_H #include #include @@ -19,13 +20,13 @@ #include "foundation/ui_command_buffer.h" #include "garbage_collected.h" #include "js_context_macros.h" -#include "kraken_foundation.h" #include "qjs_patch.h" #include "rejected_promises.h" +#include "webf_foundation.h" using JSExceptionHandler = std::function; -namespace kraken::binding::qjs { +namespace webf::binding::qjs { static std::once_flag kinitJSClassIDFlag; @@ -66,7 +67,7 @@ class ExecutionContextGCTracker : public GarbageCollected -#include "include/kraken_foundation.h" +#include "include/webf_foundation.h" #include "qjs_patch.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { template class MakeGarbageCollectedTrait; @@ -143,6 +144,6 @@ T* makeGarbageCollected(Args&&... args) { return MakeGarbageCollectedTrait::allocate(std::forward(args)...); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_GARBAGE_COLLECTED_H +#endif // BRIDGE_GARBAGE_COLLECTED_H diff --git a/bridge/bindings/qjs/heap_hashmap.h b/bridge/bindings/qjs/heap_hashmap.h index 76a75c4457..f7a64d0f9d 100644 --- a/bridge/bindings/qjs/heap_hashmap.h +++ b/bridge/bindings/qjs/heap_hashmap.h @@ -1,14 +1,15 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_BINDINGS_QJS_HEAP_HASHMAP_H_ -#define KRAKENBRIDGE_BINDINGS_QJS_HEAP_HASHMAP_H_ +#ifndef BRIDGE_BINDINGS_QJS_HEAP_HASHMAP_H_ +#define BRIDGE_BINDINGS_QJS_HEAP_HASHMAP_H_ #include #include -namespace kraken::binding::qjs { +namespace webf::binding::qjs { template class HeapHashMap { @@ -97,6 +98,6 @@ void HeapHashMap::trace(JSRuntime* rt, JSValue val, JS_MarkFunc* mark_func) c } } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_BINDINGS_QJS_HEAP_HASHMAP_H_ +#endif // BRIDGE_BINDINGS_QJS_HEAP_HASHMAP_H_ diff --git a/bridge/bindings/qjs/host_class.h b/bridge/bindings/qjs/host_class.h index 6e05a7950a..a9ef7de300 100644 --- a/bridge/bindings/qjs/host_class.h +++ b/bridge/bindings/qjs/host_class.h @@ -1,21 +1,22 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_HOST_CLASS_H -#define KRAKENBRIDGE_HOST_CLASS_H +#ifndef BRIDGE_HOST_CLASS_H +#define BRIDGE_HOST_CLASS_H #include "executing_context.h" #include "qjs_patch.h" #include "third_party/quickjs/quickjs.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { class Instance; class HostClass { public: - KRAKEN_DISALLOW_COPY_AND_ASSIGN(HostClass); + DISALLOW_COPY_AND_ASSIGN(HostClass); HostClass(ExecutionContext* context, std::string name) : m_context(context), m_name(std::move(name)), m_ctx(context->ctx()), m_contextId(context->getContextId()) { /// JavaScript object in QuickJS are created by template, in QuickJS, these template is called JSClassDef. @@ -139,6 +140,6 @@ class Instance { friend HostClass; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_HOST_CLASS_H +#endif // BRIDGE_HOST_CLASS_H diff --git a/bridge/bindings/qjs/host_class_test.cc b/bridge/bindings/qjs/host_class_test.cc index 00cd87cba7..bfd1953a02 100644 --- a/bridge/bindings/qjs/host_class_test.cc +++ b/bridge/bindings/qjs/host_class_test.cc @@ -1,14 +1,15 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "host_class.h" #include #include "gtest/gtest.h" -#include "kraken_test_env.h" #include "page.h" +#include "webf_test_env.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { class ParentClass : public HostClass { public: @@ -63,12 +64,12 @@ class SampleClass : public ParentClass { TEST(HostClass, newInstance) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "10"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -86,13 +87,13 @@ TEST(HostClass, newInstance) { TEST(HostClass, instanceOf) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "true"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { errorCalled = true; - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; }); auto context = bridge->getContext(); auto* sampleObject = new SampleClass(context); @@ -117,13 +118,13 @@ TEST(HostClass, instanceOf) { TEST(HostClass, inheritance) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "20"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { errorCalled = true; - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; }); auto context = bridge->getContext(); auto* sampleObject = new SampleClass(context); @@ -145,13 +146,13 @@ TEST(HostClass, inheritance) { TEST(HostClass, inherintanceInJavaScript) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "TEST 10 20"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { errorCalled = true; - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; }); auto context = bridge->getContext(); auto* sampleObject = new SampleClass(context); @@ -184,13 +185,13 @@ console.log(demo.getName(), demo.f(), demo.foo()); TEST(HostClass, haveFunctionProtoMethods) { bool static errorCalled = false; bool static logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "ƒ ()"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { errorCalled = true; - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; }); auto context = bridge->getContext(); auto* parentObject = ParentClass::instance(context); @@ -219,7 +220,7 @@ TEST(HostClass, multipleInstance) { bool static errorCalled = false; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { errorCalled = true; - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; }); auto context = bridge->getContext(); @@ -358,10 +359,10 @@ TEST(HostClass, exoticClass) { bool static errorCalled = false; bool static logCalled = false; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "10"); }; @@ -386,10 +387,10 @@ TEST(HostClass, setExoticClassProperty) { bool static errorCalled = false; bool static logCalled = false; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "200"); }; @@ -413,7 +414,7 @@ TEST(HostClass, finalizeShouldNotFree) { bool static errorCalled = false; bool static logCalled = false; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { errorCalled = true; }); - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; }; + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; }; auto context = bridge->getContext(); auto* constructor = new ExoticClass(context); @@ -423,7 +424,7 @@ TEST(HostClass, finalizeShouldNotFree) { JS_RunGC(JS_GetRuntime(ctx)); return JS_NULL; }; - QJS_GLOBAL_BINDING_FUNCTION(context, runGC, "__kraken_run_gc__", 1); + QJS_GLOBAL_BINDING_FUNCTION(context, runGC, "__webf_run_gc__", 1); std::string code = R"( function throttle(func, wait) { @@ -508,4 +509,4 @@ var handleScroll = function (e) { triggerScrollEventAndLoopTimer(); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/host_object.cc b/bridge/bindings/qjs/host_object.cc index 9bf1a5b662..a86db4f12c 100644 --- a/bridge/bindings/qjs/host_object.cc +++ b/bridge/bindings/qjs/host_object.cc @@ -1,10 +1,11 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "host_object.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { JSValue ExoticHostObject::getProperty(JSContext* ctx, JSValue obj, JSAtom atom, JSValue receiver) { return JS_NULL; @@ -13,4 +14,4 @@ int ExoticHostObject::setProperty(JSContext* ctx, JSValue obj, JSAtom atom, JSVa return 0; } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/host_object.h b/bridge/bindings/qjs/host_object.h index f69086f385..7e54d1943a 100644 --- a/bridge/bindings/qjs/host_object.h +++ b/bridge/bindings/qjs/host_object.h @@ -1,17 +1,18 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_HOST_OBJECT_H -#define KRAKENBRIDGE_HOST_OBJECT_H +#ifndef BRIDGE_HOST_OBJECT_H +#define BRIDGE_HOST_OBJECT_H #include "executing_context.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { class HostObject { public: - KRAKEN_DISALLOW_COPY_AND_ASSIGN(HostObject); + DISALLOW_COPY_AND_ASSIGN(HostObject); HostObject() = delete; HostObject(ExecutionContext* context, std::string name) : m_context(context), m_name(std::move(name)), m_ctx(context->ctx()), m_contextId(context->getContextId()) { @@ -41,7 +42,7 @@ class HostObject { class ExoticHostObject { public: - KRAKEN_DISALLOW_COPY_AND_ASSIGN(ExoticHostObject); + DISALLOW_COPY_AND_ASSIGN(ExoticHostObject); ExoticHostObject() = delete; ExoticHostObject(ExecutionContext* context, std::string name) : m_context(context), m_name(std::move(name)), m_ctx(context->ctx()), m_contextId(context->getContextId()) { @@ -82,6 +83,6 @@ class ExoticHostObject { }; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_HOST_OBJECT_H +#endif // BRIDGE_HOST_OBJECT_H diff --git a/bridge/bindings/qjs/host_object_test.cc b/bridge/bindings/qjs/host_object_test.cc index c02bb8046d..66d0ffa1cf 100644 --- a/bridge/bindings/qjs/host_object_test.cc +++ b/bridge/bindings/qjs/host_object_test.cc @@ -1,14 +1,15 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "host_object.h" #include #include "executing_context.h" -#include "kraken_test_env.h" #include "page.h" +#include "webf_test_env.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { static bool isSampleFree = false; @@ -47,7 +48,7 @@ class SampleObject : public HostObject { TEST(HostObject, defineProperty) { bool static logCalled = false; bool static errorCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "{f: ƒ (), foo: 1}"); @@ -67,12 +68,12 @@ TEST(HostObject, defineProperty) { TEST(ObjectProperty, worksWithProxy) { bool static logCalled = false; bool static errorCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "0"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -96,12 +97,12 @@ console.log(p.foo); TEST(HostObject, defineFunction) { bool static logCalled = false; bool static errorCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "20"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -137,12 +138,12 @@ int SampleExoticHostObject::setProperty(JSContext* ctx, JSValue obj, JSAtom atom TEST(ExoticHostObject, overriteGetterSetter) { bool static logCalled = false; bool static errorCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "100"); }; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) { - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; errorCalled = true; }); auto context = bridge->getContext(); @@ -157,4 +158,4 @@ TEST(ExoticHostObject, overriteGetterSetter) { EXPECT_EQ(isSampleFree, true); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/html_parser.cc b/bridge/bindings/qjs/html_parser.cc index fd85d0625c..05dc5e61cd 100644 --- a/bridge/bindings/qjs/html_parser.cc +++ b/bridge/bindings/qjs/html_parser.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "html_parser.h" @@ -10,7 +11,7 @@ #include -namespace kraken::binding::qjs { +namespace webf::binding::qjs { inline std::string trim(std::string& str) { str.erase(0, str.find_first_not_of(' ')); // prefixing spaces @@ -114,7 +115,7 @@ bool HTMLParser::parseHTML(std::string html, NodeInstance* rootNode, bool isHTML gumbo_destroy_output(&kGumboDefaultOptions, htmlTree); } } else { - KRAKEN_LOG(ERROR) << "Root node is null."; + WEBF_LOG(ERROR) << "Root node is null."; } return true; @@ -191,4 +192,4 @@ void HTMLParser::parseProperty(ElementInstance* element, GumboElement* gumboElem } } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/html_parser.h b/bridge/bindings/qjs/html_parser.h index 0b3f32e428..939a45f6b2 100644 --- a/bridge/bindings/qjs/html_parser.h +++ b/bridge/bindings/qjs/html_parser.h @@ -1,16 +1,17 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_HTML_PARSER_H -#define KRAKENBRIDGE_HTML_PARSER_H +#ifndef BRIDGE_HTML_PARSER_H +#define BRIDGE_HTML_PARSER_H #include "bindings/qjs/dom/element.h" #include "executing_context.h" -#include "include/kraken_bridge.h" +#include "include/webf_bridge.h" #include "third_party/gumbo-parser/src/gumbo.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { class HTMLParser { public: @@ -25,6 +26,6 @@ class HTMLParser { static bool parseHTML(std::string html, NodeInstance* rootNode, bool isHTMLFragment); }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_HTML_PARSER_H +#endif // BRIDGE_HTML_PARSER_H diff --git a/bridge/bindings/qjs/js_context_macros.h b/bridge/bindings/qjs/js_context_macros.h index 55966bb1e0..fdc7859e33 100644 --- a/bridge/bindings/qjs/js_context_macros.h +++ b/bridge/bindings/qjs/js_context_macros.h @@ -1,9 +1,10 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_JS_CONTEXT_MACROS_H -#define KRAKENBRIDGE_JS_CONTEXT_MACROS_H +#ifndef BRIDGE_JS_CONTEXT_MACROS_H +#define BRIDGE_JS_CONTEXT_MACROS_H #define OBJECT_INSTANCE(NAME) \ static NAME* instance(ExecutionContext* context) { \ @@ -58,4 +59,4 @@ }; \ ObjectProperty __##PROPERTY##__ { m_context, jsObject, #PROPERTY, PROPERTY##PropertyDescriptor::getter, PROPERTY##PropertyDescriptor::setter } -#endif // KRAKENBRIDGE_JS_CONTEXT_MACROS_H +#endif // BRIDGE_JS_CONTEXT_MACROS_H diff --git a/bridge/bindings/qjs/js_context_test.cc b/bridge/bindings/qjs/js_context_test.cc index 0c2cfa54f8..d1b26c1a6d 100644 --- a/bridge/bindings/qjs/js_context_test.cc +++ b/bridge/bindings/qjs/js_context_test.cc @@ -1,10 +1,11 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "gtest/gtest.h" -#include "kraken_test_env.h" #include "page.h" +#include "webf_test_env.h" TEST(Context, isValid) { auto bridge = TEST_init(); @@ -66,7 +67,7 @@ TEST(Context, globalErrorHandlerTargetReturnToWindow) { static bool logCalled = false; auto errorHandler = [](int32_t contextId, const char* errmsg) {}; auto bridge = TEST_init(errorHandler); - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "true"); @@ -78,7 +79,7 @@ throw new Error('1234'); )"; bridge->evaluateScript(code.c_str(), code.size(), "file://", 0); EXPECT_EQ(logCalled, true); - kraken::KrakenPage::consoleMessageHandler = nullptr; + webf::WebFPage::consoleMessageHandler = nullptr; } TEST(Context, unrejectPromiseWillTriggerUnhandledRejectionEvent) { @@ -95,7 +96,7 @@ TEST(Context, unrejectPromiseWillTriggerUnhandledRejectionEvent) { auto bridge = TEST_init(errorHandler); static int logIndex = 0; static std::string logs[] = {"error event cannot read property 'forceNullError' of null", "unhandled event {promise: Promise {...}, reason: Error {...}} true"}; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(logs[logIndex++].c_str(), message.c_str()); }; @@ -119,7 +120,7 @@ var p = new Promise(function (resolve, reject) { EXPECT_EQ(errorHandlerExecuted, true); EXPECT_EQ(logCalled, true); EXPECT_EQ(logIndex, 2); - kraken::KrakenPage::consoleMessageHandler = nullptr; + webf::WebFPage::consoleMessageHandler = nullptr; } TEST(Context, handledRejectionWillNotTriggerUnHandledRejectionEvent) { @@ -127,7 +128,7 @@ TEST(Context, handledRejectionWillNotTriggerUnHandledRejectionEvent) { static bool logCalled = false; auto errorHandler = [](int32_t contextId, const char* errmsg) { errorHandlerExecuted = true; }; auto bridge = TEST_init(errorHandler); - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "rejected"); }; @@ -155,7 +156,7 @@ generateRejectedPromise(true); bridge->evaluateScript(code.c_str(), code.size(), "file://", 0); EXPECT_EQ(errorHandlerExecuted, false); EXPECT_EQ(logCalled, true); - kraken::KrakenPage::consoleMessageHandler = nullptr; + webf::WebFPage::consoleMessageHandler = nullptr; } TEST(Context, unhandledRejectionEventWillTriggerWhenNotHandled) { @@ -163,7 +164,7 @@ TEST(Context, unhandledRejectionEventWillTriggerWhenNotHandled) { static bool logCalled = false; auto errorHandler = [](int32_t contextId, const char* errmsg) { errorHandlerExecuted = true; }; auto bridge = TEST_init(errorHandler); - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; }; + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; }; std::string code = R"( window.addEventListener('unhandledrejection', event => { @@ -184,7 +185,7 @@ generateRejectedPromise(true); bridge->evaluateScript(code.c_str(), code.size(), "file://", 0); EXPECT_EQ(errorHandlerExecuted, false); EXPECT_EQ(logCalled, true); - kraken::KrakenPage::consoleMessageHandler = nullptr; + webf::WebFPage::consoleMessageHandler = nullptr; } TEST(Context, handledRejectionEventWillTriggerWhenUnHandledRejectHandled) { @@ -192,7 +193,7 @@ TEST(Context, handledRejectionEventWillTriggerWhenUnHandledRejectHandled) { static bool logCalled = false; auto errorHandler = [](int32_t contextId, const char* errmsg) { errorHandlerExecuted = true; }; auto bridge = TEST_init(errorHandler); - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; }; + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; }; std::string code = R"( window.addEventListener('unhandledrejection', event => { @@ -225,7 +226,7 @@ generateRejectedPromise(); TEST_runLoop(bridge->getContext()); EXPECT_EQ(errorHandlerExecuted, false); EXPECT_EQ(logCalled, true); - kraken::KrakenPage::consoleMessageHandler = nullptr; + webf::WebFPage::consoleMessageHandler = nullptr; } TEST(Context, unrejectPromiseErrorWithMultipleContext) { @@ -271,9 +272,9 @@ TEST(Context, disposeContext) { initJSPagePool(1024 * 1024); TEST_mockDartMethods(nullptr); uint32_t contextId = 0; - auto bridge = static_cast(getPage(contextId)); + auto bridge = static_cast(getPage(contextId)); static bool disposed = false; - bridge->disposeCallback = [](kraken::KrakenPage* bridge) { disposed = true; }; + bridge->disposeCallback = [](webf::WebFPage* bridge) { disposed = true; }; disposePage(bridge->getContext()->getContextId()); EXPECT_EQ(disposed, true); } @@ -281,14 +282,14 @@ TEST(Context, disposeContext) { TEST(Context, window) { static bool errorHandlerExecuted = false; static bool logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "true"); }; auto errorHandler = [](int32_t contextId, const char* errmsg) { errorHandlerExecuted = true; - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; }; auto bridge = TEST_init(errorHandler); const char* code = "console.log(window == globalThis)"; @@ -300,14 +301,14 @@ TEST(Context, window) { TEST(Context, windowInheritEventTarget) { static bool errorHandlerExecuted = false; static bool logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "ƒ () ƒ () ƒ () true"); }; auto errorHandler = [](int32_t contextId, const char* errmsg) { errorHandlerExecuted = true; - KRAKEN_LOG(VERBOSE) << errmsg; + WEBF_LOG(VERBOSE) << errmsg; }; auto bridge = TEST_init(errorHandler); const char* code = "console.log(window.addEventListener, addEventListener, globalThis.addEventListener, window.addEventListener === addEventListener)"; @@ -319,7 +320,7 @@ TEST(Context, windowInheritEventTarget) { TEST(Context, evaluateByteCode) { static bool errorHandlerExecuted = false; static bool logCalled = false; - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), "Arguments {0: 1, 1: 2, 2: 3, 3: 4, callee: ƒ (), length: 4}"); }; @@ -338,7 +339,7 @@ TEST(Context, evaluateByteCode) { TEST(jsValueToNativeString, utf8String) { auto bridge = TEST_init([](int32_t contextId, const char* errmsg) {}); JSValue str = JS_NewString(bridge->getContext()->ctx(), "helloworld"); - std::unique_ptr nativeString = kraken::binding::qjs::jsValueToNativeString(bridge->getContext()->ctx(), str); + std::unique_ptr nativeString = webf::binding::qjs::jsValueToNativeString(bridge->getContext()->ctx(), str); EXPECT_EQ(nativeString->length, 10); uint8_t expectedString[10] = {104, 101, 108, 108, 111, 119, 111, 114, 108, 100}; for (int i = 0; i < 10; i++) { @@ -350,7 +351,7 @@ TEST(jsValueToNativeString, utf8String) { TEST(jsValueToNativeString, unicodeChinese) { auto bridge = TEST_init([](int32_t contextId, const char* errmsg) {}); JSValue str = JS_NewString(bridge->getContext()->ctx(), "这是你的优乐美"); - std::unique_ptr nativeString = kraken::binding::qjs::jsValueToNativeString(bridge->getContext()->ctx(), str); + std::unique_ptr nativeString = webf::binding::qjs::jsValueToNativeString(bridge->getContext()->ctx(), str); std::u16string expectedString = u"这是你的优乐美"; EXPECT_EQ(nativeString->length, expectedString.size()); for (int i = 0; i < nativeString->length; i++) { @@ -362,7 +363,7 @@ TEST(jsValueToNativeString, unicodeChinese) { TEST(jsValueToNativeString, emoji) { auto bridge = TEST_init([](int32_t contextId, const char* errmsg) {}); JSValue str = JS_NewString(bridge->getContext()->ctx(), "……🤪"); - std::unique_ptr nativeString = kraken::binding::qjs::jsValueToNativeString(bridge->getContext()->ctx(), str); + std::unique_ptr nativeString = webf::binding::qjs::jsValueToNativeString(bridge->getContext()->ctx(), str); std::u16string expectedString = u"……🤪"; EXPECT_EQ(nativeString->length, expectedString.length()); for (int i = 0; i < nativeString->length; i++) { diff --git a/bridge/bindings/qjs/module_manager.cc b/bridge/bindings/qjs/module_manager.cc index 456672be46..75b4672303 100644 --- a/bridge/bindings/qjs/module_manager.cc +++ b/bridge/bindings/qjs/module_manager.cc @@ -1,25 +1,26 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "module_manager.h" #include "page.h" #include "qjs_patch.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { -JSValue krakenModuleListener(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) { +JSValue webFModuleListener(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) { if (argc < 1) { - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_module_listener__': 1 parameter required, but only 0 present."); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_module_listener__': 1 parameter required, but only 0 present."); } JSValue callbackValue = argv[0]; if (!JS_IsObject(callbackValue)) { - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_module_listener__': parameter 1 (callback) must be a function."); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_module_listener__': parameter 1 (callback) must be a function."); } if (!JS_IsFunction(ctx, callbackValue)) { - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_module_listener__': parameter 1 (callback) must be a function."); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_module_listener__': parameter 1 (callback) must be a function."); } auto context = static_cast(JS_GetContextOpaque(ctx)); @@ -39,7 +40,7 @@ void handleInvokeModuleTransientCallback(void* callbackContext, int32_t contextI return; if (JS_IsNull(moduleContext->callback)) { - JSValue exception = JS_ThrowTypeError(moduleContext->context->ctx(), "Failed to execute '__kraken_invoke_module__': callback is null."); + JSValue exception = JS_ThrowTypeError(moduleContext->context->ctx(), "Failed to execute '__webf_invoke_module__': callback is null."); context->handleException(&exception); return; } @@ -78,9 +79,9 @@ void handleInvokeModuleUnexpectedCallback(void* callbackContext, int32_t context static_assert("Unexpected module callback, please check your invokeModule implementation on the dart side."); } -JSValue krakenInvokeModule(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) { +JSValue webFInvokeModule(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) { if (argc < 2) { - return JS_ThrowTypeError(ctx, "Failed to execute 'kraken.invokeModule()': 2 arguments required."); + return JS_ThrowTypeError(ctx, "Failed to execute 'webf.invokeModule()': 2 arguments required."); } JSValue moduleNameValue = argv[0]; @@ -112,7 +113,7 @@ JSValue krakenInvokeModule(JSContext* ctx, JSValueConst this_val, int argc, JSVa if (getDartMethod()->invokeModule == nullptr) { #if FLUTTER_BACKEND - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_invoke_module__': dart method (invokeModule) is not registered."); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_invoke_module__': dart method (invokeModule) is not registered."); #else return JS_NULL; #endif @@ -154,16 +155,16 @@ JSValue krakenInvokeModule(JSContext* ctx, JSValueConst this_val, int argc, JSVa JSValue flushUICommand(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) { if (getDartMethod()->flushUICommand == nullptr) { - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_flush_ui_command__': dart method (flushUICommand) is not registered."); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_flush_ui_command__': dart method (flushUICommand) is not registered."); } getDartMethod()->flushUICommand(); return JS_NULL; } void bindModuleManager(ExecutionContext* context) { - QJS_GLOBAL_BINDING_FUNCTION(context, krakenModuleListener, "__kraken_module_listener__", 1); - QJS_GLOBAL_BINDING_FUNCTION(context, krakenInvokeModule, "__kraken_invoke_module__", 3); - QJS_GLOBAL_BINDING_FUNCTION(context, flushUICommand, "__kraken_flush_ui_command__", 0); + QJS_GLOBAL_BINDING_FUNCTION(context, webFModuleListener, "__webf_module_listener__", 1); + QJS_GLOBAL_BINDING_FUNCTION(context, webFInvokeModule, "__webf_invoke_module__", 3); + QJS_GLOBAL_BINDING_FUNCTION(context, flushUICommand, "__webf_flush_ui_command__", 0); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/module_manager.h b/bridge/bindings/qjs/module_manager.h index b263152059..814de1c0e8 100644 --- a/bridge/bindings/qjs/module_manager.h +++ b/bridge/bindings/qjs/module_manager.h @@ -1,13 +1,14 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_MODULE_MANAGER_H -#define KRAKENBRIDGE_MODULE_MANAGER_H +#ifndef BRIDGE_MODULE_MANAGER_H +#define BRIDGE_MODULE_MANAGER_H #include "executing_context.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { struct ModuleContext { JSValue callback; @@ -17,6 +18,6 @@ struct ModuleContext { void bindModuleManager(ExecutionContext* context); void handleInvokeModuleUnexpectedCallback(void* callbackContext, int32_t contextId, NativeString* errmsg, NativeString* json); -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_MODULE_MANAGER_H +#endif // BRIDGE_MODULE_MANAGER_H diff --git a/bridge/bindings/qjs/module_manager_test.cc b/bridge/bindings/qjs/module_manager_test.cc index f64fbf370b..adc3d252d5 100644 --- a/bridge/bindings/qjs/module_manager_test.cc +++ b/bridge/bindings/qjs/module_manager_test.cc @@ -1,14 +1,15 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include #include "executing_context.h" #include "host_object.h" -#include "kraken_test_env.h" #include "page.h" +#include "webf_test_env.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { TEST(ModuleManager, shouldThrowErrorWhenBadJSON) { bool static errorCalled = false; @@ -17,7 +18,7 @@ TEST(ModuleManager, shouldThrowErrorWhenBadJSON) { EXPECT_EQ(stdErrorMsg.find("TypeError: circular reference") != std::string::npos, true); errorCalled = true; }); - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) {}; + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) {}; auto context = bridge->getContext(); @@ -32,7 +33,7 @@ let object = { } }; object.other = object; -kraken.methodChannel.invokeMethod('abc', 'fn', object); +webf.methodChannel.invokeMethod('abc', 'fn', object); )"); context->evaluateJavaScript(code.c_str(), code.size(), "vm://", 0); @@ -42,10 +43,10 @@ kraken.methodChannel.invokeMethod('abc', 'fn', object); TEST(ModuleManager, invokeModuleError) { bool static logCalled = false; auto bridge = TEST_init([](int32_t contextId, const char* errmsg) {}); - kraken::KrakenPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { + webf::WebFPage::consoleMessageHandler = [](void* ctx, const std::string& message, int logLevel) { logCalled = true; EXPECT_STREQ(message.c_str(), - "Error {message: 'kraken://', stack: ' at __kraken_invoke_module__ (native)\n" + "Error {message: 'webf://', stack: ' at __webf_invoke_module__ (native)\n" " at f (vm://:9)\n" " at (vm://:11)\n" "'}"); @@ -55,7 +56,7 @@ TEST(ModuleManager, invokeModuleError) { std::string code = std::string(R"( function f() { - kraken.invokeModule('throwError', 'kraken://', null, (e, error) => { + webf.invokeModule('throwError', 'webf://', null, (e, error) => { if (e) { console.log(e); } else { @@ -70,4 +71,4 @@ f(); EXPECT_EQ(logCalled, true); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/native_value.cc b/bridge/bindings/qjs/native_value.cc index 5fead8ede4..663ef3588d 100644 --- a/bridge/bindings/qjs/native_value.cc +++ b/bridge/bindings/qjs/native_value.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "native_value.h" @@ -7,9 +8,9 @@ #include "bindings/qjs/qjs_patch.h" #include "dom/element.h" #include "dom/elements/.gen/canvas_element.h" -#include "kraken_bridge.h" +#include "webf_bridge.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { #define AnonymousFunctionCallPreFix "_anonymous_fn_" #define AsyncAnonymousFunctionCallPreFix "_anonymous_async_fn_" @@ -276,4 +277,4 @@ std::string nativeStringToStdString(NativeString* nativeString) { return toUTF8(u16EventType); } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/native_value.h b/bridge/bindings/qjs/native_value.h index 1e16ab4882..3c7e4ab59d 100644 --- a/bridge/bindings/qjs/native_value.h +++ b/bridge/bindings/qjs/native_value.h @@ -1,9 +1,10 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_NATIVE_VALUE_H -#define KRAKENBRIDGE_NATIVE_VALUE_H +#ifndef BRIDGE_NATIVE_VALUE_H +#define BRIDGE_NATIVE_VALUE_H #include "executing_context.h" @@ -21,7 +22,7 @@ enum NativeTag { enum class JSPointerType { AsyncContextContext = 0, NativeFunctionContext = 1, NativeBoundingClientRect = 2, NativeCanvasRenderingContext2D = 3, NativeEventTarget = 4 }; -namespace kraken::binding::qjs { +namespace webf::binding::qjs { // Exchange data struct between dart and C++ struct NativeValue { @@ -62,6 +63,6 @@ JSValue nativeValueToJSValue(ExecutionContext* context, NativeValue& value); std::string nativeStringToStdString(NativeString* nativeString); -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_NATIVE_VALUE_H +#endif // BRIDGE_NATIVE_VALUE_H diff --git a/bridge/bindings/qjs/qjs_patch.cc b/bridge/bindings/qjs/qjs_patch.cc index 7aac617f65..329c726234 100644 --- a/bridge/bindings/qjs/qjs_patch.cc +++ b/bridge/bindings/qjs/qjs_patch.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "qjs_patch.h" diff --git a/bridge/bindings/qjs/qjs_patch.h b/bridge/bindings/qjs/qjs_patch.h index 929b5093c8..4b98ebb6cc 100644 --- a/bridge/bindings/qjs/qjs_patch.h +++ b/bridge/bindings/qjs/qjs_patch.h @@ -1,9 +1,10 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_QJS_PATCH_H -#define KRAKENBRIDGE_QJS_PATCH_H +#ifndef BRIDGE_QJS_PATCH_H +#define BRIDGE_QJS_PATCH_H #include #include @@ -109,4 +110,4 @@ JSValue JS_GetProxyTarget(JSValue value); } #endif -#endif // KRAKENBRIDGE_QJS_PATCH_H +#endif // BRIDGE_QJS_PATCH_H diff --git a/bridge/bindings/qjs/qjs_patch_test.cc b/bridge/bindings/qjs/qjs_patch_test.cc index 76dd18a29d..434a6f7d38 100644 --- a/bridge/bindings/qjs/qjs_patch_test.cc +++ b/bridge/bindings/qjs/qjs_patch_test.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "qjs_patch.h" diff --git a/bridge/bindings/qjs/rejected_promises.cc b/bridge/bindings/qjs/rejected_promises.cc index d2a1afd897..1973d71a18 100644 --- a/bridge/bindings/qjs/rejected_promises.cc +++ b/bridge/bindings/qjs/rejected_promises.cc @@ -1,11 +1,12 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "rejected_promises.h" #include "executing_context.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { RejectedPromises::Message::Message(ExecutionContext* context, JSValue promise, JSValue reason) : m_runtime(context->runtime()), m_promise(JS_DupValue(context->ctx(), promise)), m_reason(JS_DupValue(context->ctx(), reason)) {} @@ -63,4 +64,4 @@ void RejectedPromises::process(ExecutionContext* context) { } } -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs diff --git a/bridge/bindings/qjs/rejected_promises.h b/bridge/bindings/qjs/rejected_promises.h index dbc558c06d..9ba429aaee 100644 --- a/bridge/bindings/qjs/rejected_promises.h +++ b/bridge/bindings/qjs/rejected_promises.h @@ -1,16 +1,17 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_BINDINGS_QJS_REJECTED_PROMISES_H_ -#define KRAKENBRIDGE_BINDINGS_QJS_REJECTED_PROMISES_H_ +#ifndef BRIDGE_BINDINGS_QJS_REJECTED_PROMISES_H_ +#define BRIDGE_BINDINGS_QJS_REJECTED_PROMISES_H_ #include #include #include #include -namespace kraken::binding::qjs { +namespace webf::binding::qjs { class ExecutionContext; @@ -38,6 +39,6 @@ class RejectedPromises { std::vector> m_reportHandledRejection; }; -} // namespace kraken::binding::qjs +} // namespace webf::binding::qjs -#endif // KRAKENBRIDGE_BINDINGS_QJS_REJECTED_PROMISES_H_ +#endif // BRIDGE_BINDINGS_QJS_REJECTED_PROMISES_H_ diff --git a/bridge/dart_methods.cc b/bridge/dart_methods.cc index af21efeb41..918dc78a19 100644 --- a/bridge/dart_methods.cc +++ b/bridge/dart_methods.cc @@ -4,9 +4,9 @@ #include "dart_methods.h" #include -#include "kraken_bridge.h" +#include "webf_bridge.h" -namespace kraken { +namespace webf { std::shared_ptr methodPointer = std::make_shared(); @@ -73,4 +73,4 @@ void registerGetPerformanceEntries(GetPerformanceEntries getPerformanceEntries) } #endif -} // namespace kraken +} // namespace webf diff --git a/bridge/foundation/closure.h b/bridge/foundation/closure.h index 39fb20b6d6..eb52a86c5d 100644 --- a/bridge/foundation/closure.h +++ b/bridge/foundation/closure.h @@ -2,8 +2,8 @@ * Copyright (C) 2020-present The Kraken authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_CLOSURE_H -#define KRAKENBRIDGE_CLOSURE_H +#ifndef BRIDGE_CLOSURE_H +#define BRIDGE_CLOSURE_H #include @@ -11,4 +11,4 @@ namespace fml { using closure = std::function; } -#endif // KRAKENBRIDGE_CLOSURE_H +#endif // BRIDGE_CLOSURE_H diff --git a/bridge/foundation/colors.h b/bridge/foundation/colors.h index 9c4f7854ec..373a6f3b86 100644 --- a/bridge/foundation/colors.h +++ b/bridge/foundation/colors.h @@ -1,8 +1,8 @@ /* * Copyright (C) 2019-present The Kraken authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_COLORS_H -#define KRAKENBRIDGE_COLORS_H +#ifndef BRIDGE_COLORS_H +#define BRIDGE_COLORS_H /* FOREGROUND */ #define RST "\x1B[0m" @@ -25,4 +25,4 @@ #define BOLD(x) "\x1B[1m" x RST #define UNDL(x) "\x1B[4m" x RST -#endif // KRAKENBRIDGE_COLORS_H +#endif // BRIDGE_COLORS_H diff --git a/bridge/foundation/inspector_task_queue.cc b/bridge/foundation/inspector_task_queue.cc index 3f4af75c5b..6fa4d5e5eb 100644 --- a/bridge/foundation/inspector_task_queue.cc +++ b/bridge/foundation/inspector_task_queue.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "inspector_task_queue.h" diff --git a/bridge/foundation/inspector_task_queue.h b/bridge/foundation/inspector_task_queue.h index fe0d52ffce..c899ddffd7 100644 --- a/bridge/foundation/inspector_task_queue.h +++ b/bridge/foundation/inspector_task_queue.h @@ -1,12 +1,13 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_INSPECTOR_TASK_QUEUE_H -#define KRAKENBRIDGE_INSPECTOR_TASK_QUEUE_H +#ifndef BRIDGE_INSPECTOR_TASK_QUEUE_H +#define BRIDGE_INSPECTOR_TASK_QUEUE_H -#include "kraken_foundation.h" #include "task_queue.h" +#include "webf_foundation.h" namespace foundation { @@ -37,4 +38,4 @@ class InspectorTaskQueue : public TaskQueue { } // namespace foundation -#endif // KRAKENBRIDGE_INSPECTOR_TASK_QUEUE_H +#endif // BRIDGE_INSPECTOR_TASK_QUEUE_H diff --git a/bridge/foundation/logging.cc b/bridge/foundation/logging.cc index cbfd79544e..65a0bac8bf 100644 --- a/bridge/foundation/logging.cc +++ b/bridge/foundation/logging.cc @@ -68,7 +68,7 @@ LogMessage::~LogMessage() { priority = ANDROID_LOG_ERROR; break; } - __android_log_write(priority, "KRAKEN_NATIVE_LOG", stream_.str().c_str()); + __android_log_write(priority, "WEBF_NATIVE_LOG", stream_.str().c_str()); #elif defined(IS_IOS) syslog(LOG_ALERT, "%s", stream_.str().c_str()); #else @@ -87,7 +87,7 @@ void pipeMessageToInspector(JSGlobalContextRef ctx, const std::string message, c JSObjectRef globalObjectRef = JSContextGetGlobalObject(ctx); auto client = JSObjectGetPrivate(globalObjectRef); if (client && client != ((void*)0x1)) { - auto client_impl = reinterpret_cast(client); + auto client_impl = reinterpret_cast(client); client_impl->sendMessageToConsole(logLevel, message); } }; @@ -97,35 +97,35 @@ void printLog(int32_t contextId, std::stringstream& stream, std::string level, v MessageLevel _log_level = MessageLevel::Info; switch (level[0]) { case 'l': - KRAKEN_LOG(VERBOSE) << stream.str(); + WEBF_LOG(VERBOSE) << stream.str(); _log_level = MessageLevel::Log; break; case 'i': - KRAKEN_LOG(INFO) << stream.str(); + WEBF_LOG(INFO) << stream.str(); _log_level = MessageLevel::Info; break; case 'd': - KRAKEN_LOG(DEBUG) << stream.str(); + WEBF_LOG(DEBUG) << stream.str(); _log_level = MessageLevel::Debug; break; case 'w': - KRAKEN_LOG(WARN) << stream.str(); + WEBF_LOG(WARN) << stream.str(); _log_level = MessageLevel::Warning; break; case 'e': - KRAKEN_LOG(ERROR) << stream.str(); + WEBF_LOG(ERROR) << stream.str(); _log_level = MessageLevel::Error; break; default: - KRAKEN_LOG(VERBOSE) << stream.str(); + WEBF_LOG(VERBOSE) << stream.str(); } - if (kraken::KrakenPage::consoleMessageHandler != nullptr) { - kraken::KrakenPage::consoleMessageHandler(ctx, stream.str(), static_cast(_log_level)); + if (webf::WebFPage::consoleMessageHandler != nullptr) { + webf::WebFPage::consoleMessageHandler(ctx, stream.str(), static_cast(_log_level)); } - if (kraken::getDartMethod()->onJsLog != nullptr) { - kraken::getDartMethod()->onJsLog(contextId, static_cast(_log_level), stream.str().c_str()); + if (webf::getDartMethod()->onJsLog != nullptr) { + webf::getDartMethod()->onJsLog(contextId, static_cast(_log_level), stream.str().c_str()); } } diff --git a/bridge/foundation/logging.h b/bridge/foundation/logging.h index eca7b33d8d..f2905644b5 100644 --- a/bridge/foundation/logging.h +++ b/bridge/foundation/logging.h @@ -2,13 +2,13 @@ * Copyright (C) 2022-present The Kraken authors. All rights reserved. */ -#ifndef KRAKEN_FOUNDATION_LOGGING_H_ -#define KRAKEN_FOUNDATION_LOGGING_H_ +#ifndef FOUNDATION_LOGGING_H_ +#define FOUNDATION_LOGGING_H_ #include #include -#include "include/kraken_bridge.h" +#include "include/webf_bridge.h" namespace foundation { @@ -48,19 +48,19 @@ class LogMessage { const char* file_; const int line_; - KRAKEN_DISALLOW_COPY_AND_ASSIGN(LogMessage); + DISALLOW_COPY_AND_ASSIGN(LogMessage); }; void printLog(int32_t contextId, std::stringstream& stream, std::string level, void* ctx); -#define KRAKEN_LOG_STREAM(severity) ::foundation::LogMessage(::foundation::severity, __FILE__, __LINE__, nullptr).stream() +#define WEBF_LOG_STREAM(severity) ::foundation::LogMessage(::foundation::severity, __FILE__, __LINE__, nullptr).stream() -#define KRAKEN_LAZY_STREAM(stream, condition) !(condition) ? (void)0 : foundation::LogMessageVoidify() & (stream) +#define WEBF_LAZY_STREAM(stream, condition) !(condition) ? (void)0 : foundation::LogMessageVoidify() & (stream) -#define KRAKEN_LOG(severity) KRAKEN_LAZY_STREAM(KRAKEN_LOG_STREAM(severity), true) +#define WEBF_LOG(severity) WEBF_LAZY_STREAM(WEBF_LOG_STREAM(severity), true) -#define KRAKEN_CHECK(condition) KRAKEN_LAZY_STREAM(::foundation::LogMessage(::foundation::FATAL, __FILE__, __LINE__, #condition).stream(), !(condition)) +#define WEBF_CHECK(condition) WEBF_LAZY_STREAM(::foundation::LogMessage(::foundation::FATAL, __FILE__, __LINE__, #condition).stream(), !(condition)) } // namespace foundation -#endif // KRAKEN_FOUNDATION_LOGGING_H_ +#endif // FOUNDATION_LOGGING_H_ diff --git a/bridge/foundation/ref_counted_internal.h b/bridge/foundation/ref_counted_internal.h index 25c11ac36e..d3e98cbc33 100644 --- a/bridge/foundation/ref_counted_internal.h +++ b/bridge/foundation/ref_counted_internal.h @@ -11,7 +11,7 @@ #define FLUTTER_FML_MEMORY_REF_COUNTED_INTERNAL_H_ #include -#include "include/kraken_bridge.h" +#include "include/webf_bridge.h" #include "logging.h" namespace fml { @@ -22,15 +22,15 @@ class RefCountedThreadSafeBase { public: void AddRef() const { #ifndef NDEBUG - KRAKEN_CHECK(!adoption_required_); - KRAKEN_CHECK(!destruction_started_); + WEBF_CHECK(!adoption_required_); + WEBF_CHECK(!destruction_started_); #endif ref_count_.fetch_add(1u, std::memory_order_relaxed); } bool HasOneRef() const { return ref_count_.load(std::memory_order_acquire) == 1u; } - void AssertHasOneRef() const { KRAKEN_CHECK(HasOneRef()); } + void AssertHasOneRef() const { WEBF_CHECK(HasOneRef()); } protected: RefCountedThreadSafeBase(); @@ -39,10 +39,10 @@ class RefCountedThreadSafeBase { // Returns true if the object should self-delete. bool Release() const { #ifndef NDEBUG - KRAKEN_CHECK(!adoption_required_); - KRAKEN_CHECK(!destruction_started_); + WEBF_CHECK(!adoption_required_); + WEBF_CHECK(!destruction_started_); #endif - KRAKEN_CHECK(ref_count_.load(std::memory_order_acquire) != 0u); + WEBF_CHECK(ref_count_.load(std::memory_order_acquire) != 0u); // TODO(vtl): We could add the following: // if (ref_count_.load(std::memory_order_relaxed) == 1u) { // #ifndef NDEBUG @@ -67,7 +67,7 @@ class RefCountedThreadSafeBase { #ifndef NDEBUG void Adopt() { - KRAKEN_CHECK(adoption_required_); + WEBF_CHECK(adoption_required_); adoption_required_ = false; } #endif @@ -80,7 +80,7 @@ class RefCountedThreadSafeBase { mutable bool destruction_started_; #endif - KRAKEN_DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafeBase); + DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafeBase); }; inline RefCountedThreadSafeBase::RefCountedThreadSafeBase() @@ -95,9 +95,9 @@ inline RefCountedThreadSafeBase::RefCountedThreadSafeBase() inline RefCountedThreadSafeBase::~RefCountedThreadSafeBase() { #ifndef NDEBUG - KRAKEN_CHECK(!adoption_required_); + WEBF_CHECK(!adoption_required_); // Should only be destroyed as a result of |Release()|. - KRAKEN_CHECK(destruction_started_); + WEBF_CHECK(destruction_started_); #endif } diff --git a/bridge/foundation/ref_counter.h b/bridge/foundation/ref_counter.h index adbaf0811d..ae8f77f980 100644 --- a/bridge/foundation/ref_counter.h +++ b/bridge/foundation/ref_counter.h @@ -119,7 +119,7 @@ class RefCountedThreadSafe : public internal::RefCountedThreadSafeBase { void Adopt() { internal::RefCountedThreadSafeBase::Adopt(); } #endif - KRAKEN_DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafe); + DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafe); }; // If you subclass |RefCountedThreadSafe| and want to keep your destructor diff --git a/bridge/foundation/ref_ptr.h b/bridge/foundation/ref_ptr.h index eab16fc2d7..c99bacf799 100644 --- a/bridge/foundation/ref_ptr.h +++ b/bridge/foundation/ref_ptr.h @@ -109,12 +109,12 @@ class RefPtr final { T* get() const { return ptr_; } T& operator*() const { - KRAKEN_CHECK(ptr_); + WEBF_CHECK(ptr_); return *ptr_; } T* operator->() const { - KRAKEN_CHECK(ptr_); + WEBF_CHECK(ptr_); return ptr_; } @@ -191,7 +191,7 @@ class RefPtr final { friend RefPtr AdoptRef(T*); enum AdoptTag { ADOPT }; - RefPtr(T* ptr, AdoptTag) : ptr_(ptr) { KRAKEN_CHECK(ptr_); } + RefPtr(T* ptr, AdoptTag) : ptr_(ptr) { WEBF_CHECK(ptr_); } T* ptr_; }; diff --git a/bridge/foundation/ref_ptr_internal.h b/bridge/foundation/ref_ptr_internal.h index 15e95e3ec3..b5be8004de 100644 --- a/bridge/foundation/ref_ptr_internal.h +++ b/bridge/foundation/ref_ptr_internal.h @@ -9,7 +9,7 @@ #define FLUTTER_FML_MEMORY_REF_PTR_INTERNAL_H_ #include -#include "include/kraken_bridge.h" +#include "include/webf_bridge.h" namespace fml { diff --git a/bridge/foundation/task_queue.cc b/bridge/foundation/task_queue.cc index 9dee3bc04f..084dc7b636 100644 --- a/bridge/foundation/task_queue.cc +++ b/bridge/foundation/task_queue.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "task_queue.h" diff --git a/bridge/foundation/task_queue.h b/bridge/foundation/task_queue.h index c99f19acf7..54d2ef065d 100644 --- a/bridge/foundation/task_queue.h +++ b/bridge/foundation/task_queue.h @@ -1,9 +1,10 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_TASK_QUEUE_H -#define KRAKENBRIDGE_TASK_QUEUE_H +#ifndef BRIDGE_TASK_QUEUE_H +#define BRIDGE_TASK_QUEUE_H #include #include @@ -36,4 +37,4 @@ class TaskQueue : public fml::RefCountedThreadSafe { } // namespace foundation -#endif // KRAKENBRIDGE_TASK_QUEUE_H +#endif // BRIDGE_TASK_QUEUE_H diff --git a/bridge/foundation/ui_command_buffer.cc b/bridge/foundation/ui_command_buffer.cc index 64fd8f784c..f38b67d7b4 100644 --- a/bridge/foundation/ui_command_buffer.cc +++ b/bridge/foundation/ui_command_buffer.cc @@ -4,7 +4,7 @@ #include "ui_command_buffer.h" #include "dart_methods.h" -#include "include/kraken_bridge.h" +#include "include/webf_bridge.h" namespace foundation { @@ -12,7 +12,7 @@ UICommandBuffer::UICommandBuffer(int32_t contextId) : contextId(contextId) {} void UICommandBuffer::addCommand(int32_t id, int32_t type, void* nativePtr, bool batchedUpdate) { if (batchedUpdate) { - kraken::getDartMethod()->requestBatchUpdate(contextId); + webf::getDartMethod()->requestBatchUpdate(contextId); update_batched = true; } @@ -23,7 +23,7 @@ void UICommandBuffer::addCommand(int32_t id, int32_t type, void* nativePtr, bool void UICommandBuffer::addCommand(int32_t id, int32_t type, void* nativePtr) { if (!update_batched) { #if FLUTTER_BACKEND - kraken::getDartMethod()->requestBatchUpdate(contextId); + webf::getDartMethod()->requestBatchUpdate(contextId); #endif update_batched = true; } @@ -35,7 +35,7 @@ void UICommandBuffer::addCommand(int32_t id, int32_t type, void* nativePtr) { void UICommandBuffer::addCommand(int32_t id, int32_t type, NativeString& args_01, void* nativePtr) { if (!update_batched) { #if FLUTTER_BACKEND - kraken::getDartMethod()->requestBatchUpdate(contextId); + webf::getDartMethod()->requestBatchUpdate(contextId); update_batched = true; #endif } @@ -47,7 +47,7 @@ void UICommandBuffer::addCommand(int32_t id, int32_t type, NativeString& args_01 void UICommandBuffer::addCommand(int32_t id, int32_t type, NativeString& args_01, NativeString& args_02, void* nativePtr) { #if FLUTTER_BACKEND if (!update_batched) { - kraken::getDartMethod()->requestBatchUpdate(contextId); + webf::getDartMethod()->requestBatchUpdate(contextId); update_batched = true; } #endif diff --git a/bridge/foundation/ui_command_buffer.h b/bridge/foundation/ui_command_buffer.h index bf25bac083..c365571647 100644 --- a/bridge/foundation/ui_command_buffer.h +++ b/bridge/foundation/ui_command_buffer.h @@ -2,10 +2,10 @@ * Copyright (C) 2020-present The Kraken authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_FOUNDATION_UI_COMMAND_BUFFER_H_ -#define KRAKENBRIDGE_FOUNDATION_UI_COMMAND_BUFFER_H_ +#ifndef BRIDGE_FOUNDATION_UI_COMMAND_BUFFER_H_ +#define BRIDGE_FOUNDATION_UI_COMMAND_BUFFER_H_ -#include "include/kraken_bridge.h" +#include "include/webf_bridge.h" namespace foundation { @@ -29,4 +29,4 @@ class UICommandBuffer { } // namespace foundation -#endif // KRAKENBRIDGE_FOUNDATION_UI_COMMAND_BUFFER_H_ +#endif // BRIDGE_FOUNDATION_UI_COMMAND_BUFFER_H_ diff --git a/bridge/foundation/ui_command_callback_queue.cc b/bridge/foundation/ui_command_callback_queue.cc index df3d0e0e0e..9013d5e9bf 100644 --- a/bridge/foundation/ui_command_callback_queue.cc +++ b/bridge/foundation/ui_command_callback_queue.cc @@ -2,7 +2,7 @@ * Copyright (C) 2020-present The Kraken authors. All rights reserved. */ -#include "kraken_bridge.h" +#include "webf_bridge.h" namespace foundation { diff --git a/bridge/foundation/ui_task_queue.cc b/bridge/foundation/ui_task_queue.cc index ae90b011a1..23e967be84 100644 --- a/bridge/foundation/ui_task_queue.cc +++ b/bridge/foundation/ui_task_queue.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "ui_task_queue.h" diff --git a/bridge/foundation/ui_task_queue.h b/bridge/foundation/ui_task_queue.h index fc730c1431..4a1764a941 100644 --- a/bridge/foundation/ui_task_queue.h +++ b/bridge/foundation/ui_task_queue.h @@ -2,8 +2,8 @@ * Copyright (C) 2019-present The Kraken authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_UI_TASK_QUEUE_H -#define KRAKENBRIDGE_UI_TASK_QUEUE_H +#ifndef BRIDGE_UI_TASK_QUEUE_H +#define BRIDGE_UI_TASK_QUEUE_H #include "task_queue.h" @@ -31,4 +31,4 @@ class UITaskQueue : public TaskQueue { } // namespace foundation -#endif // KRAKENBRIDGE_UI_TASK_QUEUE_H +#endif // BRIDGE_UI_TASK_QUEUE_H diff --git a/bridge/include/dart_methods.h b/bridge/include/dart_methods.h index dd8c519744..678b9e3f83 100644 --- a/bridge/include/dart_methods.h +++ b/bridge/include/dart_methods.h @@ -2,15 +2,15 @@ * Copyright (C) 2019-present The Kraken authors. All rights reserved. */ -#ifndef KRAKEN_DART_METHODS_H_ -#define KRAKEN_DART_METHODS_H_ +#ifndef WEBF_DART_METHODS_H_ +#define WEBF_DART_METHODS_H_ -#include "kraken_bridge.h" +#include "webf_bridge.h" #include #include -#define KRAKEN_EXPORT __attribute__((__visibility__("default"))) +#define WEBF_EXPORT __attribute__((__visibility__("default"))) struct NativeString; struct NativeScreen; @@ -56,7 +56,7 @@ struct MousePointer { using SimulatePointer = void (*)(MousePointer**, int32_t length, int32_t pointer); using SimulateInputText = void (*)(NativeString* nativeString); -namespace kraken { +namespace webf { struct DartMethodPointer { DartMethodPointer() = default; InvokeModule invokeModule{nullptr}; @@ -86,13 +86,13 @@ struct DartMethodPointer { void registerDartMethods(uint64_t* methodBytes, int32_t length); #ifdef IS_TEST -KRAKEN_EXPORT +WEBF_EXPORT void registerTestEnvDartMethods(uint64_t* methodBytes, int32_t length); #endif -KRAKEN_EXPORT +WEBF_EXPORT std::shared_ptr getDartMethod(); -} // namespace kraken +} // namespace webf #endif diff --git a/bridge/include/kraken_bridge.h b/bridge/include/webf_bridge.h similarity index 79% rename from bridge/include/kraken_bridge.h rename to bridge/include/webf_bridge.h index 6fb052d485..9793a47aca 100644 --- a/bridge/include/kraken_bridge.h +++ b/bridge/include/webf_bridge.h @@ -2,24 +2,19 @@ * Copyright (C) 2019-present The Kraken authors. All rights reserved. */ -#ifndef KRAKEN_BRIDGE_EXPORT_H -#define KRAKEN_BRIDGE_EXPORT_H +#ifndef WEBF_BRIDGE_EXPORT_H +#define WEBF_BRIDGE_EXPORT_H #include #include #include "dart_methods.h" -#include "kraken_foundation.h" +#include "webf_foundation.h" -#if KRAKEN_JSC_ENGINE -#include "kraken_bridge_jsc.h" -#elif KRAKEN_QUICK_JS_ENGINE -#endif +#define WEBF_EXPORT_C extern "C" __attribute__((visibility("default"))) __attribute__((used)) +#define WEBF_EXPORT __attribute__((__visibility__("default"))) -#define KRAKEN_EXPORT_C extern "C" __attribute__((visibility("default"))) __attribute__((used)) -#define KRAKEN_EXPORT __attribute__((__visibility__("default"))) - -KRAKEN_EXPORT +WEBF_EXPORT std::thread::id getUIThreadId(); struct NativeString { @@ -35,9 +30,9 @@ struct NativeByteCode { int32_t length; }; -struct KrakenInfo; +struct WebFInfo; -struct KrakenInfo { +struct WebFInfo { const char* app_name{nullptr}; const char* app_version{nullptr}; const char* app_revision{nullptr}; @@ -65,7 +60,7 @@ enum UICommand { createDocumentFragment, }; -struct KRAKEN_EXPORT UICommandItem { +struct WEBF_EXPORT UICommandItem { UICommandItem(int32_t id, int32_t type, NativeString args_01, NativeString args_02, void* nativePtr) : type(type), string_01(reinterpret_cast(args_01.string)), @@ -89,54 +84,54 @@ struct KRAKEN_EXPORT UICommandItem { typedef void (*Task)(void*); typedef void (*ConsoleMessageHandler)(void* ctx, const std::string& message, int logLevel); -KRAKEN_EXPORT_C +WEBF_EXPORT_C void initJSPagePool(int poolSize); -KRAKEN_EXPORT_C +WEBF_EXPORT_C void disposePage(int32_t contextId); -KRAKEN_EXPORT_C +WEBF_EXPORT_C int32_t allocateNewPage(int32_t targetContextId); -KRAKEN_EXPORT_C +WEBF_EXPORT_C void* getPage(int32_t contextId); bool checkPage(int32_t contextId); bool checkPage(int32_t contextId, void* context); -KRAKEN_EXPORT_C +WEBF_EXPORT_C void evaluateScripts(int32_t contextId, NativeString* code, const char* bundleFilename, int startLine); -KRAKEN_EXPORT_C +WEBF_EXPORT_C void evaluateQuickjsByteCode(int32_t contextId, uint8_t* bytes, int32_t byteLen); -KRAKEN_EXPORT_C +WEBF_EXPORT_C void parseHTML(int32_t contextId, const char* code, int32_t length); -KRAKEN_EXPORT_C +WEBF_EXPORT_C void reloadJsContext(int32_t contextId); -KRAKEN_EXPORT_C +WEBF_EXPORT_C void invokeModuleEvent(int32_t contextId, NativeString* module, const char* eventType, void* event, NativeString* extra); -KRAKEN_EXPORT_C +WEBF_EXPORT_C void registerDartMethods(uint64_t* methodBytes, int32_t length); -KRAKEN_EXPORT_C +WEBF_EXPORT_C NativeScreen* createScreen(double width, double height); -KRAKEN_EXPORT_C -KrakenInfo* getKrakenInfo(); -KRAKEN_EXPORT_C +WEBF_EXPORT_C +WebFInfo* getWebFInfo(); +WEBF_EXPORT_C void dispatchUITask(int32_t contextId, void* context, void* callback); -KRAKEN_EXPORT_C +WEBF_EXPORT_C void flushUITask(int32_t contextId); -KRAKEN_EXPORT_C +WEBF_EXPORT_C void registerUITask(int32_t contextId, Task task, void* data); -KRAKEN_EXPORT_C +WEBF_EXPORT_C void flushUICommandCallback(); -KRAKEN_EXPORT_C +WEBF_EXPORT_C UICommandItem* getUICommandItems(int32_t contextId); -KRAKEN_EXPORT_C +WEBF_EXPORT_C int64_t getUICommandItemSize(int32_t contextId); -KRAKEN_EXPORT_C +WEBF_EXPORT_C void clearUICommandItems(int32_t contextId); -KRAKEN_EXPORT_C +WEBF_EXPORT_C void registerContextDisposedCallbacks(int32_t contextId, Task task, void* data); -KRAKEN_EXPORT_C +WEBF_EXPORT_C void registerPluginByteCode(uint8_t* bytes, int32_t length, const char* pluginName); -KRAKEN_EXPORT_C +WEBF_EXPORT_C int32_t profileModeEnabled(); -KRAKEN_EXPORT +WEBF_EXPORT void setConsoleMessageHandler(ConsoleMessageHandler handler); -#endif // KRAKEN_BRIDGE_EXPORT_H +#endif // WEBF_BRIDGE_EXPORT_H diff --git a/bridge/include/kraken_bridge_test.h b/bridge/include/webf_bridge_test.h similarity index 74% rename from bridge/include/kraken_bridge_test.h rename to bridge/include/webf_bridge_test.h index 97a2c44c99..55eb6528f8 100644 --- a/bridge/include/kraken_bridge_test.h +++ b/bridge/include/webf_bridge_test.h @@ -2,23 +2,23 @@ * Copyright (C) 2019-present The Kraken authors. All rights reserved. */ -#ifndef KRAKEN_BRIDGE_TEST_EXPORT_H -#define KRAKEN_BRIDGE_TEST_EXPORT_H +#ifndef WEBF_BRIDGE_TEST_EXPORT_H +#define WEBF_BRIDGE_TEST_EXPORT_H #include -#include "kraken_bridge.h" +#include "webf_bridge.h" -KRAKEN_EXPORT_C +WEBF_EXPORT_C void initTestFramework(int32_t contextId); -KRAKEN_EXPORT_C +WEBF_EXPORT_C int8_t evaluateTestScripts(int32_t contextId, NativeString* code, const char* bundleFilename, int startLine); using ExecuteCallback = void* (*)(int32_t contextId, NativeString* status); -KRAKEN_EXPORT_C +WEBF_EXPORT_C void executeTest(int32_t contextId, ExecuteCallback executeCallback); -KRAKEN_EXPORT_C +WEBF_EXPORT_C void registerTestEnvDartMethods(uint64_t* methodBytes, int32_t length); #endif diff --git a/bridge/include/kraken_foundation.h b/bridge/include/webf_foundation.h similarity index 63% rename from bridge/include/kraken_foundation.h rename to bridge/include/webf_foundation.h index 30e27dedb1..d5293a0fd5 100644 --- a/bridge/include/kraken_foundation.h +++ b/bridge/include/webf_foundation.h @@ -3,8 +3,8 @@ * Author: Kraken Team. */ -#ifndef KRAKENBRIDGE_FOUNDATION_H -#define KRAKENBRIDGE_FOUNDATION_H +#ifndef BRIDGE_FOUNDATION_H +#define BRIDGE_FOUNDATION_H #include #include @@ -21,7 +21,7 @@ #define assert_m(exp, msg) assert(((void)msg, exp)) -#define KRAKEN_EXPORT __attribute__((__visibility__("default"))) +#define WEBF_EXPORT __attribute__((__visibility__("default"))) #if defined(__GNUC__) || defined(__clang__) #define LIKELY(x) __builtin_expect(!!(x), 1) @@ -33,27 +33,27 @@ #define FORCE_INLINE inline #endif -#define KRAKEN_DISALLOW_COPY(TypeName) TypeName(const TypeName&) = delete +#define DISALLOW_COPY(TypeName) TypeName(const TypeName&) = delete -#define KRAKEN_DISALLOW_ASSIGN(TypeName) TypeName& operator=(const TypeName&) = delete +#define DISALLOW_ASSIGN(TypeName) TypeName& operator=(const TypeName&) = delete -#define KRAKEN_DISALLOW_MOVE(TypeName) \ - TypeName(TypeName&&) = delete; \ +#define DISALLOW_MOVE(TypeName) \ + TypeName(TypeName&&) = delete; \ TypeName& operator=(TypeName&&) = delete -#define KRAKEN_DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName&) = delete; \ +#define DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName&) = delete; \ TypeName& operator=(const TypeName&) = delete -#define KRAKEN_DISALLOW_COPY_ASSIGN_AND_MOVE(TypeName) \ - TypeName(const TypeName&) = delete; \ - TypeName(TypeName&&) = delete; \ - TypeName& operator=(const TypeName&) = delete; \ +#define DISALLOW_COPY_ASSIGN_AND_MOVE(TypeName) \ + TypeName(const TypeName&) = delete; \ + TypeName(TypeName&&) = delete; \ + TypeName& operator=(const TypeName&) = delete; \ TypeName& operator=(TypeName&&) = delete -#define KRAKEN_DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ - TypeName() = delete; \ - KRAKEN_DISALLOW_COPY_ASSIGN_AND_MOVE(TypeName) +#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ + TypeName() = delete; \ + DISALLOW_COPY_ASSIGN_AND_MOVE(TypeName) struct NativeString; struct UICommandItem; @@ -65,9 +65,9 @@ class UICommandCallbackQueue { public: using Callback = void (*)(void*); UICommandCallbackQueue() = default; - static KRAKEN_EXPORT UICommandCallbackQueue* instance(); - KRAKEN_EXPORT void registerCallback(const Callback& callback, void* data); - KRAKEN_EXPORT void flushCallbacks(); + static WEBF_EXPORT UICommandCallbackQueue* instance(); + WEBF_EXPORT void registerCallback(const Callback& callback, void* data); + WEBF_EXPORT void flushCallbacks(); private: struct CallbackItem { diff --git a/bridge/page.cc b/bridge/page.cc index 356b57fd28..152a2c7062 100644 --- a/bridge/page.cc +++ b/bridge/page.cc @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "polyfill.h" @@ -43,16 +44,16 @@ #include "bindings/qjs/dom/text_node.h" #include "bindings/qjs/module_manager.h" -namespace kraken { +namespace webf { using namespace binding::qjs; -std::unordered_map KrakenPage::pluginByteCode{}; -ConsoleMessageHandler KrakenPage::consoleMessageHandler{nullptr}; +std::unordered_map WebFPage::pluginByteCode{}; +ConsoleMessageHandler WebFPage::consoleMessageHandler{nullptr}; -kraken::KrakenPage** KrakenPage::pageContextPool{nullptr}; +webf::WebFPage** WebFPage::pageContextPool{nullptr}; -KrakenPage::KrakenPage(int32_t contextId, const JSExceptionHandler& handler) : contextId(contextId) { +WebFPage::WebFPage(int32_t contextId, const JSExceptionHandler& handler) : contextId(contextId) { #if ENABLE_PROFILE auto jsContextStartTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); #endif @@ -105,7 +106,7 @@ KrakenPage::KrakenPage(int32_t contextId, const JSExceptionHandler& handler) : c nativePerformance.mark(PERF_JS_POLYFILL_INIT_START); #endif - initKrakenPolyFill(this); + initWebFPolyFill(this); for (auto& p : pluginByteCode) { evaluateByteCode(p.second.bytes, p.second.length); @@ -116,7 +117,7 @@ KrakenPage::KrakenPage(int32_t contextId, const JSExceptionHandler& handler) : c #endif } -bool KrakenPage::parseHTML(const char* code, size_t length) { +bool WebFPage::parseHTML(const char* code, size_t length) { if (!m_context->isValid()) return false; @@ -143,7 +144,7 @@ bool KrakenPage::parseHTML(const char* code, size_t length) { return true; } -void KrakenPage::invokeModuleEvent(NativeString* moduleName, const char* eventType, void* rawEvent, NativeString* extra) { +void WebFPage::invokeModuleEvent(NativeString* moduleName, const char* eventType, void* rawEvent, NativeString* extra) { if (!m_context->isValid()) return; @@ -186,7 +187,7 @@ void KrakenPage::invokeModuleEvent(NativeString* moduleName, const char* eventTy } } -void KrakenPage::evaluateScript(const NativeString* script, const char* url, int startLine) { +void WebFPage::evaluateScript(const NativeString* script, const char* url, int startLine) { if (!m_context->isValid()) return; @@ -200,42 +201,42 @@ void KrakenPage::evaluateScript(const NativeString* script, const char* url, int #endif } -void KrakenPage::evaluateScript(const uint16_t* script, size_t length, const char* url, int startLine) { +void WebFPage::evaluateScript(const uint16_t* script, size_t length, const char* url, int startLine) { if (!m_context->isValid()) return; m_context->evaluateJavaScript(script, length, url, startLine); } -void KrakenPage::evaluateScript(const char* script, size_t length, const char* url, int startLine) { +void WebFPage::evaluateScript(const char* script, size_t length, const char* url, int startLine) { if (!m_context->isValid()) return; m_context->evaluateJavaScript(script, length, url, startLine); } -uint8_t* KrakenPage::dumpByteCode(const char* script, size_t length, const char* url, size_t* byteLength) { +uint8_t* WebFPage::dumpByteCode(const char* script, size_t length, const char* url, size_t* byteLength) { if (!m_context->isValid()) return nullptr; return m_context->dumpByteCode(script, length, url, byteLength); } -void KrakenPage::evaluateByteCode(uint8_t* bytes, size_t byteLength) { +void WebFPage::evaluateByteCode(uint8_t* bytes, size_t byteLength) { if (!m_context->isValid()) return; m_context->evaluateByteCode(bytes, byteLength); } -KrakenPage::~KrakenPage() { +WebFPage::~WebFPage() { #if IS_TEST if (disposeCallback != nullptr) { disposeCallback(this); } #endif delete m_context; - KrakenPage::pageContextPool[contextId] = nullptr; + WebFPage::pageContextPool[contextId] = nullptr; } -void KrakenPage::reportError(const char* errmsg) { +void WebFPage::reportError(const char* errmsg) { m_handler(m_context->getContextId(), errmsg); } -} // namespace kraken +} // namespace webf diff --git a/bridge/page.h b/bridge/page.h index 4619d0ee2e..aa64bb1b85 100644 --- a/bridge/page.h +++ b/bridge/page.h @@ -1,37 +1,38 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKEN_JS_QJS_BRIDGE_H_ -#define KRAKEN_JS_QJS_BRIDGE_H_ +#ifndef WEBF_JS_QJS_BRIDGE_H_ +#define WEBF_JS_QJS_BRIDGE_H_ #include #include "bindings/qjs/executing_context.h" #include "bindings/qjs/html_parser.h" -#include "include/kraken_bridge.h" +#include "include/webf_bridge.h" #include #include #include -namespace kraken { +namespace webf { -class KrakenPage; -using JSBridgeDisposeCallback = void (*)(KrakenPage* bridge); +class WebFPage; +using JSBridgeDisposeCallback = void (*)(WebFPage* bridge); -/// KrakenPage is class which manage all js objects create by flutter widget. -/// Every flutter widgets have a corresponding KrakenPage, and all objects created by JavaScript are stored here, -/// and there is no data sharing between objects between different KrakenPages. -/// It's safe to allocate many KrakenPages at the same times on one thread, but not safe for multi-threads, only one thread can enter to KrakenPage at the same time. -class KrakenPage final { +/// WebFPage is class which manage all js objects create by flutter widget. +/// Every flutter widgets have a corresponding WebFPage, and all objects created by JavaScript are stored here, +/// and there is no data sharing between objects between different WebFPages. +/// It's safe to allocate many WebFPages at the same times on one thread, but not safe for multi-threads, only one thread can enter to WebFPage at the same time. +class WebFPage final { public: - static kraken::KrakenPage** pageContextPool; + static webf::WebFPage** pageContextPool; static ConsoleMessageHandler consoleMessageHandler; - KrakenPage() = delete; - KrakenPage(int32_t jsContext, const JSExceptionHandler& handler); - ~KrakenPage(); + WebFPage() = delete; + WebFPage(int32_t jsContext, const JSExceptionHandler& handler); + ~WebFPage(); - // Bytecodes which registered by kraken plugins. + // Bytecodes which registered by webf plugins. static std::unordered_map pluginByteCode; // evaluate JavaScript source codes in standard mode. @@ -42,7 +43,7 @@ class KrakenPage final { uint8_t* dumpByteCode(const char* script, size_t length, const char* url, size_t* byteLength); void evaluateByteCode(uint8_t* bytes, size_t byteLength); - [[nodiscard]] kraken::binding::qjs::ExecutionContext* getContext() const { return m_context; } + [[nodiscard]] webf::binding::qjs::ExecutionContext* getContext() const { return m_context; } void invokeModuleEvent(NativeString* moduleName, const char* eventType, void* event, NativeString* extra); void reportError(const char* errmsg); @@ -60,6 +61,6 @@ class KrakenPage final { JSExceptionHandler m_handler; }; -} // namespace kraken +} // namespace webf -#endif // KRAKEN_JS_QJS_BRIDGE_H_ +#endif // WEBF_JS_QJS_BRIDGE_H_ diff --git a/bridge/page_test.cc b/bridge/page_test.cc index 3b33757b9f..f3a85a1de5 100644 --- a/bridge/page_test.cc +++ b/bridge/page_test.cc @@ -6,15 +6,15 @@ #include "bindings/qjs/bom/blob.h" #include "testframework.h" -namespace kraken { +namespace webf { -bool KrakenPageTest::evaluateTestScripts(const uint16_t* code, size_t codeLength, const char* sourceURL, int startLine) { +bool WebFPageTest::evaluateTestScripts(const uint16_t* code, size_t codeLength, const char* sourceURL, int startLine) { if (!m_page_context->isValid()) return false; return m_page_context->evaluateJavaScript(code, codeLength, sourceURL, startLine); } -bool KrakenPageTest::parseTestHTML(const uint16_t* code, size_t codeLength) { +bool WebFPageTest::parseTestHTML(const uint16_t* code, size_t codeLength) { if (!m_page_context->isValid()) return false; std::string utf8Code = toUTF8(std::u16string(reinterpret_cast(code), codeLength)); @@ -31,8 +31,8 @@ static JSValue executeTest(JSContext* ctx, JSValueConst this_val, int argc, JSVa if (!JS_IsFunction(ctx, callback)) { return JS_ThrowTypeError(ctx, "Failed to execute 'executeTest': parameter 1 (callback) is not an function."); } - auto bridge = static_cast(context->getOwner()); - auto bridgeTest = static_cast(bridge->owner); + auto bridge = static_cast(context->getOwner()); + auto bridgeTest = static_cast(bridge->owner); JS_DupValue(ctx, callback); bridgeTest->executeTestCallback = callback; return JS_NULL; @@ -45,32 +45,32 @@ static JSValue matchImageSnapshot(JSContext* ctx, JSValueConst this_val, int arg auto* context = static_cast(JS_GetContextOpaque(ctx)); if (!JS_IsObject(blobValue)) { - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_match_image_snapshot__': parameter 1 (blob) must be an Blob object."); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_match_image_snapshot__': parameter 1 (blob) must be an Blob object."); } - auto blob = static_cast(JS_GetOpaque(blobValue, kraken::binding::qjs::Blob::kBlobClassID)); + auto blob = static_cast(JS_GetOpaque(blobValue, webf::binding::qjs::Blob::kBlobClassID)); if (blob == nullptr) { - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_match_image_snapshot__': parameter 1 (blob) must be an Blob object."); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_match_image_snapshot__': parameter 1 (blob) must be an Blob object."); } if (!JS_IsString(screenShotValue)) { - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_match_image_snapshot__': parameter 2 (match) must be an string."); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_match_image_snapshot__': parameter 2 (match) must be an string."); } if (!JS_IsObject(callbackValue)) { - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_match_image_snapshot__': parameter 3 (callback) is not an function."); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_match_image_snapshot__': parameter 3 (callback) is not an function."); } if (!JS_IsFunction(ctx, callbackValue)) { - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_match_image_snapshot__': parameter 3 (callback) is not an function."); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_match_image_snapshot__': parameter 3 (callback) is not an function."); } if (getDartMethod()->matchImageSnapshot == nullptr) { - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_match_image_snapshot__': dart method (matchImageSnapshot) is not registered."); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_match_image_snapshot__': dart method (matchImageSnapshot) is not registered."); } - std::unique_ptr screenShotNativeString = kraken::binding::qjs::jsValueToNativeString(ctx, screenShotValue); - auto bridge = static_cast(static_cast(context->getOwner())->owner); + std::unique_ptr screenShotNativeString = webf::binding::qjs::jsValueToNativeString(ctx, screenShotValue); + auto bridge = static_cast(static_cast(context->getOwner())->owner); auto* callbackContext = new ImageSnapShotContext{JS_DupValue(ctx, callbackValue), context}; list_add_tail(&callbackContext->link, &bridge->image_link); @@ -102,7 +102,7 @@ static JSValue matchImageSnapshot(JSContext* ctx, JSValueConst this_val, int arg static JSValue environment(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) { #if FLUTTER_BACKEND if (getDartMethod()->environment == nullptr) { - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_environment__': dart method (environment) is not registered."); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_environment__': dart method (environment) is not registered."); } const char* env = getDartMethod()->environment(); return JS_ParseJSON(ctx, env, strlen(env), ""); @@ -113,19 +113,19 @@ static JSValue environment(JSContext* ctx, JSValueConst this_val, int argc, JSVa static JSValue simulatePointer(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) { if (getDartMethod()->simulatePointer == nullptr) { - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_simulate_pointer__': dart method(simulatePointer) is not registered."); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_simulate_pointer__': dart method(simulatePointer) is not registered."); } auto* context = static_cast(JS_GetContextOpaque(ctx)); JSValue inputArrayValue = argv[0]; if (!JS_IsObject(inputArrayValue)) { - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_simulate_pointer__': first arguments should be an array."); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_simulate_pointer__': first arguments should be an array."); } JSValue pointerValue = argv[1]; if (!JS_IsNumber(pointerValue)) { - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_simulate_pointer__': second arguments should be an number."); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_simulate_pointer__': second arguments should be an number."); } uint32_t length; @@ -174,16 +174,16 @@ static JSValue simulatePointer(JSContext* ctx, JSValueConst this_val, int argc, static JSValue simulateInputText(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) { if (getDartMethod()->simulateInputText == nullptr) { - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_simulate_keypress__': dart method(simulateInputText) is not registered."); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_simulate_keypress__': dart method(simulateInputText) is not registered."); } JSValue& charStringValue = argv[0]; if (!JS_IsString(charStringValue)) { - return JS_ThrowTypeError(ctx, "Failed to execute '__kraken_simulate_keypress__': first arguments should be a string"); + return JS_ThrowTypeError(ctx, "Failed to execute '__webf_simulate_keypress__': first arguments should be a string"); } - std::unique_ptr nativeString = kraken::binding::qjs::jsValueToNativeString(ctx, charStringValue); + std::unique_ptr nativeString = webf::binding::qjs::jsValueToNativeString(ctx, charStringValue); getDartMethod()->simulateInputText(nativeString.get()); nativeString->free(); return JS_NULL; @@ -221,18 +221,18 @@ static JSValue triggerGlobalError(JSContext* ctx, JSValueConst this_val, int arg return JS_NULL; } -KrakenPageTest::KrakenPageTest(KrakenPage* bridge) : m_page(bridge), m_page_context(bridge->getContext()) { +WebFPageTest::WebFPageTest(WebFPage* bridge) : m_page(bridge), m_page_context(bridge->getContext()) { bridge->owner = this; - bridge->disposeCallback = [](KrakenPage* bridge) { delete static_cast(bridge->owner); }; - QJS_GLOBAL_BINDING_FUNCTION(m_page_context, executeTest, "__kraken_execute_test__", 1); - QJS_GLOBAL_BINDING_FUNCTION(m_page_context, matchImageSnapshot, "__kraken_match_image_snapshot__", 3); - QJS_GLOBAL_BINDING_FUNCTION(m_page_context, environment, "__kraken_environment__", 0); - QJS_GLOBAL_BINDING_FUNCTION(m_page_context, simulatePointer, "__kraken_simulate_pointer__", 1); - QJS_GLOBAL_BINDING_FUNCTION(m_page_context, simulateInputText, "__kraken_simulate_inputtext__", 1); - QJS_GLOBAL_BINDING_FUNCTION(m_page_context, triggerGlobalError, "__kraken_trigger_global_error__", 0); - QJS_GLOBAL_BINDING_FUNCTION(m_page_context, parseHTML, "__kraken_parse_html__", 1); - - initKrakenTestFramework(bridge); + bridge->disposeCallback = [](WebFPage* bridge) { delete static_cast(bridge->owner); }; + QJS_GLOBAL_BINDING_FUNCTION(m_page_context, executeTest, "__webf_execute_test__", 1); + QJS_GLOBAL_BINDING_FUNCTION(m_page_context, matchImageSnapshot, "__webf_match_image_snapshot__", 3); + QJS_GLOBAL_BINDING_FUNCTION(m_page_context, environment, "__webf_environment__", 0); + QJS_GLOBAL_BINDING_FUNCTION(m_page_context, simulatePointer, "__webf_simulate_pointer__", 1); + QJS_GLOBAL_BINDING_FUNCTION(m_page_context, simulateInputText, "__webf_simulate_inputtext__", 1); + QJS_GLOBAL_BINDING_FUNCTION(m_page_context, triggerGlobalError, "__webf_trigger_global_error__", 0); + QJS_GLOBAL_BINDING_FUNCTION(m_page_context, parseHTML, "__webf_parse_html__", 1); + + initWebFTestFramework(bridge); init_list_head(&image_link); } @@ -244,7 +244,7 @@ struct ExecuteCallbackContext { binding::qjs::ExecutionContext* context; }; -void KrakenPageTest::invokeExecuteTest(ExecuteCallback executeCallback) { +void WebFPageTest::invokeExecuteTest(ExecuteCallback executeCallback) { if (JS_IsNull(executeTestCallback)) { return; } @@ -261,7 +261,7 @@ void KrakenPageTest::invokeExecuteTest(ExecuteCallback executeCallback) { return JS_ThrowTypeError(ctx, "failed to execute 'done': parameter 1 (status) is not a string"); } - std::unique_ptr status = kraken::binding::qjs::jsValueToNativeString(ctx, statusValue); + std::unique_ptr status = webf::binding::qjs::jsValueToNativeString(ctx, statusValue); callbackContext->executeCallback(callbackContext->context->getContextId(), status.get()); return JS_NULL; }; @@ -280,4 +280,4 @@ void KrakenPageTest::invokeExecuteTest(ExecuteCallback executeCallback) { executeTestCallback = JS_NULL; } -} // namespace kraken +} // namespace webf diff --git a/bridge/page_test.h b/bridge/page_test.h index c2f186c80e..38e8363451 100644 --- a/bridge/page_test.h +++ b/bridge/page_test.h @@ -2,15 +2,15 @@ * Copyright (C) 2020-present The Kraken authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_PAGE_TEST_H -#define KRAKENBRIDGE_PAGE_TEST_H +#ifndef BRIDGE_PAGE_TEST_H +#define BRIDGE_PAGE_TEST_H #include "bindings/qjs/dom/document.h" #include "bindings/qjs/html_parser.h" -#include "kraken_bridge_test.h" #include "page.h" +#include "webf_bridge_test.h" -namespace kraken { +namespace webf { struct ImageSnapShotContext { JSValue callback; @@ -18,12 +18,12 @@ struct ImageSnapShotContext { list_head link; }; -class KrakenPageTest final { +class WebFPageTest final { public: - explicit KrakenPageTest() = delete; - explicit KrakenPageTest(KrakenPage* bridge); + explicit WebFPageTest() = delete; + explicit WebFPageTest(WebFPage* bridge); - ~KrakenPageTest() { + ~WebFPageTest() { if (!JS_IsNull(executeTestCallback)) { JS_FreeValue(m_page_context->ctx(), executeTestCallback); } @@ -51,11 +51,11 @@ class KrakenPageTest final { private: /// the pointer of bridge, ownership belongs to JSBridge - KrakenPage* m_page; + WebFPage* m_page; /// the pointer of JSContext, overship belongs to JSContext binding::qjs::ExecutionContext* m_page_context; }; -} // namespace kraken +} // namespace webf -#endif // KRAKENBRIDGE_PAGE_TEST_H +#endif // BRIDGE_PAGE_TEST_H diff --git a/bridge/polyfill/package.json b/bridge/polyfill/package.json index d0941dd569..168ec28fa4 100644 --- a/bridge/polyfill/package.json +++ b/bridge/polyfill/package.json @@ -1,6 +1,6 @@ { "private": true, - "description": "JavaScript polyfill for kraken", + "description": "JavaScript polyfill for webf", "main": "dist/index.js", "scripts": { "build": "NODE_ENV=development rollup --config rollup.config.js && npm run mainToC && npm run testToC", diff --git a/bridge/polyfill/rollup.config.js b/bridge/polyfill/rollup.config.js index 4aad8f2e86..ef2ef59612 100644 --- a/bridge/polyfill/rollup.config.js +++ b/bridge/polyfill/rollup.config.js @@ -26,7 +26,7 @@ const plugins = [ resolve(), replace({ 'process.env.NODE_ENV': JSON.stringify(NODE_ENV), - ['import \'es6-promise/dist/es6-promise.auto\'']: (process.env.PATCH_PROMISE_POLYFILL === 'true' && process.env.KRAKEN_JS_ENGINE === 'jsc') ? + ['import \'es6-promise/dist/es6-promise.auto\'']: (process.env.PATCH_PROMISE_POLYFILL === 'true' && process.env.WEBF_JS_ENGINE === 'jsc') ? 'import \'es6-promise/dist/es6-promise.auto\';' : '', delimiters: ['', ''], preventAssignment: false diff --git a/bridge/polyfill/scripts/js_to_c.js b/bridge/polyfill/scripts/js_to_c.js index c25cbc873e..a606299f08 100644 --- a/bridge/polyfill/scripts/js_to_c.js +++ b/bridge/polyfill/scripts/js_to_c.js @@ -27,20 +27,20 @@ function strEncodeUTF8(str) { } const getPolyFillHeader = (outputName) => `/* - * Copyright (C) 2022-present The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKEN_${outputName.toUpperCase()}_H -#define KRAKEN_${outputName.toUpperCase()}_H +#ifndef ${outputName.toUpperCase()}_H +#define ${outputName.toUpperCase()}_H -#if KRAKEN_JSC_ENGINE +#if WEBF_JSC_ENGINE #include "bridge_jsc.h" -#elif KRAKEN_QUICK_JS_ENGINE +#elif WEBF_QUICK_JS_ENGINE #include "page.h" #endif -void initKraken${outputName}(kraken::KrakenPage *page); +void initWebF${outputName}(webf::WebFPage *page); -#endif // KRAKEN_${outputName.toUpperCase()}_H +#endif // ${outputName.toUpperCase()}_H `; const getPolyFillJavaScriptSource = (source) => { @@ -57,14 +57,15 @@ const getPolyfillEvalCall = () => { } const getPolyFillSource = (source, outputName) => `/* - * Copyright (C) 2022-present The Kraken authors. All rights reserved. - */ +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ #include "${outputName.toLowerCase()}.h" ${getPolyFillJavaScriptSource(source)} -void initKraken${outputName}(kraken::KrakenPage *page) { +void initWebF${outputName}(webf::WebFPage *page) { ${getPolyfillEvalCall()} } `; diff --git a/bridge/polyfill/src/async-storage.ts b/bridge/polyfill/src/async-storage.ts index 546f2d3c6d..1bff58605a 100644 --- a/bridge/polyfill/src/async-storage.ts +++ b/bridge/polyfill/src/async-storage.ts @@ -1,9 +1,14 @@ -import { kraken } from './kraken'; +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +import { webf } from './webf'; export const asyncStorage = { getItem(key: number | string) { return new Promise((resolve, reject) => { - kraken.invokeModule('AsyncStorage', 'getItem', String(key), (e, data) => { + webf.invokeModule('AsyncStorage', 'getItem', String(key), (e, data) => { if (e) return reject(e); resolve(data == null ? '' : data); }); @@ -11,7 +16,7 @@ export const asyncStorage = { }, setItem(key: number | string, value: number | string) { return new Promise((resolve, reject) => { - kraken.invokeModule('AsyncStorage', 'setItem', [String(key), String(value)], (e, data) => { + webf.invokeModule('AsyncStorage', 'setItem', [String(key), String(value)], (e, data) => { if (e) return reject(e); resolve(data); }); @@ -19,7 +24,7 @@ export const asyncStorage = { }, removeItem(key: number | string) { return new Promise((resolve, reject) => { - kraken.invokeModule('AsyncStorage', 'removeItem', String(key), (e, data) => { + webf.invokeModule('AsyncStorage', 'removeItem', String(key), (e, data) => { if (e) return reject(e); resolve(data); }); @@ -27,7 +32,7 @@ export const asyncStorage = { }, clear() { return new Promise((resolve, reject) => { - kraken.invokeModule('AsyncStorage', 'clear', '', (e, data) => { + webf.invokeModule('AsyncStorage', 'clear', '', (e, data) => { if (e) return reject(e); resolve(data); }); @@ -35,7 +40,7 @@ export const asyncStorage = { }, getAllKeys() { return new Promise((resolve, reject) => { - kraken.invokeModule('AsyncStorage', 'getAllKeys', '', (e, data) => { + webf.invokeModule('AsyncStorage', 'getAllKeys', '', (e, data) => { if (e) return reject(e); resolve(data); }); @@ -43,7 +48,7 @@ export const asyncStorage = { }, length(): Promise { return new Promise((resolve, reject) => { - kraken.invokeModule('AsyncStorage', 'length', '', (e, data) => { + webf.invokeModule('AsyncStorage', 'length', '', (e, data) => { if (e) return reject(e); resolve(data); }); diff --git a/bridge/polyfill/src/bridge.ts b/bridge/polyfill/src/bridge.ts index 6d6e681b05..30da7c8b40 100644 --- a/bridge/polyfill/src/bridge.ts +++ b/bridge/polyfill/src/bridge.ts @@ -1,26 +1,13 @@ +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ -export interface KrakenBlob { - size: number; - type: string; - slice(start?: number, end?: number, contentType?: string): KrakenBlob; - text(): string; - arrayBuffer(): ArrayBuffer; -} +declare const __webf_invoke_module__: (module: string, method: string, params?: Object | null, fn?: (err: Error, data: any) => void) => string; +export const webfInvokeModule = __webf_invoke_module__; -export interface PrivateKraken { - appName: string; - appVersion: string; - platform: string; - product: string; - productSub: string; - comment: string; -} +declare const __webf_module_listener__: (fn: (moduleName: string, event: Event, extra: string) => void) => void; +export const addWebfModuleListener = __webf_module_listener__; -declare const __kraken_invoke_module__: (module: string, method: string, params?: Object | null, fn?: (err: Error, data: any) => void) => string; -export const krakenInvokeModule = __kraken_invoke_module__; - -declare const __kraken_module_listener__: (fn: (moduleName: string, event: Event, extra: string) => void) => void; -export const addKrakenModuleListener = __kraken_module_listener__; - -declare const __kraken_print__: (log: string, level?: string) => void; -export const krakenPrint = __kraken_print__; +declare const __webf_print__: (log: string, level?: string) => void; +export const webfPrint = __webf_print__; diff --git a/bridge/polyfill/src/connection.ts b/bridge/polyfill/src/connection.ts index 4daf1b9edb..63e01c088d 100644 --- a/bridge/polyfill/src/connection.ts +++ b/bridge/polyfill/src/connection.ts @@ -1,4 +1,9 @@ -import { krakenInvokeModule } from './bridge'; +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +import { webfInvokeModule } from './bridge'; let connectivityChangeListener: (data: Object) => any; @@ -11,7 +16,7 @@ export function dispatchConnectivityChangeEvent(event: any) { export default { getConnectivity() { return new Promise((resolve, reject) => { - krakenInvokeModule('Connection', 'getConnectivity', null, (e, data) => { + webfInvokeModule('Connection', 'getConnectivity', null, (e, data) => { if (e) return reject(e); resolve(data); }); @@ -21,7 +26,7 @@ export default { if (typeof listener === 'function') { connectivityChangeListener = listener; // TODO: should remove old listener when onchange reset with a null listener - krakenInvokeModule('Connection', 'onConnectivityChanged'); + webfInvokeModule('Connection', 'onConnectivityChanged'); } } } diff --git a/bridge/polyfill/src/console.ts b/bridge/polyfill/src/console.ts index 5241f80323..85be51a452 100644 --- a/bridge/polyfill/src/console.ts +++ b/bridge/polyfill/src/console.ts @@ -1,5 +1,10 @@ +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + // https://console.spec.whatwg.org/ -import { krakenPrint } from './bridge'; +import { webfPrint } from './bridge'; const SEPARATOR = ' '; const INTERPOLATE = /%[sdifoO]/g; @@ -20,7 +25,7 @@ function printer(message: string, level?: string) { message = groupIndent + message; } - krakenPrint(message, level); + webfPrint(message, level); } /** diff --git a/bridge/polyfill/src/cookie.ts b/bridge/polyfill/src/cookie.ts index 23d3a4eab3..011b13e278 100644 --- a/bridge/polyfill/src/cookie.ts +++ b/bridge/polyfill/src/cookie.ts @@ -1,3 +1,8 @@ +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + const cookieStorage = {}; // @TODO Persisent cookie and Session cookie support diff --git a/bridge/polyfill/src/dom.ts b/bridge/polyfill/src/dom.ts index 310f383153..f21734f7ed 100644 --- a/bridge/polyfill/src/dom.ts +++ b/bridge/polyfill/src/dom.ts @@ -1,3 +1,8 @@ +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + let html = document.createElement('html'); document.appendChild(html); diff --git a/bridge/polyfill/src/events.ts b/bridge/polyfill/src/events.ts index c693c664e7..59e35d285c 100644 --- a/bridge/polyfill/src/events.ts +++ b/bridge/polyfill/src/events.ts @@ -1,3 +1,8 @@ +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + const builtInWindowEvents = [ "onclick", "ondblclick", diff --git a/bridge/polyfill/src/fetch.ts b/bridge/polyfill/src/fetch.ts index ec86872cfb..8ea520890b 100644 --- a/bridge/polyfill/src/fetch.ts +++ b/bridge/polyfill/src/fetch.ts @@ -1,4 +1,9 @@ -import { kraken } from './kraken'; +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +import { webf } from './webf'; function normalizeName(name: any) { if (typeof name !== 'string') { @@ -272,7 +277,7 @@ export function fetch(input: Request | string, init?: RequestInit) { headers = new Headers(headers); } - kraken.invokeModule('Fetch', url, ({ + webf.invokeModule('Fetch', url, ({ ...init, headers: (headers as Headers).map }), (e, data) => { diff --git a/bridge/polyfill/src/global-event-handlers.ts b/bridge/polyfill/src/global-event-handlers.ts index 3ece2e121f..8342dba2cc 100644 --- a/bridge/polyfill/src/global-event-handlers.ts +++ b/bridge/polyfill/src/global-event-handlers.ts @@ -1,3 +1,8 @@ +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + // IDL definitions for GlobalEventHandlers // https://html.spec.whatwg.org/multipage/webappapis.html#idl-definitions diff --git a/bridge/polyfill/src/helpers.ts b/bridge/polyfill/src/helpers.ts index 5a10e76a4e..36d5b21164 100644 --- a/bridge/polyfill/src/helpers.ts +++ b/bridge/polyfill/src/helpers.ts @@ -1,3 +1,8 @@ +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + export function initPropertyHandlersForEventTargets(eventTarget: EventTarget, builtInEvents: string[]) { for (let i = 0; i < builtInEvents.length; i ++) { let eventName = builtInEvents[i]; diff --git a/bridge/polyfill/src/history.ts b/bridge/polyfill/src/history.ts index aff2ca4b84..cd8b349aba 100644 --- a/bridge/polyfill/src/history.ts +++ b/bridge/polyfill/src/history.ts @@ -1,27 +1,32 @@ -import { kraken } from './kraken'; +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +import { webf } from './webf'; class History { constructor() { } get length() { - return Number(kraken.invokeModule('History', 'length')); + return Number(webf.invokeModule('History', 'length')); } get state() { - return JSON.parse(kraken.invokeModule('History', 'state')); + return JSON.parse(webf.invokeModule('History', 'state')); } back() { - kraken.invokeModule('History', 'back'); + webf.invokeModule('History', 'back'); } forward() { - kraken.invokeModule('History', 'forward'); + webf.invokeModule('History', 'forward'); } go(delta?: number) { - kraken.invokeModule('History', 'go', delta ? Number(delta) : null); + webf.invokeModule('History', 'go', delta ? Number(delta) : null); } pushState(state: any, title: string, url?: string) { @@ -29,7 +34,7 @@ class History { throw TypeError("Failed to execute 'pushState' on 'History': 2 arguments required, but only " + arguments.length + " present"); } - kraken.invokeModule('History', 'pushState', [state, title, url]); + webf.invokeModule('History', 'pushState', [state, title, url]); } replaceState(state: any, title: string, url?: string) { @@ -37,7 +42,7 @@ class History { throw TypeError("Failed to execute 'pushState' on 'History': 2 arguments required, but only " + arguments.length + " present"); } - kraken.invokeModule('History', 'replaceState', [state, title, url]); + webf.invokeModule('History', 'replaceState', [state, title, url]); } } diff --git a/bridge/polyfill/src/index.ts b/bridge/polyfill/src/index.ts index ab7b4a2ac7..05119be5e9 100644 --- a/bridge/polyfill/src/index.ts +++ b/bridge/polyfill/src/index.ts @@ -1,3 +1,8 @@ +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + import 'es6-promise/dist/es6-promise.auto'; import './dom'; import './query-selector'; @@ -11,7 +16,7 @@ import { XMLHttpRequest } from './xhr'; import { asyncStorage } from './async-storage'; import { URLSearchParams } from './url-search-params'; import { URL } from './url'; -import { kraken } from './kraken'; +import { webf } from './webf'; import { ErrorEvent, PromiseRejectionEvent } from './events'; defineGlobalProperty('ErrorEvent', ErrorEvent); @@ -29,7 +34,7 @@ defineGlobalProperty('XMLHttpRequest', XMLHttpRequest); defineGlobalProperty('asyncStorage', asyncStorage); defineGlobalProperty('URLSearchParams', URLSearchParams); defineGlobalProperty('URL', URL); -defineGlobalProperty('kraken', kraken); +defineGlobalProperty('webf', webf); defineGlobalProperty('ErrorEvent', ErrorEvent); function defineGlobalProperty(key: string, value: any, isEnumerable: boolean = true) { diff --git a/bridge/polyfill/src/location.ts b/bridge/polyfill/src/location.ts index 65319e9627..6ab99c2d36 100644 --- a/bridge/polyfill/src/location.ts +++ b/bridge/polyfill/src/location.ts @@ -1,21 +1,26 @@ +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + import { URL } from './url'; -import { kraken } from './kraken'; +import { webf } from './webf'; // @ts-ignore -const krakenLocation = window.__location__; +const webfLocation = window.__location__; // Lazy parse url. let _url: URL; export function getUrl() : URL { return _url ? _url : (_url = new URL(location.href)); } -const bindReload = krakenLocation.reload.bind(krakenLocation); +const bindReload = webfLocation.reload.bind(webfLocation); export const location = { get href() { - return kraken.invokeModule('Location', 'getHref'); + return webf.invokeModule('Location', 'getHref'); }, set href(url: string) { - kraken.invokeModule('Navigation', 'goTo', url); + webf.invokeModule('Navigation', 'goTo', url); }, get origin() { return getUrl().origin; @@ -44,7 +49,7 @@ export const location = { get assign() { return (assignURL: string) => { - kraken.invokeModule('Navigation', 'goTo', assignURL); + webf.invokeModule('Navigation', 'goTo', assignURL); }; }, get reload() { @@ -52,7 +57,7 @@ export const location = { }, get replace() { return (replaceURL: string) => { - kraken.invokeModule('Navigation', 'goTo', replaceURL); + webf.invokeModule('Navigation', 'goTo', replaceURL); }; }, get toString() { diff --git a/bridge/polyfill/src/match-media.ts b/bridge/polyfill/src/match-media.ts index 0b33b7cca6..3ddbed0b43 100644 --- a/bridge/polyfill/src/match-media.ts +++ b/bridge/polyfill/src/match-media.ts @@ -1,3 +1,7 @@ +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ // https://github.com/ericf/css-mediaquery const RE_MEDIA_QUERY = /^(?:(only|not)?\s*([_a-z][_a-z0-9-]*)|(\([^\)]+\)))(?:\s*and\s*(.*))?$/i; diff --git a/bridge/polyfill/src/method-channel.ts b/bridge/polyfill/src/method-channel.ts index e93a9afafa..179623c855 100644 --- a/bridge/polyfill/src/method-channel.ts +++ b/bridge/polyfill/src/method-channel.ts @@ -1,4 +1,9 @@ -import { krakenInvokeModule } from './bridge'; +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +import { webfInvokeModule } from './bridge'; type MethodCallHandler = (method: string, args: any[]) => void; @@ -7,7 +12,7 @@ let methodCallHandlers: MethodCallHandler[] = []; // Like flutter platform channels export const methodChannel = { setMethodCallHandler(handler: MethodCallHandler) { - console.warn('kraken.methodChannel.setMethodCallHandler is a Deprecated API, use kraken.methodChannel.addMethodCallHandler instead.'); + console.warn('webf.methodChannel.setMethodCallHandler is a Deprecated API, use webf.methodChannel.addMethodCallHandler instead.'); methodChannel.addMethodCallHandler(handler); }, addMethodCallHandler(handler: MethodCallHandler) { @@ -24,7 +29,7 @@ export const methodChannel = { }, invokeMethod(method: string, ...args: any[]): Promise { return new Promise((resolve, reject) => { - krakenInvokeModule('MethodChannel', 'invokeMethod', [method, args], (e, data) => { + webfInvokeModule('MethodChannel', 'invokeMethod', [method, args], (e, data) => { if (e) return reject(e); resolve(data); }); diff --git a/bridge/polyfill/src/navigator.ts b/bridge/polyfill/src/navigator.ts index 31e01069bf..fbf87bd8a5 100644 --- a/bridge/polyfill/src/navigator.ts +++ b/bridge/polyfill/src/navigator.ts @@ -1,35 +1,40 @@ -import { kraken } from './kraken'; +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +import { webf } from './webf'; import connection from './connection'; export const navigator = { connection, // UA is read-only. get userAgent() { - return kraken.invokeModule('Navigator', 'getUserAgent'); + return webf.invokeModule('Navigator', 'getUserAgent'); }, get platform() { - return kraken.invokeModule('Navigator', 'getPlatform'); + return webf.invokeModule('Navigator', 'getPlatform'); }, get language() { - return kraken.invokeModule('Navigator', 'getLanguage'); + return webf.invokeModule('Navigator', 'getLanguage'); }, get languages() { - return JSON.parse(kraken.invokeModule('Navigator', 'getLanguages')); + return JSON.parse(webf.invokeModule('Navigator', 'getLanguages')); }, get appName() { - return kraken.invokeModule('Navigator', 'getAppName'); + return webf.invokeModule('Navigator', 'getAppName'); }, get appVersion() { - return kraken.invokeModule('Navigator', 'getAppVersion'); + return webf.invokeModule('Navigator', 'getAppVersion'); }, get hardwareConcurrency() { - const logicalProcessors = kraken.invokeModule('Navigator', 'getHardwareConcurrency'); + const logicalProcessors = webf.invokeModule('Navigator', 'getHardwareConcurrency'); return parseInt(logicalProcessors); }, clipboard: { readText() { return new Promise((resolve, reject) => { - kraken.invokeModule('Clipboard', 'readText', null, (e, data) => { + webf.invokeModule('Clipboard', 'readText', null, (e, data) => { if (e) { return reject(e); } @@ -39,7 +44,7 @@ export const navigator = { }, writeText(text: string) { return new Promise((resolve, reject) => { - kraken.invokeModule('Clipboard', 'writeText', String(text), (e, data) => { + webf.invokeModule('Clipboard', 'writeText', String(text), (e, data) => { if (e) { return reject(e); } diff --git a/bridge/polyfill/src/query-selector.ts b/bridge/polyfill/src/query-selector.ts index ce90b04e57..2c69a0cc2d 100644 --- a/bridge/polyfill/src/query-selector.ts +++ b/bridge/polyfill/src/query-selector.ts @@ -1,3 +1,8 @@ +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + function fetchSelector(str: string, regex: RegExp) { return { selectors: str.match(regex) || [], diff --git a/bridge/polyfill/src/test/index.js b/bridge/polyfill/src/test/index.js index 967b90ab86..4c02f837ed 100644 --- a/bridge/polyfill/src/test/index.js +++ b/bridge/polyfill/src/test/index.js @@ -3,7 +3,7 @@ const ConsoleReporter = require('./console-reporter'); const jasmine = jasmineCore.core(jasmineCore); const env = jasmine.getEnv({ suppressLoadErrors: true }); const jasmineInterface = jasmineCore.interface(jasmine, env); -const environment = __kraken_environment__(); +const environment = __webf_environment__(); const global = globalThis; let timers = []; @@ -59,7 +59,7 @@ class JasmineTracker { specDone(result) { clearAllTimer(); resetDocumentElement(); - kraken.methodChannel.clearMethodCallHandler(); + webf.methodChannel.clearMethodCallHandler(); } specStarted(result) { } @@ -68,7 +68,7 @@ class JasmineTracker { const consoleReporter = new ConsoleReporter(); const jasmineTracker = new JasmineTracker(); -// @NOTE: Hack for kraken js engine have no stdout. +// @NOTE: Hack for webf js engine have no stdout. function createPrinter(logger) { let stdoutMessage = ''; return function printToStdout(msg) { @@ -97,13 +97,13 @@ function HtmlSpecFilter(options) { var specFilter = new HtmlSpecFilter({ filterString() { - return environment.KRAKEN_TEST_FILTER; + return environment.WEBF_TEST_FILTER; } }); let config = { oneFailurePerSpec: true, - failFast: environment.KRAKEN_STOP_ON_FAIL === 'true', + failFast: environment.WEBF_STOP_ON_FAIL === 'true', random: false, specFilter: function (spec) { return specFilter.matches(spec.getFullName()); @@ -147,14 +147,14 @@ global.simulatePointer = function simulatePointer(list, pointer) { if (typeof value[2] != 'number') throw new Error(`list[${i}][2] should be an number`); }); - __kraken_simulate_pointer__(list, pointer); + __webf_simulate_pointer__(list, pointer); resolve(); }); }); } -global.simulateInputText = __kraken_simulate_inputtext__; +global.simulateInputText = __webf_simulate_inputtext__; function resetDocumentElement() { window.scrollTo(0, 0); @@ -182,13 +182,13 @@ function traverseNode(node, handle) { } } -__kraken_execute_test__((done) => { +__webf_execute_test__((done) => { jasmineTracker.onJasmineDone = (result) => { done(result.overallStatus); }; // Trigger global js exception to test window.onerror. - __kraken_trigger_global_error__(); + __webf_trigger_global_error__(); env.execute(); }); diff --git a/bridge/polyfill/src/test/jasmine.js b/bridge/polyfill/src/test/jasmine.js index 84f444c0a9..a0831acda1 100644 --- a/bridge/polyfill/src/test/jasmine.js +++ b/bridge/polyfill/src/test/jasmine.js @@ -4140,7 +4140,7 @@ getJasmineRequireObj().toMatchSnapshot = function (j$) { return actualPromise.then(blob => { return new Promise((resolve, reject) => { // @TODO: the C++ HostingObject of Blob, need to removed when jsa support constructor operation. - __kraken_match_image_snapshot__(blob, filename, (status, errmsg) => { + __webf_match_image_snapshot__(blob, filename, (status, errmsg) => { // @NOTE: toMatchSnapshot should resolve before spec done. const _currentSpec = j$.getEnv().currentRunnable(); if (_currentSpec.id !== specId) { diff --git a/bridge/polyfill/src/url-search-params.ts b/bridge/polyfill/src/url-search-params.ts index b236c09323..f64122a28c 100644 --- a/bridge/polyfill/src/url-search-params.ts +++ b/bridge/polyfill/src/url-search-params.ts @@ -1,3 +1,8 @@ +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + // https://github.com/WebReflection/url-search-params const find = /[!'\(\)~]|%20|%00/g; diff --git a/bridge/polyfill/src/url.ts b/bridge/polyfill/src/url.ts index 1b55b7261c..0b231e48cc 100644 --- a/bridge/polyfill/src/url.ts +++ b/bridge/polyfill/src/url.ts @@ -1,3 +1,8 @@ +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + import { URLSearchParams } from './url-search-params'; // https://github.com/Polymer/URL diff --git a/bridge/polyfill/src/kraken.ts b/bridge/polyfill/src/webf.ts similarity index 50% rename from bridge/polyfill/src/kraken.ts rename to bridge/polyfill/src/webf.ts index 2f415455ef..20d47d6e66 100644 --- a/bridge/polyfill/src/kraken.ts +++ b/bridge/polyfill/src/webf.ts @@ -1,8 +1,13 @@ -import { addKrakenModuleListener, krakenInvokeModule } from './bridge'; +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +import { addWebfModuleListener, webfInvokeModule } from './bridge'; import { methodChannel, triggerMethodCallHandler } from './method-channel'; import { dispatchConnectivityChangeEvent } from "./connection"; -function krakenModuleListener(moduleName: string, event: Event, data: any) { +function webfModuleListener(moduleName: string, event: Event, data: any) { switch (moduleName) { case 'Connection': { dispatchConnectivityChangeEvent(event); @@ -17,10 +22,10 @@ function krakenModuleListener(moduleName: string, event: Event, data: any) { } } -addKrakenModuleListener(krakenModuleListener); +addWebfModuleListener(webfModuleListener); -export const kraken = { +export const webf = { methodChannel, - invokeModule: krakenInvokeModule, - addKrakenModuleListener: addKrakenModuleListener + invokeModule: webfInvokeModule, + addWebfModuleListener: addWebfModuleListener }; diff --git a/bridge/polyfill/src/xhr.ts b/bridge/polyfill/src/xhr.ts index 54893cc9a0..61376cb05f 100644 --- a/bridge/polyfill/src/xhr.ts +++ b/bridge/polyfill/src/xhr.ts @@ -1,3 +1,8 @@ +/* +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + // Forked from https://github.com/driverdan/node-XMLHttpRequest/blob/master/lib/XMLHttpRequest.js import { URL } from './url'; diff --git a/bridge/scripts/code_generator/bin/code_generator.js b/bridge/scripts/code_generator/bin/code_generator.js index b0b7dbe531..9f6622051b 100644 --- a/bridge/scripts/code_generator/bin/code_generator.js +++ b/bridge/scripts/code_generator/bin/code_generator.js @@ -10,7 +10,7 @@ const { analyzer } = require('../dist/analyzer'); program .version(packageJSON.version) - .description('Kraken code generator.') + .description('WebF code generator.') .requiredOption('-s, --source ', 'source directory.') .requiredOption('-d, --dist ', 'destionation directory.') diff --git a/bridge/scripts/code_generator/src/generate_header.ts b/bridge/scripts/code_generator/src/generate_header.ts index 158b1e4a6c..c149b18787 100644 --- a/bridge/scripts/code_generator/src/generate_header.ts +++ b/bridge/scripts/code_generator/src/generate_header.ts @@ -164,18 +164,19 @@ export function generateCppHeader(blob: Blob) { let headers = blob.objects.map(o => generateObjectHeader(o)); return `/* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. - */ +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ -#ifndef KRAKENBRIDGE_${blob.filename.toUpperCase()}_H -#define KRAKENBRIDGE_${blob.filename.toUpperCase()}_H +#ifndef BRIDGE_${blob.filename.toUpperCase()}_H +#define BRIDGE_${blob.filename.toUpperCase()}_H #include "bindings/qjs/dom/element.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { ${headers.join('')} } -#endif //KRAKENBRIDGE_${blob.filename.toUpperCase()}T_H +#endif //BRIDGE_${blob.filename.toUpperCase()}T_H `; } diff --git a/bridge/scripts/code_generator/src/genereate_source.ts b/bridge/scripts/code_generator/src/genereate_source.ts index 6b42b4ffc9..c9c970e8e9 100644 --- a/bridge/scripts/code_generator/src/genereate_source.ts +++ b/bridge/scripts/code_generator/src/genereate_source.ts @@ -504,14 +504,15 @@ function generateObjectSource(object: ClassObject) { export function generateCppSource(blob: Blob) { let sources = blob.objects.map(o => generateObjectSource(o)); return `/* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. - */ +* Copyright (C) 2019-2022 The Kraken authors. All rights reserved. +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ #include "${blob.filename}.h" #include "page.h" #include "bindings/qjs/qjs_patch.h" -namespace kraken::binding::qjs { +namespace webf::binding::qjs { ${sources.join('')} }`; } diff --git a/bridge/test/benchmark/create_element.cc b/bridge/test/benchmark/create_element.cc index ecf29b6406..3d7edee8e2 100644 --- a/bridge/test/benchmark/create_element.cc +++ b/bridge/test/benchmark/create_element.cc @@ -1,10 +1,11 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include -#include "kraken_test_env.h" #include "page.h" +#include "webf_test_env.h" auto bridge = TEST_init(); diff --git a/bridge/test/run_integration_test.cc b/bridge/test/run_integration_test.cc index e6eaf5a9e5..87db3a4cad 100644 --- a/bridge/test/run_integration_test.cc +++ b/bridge/test/run_integration_test.cc @@ -1,12 +1,13 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include #include "gtest/gtest.h" -#include "kraken_bridge_test.h" -#include "kraken_test_env.h" #include "page.h" +#include "webf_bridge_test.h" +#include "webf_test_env.h" std::string readTestSpec() { std::string filepath = std::string(SPEC_FILE_PATH) + "/../integration_tests/.specs/core.build.js"; @@ -26,7 +27,7 @@ std::string readTestSpec() { return content; } -// Run kraken integration test specs with Google Test. +// Run webf integration test specs with Google Test. // Very useful to fix bridge bugs. TEST(IntegrationTest, runSpecs) { auto bridge = TEST_init(); @@ -35,7 +36,7 @@ TEST(IntegrationTest, runSpecs) { std::string code = readTestSpec(); bridge->evaluateScript(code.c_str(), code.size(), "vm://", 0); - executeTest(context->getContextId(), [](int32_t contextId, NativeString* status) -> void* { KRAKEN_LOG(VERBOSE) << "done"; }); + executeTest(context->getContextId(), [](int32_t contextId, NativeString* status) -> void* { WEBF_LOG(VERBOSE) << "done"; }); TEST_runLoop(context); } diff --git a/bridge/test/test.cmake b/bridge/test/test.cmake index b9fefd4766..2e7dc68550 100644 --- a/bridge/test/test.cmake +++ b/bridge/test/test.cmake @@ -1,6 +1,6 @@ list(APPEND WEBF_TEST_SOURCE - include/kraken_bridge_test.h - kraken_bridge_test.cc + include/webf_bridge_test.h + webf_bridge_test.cc polyfill/dist/testframework.cc ) @@ -14,8 +14,8 @@ list(APPEND WEBF_TEST_SOURCE page_test.h ) list(APPEND WEBF_UNIT_TEST_SOURCEURCE - ./test/kraken_test_env.cc - ./test/kraken_test_env.h + ./test/webf_test_env.cc + ./test/webf_test_env.h ./bindings/qjs/js_context_test.cc ./bindings/qjs/bom/timer_test.cc ./bindings/qjs/bom/console_test.cc @@ -63,8 +63,8 @@ endif() add_executable(webf_integration_test ${WEBF_TEST_SOURCE} ${BRIDGE_SOURCE} - ./test/kraken_test_env.cc - ./test/kraken_test_env.h + ./test/webf_test_env.cc + ./test/webf_test_env.h ./test/run_integration_test.cc ) target_include_directories(webf_integration_test PUBLIC ./third_party/googletest/googletest/include ${BRIDGE_INCLUDE} ./test) @@ -77,8 +77,8 @@ target_compile_definitions(webf_integration_test PUBLIC -DSPEC_FILE_PATH="${CMAK add_executable(webf_benchmark ${WEBF_TEST_SOURCE} ${BRIDGE_SOURCE} - ./test/kraken_test_env.cc - ./test/kraken_test_env.h + ./test/webf_test_env.cc + ./test/webf_test_env.h ./test/benchmark/create_element.cc ) target_include_directories(webf_benchmark PUBLIC diff --git a/bridge/test/kraken_test_env.cc b/bridge/test/webf_test_env.cc similarity index 92% rename from bridge/test/kraken_test_env.cc rename to bridge/test/webf_test_env.cc index d67ee971da..d5098ceaba 100644 --- a/bridge/test/kraken_test_env.cc +++ b/bridge/test/webf_test_env.cc @@ -1,15 +1,16 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#include "kraken_test_env.h" +#include "webf_test_env.h" #include #include #include "bindings/qjs/dom/event_target.h" #include "dart_methods.h" -#include "include/kraken_bridge.h" -#include "kraken_bridge_test.h" +#include "include/webf_bridge.h" #include "page.h" +#include "webf_bridge_test.h" #if defined(__linux__) || defined(__APPLE__) static int64_t get_time_ms(void) { @@ -126,14 +127,14 @@ uint32_t TEST_requestAnimationFrame(FrameCallback* frameCallback, int32_t contex } void TEST_cancelAnimationFrame(int32_t contextId, int32_t id) { - auto* page = static_cast(getPage(contextId)); + auto* page = static_cast(getPage(contextId)); auto* context = page->getContext(); JSThreadState* ts = static_cast(JS_GetRuntimeOpaque(context->runtime())); ts->os_frameCallbacks.erase(id); } void TEST_clearTimeout(int32_t contextId, int32_t timerId) { - auto* page = static_cast(getPage(contextId)); + auto* page = static_cast(getPage(contextId)); auto* context = page->getContext(); JSThreadState* ts = static_cast(JS_GetRuntimeOpaque(context->runtime())); ts->os_timers.erase(timerId); @@ -170,7 +171,7 @@ NativePerformanceEntryList* TEST_getPerformanceEntries(int32_t) { std::once_flag testInitOnceFlag; static int32_t inited{false}; -std::unique_ptr TEST_init(OnJSError onJsError) { +std::unique_ptr TEST_init(OnJSError onJsError) { uint32_t contextId; if (inited) { contextId = allocateNewPage(-1); @@ -182,24 +183,24 @@ std::unique_ptr TEST_init(OnJSError onJsError) { inited = true; }); initTestFramework(contextId); - auto* page = static_cast(getPage(contextId)); + auto* page = static_cast(getPage(contextId)); auto* context = page->getContext(); JSThreadState* th = new JSThreadState(); JS_SetRuntimeOpaque(context->runtime(), th); TEST_mockDartMethods(onJsError); - return std::unique_ptr(page); + return std::unique_ptr(page); } -std::unique_ptr TEST_init() { +std::unique_ptr TEST_init() { return TEST_init(nullptr); } -std::unique_ptr TEST_allocateNewPage() { +std::unique_ptr TEST_allocateNewPage() { uint32_t newContextId = allocateNewPage(-1); initTestFramework(newContextId); - return std::unique_ptr(static_cast(getPage(newContextId))); + return std::unique_ptr(static_cast(getPage(newContextId))); } static bool jsPool(ExecutionContext* context) { diff --git a/bridge/test/kraken_test_env.h b/bridge/test/webf_test_env.h similarity index 57% rename from bridge/test/kraken_test_env.h rename to bridge/test/webf_test_env.h index 4bc17084a5..2a71828d96 100644 --- a/bridge/test/kraken_test_env.h +++ b/bridge/test/webf_test_env.h @@ -1,9 +1,10 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#ifndef KRAKENBRIDGE_TEST_KRAKEN_TEST_ENV_H_ -#define KRAKENBRIDGE_TEST_KRAKEN_TEST_ENV_H_ +#ifndef BRIDGE_TEST_WEBF_TEST_ENV_H_ +#define BRIDGE_TEST_WEBF_TEST_ENV_H_ #include #include "bindings/qjs/bom/timer.h" @@ -13,19 +14,19 @@ #include "include/dart_methods.h" #include "page.h" -using namespace kraken::binding::qjs; +using namespace webf::binding::qjs; // Trigger a callbacks before GC free the eventTargets. -using TEST_OnEventTargetDisposed = void (*)(kraken::binding::qjs::EventTargetInstance* eventTargetInstance); +using TEST_OnEventTargetDisposed = void (*)(webf::binding::qjs::EventTargetInstance* eventTargetInstance); struct UnitTestEnv { TEST_OnEventTargetDisposed onEventTargetDisposed{nullptr}; }; -// Mock dart methods and add async timer to emulate kraken environment in C++ unit test. +// Mock dart methods and add async timer to emulate webf environment in C++ unit test. -std::unique_ptr TEST_init(OnJSError onJsError); -std::unique_ptr TEST_init(); -std::unique_ptr TEST_allocateNewPage(); +std::unique_ptr TEST_init(OnJSError onJsError); +std::unique_ptr TEST_init(); +std::unique_ptr TEST_allocateNewPage(); void TEST_runLoop(ExecutionContext* context); void TEST_dispatchEvent(int32_t contextId, EventTargetInstance* eventTarget, const std::string type); void TEST_invokeBindingMethod(void* nativePtr, void* returnValue, void* method, int32_t argc, void* argv); @@ -33,4 +34,4 @@ void TEST_registerEventTargetDisposedCallback(int32_t contextUniqueId, TEST_OnEv void TEST_mockDartMethods(OnJSError onJSError); std::shared_ptr TEST_getEnv(int32_t contextUniqueId); -#endif // KRAKENBRIDGE_TEST_KRAKEN_TEST_ENV_H_ +#endif // BRIDGE_TEST_WEBF_TEST_ENV_H_ diff --git a/bridge/kraken_bridge.cc b/bridge/webf_bridge.cc similarity index 67% rename from bridge/kraken_bridge.cc rename to bridge/webf_bridge.cc index 872b5f8587..2711704c8f 100644 --- a/bridge/kraken_bridge.cc +++ b/bridge/webf_bridge.cc @@ -2,22 +2,15 @@ * Copyright (C) 2019-present The Kraken authors. All rights reserved. */ -#include "kraken_bridge.h" +#include "webf_bridge.h" #include #include "dart_methods.h" -#include "foundation/inspector_task_queue.h" #include "foundation/logging.h" #include "foundation/ui_task_queue.h" -#if KRAKEN_JSC_ENGINE -#include "bindings/jsc/KOM/performance.h" -#elif KRAKEN_QUICK_JS_ENGINE +#if WEBF_QUICK_JS_ENGINE #include "page.h" #endif -#if KRAKEN_JSC_ENGINE -#include "bridge_jsc.h" -#endif - #include #include @@ -57,14 +50,14 @@ std::thread::id getUIThreadId() { } void printError(int32_t contextId, const char* errmsg) { - if (kraken::getDartMethod()->onJsError != nullptr) { - kraken::getDartMethod()->onJsError(contextId, errmsg); + if (webf::getDartMethod()->onJsError != nullptr) { + webf::getDartMethod()->onJsError(contextId, errmsg); } - if (kraken::getDartMethod()->onJsLog != nullptr) { - kraken::getDartMethod()->onJsLog(contextId, static_cast(foundation::MessageLevel::Error), errmsg); + if (webf::getDartMethod()->onJsLog != nullptr) { + webf::getDartMethod()->onJsLog(contextId, static_cast(foundation::MessageLevel::Error), errmsg); } - KRAKEN_LOG(ERROR) << errmsg << std::endl; + WEBF_LOG(ERROR) << errmsg << std::endl; } namespace { @@ -79,7 +72,7 @@ void disposeAllPages() { int32_t searchForAvailableContextId() { for (int i = 0; i < maxPoolSize; i++) { - if (kraken::KrakenPage::pageContextPool[i] == nullptr) { + if (webf::WebFPage::pageContextPool[i] == nullptr) { return i; } } @@ -94,24 +87,24 @@ void initJSPagePool(int poolSize) { if (inited) { disposeAllPages(); }; - kraken::KrakenPage::pageContextPool = new kraken::KrakenPage*[poolSize]; + webf::WebFPage::pageContextPool = new webf::WebFPage*[poolSize]; for (int i = 1; i < poolSize; i++) { - kraken::KrakenPage::pageContextPool[i] = nullptr; + webf::WebFPage::pageContextPool[i] = nullptr; } - kraken::KrakenPage::pageContextPool[0] = new kraken::KrakenPage(0, printError); + webf::WebFPage::pageContextPool[0] = new webf::WebFPage(0, printError); inited = true; maxPoolSize = poolSize; } void disposePage(int32_t contextId) { assert(contextId < maxPoolSize); - if (kraken::KrakenPage::pageContextPool[contextId] == nullptr) + if (webf::WebFPage::pageContextPool[contextId] == nullptr) return; - auto* page = static_cast(kraken::KrakenPage::pageContextPool[contextId]); + auto* page = static_cast(webf::WebFPage::pageContextPool[contextId]); delete page; - kraken::KrakenPage::pageContextPool[contextId] = nullptr; + webf::WebFPage::pageContextPool[contextId] = nullptr; } int32_t allocateNewPage(int32_t targetContextId) { @@ -123,65 +116,65 @@ int32_t allocateNewPage(int32_t targetContextId) { targetContextId = searchForAvailableContextId(); } - assert(kraken::KrakenPage::pageContextPool[targetContextId] == nullptr && + assert(webf::WebFPage::pageContextPool[targetContextId] == nullptr && (std::string("can not allocate page at index") + std::to_string(targetContextId) + std::string(": page have already exist.")).c_str()); - auto* page = new kraken::KrakenPage(targetContextId, printError); - kraken::KrakenPage::pageContextPool[targetContextId] = page; + auto* page = new webf::WebFPage(targetContextId, printError); + webf::WebFPage::pageContextPool[targetContextId] = page; return targetContextId; } void* getPage(int32_t contextId) { if (!checkPage(contextId)) return nullptr; - return kraken::KrakenPage::pageContextPool[contextId]; + return webf::WebFPage::pageContextPool[contextId]; } bool checkPage(int32_t contextId) { - return inited && contextId < maxPoolSize && kraken::KrakenPage::pageContextPool[contextId] != nullptr; + return inited && contextId < maxPoolSize && webf::WebFPage::pageContextPool[contextId] != nullptr; } bool checkPage(int32_t contextId, void* context) { - if (kraken::KrakenPage::pageContextPool[contextId] == nullptr) + if (webf::WebFPage::pageContextPool[contextId] == nullptr) return false; - auto* page = static_cast(getPage(contextId)); + auto* page = static_cast(getPage(contextId)); return page->getContext() == context; } void evaluateScripts(int32_t contextId, NativeString* code, const char* bundleFilename, int startLine) { assert(checkPage(contextId) && "evaluateScripts: contextId is not valid"); - auto context = static_cast(getPage(contextId)); + auto context = static_cast(getPage(contextId)); context->evaluateScript(code, bundleFilename, startLine); } void evaluateQuickjsByteCode(int32_t contextId, uint8_t* bytes, int32_t byteLen) { assert(checkPage(contextId) && "evaluateScripts: contextId is not valid"); - auto context = static_cast(getPage(contextId)); + auto context = static_cast(getPage(contextId)); context->evaluateByteCode(bytes, byteLen); } void parseHTML(int32_t contextId, const char* code, int32_t length) { assert(checkPage(contextId) && "parseHTML: contextId is not valid"); - auto context = static_cast(getPage(contextId)); + auto context = static_cast(getPage(contextId)); context->parseHTML(code, length); } void reloadJsContext(int32_t contextId) { assert(checkPage(contextId) && "reloadJSContext: contextId is not valid"); auto bridgePtr = getPage(contextId); - auto context = static_cast(bridgePtr); - auto newContext = new kraken::KrakenPage(contextId, printError); + auto context = static_cast(bridgePtr); + auto newContext = new webf::WebFPage(contextId, printError); delete context; - kraken::KrakenPage::pageContextPool[contextId] = newContext; + webf::WebFPage::pageContextPool[contextId] = newContext; } void invokeModuleEvent(int32_t contextId, NativeString* moduleName, const char* eventType, void* event, NativeString* extra) { assert(checkPage(contextId) && "invokeEventListener: contextId is not valid"); - auto context = static_cast(getPage(contextId)); + auto context = static_cast(getPage(contextId)); context->invokeModuleEvent(moduleName, eventType, event, extra); } void registerDartMethods(uint64_t* methodBytes, int32_t length) { - kraken::registerDartMethods(methodBytes, length); + webf::registerDartMethods(methodBytes, length); } NativeScreen* createScreen(double width, double height) { @@ -190,22 +183,22 @@ NativeScreen* createScreen(double width, double height) { return &screen; } -static KrakenInfo* krakenInfo{nullptr}; +static WebFInfo* webfInfo{nullptr}; -KrakenInfo* getKrakenInfo() { - if (krakenInfo == nullptr) { - krakenInfo = new KrakenInfo(); - krakenInfo->app_name = "Kraken"; - krakenInfo->app_revision = APP_REV; - krakenInfo->app_version = APP_VERSION; - krakenInfo->system_name = SYSTEM_NAME; +WebFInfo* getWebFInfo() { + if (webfInfo == nullptr) { + webfInfo = new WebFInfo(); + webfInfo->app_name = "WebF"; + webfInfo->app_revision = APP_REV; + webfInfo->app_version = APP_VERSION; + webfInfo->system_name = SYSTEM_NAME; } - return krakenInfo; + return webfInfo; } void setConsoleMessageHandler(ConsoleMessageHandler handler) { - kraken::KrakenPage::consoleMessageHandler = handler; + webf::WebFPage::consoleMessageHandler = handler; } void dispatchUITask(int32_t contextId, void* context, void* callback) { @@ -226,21 +219,21 @@ void flushUICommandCallback() { } UICommandItem* getUICommandItems(int32_t contextId) { - auto* page = static_cast(getPage(contextId)); + auto* page = static_cast(getPage(contextId)); if (page == nullptr) return nullptr; return page->getContext()->uiCommandBuffer()->data(); } int64_t getUICommandItemSize(int32_t contextId) { - auto* page = static_cast(getPage(contextId)); + auto* page = static_cast(getPage(contextId)); if (page == nullptr) return 0; return page->getContext()->uiCommandBuffer()->size(); } void clearUICommandItems(int32_t contextId) { - auto* page = static_cast(getPage(contextId)); + auto* page = static_cast(getPage(contextId)); if (page == nullptr) return; page->getContext()->uiCommandBuffer()->clear(); @@ -248,11 +241,11 @@ void clearUICommandItems(int32_t contextId) { void registerContextDisposedCallbacks(int32_t contextId, Task task, void* data) { assert(checkPage(contextId)); - auto context = static_cast(getPage(contextId)); + auto context = static_cast(getPage(contextId)); } void registerPluginByteCode(uint8_t* bytes, int32_t length, const char* pluginName) { - kraken::KrakenPage::pluginByteCode[pluginName] = NativeByteCode{bytes, length}; + webf::WebFPage::pluginByteCode[pluginName] = NativeByteCode{bytes, length}; } int32_t profileModeEnabled() { diff --git a/bridge/kraken_bridge_test.cc b/bridge/webf_bridge_test.cc similarity index 67% rename from bridge/kraken_bridge_test.cc rename to bridge/webf_bridge_test.cc index 9567b1c29b..a6254dadda 100644 --- a/bridge/kraken_bridge_test.cc +++ b/bridge/webf_bridge_test.cc @@ -2,21 +2,21 @@ * Copyright (C) 2020-present The Kraken authors. All rights reserved. */ -#include "kraken_bridge_test.h" +#include "webf_bridge_test.h" #include "dart_methods.h" -#if KRAKEN_JSC_ENGINE +#if WEBF_JSC_ENGINE #include "bridge_test_jsc.h" -#elif KRAKEN_QUICK_JS_ENGINE +#elif WEBF_QUICK_JS_ENGINE #include "page_test.h" #endif #include -std::unordered_map bridgeTestPool = std::unordered_map(); +std::unordered_map bridgeTestPool = std::unordered_map(); void initTestFramework(int32_t contextId) { - auto* page = static_cast(getPage(contextId)); - auto bridgeTest = new kraken::KrakenPageTest(page); + auto* page = static_cast(getPage(contextId)); + auto bridgeTest = new webf::WebFPageTest(page); bridgeTestPool[contextId] = bridgeTest; } @@ -31,5 +31,5 @@ void executeTest(int32_t contextId, ExecuteCallback executeCallback) { } void registerTestEnvDartMethods(uint64_t* methodBytes, int32_t length) { - kraken::registerTestEnvDartMethods(methodBytes, length); + webf::registerTestEnvDartMethods(methodBytes, length); } diff --git a/integration_tests/README.md b/integration_tests/README.md index b8d0da3662..e896169cfa 100644 --- a/integration_tests/README.md +++ b/integration_tests/README.md @@ -1,4 +1,4 @@ -# Kraken integration tests +# WebF integration tests ## Dart Unit test @@ -42,5 +42,5 @@ sudo pmset -a gpuswitch 0 this above command will execute which spec's name contains "synthesized-baseline-flexbox-001" ``` - KRAKEN_TEST_FILTER="synthesized-baseline-flexbox-001" npm run integration + WEBF_TEST_FILTER="synthesized-baseline-flexbox-001" npm run integration ``` diff --git a/integration_tests/android/.gitignore b/integration_tests/android/.gitignore deleted file mode 100644 index bc2100d8f7..0000000000 --- a/integration_tests/android/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -gradle-wrapper.jar -/.gradle -/captures/ -/gradlew -/gradlew.bat -/local.properties -GeneratedPluginRegistrant.java diff --git a/integration_tests/android/app/build.gradle b/integration_tests/android/app/build.gradle deleted file mode 100644 index 326fa6c9f7..0000000000 --- a/integration_tests/android/app/build.gradle +++ /dev/null @@ -1,67 +0,0 @@ -def localProperties = new Properties() -def localPropertiesFile = rootProject.file('local.properties') -if (localPropertiesFile.exists()) { - localPropertiesFile.withReader('UTF-8') { reader -> - localProperties.load(reader) - } -} - -def flutterRoot = localProperties.getProperty('flutter.sdk') -if (flutterRoot == null) { - throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") -} - -def flutterVersionCode = localProperties.getProperty('flutter.versionCode') -if (flutterVersionCode == null) { - flutterVersionCode = '1' -} - -def flutterVersionName = localProperties.getProperty('flutter.versionName') -if (flutterVersionName == null) { - flutterVersionName = '1.0' -} - -apply plugin: 'com.android.application' -apply plugin: 'kotlin-android' -apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" - -android { - compileSdkVersion 28 - - sourceSets { - main.java.srcDirs += 'src/main/kotlin' - } - - lintOptions { - disable 'InvalidPackage' - } - - defaultConfig { - // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId "com.openkraken.tests" - minSdkVersion 16 - targetSdkVersion 28 - versionCode flutterVersionCode.toInteger() - versionName flutterVersionName - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - } - - buildTypes { - release { - // TODO: Add your own signing config for the release build. - // Signing with the debug keys for now, so `flutter run --release` works. - signingConfig signingConfigs.debug - } - } -} - -flutter { - source '../..' -} - -dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" - testImplementation 'junit:junit:4.12' - androidTestImplementation 'androidx.test:runner:1.1.1' - androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' -} diff --git a/integration_tests/android/app/src/debug/AndroidManifest.xml b/integration_tests/android/app/src/debug/AndroidManifest.xml deleted file mode 100644 index 7d377454b7..0000000000 --- a/integration_tests/android/app/src/debug/AndroidManifest.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - diff --git a/integration_tests/android/app/src/main/AndroidManifest.xml b/integration_tests/android/app/src/main/AndroidManifest.xml deleted file mode 100644 index 36581fb2ce..0000000000 --- a/integration_tests/android/app/src/main/AndroidManifest.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - diff --git a/integration_tests/android/app/src/main/kotlin/com/openkraken/tests/MainActivity.kt b/integration_tests/android/app/src/main/kotlin/com/openkraken/tests/MainActivity.kt deleted file mode 100644 index cbb6dc3d49..0000000000 --- a/integration_tests/android/app/src/main/kotlin/com/openkraken/tests/MainActivity.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.openkraken.tests - -import androidx.annotation.NonNull; -import io.flutter.embedding.android.FlutterActivity -import io.flutter.embedding.engine.FlutterEngine -import io.flutter.plugins.GeneratedPluginRegistrant - -class MainActivity: FlutterActivity() { - override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) { - GeneratedPluginRegistrant.registerWith(flutterEngine); - } -} diff --git a/integration_tests/android/app/src/main/res/drawable/launch_background.xml b/integration_tests/android/app/src/main/res/drawable/launch_background.xml deleted file mode 100644 index 304732f884..0000000000 --- a/integration_tests/android/app/src/main/res/drawable/launch_background.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - diff --git a/integration_tests/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/integration_tests/android/app/src/main/res/mipmap-hdpi/ic_launcher.png deleted file mode 100644 index db77bb4b7b..0000000000 Binary files a/integration_tests/android/app/src/main/res/mipmap-hdpi/ic_launcher.png and /dev/null differ diff --git a/integration_tests/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/integration_tests/android/app/src/main/res/mipmap-mdpi/ic_launcher.png deleted file mode 100644 index 17987b79bb..0000000000 Binary files a/integration_tests/android/app/src/main/res/mipmap-mdpi/ic_launcher.png and /dev/null differ diff --git a/integration_tests/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/integration_tests/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png deleted file mode 100644 index 09d4391482..0000000000 Binary files a/integration_tests/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png and /dev/null differ diff --git a/integration_tests/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/integration_tests/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png deleted file mode 100644 index d5f1c8d34e..0000000000 Binary files a/integration_tests/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png and /dev/null differ diff --git a/integration_tests/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/integration_tests/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png deleted file mode 100644 index 4d6372eebd..0000000000 Binary files a/integration_tests/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png and /dev/null differ diff --git a/integration_tests/android/app/src/main/res/values/styles.xml b/integration_tests/android/app/src/main/res/values/styles.xml deleted file mode 100644 index 00fa4417cf..0000000000 --- a/integration_tests/android/app/src/main/res/values/styles.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - diff --git a/integration_tests/android/app/src/profile/AndroidManifest.xml b/integration_tests/android/app/src/profile/AndroidManifest.xml deleted file mode 100644 index 7d377454b7..0000000000 --- a/integration_tests/android/app/src/profile/AndroidManifest.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - diff --git a/integration_tests/android/build.gradle b/integration_tests/android/build.gradle deleted file mode 100644 index 3100ad2d55..0000000000 --- a/integration_tests/android/build.gradle +++ /dev/null @@ -1,31 +0,0 @@ -buildscript { - ext.kotlin_version = '1.3.50' - repositories { - google() - jcenter() - } - - dependencies { - classpath 'com.android.tools.build:gradle:3.5.0' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - -allprojects { - repositories { - google() - jcenter() - } -} - -rootProject.buildDir = '../build' -subprojects { - project.buildDir = "${rootProject.buildDir}/${project.name}" -} -subprojects { - project.evaluationDependsOn(':app') -} - -task clean(type: Delete) { - delete rootProject.buildDir -} diff --git a/integration_tests/android/gradle.properties b/integration_tests/android/gradle.properties deleted file mode 100644 index 38c8d4544f..0000000000 --- a/integration_tests/android/gradle.properties +++ /dev/null @@ -1,4 +0,0 @@ -org.gradle.jvmargs=-Xmx1536M -android.enableR8=true -android.useAndroidX=true -android.enableJetifier=true diff --git a/integration_tests/android/gradle/wrapper/gradle-wrapper.properties b/integration_tests/android/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 296b146b73..0000000000 --- a/integration_tests/android/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Fri Jun 23 08:50:38 CEST 2017 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip diff --git a/integration_tests/android/settings.gradle b/integration_tests/android/settings.gradle deleted file mode 100644 index 5a2f14fb18..0000000000 --- a/integration_tests/android/settings.gradle +++ /dev/null @@ -1,15 +0,0 @@ -include ':app' - -def flutterProjectRoot = rootProject.projectDir.parentFile.toPath() - -def plugins = new Properties() -def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins') -if (pluginsFile.exists()) { - pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) } -} - -plugins.each { name, path -> - def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile() - include ":$name" - project(":$name").projectDir = pluginDirectory -} diff --git a/integration_tests/ios/.gitignore b/integration_tests/ios/.gitignore deleted file mode 100644 index e96ef602b8..0000000000 --- a/integration_tests/ios/.gitignore +++ /dev/null @@ -1,32 +0,0 @@ -*.mode1v3 -*.mode2v3 -*.moved-aside -*.pbxuser -*.perspectivev3 -**/*sync/ -.sconsign.dblite -.tags* -**/.vagrant/ -**/DerivedData/ -Icon? -**/Pods/ -**/.symlinks/ -profile -xcuserdata -**/.generated/ -Flutter/App.framework -Flutter/Flutter.framework -Flutter/Flutter.podspec -Flutter/Generated.xcconfig -Flutter/app.flx -Flutter/app.zip -Flutter/flutter_assets/ -Flutter/flutter_export_environment.sh -ServiceDefinitions.json -Runner/GeneratedPluginRegistrant.* - -# Exceptions to above rules. -!default.mode1v3 -!default.mode2v3 -!default.pbxuser -!default.perspectivev3 diff --git a/integration_tests/ios/Flutter/AppFrameworkInfo.plist b/integration_tests/ios/Flutter/AppFrameworkInfo.plist deleted file mode 100644 index 6b4c0f78a7..0000000000 --- a/integration_tests/ios/Flutter/AppFrameworkInfo.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - App - CFBundleIdentifier - io.flutter.flutter.app - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - App - CFBundlePackageType - FMWK - CFBundleShortVersionString - 1.0 - CFBundleSignature - ???? - CFBundleVersion - 1.0 - MinimumOSVersion - 8.0 - - diff --git a/integration_tests/ios/Flutter/Debug.xcconfig b/integration_tests/ios/Flutter/Debug.xcconfig deleted file mode 100644 index e8efba1146..0000000000 --- a/integration_tests/ios/Flutter/Debug.xcconfig +++ /dev/null @@ -1,2 +0,0 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" -#include "Generated.xcconfig" diff --git a/integration_tests/ios/Flutter/Release.xcconfig b/integration_tests/ios/Flutter/Release.xcconfig deleted file mode 100644 index 399e9340e6..0000000000 --- a/integration_tests/ios/Flutter/Release.xcconfig +++ /dev/null @@ -1,2 +0,0 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" -#include "Generated.xcconfig" diff --git a/integration_tests/ios/Podfile b/integration_tests/ios/Podfile deleted file mode 100644 index b30a428b5e..0000000000 --- a/integration_tests/ios/Podfile +++ /dev/null @@ -1,90 +0,0 @@ -# Uncomment this line to define a global platform for your project -# platform :ios, '9.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def parse_KV_file(file, separator='=') - file_abs_path = File.expand_path(file) - if !File.exists? file_abs_path - return []; - end - generated_key_values = {} - skip_line_start_symbols = ["#", "/"] - File.foreach(file_abs_path) do |line| - next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ } - plugin = line.split(pattern=separator) - if plugin.length == 2 - podname = plugin[0].strip() - path = plugin[1].strip() - podpath = File.expand_path("#{path}", file_abs_path) - generated_key_values[podname] = podpath - else - puts "Invalid plugin specification: #{line}" - end - end - generated_key_values -end - -target 'Runner' do - use_frameworks! - use_modular_headers! - - # Flutter Pod - - copied_flutter_dir = File.join(__dir__, 'Flutter') - copied_framework_path = File.join(copied_flutter_dir, 'Flutter.framework') - copied_podspec_path = File.join(copied_flutter_dir, 'Flutter.podspec') - unless File.exist?(copied_framework_path) && File.exist?(copied_podspec_path) - # Copy Flutter.framework and Flutter.podspec to Flutter/ to have something to link against if the xcode backend script has not run yet. - # That script will copy the correct debug/profile/release version of the framework based on the currently selected Xcode configuration. - # CocoaPods will not embed the framework on pod install (before any build phases can generate) if the dylib does not exist. - - generated_xcode_build_settings_path = File.join(copied_flutter_dir, 'Generated.xcconfig') - unless File.exist?(generated_xcode_build_settings_path) - raise "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - generated_xcode_build_settings = parse_KV_file(generated_xcode_build_settings_path) - cached_framework_dir = generated_xcode_build_settings['FLUTTER_FRAMEWORK_DIR']; - - unless File.exist?(copied_framework_path) - FileUtils.cp_r(File.join(cached_framework_dir, 'Flutter.framework'), copied_flutter_dir) - end - unless File.exist?(copied_podspec_path) - FileUtils.cp(File.join(cached_framework_dir, 'Flutter.podspec'), copied_flutter_dir) - end - end - - # Keep pod path relative so it can be checked into Podfile.lock. - pod 'Flutter', :path => 'Flutter' - - # Plugin Pods - - # Prepare symlinks folder. We use symlinks to avoid having Podfile.lock - # referring to absolute paths on developers' machines. - system('rm -rf .symlinks') - system('mkdir -p .symlinks/plugins') - plugin_pods = parse_KV_file('../.flutter-plugins') - plugin_pods.each do |name, path| - symlink = File.join('.symlinks', 'plugins', name) - File.symlink(path, symlink) - pod name, :path => File.join(symlink, 'ios') - end -end - -# Prevent Cocoapods from embedding a second Flutter framework and causing an error with the new Xcode build system. -install! 'cocoapods', :disable_input_output_paths => true - -post_install do |installer| - installer.pods_project.targets.each do |target| - target.build_configurations.each do |config| - config.build_settings['ENABLE_BITCODE'] = 'NO' - end - end -end diff --git a/integration_tests/ios/Runner.xcodeproj/project.pbxproj b/integration_tests/ios/Runner.xcodeproj/project.pbxproj deleted file mode 100644 index 73e6857f06..0000000000 --- a/integration_tests/ios/Runner.xcodeproj/project.pbxproj +++ /dev/null @@ -1,584 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; - 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; - 3B80C3941E831B6300D905FE /* App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3B80C3931E831B6300D905FE /* App.framework */; }; - 3B80C3951E831B6300D905FE /* App.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 3B80C3931E831B6300D905FE /* App.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; - 6A0CB1123A9C4850DA27CD56 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BC6B06E2A986C48B0AF547AF /* Pods_Runner.framework */; }; - 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; - 9705A1C61CF904A100538489 /* Flutter.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9740EEBA1CF902C7004384FC /* Flutter.framework */; }; - 9705A1C71CF904A300538489 /* Flutter.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 9740EEBA1CF902C7004384FC /* Flutter.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; - 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; - 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; - 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; -/* End PBXBuildFile section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 9705A1C41CF9048500538489 /* Embed Frameworks */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 10; - files = ( - 3B80C3951E831B6300D905FE /* App.framework in Embed Frameworks */, - 9705A1C71CF904A300538489 /* Flutter.framework in Embed Frameworks */, - ); - name = "Embed Frameworks"; - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; - 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; - 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 3B80C3931E831B6300D905FE /* App.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = App.framework; path = Flutter/App.framework; sourceTree = ""; }; - 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; - 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; - 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; - 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; - 9740EEBA1CF902C7004384FC /* Flutter.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Flutter.framework; path = Flutter/Flutter.framework; sourceTree = ""; }; - 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; - 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; - 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - BC6B06E2A986C48B0AF547AF /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - C190D38FFD2D24A5B59EB553 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; - C1F9460A9B3907E34DBA7A14 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; - F65AF51A5768199CD0932EBE /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 97C146EB1CF9000F007C117D /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 9705A1C61CF904A100538489 /* Flutter.framework in Frameworks */, - 3B80C3941E831B6300D905FE /* App.framework in Frameworks */, - 6A0CB1123A9C4850DA27CD56 /* Pods_Runner.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 3EF66B0E789543490505C667 /* Pods */ = { - isa = PBXGroup; - children = ( - F65AF51A5768199CD0932EBE /* Pods-Runner.debug.xcconfig */, - C1F9460A9B3907E34DBA7A14 /* Pods-Runner.release.xcconfig */, - C190D38FFD2D24A5B59EB553 /* Pods-Runner.profile.xcconfig */, - ); - name = Pods; - path = Pods; - sourceTree = ""; - }; - 9740EEB11CF90186004384FC /* Flutter */ = { - isa = PBXGroup; - children = ( - 3B80C3931E831B6300D905FE /* App.framework */, - 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, - 9740EEBA1CF902C7004384FC /* Flutter.framework */, - 9740EEB21CF90195004384FC /* Debug.xcconfig */, - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, - 9740EEB31CF90195004384FC /* Generated.xcconfig */, - ); - name = Flutter; - sourceTree = ""; - }; - 97C146E51CF9000F007C117D = { - isa = PBXGroup; - children = ( - 9740EEB11CF90186004384FC /* Flutter */, - 97C146F01CF9000F007C117D /* Runner */, - 97C146EF1CF9000F007C117D /* Products */, - 3EF66B0E789543490505C667 /* Pods */, - EF60EDB9A9B1ED0D3B2B4ED4 /* Frameworks */, - ); - sourceTree = ""; - }; - 97C146EF1CF9000F007C117D /* Products */ = { - isa = PBXGroup; - children = ( - 97C146EE1CF9000F007C117D /* Runner.app */, - ); - name = Products; - sourceTree = ""; - }; - 97C146F01CF9000F007C117D /* Runner */ = { - isa = PBXGroup; - children = ( - 97C146FA1CF9000F007C117D /* Main.storyboard */, - 97C146FD1CF9000F007C117D /* Assets.xcassets */, - 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, - 97C147021CF9000F007C117D /* Info.plist */, - 97C146F11CF9000F007C117D /* Supporting Files */, - 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, - 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, - 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, - 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, - ); - path = Runner; - sourceTree = ""; - }; - 97C146F11CF9000F007C117D /* Supporting Files */ = { - isa = PBXGroup; - children = ( - ); - name = "Supporting Files"; - sourceTree = ""; - }; - EF60EDB9A9B1ED0D3B2B4ED4 /* Frameworks */ = { - isa = PBXGroup; - children = ( - BC6B06E2A986C48B0AF547AF /* Pods_Runner.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 97C146ED1CF9000F007C117D /* Runner */ = { - isa = PBXNativeTarget; - buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; - buildPhases = ( - 4802D809A84268E57D7AE590 /* [CP] Check Pods Manifest.lock */, - 9740EEB61CF901F6004384FC /* Run Script */, - 97C146EA1CF9000F007C117D /* Sources */, - 97C146EB1CF9000F007C117D /* Frameworks */, - 97C146EC1CF9000F007C117D /* Resources */, - 9705A1C41CF9048500538489 /* Embed Frameworks */, - 3B06AD1E1E4923F5004D2608 /* Thin Binary */, - 45F4D7A98A9F46BE106DE5A7 /* [CP] Embed Pods Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = Runner; - productName = Runner; - productReference = 97C146EE1CF9000F007C117D /* Runner.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 97C146E61CF9000F007C117D /* Project object */ = { - isa = PBXProject; - attributes = { - LastUpgradeCheck = 1020; - ORGANIZATIONNAME = ""; - TargetAttributes = { - 97C146ED1CF9000F007C117D = { - CreatedOnToolsVersion = 7.3.1; - LastSwiftMigration = 1100; - }; - }; - }; - buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 97C146E51CF9000F007C117D; - productRefGroup = 97C146EF1CF9000F007C117D /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 97C146ED1CF9000F007C117D /* Runner */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 97C146EC1CF9000F007C117D /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, - 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, - 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, - 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXShellScriptBuildPhase section */ - 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "Thin Binary"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" thin"; - }; - 45F4D7A98A9F46BE106DE5A7 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - 4802D809A84268E57D7AE590 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 9740EEB61CF901F6004384FC /* Run Script */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "Run Script"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; - }; -/* End PBXShellScriptBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 97C146EA1CF9000F007C117D /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, - 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXVariantGroup section */ - 97C146FA1CF9000F007C117D /* Main.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 97C146FB1CF9000F007C117D /* Base */, - ); - name = Main.storyboard; - sourceTree = ""; - }; - 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 97C147001CF9000F007C117D /* Base */, - ); - name = LaunchScreen.storyboard; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 249021D3217E4FDB00AE95B9 /* Profile */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = iphoneos; - SUPPORTED_PLATFORMS = iphoneos; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - }; - name = Profile; - }; - 249021D4217E4FDB00AE95B9 /* Profile */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - ENABLE_BITCODE = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.openkraken.tests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; - SWIFT_VERSION = 5.0; - VERSIONING_SYSTEM = "apple-generic"; - }; - name = Profile; - }; - 97C147031CF9000F007C117D /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - MTL_ENABLE_DEBUG_INFO = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Debug; - }; - 97C147041CF9000F007C117D /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = iphoneos; - SUPPORTED_PLATFORMS = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 97C147061CF9000F007C117D /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - ENABLE_BITCODE = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.openkraken.tests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; - VERSIONING_SYSTEM = "apple-generic"; - }; - name = Debug; - }; - 97C147071CF9000F007C117D /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - ENABLE_BITCODE = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.openkraken.tests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; - SWIFT_VERSION = 5.0; - VERSIONING_SYSTEM = "apple-generic"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 97C147031CF9000F007C117D /* Debug */, - 97C147041CF9000F007C117D /* Release */, - 249021D3217E4FDB00AE95B9 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 97C147061CF9000F007C117D /* Debug */, - 97C147071CF9000F007C117D /* Release */, - 249021D4217E4FDB00AE95B9 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 97C146E61CF9000F007C117D /* Project object */; -} diff --git a/integration_tests/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/integration_tests/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 1d526a16ed..0000000000 --- a/integration_tests/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/integration_tests/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/integration_tests/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme deleted file mode 100644 index a28140cfdb..0000000000 --- a/integration_tests/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ /dev/null @@ -1,91 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/integration_tests/ios/Runner.xcworkspace/contents.xcworkspacedata b/integration_tests/ios/Runner.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 21a3cc14c7..0000000000 --- a/integration_tests/ios/Runner.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - diff --git a/integration_tests/ios/Runner/AppDelegate.swift b/integration_tests/ios/Runner/AppDelegate.swift deleted file mode 100644 index 70693e4a8c..0000000000 --- a/integration_tests/ios/Runner/AppDelegate.swift +++ /dev/null @@ -1,13 +0,0 @@ -import UIKit -import Flutter - -@UIApplicationMain -@objc class AppDelegate: FlutterAppDelegate { - override func application( - _ application: UIApplication, - didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? - ) -> Bool { - GeneratedPluginRegistrant.register(with: self) - return super.application(application, didFinishLaunchingWithOptions: launchOptions) - } -} diff --git a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index d36b1fab2d..0000000000 --- a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,122 +0,0 @@ -{ - "images" : [ - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "Icon-App-20x20@2x.png", - "scale" : "2x" - }, - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "Icon-App-20x20@3x.png", - "scale" : "3x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@1x.png", - "scale" : "1x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@2x.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@3x.png", - "scale" : "3x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "Icon-App-40x40@2x.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "Icon-App-40x40@3x.png", - "scale" : "3x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "Icon-App-60x60@2x.png", - "scale" : "2x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "Icon-App-60x60@3x.png", - "scale" : "3x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "Icon-App-20x20@1x.png", - "scale" : "1x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "Icon-App-20x20@2x.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "Icon-App-29x29@1x.png", - "scale" : "1x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "Icon-App-29x29@2x.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "Icon-App-40x40@1x.png", - "scale" : "1x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "Icon-App-40x40@2x.png", - "scale" : "2x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "Icon-App-76x76@1x.png", - "scale" : "1x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "Icon-App-76x76@2x.png", - "scale" : "2x" - }, - { - "size" : "83.5x83.5", - "idiom" : "ipad", - "filename" : "Icon-App-83.5x83.5@2x.png", - "scale" : "2x" - }, - { - "size" : "1024x1024", - "idiom" : "ios-marketing", - "filename" : "Icon-App-1024x1024@1x.png", - "scale" : "1x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} diff --git a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png deleted file mode 100644 index dc9ada4725..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png deleted file mode 100644 index 28c6bf0301..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png deleted file mode 100644 index 2ccbfd967d..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png deleted file mode 100644 index f091b6b0bc..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png deleted file mode 100644 index 4cde12118d..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png deleted file mode 100644 index d0ef06e7ed..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png deleted file mode 100644 index dcdc2306c2..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png deleted file mode 100644 index 2ccbfd967d..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png deleted file mode 100644 index c8f9ed8f5c..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png deleted file mode 100644 index a6d6b8609d..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png deleted file mode 100644 index a6d6b8609d..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png deleted file mode 100644 index 75b2d164a5..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png deleted file mode 100644 index c4df70d39d..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png deleted file mode 100644 index 6a84f41e14..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png deleted file mode 100644 index d0e1f58536..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/integration_tests/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json deleted file mode 100644 index 0bedcf2fd4..0000000000 --- a/integration_tests/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "LaunchImage.png", - "scale" : "1x" - }, - { - "idiom" : "universal", - "filename" : "LaunchImage@2x.png", - "scale" : "2x" - }, - { - "idiom" : "universal", - "filename" : "LaunchImage@3x.png", - "scale" : "3x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} diff --git a/integration_tests/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/integration_tests/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png deleted file mode 100644 index 9da19eacad..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/integration_tests/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png deleted file mode 100644 index 9da19eacad..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/integration_tests/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png deleted file mode 100644 index 9da19eacad..0000000000 Binary files a/integration_tests/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png and /dev/null differ diff --git a/integration_tests/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/integration_tests/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md deleted file mode 100644 index 89c2725b70..0000000000 --- a/integration_tests/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Launch Screen Assets - -You can customize the launch screen with your own desired assets by replacing the image files in this directory. - -You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/integration_tests/ios/Runner/Base.lproj/LaunchScreen.storyboard b/integration_tests/ios/Runner/Base.lproj/LaunchScreen.storyboard deleted file mode 100644 index f2e259c7c9..0000000000 --- a/integration_tests/ios/Runner/Base.lproj/LaunchScreen.storyboard +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/integration_tests/ios/Runner/Base.lproj/Main.storyboard b/integration_tests/ios/Runner/Base.lproj/Main.storyboard deleted file mode 100644 index f3c28516fb..0000000000 --- a/integration_tests/ios/Runner/Base.lproj/Main.storyboard +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/integration_tests/ios/Runner/Info.plist b/integration_tests/ios/Runner/Info.plist deleted file mode 100644 index d34500cad2..0000000000 --- a/integration_tests/ios/Runner/Info.plist +++ /dev/null @@ -1,45 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - tests - CFBundlePackageType - APPL - CFBundleShortVersionString - $(FLUTTER_BUILD_NAME) - CFBundleSignature - ???? - CFBundleVersion - $(FLUTTER_BUILD_NUMBER) - LSRequiresIPhoneOS - - UILaunchStoryboardName - LaunchScreen - UIMainStoryboardFile - Main - UISupportedInterfaceOrientations - - UIInterfaceOrientationPortrait - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UISupportedInterfaceOrientations~ipad - - UIInterfaceOrientationPortrait - UIInterfaceOrientationPortraitUpsideDown - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UIViewControllerBasedStatusBarAppearance - - - diff --git a/integration_tests/ios/Runner/Runner-Bridging-Header.h b/integration_tests/ios/Runner/Runner-Bridging-Header.h deleted file mode 100644 index 308a2a560b..0000000000 --- a/integration_tests/ios/Runner/Runner-Bridging-Header.h +++ /dev/null @@ -1 +0,0 @@ -#import "GeneratedPluginRegistrant.h" diff --git a/integration_tests/lib/bridge/from_native.dart b/integration_tests/lib/bridge/from_native.dart index 3a3eb69327..27bde2f385 100644 --- a/integration_tests/lib/bridge/from_native.dart +++ b/integration_tests/lib/bridge/from_native.dart @@ -1,25 +1,26 @@ /* - * Copyright (C) 2020-present The Kraken authors. All rights reserved. + * Copyright (C) 2020-present The WebF authors. All rights reserved. */ // ignore_for_file: unused_import, undefined_function import 'dart:async'; import 'dart:convert'; import 'dart:ffi'; -import 'dart:ui'; import 'dart:io' show Platform; import 'dart:typed_data'; +import 'dart:ui'; + import 'package:ffi/ffi.dart'; import 'package:flutter/material.dart'; -import 'package:kraken/launcher.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/bridge.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:test/test.dart'; +import 'package:webf/bridge.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/launcher.dart'; -import 'test_input.dart'; import 'match_snapshots.dart'; +import 'test_input.dart'; // Steps for using dart:ffi to call a Dart function from C: // 1. Import dart:ffi. @@ -29,7 +30,7 @@ import 'match_snapshots.dart'; // 5. Get a reference to the C function, and put it into a variable. // 6. Call from C. -typedef Native_JSError = Void Function(Int32 contextId, Pointer); +typedef NativeJSError = Void Function(Int32 contextId, Pointer); typedef JSErrorListener = void Function(String); List _listenerList = List.filled(10, (String string) { @@ -45,16 +46,18 @@ void _onJSError(int contextId, Pointer charStr) { _listenerList[contextId](msg); } -final Pointer> _nativeOnJsError = Pointer.fromFunction(_onJSError); +final Pointer> _nativeOnJsError = Pointer.fromFunction(_onJSError); -typedef Native_MatchImageSnapshotCallback = Void Function(Pointer callbackContext, Int32 contextId, Int8, Pointer); -typedef Dart_MatchImageSnapshotCallback = void Function(Pointer callbackContext, int contextId, int, Pointer); -typedef Native_MatchImageSnapshot = Void Function( - Pointer callbackContext, Int32 contextId, - Pointer, Int32, Pointer, Pointer>); +typedef NativeMatchImageSnapshotCallback = Void Function( + Pointer callbackContext, Int32 contextId, Int8, Pointer); +typedef DartMatchImageSnapshotCallback = void Function( + Pointer callbackContext, int contextId, int, Pointer); +typedef NativeMatchImageSnapshot = Void Function(Pointer callbackContext, Int32 contextId, Pointer, Int32, + Pointer, Pointer>); -void _matchImageSnapshot(Pointer callbackContext, int contextId, Pointer bytes, int size, Pointer snapshotNamePtr, Pointer> pointer) { - Dart_MatchImageSnapshotCallback callback = pointer.asFunction(); +void _matchImageSnapshot(Pointer callbackContext, int contextId, Pointer bytes, int size, + Pointer snapshotNamePtr, Pointer> pointer) { + DartMatchImageSnapshotCallback callback = pointer.asFunction(); String filename = nativeStringToString(snapshotNamePtr); matchImageSnapshot(bytes.asTypedList(size), filename).then((value) { callback(callbackContext, contextId, value ? 1 : 0, nullptr); @@ -64,7 +67,8 @@ void _matchImageSnapshot(Pointer callbackContext, int contextId, Pointer> _nativeMatchImageSnapshot = Pointer.fromFunction(_matchImageSnapshot); +final Pointer> _nativeMatchImageSnapshot = + Pointer.fromFunction(_matchImageSnapshot); typedef NativeEnvironment = Pointer Function(); typedef DartEnvironment = Pointer Function(); @@ -75,8 +79,8 @@ Pointer _environment() { final Pointer> _nativeEnvironment = Pointer.fromFunction(_environment); -typedef Native_SimulatePointer = Void Function(Pointer>, Int32 length, Int32 pointer); -typedef Native_SimulateInputText = Void Function(Pointer); +typedef NativeSimulatePointer = Void Function(Pointer>, Int32 length, Int32 pointer); +typedef NativeSimulateInputText = Void Function(Pointer); PointerChange _getPointerChange(double change) { return PointerChange.values[change.toInt()]; @@ -106,23 +110,22 @@ void _simulatePointer(Pointer> mousePointerList, int lengt double change = mousePointerList[i].ref.change; data.add(PointerData( - // TODO: remove hardcode '360' width that for double testing in one flutter window - physicalX: (360 * contextId + x) * window.devicePixelRatio, - physicalY: (56.0 + y) * window.devicePixelRatio, - // MouseEvent will trigger [RendererBinding.dispatchEvent] -> [BaseMouseTracker.updateWithEvent] - // which handle extra mouse connection phase for [event.kind = PointerDeviceKind.mouse]. - // Prefer to use touch event. - kind: PointerDeviceKind.touch, - change: _getPointerChange(change), - pointerIdentifier: pointer - )); + // TODO: remove hardcode '360' width that for double testing in one flutter window + physicalX: (360 * contextId + x) * window.devicePixelRatio, + physicalY: (56.0 + y) * window.devicePixelRatio, + // MouseEvent will trigger [RendererBinding.dispatchEvent] -> [BaseMouseTracker.updateWithEvent] + // which handle extra mouse connection phase for [event.kind = PointerDeviceKind.mouse]. + // Prefer to use touch event. + kind: PointerDeviceKind.touch, + change: _getPointerChange(change), + pointerIdentifier: pointer)); } PointerDataPacket dataPacket = PointerDataPacket(data: data); window.onPointerDataPacket!(dataPacket); } -final Pointer> _nativeSimulatePointer = Pointer.fromFunction(_simulatePointer); +final Pointer> _nativeSimulatePointer = Pointer.fromFunction(_simulatePointer); late TestTextInput testTextInput; void _simulateInputText(Pointer nativeChars) { @@ -130,7 +133,8 @@ void _simulateInputText(Pointer nativeChars) { testTextInput.enterText(text); } -final Pointer> _nativeSimulateInputText = Pointer.fromFunction(_simulateInputText); +final Pointer> _nativeSimulateInputText = + Pointer.fromFunction(_simulateInputText); final List _dartNativeMethods = [ _nativeOnJsError.address, @@ -140,11 +144,12 @@ final List _dartNativeMethods = [ _nativeSimulateInputText.address ]; -typedef Native_RegisterTestEnvDartMethods = Void Function(Pointer methodBytes, Int32 length); -typedef Dart_RegisterTestEnvDartMethods = void Function(Pointer methodBytes, int length); +typedef NativeRegisterTestEnvDartMethods = Void Function(Pointer methodBytes, Int32 length); +typedef DartRegisterTestEnvDartMethods = void Function(Pointer methodBytes, int length); -final Dart_RegisterTestEnvDartMethods _registerTestEnvDartMethods = -KrakenDynamicLibrary.ref.lookup>('registerTestEnvDartMethods').asFunction(); +final DartRegisterTestEnvDartMethods _registerTestEnvDartMethods = WebFDynamicLibrary.ref + .lookup>('registerTestEnvDartMethods') + .asFunction(); void registerDartTestMethodsToCpp() { Pointer bytes = malloc.allocate(sizeOf() * _dartNativeMethods.length); diff --git a/integration_tests/lib/bridge/match_snapshots.dart b/integration_tests/lib/bridge/match_snapshots.dart index 04fc079d1e..7ce2172b7f 100644 --- a/integration_tests/lib/bridge/match_snapshots.dart +++ b/integration_tests/lib/bridge/match_snapshots.dart @@ -1,15 +1,18 @@ /* - * Copyright (C) 2022-present The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -import 'dart:typed_data'; -import 'dart:io'; import 'dart:async'; -import 'package:path/path.dart' as path; +import 'dart:io'; +import 'dart:typed_data'; +import 'package:image_compare/image_compare.dart'; + import 'package:image/image.dart'; +import 'package:path/path.dart' as path; ///Check if [firstImg] and [secondImg] have the same width and height bool haveSameSize(Image firstImg, Image secondImg) { - if (firstImg.width != secondImg.width || firstImg.height != secondImg.height) { + if (firstImg.width != secondImg.width || + firstImg.height != secondImg.height) { return false; } return true; @@ -25,8 +28,10 @@ int selectColor(firstPixel, secondPixel, diffAtPixel) { var sBlue = getBlue(secondPixel); if (diffAtPixel == 0) return Color.fromRgba(fRed, fGreen, fBlue, 50); - if (fRed == 0 && fGreen == 0 && fBlue == 0) return Color.fromRgba(sRed, sGreen, sBlue, 50); - if (sRed == 0 && sGreen == 0 && sBlue == 0) return Color.fromRgba(fRed, fGreen, fBlue, 50); + if (fRed == 0 && fGreen == 0 && fBlue == 0) + return Color.fromRgba(sRed, sGreen, sBlue, 50); + if (sRed == 0 && sGreen == 0 && sBlue == 0) + return Color.fromRgba(fRed, fGreen, fBlue, 50); int alpha, red, green, blue; @@ -48,7 +53,8 @@ num diffBetweenPixels(firstPixel, secondPixel, ignoreAlpha) { var sBlue = getBlue(secondPixel); var sAlpha = getAlpha(secondPixel); - num diff = (fRed - sRed).abs() + (fGreen - sGreen).abs() + (fBlue - sBlue).abs(); + num diff = + (fRed - sRed).abs() + (fGreen - sGreen).abs() + (fBlue - sBlue).abs(); if (ignoreAlpha) { diff = (diff / 255) / 3; @@ -60,7 +66,7 @@ num diffBetweenPixels(firstPixel, secondPixel, ignoreAlpha) { return diff; } -bool matchImage(Uint8List imageA, List imageB, String filename) { +Future matchImage(Uint8List imageA, List imageB, String filename) async { if (imageA.length == 0 || imageB.length == 0) { return false; } @@ -71,37 +77,34 @@ bool matchImage(Uint8List imageA, List imageB, String filename) { return false; } - var width = a.width; - var height = b.height; - var diff = 0.0; + double ratio = await compareImages(src1: a, src2: b, algorithm: EuclideanColorDistance(ignoreAlpha: true)); + bool isMatch = (ratio * 100) < 1; - //Create an image to show the differences - var diffImg = Image(width, height); - - for (var i = 0; i < width; i++) { - var diffAtPixel, firstPixel, secondPixel; - for (var j = 0; j < height; j++) { - firstPixel = a.getPixel(i, j); - secondPixel = b.getPixel(i, j); + if (!isMatch) { + var width = a.width; + var height = b.height; - diffAtPixel = diffBetweenPixels(firstPixel, secondPixel, true); - diff += diffAtPixel; + //Create an image to show the differences + var diffImg = Image(width, height); - //Shows in red the different pixels and in semitransparent the same ones - diffImg.setPixel(i, j, selectColor(firstPixel, secondPixel, diffAtPixel)); - } - } + for (var i = 0; i < width; i++) { + var diffAtPixel, firstPixel, secondPixel; + for (var j = 0; j < height; j++) { + firstPixel = a.getPixel(i, j); + secondPixel = b.getPixel(i, j); - diff /= height * width; + diffAtPixel = diffBetweenPixels(firstPixel, secondPixel, true); - bool isMatch = (diff * 10e5) < 1; + //Shows in red the different pixels and in semitransparent the same ones + diffImg.setPixel(i, j, selectColor(firstPixel, secondPixel, diffAtPixel)); + } + } - if (!isMatch) { final newSnap = File('$filename.diff.png'); newSnap.writeAsBytesSync(encodePng(diffImg)); } - return isMatch; // < 0.001% + return isMatch; // < 0.01% } bool matchFile(List left, List right) { @@ -109,7 +112,7 @@ bool matchFile(List left, List right) { return false; } - for (int i = 0; i < left.length; i ++) { + for (int i = 0; i < left.length; i++) { if (left[i] != right[i]) { return false; } @@ -135,7 +138,7 @@ Future matchImageSnapshot(Uint8List bytes, String filename) async { match = matchFile(snapPixels, currentPixels); } if (!match) { - match = matchImage(snapPixels, currentPixels, filename); + match = await matchImage(snapPixels, currentPixels, filename); } if (!match) { final newSnap = File('$filename.current.png'); diff --git a/integration_tests/lib/bridge/test_input.dart b/integration_tests/lib/bridge/test_input.dart index 9f6f227576..77afb7b68a 100644 --- a/integration_tests/lib/bridge/test_input.dart +++ b/integration_tests/lib/bridge/test_input.dart @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022-present The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ // Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be @@ -39,7 +39,7 @@ class TestTextInput { /// /// The [onCleared] argument may be set to be notified of when the keyboard /// is dismissed. - TestTextInput({ this.onCleared }); + TestTextInput({this.onCleared}); /// Called when the keyboard goes away. /// @@ -104,6 +104,7 @@ class TestTextInput { assert(isRegistered); return _isVisible; } + bool _isVisible = false; /// Resets any internal state of this object. @@ -196,7 +197,7 @@ class TestTextInput { /// * [enterText], which is similar but takes only a String and resets the /// selection. void updateEditingValue(TextEditingValue value) { - ServicesBinding.instance!.defaultBinaryMessenger.handlePlatformMessage( + ServicesBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.textInput.name, SystemChannels.textInput.codec.encodeMethodCall( MethodCall( @@ -204,7 +205,7 @@ class TestTextInput { [_client ?? -1, value.toJSON()], ), ), - (ByteData? data) { /* ignored */ }, + (ByteData? data) {/* ignored */}, ); } @@ -220,7 +221,7 @@ class TestTextInput { Future receiveAction(TextInputAction action) async { return TestAsyncUtils.guard(() { final Completer completer = Completer(); - ServicesBinding.instance!.defaultBinaryMessenger.handlePlatformMessage( + ServicesBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.textInput.name, SystemChannels.textInput.codec.encodeMethodCall( MethodCall( @@ -260,16 +261,15 @@ class TestTextInput { /// example when using the [integration_test] library, there is a risk that /// the real IME will become confused as to the current state of input. void closeConnection() { - ServicesBinding.instance!.defaultBinaryMessenger.handlePlatformMessage( + ServicesBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.textInput.name, SystemChannels.textInput.codec.encodeMethodCall( MethodCall( 'TextInputClient.onConnectionClosed', - [_client ?? -1], + [_client ?? -1], ), ), - (ByteData? data) { /* response from framework is discarded */ }, + (ByteData? data) {/* response from framework is discarded */}, ); } } - diff --git a/integration_tests/lib/bridge/to_native.dart b/integration_tests/lib/bridge/to_native.dart index 0eb96bc5c1..d63c048f1d 100644 --- a/integration_tests/lib/bridge/to_native.dart +++ b/integration_tests/lib/bridge/to_native.dart @@ -1,12 +1,12 @@ /* - * Copyright (C) 2020-present The Kraken authors. All rights reserved. + * Copyright (C) 2020-present The WebF authors. All rights reserved. */ import 'dart:async'; import 'dart:ffi'; import 'package:ffi/ffi.dart'; -import 'package:kraken/bridge.dart'; +import 'package:webf/bridge.dart'; // Steps for using dart:ffi to call a C function from Dart: // 1. Import dart:ffi. @@ -17,22 +17,22 @@ import 'package:kraken/bridge.dart'; // 6. Call the C function. // Init Test Framework -typedef Native_InitTestFramework = Void Function(Int32 contextId); -typedef Dart_InitTestFramework = void Function(int contextId); +typedef NativeInitTestFramework = Void Function(Int32 contextId); +typedef DartInitTestFramework = void Function(int contextId); -final Dart_InitTestFramework _initTestFramework = - KrakenDynamicLibrary.ref.lookup>('initTestFramework').asFunction(); +final DartInitTestFramework _initTestFramework = + WebFDynamicLibrary.ref.lookup>('initTestFramework').asFunction(); void initTestFramework(int contextId) { _initTestFramework(contextId); } // Register evaluteTestScripts -typedef Native_EvaluateTestScripts = Int8 Function(Int32 contextId, Pointer, Pointer, Int32); -typedef Dart_EvaluateTestScripts = int Function(int contextId, Pointer, Pointer, int); +typedef NativeEvaluateTestScripts = Int8 Function(Int32 contextId, Pointer, Pointer, Int32); +typedef DartEvaluateTestScripts = int Function(int contextId, Pointer, Pointer, int); -final Dart_EvaluateTestScripts _evaluateTestScripts = -KrakenDynamicLibrary.ref.lookup>('evaluateTestScripts').asFunction(); +final DartEvaluateTestScripts _evaluateTestScripts = + WebFDynamicLibrary.ref.lookup>('evaluateTestScripts').asFunction(); void evaluateTestScripts(int contextId, String code, {String url = 'test://', int line = 0}) { Pointer _url = (url).toNativeUtf8(); @@ -41,11 +41,11 @@ void evaluateTestScripts(int contextId, String code, {String url = 'test://', in typedef NativeExecuteCallback = Void Function(Int32 contextId, Pointer status); typedef DartExecuteCallback = void Function(int); -typedef Native_ExecuteTest = Void Function(Int32 contextId, Pointer>); -typedef Dart_ExecuteTest = void Function(int contextId, Pointer>); +typedef NativeExecuteTest = Void Function(Int32 contextId, Pointer>); +typedef DartExecuteTest = void Function(int contextId, Pointer>); -final Dart_ExecuteTest _executeTest = -KrakenDynamicLibrary.ref.lookup>('executeTest').asFunction(); +final DartExecuteTest _executeTest = + WebFDynamicLibrary.ref.lookup>('executeTest').asFunction(); List?> completerList = List.filled(10, null); diff --git a/integration_tests/lib/custom/custom_element.dart b/integration_tests/lib/custom/custom_element.dart index 3ee787ea03..e620da9e56 100644 --- a/integration_tests/lib/custom/custom_element.dart +++ b/integration_tests/lib/custom/custom_element.dart @@ -1,20 +1,20 @@ /* - * Copyright (C) 2022-present The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; -import 'package:kraken/dom.dart' as dom; -import 'package:kraken/foundation.dart'; -import 'package:kraken/widget.dart'; -import 'package:waterfall_flow/waterfall_flow.dart'; + import 'package:flutter/material.dart'; +import 'package:waterfall_flow/waterfall_flow.dart'; +import 'package:webf/dom.dart' as dom; +import 'package:webf/foundation.dart'; +import 'package:webf/widget.dart'; class WaterfallFlowWidgetElement extends WidgetElement { - WaterfallFlowWidgetElement(BindingContext? context) : - super(context); + WaterfallFlowWidgetElement(BindingContext? context) : super(context); List _children = []; - Widget _func (BuildContext context, int index) { + Widget _func(BuildContext context, int index) { return _children[index]; } @@ -29,27 +29,25 @@ class WaterfallFlowWidgetElement extends WidgetElement { crossAxisCount: 2, crossAxisSpacing: 5.0, mainAxisSpacing: 5.0, - lastChildLayoutTypeBuilder: (index) => index == children.length - ? LastChildLayoutType.foot - : LastChildLayoutType.none, + lastChildLayoutTypeBuilder: (index) => + index == children.length ? LastChildLayoutType.foot : LastChildLayoutType.none, ), ); } } class TextWidgetElement extends WidgetElement { - TextWidgetElement(BindingContext? context) : - super(context); + TextWidgetElement(BindingContext? context) : super(context); @override Widget build(BuildContext context, Map properties, List children) { - return Text(properties['value'] ?? '', textDirection: TextDirection.ltr, style: TextStyle(color: Color.fromARGB(255, 100, 100, 100))); + return Text(properties['value'] ?? '', + textDirection: TextDirection.ltr, style: TextStyle(color: Color.fromARGB(255, 100, 100, 100))); } } class ImageWidgetElement extends WidgetElement { - ImageWidgetElement(BindingContext? context) : - super(context); + ImageWidgetElement(BindingContext? context) : super(context); @override Widget build(BuildContext context, Map properties, List children) { @@ -58,8 +56,7 @@ class ImageWidgetElement extends WidgetElement { } class ContainerWidgetElement extends WidgetElement { - ContainerWidgetElement(BindingContext? context) : - super(context); + ContainerWidgetElement(BindingContext? context) : super(context); @override Widget build(BuildContext context, Map properties, List children) { @@ -67,7 +64,11 @@ class ContainerWidgetElement extends WidgetElement { width: 200, height: 200, decoration: const BoxDecoration( - border: Border( top: BorderSide( width: 5, color: Colors.red ), bottom: BorderSide( width: 5, color: Colors.red ), left: BorderSide( width: 5, color: Colors.red ), right: BorderSide( width: 5, color: Colors.red )), + border: Border( + top: BorderSide(width: 5, color: Colors.red), + bottom: BorderSide(width: 5, color: Colors.red), + left: BorderSide(width: 5, color: Colors.red), + right: BorderSide(width: 5, color: Colors.red)), ), child: Column( children: children, @@ -77,16 +78,20 @@ class ContainerWidgetElement extends WidgetElement { } class SampleElement extends dom.Element implements BindingObject { - SampleElement(BindingContext? context) - : super(context); + SampleElement(BindingContext? context) : super(context); getBindingProperty(String key) { switch (key) { - case 'ping': return ping; - case 'fake': return fake; - case 'fn': return fn; - case 'asyncFn': return asyncFn; - case 'asyncFnFailed': return asyncFnFailed; + case 'ping': + return ping; + case 'fake': + return fake; + case 'fn': + return fn; + case 'asyncFn': + return asyncFn; + case 'asyncFnFailed': + return asyncFnFailed; } } @@ -95,42 +100,42 @@ class SampleElement extends dom.Element implements BindingObject { int get fake => 1234; Function get fn => (List args) { - return List.generate(args.length, (index) { - return args[index] * 2; - }); - }; + return List.generate(args.length, (index) { + return args[index] * 2; + }); + }; Function get asyncFn => (List argv) async { - Completer completer = Completer(); - Timer(Duration(seconds: 1), () { - completer.complete(argv[0]); - }); - return completer.future; - }; + Completer completer = Completer(); + Timer(Duration(seconds: 1), () { + completer.complete(argv[0]); + }); + return completer.future; + }; Function get asyncFnFailed => (List args) async { - Completer completer = Completer(); - Timer(Duration(milliseconds: 100), () { - completer.completeError(AssertionError('Asset error')); - }); - return completer.future; - }; + Completer completer = Completer(); + Timer(Duration(milliseconds: 100), () { + completer.completeError(AssertionError('Asset error')); + }); + return completer.future; + }; } -void defineKrakenCustomElements() { - Kraken.defineCustomElement('waterfall-flow', (BindingContext? context) { +void defineWebFCustomElements() { + WebF.defineCustomElement('waterfall-flow', (BindingContext? context) { return WaterfallFlowWidgetElement(context); }); - Kraken.defineCustomElement('flutter-container', (BindingContext? context) { + WebF.defineCustomElement('flutter-container', (BindingContext? context) { return ContainerWidgetElement(context); }); - Kraken.defineCustomElement('sample-element', (BindingContext? context) { + WebF.defineCustomElement('sample-element', (BindingContext? context) { return SampleElement(context); }); - Kraken.defineCustomElement('flutter-text', (BindingContext? context) { + WebF.defineCustomElement('flutter-text', (BindingContext? context) { return TextWidgetElement(context); }); - Kraken.defineCustomElement('flutter-asset-image', (BindingContext? context) { + WebF.defineCustomElement('flutter-asset-image', (BindingContext? context) { return ImageWidgetElement(context); }); } diff --git a/integration_tests/lib/custom/custom_object_element.dart b/integration_tests/lib/custom/custom_object_element.dart index bce2739b26..ec58b44567 100644 --- a/integration_tests/lib/custom/custom_object_element.dart +++ b/integration_tests/lib/custom/custom_object_element.dart @@ -1,161 +1,159 @@ -/* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. - */ - -import 'dart:async'; - -import 'package:flutter/rendering.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken_video_player/video_player.dart'; - -class CustomObjectElement implements ObjectElementClient { - ObjectElementHost objectElementHost; - - CustomObjectElement(this.objectElementHost); - - VideoPlayerController? controller; - - String? _src; - - String? get src => _src; - - set src(String? value) { - if (_src != value) { - bool needDispose = _src != null; - _src = value; - - if (needDispose && controller != null) { - controller!.dispose().then((_) { - _createVideoBox(); - }); - } else { - _createVideoBox(); - } - } - } - - Future createVideoPlayer(String src) { - Completer completer = new Completer(); - - if (src.startsWith('//') || - src.startsWith('http://') || - src.startsWith('https://')) { - controller = VideoPlayerController.network( - src.startsWith('//') ? 'https:' + src : src); - } else if (src.startsWith('file://')) { - controller = VideoPlayerController.file(src); - } else { - // Fallback to asset video - controller = VideoPlayerController.asset(src); - } - - _src = src; - - controller!.initialize().then((int textureId) { - completer.complete(textureId); - }); - - return completer.future; - } - - void addVideoBox(int textureId) { - TextureBox box = TextureBox(textureId: textureId); - objectElementHost.updateChildTextureBox(box); - controller?.play(); - } - - void _createVideoBox() { - createVideoPlayer(_src!).then((textureId) { - addVideoBox(textureId); - _dispatchCustomEvent(); - }); - } - - void _dispatchCustomEvent() { - CustomEvent event = CustomEvent('customevent', CustomEventInit(detail: 'hello world')); - objectElementHost.dispatchEvent(event); - } - - @override - dynamic handleJSCall(String name, List args) { - switch (name) { - case 'play': - controller!.play(); - break; - case 'pause': - controller!.pause(); - break; - } - } - - @override - void setProperty(String key, value) { - if (key == 'src') { - src = value.toString(); - } else if (key == 'data') { - src = value.toString(); - } else if (key == 'loop') { - controller!.setLooping(value == 'true' ? true : false); - } else if (key == 'currentTime') { - controller!.seekTo(Duration(seconds: int.parse(value))); - } - } - - @override - dynamic getProperty(String key) { - switch (key) { - case 'loop': - return controller!.value.isLooping; - case 'currentTime': - return controller!.value.position.inSeconds; - case 'src': - return _src; - case 'videoWidth': - return controller!.value.size!.width; - case 'videoHeight': - return controller!.value.size!.height; - } - } - - @override - void removeProperty(String key) {} - - @override - void setStyle(key, value) { - } - - @override - Future initElementClient(Map properties) async { - return null; - } - - @override - void dispose() { - objectElementHost.updateChildTextureBox(null); - controller?.pause(); - controller?.dispose(); - controller = null; - } - - @override - void didAttachRenderer() {} - - @override - void didDetachRenderer() { - controller?.pause(); - controller?.dispose(); - controller = null; - } - - @override - void willAttachRenderer() { - } - - @override - void willDetachRenderer() { - } -} - -ObjectElementClient customObjectElementFactory(ObjectElementHost host) { - return CustomObjectElement(host); -} +// /* +// * Copyright (C) 2019-present The Kraken authors. All rights reserved. +// */ + +// import 'dart:async'; + +// import 'package:flutter/rendering.dart'; +// import 'package:webf/dom.dart'; +// // import 'package:kraken_video_player/video_player.dart'; + +// class CustomObjectElement implements ObjectElementClient { +// ObjectElementHost objectElementHost; + +// CustomObjectElement(this.objectElementHost); + +// VideoPlayerController? controller; + +// String? _src; + +// String? get src => _src; + +// set src(String? value) { +// if (_src != value) { +// bool needDispose = _src != null; +// _src = value; + +// if (needDispose && controller != null) { +// controller!.dispose().then((_) { +// _createVideoBox(); +// }); +// } else { +// _createVideoBox(); +// } +// } +// } + +// Future createVideoPlayer(String src) { +// Completer completer = new Completer(); + +// if (src.startsWith('//') || +// src.startsWith('http://') || +// src.startsWith('https://')) { +// controller = VideoPlayerController.network( +// src.startsWith('//') ? 'https:' + src : src); +// } else if (src.startsWith('file://')) { +// controller = VideoPlayerController.file(src); +// } else { +// // Fallback to asset video +// controller = VideoPlayerController.asset(src); +// } + +// _src = src; + +// controller!.initialize().then((int textureId) { +// completer.complete(textureId); +// }); + +// return completer.future; +// } + +// void addVideoBox(int textureId) { +// TextureBox box = TextureBox(textureId: textureId); +// objectElementHost.updateChildTextureBox(box); +// controller?.play(); +// } + +// void _createVideoBox() { +// createVideoPlayer(_src!).then((textureId) { +// addVideoBox(textureId); +// _dispatchCustomEvent(); +// }); +// } + +// void _dispatchCustomEvent() { +// CustomEvent event = +// CustomEvent('customevent', CustomEventInit(detail: 'hello world')); +// objectElementHost.dispatchEvent(event); +// } + +// @override +// dynamic handleJSCall(String name, List args) { +// switch (name) { +// case 'play': +// controller!.play(); +// break; +// case 'pause': +// controller!.pause(); +// break; +// } +// } + +// @override +// void setProperty(String key, value) { +// if (key == 'src') { +// src = value.toString(); +// } else if (key == 'data') { +// src = value.toString(); +// } else if (key == 'loop') { +// controller!.setLooping(value == 'true' ? true : false); +// } else if (key == 'currentTime') { +// controller!.seekTo(Duration(seconds: int.parse(value))); +// } +// } + +// @override +// dynamic getProperty(String key) { +// switch (key) { +// case 'loop': +// return controller!.value.isLooping; +// case 'currentTime': +// return controller!.value.position.inSeconds; +// case 'src': +// return _src; +// case 'videoWidth': +// return controller!.value.size!.width; +// case 'videoHeight': +// return controller!.value.size!.height; +// } +// } + +// @override +// void removeProperty(String key) {} + +// @override +// void setStyle(key, value) {} + +// @override +// Future initElementClient(Map properties) async { +// return null; +// } + +// @override +// void dispose() { +// objectElementHost.updateChildTextureBox(null); +// controller?.pause(); +// controller?.dispose(); +// controller = null; +// } + +// @override +// void didAttachRenderer() {} + +// @override +// void didDetachRenderer() { +// controller?.pause(); +// controller?.dispose(); +// controller = null; +// } + +// @override +// void willAttachRenderer() {} + +// @override +// void willDetachRenderer() {} +// } + +// ObjectElementClient customObjectElementFactory(ObjectElementHost host) { +// return CustomObjectElement(host); +// } diff --git a/integration_tests/lib/local_http_server.dart b/integration_tests/lib/local_http_server.dart index 71a44edd67..818ba6bde9 120000 --- a/integration_tests/lib/local_http_server.dart +++ b/integration_tests/lib/local_http_server.dart @@ -1 +1 @@ -../../kraken/test/local_http_server.dart \ No newline at end of file +../../webf/test/local_http_server.dart \ No newline at end of file diff --git a/integration_tests/lib/main.dart b/integration_tests/lib/main.dart index b4da5d49d6..e80b44e795 100644 --- a/integration_tests/lib/main.dart +++ b/integration_tests/lib/main.dart @@ -1,20 +1,20 @@ /* - * Copyright (C) 2022-present The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; import 'dart:io'; -import 'package:flutter/material.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/gesture.dart'; -import 'package:kraken/kraken.dart'; import 'package:ansicolor/ansicolor.dart'; +import 'package:flutter/material.dart'; import 'package:path/path.dart' as path; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/gesture.dart'; +import 'package:webf/webf.dart'; import 'bridge/from_native.dart'; -import 'bridge/to_native.dart'; import 'bridge/test_input.dart'; +import 'bridge/to_native.dart'; import 'custom/custom_element.dart'; import 'local_http_server.dart'; @@ -27,11 +27,11 @@ final String testDirectory = Platform.environment['KRAKEN_TEST_DIR'] ?? __dirnam // By CLI: `KRAKEN_ENABLE_TEST=true flutter run` void main() async { // Overrides library name. - KrakenDynamicLibrary.libName = 'libkraken_test'; - defineKrakenCustomElements(); + WebFDynamicLibrary.libName = 'libwebf_test'; + defineWebFCustomElements(); // FIXME: This is a workaround for testcases. - ParagraphElement.defaultStyle = { DISPLAY: BLOCK }; + ParagraphElement.defaultStyle = {DISPLAY: BLOCK}; // Start local HTTP server. var httpServer = LocalHttpServer.getInstance(); @@ -47,7 +47,7 @@ void main() async { final String specTarget = '.specs/core.build.js'; final File spec = File(path.join(testDirectory, specTarget)); - KrakenJavaScriptChannel javaScriptChannel = KrakenJavaScriptChannel(); + WebFJavaScriptChannel javaScriptChannel = WebFJavaScriptChannel(); javaScriptChannel.onMethodCall = (String method, dynamic arguments) async { javaScriptChannel.invokeMethod(method, arguments); return 'method: ' + method; @@ -55,12 +55,12 @@ void main() async { // This is a virtual location for test program to test [Location] functionality. final String specUrl = 'assets:///test.js'; - late Kraken kraken; + late WebF webF; - kraken = Kraken( + webF = WebF( viewportWidth: 360, viewportHeight: 640, - bundle: KrakenBundle.fromContent('console.log("Starting integration tests...")', url: specUrl), + bundle: WebFBundle.fromContent('console.log("Starting integration tests...")', url: specUrl), disableViewportWidthAssertion: true, disableViewportHeightAssertion: true, javaScriptChannel: javaScriptChannel, @@ -68,7 +68,7 @@ void main() async { onDrag: (GestureEvent gestureEvent) { if (gestureEvent.state == EVENT_STATE_START) { var event = CustomEvent('nativegesture', CustomEventInit(detail: 'nativegesture')); - kraken.controller!.view.document.documentElement?.dispatchEvent(event); + webF.controller!.view.document.documentElement?.dispatchEvent(event); } }, ), @@ -76,15 +76,13 @@ void main() async { runZonedGuarded(() { runApp(MaterialApp( - title: 'Kraken Integration Tests', + title: 'webF Integration Tests', debugShowCheckedModeBanner: false, home: Scaffold( - appBar: AppBar( - title: Text('Kraken Integration Tests') - ), + appBar: AppBar(title: Text('WebF Integration Tests')), body: Wrap( children: [ - kraken, + webF, ], ), ), @@ -95,9 +93,9 @@ void main() async { testTextInput = TestTextInput(); - WidgetsBinding.instance!.addPostFrameCallback((_) async { + WidgetsBinding.instance.addPostFrameCallback((_) async { registerDartTestMethodsToCpp(); - int contextId = kraken.controller!.view.contextId; + int contextId = webF.controller!.view.contextId; initTestFramework(contextId); addJSErrorListener(contextId, print); @@ -106,9 +104,8 @@ void main() async { evaluateTestScripts(contextId, codeInjection + code, url: specUrl); String result = await executeTest(contextId); // Manual dispose context for memory leak check. - disposePage(kraken.controller!.view.contextId); + disposePage(webF.controller!.view.contextId); exit(result == 'failed' ? 1 : 0); }); } - diff --git a/integration_tests/lib/plugin.dart b/integration_tests/lib/plugin.dart index 4e9b031acf..a2cfe8d49f 100644 --- a/integration_tests/lib/plugin.dart +++ b/integration_tests/lib/plugin.dart @@ -1,130 +1,131 @@ -/* - * Copyright (C) 2022-present The Kraken authors. All rights reserved. - */ -import 'dart:async'; -import 'dart:io'; - -import 'package:flutter/material.dart'; -import 'package:kraken/bridge.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/foundation.dart'; -import 'package:kraken/widget.dart'; -import 'package:ansicolor/ansicolor.dart'; -import 'package:path/path.dart' as path; -import 'package:kraken_websocket/kraken_websocket.dart'; -import 'package:kraken_video_player/kraken_video_player.dart'; -import 'package:kraken_webview/kraken_webview.dart'; - -import 'bridge/from_native.dart'; -import 'bridge/to_native.dart'; -import 'custom/custom_object_element.dart'; - -String? pass = (AnsiPen()..green())('[TEST PASS]'); -String? err = (AnsiPen()..red())('[TEST FAILED]'); - -final String __dirname = path.dirname(Platform.script.path); -final String testDirectory = - Platform.environment['KRAKEN_TEST_DIR'] ?? __dirname; - -const int KRAKEN_NUM = 1; -Map krakenMap = Map(); - -// Test for UriParser. -class IntegrationTestUriParser extends UriParser { - @override - Uri resolve(Uri base, Uri relative) { - if (base.toString().isEmpty && relative.path.startsWith('assets/')) { - return Uri.file(relative.path); - } else { - return super.resolve(base, relative); - } - } -} - -// By CLI: `KRAKEN_ENABLE_TEST=true flutter run` -void main() async { - // Overrides library name. - KrakenDynamicLibrary.libName = 'libkraken_test'; - - KrakenWebsocket.initialize(); - KrakenVideoPlayer.initialize(); - KrakenWebView.initialize(); - setObjectElementFactory(customObjectElementFactory); - - // FIXME: This is a workaround for testcase - ParagraphElement.defaultStyle = { - DISPLAY: BLOCK, - }; - - // Set render font family AlibabaPuHuiTi to resolve rendering difference. - CSSText.DEFAULT_FONT_FAMILY_FALLBACK = ['AlibabaPuHuiTi']; - - File specs = File(path.join(testDirectory, '.specs/plugin.build.js')); - - List> allSpecsPayload = [ - { - 'filename': path.basename(specs.path), - 'filepath': specs.path, - 'code': specs.readAsStringSync() - } - ]; - List widgets = []; - - for (int i = 0; i < KRAKEN_NUM; i++) { - var kraken = krakenMap[i] = Kraken( - viewportWidth: 360, - viewportHeight: 640, - bundle: KrakenBundle.fromContent('console.log("Starting Plugin tests...")'), - disableViewportWidthAssertion: true, - disableViewportHeightAssertion: true, - uriParser: IntegrationTestUriParser(), - ); - widgets.add(kraken); - } - - runApp(MaterialApp( - title: 'Kraken Plugin Tests', - debugShowCheckedModeBanner: false, - home: Scaffold( - appBar: AppBar(title: Text('Kraken Plugin Tests')), - body: Wrap( - children: widgets, - ), - ), - )); - - WidgetsBinding.instance!.addPostFrameCallback((_) async { - registerDartTestMethodsToCpp(); - - List> testResults = []; - - for (int i = 0; i < widgets.length; i++) { - int contextId = i; - initTestFramework(contextId); - addJSErrorListener(contextId, (String err) { - print(err); - }); - - Map payload = allSpecsPayload[i]; - - // Preload load test cases - String filename = payload['filename']!; - String code = payload['code']!; - evaluateTestScripts(contextId, code, url: filename); - - testResults.add(executeTest(contextId)); - } - - List results = await Future.wait(testResults); - - for (int i = 0; i < results.length; i++) { - String status = results[i]; - if (status == 'failed') { - exit(1); - } - } - - exit(0); - }); -} +// /* +// * Copyright (C) 2022-present The Kraken authors. All rights reserved. +// */ +// import 'dart:async'; +// import 'dart:io'; + +// import 'package:flutter/material.dart'; +// import 'package:webf/bridge.dart'; +// import 'package:webf/css.dart'; +// import 'package:webf/dom.dart'; +// import 'package:webf/foundation.dart'; +// import 'package:webf/widget.dart'; +// import 'package:ansicolor/ansicolor.dart'; +// import 'package:path/path.dart' as path; +// // import 'package:kraken_websocket/kraken_websocket.dart'; +// // import 'package:kraken_video_player/kraken_video_player.dart'; +// // import 'package:kraken_webview/kraken_webview.dart'; + +// import 'bridge/from_native.dart'; +// import 'bridge/to_native.dart'; +// import 'custom/custom_object_element.dart'; + +// String? pass = (AnsiPen()..green())('[TEST PASS]'); +// String? err = (AnsiPen()..red())('[TEST FAILED]'); + +// final String __dirname = path.dirname(Platform.script.path); +// final String testDirectory = +// Platform.environment['KRAKEN_TEST_DIR'] ?? __dirname; + +// const int KRAKEN_NUM = 1; +// Map krakenMap = Map(); + +// // Test for UriParser. +// class IntegrationTestUriParser extends UriParser { +// @override +// Uri resolve(Uri base, Uri relative) { +// if (base.toString().isEmpty && relative.path.startsWith('assets/')) { +// return Uri.file(relative.path); +// } else { +// return super.resolve(base, relative); +// } +// } +// } + +// // By CLI: `KRAKEN_ENABLE_TEST=true flutter run` +// void main() async { +// // Overrides library name. +// KrakenDynamicLibrary.libName = 'libkraken_test'; + +// KrakenWebsocket.initialize(); +// KrakenVideoPlayer.initialize(); +// KrakenWebView.initialize(); +// setObjectElementFactory(customObjectElementFactory); + +// // FIXME: This is a workaround for testcase +// ParagraphElement.defaultStyle = { +// DISPLAY: BLOCK, +// }; + +// // Set render font family AlibabaPuHuiTi to resolve rendering difference. +// CSSText.DEFAULT_FONT_FAMILY_FALLBACK = ['AlibabaPuHuiTi']; + +// File specs = File(path.join(testDirectory, '.specs/plugin.build.js')); + +// List> allSpecsPayload = [ +// { +// 'filename': path.basename(specs.path), +// 'filepath': specs.path, +// 'code': specs.readAsStringSync() +// } +// ]; +// List widgets = []; + +// for (int i = 0; i < KRAKEN_NUM; i++) { +// var kraken = krakenMap[i] = Kraken( +// viewportWidth: 360, +// viewportHeight: 640, +// bundle: +// KrakenBundle.fromContent('console.log("Starting Plugin tests...")'), +// disableViewportWidthAssertion: true, +// disableViewportHeightAssertion: true, +// uriParser: IntegrationTestUriParser(), +// ); +// widgets.add(kraken); +// } + +// runApp(MaterialApp( +// title: 'Kraken Plugin Tests', +// debugShowCheckedModeBanner: false, +// home: Scaffold( +// appBar: AppBar(title: Text('Kraken Plugin Tests')), +// body: Wrap( +// children: widgets, +// ), +// ), +// )); + +// WidgetsBinding.instance.addPostFrameCallback((_) async { +// registerDartTestMethodsToCpp(); + +// List> testResults = []; + +// for (int i = 0; i < widgets.length; i++) { +// int contextId = i; +// initTestFramework(contextId); +// addJSErrorListener(contextId, (String err) { +// print(err); +// }); + +// Map payload = allSpecsPayload[i]; + +// // Preload load test cases +// String filename = payload['filename']!; +// String code = payload['code']!; +// evaluateTestScripts(contextId, code, url: filename); + +// testResults.add(executeTest(contextId)); +// } + +// List results = await Future.wait(testResults); + +// for (int i = 0; i < results.length; i++) { +// String status = results[i]; +// if (status == 'failed') { +// exit(1); +// } +// } + +// exit(0); +// }); +// } diff --git a/integration_tests/linux/.gitignore b/integration_tests/linux/.gitignore new file mode 100644 index 0000000000..d3896c9844 --- /dev/null +++ b/integration_tests/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/integration_tests/linux/CMakeLists.txt b/integration_tests/linux/CMakeLists.txt new file mode 100644 index 0000000000..849967ee9b --- /dev/null +++ b/integration_tests/linux/CMakeLists.txt @@ -0,0 +1,119 @@ +cmake_minimum_required(VERSION 3.10) +project(runner LANGUAGES CXX) + +set(BINARY_NAME "app") +set(APPLICATION_ID "com.example.app") + +cmake_policy(SET CMP0063 NEW) + +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Configure build options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") + +# Flutter library and tool build rules. +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Application build +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) +apply_standard_settings(${BINARY_NAME}) +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) +add_dependencies(${BINARY_NAME} flutter_assemble) +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +set(KRAKEN_TEST_LIBRARY "${CMAKE_CURRENT_SOURCE_DIR}/../../bridge/build/linux/lib/libkraken_test.so") +install(FILES "${KRAKEN_TEST_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/integration_tests/linux/flutter/CMakeLists.txt b/integration_tests/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000000..33fd5801e7 --- /dev/null +++ b/integration_tests/linux/flutter/CMakeLists.txt @@ -0,0 +1,87 @@ +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/integration_tests/linux/flutter/generated_plugin_registrant.cc b/integration_tests/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000000..92f2fbaaa3 --- /dev/null +++ b/integration_tests/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) webf_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "WebfPlugin"); + webf_plugin_register_with_registrar(webf_registrar); +} diff --git a/integration_tests/linux/flutter/generated_plugin_registrant.h b/integration_tests/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000000..e0f0a47bc0 --- /dev/null +++ b/integration_tests/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/integration_tests/linux/flutter/generated_plugins.cmake b/integration_tests/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000000..3b18a0b7de --- /dev/null +++ b/integration_tests/linux/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + webf +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/integration_tests/linux/main.cc b/integration_tests/linux/main.cc new file mode 100644 index 0000000000..e7c5c54370 --- /dev/null +++ b/integration_tests/linux/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/integration_tests/linux/my_application.cc b/integration_tests/linux/my_application.cc new file mode 100644 index 0000000000..3a86cf5fe7 --- /dev/null +++ b/integration_tests/linux/my_application.cc @@ -0,0 +1,104 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "app"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "app"); + } + + gtk_window_set_default_size(window, 360, 640); + gtk_widget_show(GTK_WIDGET(window)); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, + "flags", G_APPLICATION_NON_UNIQUE, + nullptr)); +} diff --git a/integration_tests/linux/my_application.h b/integration_tests/linux/my_application.h new file mode 100644 index 0000000000..72271d5e41 --- /dev/null +++ b/integration_tests/linux/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/integration_tests/macos/Runner.xcodeproj/project.pbxproj b/integration_tests/macos/Runner.xcodeproj/project.pbxproj index a0d13f3f03..7a9fccfe7c 100644 --- a/integration_tests/macos/Runner.xcodeproj/project.pbxproj +++ b/integration_tests/macos/Runner.xcodeproj/project.pbxproj @@ -21,7 +21,7 @@ /* End PBXAggregateTarget section */ /* Begin PBXBuildFile section */ - 1BBD1BD926F386FE00962139 /* libkraken_test.dylib in Embed Libraries */ = {isa = PBXBuildFile; fileRef = 1BBD1BD726F386FE00962139 /* libkraken_test.dylib */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; + 1BBD1BD926F386FE00962139 /* libwebf_test.dylib in Embed Libraries */ = {isa = PBXBuildFile; fileRef = 1BBD1BD726F386FE00962139 /* libwebf_test.dylib */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; @@ -47,7 +47,7 @@ dstPath = ""; dstSubfolderSpec = 10; files = ( - 1BBD1BD926F386FE00962139 /* libkraken_test.dylib in Embed Libraries */, + 1BBD1BD926F386FE00962139 /* libwebf_test.dylib in Embed Libraries */, ); name = "Embed Libraries"; runOnlyForDeploymentPostprocessing = 0; @@ -55,7 +55,7 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 1BBD1BD726F386FE00962139 /* libkraken_test.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libkraken_test.dylib; path = ../../bridge/build/macos/lib/x86_64/libkraken_test.dylib; sourceTree = ""; }; + 1BBD1BD726F386FE00962139 /* libwebf_test.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libwebf_test.dylib; path = ../../bridge/build/macos/lib/x86_64/libwebf_test.dylib; sourceTree = ""; }; 232E80EF84E689DED3537A8E /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; @@ -168,7 +168,7 @@ D73912EC22F37F3D000D13A0 /* Frameworks */ = { isa = PBXGroup; children = ( - 1BBD1BD726F386FE00962139 /* libkraken_test.dylib */, + 1BBD1BD726F386FE00962139 /* libwebf_test.dylib */, 232E80EF84E689DED3537A8E /* Pods_Runner.framework */, ); name = Frameworks; diff --git a/integration_tests/pubspec.yaml b/integration_tests/pubspec.yaml index 4368321462..db48adb09f 100644 --- a/integration_tests/pubspec.yaml +++ b/integration_tests/pubspec.yaml @@ -17,25 +17,25 @@ environment: sdk: '>=2.12.0 <3.0.0' dependency_overrides: - kraken: - path: ../kraken + webf: + path: ../webf dependencies: - ffi: ^1.0.0 + ffi: ^2.0.1 colorize: ^3.0.0 flutter: sdk: flutter - kraken: 0.8.0-dev.1 image: ^3.0.2 - kraken_video_player: ^2.4.0 - kraken_websocket: ^2.0.0 - kraken_webview: ^2.4.0 +# kraken_video_player: ^2.4.0 +# kraken_websocket: ^2.0.0 +# kraken_webview: ^2.5.0 waterfall_flow: ^3.0.1 - + image_compare: ^1.1.2 + dev_dependencies: flutter_test: sdk: flutter - test: ^1.16.8 + test: ^1.20.2 ansicolor: ^2.0.1 # For information on the generic Dart part of this file, see the diff --git a/integration_tests/runtime/kraken.d.ts b/integration_tests/runtime/kraken.d.ts index 03f3a70441..54e08e7034 100644 --- a/integration_tests/runtime/kraken.d.ts +++ b/integration_tests/runtime/kraken.d.ts @@ -8,11 +8,11 @@ interface MethodChannel { invokeMethod(method: string, ...args: any[]): Promise } -interface Kraken { +interface WebF { methodChannel: MethodChannel; } -declare const kraken: Kraken; +declare const webf: WebF; interface Connection { isConnected: boolean; diff --git a/integration_tests/scripts/core_integration_starter.js b/integration_tests/scripts/core_integration_starter.js index 4e1f028089..7205b62884 100644 --- a/integration_tests/scripts/core_integration_starter.js +++ b/integration_tests/scripts/core_integration_starter.js @@ -3,6 +3,7 @@ */ const { spawn, spawnSync } = require('child_process'); const path = require('path'); +const os = require('os'); // Dart null safety error didn't report in dist binaries. Should run integration test with flutter run directly. function startIntegrationTest() { @@ -14,7 +15,16 @@ function startIntegrationTest() { }); } - const testExecutable = path.join(__dirname, '../build/macos/Build/Products/Debug/tests.app/Contents/MacOS/tests'); + const platform = os.platform(); + let testExecutable; + if (platform === 'linux') { + testExecutable = path.join(__dirname, '../build/linux/x64/debug/bundle/app'); + } else if (platform === 'darwin') { + testExecutable = path.join(__dirname, '../build/macos/Build/Products/Debug/tests.app/Contents/MacOS/tests'); + } else { + throw new Error('Unsupported platform:' + platform); + } + const tester = spawn(testExecutable, [], { env: { ...process.env, @@ -26,6 +36,7 @@ function startIntegrationTest() { cwd: process.cwd(), stdio: 'inherit' }); + tester.on('close', (code) => { process.exit(code); }); diff --git a/integration_tests/snapshots/css/css-display/insert-block-in-inlines.ts.1c4efbd11.png b/integration_tests/snapshots/css/css-display/insert-block-in-inlines.ts.1c4efbd11.png index dcbb5800ac..fb8368ddc9 100644 Binary files a/integration_tests/snapshots/css/css-display/insert-block-in-inlines.ts.1c4efbd11.png and b/integration_tests/snapshots/css/css-display/insert-block-in-inlines.ts.1c4efbd11.png differ diff --git a/integration_tests/snapshots/css/css-display/insert-block-in-inlines.ts.65cfa09f1.png b/integration_tests/snapshots/css/css-display/insert-block-in-inlines.ts.65cfa09f1.png index 2851a789af..8e96b014f6 100644 Binary files a/integration_tests/snapshots/css/css-display/insert-block-in-inlines.ts.65cfa09f1.png and b/integration_tests/snapshots/css/css-display/insert-block-in-inlines.ts.65cfa09f1.png differ diff --git a/integration_tests/snapshots/css/css-display/insert-block-in-inlines.ts.eaefee701.png b/integration_tests/snapshots/css/css-display/insert-block-in-inlines.ts.eaefee701.png index 12638dfb28..9f9b1dafb2 100644 Binary files a/integration_tests/snapshots/css/css-display/insert-block-in-inlines.ts.eaefee701.png and b/integration_tests/snapshots/css/css-display/insert-block-in-inlines.ts.eaefee701.png differ diff --git a/integration_tests/snapshots/css/css-flow/dynamic-change.ts.148ab8cc2.png b/integration_tests/snapshots/css/css-flow/dynamic-change.ts.148ab8cc2.png index 0cff04b3ba..4d73d10a6a 100644 Binary files a/integration_tests/snapshots/css/css-flow/dynamic-change.ts.148ab8cc2.png and b/integration_tests/snapshots/css/css-flow/dynamic-change.ts.148ab8cc2.png differ diff --git a/integration_tests/snapshots/css/css-images/image-fit.ts.cc4d66791.png b/integration_tests/snapshots/css/css-images/image-fit.ts.cc4d66791.png index 29a3a7ccc0..239a0f1425 100644 Binary files a/integration_tests/snapshots/css/css-images/image-fit.ts.cc4d66791.png and b/integration_tests/snapshots/css/css-images/image-fit.ts.cc4d66791.png differ diff --git a/integration_tests/snapshots/dom/elements/span.ts.adb138ae1.png b/integration_tests/snapshots/dom/elements/span.ts.adb138ae1.png index dc9165c331..a0bada1e55 100644 Binary files a/integration_tests/snapshots/dom/elements/span.ts.adb138ae1.png and b/integration_tests/snapshots/dom/elements/span.ts.adb138ae1.png differ diff --git a/integration_tests/snapshots/dom/elements/textarea.ts.e3b8640f1.png b/integration_tests/snapshots/dom/elements/textarea.ts.e3b8640f1.png index a772503cbe..5b07d51736 100644 Binary files a/integration_tests/snapshots/dom/elements/textarea.ts.e3b8640f1.png and b/integration_tests/snapshots/dom/elements/textarea.ts.e3b8640f1.png differ diff --git a/integration_tests/specs/dom/elements/input.ts b/integration_tests/specs/dom/elements/input.ts index 8cb0f99711..72e0e64a60 100644 --- a/integration_tests/specs/dom/elements/input.ts +++ b/integration_tests/specs/dom/elements/input.ts @@ -254,8 +254,10 @@ describe('Tags input', () => { done(); }); - input1.focus(); - input2.focus(); + requestAnimationFrame(() => { + input1.focus(); + input2.focus(); + }); }); @@ -272,8 +274,10 @@ describe('Tags input', () => { done(); }); - input1.focus(); - input2.focus(); + requestAnimationFrame(() => { + input1.focus(); + input2.focus(); + }); }); @@ -478,21 +482,23 @@ describe('Tags input', () => { }) as HTMLInputElement; document.body.appendChild(input); - input.setAttribute('value', 'attribute value'); - expect(input.defaultValue).toBe('attribute value'); - expect(input.value).toBe('attribute value'); - - input.defaultValue = 'default value'; - expect(input.defaultValue).toBe('default value'); - expect(input.value).toBe('default value'); - - input.value = 'property value'; - expect(input.defaultValue).toBe('default value'); - expect(input.value).toBe('property value'); - - input.setAttribute('value', 'attribute value 2'); - expect(input.defaultValue).toBe('attribute value 2'); - // @ts-ignore - expect(input.value).toBe('property value'); + requestAnimationFrame(() => { + input.setAttribute('value', 'attribute value'); + expect(input.defaultValue).toBe('attribute value'); + expect(input.value).toBe('attribute value'); + + input.defaultValue = 'default value'; + expect(input.defaultValue).toBe('default value'); + expect(input.value).toBe('default value'); + + input.value = 'property value'; + expect(input.defaultValue).toBe('default value'); + expect(input.value).toBe('property value'); + + input.setAttribute('value', 'attribute value 2'); + expect(input.defaultValue).toBe('attribute value 2'); + // @ts-ignore + expect(input.value).toBe('property value'); + }); }); }); diff --git a/integration_tests/specs/dom/elements/textarea.ts b/integration_tests/specs/dom/elements/textarea.ts index ca4ccc1a7e..3c2e023968 100644 --- a/integration_tests/specs/dom/elements/textarea.ts +++ b/integration_tests/specs/dom/elements/textarea.ts @@ -467,8 +467,10 @@ describe('Tags textarea', () => { done(); }); - textarea1.focus(); - textarea2.focus(); + requestAnimationFrame(async () => { + textarea1.focus(); + textarea2.focus(); + }); }); @@ -485,8 +487,10 @@ describe('Tags textarea', () => { done(); }); - textarea1.focus(); - textarea2.focus(); + requestAnimationFrame(() => { + textarea1.focus(); + textarea2.focus(); + }); }); it('event input', (done) => { @@ -591,20 +595,22 @@ describe('Tags textarea', () => { ]) as HTMLTextAreaElement; document.body.appendChild(textarea); - text.data = 'text content value'; - expect(textarea.defaultValue).toBe('text content value'); - expect(textarea.value).toBe('text content value'); + requestAnimationFrame(() => { + text.data = 'text content value'; + expect(textarea.defaultValue).toBe('text content value'); + expect(textarea.value).toBe('text content value'); - textarea.defaultValue = 'default value'; - expect(textarea.defaultValue).toBe('default value'); - expect(textarea.value).toBe('default value'); + textarea.defaultValue = 'default value'; + expect(textarea.defaultValue).toBe('default value'); + expect(textarea.value).toBe('default value'); - textarea.value = 'property value'; - expect(textarea.defaultValue).toBe('default value'); - expect(textarea.value).toBe('property value'); + textarea.value = 'property value'; + expect(textarea.defaultValue).toBe('default value'); + expect(textarea.value).toBe('property value'); - text.data = 'text content value 2'; - expect(textarea.defaultValue).toBe('text content value 2'); - expect(textarea.value).toBe('property value'); + text.data = 'text content value 2'; + expect(textarea.defaultValue).toBe('text content value 2'); + expect(textarea.value).toBe('property value'); + }); }); }); diff --git a/integration_tests/specs/method-channel/method-channel.ts b/integration_tests/specs/method-channel/method-channel.ts index c4abb7144c..f8c39b24b4 100644 --- a/integration_tests/specs/method-channel/method-channel.ts +++ b/integration_tests/specs/method-channel/method-channel.ts @@ -1,27 +1,27 @@ describe('MethodChannel', () => { it('addMethodCallHandler multi params', async (done) => { - kraken.methodChannel.addMethodCallHandler((method: string, args: any[]) => { + webf.methodChannel.addMethodCallHandler((method: string, args: any[]) => { expect(method).toBe('helloworld'); expect(args).toEqual(['abc', 1234, null, /* undefined will be converted to */ null, [], true, false, {name: 1}]); done(); }); - let result = await kraken.methodChannel.invokeMethod('helloworld', 'abc', 1234, null, undefined, [], true, false, {name: 1}); + let result = await webf.methodChannel.invokeMethod('helloworld', 'abc', 1234, null, undefined, [], true, false, {name: 1}); expect(result).toBe('method: helloworld'); }); it('invokeMethod', async () => { - let result = await kraken.methodChannel.invokeMethod('helloworld', 'abc'); + let result = await webf.methodChannel.invokeMethod('helloworld', 'abc'); // TEST App will return method string expect(result).toBe('method: helloworld'); }); it('addMethodCallHandler', async (done) => { - kraken.methodChannel.addMethodCallHandler((method: string, args: any[]) => { + webf.methodChannel.addMethodCallHandler((method: string, args: any[]) => { expect(method).toBe('helloworld'); expect(args).toEqual(['abc']); done(); }); - let result = await kraken.methodChannel.invokeMethod('helloworld', 'abc'); + let result = await webf.methodChannel.invokeMethod('helloworld', 'abc'); expect(result).toBe('method: helloworld'); }); @@ -30,16 +30,16 @@ describe('MethodChannel', () => { var handler = (method: string, args: any[]) => { done.fail('should not execute here.'); }; - kraken.methodChannel.addMethodCallHandler(handler); - kraken.methodChannel.removeMethodCallHandler(handler); - let result = await kraken.methodChannel.invokeMethod('helloworld', 'abc'); + webf.methodChannel.addMethodCallHandler(handler); + webf.methodChannel.removeMethodCallHandler(handler); + let result = await webf.methodChannel.invokeMethod('helloworld', 'abc'); expect(result).toBe('method: helloworld'); done(); }); it('addMethodCallHandler multi params with multi handler', async (done) => { let handlerCount = 0; - kraken.methodChannel.addMethodCallHandler((method: string, args: any[]) => { + webf.methodChannel.addMethodCallHandler((method: string, args: any[]) => { handlerCount++; expect(method).toBe('helloworld'); expect(args).toEqual(['abc', 1234, null, /* undefined will be converted to */ null, [], true, false, {name: 1}]); @@ -47,7 +47,7 @@ describe('MethodChannel', () => { done(); } }); - kraken.methodChannel.addMethodCallHandler((method: string, args: any[]) => { + webf.methodChannel.addMethodCallHandler((method: string, args: any[]) => { handlerCount++; expect(method).toBe('helloworld'); expect(args).toEqual(['abc', 1234, null, /* undefined will be converted to */ null, [], true, false, {name: 1}]); @@ -55,7 +55,7 @@ describe('MethodChannel', () => { done(); } }); - let result = await kraken.methodChannel.invokeMethod('helloworld', 'abc', 1234, null, undefined, [], true, false, {name: 1}); + let result = await webf.methodChannel.invokeMethod('helloworld', 'abc', 1234, null, undefined, [], true, false, {name: 1}); expect(result).toBe('method: helloworld'); expect(handlerCount).toBe(2); }); diff --git a/integration_tests/specs/navigator/navigator.ts b/integration_tests/specs/navigator/navigator.ts index 3830100acc..7e66ea5486 100644 --- a/integration_tests/specs/navigator/navigator.ts +++ b/integration_tests/specs/navigator/navigator.ts @@ -2,7 +2,6 @@ describe('Navigator', () => { it('connectivity', async () => { let connection = await navigator.connection.getConnectivity(); expect(connection.isConnected).toBeTrue(); - expect(['wifi', '4g'].includes(connection.type)).toBeTrue(); }); it('hardwareConcurrency', () => { @@ -32,7 +31,7 @@ describe('Navigator', () => { }); it('userAgent', () => { - expect(navigator.userAgent).toMatch(/Kraken/); + expect(navigator.userAgent).toMatch(/WebF/); }); it('clipboard', async () => { diff --git a/integration_tests/specs/window/global.ts b/integration_tests/specs/window/global.ts index 85fb17804b..9baa4f44ec 100644 --- a/integration_tests/specs/window/global.ts +++ b/integration_tests/specs/window/global.ts @@ -3,9 +3,9 @@ describe('window', () => { expect(window).toBe(globalThis as any); }); - it('has kraken defined', () => { + it('has webf defined', () => { // @ts-ignore - expect(typeof window.kraken).toBe('object'); + expect(typeof window.webf).toBe('object'); }); it('equal to this', () => { diff --git a/package.json b/package.json index 3f9eed2557..7f569d11a4 100644 --- a/package.json +++ b/package.json @@ -2,32 +2,32 @@ "private": true, "scripts": { "build:bridge:macos": "node scripts/build_darwin_dylib", - "build:bridge:macos:release": "KRAKEN_BUILD=Release node scripts/build_darwin_dylib", + "build:bridge:macos:release": "WEBF_BUILD=Release node scripts/build_darwin_dylib", "build:bridge:macos:profile": "ENABLE_PROFILE=true npm run build:bridge:macos:release", "build:bridge:android": "node scripts/build_android_so", - "build:bridge:android:release": "KRAKEN_BUILD=Release node scripts/build_android_so", + "build:bridge:android:release": "WEBF_BUILD=Release node scripts/build_android_so", "build:bridge:linux": "node scripts/build_linux", - "build:bridge:linux:release": "KRAKEN_BUILD=Release node scripts/build_linux", + "build:bridge:linux:release": "WEBF_BUILD=Release node scripts/build_linux", "build:bridge:linux:profile": "ENABLE_PROFILE=true node scripts/build_linux", "build:bridge:android:profile": "ENABLE_PROFILE=true npm run build:bridge:android:release", "build:bridge:ios": "node scripts/build_ios_framework", - "build:bridge:ios:release": "KRAKEN_BUILD=Release node scripts/build_ios_framework", + "build:bridge:ios:release": "WEBF_BUILD=Release node scripts/build_ios_framework", "build:bridge:ios:profile": "ENABLE_PROFILE=true npm run build:bridge:ios:release", - "build:bridge:all": "node scripts/prepare_kraken_release_binary", - "build:bridge:all:release": "KRAKEN_BUILD=Release node scripts/prepare_kraken_release_binary", + "build:bridge:all": "node scripts/prepare_webf_release_binary", + "build:bridge:all:release": "WEBF_BUILD=Release node scripts/prepare_webf_release_binary", "build_bridge:all:profile": "ENABLE_PROFILE=true npm run build:bridge:all:release", - "build:android:sdk": "KRAKEN_BUILD=Release node scripts/build_android_sdk", - "build:ios:sdk": "KRAKEN_BUILD=Release node scripts/build_ios_sdk", + "build:android:sdk": "WEBF_BUILD=Release node scripts/build_android_sdk", + "build:ios:sdk": "WEBF_BUILD=Release node scripts/build_ios_sdk", "pretest": "npm install && ENABLE_ASAN=true node scripts/build_darwin_dylib", "posttest": "npm run lint", - "benchmark": "npm install && ENABLE_PROFILE=true KRAKEN_BUILD=Release node scripts/run_benchmark.js", - "start": "cd kraken/example && flutter run", + "benchmark": "npm install && ENABLE_PROFILE=true WEBF_BUILD=Release node scripts/run_benchmark.js", + "start": "cd webf/example && flutter run", "test": "node scripts/run_test.js", "plugin_test": "node scripts/run_plugin_test.js", - "lint": "cd kraken && flutter pub get && flutter analyze", - "format": "cd kraken && flutter format . --line-length=120", + "lint": "cd webf && flutter pub get && flutter analyze", + "format": "cd webf && flutter format . --line-length=120", "ci": "npm install && npm run lint", - "test:unit:report": "lcov-summary kraken/coverage/lcov.info" + "test:unit:report": "lcov-summary webf/coverage/lcov.info" }, "devDependencies": { "ali-oss": "^6.13.2", @@ -36,13 +36,13 @@ "commander": "^5.1.0", "del": "^5.1.0", "gulp": "^4.0.2", + "http-server": "^14.1.0", "lcov-summary": "^1.0.1", "minimist": "^1.2.4", "mkdirp": "^0.5.1", "rimraf": "^3.0.2", "uuid": "^8.3.2", - "ws": "^7.3.0", - "http-server": "^14.1.0" + "ws": "^7.3.0" }, "dependencies": { "prepend-file": "^2.0.1" diff --git a/performance_tests/lib/main.dart b/performance_tests/lib/main.dart index 0b944e2264..2ad20c22b0 100644 --- a/performance_tests/lib/main.dart +++ b/performance_tests/lib/main.dart @@ -2,11 +2,11 @@ * Copyright (C) 2022-present The Kraken authors. All rights reserved. */ -import 'dart:io'; import 'dart:async'; +import 'dart:io'; import 'package:flutter/material.dart'; -import 'package:kraken/kraken.dart'; +import 'package:webf/webf.dart'; import 'package:webview_flutter/webview_flutter.dart'; const benchMarkServer = String.fromEnvironment("SERVER"); @@ -51,8 +51,8 @@ class _WebViewPage extends StatelessWidget { final PerformanceDataCallback _performanceDataCallback; final int _startTime; - _WebViewPage(PerformanceDataCallback performanceDataCallback) : - _performanceDataCallback = performanceDataCallback, + _WebViewPage(PerformanceDataCallback performanceDataCallback) + : _performanceDataCallback = performanceDataCallback, _startTime = DateTime.now().millisecondsSinceEpoch; JavascriptChannel _javascriptChannel(BuildContext context) { @@ -60,8 +60,7 @@ class _WebViewPage extends StatelessWidget { name: 'Message', onMessageReceived: (JavascriptMessage message) { _performanceDataCallback('Web', int.parse(message.message) - _startTime); - } - ); + }); } @override @@ -84,17 +83,17 @@ class _KrakenPage extends StatelessWidget { : _performanceDataCallback = performanceDataCallback, _startTime = DateTime.now().millisecondsSinceEpoch; - KrakenJavaScriptChannel get javaScriptChannel => KrakenJavaScriptChannel() + WebFJavaScriptChannel get javaScriptChannel => WebFJavaScriptChannel() ..onMethodCall = (String method, arguments) async { if (method == 'performance') { - _performanceDataCallback('Kraken', int.parse((arguments as List)[0]) - _startTime); + _performanceDataCallback('WebF', int.parse((arguments as List)[0]) - _startTime); } }; @override Widget build(BuildContext context) { - return Kraken( - bundle: KrakenBundle.fromUrl('http://$benchMarkServer/kraken/home.kbc1'), + return WebF( + bundle: WebFBundle.fromUrl('http://$benchMarkServer/kraken/home.kbc1'), javaScriptChannel: javaScriptChannel, ); } @@ -116,9 +115,7 @@ class _MyHomePageState extends State { void _changeViewAndReloadPage() async { setState(() { - _currentView = _currentView is _KrakenPage - ? _WebViewPage(_getPerformanceData) - :_KrakenPage(_getPerformanceData); + _currentView = _currentView is _KrakenPage ? _WebViewPage(_getPerformanceData) : _KrakenPage(_getPerformanceData); }); } @@ -180,11 +177,11 @@ class _MyHomePageState extends State { ); return Scaffold( - appBar: appBar, - body: Center( - // Center is a layout widget. It takes a single child and positions it - // in the middle of the parent. + appBar: appBar, + body: Center( + // Center is a layout widget. It takes a single child and positions it + // in the middle of the parent. child: _currentView ?? Text('Performance test'), - )); + )); } } diff --git a/performance_tests/pubspec.yaml b/performance_tests/pubspec.yaml index 60c494b793..c4740d24ea 100644 --- a/performance_tests/pubspec.yaml +++ b/performance_tests/pubspec.yaml @@ -23,8 +23,8 @@ environment: dependencies: flutter: sdk: flutter - kraken: - path: ../kraken + webf: + path: ../webf # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. diff --git a/scripts/pre_publish_kraken.js b/scripts/pre_publish_webf.js similarity index 100% rename from scripts/pre_publish_kraken.js rename to scripts/pre_publish_webf.js diff --git a/scripts/prepare_kraken_release_binary.js b/scripts/prepare_webf_release_binary.js similarity index 100% rename from scripts/prepare_kraken_release_binary.js rename to scripts/prepare_webf_release_binary.js diff --git a/scripts/run_bridge_unit_test.js b/scripts/run_bridge_unit_test.js new file mode 100644 index 0000000000..cabc0edd86 --- /dev/null +++ b/scripts/run_bridge_unit_test.js @@ -0,0 +1,15 @@ +/** + * Test script + */ + + require('./tasks'); + + const { series } = require('gulp'); + const chalk = require('chalk'); + + series( + 'run-bridge-unit-test' + )(() => { + console.log(chalk.green('Test Success.')); + }); + \ No newline at end of file diff --git a/scripts/tasks.js b/scripts/tasks.js index 08498391a9..d130b22926 100644 --- a/scripts/tasks.js +++ b/scripts/tasks.js @@ -134,8 +134,14 @@ task('build-darwin-webf-lib', done => { }); task('run-bridge-unit-test', done => { - execSync(`${path.join(paths.bridge, 'build/macos/lib/x86_64/webf_unit_test')}`, {stdio: 'inherit'}); - done(); + if (platform === 'darwin') { + execSync(`${path.join(paths.bridge, 'build/macos/lib/x86_64/webf_unit_test')}`, {stdio: 'inherit'}); + } else if (platform === 'linux') { + execSync(`${path.join(paths.bridge, 'build/linux/lib/webf_unit_test')}`, {stdio: 'inherit'}); + } else { + throw new Error('Platform not supported.'); + } + done(); }); task('compile-polyfill', (done) => { @@ -481,6 +487,7 @@ task('build-linux-webf-lib', (done) => { // generate project execSync(`cmake -DCMAKE_BUILD_TYPE=${buildType} \ ${isProfile ? '-DENABLE_PROFILE=TRUE \\' : '\\'} + ${'-DENABLE_TEST=true \\'} -G "${cmakeGeneratorTemplate}" \ -B ${paths.bridge}/cmake-build-linux -S ${paths.bridge}`, { @@ -494,13 +501,23 @@ task('build-linux-webf-lib', (done) => { }); // build - execSync(`cmake --build ${bridgeCmakeDir} --target webf -- -j 12`, { + execSync(`cmake --build ${bridgeCmakeDir} --target webf ${buildMode != 'Release' ? 'webf_test' : ''} webf_unit_test -- -j 12`, { stdio: 'inherit' }); - const libwebfPath = path.join(paths.bridge, 'build/linux/lib/libwebf.so'); - // Patch libwebf.so's runtime path. - execSync(`chrpath --replace \\$ORIGIN ${libwebfPath}`, { stdio: 'inherit' }); + const libs = [ + 'libwebf.so' + ]; + + if (buildMode != 'Release') { + libs.push('libwebf_test.so'); + } + + libs.forEach(lib => { + const libkrakenPath = path.join(paths.bridge, `build/linux/lib/${lib}`); + // Patch libkraken.so's runtime path. + execSync(`chrpath --replace \\$ORIGIN ${libkrakenPath}`, { stdio: 'inherit' }); + }); done(); }); @@ -516,8 +533,10 @@ task('build-android-webf-lib', (done) => { } else { if (platform == 'win32') { androidHome = path.join(process.env.LOCALAPPDATA, 'Android\\Sdk'); - } else { + } else if (platform == 'darwin') { androidHome = path.join(process.env.HOME, 'Library/Android/sdk') + } else if (platform == 'linux') { + androidHome = path.join(process.env.HOME, 'Android/Sdk'); } const ndkVersion = '23.2.8568313'; ndkDir = path.join(androidHome, 'ndk', ndkVersion); diff --git a/sdk/lib/main.dart b/sdk/lib/main.dart index 7fae167c1d..af40f4a57f 100644 --- a/sdk/lib/main.dart +++ b/sdk/lib/main.dart @@ -1,4 +1,4 @@ -import 'package:kraken/kraken.dart'; +import 'package:webf/webf.dart'; void main() { launch(); diff --git a/sdk/pubspec.yaml b/sdk/pubspec.yaml index e6455d271b..c57d9daafb 100644 --- a/sdk/pubspec.yaml +++ b/sdk/pubspec.yaml @@ -8,15 +8,15 @@ environment: dependencies: flutter: sdk: flutter - kraken: ^0.8.0 + webf: ^0.8.0 dev_dependencies: flutter_test: sdk: flutter dependency_overrides: - kraken: - path: ../kraken + webf: + path: ../webf # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/webf/android/build.gradle b/webf/android/build.gradle index 67ac20dce8..267e0ae98e 100644 --- a/webf/android/build.gradle +++ b/webf/android/build.gradle @@ -3,8 +3,15 @@ version '1.0' buildscript { repositories { - google() - jcenter() + maven { + url 'https://maven.aliyun.com/repository/public/' + } + maven { + url 'https://maven.aliyun.com/repository/google/' + } + maven { + url 'https://maven.aliyun.com/repository/jcenter/' + } } dependencies { @@ -14,8 +21,15 @@ buildscript { rootProject.allprojects { repositories { - google() - jcenter() + maven { + url 'https://maven.aliyun.com/repository/public/' + } + maven { + url 'https://maven.aliyun.com/repository/google/' + } + maven { + url 'https://maven.aliyun.com/repository/jcenter/' + } } } diff --git a/webf/android/settings.gradle b/webf/android/settings.gradle index 6f7d762e54..d1f4b345e5 100644 --- a/webf/android/settings.gradle +++ b/webf/android/settings.gradle @@ -1 +1 @@ -rootProject.name = 'kraken' +rootProject.name = 'webf' diff --git a/webf/android/src/main/java/com/openwebf/webf/Webf.java b/webf/android/src/main/java/com/openwebf/webf/WebF.java similarity index 86% rename from webf/android/src/main/java/com/openwebf/webf/Webf.java rename to webf/android/src/main/java/com/openwebf/webf/WebF.java index 824911ff8c..9c0fc17375 100644 --- a/webf/android/src/main/java/com/openwebf/webf/Webf.java +++ b/webf/android/src/main/java/com/openwebf/webf/WebF.java @@ -18,9 +18,9 @@ public class WebF { private FlutterEngine flutterEngine; private MethodChannel.MethodCallHandler handler; - private static Map sdkMap = new HashMap<>(); + private static Map sdkMap = new HashMap<>(); - public Kraken(FlutterEngine flutterEngine) { + public WebF(FlutterEngine flutterEngine) { if (flutterEngine != null) { this.flutterEngine = flutterEngine; sdkMap.put(flutterEngine, this); @@ -29,7 +29,7 @@ public Kraken(FlutterEngine flutterEngine) { } } - public static Kraken get(FlutterEngine engine) { + public static WebF get(FlutterEngine engine) { return sdkMap.get(engine); } @@ -74,7 +74,7 @@ public void invokeMethod(final String method, final Object arguments) { public void run() { if (flutterEngine != null) { PluginRegistry pluginRegistry = flutterEngine.getPlugins(); - KrakenPlugin krakenSDKPlugin = (KrakenPlugin) pluginRegistry.get(KrakenPlugin.class); + WebFPlugin krakenSDKPlugin = (WebFPlugin) pluginRegistry.get(WebFPlugin.class); if (krakenSDKPlugin != null && krakenSDKPlugin.channel != null) { krakenSDKPlugin.channel.invokeMethod(method, arguments); } @@ -86,7 +86,7 @@ public void run() { public void reload() { if (flutterEngine != null) { PluginRegistry pluginRegistry = flutterEngine.getPlugins(); - KrakenPlugin krakenSDKPlugin = (KrakenPlugin) pluginRegistry.get(KrakenPlugin.class); + WebFPlugin krakenSDKPlugin = (WebFPlugin) pluginRegistry.get(WebFPlugin.class); if (krakenSDKPlugin != null) { krakenSDKPlugin.reload(); } diff --git a/webf/android/src/main/java/com/openwebf/webf/WebfPlugin.java b/webf/android/src/main/java/com/openwebf/webf/WebFPlugin.java similarity index 89% rename from webf/android/src/main/java/com/openwebf/webf/WebfPlugin.java rename to webf/android/src/main/java/com/openwebf/webf/WebFPlugin.java index 70d8a5e33c..acddbfe3b6 100644 --- a/webf/android/src/main/java/com/openwebf/webf/WebfPlugin.java +++ b/webf/android/src/main/java/com/openwebf/webf/WebFPlugin.java @@ -1,6 +1,9 @@ -package com.openkraken.kraken; +package com.openwebf.webf; import android.content.Context; + +import com.openwebf.webf.WebF; + import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.plugin.common.MethodCall; @@ -12,7 +15,7 @@ /** * KrakenPlugin */ -public class KrakenPlugin implements FlutterPlugin, MethodCallHandler { +public class WebFPlugin implements FlutterPlugin, MethodCallHandler { /// The MethodChannel that will the communication between Flutter and native Android /// /// This local reference serves to register the plugin with the Flutter Engine and unregister it @@ -20,7 +23,7 @@ public class KrakenPlugin implements FlutterPlugin, MethodCallHandler { public MethodChannel channel; private FlutterEngine flutterEngine; private Context mContext; - private Kraken mKraken; + private WebF mKraken; // This static function is optional and equivalent to onAttachedToEngine. It supports the old // pre-Flutter-1.12 Android projects. You are encouraged to continue supporting @@ -33,7 +36,7 @@ public class KrakenPlugin implements FlutterPlugin, MethodCallHandler { // in the same class. public static void registerWith(Registrar registrar) { final MethodChannel channel = new MethodChannel(registrar.messenger(), "kraken"); - KrakenPlugin plugin = new KrakenPlugin(); + WebFPlugin plugin = new WebFPlugin(); plugin.mContext = registrar.context(); channel.setMethodCallHandler(plugin); } @@ -52,9 +55,9 @@ public void reload() { } } - Kraken getKraken() { + WebF getKraken() { if (mKraken == null) { - mKraken = Kraken.get(flutterEngine); + mKraken = WebF.get(flutterEngine); } return mKraken; } @@ -63,19 +66,19 @@ Kraken getKraken() { public void onMethodCall(MethodCall call, Result result) { switch (call.method) { case "getUrl": { - Kraken kraken = getKraken(); + WebF kraken = getKraken(); result.success(kraken == null ? "" : kraken.getUrl()); break; } case "getDynamicLibraryPath": { - Kraken kraken = getKraken(); + WebF kraken = getKraken(); result.success(kraken == null ? "" : kraken.getDynamicLibraryPath()); break; } case "invokeMethod": { - Kraken kraken = getKraken(); + WebF kraken = getKraken(); if (kraken != null) { String method = call.argument("method"); Object args = call.argument("args"); @@ -100,7 +103,7 @@ public void onMethodCall(MethodCall call, Result result) { @Override public void onDetachedFromEngine(FlutterPluginBinding binding) { channel.setMethodCallHandler(null); - Kraken kraken = Kraken.get(flutterEngine); + WebF kraken = WebF.get(flutterEngine); if (kraken == null) return; kraken.destroy(); flutterEngine = null; diff --git a/webf/example/android/.gitignore b/webf/example/android/.gitignore index 0a741cb43d..6f568019d3 100644 --- a/webf/example/android/.gitignore +++ b/webf/example/android/.gitignore @@ -9,3 +9,5 @@ GeneratedPluginRegistrant.java # Remember to never publicly share your keystore. # See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app key.properties +**/*.keystore +**/*.jks diff --git a/webf/example/android/app/build.gradle b/webf/example/android/app/build.gradle index c12637cd58..40b6b768fb 100644 --- a/webf/example/android/app/build.gradle +++ b/webf/example/android/app/build.gradle @@ -22,20 +22,22 @@ if (flutterVersionName == null) { } apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { - compileSdkVersion 29 + compileSdkVersion flutter.compileSdkVersion - lintOptions { - disable 'InvalidPackage' + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId "com.openkraken.kraken_example" - minSdkVersion 21 - targetSdkVersion 29 + applicationId "com.openwebf.webf_example" + minSdkVersion flutter.minSdkVersion + targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName } diff --git a/webf/example/android/app/src/main/AndroidManifest.xml b/webf/example/android/app/src/main/AndroidManifest.xml index 751cd648b9..051e85236a 100644 --- a/webf/example/android/app/src/main/AndroidManifest.xml +++ b/webf/example/android/app/src/main/AndroidManifest.xml @@ -5,13 +5,14 @@ In most cases you can leave this as-is, but you if you want to provide additional functionality it is fine to subclass or reimplement FlutterApplication and put your custom class here. --> - - + - RenderFlexLayout nextRenderLayoutBox = previousRenderLayoutBox.toFlexLayout(); } - } else if (display == CSSDisplay.block || - display == CSSDisplay.none || - display == CSSDisplay.inline || - display == CSSDisplay.inlineBlock) { - + display == CSSDisplay.none || + display == CSSDisplay.inline || + display == CSSDisplay.inlineBlock) { if (previousRenderLayoutBox == null) { if (isRepaintBoundary) { nextRenderLayoutBox = RenderRepaintBoundaryFlowLayout( @@ -438,7 +455,6 @@ abstract class Element // RenderSliverListLayout --> RenderFlowLayout nextRenderLayoutBox = previousRenderLayoutBox.toFlowLayout(); } - } else if (display == CSSDisplay.sliver) { if (previousRenderLayoutBox == null) { nextRenderLayoutBox = RenderSliverListLayout( @@ -448,7 +464,8 @@ abstract class Element ); } else if (previousRenderLayoutBox is RenderFlowLayout || previousRenderLayoutBox is RenderFlexLayout) { // RenderFlow/FlexLayout --> RenderSliverListLayout - nextRenderLayoutBox = previousRenderLayoutBox.toSliverLayout(RenderSliverElementChildManager(this), _handleScroll); + nextRenderLayoutBox = + previousRenderLayoutBox.toSliverLayout(RenderSliverElementChildManager(this), _handleScroll); } else if (previousRenderLayoutBox is RenderSliverListLayout) { nextRenderLayoutBox = previousRenderLayoutBox; } @@ -491,7 +508,6 @@ abstract class Element RenderBoxModel? renderBoxModel = this.renderBoxModel; if (renderBoxModel != null) { - // The node detach may affect the whitespace of the nextSibling and previousSibling text node so prev and next node require layout. renderBoxModel.markAdjacentRenderParagraphNeedsLayout(); @@ -532,8 +548,8 @@ abstract class Element if (!_shouldConsumeScrollTicker) { // Make sure scroll listener trigger most to 1 time each frame. - SchedulerBinding.instance!.addPostFrameCallback(_consumeScrollTicker); - SchedulerBinding.instance!.scheduleFrame(); + SchedulerBinding.instance.addPostFrameCallback(_consumeScrollTicker); + SchedulerBinding.instance.scheduleFrame(); } _shouldConsumeScrollTicker = true; } @@ -622,7 +638,7 @@ abstract class Element while (child != null) { final ContainerParentDataMixin? childParentData = - child.parentData as ContainerParentDataMixin?; + child.parentData as ContainerParentDataMixin?; if (child is! RenderLayoutBox) { child = childParentData!.nextSibling; continue; @@ -641,9 +657,8 @@ abstract class Element // No need to detach and reattach renderBoxMode when its position // changes between static and relative. - if (!(oldPosition == CSSPositionType.static && currentPosition == CSSPositionType.relative) - && !(oldPosition == CSSPositionType.relative && currentPosition == CSSPositionType.static) - ) { + if (!(oldPosition == CSSPositionType.static && currentPosition == CSSPositionType.relative) && + !(oldPosition == CSSPositionType.relative && currentPosition == CSSPositionType.static)) { RenderBoxModel _renderBoxModel = renderBoxModel!; // Remove fixed children before convert to non repaint boundary renderObject if (currentPosition != CSSPositionType.fixed) { @@ -662,7 +677,8 @@ abstract class Element // Original parent renderBox. RenderBox parentRenderBox = parentNode!.renderer!; // Attach renderBoxModel to its containing block. - renderBoxModel!.attachToContainingBlock(containingBlockRenderBox, parent: parentRenderBox, after: previousSibling); + renderBoxModel! + .attachToContainingBlock(containingBlockRenderBox, parent: parentRenderBox, after: previousSibling); // Add fixed children after convert to repaint boundary renderObject. if (currentPosition == CSSPositionType.fixed) { @@ -678,8 +694,8 @@ abstract class Element child.addToContainingBlock(); }); - // Need to change the containing block of direct position absolute children from this element - // to its upper parent when element's position is changed from relative to static. + // Need to change the containing block of direct position absolute children from this element + // to its upper parent when element's position is changed from relative to static. } else if (currentPosition == CSSPositionType.static) { List directPositionAbsoluteChildren = findDirectPositionAbsoluteChildren(); directPositionAbsoluteChildren.forEach((Element child) { @@ -758,7 +774,7 @@ abstract class Element if (renderer != null) { // If element attach WidgetElement, render object should be attach to render tree when mount. - if (parent.renderObjectManagerType == RenderObjectManagerType.KRAKEN_NODE) { + if (parent.renderObjectManagerType == RenderObjectManagerType.WEBF_NODE) { RenderBoxModel.attachRenderBox(parent.renderer!, renderer!, after: after); } @@ -771,7 +787,7 @@ abstract class Element /// Unmount [renderBoxModel]. @override - void unmountRenderObject({ bool deep = true, bool keepFixedAlive = false, bool dispose = true }) { + void unmountRenderObject({bool deep = true, bool keepFixedAlive = false, bool dispose = true}) { // Ignore the fixed element to unmount render object. // It's useful for sliver manager to unmount child render object, but excluding fixed elements. if (keepFixedAlive && renderStyle.position == CSSPositionType.fixed) { @@ -827,7 +843,9 @@ abstract class Element RenderLayoutBox? renderLayoutBox = _renderLayoutBox; if (isRendererAttached) { // Only append child renderer when which is not attached. - if (!child.isRendererAttached && renderLayoutBox != null && renderObjectManagerType == RenderObjectManagerType.KRAKEN_NODE) { + if (!child.isRendererAttached && + renderLayoutBox != null && + renderObjectManagerType == RenderObjectManagerType.WEBF_NODE) { RenderBox? after; RenderLayoutBox? scrollingContentBox = renderLayoutBox.renderScrollingContent; if (scrollingContentBox != null) { @@ -920,7 +938,7 @@ abstract class Element RenderBox? containingBlockRenderBox; CSSPositionType positionType = renderStyle.position; - switch(positionType) { + switch (positionType) { case CSSPositionType.relative: case CSSPositionType.static: case CSSPositionType.sticky: @@ -1000,7 +1018,7 @@ abstract class Element // Attach renderBoxModel to parent if change from `display: none` to other values. if (!isRendererAttached && parentElement != null && parentElement!.isRendererAttached) { // If element attach WidgetElement, render object should be attach to render tree when mount. - if (parentElement!.renderObjectManagerType == RenderObjectManagerType.KRAKEN_NODE) { + if (parentElement!.renderObjectManagerType == RenderObjectManagerType.WEBF_NODE) { RenderBoxModel _renderBoxModel = renderBoxModel!; // Find the renderBox of its containing block. RenderBox? containingBlockRenderBox = getContainingBlockRenderBox(); @@ -1029,7 +1047,7 @@ abstract class Element switch (name) { case DISPLAY: renderStyle.display = value; - _updateRenderBoxModelWithDisplay(); + _updateRenderBoxModelWithDisplay(); break; case Z_INDEX: renderStyle.zIndex = value; @@ -1327,7 +1345,7 @@ abstract class Element break; case SLIVER_DIRECTION: renderStyle.sliverDirection = value; - break; + break; } } @@ -1493,15 +1511,8 @@ abstract class Element if (sizedBox.hasSize) { Offset offset = _getOffset(sizedBox, ancestor: ownerDocument.documentElement); Size size = sizedBox.size; - boundingClientRect = BoundingClientRect( - offset.dx, - offset.dy, - size.width, - size.height, - offset.dy, - offset.dx + size.width, - offset.dy + size.height, - offset.dx); + boundingClientRect = BoundingClientRect(offset.dx, offset.dy, size.width, size.height, offset.dy, + offset.dx + size.width, offset.dy + size.height, offset.dx); } } @@ -1540,10 +1551,10 @@ abstract class Element Element? get offsetParent { // Returns null in the following cases. // https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetParent - if (renderStyle.display == CSSDisplay.none - || renderStyle.position == CSSPositionType.fixed - || this is BodyElement - || this == ownerDocument.documentElement) { + if (renderStyle.display == CSSDisplay.none || + renderStyle.position == CSSPositionType.fixed || + this is BodyElement || + this == ownerDocument.documentElement) { return null; } @@ -1560,7 +1571,7 @@ abstract class Element } // Get the offset of current element relative to specified ancestor element. - Offset _getOffset(RenderBoxModel renderBox, { Element? ancestor }) { + Offset _getOffset(RenderBoxModel renderBox, {Element? ancestor}) { // Need to flush layout to get correct size. flushLayout(); @@ -1591,12 +1602,12 @@ abstract class Element // TODO } - Future toBlob({ double? devicePixelRatio }) { + Future toBlob({double? devicePixelRatio}) { flushLayout(); forceToRepaintBoundary = true; Completer completer = Completer(); - SchedulerBinding.instance!.addPostFrameCallback((_) async { + SchedulerBinding.instance.addPostFrameCallback((_) async { Uint8List captured; RenderBoxModel _renderBoxModel = renderBoxModel!; @@ -1614,7 +1625,7 @@ abstract class Element // May be disposed before this callback. flushLayout(); }); - SchedulerBinding.instance!.scheduleFrame(); + SchedulerBinding.instance.scheduleFrame(); return completer.future; } @@ -1631,6 +1642,11 @@ abstract class Element } } + @override + String toString() { + return '$tagName Element($hashCode)'; + } + // Create a new RenderLayoutBox for the scrolling content. RenderLayoutBox createScrollingContentLayout() { // FIXME: Create an empty renderStyle for do not share renderStyle with element. diff --git a/webf/lib/src/dom/element_inspector.dart b/webf/lib/src/dom/element_inspector.dart index 0def44a470..a16a96c249 100644 --- a/webf/lib/src/dom/element_inspector.dart +++ b/webf/lib/src/dom/element_inspector.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ // Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be @@ -467,12 +468,12 @@ mixin ElementInspectorService { selection.current = object; developer.inspect(selection.current); if (selectionChangedCallback != null) { - if (SchedulerBinding.instance?.schedulerPhase == SchedulerPhase.idle) { + if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.idle) { selectionChangedCallback!(); } else { // It isn't safe to trigger the selection change callback if we are in // the middle of rendering the frame. - SchedulerBinding.instance!.scheduleTask( + SchedulerBinding.instance.scheduleTask( selectionChangedCallback!, Priority.touch, ); @@ -484,9 +485,9 @@ mixin ElementInspectorService { } Map? _nodeToJson( - DiagnosticsNode? node, - InspectorSerializationDelegate delegate, - ) { + DiagnosticsNode? node, + InspectorSerializationDelegate delegate, + ) { return node?.toJsonMap(delegate); } @@ -631,7 +632,8 @@ mixin ElementInspectorService { } Map? _getRootRenderObject(String groupName) { - return _nodeToJson(RendererBinding.instance?.renderView.toDiagnosticsNode(), InspectorSerializationDelegate(groupName: groupName, service: this)); + return _nodeToJson(RendererBinding.instance.renderView.toDiagnosticsNode(), + InspectorSerializationDelegate(groupName: groupName, service: this)); } /// Returns a JSON representation of the subtree rooted at the @@ -689,7 +691,8 @@ mixin ElementInspectorService { Map? _getSelectedRenderObject(String? previousSelectionId, String groupName) { final DiagnosticsNode? previousSelection = toObject(previousSelectionId) as DiagnosticsNode?; final RenderObject? current = selection.current; - return _nodeToJson(current == previousSelection?.value ? previousSelection : current?.toDiagnosticsNode(), InspectorSerializationDelegate(groupName: groupName, service: this)); + return _nodeToJson(current == previousSelection?.value ? previousSelection : current?.toDiagnosticsNode(), + InspectorSerializationDelegate(groupName: groupName, service: this)); } /// This method is called by [WidgetBinding.performReassemble] to flush caches diff --git a/webf/lib/src/dom/element_registry.dart b/webf/lib/src/dom/element_registry.dart index 36d43bf620..e59645c551 100644 --- a/webf/lib/src/dom/element_registry.dart +++ b/webf/lib/src/dom/element_registry.dart @@ -1,8 +1,9 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -import 'package:kraken/dom.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/foundation.dart'; typedef ElementCreator = Element Function(BindingContext? context); @@ -19,7 +20,7 @@ class _UnknownElement extends Element { _UnknownElement([BindingContext? context]) : super(context); } -Element createElement(String name, [BindingContext? context]){ +Element createElement(String name, [BindingContext? context]) { ElementCreator? creator = _elementRegistry[name]; if (creator == null) { print('Unexpected element "$name"'); @@ -114,4 +115,3 @@ void defineBuiltInElements() { defineElement(IMAGE, (context) => ImageElement(context)); defineElement(CANVAS, (context) => CanvasElement(context)); } - diff --git a/webf/lib/src/dom/elements/a.dart b/webf/lib/src/dom/elements/a.dart index 6158318c07..70d4d1ecdd 100644 --- a/webf/lib/src/dom/elements/a.dart +++ b/webf/lib/src/dom/elements/a.dart @@ -1,17 +1,17 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -import 'package:kraken/dom.dart'; -import 'package:kraken/kraken.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/webf.dart'; const String ANCHOR = 'A'; const String _TARGET_SELF = 'self'; class AnchorElement extends Element { - AnchorElement([BindingContext? context]) - : super(context) { - addEventListener(EVENT_CLICK, _handleClick); - } + AnchorElement([BindingContext? context]) : super(context) { + addEventListener(EVENT_CLICK, _handleClick); + } void _handleClick(Event event) { String? href = attributes['href']; @@ -19,58 +19,93 @@ class AnchorElement extends Element { String baseUrl = ownerDocument.controller.url; Uri baseUri = Uri.parse(baseUrl); Uri resolvedUri = ownerDocument.controller.uriParser!.resolve(baseUri, Uri.parse(href)); - ownerDocument.controller.view.handleNavigationAction( - baseUrl, resolvedUri.toString(), _getNavigationType(resolvedUri.scheme)); + ownerDocument.controller.view + .handleNavigationAction(baseUrl, resolvedUri.toString(), _getNavigationType(resolvedUri.scheme)); } } - KrakenNavigationType _getNavigationType(String scheme) { + WebFNavigationType _getNavigationType(String scheme) { switch (scheme.toLowerCase()) { case 'http': case 'https': case 'file': if (target.isEmpty || target == _TARGET_SELF) { - return KrakenNavigationType.reload; + return WebFNavigationType.reload; } } - return KrakenNavigationType.navigate; + return WebFNavigationType.navigate; } // Bindings. @override getBindingProperty(String key) { switch (key) { - case 'href': return href; - case 'target': return target; - case 'rel': return rel; - case 'type': return type; - case 'protocol': return protocol; - case 'host': return host; - case 'hostname': return hostname; - case 'port': return port; - case 'pathname': return pathname; - case 'search': return search; - case 'hash': return hash; - default: return super.getBindingProperty(key); + case 'href': + return href; + case 'target': + return target; + case 'rel': + return rel; + case 'type': + return type; + case 'protocol': + return protocol; + case 'host': + return host; + case 'hostname': + return hostname; + case 'port': + return port; + case 'pathname': + return pathname; + case 'search': + return search; + case 'hash': + return hash; + default: + return super.getBindingProperty(key); } } @override void setBindingProperty(String key, value) { switch (key) { - case 'href': href = castToType(value); break; - case 'target': target = castToType(value); break; - case 'rel': rel = castToType(value); break; - case 'type': type = castToType(value); break; - case 'protocol': protocol = castToType(value); break; - case 'host': host = castToType(value); break; - case 'hostname': hostname = castToType(value); break; - case 'port': port = castToType(value); break; - case 'pathname': pathname = castToType(value); break; - case 'search': search = castToType(value); break; - case 'hash': hash = castToType(value); break; - default: super.setBindingProperty(key, value); + case 'href': + href = castToType(value); + break; + case 'target': + target = castToType(value); + break; + case 'rel': + rel = castToType(value); + break; + case 'type': + type = castToType(value); + break; + case 'protocol': + protocol = castToType(value); + break; + case 'host': + host = castToType(value); + break; + case 'hostname': + hostname = castToType(value); + break; + case 'port': + port = castToType(value); + break; + case 'pathname': + pathname = castToType(value); + break; + case 'search': + search = castToType(value); + break; + case 'hash': + hash = castToType(value); + break; + default: + super.setBindingProperty(key, value); } } @@ -79,17 +114,39 @@ class AnchorElement extends Element { super.setAttribute(qualifiedName, value); // Reflect setAttribute to properties. switch (qualifiedName) { - case 'href': href = attributeToProperty(value); break; - case 'target': target = attributeToProperty(value); break; - case 'rel': rel = attributeToProperty(value); break; - case 'type': type = attributeToProperty(value); break; - case 'protocol': protocol = attributeToProperty(value); break; - case 'host': host = attributeToProperty(value); break; - case 'hostname': hostname = attributeToProperty(value); break; - case 'port': port = attributeToProperty(value); break; - case 'pathname': pathname = attributeToProperty(value); break; - case 'search': search = attributeToProperty(value); break; - case 'hash': hash = attributeToProperty(value); break; + case 'href': + href = attributeToProperty(value); + break; + case 'target': + target = attributeToProperty(value); + break; + case 'rel': + rel = attributeToProperty(value); + break; + case 'type': + type = attributeToProperty(value); + break; + case 'protocol': + protocol = attributeToProperty(value); + break; + case 'host': + host = attributeToProperty(value); + break; + case 'hostname': + hostname = attributeToProperty(value); + break; + case 'port': + port = attributeToProperty(value); + break; + case 'pathname': + pathname = attributeToProperty(value); + break; + case 'search': + search = attributeToProperty(value); + break; + case 'hash': + hash = attributeToProperty(value); + break; } } @@ -205,6 +262,7 @@ class AnchorElement extends Element { } return _DOMString(search); } + set search(String value) { if (_resolvedHyperlink == null) return; // Remove starting `?`. diff --git a/webf/lib/src/dom/elements/body.dart b/webf/lib/src/dom/elements/body.dart index b0e126873e..cff91644a4 100644 --- a/webf/lib/src/dom/elements/body.dart +++ b/webf/lib/src/dom/elements/body.dart @@ -1,9 +1,10 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/foundation.dart'; const String BODY = 'BODY'; @@ -12,8 +13,7 @@ const Map _defaultStyle = { }; class BodyElement extends Element { - BodyElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + BodyElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); @override void addEventListener(String eventType, EventHandler eventHandler) { diff --git a/webf/lib/src/dom/elements/canvas/canvas.dart b/webf/lib/src/dom/elements/canvas/canvas.dart index f84ef7d260..c6d86fc8b8 100644 --- a/webf/lib/src/dom/elements/canvas/canvas.dart +++ b/webf/lib/src/dom/elements/canvas/canvas.dart @@ -1,13 +1,14 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/rendering.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/rendering.dart'; +import 'package:webf/foundation.dart'; const String CANVAS = 'CANVAS'; const int _ELEMENT_DEFAULT_WIDTH_IN_PIXEL = 300; @@ -31,6 +32,7 @@ class RenderCanvasPaint extends RenderCustomPaint { class CanvasElement extends Element { final ChangeNotifier repaintNotifier = ChangeNotifier(); + /// The painter that paints before the children. late CanvasPainter painter; @@ -54,26 +56,36 @@ class CanvasElement extends Element { @override getBindingProperty(String key) { switch (key) { - case 'width': return width; - case 'height': return height; - default: return super.getBindingProperty(key); + case 'width': + return width; + case 'height': + return height; + default: + return super.getBindingProperty(key); } } @override void setBindingProperty(String key, value) { switch (key) { - case 'width': width = castToType(value); break; - case 'height': height = castToType(value); break; - default: super.setBindingProperty(key, value); + case 'width': + width = castToType(value); + break; + case 'height': + height = castToType(value); + break; + default: + super.setBindingProperty(key, value); } } @override invokeBindingMethod(String method, List args) { switch (method) { - case 'getContext': return getContext(castToType(args[0])).toNative(); - default: return super.invokeBindingMethod(method, args); + case 'getContext': + return getContext(castToType(args[0])).toNative(); + default: + return super.invokeBindingMethod(method, args); } } @@ -97,7 +109,7 @@ class CanvasElement extends Element { renderCustomPaint = null; } - CanvasRenderingContext2D getContext(String type, { options }) { + CanvasRenderingContext2D getContext(String type, {options}) { switch (type) { case '2d': if (painter.context == null) { @@ -188,6 +200,7 @@ class CanvasElement extends Element { return _ELEMENT_DEFAULT_WIDTH_IN_PIXEL; } } + set width(int value) { _setDimensions(value, null); } @@ -201,6 +214,7 @@ class CanvasElement extends Element { return _ELEMENT_DEFAULT_HEIGHT_IN_PIXEL; } } + set height(int value) { _setDimensions(null, value); } @@ -241,8 +255,12 @@ class CanvasElement extends Element { void setAttribute(String qualifiedName, String value) { super.setAttribute(qualifiedName, value); switch (qualifiedName) { - case 'width': width = attributeToProperty(value); break; - case 'height': height = attributeToProperty(value); break; + case 'width': + width = attributeToProperty(value); + break; + case 'height': + height = attributeToProperty(value); + break; } } diff --git a/webf/lib/src/dom/elements/canvas/canvas_context.dart b/webf/lib/src/dom/elements/canvas/canvas_context.dart index 99eae75ece..d37d99c581 100644 --- a/webf/lib/src/dom/elements/canvas/canvas_context.dart +++ b/webf/lib/src/dom/elements/canvas/canvas_context.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:typed_data'; import 'dart:ui'; @@ -110,7 +111,8 @@ abstract class CanvasImageData { ImageData getImageData(double sx, double sy, double sw, double sh); - void putImageData(ImageData imagedata, double dx, double dy, {double dirtyX, double dirtyY, double dirtyWidth, double dirtyHeight}); + void putImageData(ImageData imagedata, double dx, double dy, + {double dirtyX, double dirtyY, double dirtyWidth, double dirtyHeight}); } // ignore: one_member_abstracts diff --git a/webf/lib/src/dom/elements/canvas/canvas_context_2d.dart b/webf/lib/src/dom/elements/canvas/canvas_context_2d.dart index 340f135aad..046acd0fc6 100644 --- a/webf/lib/src/dom/elements/canvas/canvas_context_2d.dart +++ b/webf/lib/src/dom/elements/canvas/canvas_context_2d.dart @@ -1,17 +1,18 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:core'; -import 'dart:ffi'; import 'dart:typed_data'; import 'dart:ui'; +import 'dart:ffi' as ffi; import 'package:ffi/ffi.dart'; import 'package:flutter/painting.dart'; -import 'package:kraken/bridge.dart'; -import 'package:kraken/foundation.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; +import 'package:webf/bridge.dart'; +import 'package:webf/foundation.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; import 'package:vector_math/vector_math_64.dart'; import 'canvas_context.dart'; @@ -43,10 +44,11 @@ class CanvasRenderingContext2DSettings { typedef CanvasAction = void Function(Canvas, Size); class CanvasRenderingContext2D extends BindingObject { - CanvasRenderingContext2D(this.canvas) : _pointer = malloc.allocate( - sizeOf()), super(); + CanvasRenderingContext2D(this.canvas) + : _pointer = malloc.allocate(ffi.sizeOf()), + super(); - final Pointer _pointer; + final ffi.Pointer _pointer; @override get pointer => _pointer; @@ -54,7 +56,7 @@ class CanvasRenderingContext2D extends BindingObject { @override get contextId => canvas.contextId; - Pointer toNative() { + ffi.Pointer toNative() { return pointer; } @@ -62,86 +64,73 @@ class CanvasRenderingContext2D extends BindingObject { invokeBindingMethod(String method, List args) { // @NOTE: Bridge not guarantee that input type number is double. switch (method) { - case 'arc': return arc( - castToType(args[0]).toDouble(), - castToType(args[1]).toDouble(), - castToType(args[2]).toDouble(), - castToType(args[3]).toDouble(), - castToType(args[4]).toDouble(), - anticlockwise : args[5] == 1 ? true : false); - case 'arcTo': return arcTo( - castToType(args[0]).toDouble(), - castToType(args[1]).toDouble(), - castToType(args[2]).toDouble(), - castToType(args[3]).toDouble(), - castToType(args[4]).toDouble() - ); - case 'fillRect': return fillRect( - castToType(args[0]).toDouble(), - castToType(args[1]).toDouble(), - castToType(args[2]).toDouble(), - castToType(args[3]).toDouble() - ); - case 'clearRect': return clearRect( - castToType(args[0]).toDouble(), - castToType(args[1]).toDouble(), - castToType(args[2]).toDouble(), - castToType(args[3]).toDouble()); - case 'strokeRect': return strokeRect( - castToType(args[0]).toDouble(), - castToType(args[1]).toDouble(), - castToType(args[2]).toDouble(), - castToType(args[3]).toDouble()); + case 'arc': + return arc( + castToType(args[0]).toDouble(), + castToType(args[1]).toDouble(), + castToType(args[2]).toDouble(), + castToType(args[3]).toDouble(), + castToType(args[4]).toDouble(), + anticlockwise: args[5] == 1 ? true : false); + case 'arcTo': + return arcTo( + castToType(args[0]).toDouble(), + castToType(args[1]).toDouble(), + castToType(args[2]).toDouble(), + castToType(args[3]).toDouble(), + castToType(args[4]).toDouble()); + case 'fillRect': + return fillRect(castToType(args[0]).toDouble(), castToType(args[1]).toDouble(), + castToType(args[2]).toDouble(), castToType(args[3]).toDouble()); + case 'clearRect': + return clearRect(castToType(args[0]).toDouble(), castToType(args[1]).toDouble(), + castToType(args[2]).toDouble(), castToType(args[3]).toDouble()); + case 'strokeRect': + return strokeRect(castToType(args[0]).toDouble(), castToType(args[1]).toDouble(), + castToType(args[2]).toDouble(), castToType(args[3]).toDouble()); case 'fillText': double maxWidth = castToType(args[3]).toDouble(); if (!maxWidth.isNaN) { return fillText( - castToType(args[0]), - castToType(args[1]).toDouble(), - castToType(args[2]).toDouble(), + castToType(args[0]), castToType(args[1]).toDouble(), castToType(args[2]).toDouble(), maxWidth: maxWidth); } else { - return fillText(castToType(args[0]), - castToType(args[1]).toDouble(), - castToType(args[2]).toDouble()); + return fillText( + castToType(args[0]), castToType(args[1]).toDouble(), castToType(args[2]).toDouble()); } case 'strokeText': double maxWidth = castToType(args[3]).toDouble(); - if (!maxWidth.isNaN) { - return strokeText(castToType(args[0]), + if (!maxWidth.isNaN) { + return strokeText( + castToType(args[0]), castToType(args[1]).toDouble(), castToType(args[2]).toDouble(), + maxWidth: maxWidth); + } else { + return strokeText( + castToType(args[0]), castToType(args[1]).toDouble(), castToType(args[2]).toDouble()); + } + case 'save': + return save(); + case 'restore': + return restore(); + case 'beginPath': + return beginPath(); + case 'bezierCurveTo': + return bezierCurveTo( + castToType(args[0]).toDouble(), castToType(args[1]).toDouble(), castToType(args[2]).toDouble(), - maxWidth: maxWidth); - } else { - return strokeText(castToType(args[0]), - castToType(args[1]).toDouble(), - castToType(args[2]).toDouble()); - } - case 'save': return save(); - case 'restore': return restore(); - case 'beginPath': return beginPath(); - case 'bezierCurveTo': return bezierCurveTo( - castToType(args[0]).toDouble(), - castToType(args[1]).toDouble(), - castToType(args[2]).toDouble(), - castToType(args[3]).toDouble(), - castToType(args[4]).toDouble(), - castToType(args[5]).toDouble()); + castToType(args[3]).toDouble(), + castToType(args[4]).toDouble(), + castToType(args[5]).toDouble()); case 'clip': PathFillType fillType = castToType(args[0]) == EVENODD ? PathFillType.evenOdd : PathFillType.nonZero; return clip(fillType); - case 'closePath': return closePath(); + case 'closePath': + return closePath(); case 'drawImage': BindingObject imageElement = BindingBridge.getBindingObject(args[0]); if (imageElement is ImageElement) { - double sx = 0.0, - sy = 0.0, - sWidth = 0.0, - sHeight = 0.0, - dx = 0.0, - dy = 0.0, - dWidth = 0.0, - dHeight = 0.0; + double sx = 0.0, sy = 0.0, sWidth = 0.0, sHeight = 0.0, dx = 0.0, dy = 0.0, dWidth = 0.0, dHeight = 0.0; if (args.length == 3) { dx = castToType(args[1]).toDouble(); @@ -162,17 +151,7 @@ class CanvasRenderingContext2D extends BindingObject { dHeight = castToType(args[8]).toDouble(); } - return drawImage( - args.length, - imageElement.image, - sx, - sy, - sWidth, - sHeight, - dx, - dy, - dWidth, - dHeight); + return drawImage(args.length, imageElement.image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight); } break; case 'ellipse': @@ -184,54 +163,50 @@ class CanvasRenderingContext2D extends BindingObject { castToType(args[4]).toDouble(), castToType(args[5]).toDouble(), castToType(args[6]).toDouble(), - anticlockwise : args[7] == 1 ? true : false); + anticlockwise: args[7] == 1 ? true : false); case 'fill': - PathFillType fillType = args[0] == EVENODD ? PathFillType.evenOdd : PathFillType.nonZero; - return fill(fillType); - case 'lineTo': return lineTo( - castToType(args[0]).toDouble(), - castToType(args[1]).toDouble()); - case 'moveTo': return moveTo( - castToType(args[0]).toDouble(), - castToType(args[1]).toDouble()); - case 'quadraticCurveTo': return quadraticCurveTo( - castToType(args[0]).toDouble(), - castToType(args[1]).toDouble(), - castToType(args[2]).toDouble(), - castToType(args[3]).toDouble()); - case 'rect': return rect( - castToType(args[0]).toDouble(), - castToType(args[1]).toDouble(), - castToType(args[2]).toDouble(), - castToType(args[3]).toDouble()); - case 'rotate': return rotate(castToType(args[0]).toDouble()); - case 'resetTransform': return resetTransform(); - case 'scale': return scale( - castToType(args[0]).toDouble(), - castToType(args[1]).toDouble() - ); - case 'stroke': return stroke(); - case 'setTransform': return setTransform( - castToType(args[0]).toDouble(), - castToType(args[1]).toDouble(), - castToType(args[2]).toDouble(), - castToType(args[3]).toDouble(), - castToType(args[4]).toDouble(), - castToType(args[5]).toDouble() - ); - case 'transform': return transform( - castToType(args[0]).toDouble(), - castToType(args[1]).toDouble(), - castToType(args[2]).toDouble(), - castToType(args[3]).toDouble(), - castToType(args[4]).toDouble(), - castToType(args[5]).toDouble() - ); - case 'translate': return translate( - castToType(args[0]).toDouble(), - castToType(args[1]).toDouble()); - case 'reset': return reset(); - default: return super.invokeBindingMethod(method, args); + PathFillType fillType = args[0] == EVENODD ? PathFillType.evenOdd : PathFillType.nonZero; + return fill(fillType); + case 'lineTo': + return lineTo(castToType(args[0]).toDouble(), castToType(args[1]).toDouble()); + case 'moveTo': + return moveTo(castToType(args[0]).toDouble(), castToType(args[1]).toDouble()); + case 'quadraticCurveTo': + return quadraticCurveTo(castToType(args[0]).toDouble(), castToType(args[1]).toDouble(), + castToType(args[2]).toDouble(), castToType(args[3]).toDouble()); + case 'rect': + return rect(castToType(args[0]).toDouble(), castToType(args[1]).toDouble(), + castToType(args[2]).toDouble(), castToType(args[3]).toDouble()); + case 'rotate': + return rotate(castToType(args[0]).toDouble()); + case 'resetTransform': + return resetTransform(); + case 'scale': + return scale(castToType(args[0]).toDouble(), castToType(args[1]).toDouble()); + case 'stroke': + return stroke(); + case 'setTransform': + return setTransform( + castToType(args[0]).toDouble(), + castToType(args[1]).toDouble(), + castToType(args[2]).toDouble(), + castToType(args[3]).toDouble(), + castToType(args[4]).toDouble(), + castToType(args[5]).toDouble()); + case 'transform': + return transform( + castToType(args[0]).toDouble(), + castToType(args[1]).toDouble(), + castToType(args[2]).toDouble(), + castToType(args[3]).toDouble(), + castToType(args[4]).toDouble(), + castToType(args[5]).toDouble()); + case 'translate': + return translate(castToType(args[0]).toDouble(), castToType(args[1]).toDouble()); + case 'reset': + return reset(); + default: + return super.invokeBindingMethod(method, args); } } @@ -242,39 +217,70 @@ class CanvasRenderingContext2D extends BindingObject { Color? color = CSSColor.parseColor(castToType(value)); if (color != null) fillStyle = color; break; - case 'direction': direction = parseDirection(castToType(value)); break; - case 'font': font = castToType(value); break; + case 'direction': + direction = parseDirection(castToType(value)); + break; + case 'font': + font = castToType(value); + break; case 'strokeStyle': Color? color = CSSColor.parseColor(castToType(value)); if (color != null) strokeStyle = color; break; - case 'lineCap': lineCap = parseLineCap(castToType(value)); break; + case 'lineCap': + lineCap = parseLineCap(castToType(value)); + break; // @TODO: Binding should guarantee that input value is determined type, like double or int. - case 'lineDashOffset': lineDashOffset = castToType(value).toDouble(); break; - case 'lineJoin': lineJoin = parseLineJoin(castToType(value)); break; - case 'lineWidth': lineWidth = castToType(value).toDouble(); break; - case 'miterLimit': miterLimit = castToType(value).toDouble(); break; - case 'textAlign': textAlign = parseTextAlign(castToType(value)); break; - case 'textBaseline': textBaseline = parseTextBaseline(castToType(value)); break; - default: super.setBindingProperty(key, value); + case 'lineDashOffset': + lineDashOffset = castToType(value).toDouble(); + break; + case 'lineJoin': + lineJoin = parseLineJoin(castToType(value)); + break; + case 'lineWidth': + lineWidth = castToType(value).toDouble(); + break; + case 'miterLimit': + miterLimit = castToType(value).toDouble(); + break; + case 'textAlign': + textAlign = parseTextAlign(castToType(value)); + break; + case 'textBaseline': + textBaseline = parseTextBaseline(castToType(value)); + break; + default: + super.setBindingProperty(key, value); } } @override getBindingProperty(String key) { switch (key) { - case 'fillStyle': return CSSColor.convertToHex(fillStyle); - case 'direction': return _textDirectionInString; - case 'font': return font; - case 'strokeStyle': return CSSColor.convertToHex(strokeStyle); - case 'lineCap': return lineCap; - case 'lineDashOffset': return lineDashOffset; - case 'lineJoin': return lineJoin; - case 'lineWidth': return lineWidth; - case 'miterLimit': return miterLimit; - case 'textAlign': return textAlign.toString(); - case 'textBaseline': return textBaseline.toString(); - default: return super.getBindingProperty(key); + case 'fillStyle': + return CSSColor.convertToHex(fillStyle); + case 'direction': + return _textDirectionInString; + case 'font': + return font; + case 'strokeStyle': + return CSSColor.convertToHex(strokeStyle); + case 'lineCap': + return lineCap; + case 'lineDashOffset': + return lineDashOffset; + case 'lineJoin': + return lineJoin; + case 'lineWidth': + return lineWidth; + case 'miterLimit': + return miterLimit; + case 'textAlign': + return textAlign.toString(); + case 'textBaseline': + return textBaseline.toString(); + default: + return super.getBindingProperty(key); } } @@ -303,7 +309,8 @@ class CanvasRenderingContext2D extends BindingObject { void addAction(CanvasAction action) { _actions.add(action); // Must trigger repaint after action - canvas.repaintNotifier.notifyListeners(); // ignore: invalid_use_of_visible_for_testing_member, invalid_use_of_protected_member + canvas.repaintNotifier + .notifyListeners(); // ignore: invalid_use_of_visible_for_testing_member, invalid_use_of_protected_member } // Perform canvas drawing. @@ -351,10 +358,11 @@ class CanvasRenderingContext2D extends BindingObject { _textAlign = value; }); } + TextAlign get textAlign => _textAlign; static CanvasTextBaseline? parseTextBaseline(String value) { - switch(value) { + switch (value) { case TOP: return CanvasTextBaseline.top; case HANGING: @@ -391,6 +399,7 @@ class CanvasRenderingContext2D extends BindingObject { } return null; } + // FIXME: The text direction is inherited from the element or the Document as appropriate. TextDirection _direction = TextDirection.ltr; // (default: "inherit") set direction(TextDirection? value) { @@ -399,11 +408,14 @@ class CanvasRenderingContext2D extends BindingObject { _direction = value; }); } + TextDirection get direction => _direction; String get _textDirectionInString { switch (_direction) { - case TextDirection.ltr: return 'ltr'; - case TextDirection.rtl: return 'rtl'; + case TextDirection.ltr: + return 'ltr'; + case TextDirection.rtl: + return 'rtl'; } } @@ -430,6 +442,7 @@ class CanvasRenderingContext2D extends BindingObject { } return true; } + String _font = _DEFAULT_FONT; // (default 10px sans-serif) set font(String value) { addAction((Canvas canvas, Size size) { @@ -439,6 +452,7 @@ class CanvasRenderingContext2D extends BindingObject { } }); } + String get font => _font; final List _states = []; @@ -465,7 +479,18 @@ class CanvasRenderingContext2D extends BindingObject { // pop state stack and restore state void save() { addAction((Canvas canvas, Size size) { - _states.add([strokeStyle, fillStyle, lineWidth, lineCap, lineJoin, lineDashOffset, miterLimit, font, textAlign, direction]); + _states.add([ + strokeStyle, + fillStyle, + lineWidth, + lineCap, + lineJoin, + lineDashOffset, + miterLimit, + font, + textAlign, + direction + ]); canvas.save(); }); } @@ -540,7 +565,8 @@ class CanvasRenderingContext2D extends BindingObject { }); } - void drawImage(int argumentCount, Image? img, double sx, double sy, double sWidth, double sHeight, double dx, double dy, double dWidth, double dHeight) { + void drawImage(int argumentCount, Image? img, double sx, double sy, double sWidth, double sHeight, double dx, + double dy, double dWidth, double dHeight) { if (img == null) return; addAction((Canvas canvas, Size size) { @@ -556,15 +582,14 @@ class CanvasRenderingContext2D extends BindingObject { sHeight = img.height.toDouble(); } - canvas.drawImageRect(img, - Rect.fromLTWH(sx, sy, sWidth, sHeight), - Rect.fromLTWH(dx, dy, dWidth, dHeight), - Paint()); + canvas.drawImageRect( + img, Rect.fromLTWH(sx, sy, sWidth, sHeight), Rect.fromLTWH(dx, dy, dWidth, dHeight), Paint()); } }); } - void ellipse(double x, double y, double radiusX, double radiusY, double rotation, double startAngle, double endAngle, {bool anticlockwise = false}) { + void ellipse(double x, double y, double radiusX, double radiusY, double rotation, double startAngle, double endAngle, + {bool anticlockwise = false}) { addAction((Canvas canvas, Size size) { path2d.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise: anticlockwise); }); @@ -596,7 +621,7 @@ class CanvasRenderingContext2D extends BindingObject { // butt, round, square static StrokeCap? parseLineCap(String value) { - switch(value) { + switch (value) { case BUTT: return StrokeCap.butt; case ROUND: @@ -614,6 +639,7 @@ class CanvasRenderingContext2D extends BindingObject { _lineCap = value; }); } + StrokeCap get lineCap => _lineCap; double _lineDashOffset = 0.0; @@ -623,6 +649,7 @@ class CanvasRenderingContext2D extends BindingObject { _lineDashOffset = value; }); } + double get lineDashOffset => _lineDashOffset; static StrokeJoin? parseLineJoin(String value) { @@ -637,6 +664,7 @@ class CanvasRenderingContext2D extends BindingObject { } return null; } + // The lineJoin can effect the stroke(), strokeRect(), and strokeText() methods. StrokeJoin _lineJoin = StrokeJoin.miter; set lineJoin(StrokeJoin? value) { @@ -645,6 +673,7 @@ class CanvasRenderingContext2D extends BindingObject { _lineJoin = value; }); } + StrokeJoin get lineJoin => _lineJoin; double _lineWidth = 1.0; // (default 1) @@ -654,6 +683,7 @@ class CanvasRenderingContext2D extends BindingObject { _lineWidth = value; }); } + double get lineWidth => _lineWidth; double _miterLimit = 10.0; // (default 10) @@ -663,6 +693,7 @@ class CanvasRenderingContext2D extends BindingObject { _miterLimit = value; }); } + double get miterLimit => _miterLimit; String _lineDash = 'empty'; // default empty @@ -751,7 +782,6 @@ class CanvasRenderingContext2D extends BindingObject { }); } - Color _strokeStyle = CSSColor.initial; // default black set strokeStyle(Color? newValue) { if (newValue == null) return; @@ -759,6 +789,7 @@ class CanvasRenderingContext2D extends BindingObject { _strokeStyle = newValue; }); } + Color get strokeStyle => _strokeStyle; Color _fillStyle = CSSColor.initial; // default black @@ -768,6 +799,7 @@ class CanvasRenderingContext2D extends BindingObject { _fillStyle = newValue; }); } + Color get fillStyle => _fillStyle; CanvasGradient createLinearGradient(double x0, double y0, double x1, double y1) { @@ -834,9 +866,7 @@ class CanvasRenderingContext2D extends BindingObject { ..strokeWidth = lineWidth ..strokeMiterLimit = miterLimit ..style = PaintingStyle.stroke - ..color = color - ); - + ..color = color); } else { return TextStyle( color: color, @@ -847,7 +877,7 @@ class CanvasRenderingContext2D extends BindingObject { } } - TextPainter _getTextPainter(String text, Color color, { bool shouldStrokeText = false }) { + TextPainter _getTextPainter(String text, Color color, {bool shouldStrokeText = false}) { TextStyle textStyle = _getTextStyle(color, shouldStrokeText); TextSpan span = TextSpan(text: text, style: textStyle); TextPainter textPainter = TextPainter( @@ -868,13 +898,13 @@ class CanvasRenderingContext2D extends BindingObject { return Offset(width, 0.0); case TextAlign.justify: case TextAlign.center: - // The alignment is relative to the x value of the fillText() method. - // For example, if textAlign is "center", then the text's left edge will be at x - (textWidth / 2). + // The alignment is relative to the x value of the fillText() method. + // For example, if textAlign is "center", then the text's left edge will be at x - (textWidth / 2). return Offset(width / 2.0, 0.0); case TextAlign.start: - return direction == TextDirection.rtl ? Offset(width, 0.0): Offset.zero; + return direction == TextDirection.rtl ? Offset(width, 0.0) : Offset.zero; case TextAlign.end: - return direction == TextDirection.rtl ? Offset.zero: Offset(width, 0.0); + return direction == TextDirection.rtl ? Offset.zero : Offset(width, 0.0); } } diff --git a/webf/lib/src/dom/elements/canvas/canvas_painter.dart b/webf/lib/src/dom/elements/canvas/canvas_painter.dart index 4232205af0..71a7dfa0a3 100644 --- a/webf/lib/src/dom/elements/canvas/canvas_painter.dart +++ b/webf/lib/src/dom/elements/canvas/canvas_painter.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:ui'; @@ -9,7 +10,7 @@ import 'package:flutter/rendering.dart'; import 'canvas_context_2d.dart'; class CanvasPainter extends CustomPainter { - CanvasPainter({ required Listenable repaint }): super(repaint: repaint); + CanvasPainter({required Listenable repaint}) : super(repaint: repaint); CanvasRenderingContext2D? context; diff --git a/webf/lib/src/dom/elements/canvas/canvas_path_2d.dart b/webf/lib/src/dom/elements/canvas/canvas_path_2d.dart index cb954e9fd0..1f2f8f17a5 100644 --- a/webf/lib/src/dom/elements/canvas/canvas_path_2d.dart +++ b/webf/lib/src/dom/elements/canvas/canvas_path_2d.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:math' as math; @@ -176,7 +177,8 @@ class Path2D { /// _points(every 0.5Pi), and end angle. /// NOTE: Before ellipse() calls this function, adjustEndAngle() is called, so /// endAngle - startAngle must be equal to or less than 2Pi. - void _addDegenerateEllipse(double x, double y, double radiusX, double radiusY, double rotation, double startAngle, double endAngle, bool anticlockwise) { + void _addDegenerateEllipse(double x, double y, double radiusX, double radiusY, double rotation, double startAngle, + double endAngle, bool anticlockwise) { assert((endAngle - startAngle).abs() <= _2pi); assert(startAngle >= 0); assert(startAngle < _2pi); @@ -215,7 +217,8 @@ class Path2D { // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/ellipse // https://github.com/chromium/chromium/blob/99314be8152e688bafbbf9a615536bdbb289ea87/third_party/blink/renderer/modules/canvas/canvas2d/canvas_path.cc#L378 - void ellipse(double x, double y, double radiusX, double radiusY, double rotation, double startAngle, double endAngle, {bool anticlockwise = false}) { + void ellipse(double x, double y, double radiusX, double radiusY, double rotation, double startAngle, double endAngle, + {bool anticlockwise = false}) { if (radiusX < 0 || radiusY < 0) { return; } @@ -237,7 +240,8 @@ class Path2D { } // https://source.chromium.org/chromium/chromium/src/+/master:third_party/blink/renderer/platform/graphics/path.cc;l=403;drc=f6baa54c02fce19a1aeafbfeeebef9676fd9408b - void _addRotateEllipse(double x, double y, double radiusX, double radiusY, double rotation, double startAngle, double endAngle) { + void _addRotateEllipse( + double x, double y, double radiusX, double radiusY, double rotation, double startAngle, double endAngle) { assert((endAngle - startAngle).abs() <= _2pi); assert(startAngle >= 0); assert(startAngle < _2pi); diff --git a/webf/lib/src/dom/elements/edits.dart b/webf/lib/src/dom/elements/edits.dart index 0b24b3257d..3e9e4e0c54 100644 --- a/webf/lib/src/dom/elements/edits.dart +++ b/webf/lib/src/dom/elements/edits.dart @@ -1,28 +1,23 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/foundation.dart'; // https://developer.mozilla.org/en-US/docs/Web/HTML/Element#demarcating_edits const String DEL = 'DEL'; const String INS = 'INS'; -const Map _insDefaultStyle = { - TEXT_DECORATION: UNDERLINE -}; +const Map _insDefaultStyle = {TEXT_DECORATION: UNDERLINE}; -const Map _delDefaultStyle = { - TEXT_DECORATION: LINE_THROUGH -}; +const Map _delDefaultStyle = {TEXT_DECORATION: LINE_THROUGH}; class DelElement extends Element { - DelElement([BindingContext? context]) - : super(context, defaultStyle: _delDefaultStyle); + DelElement([BindingContext? context]) : super(context, defaultStyle: _delDefaultStyle); } class InsElement extends Element { - InsElement([BindingContext? context]) - : super(context, defaultStyle: _insDefaultStyle); + InsElement([BindingContext? context]) : super(context, defaultStyle: _insDefaultStyle); } diff --git a/webf/lib/src/dom/elements/forms.dart b/webf/lib/src/dom/elements/forms.dart index cdfc5496c2..78b59a9c1d 100644 --- a/webf/lib/src/dom/elements/forms.dart +++ b/webf/lib/src/dom/elements/forms.dart @@ -1,23 +1,20 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/foundation.dart'; const String LABEL = 'LABEL'; const String BUTTON = 'BUTTON'; -const Map _defaultStyle = { - DISPLAY: INLINE_BLOCK -}; +const Map _defaultStyle = {DISPLAY: INLINE_BLOCK}; class LabelElement extends Element { - LabelElement([BindingContext? context]) - : super(context); + LabelElement([BindingContext? context]) : super(context); } class ButtonElement extends Element { - ButtonElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + ButtonElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } diff --git a/webf/lib/src/dom/elements/grouping_content.dart b/webf/lib/src/dom/elements/grouping_content.dart index 61fa070d55..b3d028ada9 100644 --- a/webf/lib/src/dom/elements/grouping_content.dart +++ b/webf/lib/src/dom/elements/grouping_content.dart @@ -1,9 +1,10 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/foundation.dart'; // https://developer.mozilla.org/en-US/docs/Web/HTML/Element#text_content const String UL = 'UL'; @@ -44,11 +45,7 @@ const Map _ddDefaultStyle = { MARGIN_LEFT: '40px', }; -const Map _pDefaultStyle = { - DISPLAY: BLOCK, - MARGIN_TOP: '1em', - MARGIN_BOTTOM: '1em' -}; +const Map _pDefaultStyle = {DISPLAY: BLOCK, MARGIN_TOP: '1em', MARGIN_BOTTOM: '1em'}; const Map _lDefaultStyle = { DISPLAY: BLOCK, @@ -57,70 +54,57 @@ const Map _lDefaultStyle = { PADDING_LEFT: '40px' }; - class DivElement extends Element { - DivElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + DivElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } class FigureElement extends Element { - FigureElement([BindingContext? context]) - : super(context, defaultStyle: _bDefaultStyle); + FigureElement([BindingContext? context]) : super(context, defaultStyle: _bDefaultStyle); } class FigureCaptionElement extends Element { - FigureCaptionElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + FigureCaptionElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } class BlockQuotationElement extends Element { - BlockQuotationElement([BindingContext? context]) - : super(context, defaultStyle: _bDefaultStyle); + BlockQuotationElement([BindingContext? context]) : super(context, defaultStyle: _bDefaultStyle); } // https://html.spec.whatwg.org/multipage/grouping-content.html#htmlparagraphelement class ParagraphElement extends Element { static Map defaultStyle = _pDefaultStyle; - ParagraphElement([BindingContext? context]) - : super(context, defaultStyle: defaultStyle); + ParagraphElement([BindingContext? context]) : super(context, defaultStyle: defaultStyle); } // https://html.spec.whatwg.org/multipage/grouping-content.html#htmlulistelement class UListElement extends Element { - UListElement([BindingContext? context]) - : super(context, defaultStyle: _lDefaultStyle); + UListElement([BindingContext? context]) : super(context, defaultStyle: _lDefaultStyle); } // https://html.spec.whatwg.org/multipage/grouping-content.html#htmlolistelement class OListElement extends Element { - OListElement([BindingContext? context]) - : super(context, defaultStyle: _lDefaultStyle); + OListElement([BindingContext? context]) : super(context, defaultStyle: _lDefaultStyle); } class LIElement extends Element { - LIElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + LIElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } // https://html.spec.whatwg.org/multipage/grouping-content.html#htmlpreelement class PreElement extends Element { - PreElement([BindingContext? context]) - : super(context, defaultStyle: _preDefaultStyle); + PreElement([BindingContext? context]) : super(context, defaultStyle: _preDefaultStyle); } // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dd class DDElement extends Element { - DDElement([BindingContext? context]) - : super(context, defaultStyle: _ddDefaultStyle); + DDElement([BindingContext? context]) : super(context, defaultStyle: _ddDefaultStyle); } class DTElement extends Element { - DTElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + DTElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } // https://html.spec.whatwg.org/multipage/grouping-content.html#htmldlistelement class DListElement extends Element { - DListElement([BindingContext? context]) - : super(context, defaultStyle: _pDefaultStyle); + DListElement([BindingContext? context]) : super(context, defaultStyle: _pDefaultStyle); } diff --git a/webf/lib/src/dom/elements/head.dart b/webf/lib/src/dom/elements/head.dart index 70eec0bfd4..1f64055a3e 100644 --- a/webf/lib/src/dom/elements/head.dart +++ b/webf/lib/src/dom/elements/head.dart @@ -1,11 +1,12 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/scheduler.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/kraken.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/webf.dart'; // Children of the element all have display:none const Map _defaultStyle = { @@ -21,8 +22,7 @@ const String NOSCRIPT = 'NOSCRIPT'; const String SCRIPT = 'SCRIPT'; class HeadElement extends Element { - HeadElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + HeadElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } const String _REL_STYLESHEET = 'stylesheet'; @@ -38,22 +38,36 @@ class LinkElement extends Element { @override getBindingProperty(String key) { switch (key) { - case 'disabled': return disabled; - case 'rel': return rel; - case 'href': return href; - case 'type': return type; - default: return super.getBindingProperty(key); + case 'disabled': + return disabled; + case 'rel': + return rel; + case 'href': + return href; + case 'type': + return type; + default: + return super.getBindingProperty(key); } } @override void setBindingProperty(String key, value) { switch (key) { - case 'disabled': disabled = castToType(value); break; - case 'rel': rel = castToType(value); break; - case 'href': href = castToType(value); break; - case 'type': type = castToType(value); break; - default: super.setBindingProperty(key, value); + case 'disabled': + disabled = castToType(value); + break; + case 'rel': + rel = castToType(value); + break; + case 'href': + href = castToType(value); + break; + case 'type': + type = castToType(value); + break; + default: + super.setBindingProperty(key, value); } } @@ -61,10 +75,18 @@ class LinkElement extends Element { void setAttribute(String qualifiedName, String value) { super.setAttribute(qualifiedName, value); switch (qualifiedName) { - case 'disabled': disabled = attributeToProperty(value); break; - case 'rel': rel = attributeToProperty(value); break; - case 'href': href = attributeToProperty(value); break; - case 'type': type = attributeToProperty(value); break; + case 'disabled': + disabled = attributeToProperty(value); + break; + case 'rel': + rel = attributeToProperty(value); + break; + case 'href': + href = attributeToProperty(value); + break; + case 'type': + type = attributeToProperty(value); + break; } } @@ -111,9 +133,12 @@ class LinkElement extends Element { } void _fetchAndApplyCSSStyle() async { - if (_resolvedHyperlink != null && rel == _REL_STYLESHEET && isConnected && !_stylesheetLoaded.containsKey(_resolvedHyperlink.toString())) { + if (_resolvedHyperlink != null && + rel == _REL_STYLESHEET && + isConnected && + !_stylesheetLoaded.containsKey(_resolvedHyperlink.toString())) { String url = _resolvedHyperlink.toString(); - KrakenBundle bundle = KrakenBundle.fromUrl(url); + WebFBundle bundle = WebFBundle.fromUrl(url); _stylesheetLoaded[url] = true; try { // Increment count when request. @@ -129,18 +154,18 @@ class LinkElement extends Element { _addCSSStyleSheet(cssString); // Successful load. - SchedulerBinding.instance!.addPostFrameCallback((_) { + SchedulerBinding.instance.addPostFrameCallback((_) { dispatchEvent(Event(EVENT_LOAD)); }); } catch (e) { // An error occurred. - SchedulerBinding.instance!.addPostFrameCallback((_) { + SchedulerBinding.instance.addPostFrameCallback((_) { dispatchEvent(Event(EVENT_ERROR)); }); } finally { bundle.dispose(); } - SchedulerBinding.instance!.scheduleFrame(); + SchedulerBinding.instance.scheduleFrame(); } } @@ -158,26 +183,22 @@ class LinkElement extends Element { } class MetaElement extends Element { - MetaElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + MetaElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } class TitleElement extends Element { - TitleElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + TitleElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } class NoScriptElement extends Element { - NoScriptElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + NoScriptElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } const String _CSS_MIME = 'text/css'; // https://www.w3.org/TR/2011/WD-html5-author-20110809/the-style-element.html class StyleElement extends Element { - StyleElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + StyleElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); final String _type = _CSS_MIME; CSSStyleSheet? _styleSheet; @@ -185,16 +206,21 @@ class StyleElement extends Element { @override getBindingProperty(String key) { switch (key) { - case 'type': return type; - default: return super.getBindingProperty(key); + case 'type': + return type; + default: + return super.getBindingProperty(key); } } @override void setBindingProperty(String key, value) { switch (key) { - case 'type': type = castToType(value); break; - default: super.setBindingProperty(key, value); + case 'type': + type = castToType(value); + break; + default: + super.setBindingProperty(key, value); } } @@ -202,7 +228,9 @@ class StyleElement extends Element { void setAttribute(String qualifiedName, String value) { super.setAttribute(qualifiedName, value); switch (qualifiedName) { - case 'type': type = attributeToProperty(value); break; + case 'type': + type = attributeToProperty(value); + break; } } diff --git a/webf/lib/src/dom/elements/headings.dart b/webf/lib/src/dom/elements/headings.dart index c393cdd8e2..edede4dce5 100644 --- a/webf/lib/src/dom/elements/headings.dart +++ b/webf/lib/src/dom/elements/headings.dart @@ -1,9 +1,10 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/foundation.dart'; const String H1 = 'H1'; const String H2 = 'H2'; @@ -15,7 +16,7 @@ const String H6 = 'H6'; const Map _h1DefaultStyle = { DISPLAY: BLOCK, FONT_WEIGHT: BOLD, - FONT_SIZE: '2em', // 32px + FONT_SIZE: '2em', // 32px MARGIN_TOP: '0.67em', MARGIN_BOTTOM: '0.67em', }; @@ -61,31 +62,25 @@ const Map _h6DefaultStyle = { }; class H1Element extends Element { - H1Element([BindingContext? context]) - : super(context, defaultStyle: _h1DefaultStyle); + H1Element([BindingContext? context]) : super(context, defaultStyle: _h1DefaultStyle); } class H2Element extends Element { - H2Element([BindingContext? context]) - : super(context, defaultStyle: _h2DefaultStyle); + H2Element([BindingContext? context]) : super(context, defaultStyle: _h2DefaultStyle); } class H3Element extends Element { - H3Element([BindingContext? context]) - : super(context, defaultStyle: _h3DefaultStyle); + H3Element([BindingContext? context]) : super(context, defaultStyle: _h3DefaultStyle); } class H4Element extends Element { - H4Element([BindingContext? context]) - : super(context, defaultStyle: _h4DefaultStyle); + H4Element([BindingContext? context]) : super(context, defaultStyle: _h4DefaultStyle); } class H5Element extends Element { - H5Element([BindingContext? context]) - : super(context, defaultStyle: _h5DefaultStyle); + H5Element([BindingContext? context]) : super(context, defaultStyle: _h5DefaultStyle); } class H6Element extends Element { - H6Element([BindingContext? context]) - : super(context, defaultStyle: _h6DefaultStyle); + H6Element([BindingContext? context]) : super(context, defaultStyle: _h6DefaultStyle); } diff --git a/webf/lib/src/dom/elements/html.dart b/webf/lib/src/dom/elements/html.dart index 6017295d65..a9b27a71b9 100644 --- a/webf/lib/src/dom/elements/html.dart +++ b/webf/lib/src/dom/elements/html.dart @@ -1,9 +1,10 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/foundation.dart'; const String HTML = 'HTML'; const Map _defaultStyle = { @@ -12,8 +13,7 @@ const Map _defaultStyle = { class HTMLElement extends Element { static Map defaultStyle = _defaultStyle; - HTMLElement([BindingContext? context]) - : super(context, defaultStyle: defaultStyle); + HTMLElement([BindingContext? context]) : super(context, defaultStyle: defaultStyle); @override void dispatchEvent(Event event) { @@ -31,8 +31,8 @@ class HTMLElement extends Element { @override void setRenderStyle(String property, String present) { switch (property) { - // Visible should be interpreted as auto and clip should be interpreted as hidden when overflow apply to html. - // https://drafts.csswg.org/css-overflow-3/#overflow-propagation + // Visible should be interpreted as auto and clip should be interpreted as hidden when overflow apply to html. + // https://drafts.csswg.org/css-overflow-3/#overflow-propagation case OVERFLOW: case OVERFLOW_X: case OVERFLOW_Y: diff --git a/webf/lib/src/dom/elements/img.dart b/webf/lib/src/dom/elements/img.dart index 3860c2bd62..d0588e32c3 100644 --- a/webf/lib/src/dom/elements/img.dart +++ b/webf/lib/src/dom/elements/img.dart @@ -1,16 +1,17 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; import 'dart:typed_data'; import 'dart:ui' as ui; import 'package:flutter/rendering.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/foundation.dart'; -import 'package:kraken/painting.dart'; -import 'package:kraken/rendering.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/foundation.dart'; +import 'package:webf/painting.dart'; +import 'package:webf/rendering.dart'; const String IMAGE = 'IMG'; const String NATURAL_WIDTH = 'naturalWidth'; @@ -28,7 +29,7 @@ const Map _defaultStyle = { // The HTMLImageElement. class ImageElement extends Element { // The render box to draw image. - KrakenRenderImage? _renderImage; + WebFRenderImage? _renderImage; ImageProvider? _currentImageProvider; @@ -67,7 +68,8 @@ class ImageElement extends Element { // @TODO: Implement the srcset. if (src.isEmpty) return true; if (_currentRequest != null && _currentRequest!.available && _pendingRequest == null) return true; - if (_currentRequest != null && _currentRequest!.state == _ImageRequestState.broken && _pendingRequest == null) return true; + if (_currentRequest != null && _currentRequest!.state == _ImageRequestState.broken && _pendingRequest == null) + return true; return true; } @@ -89,38 +91,53 @@ class ImageElement extends Element { ImageStreamCompleterHandle? _completerHandle; - ImageElement([BindingContext? context]) - : super( - context, - isReplacedElement: true, - defaultStyle: _defaultStyle) { - } + ImageElement([BindingContext? context]) : super(context, isReplacedElement: true, defaultStyle: _defaultStyle) {} // Bindings. @override getBindingProperty(String key) { switch (key) { - case 'src': return src; - case 'loading': return loading; - case 'width': return width; - case 'height': return height; - case 'scaling': return scaling; - case 'naturalWidth': return naturalWidth; - case 'naturalHeight': return naturalHeight; - case 'complete': return complete; - default: return super.getBindingProperty(key); + case 'src': + return src; + case 'loading': + return loading; + case 'width': + return width; + case 'height': + return height; + case 'scaling': + return scaling; + case 'naturalWidth': + return naturalWidth; + case 'naturalHeight': + return naturalHeight; + case 'complete': + return complete; + default: + return super.getBindingProperty(key); } } @override void setBindingProperty(String key, value) { switch (key) { - case 'src': src = castToType(value); break; - case 'loading': loading = castToType(value); break; - case 'width': width = castToType(value); break; - case 'height': height = castToType(value); break; - case 'scaling': scaling = castToType(value); break; - default: super.setBindingProperty(key, value); + case 'src': + src = castToType(value); + break; + case 'loading': + loading = castToType(value); + break; + case 'width': + width = castToType(value); + break; + case 'height': + height = castToType(value); + break; + case 'scaling': + scaling = castToType(value); + break; + default: + super.setBindingProperty(key, value); } } @@ -128,11 +145,21 @@ class ImageElement extends Element { void setAttribute(String qualifiedName, String value) { super.setAttribute(qualifiedName, value); switch (qualifiedName) { - case 'src': src = attributeToProperty(value); break; - case 'loading': loading = attributeToProperty(value); break; - case 'width': width = attributeToProperty(value); break; - case 'height': height = attributeToProperty(value); break; - case 'scaling': scaling = attributeToProperty(value); break; + case 'src': + src = attributeToProperty(value); + break; + case 'loading': + loading = attributeToProperty(value); + break; + case 'width': + width = attributeToProperty(value); + break; + case 'height': + height = attributeToProperty(value); + break; + case 'scaling': + scaling = attributeToProperty(value); + break; } } @@ -188,11 +215,11 @@ class ImageElement extends Element { } ImageStreamListener? _imageStreamListener; - ImageStreamListener get _listener => _imageStreamListener ??= ImageStreamListener(_handleImageFrame, onError: _onImageError); + ImageStreamListener get _listener => + _imageStreamListener ??= ImageStreamListener(_handleImageFrame, onError: _onImageError); void _listenToStream() { - if (_isListeningStream) - return; + if (_isListeningStream) return; _cachedImageStream?.addListener(_listener); _completerHandle?.dispose(); @@ -220,6 +247,7 @@ class ImageElement extends Element { CSSLengthValue len = CSSLength.parseLength(width, renderStyle, WIDTH); return len.computedValue; } + return null; } double? get _styleHeight { @@ -228,6 +256,7 @@ class ImageElement extends Element { CSSLengthValue len = CSSLength.parseLength(height, renderStyle, HEIGHT); return len.computedValue; } + return null; } // Width and height set through attributes. @@ -235,28 +264,26 @@ class ImageElement extends Element { if (hasAttribute(WIDTH)) { return CSSLength.toDouble(getAttribute(WIDTH)); } + return null; } double? get _attrHeight { if (hasAttribute(HEIGHT)) { return CSSLength.toDouble(getAttribute(HEIGHT)); } + return null; } int get width { // Width calc priority: style > attr > intrinsic. - final double borderBoxWidth = _styleWidth - ?? _attrWidth - ?? renderStyle.getWidthByAspectRatio(); + final double borderBoxWidth = _styleWidth ?? _attrWidth ?? renderStyle.getWidthByAspectRatio(); return borderBoxWidth.round(); } int get height { // Height calc priority: style > attr > intrinsic. - final double borderBoxHeight = _styleHeight - ?? _attrHeight - ?? renderStyle.getHeightByAspectRatio(); + final double borderBoxHeight = _styleHeight ?? _attrHeight ?? renderStyle.getHeightByAspectRatio(); return borderBoxHeight.round(); } @@ -332,8 +359,8 @@ class ImageElement extends Element { } } - KrakenRenderImage _createRenderImageBox() { - return KrakenRenderImage( + WebFRenderImage _createRenderImageBox() { + return WebFRenderImage( image: _cachedImageInfo?.image, fit: renderStyle.objectFit, alignment: renderStyle.objectPosition, @@ -359,8 +386,7 @@ class ImageElement extends Element { /// to true, which create [ImageStreamCompleterHandle] to keep the completer /// alive. void _stopListeningStream({bool keepStreamAlive = false}) { - if (!_isListeningStream) - return; + if (!_isListeningStream) return; if (keepStreamAlive && _completerHandle == null && _cachedImageStream?.completer != null) { _completerHandle = _cachedImageStream!.completer!.keepAlive(); @@ -390,7 +416,7 @@ class ImageElement extends Element { // Create an ImageStream that decodes the obtained image. // If imageElement has property size or width/height property on [renderStyle], // The image will be encoded into a small size for better rasterization performance. - void _decode({ bool updateImageProvider = false }) { + void _decode({bool updateImageProvider = false}) { ImageProvider? provider = _currentImageProvider; if (updateImageProvider || provider == null) { // Image should be resized based on different ratio according to object-fit value. @@ -493,7 +519,8 @@ class ImageElement extends Element { // Image dimensions (width or height) should specified for performance when lazy-load. if (_shouldLazyLoading) { RenderReplaced? renderReplaced = renderBoxModel as RenderReplaced?; - renderReplaced?..isInLazyRendering = true + renderReplaced + ?..isInLazyRendering = true // When detach renderer, all listeners will be cleared. ..addIntersectionChangeListener(_handleIntersectionChange); } else { @@ -596,7 +623,8 @@ enum _ImageRequestState { // https://html.spec.whatwg.org/multipage/images.html#image-request class ImageRequest { - ImageRequest.fromUri(this.currentUri, { + ImageRequest.fromUri( + this.currentUri, { this.state = _ImageRequestState.unavailable, }); @@ -608,11 +636,11 @@ class ImageRequest { /// When an image request's state is either partially available or completely available, /// the image request is said to be available. - bool get available => state == _ImageRequestState.completelyAvailable - || state == _ImageRequestState.partiallyAvailable; + bool get available => + state == _ImageRequestState.completelyAvailable || state == _ImageRequestState.partiallyAvailable; Future _obtainImage(int? contextId) async { - final KrakenBundle bundle = KrakenBundle.fromUrl(currentUri.toString()); + final WebFBundle bundle = WebFBundle.fromUrl(currentUri.toString()); await bundle.resolve(contextId); diff --git a/webf/lib/src/dom/elements/input.dart b/webf/lib/src/dom/elements/input.dart index 55aa8550fd..d852cf3037 100644 --- a/webf/lib/src/dom/elements/input.dart +++ b/webf/lib/src/dom/elements/input.dart @@ -1,9 +1,12 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -import 'package:kraken/foundation.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; +import 'dart:ui'; + +import 'package:webf/foundation.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; const String INPUT = 'INPUT'; const String SIZE = 'size'; @@ -14,76 +17,149 @@ const Map _defaultStyle = { }; class InputElement extends TextFormControlElement { - InputElement(context) - : super(context, defaultStyle: _defaultStyle, isReplacedElement: true); + InputElement(context) : super(context, defaultStyle: _defaultStyle, isReplacedElement: true); // Bindings. @override getBindingProperty(String key) { switch (key) { - case 'width': return width; - case 'height': return height; - case 'size': return size; - case 'value': return value; - case 'defaultValue': return defaultValue; - case 'accept': return accept; - case 'autocomplete': return autocomplete; - case 'autofocus': return autofocus; - case 'required': return required; - case 'readonly': return readOnly; - case 'pattern': return pattern; - case 'step': return step; - case 'name': return name; - case 'multiple': return multiple; - case 'checked': return checked; - case 'disabled': return disabled; - case 'min': return min; - case 'max': return max; - case 'minLength': return minLength; - case 'maxLength': return maxLength; - case 'placeholder': return placeholder; - case 'type': return type; - case 'inputMode': return inputMode; - default: return super.getBindingProperty(key); + case 'width': + return width; + case 'height': + return height; + case 'size': + return size; + case 'value': + return value; + case 'defaultValue': + return defaultValue; + case 'accept': + return accept; + case 'autocomplete': + return autocomplete; + case 'autofocus': + return autofocus; + case 'required': + return required; + case 'readonly': + return readOnly; + case 'pattern': + return pattern; + case 'step': + return step; + case 'name': + return name; + case 'multiple': + return multiple; + case 'checked': + return checked; + case 'disabled': + return disabled; + case 'min': + return min; + case 'max': + return max; + case 'minLength': + return minLength; + case 'maxLength': + return maxLength; + case 'placeholder': + return placeholder; + case 'type': + return type; + case 'inputMode': + return inputMode; + default: + return super.getBindingProperty(key); } } @override void setBindingProperty(String key, val) { switch (key) { - case 'width': width = castToType(val).toInt(); break; - case 'height': height = castToType(val).toInt(); break; - case 'size': size = castToType(val).toInt(); break; - case 'value': value = castToType(val); break; - case 'defaultValue': defaultValue = castToType(val); break; - case 'accept': accept = castToType(val); break; - case 'autocomplete': autocomplete = castToType(val); break; - case 'autofocus': autofocus = castToType(val); break; - case 'required': required = castToType(val); break; - case 'readonly': readOnly = castToType(val); break; - case 'pattern': pattern = castToType(val); break; - case 'step': step = castToType(val); break; - case 'name': name = castToType(val); break; - case 'multiple': multiple = castToType(val); break; - case 'checked': checked = castToType(val); break; - case 'disabled': disabled = castToType(val); break; - case 'min': min = castToType(val); break; - case 'max': max = castToType(val); break; - case 'minLength': minLength = castToType(val).toInt(); break; - case 'maxLength': maxLength = castToType(val).toInt(); break; - case 'placeholder': placeholder = castToType(val); break; - case 'type': type = castToType(val); break; - case 'inputMode': inputMode = castToType(val); break; - default: super.setBindingProperty(key, value); + case 'width': + width = castToType(val).toInt(); + break; + case 'height': + height = castToType(val).toInt(); + break; + case 'size': + size = castToType(val).toInt(); + break; + case 'value': + value = castToType(val); + break; + case 'defaultValue': + defaultValue = castToType(val); + break; + case 'accept': + accept = castToType(val); + break; + case 'autocomplete': + autocomplete = castToType(val); + break; + case 'autofocus': + autofocus = castToType(val); + break; + case 'required': + required = castToType(val); + break; + case 'readonly': + readOnly = castToType(val); + break; + case 'pattern': + pattern = castToType(val); + break; + case 'step': + step = castToType(val); + break; + case 'name': + name = castToType(val); + break; + case 'multiple': + multiple = castToType(val); + break; + case 'checked': + checked = castToType(val); + break; + case 'disabled': + disabled = castToType(val); + break; + case 'min': + min = castToType(val); + break; + case 'max': + max = castToType(val); + break; + case 'minLength': + minLength = castToType(val).toInt(); + break; + case 'maxLength': + maxLength = castToType(val).toInt(); + break; + case 'placeholder': + placeholder = castToType(val); + break; + case 'type': + type = castToType(val); + break; + case 'inputMode': + inputMode = castToType(val); + break; + default: + super.setBindingProperty(key, value); } } @override invokeBindingMethod(String method, List args) { switch (method) { - case 'focus': return focus(); - case 'blur': return blur(); - default: return super.invokeBindingMethod(method, args); + case 'focus': + return focus(); + case 'blur': + return blur(); + default: + return super.invokeBindingMethod(method, args); } } @@ -91,28 +167,72 @@ class InputElement extends TextFormControlElement { void setAttribute(String qualifiedName, String val) { super.setAttribute(qualifiedName, val); switch (qualifiedName) { - case 'width': width = attributeToProperty(val); break; - case 'height': height = attributeToProperty(val); break; - case 'size': size = attributeToProperty(val); break; - case 'value': defaultValue = attributeToProperty(val); break; - case 'accept': accept = attributeToProperty(val); break; - case 'autocomplete': autocomplete = attributeToProperty(val); break; - case 'autofocus': autofocus = attributeToProperty(val); break; - case 'required': required = attributeToProperty(val); break; - case 'readonly': readOnly = attributeToProperty(val); break; - case 'pattern': pattern = attributeToProperty(val); break; - case 'step': step = attributeToProperty(val); break; - case 'name': name = attributeToProperty(val); break; - case 'multiple': multiple = attributeToProperty(val); break; - case 'checked': checked = attributeToProperty(val); break; - case 'disabled': disabled = attributeToProperty(val); break; - case 'min': min = attributeToProperty(val); break; - case 'max': max = attributeToProperty(val); break; - case 'minlength': minLength = attributeToProperty(val); break; - case 'maxlength': maxLength = attributeToProperty(val); break; - case 'placeholder': placeholder = attributeToProperty(val); break; - case 'type': type = attributeToProperty(val); break; - case 'inputmode': inputMode = attributeToProperty(val); break; + case 'width': + width = attributeToProperty(val); + break; + case 'height': + height = attributeToProperty(val); + break; + case 'size': + size = attributeToProperty(val); + break; + case 'value': + defaultValue = attributeToProperty(val); + break; + case 'accept': + accept = attributeToProperty(val); + break; + case 'autocomplete': + autocomplete = attributeToProperty(val); + break; + case 'autofocus': + autofocus = attributeToProperty(val); + break; + case 'required': + required = attributeToProperty(val); + break; + case 'readonly': + readOnly = attributeToProperty(val); + break; + case 'pattern': + pattern = attributeToProperty(val); + break; + case 'step': + step = attributeToProperty(val); + break; + case 'name': + name = attributeToProperty(val); + break; + case 'multiple': + multiple = attributeToProperty(val); + break; + case 'checked': + checked = attributeToProperty(val); + break; + case 'disabled': + disabled = attributeToProperty(val); + break; + case 'min': + min = attributeToProperty(val); + break; + case 'max': + max = attributeToProperty(val); + break; + case 'minlength': + minLength = attributeToProperty(val); + break; + case 'maxlength': + maxLength = attributeToProperty(val); + break; + case 'placeholder': + placeholder = attributeToProperty(val); + break; + case 'type': + type = attributeToProperty(val); + break; + case 'inputmode': + inputMode = attributeToProperty(val); + break; } } @@ -166,5 +286,19 @@ class InputElement extends TextFormControlElement { renderStyle.width = CSSLengthValue(_defaultWidth, CSSLengthType.PX); } } -} + @override + void insertTextPlaceholder(Size size) { + // TODO: implement insertTextPlaceholder + } + + @override + void removeTextPlaceholder() { + // TODO: implement removeTextPlaceholder + } + + @override + void showToolbar() { + // TODO: implement showToolbar + } +} diff --git a/webf/lib/src/dom/elements/object.dart b/webf/lib/src/dom/elements/object.dart index 7f07a721e5..f2a9b614cf 100644 --- a/webf/lib/src/dom/elements/object.dart +++ b/webf/lib/src/dom/elements/object.dart @@ -1,10 +1,11 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/rendering.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/foundation.dart'; const String OBJECT = 'OBJECT'; const String PARAM = 'PARAM'; @@ -21,8 +22,7 @@ const Map _paramStyle = { // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/param class ParamElement extends Element { - ParamElement([BindingContext? context]) - : super(context, defaultStyle: _paramStyle); + ParamElement([BindingContext? context]) : super(context, defaultStyle: _paramStyle); } _DefaultObjectElementClient _DefaultObjectElementClientFactory(ObjectElementHost objectElementHost) { @@ -31,12 +31,10 @@ _DefaultObjectElementClient _DefaultObjectElementClientFactory(ObjectElementHost ///https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object class ObjectElement extends Element implements ObjectElementHost { - late ObjectElementClientFactory _objectElementClientFactory; late ObjectElementClient _objectElementClient; - ObjectElement([BindingContext? context]) - : super(context, defaultStyle: _objectStyle, isReplacedElement: true) { + ObjectElement([BindingContext? context]) : super(context, defaultStyle: _objectStyle, isReplacedElement: true) { initObjectClient(); initElementClient(); } @@ -63,8 +61,12 @@ class ObjectElement extends Element implements ObjectElementHost { void setAttribute(String qualifiedName, String value) { super.setAttribute(qualifiedName, value); switch (qualifiedName) { - case 'type': type = attributeToProperty(value); break; - case 'data': data = attributeToProperty(value); break; + case 'type': + type = attributeToProperty(value); + break; + case 'data': + data = attributeToProperty(value); + break; } } @@ -145,8 +147,7 @@ class _DefaultObjectElementClient implements ObjectElementClient { /// [name] method name /// [args] method params @override - dynamic handleJSCall(String method, List argv) { - } + dynamic handleJSCall(String method, List argv) {} @override void removeProperty(String key) { @@ -177,18 +178,14 @@ class _DefaultObjectElementClient implements ObjectElementClient { } @override - void didAttachRenderer() { - } + void didAttachRenderer() {} @override - void didDetachRenderer() { - } + void didDetachRenderer() {} @override - void willAttachRenderer() { - } + void willAttachRenderer() {} @override - void willDetachRenderer() { - } + void willDetachRenderer() {} } diff --git a/webf/lib/src/dom/elements/script.dart b/webf/lib/src/dom/elements/script.dart index 03c78fe841..9df5d7d914 100644 --- a/webf/lib/src/dom/elements/script.dart +++ b/webf/lib/src/dom/elements/script.dart @@ -1,14 +1,15 @@ /* - * Copyright (C) 2022-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/scheduler.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/kraken.dart'; -import 'package:kraken/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/webf.dart'; +import 'package:webf/css.dart'; import 'package:path/path.dart'; // Children of the element all have display:none @@ -24,7 +25,9 @@ const String _JAVASCRIPT_MODULE = 'module'; typedef ScriptExecution = void Function(bool async); class ScriptRunner { - ScriptRunner(Document document, int contextId) : _document = document, _contextId = contextId; + ScriptRunner(Document document, int contextId) + : _document = document, + _contextId = contextId; final Document _document; final int _contextId; @@ -32,7 +35,7 @@ class ScriptRunner { // Indicate the sync pending scripts. int _resolvingCount = 0; - static void _evaluateScriptBundle(int contextId, KrakenBundle bundle, { bool async = false }) async { + static void _evaluateScriptBundle(int contextId, WebFBundle bundle, {bool async = false}) async { // Evaluate bundle. if (bundle.isJavascript) { final String contentInString = await resolveStringFromData(bundle.data!, preferSync: !async); @@ -44,7 +47,7 @@ class ScriptRunner { } } - void _execute(List tasks, { bool async = false }) { + void _execute(List tasks, {bool async = false}) { List executingTasks = [...tasks]; tasks.clear(); @@ -60,7 +63,7 @@ class ScriptRunner { String url = element.src.toString(); // Obtain bundle. - KrakenBundle bundle = KrakenBundle.fromUrl(url); + WebFBundle bundle = WebFBundle.fromUrl(url); // The bundle execution task. void task(bool async) { @@ -125,7 +128,7 @@ class ScriptRunner { // Script executing phrase. if (shouldAsync) { // @TODO: Use requestIdleCallback - SchedulerBinding.instance!.scheduleFrameCallback((_) { + SchedulerBinding.instance.scheduleFrameCallback((_) { task(shouldAsync); }); } else { @@ -150,26 +153,46 @@ class ScriptElement extends Element { @override getBindingProperty(String key) { switch (key) { - case 'src': return src; - case 'async': return async; - case 'defer': return defer; - case 'type': return type; - case 'charset': return charset; - case 'text': return text; - default: return super.getBindingProperty(key); + case 'src': + return src; + case 'async': + return async; + case 'defer': + return defer; + case 'type': + return type; + case 'charset': + return charset; + case 'text': + return text; + default: + return super.getBindingProperty(key); } } @override void setBindingProperty(String key, value) { switch (key) { - case 'src': src = castToType(value); break; - case 'async': async = castToType(value); break; - case 'defer': defer = castToType(value); break; - case 'type': type = castToType(value); break; - case 'charset': charset = castToType(value); break; - case 'text': text = castToType(value); break; - default: super.setBindingProperty(key, value); + case 'src': + src = castToType(value); + break; + case 'async': + async = castToType(value); + break; + case 'defer': + defer = castToType(value); + break; + case 'type': + type = castToType(value); + break; + case 'charset': + charset = castToType(value); + break; + case 'text': + text = castToType(value); + break; + default: + super.setBindingProperty(key, value); } } @@ -177,12 +200,24 @@ class ScriptElement extends Element { void setAttribute(String qualifiedName, String value) { super.setAttribute(qualifiedName, value); switch (qualifiedName) { - case 'src': src = attributeToProperty(value); break; - case 'async': async = attributeToProperty(value); break; - case 'defer': defer = attributeToProperty(value); break; - case 'type': type = attributeToProperty(value); break; - case 'charset': charset = attributeToProperty(value); break; - case 'text': text = attributeToProperty(value); break; + case 'src': + src = attributeToProperty(value); + break; + case 'async': + async = attributeToProperty(value); + break; + case 'defer': + defer = attributeToProperty(value); + break; + case 'type': + type = attributeToProperty(value); + break; + case 'charset': + charset = attributeToProperty(value); + break; + case 'text': + text = attributeToProperty(value); + break; } } @@ -241,16 +276,16 @@ class ScriptElement extends Element { int? contextId = ownerDocument.contextId; if (contextId == null) return; // Must - if (src.isNotEmpty && isConnected && ( - _type == _MIME_TEXT_JAVASCRIPT - || _type == _MIME_APPLICATION_JAVASCRIPT - || _type == _MIME_X_APPLICATION_JAVASCRIPT - || _type == _JAVASCRIPT_MODULE - )) { + if (src.isNotEmpty && + isConnected && + (_type == _MIME_TEXT_JAVASCRIPT || + _type == _MIME_APPLICATION_JAVASCRIPT || + _type == _MIME_X_APPLICATION_JAVASCRIPT || + _type == _JAVASCRIPT_MODULE)) { // Add bundle to scripts queue. ownerDocument.scriptRunner._queueScriptForExecution(this); - SchedulerBinding.instance!.scheduleFrame(); + SchedulerBinding.instance.scheduleFrame(); } } @@ -261,7 +296,7 @@ class ScriptElement extends Element { if (contextId == null) return; if (src.isNotEmpty) { _fetchAndExecuteSource(); - } else if (_type == _MIME_TEXT_JAVASCRIPT || _type == _JAVASCRIPT_MODULE){ + } else if (_type == _MIME_TEXT_JAVASCRIPT || _type == _JAVASCRIPT_MODULE) { // Eval script context: String? script = collectElementChildText(); if (script != null && script.isNotEmpty) { diff --git a/webf/lib/src/dom/elements/sections.dart b/webf/lib/src/dom/elements/sections.dart index 344617be40..4d9a424869 100644 --- a/webf/lib/src/dom/elements/sections.dart +++ b/webf/lib/src/dom/elements/sections.dart @@ -1,9 +1,10 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/foundation.dart'; // https://developer.mozilla.org/en-US/docs/Web/HTML/Element#content_sectioning @@ -20,47 +21,36 @@ const Map _defaultStyle = { DISPLAY: BLOCK, }; -const Map _addressDefaultStyle = { - DISPLAY: BLOCK, - FONT_STYLE: ITALIC -}; +const Map _addressDefaultStyle = {DISPLAY: BLOCK, FONT_STYLE: ITALIC}; class AddressElement extends Element { - AddressElement([BindingContext? context]) - : super(context, defaultStyle: _addressDefaultStyle); + AddressElement([BindingContext? context]) : super(context, defaultStyle: _addressDefaultStyle); } class ArticleElement extends Element { - ArticleElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + ArticleElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } class AsideElement extends Element { - AsideElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + AsideElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } class FooterElement extends Element { - FooterElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + FooterElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } class HeaderElement extends Element { - HeaderElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + HeaderElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } class MainElement extends Element { - MainElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + MainElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } class NavElement extends Element { - NavElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + NavElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } class SectionElement extends Element { - SectionElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + SectionElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } diff --git a/webf/lib/src/dom/elements/semantics_text.dart b/webf/lib/src/dom/elements/semantics_text.dart index 66fc8d5576..9c0d3a910d 100644 --- a/webf/lib/src/dom/elements/semantics_text.dart +++ b/webf/lib/src/dom/elements/semantics_text.dart @@ -1,11 +1,12 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/rendering.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/rendering.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/rendering.dart'; +import 'package:webf/foundation.dart'; // https://developer.mozilla.org/en-US/docs/Web/HTML/Element#inline_text_semantics const String SPAN = 'SPAN'; @@ -29,46 +30,30 @@ const String KBD = 'KBD'; const String DFN = 'DFN'; const String BR = 'BR'; -const Map _uDefaultStyle = { - TEXT_DECORATION: UNDERLINE -}; +const Map _uDefaultStyle = {TEXT_DECORATION: UNDERLINE}; -const Map _sDefaultStyle = { - TEXT_DECORATION: LINE_THROUGH -}; +const Map _sDefaultStyle = {TEXT_DECORATION: LINE_THROUGH}; -const Map _smallDefaultStyle = { - FONT_SIZE: SMALLER -}; +const Map _smallDefaultStyle = {FONT_SIZE: SMALLER}; -const Map _codeDefaultStyle = { - FONT_FAMILY: 'monospace' -}; +const Map _codeDefaultStyle = {FONT_FAMILY: 'monospace'}; -const Map _boldDefaultStyle = { - FONT_WEIGHT: BOLD -}; +const Map _boldDefaultStyle = {FONT_WEIGHT: BOLD}; const Map _abbrDefaultStyle = { TEXT_DECORATION_LINE: UNDERLINE, TEXT_DECORATION_STYLE: DOTTED, }; -const Map _markDefaultStyle = { - BACKGROUND_COLOR: 'yellow', - COLOR: 'black' -}; +const Map _markDefaultStyle = {BACKGROUND_COLOR: 'yellow', COLOR: 'black'}; -const Map _defaultStyle = { - FONT_STYLE: ITALIC -}; +const Map _defaultStyle = {FONT_STYLE: ITALIC}; // https://html.spec.whatwg.org/multipage/text-level-semantics.html#htmlbrelement class BRElement extends Element { RenderLineBreak? _renderLineBreak; - BRElement([BindingContext? context]) - : super(context, isReplacedElement: true); + BRElement([BindingContext? context]) : super(context, isReplacedElement: true); @override RenderBoxModel? get renderBoxModel => _renderLineBreak; @@ -85,99 +70,80 @@ class BRElement extends Element { } class BringElement extends Element { - BringElement([BindingContext? context]) - : super(context, defaultStyle: _boldDefaultStyle); + BringElement([BindingContext? context]) : super(context, defaultStyle: _boldDefaultStyle); } class AbbreviationElement extends Element { - AbbreviationElement([BindingContext? context]) - : super(context, defaultStyle: _abbrDefaultStyle); + AbbreviationElement([BindingContext? context]) : super(context, defaultStyle: _abbrDefaultStyle); } class EmphasisElement extends Element { - EmphasisElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + EmphasisElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } class CitationElement extends Element { - CitationElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + CitationElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } class DefinitionElement extends Element { - DefinitionElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + DefinitionElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i class IdiomaticElement extends Element { - IdiomaticElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + IdiomaticElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } class CodeElement extends Element { - CodeElement([BindingContext? context]) - : super(context, defaultStyle: _codeDefaultStyle); + CodeElement([BindingContext? context]) : super(context, defaultStyle: _codeDefaultStyle); } class SampleElement extends Element { - SampleElement([BindingContext? context]) - : super(context, defaultStyle: _codeDefaultStyle); + SampleElement([BindingContext? context]) : super(context, defaultStyle: _codeDefaultStyle); } class KeyboardElement extends Element { - KeyboardElement([BindingContext? context]) - : super(context, defaultStyle: _codeDefaultStyle); + KeyboardElement([BindingContext? context]) : super(context, defaultStyle: _codeDefaultStyle); } class SpanElement extends Element { - SpanElement([BindingContext? context]) - : super(context); + SpanElement([BindingContext? context]) : super(context); } class DataElement extends Element { - DataElement([BindingContext? context]) - : super(context); + DataElement([BindingContext? context]) : super(context); } // TODO: enclosed text is a short inline quotation class QuoteElement extends Element { - QuoteElement([BindingContext? context]) - : super(context); + QuoteElement([BindingContext? context]) : super(context); } class StrongElement extends Element { - StrongElement([BindingContext? context]) - : super(context, defaultStyle: _boldDefaultStyle); + StrongElement([BindingContext? context]) : super(context, defaultStyle: _boldDefaultStyle); } class TimeElement extends Element { - TimeElement([BindingContext? context]) - : super(context, defaultStyle: _boldDefaultStyle); + TimeElement([BindingContext? context]) : super(context, defaultStyle: _boldDefaultStyle); } class SmallElement extends Element { - SmallElement([BindingContext? context]) - : super(context, defaultStyle: _smallDefaultStyle); + SmallElement([BindingContext? context]) : super(context, defaultStyle: _smallDefaultStyle); } class StrikethroughElement extends Element { - StrikethroughElement([BindingContext? context]) - : super(context, defaultStyle: _sDefaultStyle); + StrikethroughElement([BindingContext? context]) : super(context, defaultStyle: _sDefaultStyle); } // https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-u-element class UnarticulatedElement extends Element { - UnarticulatedElement([BindingContext? context]) - : super(context, defaultStyle: _uDefaultStyle); + UnarticulatedElement([BindingContext? context]) : super(context, defaultStyle: _uDefaultStyle); } class VariableElement extends Element { - VariableElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + VariableElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } class MarkElement extends Element { - MarkElement([BindingContext? context]) - : super(context, defaultStyle: _markDefaultStyle); + MarkElement([BindingContext? context]) : super(context, defaultStyle: _markDefaultStyle); } diff --git a/webf/lib/src/dom/elements/template.dart b/webf/lib/src/dom/elements/template.dart index ba7a6d704d..6de756061f 100644 --- a/webf/lib/src/dom/elements/template.dart +++ b/webf/lib/src/dom/elements/template.dart @@ -1,9 +1,10 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/foundation.dart'; const String TEMPLATE = 'TEMPLATE'; @@ -12,6 +13,5 @@ const Map _defaultStyle = { }; class TemplateElement extends Element { - TemplateElement([BindingContext? context]) - : super(context, defaultStyle: _defaultStyle); + TemplateElement([BindingContext? context]) : super(context, defaultStyle: _defaultStyle); } diff --git a/webf/lib/src/dom/elements/text_form_control.dart b/webf/lib/src/dom/elements/text_form_control.dart index eab669748b..a3e393f770 100644 --- a/webf/lib/src/dom/elements/text_form_control.dart +++ b/webf/lib/src/dom/elements/text_form_control.dart @@ -1,22 +1,30 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; import 'dart:math' as math; import 'dart:ui'; +import 'package:characters/characters.dart' show CharacterRange; import 'package:flutter/animation.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; -import 'package:flutter/widgets.dart' show TextSelectionOverlay, TextSelectionControls, ClipboardStatusNotifier, TextEditingActionTarget; -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/gesture.dart'; -import 'package:kraken/rendering.dart'; -import 'package:kraken/widget.dart'; +import 'package:flutter/widgets.dart' + show + TextSelectionOverlay, + TextSelectionControls, + ClipboardStatusNotifier, + DirectionalTextEditingIntent, + ReplaceTextIntent; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/gesture.dart'; +import 'package:webf/rendering.dart'; +import 'package:webf/widget.dart'; const String VALUE = 'value'; const String DEFAULT_VALUE = 'defaultValue'; @@ -39,7 +47,7 @@ const Duration _kCursorBlinkWaitForStart = Duration(milliseconds: 150); const TextSelection blurSelection = TextSelection.collapsed(offset: -1); -class EditableTextDelegate with TextEditingActionTarget implements TextSelectionDelegate { +class EditableTextDelegate implements TextSelectionDelegate { final TextFormControlElement _textFormControlElement; EditableTextDelegate(this._textFormControlElement); @@ -48,15 +56,15 @@ class EditableTextDelegate with TextEditingActionTarget implements TextSelection @override TextEditingValue get textEditingValue => _textEditingValue; - @override - set textEditingValue(TextEditingValue value) { - // Deprecated, update the lasted value in the userUpdateTextEditingValue. - } + // Add alias for use in actions forked from Flutter source. + TextEditingValue get value => _textEditingValue; + TextFormControlElement get element => _textFormControlElement; + RenderEditable get renderEditable => _textFormControlElement.renderEditable!; + TextEditingValue get _textEditingValueforTextLayoutMetrics => _textEditingValue; @override void bringIntoView(TextPosition position) { - RenderEditable renderEditable = _textFormControlElement.renderEditable!; - KrakenScrollable _scrollable = _textFormControlElement._scrollable; + WebFScrollable _scrollable = _textFormControlElement._scrollable; final Rect localRect = renderEditable.getLocalRectForCaret(position); final RevealedOffset targetOffset = _textFormControlElement._getOffsetToRevealCaret(localRect); _scrollable.position!.jumpTo(targetOffset.offset); @@ -132,7 +140,12 @@ class EditableTextDelegate with TextEditingActionTarget implements TextSelection @override void copySelection(SelectionChangedCause cause) { - super.copySelection(cause); + final TextSelection selection = textEditingValue.selection; + final String text = textEditingValue.text; + if (selection.isCollapsed) { + return; + } + Clipboard.setData(ClipboardData(text: selection.textInside(text))); if (cause == SelectionChangedCause.toolbar) { bringIntoView(textEditingValue.selection.extent); hideToolbar(false); @@ -145,7 +158,7 @@ class EditableTextDelegate with TextEditingActionTarget implements TextSelection case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: - // Collapse the selection and hide the toolbar and handles. + // Collapse the selection and hide the toolbar and handles. userUpdateTextEditingValue( TextEditingValue( text: textEditingValue.text, @@ -160,7 +173,13 @@ class EditableTextDelegate with TextEditingActionTarget implements TextSelection @override void cutSelection(SelectionChangedCause cause) { - super.cutSelection(cause); + final TextSelection selection = textEditingValue.selection; + final String text = textEditingValue.text; + if (selection.isCollapsed) { + return; + } + Clipboard.setData(ClipboardData(text: selection.textInside(text))); + _replaceText(ReplaceTextIntent(textEditingValue, '', selection, cause)); if (cause == SelectionChangedCause.toolbar) { bringIntoView(textEditingValue.selection.extent); hideToolbar(); @@ -169,7 +188,18 @@ class EditableTextDelegate with TextEditingActionTarget implements TextSelection @override Future pasteText(SelectionChangedCause cause) async { - super.pasteText(cause); + final TextSelection selection = textEditingValue.selection; + if (!selection.isValid) { + return; + } + // Snapshot the input before using `await`. + // See https://github.com/flutter/flutter/issues/11427 + final ClipboardData? data = await Clipboard.getData(Clipboard.kTextPlain); + if (data == null) { + return; + } + + _replaceText(ReplaceTextIntent(textEditingValue, data.text!, selection, cause)); if (cause == SelectionChangedCause.toolbar) { bringIntoView(textEditingValue.selection.extent); hideToolbar(); @@ -178,57 +208,89 @@ class EditableTextDelegate with TextEditingActionTarget implements TextSelection @override void selectAll(SelectionChangedCause cause) async { - super.selectAll(cause); + userUpdateTextEditingValue( + textEditingValue.copyWith( + selection: TextSelection(baseOffset: 0, extentOffset: textEditingValue.text.length), + ), + cause, + ); if (cause == SelectionChangedCause.toolbar) { bringIntoView(textEditingValue.selection.extent); } } - @override - void debugAssertLayoutUpToDate() { - RenderEditable? editable = _textFormControlElement.renderEditable; - assert(editable != null); - editable!.debugAssertLayoutUpToDate(); + void _replaceText(ReplaceTextIntent intent) { + userUpdateTextEditingValue( + intent.currentTextEditingValue.replaced(intent.replacementRange, intent.replacementText), + intent.cause, + ); } + // --------------------------- Text Editing Actions --------------------------- - @override - bool get obscureText => _textFormControlElement.obscureText; - - @override - bool get readOnly => _textFormControlElement.readOnly; + TextBoundary characterBoundary(DirectionalTextEditingIntent intent) { + final TextBoundary atomicTextBoundary = element.obscureText ? CodeUnitBoundary(value) : CharacterBoundary(value); + return CollapsedSelectionBoundary(atomicTextBoundary, intent.forward); + } - @override - bool get selectionEnabled => _textFormControlElement.renderEditable?.selectionEnabled ?? false; + TextBoundary nextWordBoundary(DirectionalTextEditingIntent intent) { + final TextBoundary atomicTextBoundary; + final TextBoundary boundary; - @override - void setTextEditingValue(TextEditingValue newValue, SelectionChangedCause cause) { - if (newValue == textEditingValue) { - return; + if (element.obscureText) { + atomicTextBoundary = CodeUnitBoundary(value); + boundary = DocumentBoundary(value); + } else { + final TextEditingValue textEditingValue = _textEditingValueforTextLayoutMetrics; + atomicTextBoundary = CharacterBoundary(textEditingValue); + // This isn't enough. Newline characters. + boundary = + ExpandedTextBoundary(WhitespaceBoundary(textEditingValue), WordBoundary(renderEditable, textEditingValue)); } - RenderEditable? renderEditable = _textFormControlElement.renderEditable; - if (renderEditable != null) { - renderEditable.textSelectionDelegate.userUpdateTextEditingValue(newValue, cause); + final MixedBoundary mixedBoundary = + intent.forward ? MixedBoundary(atomicTextBoundary, boundary) : MixedBoundary(boundary, atomicTextBoundary); + // Use a MixedBoundary to make sure we don't leave invalid codepoints in + // the field after deletion. + return CollapsedSelectionBoundary(mixedBoundary, intent.forward); + } + + TextBoundary linebreak(DirectionalTextEditingIntent intent) { + final TextBoundary atomicTextBoundary; + final TextBoundary boundary; + + if (element.obscureText) { + atomicTextBoundary = CodeUnitBoundary(value); + boundary = DocumentBoundary(value); + } else { + final TextEditingValue textEditingValue = _textEditingValueforTextLayoutMetrics; + atomicTextBoundary = CharacterBoundary(textEditingValue); + boundary = LineBreak(renderEditable, textEditingValue); } + + // The MixedBoundary is to make sure we don't leave invalid code units in + // the field after deletion. + // `boundary` doesn't need to be wrapped in a CollapsedSelectionBoundary, + // since the document boundary is unique and the linebreak boundary is + // already caret-location based. + return intent.forward + ? MixedBoundary(CollapsedSelectionBoundary(atomicTextBoundary, true), boundary) + : MixedBoundary(boundary, CollapsedSelectionBoundary(atomicTextBoundary, false)); } - @override - TextLayoutMetrics get textLayoutMetrics => _textFormControlElement.renderEditable!; + TextBoundary documentBoundary(DirectionalTextEditingIntent intent) => DocumentBoundary(value); } class TextFormControlElement extends Element implements TextInputClient, TickerProvider { - - TextFormControlElement(context, { + TextFormControlElement( + context, { this.isMultiline = false, this.defaultStyle, this.isReplacedElement, }) : super(context, defaultStyle: _defaultStyle, isReplacedElement: true) { textSelectionDelegate = EditableTextDelegate(this); _textInputType = isMultiline ? TextInputType.multiline : TextInputType.text; - _scrollable = KrakenScrollable( - axisDirection: isMultiline ? AxisDirection.down : AxisDirection.right - ); + _scrollable = WebFScrollable(axisDirection: isMultiline ? AxisDirection.down : AxisDirection.right); scrollOffset = _scrollable.position; } @@ -244,13 +306,14 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP return 1; } } + Timer? _cursorTimer; bool _targetCursorVisibility = false; final ValueNotifier _cursorVisibilityNotifier = ValueNotifier(false); AnimationController? _cursorBlinkOpacityController; int _obscureShowCharTicksPending = 0; - late KrakenScrollable _scrollable; + late WebFScrollable _scrollable; ViewportOffset get scrollOffset => _scrollOffset; late ViewportOffset _scrollOffset = ViewportOffset.zero(); @@ -286,10 +349,9 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP TextSpan get placeholderTextSpan { // TODO: support ::placeholder pseudo element return _buildTextSpan( - text: placeholderText, - // The color of placeholder. - color: Color.fromARGB(255, 169, 169, 169) - ); + text: placeholderText, + // The color of placeholder. + color: Color.fromARGB(255, 169, 169, 169)); } TextInputConfiguration? _textInputConfiguration; @@ -518,12 +580,13 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP addEventListener(EVENT_DOUBLE_CLICK, _handleEditable); addEventListener(EVENT_LONG_PRESS, _handleEditable); - AnimationController animationController = _cursorBlinkOpacityController = AnimationController(vsync: this, duration: _fadeDuration); + AnimationController animationController = + _cursorBlinkOpacityController = AnimationController(vsync: this, duration: _fadeDuration); animationController.addListener(_onCursorColorTick); addChild(createRenderBox()); - SchedulerBinding.instance!.addPostFrameCallback((_) { + SchedulerBinding.instance.addPostFrameCallback((_) { if (autofocus) { focus(); } @@ -564,20 +627,19 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP void _onStyleChanged(String property, String? original, String present) { // Need to rebuild text span when text related style changed. - if (property == COLOR - || property == FONT_WEIGHT - || property == FONT_STYLE - || property == FONT_FAMILY - || property == FONT_SIZE - || property == LINE_HEIGHT - || property == LETTER_SPACING - || property == WORD_SPACING - || property == WHITE_SPACE - || property == TEXT_DECORATION_LINE - || property == TEXT_DECORATION_COLOR - || property == TEXT_DECORATION_STYLE - || property == TEXT_SHADOW - ) { + if (property == COLOR || + property == FONT_WEIGHT || + property == FONT_STYLE || + property == FONT_FAMILY || + property == FONT_SIZE || + property == LINE_HEIGHT || + property == LETTER_SPACING || + property == WORD_SPACING || + property == WHITE_SPACE || + property == TEXT_DECORATION_LINE || + property == TEXT_DECORATION_COLOR || + property == TEXT_DECORATION_STYLE || + property == TEXT_SHADOW) { _rebuildTextSpan(); } @@ -593,21 +655,18 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP textSelectionDelegate.userUpdateTextEditingValue(value, SelectionChangedCause.keyboard); TextSpan? text = obscureText ? _buildPasswordTextSpan(_actualText!.text!) : _actualText; if (renderEditable != null) { - renderEditable!.text = _actualText!.text!.isEmpty - ? placeholderTextSpan - : text; + renderEditable!.text = _actualText!.text!.isEmpty ? placeholderTextSpan : text; } } - TextSpan _buildTextSpan({ String? text, Color? color }) { + TextSpan _buildTextSpan({String? text, Color? color}) { return CSSTextMixin.createTextSpan(text ?? '', renderStyle, - color: color, - // For multiline editing, lineHeight works for inner text in the element, - // so it needs to set line-height of textSpan for RenderEditable to use. - height: isMultiline && renderStyle.lineHeight != CSSLengthValue.normal - ? renderStyle.lineHeight.computedValue / renderStyle.fontSize.computedValue - : null - ); + color: color, + // For multiline editing, lineHeight works for inner text in the element, + // so it needs to set line-height of textSpan for RenderEditable to use. + height: isMultiline && renderStyle.lineHeight != CSSLengthValue.normal + ? renderStyle.lineHeight.computedValue / renderStyle.fontSize.computedValue + : null); } TextSpan _buildPasswordTextSpan(String text) { @@ -625,15 +684,10 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP // Get the text size of text control form element by manually layout // cause RenderEditable does not expose textPainter. Size getTextSize() { - TextPainter textPainter = TextPainter( - text: renderEditable!.text, - maxLines: _maxLines, - textDirection: TextDirection.ltr - ); + TextPainter textPainter = + TextPainter(text: renderEditable!.text, maxLines: _maxLines, textDirection: TextDirection.ltr); - double maxWidth = isMultiline - ? renderEditable!.size.width - : double.infinity; + double maxWidth = isMultiline ? renderEditable!.size.width : double.infinity; textPainter.layout(maxWidth: maxWidth); @@ -649,12 +703,11 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP locale: CSSText.getLocale(), ); TextPainter painter = TextPainter( - text: TextSpan( - text: '0', - style: textStyle, - ), - textDirection: TextDirection.ltr - ); + text: TextSpan( + text: '0', + style: textStyle, + ), + textDirection: TextDirection.ltr); painter.layout(); List lineMetrics = painter.computeLineMetrics(); @@ -704,9 +757,7 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP } // Cache text size on touch start to be used in touch move and touch end. _textSize = getTextSize(); - } else if (event.type == EVENT_TOUCH_MOVE || - event.type == EVENT_TOUCH_END - ) { + } else if (event.type == EVENT_TOUCH_MOVE || event.type == EVENT_TOUCH_END) { TouchList touches = (event as TouchEvent).touches; if (touches.length > 1) return; @@ -715,8 +766,8 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP // Disable text selection and enable scrolling when text size is larger than // text form control element size. - if ((!isMultiline && (_textSize!.width > renderEditable!.size.width)) - || (isMultiline && (_textSize!.height > renderEditable!.size.height))) { + if ((!isMultiline && (_textSize!.width > renderEditable!.size.width)) || + (isMultiline && (_textSize!.height > renderEditable!.size.height))) { return; } @@ -772,9 +823,7 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP inputType: _textInputType, obscureText: obscureText, autocorrect: autoCorrect, - inputAction: _textInputType == TextInputType.multiline - ? TextInputAction.newline - : _textInputAction, + inputAction: _textInputType == TextInputType.multiline ? TextInputAction.newline : _textInputAction, textCapitalization: TextCapitalization.none, keyboardAppearance: Brightness.light, ); @@ -881,8 +930,7 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP // If this is a multiline EditableText, do nothing for a "newline" // action; The newline is already inserted. Otherwise, finalize // editing. - if (!isMultiline) - blur(); + if (!isMultiline) blur(); break; case TextInputAction.done: blur(); @@ -933,11 +981,9 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP TextEditingValue? _lastKnownRemoteTextEditingValue; void _updateRemoteEditingValueIfNeeded() { - if (_batchEditDepth > 0 || !_hasInputConnection) - return; + if (_batchEditDepth > 0 || !_hasInputConnection) return; final TextEditingValue localValue = _value; - if (localValue == _lastKnownRemoteTextEditingValue) - return; + if (localValue == _lastKnownRemoteTextEditingValue) return; _textInputConnection!.setEditingState(localValue); _lastKnownRemoteTextEditingValue = localValue; } @@ -947,8 +993,8 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP textSelectionDelegate._textEditingValue = value; } - int _batchEditDepth = 0; + /// Begins a new batch edit, within which new updates made to the text editing /// value will not be sent to the platform text input plugin. /// @@ -967,23 +1013,23 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP void endBatchEdit() { _batchEditDepth -= 1; assert( - _batchEditDepth >= 0, - 'Unbalanced call to endBatchEdit: beginBatchEdit must be called first.', + _batchEditDepth >= 0, + 'Unbalanced call to endBatchEdit: beginBatchEdit must be called first.', ); _updateRemoteEditingValueIfNeeded(); } - void _formatAndSetValue(TextEditingValue value, { + void _formatAndSetValue( + TextEditingValue value, { bool userInteraction = false, SelectionChangedCause? cause, }) { if (userInteraction && value.text.length > _maxLength) return; - final bool textChanged = _value.text != value.text - || (!_value.composing.isCollapsed && value.composing.isCollapsed); + final bool textChanged = + _value.text != value.text || (!_value.composing.isCollapsed && value.composing.isCollapsed); final bool selectionChanged = _value.selection != value.selection; - // Put all optional user callback invocations in a batch edit to prevent // sending multiple `TextInput.updateEditingValue` messages. beginBatchEdit(); @@ -994,9 +1040,7 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP // changed. Also, the user long pressing should always send a selection change // as well. if (selectionChanged || - (userInteraction && - (cause == SelectionChangedCause.longPress || - cause == SelectionChangedCause.keyboard))) { + (userInteraction && (cause == SelectionChangedCause.longPress || cause == SelectionChangedCause.keyboard))) { _handleSelectionChanged(value.selection, cause); } @@ -1051,7 +1095,7 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP // Show keyboard for selection change or user gestures. requestKeyboard(); - if (renderEditable == null) { + if (renderEditable == null || !renderEditable!.hasSize) { return; } @@ -1113,18 +1157,14 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP // Do nothing. } } - } bool _shouldShowSelectionHandles(SelectionChangedCause? cause) { - if (cause == SelectionChangedCause.keyboard) - return false; + if (cause == SelectionChangedCause.keyboard) return false; - if (cause == SelectionChangedCause.longPress || cause == SelectionChangedCause.drag) - return true; + if (cause == SelectionChangedCause.longPress || cause == SelectionChangedCause.drag) return true; - if (_value.text.isNotEmpty) - return true; + if (_value.text.isNotEmpty) return true; return false; } @@ -1144,7 +1184,7 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP @override void updateEditingValue(TextEditingValue value) { - _lastKnownRemoteTextEditingValue = value; + _lastKnownRemoteTextEditingValue = value; if (value == _value) { // This is possible, for example, when the numeric keyboard is input, @@ -1261,7 +1301,7 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP } _showCaretOnScreenScheduled = true; - SchedulerBinding.instance!.addPostFrameCallback((Duration _) { + SchedulerBinding.instance.addPostFrameCallback((Duration _) { _showCaretOnScreenScheduled = false; Rect? currentCaretRect = _currentCaretRect; if (currentCaretRect == null || renderEditable == null) { @@ -1305,9 +1345,10 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP // Make input box scroll to the offset that the caret shown. void scrollToCaret() { - SchedulerBinding.instance!.addPostFrameCallback((Duration _) { + SchedulerBinding.instance.addPostFrameCallback((Duration _) { final RevealedOffset targetOffset = _getOffsetToRevealCaret(_currentCaretRect!); - _scrollable.position!.animateTo(targetOffset.offset, duration: _caretAnimationDuration, curve: _caretAnimationCurve); + _scrollable.position! + .animateTo(targetOffset.offset, duration: _caretAnimationDuration, curve: _caretAnimationCurve); }); } @@ -1327,11 +1368,11 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP if (!isMultiline) { additionalOffset = rect.width >= editableSize.width - // Center `rect` if it's oversized. - ? editableSize.width / 2 - rect.center.dx - // Valid additional offsets range from (rect.right - size.width) - // to (rect.left). Pick the closest one if out of range. - : 0.0.clamp(rect.right - editableSize.width, rect.left); + // Center `rect` if it's oversized. + ? editableSize.width / 2 - rect.center.dx + // Valid additional offsets range from (rect.right - size.width) + // to (rect.left). Pick the closest one if out of range. + : 0.0.clamp(rect.right - editableSize.width, rect.left); unitOffset = const Offset(1, 0); } else { // The caret is vertically centered within the line. Expand the caret's @@ -1344,15 +1385,14 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP ); additionalOffset = expandedRect.height >= editableSize.height - ? editableSize.height / 2 - expandedRect.center.dy - : 0.0.clamp(expandedRect.bottom - editableSize.height, expandedRect.top); + ? editableSize.height / 2 - expandedRect.center.dy + : 0.0.clamp(expandedRect.bottom - editableSize.height, expandedRect.top); unitOffset = const Offset(0, 1); } // No over scrolling when encountering tall fonts/scripts that extend past // the ascent. - final double targetOffset = (additionalOffset + _scrollable.position!.pixels) - .clamp( + final double targetOffset = (additionalOffset + _scrollable.position!.pixels).clamp( _scrollable.position!.minScrollExtent, _scrollable.position!.maxScrollExtent, ); @@ -1457,5 +1497,299 @@ class TextFormControlElement extends Element implements TextInputClient, TickerP textEditingActionTarget = null; super.dispose(); } + + @override + void insertTextPlaceholder(Size size) { + // TODO: implement insertTextPlaceholder + } + + @override + void removeTextPlaceholder() { + // TODO: implement removeTextPlaceholder + } + + @override + void showToolbar() { + // TODO: implement showToolbar + } +} + +/// An interface for retriving the logical text boundary (left-closed-right-open) +/// at a given location in a document. +/// +/// Depending on the implementation of the [TextBoundary], the input +/// [TextPosition] can either point to a code unit, or a position between 2 code +/// units (which can be visually represented by the caret if the selection were +/// to collapse to that position). +/// +/// For example, [LineBreak] interprets the input [TextPosition] as a caret +/// location, since in Flutter the caret is generally painted between the +/// character the [TextPosition] points to and its previous character, and +/// [LineBreak] cares about the affinity of the input [TextPosition]. Most +/// other text boundaries however, interpret the input [TextPosition] as the +/// location of a code unit in the document, since it's easier to reason about +/// the text boundary given a code unit in the text. +/// +/// To convert a "code-unit-based" [TextBoundary] to "caret-location-based", +/// use the [CollapsedSelectionBoundary] combinator. +abstract class TextBoundary { + const TextBoundary(); + + TextEditingValue get textEditingValue; + + /// Returns the leading text boundary at the given location, inclusive. + TextPosition getLeadingTextBoundaryAt(TextPosition position); + + /// Returns the trailing text boundary at the given location, exclusive. + TextPosition getTrailingTextBoundaryAt(TextPosition position); + + TextRange getTextBoundaryAt(TextPosition position) { + return TextRange( + start: getLeadingTextBoundaryAt(position).offset, + end: getTrailingTextBoundaryAt(position).offset, + ); + } +} + +// ----------------------------- Text Boundaries ----------------------------- + +class CodeUnitBoundary extends TextBoundary { + const CodeUnitBoundary(this.textEditingValue); + + @override + final TextEditingValue textEditingValue; + + @override + TextPosition getLeadingTextBoundaryAt(TextPosition position) => TextPosition(offset: position.offset); + @override + TextPosition getTrailingTextBoundaryAt(TextPosition position) => + TextPosition(offset: math.min(position.offset + 1, textEditingValue.text.length)); +} + +// The word modifier generally removes the word boundaries around white spaces +// (and newlines), IOW white spaces and some other punctuations are considered +// a part of the next word in the search direction. +class WhitespaceBoundary extends TextBoundary { + const WhitespaceBoundary(this.textEditingValue); + + @override + final TextEditingValue textEditingValue; + + @override + TextPosition getLeadingTextBoundaryAt(TextPosition position) { + for (int index = position.offset; index >= 0; index -= 1) { + if (!TextLayoutMetrics.isWhitespace(textEditingValue.text.codeUnitAt(index))) { + return TextPosition(offset: index); + } + } + return const TextPosition(offset: 0); + } + + @override + TextPosition getTrailingTextBoundaryAt(TextPosition position) { + for (int index = position.offset; index < textEditingValue.text.length; index += 1) { + if (!TextLayoutMetrics.isWhitespace(textEditingValue.text.codeUnitAt(index))) { + return TextPosition(offset: index + 1); + } + } + return TextPosition(offset: textEditingValue.text.length); + } } +// Most apps delete the entire grapheme when the backspace key is pressed. +// Also always put the new caret location to character boundaries to avoid +// sending malformed UTF-16 code units to the paragraph builder. +class CharacterBoundary extends TextBoundary { + const CharacterBoundary(this.textEditingValue); + + @override + final TextEditingValue textEditingValue; + + @override + TextPosition getLeadingTextBoundaryAt(TextPosition position) { + final int endOffset = math.min(position.offset + 1, textEditingValue.text.length); + return TextPosition( + offset: CharacterRange.at(textEditingValue.text, position.offset, endOffset).stringBeforeLength, + ); + } + + @override + TextPosition getTrailingTextBoundaryAt(TextPosition position) { + final int endOffset = math.min(position.offset + 1, textEditingValue.text.length); + final CharacterRange range = CharacterRange.at(textEditingValue.text, position.offset, endOffset); + return TextPosition( + offset: textEditingValue.text.length - range.stringAfterLength, + ); + } + + @override + TextRange getTextBoundaryAt(TextPosition position) { + final int endOffset = math.min(position.offset + 1, textEditingValue.text.length); + final CharacterRange range = CharacterRange.at(textEditingValue.text, position.offset, endOffset); + return TextRange( + start: range.stringBeforeLength, + end: textEditingValue.text.length - range.stringAfterLength, + ); + } +} + +// [UAX #29](https://unicode.org/reports/tr29/) defined word boundaries. +class WordBoundary extends TextBoundary { + const WordBoundary(this.textLayout, this.textEditingValue); + + final TextLayoutMetrics textLayout; + + @override + final TextEditingValue textEditingValue; + + @override + TextPosition getLeadingTextBoundaryAt(TextPosition position) { + return TextPosition( + offset: textLayout.getWordBoundary(position).start, + // Word boundary seems to always report downstream on many platforms. + affinity: TextAffinity.downstream, // ignore: avoid_redundant_argument_values + ); + } + + @override + TextPosition getTrailingTextBoundaryAt(TextPosition position) { + return TextPosition( + offset: textLayout.getWordBoundary(position).end, + // Word boundary seems to always report downstream on many platforms. + affinity: TextAffinity.downstream, // ignore: avoid_redundant_argument_values + ); + } +} + +// The linebreaks of the current text layout. The input [TextPosition]s are +// interpreted as caret locations because [TextPainter.getLineAtOffset] is +// text-affinity-aware. +class LineBreak extends TextBoundary { + const LineBreak(this.textLayout, this.textEditingValue); + + final TextLayoutMetrics textLayout; + + @override + final TextEditingValue textEditingValue; + + @override + TextPosition getLeadingTextBoundaryAt(TextPosition position) { + return TextPosition( + offset: textLayout.getLineAtOffset(position).start, + ); + } + + @override + TextPosition getTrailingTextBoundaryAt(TextPosition position) { + return TextPosition( + offset: textLayout.getLineAtOffset(position).end, + affinity: TextAffinity.upstream, + ); + } +} + +// The document boundary is unique and is a constant function of the input +// position. +class DocumentBoundary extends TextBoundary { + const DocumentBoundary(this.textEditingValue); + + @override + final TextEditingValue textEditingValue; + + @override + TextPosition getLeadingTextBoundaryAt(TextPosition position) => const TextPosition(offset: 0); + @override + TextPosition getTrailingTextBoundaryAt(TextPosition position) { + return TextPosition( + offset: textEditingValue.text.length, + affinity: TextAffinity.upstream, + ); + } +} + +// ------------------------ Text Boundary Combinators ------------------------ + +// Expands the innerTextBoundary with outerTextBoundary. +class ExpandedTextBoundary extends TextBoundary { + ExpandedTextBoundary(this.innerTextBoundary, this.outerTextBoundary); + + final TextBoundary innerTextBoundary; + final TextBoundary outerTextBoundary; + + @override + TextEditingValue get textEditingValue { + assert(innerTextBoundary.textEditingValue == outerTextBoundary.textEditingValue); + return innerTextBoundary.textEditingValue; + } + + @override + TextPosition getLeadingTextBoundaryAt(TextPosition position) { + return outerTextBoundary.getLeadingTextBoundaryAt( + innerTextBoundary.getLeadingTextBoundaryAt(position), + ); + } + + @override + TextPosition getTrailingTextBoundaryAt(TextPosition position) { + return outerTextBoundary.getTrailingTextBoundaryAt( + innerTextBoundary.getTrailingTextBoundaryAt(position), + ); + } +} + +// Force the innerTextBoundary to interpret the input [TextPosition]s as caret +// locations instead of code unit positions. +// +// The innerTextBoundary must be a [TextBoundary] that interprets the input +// [TextPosition]s as code unit positions. +class CollapsedSelectionBoundary extends TextBoundary { + CollapsedSelectionBoundary(this.innerTextBoundary, this.isForward); + + final TextBoundary innerTextBoundary; + final bool isForward; + + @override + TextEditingValue get textEditingValue => innerTextBoundary.textEditingValue; + + @override + TextPosition getLeadingTextBoundaryAt(TextPosition position) { + return isForward + ? innerTextBoundary.getLeadingTextBoundaryAt(position) + : position.offset <= 0 + ? const TextPosition(offset: 0) + : innerTextBoundary.getLeadingTextBoundaryAt(TextPosition(offset: position.offset - 1)); + } + + @override + TextPosition getTrailingTextBoundaryAt(TextPosition position) { + return isForward + ? innerTextBoundary.getTrailingTextBoundaryAt(position) + : position.offset <= 0 + ? const TextPosition(offset: 0) + : innerTextBoundary.getTrailingTextBoundaryAt(TextPosition(offset: position.offset - 1)); + } +} + +// A TextBoundary that creates a [TextRange] where its start is from the +// specified leading text boundary and its end is from the specified trailing +// text boundary. +class MixedBoundary extends TextBoundary { + MixedBoundary(this.leadingTextBoundary, this.trailingTextBoundary); + + final TextBoundary leadingTextBoundary; + final TextBoundary trailingTextBoundary; + + @override + TextEditingValue get textEditingValue { + assert(leadingTextBoundary.textEditingValue == trailingTextBoundary.textEditingValue); + return leadingTextBoundary.textEditingValue; + } + + @override + TextPosition getLeadingTextBoundaryAt(TextPosition position) => + leadingTextBoundary.getLeadingTextBoundaryAt(position); + + @override + TextPosition getTrailingTextBoundaryAt(TextPosition position) => + trailingTextBoundary.getTrailingTextBoundaryAt(position); +} diff --git a/webf/lib/src/dom/elements/textarea.dart b/webf/lib/src/dom/elements/textarea.dart index 761034c1d9..253bbc8ede 100644 --- a/webf/lib/src/dom/elements/textarea.dart +++ b/webf/lib/src/dom/elements/textarea.dart @@ -1,9 +1,10 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -import 'package:kraken/foundation.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; +import 'package:webf/foundation.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; const String TEXTAREA = 'TEXTAREA'; const String ROWS = 'rows'; @@ -15,62 +16,114 @@ const Map _defaultStyle = { }; class TextareaElement extends TextFormControlElement { - TextareaElement(context) - : super(context, isMultiline: true, defaultStyle: _defaultStyle, isReplacedElement: true); + TextareaElement(context) : super(context, isMultiline: true, defaultStyle: _defaultStyle, isReplacedElement: true); // Bindings. @override getBindingProperty(String key) { switch (key) { - case 'width': return width; - case 'height': return height; - case 'rows': return rows; - case 'cols': return cols; - case 'value': return value; - case 'defaultValue': return defaultValue; - case 'autocomplete': return autocomplete; - case 'autofocus': return autofocus; - case 'required': return required; - case 'readonly': return readOnly; - case 'name': return name; - case 'disabled': return disabled; - case 'minLength': return minLength; - case 'maxLength': return maxLength; - case 'placeholder': return placeholder; - case 'inputMode': return inputMode; - default: return super.getBindingProperty(key); + case 'width': + return width; + case 'height': + return height; + case 'rows': + return rows; + case 'cols': + return cols; + case 'value': + return value; + case 'defaultValue': + return defaultValue; + case 'autocomplete': + return autocomplete; + case 'autofocus': + return autofocus; + case 'required': + return required; + case 'readonly': + return readOnly; + case 'name': + return name; + case 'disabled': + return disabled; + case 'minLength': + return minLength; + case 'maxLength': + return maxLength; + case 'placeholder': + return placeholder; + case 'inputMode': + return inputMode; + default: + return super.getBindingProperty(key); } } @override void setBindingProperty(String key, val) { switch (key) { - case 'width': width = castToType(val).toInt(); break; - case 'height': height = castToType(val).toInt(); break; - case 'rows': rows = castToType(val).toInt(); break; - case 'cols': cols = castToType(val).toInt(); break; - case 'value': value = castToType(val); break; - case 'defaultValue': defaultValue = castToType(val); break; - case 'autocomplete': autocomplete = castToType(val); break; - case 'autofocus': autofocus = castToType(val); break; - case 'required': required = castToType(val); break; - case 'readonly': readOnly = castToType(val); break; - case 'name': name = castToType(val); break; - case 'disabled': disabled = castToType(val); break; - case 'minLength': minLength = castToType(val).toInt(); break; - case 'maxLength': maxLength = castToType(val).toInt(); break; - case 'placeholder': placeholder = castToType(val); break; - case 'inputMode': inputMode = castToType(val); break; - default: super.setBindingProperty(key, value); + case 'width': + width = castToType(val).toInt(); + break; + case 'height': + height = castToType(val).toInt(); + break; + case 'rows': + rows = castToType(val).toInt(); + break; + case 'cols': + cols = castToType(val).toInt(); + break; + case 'value': + value = castToType(val); + break; + case 'defaultValue': + defaultValue = castToType(val); + break; + case 'autocomplete': + autocomplete = castToType(val); + break; + case 'autofocus': + autofocus = castToType(val); + break; + case 'required': + required = castToType(val); + break; + case 'readonly': + readOnly = castToType(val); + break; + case 'name': + name = castToType(val); + break; + case 'disabled': + disabled = castToType(val); + break; + case 'minLength': + minLength = castToType(val).toInt(); + break; + case 'maxLength': + maxLength = castToType(val).toInt(); + break; + case 'placeholder': + placeholder = castToType(val); + break; + case 'inputMode': + inputMode = castToType(val); + break; + default: + super.setBindingProperty(key, value); } } @override invokeBindingMethod(String method, List args) { switch (method) { - case 'focus': return focus(); - case 'blur': return blur(); - default: return super.invokeBindingMethod(method, args); + case 'focus': + return focus(); + case 'blur': + return blur(); + default: + return super.invokeBindingMethod(method, args); } } @@ -78,21 +131,51 @@ class TextareaElement extends TextFormControlElement { void setAttribute(String qualifiedName, String val) { super.setAttribute(qualifiedName, val); switch (qualifiedName) { - case 'width': width = attributeToProperty(val); break; - case 'height': height = attributeToProperty(val); break; - case 'rows': rows = attributeToProperty(val); break; - case 'cols': cols = attributeToProperty(val); break; - case 'value': defaultValue = attributeToProperty(val); break; - case 'autocomplete': autocomplete = attributeToProperty(val); break; - case 'autofocus': autofocus = attributeToProperty(val); break; - case 'required': required = attributeToProperty(val); break; - case 'readonly': readOnly = attributeToProperty(val); break; - case 'name': name = attributeToProperty(val); break; - case 'disabled': disabled = attributeToProperty(val); break; - case 'minlength': minLength = attributeToProperty(val); break; - case 'maxlength': maxLength = attributeToProperty(val); break; - case 'placeholder': placeholder = attributeToProperty(val); break; - case 'inputmode': inputMode = attributeToProperty(val); break; + case 'width': + width = attributeToProperty(val); + break; + case 'height': + height = attributeToProperty(val); + break; + case 'rows': + rows = attributeToProperty(val); + break; + case 'cols': + cols = attributeToProperty(val); + break; + case 'value': + defaultValue = attributeToProperty(val); + break; + case 'autocomplete': + autocomplete = attributeToProperty(val); + break; + case 'autofocus': + autofocus = attributeToProperty(val); + break; + case 'required': + required = attributeToProperty(val); + break; + case 'readonly': + readOnly = attributeToProperty(val); + break; + case 'name': + name = attributeToProperty(val); + break; + case 'disabled': + disabled = attributeToProperty(val); + break; + case 'minlength': + minLength = attributeToProperty(val); + break; + case 'maxlength': + maxLength = attributeToProperty(val); + break; + case 'placeholder': + placeholder = attributeToProperty(val); + break; + case 'inputmode': + inputMode = attributeToProperty(val); + break; } } @@ -127,9 +210,8 @@ class TextareaElement extends TextFormControlElement { double? get _defaultHeight { // rows defaults to 2. // https://html.spec.whatwg.org/multipage/form-elements.html#attr-textarea-rows - double computedLineHeight = renderStyle.lineHeight != CSSLengthValue.normal - ? renderStyle.lineHeight.computedValue - : avgCharHeight; + double computedLineHeight = + renderStyle.lineHeight != CSSLengthValue.normal ? renderStyle.lineHeight.computedValue : avgCharHeight; return computedLineHeight * double.parse(attributes[ROWS] ?? '2'); } @@ -193,4 +275,3 @@ class TextareaElement extends TextFormControlElement { } } } - diff --git a/webf/lib/src/dom/event.dart b/webf/lib/src/dom/event.dart index ac8d673535..45839178bb 100644 --- a/webf/lib/src/dom/event.dart +++ b/webf/lib/src/dom/event.dart @@ -1,21 +1,18 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:convert'; import 'dart:ffi'; import 'dart:typed_data'; import 'package:ffi/ffi.dart'; -import 'package:kraken/bridge.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/gesture.dart'; -import 'package:kraken/rendering.dart'; - -enum AppearEventType { - none, - appear, - disappear -} +import 'package:webf/bridge.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/gesture.dart'; +import 'package:webf/rendering.dart'; + +enum AppearEventType { none, appear, disappear } const String EVENT_CLICK = 'click'; const String EVENT_INPUT = 'input'; @@ -96,7 +93,9 @@ mixin ElementEventMixin on ElementBase { } bool _hasIntersectionObserverEvent() { - return hasEventListener(EVENT_APPEAR) || hasEventListener(EVENT_DISAPPEAR) || hasEventListener(EVENT_INTERSECTION_CHANGE); + return hasEventListener(EVENT_APPEAR) || + hasEventListener(EVENT_DISAPPEAR) || + hasEventListener(EVENT_INTERSECTION_CHANGE); } @override @@ -232,9 +231,7 @@ class PopStateEvent extends Event { @override Pointer toRaw([int methodLength = 0]) { - List methods = [ - stringToNativeString(jsonEncode(_popStateEventInit.state)).address - ]; + List methods = [stringToNativeString(jsonEncode(_popStateEventInit.state)).address]; Pointer rawEvent = super.toRaw(methods.length).cast(); Uint64List bytes = rawEvent.ref.bytes.asTypedList((rawEvent.ref.length + methods.length)); @@ -259,7 +256,8 @@ class MouseEvent extends Event { double get offsetY => _mouseEventInit.offsetY; MouseEvent(String type, MouseEventInit mouseEventInit) - : _mouseEventInit = mouseEventInit, super(type, mouseEventInit); + : _mouseEventInit = mouseEventInit, + super(type, mouseEventInit); @override Pointer toRaw([int methodLength = 0]) { @@ -291,8 +289,7 @@ class MouseEventInit extends EventInit { this.clientY = 0.0, this.offsetX = 0.0, this.offsetY = 0.0, - }) - : super(bubbles: bubbles, cancelable: cancelable); + }) : super(bubbles: bubbles, cancelable: cancelable); } class GestureEventInit extends EventInit { @@ -316,8 +313,7 @@ class GestureEventInit extends EventInit { this.velocityX = 0.0, this.velocityY = 0.0, this.scale = 0.0, - }) - : super(bubbles: bubbles, cancelable: cancelable); + }) : super(bubbles: bubbles, cancelable: cancelable); } /// reference: https://developer.mozilla.org/en-US/docs/Web/API/GestureEvent @@ -334,7 +330,8 @@ class GestureEvent extends Event { double get scale => _gestureEventInit.scale; GestureEvent(String type, GestureEventInit gestureEventInit) - : _gestureEventInit = gestureEventInit, super(type, gestureEventInit); + : _gestureEventInit = gestureEventInit, + super(type, gestureEventInit); @override Pointer toRaw([int methodLength = 0]) { @@ -360,7 +357,7 @@ class GestureEvent extends Event { class CustomEventInit extends EventInit { final String detail; - CustomEventInit({bool bubbles = false, bool cancelable = false, required this.detail }) + CustomEventInit({bool bubbles = false, bool cancelable = false, required this.detail}) : super(bubbles: bubbles, cancelable: cancelable); } @@ -371,13 +368,12 @@ class CustomEvent extends Event { String get detail => _customEventInit.detail; CustomEvent(String type, CustomEventInit customEventInit) - : _customEventInit = customEventInit, super(type, customEventInit); + : _customEventInit = customEventInit, + super(type, customEventInit); @override Pointer toRaw([int methodLength = 0]) { - List methods = [ - stringToNativeString(detail).address - ]; + List methods = [stringToNativeString(detail).address]; Pointer rawEvent = super.toRaw(methods.length).cast(); Uint64List bytes = rawEvent.ref.bytes.asTypedList((rawEvent.ref.length + methods.length)); @@ -397,10 +393,7 @@ class InputEvent extends Event { @override Pointer toRaw([int methodLength = 0]) { - List methods = [ - stringToNativeString(inputType).address, - stringToNativeString(data).address - ]; + List methods = [stringToNativeString(inputType).address, stringToNativeString(data).address]; Pointer rawEvent = super.toRaw(methods.length).cast(); Uint64List bytes = rawEvent.ref.bytes.asTypedList((rawEvent.ref.length + methods.length)); @@ -451,10 +444,7 @@ class MediaError extends Event { @override Pointer toRaw([int methodLength = 0]) { - List methods = [ - code, - stringToNativeString(message).address - ]; + List methods = [code, stringToNativeString(message).address]; Pointer rawEvent = super.toRaw(methods.length).cast(); Uint64List bytes = rawEvent.ref.bytes.asTypedList((rawEvent.ref.length + methods.length)); @@ -478,10 +468,7 @@ class MessageEvent extends Event { @override Pointer toRaw([int methodLength = 0]) { - List methods = [ - stringToNativeString(jsonEncode(data)).address, - stringToNativeString(origin).address - ]; + List methods = [stringToNativeString(jsonEncode(data)).address, stringToNativeString(origin).address]; Pointer rawEvent = super.toRaw(methods.length).cast(); Uint64List bytes = rawEvent.ref.bytes.asTypedList((rawEvent.ref.length + methods.length)); @@ -506,11 +493,7 @@ class CloseEvent extends Event { @override Pointer toRaw([int methodLength = 0]) { - List methods = [ - code, - stringToNativeString(reason).address, - wasClean ? 1 : 0 - ]; + List methods = [code, stringToNativeString(reason).address, wasClean ? 1 : 0]; Pointer rawEvent = super.toRaw(methods.length).cast(); Uint64List bytes = rawEvent.ref.bytes.asTypedList((rawEvent.ref.length + methods.length)); @@ -526,11 +509,10 @@ class IntersectionChangeEvent extends Event { @override Pointer toRaw([int methodLength = 0]) { - List methods = [ - doubleToUint64(intersectionRatio) - ]; + List methods = [doubleToUint64(intersectionRatio)]; - Pointer rawEvent = super.toRaw(methods.length).cast(); + Pointer rawEvent = + super.toRaw(methods.length).cast(); Uint64List bytes = rawEvent.ref.bytes.asTypedList((rawEvent.ref.length + methods.length)); bytes.setAll(rawEvent.ref.length, methods); @@ -645,7 +627,7 @@ class TouchList { return _items[index]; } - Touch operator[](int index) { + Touch operator [](int index) { return _items[index]; } @@ -655,8 +637,9 @@ class TouchList { } Pointer> toNative() { - Pointer> touchList = malloc.allocate(sizeOf() * _items.length).cast>(); - for (int i = 0; i < _items.length; i ++) { + Pointer> touchList = + malloc.allocate(sizeOf() * _items.length).cast>(); + for (int i = 0; i < _items.length; i++) { touchList[i] = _items[i].toNative(); } diff --git a/webf/lib/src/dom/event_target.dart b/webf/lib/src/dom/event_target.dart index 92563ab913..839e65dec5 100644 --- a/webf/lib/src/dom/event_target.dart +++ b/webf/lib/src/dom/event_target.dart @@ -1,10 +1,11 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/foundation.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/foundation.dart'; -import 'package:kraken/module.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/foundation.dart'; +import 'package:webf/module.dart'; typedef EventHandler = void Function(Event event); diff --git a/webf/lib/src/dom/node.dart b/webf/lib/src/dom/node.dart index 816cb645d2..b8db70e756 100644 --- a/webf/lib/src/dom/node.dart +++ b/webf/lib/src/dom/node.dart @@ -1,11 +1,12 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/foundation.dart'; -import 'package:kraken/widget.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/foundation.dart'; +import 'package:webf/widget.dart'; enum NodeType { ELEMENT_NODE, @@ -15,10 +16,7 @@ enum NodeType { DOCUMENT_FRAGMENT_NODE, } -enum RenderObjectManagerType { - FLUTTER_ELEMENT, - KRAKEN_NODE -} +enum RenderObjectManagerType { FLUTTER_ELEMENT, WEBF_NODE } /// [RenderObjectNode] provide the renderObject related abstract life cycle for /// [Node] or [Element]s, which wrap [RenderObject]s, which provide the actual @@ -76,9 +74,10 @@ abstract class LifecycleCallbacks { } abstract class Node extends EventTarget implements RenderObjectNode, LifecycleCallbacks { - KrakenElementToFlutterElementAdaptor? flutterElement; - KrakenElementToWidgetAdaptor? flutterWidget; + WebFElementToFlutterElementAdaptor? flutterElement; + WebFElementToWidgetAdaptor? flutterWidget; List childNodes = []; + /// The Node.parentNode read-only property returns the parent of the specified node in the DOM tree. Node? parentNode; NodeType nodeType; @@ -132,6 +131,7 @@ abstract class Node extends EventTarget implements RenderObjectNode, LifecycleCa if (index + 1 > parentNode!.childNodes.length - 1) return null; return parentNode!.childNodes[index + 1]; } + // Is child renderObject attached. bool get isRendererAttached => renderer != null && renderer!.attached; @@ -143,7 +143,7 @@ abstract class Node extends EventTarget implements RenderObjectNode, LifecycleCa void attachTo(Element parent, {RenderBox? after}) {} /// Unmount referenced render object. - void unmountRenderObject({ bool deep = false, bool keepFixedAlive = false }) {} + void unmountRenderObject({bool deep = false, bool keepFixedAlive = false}) {} /// Release any resources held by this node. @override @@ -268,7 +268,7 @@ abstract class Node extends EventTarget implements RenderObjectNode, LifecycleCa } /// Ensure child and child's child render object is attached. - void ensureChildAttached() { } + void ensureChildAttached() {} @override void connectedCallback() { @@ -294,7 +294,7 @@ abstract class Node extends EventTarget implements RenderObjectNode, LifecycleCa EventTarget? get parentEventTarget => parentNode; // Whether Kraken Node need to manage render object. - RenderObjectManagerType get renderObjectManagerType => RenderObjectManagerType.KRAKEN_NODE; + RenderObjectManagerType get renderObjectManagerType => RenderObjectManagerType.WEBF_NODE; } /// https://dom.spec.whatwg.org/#dom-node-nodetype diff --git a/webf/lib/src/dom/object_element_client.dart b/webf/lib/src/dom/object_element_client.dart index 17e4ee416d..fe26f1385a 100644 --- a/webf/lib/src/dom/object_element_client.dart +++ b/webf/lib/src/dom/object_element_client.dart @@ -1,9 +1,10 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/rendering.dart'; -import 'package:kraken/dom.dart'; +import 'package:webf/dom.dart'; typedef ObjectElementClientFactory = ObjectElementClient Function(ObjectElementHost objectElementHost); diff --git a/webf/lib/src/dom/screen.dart b/webf/lib/src/dom/screen.dart index 5febe0ea8f..80a639fd33 100644 --- a/webf/lib/src/dom/screen.dart +++ b/webf/lib/src/dom/screen.dart @@ -1,10 +1,10 @@ /* * Copyright (C) 2022-present Alibaba Inc. All rights reserved. - * Author: Kraken Team. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:ui'; -import 'package:kraken/foundation.dart'; +import 'package:webf/foundation.dart'; // As its name suggests, the Screen interface represents information about the screen of the output device. // https://drafts.csswg.org/cssom-view/#the-screen-interface @@ -14,11 +14,16 @@ class Screen extends BindingObject { @override getBindingProperty(String key) { switch (key) { - case 'availWidth': return availWidth; - case 'availHeight': return availHeight; - case 'width': return width; - case 'height': return height; - default: return super.getBindingProperty(key); + case 'availWidth': + return availWidth; + case 'availHeight': + return availHeight; + case 'width': + return width; + case 'height': + return height; + default: + return super.getBindingProperty(key); } } diff --git a/webf/lib/src/dom/sliver_manager.dart b/webf/lib/src/dom/sliver_manager.dart index bc4bf52832..03c0929bfc 100644 --- a/webf/lib/src/dom/sliver_manager.dart +++ b/webf/lib/src/dom/sliver_manager.dart @@ -1,17 +1,18 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/rendering.dart'; -import 'package:kraken/rendering.dart'; -import 'package:kraken/dom.dart'; +import 'package:webf/rendering.dart'; +import 'package:webf/dom.dart'; /// An implementation of [RenderSliverBoxChildManager] for sliver, /// manage element to implement lifecycles for sliver list, generate /// renderer from existing element tree. class RenderSliverElementChildManager implements RenderSliverBoxChildManager { // @NOTE: For hummer support, no real function here. - void restorePreparedChild(int index) { } - void stashPreparedChild(int index) { } + void restorePreparedChild(int index) {} + void stashPreparedChild(int index) {} final Element _target; late RenderSliverListLayout _sliverListLayout; @@ -85,9 +86,7 @@ class RenderSliverElementChildManager implements RenderSliverBoxChildManager { Iterable renderNodes = _renderNodes; if (index < renderNodes.length) { - renderNodes - .elementAt(index) - .unmountRenderObject(deep: true, keepFixedAlive: true); + renderNodes.elementAt(index).unmountRenderObject(deep: true, keepFixedAlive: true); return; } } @@ -108,25 +107,24 @@ class RenderSliverElementChildManager implements RenderSliverBoxChildManager { void didStartLayout() {} @override - double estimateMaxScrollOffset(SliverConstraints constraints, {int? firstIndex, int? lastIndex, double? leadingScrollOffset, double? trailingScrollOffset}) { - return _extrapolateMaxScrollOffset(firstIndex, lastIndex, - leadingScrollOffset, trailingScrollOffset, childCount)!; + double estimateMaxScrollOffset(SliverConstraints constraints, + {int? firstIndex, int? lastIndex, double? leadingScrollOffset, double? trailingScrollOffset}) { + return _extrapolateMaxScrollOffset(firstIndex, lastIndex, leadingScrollOffset, trailingScrollOffset, childCount)!; } static double? _extrapolateMaxScrollOffset( - int? firstIndex, - int? lastIndex, - double? leadingScrollOffset, - double? trailingScrollOffset, - int childCount, - ) { + int? firstIndex, + int? lastIndex, + double? leadingScrollOffset, + double? trailingScrollOffset, + int childCount, + ) { if (lastIndex == childCount - 1) { return trailingScrollOffset; } final int reifiedCount = lastIndex! - firstIndex! + 1; - final double averageExtent = - (trailingScrollOffset! - leadingScrollOffset!) / reifiedCount; + final double averageExtent = (trailingScrollOffset! - leadingScrollOffset!) / reifiedCount; final int remainingCount = childCount - lastIndex - 1; return trailingScrollOffset + averageExtent * remainingCount; } diff --git a/webf/lib/src/dom/text_node.dart b/webf/lib/src/dom/text_node.dart index a28a867be3..e1eb9f5876 100644 --- a/webf/lib/src/dom/text_node.dart +++ b/webf/lib/src/dom/text_node.dart @@ -1,10 +1,11 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/rendering.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/rendering.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/rendering.dart'; +import 'package:webf/foundation.dart'; const String WHITE_SPACE_CHAR = ' '; const String NEW_LINE_CHAR = '\n'; @@ -57,7 +58,7 @@ class TextNode extends Node { _renderTextBox!.renderStyle = _parentElement.renderStyle; _renderTextBox!.data = data; - KrakenRenderParagraph renderParagraph = _renderTextBox!.child as KrakenRenderParagraph; + WebFRenderParagraph renderParagraph = _renderTextBox!.child as WebFRenderParagraph; renderParagraph.markNeedsLayout(); RenderLayoutBox parentRenderLayoutBox = _parentElement.renderBoxModel as RenderLayoutBox; @@ -74,14 +75,15 @@ class TextNode extends Node { // Attach renderObject of current node to parent @override - void attachTo(Element parent, { RenderBox? after }) { + void attachTo(Element parent, {RenderBox? after}) { // Empty string of TextNode should not attach to render tree. if (_data.isEmpty) return; createRenderer(); // If element attach WidgetElement, render object should be attach to render tree when mount. - if (parent.renderObjectManagerType == RenderObjectManagerType.KRAKEN_NODE && parent.renderBoxModel is RenderLayoutBox) { + if (parent.renderObjectManagerType == RenderObjectManagerType.WEBF_NODE && + parent.renderBoxModel is RenderLayoutBox) { RenderLayoutBox parentRenderLayoutBox = parent.renderBoxModel as RenderLayoutBox; parentRenderLayoutBox = parentRenderLayoutBox.renderScrollingContent ?? parentRenderLayoutBox; parentRenderLayoutBox.insert(_renderTextBox!, after: after); @@ -101,7 +103,7 @@ class TextNode extends Node { // Detach renderObject of current node from parent @override - void unmountRenderObject({ bool deep = false, bool keepFixedAlive = false }) { + void unmountRenderObject({bool deep = false, bool keepFixedAlive = false}) { _detachRenderTextBox(); _renderTextBox = null; } diff --git a/webf/lib/src/dom/window.dart b/webf/lib/src/dom/window.dart index a89deae991..612a5ae995 100644 --- a/webf/lib/src/dom/window.dart +++ b/webf/lib/src/dom/window.dart @@ -1,13 +1,14 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:ui'; -import 'package:kraken/bridge.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/foundation.dart'; -import 'package:kraken/rendering.dart'; -import 'package:kraken/module.dart'; +import 'package:webf/bridge.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/foundation.dart'; +import 'package:webf/rendering.dart'; +import 'package:webf/module.dart'; const String WINDOW = 'WINDOW'; @@ -16,7 +17,8 @@ class Window extends EventTarget { final Screen screen; Window(BindingContext? context, this.document) - : screen = Screen(context), super(context); + : screen = Screen(context), + super(context); @override EventTarget? get parentEventTarget => null; @@ -25,14 +27,22 @@ class Window extends EventTarget { @override getBindingProperty(String key) { switch (key) { - case 'innerWidth': return innerWidth; - case 'innerHeight': return innerHeight; - case 'scrollX': return scrollX; - case 'scrollY': return scrollY; - case 'screen': return screen; - case 'colorScheme': return colorScheme; - case 'devicePixelRatio': return devicePixelRatio; - default: return super.getBindingProperty(key); + case 'innerWidth': + return innerWidth; + case 'innerHeight': + return innerHeight; + case 'scrollX': + return scrollX; + case 'scrollY': + return scrollY; + case 'screen': + return screen; + case 'colorScheme': + return colorScheme; + case 'devicePixelRatio': + return devicePixelRatio; + default: + return super.getBindingProperty(key); } } @@ -41,24 +51,19 @@ class Window extends EventTarget { switch (method) { case 'scroll': case 'scrollTo': - return scrollTo( - castToType(args[0]), - castToType(args[1]) - ); + return scrollTo(castToType(args[0]), castToType(args[1])); case 'scrollBy': - return scrollBy( - castToType(args[0]), - castToType(args[1]) - ); + return scrollBy(castToType(args[0]), castToType(args[1])); case 'open': return open(castToType(args[0])); - default: return super.invokeBindingMethod(method, args); + default: + return super.invokeBindingMethod(method, args); } } void open(String url) { String? sourceUrl = document.controller.view.rootController.url; - document.controller.view.handleNavigationAction(sourceUrl, url, KrakenNavigationType.navigate); + document.controller.view.handleNavigationAction(sourceUrl, url, WebFNavigationType.navigate); } double get scrollX => document.documentElement!.scrollLeft; @@ -97,7 +102,6 @@ class Window extends EventTarget { } } - @override void dispatchEvent(Event event) { // Events such as EVENT_DOM_CONTENT_LOADED need to ensure that listeners are flushed and registered. diff --git a/webf/lib/src/foundation/binding.dart b/webf/lib/src/foundation/binding.dart index bf24ced53a..f053bc25e7 100644 --- a/webf/lib/src/foundation/binding.dart +++ b/webf/lib/src/foundation/binding.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/foundation.dart'; diff --git a/webf/lib/src/foundation/bundle.dart b/webf/lib/src/foundation/bundle.dart index 923470d443..27808a7ba9 100644 --- a/webf/lib/src/foundation/bundle.dart +++ b/webf/lib/src/foundation/bundle.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:convert'; import 'dart:core'; @@ -8,9 +9,9 @@ import 'dart:typed_data'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; -import 'package:kraken/foundation.dart'; -import 'package:kraken/launcher.dart'; -import 'package:kraken/module.dart'; +import 'package:webf/foundation.dart'; +import 'package:webf/launcher.dart'; +import 'package:webf/module.dart'; const String DEFAULT_URL = 'about:blank'; const String UTF_8 = 'utf-8'; @@ -20,14 +21,14 @@ final ContentType _cssContentType = ContentType('text', 'css', charset: UTF_8); final ContentType _javascriptContentType = ContentType('text', 'javascript', charset: UTF_8); final ContentType _javascriptApplicationContentType = ContentType('application', 'javascript', charset: UTF_8); final ContentType _xJavascriptContentType = ContentType('application', 'x-javascript', charset: UTF_8); -final ContentType _krakenBc1ContentType = ContentType('application', 'vnd.kraken.bc1'); +final ContentType _webfBc1ContentType = ContentType('application', 'vnd.webf.bc1'); const List _supportedByteCodeVersions = ['1']; bool _isSupportedBytecode(String mimeType, Uri? uri) { if (uri != null) { - for (int i = 0; i < _supportedByteCodeVersions.length; i ++) { - if (mimeType.contains('application/vnd.kraken.bc' + _supportedByteCodeVersions[i])) return true; + for (int i = 0; i < _supportedByteCodeVersions.length; i++) { + if (mimeType.contains('application/vnd.webf.bc' + _supportedByteCodeVersions[i])) return true; // @NOTE: This is useful for most http server that did not recognize a .kbc1 file. // Simply treat some.kbc1 file as the bytecode. if (uri.path.endsWith('.kbc' + _supportedByteCodeVersions[i])) return true; @@ -39,7 +40,7 @@ bool _isSupportedBytecode(String mimeType, Uri? uri) { // The default accept request header. // The order is HTML -> KBC -> JavaScript. String _acceptHeader() { - String bc = _supportedByteCodeVersions.map((String v) => 'application/vnd.kraken.bc$v').join(','); + String bc = _supportedByteCodeVersions.map((String v) => 'application/vnd.webf.bc$v').join(','); return 'text/html,$bc,application/javascript'; } @@ -67,8 +68,8 @@ void _failedToResolveBundle(String url) { throw FlutterError('Failed to resolve bundle for $url'); } -abstract class KrakenBundle { - KrakenBundle(this.url); +abstract class WebFBundle { + WebFBundle(this.url); // Unique resource locator. final String url; @@ -94,7 +95,7 @@ abstract class KrakenBundle { // Source is input by user, do not trust it's a valid URL. _uri = Uri.tryParse(url); if (contextId != null && _uri != null) { - KrakenController? controller = KrakenController.getControllerOfJSContextId(contextId); + WebFController? controller = WebFController.getControllerOfJSContextId(contextId); if (controller != null) { _uri = controller.uriParser!.resolve(Uri.parse(controller.url), _uri!); } @@ -107,7 +108,7 @@ abstract class KrakenBundle { data = null; } - static KrakenBundle fromUrl(String url, { Map? additionalHttpHeaders }) { + static WebFBundle fromUrl(String url, {Map? additionalHttpHeaders}) { if (_isHttpScheme(url)) { return NetworkBundle(url, additionalHttpHeaders: additionalHttpHeaders); } else if (_isAssetsScheme(url)) { @@ -123,36 +124,37 @@ abstract class KrakenBundle { } } - static KrakenBundle fromContent(String content, { String url = DEFAULT_URL }) { + static WebFBundle fromContent(String content, {String url = DEFAULT_URL}) { return DataBundle.fromString(content, url, contentType: _javascriptContentType); } - static KrakenBundle fromBytecode(Uint8List data, { String url = DEFAULT_URL }) { - return DataBundle(data, url, contentType: _krakenBc1ContentType); + static WebFBundle fromBytecode(Uint8List data, {String url = DEFAULT_URL}) { + return DataBundle(data, url, contentType: _webfBc1ContentType); } bool get isHTML => contentType.mimeType == ContentType.html.mimeType; bool get isCSS => contentType.mimeType == _cssContentType.mimeType; - bool get isJavascript => contentType.mimeType == _javascriptContentType.mimeType || - contentType.mimeType == _javascriptApplicationContentType.mimeType || - contentType.mimeType == _xJavascriptContentType.mimeType; + bool get isJavascript => + contentType.mimeType == _javascriptContentType.mimeType || + contentType.mimeType == _javascriptApplicationContentType.mimeType || + contentType.mimeType == _xJavascriptContentType.mimeType; bool get isBytecode => _isSupportedBytecode(contentType.mimeType, _uri); } // The bundle that output input data. -class DataBundle extends KrakenBundle { - DataBundle(Uint8List data, String url, { ContentType? contentType }) : super(url) { +class DataBundle extends WebFBundle { + DataBundle(Uint8List data, String url, {ContentType? contentType}) : super(url) { this.data = data; this.contentType = contentType ?? ContentType.binary; } - DataBundle.fromString(String content, String url, { ContentType? contentType }) : super(url) { + DataBundle.fromString(String content, String url, {ContentType? contentType}) : super(url) { // Encode string to data by utf8. data = Uint8List.fromList(utf8.encode(content)); this.contentType = contentType ?? ContentType.text; } - DataBundle.fromDataUrl(String dataUrl, { ContentType? contentType }) : super(dataUrl) { + DataBundle.fromDataUrl(String dataUrl, {ContentType? contentType}) : super(dataUrl) { UriData uriData = UriData.parse(dataUrl); data = uriData.contentAsBytes(); this.contentType = contentType ?? ContentType.parse('${uriData.mimeType}; charset=${uriData.charset}'); @@ -160,7 +162,7 @@ class DataBundle extends KrakenBundle { } // The bundle that source from http or https. -class NetworkBundle extends KrakenBundle { +class NetworkBundle extends WebFBundle { // Do not access this field directly; use [_httpClient] instead. // We set `autoUncompress` to false to ensure that we can trust the value of // the `Content-CSSLength` HTTP header. We automatically uncompress the content @@ -169,8 +171,7 @@ class NetworkBundle extends KrakenBundle { ..userAgent = NavigatorModule.getUserAgent() ..autoUncompress = false; - NetworkBundle(String url, { this.additionalHttpHeaders }) - : super(url); + NetworkBundle(String url, {this.additionalHttpHeaders}) : super(url); Map? additionalHttpHeaders = {}; @@ -183,7 +184,7 @@ class NetworkBundle extends KrakenBundle { request.headers.set('Accept', _acceptHeader()); additionalHttpHeaders?.forEach(request.headers.set); if (contextId != null) { - KrakenHttpOverrides.setContextHeader(request.headers, contextId); + WebFHttpOverrides.setContextHeader(request.headers, contextId); } final HttpClientResponse response = await request.close(); @@ -198,11 +199,11 @@ class NetworkBundle extends KrakenBundle { } } -class AssetsBundle extends KrakenBundle with _ExtensionContentTypeResolver { +class AssetsBundle extends WebFBundle with _ExtensionContentTypeResolver { AssetsBundle(String url) : super(url); @override - Future resolve(int? contextId) async { + Future resolve(int? contextId) async { super.resolve(contextId); final Uri? _resolvedUri = resolvedUri; if (_resolvedUri != null) { @@ -230,11 +231,11 @@ class AssetsBundle extends KrakenBundle with _ExtensionContentTypeResolver { } /// The bundle that source from local io. -class FileBundle extends KrakenBundle with _ExtensionContentTypeResolver { +class FileBundle extends WebFBundle with _ExtensionContentTypeResolver { FileBundle(String url) : super(url); @override - Future resolve(int? contextId) async { + Future resolve(int? contextId) async { super.resolve(contextId); Uri uri = _uri!; @@ -250,9 +251,9 @@ class FileBundle extends KrakenBundle with _ExtensionContentTypeResolver { } } -/// [_ExtensionContentTypeResolver] is useful for [KrakenBundle] to determine +/// [_ExtensionContentTypeResolver] is useful for [WebFBundle] to determine /// content-type by uri's extension. -mixin _ExtensionContentTypeResolver on KrakenBundle { +mixin _ExtensionContentTypeResolver on WebFBundle { ContentType? _contentType; @override @@ -264,7 +265,7 @@ mixin _ExtensionContentTypeResolver on KrakenBundle { } else if (_isUriExt(uri, '.html')) { return ContentType.html; } else if (_isSupportedBytecode('', uri)) { - return _krakenBc1ContentType; + return _webfBc1ContentType; } else if (_isUriExt(uri, '.css')) { return _cssContentType; } diff --git a/webf/lib/src/foundation/convert.dart b/webf/lib/src/foundation/convert.dart index d0cdc10d14..a3cd647850 100644 --- a/webf/lib/src/foundation/convert.dart +++ b/webf/lib/src/foundation/convert.dart @@ -1,12 +1,13 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; import 'dart:convert'; import 'package:flutter/foundation.dart'; -FutureOr resolveStringFromData(final List data, { Codec codec = utf8, bool preferSync = false }) async { +FutureOr resolveStringFromData(final List data, {Codec codec = utf8, bool preferSync = false}) async { if (codec == utf8) { return _resolveUtf8StringFromData(data, preferSync); } else { diff --git a/webf/lib/src/foundation/environment.dart b/webf/lib/src/foundation/environment.dart index 1591452329..d106f1b14c 100644 --- a/webf/lib/src/foundation/environment.dart +++ b/webf/lib/src/foundation/environment.dart @@ -1,24 +1,24 @@ /* - * Copyright (C) 2020-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; -String? _krakenTemporaryPath; -Future getKrakenTemporaryPath() async { - if (_krakenTemporaryPath == null) { - String? temporaryDirectory = await getKrakenMethodChannel() - .invokeMethod('getTemporaryDirectory'); +String? _webfTemporaryPath; +Future getWebFTemporaryPath() async { + if (_webfTemporaryPath == null) { + String? temporaryDirectory = await getWebFMethodChannel().invokeMethod('getTemporaryDirectory'); if (temporaryDirectory == null) { throw FlutterError('Can\'t get temporary directory from native side.'); } - _krakenTemporaryPath = temporaryDirectory; + _webfTemporaryPath = temporaryDirectory; } - return _krakenTemporaryPath!; + return _webfTemporaryPath!; } -MethodChannel _methodChannel = const MethodChannel('kraken'); -MethodChannel getKrakenMethodChannel() { +MethodChannel _methodChannel = const MethodChannel('webf'); +MethodChannel getWebFMethodChannel() { return _methodChannel; } diff --git a/webf/lib/src/foundation/http_cache.dart b/webf/lib/src/foundation/http_cache.dart index 58e76eba3e..f95e4a7864 100644 --- a/webf/lib/src/foundation/http_cache.dart +++ b/webf/lib/src/foundation/http_cache.dart @@ -1,16 +1,16 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; import 'dart:collection'; import 'dart:io'; import 'package:async/async.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/foundation.dart'; import 'package:path/path.dart' as path; enum HttpCacheMode { - /// Default cache usage mode. If the navigation type doesn't impose any specific /// behavior, use cached resources when they are available and not expired, /// otherwise load resources from the network. @@ -25,7 +25,7 @@ enum HttpCacheMode { class HttpCacheController { // TODO: Add HTTP Cache for Windows and Linux - static HttpCacheMode mode = Platform.isLinux || Platform.isWindows ? HttpCacheMode.NO_CACHE : HttpCacheMode.DEFAULT; + static HttpCacheMode mode = Platform.isWindows ? HttpCacheMode.NO_CACHE : HttpCacheMode.DEFAULT; static final Map _controllers = HashMap(); @@ -35,7 +35,7 @@ class HttpCacheController { return _cacheDirectory!; } - final String appTemporaryPath = await getKrakenTemporaryPath(); + final String appTemporaryPath = await getWebFTemporaryPath(); final Directory cacheDirectory = Directory(path.join(appTemporaryPath, 'HttpCaches')); bool isThere = await cacheDirectory.exists(); if (!isThere) { @@ -72,7 +72,7 @@ class HttpCacheController { // A splay tree is a good choice for data that is stored and accessed frequently. final SplayTreeMap _caches = SplayTreeMap(); - HttpCacheController._(String origin, { int maxCachedObjects = 1000 }) + HttpCacheController._(String origin, {int maxCachedObjects = 1000}) : _origin = origin, _maxCachedObjects = maxCachedObjects; @@ -110,16 +110,13 @@ class HttpCacheController { _caches.remove(key); } - Future interceptResponse( - HttpClientRequest request, - HttpClientResponse response, - HttpCacheObject cacheObject, - HttpClient httpClient) async { + Future interceptResponse(HttpClientRequest request, HttpClientResponse response, + HttpCacheObject cacheObject, HttpClient httpClient) async { await cacheObject.updateIndex(response); // Negotiate cache with HTTP 304 if (response.statusCode == HttpStatus.notModified) { - HttpClientResponse? cachedResponse = await cacheObject.toHttpClientResponse(httpClient); + HttpClientResponse? cachedResponse = await cacheObject.toHttpClientResponse(httpClient); if (cachedResponse != null) { return cachedResponse; } @@ -127,12 +124,8 @@ class HttpCacheController { if (response.statusCode == HttpStatus.ok) { // Create cache object. - HttpCacheObject cacheObject = HttpCacheObject - .fromResponse( - _getCacheKey(request.uri), - response, - (await getCacheDirectory()).path - ); + HttpCacheObject cacheObject = + HttpCacheObject.fromResponse(_getCacheKey(request.uri), response, (await getCacheDirectory()).path); // Cache the object. if (cacheObject.valid) { @@ -183,10 +176,8 @@ class HttpClientCachedResponse extends Stream> implements HttpClientRe bool get isRedirect => response.isRedirect; @override - StreamSubscription> listen( - void Function(List event)? onData, { - Function? onError, void Function()? onDone, bool? cancelOnError - }) { + StreamSubscription> listen(void Function(List event)? onData, + {Function? onError, void Function()? onDone, bool? cancelOnError}) { _blobSink ??= cacheObject.openBlobWrite(); void _handleData(List data) { @@ -205,8 +196,7 @@ class HttpClientCachedResponse extends Stream> implements HttpClientRe } return _DelegatingStreamSubscription( - response.listen(_handleData, - onError: _handleError, onDone: _handleDone, cancelOnError: cancelOnError), + response.listen(_handleData, onError: _handleError, onDone: _handleDone, cancelOnError: cancelOnError), handleData: _handleData, handleDone: _handleDone, handleError: _handleError, @@ -253,11 +243,12 @@ class _DelegatingStreamSubscription extends DelegatingStreamSubscription> source, { + _DelegatingStreamSubscription( + StreamSubscription> source, { required void Function(List) handleData, required Function handleError, required void Function() handleDone, - }) :_handleData = handleData, + }) : _handleData = handleData, _handleError = handleError, _handleDone = handleDone, super(source); diff --git a/webf/lib/src/foundation/http_cache_object.dart b/webf/lib/src/foundation/http_cache_object.dart index 766392db60..bcf613ff16 100644 --- a/webf/lib/src/foundation/http_cache_object.dart +++ b/webf/lib/src/foundation/http_cache_object.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; @@ -56,7 +57,9 @@ class HttpCacheObject { bool _valid = false; bool get valid => _valid; - HttpCacheObject(this.url, this.cacheDirectory, { + HttpCacheObject( + this.url, + this.cacheDirectory, { this.headers, this.expiredTime, this.eTag, @@ -65,7 +68,7 @@ class HttpCacheObject { this.lastModified, this.origin, required this.hash, - }) : _file = File(path.join(cacheDirectory, '$hash')), + }) : _file = File(path.join(cacheDirectory, '$hash')), _blob = HttpCacheObjectBlob(path.join(cacheDirectory, '$hash-blob')); factory HttpCacheObject.fromResponse(String url, HttpClientResponse response, String cacheDirectory) { @@ -73,11 +76,11 @@ class HttpCacheObject { String? eTag = response.headers.value(HttpHeaders.etagHeader); int contentLength = response.headers.contentLength; String? lastModifiedValue = response.headers.value(HttpHeaders.lastModifiedHeader); - DateTime? lastModified = lastModifiedValue != null - ? tryParseHttpDate(lastModifiedValue) - : null; + DateTime? lastModified = lastModifiedValue != null ? tryParseHttpDate(lastModifiedValue) : null; - return HttpCacheObject(url, cacheDirectory, + return HttpCacheObject( + url, + cacheDirectory, headers: response.headers.toString(), eTag: eTag, expiredTime: expiredTime, @@ -253,7 +256,10 @@ class HttpCacheObject { // Index bytes format: // | Type x 1B | Reserved x 3B | bytesBuilder.add([ - NetworkType, Reserved, Reserved, Reserved, + NetworkType, + Reserved, + Reserved, + Reserved, ]); // | ExpiredTimeStamp x 8B | @@ -385,7 +391,6 @@ class HttpCacheObject { )..compressionState = _getCompressionState(httpClient, responseHeaders); } - static HttpClientResponseCompressionState _getCompressionState(HttpClient? httpClient, HttpHeaders responseHeaders) { if (httpClient != null && responseHeaders.value(HttpHeaders.contentEncodingHeader) == 'gzip') { return httpClient.autoUncompress @@ -406,13 +411,8 @@ class HttpCacheObject { // Consume stream. Completer completer = Completer(); - ByteConversionSink sink = ByteConversionSink.withCallback( - (bytes) => completer.complete(Uint8List.fromList(bytes))); - blobStream.listen( - sink.add, - onError: completer.completeError, - onDone: sink.close, - cancelOnError: true); + ByteConversionSink sink = ByteConversionSink.withCallback((bytes) => completer.complete(Uint8List.fromList(bytes))); + blobStream.listen(sink.add, onError: completer.completeError, onDone: sink.close, cancelOnError: true); return completer.future; } @@ -431,8 +431,7 @@ class HttpCacheObject { String? remoteLastModifiedString = response.headers.value(HttpHeaders.lastModifiedHeader); if (remoteLastModifiedString != null) { DateTime? remoteLastModified = tryParseHttpDate(remoteLastModifiedString); - if (remoteLastModified != null - && (lastModified == null || !remoteLastModified.isAtSameMomentAs(lastModified!))) { + if (remoteLastModified != null && (lastModified == null || !remoteLastModified.isAtSameMomentAs(lastModified!))) { lastModified = remoteLastModified; indexChanged = true; } diff --git a/webf/lib/src/foundation/http_client.dart b/webf/lib/src/foundation/http_client.dart index 27eb989318..068fd49b7b 100644 --- a/webf/lib/src/foundation/http_client.dart +++ b/webf/lib/src/foundation/http_client.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; @@ -9,11 +10,11 @@ import 'http_client_request.dart'; import 'http_overrides.dart'; class ProxyHttpClient implements HttpClient { - ProxyHttpClient(HttpClient nativeHttpClient, KrakenHttpOverrides httpOverrides) + ProxyHttpClient(HttpClient nativeHttpClient, WebFHttpOverrides httpOverrides) : _nativeHttpClient = nativeHttpClient, _httpOverrides = httpOverrides; - final KrakenHttpOverrides _httpOverrides; + final WebFHttpOverrides _httpOverrides; final HttpClient _nativeHttpClient; bool _closed = false; @@ -168,15 +169,25 @@ class ProxyHttpClient implements HttpClient { @override Future deleteUrl(Uri url) => _openUrl('delete', url); + + @override + set connectionFactory(Future> Function(Uri url, String? proxyHost, int? proxyPort)? f) { + // TODO: implement connectionFactory + } + + @override + set keyLog(Function(String line)? callback) { + // TODO: implement keyLog + } } -HttpHeaders createHttpHeaders({ Map>? initialHeaders }) { +HttpHeaders createHttpHeaders({Map>? initialHeaders}) { return _HttpHeaders(initialHeaders: initialHeaders); } class _HttpHeaders implements HttpHeaders { final Map> _headers = >{}; - _HttpHeaders({ Map>? initialHeaders }) { + _HttpHeaders({Map>? initialHeaders}) { if (initialHeaders != null) { _headers.addAll(initialHeaders); } @@ -355,7 +366,6 @@ class _HttpHeaders implements HttpHeaders { return values[0]; } - void _addAll(String name, value) { if (value is Iterable) { for (var v in value) { @@ -390,7 +400,8 @@ class _HttpHeaders implements HttpHeaders { if (hasValue) { sb.write('\n'); } - sb..write(name) + sb + ..write(name) ..write(': ') ..write(value); hasValue = true; diff --git a/webf/lib/src/foundation/http_client_interceptor.dart b/webf/lib/src/foundation/http_client_interceptor.dart index 4e82ec9efc..e6ec7c40ed 100644 --- a/webf/lib/src/foundation/http_client_interceptor.dart +++ b/webf/lib/src/foundation/http_client_interceptor.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:io'; diff --git a/webf/lib/src/foundation/http_client_request.dart b/webf/lib/src/foundation/http_client_request.dart index c9bc468e25..4c4f04ba2e 100644 --- a/webf/lib/src/foundation/http_client_request.dart +++ b/webf/lib/src/foundation/http_client_request.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; import 'dart:convert'; @@ -18,7 +19,7 @@ import 'queue.dart'; final _requestQueue = Queue(parallel: 10); class ProxyHttpClientRequest extends HttpClientRequest { - final KrakenHttpOverrides _httpOverrides; + final WebFHttpOverrides _httpOverrides; final HttpClient _nativeHttpClient; final String _method; final Uri _uri; @@ -32,11 +33,11 @@ class ProxyHttpClientRequest extends HttpClientRequest { // Saving request headers. final HttpHeaders _httpHeaders = createHttpHeaders(); - ProxyHttpClientRequest(String method, Uri uri, KrakenHttpOverrides httpOverrides, HttpClient nativeHttpClient) : - _method = method.toUpperCase(), - _uri = uri, - _httpOverrides = httpOverrides, - _nativeHttpClient = nativeHttpClient; + ProxyHttpClientRequest(String method, Uri uri, WebFHttpOverrides httpOverrides, HttpClient nativeHttpClient) + : _method = method.toUpperCase(), + _uri = uri, + _httpOverrides = httpOverrides, + _nativeHttpClient = nativeHttpClient; @override Encoding get encoding => _backendRequest?.encoding ?? utf8; @@ -55,12 +56,7 @@ class ProxyHttpClientRequest extends HttpClientRequest { Future addStream(Stream> stream) { // Consume stream. Completer completer = Completer(); - stream.listen( - _data.addAll, - onError: completer.completeError, - onDone: completer.complete, - cancelOnError: true - ); + stream.listen(_data.addAll, onError: completer.completeError, onDone: completer.complete, cancelOnError: true); return completer.future; } @@ -74,7 +70,8 @@ class ProxyHttpClientRequest extends HttpClientRequest { _backendRequest?.addError(error, stackTrace); } - Future _beforeRequest(HttpClientInterceptor _clientInterceptor, HttpClientRequest _clientRequest) async { + Future _beforeRequest( + HttpClientInterceptor _clientInterceptor, HttpClientRequest _clientRequest) async { try { return await _clientInterceptor.beforeRequest(_clientRequest); } catch (err, stack) { @@ -83,9 +80,7 @@ class ProxyHttpClientRequest extends HttpClientRequest { return null; } - Future _afterResponse( - HttpClientInterceptor _clientInterceptor, - HttpClientRequest _clientRequest, + Future _afterResponse(HttpClientInterceptor _clientInterceptor, HttpClientRequest _clientRequest, HttpClientResponse _clientResponse) async { try { return await _clientInterceptor.afterResponse(_clientRequest, _clientResponse); @@ -95,7 +90,8 @@ class ProxyHttpClientRequest extends HttpClientRequest { return null; } - Future _shouldInterceptRequest(HttpClientInterceptor _clientInterceptor, HttpClientRequest _clientRequest) async { + Future _shouldInterceptRequest( + HttpClientInterceptor _clientInterceptor, HttpClientRequest _clientRequest) async { try { return await _clientInterceptor.shouldInterceptRequest(_clientRequest); } catch (err, stack) { @@ -108,7 +104,7 @@ class ProxyHttpClientRequest extends HttpClientRequest { @override Future close() async { - int? contextId = KrakenHttpOverrides.getContextHeader(headers); + int? contextId = WebFHttpOverrides.getContextHeader(headers); HttpClientRequest request = this; if (contextId != null) { @@ -157,7 +153,9 @@ class ProxyHttpClientRequest extends HttpClientRequest { } // Step 3: Handle negotiate cache request header. - if (cacheObject.valid && headers.ifModifiedSince == null && headers.value(HttpHeaders.ifNoneMatchHeader) == null) { + if (cacheObject.valid && + headers.ifModifiedSince == null && + headers.value(HttpHeaders.ifNoneMatchHeader) == null) { // ETag has higher priority of lastModified. if (cacheObject.eTag != null) { headers.set(HttpHeaders.ifNoneMatchHeader, cacheObject.eTag!); @@ -184,8 +182,7 @@ class ProxyHttpClientRequest extends HttpClientRequest { bool hitNegotiateCache = false; // If cache only, but no cache hit, throw error directly. - if (HttpCacheController.mode == HttpCacheMode.CACHE_ONLY - && response == null) { + if (HttpCacheController.mode == HttpCacheMode.CACHE_ONLY && response == null) { throw FlutterError('HttpCacheMode is CACHE_ONLY, but no cache hit for $uri'); } @@ -195,7 +192,8 @@ class ProxyHttpClientRequest extends HttpClientRequest { final HttpClientResponse rawResponse = await _requestQueue.add(request.close); response = cacheObject == null ? rawResponse - : await HttpCacheController.instance(origin).interceptResponse(request, rawResponse, cacheObject, _nativeHttpClient); + : await HttpCacheController.instance(origin) + .interceptResponse(request, rawResponse, cacheObject, _nativeHttpClient); hitNegotiateCache = rawResponse != response; } @@ -216,11 +214,11 @@ class ProxyHttpClientRequest extends HttpClientRequest { if (cacheObject != null) { // Step 6: Intercept response by cache controller (handle 304). // Note: No need to negotiate cache here, this is final response, hit or not hit. - return HttpCacheController.instance(origin).interceptResponse(request, response, cacheObject, _nativeHttpClient); + return HttpCacheController.instance(origin) + .interceptResponse(request, response, cacheObject, _nativeHttpClient); } else { return response; } - } else { request = await _createBackendClientRequest(); // Not using request.add, because large data will cause core exception. @@ -246,11 +244,11 @@ class ProxyHttpClientRequest extends HttpClientRequest { // Assign configs for backend request. backendRequest - ..bufferOutput = bufferOutput - ..contentLength = contentLength - ..followRedirects = followRedirects - ..persistentConnection = persistentConnection - ..maxRedirects = maxRedirects; + ..bufferOutput = bufferOutput + ..contentLength = contentLength + ..followRedirects = followRedirects + ..persistentConnection = persistentConnection + ..maxRedirects = maxRedirects; _backendRequest = backendRequest; return backendRequest; @@ -264,10 +262,10 @@ class ProxyHttpClientRequest extends HttpClientRequest { @override Future get done async { - if (_backendRequest == null) { - await _createBackendClientRequest(); - } - return _backendRequest!.done; + if (_backendRequest == null) { + await _createBackendClientRequest(); + } + return _backendRequest!.done; } @override diff --git a/webf/lib/src/foundation/http_client_response.dart b/webf/lib/src/foundation/http_client_response.dart index 58d053fc0a..ff06ca49fb 100644 --- a/webf/lib/src/foundation/http_client_response.dart +++ b/webf/lib/src/foundation/http_client_response.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; import 'dart:io'; @@ -33,7 +34,8 @@ class HttpClientStreamResponse extends Stream> implements HttpClientRe final HttpHeaders _headers; - HttpClientStreamResponse(this._data, { + HttpClientStreamResponse( + this._data, { this.statusCode = HttpStatus.ok, this.reasonPhrase = '', this.compressionState = HttpClientResponseCompressionState.notCompressed, @@ -78,7 +80,8 @@ class HttpClientStreamResponse extends Stream> implements HttpClientRe List get redirects => const []; @override - StreamSubscription> listen(void Function(List event)? onData, { Function? onError, void Function()? onDone, bool? cancelOnError }) { + StreamSubscription> listen(void Function(List event)? onData, + {Function? onError, void Function()? onDone, bool? cancelOnError}) { return _data.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); } } diff --git a/webf/lib/src/foundation/http_overrides.dart b/webf/lib/src/foundation/http_overrides.dart index 792562fea8..ed92a607a2 100644 --- a/webf/lib/src/foundation/http_overrides.dart +++ b/webf/lib/src/foundation/http_overrides.dart @@ -1,19 +1,21 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:io'; -import 'package:kraken/kraken.dart'; +import 'package:webf/webf.dart'; // TODO: Don't use header to mark context. const String HttpHeaderContext = 'x-context'; -class KrakenHttpOverrides extends HttpOverrides { - static KrakenHttpOverrides? _instance; - KrakenHttpOverrides._(); +class WebFHttpOverrides extends HttpOverrides { + static WebFHttpOverrides? _instance; - factory KrakenHttpOverrides.instance() { - _instance ??= KrakenHttpOverrides._(); + WebFHttpOverrides._(); + + factory WebFHttpOverrides.instance() { + _instance ??= WebFHttpOverrides._(); return _instance!; } @@ -32,11 +34,11 @@ class KrakenHttpOverrides extends HttpOverrides { final HttpOverrides? parentHttpOverrides = HttpOverrides.current; final Map _contextIdToHttpClientInterceptorMap = {}; - void registerKrakenContext(int contextId, HttpClientInterceptor httpClientInterceptor) { + void registerWebFContext(int contextId, HttpClientInterceptor httpClientInterceptor) { _contextIdToHttpClientInterceptorMap[contextId] = httpClientInterceptor; } - bool unregisterKrakenContext(int contextId) { + bool unregisterWebFContext(int contextId) { // Returns true if [value] was in the map, false otherwise. return _contextIdToHttpClientInterceptorMap.remove(contextId) != null; } @@ -75,11 +77,11 @@ class KrakenHttpOverrides extends HttpOverrides { } } -KrakenHttpOverrides setupHttpOverrides(HttpClientInterceptor? httpClientInterceptor, { required int contextId }) { - final KrakenHttpOverrides httpOverrides = KrakenHttpOverrides.instance(); +WebFHttpOverrides setupHttpOverrides(HttpClientInterceptor? httpClientInterceptor, {required int contextId}) { + final WebFHttpOverrides httpOverrides = WebFHttpOverrides.instance(); if (httpClientInterceptor != null) { - httpOverrides.registerKrakenContext(contextId, httpClientInterceptor); + httpOverrides.registerWebFContext(contextId, httpClientInterceptor); } HttpOverrides.global = httpOverrides; @@ -88,8 +90,7 @@ KrakenHttpOverrides setupHttpOverrides(HttpClientInterceptor? httpClientIntercep // Returns the origin of the URI in the form scheme://host:port String getOrigin(Uri uri) { - if (uri.isScheme('http') - || uri.isScheme('https')) { + if (uri.isScheme('http') || uri.isScheme('https')) { return uri.origin; } else { return uri.path; @@ -98,7 +99,7 @@ String getOrigin(Uri uri) { // @TODO: Remove controller dependency. Uri getEntrypointUri(int? contextId) { - KrakenController? controller = KrakenController.getControllerOfJSContextId(contextId); + WebFController? controller = WebFController.getControllerOfJSContextId(contextId); String url = controller?.url ?? ''; - return Uri.tryParse(url) ?? KrakenController.fallbackBundleUri(contextId ?? 0); + return Uri.tryParse(url) ?? WebFController.fallbackBundleUri(contextId ?? 0); } diff --git a/webf/lib/src/foundation/queue.dart b/webf/lib/src/foundation/queue.dart index c5c0ae7232..7cb1007d71 100644 --- a/webf/lib/src/foundation/queue.dart +++ b/webf/lib/src/foundation/queue.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ // Original version: https://github.com/rknell/dart_queue import 'dart:async'; @@ -77,8 +78,7 @@ class Queue { } void _queueUpNext() { - if (_nextCycle.isNotEmpty && - _activeItems.length <= parallel) { + if (_nextCycle.isNotEmpty && _activeItems.length <= parallel) { final processId = _lastProcessId; _activeItems.add(processId); final item = _nextCycle.first; diff --git a/webf/lib/src/foundation/type.dart b/webf/lib/src/foundation/type.dart index 31a9a14a11..21789a45e8 100644 --- a/webf/lib/src/foundation/type.dart +++ b/webf/lib/src/foundation/type.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:ui'; diff --git a/webf/lib/src/foundation/uri_parser.dart b/webf/lib/src/foundation/uri_parser.dart index 231c87bd0f..3712551c2d 100644 --- a/webf/lib/src/foundation/uri_parser.dart +++ b/webf/lib/src/foundation/uri_parser.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ class UriParser { diff --git a/webf/lib/src/gesture/gesture_detector.dart b/webf/lib/src/gesture/gesture_detector.dart index c4e0e15fa8..6dabf7eee2 100644 --- a/webf/lib/src/gesture/gesture_detector.dart +++ b/webf/lib/src/gesture/gesture_detector.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ // Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be diff --git a/webf/lib/src/gesture/gesture_dispatcher.dart b/webf/lib/src/gesture/gesture_dispatcher.dart index 72af41cc32..4e60c39231 100644 --- a/webf/lib/src/gesture/gesture_dispatcher.dart +++ b/webf/lib/src/gesture/gesture_dispatcher.dart @@ -1,14 +1,15 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/gesture.dart'; -import 'package:kraken/src/scheduler/throttle.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/gesture.dart'; +import 'package:webf/src/scheduler/throttle.dart'; const int _MAX_STEP_MS = 16; @@ -20,7 +21,8 @@ class _DragEventInfo extends Drag { /// The pointer has moved. @override void update(DragUpdateDetails details) { - gestureDispatcher._handleGestureEvent(EVENT_DRAG, state: EVENT_STATE_UPDATE, deltaX: details.globalPosition.dx, deltaY: details.globalPosition.dy); + gestureDispatcher._handleGestureEvent(EVENT_DRAG, + state: EVENT_STATE_UPDATE, deltaX: details.globalPosition.dx, deltaY: details.globalPosition.dy); } /// The pointer is no longer in contact with the screen. @@ -29,7 +31,10 @@ class _DragEventInfo extends Drag { /// the screen is available in the `details`. @override void end(DragEndDetails details) { - gestureDispatcher._handleGestureEvent(EVENT_DRAG, state: EVENT_STATE_END, velocityX: details.velocity.pixelsPerSecond.dx, velocityY: details.velocity.pixelsPerSecond.dy); + gestureDispatcher._handleGestureEvent(EVENT_DRAG, + state: EVENT_STATE_END, + velocityX: details.velocity.pixelsPerSecond.dx, + velocityY: details.velocity.pixelsPerSecond.dy); } /// The input from the pointer is no longer directed towards this receiver. @@ -42,12 +47,7 @@ class _DragEventInfo extends Drag { } } -enum PointState { - Down, - Move, - Up, - Cancel -} +enum PointState { Down, Move, Up, Cancel } // The coordinate point at which a pointer (e.g finger or stylus) intersects the target surface of an interface. // This may apply to a finger touching a touch-screen, or an digital pen writing on a piece of paper. @@ -63,7 +63,8 @@ class TouchPoint { final double rotationAngle; final double force; - const TouchPoint(this.id, this.state, this.pos, this.screenPos, this.radiusX, this.radiusY, this.rotationAngle, this.force); + const TouchPoint( + this.id, this.state, this.pos, this.screenPos, this.radiusX, this.radiusY, this.rotationAngle, this.force); } class GestureDispatcher { @@ -87,8 +88,7 @@ class GestureDispatcher { ..onUpdate = _onScaleUpdate ..onEnd = _onScaleEnd; // Drag Recognizer - _gestureRecognizers[EVENT_DRAG] = ImmediateMultiDragGestureRecognizer() - ..onStart = _onDragStart; + _gestureRecognizers[EVENT_DRAG] = ImmediateMultiDragGestureRecognizer()..onStart = _onDragStart; _dragEventInfo = _DragEventInfo(this); } @@ -107,6 +107,7 @@ class GestureDispatcher { void _bindEventTargetWithTouchPoint(TouchPoint touchPoint, EventTarget eventTarget) { _pointTargets[touchPoint.id] = eventTarget; } + void _unbindEventTargetWithTouchPoint(TouchPoint touchPoint) { _pointTargets.remove(touchPoint.id); } @@ -123,22 +124,15 @@ class GestureDispatcher { pointState = PointState.Cancel; } - return TouchPoint( - pointerEvent.pointer, - pointState, - pointerEvent.localPosition, - pointerEvent.position, - pointerEvent.radiusMajor, - pointerEvent.radiusMinor, - pointerEvent.orientation, - pointerEvent.pressure - ); + return TouchPoint(pointerEvent.pointer, pointState, pointerEvent.localPosition, pointerEvent.position, + pointerEvent.radiusMajor, pointerEvent.radiusMinor, pointerEvent.orientation, pointerEvent.pressure); } final Map _touchPoints = {}; void _addPoint(TouchPoint touchPoint) { _touchPoints[touchPoint.id] = touchPoint; } + void _removePoint(TouchPoint touchPoint) { _touchPoints.remove(touchPoint.id); } @@ -184,9 +178,11 @@ class GestureDispatcher { }); } - void handlePointerEvent(PointerEvent event) { - if (!(event is PointerDownEvent || event is PointerUpEvent || event is PointerMoveEvent || event is PointerCancelEvent)) { + if (!(event is PointerDownEvent || + event is PointerUpEvent || + event is PointerMoveEvent || + event is PointerCancelEvent)) { // Only basic Point events are handled, other event does nothing and returns directly such as hover and scroll. return; } @@ -277,19 +273,25 @@ class GestureDispatcher { } void _onSwipe(SwipeDetails details) { - _handleGestureEvent(EVENT_SWIPE, velocityX: details.velocity.pixelsPerSecond.dx, velocityY: details.velocity.pixelsPerSecond.dy); + _handleGestureEvent(EVENT_SWIPE, + velocityX: details.velocity.pixelsPerSecond.dx, velocityY: details.velocity.pixelsPerSecond.dy); } void _onPanStart(DragStartDetails details) { - _handleGestureEvent(EVENT_PAN, state: EVENT_STATE_START, deltaX: details.globalPosition.dx, deltaY: details.globalPosition.dy); + _handleGestureEvent(EVENT_PAN, + state: EVENT_STATE_START, deltaX: details.globalPosition.dx, deltaY: details.globalPosition.dy); } void _onPanUpdate(DragUpdateDetails details) { - _handleGestureEvent(EVENT_PAN, state: EVENT_STATE_UPDATE, deltaX: details.globalPosition.dx, deltaY: details.globalPosition.dy); + _handleGestureEvent(EVENT_PAN, + state: EVENT_STATE_UPDATE, deltaX: details.globalPosition.dx, deltaY: details.globalPosition.dy); } void _onPanEnd(DragEndDetails details) { - _handleGestureEvent(EVENT_PAN, state: EVENT_STATE_END, velocityX: details.velocity.pixelsPerSecond.dx, velocityY: details.velocity.pixelsPerSecond.dy); + _handleGestureEvent(EVENT_PAN, + state: EVENT_STATE_END, + velocityX: details.velocity.pixelsPerSecond.dx, + velocityY: details.velocity.pixelsPerSecond.dy); } void _onScaleStart(ScaleStartDetails details) { @@ -309,7 +311,8 @@ class GestureDispatcher { return _dragEventInfo; } - void _handleMouseEvent(String type, { + void _handleMouseEvent( + String type, { Offset localPosition = Offset.zero, Offset globalPosition = Offset.zero, bool bubbles = true, @@ -330,39 +333,40 @@ class GestureDispatcher { double clientX = globalOffset.dx; double clientY = globalOffset.dy; - Event event = MouseEvent(type, - MouseEventInit( - bubbles: bubbles, - cancelable: cancelable, - clientX: clientX, - clientY: clientY, - offsetX: localPosition.dx, - offsetY: localPosition.dy, - ) - ); + Event event = MouseEvent( + type, + MouseEventInit( + bubbles: bubbles, + cancelable: cancelable, + clientX: clientX, + clientY: clientY, + offsetX: localPosition.dx, + offsetY: localPosition.dy, + )); _target?.dispatchEvent(event); } - void _handleGestureEvent(String type, { - String state = '', - String direction = '', - double rotation = 0.0, - double deltaX = 0.0, - double deltaY = 0.0, - double velocityX = 0.0, - double velocityY = 0.0, - double scale = 0.0 - }) { - Event event = GestureEvent(type, GestureEventInit( - state: state, - direction: direction, - rotation: rotation, - deltaX: deltaX, - deltaY: deltaY, - velocityX: velocityX, - velocityY: velocityY, - scale: scale, - )); + void _handleGestureEvent(String type, + {String state = '', + String direction = '', + double rotation = 0.0, + double deltaX = 0.0, + double deltaY = 0.0, + double velocityX = 0.0, + double velocityY = 0.0, + double scale = 0.0}) { + Event event = GestureEvent( + type, + GestureEventInit( + state: state, + direction: direction, + rotation: rotation, + deltaX: deltaX, + deltaY: deltaY, + velocityX: velocityX, + velocityY: velocityY, + scale: scale, + )); _target?.dispatchEvent(event); } @@ -398,7 +402,6 @@ class GestureDispatcher { e.touches.append(touch); } - if (eventType == EVENT_TOUCH_MOVE) { _throttler.throttle(() { _pointTargets[currentTouchPoint.id]?.dispatchEvent(e); diff --git a/webf/lib/src/gesture/monodrag.dart b/webf/lib/src/gesture/monodrag.dart index 880b96e944..d42e7f5058 100644 --- a/webf/lib/src/gesture/monodrag.dart +++ b/webf/lib/src/gesture/monodrag.dart @@ -1,14 +1,14 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ // Modified from Flutter gesture/monodrag.dart. // Copyright 2014 The Flutter Authors. All rights reserved. import 'package:flutter/gestures.dart'; - import 'package:flutter/rendering.dart'; -import 'package:kraken/dom.dart'; +import 'package:webf/dom.dart'; typedef IsAcceptedDragCallback = bool Function(AxisDirection direction); @@ -51,6 +51,7 @@ abstract class CompetitiveDragGestureRecognizer extends OneSequenceGestureRecogn }) : super(debugOwner: debugOwner, supportedDevices: supportedDevices); static VelocityTracker _defaultBuilder(PointerEvent event) => VelocityTracker.withKind(event.kind); + /// Configure the behavior of offsets sent to [onStart]. /// /// If set to [DragStartBehavior.start], the [onStart] callback will be called @@ -214,12 +215,7 @@ abstract class CompetitiveDragGestureRecognizer extends OneSequenceGestureRecogn if (_initialButtons == null) { switch (event.buttons) { case kPrimaryButton: - if (onDown == null && - onStart == null && - onUpdate == null && - onEnd == null && - onCancel == null) - return false; + if (onDown == null && onStart == null && onUpdate == null && onEnd == null && onCancel == null) return false; break; default: return false; @@ -254,8 +250,7 @@ abstract class CompetitiveDragGestureRecognizer extends OneSequenceGestureRecogn @override void handleEvent(PointerEvent event) { assert(_state != _DragState.ready); - if (!event.synthesized - && (event is PointerDownEvent || event is PointerMoveEvent)) { + if (!event.synthesized && (event is PointerDownEvent || event is PointerMoveEvent)) { final VelocityTracker tracker = _velocityTrackers[event.pointer]!; tracker.addPosition(event.timeStamp, event.localPosition); } @@ -283,10 +278,11 @@ abstract class CompetitiveDragGestureRecognizer extends OneSequenceGestureRecogn final Offset movedLocally = _getDeltaForDetails(event.localDelta); final Matrix4? localToGlobalTransform = event.transform == null ? null : Matrix4.tryInvert(event.transform!); _globalDistanceMoved += PointerEvent.transformDeltaViaPositions( - transform: localToGlobalTransform, - untransformedDelta: movedLocally, - untransformedEndPosition: event.localPosition, - ).distance * (_getPrimaryValueFromOffset(movedLocally)).sign; + transform: localToGlobalTransform, + untransformedDelta: movedLocally, + untransformedEndPosition: event.localPosition, + ).distance * + (_getPrimaryValueFromOffset(movedLocally)).sign; if (_hasSufficientGlobalDistanceToAccept(event.kind) && _acceptDragGesture(event)) resolve(GestureDisposition.accepted); } @@ -294,7 +290,7 @@ abstract class CompetitiveDragGestureRecognizer extends OneSequenceGestureRecogn if (event is PointerUpEvent || event is PointerCancelEvent) { _giveUpPointer( event.pointer, - reject: event is PointerCancelEvent || _state ==_DragState.possible, + reject: event is PointerCancelEvent || _state == _DragState.possible, ); } } @@ -348,7 +344,7 @@ abstract class CompetitiveDragGestureRecognizer extends OneSequenceGestureRecogn @override void didStopTrackingLastPointer(int pointer) { assert(_state != _DragState.ready); - switch(_state) { + switch (_state) { case _DragState.ready: break; @@ -382,8 +378,7 @@ abstract class CompetitiveDragGestureRecognizer extends OneSequenceGestureRecogn globalPosition: _initialPosition.global, localPosition: _initialPosition.local, ); - if (onDown != null) - invokeCallback('onDown', () => onDown!(details)); + if (onDown != null) invokeCallback('onDown', () => onDown!(details)); } void _checkStart(Duration? timestamp) { @@ -393,8 +388,7 @@ abstract class CompetitiveDragGestureRecognizer extends OneSequenceGestureRecogn globalPosition: _initialPosition.global, localPosition: _initialPosition.local, ); - if (onStart != null) - invokeCallback('onStart', () => onStart!(details)); + if (onStart != null) invokeCallback('onStart', () => onStart!(details)); } void _checkUpdate({ @@ -412,14 +406,12 @@ abstract class CompetitiveDragGestureRecognizer extends OneSequenceGestureRecogn globalPosition: globalPosition, localPosition: localPosition, ); - if (onUpdate != null) - invokeCallback('onUpdate', () => onUpdate!(details)); + if (onUpdate != null) invokeCallback('onUpdate', () => onUpdate!(details)); } void _checkEnd(int pointer) { assert(_initialButtons == kPrimaryButton); - if (onEnd == null) - return; + if (onEnd == null) return; final VelocityTracker tracker = _velocityTrackers[pointer]!; @@ -443,8 +435,7 @@ abstract class CompetitiveDragGestureRecognizer extends OneSequenceGestureRecogn primaryVelocity: 0.0, ); debugReport = () { - if (estimate == null) - return 'Could not estimate velocity.'; + if (estimate == null) return 'Could not estimate velocity.'; return '$estimate; judged to not be a fling.'; }; } @@ -454,8 +445,7 @@ abstract class CompetitiveDragGestureRecognizer extends OneSequenceGestureRecogn void _checkCancel() { assert(_initialButtons == kPrimaryButton); - if (onCancel != null) - invokeCallback('onCancel', onCancel!); + if (onCancel != null) invokeCallback('onCancel', onCancel!); } @override @@ -463,6 +453,7 @@ abstract class CompetitiveDragGestureRecognizer extends OneSequenceGestureRecogn _velocityTrackers.clear(); super.dispose(); } + @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); @@ -512,7 +503,6 @@ class ScrollVerticalDragGestureRecognizer extends CompetitiveDragGestureRecogniz String get debugDescription => 'scroll vertical drag'; } - /// Recognizes movement in the horizontal direction. /// /// Used for horizontal scrolling. diff --git a/webf/lib/src/gesture/scroll_activity.dart b/webf/lib/src/gesture/scroll_activity.dart index 9e59221367..09303fdbbc 100644 --- a/webf/lib/src/gesture/scroll_activity.dart +++ b/webf/lib/src/gesture/scroll_activity.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ // Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be diff --git a/webf/lib/src/gesture/scroll_context.dart b/webf/lib/src/gesture/scroll_context.dart index 29ac124aa6..e67db6dd44 100644 --- a/webf/lib/src/gesture/scroll_context.dart +++ b/webf/lib/src/gesture/scroll_context.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ // Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be diff --git a/webf/lib/src/gesture/scroll_metrics.dart b/webf/lib/src/gesture/scroll_metrics.dart index d48e5f4e4f..b5edb2526d 100644 --- a/webf/lib/src/gesture/scroll_metrics.dart +++ b/webf/lib/src/gesture/scroll_metrics.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ // Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be @@ -118,9 +119,11 @@ abstract class ScrollMetrics { assert(minScrollExtent <= maxScrollExtent); return viewportDimension // "above" overscroll value - - (minScrollExtent - pixels).clamp(0, viewportDimension) + - + (minScrollExtent - pixels).clamp(0, viewportDimension) // "below" overscroll value - - (pixels - maxScrollExtent).clamp(0, viewportDimension); + - + (pixels - maxScrollExtent).clamp(0, viewportDimension); } /// The quantity of content conceptually "below" the viewport in the scrollable. @@ -139,7 +142,7 @@ class FixedScrollMetrics with ScrollMetrics { required double? pixels, required double? viewportDimension, required this.axisDirection, - }) : _minScrollExtent = minScrollExtent, + }) : _minScrollExtent = minScrollExtent, _maxScrollExtent = maxScrollExtent, _pixels = pixels, _viewportDimension = viewportDimension; diff --git a/webf/lib/src/gesture/scroll_physics.dart b/webf/lib/src/gesture/scroll_physics.dart index ab3c35884f..d6f69d1d5d 100644 --- a/webf/lib/src/gesture/scroll_physics.dart +++ b/webf/lib/src/gesture/scroll_physics.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ // Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be @@ -46,7 +47,7 @@ class ScrollPhysics { static ScrollPhysicsFactory? scrollPhysicsFactory; // Automatically determine scroll physics due to devices. - static ScrollPhysics createScrollPhysics({ ScrollPhysics? parent }) { + static ScrollPhysics createScrollPhysics({ScrollPhysics? parent}) { if (scrollPhysicsFactory != null) { return scrollPhysicsFactory!(parent); } else if (Platform.isIOS || Platform.isMacOS) { @@ -58,7 +59,7 @@ class ScrollPhysics { } /// Creates an object with the default scroll physics. - const ScrollPhysics({ this.parent }); + const ScrollPhysics({this.parent}); /// If non-null, determines the default behavior for each method. /// @@ -421,7 +422,7 @@ class BouncingScrollPhysics extends ScrollPhysics { class ClampingScrollPhysics extends ScrollPhysics { /// Creates scroll physics that prevent the scroll offset from exceeding the /// bounds of the content. - const ClampingScrollPhysics({ ScrollPhysics? parent }) : super(parent: parent); + const ClampingScrollPhysics({ScrollPhysics? parent}) : super(parent: parent); @override ClampingScrollPhysics applyTo(ScrollPhysics? ancestor) { @@ -436,12 +437,14 @@ class ClampingScrollPhysics extends ScrollPhysics { ErrorSummary('$runtimeType.applyBoundaryConditions() was called redundantly.'), ErrorDescription( 'The proposed new position, $value, is exactly equal to the current position of the ' - 'given ${position.runtimeType}, ${position.pixels}.\n' - 'The applyBoundaryConditions method should only be called when the value is ' - 'going to actually change the pixels, otherwise it is redundant.', + 'given ${position.runtimeType}, ${position.pixels}.\n' + 'The applyBoundaryConditions method should only be called when the value is ' + 'going to actually change the pixels, otherwise it is redundant.', ), - DiagnosticsProperty('The physics object in question was', this, style: DiagnosticsTreeStyle.errorProperty), - DiagnosticsProperty('The position object in question was', position, style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty('The physics object in question was', this, + style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty('The position object in question was', position, + style: DiagnosticsTreeStyle.errorProperty), ]); } return true; @@ -462,10 +465,8 @@ class ClampingScrollPhysics extends ScrollPhysics { final Tolerance tolerance = this.tolerance; if (position.outOfRange) { double? end; - if (position.pixels > position.maxScrollExtent) - end = position.maxScrollExtent; - if (position.pixels < position.minScrollExtent) - end = position.minScrollExtent; + if (position.pixels > position.maxScrollExtent) end = position.maxScrollExtent; + if (position.pixels < position.minScrollExtent) end = position.minScrollExtent; assert(end != null); return ScrollSpringSimulation( spring, @@ -475,12 +476,9 @@ class ClampingScrollPhysics extends ScrollPhysics { tolerance: tolerance, ); } - if (velocity.abs() < tolerance.velocity) - return null; - if (velocity > 0.0 && position.pixels >= position.maxScrollExtent) - return null; - if (velocity < 0.0 && position.pixels <= position.minScrollExtent) - return null; + if (velocity.abs() < tolerance.velocity) return null; + if (velocity > 0.0 && position.pixels >= position.maxScrollExtent) return null; + if (velocity < 0.0 && position.pixels <= position.minScrollExtent) return null; return ClampingScrollSimulation( position: position.pixels, velocity: velocity, diff --git a/webf/lib/src/gesture/scroll_position.dart b/webf/lib/src/gesture/scroll_position.dart index 7cd2953551..d2bbb5f348 100644 --- a/webf/lib/src/gesture/scroll_position.dart +++ b/webf/lib/src/gesture/scroll_position.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ // Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be @@ -228,7 +229,7 @@ abstract class ScrollPosition extends ViewportOffset with ScrollMetrics { /// If there is any overscroll, it is reported using [didOverscrollBy]. double setPixels(double newPixels) { assert(_pixels != null); - assert(SchedulerBinding.instance!.schedulerPhase.index <= SchedulerPhase.transientCallbacks.index); + assert(SchedulerBinding.instance.schedulerPhase.index <= SchedulerPhase.transientCallbacks.index); if (newPixels != pixels) { final double overscroll = applyBoundaryConditions(newPixels); diff --git a/webf/lib/src/gesture/scroll_position_with_single_context.dart b/webf/lib/src/gesture/scroll_position_with_single_context.dart index 9fd9b33cae..a9856d3d7f 100644 --- a/webf/lib/src/gesture/scroll_position_with_single_context.dart +++ b/webf/lib/src/gesture/scroll_position_with_single_context.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ // Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be @@ -153,8 +154,7 @@ class ScrollPositionWithSingleContext extends ScrollPosition implements ScrollAc /// /// If this changes the value, then a [UserScrollNotification] is dispatched. void updateUserScrollDirection(ScrollDirection value) { - if (userScrollDirection == value) - return; + if (userScrollDirection == value) return; _userScrollDirection = value; } @@ -196,12 +196,11 @@ class ScrollPositionWithSingleContext extends ScrollPosition implements ScrollAc void pointerScroll(double delta) { assert(delta != 0.0); - final double targetPixels = - math.min(math.max(pixels + delta, minScrollExtent), maxScrollExtent); + final double targetPixels = math.min(math.max(pixels + delta, minScrollExtent), maxScrollExtent); if (targetPixels != pixels) { goIdle(); updateUserScrollDirection( - -delta > 0.0 ? ScrollDirection.forward : ScrollDirection.reverse, + -delta > 0.0 ? ScrollDirection.forward : ScrollDirection.reverse, ); forcePixels(targetPixels); isScrollingNotifier.value = true; diff --git a/webf/lib/src/gesture/scroll_simulation.dart b/webf/lib/src/gesture/scroll_simulation.dart index 7fa48a88f0..68448b6765 100644 --- a/webf/lib/src/gesture/scroll_simulation.dart +++ b/webf/lib/src/gesture/scroll_simulation.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ // Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be diff --git a/webf/lib/src/gesture/scrollable.dart b/webf/lib/src/gesture/scrollable.dart index 0dd157dab1..862767f764 100644 --- a/webf/lib/src/gesture/scrollable.dart +++ b/webf/lib/src/gesture/scrollable.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/gestures.dart'; @@ -57,7 +58,7 @@ class _CustomTicker extends Ticker { } } -class KrakenScrollable with _CustomTickerProviderStateMixin implements ScrollContext { +class WebFScrollable with _CustomTickerProviderStateMixin implements ScrollContext { late AxisDirection _axisDirection; ScrollPositionWithSingleContext? position; final ScrollPhysics _physics = ScrollPhysics.createScrollPhysics(); @@ -65,12 +66,11 @@ class KrakenScrollable with _CustomTickerProviderStateMixin implements ScrollCon ScrollListener? scrollListener; final Set dragDevices; - KrakenScrollable({ - AxisDirection axisDirection = AxisDirection.down, - this.dragStartBehavior = DragStartBehavior.start, - this.scrollListener, - this.dragDevices = _kTouchLikeDeviceTypes - }) { + WebFScrollable( + {AxisDirection axisDirection = AxisDirection.down, + this.dragStartBehavior = DragStartBehavior.start, + this.scrollListener, + this.dragDevices = _kTouchLikeDeviceTypes}) { _axisDirection = axisDirection; position = ScrollPositionWithSingleContext(physics: _physics, context: this, oldPosition: null); } @@ -109,7 +109,8 @@ class KrakenScrollable with _CustomTickerProviderStateMixin implements ScrollCon case Axis.vertical: // Vertical drag gesture recognizer to trigger vertical scroll. _gestureRecognizers = { - ScrollVerticalDragGestureRecognizer: GestureRecognizerFactoryWithHandlers( + ScrollVerticalDragGestureRecognizer: + GestureRecognizerFactoryWithHandlers( () => ScrollVerticalDragGestureRecognizer(supportedDevices: dragDevices), (ScrollVerticalDragGestureRecognizer instance) { instance @@ -130,7 +131,8 @@ class KrakenScrollable with _CustomTickerProviderStateMixin implements ScrollCon case Axis.horizontal: // Horizontal drag gesture recognizer to horizontal vertical scroll. _gestureRecognizers = { - ScrollHorizontalDragGestureRecognizer: GestureRecognizerFactoryWithHandlers( + ScrollHorizontalDragGestureRecognizer: + GestureRecognizerFactoryWithHandlers( () => ScrollHorizontalDragGestureRecognizer(supportedDevices: dragDevices), (ScrollHorizontalDragGestureRecognizer instance) { instance @@ -162,8 +164,10 @@ class KrakenScrollable with _CustomTickerProviderStateMixin implements ScrollCon double maxScrollExtent = drag.maxScrollExtent!; double minScrollExtent = drag.minScrollExtent!; - return !((direction == AxisDirection.down && (pixels <= minScrollExtent || nearEqual(pixels, minScrollExtent, Tolerance.defaultTolerance.distance))) - || direction == AxisDirection.up && (pixels >= maxScrollExtent || nearEqual(pixels, maxScrollExtent, Tolerance.defaultTolerance.distance))); + return !((direction == AxisDirection.down && + (pixels <= minScrollExtent || nearEqual(pixels, minScrollExtent, Tolerance.defaultTolerance.distance))) || + direction == AxisDirection.up && + (pixels >= maxScrollExtent || nearEqual(pixels, maxScrollExtent, Tolerance.defaultTolerance.distance))); } // Used in the Arena to judge whether the horizontal drag gesture can trigger the current container to scroll. @@ -172,8 +176,10 @@ class KrakenScrollable with _CustomTickerProviderStateMixin implements ScrollCon double pixels = drag.pixels!; double maxScrollExtent = drag.maxScrollExtent!; double minScrollExtent = drag.minScrollExtent!; - return !((direction == AxisDirection.right && (pixels <= minScrollExtent || nearEqual(pixels, minScrollExtent, Tolerance.defaultTolerance.distance))) - || direction == AxisDirection.left && (pixels >= maxScrollExtent || nearEqual(pixels, maxScrollExtent, Tolerance.defaultTolerance.distance))); + return !((direction == AxisDirection.right && + (pixels <= minScrollExtent || nearEqual(pixels, minScrollExtent, Tolerance.defaultTolerance.distance))) || + direction == AxisDirection.left && + (pixels >= maxScrollExtent || nearEqual(pixels, maxScrollExtent, Tolerance.defaultTolerance.distance))); } void _syncAll(Map gestures) { @@ -227,14 +233,13 @@ class KrakenScrollable with _CustomTickerProviderStateMixin implements ScrollCon final double targetScrollOffset = _targetScrollOffsetForPointerScroll(delta); // Only express interest in the event if it would actually result in a scroll. if (delta != 0.0 && targetScrollOffset != position?.pixels) { - GestureBinding.instance!.pointerSignalResolver.register(event, _handlePointerScroll); + GestureBinding.instance.pointerSignalResolver.register(event, _handlePointerScroll); } } } + double _pointerSignalEventDelta(PointerScrollEvent event) { - double delta = axis == Axis.horizontal - ? event.scrollDelta.dx - : event.scrollDelta.dy; + double delta = axis == Axis.horizontal ? event.scrollDelta.dx : event.scrollDelta.dy; if (axisDirectionIsReversed(axisDirection)) { delta *= -1; diff --git a/webf/lib/src/gesture/swipe.dart b/webf/lib/src/gesture/swipe.dart index ce5f19c83d..eba77b8d9e 100644 --- a/webf/lib/src/gesture/swipe.dart +++ b/webf/lib/src/gesture/swipe.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/gestures.dart'; @@ -41,6 +42,7 @@ class SwipeDetails { double computeSwipeSlop(PointerDeviceKind kind) { switch (kind) { case PointerDeviceKind.mouse: + case PointerDeviceKind.trackpad: return kPrecisePointerSwipeSlop; case PointerDeviceKind.stylus: case PointerDeviceKind.invertedStylus: @@ -67,6 +69,7 @@ class SwipeGestureRecognizer extends OneSequenceGestureRecognizer { }) : super(debugOwner: debugOwner, supportedDevices: supportedDevices); static VelocityTracker _defaultBuilder(PointerEvent event) => VelocityTracker.withKind(event.kind); + /// Configure the behavior of offsets sent to [onStart]. /// /// If set to [DragStartBehavior.start], the [onStart] callback will be called @@ -168,12 +171,15 @@ class SwipeGestureRecognizer extends OneSequenceGestureRecognizer { final double minVelocity = minFlingVelocity ?? kMinFlingVelocity; final double minDistance = minFlingDistance ?? computeHitSlop(kind, gestureSettings); - return ((_direction == DIRECTION_LEFT || _direction == DIRECTION_RIGHT) && (estimate.pixelsPerSecond.dx.abs() > minVelocity && estimate.offset.dx.abs() > minDistance) - || (_direction == DIRECTION_UP || _direction == DIRECTION_DOWN) && (estimate.pixelsPerSecond.dy.abs() > minVelocity && estimate.offset.dy.abs() > minDistance)); + return ((_direction == DIRECTION_LEFT || _direction == DIRECTION_RIGHT) && + (estimate.pixelsPerSecond.dx.abs() > minVelocity && estimate.offset.dx.abs() > minDistance) || + (_direction == DIRECTION_UP || _direction == DIRECTION_DOWN) && + (estimate.pixelsPerSecond.dy.abs() > minVelocity && estimate.offset.dy.abs() > minDistance)); } bool _hasSufficientGlobalDistanceToAccept(PointerDeviceKind pointerDeviceKind) { - return (_globalHorizontalDistanceMoved.abs() > computeSwipeSlop(pointerDeviceKind) || _globalVerticalDistanceMoved.abs() > computeSwipeSlop(pointerDeviceKind)); + return (_globalHorizontalDistanceMoved.abs() > computeSwipeSlop(pointerDeviceKind) || + _globalVerticalDistanceMoved.abs() > computeSwipeSlop(pointerDeviceKind)); } final Map _velocityTrackers = {}; @@ -183,8 +189,7 @@ class SwipeGestureRecognizer extends OneSequenceGestureRecognizer { if (_initialButtons == null) { switch (event.buttons) { case kPrimaryButton: - if (onSwipe == null && onCancel == null) - return false; + if (onSwipe == null && onCancel == null) return false; break; default: return false; @@ -208,7 +213,7 @@ class SwipeGestureRecognizer extends OneSequenceGestureRecognizer { _initialButtons = event.buttons; _pendingDragOffset = OffsetPair.zero; _globalHorizontalDistanceMoved = 0.0; - _globalVerticalDistanceMoved= 0.0; + _globalVerticalDistanceMoved = 0.0; } else if (_state == _SwipeState.accepted) { resolve(GestureDisposition.accepted); } @@ -217,8 +222,7 @@ class SwipeGestureRecognizer extends OneSequenceGestureRecognizer { @override void handleEvent(PointerEvent event) { assert(_state != _SwipeState.ready); - if (!event.synthesized - && (event is PointerDownEvent || event is PointerMoveEvent)) { + if (!event.synthesized && (event is PointerDownEvent || event is PointerMoveEvent)) { final VelocityTracker tracker = _velocityTrackers[event.pointer]!; tracker.addPosition(event.timeStamp, event.localPosition); } @@ -235,17 +239,19 @@ class SwipeGestureRecognizer extends OneSequenceGestureRecognizer { final Offset movedHorizontalLocally = Offset(event.localDelta.dx, 0.0); _globalHorizontalDistanceMoved += PointerEvent.transformDeltaViaPositions( - transform: localToGlobalTransform, - untransformedDelta: movedHorizontalLocally, - untransformedEndPosition: event.localPosition, - ).distance * (movedHorizontalLocally.dx).sign; + transform: localToGlobalTransform, + untransformedDelta: movedHorizontalLocally, + untransformedEndPosition: event.localPosition, + ).distance * + (movedHorizontalLocally.dx).sign; final Offset movedVerticalLocally = Offset(0.0, event.localDelta.dy); _globalVerticalDistanceMoved += PointerEvent.transformDeltaViaPositions( - transform: localToGlobalTransform, - untransformedDelta: movedVerticalLocally, - untransformedEndPosition: event.localPosition, - ).distance * (movedVerticalLocally.dy).sign; + transform: localToGlobalTransform, + untransformedDelta: movedVerticalLocally, + untransformedEndPosition: event.localPosition, + ).distance * + (movedVerticalLocally.dy).sign; if (_globalHorizontalDistanceMoved.abs() > _globalVerticalDistanceMoved.abs()) { _direction = _globalHorizontalDistanceMoved > 0 ? DIRECTION_RIGHT : DIRECTION_LEFT; @@ -254,13 +260,13 @@ class SwipeGestureRecognizer extends OneSequenceGestureRecognizer { } if (_state != _SwipeState.accepted && _hasSufficientGlobalDistanceToAccept(event.kind)) { - resolve(GestureDisposition.accepted); + resolve(GestureDisposition.accepted); } } if (event is PointerUpEvent || event is PointerCancelEvent) { _giveUpPointer( event.pointer, - reject: event is PointerCancelEvent || _state ==_SwipeState.possible, + reject: event is PointerCancelEvent || _state == _SwipeState.possible, ); } } @@ -285,7 +291,7 @@ class SwipeGestureRecognizer extends OneSequenceGestureRecognizer { @override void didStopTrackingLastPointer(int pointer) { assert(_state != _SwipeState.ready); - switch(_state) { + switch (_state) { case _SwipeState.ready: break; @@ -315,8 +321,7 @@ class SwipeGestureRecognizer extends OneSequenceGestureRecognizer { void _checkEnd(int pointer) { assert(_initialButtons == kPrimaryButton); - if (onSwipe == null) - return; + if (onSwipe == null) return; final VelocityTracker tracker = _velocityTrackers[pointer]!; @@ -340,8 +345,7 @@ class SwipeGestureRecognizer extends OneSequenceGestureRecognizer { void _checkCancel() { assert(_initialButtons == kPrimaryButton); - if (onCancel != null) - invokeCallback('onCancel', onCancel!); + if (onCancel != null) invokeCallback('onCancel', onCancel!); } @override @@ -349,6 +353,7 @@ class SwipeGestureRecognizer extends OneSequenceGestureRecognizer { _velocityTrackers.clear(); super.dispose(); } + @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); diff --git a/webf/lib/src/launcher/controller.dart b/webf/lib/src/launcher/controller.dart index 47d07085fd..7b838f788a 100644 --- a/webf/lib/src/launcher/controller.dart +++ b/webf/lib/src/launcher/controller.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2020-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; @@ -15,21 +16,20 @@ import 'package:flutter/widgets.dart' show RenderObjectElement; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; -import 'package:flutter/widgets.dart' - show RouteInformation, WidgetsBinding, WidgetsBindingObserver, AnimationController; -import 'package:kraken/bridge.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/foundation.dart'; -import 'package:kraken/gesture.dart'; -import 'package:kraken/module.dart'; -import 'package:kraken/rendering.dart'; -import 'package:kraken/widget.dart'; +import 'package:flutter/widgets.dart' show RouteInformation, WidgetsBinding, WidgetsBindingObserver, AnimationController; +import 'package:webf/bridge.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/foundation.dart'; +import 'package:webf/gesture.dart'; +import 'package:webf/module.dart'; +import 'package:webf/rendering.dart'; +import 'package:webf/widget.dart'; const int WINDOW_ID = -1; const int DOCUMENT_ID = -2; // Error handler when load bundle failed. -typedef LoadHandler = void Function(KrakenController controller); +typedef LoadHandler = void Function(WebFController controller); typedef LoadErrorHandler = void Function(FlutterError error, StackTrace stack); typedef JSErrorHandler = void Function(String message); typedef JSLogHandler = void Function(int level, String message); @@ -57,23 +57,22 @@ void setTargetPlatformForDesktop() { } abstract class DevToolsService { - void init(KrakenController controller); + void init(WebFController controller); void willReload(); void didReload(); void dispose(); } // An kraken View Controller designed for multiple kraken view control. -class KrakenViewController - implements WidgetsBindingObserver, ElementsBindingObserver { +class WebFViewController implements WidgetsBindingObserver, ElementsBindingObserver { static Map> documentNativePtrMap = {}; static Map> windowNativePtrMap = {}; - KrakenController rootController; + WebFController rootController; // The methods of the KrakenNavigateDelegation help you implement custom behaviors that are triggered // during a kraken view's process of loading, and completing a navigation request. - KrakenNavigationDelegate? navigationDelegate; + WebFNavigationDelegate? navigationDelegate; GestureListener? gestureListener; @@ -82,7 +81,7 @@ class KrakenViewController set viewportWidth(double value) { if (value != _viewportWidth) { _viewportWidth = value; - viewport.viewportSize = Size(_viewportWidth, _viewportHeight); + viewport.viewportSize = ui.Size(_viewportWidth, _viewportHeight); } } @@ -91,7 +90,7 @@ class KrakenViewController set viewportHeight(double value) { if (value != _viewportHeight) { _viewportHeight = value; - viewport.viewportSize = Size(_viewportWidth, _viewportHeight); + viewport.viewportSize = ui.Size(_viewportWidth, _viewportHeight); } } @@ -99,19 +98,16 @@ class KrakenViewController WidgetDelegate? widgetDelegate; - KrakenViewController( - this._viewportWidth, - this._viewportHeight, { - this.background, - this.enableDebug = false, - int? contextId, - required this.rootController, - this.navigationDelegate, - this.gestureListener, - this.widgetDelegate, - // Viewport won't change when kraken page reload, should reuse previous page's viewportBox. - RenderViewportBox? originalViewport - }) { + WebFViewController(this._viewportWidth, this._viewportHeight, + {this.background, + this.enableDebug = false, + int? contextId, + required this.rootController, + this.navigationDelegate, + this.gestureListener, + this.widgetDelegate, + // Viewport won't change when kraken page reload, should reuse previous page's viewportBox. + RenderViewportBox? originalViewport}) { if (enableDebug) { debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia; debugPaintSizeEnabled = true; @@ -133,11 +129,7 @@ class KrakenViewController originalViewport.controller = rootController; viewport = originalViewport; } else { - viewport = RenderViewportBox( - background: background, - viewportSize: Size(viewportWidth, viewportHeight), - controller: rootController - ); + viewport = RenderViewportBox(background: background, viewportSize: ui.Size(viewportWidth, viewportHeight), controller: rootController); } if (kProfileMode) { @@ -158,9 +150,7 @@ class KrakenViewController ); _setEventTarget(DOCUMENT_ID, document); - window = Window( - BindingContext(_contextId, windowNativePtrMap[_contextId]!), - document); + window = Window(BindingContext(_contextId, windowNativePtrMap[_contextId]!), document); _registerPlatformBrightnessChange(); _setEventTarget(WINDOW_ID, window); @@ -217,23 +207,23 @@ class KrakenViewController late Window window; void evaluateJavaScripts(String code) { - assert(!_disposed, 'Kraken have already disposed'); + assert(!_disposed, 'WebF have already disposed'); evaluateScripts(_contextId, code); } void _setupObserver() { if (ElementsBinding.instance != null) { ElementsBinding.instance!.addObserver(this); - } else if (WidgetsBinding.instance != null) { - WidgetsBinding.instance!.addObserver(this); + } else { + WidgetsBinding.instance.addObserver(this); } } void _teardownObserver() { if (ElementsBinding.instance != null) { ElementsBinding.instance!.removeObserver(this); - } else if (WidgetsBinding.instance != null) { - WidgetsBinding.instance!.removeObserver(this); + } else { + WidgetsBinding.instance.removeObserver(this); } } @@ -355,7 +345,7 @@ class KrakenViewController // export Uint8List bytes from rendered result. Future toImage(double devicePixelRatio, [int? eventTargetId]) { - assert(!_disposed, 'Kraken have already disposed'); + assert(!_disposed, 'WebF have already disposed'); Completer completer = Completer(); try { if (eventTargetId != null && !_existsTarget(eventTargetId)) { @@ -363,9 +353,7 @@ class KrakenViewController completer.completeError(Exception(msg)); return completer.future; } - var node = eventTargetId == null - ? document.documentElement - : _getEventTargetById(eventTargetId); + var node = eventTargetId == null ? document.documentElement : _getEventTargetById(eventTargetId); if (node is Element) { if (!node.isRendererAttached) { String msg = 'toImage: the element is not attached to document tree.'; @@ -376,8 +364,7 @@ class KrakenViewController node.toBlob(devicePixelRatio: devicePixelRatio).then((Uint8List bytes) { completer.complete(bytes); }).catchError((e, stack) { - String msg = - 'toBlob: failed to export image data from element id: $eventTargetId. error: $e}.\n$stack'; + String msg = 'toBlob: failed to export image data from element id: $eventTargetId. error: $e}.\n$stack'; completer.completeError(Exception(msg)); }); } else { @@ -390,71 +377,54 @@ class KrakenViewController return completer.future; } - void createElement( - int targetId, Pointer nativePtr, String tagName) { + void createElement(int targetId, Pointer nativePtr, String tagName) { if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_CREATE_ELEMENT_START, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_CREATE_ELEMENT_START, uniqueId: targetId); } - assert(!_existsTarget(targetId), - 'ERROR: Can not create element with same id "$targetId"'); - Element element = document.createElement( - tagName.toUpperCase(), BindingContext(_contextId, nativePtr)); + assert(!_existsTarget(targetId), 'ERROR: Can not create element with same id "$targetId"'); + Element element = document.createElement(tagName.toUpperCase(), BindingContext(_contextId, nativePtr)); _setEventTarget(targetId, element); if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_CREATE_ELEMENT_END, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_CREATE_ELEMENT_END, uniqueId: targetId); } } - void createTextNode( - int targetId, Pointer nativePtr, String data) { + void createTextNode(int targetId, Pointer nativePtr, String data) { if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_CREATE_TEXT_NODE_START, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_CREATE_TEXT_NODE_START, uniqueId: targetId); } - TextNode textNode = document.createTextNode( - data, BindingContext(_contextId, nativePtr)); + TextNode textNode = document.createTextNode(data, BindingContext(_contextId, nativePtr)); _setEventTarget(targetId, textNode); if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_CREATE_TEXT_NODE_END, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_CREATE_TEXT_NODE_END, uniqueId: targetId); } } void createComment(int targetId, Pointer nativePtr) { if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_CREATE_COMMENT_START, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_CREATE_COMMENT_START, uniqueId: targetId); } - Comment comment = - document.createComment(BindingContext(_contextId, nativePtr)); + Comment comment = document.createComment(BindingContext(_contextId, nativePtr)); _setEventTarget(targetId, comment); if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_CREATE_COMMENT_END, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_CREATE_COMMENT_END, uniqueId: targetId); } } - void createDocumentFragment( - int targetId, Pointer nativePtr) { + void createDocumentFragment(int targetId, Pointer nativePtr) { if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_CREATE_DOCUMENT_FRAGMENT_START, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_CREATE_DOCUMENT_FRAGMENT_START, uniqueId: targetId); } - DocumentFragment fragment = document - .createDocumentFragment(BindingContext(_contextId, nativePtr)); + DocumentFragment fragment = document.createDocumentFragment(BindingContext(_contextId, nativePtr)); _setEventTarget(targetId, fragment); if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_CREATE_DOCUMENT_FRAGMENT_END, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_CREATE_DOCUMENT_FRAGMENT_END, uniqueId: targetId); } } void addEvent(int targetId, String eventType) { if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_ADD_EVENT_START, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_ADD_EVENT_START, uniqueId: targetId); } if (!_existsTarget(targetId)) return; EventTarget? target = _getEventTargetById(targetId); @@ -469,8 +439,7 @@ class KrakenViewController void removeEvent(int targetId, String eventType) { if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_REMOVE_EVENT_START, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_REMOVE_EVENT_START, uniqueId: targetId); } assert(_existsTarget(targetId), 'targetId: $targetId event: $eventType'); @@ -480,8 +449,7 @@ class KrakenViewController } if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_REMOVE_EVENT_END, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_REMOVE_EVENT_END, uniqueId: targetId); } } @@ -505,8 +473,7 @@ class KrakenViewController void removeNode(int targetId) { if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_REMOVE_NODE_START, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_REMOVE_NODE_START, uniqueId: targetId); } assert(_existsTarget(targetId), 'targetId: $targetId'); @@ -517,8 +484,7 @@ class KrakenViewController _debugDOMTreeChanged(); if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_REMOVE_NODE_END, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_REMOVE_NODE_END, uniqueId: targetId); } } @@ -531,14 +497,11 @@ class KrakenViewController /// void insertAdjacentNode(int targetId, String position, int newTargetId) { if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_INSERT_ADJACENT_NODE_START, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_INSERT_ADJACENT_NODE_START, uniqueId: targetId); } - assert(_existsTarget(targetId), - 'targetId: $targetId position: $position newTargetId: $newTargetId'); - assert(_existsTarget(newTargetId), - 'newTargetId: $newTargetId position: $position'); + assert(_existsTarget(targetId), 'targetId: $targetId position: $position newTargetId: $newTargetId'); + assert(_existsTarget(newTargetId), 'newTargetId: $newTargetId position: $position'); Node target = _getEventTargetById(targetId)!; Node newNode = _getEventTargetById(newTargetId)!; @@ -560,8 +523,7 @@ class KrakenViewController } else { targetParentNode.insertBefore( newNode, - targetParentNode - .childNodes[targetParentNode.childNodes.indexOf(target) + 1], + targetParentNode.childNodes[targetParentNode.childNodes.indexOf(target) + 1], ); } break; @@ -570,8 +532,7 @@ class KrakenViewController _debugDOMTreeChanged(); if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_INSERT_ADJACENT_NODE_END, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_INSERT_ADJACENT_NODE_END, uniqueId: targetId); } } @@ -624,8 +585,7 @@ class KrakenViewController void removeAttribute(int targetId, String key) { if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_SET_PROPERTIES_START, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_SET_PROPERTIES_START, uniqueId: targetId); } assert(_existsTarget(targetId), 'targetId: $targetId key: $key'); Node target = _getEventTargetById(targetId)!; @@ -636,19 +596,16 @@ class KrakenViewController // @TODO: property is not attribute. target.data = ''; } else { - debugPrint( - 'Only element has attributes, try removing $key from Node(#$targetId).'); + debugPrint('Only element has attributes, try removing $key from Node(#$targetId).'); } if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_SET_PROPERTIES_END, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_SET_PROPERTIES_END, uniqueId: targetId); } } void setInlineStyle(int targetId, String key, String value) { if (kProfileMode) { - PerformanceTiming.instance() - .mark(PERF_SET_STYLE_START, uniqueId: targetId); + PerformanceTiming.instance().mark(PERF_SET_STYLE_START, uniqueId: targetId); } assert(_existsTarget(targetId), 'id: $targetId key: $key value: $value'); Node? target = _getEventTargetById(targetId); @@ -657,8 +614,7 @@ class KrakenViewController if (target is Element) { target.setInlineStyle(key, value); } else { - debugPrint( - 'Only element has style, try setting style.$key from Node(#$targetId).'); + debugPrint('Only element has style, try setting style.$key from Node(#$targetId).'); } if (kProfileMode) { PerformanceTiming.instance().mark(PERF_SET_STYLE_END, uniqueId: targetId); @@ -673,8 +629,7 @@ class KrakenViewController if (target is Element) { target.style.flushPendingProperties(); } else { - debugPrint( - 'Only element has style, try flushPendingStyleProperties from Node(#$targetId).'); + debugPrint('Only element has style, try flushPendingStyleProperties from Node(#$targetId).'); } } @@ -687,23 +642,20 @@ class KrakenViewController } } - Future handleNavigationAction(String? sourceUrl, String targetUrl, - KrakenNavigationType navigationType) async { - KrakenNavigationAction action = - KrakenNavigationAction(sourceUrl, targetUrl, navigationType); + Future handleNavigationAction(String? sourceUrl, String targetUrl, WebFNavigationType navigationType) async { + WebFNavigationAction action = WebFNavigationAction(sourceUrl, targetUrl, navigationType); - KrakenNavigationDelegate _delegate = navigationDelegate!; + WebFNavigationDelegate _delegate = navigationDelegate!; try { - KrakenNavigationActionPolicy policy = - await _delegate.dispatchDecisionHandler(action); - if (policy == KrakenNavigationActionPolicy.cancel) return; + WebFNavigationActionPolicy policy = await _delegate.dispatchDecisionHandler(action); + if (policy == WebFNavigationActionPolicy.cancel) return; switch (action.navigationType) { - case KrakenNavigationType.navigate: - await rootController.load(KrakenBundle.fromUrl(action.target)); + case WebFNavigationType.navigate: + await rootController.load(WebFBundle.fromUrl(action.target)); break; - case KrakenNavigationType.reload: + case WebFNavigationType.reload: await rootController.reload(); break; default: @@ -713,7 +665,7 @@ class KrakenViewController if (_delegate.errorHandler != null) { _delegate.errorHandler!(e, stack); } else { - print('Kraken navigation failed: $e\n$stack'); + print('WebF navigation failed: $e\n$stack'); } } } @@ -751,8 +703,7 @@ class KrakenViewController @override void didChangeMetrics() { - double bottomInset = - ui.window.viewInsets.bottom / ui.window.devicePixelRatio; + double bottomInset = ui.window.viewInsets.bottom / ui.window.devicePixelRatio; if (_prevViewInsets.bottom > ui.window.viewInsets.bottom) { // Hide keyboard viewport.bottomInset = bottomInset; @@ -764,8 +715,7 @@ class KrakenViewController if (renderer != null && renderer.hasSize) { Offset focusOffset = renderer.localToGlobal(Offset.zero); // FOCUS_VIEWINSET_BOTTOM_OVERALL to meet border case. - if (focusOffset.dy > - viewportHeight - bottomInset - FOCUS_VIEWINSET_BOTTOM_OVERALL) { + if (focusOffset.dy > viewportHeight - bottomInset - FOCUS_VIEWINSET_BOTTOM_OVERALL) { shouldScrollByToCenter = true; } } @@ -773,7 +723,7 @@ class KrakenViewController // Show keyboard viewport.bottomInset = bottomInset; if (shouldScrollByToCenter) { - SchedulerBinding.instance!.addPostFrameCallback((_) { + SchedulerBinding.instance.addPostFrameCallback((_) { window.scrollBy(0, bottomInset); }); } @@ -809,19 +759,18 @@ class KrakenViewController } @override - Future didPushRouteInformation( - RouteInformation routeInformation) async { + Future didPushRouteInformation(RouteInformation routeInformation) async { // TODO: implement didPushRouteInformation return false; } } // An controller designed to control kraken's functional modules. -class KrakenModuleController with TimerMixin, ScheduleFrameMixin { +class WebFModuleController with TimerMixin, ScheduleFrameMixin { late ModuleManager _moduleManager; ModuleManager get moduleManager => _moduleManager; - KrakenModuleController(KrakenController controller, int contextId) { + WebFModuleController(WebFController controller, int contextId) { _moduleManager = ModuleManager(controller, contextId); } @@ -832,16 +781,15 @@ class KrakenModuleController with TimerMixin, ScheduleFrameMixin { } } -class KrakenController { - static final SplayTreeMap _controllerMap = - SplayTreeMap(); +class WebFController { + static final SplayTreeMap _controllerMap = SplayTreeMap(); static final Map _nameIdMap = {}; UriParser? uriParser; late RenderObjectElement rootFlutterElement; - static KrakenController? getControllerOfJSContextId(int? contextId) { + static WebFController? getControllerOfJSContextId(int? contextId) { if (!_controllerMap.containsKey(contextId)) { return null; } @@ -849,11 +797,11 @@ class KrakenController { return _controllerMap[contextId]; } - static SplayTreeMap getControllerMap() { + static SplayTreeMap getControllerMap() { return _controllerMap; } - static KrakenController? getControllerOfName(String name) { + static WebFController? getControllerOfName(String name) { if (!_nameIdMap.containsKey(name)) return null; int? contextId = _nameIdMap[name]; return getControllerOfJSContextId(contextId); @@ -874,9 +822,9 @@ class KrakenController { final DevToolsService? devToolsService; final HttpClientInterceptor? httpClientInterceptor; - KrakenMethodChannel? _methodChannel; + WebFMethodChannel? _methodChannel; - KrakenMethodChannel? get methodChannel => _methodChannel; + WebFMethodChannel? get methodChannel => _methodChannel; JSLogHandler? _onJSLog; JSLogHandler? get onJSLog => _onJSLog; @@ -899,9 +847,9 @@ class KrakenController { final GestureListener? _gestureListener; // The kraken view entrypoint bundle. - KrakenBundle? _entrypoint; + WebFBundle? _entrypoint; - KrakenController( + WebFController( String? name, double viewportWidth, double viewportHeight, { @@ -910,9 +858,9 @@ class KrakenController { bool autoExecuteEntrypoint = true, Color? background, GestureListener? gestureListener, - KrakenNavigationDelegate? navigationDelegate, - KrakenMethodChannel? methodChannel, - KrakenBundle? entrypoint, + WebFNavigationDelegate? navigationDelegate, + WebFMethodChannel? methodChannel, + WebFBundle? entrypoint, this.widgetDelegate, this.onLoad, this.onLoadError, @@ -929,15 +877,15 @@ class KrakenController { } _methodChannel = methodChannel; - KrakenMethodChannel.setJSMethodCallCallback(this); + WebFMethodChannel.setJSMethodCallCallback(this); - _view = KrakenViewController( + _view = WebFViewController( viewportWidth, viewportHeight, background: background, enableDebug: enableDebug, rootController: this, - navigationDelegate: navigationDelegate ?? KrakenNavigationDelegate(), + navigationDelegate: navigationDelegate ?? WebFNavigationDelegate(), gestureListener: _gestureListener, widgetDelegate: widgetDelegate, ); @@ -948,19 +896,16 @@ class KrakenController { final int contextId = _view.contextId; - _module = KrakenModuleController(this, contextId); + _module = WebFModuleController(this, contextId); if (entrypoint != null) { - HistoryModule historyModule = - module.moduleManager.getModule('History')!; + HistoryModule historyModule = module.moduleManager.getModule('History')!; historyModule.add(entrypoint); } - assert(!_controllerMap.containsKey(contextId), - 'found exist contextId of KrakenController, contextId: $contextId'); + assert(!_controllerMap.containsKey(contextId), 'found exist contextId of WebFController, contextId: $contextId'); _controllerMap[contextId] = this; - assert(!_nameIdMap.containsKey(name), - 'found exist name of KrakenController, name: $name'); + assert(!_nameIdMap.containsKey(name), 'found exist name of WebFController, name: $name'); if (name != null) { _nameIdMap[name] = contextId; } @@ -978,15 +923,15 @@ class KrakenController { } } - late KrakenViewController _view; + late WebFViewController _view; - KrakenViewController get view { + WebFViewController get view { return _view; } - late KrakenModuleController _module; + late WebFModuleController _module; - KrakenModuleController get module { + WebFModuleController get module { return _module; } @@ -998,12 +943,12 @@ class KrakenController { return Uri(scheme: 'vm', host: 'bundle', path: id != null ? '$id' : null); } - void setNavigationDelegate(KrakenNavigationDelegate delegate) { + void setNavigationDelegate(WebFNavigationDelegate delegate) { _view.navigationDelegate = delegate; } Future unload() async { - assert(!_view._disposed, 'Kraken have already disposed'); + assert(!_view._disposed, 'WebF have already disposed'); // Should clear previous page cached ui commands clearUICommand(_view.contextId); @@ -1015,18 +960,17 @@ class KrakenController { allocateNewPage(_view.contextId); - _view = KrakenViewController(view.viewportWidth, view.viewportHeight, - background: _view.background, - enableDebug: _view.enableDebug, - contextId: _view.contextId, - rootController: this, - navigationDelegate: _view.navigationDelegate, - gestureListener: _view.gestureListener, - widgetDelegate: _view.widgetDelegate, - originalViewport: _view.viewport - ); + _view = WebFViewController(view.viewportWidth, view.viewportHeight, + background: _view.background, + enableDebug: _view.enableDebug, + contextId: _view.contextId, + rootController: this, + navigationDelegate: _view.navigationDelegate, + gestureListener: _view.gestureListener, + widgetDelegate: _view.widgetDelegate, + originalViewport: _view.viewport); - _module = KrakenModuleController(this, _view.contextId); + _module = WebFModuleController(this, _view.contextId); completer.complete(); }); @@ -1041,14 +985,13 @@ class KrakenController { String get url => _url ?? ''; - _addHistory(KrakenBundle bundle) { - HistoryModule historyModule = - module.moduleManager.getModule('History')!; + _addHistory(WebFBundle bundle) { + HistoryModule historyModule = module.moduleManager.getModule('History')!; historyModule.add(bundle); } Future reload() async { - assert(!_view._disposed, 'Kraken have already disposed'); + assert(!_view._disposed, 'WebF have already disposed'); if (devToolsService != null) { devToolsService!.willReload(); @@ -1062,8 +1005,8 @@ class KrakenController { } } - Future load(KrakenBundle bundle) async { - assert(!_view._disposed, 'Kraken have already disposed'); + Future load(WebFBundle bundle) async { + assert(!_view._disposed, 'WebF have already disposed'); if (devToolsService != null) { devToolsService!.willReload(); @@ -1083,10 +1026,11 @@ class KrakenController { } String? getResourceContent(String? url) { - KrakenBundle? entrypoint = _entrypoint; + WebFBundle? entrypoint = _entrypoint; if (url == this.url && entrypoint != null && entrypoint.isResolved) { return utf8.decode(entrypoint.data!); } + return null; } bool _paused = false; @@ -1130,11 +1074,7 @@ class KrakenController { String get origin => Uri.parse(url).origin; - Future executeEntrypoint({ - bool shouldResolve = true, - bool shouldEvaluate = true, - AnimationController? animationController - }) async { + Future executeEntrypoint({bool shouldResolve = true, bool shouldEvaluate = true, AnimationController? animationController}) async { if (_entrypoint != null && shouldResolve) { await _resolveEntrypoint(); if (_entrypoint!.isResolved && shouldEvaluate) { @@ -1150,13 +1090,13 @@ class KrakenController { // Resolve the entrypoint bundle. // In general you should use executeEntrypoint, which including resolving and evaluating. Future _resolveEntrypoint() async { - assert(!_view._disposed, 'Kraken have already disposed'); + assert(!_view._disposed, 'WebF have already disposed'); if (kProfileMode) { PerformanceTiming.instance().mark(PERF_JS_BUNDLE_LOAD_START); } - KrakenBundle? bundleToLoad = _entrypoint; + WebFBundle? bundleToLoad = _entrypoint; if (bundleToLoad == null) { // Do nothing if bundle is null. return; @@ -1179,7 +1119,7 @@ class KrakenController { } // Execute the content from entrypoint bundle. - void _evaluateEntrypoint({ AnimationController? animationController }) async { + void _evaluateEntrypoint({AnimationController? animationController}) async { // @HACK: Execute JavaScript scripts will block the Flutter UI Threads. // Listen for animationController listener to make sure to execute Javascript after route transition had completed. if (animationController != null) { @@ -1191,11 +1131,11 @@ class KrakenController { return; } - assert(!_view._disposed, 'Kraken have already disposed'); + assert(!_view._disposed, 'WebF have already disposed'); if (_entrypoint != null) { - KrakenBundle entrypoint = _entrypoint!; + WebFBundle entrypoint = _entrypoint!; int contextId = _view.contextId; - assert(entrypoint.isResolved, 'The kraken bundle $entrypoint is not resolved to evaluate.'); + assert(entrypoint.isResolved, 'The webf bundle $entrypoint is not resolved to evaluate.'); if (kProfileMode) { PerformanceTiming.instance().mark(PERF_JS_BUNDLE_EVAL_START); @@ -1229,12 +1169,12 @@ class KrakenController { _view.document.parsing = false; // Should check completed when parse end. - SchedulerBinding.instance!.addPostFrameCallback((_) { + SchedulerBinding.instance.addPostFrameCallback((_) { // UICommand list is read in the next frame, so we need to determine whether there are labels // such as images and scripts after it to check is completed. checkCompleted(); }); - SchedulerBinding.instance!.scheduleFrame(); + SchedulerBinding.instance.scheduleFrame(); if (kProfileMode) { PerformanceTiming.instance().mark(PERF_JS_BUNDLE_EVAL_END); @@ -1244,12 +1184,12 @@ class KrakenController { entrypoint.dispose(); // trigger DOMContentLoaded event - SchedulerBinding.instance!.addPostFrameCallback((_) { + SchedulerBinding.instance.addPostFrameCallback((_) { Event event = Event(EVENT_DOM_CONTENT_LOADED); EventTarget window = view.window; window.dispatchEvent(event); }); - SchedulerBinding.instance!.scheduleFrame(); + SchedulerBinding.instance.scheduleFrame(); } } @@ -1279,7 +1219,7 @@ class KrakenController { } void _dispatchWindowLoadEvent() { - SchedulerBinding.instance!.addPostFrameCallback((_) { + SchedulerBinding.instance.addPostFrameCallback((_) { // DOM element are created at next frame, so we should trigger onload callback in the next frame. Event event = Event(EVENT_LOAD); _view.window.dispatchEvent(event); @@ -1288,11 +1228,11 @@ class KrakenController { onLoad!(this); } }); - SchedulerBinding.instance!.scheduleFrame(); + SchedulerBinding.instance.scheduleFrame(); } } mixin RenderObjectWithControllerMixin { // Kraken controller reference which control all kraken created renderObjects. - KrakenController? controller; + WebFController? controller; } diff --git a/webf/lib/src/launcher/launcher.dart b/webf/lib/src/launcher/launcher.dart index 619409ea87..8f799e2f9f 100644 --- a/webf/lib/src/launcher/launcher.dart +++ b/webf/lib/src/launcher/launcher.dart @@ -1,20 +1,21 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:io'; import 'dart:ui'; import 'dart:async'; import 'package:flutter/rendering.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/kraken.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/webf.dart'; typedef ConnectedCallback = void Function(); -const String BUNDLE_URL = 'KRAKEN_BUNDLE_URL'; -const String BUNDLE_PATH = 'KRAKEN_BUNDLE_PATH'; -const String ENABLE_DEBUG = 'KRAKEN_ENABLE_DEBUG'; -const String ENABLE_PERFORMANCE_OVERLAY = 'KRAKEN_ENABLE_PERFORMANCE_OVERLAY'; +const String BUNDLE_URL = 'WEBF_BUNDLE_URL'; +const String BUNDLE_PATH = 'WEBF_BUNDLE_PATH'; +const String ENABLE_DEBUG = 'WEBF_ENABLE_DEBUG'; +const String ENABLE_PERFORMANCE_OVERLAY = 'WEBF_ENABLE_PERFORMANCE_OVERLAY'; const _white = Color(0xFFFFFFFF); String? getBundleURLFromEnv() { @@ -25,31 +26,33 @@ String? getBundlePathFromEnv() { return Platform.environment[BUNDLE_PATH]; } -void launch({ - KrakenBundle? bundle, - bool? debugEnableInspector, - Color background = _white, - DevToolsService? devToolsService, - HttpClientInterceptor? httpClientInterceptor, - bool? showPerformanceOverlay = false -}) async { +void launch( + {WebFBundle? bundle, + bool? debugEnableInspector, + Color background = _white, + DevToolsService? devToolsService, + HttpClientInterceptor? httpClientInterceptor, + bool? showPerformanceOverlay = false}) async { // Bootstrap binding. ElementsFlutterBinding.ensureInitialized().scheduleWarmUpFrame(); VoidCallback? _ordinaryOnMetricsChanged = window.onMetricsChanged; - Future _initKrakenApp() async { - KrakenNativeChannel channel = KrakenNativeChannel(); + Future _initWebFApp() async { + WebFNativeChannel channel = WebFNativeChannel(); if (bundle == null) { String? backendEntrypointUrl = getBundleURLFromEnv() ?? getBundlePathFromEnv(); backendEntrypointUrl ??= await channel.getUrl(); if (backendEntrypointUrl != null) { - bundle = KrakenBundle.fromUrl(backendEntrypointUrl); + bundle = WebFBundle.fromUrl(backendEntrypointUrl); } } - KrakenController controller = KrakenController(null, window.physicalSize.width / window.devicePixelRatio, window.physicalSize.height / window.devicePixelRatio, + WebFController controller = WebFController( + null, + window.physicalSize.width / window.devicePixelRatio, + window.physicalSize.height / window.devicePixelRatio, background: background, showPerformanceOverlay: showPerformanceOverlay ?? Platform.environment[ENABLE_PERFORMANCE_OVERLAY] != null, methodChannel: channel, @@ -59,7 +62,7 @@ void launch({ autoExecuteEntrypoint: false, ); - controller.view.attachTo(RendererBinding.instance!.renderView); + controller.view.attachTo(RendererBinding.instance.renderView); await controller.executeEntrypoint(); } @@ -72,7 +75,7 @@ void launch({ return; } - await _initKrakenApp(); + await _initWebFApp(); // Should proxy to ordinary window.onMetricsChanged callbacks. if (_ordinaryOnMetricsChanged != null) { @@ -82,6 +85,6 @@ void launch({ } }; } else { - await _initKrakenApp(); + await _initWebFApp(); } } diff --git a/webf/lib/src/module/async_storage.dart b/webf/lib/src/module/async_storage.dart index 1175d2c744..c7a536c0ea 100644 --- a/webf/lib/src/module/async_storage.dart +++ b/webf/lib/src/module/async_storage.dart @@ -1,11 +1,11 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ - import 'dart:async'; -import 'package:kraken/src/module/module_manager.dart'; +import 'package:webf/src/module/module_manager.dart'; import 'package:shared_preferences/shared_preferences.dart'; class AsyncStorageModule extends BaseModule { @@ -57,8 +57,7 @@ class AsyncStorageModule extends BaseModule { } @override - void dispose() { - } + void dispose() {} @override String invoke(String method, params, InvokeModuleCallback callback) { diff --git a/webf/lib/src/module/clipboard.dart b/webf/lib/src/module/clipboard.dart index 580c848f67..ec5597ad96 100644 --- a/webf/lib/src/module/clipboard.dart +++ b/webf/lib/src/module/clipboard.dart @@ -1,10 +1,10 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ - import 'package:flutter/services.dart'; -import 'package:kraken/src/module/module_manager.dart'; +import 'package:webf/src/module/module_manager.dart'; class ClipBoardModule extends BaseModule { @override diff --git a/webf/lib/src/module/connection.dart b/webf/lib/src/module/connection.dart index d6512f9a67..4a939b671e 100644 --- a/webf/lib/src/module/connection.dart +++ b/webf/lib/src/module/connection.dart @@ -1,8 +1,9 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -import 'package:connectivity/connectivity.dart'; +import 'package:connectivity_plus/connectivity_plus.dart'; import 'module_manager.dart'; @@ -58,18 +59,20 @@ class ConnectionModule extends BaseModule { @override String invoke(String method, params, InvokeModuleCallback callback) { switch (method) { - case 'getConnectivity': { - getConnectivity((Map json) { - callback(data: json); - }); - break; - } - case 'onConnectivityChanged': { - onConnectivityChanged((Map data) { - moduleManager!.emitModuleEvent(name, data: data); - }); - break; - } + case 'getConnectivity': + { + getConnectivity((Map json) { + callback(data: json); + }); + break; + } + case 'onConnectivityChanged': + { + onConnectivityChanged((Map data) { + moduleManager!.emitModuleEvent(name, data: data); + }); + break; + } } return ''; diff --git a/webf/lib/src/module/fetch.dart b/webf/lib/src/module/fetch.dart index 1053a36601..6ea9a428f6 100644 --- a/webf/lib/src/module/fetch.dart +++ b/webf/lib/src/module/fetch.dart @@ -1,13 +1,14 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:io'; import 'dart:typed_data'; import 'package:flutter/foundation.dart'; -import 'package:kraken/foundation.dart'; -import 'package:kraken/module.dart'; +import 'package:webf/foundation.dart'; +import 'package:webf/module.dart'; String EMPTY_STRING = ''; @@ -41,7 +42,7 @@ class FetchModule extends BaseModule { } } - static const String fallbackUserAgent = 'Kraken'; + static const String fallbackUserAgent = 'WebF'; static String? _defaultUserAgent; static String _getDefaultUserAgent() { if (_defaultUserAgent == null) { @@ -57,8 +58,7 @@ class FetchModule extends BaseModule { @visibleForTesting Future getRequest(Uri uri, String? method, Map? headers, data) { - return httpClient.openUrl(method ?? 'GET', uri) - .then((HttpClientRequest request) { + return httpClient.openUrl(method ?? 'GET', uri).then((HttpClientRequest request) { // Reset Kraken UA. request.headers.removeAll(HttpHeaders.userAgentHeader); request.headers.add(HttpHeaders.userAgentHeader, _getDefaultUserAgent()); @@ -98,36 +98,34 @@ class FetchModule extends BaseModule { } callback(error: errmsg); } + if (uri.host.isEmpty) { // No host specified in URI. _handleError('Failed to parse URL from $uri.', null); } else { HttpClientResponse? response; - getRequest(uri, options['method'], options['headers'], options['body']) - .then((HttpClientRequest request) { - if (_disposed) return Future.value(null); - return request.close(); - }) - .then((HttpClientResponse? res) { - if (res == null) { - return Future.value(null); - } else { - response = res; - return consolidateHttpClientResponseBytes(res); - } - }) - .then((Uint8List? bytes) { - if (bytes == null) return Future.value(null); - else return resolveStringFromData(bytes); - }) - .then((String? content) { - if (content != null) { - callback(data: [EMPTY_STRING, response?.statusCode, content]); - } else { - throw FlutterError('Failed to read response.'); - } - }) - .catchError(_handleError); + getRequest(uri, options['method'], options['headers'], options['body']).then((HttpClientRequest request) { + if (_disposed) return Future.value(null); + return request.close(); + }).then((HttpClientResponse? res) { + if (res == null) { + return Future.value(null); + } else { + response = res; + return consolidateHttpClientResponseBytes(res); + } + }).then((Uint8List? bytes) { + if (bytes == null) + return Future.value(null); + else + return resolveStringFromData(bytes); + }).then((String? content) { + if (content != null) { + callback(data: [EMPTY_STRING, response?.statusCode, content]); + } else { + throw FlutterError('Failed to read response.'); + } + }).catchError(_handleError); } return EMPTY_STRING; diff --git a/webf/lib/src/module/history.dart b/webf/lib/src/module/history.dart index fcc699c287..fa0c2a4379 100644 --- a/webf/lib/src/module/history.dart +++ b/webf/lib/src/module/history.dart @@ -1,16 +1,17 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ +import 'dart:async'; import 'dart:collection'; import 'dart:convert'; -import 'dart:async'; -import 'package:kraken/dom.dart'; -import 'package:kraken/kraken.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/webf.dart'; class HistoryItem { HistoryItem(this.bundle, this.state, this.needJump); - final KrakenBundle bundle; + final WebFBundle bundle; final dynamic state; final bool needJump; } @@ -24,7 +25,7 @@ class HistoryModule extends BaseModule { Queue get _previousStack => moduleManager!.controller.previousHistoryStack; Queue get _nextStack => moduleManager!.controller.nextHistoryStack; - KrakenBundle? get stackTop { + WebFBundle? get stackTop { if (_previousStack.isEmpty) { return null; } else { @@ -32,7 +33,7 @@ class HistoryModule extends BaseModule { } } - void add(KrakenBundle bundle) { + void add(WebFBundle bundle) { HistoryItem history = HistoryItem(bundle, null, true); _addItem(history); } @@ -43,12 +44,11 @@ class HistoryModule extends BaseModule { _previousStack.addFirst(historyItem); // Clear. - while(_nextStack.isNotEmpty) { + while (_nextStack.isNotEmpty) { _nextStack.removeFirst(); } } - void _back() async { if (_previousStack.length > 1) { HistoryItem currentItem = _previousStack.first; @@ -80,7 +80,7 @@ class HistoryModule extends BaseModule { return; } - for (int i = 0; i < num; i ++) { + for (int i = 0; i < num; i++) { HistoryItem currentItem = _nextStack.first; _nextStack.removeFirst(); _previousStack.addFirst(currentItem); @@ -90,7 +90,7 @@ class HistoryModule extends BaseModule { return; } - for (int i = 0; i < num.abs(); i ++) { + for (int i = 0; i < num.abs(); i++) { HistoryItem currentItem = _previousStack.first; _previousStack.removeFirst(); _nextStack.addFirst(currentItem); @@ -113,7 +113,7 @@ class HistoryModule extends BaseModule { } void _pushState(List params) { - KrakenController controller = moduleManager!.controller; + WebFController controller = moduleManager!.controller; dynamic state = params[0]; String? url = null; @@ -132,14 +132,14 @@ class HistoryModule extends BaseModule { return; } - KrakenBundle bundle = KrakenBundle.fromUrl(uri.toString()); + WebFBundle bundle = WebFBundle.fromUrl(uri.toString()); HistoryItem history = HistoryItem(bundle, state, false); _addItem(history); } } void _replaceState(List params) { - KrakenController controller = moduleManager!.controller; + WebFController controller = moduleManager!.controller; dynamic state = params[0]; String? url = null; @@ -158,7 +158,7 @@ class HistoryModule extends BaseModule { return; } - KrakenBundle bundle = KrakenBundle.fromUrl(uri.toString()); + WebFBundle bundle = WebFBundle.fromUrl(uri.toString()); HistoryItem history = HistoryItem(bundle, state, false); _previousStack.removeFirst(); @@ -168,7 +168,7 @@ class HistoryModule extends BaseModule { @override String invoke(String method, params, InvokeModuleCallback callback) { - switch(method) { + switch (method) { case 'length': return (_previousStack.length + _nextStack.length).toString(); case 'state': @@ -197,6 +197,5 @@ class HistoryModule extends BaseModule { } @override - void dispose() { - } + void dispose() {} } diff --git a/webf/lib/src/module/location.dart b/webf/lib/src/module/location.dart index a785f96d7e..ef9fdcb854 100644 --- a/webf/lib/src/module/location.dart +++ b/webf/lib/src/module/location.dart @@ -1,7 +1,8 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -import 'package:kraken/module.dart'; +import 'package:webf/module.dart'; class LocationModule extends BaseModule { @override diff --git a/webf/lib/src/module/method_channel.dart b/webf/lib/src/module/method_channel.dart index 0998145ec3..d314991f5e 100644 --- a/webf/lib/src/module/method_channel.dart +++ b/webf/lib/src/module/method_channel.dart @@ -1,15 +1,16 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; -import 'package:kraken/kraken.dart'; +import 'package:webf/webf.dart'; typedef MethodCallCallback = Future Function(String method, Object? arguments); const String METHOD_CHANNEL_NOT_INITIALIZED = 'MethodChannel not initialized.'; -const String CONTROLLER_NOT_INITIALIZED = 'Kraken controller not initialized.'; +const String CONTROLLER_NOT_INITIALIZED = 'WebF controller not initialized.'; const String METHOD_CHANNEL_NAME = 'MethodChannel'; class MethodChannelModule extends BaseModule { @@ -33,7 +34,7 @@ class MethodChannelModule extends BaseModule { } } -void setJSMethodCallCallback(KrakenController controller) { +void setJSMethodCallCallback(WebFController controller) { if (controller.methodChannel == null) return; controller.methodChannel!._onJSMethodCall = (String method, arguments) async { @@ -45,7 +46,7 @@ void setJSMethodCallCallback(KrakenController controller) { }; } -abstract class KrakenMethodChannel { +abstract class WebFMethodChannel { MethodCallCallback? _onJSMethodCallCallback; set _onJSMethodCall(MethodCallCallback? value) { @@ -55,14 +56,14 @@ abstract class KrakenMethodChannel { Future invokeMethodFromJavaScript(String method, List arguments); - static void setJSMethodCallCallback(KrakenController controller) { + static void setJSMethodCallCallback(WebFController controller) { controller.methodChannel?._onJSMethodCall = (String method, arguments) async { controller.module.moduleManager.emitModuleEvent(METHOD_CHANNEL_NAME, data: [method, arguments]); }; } } -class KrakenJavaScriptChannel extends KrakenMethodChannel { +class WebFJavaScriptChannel extends WebFMethodChannel { Future invokeMethod(String method, arguments) async { MethodCallCallback? jsMethodCallCallback = _onJSMethodCallCallback; if (jsMethodCallCallback != null) { @@ -92,14 +93,14 @@ class KrakenJavaScriptChannel extends KrakenMethodChannel { } } -class KrakenNativeChannel extends KrakenMethodChannel { +class WebFNativeChannel extends WebFMethodChannel { // Flutter method channel used to communicate with public SDK API // Only works when integration wieh public SDK API - static final MethodChannel _nativeChannel = getKrakenMethodChannel() + static final MethodChannel _nativeChannel = getWebFMethodChannel() ..setMethodCallHandler((call) async { String method = call.method; - KrakenController? controller = KrakenController.getControllerOfJSContextId(0); + WebFController? controller = WebFController.getControllerOfJSContextId(0); if (controller == null) return; @@ -135,15 +136,15 @@ class KrakenNativeChannel extends KrakenMethodChannel { static Future syncDynamicLibraryPath() async { String? path = await _nativeChannel.invokeMethod('getDynamicLibraryPath'); if (path != null) { - KrakenDynamicLibrary.dynamicLibraryPath = path; + WebFDynamicLibrary.dynamicLibraryPath = path; } } } -Future _invokeMethodFromJavaScript(KrakenController? controller, String method, List args) { - KrakenMethodChannel? krakenMethodChannel = controller?.methodChannel; - if (krakenMethodChannel != null) { - return krakenMethodChannel.invokeMethodFromJavaScript(method, args); +Future _invokeMethodFromJavaScript(WebFController? controller, String method, List args) { + WebFMethodChannel? webFMethodChannel = controller?.methodChannel; + if (webFMethodChannel != null) { + return webFMethodChannel.invokeMethodFromJavaScript(method, args); } else { return Future.error(FlutterError(METHOD_CHANNEL_NOT_INITIALIZED)); } diff --git a/webf/lib/src/module/module_manager.dart b/webf/lib/src/module/module_manager.dart index 3acf17c944..f1ad8ec966 100644 --- a/webf/lib/src/module/module_manager.dart +++ b/webf/lib/src/module/module_manager.dart @@ -1,11 +1,12 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:convert'; -import 'package:kraken/bridge.dart' as bridge; -import 'package:kraken/dom.dart'; -import 'package:kraken/kraken.dart'; +import 'package:webf/bridge.dart' as bridge; +import 'package:webf/dom.dart'; +import 'package:webf/webf.dart'; abstract class BaseModule { String get name; @@ -15,13 +16,13 @@ abstract class BaseModule { void dispose(); } -typedef InvokeModuleCallback = void Function({String ?error, Object? data}); +typedef InvokeModuleCallback = void Function({String? error, Object? data}); typedef NewModuleCreator = BaseModule Function(ModuleManager); typedef ModuleCreator = BaseModule Function(ModuleManager? moduleManager); class ModuleManager { final int contextId; - final KrakenController controller; + final WebFController controller; static final Map _creatorMap = {}; static bool inited = false; diff --git a/webf/lib/src/module/navigation.dart b/webf/lib/src/module/navigation.dart index 74a9877515..1ba2f4e6d2 100644 --- a/webf/lib/src/module/navigation.dart +++ b/webf/lib/src/module/navigation.dart @@ -1,12 +1,13 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'module_manager.dart'; -typedef KrakenNavigationDecisionHandler = Future Function(KrakenNavigationAction action); -typedef KrakenNavigationErrorHandler = void Function(Object error, Object stack); +typedef WebFNavigationDecisionHandler = Future Function(WebFNavigationAction action); +typedef WebFNavigationErrorHandler = void Function(Object error, Object stack); -enum KrakenNavigationActionPolicy { +enum WebFNavigationActionPolicy { // allow kraken to perform navigate. allow, @@ -15,7 +16,7 @@ enum KrakenNavigationActionPolicy { } // https://www.w3.org/TR/navigation-timing-2/#sec-performance-navigation-types -enum KrakenNavigationType { +enum WebFNavigationType { // Navigation where the history handling behavior is set to "default" // or "replace" and the navigation was not initiated by a prerender hint. navigate, @@ -46,7 +47,8 @@ class NavigationModule extends BaseModule { Uri targetUri = Uri.parse(targetUrl); Uri sourceUri = Uri.parse(sourceUrl); - await moduleManager!.controller.view.handleNavigationAction(sourceUrl, targetUrl, targetUri == sourceUri ? KrakenNavigationType.reload : KrakenNavigationType.navigate); + await moduleManager!.controller.view.handleNavigationAction( + sourceUrl, targetUrl, targetUri == sourceUri ? WebFNavigationType.reload : WebFNavigationType.navigate); } @override @@ -60,8 +62,8 @@ class NavigationModule extends BaseModule { } } -class KrakenNavigationAction { - KrakenNavigationAction(this.source, this.target, this.navigationType); +class WebFNavigationAction { + WebFNavigationAction(this.source, this.target, this.navigationType); // The current source url. String? source; @@ -70,27 +72,27 @@ class KrakenNavigationAction { String target; // The navigation type. - KrakenNavigationType navigationType; + WebFNavigationType navigationType; @override - String toString() => 'KrakenNavigationType(source:$source, target:$target, navigationType:$navigationType)'; + String toString() => 'WebFNavigationType(source:$source, target:$target, navigationType:$navigationType)'; } -Future defaultDecisionHandler(KrakenNavigationAction action) async { - return KrakenNavigationActionPolicy.allow; +Future defaultDecisionHandler(WebFNavigationAction action) async { + return WebFNavigationActionPolicy.allow; } -class KrakenNavigationDelegate { +class WebFNavigationDelegate { // Called when an error occurs during navigation. - KrakenNavigationErrorHandler? errorHandler; + WebFNavigationErrorHandler? errorHandler; - KrakenNavigationDecisionHandler _decisionHandler = defaultDecisionHandler; + WebFNavigationDecisionHandler _decisionHandler = defaultDecisionHandler; - void setDecisionHandler(KrakenNavigationDecisionHandler handler) { + void setDecisionHandler(WebFNavigationDecisionHandler handler) { _decisionHandler = handler; } - Future dispatchDecisionHandler(KrakenNavigationAction action) async { + Future dispatchDecisionHandler(WebFNavigationAction action) async { return await _decisionHandler(action); } } diff --git a/webf/lib/src/module/navigator.dart b/webf/lib/src/module/navigator.dart index e9e28c2242..bb3e14c9b1 100644 --- a/webf/lib/src/module/navigator.dart +++ b/webf/lib/src/module/navigator.dart @@ -1,11 +1,12 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:io' show Platform; import 'dart:ui'; -import 'package:kraken/bridge.dart'; -import 'package:kraken/src/module/module_manager.dart'; +import 'package:webf/bridge.dart'; +import 'package:webf/src/module/module_manager.dart'; String? _customUserAgent; @@ -50,7 +51,7 @@ class NavigatorModule extends BaseModule { static String getLanguages() { // Stringify the list of languages to JSON format. - return '[' + PlatformDispatcher.instance.locales.map(((locale) => '"${locale.toLanguageTag()}"')).join(',') + ']'; + return '[' + PlatformDispatcher.instance.locales.map(((locale) => '"${locale.toLanguageTag()}"')).join(',') + ']'; } static String getHardwareConcurrency() { @@ -58,12 +59,12 @@ class NavigatorModule extends BaseModule { } static String getAppName() { - KrakenInfo info = getKrakenInfo(); + WebFInfo info = getWebFInfo(); return info.appName; } static String getAppVersion() { - KrakenInfo info = getKrakenInfo(); + WebFInfo info = getWebFInfo(); return info.appVersion; } @@ -79,7 +80,7 @@ class NavigatorModule extends BaseModule { } static String getDefaultUserAgent() { - KrakenInfo info = getKrakenInfo(); + WebFInfo info = getWebFInfo(); String appName = info.appName; String appVersion = info.appVersion; String appRevision = info.appRevision; diff --git a/webf/lib/src/module/performance_timing.dart b/webf/lib/src/module/performance_timing.dart index 32ac1e646f..fd4d03a5b2 100644 --- a/webf/lib/src/module/performance_timing.dart +++ b/webf/lib/src/module/performance_timing.dart @@ -1,11 +1,12 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:ffi'; import 'dart:typed_data'; import 'package:ffi/ffi.dart'; -import 'package:kraken/bridge.dart'; +import 'package:webf/bridge.dart'; final String PERF_CONTROLLER_INIT_START = 'controller_init_start'; final String PERF_CONTROLLER_INIT_END = 'controller_init_end'; @@ -103,7 +104,8 @@ class PerformanceTiming { } Pointer toNative() { - Pointer list = malloc.allocate(sizeOf()); + Pointer list = + malloc.allocate(sizeOf()); int byteLength = entries.length * 3; Uint64List data = Uint64List(byteLength); @@ -117,7 +119,7 @@ class PerformanceTiming { dataIndex++; } - final Pointer bytes = malloc.allocate(sizeOf() * byteLength); + final Pointer bytes = malloc.allocate(sizeOf() * byteLength); final Uint64List buffer = bytes.asTypedList(byteLength); buffer.setAll(0, data); diff --git a/webf/lib/src/module/schedule_frame.dart b/webf/lib/src/module/schedule_frame.dart index 93fb3080e3..ac3d155f7b 100644 --- a/webf/lib/src/module/schedule_frame.dart +++ b/webf/lib/src/module/schedule_frame.dart @@ -1,8 +1,8 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ - import 'package:flutter/scheduler.dart'; typedef DoubleCallback = void Function(double); @@ -15,14 +15,14 @@ mixin ScheduleFrameMixin { int requestAnimationFrame(DoubleCallback callback) { int id = _id++; _animationFrameCallbackMap[id] = true; - SchedulerBinding.instance!.addPostFrameCallback((Duration timeStamp) { + SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) { if (_animationFrameCallbackMap.containsKey(id)) { _animationFrameCallbackMap.remove(id); double highResTimeStamp = timeStamp.inMicroseconds / 1000; callback(highResTimeStamp); } }); - SchedulerBinding.instance!.scheduleFrame(); + SchedulerBinding.instance.scheduleFrame(); return id; } @@ -33,7 +33,7 @@ mixin ScheduleFrameMixin { } void requestBatchUpdate() { - SchedulerBinding.instance!.scheduleFrame(); + SchedulerBinding.instance.scheduleFrame(); } void disposeScheduleFrame() { diff --git a/webf/lib/src/module/timer.dart b/webf/lib/src/module/timer.dart index 3e9a5d598e..62361e807e 100644 --- a/webf/lib/src/module/timer.dart +++ b/webf/lib/src/module/timer.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; diff --git a/webf/lib/src/painting/box_fit_image.dart b/webf/lib/src/painting/box_fit_image.dart index b2c2d071fc..bc8bbad282 100644 --- a/webf/lib/src/painting/box_fit_image.dart +++ b/webf/lib/src/painting/box_fit_image.dart @@ -1,14 +1,15 @@ /* - * Copyright (C) 2022-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ +import 'dart:async'; import 'dart:typed_data'; import 'dart:ui'; -import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/foundation.dart'; class BoxFitImageKey { const BoxFitImageKey({ @@ -21,11 +22,8 @@ class BoxFitImageKey { @override bool operator ==(Object other) { - if (other.runtimeType != runtimeType) - return false; - return other is BoxFitImageKey - && other.url == url - && other.configuration == configuration; + if (other.runtimeType != runtimeType) return false; + return other is BoxFitImageKey && other.url == url && other.configuration == configuration; } @override @@ -63,7 +61,8 @@ class BoxFitImage extends ImageProvider { Uint8List bytes = await loadImage(url); final ImmutableBuffer buffer = await ImmutableBuffer.fromUint8List(bytes); final ImageDescriptor descriptor = await ImageDescriptor.encoded(buffer); - final Codec codec = await _instantiateImageCodec(descriptor, + final Codec codec = await _instantiateImageCodec( + descriptor, boxFit: boxFit, preferredWidth: key.configuration?.size?.width.toInt(), preferredHeight: key.configuration?.size?.height.toInt(), @@ -96,9 +95,10 @@ class BoxFitImage extends ImageProvider { } @override - void resolveStreamForKey(ImageConfiguration configuration, ImageStream stream, BoxFitImageKey key, ImageErrorListener handleError) { + void resolveStreamForKey( + ImageConfiguration configuration, ImageStream stream, BoxFitImageKey key, ImageErrorListener handleError) { if (stream.completer != null) { - final ImageStreamCompleter? completer = PaintingBinding.instance!.imageCache!.putIfAbsent( + final ImageStreamCompleter? completer = PaintingBinding.instance.imageCache.putIfAbsent( key, () => stream.completer!, onError: handleError, @@ -106,12 +106,14 @@ class BoxFitImage extends ImageProvider { assert(identical(completer, stream.completer)); return; } - final ImageStreamCompleter? completer = PaintingBinding.instance!.imageCache!.putIfAbsent( + final ImageStreamCompleter? completer = PaintingBinding.instance.imageCache.putIfAbsent( key, - () => load(key, PaintingBinding.instance!.instantiateImageCodec), + () => load(key, PaintingBinding.instance.instantiateImageCodec), onError: handleError, ); - if (_imageStreamCompleter == null && completer is DimensionedMultiFrameImageStreamCompleter && onImageLoad != null) { + if (_imageStreamCompleter == null && + completer is DimensionedMultiFrameImageStreamCompleter && + onImageLoad != null) { completer.dimension.then((Dimension dimension) { onImageLoad!(dimension.width, dimension.height); }); @@ -121,7 +123,8 @@ class BoxFitImage extends ImageProvider { } } - static Future _instantiateImageCodec(ImageDescriptor descriptor, { + static Future _instantiateImageCodec( + ImageDescriptor descriptor, { BoxFit? boxFit = BoxFit.none, int? preferredWidth, int? preferredHeight, @@ -209,8 +212,12 @@ class DimensionedMultiFrameImageStreamCompleter extends MultiFrameImageStreamCom String? debugLabel, Stream? chunkEvents, InformationCollector? informationCollector, - }) : super(codec: codec, scale: scale, debugLabel: debugLabel, - chunkEvents: chunkEvents, informationCollector: informationCollector); + }) : super( + codec: codec, + scale: scale, + debugLabel: debugLabel, + chunkEvents: chunkEvents, + informationCollector: informationCollector); final List> _dimensionCompleter = []; Dimension? _dimension; diff --git a/webf/lib/src/painting/cached_network_image.dart b/webf/lib/src/painting/cached_network_image.dart index 3d788879a4..4c05b77c69 100644 --- a/webf/lib/src/painting/cached_network_image.dart +++ b/webf/lib/src/painting/cached_network_image.dart @@ -1,8 +1,8 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ - import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; @@ -10,13 +10,10 @@ import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/foundation.dart'; class CachedNetworkImageKey { - const CachedNetworkImageKey({ - required this.url, - required this.scale - }); + const CachedNetworkImageKey({required this.url, required this.scale}); final String url; @@ -24,11 +21,8 @@ class CachedNetworkImageKey { @override bool operator ==(Object other) { - if (other.runtimeType != runtimeType) - return false; - return other is CachedNetworkImageKey - && other.url == url - && other.scale == scale; + if (other.runtimeType != runtimeType) return false; + return other is CachedNetworkImageKey && other.url == url && other.scale == scale; } @override @@ -62,8 +56,7 @@ class CachedNetworkImage extends ImageProvider { } Future _getRawImageBytes(CachedNetworkImageKey key, StreamController chunkEvents) async { - HttpCacheController cacheController = HttpCacheController.instance( - getOrigin(getEntrypointUri(contextId))); + HttpCacheController cacheController = HttpCacheController.instance(getOrigin(getEntrypointUri(contextId))); Uri uri = Uri.parse(url); Uint8List? bytes; @@ -89,8 +82,7 @@ class CachedNetworkImage extends ImageProvider { return decode(bytes); } - Future _fetchImageBytes(CachedNetworkImageKey key, - StreamController chunkEvents, + Future _fetchImageBytes(CachedNetworkImageKey key, StreamController chunkEvents, HttpCacheController cacheController) async { try { final Uri resolved = Uri.base.resolve(key.url); @@ -102,10 +94,8 @@ class CachedNetworkImage extends ImageProvider { if (response.statusCode != HttpStatus.ok) throw NetworkImageLoadException(statusCode: response.statusCode, uri: resolved); - HttpCacheObject cacheObject = HttpCacheObject.fromResponse( - key.url, - response, - (await HttpCacheController.getCacheDirectory()).path); + HttpCacheObject cacheObject = + HttpCacheObject.fromResponse(key.url, response, (await HttpCacheController.getCacheDirectory()).path); cacheController.putObject(resolved, cacheObject); HttpClientResponse _response = HttpClientCachedResponse(response, cacheObject); @@ -129,10 +119,7 @@ class CachedNetworkImage extends ImageProvider { @override Future obtainKey(ImageConfiguration configuration) { - return SynchronousFuture(CachedNetworkImageKey( - url: url, - scale: scale - )); + return SynchronousFuture(CachedNetworkImageKey(url: url, scale: scale)); } @override diff --git a/webf/lib/src/painting/image_provider_factory.dart b/webf/lib/src/painting/image_provider_factory.dart index 7c1b910e41..766e0d4af7 100644 --- a/webf/lib/src/painting/image_provider_factory.dart +++ b/webf/lib/src/painting/image_provider_factory.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2020-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:io'; @@ -8,9 +9,9 @@ import 'dart:typed_data'; import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; -import 'package:kraken/foundation.dart'; -import 'package:kraken/painting.dart'; -import 'package:kraken/src/module/navigator.dart'; +import 'package:webf/foundation.dart'; +import 'package:webf/painting.dart'; +import 'package:webf/src/module/navigator.dart'; /// This class allows user to customize Kraken's image loading. @@ -33,22 +34,19 @@ class CachedNetworkImageProviderParams extends ImageProviderParams { class FileImageProviderParams extends ImageProviderParams { File file; - FileImageProviderParams(this.file, - {int? cachedWidth, int? cachedHeight, BoxFit objectFit = BoxFit.fill}) + FileImageProviderParams(this.file, {int? cachedWidth, int? cachedHeight, BoxFit objectFit = BoxFit.fill}) : super(cachedWidth: cachedWidth, cachedHeight: cachedHeight, objectFit: objectFit); } class DataUrlImageProviderParams extends ImageProviderParams { Uint8List bytes; - DataUrlImageProviderParams(this.bytes, - {int? cachedWidth, int? cachedHeight, BoxFit objectFit = BoxFit.fill}) + DataUrlImageProviderParams(this.bytes, {int? cachedWidth, int? cachedHeight, BoxFit objectFit = BoxFit.fill}) : super(cachedWidth: cachedWidth, cachedHeight: cachedHeight, objectFit: objectFit); } /// A factory function allow user to build an customized ImageProvider class. -typedef ImageProviderFactory = ImageProvider? Function( - Uri uri, ImageProviderParams params); +typedef ImageProviderFactory = ImageProvider? Function(Uri uri, ImageProviderParams params); /// defines the types of supported image source. enum ImageType { @@ -109,9 +107,7 @@ ImageProviderFactory _assetsProviderFactory = defaultAssetsProvider; ImageType parseImageUrl(Uri resolvedUri, {String cache = 'auto'}) { if (resolvedUri.isScheme('HTTP') || resolvedUri.isScheme('HTTPS')) { - return (cache == 'store' || cache == 'auto') - ? ImageType.cached - : ImageType.network; + return (cache == 'store' || cache == 'auto') ? ImageType.cached : ImageType.network; } else if (resolvedUri.isScheme('FILE')) { return ImageType.file; } else if (resolvedUri.isScheme('DATA')) { @@ -143,10 +139,8 @@ ImageProvider? getImageProvider(Uri resolvedUri, cachedWidth: cachedWidth, cachedHeight: cachedHeight, objectFit: objectFit)); case ImageType.file: File file = File.fromUri(resolvedUri); - return factory( - resolvedUri, - FileImageProviderParams(file, - cachedWidth: cachedWidth, cachedHeight: cachedHeight, objectFit: objectFit)); + return factory(resolvedUri, + FileImageProviderParams(file, cachedWidth: cachedWidth, cachedHeight: cachedHeight, objectFit: objectFit)); case ImageType.dataUrl: // Data URL: https://tools.ietf.org/html/rfc2397 // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data @@ -163,9 +157,7 @@ ImageProvider? getImageProvider(Uri resolvedUri, return null; case ImageType.assets: return factory( - resolvedUri, - ImageProviderParams( - cachedWidth: cachedWidth, cachedHeight: cachedHeight, objectFit: objectFit)); + resolvedUri, ImageProviderParams(cachedWidth: cachedWidth, cachedHeight: cachedHeight, objectFit: objectFit)); } } @@ -187,8 +179,8 @@ ImageProviderFactory _getImageProviderFactory(ImageType imageType) { } } -class KrakenResizeImage extends ResizeImage { - KrakenResizeImage( +class WebFResizeImage extends ResizeImage { + WebFResizeImage( ImageProvider imageProvider, { int? width, int? height, @@ -200,8 +192,7 @@ class KrakenResizeImage extends ResizeImage { static ImageProvider resizeIfNeeded( int? cacheWidth, int? cacheHeight, BoxFit? objectFit, ImageProvider provider) { if (cacheWidth != null || cacheHeight != null) { - return KrakenResizeImage(provider, - width: cacheWidth, height: cacheHeight, objectFit: objectFit); + return WebFResizeImage(provider, width: cacheWidth, height: cacheHeight, objectFit: objectFit); } return provider; } @@ -212,8 +203,7 @@ class KrakenResizeImage extends ResizeImage { // the image we want before getting to this method. We should avoid calling // load again, but still update the image cache with LRU information. if (stream.completer != null) { - final ImageStreamCompleter? completer = - PaintingBinding.instance!.imageCache!.putIfAbsent( + final ImageStreamCompleter? completer = PaintingBinding.instance.imageCache.putIfAbsent( key, () => stream.completer!, onError: handleError, @@ -221,8 +211,7 @@ class KrakenResizeImage extends ResizeImage { assert(identical(completer, stream.completer)); return; } - final ImageStreamCompleter? completer = - PaintingBinding.instance!.imageCache!.putIfAbsent( + final ImageStreamCompleter? completer = PaintingBinding.instance.imageCache.putIfAbsent( key, () => load(key, instantiateImageCodec), onError: handleError, @@ -263,9 +252,9 @@ class KrakenResizeImage extends ResizeImage { targetWidth = cacheWidth; } - // Resized image should maintain its intrinsic aspect radio event if object-fit is fill - // which behaves just like object-fit cover otherwise the cached resized image with - // distorted aspect ratio will not work when object-fit changes to not fill. + // Resized image should maintain its intrinsic aspect radio event if object-fit is fill + // which behaves just like object-fit cover otherwise the cached resized image with + // distorted aspect ratio will not work when object-fit changes to not fill. } else if (objectFit == BoxFit.fill || objectFit == BoxFit.cover) { if (cacheWidth / cacheHeight > naturalWidth / naturalHeight) { targetWidth = cacheWidth; @@ -273,13 +262,13 @@ class KrakenResizeImage extends ResizeImage { targetHeight = cacheHeight; } - // Image should maintain its aspect radio and not resized if object-fit is none. + // Image should maintain its aspect radio and not resized if object-fit is none. } else if (objectFit == BoxFit.none) { targetWidth = descriptor.width; targetHeight = descriptor.height; - // If image size is smaller than its natural size when object-fit is contain, - // scale-down is parsed as none, otherwise parsed as contain. + // If image size is smaller than its natural size when object-fit is contain, + // scale-down is parsed as none, otherwise parsed as contain. } else if (objectFit == BoxFit.scaleDown) { if (cacheWidth / cacheHeight > naturalWidth / naturalHeight) { if (cacheHeight > descriptor.height * window.devicePixelRatio) { @@ -320,52 +309,30 @@ class KrakenResizeImage extends ResizeImage { } /// default ImageProviderFactory implementation of [ImageType.cached] -ImageProvider defaultCachedProviderFactory( - Uri uri, ImageProviderParams params) { - return KrakenResizeImage.resizeIfNeeded( - params.cachedWidth, - params.cachedHeight, - params.objectFit, - CachedNetworkImage(uri.toString(), - contextId: (params as CachedNetworkImageProviderParams).contextId) - ); +ImageProvider defaultCachedProviderFactory(Uri uri, ImageProviderParams params) { + return WebFResizeImage.resizeIfNeeded(params.cachedWidth, params.cachedHeight, params.objectFit, + CachedNetworkImage(uri.toString(), contextId: (params as CachedNetworkImageProviderParams).contextId)); } /// default ImageProviderFactory implementation of [ImageType.network] -ImageProvider defaultNetworkProviderFactory( - Uri uri, ImageProviderParams params) { +ImageProvider defaultNetworkProviderFactory(Uri uri, ImageProviderParams params) { NetworkImage networkImage = NetworkImage(uri.toString(), headers: { HttpHeaders.userAgentHeader: NavigatorModule.getUserAgent(), - HttpHeaderContext: - (params as CachedNetworkImageProviderParams).contextId.toString(), + HttpHeaderContext: (params as CachedNetworkImageProviderParams).contextId.toString(), }); - return KrakenResizeImage.resizeIfNeeded( - params.cachedWidth, - params.cachedHeight, - params.objectFit, - networkImage - ); + return WebFResizeImage.resizeIfNeeded(params.cachedWidth, params.cachedHeight, params.objectFit, networkImage); } /// default ImageProviderFactory implementation of [ImageType.file] ImageProvider? defaultFileProviderFactory(Uri uri, ImageProviderParams params) { - return KrakenResizeImage.resizeIfNeeded( - params.cachedWidth, - params.cachedHeight, - params.objectFit, - FileImage((params as FileImageProviderParams).file) - ); + return WebFResizeImage.resizeIfNeeded( + params.cachedWidth, params.cachedHeight, params.objectFit, FileImage((params as FileImageProviderParams).file)); } /// default ImageProviderFactory implementation of [ImageType.dataUrl]. -ImageProvider? defaultDataUrlProviderFactory( - Uri uri, ImageProviderParams params) { - return KrakenResizeImage.resizeIfNeeded( - params.cachedWidth, - params.cachedHeight, - params.objectFit, - MemoryImage((params as DataUrlImageProviderParams).bytes) - ); +ImageProvider? defaultDataUrlProviderFactory(Uri uri, ImageProviderParams params) { + return WebFResizeImage.resizeIfNeeded(params.cachedWidth, params.cachedHeight, params.objectFit, + MemoryImage((params as DataUrlImageProviderParams).bytes)); } /// default ImageProviderFactory implementation of [ImageType.blob]. @@ -377,10 +344,6 @@ ImageProvider? defaultBlobProviderFactory(Uri uri, ImageProviderParams params) { /// default ImageProviderFactory implementation of [ImageType.assets]. ImageProvider defaultAssetsProvider(Uri uri, ImageProviderParams params) { final String assetName = AssetsBundle.getAssetName(uri); - return KrakenResizeImage.resizeIfNeeded( - params.cachedWidth, - params.cachedHeight, - params.objectFit, - AssetImage(assetName) - ); + return WebFResizeImage.resizeIfNeeded( + params.cachedWidth, params.cachedHeight, params.objectFit, AssetImage(assetName)); } diff --git a/webf/lib/src/rendering/box_decoration.dart b/webf/lib/src/rendering/box_decoration.dart index c4b2677f4e..bb42b05c7b 100644 --- a/webf/lib/src/rendering/box_decoration.dart +++ b/webf/lib/src/rendering/box_decoration.dart @@ -1,11 +1,12 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/rendering.dart'; +import 'package:webf/css.dart'; +import 'package:webf/rendering.dart'; enum BackgroundBoundary { borderBox, @@ -27,18 +28,15 @@ mixin RenderBoxDecorationMixin on RenderBoxModelBase { _painter = null; } - void paintBackground( - PaintingContext context, Offset offset, EdgeInsets? padding) { + void paintBackground(PaintingContext context, Offset offset, EdgeInsets? padding) { CSSBoxDecoration? decoration = renderStyle.decoration; DecorationPosition decorationPosition = renderStyle.decorationPosition; ImageConfiguration imageConfiguration = renderStyle.imageConfiguration; if (decoration == null) return; - _painter ??= BoxDecorationPainter( - padding, renderStyle, markNeedsPaint); + _painter ??= BoxDecorationPainter(padding, renderStyle, markNeedsPaint); - final ImageConfiguration filledConfiguration = - imageConfiguration.copyWith(size: size); + final ImageConfiguration filledConfiguration = imageConfiguration.copyWith(size: size); if (decorationPosition == DecorationPosition.background) { int? debugSaveCount; assert(() { @@ -49,16 +47,13 @@ mixin RenderBoxDecorationMixin on RenderBoxModelBase { assert(() { if (debugSaveCount != context.canvas.getSaveCount()) { throw FlutterError.fromParts([ - ErrorSummary( - '${decoration.runtimeType} painter had mismatching save and restore calls.'), - ErrorDescription( - 'Before painting the decoration, the canvas save count was $debugSaveCount. ' + ErrorSummary('${decoration.runtimeType} painter had mismatching save and restore calls.'), + ErrorDescription('Before painting the decoration, the canvas save count was $debugSaveCount. ' 'After painting it, the canvas save count was ${context.canvas.getSaveCount()}. ' 'Every call to save() or saveLayer() must be matched by a call to restore().'), DiagnosticsProperty('The decoration was', decoration, style: DiagnosticsTreeStyle.errorProperty), - DiagnosticsProperty('The painter was', _painter, - style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty('The painter was', _painter, style: DiagnosticsTreeStyle.errorProperty), ]); } return true; @@ -72,8 +67,7 @@ mixin RenderBoxDecorationMixin on RenderBoxModelBase { } } - void paintDecoration( - PaintingContext context, Offset offset, PaintingContextCallback callback) { + void paintDecoration(PaintingContext context, Offset offset, PaintingContextCallback callback) { CSSBoxDecoration? decoration = renderStyle.decoration; DecorationPosition decorationPosition = renderStyle.decorationPosition; ImageConfiguration imageConfiguration = renderStyle.imageConfiguration; @@ -81,11 +75,9 @@ mixin RenderBoxDecorationMixin on RenderBoxModelBase { if (decoration == null) return callback(context, offset); EdgeInsets? padding = renderStyle.padding.resolve(TextDirection.ltr); - _painter ??= - BoxDecorationPainter(padding, renderStyle, markNeedsPaint); + _painter ??= BoxDecorationPainter(padding, renderStyle, markNeedsPaint); - final ImageConfiguration filledConfiguration = - imageConfiguration.copyWith(size: size); + final ImageConfiguration filledConfiguration = imageConfiguration.copyWith(size: size); if (decorationPosition == DecorationPosition.background) { int? debugSaveCount; assert(() { @@ -97,16 +89,13 @@ mixin RenderBoxDecorationMixin on RenderBoxModelBase { assert(() { if (debugSaveCount != context.canvas.getSaveCount()) { throw FlutterError.fromParts([ - ErrorSummary( - '${decoration.runtimeType} painter had mismatching save and restore calls.'), - ErrorDescription( - 'Before painting the decoration, the canvas save count was $debugSaveCount. ' + ErrorSummary('${decoration.runtimeType} painter had mismatching save and restore calls.'), + ErrorDescription('Before painting the decoration, the canvas save count was $debugSaveCount. ' 'After painting it, the canvas save count was ${context.canvas.getSaveCount()}. ' 'Every call to save() or saveLayer() must be matched by a call to restore().'), DiagnosticsProperty('The decoration was', decoration, style: DiagnosticsTreeStyle.errorProperty), - DiagnosticsProperty('The painter was', _painter, - style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty('The painter was', _painter, style: DiagnosticsTreeStyle.errorProperty), ]); } return true; @@ -126,18 +115,14 @@ mixin RenderBoxDecorationMixin on RenderBoxModelBase { } void debugBoxDecorationProperties(DiagnosticPropertiesBuilder properties) { - properties - .add(DiagnosticsProperty('borderEdge', renderStyle.border)); + properties.add(DiagnosticsProperty('borderEdge', renderStyle.border)); if (renderStyle.backgroundClip != null) - properties.add( - DiagnosticsProperty('backgroundClip', renderStyle.backgroundClip)); + properties.add(DiagnosticsProperty('backgroundClip', renderStyle.backgroundClip)); if (renderStyle.backgroundOrigin != null) - properties.add(DiagnosticsProperty( - 'backgroundOrigin', renderStyle.backgroundOrigin)); + properties.add(DiagnosticsProperty('backgroundOrigin', renderStyle.backgroundOrigin)); CSSBoxDecoration? _decoration = renderStyle.decoration; if (_decoration != null && _decoration.hasBorderRadius) - properties - .add(DiagnosticsProperty('borderRadius', _decoration.borderRadius)); + properties.add(DiagnosticsProperty('borderRadius', _decoration.borderRadius)); if (_decoration != null && _decoration.image != null) properties.add(DiagnosticsProperty('backgroundImage', _decoration.image)); if (_decoration != null && _decoration.boxShadow != null) @@ -146,4 +131,3 @@ mixin RenderBoxDecorationMixin on RenderBoxModelBase { properties.add(DiagnosticsProperty('gradient', _decoration.gradient)); } } - diff --git a/webf/lib/src/rendering/box_decoration_painter.dart b/webf/lib/src/rendering/box_decoration_painter.dart index 170e61a4ca..e273967ffe 100644 --- a/webf/lib/src/rendering/box_decoration_painter.dart +++ b/webf/lib/src/rendering/box_decoration_painter.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:ui' as ui show Image; @@ -7,21 +8,14 @@ import 'dart:ui' as ui show Image; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/rendering.dart'; - -enum _BorderDirection { - top, - bottom, - left, - right -} +import 'package:webf/css.dart'; +import 'package:webf/rendering.dart'; + +enum _BorderDirection { top, bottom, left, right } /// An object that paints a [BoxDecoration] into a canvas. class BoxDecorationPainter extends BoxPainter { - BoxDecorationPainter( - this.padding, this.renderStyle, VoidCallback onChanged) - : super(onChanged); + BoxDecorationPainter(this.padding, this.renderStyle, VoidCallback onChanged) : super(onChanged); EdgeInsets? padding; CSSRenderStyle renderStyle; @@ -31,20 +25,16 @@ class BoxDecorationPainter extends BoxPainter { Rect? _rectForCachedBackgroundPaint; Paint? _getBackgroundPaint(Rect rect, TextDirection? textDirection) { - assert( - _decoration.gradient != null || _rectForCachedBackgroundPaint == null); + assert(_decoration.gradient != null || _rectForCachedBackgroundPaint == null); if (_cachedBackgroundPaint == null || - _decoration.color != null || - (_decoration.gradient != null && - _rectForCachedBackgroundPaint != rect)) { + _decoration.color != null || + (_decoration.gradient != null && _rectForCachedBackgroundPaint != rect)) { final Paint paint = Paint(); - if (_decoration.backgroundBlendMode != null) - paint.blendMode = _decoration.backgroundBlendMode!; + if (_decoration.backgroundBlendMode != null) paint.blendMode = _decoration.backgroundBlendMode!; if (_decoration.color != null) paint.color = _decoration.color!; if (_decoration.gradient != null) { - paint.shader = _decoration.gradient! - .createShader(rect, textDirection: textDirection); + paint.shader = _decoration.gradient!.createShader(rect, textDirection: textDirection); _rectForCachedBackgroundPaint = rect; } _cachedBackgroundPaint = paint; @@ -53,8 +43,7 @@ class BoxDecorationPainter extends BoxPainter { return _cachedBackgroundPaint; } - void _paintBox( - Canvas canvas, Rect rect, Paint? paint, TextDirection? textDirection) { + void _paintBox(Canvas canvas, Rect rect, Paint? paint, TextDirection? textDirection) { switch (_decoration.shape) { case BoxShape.circle: assert(!_decoration.hasBorderRadius); @@ -66,9 +55,7 @@ class BoxDecorationPainter extends BoxPainter { if (!_decoration.hasBorderRadius) { canvas.drawRect(rect, paint!); } else { - canvas.drawRRect( - _decoration.borderRadius!.toRRect(rect), - paint!); + canvas.drawRRect(_decoration.borderRadius!.toRRect(rect), paint!); } break; } @@ -76,7 +63,7 @@ class BoxDecorationPainter extends BoxPainter { void _paintShadows(Canvas canvas, Rect rect, TextDirection? textDirection) { if (_decoration.boxShadow == null) return; - for (final KrakenBoxShadow boxShadow in _decoration.boxShadow!) { + for (final WebFBoxShadow boxShadow in _decoration.boxShadow!) { if (boxShadow.inset) { _paintInsetBoxShadow(canvas, rect, textDirection, boxShadow); } else { @@ -87,24 +74,19 @@ class BoxDecorationPainter extends BoxPainter { /// An outer box-shadow casts a shadow as if the border-box of the element were opaque. /// It is clipped inside the border-box of the element. - void _paintBoxShadow(Canvas canvas, Rect rect, TextDirection? textDirection, - BoxShadow boxShadow) { + void _paintBoxShadow(Canvas canvas, Rect rect, TextDirection? textDirection, BoxShadow boxShadow) { final Paint paint = Paint() ..color = boxShadow.color - // Following W3C spec, blur sigma is exactly half the blur radius - // which is different from the value of Flutter: - // https://www.w3.org/TR/css-backgrounds-3/#shadow-blur - // https://html.spec.whatwg.org/C/#when-shadows-are-drawn - ..maskFilter = - MaskFilter.blur(BlurStyle.normal, boxShadow.blurRadius / 2); + // Following W3C spec, blur sigma is exactly half the blur radius + // which is different from the value of Flutter: + // https://www.w3.org/TR/css-backgrounds-3/#shadow-blur + // https://html.spec.whatwg.org/C/#when-shadows-are-drawn + ..maskFilter = MaskFilter.blur(BlurStyle.normal, boxShadow.blurRadius / 2); // Rect of box shadow not including blur radius - final Rect shadowRect = - rect.shift(boxShadow.offset).inflate(boxShadow.spreadRadius); + final Rect shadowRect = rect.shift(boxShadow.offset).inflate(boxShadow.spreadRadius); // Rect of box shadow including blur radius, add 1 pixel to avoid the fill bleed in (due to antialiasing) - final Rect shadowBlurRect = rect - .shift(boxShadow.offset) - .inflate(boxShadow.spreadRadius + boxShadow.blurRadius + 1); + final Rect shadowBlurRect = rect.shift(boxShadow.offset).inflate(boxShadow.spreadRadius + boxShadow.blurRadius + 1); // Path of border rect Path borderPath; // Path of box shadow rect @@ -117,22 +99,13 @@ class BoxDecorationPainter extends BoxPainter { shadowPath = Path()..addRect(shadowRect); shadowBlurPath = Path()..addRect(shadowBlurRect); } else { - borderPath = Path() - ..addRRect( - _decoration.borderRadius!.toRRect(rect)); - shadowPath = Path() - ..addRRect(_decoration.borderRadius! - .resolve(textDirection) - .toRRect(shadowRect)); - shadowBlurPath = Path() - ..addRRect(_decoration.borderRadius! - .resolve(textDirection) - .toRRect(shadowBlurRect)); + borderPath = Path()..addRRect(_decoration.borderRadius!.toRRect(rect)); + shadowPath = Path()..addRRect(_decoration.borderRadius!.resolve(textDirection).toRRect(shadowRect)); + shadowBlurPath = Path()..addRRect(_decoration.borderRadius!.resolve(textDirection).toRRect(shadowBlurRect)); } // Path of shadow blur rect subtract border rect of which the box shadow should paint - final Path clippedPath = - Path.combine(PathOperation.difference, shadowBlurPath, borderPath); + final Path clippedPath = Path.combine(PathOperation.difference, shadowBlurPath, borderPath); canvas.save(); canvas.clipPath(clippedPath); canvas.drawPath(shadowPath, paint); @@ -141,26 +114,23 @@ class BoxDecorationPainter extends BoxPainter { /// An inner box-shadow casts a shadow as if everything outside the padding edge were opaque. /// It is clipped outside the padding box of the element. - void _paintInsetBoxShadow(Canvas canvas, Rect rect, TextDirection? textDirection, - BoxShadow boxShadow) { + void _paintInsetBoxShadow(Canvas canvas, Rect rect, TextDirection? textDirection, BoxShadow boxShadow) { final Paint paint = Paint() ..color = boxShadow.color - // Following W3C spec, blur sigma is exactly half the blur radius - // which is different from the value of Flutter: - // https://www.w3.org/TR/css-backgrounds-3/#shadow-blur - // https://html.spec.whatwg.org/C/#when-shadows-are-drawn - ..maskFilter = - MaskFilter.blur(BlurStyle.normal, boxShadow.blurRadius / 2); + // Following W3C spec, blur sigma is exactly half the blur radius + // which is different from the value of Flutter: + // https://www.w3.org/TR/css-backgrounds-3/#shadow-blur + // https://html.spec.whatwg.org/C/#when-shadows-are-drawn + ..maskFilter = MaskFilter.blur(BlurStyle.normal, boxShadow.blurRadius / 2); // The normal box-shadow is drawn outside the border box edge while // the inset box-shadow is drawn inside the padding box edge. // https://drafts.csswg.org/css-backgrounds-3/#shadow-shape Rect paddingBoxRect = Rect.fromLTRB( - rect.left + renderStyle.effectiveBorderLeftWidth.computedValue, - rect.top + renderStyle.effectiveBorderTopWidth.computedValue, - rect.right - renderStyle.effectiveBorderRightWidth.computedValue, - rect.bottom - renderStyle.effectiveBorderBottomWidth.computedValue - ); + rect.left + renderStyle.effectiveBorderLeftWidth.computedValue, + rect.top + renderStyle.effectiveBorderTopWidth.computedValue, + rect.right - renderStyle.effectiveBorderRightWidth.computedValue, + rect.bottom - renderStyle.effectiveBorderBottomWidth.computedValue); Path paddingBoxPath; if (!_decoration.hasBorderRadius) { @@ -176,45 +146,24 @@ class BoxDecorationPainter extends BoxPainter { // 1. Create a shadow rect shifted by boxShadow and spread radius and get the // difference path subtracted from the padding box path. - Rect shadowOffsetRect = paddingBoxRect - .shift(Offset(boxShadow.offset.dx, boxShadow.offset.dy)) - .deflate(boxShadow.spreadRadius); - Path shadowOffsetPath = _decoration.hasBorderRadius ? - (Path()..addRRect(_decoration.borderRadius!.toRRect(shadowOffsetRect))) : - (Path()..addRect(shadowOffsetRect)); + Rect shadowOffsetRect = + paddingBoxRect.shift(Offset(boxShadow.offset.dx, boxShadow.offset.dy)).deflate(boxShadow.spreadRadius); + Path shadowOffsetPath = _decoration.hasBorderRadius + ? (Path()..addRRect(_decoration.borderRadius!.toRRect(shadowOffsetRect))) + : (Path()..addRect(shadowOffsetRect)); Path innerShadowPath = Path.combine(PathOperation.difference, paddingBoxPath, shadowOffsetPath); // 2. Create shadow rect in four directions and get the difference path // subtracted from the padding box path. Path topRectPath = _getOuterPaddingBoxPathByDirection( - paddingBoxPath, - paddingBoxRect, - textDirection, - boxShadow, - _BorderDirection.top - ); + paddingBoxPath, paddingBoxRect, textDirection, boxShadow, _BorderDirection.top); Path bottomRectPath = _getOuterPaddingBoxPathByDirection( - paddingBoxPath, - paddingBoxRect, - textDirection, - boxShadow, - _BorderDirection.bottom - ); + paddingBoxPath, paddingBoxRect, textDirection, boxShadow, _BorderDirection.bottom); Path leftRectPath = _getOuterPaddingBoxPathByDirection( - paddingBoxPath, - paddingBoxRect, - textDirection, - boxShadow, - _BorderDirection.left - ); + paddingBoxPath, paddingBoxRect, textDirection, boxShadow, _BorderDirection.left); Path rightRectPath = _getOuterPaddingBoxPathByDirection( - paddingBoxPath, - paddingBoxRect, - textDirection, - boxShadow, - _BorderDirection.right - ); + paddingBoxPath, paddingBoxRect, textDirection, boxShadow, _BorderDirection.right); // 3. Combine all the paths in step 1 and step 2 as the final shadow path. List paintPaths = [ @@ -240,26 +189,26 @@ class BoxDecorationPainter extends BoxPainter { TextDirection? textDirection, BoxShadow boxShadow, _BorderDirection direction, - ) { + ) { Rect offsetRect; Size paddingBoxSize = paddingBoxRect.size; if (direction == _BorderDirection.left) { offsetRect = paddingBoxRect - .shift(Offset(-paddingBoxSize.width + boxShadow.offset.dx + boxShadow.spreadRadius, boxShadow.offset.dy)); + .shift(Offset(-paddingBoxSize.width + boxShadow.offset.dx + boxShadow.spreadRadius, boxShadow.offset.dy)); } else if (direction == _BorderDirection.right) { offsetRect = paddingBoxRect - .shift(Offset(paddingBoxSize.width + boxShadow.offset.dx - boxShadow.spreadRadius, boxShadow.offset.dy)); + .shift(Offset(paddingBoxSize.width + boxShadow.offset.dx - boxShadow.spreadRadius, boxShadow.offset.dy)); } else if (direction == _BorderDirection.top) { offsetRect = paddingBoxRect - .shift(Offset(boxShadow.offset.dx, -paddingBoxSize.height + boxShadow.offset.dy + boxShadow.spreadRadius)); + .shift(Offset(boxShadow.offset.dx, -paddingBoxSize.height + boxShadow.offset.dy + boxShadow.spreadRadius)); } else { offsetRect = paddingBoxRect - .shift(Offset(boxShadow.offset.dx, paddingBoxSize.height + boxShadow.offset.dy - boxShadow.spreadRadius)); + .shift(Offset(boxShadow.offset.dx, paddingBoxSize.height + boxShadow.offset.dy - boxShadow.spreadRadius)); } - Path offsetRectPath = _decoration.hasBorderRadius ? - (Path()..addRRect(_decoration.borderRadius!.toRRect(offsetRect))) : - (Path()..addRect(offsetRect)); + Path offsetRectPath = _decoration.hasBorderRadius + ? (Path()..addRRect(_decoration.borderRadius!.toRRect(offsetRect))) + : (Path()..addRect(offsetRect)); Path outerBorderPath = Path.combine(PathOperation.difference, offsetRectPath, paddingBoxPath); return outerBorderPath; @@ -278,32 +227,23 @@ class BoxDecorationPainter extends BoxPainter { return finalPath; } - void _paintBackgroundColor( - Canvas canvas, Rect rect, TextDirection? textDirection) { + void _paintBackgroundColor(Canvas canvas, Rect rect, TextDirection? textDirection) { if (_decoration.color != null || _decoration.gradient != null) - _paintBox(canvas, rect, _getBackgroundPaint(rect, textDirection), - textDirection); + _paintBox(canvas, rect, _getBackgroundPaint(rect, textDirection), textDirection); } BoxDecorationImagePainter? _imagePainter; - void _paintBackgroundImage( - Canvas canvas, Rect rect, ImageConfiguration configuration) { + void _paintBackgroundImage(Canvas canvas, Rect rect, ImageConfiguration configuration) { if (_decoration.image == null) return; - _imagePainter ??= BoxDecorationImagePainter._( - _decoration.image!, - renderStyle, - onChanged! - ); + _imagePainter ??= BoxDecorationImagePainter._(_decoration.image!, renderStyle, onChanged!); Path? clipPath; switch (_decoration.shape) { case BoxShape.circle: clipPath = Path()..addOval(rect); break; case BoxShape.rectangle: - if (_decoration.hasBorderRadius) - clipPath = Path() - ..addRRect(_decoration.borderRadius!.toRRect(rect)); + if (_decoration.hasBorderRadius) clipPath = Path()..addRRect(_decoration.borderRadius!.toRRect(rect)); break; } _imagePainter!.paint(canvas, rect, clipPath, configuration); @@ -316,12 +256,10 @@ class BoxDecorationPainter extends BoxPainter { } bool _hasLocalBackgroundImage() { - return renderStyle.backgroundImage != null && - renderStyle.backgroundAttachment == CSSBackgroundAttachmentType.local; + return renderStyle.backgroundImage != null && renderStyle.backgroundAttachment == CSSBackgroundAttachmentType.local; } - void paintBackground( - Canvas canvas, Offset offset, ImageConfiguration configuration) { + void paintBackground(Canvas canvas, Offset offset, ImageConfiguration configuration) { assert(configuration.size != null); Offset baseOffset = Offset.zero; @@ -329,24 +267,19 @@ class BoxDecorationPainter extends BoxPainter { bool hasLocalAttachment = _hasLocalBackgroundImage(); // Rect of background color - Rect backgroundColorRect = - _getBackgroundClipRect(baseOffset, configuration); + Rect backgroundColorRect = _getBackgroundClipRect(baseOffset, configuration); _paintBackgroundColor(canvas, backgroundColorRect, textDirection); // Background image of background-attachment local scroll with content Offset backgroundImageOffset = hasLocalAttachment ? offset : baseOffset; // Rect of background image - Rect backgroundClipRect = - _getBackgroundClipRect(backgroundImageOffset, configuration); - Rect backgroundOriginRect = - _getBackgroundOriginRect(backgroundImageOffset, configuration); - Rect backgroundImageRect = - backgroundClipRect.intersect(backgroundOriginRect); + Rect backgroundClipRect = _getBackgroundClipRect(backgroundImageOffset, configuration); + Rect backgroundOriginRect = _getBackgroundOriginRect(backgroundImageOffset, configuration); + Rect backgroundImageRect = backgroundClipRect.intersect(backgroundOriginRect); _paintBackgroundImage(canvas, backgroundImageRect, configuration); } - Rect _getBackgroundOriginRect( - Offset offset, ImageConfiguration configuration) { + Rect _getBackgroundOriginRect(Offset offset, ImageConfiguration configuration) { Size? size = configuration.size; EdgeInsets borderEdge = renderStyle.border; @@ -367,9 +300,7 @@ class BoxDecorationPainter extends BoxPainter { backgroundOriginRect = offset & size!; break; case BackgroundBoundary.contentBox: - backgroundOriginRect = - offset.translate(borderLeft + paddingLeft, borderTop + paddingTop) & - size!; + backgroundOriginRect = offset.translate(borderLeft + paddingLeft, borderTop + paddingTop) & size!; break; default: backgroundOriginRect = offset.translate(borderLeft, borderTop) & size!; @@ -401,26 +332,17 @@ class BoxDecorationPainter extends BoxPainter { switch (backgroundClip) { case BackgroundBoundary.paddingBox: backgroundClipRect = offset.translate(borderLeft, borderTop) & - Size( - size!.width - borderRight - borderLeft, - size.height - borderBottom - borderTop, - ); + Size( + size!.width - borderRight - borderLeft, + size.height - borderBottom - borderTop, + ); break; case BackgroundBoundary.contentBox: - backgroundClipRect = - offset.translate(borderLeft + paddingLeft, borderTop + paddingTop) & - Size( - size!.width - - borderRight - - borderLeft - - paddingRight - - paddingLeft, - size.height - - borderBottom - - borderTop - - paddingBottom - - paddingTop, - ); + backgroundClipRect = offset.translate(borderLeft + paddingLeft, borderTop + paddingTop) & + Size( + size!.width - borderRight - borderLeft - paddingRight - paddingLeft, + size.height - borderBottom - borderTop - paddingBottom - paddingTop, + ); break; default: backgroundClipRect = offset & size!; @@ -442,10 +364,8 @@ class BoxDecorationPainter extends BoxPainter { Rect backgroundClipRect = _getBackgroundClipRect(offset, configuration); _paintBackgroundColor(canvas, backgroundClipRect, textDirection); - Rect backgroundOriginRect = - _getBackgroundOriginRect(offset, configuration); - Rect backgroundImageRect = - backgroundClipRect.intersect(backgroundOriginRect); + Rect backgroundOriginRect = _getBackgroundOriginRect(offset, configuration); + Rect backgroundImageRect = backgroundClipRect.intersect(backgroundOriginRect); _paintBackgroundImage(canvas, backgroundImageRect, configuration); } @@ -468,23 +388,22 @@ class BoxDecorationPainter extends BoxPainter { /// Forked from flutter of [DecorationImagePainter] Class. /// https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/painting/decoration_image.dart#L208 class BoxDecorationImagePainter { - BoxDecorationImagePainter._( - this._details, - this._renderStyle, - this._onChanged - ); + BoxDecorationImagePainter._(this._details, this._renderStyle, this._onChanged); final CSSRenderStyle _renderStyle; final DecorationImage _details; CSSBackgroundPosition get _backgroundPositionX { return _renderStyle.backgroundPositionX; } + CSSBackgroundPosition get _backgroundPositionY { return _renderStyle.backgroundPositionY; } + CSSBackgroundSize get _backgroundSize { return _renderStyle.backgroundSize; } + final VoidCallback _onChanged; ImageStream? _imageStream; @@ -503,16 +422,17 @@ class BoxDecorationImagePainter { ErrorSummary('DecorationImage.matchTextDirection can only be used when a TextDirection is available.'), ErrorDescription( 'When BoxDecorationImagePainter.paint() was called, there was no text direction provided ' - 'in the ImageConfiguration object to match.', + 'in the ImageConfiguration object to match.', ), - DiagnosticsProperty('The DecorationImage was', _details, style: DiagnosticsTreeStyle.errorProperty), - DiagnosticsProperty('The ImageConfiguration was', configuration, style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty('The DecorationImage was', _details, + style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty('The ImageConfiguration was', configuration, + style: DiagnosticsTreeStyle.errorProperty), ]); } return true; }()); - if (configuration.textDirection == TextDirection.rtl) - flipHorizontally = true; + if (configuration.textDirection == TextDirection.rtl) flipHorizontally = true; } final ImageStream newImageStream = _details.image.resolve(configuration); @@ -525,8 +445,7 @@ class BoxDecorationImagePainter { _imageStream = newImageStream; _imageStream!.addListener(listener); } - if (_image == null) - return; + if (_image == null) return; if (clipPath != null) { canvas.save(); @@ -548,21 +467,18 @@ class BoxDecorationImagePainter { filterQuality: FilterQuality.low, ); - if (clipPath != null) - canvas.restore(); + if (clipPath != null) canvas.restore(); } void _handleImage(ImageInfo value, bool synchronousCall) { - if (_image == value) - return; + if (_image == value) return; if (_image != null && _image!.isCloneOf(value)) { value.dispose(); return; } _image?.dispose(); _image = value; - if (!synchronousCall) - _onChanged(); + if (!synchronousCall) _onChanged(); } /// Releases the resources used by this painter. @@ -616,13 +532,12 @@ void _paintImage({ bool isAntiAlias = false, }) { assert( - image.debugGetOpenHandleStackTraces()?.isNotEmpty ?? true, - 'Cannot paint an image that is disposed.\n' + image.debugGetOpenHandleStackTraces()?.isNotEmpty ?? true, + 'Cannot paint an image that is disposed.\n' 'The caller of paintImage is expected to wait to dispose the image until ' 'after painting has completed.', ); - if (rect.isEmpty) - return; + if (rect.isEmpty) return; Size outputSize = rect.size; double imageWidth = image.width.toDouble(); double imageHeight = image.height.toDouble(); @@ -643,30 +558,36 @@ void _paintImage({ CSSLengthValue? backgroundHeight = backgroundSize.height; // Only background width is set, eg `100px`, `100px auto`. - if (backgroundWidth != null && !backgroundWidth.isAuto && backgroundWidth.computedValue > 0 && - (backgroundHeight == null || backgroundHeight.isAuto) - ) { + if (backgroundWidth != null && + !backgroundWidth.isAuto && + backgroundWidth.computedValue > 0 && + (backgroundHeight == null || backgroundHeight.isAuto)) { double width = backgroundWidth.computedValue; double height = width / aspectRatio; destinationSize = Size(width, height); - // Only background height is set, eg `auto 100px`. - } else if (backgroundWidth != null && backgroundWidth.isAuto && - backgroundHeight != null && !backgroundHeight.isAuto && backgroundHeight.computedValue > 0 - ) { + // Only background height is set, eg `auto 100px`. + } else if (backgroundWidth != null && + backgroundWidth.isAuto && + backgroundHeight != null && + !backgroundHeight.isAuto && + backgroundHeight.computedValue > 0) { double height = backgroundHeight.computedValue; double width = height * aspectRatio; destinationSize = Size(width, height); - // Both background width and height are set, eg `100px 100px`. - } else if (backgroundWidth != null && !backgroundWidth.isAuto && backgroundWidth.computedValue > 0 && - backgroundHeight != null && !backgroundHeight.isAuto && backgroundHeight.computedValue > 0 - ) { + // Both background width and height are set, eg `100px 100px`. + } else if (backgroundWidth != null && + !backgroundWidth.isAuto && + backgroundWidth.computedValue > 0 && + backgroundHeight != null && + !backgroundHeight.isAuto && + backgroundHeight.computedValue > 0) { double width = backgroundWidth.computedValue; double height = backgroundHeight.computedValue; destinationSize = Size(width, height); - // Keyword values are set(contain|cover|auto), eg `contain`, `auto auto`. + // Keyword values are set(contain|cover|auto), eg `contain`, `auto auto`. } else { final FittedSizes fittedSizes = applyBoxFit(fit, inputSize / scale, outputSize); sourceSize = fittedSizes.source * scale; @@ -678,7 +599,8 @@ void _paintImage({ destinationSize += sliceBorder; // We don't have the ability to draw a subset of the image at the same time // as we apply a nine-patch stretch. - assert(sourceSize == inputSize, 'centerSlice was used with a BoxFit that does not guarantee that the image is fully visible.'); + assert(sourceSize == inputSize, + 'centerSlice was used with a BoxFit that does not guarantee that the image is fully visible.'); } if (repeat != ImageRepeat.noRepeat && destinationSize == outputSize) { @@ -687,18 +609,19 @@ void _paintImage({ repeat = ImageRepeat.noRepeat; } final Paint paint = Paint()..isAntiAlias = isAntiAlias; - if (colorFilter != null) - paint.colorFilter = colorFilter; + if (colorFilter != null) paint.colorFilter = colorFilter; paint.filterQuality = filterQuality; paint.invertColors = invertColors; final double halfWidthDelta = (outputSize.width - destinationSize.width) / 2.0; final double halfHeightDelta = (outputSize.height - destinationSize.height) / 2.0; // Use position as length type if specified in positionX/ positionY, otherwise use as percentage type. - final double dx = positionX.length != null ? positionX.length!.computedValue : - halfWidthDelta + (flipHorizontally ? -positionX.percentage! : positionX.percentage!) * halfWidthDelta; - final double dy = positionY.length != null ? positionY.length!.computedValue : - halfHeightDelta + positionY.percentage! * halfHeightDelta; + final double dx = positionX.length != null + ? positionX.length!.computedValue + : halfWidthDelta + (flipHorizontally ? -positionX.percentage! : positionX.percentage!) * halfWidthDelta; + final double dy = positionY.length != null + ? positionY.length!.computedValue + : halfHeightDelta + positionY.percentage! * halfHeightDelta; final Offset destinationPosition = rect.topLeft.translate(dx, dy); final Rect destinationRect = destinationPosition & destinationSize; @@ -715,30 +638,47 @@ void _paintImage({ ); assert(() { if (debugInvertOversizedImages && - sizeInfo.decodedSizeInBytes > sizeInfo.displaySizeInBytes + debugImageOverheadAllowance) { + sizeInfo.decodedSizeInBytes > sizeInfo.displaySizeInBytes + debugImageOverheadAllowance) { final int overheadInKilobytes = (sizeInfo.decodedSizeInBytes - sizeInfo.displaySizeInBytes) ~/ 1024; final int outputWidth = outputSize.width.toInt(); final int outputHeight = outputSize.height.toInt(); FlutterError.reportError(FlutterErrorDetails( exception: 'Image $debugImageLabel has a display size of ' - '$outputWidth×$outputHeight but a decode size of ' - '${image.width}×${image.height}, which uses an additional ' - '${overheadInKilobytes}KB.\n\n' - 'Consider resizing the asset ahead of time, supplying a cacheWidth ' - 'parameter of $outputWidth, a cacheHeight parameter of ' - '$outputHeight, or using a ResizeImage.', + '$outputWidth×$outputHeight but a decode size of ' + '${image.width}×${image.height}, which uses an additional ' + '${overheadInKilobytes}KB.\n\n' + 'Consider resizing the asset ahead of time, supplying a cacheWidth ' + 'parameter of $outputWidth, a cacheHeight parameter of ' + '$outputHeight, or using a ResizeImage.', library: 'painting library', context: ErrorDescription('while painting an image'), )); // Invert the colors of the canvas. canvas.saveLayer( destinationRect, - Paint()..colorFilter = const ColorFilter.matrix([ - -1, 0, 0, 0, 255, - 0, -1, 0, 0, 255, - 0, 0, -1, 0, 255, - 0, 0, 0, 1, 0, - ]), + Paint() + ..colorFilter = const ColorFilter.matrix([ + -1, + 0, + 0, + 0, + 255, + 0, + -1, + 0, + 0, + 255, + 0, + 0, + -1, + 0, + 255, + 0, + 0, + 0, + 1, + 0, + ]), ); // Flip the canvas vertically. final double dy = -(rect.top + rect.height / 2.0); @@ -756,7 +696,7 @@ void _paintImage({ _pendingImageSizeInfo[sizeInfo.source!] = sizeInfo; } debugOnPaintImage?.call(sizeInfo); - SchedulerBinding.instance!.addPostFrameCallback((Duration timeStamp) { + SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) { _lastFrameImageSizeInfo = _pendingImageSizeInfo.values.toSet(); if (_pendingImageSizeInfo.isEmpty) { return; @@ -833,11 +773,11 @@ Iterable _generateImageTileRects(Rect outputRect, Rect fundamentalRect, Im } for (int i = startX; i <= stopX; ++i) { - for (int j = startY; j <= stopY; ++j) - yield fundamentalRect.shift(Offset(i * strideX, j * strideY)); + for (int j = startY; j <= stopY; ++j) yield fundamentalRect.shift(Offset(i * strideX, j * strideY)); } } // Forked from flutter with no modification: // https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/painting/decoration_image.dart#L621 -Rect _scaleRect(Rect rect, double scale) => Rect.fromLTRB(rect.left * scale, rect.top * scale, rect.right * scale, rect.bottom * scale); +Rect _scaleRect(Rect rect, double scale) => + Rect.fromLTRB(rect.left * scale, rect.top * scale, rect.right * scale, rect.bottom * scale); diff --git a/webf/lib/src/rendering/box_model.dart b/webf/lib/src/rendering/box_model.dart index 0253842e86..243bbd9a3e 100644 --- a/webf/lib/src/rendering/box_model.dart +++ b/webf/lib/src/rendering/box_model.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; import 'dart:math' as math; @@ -8,11 +9,11 @@ import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/gesture.dart'; -import 'package:kraken/kraken.dart'; -import 'package:kraken/rendering.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/gesture.dart'; +import 'package:webf/webf.dart'; +import 'package:webf/rendering.dart'; import 'debug_overlay.dart'; @@ -35,7 +36,7 @@ class RenderLayoutParentData extends ContainerBoxParentData { // // ReturgetLayoutTransformTolocal layout coordinate system to the // coordinate system of `ancestor`. -Matrix4 getLayoutTransformTo(RenderObject current, RenderObject ancestor, { bool excludeScrollOffset = false }) { +Matrix4 getLayoutTransformTo(RenderObject current, RenderObject ancestor, {bool excludeScrollOffset = false}) { final List renderers = []; for (RenderObject renderer = current; renderer != ancestor; renderer = renderer.parent! as RenderObject) { renderers.add(renderer); @@ -76,8 +77,7 @@ mixin RenderBoxContainerDefaultsMixin>, - RenderBoxContainerDefaultsMixin> { + with + ContainerRenderObjectMixin>, + RenderBoxContainerDefaultsMixin> { RenderLayoutBox({required CSSRenderStyle renderStyle}) : super(renderStyle: renderStyle); // Host content which can be scrolled. @@ -194,6 +190,7 @@ class RenderLayoutBox extends RenderBoxModel return _firstChild; } } + return null; } // No need to override [all] and [addAll] method cause they invoke [insert] method eventually. @@ -243,8 +240,10 @@ class RenderLayoutBox extends RenderBoxModel children.sort((RenderBox left, RenderBox right) { // @FIXME: Add patch to handle nested fixed element paint priority, need to remove // this logic after Kraken has implemented stacking context tree. - if (left is RenderBoxModel && left.renderStyle.position == CSSPositionType.fixed && - right is RenderBoxModel && right.renderStyle.position == CSSPositionType.fixed) { + if (left is RenderBoxModel && + left.renderStyle.position == CSSPositionType.fixed && + right is RenderBoxModel && + right.renderStyle.position == CSSPositionType.fixed) { // Child element always paint after parent element when their position are both fixed // as W3C stacking context specified. // Kraken will place these two renderObjects as siblings of the children of HTML renderObject @@ -275,7 +274,6 @@ class RenderLayoutBox extends RenderBoxModel for (int i = 0; i < paintingOrder.length; i++) { RenderBox child = paintingOrder[i]; if (!isPositionPlaceholder(child)) { - late DateTime childPaintStart; if (kProfileMode && PerformanceTiming.enabled()) { childPaintStart = DateTime.now(); @@ -288,8 +286,7 @@ class RenderLayoutBox extends RenderBoxModel if (kProfileMode && PerformanceTiming.enabled()) { DateTime childPaintEnd = DateTime.now(); - childPaintDuration += (childPaintEnd.microsecondsSinceEpoch - - childPaintStart.microsecondsSinceEpoch); + childPaintDuration += (childPaintEnd.microsecondsSinceEpoch - childPaintStart.microsecondsSinceEpoch); } } } @@ -336,8 +333,7 @@ class RenderLayoutBox extends RenderBoxModel } // No need to loop scrollable container children - if (overflowX != CSSOverflowType.visible || - overflowY != CSSOverflowType.visible) { + if (overflowX != CSSOverflowType.visible || overflowY != CSSOverflowType.visible) { child = childParentData!.nextSibling; continue; } @@ -366,16 +362,13 @@ class RenderLayoutBox extends RenderBoxModel double? result; RenderBox? child = firstChild; while (child != null) { - final RenderLayoutParentData childParentData = - child.parentData as RenderLayoutParentData; + final RenderLayoutParentData childParentData = child.parentData as RenderLayoutParentData; // Whether child is inline-level including text box bool isChildInline = true; if (child is RenderBoxModel) { - CSSDisplay? childTransformedDisplay = - child.renderStyle.effectiveDisplay; - if (childTransformedDisplay == CSSDisplay.block || - childTransformedDisplay == CSSDisplay.flex) { + CSSDisplay? childTransformedDisplay = child.renderStyle.effectiveDisplay; + if (childTransformedDisplay == CSSDisplay.block || childTransformedDisplay == CSSDisplay.flex) { isChildInline = false; } } @@ -389,9 +382,7 @@ class RenderLayoutBox extends RenderBoxModel double? childDistance = child.getDistanceToActualBaseline(baseline); // Use child's height if child has no baseline and not block-level // Text box always has baseline - if (childDistance == null && - isChildInline && - child is RenderBoxModel) { + if (childDistance == null && isChildInline && child is RenderBoxModel) { // Flutter only allow access size of direct children, so cannot use child.size Size childSize = child.getBoxSize(child.contentSize); childDistance = childSize.height; @@ -426,8 +417,7 @@ class RenderLayoutBox extends RenderBoxModel RenderBoxModel? parentRenderBoxModel = parent as RenderBoxModel?; double? flexBasis = renderStyle.flexBasis == CSSLengthValue.auto ? null : renderStyle.flexBasis?.computedValue; if (flexBasis != null) { - if (CSSFlex.isHorizontalFlexDirection( - parentRenderBoxModel!.renderStyle.flexDirection)) { + if (CSSFlex.isHorizontalFlexDirection(parentRenderBoxModel!.renderStyle.flexDirection)) { if (!hasOverrideContentLogicalWidth) { specifiedContentWidth = _getContentWidth(flexBasis); } @@ -486,8 +476,7 @@ class RenderLayoutBox extends RenderBoxModel CSSOverflowType overflowX = childRenderStyle.effectiveOverflowX; CSSOverflowType overflowY = childRenderStyle.effectiveOverflowY; // Only non scroll container need to use scrollable size, otherwise use its own size - if (overflowX == CSSOverflowType.visible && - overflowY == CSSOverflowType.visible) { + if (overflowX == CSSOverflowType.visible && overflowY == CSSOverflowType.visible) { childScrollableSize = child.scrollableSize; } else { childScrollableSize = child.boxSize; @@ -495,8 +484,7 @@ class RenderLayoutBox extends RenderBoxModel double maxScrollableX = childRenderStyle.left.computedValue + childScrollableSize!.width; if (childRenderStyle.right.isNotAuto) { - if (isScrollingContentBox && - (parent as RenderBoxModel).widthSizeType == BoxSizeType.specified) { + if (isScrollingContentBox && (parent as RenderBoxModel).widthSizeType == BoxSizeType.specified) { RenderBoxModel overflowContainerBox = parent as RenderBoxModel; maxScrollableX = math.max( maxScrollableX, @@ -505,15 +493,13 @@ class RenderLayoutBox extends RenderBoxModel overflowContainerBox.renderStyle.effectiveBorderLeftWidth.computedValue - overflowContainerBox.renderStyle.effectiveBorderRightWidth.computedValue); } else { - maxScrollableX = math.max(maxScrollableX, - -childRenderStyle.right.computedValue + _contentSize!.width); + maxScrollableX = math.max(maxScrollableX, -childRenderStyle.right.computedValue + _contentSize!.width); } } double maxScrollableY = childRenderStyle.top.computedValue + childScrollableSize.height; if (childRenderStyle.bottom.isNotAuto) { - if (isScrollingContentBox && - (parent as RenderBoxModel).heightSizeType == BoxSizeType.specified) { + if (isScrollingContentBox && (parent as RenderBoxModel).heightSizeType == BoxSizeType.specified) { RenderBoxModel overflowContainerBox = parent as RenderBoxModel; maxScrollableY = math.max( maxScrollableY, @@ -522,18 +508,16 @@ class RenderLayoutBox extends RenderBoxModel overflowContainerBox.renderStyle.effectiveBorderTopWidth.computedValue - overflowContainerBox.renderStyle.effectiveBorderBottomWidth.computedValue); } else { - maxScrollableY = math.max(maxScrollableY, - -childRenderStyle.bottom.computedValue + _contentSize!.height); + maxScrollableY = math.max(maxScrollableY, -childRenderStyle.bottom.computedValue + _contentSize!.height); } } - RenderBoxModel scrollContainer = isScrollingContentBox - ? parent as RenderBoxModel : this; + RenderBoxModel scrollContainer = isScrollingContentBox ? parent as RenderBoxModel : this; // Scrollable area of positioned element will ignore padding area of scroll container. - maxScrollableX -= scrollContainer.renderStyle.paddingLeft.computedValue - + scrollContainer.renderStyle.paddingRight.computedValue; - maxScrollableY -= scrollContainer.renderStyle.paddingTop.computedValue - + scrollContainer.renderStyle.paddingBottom.computedValue; + maxScrollableX -= + scrollContainer.renderStyle.paddingLeft.computedValue + scrollContainer.renderStyle.paddingRight.computedValue; + maxScrollableY -= + scrollContainer.renderStyle.paddingTop.computedValue + scrollContainer.renderStyle.paddingBottom.computedValue; maxScrollableX = math.max(maxScrollableX, scrollableSize.width); maxScrollableY = math.max(maxScrollableY, scrollableSize.height); @@ -542,17 +526,19 @@ class RenderLayoutBox extends RenderBoxModel } double _getContentWidth(double width) { - return width - (renderStyle.borderLeftWidth?.computedValue ?? 0) - - (renderStyle.borderRightWidth?.computedValue ?? 0) - - renderStyle.paddingLeft.computedValue - - renderStyle.paddingRight.computedValue; + return width - + (renderStyle.borderLeftWidth?.computedValue ?? 0) - + (renderStyle.borderRightWidth?.computedValue ?? 0) - + renderStyle.paddingLeft.computedValue - + renderStyle.paddingRight.computedValue; } double _getContentHeight(double height) { - return height - (renderStyle.borderTopWidth?.computedValue ?? 0) - - (renderStyle.borderBottomWidth?.computedValue ?? 0) - - renderStyle.paddingTop.computedValue - - renderStyle.paddingBottom.computedValue; + return height - + (renderStyle.borderTopWidth?.computedValue ?? 0) - + (renderStyle.borderBottomWidth?.computedValue ?? 0) - + renderStyle.paddingTop.computedValue - + renderStyle.paddingBottom.computedValue; } /// Convert to [RenderFlexLayout] @@ -614,7 +600,6 @@ class RenderLayoutBox extends RenderBoxModel stickyChildren.clear(); _paintingOrder = null; } - } mixin RenderBoxModelBase on RenderBox { @@ -623,24 +608,23 @@ mixin RenderBoxModelBase on RenderBox { } class RenderBoxModel extends RenderBox - with - RenderBoxModelBase, - RenderBoxDecorationMixin, - RenderTransformMixin, - RenderOverflowMixin, - RenderOpacityMixin, - RenderIntersectionObserverMixin, - RenderContentVisibilityMixin, - RenderEventListenerMixin, - RenderObjectWithControllerMixin { + with + RenderBoxModelBase, + RenderBoxDecorationMixin, + RenderTransformMixin, + RenderOverflowMixin, + RenderOpacityMixin, + RenderIntersectionObserverMixin, + RenderContentVisibilityMixin, + RenderEventListenerMixin, + RenderObjectWithControllerMixin { RenderBoxModel({ required this.renderStyle, }) : super(); @override bool get alwaysNeedsCompositing { - return intersectionObserverAlwaysNeedsCompositing() || - opacityAlwaysNeedsCompositing(); + return intersectionObserverAlwaysNeedsCompositing() || opacityAlwaysNeedsCompositing(); } RenderPositionPlaceholder? renderPositionPlaceholder; @@ -673,8 +657,7 @@ class RenderBoxModel extends RenderBox bool _needsRecalculateStyle = false; void markNeedsRecalculateRenderStyle() { - if (_needsRecalculateStyle) - return; + if (_needsRecalculateStyle) return; _needsRecalculateStyle = true; } @@ -683,7 +666,7 @@ class RenderBoxModel extends RenderBox } BoxSizeType get heightSizeType { - return renderStyle.height.isAuto ? BoxSizeType.automatic: BoxSizeType.specified; + return renderStyle.height.isAuto ? BoxSizeType.automatic : BoxSizeType.specified; } // Cache scroll offset of scrolling box in horizontal direction @@ -723,20 +706,17 @@ class RenderBoxModel extends RenderBox // https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context#the_stacking_context bool get needsStacking { return - // Element with a position value absolute, relative, fixed or sticky. - renderStyle.position != CSSPositionType.static || - // Element that is a child of a flex container with z-index value other than auto. - ( - (renderStyle.parent!.display == CSSDisplay.flex || - renderStyle.parent!.display == CSSDisplay.inlineFlex) && - renderStyle.zIndex != null - ) || - // Element with a opacity value less than 1. - renderStyle.opacity < 1.0 || - // Element with a transform value. - renderStyle.transform != null || - // Element with a filter value. - renderStyle.filter != null; + // Element with a position value absolute, relative, fixed or sticky. + renderStyle.position != CSSPositionType.static || + // Element that is a child of a flex container with z-index value other than auto. + ((renderStyle.parent!.display == CSSDisplay.flex || renderStyle.parent!.display == CSSDisplay.inlineFlex) && + renderStyle.zIndex != null) || + // Element with a opacity value less than 1. + renderStyle.opacity < 1.0 || + // Element with a transform value. + renderStyle.transform != null || + // Element with a filter value. + renderStyle.filter != null; } T copyWith(T copiedRenderBoxModel) { @@ -814,7 +794,7 @@ class RenderBoxModel extends RenderBox void markNeedsLayout() { if (doingThisLayout) { // Push delay the [markNeedsLayout] after owner [PipelineOwner] finishing current [flushLayout]. - SchedulerBinding.instance!.addPostFrameCallback((_) { + SchedulerBinding.instance.addPostFrameCallback((_) { markNeedsLayout(); }); } else { @@ -854,8 +834,7 @@ class RenderBoxModel extends RenderBox if (hasSize) { // Constraints changes between tight and no tight will cause reLayoutBoundary change // which will then cause its children to be marked as needsLayout in Flutter - if ((newConstraints.isTight && !constraints.isTight) || - (!newConstraints.isTight && constraints.isTight)) { + if ((newConstraints.isTight && !constraints.isTight) || (!newConstraints.isTight && constraints.isTight)) { syncNeedsLayoutFlag(); } } @@ -896,11 +875,13 @@ class RenderBoxModel extends RenderBox BoxConstraints parentConstraints = (parent as RenderBoxModel).constraints; BoxConstraints constraints = BoxConstraints( - minWidth: parentConstraints.maxWidth != double.infinity ? - parentConstraints.maxWidth - horizontalBorderLength - horizontalPaddingLength : 0, + minWidth: parentConstraints.maxWidth != double.infinity + ? parentConstraints.maxWidth - horizontalBorderLength - horizontalPaddingLength + : 0, maxWidth: double.infinity, - minHeight: parentConstraints.maxHeight != double.infinity ? - parentConstraints.maxHeight - verticalBorderLength - verticalPaddingLength : 0, + minHeight: parentConstraints.maxHeight != double.infinity + ? parentConstraints.maxHeight - verticalBorderLength - verticalPaddingLength + : 0, maxHeight: double.infinity, ); return constraints; @@ -920,34 +901,30 @@ class RenderBoxModel extends RenderBox // Width should be not smaller than border and padding in horizontal direction // when box-sizing is border-box which is only supported. - double minConstraintWidth = renderStyle.effectiveBorderLeftWidth.computedValue - + renderStyle.effectiveBorderRightWidth.computedValue - + renderStyle.paddingLeft.computedValue - + renderStyle.paddingRight.computedValue; + double minConstraintWidth = renderStyle.effectiveBorderLeftWidth.computedValue + + renderStyle.effectiveBorderRightWidth.computedValue + + renderStyle.paddingLeft.computedValue + + renderStyle.paddingRight.computedValue; double maxConstraintWidth = renderStyle.borderBoxLogicalWidth ?? double.infinity; // Height should be not smaller than border and padding in vertical direction // when box-sizing is border-box which is only supported. - double minConstraintHeight = renderStyle.effectiveBorderTopWidth.computedValue - + renderStyle.effectiveBorderBottomWidth.computedValue - + renderStyle.paddingTop.computedValue - + renderStyle.paddingBottom.computedValue; + double minConstraintHeight = renderStyle.effectiveBorderTopWidth.computedValue + + renderStyle.effectiveBorderBottomWidth.computedValue + + renderStyle.paddingTop.computedValue + + renderStyle.paddingBottom.computedValue; double maxConstraintHeight = renderStyle.borderBoxLogicalHeight ?? double.infinity; if (parent is RenderFlexLayout) { - double? flexBasis = renderStyle.flexBasis == CSSLengthValue.auto - ? null : renderStyle.flexBasis?.computedValue; + double? flexBasis = renderStyle.flexBasis == CSSLengthValue.auto ? null : renderStyle.flexBasis?.computedValue; RenderBoxModel? parentRenderBoxModel = parent as RenderBoxModel?; // In flex layout, flex basis takes priority over width/height if set. // Flex-basis cannot be smaller than its content size which happens can not be known // in constraints apply stage, so flex-basis acts as min-width in constraints apply stage. if (flexBasis != null) { - if (CSSFlex.isHorizontalFlexDirection( - parentRenderBoxModel!.renderStyle.flexDirection)) { - minWidth = minWidth != null - ? math.max(flexBasis, minWidth) : flexBasis; + if (CSSFlex.isHorizontalFlexDirection(parentRenderBoxModel!.renderStyle.flexDirection)) { + minWidth = minWidth != null ? math.max(flexBasis, minWidth) : flexBasis; } else { - minHeight = minHeight != null - ? math.max(flexBasis, minHeight) : flexBasis; + minHeight = minHeight != null ? math.max(flexBasis, minHeight) : flexBasis; } } } @@ -955,28 +932,20 @@ class RenderBoxModel extends RenderBox // Clamp constraints by min/max size when display is not inline. if (!isDisplayInline) { if (minWidth != null) { - minConstraintWidth = minConstraintWidth < minWidth - ? minWidth : minConstraintWidth; - maxConstraintWidth = maxConstraintWidth < minWidth - ? minWidth : maxConstraintWidth; + minConstraintWidth = minConstraintWidth < minWidth ? minWidth : minConstraintWidth; + maxConstraintWidth = maxConstraintWidth < minWidth ? minWidth : maxConstraintWidth; } if (maxWidth != null) { - minConstraintWidth = minConstraintWidth > maxWidth - ? maxWidth : minConstraintWidth; - maxConstraintWidth = maxConstraintWidth > maxWidth - ? maxWidth : maxConstraintWidth; + minConstraintWidth = minConstraintWidth > maxWidth ? maxWidth : minConstraintWidth; + maxConstraintWidth = maxConstraintWidth > maxWidth ? maxWidth : maxConstraintWidth; } if (minHeight != null) { - minConstraintHeight = minConstraintHeight < minHeight - ? minHeight : minConstraintHeight; - maxConstraintHeight = maxConstraintHeight < minHeight - ? minHeight : maxConstraintHeight; + minConstraintHeight = minConstraintHeight < minHeight ? minHeight : minConstraintHeight; + maxConstraintHeight = maxConstraintHeight < minHeight ? minHeight : maxConstraintHeight; } if (maxHeight != null) { - minConstraintHeight = minConstraintHeight > maxHeight - ? maxHeight : minConstraintHeight; - maxConstraintHeight = maxConstraintHeight > maxHeight - ? maxHeight : maxConstraintHeight; + minConstraintHeight = minConstraintHeight > maxHeight ? maxHeight : minConstraintHeight; + maxConstraintHeight = maxConstraintHeight > maxHeight ? maxHeight : maxConstraintHeight; } } @@ -992,10 +961,8 @@ class RenderBoxModel extends RenderBox /// Set the size of scrollable overflow area of renderBoxModel void setMaxScrollableSize(Size contentSize) { // Scrollable area includes right and bottom padding - scrollableSize = Size( - contentSize.width + renderStyle.paddingLeft.computedValue, - contentSize.height + renderStyle.paddingTop.computedValue - ); + scrollableSize = Size(contentSize.width + renderStyle.paddingLeft.computedValue, + contentSize.height + renderStyle.paddingTop.computedValue); } // Box size equals to RenderBox.size to avoid flutter complain when read size property. @@ -1113,25 +1080,19 @@ class RenderBoxModel extends RenderBox // Hooks when content box had layout. void didLayout() { scrollableViewportSize = Size( - _contentSize!.width + - renderStyle.paddingLeft.computedValue + - renderStyle.paddingRight.computedValue, - _contentSize!.height + - renderStyle.paddingTop.computedValue + - renderStyle.paddingBottom.computedValue); + _contentSize!.width + renderStyle.paddingLeft.computedValue + renderStyle.paddingRight.computedValue, + _contentSize!.height + renderStyle.paddingTop.computedValue + renderStyle.paddingBottom.computedValue); setUpOverflowScroller(scrollableSize, scrollableViewportSize); - if (positionedHolder != null && - renderStyle.position != CSSPositionType.sticky) { + if (positionedHolder != null && renderStyle.position != CSSPositionType.sticky) { // Make position holder preferred size equal to current element boundary size except sticky element. positionedHolder!.preferredSize = Size.copy(size); } // Positioned renderBoxModel will not trigger parent to relayout. Needs to update it's offset for itself. if (parentData is RenderLayoutParentData) { - RenderLayoutParentData selfParentData = - parentData as RenderLayoutParentData; + RenderLayoutParentData selfParentData = parentData as RenderLayoutParentData; RenderBoxModel? parentBox = parent as RenderBoxModel?; if (selfParentData.isPositioned && parentBox!.hasSize) { CSSPositionedLayout.applyPositionedChildOffset(parentBox, this); @@ -1166,16 +1127,13 @@ class RenderBoxModel extends RenderBox paintBoxModel(context, offset); if (kProfileMode && PerformanceTiming.enabled()) { - int amendEndTime = - DateTime.now().microsecondsSinceEpoch - childPaintDuration; - PerformanceTiming.instance() - .mark(PERF_PAINT_END, uniqueId: hashCode, startTime: amendEndTime); + int amendEndTime = DateTime.now().microsecondsSinceEpoch - childPaintDuration; + PerformanceTiming.instance().mark(PERF_PAINT_END, uniqueId: hashCode, startTime: amendEndTime); } } void debugPaintOverlay(PaintingContext context, Offset offset) { - Rect overlayRect = - Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height); + Rect overlayRect = Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height); context.addLayer(InspectorOverlayLayer( overlayRect: overlayRect, )); @@ -1187,7 +1145,8 @@ class RenderBoxModel extends RenderBox void paintColorFilter(PaintingContext context, Offset offset, PaintingContextCallback callback) { ColorFilter? colorFilter = renderStyle.colorFilter; if (colorFilter != null) { - _colorFilterLayer.layer = context.pushColorFilter(offset, colorFilter, callback, oldLayer: _colorFilterLayer.layer); + _colorFilterLayer.layer = + context.pushColorFilter(offset, colorFilter, callback, oldLayer: _colorFilterLayer.layer); } else { callback(context, offset); } @@ -1204,18 +1163,15 @@ class RenderBoxModel extends RenderBox performPaint(context, offset); } else { // Paint fixed element to fixed position by compensating scroll offset - double offsetY = - scrollingOffsetY != null ? offset.dy + scrollingOffsetY! : offset.dy; - double offsetX = - scrollingOffsetX != null ? offset.dx + scrollingOffsetX! : offset.dx; + double offsetY = scrollingOffsetY != null ? offset.dy + scrollingOffsetY! : offset.dy; + double offsetX = scrollingOffsetX != null ? offset.dx + scrollingOffsetX! : offset.dx; offset = Offset(offsetX, offsetY); paintColorFilter(context, offset, _chainPaintImageFilter); } } final LayerHandle _imageFilterLayer = LayerHandle(); - void paintImageFilter(PaintingContext context, Offset offset, - PaintingContextCallback callback) { + void paintImageFilter(PaintingContext context, Offset offset, PaintingContextCallback callback) { if (renderStyle.imageFilter != null) { _imageFilterLayer.layer ??= ImageFilterLayer(); _imageFilterLayer.layer!.imageFilter = renderStyle.imageFilter; @@ -1255,11 +1211,9 @@ class RenderBoxModel extends RenderBox bool hasLocalAttachment = _hasLocalBackgroundImage(renderStyle); if (hasLocalAttachment) { - paintOverflow( - context, offset, borderEdge, decoration, _chainPaintBackground); + paintOverflow(context, offset, borderEdge, decoration, _chainPaintBackground); } else { - paintOverflow(context, offset, borderEdge, decoration, - _chainPaintContentVisibility); + paintOverflow(context, offset, borderEdge, decoration, _chainPaintContentVisibility); } } @@ -1288,13 +1242,13 @@ class RenderBoxModel extends RenderBox // Get the layout offset of renderObject to its ancestor which does not include the paint offset // such as scroll or transform.getLayoutTransformTo - Offset getOffsetToAncestor(Offset point, RenderObject ancestor, { bool excludeScrollOffset = false }) { - return MatrixUtils.transformPoint(getLayoutTransformTo(this, ancestor, excludeScrollOffset: excludeScrollOffset), point); + Offset getOffsetToAncestor(Offset point, RenderObject ancestor, {bool excludeScrollOffset = false}) { + return MatrixUtils.transformPoint( + getLayoutTransformTo(this, ancestor, excludeScrollOffset: excludeScrollOffset), point); } bool _hasLocalBackgroundImage(CSSRenderStyle renderStyle) { - return renderStyle.backgroundImage != null && - renderStyle.backgroundAttachment == CSSBackgroundAttachmentType.local; + return renderStyle.backgroundImage != null && renderStyle.backgroundAttachment == CSSBackgroundAttachmentType.local; } // Detach renderBoxModel from its containing block. @@ -1309,19 +1263,15 @@ class RenderBoxModel extends RenderBox // The position and size of an element's box(es) are sometimes calculated relative to a certain rectangle, // called the containing block of the element. // Definition of "containing block": https://www.w3.org/TR/CSS21/visudet.html#containing-block-details - void attachToContainingBlock( - RenderBox? containingBlockRenderBox, - { RenderBox? parent, RenderBox? after } - ) { + void attachToContainingBlock(RenderBox? containingBlockRenderBox, {RenderBox? parent, RenderBox? after}) { if (parent == null || containingBlockRenderBox == null) return; RenderBoxModel renderBoxModel = this; CSSPositionType positionType = renderBoxModel.renderStyle.position; // The containing block of an element is defined as follows: - if (positionType == CSSPositionType.relative - || positionType == CSSPositionType.static - || positionType == CSSPositionType.sticky - ) { + if (positionType == CSSPositionType.relative || + positionType == CSSPositionType.static || + positionType == CSSPositionType.sticky) { // If the element's position is 'relative' or 'static', // the containing block is formed by the content edge of the nearest block container ancestor box. attachRenderBox(containingBlockRenderBox, renderBoxModel, after: after); @@ -1339,8 +1289,7 @@ class RenderBoxModel extends RenderBox // If container block is same as origin parent, the placeholder must after the origin renderBox // because placeholder depends the constraints in layout stage. - RenderBox? previousSibling = containingBlockRenderBox == parent ? - renderBoxModel : after; + RenderBox? previousSibling = containingBlockRenderBox == parent ? renderBoxModel : after; // Add position holder to origin position parent. _attachPositionPlaceholder(parent, renderBoxModel, after: previousSibling); @@ -1393,7 +1342,7 @@ class RenderBoxModel extends RenderBox @mustCallSuper void dispose() { // Ensure pending layout/compositeBitsUpdate/paint render object to be finished. - SchedulerBinding.instance!.addPostFrameCallback((_) { + SchedulerBinding.instance.addPostFrameCallback((_) { // Call dispose method of renderBoxModel when it is detached from tree. super.dispose(); }); @@ -1429,9 +1378,7 @@ class RenderBoxModel extends RenderBox @override bool hitTest(BoxHitTestResult result, {required Offset position}) { - if (!hasSize || - !contentVisibilityHitTest(result, position: position) || - renderStyle.isVisibilityHidden) { + if (!hasSize || !contentVisibilityHitTest(result, position: position) || renderStyle.isVisibilityHidden) { return false; } @@ -1439,12 +1386,9 @@ class RenderBoxModel extends RenderBox if (!hasSize) { if (debugNeedsLayout) { throw FlutterError.fromParts([ - ErrorSummary( - 'Cannot hit test a render box that has never been laid out.'), - describeForError( - 'The hitTest() method was called on this RenderBox'), - ErrorDescription( - "Unfortunately, this object's geometry is not known at this time, " + ErrorSummary('Cannot hit test a render box that has never been laid out.'), + describeForError('The hitTest() method was called on this RenderBox'), + ErrorDescription("Unfortunately, this object's geometry is not known at this time, " 'probably because it has never been laid out. ' 'This means it cannot be accurately hit-tested.'), ErrorHint('If you are trying ' @@ -1456,8 +1400,7 @@ class RenderBoxModel extends RenderBox throw FlutterError.fromParts([ ErrorSummary('Cannot hit test a render box with no size.'), describeForError('The hitTest() method was called on this RenderBox'), - ErrorDescription( - 'Although this node is not marked as needing layout, ' + ErrorDescription('Although this node is not marked as needing layout, ' 'its size is not set.'), ErrorHint('A RenderBox object must have an ' 'explicit size before it can be hit-tested. Make sure ' @@ -1472,9 +1415,7 @@ class RenderBoxModel extends RenderBox position: position, hitTest: (BoxHitTestResult result, Offset transformPosition) { return result.addWithPaintOffset( - offset: (scrollLeft != 0.0 || scrollTop != 0.0) - ? Offset(-scrollLeft, -scrollTop) - : null, + offset: (scrollLeft != 0.0 || scrollTop != 0.0) ? Offset(-scrollLeft, -scrollTop) : null, position: transformPosition, hitTest: (BoxHitTestResult result, Offset position) { CSSPositionType positionType = renderStyle.position; @@ -1490,8 +1431,7 @@ class RenderBoxModel extends RenderBox } // addWithPaintOffset is to add an offset to the child node, the calculation itself does not need to bring an offset. - if (hitTestChildren(result, position: position) || - hitTestSelf(transformPosition)) { + if (hitTestChildren(result, position: position) || hitTestSelf(transformPosition)) { result.add(BoxHitTestEntry(this, position)); return true; } @@ -1520,7 +1460,7 @@ class RenderBoxModel extends RenderBox Future toImage({double pixelRatio = 1.0}) { if (layer == null) { Completer completer = Completer(); - SchedulerBinding.instance!.scheduleFrameCallback((_) { + SchedulerBinding.instance.scheduleFrameCallback((_) { completer.complete(toImage(pixelRatio: pixelRatio)); }); return completer.future; @@ -1543,23 +1483,16 @@ class RenderBoxModel extends RenderBox super.debugFillProperties(properties); properties.add(DiagnosticsProperty('creatorElement', renderStyle.target)); properties.add(DiagnosticsProperty('contentSize', _contentSize)); - properties.add(DiagnosticsProperty( - 'contentConstraints', _contentConstraints, - missingIfNull: true)); - properties.add(DiagnosticsProperty('widthSizeType', widthSizeType, - missingIfNull: true)); - properties.add(DiagnosticsProperty('heightSizeType', heightSizeType, - missingIfNull: true)); - properties.add(DiagnosticsProperty('maxScrollableSize', scrollableSize, - missingIfNull: true)); + properties.add(DiagnosticsProperty('contentConstraints', _contentConstraints, missingIfNull: true)); + properties.add(DiagnosticsProperty('widthSizeType', widthSizeType, missingIfNull: true)); + properties.add(DiagnosticsProperty('heightSizeType', heightSizeType, missingIfNull: true)); + properties.add(DiagnosticsProperty('maxScrollableSize', scrollableSize, missingIfNull: true)); if (renderPositionPlaceholder != null) - properties.add( - DiagnosticsProperty('renderPositionHolder', renderPositionPlaceholder)); + properties.add(DiagnosticsProperty('renderPositionHolder', renderPositionPlaceholder)); properties.add(DiagnosticsProperty('intrinsicWidth', renderStyle.intrinsicWidth)); properties.add(DiagnosticsProperty('intrinsicHeight', renderStyle.intrinsicHeight)); - if (renderStyle.aspectRatio != null) - properties.add(DiagnosticsProperty('intrinsicRatio', renderStyle.aspectRatio)); + if (renderStyle.aspectRatio != null) properties.add(DiagnosticsProperty('intrinsicRatio', renderStyle.aspectRatio)); debugBoxDecorationProperties(properties); debugVisibilityProperties(properties); @@ -1569,17 +1502,16 @@ class RenderBoxModel extends RenderBox } // Attach renderBox from tree. - static void attachRenderBox( - RenderObject parentRenderObject, - RenderBox renderBox, - {RenderObject? after, bool isLast = false} - ) { + static void attachRenderBox(RenderObject parentRenderObject, RenderBox renderBox, + {RenderObject? after, bool isLast = false}) { if (isLast) { assert(after == null); } - if (parentRenderObject is RenderObjectWithChildMixin) { // RenderViewportBox + if (parentRenderObject is RenderObjectWithChildMixin) { + // RenderViewportBox parentRenderObject.child = renderBox; - } else if (parentRenderObject is ContainerRenderObjectMixin) { // RenderLayoutBox or RenderSliverList + } else if (parentRenderObject is ContainerRenderObjectMixin) { + // RenderLayoutBox or RenderSliverList // Should attach to renderScrollingContent if it is scrollable. if (parentRenderObject is RenderLayoutBox) { parentRenderObject = parentRenderObject.renderScrollingContent ?? parentRenderObject; diff --git a/webf/lib/src/rendering/content_visibility.dart b/webf/lib/src/rendering/content_visibility.dart index 716d134900..87e33ff9c1 100644 --- a/webf/lib/src/rendering/content_visibility.dart +++ b/webf/lib/src/rendering/content_visibility.dart @@ -1,10 +1,11 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/rendering.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/rendering.dart'; +import 'package:webf/css.dart'; +import 'package:webf/rendering.dart'; /// Lays the child out as if it was in the tree, but without painting anything, /// without making the child available for hit testing, and without taking any @@ -15,8 +16,7 @@ mixin RenderContentVisibilityMixin on RenderBoxModelBase { return _contentVisibility != ContentVisibility.hidden; } - void paintContentVisibility(PaintingContext context, Offset offset, - PaintingContextCallback callback) { + void paintContentVisibility(PaintingContext context, Offset offset, PaintingContextCallback callback) { ContentVisibility? _contentVisibility = renderStyle.contentVisibility; if (_contentVisibility == ContentVisibility.hidden) { return; diff --git a/webf/lib/src/rendering/debug_overlay.dart b/webf/lib/src/rendering/debug_overlay.dart index 605c134eeb..984273eccb 100644 --- a/webf/lib/src/rendering/debug_overlay.dart +++ b/webf/lib/src/rendering/debug_overlay.dart @@ -1,15 +1,14 @@ /* - * Copyright (C) 2020-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; -const Color _kHighlightedRenderObjectFillColor = - Color.fromARGB(128, 128, 128, 255); -const Color _kHighlightedRenderObjectBorderColor = - Color.fromARGB(128, 64, 64, 128); +const Color _kHighlightedRenderObjectFillColor = Color.fromARGB(128, 128, 128, 255); +const Color _kHighlightedRenderObjectBorderColor = Color.fromARGB(128, 64, 64, 128); class InspectorOverlayLayer extends Layer { /// Creates a layer that displays the inspector overlay. @@ -17,8 +16,7 @@ class InspectorOverlayLayer extends Layer { bool inDebugMode = kDebugMode || kProfileMode; if (inDebugMode == false) { throw FlutterError.fromParts([ - ErrorSummary( - 'The inspector should never be used in production mode due to the ' + ErrorSummary('The inspector should never be used in production mode due to the ' 'negative performance impact.'), ]); } diff --git a/webf/lib/src/rendering/event.dart b/webf/lib/src/rendering/event.dart index 724ffd7879..2519d648b0 100644 --- a/webf/lib/src/rendering/event.dart +++ b/webf/lib/src/rendering/event.dart @@ -1,17 +1,17 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/rendering.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/src/gesture/gesture_dispatcher.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/src/gesture/gesture_dispatcher.dart'; typedef HandleGetEventTarget = EventTarget Function(); typedef HandleGetGestureDispather = GestureDispatcher Function(); mixin RenderEventListenerMixin on RenderBox { - HandleGetEventTarget? getEventTarget; HandleGetGestureDispather? getGestureDispather; diff --git a/webf/lib/src/rendering/fallback_view.dart b/webf/lib/src/rendering/fallback_view.dart index 00cbbe1b21..91ddf34e52 100644 --- a/webf/lib/src/rendering/fallback_view.dart +++ b/webf/lib/src/rendering/fallback_view.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:ui'; @@ -9,8 +10,7 @@ import 'package:flutter/rendering.dart' hide Gradient; const Color _black = Color(0xBF000000); const Color _yellow = Color(0xBFFFFF00); -class RenderFallbackViewBox extends RenderBox - with RenderObjectWithChildMixin { +class RenderFallbackViewBox extends RenderBox with RenderObjectWithChildMixin { RenderFallbackViewBox({required RenderBox child}) { this.child = child; } @@ -26,9 +26,7 @@ class RenderFallbackViewBox extends RenderBox @override void paint(PaintingContext context, Offset offset) { - context.canvas.drawRect( - Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height), - _linePaint); + context.canvas.drawRect(Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height), _linePaint); if (child != null) { // Add some offset to show borders. child!.paint(context, offset + Offset(5.0, 5.0)); diff --git a/webf/lib/src/rendering/flex.dart b/webf/lib/src/rendering/flex.dart index 44324117ae..612eb168ee 100644 --- a/webf/lib/src/rendering/flex.dart +++ b/webf/lib/src/rendering/flex.dart @@ -1,13 +1,14 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:math' as math; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; -import 'package:kraken/module.dart'; -import 'package:kraken/rendering.dart'; -import 'package:kraken/css.dart'; +import 'package:webf/module.dart'; +import 'package:webf/rendering.dart'; +import 'package:webf/css.dart'; // Position and size info of each run (flex line) in flex layout. // https://www.w3.org/TR/css-flexbox-1/#flex-lines @@ -174,8 +175,7 @@ class RenderFlexLayout extends RenderLayoutBox { child.parentData = RenderLayoutParentData(); } if (child is RenderBoxModel) { - child.parentData = CSSPositionedLayout.getPositionParentData( - child, child.parentData as RenderLayoutParentData); + child.parentData = CSSPositionedLayout.getPositionParentData(child, child.parentData as RenderLayoutParentData); } } @@ -204,18 +204,26 @@ class RenderFlexLayout extends RenderLayoutBox { // Get start/end border in the main axis according to flex direction. double _flowAwareMainAxisBorder({bool isEnd = false}) { if (_isHorizontalFlexDirection) { - return isEnd ? renderStyle.effectiveBorderRightWidth.computedValue : renderStyle.effectiveBorderLeftWidth.computedValue; + return isEnd + ? renderStyle.effectiveBorderRightWidth.computedValue + : renderStyle.effectiveBorderLeftWidth.computedValue; } else { - return isEnd ? renderStyle.effectiveBorderBottomWidth.computedValue : renderStyle.effectiveBorderTopWidth.computedValue; + return isEnd + ? renderStyle.effectiveBorderBottomWidth.computedValue + : renderStyle.effectiveBorderTopWidth.computedValue; } } // Get start/end border in the cross axis according to flex direction. double _flowAwareCrossAxisBorder({bool isEnd = false}) { if (_isHorizontalFlexDirection) { - return isEnd ? renderStyle.effectiveBorderBottomWidth.computedValue : renderStyle.effectiveBorderTopWidth.computedValue; + return isEnd + ? renderStyle.effectiveBorderBottomWidth.computedValue + : renderStyle.effectiveBorderTopWidth.computedValue; } else { - return isEnd ? renderStyle.effectiveBorderRightWidth.computedValue : renderStyle.effectiveBorderLeftWidth.computedValue; + return isEnd + ? renderStyle.effectiveBorderRightWidth.computedValue + : renderStyle.effectiveBorderLeftWidth.computedValue; } } @@ -287,18 +295,12 @@ class RenderFlexLayout extends RenderLayoutBox { // Clamp flex-basis by min and max size. if (flexBasis != null) { - double? minWidth = child.renderStyle.minWidth.isAuto - ? null : child.renderStyle.minWidth.computedValue; - double? minHeight = child.renderStyle.minHeight.isAuto - ? null : child.renderStyle.minHeight.computedValue; - double? maxWidth = child.renderStyle.maxWidth.isNone - ? null : child.renderStyle.maxWidth.computedValue; - double? maxHeight = child.renderStyle.maxHeight.isNone - ? null : child.renderStyle.maxHeight.computedValue; - double? minMainSize = _isHorizontalFlexDirection - ? minWidth : minHeight; - double? maxMainSize = _isHorizontalFlexDirection - ? maxWidth : maxHeight; + double? minWidth = child.renderStyle.minWidth.isAuto ? null : child.renderStyle.minWidth.computedValue; + double? minHeight = child.renderStyle.minHeight.isAuto ? null : child.renderStyle.minHeight.computedValue; + double? maxWidth = child.renderStyle.maxWidth.isNone ? null : child.renderStyle.maxWidth.computedValue; + double? maxHeight = child.renderStyle.maxHeight.isNone ? null : child.renderStyle.maxHeight.computedValue; + double? minMainSize = _isHorizontalFlexDirection ? minWidth : minHeight; + double? maxMainSize = _isHorizontalFlexDirection ? maxWidth : maxHeight; if (minMainSize != null && flexBasis < minMainSize) flexBasis = minMainSize; if (maxMainSize != null && flexBasis > maxMainSize) flexBasis = maxMainSize; @@ -326,11 +328,9 @@ class RenderFlexLayout extends RenderLayoutBox { double? maxMainSize; if (child is RenderBoxModel) { if (_isHorizontalFlexDirection) { - maxMainSize = child.renderStyle.maxWidth.isNone - ? null : child.renderStyle.maxWidth.computedValue; + maxMainSize = child.renderStyle.maxWidth.isNone ? null : child.renderStyle.maxWidth.computedValue; } else { - maxMainSize = child.renderStyle.maxHeight.isNone - ? null : child.renderStyle.maxHeight.computedValue; + maxMainSize = child.renderStyle.maxHeight.isNone ? null : child.renderStyle.maxHeight.computedValue; } } return maxMainSize ?? double.infinity; @@ -341,11 +341,9 @@ class RenderFlexLayout extends RenderLayoutBox { if (child is RenderBoxModel) { double autoMinSize = _getAutoMinSize(child); if (_isHorizontalFlexDirection) { - minMainSize = child.renderStyle.minWidth.isAuto - ? autoMinSize : child.renderStyle.minWidth.computedValue; + minMainSize = child.renderStyle.minWidth.isAuto ? autoMinSize : child.renderStyle.minWidth.computedValue; } else { - minMainSize = child.renderStyle.minHeight.isAuto - ? autoMinSize : child.renderStyle.minHeight.computedValue; + minMainSize = child.renderStyle.minHeight.isAuto ? autoMinSize : child.renderStyle.minHeight.computedValue; } } @@ -363,9 +361,7 @@ class RenderFlexLayout extends RenderLayoutBox { // If the item’s computed main size property is definite, then the specified size suggestion is that size // (clamped by its max main size property if it’s definite). It is otherwise undefined. // https://www.w3.org/TR/css-flexbox-1/#specified-size-suggestion - double? specifiedSize = _isHorizontalFlexDirection - ? childLogicalWidth - : childLogicalHeight; + double? specifiedSize = _isHorizontalFlexDirection ? childLogicalWidth : childLogicalHeight; // If the item has an intrinsic aspect ratio and its computed cross size property is definite, then the // transferred size suggestion is that size (clamped by its min and max cross size properties if they @@ -384,13 +380,9 @@ class RenderFlexLayout extends RenderLayoutBox { // by any definite min and max cross size properties converted through the aspect ratio, and then further // clamped by the max main size property if that is definite. // https://www.w3.org/TR/css-flexbox-1/#content-size-suggestion - double contentSize = _isHorizontalFlexDirection - ? child.minContentWidth - : child.minContentHeight; + double contentSize = _isHorizontalFlexDirection ? child.minContentWidth : child.minContentHeight; - CSSLengthValue childCrossSize = _isHorizontalFlexDirection - ? childRenderStyle.height - : childRenderStyle.width; + CSSLengthValue childCrossSize = _isHorizontalFlexDirection ? childRenderStyle.height : childRenderStyle.width; if (childCrossSize.isNotAuto && transferredSize != null) { contentSize = transferredSize; @@ -424,9 +416,8 @@ class RenderFlexLayout extends RenderLayoutBox { contentSize = transferredMaxSize; } - double? crossSize = _isHorizontalFlexDirection - ? renderStyle.contentBoxLogicalHeight - : renderStyle.contentBoxLogicalWidth; + double? crossSize = + _isHorizontalFlexDirection ? renderStyle.contentBoxLogicalHeight : renderStyle.contentBoxLogicalWidth; // Content size suggestion of replaced flex item will use the cross axis preferred size which came from flexbox's // fixed cross size in newer version of Blink and Gecko which is different from the behavior of WebKit. @@ -437,9 +428,7 @@ class RenderFlexLayout extends RenderLayoutBox { contentSize = transferredSize; } - CSSLengthValue maxMainLength = _isHorizontalFlexDirection - ? childRenderStyle.maxWidth - : childRenderStyle.maxHeight; + CSSLengthValue maxMainLength = _isHorizontalFlexDirection ? childRenderStyle.maxWidth : childRenderStyle.maxHeight; // Further clamped by the max main size property if that is definite. if (maxMainLength.isNotNone) { @@ -469,8 +458,7 @@ class RenderFlexLayout extends RenderLayoutBox { return autoMinSize; } - double _getShrinkConstraints(RenderBox child, - Map runChildren, double remainingFreeSpace) { + double _getShrinkConstraints(RenderBox child, Map runChildren, double remainingFreeSpace) { double totalWeightedFlexShrink = 0; runChildren.forEach((int? hashCode, _RunChild runChild) { double childOriginalMainSize = runChild.originalMainSize; @@ -495,8 +483,7 @@ class RenderFlexLayout extends RenderLayoutBox { double currentOriginalMainSize = current.originalMainSize; double currentFlexShrink = _getFlexShrink(current.child); double currentExtent = currentFlexShrink * currentOriginalMainSize; - double minusConstraints = - (currentExtent / totalWeightedFlexShrink) * remainingFreeSpace; + double minusConstraints = (currentExtent / totalWeightedFlexShrink) * remainingFreeSpace; return minusConstraints; } @@ -540,8 +527,7 @@ class RenderFlexLayout extends RenderLayoutBox { } } - double _getMainAxisExtent(RenderBox child, - {bool shouldUseIntrinsicMainSize = false}) { + double _getMainAxisExtent(RenderBox child, {bool shouldUseIntrinsicMainSize = false}) { double marginHorizontal = 0; double marginVertical = 0; @@ -561,8 +547,7 @@ class RenderFlexLayout extends RenderLayoutBox { childRenderBoxModel.renderStyle.marginBottom.computedValue; } - double baseSize = _getMainSize(child, - shouldUseIntrinsicMainSize: shouldUseIntrinsicMainSize); + double baseSize = _getMainSize(child, shouldUseIntrinsicMainSize: shouldUseIntrinsicMainSize); if (_isHorizontalFlexDirection) { return baseSize + marginHorizontal; } else { @@ -570,10 +555,8 @@ class RenderFlexLayout extends RenderLayoutBox { } } - double _getMainSize(RenderBox child, - {bool shouldUseIntrinsicMainSize = false}) { - Size? childSize = _getChildSize(child, - shouldUseIntrinsicMainSize: shouldUseIntrinsicMainSize); + double _getMainSize(RenderBox child, {bool shouldUseIntrinsicMainSize = false}) { + Size? childSize = _getChildSize(child, shouldUseIntrinsicMainSize: shouldUseIntrinsicMainSize); if (_isHorizontalFlexDirection) { return childSize!.width; } else { @@ -586,8 +569,7 @@ class RenderFlexLayout extends RenderLayoutBox { doingThisLayout = true; if (kProfileMode && PerformanceTiming.enabled()) { childLayoutDuration = 0; - PerformanceTiming.instance() - .mark(PERF_FLEX_LAYOUT_START, uniqueId: hashCode); + PerformanceTiming.instance().mark(PERF_FLEX_LAYOUT_START, uniqueId: hashCode); } _doPerformLayout(); @@ -599,10 +581,8 @@ class RenderFlexLayout extends RenderLayoutBox { if (kProfileMode && PerformanceTiming.enabled()) { DateTime flexLayoutEndTime = DateTime.now(); - int amendEndTime = - flexLayoutEndTime.microsecondsSinceEpoch - childLayoutDuration; - PerformanceTiming.instance().mark(PERF_FLEX_LAYOUT_END, - uniqueId: hashCode, startTime: amendEndTime); + int amendEndTime = flexLayoutEndTime.microsecondsSinceEpoch - childLayoutDuration; + PerformanceTiming.instance().mark(PERF_FLEX_LAYOUT_END, uniqueId: hashCode, startTime: amendEndTime); } doingThisLayout = false; } @@ -668,9 +648,8 @@ class RenderFlexLayout extends RenderLayoutBox { } } - bool isScrollContainer = - renderStyle.effectiveOverflowX != CSSOverflowType.visible - || renderStyle.effectiveOverflowY != CSSOverflowType.visible; + bool isScrollContainer = renderStyle.effectiveOverflowX != CSSOverflowType.visible || + renderStyle.effectiveOverflowY != CSSOverflowType.visible; if (isScrollContainer) { // Find all the sticky children when scroll container is layouted. @@ -746,8 +725,7 @@ class RenderFlexLayout extends RenderLayoutBox { double flexLineLimit = 0.0; // Use scrolling container to calculate flex line limit for scrolling content box - RenderBoxModel? containerBox = - isScrollingContentBox ? parent as RenderBoxModel? : this; + RenderBoxModel? containerBox = isScrollingContentBox ? parent as RenderBoxModel? : this; if (_isHorizontalFlexDirection) { flexLineLimit = renderStyle.contentMaxConstraintsWidth; } else { @@ -792,10 +770,9 @@ class RenderFlexLayout extends RenderLayoutBox { // Whether child need to layout. bool isChildNeedsLayout = true; if (child.hasSize && - !needsRelayout && - (childConstraints == _childrenOldConstraints[child.hashCode]) && - ((child is RenderBoxModel && !child.needsLayout) || - (child is RenderTextBox && !child.needsLayout))) { + !needsRelayout && + (childConstraints == _childrenOldConstraints[child.hashCode]) && + ((child is RenderBoxModel && !child.needsLayout) || (child is RenderTextBox && !child.needsLayout))) { isChildNeedsLayout = false; } @@ -810,13 +787,9 @@ class RenderFlexLayout extends RenderLayoutBox { // cause Flutter will skip child layout if its constraints not changed between two layouts. if (child is RenderBoxModel && needsRelayout) { childConstraints = BoxConstraints( - minWidth: childConstraints.maxWidth != double.infinity - ? childConstraints.maxWidth - : 0, + minWidth: childConstraints.maxWidth != double.infinity ? childConstraints.maxWidth : 0, maxWidth: double.infinity, - minHeight: childConstraints.maxHeight != double.infinity - ? childConstraints.maxHeight - : 0, + minHeight: childConstraints.maxHeight != double.infinity ? childConstraints.maxHeight : 0, maxHeight: double.infinity, ); } @@ -825,37 +798,23 @@ class RenderFlexLayout extends RenderLayoutBox { if (kProfileMode && PerformanceTiming.enabled()) { DateTime childLayoutEnd = DateTime.now(); - childLayoutDuration += (childLayoutEnd.microsecondsSinceEpoch - - childLayoutStart.microsecondsSinceEpoch); + childLayoutDuration += (childLayoutEnd.microsecondsSinceEpoch - childLayoutStart.microsecondsSinceEpoch); } Size? childSize = _getChildSize(child); - _childrenIntrinsicMainSizes[child.hashCode] = - _isHorizontalFlexDirection - ? childSize!.width - : childSize!.height; + _childrenIntrinsicMainSizes[child.hashCode] = _isHorizontalFlexDirection ? childSize!.width : childSize!.height; } Size? childSize = _getChildSize(child, shouldUseIntrinsicMainSize: true); - double childMainAxisExtent = - _getMainAxisExtent(child, shouldUseIntrinsicMainSize: true); + double childMainAxisExtent = _getMainAxisExtent(child, shouldUseIntrinsicMainSize: true); double childCrossAxisExtent = _getCrossAxisExtent(child); - bool isExceedFlexLineLimit = - runMainAxisExtent + childMainAxisExtent > flexLineLimit; + bool isExceedFlexLineLimit = runMainAxisExtent + childMainAxisExtent > flexLineLimit; // calculate flex line - if ((renderStyle.flexWrap == FlexWrap.wrap || - renderStyle.flexWrap == FlexWrap.wrapReverse) && - runChildren.isNotEmpty && - isExceedFlexLineLimit) { - - _runMetrics.add(_RunMetrics( - runMainAxisExtent, - runCrossAxisExtent, - totalFlexGrow, - totalFlexShrink, - maxSizeAboveBaseline, - runChildren, - 0)); + if ((renderStyle.flexWrap == FlexWrap.wrap || renderStyle.flexWrap == FlexWrap.wrapReverse) && + runChildren.isNotEmpty && + isExceedFlexLineLimit) { + _runMetrics.add(_RunMetrics(runMainAxisExtent, runCrossAxisExtent, totalFlexGrow, totalFlexShrink, + maxSizeAboveBaseline, runChildren, 0)); runChildren = {}; runMainAxisExtent = 0.0; runCrossAxisExtent = 0.0; @@ -871,8 +830,7 @@ class RenderFlexLayout extends RenderLayoutBox { // Vertical align is only valid for inline box. // Baseline alignment in column direction behave the same as flex-start. AlignSelf alignSelf = _getAlignSelf(child); - bool isBaselineAlign = alignSelf == AlignSelf.baseline - || renderStyle.alignItems == AlignItems.baseline; + bool isBaselineAlign = alignSelf == AlignSelf.baseline || renderStyle.alignItems == AlignItems.baseline; if (_isHorizontalFlexDirection && isBaselineAlign) { // Distance from top to baseline of child @@ -888,10 +846,7 @@ class RenderFlexLayout extends RenderLayoutBox { maxSizeAboveBaseline, ); maxSizeBelowBaseline = math.max( - childMarginTop + - childMarginBottom + - childSize!.height - - childAscent, + childMarginTop + childMarginBottom + childSize!.height - childAscent, maxSizeBelowBaseline, ); runCrossAxisExtent = maxSizeAboveBaseline + maxSizeBelowBaseline; @@ -922,13 +877,7 @@ class RenderFlexLayout extends RenderLayoutBox { if (runChildren.isNotEmpty) { _runMetrics.add(_RunMetrics( - runMainAxisExtent, - runCrossAxisExtent, - totalFlexGrow, - totalFlexShrink, - maxSizeAboveBaseline, - runChildren, - 0)); + runMainAxisExtent, runCrossAxisExtent, totalFlexGrow, totalFlexShrink, maxSizeAboveBaseline, runChildren, 0)); } _flexLineBoxMetrics = _runMetrics; @@ -939,7 +888,7 @@ class RenderFlexLayout extends RenderLayoutBox { // Compute the leading and between spacing of each flex line. Map _computeRunSpacing( List<_RunMetrics> _runMetrics, - ) { + ) { double? contentBoxLogicalWidth = renderStyle.contentBoxLogicalWidth; double? contentBoxLogicalHeight = renderStyle.contentBoxLogicalHeight; double containerCrossAxisExtent = 0.0; @@ -959,8 +908,7 @@ class RenderFlexLayout extends RenderLayoutBox { double runBetweenSpace = 0.0; // Align-content only works in when flex-wrap is no nowrap. - if (renderStyle.flexWrap == FlexWrap.wrap || - renderStyle.flexWrap == FlexWrap.wrapReverse) { + if (renderStyle.flexWrap == FlexWrap.wrap || renderStyle.flexWrap == FlexWrap.wrapReverse) { switch (renderStyle.alignContent) { case AlignContent.flexStart: case AlignContent.start: @@ -976,8 +924,7 @@ class RenderFlexLayout extends RenderLayoutBox { if (crossAxisFreeSpace < 0) { runBetweenSpace = 0; } else { - runBetweenSpace = - runCount > 1 ? crossAxisFreeSpace / (runCount - 1) : 0.0; + runBetweenSpace = runCount > 1 ? crossAxisFreeSpace / (runCount - 1) : 0.0; } break; case AlignContent.spaceAround: @@ -1006,10 +953,7 @@ class RenderFlexLayout extends RenderLayoutBox { break; } } - Map _runSpacingMap = { - 'leading': runLeadingSpace, - 'between': runBetweenSpace - }; + Map _runSpacingMap = {'leading': runLeadingSpace, 'between': runBetweenSpace}; return _runSpacingMap; } @@ -1031,10 +975,9 @@ class RenderFlexLayout extends RenderLayoutBox { List<_RunMetrics> _runMetrics, ) { // Find the max size of flex lines. - _RunMetrics maxMainSizeMetrics = - _runMetrics.reduce((_RunMetrics curr, _RunMetrics next) { - return curr.mainAxisExtent > next.mainAxisExtent ? curr : next; - }); + _RunMetrics maxMainSizeMetrics = _runMetrics.reduce((_RunMetrics curr, _RunMetrics next) { + return curr.mainAxisExtent > next.mainAxisExtent ? curr : next; + }); return maxMainSizeMetrics.mainAxisExtent; } @@ -1079,8 +1022,7 @@ class RenderFlexLayout extends RenderLayoutBox { _RunChild? current = runChildren[childNodeId]; double? flexBasis = _getFlexBasis(child); - double originalMainSize = - flexBasis ?? current!.originalMainSize; + double originalMainSize = flexBasis ?? current!.originalMainSize; double computedSize = originalMainSize; @@ -1093,20 +1035,16 @@ class RenderFlexLayout extends RenderLayoutBox { double remainingFreeSpace = runMetric.remainingFreeSpace; if (isFlexGrow && flexGrow > 0) { - final double spacePerFlex = totalFlexGrow > 0 - ? (remainingFreeSpace / totalFlexGrow) - : double.nan; + final double spacePerFlex = totalFlexGrow > 0 ? (remainingFreeSpace / totalFlexGrow) : double.nan; final double flexGrow = _getFlexGrow(child); computedSize = originalMainSize + spacePerFlex * flexGrow; } else if (isFlexShrink && flexShrink > 0) { // If child's mainAxis have clips, it will create a new format context in it's children's. // so we do't need to care about child's size. if (child is RenderBoxModel && _isChildMainAxisClip(child)) { - computedSize = originalMainSize + remainingFreeSpace > 0 ? - originalMainSize + remainingFreeSpace : 0; + computedSize = originalMainSize + remainingFreeSpace > 0 ? originalMainSize + remainingFreeSpace : 0; } else { - double shrinkValue = - _getShrinkConstraints(child, runChildren, remainingFreeSpace); + double shrinkValue = _getShrinkConstraints(child, runChildren, remainingFreeSpace); computedSize = originalMainSize + shrinkValue; } } @@ -1143,16 +1081,14 @@ class RenderFlexLayout extends RenderLayoutBox { runChild.frozen = true; }); } else { - List<_RunChild> violations = - totalViolation < 0 ? maxViolations : minViolations; + List<_RunChild> violations = totalViolation < 0 ? maxViolations : minViolations; // Find all the violations, set main size and freeze all the flex items. for (int i = 0; i < violations.length; i++) { _RunChild runChild = violations[i]; runChild.frozen = true; RenderBox child = runChild.child; - runMetric.remainingFreeSpace -= - runChild.flexedMainSize - runChild.originalMainSize; + runMetric.remainingFreeSpace -= runChild.flexedMainSize - runChild.originalMainSize; double flexGrow = _getFlexGrow(child); double flexShrink = _getFlexShrink(child); @@ -1161,7 +1097,7 @@ class RenderFlexLayout extends RenderLayoutBox { if (flexGrow > 0) { totalFlexFactor['flexGrow'] = totalFlexFactor['flexGrow']! - flexGrow; - // If total violation is negative, freeze all the items with max violations. + // If total violation is negative, freeze all the items with max violations. } else if (flexShrink > 0) { totalFlexFactor['flexShrink'] = totalFlexFactor['flexShrink']! - flexShrink; } @@ -1206,9 +1142,8 @@ class RenderFlexLayout extends RenderLayoutBox { // Flexbox has several additional cases where a length can be considered definite. // https://www.w3.org/TR/css-flexbox-1/#definite-sizes - bool isMainSizeDefinite = _isHorizontalFlexDirection - ? contentBoxLogicalWidth != null - : contentBoxLogicalHeight != null; + bool isMainSizeDefinite = + _isHorizontalFlexDirection ? contentBoxLogicalWidth != null : contentBoxLogicalHeight != null; for (int i = 0; i < _runMetrics.length; ++i) { final _RunMetrics metrics = _runMetrics[i]; @@ -1226,10 +1161,8 @@ class RenderFlexLayout extends RenderLayoutBox { double marginVertical = 0; if (child is RenderBoxModel) { double? flexBasis = _getFlexBasis(child); - marginHorizontal = child.renderStyle.marginLeft.computedValue + - child.renderStyle.marginRight.computedValue; - marginVertical = child.renderStyle.marginTop.computedValue + - child.renderStyle.marginBottom.computedValue; + marginHorizontal = child.renderStyle.marginLeft.computedValue + child.renderStyle.marginRight.computedValue; + marginVertical = child.renderStyle.marginTop.computedValue + child.renderStyle.marginBottom.computedValue; if (flexBasis != null) { childSpace = flexBasis; } @@ -1241,8 +1174,7 @@ class RenderFlexLayout extends RenderLayoutBox { runChildren.forEach(calTotalSpace); // Flexbox with no size on main axis should adapt the main axis size with children. - double initialFreeSpace = isMainSizeDefinite - ? maxMainSize - totalSpace : 0; + double initialFreeSpace = isMainSizeDefinite ? maxMainSize - totalSpace : 0; bool isFlexGrow = initialFreeSpace > 0 && totalFlexGrow > 0; bool isFlexShrink = initialFreeSpace < 0 && totalFlexShrink > 0; @@ -1287,26 +1219,19 @@ class RenderFlexLayout extends RenderLayoutBox { } // Original size of child. - double childOldMainSize = _isHorizontalFlexDirection - ? child.size.width : child.size.height; - double childOldCrossSize = _isHorizontalFlexDirection - ? child.size.height : child.size.width; + double childOldMainSize = _isHorizontalFlexDirection ? child.size.width : child.size.height; + double childOldCrossSize = _isHorizontalFlexDirection ? child.size.height : child.size.width; // Child need to layout when main axis size or cross size has changed // due to flex-grow/flex-shrink/align-items/align-self specified. - bool childMainSizeChanged = - childFlexedMainSize != null && childFlexedMainSize != childOldMainSize; + bool childMainSizeChanged = childFlexedMainSize != null && childFlexedMainSize != childOldMainSize; bool childCrossSizeChanged = false; // Child cross size adjusted due to align-items/align-self style. double? childStretchedCrossSize; if (_needToStretchChildCrossSize(child)) { - childStretchedCrossSize = _getChildStretchedCrossSize( - child, - metrics.crossAxisExtent, - runBetweenSpace - ); + childStretchedCrossSize = _getChildStretchedCrossSize(child, metrics.crossAxisExtent, runBetweenSpace); childCrossSizeChanged = childStretchedCrossSize != childOldCrossSize; } @@ -1332,13 +1257,9 @@ class RenderFlexLayout extends RenderLayoutBox { // its constraints not changed between two layouts. if (child.constraints == childConstraints) { childConstraints = BoxConstraints( - minWidth: childConstraints.maxWidth != double.infinity - ? childConstraints.maxWidth - : 0, + minWidth: childConstraints.maxWidth != double.infinity ? childConstraints.maxWidth : 0, maxWidth: double.infinity, - minHeight: childConstraints.maxHeight != double.infinity - ? childConstraints.maxHeight - : 0, + minHeight: childConstraints.maxHeight != double.infinity ? childConstraints.maxHeight : 0, maxHeight: double.infinity, ); } @@ -1351,8 +1272,7 @@ class RenderFlexLayout extends RenderLayoutBox { if (kProfileMode && PerformanceTiming.enabled()) { DateTime childLayoutEnd = DateTime.now(); - childLayoutDuration += (childLayoutEnd.microsecondsSinceEpoch - - childLayoutStart.microsecondsSinceEpoch); + childLayoutDuration += (childLayoutEnd.microsecondsSinceEpoch - childLayoutStart.microsecondsSinceEpoch); } } @@ -1374,24 +1294,19 @@ class RenderFlexLayout extends RenderLayoutBox { for (_RunChild runChild in runChildrenList) { RenderBox child = runChild.child; - double childMainSize = _isHorizontalFlexDirection - ? child.size.width - : child.size.height; - double childCrossSize = _isHorizontalFlexDirection - ? child.size.height - : child.size.width; + double childMainSize = _isHorizontalFlexDirection ? child.size.width : child.size.height; + double childCrossSize = _isHorizontalFlexDirection ? child.size.height : child.size.width; double childCrossMargin = 0; if (child is RenderBoxModel) { childCrossMargin = _isHorizontalFlexDirection - ? child.renderStyle.marginTop.computedValue + child.renderStyle.marginBottom.computedValue - : child.renderStyle.marginLeft.computedValue + child.renderStyle.marginRight.computedValue; + ? child.renderStyle.marginTop.computedValue + child.renderStyle.marginBottom.computedValue + : child.renderStyle.marginLeft.computedValue + child.renderStyle.marginRight.computedValue; } double childCrossExtent = childCrossSize + childCrossMargin; - if (runChild.flexedMainSize != childMainSize - && child is RenderReplaced - && child.renderStyle.aspectRatio != null - ) { + if (runChild.flexedMainSize != childMainSize && + child is RenderReplaced && + child.renderStyle.aspectRatio != null) { double childAspectRatio = child.renderStyle.aspectRatio!; if (_isHorizontalFlexDirection && child.renderStyle.height.isAuto) { childCrossSize = runChild.flexedMainSize / childAspectRatio; @@ -1404,8 +1319,7 @@ class RenderFlexLayout extends RenderLayoutBox { // Vertical align is only valid for inline box. // Baseline alignment in column direction behave the same as flex-start. AlignSelf alignSelf = _getAlignSelf(child); - bool isBaselineAlign = alignSelf == AlignSelf.baseline - || renderStyle.alignItems == AlignItems.baseline; + bool isBaselineAlign = alignSelf == AlignSelf.baseline || renderStyle.alignItems == AlignItems.baseline; if (_isHorizontalFlexDirection && isBaselineAlign) { // Distance from top to baseline of child @@ -1421,18 +1335,12 @@ class RenderFlexLayout extends RenderLayoutBox { maxSizeAboveBaseline, ); maxSizeBelowBaseline = math.max( - childMarginTop + - childMarginBottom + - childCrossSize - - childAscent, + childMarginTop + childMarginBottom + childCrossSize - childAscent, maxSizeBelowBaseline, ); runCrossAxisExtent = maxSizeAboveBaseline + maxSizeBelowBaseline; } else { - runCrossAxisExtent = math.max( - runCrossAxisExtent, - childCrossExtent - ); + runCrossAxisExtent = math.max(runCrossAxisExtent, childCrossExtent); } } @@ -1463,25 +1371,19 @@ class RenderFlexLayout extends RenderLayoutBox { } if (child is RenderReplaced && child.renderStyle.aspectRatio != null) { - _overrideReplacedChildLength( - child, - childFlexedMainSize, - childStretchedCrossSize - ); + _overrideReplacedChildLength(child, childFlexedMainSize, childStretchedCrossSize); } BoxConstraints oldConstraints = child.constraints; - double maxConstraintWidth = child.hasOverrideContentLogicalWidth - ? child.renderStyle.borderBoxLogicalWidth! - : oldConstraints.maxWidth; - double maxConstraintHeight = child.hasOverrideContentLogicalHeight - ? child.renderStyle.borderBoxLogicalHeight! - : oldConstraints.maxHeight; - - double minConstraintWidth = oldConstraints.minWidth > maxConstraintWidth - ? maxConstraintWidth : oldConstraints.minWidth; - double minConstraintHeight = oldConstraints.minHeight > maxConstraintHeight - ? maxConstraintHeight : oldConstraints.minHeight; + double maxConstraintWidth = + child.hasOverrideContentLogicalWidth ? child.renderStyle.borderBoxLogicalWidth! : oldConstraints.maxWidth; + double maxConstraintHeight = + child.hasOverrideContentLogicalHeight ? child.renderStyle.borderBoxLogicalHeight! : oldConstraints.maxHeight; + + double minConstraintWidth = + oldConstraints.minWidth > maxConstraintWidth ? maxConstraintWidth : oldConstraints.minWidth; + double minConstraintHeight = + oldConstraints.minHeight > maxConstraintHeight ? maxConstraintHeight : oldConstraints.minHeight; BoxConstraints childConstraints = BoxConstraints( minWidth: minConstraintWidth, @@ -1528,13 +1430,11 @@ class RenderFlexLayout extends RenderLayoutBox { // Clamp replaced element height by min/max height. if (child.renderStyle.minHeight.isNotAuto) { double minHeight = child.renderStyle.minHeight.computedValue; - maxConstraintHeight = maxConstraintHeight < minHeight - ? minHeight : maxConstraintHeight; + maxConstraintHeight = maxConstraintHeight < minHeight ? minHeight : maxConstraintHeight; } if (child.renderStyle.maxHeight.isNotNone) { double maxHeight = child.renderStyle.maxHeight.computedValue; - maxConstraintHeight = maxConstraintHeight > maxHeight - ? maxHeight : maxConstraintHeight; + maxConstraintHeight = maxConstraintHeight > maxHeight ? maxHeight : maxConstraintHeight; } _overrideChildContentBoxLogicalHeight(child, maxConstraintHeight); } @@ -1543,20 +1443,18 @@ class RenderFlexLayout extends RenderLayoutBox { // Override replaced child width when its width is auto. void _overrideReplacedChildWidth( RenderReplaced child, - ) { + ) { if (child.renderStyle.width.isAuto) { double maxConstraintHeight = child.renderStyle.borderBoxLogicalHeight!; double maxConstraintWidth = maxConstraintHeight * child.renderStyle.aspectRatio!; // Clamp replaced element width by min/max width. if (child.renderStyle.minWidth.isNotAuto) { double minWidth = child.renderStyle.minWidth.computedValue; - maxConstraintWidth = maxConstraintWidth < minWidth - ? minWidth : maxConstraintWidth; + maxConstraintWidth = maxConstraintWidth < minWidth ? minWidth : maxConstraintWidth; } if (child.renderStyle.maxWidth.isNotNone) { double maxWidth = child.renderStyle.maxWidth.computedValue; - maxConstraintWidth = maxConstraintWidth > maxWidth - ? maxWidth : maxConstraintWidth; + maxConstraintWidth = maxConstraintWidth > maxWidth ? maxWidth : maxConstraintWidth; } _overrideChildContentBoxLogicalWidth(child, maxConstraintWidth); } @@ -1565,16 +1463,14 @@ class RenderFlexLayout extends RenderLayoutBox { // Override content box logical width of child when flex-grow/flex-shrink/align-items has changed // child's size. void _overrideChildContentBoxLogicalWidth(RenderBoxModel child, double maxConstraintWidth) { - child.renderStyle.contentBoxLogicalWidth = - child.renderStyle.deflatePaddingBorderWidth(maxConstraintWidth); + child.renderStyle.contentBoxLogicalWidth = child.renderStyle.deflatePaddingBorderWidth(maxConstraintWidth); child.hasOverrideContentLogicalWidth = true; } // Override content box logical height of child when flex-grow/flex-shrink/align-items has changed // child's size. void _overrideChildContentBoxLogicalHeight(RenderBoxModel child, double maxConstraintHeight) { - child.renderStyle.contentBoxLogicalHeight = - child.renderStyle.deflatePaddingBorderHeight(maxConstraintHeight); + child.renderStyle.contentBoxLogicalHeight = child.renderStyle.deflatePaddingBorderHeight(maxConstraintHeight); child.hasOverrideContentLogicalHeight = true; } @@ -1590,12 +1486,8 @@ class RenderFlexLayout extends RenderLayoutBox { double runMaxMainSize = _getRunsMaxMainSize(_runMetrics); double runCrossSize = _getRunsCrossSize(_runMetrics); - double contentWidth = _isHorizontalFlexDirection - ? runMaxMainSize - : runCrossSize; - double contentHeight = _isHorizontalFlexDirection - ? runCrossSize - : runMaxMainSize; + double contentWidth = _isHorizontalFlexDirection ? runMaxMainSize : runCrossSize; + double contentHeight = _isHorizontalFlexDirection ? runCrossSize : runMaxMainSize; // Set flex container size. Size layoutContentSize = getContentSize( @@ -1630,12 +1522,9 @@ class RenderFlexLayout extends RenderLayoutBox { double runMainExtent = 0; void iterateRunChildren(int? hashCode, _RunChild runChild) { RenderBox child = runChild.child; - double runChildMainSize = - _isHorizontalFlexDirection ? child.size.width : child.size.height; + double runChildMainSize = _isHorizontalFlexDirection ? child.size.width : child.size.height; if (child is RenderTextBox) { - runChildMainSize = _isHorizontalFlexDirection - ? child.minContentWidth - : child.minContentHeight; + runChildMainSize = _isHorizontalFlexDirection ? child.minContentWidth : child.minContentHeight; } // Should add main axis margin of child to the main axis auto size of parent. if (child is RenderBoxModel) { @@ -1643,9 +1532,8 @@ class RenderFlexLayout extends RenderLayoutBox { double childMarginBottom = child.renderStyle.marginBottom.computedValue; double childMarginLeft = child.renderStyle.marginLeft.computedValue; double childMarginRight = child.renderStyle.marginRight.computedValue; - runChildMainSize += _isHorizontalFlexDirection ? - childMarginLeft + childMarginRight : - childMarginTop + childMarginBottom; + runChildMainSize += + _isHorizontalFlexDirection ? childMarginLeft + childMarginRight : childMarginTop + childMarginBottom; } runMainExtent += runChildMainSize; } @@ -1682,12 +1570,9 @@ class RenderFlexLayout extends RenderLayoutBox { List runChildrenCrossSize = []; void iterateRunChildren(int? hashCode, _RunChild runChild) { RenderBox child = runChild.child; - double runChildCrossSize = - _isHorizontalFlexDirection ? child.size.height : child.size.width; + double runChildCrossSize = _isHorizontalFlexDirection ? child.size.height : child.size.width; if (child is RenderTextBox) { - runChildCrossSize = _isHorizontalFlexDirection - ? child.minContentHeight - : child.minContentWidth; + runChildCrossSize = _isHorizontalFlexDirection ? child.minContentHeight : child.minContentWidth; } runChildrenCrossSize.add(runChildCrossSize); } @@ -1747,8 +1632,7 @@ class RenderFlexLayout extends RenderLayoutBox { // Total main size of previous siblings. double preSiblingsMainSize = 0; for (RenderBox sibling in runChildrenList) { - preSiblingsMainSize += - _isHorizontalFlexDirection ? sibling.size.width : sibling.size.height; + preSiblingsMainSize += _isHorizontalFlexDirection ? sibling.size.width : sibling.size.height; } Size childScrollableSize = child.size; @@ -1761,8 +1645,7 @@ class RenderFlexLayout extends RenderLayoutBox { CSSOverflowType overflowX = childRenderStyle.effectiveOverflowX; CSSOverflowType overflowY = childRenderStyle.effectiveOverflowY; // Only non scroll container need to use scrollable size, otherwise use its own size. - if (overflowX == CSSOverflowType.visible && - overflowY == CSSOverflowType.visible) { + if (overflowX == CSSOverflowType.visible && overflowY == CSSOverflowType.visible) { childScrollableSize = child.scrollableSize; } @@ -1771,10 +1654,8 @@ class RenderFlexLayout extends RenderLayoutBox { // https://www.w3.org/TR/css-overflow-3/#scrollable-overflow-region // Add offset of margin. - childOffsetX += childRenderStyle.marginLeft.computedValue - + childRenderStyle.marginRight.computedValue; - childOffsetY += childRenderStyle.marginTop.computedValue - + childRenderStyle.marginBottom.computedValue; + childOffsetX += childRenderStyle.marginLeft.computedValue + childRenderStyle.marginRight.computedValue; + childOffsetY += childRenderStyle.marginTop.computedValue + childRenderStyle.marginBottom.computedValue; // Add offset of position relative. // Offset of position absolute and fixed is added in layout stage of positioned renderBox. @@ -1797,16 +1678,15 @@ class RenderFlexLayout extends RenderLayoutBox { ? childScrollableSize.width + childOffsetX : childScrollableSize.height + childOffsetY)); scrollableCrossSizeOfChildren.add(_isHorizontalFlexDirection - ? childScrollableSize.height + childOffsetY - : childScrollableSize.width + childOffsetX); + ? childScrollableSize.height + childOffsetY + : childScrollableSize.width + childOffsetX); runChildrenList.add(child); } runChildren.forEach(iterateRunChildren); // Max scrollable main size of all the children in the line. - double maxScrollableMainSizeOfLine = - scrollableMainSizeOfChildren.reduce((double curr, double next) { + double maxScrollableMainSizeOfLine = scrollableMainSizeOfChildren.reduce((double curr, double next) { return curr > next ? curr : next; }); @@ -1822,32 +1702,28 @@ class RenderFlexLayout extends RenderLayoutBox { } // Max scrollable main size of all lines. - double maxScrollableMainSizeOfLines = - scrollableMainSizeOfLines.reduce((double curr, double next) { + double maxScrollableMainSizeOfLines = scrollableMainSizeOfLines.reduce((double curr, double next) { return curr > next ? curr : next; }); - RenderBoxModel container = - isScrollingContentBox ? parent as RenderBoxModel : this; - bool isScrollContainer = - renderStyle.effectiveOverflowX != CSSOverflowType.visible || + RenderBoxModel container = isScrollingContentBox ? parent as RenderBoxModel : this; + bool isScrollContainer = renderStyle.effectiveOverflowX != CSSOverflowType.visible || renderStyle.effectiveOverflowY != CSSOverflowType.visible; // Padding in the end direction of axis should be included in scroll container. - double maxScrollableMainSizeOfChildren = - maxScrollableMainSizeOfLines + _flowAwareMainAxisPadding() - + (isScrollContainer ? _flowAwareMainAxisPadding(isEnd: true) : 0); + double maxScrollableMainSizeOfChildren = maxScrollableMainSizeOfLines + + _flowAwareMainAxisPadding() + + (isScrollContainer ? _flowAwareMainAxisPadding(isEnd: true) : 0); // Max scrollable cross size of all lines. - double maxScrollableCrossSizeOfLines = - scrollableCrossSizeOfLines.reduce((double curr, double next) { + double maxScrollableCrossSizeOfLines = scrollableCrossSizeOfLines.reduce((double curr, double next) { return curr > next ? curr : next; }); // Padding in the end direction of axis should be included in scroll container. - double maxScrollableCrossSizeOfChildren = - maxScrollableCrossSizeOfLines + _flowAwareCrossAxisPadding() - + (isScrollContainer ? _flowAwareCrossAxisPadding(isEnd: true) : 0); + double maxScrollableCrossSizeOfChildren = maxScrollableCrossSizeOfLines + + _flowAwareCrossAxisPadding() + + (isScrollContainer ? _flowAwareCrossAxisPadding(isEnd: true) : 0); double containerContentWidth = size.width - container.renderStyle.effectiveBorderLeftWidth.computedValue - @@ -1856,11 +1732,9 @@ class RenderFlexLayout extends RenderLayoutBox { container.renderStyle.effectiveBorderTopWidth.computedValue - container.renderStyle.effectiveBorderBottomWidth.computedValue; double maxScrollableMainSize = math.max( - _isHorizontalFlexDirection ? containerContentWidth : containerContentHeight, - maxScrollableMainSizeOfChildren); + _isHorizontalFlexDirection ? containerContentWidth : containerContentHeight, maxScrollableMainSizeOfChildren); double maxScrollableCrossSize = math.max( - _isHorizontalFlexDirection ? containerContentHeight : containerContentWidth, - maxScrollableCrossSizeOfChildren); + _isHorizontalFlexDirection ? containerContentHeight : containerContentWidth, maxScrollableCrossSizeOfChildren); scrollableSize = _isHorizontalFlexDirection ? Size(maxScrollableMainSize, maxScrollableCrossSize) @@ -1873,16 +1747,15 @@ class RenderFlexLayout extends RenderLayoutBox { double runCrossAxisExtent, double runBetweenSpace, ) { - bool isSingleLine = (renderStyle.flexWrap != FlexWrap.wrap && - renderStyle.flexWrap != FlexWrap.wrapReverse); + bool isSingleLine = (renderStyle.flexWrap != FlexWrap.wrap && renderStyle.flexWrap != FlexWrap.wrapReverse); if (isSingleLine) { // Normally the height of flex line in single line equals to flex container's cross size. // But it may change in cases of the cross size of replaced flex item tranferred from // its flexed main size. bool isCrossSizeDefinite = _isHorizontalFlexDirection - ? renderStyle.contentBoxLogicalHeight != null - : renderStyle.contentBoxLogicalWidth != null; + ? renderStyle.contentBoxLogicalHeight != null + : renderStyle.contentBoxLogicalWidth != null; if (_needToStretchChildCrossSize(child) && !isCrossSizeDefinite) { return runCrossAxisExtent; } else { @@ -1942,8 +1815,7 @@ class RenderFlexLayout extends RenderLayoutBox { // right-to-left/bottom-to-top (true). The _startIsTopLeft will return null if there's only // one child and the relevant direction is null, in which case we arbitrarily decide not to // flip, but that doesn't have any detectable effect. - final bool flipMainAxis = - !(_startIsTopLeft(renderStyle.flexDirection) ?? true); + final bool flipMainAxis = !(_startIsTopLeft(renderStyle.flexDirection) ?? true); switch (renderStyle.justifyContent) { case JustifyContent.flexStart: case JustifyContent.start: @@ -1964,9 +1836,7 @@ class RenderFlexLayout extends RenderLayoutBox { if (remainingSpace < 0) { betweenSpace = 0.0; } else { - betweenSpace = runChildrenCount > 1 - ? remainingSpace / (runChildrenCount - 1) - : 0.0; + betweenSpace = runChildrenCount > 1 ? remainingSpace / (runChildrenCount - 1) : 0.0; } break; case JustifyContent.spaceAround: @@ -1974,8 +1844,7 @@ class RenderFlexLayout extends RenderLayoutBox { leadingSpace = remainingSpace / 2.0; betweenSpace = 0.0; } else { - betweenSpace = - runChildrenCount > 0 ? remainingSpace / runChildrenCount : 0.0; + betweenSpace = runChildrenCount > 0 ? remainingSpace / runChildrenCount : 0.0; leadingSpace = betweenSpace / 2.0; } break; @@ -1984,9 +1853,7 @@ class RenderFlexLayout extends RenderLayoutBox { leadingSpace = remainingSpace / 2.0; betweenSpace = 0.0; } else { - betweenSpace = runChildrenCount > 0 - ? remainingSpace / (runChildrenCount + 1) - : 0.0; + betweenSpace = runChildrenCount > 0 ? remainingSpace / (runChildrenCount + 1) : 0.0; leadingSpace = betweenSpace; } break; @@ -2017,10 +1884,7 @@ class RenderFlexLayout extends RenderLayoutBox { // Main axis position of child on layout. double childMainPosition = flipMainAxis - ? mainAxisStartPadding + - mainAxisStartBorder + - mainAxisContentSize - - leadingSpace + ? mainAxisStartPadding + mainAxisStartBorder + mainAxisContentSize - leadingSpace : leadingSpace + mainAxisStartPadding + mainAxisStartBorder; for (_RunChild runChild in runChildrenList) { @@ -2083,10 +1947,7 @@ class RenderFlexLayout extends RenderLayoutBox { // Text is aligned in anonymous block container rather than flexbox container. // https://www.w3.org/TR/css-flexbox-1/#flex-items - if (renderStyle.alignItems == AlignItems.stretch - && child is RenderTextBox - && !_isHorizontalFlexDirection - ) { + if (renderStyle.alignItems == AlignItems.stretch && child is RenderTextBox && !_isHorizontalFlexDirection) { TextAlign textAlign = renderStyle.textAlign; if (textAlign == TextAlign.start) { alignment = 'start'; @@ -2123,21 +1984,17 @@ class RenderFlexLayout extends RenderLayoutBox { double verticalRemainingSpace; // Margin auto does not work with negative remaining space. double mainAxisRemainingSpace = math.max(0, remainingSpace); - double crossAxisRemainingSpace = - math.max(0, crossAxisContentSize - _getCrossAxisExtent(child)); + double crossAxisRemainingSpace = math.max(0, crossAxisContentSize - _getCrossAxisExtent(child)); if (_isHorizontalFlexDirection) { horizontalRemainingSpace = mainAxisRemainingSpace; verticalRemainingSpace = crossAxisRemainingSpace; if (marginLeft.isAuto) { if (marginRight.isAuto) { - childMainPosition += - (horizontalRemainingSpace / mainAxisMarginAutoChildrenCount) / 2; - betweenSpace = - (horizontalRemainingSpace / mainAxisMarginAutoChildrenCount) / 2; + childMainPosition += (horizontalRemainingSpace / mainAxisMarginAutoChildrenCount) / 2; + betweenSpace = (horizontalRemainingSpace / mainAxisMarginAutoChildrenCount) / 2; } else { - childMainPosition += - horizontalRemainingSpace / mainAxisMarginAutoChildrenCount; + childMainPosition += horizontalRemainingSpace / mainAxisMarginAutoChildrenCount; } } @@ -2153,13 +2010,10 @@ class RenderFlexLayout extends RenderLayoutBox { verticalRemainingSpace = mainAxisRemainingSpace; if (marginTop.isAuto) { if (marginBottom.isAuto) { - childMainPosition += - (verticalRemainingSpace / mainAxisMarginAutoChildrenCount) / 2; - betweenSpace = - (verticalRemainingSpace / mainAxisMarginAutoChildrenCount) / 2; + childMainPosition += (verticalRemainingSpace / mainAxisMarginAutoChildrenCount) / 2; + betweenSpace = (verticalRemainingSpace / mainAxisMarginAutoChildrenCount) / 2; } else { - childMainPosition += - verticalRemainingSpace / mainAxisMarginAutoChildrenCount; + childMainPosition += verticalRemainingSpace / mainAxisMarginAutoChildrenCount; } } @@ -2177,11 +2031,8 @@ class RenderFlexLayout extends RenderLayoutBox { double crossOffset; if (renderStyle.flexWrap == FlexWrap.wrapReverse) { - crossOffset = childCrossPosition! + - (crossAxisContentSize - - crossAxisOffset - - runCrossAxisExtent - - runBetweenSpace); + crossOffset = + childCrossPosition! + (crossAxisContentSize - crossAxisOffset - runCrossAxisExtent - runBetweenSpace); } else { crossOffset = childCrossPosition! + crossAxisOffset; } @@ -2194,8 +2045,7 @@ class RenderFlexLayout extends RenderLayoutBox { if (flipMainAxis) { childMainPosition -= betweenSpace + childMainAxisMargin; } else { - childMainPosition += - _getMainAxisExtent(child) - childMainAxisMargin + betweenSpace; + childMainPosition += _getMainAxisExtent(child) - childMainAxisMargin + betweenSpace; } } @@ -2210,29 +2060,21 @@ class RenderFlexLayout extends RenderLayoutBox { // is treated the same as flex-start. // https://www.w3.org/TR/css-flexbox-1/#abspos-items final RenderLayoutParentData childParentData = child.parentData as RenderLayoutParentData; - if (child is! RenderBoxModel - || child is RenderLineBreak - || (childParentData.isPositioned) - ) { + if (child is! RenderBoxModel || child is RenderLineBreak || (childParentData.isPositioned)) { return false; } AlignSelf alignSelf = _getAlignSelf(child); - bool isChildAlignmentStretch = alignSelf != AlignSelf.auto - ? alignSelf == AlignSelf.stretch - : renderStyle.alignItems == AlignItems.stretch; + bool isChildAlignmentStretch = + alignSelf != AlignSelf.auto ? alignSelf == AlignSelf.stretch : renderStyle.alignItems == AlignItems.stretch; - bool isChildLengthAuto = _isHorizontalFlexDirection - ? child.renderStyle.height.isAuto - : child.renderStyle.width.isAuto; + bool isChildLengthAuto = + _isHorizontalFlexDirection ? child.renderStyle.height.isAuto : child.renderStyle.width.isAuto; // If the cross size property of the flex item computes to auto, and neither of // the cross axis margins are auto, the flex item is stretched. // https://www.w3.org/TR/css-flexbox-1/#valdef-align-items-stretch - if (isChildAlignmentStretch - && !_isChildCrossAxisMarginAutoExist(child) - && isChildLengthAuto - ) { + if (isChildAlignmentStretch && !_isChildCrossAxisMarginAutoExist(child) && isChildLengthAuto) { return true; } @@ -2245,24 +2087,20 @@ class RenderFlexLayout extends RenderLayoutBox { double runCrossAxisExtent, double runBetweenSpace, ) { - bool isFlexWrap = renderStyle.flexWrap == FlexWrap.wrap - || renderStyle.flexWrap == FlexWrap.wrapReverse; - double childCrossAxisMargin = _isHorizontalFlexDirection - ? child.renderStyle.margin.vertical : child.renderStyle.margin.horizontal; - double maxCrossSizeConstraints = _isHorizontalFlexDirection - ? constraints.maxHeight : constraints.maxWidth; + bool isFlexWrap = renderStyle.flexWrap == FlexWrap.wrap || renderStyle.flexWrap == FlexWrap.wrapReverse; + double childCrossAxisMargin = + _isHorizontalFlexDirection ? child.renderStyle.margin.vertical : child.renderStyle.margin.horizontal; + double maxCrossSizeConstraints = _isHorizontalFlexDirection ? constraints.maxHeight : constraints.maxWidth; double flexLineCrossSize = _getFlexLineCrossSize(child, runCrossAxisExtent, runBetweenSpace); // Should subtract margin when stretch flex item. double childStretchedCrossSize = flexLineCrossSize - childCrossAxisMargin; // Flex line cross size should not exceed container's cross size if specified when flex-wrap is nowrap. if (!isFlexWrap && maxCrossSizeConstraints.isFinite) { - double crossAxisBorder = _isHorizontalFlexDirection - ? renderStyle.border.vertical : renderStyle.border.horizontal; - double crossAxisPadding = _isHorizontalFlexDirection - ? renderStyle.padding.vertical : renderStyle.padding.horizontal; - childStretchedCrossSize = math.min( - maxCrossSizeConstraints - crossAxisBorder - crossAxisPadding, - childStretchedCrossSize); + double crossAxisBorder = _isHorizontalFlexDirection ? renderStyle.border.vertical : renderStyle.border.horizontal; + double crossAxisPadding = + _isHorizontalFlexDirection ? renderStyle.padding.vertical : renderStyle.padding.horizontal; + childStretchedCrossSize = + math.min(maxCrossSizeConstraints - crossAxisBorder - crossAxisPadding, childStretchedCrossSize); } // Constrain stretched size by max-width/max-height. @@ -2273,8 +2111,7 @@ class RenderFlexLayout extends RenderLayoutBox { maxCrossSize = child.renderStyle.maxWidth.computedValue; } if (maxCrossSize != null) { - childStretchedCrossSize = childStretchedCrossSize > maxCrossSize - ? maxCrossSize : childStretchedCrossSize; + childStretchedCrossSize = childStretchedCrossSize > maxCrossSize ? maxCrossSize : childStretchedCrossSize; } return childStretchedCrossSize; @@ -2289,8 +2126,7 @@ class RenderFlexLayout extends RenderLayoutBox { CSSLengthValue marginTop = childRenderStyle.marginTop; CSSLengthValue marginBottom = childRenderStyle.marginBottom; if (_isHorizontalFlexDirection && (marginLeft.isAuto || marginRight.isAuto) || - !_isHorizontalFlexDirection && (marginTop.isAuto || marginBottom.isAuto) - ) { + !_isHorizontalFlexDirection && (marginTop.isAuto || marginBottom.isAuto)) { return true; } } @@ -2306,8 +2142,7 @@ class RenderFlexLayout extends RenderLayoutBox { CSSLengthValue marginTop = childRenderStyle.marginTop; CSSLengthValue marginBottom = childRenderStyle.marginBottom; if (_isHorizontalFlexDirection && (marginTop.isAuto || marginBottom.isAuto) || - !_isHorizontalFlexDirection && (marginLeft.isAuto || marginRight.isAuto) - ) { + !_isHorizontalFlexDirection && (marginLeft.isAuto || marginRight.isAuto)) { return true; } } @@ -2338,9 +2173,7 @@ class RenderFlexLayout extends RenderLayoutBox { runBetweenSpace, ); double childCrossAxisStartMargin = _flowAwareChildCrossAxisMargin(child)!; - double crossStartAddedOffset = crossAxisStartPadding + - crossAxisStartBorder + - childCrossAxisStartMargin; + double crossStartAddedOffset = crossAxisStartPadding + crossAxisStartBorder + childCrossAxisStartMargin; // Align-items and align-self have no effect if auto margin of child exists in the cross axis. if (_isChildCrossAxisMarginAutoExist(child)) { @@ -2353,19 +2186,16 @@ class RenderFlexLayout extends RenderLayoutBox { case 'end': // Length returned by _getCrossAxisExtent includes margin, so end alignment should add start margin. return crossAxisStartPadding + - crossAxisStartBorder + - flexLineCrossSize - - _getCrossAxisExtent(child) + - childCrossAxisStartMargin; + crossAxisStartBorder + + flexLineCrossSize - + _getCrossAxisExtent(child) + + childCrossAxisStartMargin; case 'center': - return childCrossPosition = crossStartAddedOffset + - (flexLineCrossSize - _getCrossAxisExtent(child)) / 2.0; + return childCrossPosition = crossStartAddedOffset + (flexLineCrossSize - _getCrossAxisExtent(child)) / 2.0; case 'baseline': // Distance from top to baseline of child. double childAscent = _getChildAscent(child); - return crossStartAddedOffset + - lineBoxLeading / 2 + - (runBaselineExtent - childAscent); + return crossStartAddedOffset + lineBoxLeading / 2 + (runBaselineExtent - childAscent); default: return null; } @@ -2379,15 +2209,12 @@ class RenderFlexLayout extends RenderLayoutBox { double marginBottom = renderStyle.marginBottom.computedValue; bool isParentFlowLayout = parent is RenderFlowLayout; CSSDisplay? effectiveDisplay = renderStyle.effectiveDisplay; - bool isDisplayInline = effectiveDisplay != CSSDisplay.block && - effectiveDisplay != CSSDisplay.flex; + bool isDisplayInline = effectiveDisplay != CSSDisplay.block && effectiveDisplay != CSSDisplay.flex; // Use margin bottom as baseline if layout has no children if (_flexLineBoxMetrics.isEmpty) { if (isDisplayInline) { // Flex item baseline does not includes margin-bottom - lineDistance = isParentFlowLayout - ? marginTop + boxSize!.height + marginBottom - : marginTop + boxSize!.height; + lineDistance = isParentFlowLayout ? marginTop + boxSize!.height + marginBottom : marginTop + boxSize!.height; return lineDistance; } else { return null; @@ -2396,15 +2223,12 @@ class RenderFlexLayout extends RenderLayoutBox { // Always use the baseline of the first child as the baseline in flex layout. _RunMetrics firstLineMetrics = _flexLineBoxMetrics[0]; - List<_RunChild> firstRunChildren = - firstLineMetrics.runChildren.values.toList(); + List<_RunChild> firstRunChildren = firstLineMetrics.runChildren.values.toList(); _RunChild firstRunChild = firstRunChildren[0]; RenderBox child = firstRunChild.child; - double childMarginTop = - child is RenderBoxModel ? child.renderStyle.marginTop.computedValue : 0; - RenderLayoutParentData childParentData = - child.parentData as RenderLayoutParentData; + double childMarginTop = child is RenderBoxModel ? child.renderStyle.marginTop.computedValue : 0; + RenderLayoutParentData childParentData = child.parentData as RenderLayoutParentData; double? childBaseLineDistance = 0; if (child is RenderBoxModel) { childBaseLineDistance = child.computeDistanceToBaseline(); @@ -2417,8 +2241,7 @@ class RenderFlexLayout extends RenderLayoutBox { Offset? relativeOffset; double childOffsetY = childParentData.offset.dy - childMarginTop; if (child is RenderBoxModel) { - relativeOffset = - CSSPositionedLayout.getRelativeOffset(child.renderStyle); + relativeOffset = CSSPositionedLayout.getRelativeOffset(child.renderStyle); } if (relativeOffset != null) { childOffsetY -= relativeOffset.dy; @@ -2431,8 +2254,7 @@ class RenderFlexLayout extends RenderLayoutBox { } // Get child size through boxSize to avoid flutter error when parentUsesSize is set to false. - Size? _getChildSize(RenderBox? child, - {bool shouldUseIntrinsicMainSize = false}) { + Size? _getChildSize(RenderBox? child, {bool shouldUseIntrinsicMainSize = false}) { Size? childSize; if (child is RenderBoxModel) { childSize = child.boxSize; @@ -2446,8 +2268,7 @@ class RenderFlexLayout extends RenderLayoutBox { } if (shouldUseIntrinsicMainSize) { - double? childIntrinsicMainSize = - _childrenIntrinsicMainSizes[child.hashCode]; + double? childIntrinsicMainSize = _childrenIntrinsicMainSizes[child.hashCode]; if (_isHorizontalFlexDirection) { childSize = Size(childIntrinsicMainSize!, childSize!.height); } else { @@ -2460,8 +2281,7 @@ class RenderFlexLayout extends RenderLayoutBox { // Get distance from top to baseline of child including margin. double _getChildAscent(RenderBox child) { // Distance from top to baseline of child. - double? childAscent = - child.getDistanceToBaseline(TextBaseline.alphabetic, onlyReal: true); + double? childAscent = child.getDistanceToBaseline(TextBaseline.alphabetic, onlyReal: true); double? childMarginTop = 0; double? childMarginBottom = 0; if (child is RenderBoxModel) { @@ -2521,14 +2341,10 @@ class RenderFlexLayout extends RenderLayoutBox { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty( - 'flexDirection', renderStyle.flexDirection)); - properties.add(DiagnosticsProperty( - 'justifyContent', renderStyle.justifyContent)); - properties.add( - DiagnosticsProperty('alignItems', renderStyle.alignItems)); - properties - .add(DiagnosticsProperty('flexWrap', renderStyle.flexWrap)); + properties.add(DiagnosticsProperty('flexDirection', renderStyle.flexDirection)); + properties.add(DiagnosticsProperty('justifyContent', renderStyle.justifyContent)); + properties.add(DiagnosticsProperty('alignItems', renderStyle.alignItems)); + properties.add(DiagnosticsProperty('flexWrap', renderStyle.flexWrap)); } static bool _isPlaceholderPositioned(RenderObject child) { @@ -2560,9 +2376,9 @@ class RenderRepaintBoundaryFlexLayout extends RenderFlexLayout { List? children, required CSSRenderStyle renderStyle, }) : super( - children: children, - renderStyle: renderStyle, - ); + children: children, + renderStyle: renderStyle, + ); @override bool get isRepaintBoundary => true; diff --git a/webf/lib/src/rendering/flow.dart b/webf/lib/src/rendering/flow.dart index 61dcd27148..245c0aefe6 100644 --- a/webf/lib/src/rendering/flow.dart +++ b/webf/lib/src/rendering/flow.dart @@ -1,13 +1,14 @@ /* - * Copyright (C) 2020-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:math' as math; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/module.dart'; -import 'package:kraken/rendering.dart'; +import 'package:webf/css.dart'; +import 'package:webf/module.dart'; +import 'package:webf/rendering.dart'; // Position and size of each run (line box) in flow layout. // https://www.w3.org/TR/css-inline-3/#line-boxes @@ -72,8 +73,7 @@ class RenderFlowLayout extends RenderLayoutBox { child.parentData = RenderLayoutParentData(); } if (child is RenderBoxModel) { - child.parentData = CSSPositionedLayout.getPositionParentData( - child, child.parentData as RenderLayoutParentData); + child.parentData = CSSPositionedLayout.getPositionParentData(child, child.parentData as RenderLayoutParentData); } } @@ -81,8 +81,7 @@ class RenderFlowLayout extends RenderLayoutBox { double marginHorizontal = 0; if (child is RenderBoxModel) { - marginHorizontal = child.renderStyle.marginLeft.computedValue + - child.renderStyle.marginRight.computedValue; + marginHorizontal = child.renderStyle.marginLeft.computedValue + child.renderStyle.marginRight.computedValue; } Size childSize = _getChildSize(child) ?? Size.zero; @@ -101,18 +100,15 @@ class RenderFlowLayout extends RenderLayoutBox { Size childSize = _getChildSize(child) ?? Size.zero; return lineHeight != null - ? math.max(lineHeight, childSize.height) + marginVertical - : childSize.height + marginVertical; + ? math.max(lineHeight, childSize.height) + marginVertical + : childSize.height + marginVertical; } Offset _getOffset(double mainAxisOffset, double crossAxisOffset) { return Offset(mainAxisOffset, crossAxisOffset); } - double _getChildCrossAxisOffset( - double runCrossAxisExtent, - double childCrossAxisExtent - ) { + double _getChildCrossAxisOffset(double runCrossAxisExtent, double childCrossAxisExtent) { return runCrossAxisExtent - childCrossAxisExtent; } @@ -137,8 +133,7 @@ class RenderFlowLayout extends RenderLayoutBox { doingThisLayout = true; if (kProfileMode && PerformanceTiming.enabled()) { childLayoutDuration = 0; - PerformanceTiming.instance() - .mark(PERF_FLOW_LAYOUT_START, uniqueId: hashCode); + PerformanceTiming.instance().mark(PERF_FLOW_LAYOUT_START, uniqueId: hashCode); } _doPerformLayout(); @@ -150,10 +145,8 @@ class RenderFlowLayout extends RenderLayoutBox { if (kProfileMode && PerformanceTiming.enabled()) { DateTime flowLayoutEndTime = DateTime.now(); - int amendEndTime = - flowLayoutEndTime.microsecondsSinceEpoch - childLayoutDuration; - PerformanceTiming.instance().mark(PERF_FLOW_LAYOUT_END, - uniqueId: hashCode, startTime: amendEndTime); + int amendEndTime = flowLayoutEndTime.microsecondsSinceEpoch - childLayoutDuration; + PerformanceTiming.instance().mark(PERF_FLOW_LAYOUT_END, uniqueId: hashCode, startTime: amendEndTime); } doingThisLayout = false; } @@ -209,9 +202,8 @@ class RenderFlowLayout extends RenderLayoutBox { } } - bool isScrollContainer = - renderStyle.effectiveOverflowX != CSSOverflowType.visible - || renderStyle.effectiveOverflowY != CSSOverflowType.visible; + bool isScrollContainer = renderStyle.effectiveOverflowX != CSSOverflowType.visible || + renderStyle.effectiveOverflowY != CSSOverflowType.visible; if (isScrollContainer) { // Find all the sticky children when scroll container is layouted. @@ -225,7 +217,6 @@ class RenderFlowLayout extends RenderLayoutBox { didLayout(); } - // There are 3 steps for layout children. // 1. Layout children to generate line boxes metrics. // 2. Set flex container size according to children size and its own size styles. @@ -257,7 +248,7 @@ class RenderFlowLayout extends RenderLayoutBox { // and alignment properties. List<_RunMetrics> _computeRunMetrics( List children, - ) { + ) { List<_RunMetrics> _runMetrics = <_RunMetrics>[]; double mainAxisLimit = renderStyle.contentMaxConstraintsWidth; @@ -291,10 +282,9 @@ class RenderFlowLayout extends RenderLayoutBox { bool isChildNeedsLayout = true; if (child.hasSize && - !needsRelayout && - (childConstraints == child.constraints) && - ((child is RenderBoxModel && !child.needsLayout) || - (child is RenderTextBox && !child.needsLayout))) { + !needsRelayout && + (childConstraints == child.constraints) && + ((child is RenderBoxModel && !child.needsLayout) || (child is RenderTextBox && !child.needsLayout))) { isChildNeedsLayout = false; } @@ -308,13 +298,9 @@ class RenderFlowLayout extends RenderLayoutBox { // cause Flutter will skip child layout if its constraints not changed between two layouts. if (child is RenderBoxModel && needsRelayout) { childConstraints = BoxConstraints( - minWidth: childConstraints.maxWidth != double.infinity - ? childConstraints.maxWidth - : 0, + minWidth: childConstraints.maxWidth != double.infinity ? childConstraints.maxWidth : 0, maxWidth: double.infinity, - minHeight: childConstraints.maxHeight != double.infinity - ? childConstraints.maxHeight - : 0, + minHeight: childConstraints.maxHeight != double.infinity ? childConstraints.maxHeight : 0, maxHeight: double.infinity, ); } @@ -322,8 +308,7 @@ class RenderFlowLayout extends RenderLayoutBox { if (kProfileMode && PerformanceTiming.enabled()) { DateTime childLayoutEnd = DateTime.now(); - childLayoutDuration += (childLayoutEnd.microsecondsSinceEpoch - - childLayoutStart.microsecondsSinceEpoch); + childLayoutDuration += (childLayoutEnd.microsecondsSinceEpoch - childLayoutStart.microsecondsSinceEpoch); } } @@ -334,25 +319,24 @@ class RenderFlowLayout extends RenderLayoutBox { RenderPositionPlaceholder positionHolder = child as RenderPositionPlaceholder; RenderBoxModel? childRenderBoxModel = positionHolder.positioned; if (childRenderBoxModel != null) { - RenderLayoutParentData childParentData = - childRenderBoxModel.parentData as RenderLayoutParentData; + RenderLayoutParentData childParentData = childRenderBoxModel.parentData as RenderLayoutParentData; if (childParentData.isPositioned) { childMainAxisExtent = childCrossAxisExtent = 0; } } } if (runChildren.isNotEmpty && - // Current is block. - (_isChildBlockLevel(child) || - // Previous is block. - _isChildBlockLevel(preChild) || - // Line length is exceed container. - // The white-space property not only specifies whether and how white space is collapsed - // but only specifies whether lines may wrap at unforced soft wrap opportunities - // https://www.w3.org/TR/css-text-3/#line-breaking - (whiteSpace != WhiteSpace.nowrap && (runMainAxisExtent + childMainAxisExtent > mainAxisLimit)) || - // Previous is linebreak. - preChild is RenderLineBreak)) { + // Current is block. + (_isChildBlockLevel(child) || + // Previous is block. + _isChildBlockLevel(preChild) || + // Line length is exceed container. + // The white-space property not only specifies whether and how white space is collapsed + // but only specifies whether lines may wrap at unforced soft wrap opportunities + // https://www.w3.org/TR/css-text-3/#line-breaking + (whiteSpace != WhiteSpace.nowrap && (runMainAxisExtent + childMainAxisExtent > mainAxisLimit)) || + // Previous is linebreak. + preChild is RenderLineBreak)) { _runMetrics.add(_RunMetrics( runMainAxisExtent, runCrossAxisExtent, @@ -389,10 +373,7 @@ class RenderFlowLayout extends RenderLayoutBox { // When baseline of children not found, use boundary of margin bottom as baseline. double childAscent = _getChildAscent(child); double extentAboveBaseline = childAscent; - double extentBelowBaseline = childMarginTop + - childSize.height + - childMarginBottom - - childAscent; + double extentBelowBaseline = childMarginTop + childSize.height + childMarginBottom - childAscent; maxSizeAboveBaseline = math.max( extentAboveBaseline, @@ -437,7 +418,7 @@ class RenderFlowLayout extends RenderLayoutBox { // @TODO: add cache to avoid recalculate in one layout stage. double _getRunsCrossSize( List<_RunMetrics> _runMetrics, - ) { + ) { double crossSize = 0; for (_RunMetrics run in _runMetrics) { crossSize += run.crossAxisExtent; @@ -449,10 +430,9 @@ class RenderFlowLayout extends RenderLayoutBox { // @TODO: add cache to avoid recalculate in one layout stage. double _getRunsMaxMainSize( List<_RunMetrics> _runMetrics, - ) { + ) { // Find the max size of lines. - _RunMetrics maxMainSizeMetrics = - _runMetrics.reduce((_RunMetrics curr, _RunMetrics next) { + _RunMetrics maxMainSizeMetrics = _runMetrics.reduce((_RunMetrics curr, _RunMetrics next) { return curr.mainAxisExtent > next.mainAxisExtent ? curr : next; }); return maxMainSizeMetrics.mainAxisExtent; @@ -461,7 +441,7 @@ class RenderFlowLayout extends RenderLayoutBox { // Set flex container size according to children size. void _setContainerSize( List<_RunMetrics> _runMetrics, - ) { + ) { if (_runMetrics.isEmpty) { _setContainerSizeWithNoChild(); return; @@ -504,7 +484,7 @@ class RenderFlowLayout extends RenderLayoutBox { // void _adjustChildrenSize( List<_RunMetrics> _runMetrics, - ) { + ) { if (_runMetrics.isEmpty) return; // Element of inline-block will shrink to its maximum children size @@ -518,8 +498,8 @@ class RenderFlowLayout extends RenderLayoutBox { for (RenderBox child in runChildrenList) { if (child is RenderBoxModel) { - bool isChildBlockLevel = child.renderStyle.effectiveDisplay == CSSDisplay.block - || child.renderStyle.effectiveDisplay == CSSDisplay.flex; + bool isChildBlockLevel = child.renderStyle.effectiveDisplay == CSSDisplay.block || + child.renderStyle.effectiveDisplay == CSSDisplay.flex; // Element of display block will stretch to the width of its container // when its width is not specified. if (isChildBlockLevel && child.constraints.maxWidth.isInfinite) { @@ -614,15 +594,13 @@ class RenderFlowLayout extends RenderLayoutBox { // which is not positioned and computed to 0px in other cases. if (child is RenderBoxModel) { RenderStyle childRenderStyle = child.renderStyle; - CSSDisplay? childEffectiveDisplay = - childRenderStyle.effectiveDisplay; + CSSDisplay? childEffectiveDisplay = childRenderStyle.effectiveDisplay; CSSLengthValue marginLeft = childRenderStyle.marginLeft; CSSLengthValue marginRight = childRenderStyle.marginRight; // 'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + // 'border-right-width' + 'margin-right' = width of containing block - if (childEffectiveDisplay == CSSDisplay.block || - childEffectiveDisplay == CSSDisplay.flex) { + if (childEffectiveDisplay == CSSDisplay.block || childEffectiveDisplay == CSSDisplay.flex) { if (marginLeft.isAuto) { double remainingSpace = mainAxisContentSize - childMainAxisExtent; if (marginRight.isAuto) { @@ -636,9 +614,8 @@ class RenderFlowLayout extends RenderLayoutBox { // Always align to the top of run when positioning positioned element placeholder // @HACK(kraken): Judge positioned holder to impl top align. - final double childCrossAxisOffset = isPositionPlaceholder(child) - ? 0 - : _getChildCrossAxisOffset(runCrossAxisExtent, childCrossAxisExtent); + final double childCrossAxisOffset = + isPositionPlaceholder(child) ? 0 : _getChildCrossAxisOffset(runCrossAxisExtent, childCrossAxisExtent); Size? childSize = _getChildSize(child); // Child line extent calculated according to vertical align. @@ -661,20 +638,18 @@ class RenderFlowLayout extends RenderLayoutBox { switch (verticalAlign) { case VerticalAlign.baseline: - childLineExtent = - lineBoxLeading / 2 + (runBaselineExtent - childAscent); + childLineExtent = lineBoxLeading / 2 + (runBaselineExtent - childAscent); break; case VerticalAlign.top: childLineExtent = 0; break; case VerticalAlign.bottom: - childLineExtent = - (lineBoxHeight ?? runCrossAxisExtent) - childSize!.height; + childLineExtent = (lineBoxHeight ?? runCrossAxisExtent) - childSize!.height; break; - // @TODO: Vertical align middle needs to calculate the baseline of the parent box plus - // half the x-height of the parent from W3C spec currently flutter lack the api to calculate x-height of glyph. - // case VerticalAlign.middle: - // break; + // @TODO: Vertical align middle needs to calculate the baseline of the parent box plus + // half the x-height of the parent from W3C spec currently flutter lack the api to calculate x-height of glyph. + // case VerticalAlign.middle: + // break; } // Child should not exceed over the top of parent. childLineExtent = childLineExtent < 0 ? 0 : childLineExtent; @@ -697,15 +672,15 @@ class RenderFlowLayout extends RenderLayoutBox { // No need to add padding and border for scrolling content box. Offset relativeOffset = _getOffset( - childMainPosition + - renderStyle.paddingLeft.computedValue + - renderStyle.effectiveBorderLeftWidth.computedValue + - childMarginLeft, - crossAxisOffset + - childLineExtent + - renderStyle.paddingTop.computedValue + - renderStyle.effectiveBorderTopWidth.computedValue + - childMarginTop); + childMainPosition + + renderStyle.paddingLeft.computedValue + + renderStyle.effectiveBorderLeftWidth.computedValue + + childMarginLeft, + crossAxisOffset + + childLineExtent + + renderStyle.paddingTop.computedValue + + renderStyle.effectiveBorderTopWidth.computedValue + + childMarginTop); // Apply position relative offset change. CSSPositionedLayout.applyRelativeOffset(relativeOffset, child); @@ -734,9 +709,7 @@ class RenderFlowLayout extends RenderLayoutBox { if (_lineBoxMetrics.isEmpty) { if (isDisplayInline) { // Flex item baseline does not includes margin-bottom. - lineDistance = isParentFlowLayout - ? marginTop + boxSize!.height + marginBottom - : marginTop + boxSize!.height; + lineDistance = isParentFlowLayout ? marginTop + boxSize!.height + marginBottom : marginTop + boxSize!.height; return lineDistance; } else { return null; @@ -746,23 +719,18 @@ class RenderFlowLayout extends RenderLayoutBox { // Use baseline of last line in flow layout and layout is inline-level // otherwise use baseline of first line. bool isLastLineBaseline = isParentFlowLayout && isDisplayInline; - _RunMetrics lineMetrics = isLastLineBaseline - ? _lineBoxMetrics[_lineBoxMetrics.length - 1] - : _lineBoxMetrics[0]; + _RunMetrics lineMetrics = isLastLineBaseline ? _lineBoxMetrics[_lineBoxMetrics.length - 1] : _lineBoxMetrics[0]; // Use the max baseline of the children as the baseline in flow layout. lineMetrics.runChildren.forEach((int? hashCode, RenderBox child) { - double? childMarginTop = - child is RenderBoxModel ? _getChildMarginTop(child) : 0; - RenderLayoutParentData? childParentData = - child.parentData as RenderLayoutParentData?; + double? childMarginTop = child is RenderBoxModel ? _getChildMarginTop(child) : 0; + RenderLayoutParentData? childParentData = child.parentData as RenderLayoutParentData?; double? childBaseLineDistance; if (child is RenderBoxModel) { childBaseLineDistance = child.computeDistanceToBaseline(); } else if (child is RenderTextBox) { // Text baseline not depends on its own parent but its grand parents. - childBaseLineDistance = isLastLineBaseline - ? child.computeDistanceToLastLineBaseline() - : child.computeDistanceToFirstLineBaseline(); + childBaseLineDistance = + isLastLineBaseline ? child.computeDistanceToLastLineBaseline() : child.computeDistanceToFirstLineBaseline(); } if (childBaseLineDistance != null && childParentData != null) { // Baseline of relative positioned element equals its original position @@ -770,8 +738,7 @@ class RenderFlowLayout extends RenderLayoutBox { Offset? relativeOffset; double childOffsetY = childParentData.offset.dy - childMarginTop; if (child is RenderBoxModel) { - relativeOffset = - CSSPositionedLayout.getRelativeOffset(child.renderStyle); + relativeOffset = CSSPositionedLayout.getRelativeOffset(child.renderStyle); } if (relativeOffset != null) { childOffsetY -= relativeOffset.dy; @@ -917,8 +884,7 @@ class RenderFlowLayout extends RenderLayoutBox { CSSOverflowType overflowX = childRenderStyle.effectiveOverflowX; CSSOverflowType overflowY = childRenderStyle.effectiveOverflowY; // Only non scroll container need to use scrollable size, otherwise use its own size. - if (overflowX == CSSOverflowType.visible && - overflowY == CSSOverflowType.visible) { + if (overflowX == CSSOverflowType.visible && overflowY == CSSOverflowType.visible) { childScrollableSize = child.scrollableSize; } @@ -927,10 +893,8 @@ class RenderFlowLayout extends RenderLayoutBox { // https://www.w3.org/TR/css-overflow-3/#scrollable-overflow-region // Add offset of margin. - childOffsetX += childRenderStyle.marginLeft.computedValue - + childRenderStyle.marginRight.computedValue; - childOffsetY += _getChildMarginTop(child) - + _getChildMarginBottom(child); + childOffsetX += childRenderStyle.marginLeft.computedValue + childRenderStyle.marginRight.computedValue; + childOffsetY += _getChildMarginTop(child) + _getChildMarginBottom(child); // Add offset of position relative. // Offset of position absolute and fixed is added in layout stage of positioned renderBox. @@ -948,18 +912,15 @@ class RenderFlowLayout extends RenderLayoutBox { } } - scrollableMainSizeOfChildren.add( - preSiblingsMainSize + childScrollableSize.width + childOffsetX); - scrollableCrossSizeOfChildren - .add(childScrollableSize.height + childOffsetY); + scrollableMainSizeOfChildren.add(preSiblingsMainSize + childScrollableSize.width + childOffsetX); + scrollableCrossSizeOfChildren.add(childScrollableSize.height + childOffsetY); runChildrenList.add(child); } runChildren.forEach(iterateRunChildren); // Max scrollable main size of all the children in the line. - double maxScrollableMainSizeOfLine = - scrollableMainSizeOfChildren.reduce((double curr, double next) { + double maxScrollableMainSizeOfLine = scrollableMainSizeOfChildren.reduce((double curr, double next) { return curr > next ? curr : next; }); @@ -975,32 +936,28 @@ class RenderFlowLayout extends RenderLayoutBox { } // Max scrollable main size of all lines. - double maxScrollableMainSizeOfLines = - scrollableMainSizeOfLines.reduce((double curr, double next) { + double maxScrollableMainSizeOfLines = scrollableMainSizeOfLines.reduce((double curr, double next) { return curr > next ? curr : next; }); - RenderBoxModel container = - isScrollingContentBox ? parent as RenderBoxModel : this; - bool isScrollContainer = - renderStyle.effectiveOverflowX != CSSOverflowType.visible || + RenderBoxModel container = isScrollingContentBox ? parent as RenderBoxModel : this; + bool isScrollContainer = renderStyle.effectiveOverflowX != CSSOverflowType.visible || renderStyle.effectiveOverflowY != CSSOverflowType.visible; // Padding in the end direction of axis should be included in scroll container. - double maxScrollableMainSizeOfChildren = - maxScrollableMainSizeOfLines + renderStyle.paddingLeft.computedValue - + (isScrollContainer ? renderStyle.paddingRight.computedValue : 0); + double maxScrollableMainSizeOfChildren = maxScrollableMainSizeOfLines + + renderStyle.paddingLeft.computedValue + + (isScrollContainer ? renderStyle.paddingRight.computedValue : 0); // Max scrollable cross size of all lines. - double maxScrollableCrossSizeOfLines = - scrollableCrossSizeOfLines.reduce((double curr, double next) { + double maxScrollableCrossSizeOfLines = scrollableCrossSizeOfLines.reduce((double curr, double next) { return curr > next ? curr : next; }); // Padding in the end direction of axis should be included in scroll container. - double maxScrollableCrossSizeOfChildren = - maxScrollableCrossSizeOfLines + renderStyle.paddingTop.computedValue - + (isScrollContainer ? renderStyle.paddingBottom.computedValue : 0); + double maxScrollableCrossSizeOfChildren = maxScrollableCrossSizeOfLines + + renderStyle.paddingTop.computedValue + + (isScrollContainer ? renderStyle.paddingBottom.computedValue : 0); double maxScrollableMainSize = math.max( size.width - @@ -1019,8 +976,7 @@ class RenderFlowLayout extends RenderLayoutBox { // Get distance from top to baseline of child including margin. double _getChildAscent(RenderBox child) { // Distance from top to baseline of child. - double? childAscent = - child.getDistanceToBaseline(TextBaseline.alphabetic, onlyReal: true); + double? childAscent = child.getDistanceToBaseline(TextBaseline.alphabetic, onlyReal: true); double? childMarginTop = 0; double? childMarginBottom = 0; if (child is RenderBoxModel) { @@ -1060,8 +1016,8 @@ class RenderFlowLayout extends RenderLayoutBox { } else if (child is RenderBoxModel) { CSSDisplay? childDisplay = child.renderStyle.display; return childDisplay == CSSDisplay.inline || - childDisplay == CSSDisplay.inlineBlock || - childDisplay == CSSDisplay.inlineFlex; + childDisplay == CSSDisplay.inlineBlock || + childDisplay == CSSDisplay.inlineFlex; } return false; } @@ -1083,8 +1039,7 @@ class RenderFlowLayout extends RenderLayoutBox { RenderStyle? childRenderStyle = _getChildRenderStyle(child!); if (childRenderStyle != null) { CSSDisplay? childDisplay = childRenderStyle.display; - return childDisplay == CSSDisplay.block || - childDisplay == CSSDisplay.flex; + return childDisplay == CSSDisplay.block || childDisplay == CSSDisplay.flex; } } return false; @@ -1116,9 +1071,9 @@ class RenderRepaintBoundaryFlowLayout extends RenderFlowLayout { List? children, required CSSRenderStyle renderStyle, }) : super( - children: children, - renderStyle: renderStyle, - ); + children: children, + renderStyle: renderStyle, + ); @override bool get isRepaintBoundary => true; diff --git a/webf/lib/src/rendering/image.dart b/webf/lib/src/rendering/image.dart index ea8fb921d2..d0a41ce974 100644 --- a/webf/lib/src/rendering/image.dart +++ b/webf/lib/src/rendering/image.dart @@ -1,19 +1,20 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:ui' as ui show Image; import 'package:flutter/rendering.dart'; -class KrakenRenderImage extends RenderImage { - KrakenRenderImage({ +class WebFRenderImage extends RenderImage { + WebFRenderImage({ ui.Image? image, BoxFit? fit, AlignmentGeometry alignment = Alignment.center, }) : super( - image: image, - fit: fit, - alignment: alignment, - ); + image: image, + fit: fit, + alignment: alignment, + ); @override void performLayout() { @@ -21,5 +22,3 @@ class KrakenRenderImage extends RenderImage { size = trySize.isInfinite ? constraints.smallest : trySize; } } - - diff --git a/webf/lib/src/rendering/intersection_observer.dart b/webf/lib/src/rendering/intersection_observer.dart index 3add1f60db..252072600c 100644 --- a/webf/lib/src/rendering/intersection_observer.dart +++ b/webf/lib/src/rendering/intersection_observer.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; import 'dart:math' show max; @@ -19,8 +20,7 @@ Iterable _getLayerChain(Layer start) { return layerChain.reversed; } -typedef IntersectionChangeCallback = void Function( - IntersectionObserverEntry info); +typedef IntersectionChangeCallback = void Function(IntersectionObserverEntry info); mixin RenderIntersectionObserverMixin on RenderBox { IntersectionChangeCallback? _onIntersectionChange; @@ -76,8 +76,7 @@ mixin RenderIntersectionObserverMixin on RenderBox { } } - void paintIntersectionObserver(PaintingContext context, Offset offset, - PaintingContextCallback callback) { + void paintIntersectionObserver(PaintingContext context, Offset offset, PaintingContextCallback callback) { // Skip to next if not has intersection observer if (_onIntersectionChange == null) { callback(context, offset); @@ -85,11 +84,7 @@ mixin RenderIntersectionObserverMixin on RenderBox { } if (_intersectionObserverLayer.layer == null) { - _intersectionObserverLayer.layer = IntersectionObserverLayer( - elementSize: size, - paintOffset: offset, - onIntersectionChange: _onIntersectionChange! - ); + _intersectionObserverLayer.layer = IntersectionObserverLayer(elementSize: size, paintOffset: offset, onIntersectionChange: _onIntersectionChange!); } else { _intersectionObserverLayer.layer!.elementSize = semanticBounds.size; _intersectionObserverLayer.layer!.paintOffset = offset; @@ -100,10 +95,7 @@ mixin RenderIntersectionObserverMixin on RenderBox { } class IntersectionObserverLayer extends ContainerLayer { - IntersectionObserverLayer( - {required Size elementSize, - required Offset paintOffset, - required this.onIntersectionChange}) + IntersectionObserverLayer({required Size elementSize, required Offset paintOffset, required this.onIntersectionChange}) : // TODO: This is zero for box element. For sliver element, this offset points to the start of the element which may be outside the viewport. _elementOffset = Offset.zero, _elementSize = elementSize, @@ -238,8 +230,7 @@ class IntersectionObserverLayer extends ContainerLayer { // of `addPostFrameCallback` or `scheduleFrameCallback` so that work will // be done even if a new frame isn't scheduled and without unnecessarily // scheduling a new frame. - SchedulerBinding.instance! - .scheduleTask(_processCallbacks, Priority.touch); + SchedulerBinding.instance.scheduleTask(_processCallbacks, Priority.touch); } /// Computes the bounds for the corresponding element in @@ -252,8 +243,7 @@ class IntersectionObserverLayer extends ContainerLayer { // https://github.com/google/flutter.widgets/blob/master/packages/visibility_detector/lib/src/visibility_detector_layer.dart#L130 // Computes the accumulated clipping bounds, in global coordinates. Rect _computeClipRect() { - assert(RendererBinding.instance?.renderView != null); - var clipRect = Offset.zero & RendererBinding.instance!.renderView.size; + var clipRect = Offset.zero & RendererBinding.instance.renderView.size; var parentLayer = parent; while (parentLayer != null) { @@ -321,8 +311,7 @@ class IntersectionObserverLayer extends ContainerLayer { Rect elementBounds = layer._computeElementBounds(); Rect rootBounds = layer._computeClipRect(); - final info = IntersectionObserverEntry.fromRects( - boundingClientRect: elementBounds, rootBounds: rootBounds); + final info = IntersectionObserverEntry.fromRects(boundingClientRect: elementBounds, rootBounds: rootBounds); layer._fireCallback(info); } _updated.clear(); @@ -332,11 +321,7 @@ class IntersectionObserverLayer extends ContainerLayer { @immutable class IntersectionObserverEntry { - const IntersectionObserverEntry( - {Rect? boundingClientRect, - Rect? intersectionRect, - Rect? rootBounds, - Size? size}) + const IntersectionObserverEntry({Rect? boundingClientRect, Rect? intersectionRect, Rect? rootBounds, Size? size}) : boundingClientRect = boundingClientRect ?? Rect.zero, intersectionRect = intersectionRect ?? Rect.zero, rootBounds = rootBounds ?? Rect.zero, @@ -351,19 +336,10 @@ class IntersectionObserverEntry { required Rect boundingClientRect, required Rect rootBounds, }) { - // Compute the intersection in the element's local coordinates. - final intersectionRect = boundingClientRect.overlaps(rootBounds) - ? boundingClientRect - .intersect(rootBounds) - .shift(-boundingClientRect.topLeft) - : Rect.zero; - - return IntersectionObserverEntry( - boundingClientRect: boundingClientRect, - intersectionRect: intersectionRect, - rootBounds: rootBounds, - size: boundingClientRect.size); + final intersectionRect = boundingClientRect.overlaps(rootBounds) ? boundingClientRect.intersect(rootBounds).shift(-boundingClientRect.topLeft) : Rect.zero; + + return IntersectionObserverEntry(boundingClientRect: boundingClientRect, intersectionRect: intersectionRect, rootBounds: rootBounds, size: boundingClientRect.size); } // A Boolean value which is true if the target element intersects with the intersection observer's root. @@ -372,10 +348,8 @@ class IntersectionObserverEntry { bool get isIntersecting { if (size == Size.zero) return false; - if (boundingClientRect.right < rootBounds.left || - rootBounds.right < boundingClientRect.left) return false; - if (boundingClientRect.bottom < rootBounds.top || - rootBounds.bottom < boundingClientRect.top) return false; + if (boundingClientRect.right < rootBounds.left || rootBounds.right < boundingClientRect.left) return false; + if (boundingClientRect.bottom < rootBounds.top || rootBounds.bottom < boundingClientRect.top) return false; return true; } @@ -451,6 +425,5 @@ double _area(Size size) { /// Returns whether two floating-point values are approximately equal. bool _floatNear(double f1, double f2) { final absDiff = (f1 - f2).abs(); - return absDiff <= _kDefaultTolerance || - (absDiff / max(f1.abs(), f2.abs()) <= _kDefaultTolerance); + return absDiff <= _kDefaultTolerance || (absDiff / max(f1.abs(), f2.abs()) <= _kDefaultTolerance); } diff --git a/webf/lib/src/rendering/line_break.dart b/webf/lib/src/rendering/line_break.dart index 915120f891..86c98f4271 100644 --- a/webf/lib/src/rendering/line_break.dart +++ b/webf/lib/src/rendering/line_break.dart @@ -1,17 +1,18 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/rendering.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/rendering.dart'; +import 'package:webf/css.dart'; +import 'package:webf/rendering.dart'; class RenderLineBreak extends RenderReplaced { RenderLineBreak( CSSRenderStyle renderStyle, ) : super( - renderStyle, - ); + renderStyle, + ); TextPainter get textPainter { double fontSize = renderStyle.fontSize.computedValue; @@ -24,12 +25,11 @@ class RenderLineBreak extends RenderReplaced { locale: CSSText.getLocale(), ); TextPainter painter = TextPainter( - text: TextSpan( - text: ' ', - style: textStyle, - ), - textDirection: TextDirection.ltr - ); + text: TextSpan( + text: ' ', + style: textStyle, + ), + textDirection: TextDirection.ltr); painter.layout(); return painter; } @@ -52,7 +52,6 @@ class RenderLineBreak extends RenderReplaced { @override BoxConstraints getConstraints() { - // BR element is a special element in HTML which accepts no style, // it dimension is only affected by the line-height of its parent. // https://www.w3.org/TR/CSS1/#br-elements diff --git a/webf/lib/src/rendering/opacity.dart b/webf/lib/src/rendering/opacity.dart index 09337b49f2..d244ff7e44 100644 --- a/webf/lib/src/rendering/opacity.dart +++ b/webf/lib/src/rendering/opacity.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:ui' as ui; @@ -16,9 +17,7 @@ mixin RenderOpacityMixin on RenderBox { _opacityLayer.layer = null; } - void paintOpacity(PaintingContext context, Offset offset, - PaintingContextCallback callback) { - + void paintOpacity(PaintingContext context, Offset offset, PaintingContextCallback callback) { if (alpha == 255) { _opacityLayer.layer = null; // No need to keep the layer. We'll create a new one if necessary. @@ -26,12 +25,10 @@ mixin RenderOpacityMixin on RenderBox { return; } - _opacityLayer.layer = - context.pushOpacity(offset, alpha, callback, oldLayer: _opacityLayer.layer); + _opacityLayer.layer = context.pushOpacity(offset, alpha, callback, oldLayer: _opacityLayer.layer); } void debugOpacityProperties(DiagnosticPropertiesBuilder properties) { - if (alpha != 0 && alpha != 255) - properties.add(DiagnosticsProperty('alpha', alpha)); + if (alpha != 0 && alpha != 255) properties.add(DiagnosticsProperty('alpha', alpha)); } } diff --git a/webf/lib/src/rendering/overflow.dart b/webf/lib/src/rendering/overflow.dart index 46955ab622..0faefb6ad3 100644 --- a/webf/lib/src/rendering/overflow.dart +++ b/webf/lib/src/rendering/overflow.dart @@ -1,12 +1,13 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:math' as math; import 'package:flutter/rendering.dart'; -import 'package:kraken/rendering.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/gesture.dart'; +import 'package:webf/rendering.dart'; +import 'package:webf/css.dart'; +import 'package:webf/gesture.dart'; mixin RenderOverflowMixin on RenderBoxModelBase { ScrollListener? scrollListener; @@ -35,10 +36,7 @@ mixin RenderOverflowMixin on RenderBoxModelBase { // The content of replaced elements is always trimmed to the content edge curve. // https://www.w3.org/TR/css-backgrounds-3/#corner-clipping - if( borderRadius != null - && this is RenderReplaced - && renderStyle.aspectRatio != null - ) { + if (borderRadius != null && this is RenderReplaced && renderStyle.aspectRatio != null) { return true; } @@ -49,9 +47,7 @@ mixin RenderOverflowMixin on RenderBoxModelBase { Size scrollableSize = renderBoxModel.scrollableSize; Size scrollableViewportSize = renderBoxModel.scrollableViewportSize; // Border-radius always to clip inner content when overflow is not visible. - if (scrollableSize.width > scrollableViewportSize.width - || borderRadius != null - ) { + if (scrollableSize.width > scrollableViewportSize.width || borderRadius != null) { return true; } } @@ -72,10 +68,7 @@ mixin RenderOverflowMixin on RenderBoxModelBase { // The content of replaced elements is always trimmed to the content edge curve. // https://www.w3.org/TR/css-backgrounds-3/#corner-clipping - if( borderRadius != null - && this is RenderReplaced - && renderStyle.aspectRatio != null - ) { + if (borderRadius != null && this is RenderReplaced && renderStyle.aspectRatio != null) { return true; } @@ -86,9 +79,7 @@ mixin RenderOverflowMixin on RenderBoxModelBase { Size scrollableSize = renderBoxModel.scrollableSize; Size scrollableViewportSize = renderBoxModel.scrollableViewportSize; // Border-radius always to clip inner content when overflow is not visible. - if (scrollableSize.height > scrollableViewportSize.height - || borderRadius != null - ) { + if (scrollableSize.height > scrollableViewportSize.height || borderRadius != null) { return true; } } @@ -167,6 +158,7 @@ mixin RenderOverflowMixin on RenderBoxModelBase { if (_scrollOffsetX == null) return 0.0; return -_scrollOffsetX!.pixels; } + double get _paintOffsetY { if (_scrollOffsetY == null) return 0.0; return -_scrollOffsetY!.pixels; @@ -189,23 +181,19 @@ mixin RenderOverflowMixin on RenderBoxModelBase { final LayerHandle _clipRRectLayer = LayerHandle(); final LayerHandle _clipRectLayer = LayerHandle(); - void paintOverflow( - PaintingContext context, - Offset offset, - EdgeInsets borderEdge, - CSSBoxDecoration? decoration, - PaintingContextCallback callback - ) { + void paintOverflow(PaintingContext context, Offset offset, EdgeInsets borderEdge, CSSBoxDecoration? decoration, + PaintingContextCallback callback) { if (clipX == false && clipY == false) return callback(context, offset); final double paintOffsetX = _paintOffsetX; final double paintOffsetY = _paintOffsetY; final Offset paintOffset = Offset(paintOffsetX, paintOffsetY); // Overflow should not cover border. - Rect clipRect = Offset(borderEdge.left, borderEdge.top) & Size( - size.width - borderEdge.right - borderEdge.left, - size.height - borderEdge.bottom - borderEdge.top, - ); + Rect clipRect = Offset(borderEdge.left, borderEdge.top) & + Size( + size.width - borderEdge.right - borderEdge.left, + size.height - borderEdge.bottom - borderEdge.top, + ); if (_shouldClipAtPaintOffset(paintOffset, size)) { // ignore: prefer_function_declarations_over_variables PaintingContextCallback painter = (PaintingContext context, Offset offset) { @@ -226,9 +214,7 @@ mixin RenderOverflowMixin on RenderBoxModelBase { double? borderTop = renderStyle.borderTopWidth?.computedValue; // The content of overflow is trimmed to the padding edge curve. // https://www.w3.org/TR/css-backgrounds-3/#corner-clipping - RRect clipRRect = borderTop != null - ? borderRRect.deflate(borderTop) - : borderRRect; + RRect clipRRect = borderTop != null ? borderRRect.deflate(borderTop) : borderRRect; // The content of replaced elements is trimmed to the content edge curve. if (this is RenderReplaced) { @@ -236,9 +222,11 @@ mixin RenderOverflowMixin on RenderBoxModelBase { double paddingTop = renderStyle.paddingTop.computedValue; clipRRect = clipRRect.deflate(paddingTop); } - _clipRRectLayer.layer = context.pushClipRRect(_needsCompositing, offset, clipRect, clipRRect, painter, oldLayer: _clipRRectLayer.layer); + _clipRRectLayer.layer = context.pushClipRRect(_needsCompositing, offset, clipRect, clipRRect, painter, + oldLayer: _clipRRectLayer.layer); } else { - _clipRectLayer.layer = context.pushClipRect(_needsCompositing, offset, clipRect, painter, oldLayer: _clipRectLayer.layer); + _clipRectLayer.layer = + context.pushClipRect(_needsCompositing, offset, clipRect, painter, oldLayer: _clipRectLayer.layer); } } else { _clipRectLayer.layer = null; @@ -281,4 +269,3 @@ mixin RenderOverflowMixin on RenderBoxModelBase { properties.add(DiagnosticsProperty('clipY', clipY)); } } - diff --git a/webf/lib/src/rendering/paragraph.dart b/webf/lib/src/rendering/paragraph.dart index 5f95c238a3..2bbdbfd4c5 100644 --- a/webf/lib/src/rendering/paragraph.dart +++ b/webf/lib/src/rendering/paragraph.dart @@ -1,14 +1,9 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -import 'dart:ui' as ui - show - LineMetrics, - Gradient, - Shader, - TextBox, - TextHeightBehavior; +import 'dart:ui' as ui show LineMetrics, Gradient, Shader, TextBox, TextHeightBehavior; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; @@ -20,7 +15,7 @@ const String _kEllipsis = '\u2026'; /// Use multiple line text painters to controll the leading of font in paint stage /// A render object that displays a paragraph of text. /// W3C line-height spec: https://www.w3.org/TR/css-inline-3/#inline-height -class KrakenRenderParagraph extends RenderBox +class WebFRenderParagraph extends RenderBox with ContainerRenderObjectMixin, RenderBoxContainerDefaultsMixin, @@ -32,7 +27,7 @@ class KrakenRenderParagraph extends RenderBox /// /// The [maxLines] property may be null (and indeed defaults to null), but if /// it is not null, it must be greater than zero. - KrakenRenderParagraph( + WebFRenderParagraph( InlineSpan text, { TextAlign textAlign = TextAlign.start, required TextDirection textDirection, @@ -63,8 +58,7 @@ class KrakenRenderParagraph extends RenderBox @override void setupParentData(RenderBox child) { - if (child.parentData is! TextParentData) - child.parentData = TextParentData(); + if (child.parentData is! TextParentData) child.parentData = TextParentData(); } final TextPainter _textPainter; @@ -222,8 +216,7 @@ class KrakenRenderParagraph extends RenderBox } /// {@macro flutter.dart:ui.textHeightBehavior} - ui.TextHeightBehavior? get textHeightBehavior => - _textPainter.textHeightBehavior; + ui.TextHeightBehavior? get textHeightBehavior => _textPainter.textHeightBehavior; set textHeightBehavior(ui.TextHeightBehavior? value) { if (_textPainter.textHeightBehavior == value) return; @@ -231,6 +224,7 @@ class KrakenRenderParagraph extends RenderBox _overflowShader = null; markNeedsLayout(); } + /// Compute distance to baseline of first text line double computeDistanceToFirstLineBaseline() { double firstLineOffset = _lineOffset[0]; @@ -271,12 +265,9 @@ class KrakenRenderParagraph extends RenderBox position: position!, hitTest: (BoxHitTestResult result, Offset transformed) { assert(() { - final Offset manualPosition = - (position - textParentData.offset) / textParentData.scale!; - return (transformed.dx - manualPosition.dx).abs() < - precisionErrorTolerance && - (transformed.dy - manualPosition.dy).abs() < - precisionErrorTolerance; + final Offset manualPosition = (position - textParentData.offset) / textParentData.scale!; + return (transformed.dx - manualPosition.dx).abs() < precisionErrorTolerance && + (transformed.dy - manualPosition.dy).abs() < precisionErrorTolerance; }()); return child!.hitTest(result, position: transformed); }, @@ -336,8 +327,7 @@ class KrakenRenderParagraph extends RenderBox // Get text of each line in the paragraph. List _getLineTexts(TextPainter textPainter, TextSpan textSpan) { - TextSelection selection = - TextSelection(baseOffset: 0, extentOffset: textSpan.text!.length); + TextSelection selection = TextSelection(baseOffset: 0, extentOffset: textSpan.text!.length); List boxes = textPainter.getBoxesForSelection(selection); List lineTexts = []; int start = 0; @@ -356,9 +346,7 @@ class KrakenRenderParagraph extends RenderBox if (index == 0) continue; // Go one logical pixel within the box and get the position // of the character in the string. - end = textPainter - .getPositionForOffset(Offset(box.left + 1, box.top + 1)) - .offset; + end = textPainter.getPositionForOffset(Offset(box.left + 1, box.top + 1)).offset; // add the substring to the list of lines final line = textSpan.text!.substring(start, end); lineTexts.add(line); @@ -383,14 +371,10 @@ class KrakenRenderParagraph extends RenderBox ui.LineMetrics lineMetric = _lineMetrics[i]; // Do not add line height in the case of textOverflow ellipsis // cause height of line metric equals to 0. - double leading = lineHeight != null && lineMetric.height != 0 - ? lineHeight! - lineMetric.height - : 0; + double leading = lineHeight != null && lineMetric.height != 0 ? lineHeight! - lineMetric.height : 0; _lineLeading.add(leading); // Offset of previous line - double preLineBottom = i > 0 - ? _lineOffset[i - 1] + _lineMetrics[i - 1].height + _lineLeading[i - 1] / 2 - : 0; + double preLineBottom = i > 0 ? _lineOffset[i - 1] + _lineMetrics[i - 1].height + _lineLeading[i - 1] / 2 : 0; double offset = preLineBottom + leading / 2; _lineOffset.add(offset); } @@ -404,8 +388,7 @@ class KrakenRenderParagraph extends RenderBox ui.LineMetrics lineMetric = _lineMetrics[i]; // Do not add line height in the case of textOverflow ellipsis // cause height of line metric equals to 0. - double height = lineHeight != null && lineMetric.height != 0 ? - lineHeight! : lineMetric.height; + double height = lineHeight != null && lineMetric.height != 0 ? lineHeight! : lineMetric.height; paragraphHeight += height; } @@ -480,8 +463,7 @@ class KrakenRenderParagraph extends RenderBox size = constraints.constrain(paragraphSize); - final bool didOverflowHeight = - size.height < textSize.height || textDidExceedMaxLines; + final bool didOverflowHeight = size.height < textSize.height || textDidExceedMaxLines; final bool didOverflowWidth = size.width < textSize.width; // TODO(abarth): We're only measuring the sizes of the line boxes here. If* // the glyphs draw outside the line boxes, we might think that there isn't @@ -662,8 +644,7 @@ class KrakenRenderParagraph extends RenderBox super.describeSemanticsConfiguration(config); _semanticsInfo = text.getSemanticsInformation(); - if (_semanticsInfo!.any( - (InlineSpanSemanticsInformation info) => info.recognizer != null)) { + if (_semanticsInfo!.any((InlineSpanSemanticsInformation info) => info.recognizer != null)) { config.explicitChildNodes = true; config.isSemanticBoundary = true; } else { diff --git a/webf/lib/src/rendering/preferred_size.dart b/webf/lib/src/rendering/preferred_size.dart index ca96a6df3c..d0223eb7e3 100644 --- a/webf/lib/src/rendering/preferred_size.dart +++ b/webf/lib/src/rendering/preferred_size.dart @@ -1,10 +1,11 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; -import 'package:kraken/rendering.dart'; +import 'package:webf/rendering.dart'; /// [RenderPreferredSize] Render a box with preferred size, /// if no child provided, size is exactly what preferred size @@ -24,7 +25,7 @@ class RenderPreferredSize extends RenderProxyBox { if (_preferredSize == value) return; _preferredSize = value; - SchedulerBinding.instance!.addPostFrameCallback((_) { + SchedulerBinding.instance.addPostFrameCallback((_) { markNeedsLayout(); }); } @@ -38,8 +39,7 @@ class RenderPreferredSize extends RenderProxyBox { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty('preferredSize', _preferredSize, - missingIfNull: true)); + properties.add(DiagnosticsProperty('preferredSize', _preferredSize, missingIfNull: true)); } } @@ -74,8 +74,9 @@ class RenderPositionPlaceholder extends RenderPreferredSize { // Get the layout offset of renderObject to its ancestor which does not include the paint offset // such as scroll or transform. - Offset getOffsetToAncestor(Offset point, RenderObject ancestor, { bool excludeScrollOffset = false }) { - return MatrixUtils.transformPoint(getLayoutTransformTo(this, ancestor, excludeScrollOffset: excludeScrollOffset), point); + Offset getOffsetToAncestor(Offset point, RenderObject ancestor, {bool excludeScrollOffset = false}) { + return MatrixUtils.transformPoint( + getLayoutTransformTo(this, ancestor, excludeScrollOffset: excludeScrollOffset), point); } } diff --git a/webf/lib/src/rendering/replaced.dart b/webf/lib/src/rendering/replaced.dart index ed95923e63..e9fe4dd377 100644 --- a/webf/lib/src/rendering/replaced.dart +++ b/webf/lib/src/rendering/replaced.dart @@ -1,19 +1,19 @@ /* - * Copyright (C) 2020-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/module.dart'; -import 'package:kraken/rendering.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/module.dart'; +import 'package:webf/rendering.dart'; /// RenderBox of a replaced element whose content is outside the scope of the CSS formatting model, /// such as an image or embedded document. /// https://drafts.csswg.org/css-display/#replaced-element -class RenderReplaced extends RenderBoxModel - with RenderObjectWithChildMixin, RenderProxyBoxMixin { +class RenderReplaced extends RenderBoxModel with RenderObjectWithChildMixin, RenderProxyBoxMixin { RenderReplaced(CSSRenderStyle renderStyle) : super(renderStyle: renderStyle); @override @@ -45,8 +45,7 @@ class RenderReplaced extends RenderBoxModel if (child.parentData is! RenderLayoutParentData) { if (child is RenderBoxModel) { RenderLayoutParentData parentData = RenderLayoutParentData(); - child.parentData = - CSSPositionedLayout.getPositionParentData(child, parentData); + child.parentData = CSSPositionedLayout.getPositionParentData(child, parentData); } else { child.parentData = RenderLayoutParentData(); } @@ -57,8 +56,7 @@ class RenderReplaced extends RenderBoxModel void performLayout() { if (kProfileMode && PerformanceTiming.enabled()) { childLayoutDuration = 0; - PerformanceTiming.instance() - .mark(PERF_INTRINSIC_LAYOUT_START, uniqueId: hashCode); + PerformanceTiming.instance().mark(PERF_INTRINSIC_LAYOUT_START, uniqueId: hashCode); } beforeLayout(); @@ -73,8 +71,7 @@ class RenderReplaced extends RenderBoxModel if (kProfileMode && PerformanceTiming.enabled()) { DateTime childLayoutEnd = DateTime.now(); - childLayoutDuration += (childLayoutEnd.microsecondsSinceEpoch) - - childLayoutStart.microsecondsSinceEpoch; + childLayoutDuration += (childLayoutEnd.microsecondsSinceEpoch) - childLayoutStart.microsecondsSinceEpoch; } Size childSize = child!.size; @@ -91,8 +88,7 @@ class RenderReplaced extends RenderBoxModel } if (kProfileMode && PerformanceTiming.enabled()) { - PerformanceTiming.instance() - .mark(PERF_INTRINSIC_LAYOUT_END, uniqueId: hashCode); + PerformanceTiming.instance().mark(PERF_INTRINSIC_LAYOUT_END, uniqueId: hashCode); } } @@ -144,10 +140,10 @@ class RenderReplaced extends RenderBoxModel @override void performPaint(PaintingContext context, Offset offset) { - offset += Offset(renderStyle.paddingLeft.computedValue, renderStyle.paddingTop.computedValue); - offset += Offset(renderStyle.effectiveBorderLeftWidth.computedValue, renderStyle.effectiveBorderTopWidth.computedValue); + offset += + Offset(renderStyle.effectiveBorderLeftWidth.computedValue, renderStyle.effectiveBorderTopWidth.computedValue); if (child != null) { late DateTime childPaintStart; @@ -157,8 +153,7 @@ class RenderReplaced extends RenderBoxModel context.paintChild(child!, offset); if (kProfileMode && PerformanceTiming.enabled()) { DateTime childPaintEnd = DateTime.now(); - childPaintDuration += (childPaintEnd.microsecondsSinceEpoch - - childPaintStart.microsecondsSinceEpoch); + childPaintDuration += (childPaintEnd.microsecondsSinceEpoch - childPaintStart.microsecondsSinceEpoch); } } } diff --git a/webf/lib/src/rendering/sliver_list.dart b/webf/lib/src/rendering/sliver_list.dart index 4c6ab31193..90009fd3a2 100644 --- a/webf/lib/src/rendering/sliver_list.dart +++ b/webf/lib/src/rendering/sliver_list.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2020-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:ui'; @@ -7,11 +8,11 @@ import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/gesture.dart'; -import 'package:kraken/module.dart'; -import 'package:kraken/rendering.dart'; -import 'package:kraken/src/dom/sliver_manager.dart'; +import 'package:webf/css.dart'; +import 'package:webf/gesture.dart'; +import 'package:webf/module.dart'; +import 'package:webf/rendering.dart'; +import 'package:webf/src/dom/sliver_manager.dart'; class RenderSliverListLayout extends RenderLayoutBox { // Expose viewport for sliver mixin. @@ -23,7 +24,7 @@ class RenderSliverListLayout extends RenderLayoutBox { RenderSliverList? _renderSliverList; // The scrollable context to handle gestures. - late KrakenScrollable scrollable; + late WebFScrollable scrollable; // Called if scrolling pixel has moved. final ScrollListener? _scrollListener; @@ -38,10 +39,10 @@ class RenderSliverListLayout extends RenderLayoutBox { required CSSRenderStyle renderStyle, required RenderSliverElementChildManager manager, ScrollListener? onScroll, - }) : _renderSliverBoxChildManager = manager, - _scrollListener = onScroll, + }) : _renderSliverBoxChildManager = manager, + _scrollListener = onScroll, super(renderStyle: renderStyle) { - scrollable = KrakenScrollable(axisDirection: getAxisDirection(axis)); + scrollable = WebFScrollable(axisDirection: getAxisDirection(axis)); axis = renderStyle.sliverDirection; switch (axis) { @@ -87,7 +88,7 @@ class RenderSliverListLayout extends RenderLayoutBox { void addAll(List? children) {} // Insert render box child as sliver child. - void insertSliverChild(RenderBox child, { RenderBox? after }) { + void insertSliverChild(RenderBox child, {RenderBox? after}) { setupParentData(child); _renderSliverList?.insert(child, after: after); } @@ -115,7 +116,7 @@ class RenderSliverListLayout extends RenderLayoutBox { @override void setupParentData(RenderBox child) { - if (child == _renderViewport && child.parentData is ! RenderLayoutParentData) { + if (child == _renderViewport && child.parentData is! RenderLayoutParentData) { child.parentData = RenderLayoutParentData(); } else if (child.parentData is! SliverMultiBoxAdaptorParentData) { child.parentData = SliverMultiBoxAdaptorParentData(); @@ -154,8 +155,7 @@ class RenderSliverListLayout extends RenderLayoutBox { doingThisLayout = true; if (kProfileMode && PerformanceTiming.enabled()) { childLayoutDuration = 0; - PerformanceTiming.instance() - .mark(PERF_SILVER_LAYOUT_START, uniqueId: hashCode); + PerformanceTiming.instance().mark(PERF_SILVER_LAYOUT_START, uniqueId: hashCode); } beforeLayout(); @@ -194,8 +194,7 @@ class RenderSliverListLayout extends RenderLayoutBox { if (kProfileMode && PerformanceTiming.enabled()) { DateTime childLayoutEnd = DateTime.now(); - childLayoutDuration += (childLayoutEnd.microsecondsSinceEpoch - - childLayoutStart.microsecondsSinceEpoch); + childLayoutDuration += (childLayoutEnd.microsecondsSinceEpoch - childLayoutStart.microsecondsSinceEpoch); } size = getBoxSize(child.size); @@ -204,19 +203,17 @@ class RenderSliverListLayout extends RenderLayoutBox { if (kProfileMode && PerformanceTiming.enabled()) { PerformanceTiming.instance().mark(PERF_SILVER_LAYOUT_END, - uniqueId: hashCode, - startTime: - DateTime.now().microsecondsSinceEpoch - childLayoutDuration); + uniqueId: hashCode, startTime: DateTime.now().microsecondsSinceEpoch - childLayoutDuration); } doingThisLayout = false; } @override void performPaint(PaintingContext context, Offset offset) { - offset += Offset(renderStyle.paddingLeft.computedValue, renderStyle.paddingTop.computedValue); - offset += Offset(renderStyle.effectiveBorderLeftWidth.computedValue, renderStyle.effectiveBorderTopWidth.computedValue); + offset += + Offset(renderStyle.effectiveBorderLeftWidth.computedValue, renderStyle.effectiveBorderTopWidth.computedValue); if (firstChild != null) { late DateTime childPaintStart; @@ -226,14 +223,13 @@ class RenderSliverListLayout extends RenderLayoutBox { context.paintChild(firstChild!, offset); if (kProfileMode && PerformanceTiming.enabled()) { DateTime childPaintEnd = DateTime.now(); - childPaintDuration += (childPaintEnd.microsecondsSinceEpoch - - childPaintStart.microsecondsSinceEpoch); + childPaintDuration += (childPaintEnd.microsecondsSinceEpoch - childPaintStart.microsecondsSinceEpoch); } } } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { // The x, y parameters have the top left of the node's box as the origin. // Get the sliver content scrolling offset. final Offset currentOffset = Offset(scrollLeft, scrollTop); @@ -258,7 +254,6 @@ class RenderSliverListLayout extends RenderLayoutBox { return false; } - @override void applyPaintTransform(RenderBox child, Matrix4 transform) { super.applyPaintTransform(child, transform); @@ -266,15 +261,10 @@ class RenderSliverListLayout extends RenderLayoutBox { } Offset getChildScrollOffset(RenderObject child, Offset offset) { - final RenderLayoutParentData? childParentData = - child.parentData as RenderLayoutParentData?; - bool isChildFixed = child is RenderBoxModel - ? child.renderStyle.position == CSSPositionType.fixed - : false; + final RenderLayoutParentData? childParentData = child.parentData as RenderLayoutParentData?; + bool isChildFixed = child is RenderBoxModel ? child.renderStyle.position == CSSPositionType.fixed : false; // Fixed elements always paint original offset - Offset scrollOffset = isChildFixed - ? childParentData!.offset - : childParentData!.offset + offset; + Offset scrollOffset = isChildFixed ? childParentData!.offset : childParentData!.offset + offset; return scrollOffset; } diff --git a/webf/lib/src/rendering/text.dart b/webf/lib/src/rendering/text.dart index fa6669005d..65eb1d8922 100644 --- a/webf/lib/src/rendering/text.dart +++ b/webf/lib/src/rendering/text.dart @@ -1,11 +1,12 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/rendering.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/rendering.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/rendering.dart'; // White space processing in CSS affects only the document white space characters: // spaces (U+0020), tabs (U+0009), and segment breaks. @@ -20,13 +21,13 @@ class TextParentData extends ContainerBoxParentData {} enum WhiteSpace { normal, nowrap, pre, preWrap, preLine, breakSpaces } -class RenderTextBox extends RenderBox - with RenderObjectWithChildMixin { - RenderTextBox(data, { +class RenderTextBox extends RenderBox with RenderObjectWithChildMixin { + RenderTextBox( + data, { required this.renderStyle, }) : _data = data { TextSpan text = CSSTextMixin.createTextSpan(_data, renderStyle); - _renderParagraph = child = KrakenRenderParagraph( + _renderParagraph = child = WebFRenderParagraph( text, textDirection: TextDirection.ltr, ); @@ -41,7 +42,10 @@ class RenderTextBox extends RenderBox String get data => _data; bool isEndWithSpace(String str) { - return str.endsWith(WHITE_SPACE_CHAR) || str.endsWith(NEW_LINE_CHAR) || str.endsWith(RETURN_CHAR) || str.endsWith(TAB_CHAR); + return str.endsWith(WHITE_SPACE_CHAR) || + str.endsWith(NEW_LINE_CHAR) || + str.endsWith(RETURN_CHAR) || + str.endsWith(TAB_CHAR); } String get _trimmedData { @@ -74,7 +78,9 @@ class RenderTextBox extends RenderBox if (previousSibling == null) { collapsedData = _trimLeftWhitespace(collapsedData); - } else if (previousSibling is RenderBoxModel &&(previousSibling.renderStyle.display == CSSDisplay.block || previousSibling.renderStyle.display == CSSDisplay.flex)) { + } else if (previousSibling is RenderBoxModel && + (previousSibling.renderStyle.display == CSSDisplay.block || + previousSibling.renderStyle.display == CSSDisplay.flex)) { // If previousSibling is block,should trimLeft slef. CSSDisplay? display = previousSibling.renderStyle.display; if (display == CSSDisplay.block || display == CSSDisplay.sliver || display == CSSDisplay.flex) { @@ -87,7 +93,9 @@ class RenderTextBox extends RenderBox RenderObject? nextSibling = (parentData as RenderLayoutParentData).nextSibling; if (nextSibling == null) { collapsedData = _trimRightWhitespace(collapsedData); - } else if (nextSibling is RenderBoxModel && (nextSibling.renderStyle.display == CSSDisplay.block || nextSibling.renderStyle.display == CSSDisplay.flex)) { + } else if (nextSibling is RenderBoxModel && + (nextSibling.renderStyle.display == CSSDisplay.block || + nextSibling.renderStyle.display == CSSDisplay.flex)) { // If nextSibling is block,should trimRight slef. CSSDisplay? display = nextSibling.renderStyle.display; if (display == CSSDisplay.block || display == CSSDisplay.sliver || display == CSSDisplay.flex) { @@ -102,7 +110,7 @@ class RenderTextBox extends RenderBox return _data; } - late KrakenRenderParagraph _renderParagraph; + late WebFRenderParagraph _renderParagraph; CSSRenderStyle renderStyle; BoxSizeType? widthSizeType; @@ -181,8 +189,7 @@ class RenderTextBox extends RenderBox } BoxConstraints getConstraints() { - if (renderStyle.whiteSpace == WhiteSpace.nowrap && - renderStyle.effectiveTextOverflow != TextOverflow.ellipsis) { + if (renderStyle.whiteSpace == WhiteSpace.nowrap && renderStyle.effectiveTextOverflow != TextOverflow.ellipsis) { return BoxConstraints(); } @@ -221,11 +228,7 @@ class RenderTextBox extends RenderBox // Text will not overflow from container, so it can inherit // constraints from parents - return BoxConstraints( - minWidth: 0, - maxWidth: maxConstraintWidth, - minHeight: 0, - maxHeight: double.infinity); + return BoxConstraints(minWidth: 0, maxWidth: maxConstraintWidth, minHeight: 0, maxHeight: double.infinity); } // Empty string is the minimum size character, use it as the base size @@ -239,12 +242,11 @@ class RenderTextBox extends RenderBox locale: CSSText.getLocale(), ); TextPainter painter = TextPainter( - text: TextSpan( - text: ' ', - style: textStyle, - ), - textDirection: TextDirection.ltr - ); + text: TextSpan( + text: ' ', + style: textStyle, + ), + textDirection: TextDirection.ltr); painter.layout(); return painter.size; } @@ -264,10 +266,8 @@ class RenderTextBox extends RenderBox // white-space is nowrap and overflow is hidden/clip. CSSOverflowType effectiveOverflowX = renderStyle.effectiveOverflowX; - if (parentContentConstraints != null - && (effectiveOverflowX == CSSOverflowType.hidden - || effectiveOverflowX == CSSOverflowType.clip) - ) { + if (parentContentConstraints != null && + (effectiveOverflowX == CSSOverflowType.hidden || effectiveOverflowX == CSSOverflowType.clip)) { // Max character to display in one line. int? maxCharsOfLine; // Max lines in parent. @@ -316,7 +316,7 @@ class RenderTextBox extends RenderBox @override void performLayout() { - KrakenRenderParagraph? paragraph = child as KrakenRenderParagraph?; + WebFRenderParagraph? paragraph = child as WebFRenderParagraph?; if (paragraph != null) { paragraph.overflow = renderStyle.effectiveTextOverflow; paragraph.textAlign = renderStyle.textAlign; diff --git a/webf/lib/src/rendering/text_control.dart b/webf/lib/src/rendering/text_control.dart index de6cc69105..7d554f46eb 100644 --- a/webf/lib/src/rendering/text_control.dart +++ b/webf/lib/src/rendering/text_control.dart @@ -1,14 +1,16 @@ /* - * Copyright (C) 2020-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:math' as math; + import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; -import 'package:kraken/gesture.dart'; -import 'package:kraken/rendering.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; +import 'package:webf/gesture.dart'; +import 'package:webf/rendering.dart'; /// RenderLeaderLayer of [TextFormControlElement] used for toolbar overlay /// which includes [Cut], [Copy], [Paste], [Select All] shortcuts to float with. @@ -20,7 +22,7 @@ class RenderTextControlLeaderLayer extends RenderLeaderLayer { this.isMultiline = false, }) : super(link: link, child: child); - KrakenScrollable scrollable; + WebFScrollable scrollable; bool isMultiline; @@ -48,9 +50,11 @@ class RenderTextControlLeaderLayer extends RenderLeaderLayer { RenderReplaced renderReplaced = parent as RenderReplaced; RenderStyle renderStyle = renderReplaced.renderStyle; - double intrinsicHeight = (child as RenderEditable).preferredLineHeight - + renderStyle.paddingTop.computedValue + renderStyle.paddingBottom.computedValue - + renderStyle.effectiveBorderTopWidth.computedValue + renderStyle.effectiveBorderBottomWidth.computedValue; + double intrinsicHeight = (child as RenderEditable).preferredLineHeight + + renderStyle.paddingTop.computedValue + + renderStyle.paddingBottom.computedValue + + renderStyle.effectiveBorderTopWidth.computedValue + + renderStyle.effectiveBorderBottomWidth.computedValue; // Editable area should align to the center vertically for text control element which // does not support multiline editing. @@ -58,8 +62,8 @@ class RenderTextControlLeaderLayer extends RenderLeaderLayer { if (renderStyle.height.isNotAuto) { dy = (renderStyle.height.computedValue - intrinsicHeight) / 2; } else if (renderStyle.lineHeight.type != CSSLengthType.NORMAL && - renderStyle.lineHeight.computedValue > intrinsicHeight) { - dy = (renderStyle.lineHeight.computedValue - intrinsicHeight) /2; + renderStyle.lineHeight.computedValue > intrinsicHeight) { + dy = (renderStyle.lineHeight.computedValue - intrinsicHeight) / 2; } else { dy = 0; } @@ -88,7 +92,7 @@ class RenderTextControlLeaderLayer extends RenderLeaderLayer { // Height priority: height > max(line-height, child height) > child height if (constraints.maxHeight != double.infinity) { height = constraints.maxHeight; - } else { + } else { height = math.max(renderStyle.lineHeight.computedValue, childSize.height); } diff --git a/webf/lib/src/rendering/transform.dart b/webf/lib/src/rendering/transform.dart index 1b8f026510..4a9eb1d46a 100644 --- a/webf/lib/src/rendering/transform.dart +++ b/webf/lib/src/rendering/transform.dart @@ -1,8 +1,9 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/rendering.dart'; -import 'package:kraken/rendering.dart'; +import 'package:webf/rendering.dart'; mixin RenderTransformMixin on RenderBoxModelBase { final LayerHandle _transformLayer = LayerHandle(); @@ -11,8 +12,7 @@ mixin RenderTransformMixin on RenderBoxModelBase { _transformLayer.layer = null; } - void paintTransform(PaintingContext context, Offset offset, - PaintingContextCallback callback) { + void paintTransform(PaintingContext context, Offset offset, PaintingContextCallback callback) { if (renderStyle.transformMatrix != null) { final Matrix4 transform = renderStyle.effectiveTransformMatrix; final Offset? childOffset = MatrixUtils.getAsTranslation(transform); @@ -39,11 +39,9 @@ mixin RenderTransformMixin on RenderBoxModelBase { } } - bool hitTestLayoutChildren( - BoxHitTestResult result, RenderBox? child, Offset position) { + bool hitTestLayoutChildren(BoxHitTestResult result, RenderBox? child, Offset position) { while (child != null) { - final RenderLayoutParentData? childParentData = - child.parentData as RenderLayoutParentData?; + final RenderLayoutParentData? childParentData = child.parentData as RenderLayoutParentData?; final bool isHit = result.addWithPaintTransform( transform: renderStyle.effectiveTransformMatrix, position: position, @@ -64,8 +62,7 @@ mixin RenderTransformMixin on RenderBoxModelBase { return false; } - bool hitTestIntrinsicChild( - BoxHitTestResult result, RenderBox? child, Offset position) { + bool hitTestIntrinsicChild(BoxHitTestResult result, RenderBox? child, Offset position) { final bool isHit = result.addWithPaintTransform( transform: renderStyle.effectiveTransformMatrix, position: position, @@ -81,7 +78,6 @@ mixin RenderTransformMixin on RenderBoxModelBase { Offset transformOffset = renderStyle.transformOffset; Alignment transformAlignment = renderStyle.transformAlignment; properties.add(DiagnosticsProperty('transformOrigin', transformOffset)); - properties - .add(DiagnosticsProperty('transformAlignment', transformAlignment)); + properties.add(DiagnosticsProperty('transformAlignment', transformAlignment)); } } diff --git a/webf/lib/src/rendering/viewport.dart b/webf/lib/src/rendering/viewport.dart index 3bdae36001..6a7820ac1f 100644 --- a/webf/lib/src/rendering/viewport.dart +++ b/webf/lib/src/rendering/viewport.dart @@ -1,18 +1,18 @@ /* - * Copyright (C) 2020-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/rendering.dart'; -import 'package:kraken/launcher.dart'; -import 'package:kraken/rendering.dart'; +import 'package:webf/launcher.dart'; +import 'package:webf/rendering.dart'; -class RenderViewportBox extends RenderProxyBox - with RenderObjectWithControllerMixin, RenderEventListenerMixin { +class RenderViewportBox extends RenderProxyBox with RenderObjectWithControllerMixin, RenderEventListenerMixin { RenderViewportBox({ required Size viewportSize, RenderBox? child, this.background, - required KrakenController controller, - }) : _viewportSize = viewportSize, + required WebFController controller, + }) : _viewportSize = viewportSize, super(child) { this.controller = controller; } diff --git a/webf/lib/src/scheduler/fps.dart b/webf/lib/src/scheduler/fps.dart index 480266d831..f29039c84a 100644 --- a/webf/lib/src/scheduler/fps.dart +++ b/webf/lib/src/scheduler/fps.dart @@ -1,12 +1,13 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:ui'; import 'package:flutter/rendering.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart'; /// Fps callback. typedef FpsCallback = void Function(List fps); diff --git a/webf/lib/src/scheduler/throttle.dart b/webf/lib/src/scheduler/throttle.dart index 727b8b5466..a92f1623c2 100644 --- a/webf/lib/src/scheduler/throttle.dart +++ b/webf/lib/src/scheduler/throttle.dart @@ -1,5 +1,6 @@ /* - * Copyright (C) 2021-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'dart:async'; diff --git a/webf/lib/src/widget/element_to_widget_adaptor.dart b/webf/lib/src/widget/element_to_widget_adaptor.dart index 378dfb292c..bdb672b5be 100644 --- a/webf/lib/src/widget/element_to_widget_adaptor.dart +++ b/webf/lib/src/widget/element_to_widget_adaptor.dart @@ -1,54 +1,55 @@ /* - * Copyright (C) 2022-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/widgets.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/dom.dart' as dom; -import 'package:kraken/rendering.dart'; +import 'package:webf/css.dart'; +import 'package:webf/dom.dart' as dom; +import 'package:webf/rendering.dart'; -class KrakenElementToWidgetAdaptor extends RenderObjectWidget { - final dom.Node _krakenNode; +class WebFElementToWidgetAdaptor extends RenderObjectWidget { + final dom.Node _webFNode; - KrakenElementToWidgetAdaptor(this._krakenNode, { Key? key }): super(key: key) { - _krakenNode.flutterWidget = this; + WebFElementToWidgetAdaptor(this._webFNode, {Key? key}) : super(key: key) { + _webFNode.flutterWidget = this; } @override RenderObjectElement createElement() { - _krakenNode.flutterElement = KrakenElementToFlutterElementAdaptor(this); - return _krakenNode.flutterElement as RenderObjectElement; + _webFNode.flutterElement = WebFElementToFlutterElementAdaptor(this); + return _webFNode.flutterElement as RenderObjectElement; } @override RenderObject createRenderObject(BuildContext context) { // Children of custom element need RenderFlowLayout nesting, // otherwise the parent render layout will not be called when setting properties. - if (_krakenNode is dom.Element) { - CSSRenderStyle renderStyle = CSSRenderStyle(target: _krakenNode as dom.Element); + if (_webFNode is dom.Element) { + CSSRenderStyle renderStyle = CSSRenderStyle(target: _webFNode as dom.Element); RenderFlowLayout renderFlowLayout = RenderFlowLayout(renderStyle: renderStyle); - renderFlowLayout.insert(_krakenNode.renderer!); + renderFlowLayout.insert(_webFNode.renderer!); return renderFlowLayout; } else { - return _krakenNode.renderer!; + return _webFNode.renderer!; } } } -class KrakenElementToFlutterElementAdaptor extends RenderObjectElement { - KrakenElementToFlutterElementAdaptor(RenderObjectWidget widget) : super(widget); +class WebFElementToFlutterElementAdaptor extends RenderObjectElement { + WebFElementToFlutterElementAdaptor(RenderObjectWidget widget) : super(widget); @override - KrakenElementToWidgetAdaptor get widget => super.widget as KrakenElementToWidgetAdaptor; + WebFElementToWidgetAdaptor get widget => super.widget as WebFElementToWidgetAdaptor; @override void mount(Element? parent, Object? newSlot) { - widget._krakenNode.createRenderer(); + widget._webFNode.createRenderer(); super.mount(parent, newSlot); - widget._krakenNode.ensureChildAttached(); + widget._webFNode.ensureChildAttached(); - if (widget._krakenNode is dom.Element) { - dom.Element element = (widget._krakenNode as dom.Element); + if (widget._webFNode is dom.Element) { + dom.Element element = (widget._webFNode as dom.Element); element.applyStyle(element.style); if (element.renderer != null) { @@ -61,8 +62,11 @@ class KrakenElementToFlutterElementAdaptor extends RenderObjectElement { @override void unmount() { // Flutter element unmount call dispose of _renderObject, so we should not call dispose in unmountRenderObject. - dom.Element element = (widget._krakenNode as dom.Element); - element.unmountRenderObject(dispose: false); + dom.Node node = widget._webFNode; + + if (node is dom.Element) { + node.unmountRenderObject(dispose: false); + } super.unmount(); } diff --git a/webf/lib/src/widget/kraken.dart b/webf/lib/src/widget/kraken.dart deleted file mode 100644 index 03948fcbe6..0000000000 --- a/webf/lib/src/widget/kraken.dart +++ /dev/null @@ -1,305 +0,0 @@ -/* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. - */ -import 'dart:io'; -import 'dart:ui'; - -import 'package:flutter/foundation.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/rendering.dart'; -import 'package:kraken/kraken.dart'; -import 'package:kraken/gesture.dart'; -import 'package:kraken/css.dart'; -import 'package:kraken/src/dom/element_registry.dart'; - -class Kraken extends StatefulWidget { - // The background color for viewport, default to transparent. - final Color? background; - - // the width of krakenWidget - final double? viewportWidth; - - // the height of krakenWidget - final double? viewportHeight; - - // The initial bundle to load. - final KrakenBundle? bundle; - - // The animationController of Flutter Route object. - // Pass this object to KrakenWidget to make sure Kraken execute JavaScripts scripts after route transition animation completed. - final AnimationController? animationController; - - // The methods of the KrakenNavigateDelegation help you implement custom behaviors that are triggered - // during a kraken view's process of loading, and completing a navigation request. - final KrakenNavigationDelegate? navigationDelegate; - - // A method channel for receiving messaged from JavaScript code and sending message to JavaScript. - final KrakenMethodChannel? javaScriptChannel; - - // Register the RouteObserver to observer page navigation. - // This is useful if you wants to pause kraken timers and callbacks when kraken widget are hidden by page route. - // https://api.flutter.dev/flutter/widgets/RouteObserver-class.html - final RouteObserver>? routeObserver; - - // Trigger when kraken controller once created. - final OnControllerCreated? onControllerCreated; - - final LoadErrorHandler? onLoadError; - - final LoadHandler? onLoad; - - final JSErrorHandler ?onJSError; - - // Open a service to support Chrome DevTools for debugging. - // https://github.com/openkraken/devtools - final DevToolsService? devToolsService; - - final GestureListener? gestureListener; - - final HttpClientInterceptor? httpClientInterceptor; - - final UriParser? uriParser; - - KrakenController? get controller { - return KrakenController.getControllerOfName(shortHash(this)); - } - - // Set kraken http cache mode. - static void setHttpCacheMode(HttpCacheMode mode) { - HttpCacheController.mode = mode; - if (kDebugMode) { - print('Kraken http cache mode set to $mode.'); - } - } - - static bool _isValidCustomElementName(localName) { - return RegExp(r'^[a-z][.0-9_a-z]*-[\-.0-9_a-z]*$').hasMatch(localName); - } - - static void defineCustomElement(String tagName, ElementCreator creator) { - if (!_isValidCustomElementName(tagName)) { - throw ArgumentError('The element name "$tagName" is not valid.'); - } - defineElement(tagName.toUpperCase(), creator); - } - - Future load(KrakenBundle bundle) async { - await controller?.load(bundle); - } - - Future reload() async { - await controller?.reload(); - } - - Kraken({ - Key? key, - this.viewportWidth, - this.viewportHeight, - this.bundle, - this.onControllerCreated, - this.onLoad, - this.navigationDelegate, - this.javaScriptChannel, - this.background, - this.gestureListener, - this.devToolsService, - // Kraken's http client interceptor. - this.httpClientInterceptor, - this.uriParser, - this.routeObserver, - // Kraken's viewportWidth options only works fine when viewportWidth is equal to window.physicalSize.width / window.devicePixelRatio. - // Maybe got unexpected error when change to other values, use this at your own risk! - // We will fixed this on next version released. (v0.6.0) - // Disable viewportWidth check and no assertion error report. - bool disableViewportWidthAssertion = false, - // Kraken's viewportHeight options only works fine when viewportHeight is equal to window.physicalSize.height / window.devicePixelRatio. - // Maybe got unexpected error when change to other values, use this at your own risk! - // We will fixed this on next version release. (v0.6.0) - // Disable viewportHeight check and no assertion error report. - bool disableViewportHeightAssertion = false, - // Callback functions when loading Javascript scripts failed. - this.onLoadError, - this.animationController, - this.onJSError - }) : super(key: key); - - @override - void debugFillProperties(DiagnosticPropertiesBuilder properties) { - super.debugFillProperties(properties); - properties.add(DiagnosticsProperty('viewportWidth', viewportWidth)); - properties.add(DiagnosticsProperty('viewportHeight', viewportHeight)); - } - - @override - _KrakenState createState() => _KrakenState(); -} - -class _KrakenState extends State with RouteAware { - @override - Widget build(BuildContext context) { - return KrakenTextControl(context); - } - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - if (widget.routeObserver != null) { - widget.routeObserver!.subscribe(this, ModalRoute.of(context)!); - } - } - - // Resume call timer and callbacks when kraken widget change to visible. - @override - void didPopNext() { - assert(widget.controller != null); - widget.controller!.resume(); - } - - // Pause all timer and callbacks when kraken widget has been invisible. - @override - void didPushNext() { - assert(widget.controller != null); - widget.controller!.pause(); - } - - @override - void dispose() { - if (widget.routeObserver != null) { - widget.routeObserver!.unsubscribe(this); - } - super.dispose(); - } - - @override - void deactivate() { - // Deactivate all WidgetElements in Kraken when Kraken Widget is deactivated. - widget.controller!.view.deactivateWidgetElements(); - - super.deactivate(); - } -} - -class KrakenRenderObjectWidget extends SingleChildRenderObjectWidget { - // Creates a widget that visually hides its child. - const KrakenRenderObjectWidget( - Kraken widget, - WidgetDelegate widgetDelegate, - {Key? key} - ) : _krakenWidget = widget, - _widgetDelegate = widgetDelegate, - super(key: key); - - final Kraken _krakenWidget; - final WidgetDelegate _widgetDelegate; - - @override - RenderObject createRenderObject(BuildContext context) { - if (kProfileMode) { - PerformanceTiming.instance().mark(PERF_CONTROLLER_INIT_START); - } - - double viewportWidth = _krakenWidget.viewportWidth ?? window.physicalSize.width / window.devicePixelRatio; - double viewportHeight = _krakenWidget.viewportHeight ?? window.physicalSize.height / window.devicePixelRatio; - - if (viewportWidth == 0.0 && viewportHeight == 0.0) { - throw FlutterError('''Can't get viewportSize from window. Please set viewportWidth and viewportHeight manually. -This situation often happened when you trying creating kraken when FlutterView not initialized.'''); - } - - KrakenController controller = KrakenController( - shortHash(_krakenWidget.hashCode), - viewportWidth, - viewportHeight, - background: _krakenWidget.background, - showPerformanceOverlay: Platform.environment[ENABLE_PERFORMANCE_OVERLAY] != null, - entrypoint: _krakenWidget.bundle, - // Execute entrypoint when mount manually. - autoExecuteEntrypoint: false, - onLoad: _krakenWidget.onLoad, - onLoadError: _krakenWidget.onLoadError, - onJSError: _krakenWidget.onJSError, - methodChannel: _krakenWidget.javaScriptChannel, - gestureListener: _krakenWidget.gestureListener, - navigationDelegate: _krakenWidget.navigationDelegate, - devToolsService: _krakenWidget.devToolsService, - httpClientInterceptor: _krakenWidget.httpClientInterceptor, - widgetDelegate: _widgetDelegate, - uriParser: _krakenWidget.uriParser - ); - - OnControllerCreated? onControllerCreated = _krakenWidget.onControllerCreated; - if (onControllerCreated != null) { - onControllerCreated(controller); - } - - if (kProfileMode) { - PerformanceTiming.instance().mark(PERF_CONTROLLER_INIT_END); - } - - return controller.view.getRootRenderObject(); - } - - @override - void updateRenderObject(BuildContext context, covariant RenderObject renderObject) { - super.updateRenderObject(context, renderObject); - KrakenController controller = (renderObject as RenderObjectWithControllerMixin).controller!; - controller.name = shortHash(_krakenWidget.hashCode); - - bool viewportWidthHasChanged = controller.view.viewportWidth != _krakenWidget.viewportWidth; - bool viewportHeightHasChanged = controller.view.viewportHeight != _krakenWidget.viewportHeight; - - double viewportWidth = _krakenWidget.viewportWidth ?? window.physicalSize.width / window.devicePixelRatio; - double viewportHeight = _krakenWidget.viewportHeight ?? window.physicalSize.height / window.devicePixelRatio; - - if (controller.view.document.documentElement == null) return; - - if (viewportWidthHasChanged) { - controller.view.viewportWidth = viewportWidth; - controller.view.document.documentElement!.renderStyle.width = CSSLengthValue(viewportWidth, CSSLengthType.PX); - } - - if (viewportHeightHasChanged) { - controller.view.viewportHeight = viewportHeight; - controller.view.document.documentElement!.renderStyle.height = CSSLengthValue(viewportHeight, CSSLengthType.PX); - } - } - - @override - void didUnmountRenderObject(covariant RenderObject renderObject) { - KrakenController controller = (renderObject as RenderObjectWithControllerMixin).controller!; - controller.dispose(); - } - - @override - _KrakenRenderObjectElement createElement() { - return _KrakenRenderObjectElement(this); - } -} - -class _KrakenRenderObjectElement extends SingleChildRenderObjectElement { - _KrakenRenderObjectElement(KrakenRenderObjectWidget widget) : super(widget); - - @override - void mount(Element? parent, Object? newSlot) async { - super.mount(parent, newSlot); - - KrakenController controller = (renderObject as RenderObjectWithControllerMixin).controller!; - - // We should make sure every flutter elements created under kraken can be walk up to the root. - // So we bind _KrakenRenderObjectElement into KrakenController, and widgetElements created by controller can follow this to the root. - controller.rootFlutterElement = this; - await controller.executeEntrypoint(animationController: widget._krakenWidget.animationController); - } - - // RenderObjects created by kraken are manager by kraken itself. There are no needs to operate renderObjects on _KrakenRenderObjectElement. - @override - void insertRenderObjectChild(RenderObject child, Object? slot) {} - @override - void moveRenderObjectChild(RenderObject child, Object? oldSlot, Object? newSlot) {} - @override - void removeRenderObjectChild(RenderObject child, Object? slot) {} - - @override - KrakenRenderObjectWidget get widget => super.widget as KrakenRenderObjectWidget; -} diff --git a/webf/lib/src/widget/text_control.dart b/webf/lib/src/widget/text_control.dart index c68b7b9077..496392213d 100644 --- a/webf/lib/src/widget/text_control.dart +++ b/webf/lib/src/widget/text_control.dart @@ -1,29 +1,36 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; -import 'package:kraken/kraken.dart'; -import 'package:kraken/rendering.dart'; -import 'package:kraken/dom.dart' as dom; -import 'package:kraken/css.dart'; +import 'package:webf/webf.dart'; +import 'package:webf/rendering.dart'; +import 'package:webf/dom.dart' as dom; +import 'package:webf/css.dart'; /// Get context of current widget. typedef GetContext = BuildContext Function(); + /// Request focus of current widget. typedef RequestFocus = void Function(); + /// Get the target platform. typedef GetTargetPlatform = TargetPlatform Function(); + /// Get the cursor color according to the widget theme and platform theme. typedef GetCursorColor = Color Function(); + /// Get the selection color according to the widget theme and platform theme. typedef GetSelectionColor = Color Function(); + /// Get the cursor radius according to the target platform. typedef GetCursorRadius = Radius Function(); + /// Get the text selection controls according to the target platform. typedef GetTextSelectionControls = TextSelectionControls Function(); -typedef OnControllerCreated = void Function(KrakenController controller); +typedef OnControllerCreated = void Function(WebFController controller); /// Delegate methods of widget class WidgetDelegate { @@ -47,16 +54,16 @@ class WidgetDelegate { } // Widget involves actions of text control elements(input, textarea). -class KrakenTextControl extends StatefulWidget { - KrakenTextControl(this.parentContext); +class WebFTextControl extends StatefulWidget { + WebFTextControl(this.parentContext); final BuildContext parentContext; @override - _KrakenTextControlState createState() => _KrakenTextControlState(); + _WebFTextControlState createState() => _WebFTextControlState(); } -class _KrakenTextControlState extends State { +class _WebFTextControlState extends State with _FindElementFromContextMixin { @override void initState() { super.initState(); @@ -70,12 +77,10 @@ class _KrakenTextControlState extends State { actions: _actionMap, focusNode: _focusNode, onFocusChange: _handleFocusChange, - child: KrakenRenderObjectWidget( - widget.parentContext.widget as Kraken, + child: WebFRenderObjectWidget( + widget.parentContext.widget as WebF, widgetDelegate, - ) - ) - ); + ))); } final FocusNode _focusNode = FocusNode(); @@ -94,13 +99,9 @@ class _KrakenTextControlState extends State { ); } - FocusableActionDetector createTextControlDetector(KrakenRenderObjectWidget child) { + FocusableActionDetector createTextControlDetector(WebFRenderObjectWidget child) { return FocusableActionDetector( - actions: _actionMap, - focusNode: _focusNode, - onFocusChange: _handleFocusChange, - child: child - ); + actions: _actionMap, focusNode: _focusNode, onFocusChange: _handleFocusChange, child: child); } void _initActionMap() { @@ -109,57 +110,80 @@ class _KrakenTextControlState extends State { NextFocusIntent: CallbackAction(onInvoke: _handleNextFocus), PreviousFocusIntent: CallbackAction(onInvoke: _handlePreviousFocus), - // Action to delete text. - DeleteTextIntent: CallbackAction(onInvoke: _handleDeleteText), - DeleteByWordTextIntent: CallbackAction(onInvoke: _handleDeleteByWordText), - DeleteByLineTextIntent: CallbackAction(onInvoke: _handleDeleteByLineText), - DeleteForwardTextIntent: CallbackAction(onInvoke: _handleDeleteForwardText), - DeleteForwardByWordTextIntent: CallbackAction(onInvoke: _handleDeleteForwardByWordText), - DeleteForwardByLineTextIntent: CallbackAction(onInvoke: _handleDeleteForwardByLineText), - - // Action of hot keys control/command + (X, C, V, A). - SelectAllTextIntent: CallbackAction(onInvoke: _handleSelectAllText), - CopySelectionTextIntent: CallbackAction(onInvoke: _handleCopySelectionText), - CutSelectionTextIntent: CallbackAction(onInvoke: _handleCutSelectionText), - PasteTextIntent: CallbackAction(onInvoke: _handlePasteText), - - // Action of mouse move hotkeys. - MoveSelectionRightByLineTextIntent: CallbackAction(onInvoke: _handleMoveSelectionRightByLineText), - MoveSelectionLeftByLineTextIntent: CallbackAction(onInvoke: _handleMoveSelectionLeftByLineText), - MoveSelectionRightByWordTextIntent: CallbackAction(onInvoke: _handleMoveSelectionRightByWordText), - MoveSelectionLeftByWordTextIntent: CallbackAction(onInvoke: _handleMoveSelectionLeftByWordText), - MoveSelectionUpTextIntent: CallbackAction(onInvoke: _handleMoveSelectionUpText), - MoveSelectionDownTextIntent: CallbackAction(onInvoke: _handleMoveSelectionDownText), - MoveSelectionLeftTextIntent: CallbackAction(onInvoke: _handleMoveSelectionLeftText), - MoveSelectionRightTextIntent: CallbackAction(onInvoke: _handleMoveSelectionRightText), - MoveSelectionToStartTextIntent: CallbackAction(onInvoke: _handleMoveSelectionToStartText), - MoveSelectionToEndTextIntent: CallbackAction(onInvoke: _handleMoveSelectionToEndText), - - // Action of selection hotkeys. - ExtendSelectionLeftTextIntent: CallbackAction(onInvoke: _handleExtendSelectionLeftText), - ExtendSelectionRightTextIntent: CallbackAction(onInvoke: _handleExtendSelectionRightText), - ExtendSelectionUpTextIntent: CallbackAction(onInvoke: _handleExtendSelectionUpText), - ExtendSelectionDownTextIntent: CallbackAction(onInvoke: _handleExtendSelectionDownText), - ExtendSelectionLeftByWordTextIntent: CallbackAction(onInvoke: _handleExtendSelectionLeftByWordText), - ExtendSelectionLeftByLineTextIntent: CallbackAction(onInvoke: _handleExtendSelectionLeftByLineText), - ExtendSelectionLeftByWordAndStopAtReversalTextIntent: CallbackAction(onInvoke: _handleExtendSelectionLeftByWordAndStopAtReversalText), - ExtendSelectionRightByWordTextIntent: CallbackAction(onInvoke: _handleExtendSelectionRightByWordText), - ExtendSelectionRightByLineTextIntent: CallbackAction(onInvoke: _handleExtendSelectionRightByLineText), - ExtendSelectionRightByWordAndStopAtReversalTextIntent: CallbackAction(onInvoke: _handleExtendSelectionRightByWordAndStopAtReversalText), - - ExpandSelectionToEndTextIntent: CallbackAction(onInvoke: _handleExtendSelectionToEndText), - ExpandSelectionToStartTextIntent: CallbackAction(onInvoke: _handleExtendSelectionToStartText), - ExpandSelectionLeftByLineTextIntent: CallbackAction(onInvoke: _handleExpandSelectionLeftByLineText), - ExpandSelectionRightByLineTextIntent: CallbackAction(onInvoke: _handleExpandSelectionRightByLineText), + DoNothingAndStopPropagationTextIntent: DoNothingAction(consumesKey: false), + ReplaceTextIntent: _replaceTextAction, + UpdateSelectionIntent: _updateSelectionAction, + DirectionalFocusIntent: DirectionalFocusAction.forTextField(), + + // Delete + DeleteCharacterIntent: + _makeOverridable(_DeleteTextAction(context, TextBoundaryType.characterBoundary)), + DeleteToNextWordBoundaryIntent: _makeOverridable( + _DeleteTextAction(context, TextBoundaryType.nextWordBoundary)), + DeleteToLineBreakIntent: + _makeOverridable(_DeleteTextAction(context, TextBoundaryType.lineBreak)), + + // Extend/Move Selection + ExtendSelectionByCharacterIntent: _makeOverridable(_UpdateTextSelectionAction( + context, TextBoundaryType.characterBoundary, false)), + ExtendSelectionToNextWordBoundaryIntent: _makeOverridable( + _UpdateTextSelectionAction( + context, TextBoundaryType.nextWordBoundary, true)), + ExtendSelectionToLineBreakIntent: _makeOverridable( + _UpdateTextSelectionAction(context, TextBoundaryType.lineBreak, true)), + ExtendSelectionVerticallyToAdjacentLineIntent: _makeOverridable(_adjacentLineAction), + ExtendSelectionToDocumentBoundaryIntent: _makeOverridable( + _UpdateTextSelectionAction( + context, TextBoundaryType.documentBoundary, true)), + ExtendSelectionToNextWordBoundaryOrCaretLocationIntent: + _makeOverridable(_ExtendSelectionOrCaretPositionAction(context, TextBoundaryType.nextWordBoundary)), + + // Copy Paste + SelectAllTextIntent: _makeOverridable(_SelectAllAction(context)), + CopySelectionTextIntent: _makeOverridable(_CopySelectionAction(context)), + PasteTextIntent: _makeOverridable(_PasteAction(context)), }; } + Action _makeOverridable(Action defaultAction) { + return Action.overridable(context: context, defaultAction: defaultAction); + } + + void _replaceText(ReplaceTextIntent intent) { + dom.TextFormControlElement? focusedElement = _findFocusedElement(context); + if (focusedElement != null) { + focusedElement.textSelectionDelegate.userUpdateTextEditingValue( + intent.currentTextEditingValue.replaced(intent.replacementRange, intent.replacementText), + intent.cause, + ); + } + } + + late final Action _replaceTextAction = CallbackAction(onInvoke: _replaceText); + + void _updateSelection(UpdateSelectionIntent intent) { + dom.TextFormControlElement? focusedElement = _findFocusedElement(context); + if (focusedElement != null) { + focusedElement.textSelectionDelegate.userUpdateTextEditingValue( + intent.currentTextEditingValue.copyWith(selection: intent.newSelection), + intent.cause, + ); + } + } + + late final Action _updateSelectionAction = + CallbackAction(onInvoke: _updateSelection); + + late final _UpdateTextSelectionToAdjacentLineAction + _adjacentLineAction = + _UpdateTextSelectionToAdjacentLineAction(context); + // Handle focus action usually by pressing the [Tab] hotkey. void _handleNextFocus(NextFocusIntent intent) { - dom.Element rootElement = _findRootElement(); + dom.Element rootElement = _findRootElement(context); List focusableElements = _findFocusableElements(rootElement); if (focusableElements.isNotEmpty) { - dom.Element? focusedElement = _findFocusedElement(focusableElements); + dom.Element? focusedElement = _findFocusedElement(context, focusableElements); // None focusable element is focused, focus the first focusable element. if (focusedElement == null) { _focusNode.requestFocus(); @@ -187,10 +211,10 @@ class _KrakenTextControlState extends State { // Handle focus action usually by pressing the [Shift]+[Tab] hotkey in the reverse direction. void _handlePreviousFocus(PreviousFocusIntent intent) { - dom.Element rootElement = _findRootElement(); + dom.Element rootElement = _findRootElement(context); List focusableElements = _findFocusableElements(rootElement); if (focusableElements.isNotEmpty) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(focusableElements); + dom.TextFormControlElement? focusedElement = _findFocusedElement(context, focusableElements); // None editable is focused, focus the last editable. if (focusedElement == null) { _focusNode.requestFocus(); @@ -215,341 +239,12 @@ class _KrakenTextControlState extends State { } } - void _handleDeleteText(DeleteTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .delete(SelectionChangedCause.keyboard); - } - } - - void _handleDeleteByWordText(DeleteByWordTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .deleteByWord(SelectionChangedCause.keyboard, false); - } - } - - void _handleDeleteByLineText(DeleteByLineTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .deleteByLine(SelectionChangedCause.keyboard); - } - } - - void _handleDeleteForwardText(DeleteForwardTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .deleteForward(SelectionChangedCause.keyboard); - } - } - - void _handleDeleteForwardByWordText(DeleteForwardByWordTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .deleteForwardByWord(SelectionChangedCause.keyboard, false); - } - } - - void _handleDeleteForwardByLineText(DeleteForwardByLineTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .deleteForwardByLine(SelectionChangedCause.keyboard); - } - } - - - void _handleSelectAllText(SelectAllTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .selectAll(SelectionChangedCause.keyboard); - } - } - - void _handleCopySelectionText(CopySelectionTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .copySelection(SelectionChangedCause.keyboard); - } - } - - void _handleCutSelectionText(CutSelectionTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .cutSelection(SelectionChangedCause.keyboard); - } - } - - void _handlePasteText(PasteTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .pasteText(SelectionChangedCause.keyboard); - } - } - - void _handleMoveSelectionRightByLineText(MoveSelectionRightByLineTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .moveSelectionRightByLine(SelectionChangedCause.keyboard); - // Make caret visible while moving cursor. - focusedElement.scrollToCaret(); - } - } - - void _handleMoveSelectionLeftByLineText(MoveSelectionLeftByLineTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .moveSelectionLeftByLine(SelectionChangedCause.keyboard); - // Make caret visible while moving cursor. - focusedElement.scrollToCaret(); - } - } - - void _handleMoveSelectionRightByWordText(MoveSelectionRightByWordTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .moveSelectionRightByWord(SelectionChangedCause.keyboard); - // Make caret visible while moving cursor. - focusedElement.scrollToCaret(); - } - } - - void _handleMoveSelectionLeftByWordText(MoveSelectionLeftByWordTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .moveSelectionLeftByWord(SelectionChangedCause.keyboard); - // Make caret visible while moving cursor. - focusedElement.scrollToCaret(); - } - } - - void _handleMoveSelectionUpText(MoveSelectionUpTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .moveSelectionUp(SelectionChangedCause.keyboard); - // Make caret visible while moving cursor. - focusedElement.scrollToCaret(); - } - } - - void _handleMoveSelectionDownText(MoveSelectionDownTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .moveSelectionDown(SelectionChangedCause.keyboard); - // Make caret visible while moving cursor. - focusedElement.scrollToCaret(); - } - } - - void _handleMoveSelectionLeftText(MoveSelectionLeftTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .moveSelectionLeft(SelectionChangedCause.keyboard); - // Make caret visible while moving cursor. - focusedElement.scrollToCaret(); - } - } - - void _handleMoveSelectionRightText(MoveSelectionRightTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .moveSelectionRight(SelectionChangedCause.keyboard); - // Make caret visible while moving cursor. - focusedElement.scrollToCaret(); - } - } - - void _handleMoveSelectionToEndText(MoveSelectionToEndTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .moveSelectionToEnd(SelectionChangedCause.keyboard); - // Make caret visible while moving cursor. - focusedElement.scrollToCaret(); - } - } - - void _handleMoveSelectionToStartText(MoveSelectionToStartTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .moveSelectionToStart(SelectionChangedCause.keyboard); - // Make caret visible while moving cursor. - focusedElement.scrollToCaret(); - } - } - - void _handleExtendSelectionLeftText(ExtendSelectionLeftTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .extendSelectionLeft(SelectionChangedCause.keyboard); - // Make caret visible while moving cursor. - focusedElement.scrollToCaret(); - } - } - - void _handleExtendSelectionRightText(ExtendSelectionRightTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .extendSelectionRight(SelectionChangedCause.keyboard); - } - } - - void _handleExtendSelectionUpText(ExtendSelectionUpTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .extendSelectionUp(SelectionChangedCause.keyboard); - } - } - - void _handleExtendSelectionDownText(ExtendSelectionDownTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .extendSelectionDown(SelectionChangedCause.keyboard); - } - } - - void _handleExtendSelectionToEndText(ExpandSelectionToEndTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .expandSelectionToEnd(SelectionChangedCause.keyboard); - } - } - - void _handleExtendSelectionToStartText(ExpandSelectionToStartTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .expandSelectionToStart(SelectionChangedCause.keyboard); - } - } - - void _handleExpandSelectionLeftByLineText(ExpandSelectionLeftByLineTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .expandSelectionLeftByLine(SelectionChangedCause.keyboard); - } - } - - void _handleExpandSelectionRightByLineText(ExpandSelectionRightByLineTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .expandSelectionRightByLine(SelectionChangedCause.keyboard); - } - } - - void _handleExtendSelectionLeftByWordText(ExtendSelectionLeftByWordTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .extendSelectionLeftByWord(SelectionChangedCause.keyboard); - } - } - - void _handleExtendSelectionLeftByLineText(ExtendSelectionLeftByLineTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .extendSelectionLeftByLine(SelectionChangedCause.keyboard); - } - } - - void _handleExtendSelectionLeftByWordAndStopAtReversalText(ExtendSelectionLeftByWordAndStopAtReversalTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .extendSelectionLeftByWord(SelectionChangedCause.keyboard, false, true); - } - } - - void _handleExtendSelectionRightByWordText(ExtendSelectionRightByWordTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .extendSelectionRightByWord(SelectionChangedCause.keyboard); - } - } - - void _handleExtendSelectionRightByLineText(ExtendSelectionRightByLineTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .extendSelectionRightByLine(SelectionChangedCause.keyboard); - } - } - - void _handleExtendSelectionRightByWordAndStopAtReversalText(ExtendSelectionRightByWordAndStopAtReversalTextIntent intent) { - dom.TextFormControlElement? focusedElement = _findFocusedElement(); - if (focusedElement != null) { - focusedElement - .textSelectionDelegate - .extendSelectionRightByWord(SelectionChangedCause.keyboard, false, true); - } - } - // Handle focus change of _focusNode. void _handleFocusChange(bool focused) { - dom.Element rootElement = _findRootElement(); + dom.Element rootElement = _findRootElement(context); List focusableElements = _findFocusableElements(rootElement); if (focusableElements.isNotEmpty) { - dom.Element? focusedElement = _findFocusedElement(focusableElements); + dom.Element? focusedElement = _findFocusedElement(context, focusableElements); // Currently only input element is focusable. if (focused) { if (rootElement.ownerDocument.focusedElement == null) { @@ -563,62 +258,6 @@ class _KrakenTextControlState extends State { } } - - // Find RenderViewportBox in the renderObject tree. - RenderViewportBox? _findRenderViewportBox(RenderObject parent) { - RenderViewportBox? result; - parent.visitChildren((RenderObject child) { - if (child is RenderViewportBox) { - result = child; - } else { - result = _findRenderViewportBox(child); - } - }); - return result; - } - - // Find root element of dom tree. - dom.Element _findRootElement() { - RenderObject? _rootRenderObject = context.findRenderObject(); - RenderViewportBox? renderViewportBox = _findRenderViewportBox(_rootRenderObject!); - KrakenController controller = (renderViewportBox as RenderObjectWithControllerMixin).controller!; - dom.Element documentElement = controller.view.document.documentElement!; - return documentElement; - } - - // Find all the focusable elements in the element tree. - List _findFocusableElements(dom.Element element) { - List result = []; - traverseElement(element, (dom.Element child) { - // Currently only input element is focusable. - if (child is dom.TextFormControlElement) { - result.add(child); - } - }); - return result; - } - - // Find the focused element in the element tree. - dom.TextFormControlElement? _findFocusedElement([List? focusableElements]) { - dom.TextFormControlElement? result; - if (focusableElements == null) { - dom.Element rootElement = _findRootElement(); - focusableElements = _findFocusableElements(rootElement); - } - - if (focusableElements.isNotEmpty) { - // Currently only TextFormControlElement is focusable. - for (dom.Element element in focusableElements) { - RenderEditable? renderEditable = (element as dom.TextFormControlElement).renderEditable; - if (renderEditable != null && renderEditable.hasFocus) { - result = element; - break; - } - } - } - return result; - } - // Get context of current widget. BuildContext _getContext() { return context; @@ -749,3 +388,504 @@ class _KrakenTextControlState extends State { return _selectionControls; } } + +enum TextBoundaryType { + characterBoundary, + nextWordBoundary, + lineBreak, + documentBoundary, +} + +mixin _FindElementFromContextMixin { + // Find RenderViewportBox in the renderObject tree. + RenderViewportBox? _findRenderViewportBox(RenderObject parent) { + RenderViewportBox? result; + parent.visitChildren((RenderObject child) { + if (child is RenderViewportBox) { + result = child; + } else { + result = _findRenderViewportBox(child); + } + }); + return result; + } + + // Find root element of dom tree. + dom.Element _findRootElement(BuildContext context) { + RenderObject? _rootRenderObject = context.findRenderObject(); + RenderViewportBox? renderViewportBox = _findRenderViewportBox(_rootRenderObject!); + WebFController controller = (renderViewportBox as RenderObjectWithControllerMixin).controller!; + dom.Element documentElement = controller.view.document.documentElement!; + return documentElement; + } + + // Find all the focusable elements in the element tree. + List _findFocusableElements(dom.Element element) { + List result = []; + traverseElement(element, (dom.Element child) { + // Currently only input element is focusable. + if (child is dom.TextFormControlElement) { + result.add(child); + } + }); + return result; + } + + // Find the focused element in the element tree. + dom.TextFormControlElement? _findFocusedElement(BuildContext context, [List? focusableElements]) { + dom.TextFormControlElement? result; + if (focusableElements == null) { + dom.Element rootElement = _findRootElement(context); + focusableElements = _findFocusableElements(rootElement); + } + + if (focusableElements.isNotEmpty) { + // Currently only TextFormControlElement is focusable. + for (dom.Element element in focusableElements) { + RenderEditable? renderEditable = (element as dom.TextFormControlElement).renderEditable; + if (renderEditable != null && renderEditable.hasFocus) { + result = element; + break; + } + } + } + return result; + } +} + +// ------------------------------- Text Actions ------------------------------- +class _DeleteTextAction extends ContextAction + with _FindElementFromContextMixin { + _DeleteTextAction(this.context, this.textBoundaryType); + + BuildContext context; + TextBoundaryType textBoundaryType; + dom.EditableTextDelegate? delegate; + + TextRange _expandNonCollapsedRange(TextEditingValue value, bool obscureText) { + final TextRange selection = value.selection; + assert(selection.isValid); + assert(!selection.isCollapsed); + final dom.TextBoundary atomicBoundary = obscureText ? dom.CodeUnitBoundary(value) : dom.CharacterBoundary(value); + + return TextRange( + start: atomicBoundary.getLeadingTextBoundaryAt(TextPosition(offset: selection.start)).offset, + end: atomicBoundary.getTrailingTextBoundaryAt(TextPosition(offset: selection.end - 1)).offset, + ); + } + + @override + Object? invoke(T intent, [BuildContext? context]) { + if (delegate == null) return null; + + dom.EditableTextDelegate _delegate = delegate!; + dom.TextBoundary Function(T intent) getTextBoundariesForIntent; + + switch (textBoundaryType) { + case TextBoundaryType.characterBoundary: + getTextBoundariesForIntent = _delegate.characterBoundary; + break; + case TextBoundaryType.nextWordBoundary: + getTextBoundariesForIntent = _delegate.nextWordBoundary; + break; + case TextBoundaryType.lineBreak: + getTextBoundariesForIntent = _delegate.linebreak; + break; + case TextBoundaryType.documentBoundary: + getTextBoundariesForIntent = _delegate.documentBoundary; + break; + } + + final TextSelection selection = _delegate.value.selection; + assert(selection.isValid); + + if (!selection.isCollapsed) { + return Actions.invoke( + context!, + ReplaceTextIntent(_delegate.value, '', _expandNonCollapsedRange(_delegate.value, _delegate.element.obscureText), + SelectionChangedCause.keyboard), + ); + } + + final dom.TextBoundary textBoundary = getTextBoundariesForIntent(intent); + if (!textBoundary.textEditingValue.selection.isValid) { + return null; + } + if (!textBoundary.textEditingValue.selection.isCollapsed) { + return Actions.invoke( + context!, + ReplaceTextIntent( + _delegate.value, + '', + _expandNonCollapsedRange(textBoundary.textEditingValue, _delegate.element.obscureText), + SelectionChangedCause.keyboard), + ); + } + + return Actions.invoke( + context!, + ReplaceTextIntent( + textBoundary.textEditingValue, + '', + textBoundary.getTextBoundaryAt(textBoundary.textEditingValue.selection.base), + SelectionChangedCause.keyboard, + ), + ); + } + + @override + bool get isActionEnabled { + dom.TextFormControlElement? focusedElement = _findFocusedElement(context); + if (focusedElement == null) { + return false; + } + delegate = focusedElement.textSelectionDelegate; + dom.EditableTextDelegate _delegate = delegate!; + return !_delegate.element.readOnly && _delegate.value.selection.isValid; + } +} + +class _UpdateTextSelectionAction extends ContextAction + with _FindElementFromContextMixin { + _UpdateTextSelectionAction(this.context, this.textBoundaryType, this.ignoreNonCollapsedSelection); + + BuildContext context; + TextBoundaryType textBoundaryType; + dom.EditableTextDelegate? delegate; + final bool ignoreNonCollapsedSelection; + + @override + Object? invoke(T intent, [BuildContext? context]) { + if (delegate == null) return null; + + dom.EditableTextDelegate _delegate = delegate!; + dom.TextBoundary Function(T intent) getTextBoundariesForIntent; + + switch (textBoundaryType) { + case TextBoundaryType.characterBoundary: + getTextBoundariesForIntent = _delegate.characterBoundary; + break; + case TextBoundaryType.nextWordBoundary: + getTextBoundariesForIntent = _delegate.nextWordBoundary; + break; + case TextBoundaryType.lineBreak: + getTextBoundariesForIntent = _delegate.linebreak; + break; + case TextBoundaryType.documentBoundary: + getTextBoundariesForIntent = _delegate.documentBoundary; + break; + } + + final TextSelection selection = _delegate.value.selection; + assert(selection.isValid); + + final bool collapseSelection = intent.collapseSelection; + // Collapse to the logical start/end. + TextSelection _collapse(TextSelection selection) { + assert(selection.isValid); + assert(!selection.isCollapsed); + return selection.copyWith( + baseOffset: intent.forward ? selection.end : selection.start, + extentOffset: intent.forward ? selection.end : selection.start, + ); + } + + if (!selection.isCollapsed && !ignoreNonCollapsedSelection && collapseSelection) { + return Actions.invoke( + context!, + UpdateSelectionIntent(_delegate.value, _collapse(selection), SelectionChangedCause.keyboard), + ); + } + + final dom.TextBoundary textBoundary = getTextBoundariesForIntent(intent); + final TextSelection textBoundarySelection = textBoundary.textEditingValue.selection; + if (!textBoundarySelection.isValid) { + return null; + } + if (!textBoundarySelection.isCollapsed && !ignoreNonCollapsedSelection && collapseSelection) { + return Actions.invoke( + context!, + UpdateSelectionIntent(_delegate.value, _collapse(textBoundarySelection), SelectionChangedCause.keyboard), + ); + } + + final TextPosition extent = textBoundarySelection.extent; + final TextPosition newExtent = + intent.forward ? textBoundary.getTrailingTextBoundaryAt(extent) : textBoundary.getLeadingTextBoundaryAt(extent); + + final TextSelection newSelection = + collapseSelection ? TextSelection.fromPosition(newExtent) : textBoundarySelection.extendTo(newExtent); + + // If collapseAtReversal is true and would have an effect, collapse it. + if (!selection.isCollapsed && + intent.collapseAtReversal && + (selection.baseOffset < selection.extentOffset != newSelection.baseOffset < newSelection.extentOffset)) { + return Actions.invoke( + context!, + UpdateSelectionIntent( + _delegate.value, + TextSelection.fromPosition(selection.base), + SelectionChangedCause.keyboard, + ), + ); + } + + return Actions.invoke( + context!, + UpdateSelectionIntent(textBoundary.textEditingValue, newSelection, SelectionChangedCause.keyboard), + ); + } + + @override + bool get isActionEnabled { + dom.TextFormControlElement? focusedElement = _findFocusedElement(context); + if (focusedElement == null) { + return false; + } + delegate = focusedElement.textSelectionDelegate; + dom.EditableTextDelegate _delegate = delegate!; + return _delegate.value.selection.isValid; + } +} + +class _ExtendSelectionOrCaretPositionAction + extends ContextAction with _FindElementFromContextMixin { + _ExtendSelectionOrCaretPositionAction(this.context, this.textBoundaryType); + + BuildContext context; + TextBoundaryType textBoundaryType; + dom.EditableTextDelegate? delegate; + + @override + Object? invoke(ExtendSelectionToNextWordBoundaryOrCaretLocationIntent intent, [BuildContext? context]) { + if (delegate == null) return null; + + dom.EditableTextDelegate _delegate = delegate!; + dom.TextBoundary Function(ExtendSelectionToNextWordBoundaryOrCaretLocationIntent intent) getTextBoundariesForIntent; + + switch (textBoundaryType) { + case TextBoundaryType.characterBoundary: + getTextBoundariesForIntent = _delegate.characterBoundary; + break; + case TextBoundaryType.nextWordBoundary: + getTextBoundariesForIntent = _delegate.nextWordBoundary; + break; + case TextBoundaryType.lineBreak: + getTextBoundariesForIntent = _delegate.linebreak; + break; + case TextBoundaryType.documentBoundary: + getTextBoundariesForIntent = _delegate.documentBoundary; + break; + } + + final TextSelection selection = _delegate.value.selection; + assert(selection.isValid); + + final dom.TextBoundary textBoundary = getTextBoundariesForIntent(intent); + final TextSelection textBoundarySelection = textBoundary.textEditingValue.selection; + if (!textBoundarySelection.isValid) { + return null; + } + + final TextPosition extent = textBoundarySelection.extent; + final TextPosition newExtent = + intent.forward ? textBoundary.getTrailingTextBoundaryAt(extent) : textBoundary.getLeadingTextBoundaryAt(extent); + + final TextSelection newSelection = (newExtent.offset - textBoundarySelection.baseOffset) * + (textBoundarySelection.extentOffset - textBoundarySelection.baseOffset) < + 0 + ? textBoundarySelection.copyWith( + extentOffset: textBoundarySelection.baseOffset, + affinity: textBoundarySelection.extentOffset > textBoundarySelection.baseOffset + ? TextAffinity.downstream + : TextAffinity.upstream, + ) + : textBoundarySelection.extendTo(newExtent); + + return Actions.invoke( + context!, + UpdateSelectionIntent(textBoundary.textEditingValue, newSelection, SelectionChangedCause.keyboard), + ); + } + + @override + bool get isActionEnabled { + dom.TextFormControlElement? focusedElement = _findFocusedElement(context); + if (focusedElement == null) { + return false; + } + delegate = focusedElement.textSelectionDelegate; + dom.EditableTextDelegate _delegate = delegate!; + return _delegate.value.selection.isValid; + } +} + +class _UpdateTextSelectionToAdjacentLineAction extends ContextAction + with _FindElementFromContextMixin { + _UpdateTextSelectionToAdjacentLineAction(this.context); + + BuildContext context; + dom.EditableTextDelegate? delegate; + + VerticalCaretMovementRun? _verticalMovementRun; + TextSelection? _runSelection; + + void stopCurrentVerticalRunIfSelectionChanges() { + if (delegate == null) return null; + + dom.EditableTextDelegate _delegate = delegate!; + + final TextSelection? runSelection = _runSelection; + if (runSelection == null) { + assert(_verticalMovementRun == null); + return; + } + _runSelection = _delegate.value.selection; + final TextSelection currentSelection = _delegate.value.selection; + final bool continueCurrentRun = currentSelection.isValid && + currentSelection.isCollapsed && + currentSelection.baseOffset == runSelection.baseOffset && + currentSelection.extentOffset == runSelection.extentOffset; + if (!continueCurrentRun) { + _verticalMovementRun = null; + _runSelection = null; + } + } + + @override + void invoke(T intent, [BuildContext? context]) { + if (delegate == null) return null; + + dom.EditableTextDelegate _delegate = delegate!; + + assert(_delegate.value.selection.isValid); + + final bool collapseSelection = intent.collapseSelection; + final TextEditingValue value = _delegate.value; + if (!value.selection.isValid) { + return; + } + + if (_verticalMovementRun?.isValid == false) { + _verticalMovementRun = null; + _runSelection = null; + } + + final VerticalCaretMovementRun currentRun = _verticalMovementRun ?? + _delegate.renderEditable.startVerticalCaretMovement(_delegate.renderEditable.selection!.extent); + + final bool shouldMove = intent.forward ? currentRun.moveNext() : currentRun.movePrevious(); + final TextPosition newExtent = shouldMove + ? currentRun.current + : (intent.forward ? TextPosition(offset: _delegate.value.text.length) : const TextPosition(offset: 0)); + final TextSelection newSelection = + collapseSelection ? TextSelection.fromPosition(newExtent) : value.selection.extendTo(newExtent); + + Actions.invoke( + context!, + UpdateSelectionIntent(value, newSelection, SelectionChangedCause.keyboard), + ); + if (_delegate.value.selection == newSelection) { + _verticalMovementRun = currentRun; + _runSelection = newSelection; + } + } + + @override + bool get isActionEnabled { + dom.TextFormControlElement? focusedElement = _findFocusedElement(context); + if (focusedElement == null) { + return false; + } + delegate = focusedElement.textSelectionDelegate; + dom.EditableTextDelegate _delegate = delegate!; + return _delegate.value.selection.isValid; + } +} + +class _SelectAllAction extends ContextAction with _FindElementFromContextMixin { + _SelectAllAction(this.context); + + BuildContext context; + dom.EditableTextDelegate? delegate; + + @override + Object? invoke(SelectAllTextIntent intent, [BuildContext? context]) { + if (delegate == null) return null; + + dom.EditableTextDelegate _delegate = delegate!; + return Actions.invoke( + context!, + UpdateSelectionIntent( + _delegate.value, + TextSelection(baseOffset: 0, extentOffset: _delegate.value.text.length), + intent.cause, + ), + ); + } + + @override + bool get isActionEnabled { + dom.TextFormControlElement? focusedElement = _findFocusedElement(context); + if (focusedElement == null) { + return false; + } + delegate = focusedElement.textSelectionDelegate; + return true; + } +} + +class _CopySelectionAction extends ContextAction with _FindElementFromContextMixin { + _CopySelectionAction(this.context); + + BuildContext context; + dom.EditableTextDelegate? delegate; + + @override + void invoke(CopySelectionTextIntent intent, [BuildContext? context]) { + if (delegate == null) return null; + + dom.EditableTextDelegate _delegate = delegate!; + if (intent.collapseSelection) { + _delegate.cutSelection(intent.cause); + } else { + _delegate.copySelection(intent.cause); + } + } + + @override + bool get isActionEnabled { + dom.TextFormControlElement? focusedElement = _findFocusedElement(context); + if (focusedElement == null) { + return false; + } + delegate = focusedElement.textSelectionDelegate; + dom.EditableTextDelegate _delegate = delegate!; + return _delegate.value.selection.isValid && !_delegate.value.selection.isCollapsed; + } +} + +class _PasteAction extends ContextAction with _FindElementFromContextMixin { + _PasteAction(this.context); + + BuildContext context; + dom.EditableTextDelegate? delegate; + + @override + void invoke(PasteTextIntent intent, [BuildContext? context]) { + if (delegate == null) return null; + + dom.EditableTextDelegate _delegate = delegate!; + _delegate.pasteText(intent.cause); + } + + @override + bool get isActionEnabled { + dom.TextFormControlElement? focusedElement = _findFocusedElement(context); + if (focusedElement == null) { + return false; + } + delegate = focusedElement.textSelectionDelegate; + return true; + } +} diff --git a/webf/lib/src/widget/webf.dart b/webf/lib/src/widget/webf.dart new file mode 100644 index 0000000000..70dfe16bbc --- /dev/null +++ b/webf/lib/src/widget/webf.dart @@ -0,0 +1,298 @@ +/* + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +import 'dart:io'; +import 'dart:ui'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:webf/webf.dart'; +import 'package:webf/gesture.dart'; +import 'package:webf/css.dart'; +import 'package:webf/src/dom/element_registry.dart'; + +class WebF extends StatefulWidget { + // The background color for viewport, default to transparent. + final Color? background; + + // the width of webFWidget + final double? viewportWidth; + + // the height of webFWidget + final double? viewportHeight; + + // The initial bundle to load. + final WebFBundle? bundle; + + // The animationController of Flutter Route object. + // Pass this object to webFWidget to make sure webF execute JavaScripts scripts after route transition animation completed. + final AnimationController? animationController; + + // The methods of the webFNavigateDelegation help you implement custom behaviors that are triggered + // during a webf view's process of loading, and completing a navigation request. + final WebFNavigationDelegate? navigationDelegate; + + // A method channel for receiving messaged from JavaScript code and sending message to JavaScript. + final WebFMethodChannel? javaScriptChannel; + + // Register the RouteObserver to observer page navigation. + // This is useful if you wants to pause webf timers and callbacks when webf widget are hidden by page route. + // https://api.flutter.dev/flutter/widgets/RouteObserver-class.html + final RouteObserver>? routeObserver; + + // Trigger when webf controller once created. + final OnControllerCreated? onControllerCreated; + + final LoadErrorHandler? onLoadError; + + final LoadHandler? onLoad; + + final JSErrorHandler? onJSError; + + // Open a service to support Chrome DevTools for debugging. + final DevToolsService? devToolsService; + + final GestureListener? gestureListener; + + final HttpClientInterceptor? httpClientInterceptor; + + final UriParser? uriParser; + + WebFController? get controller { + return WebFController.getControllerOfName(shortHash(this)); + } + + // Set webf http cache mode. + static void setHttpCacheMode(HttpCacheMode mode) { + HttpCacheController.mode = mode; + if (kDebugMode) { + print('WebF http cache mode set to $mode.'); + } + } + + static bool _isValidCustomElementName(localName) { + return RegExp(r'^[a-z][.0-9_a-z]*-[\-.0-9_a-z]*$').hasMatch(localName); + } + + static void defineCustomElement(String tagName, ElementCreator creator) { + if (!_isValidCustomElementName(tagName)) { + throw ArgumentError('The element name "$tagName" is not valid.'); + } + defineElement(tagName.toUpperCase(), creator); + } + + Future load(WebFBundle bundle) async { + await controller?.load(bundle); + } + + Future reload() async { + await controller?.reload(); + } + + WebF( + {Key? key, + this.viewportWidth, + this.viewportHeight, + this.bundle, + this.onControllerCreated, + this.onLoad, + this.navigationDelegate, + this.javaScriptChannel, + this.background, + this.gestureListener, + this.devToolsService, + // webf's http client interceptor. + this.httpClientInterceptor, + this.uriParser, + this.routeObserver, + // webf's viewportWidth options only works fine when viewportWidth is equal to window.physicalSize.width / window.devicePixelRatio. + // Maybe got unexpected error when change to other values, use this at your own risk! + // We will fixed this on next version released. (v0.6.0) + // Disable viewportWidth check and no assertion error report. + bool disableViewportWidthAssertion = false, + // webf's viewportHeight options only works fine when viewportHeight is equal to window.physicalSize.height / window.devicePixelRatio. + // Maybe got unexpected error when change to other values, use this at your own risk! + // We will fixed this on next version release. (v0.6.0) + // Disable viewportHeight check and no assertion error report. + bool disableViewportHeightAssertion = false, + // Callback functions when loading Javascript scripts failed. + this.onLoadError, + this.animationController, + this.onJSError}) + : super(key: key); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(DiagnosticsProperty('viewportWidth', viewportWidth)); + properties.add(DiagnosticsProperty('viewportHeight', viewportHeight)); + } + + @override + _WebFState createState() => _WebFState(); +} + +class _WebFState extends State with RouteAware { + @override + Widget build(BuildContext context) { + return WebFTextControl(context); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + if (widget.routeObserver != null) { + widget.routeObserver!.subscribe(this, ModalRoute.of(context)!); + } + } + + // Resume call timer and callbacks when webf widget change to visible. + @override + void didPopNext() { + assert(widget.controller != null); + widget.controller!.resume(); + } + + // Pause all timer and callbacks when webf widget has been invisible. + @override + void didPushNext() { + assert(widget.controller != null); + widget.controller!.pause(); + } + + @override + void dispose() { + if (widget.routeObserver != null) { + widget.routeObserver!.unsubscribe(this); + } + super.dispose(); + } + + @override + void deactivate() { + // Deactivate all WidgetElements in webf when webf Widget is deactivated. + widget.controller!.view.deactivateWidgetElements(); + + super.deactivate(); + } +} + +class WebFRenderObjectWidget extends SingleChildRenderObjectWidget { + // Creates a widget that visually hides its child. + const WebFRenderObjectWidget(WebF widget, WidgetDelegate widgetDelegate, {Key? key}) + : _webfWidget = widget, + _widgetDelegate = widgetDelegate, + super(key: key); + + final WebF _webfWidget; + final WidgetDelegate _widgetDelegate; + + @override + RenderObject createRenderObject(BuildContext context) { + if (kProfileMode) { + PerformanceTiming.instance().mark(PERF_CONTROLLER_INIT_START); + } + + double viewportWidth = _webfWidget.viewportWidth ?? window.physicalSize.width / window.devicePixelRatio; + double viewportHeight = _webfWidget.viewportHeight ?? window.physicalSize.height / window.devicePixelRatio; + + if (viewportWidth == 0.0 && viewportHeight == 0.0) { + throw FlutterError('''Can't get viewportSize from window. Please set viewportWidth and viewportHeight manually. +This situation often happened when you trying creating webf when FlutterView not initialized.'''); + } + + WebFController controller = WebFController(shortHash(_webfWidget.hashCode), viewportWidth, viewportHeight, + background: _webfWidget.background, + showPerformanceOverlay: Platform.environment[ENABLE_PERFORMANCE_OVERLAY] != null, + entrypoint: _webfWidget.bundle, + // Execute entrypoint when mount manually. + autoExecuteEntrypoint: false, + onLoad: _webfWidget.onLoad, + onLoadError: _webfWidget.onLoadError, + onJSError: _webfWidget.onJSError, + methodChannel: _webfWidget.javaScriptChannel, + gestureListener: _webfWidget.gestureListener, + navigationDelegate: _webfWidget.navigationDelegate, + devToolsService: _webfWidget.devToolsService, + httpClientInterceptor: _webfWidget.httpClientInterceptor, + widgetDelegate: _widgetDelegate, + uriParser: _webfWidget.uriParser); + + OnControllerCreated? onControllerCreated = _webfWidget.onControllerCreated; + if (onControllerCreated != null) { + onControllerCreated(controller); + } + + if (kProfileMode) { + PerformanceTiming.instance().mark(PERF_CONTROLLER_INIT_END); + } + + return controller.view.getRootRenderObject(); + } + + @override + void updateRenderObject(BuildContext context, covariant RenderObject renderObject) { + super.updateRenderObject(context, renderObject); + WebFController controller = (renderObject as RenderObjectWithControllerMixin).controller!; + controller.name = shortHash(_webfWidget.hashCode); + + bool viewportWidthHasChanged = controller.view.viewportWidth != _webfWidget.viewportWidth; + bool viewportHeightHasChanged = controller.view.viewportHeight != _webfWidget.viewportHeight; + + double viewportWidth = _webfWidget.viewportWidth ?? window.physicalSize.width / window.devicePixelRatio; + double viewportHeight = _webfWidget.viewportHeight ?? window.physicalSize.height / window.devicePixelRatio; + + if (controller.view.document.documentElement == null) return; + + if (viewportWidthHasChanged) { + controller.view.viewportWidth = viewportWidth; + controller.view.document.documentElement!.renderStyle.width = CSSLengthValue(viewportWidth, CSSLengthType.PX); + } + + if (viewportHeightHasChanged) { + controller.view.viewportHeight = viewportHeight; + controller.view.document.documentElement!.renderStyle.height = CSSLengthValue(viewportHeight, CSSLengthType.PX); + } + } + + @override + void didUnmountRenderObject(covariant RenderObject renderObject) { + WebFController controller = (renderObject as RenderObjectWithControllerMixin).controller!; + controller.dispose(); + } + + @override + _WebFRenderObjectElement createElement() { + return _WebFRenderObjectElement(this); + } +} + +class _WebFRenderObjectElement extends SingleChildRenderObjectElement { + _WebFRenderObjectElement(WebFRenderObjectWidget widget) : super(widget); + + @override + void mount(Element? parent, Object? newSlot) async { + super.mount(parent, newSlot); + + WebFController controller = (renderObject as RenderObjectWithControllerMixin).controller!; + + // We should make sure every flutter elements created under webf can be walk up to the root. + // So we bind _WebFRenderObjectElement into WebFController, and widgetElements created by controller can follow this to the root. + controller.rootFlutterElement = this; + await controller.executeEntrypoint(animationController: widget._webfWidget.animationController); + } + + // RenderObjects created by webf are manager by webf itself. There are no needs to operate renderObjects on _WebFRenderObjectElement. + @override + void insertRenderObjectChild(RenderObject child, Object? slot) {} + @override + void moveRenderObjectChild(RenderObject child, Object? oldSlot, Object? newSlot) {} + @override + void removeRenderObjectChild(RenderObject child, Object? slot) {} + + @override + WebFRenderObjectWidget get widget => super.widget as WebFRenderObjectWidget; +} diff --git a/webf/lib/src/widget/widget_to_element_adaptor.dart b/webf/lib/src/widget/widget_to_element_adaptor.dart index 49b95df254..496312a3e7 100644 --- a/webf/lib/src/widget/widget_to_element_adaptor.dart +++ b/webf/lib/src/widget/widget_to_element_adaptor.dart @@ -1,18 +1,19 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; -import 'package:kraken/kraken.dart'; -import 'package:kraken/dom.dart' as dom; +import 'package:webf/webf.dart'; +import 'package:webf/dom.dart' as dom; -class KrakenRenderObjectToWidgetAdapter extends RenderObjectWidget { +class WebFRenderObjectToWidgetAdapter extends RenderObjectWidget { /// Creates a bridge from a [RenderObject] to an [Element] tree. /// /// Used by [WidgetsBinding] to attach the root widget to the [RenderView]. - KrakenRenderObjectToWidgetAdapter({ + WebFRenderObjectToWidgetAdapter({ this.child, required this.container, this.debugShortDescription, @@ -30,17 +31,19 @@ class KrakenRenderObjectToWidgetAdapter extends RenderOb final String? debugShortDescription; @override - KrakenRenderObjectToWidgetElement createElement() => KrakenRenderObjectToWidgetElement(this); + WebFRenderObjectToWidgetElement createElement() => WebFRenderObjectToWidgetElement(this); @override - ContainerRenderObjectMixin> createRenderObject(BuildContext context) => container; + ContainerRenderObjectMixin> createRenderObject(BuildContext context) => + container; @override - void updateRenderObject(BuildContext context, RenderObject renderObject) { } + void updateRenderObject(BuildContext context, RenderObject renderObject) {} /// Inflate this widget and actually set the resulting [RenderObject] as the /// child of [container]. - KrakenRenderObjectToWidgetElement attachToRenderTree(BuildOwner owner, RenderObjectElement parentElement, bool needBuild) { + WebFRenderObjectToWidgetElement attachToRenderTree( + BuildOwner owner, RenderObjectElement parentElement, bool needBuild) { Element? element; owner.lockState(() { @@ -61,23 +64,23 @@ class KrakenRenderObjectToWidgetAdapter extends RenderOb }); } - return element! as KrakenRenderObjectToWidgetElement; + return element! as WebFRenderObjectToWidgetElement; } @override String toStringShort() => debugShortDescription ?? super.toStringShort(); } -class KrakenRenderObjectToWidgetElement extends RenderObjectElement { +class WebFRenderObjectToWidgetElement extends RenderObjectElement { /// Creates an element that is hosted by a [RenderObject]. /// /// The [RenderObject] created by this element is not automatically set as a /// child of the hosting [RenderObject]. To actually attach this element to /// the render tree, call [RenderObjectToWidgetAdapter.attachToRenderTree]. - KrakenRenderObjectToWidgetElement(KrakenRenderObjectToWidgetAdapter widget) : super(widget); + WebFRenderObjectToWidgetElement(WebFRenderObjectToWidgetAdapter widget) : super(widget); @override - KrakenRenderObjectToWidgetAdapter get widget => super.widget as KrakenRenderObjectToWidgetAdapter; + WebFRenderObjectToWidgetAdapter get widget => super.widget as WebFRenderObjectToWidgetAdapter; Element? _child; @@ -85,8 +88,7 @@ class KrakenRenderObjectToWidgetElement extends RenderOb @override void visitChildren(ElementVisitor visitor) { - if (_child != null) - visitor(_child!); + if (_child != null) visitor(_child!); } @override @@ -144,7 +146,8 @@ class KrakenRenderObjectToWidgetElement extends RenderOb } @override - ContainerRenderObjectMixin> get renderObject => super.renderObject as ContainerRenderObjectMixin>; + ContainerRenderObjectMixin> get renderObject => + super.renderObject as ContainerRenderObjectMixin>; @override void insertRenderObjectChild(RenderObject child, Object? slot) { @@ -165,9 +168,10 @@ class KrakenRenderObjectToWidgetElement extends RenderOb abstract class WidgetElement extends dom.Element { late Widget _widget; - _KrakenAdapterWidgetState? _state; + _WebFAdapterWidgetState? _state; - WidgetElement(BindingContext? context, { + WidgetElement( + BindingContext? context, { Map? defaultStyle, bool isReplacedElement = false, // WidgetElement Adds repaintBoundary by default to prevent the internal paint process from affecting the outside. @@ -175,14 +179,14 @@ abstract class WidgetElement extends dom.Element { // Otherwise it will cause performance problems by creating most layers. bool isDefaultRepaintBoundary = true, }) : super( - context, - defaultStyle: defaultStyle, - isReplacedElement: isReplacedElement, - isDefaultRepaintBoundary: isDefaultRepaintBoundary, - ) { + context, + defaultStyle: defaultStyle, + isReplacedElement: isReplacedElement, + isDefaultRepaintBoundary: isDefaultRepaintBoundary, + ) { WidgetsFlutterBinding.ensureInitialized(); - _state = _KrakenAdapterWidgetState(this, attributes, childNodes); - _widget = _KrakenAdapterWidget(_state!); + _state = _WebFAdapterWidgetState(this, attributes, childNodes); + _widget = _WebFAdapterWidget(_state!); } Widget build(BuildContext context, Map attributes, List children); @@ -245,11 +249,9 @@ abstract class WidgetElement extends dom.Element { void _attachWidget(Widget widget) { RenderObjectElement rootFlutterElement = ownerDocument.controller.rootFlutterElement; - KrakenRenderObjectToWidgetAdapter adaptor = KrakenRenderObjectToWidgetAdapter( - child: widget, - container: renderBoxModel as ContainerRenderObjectMixin> - ); + WebFRenderObjectToWidgetAdapter adaptor = WebFRenderObjectToWidgetAdapter( + child: widget, + container: renderBoxModel as ContainerRenderObjectMixin>); ownerDocument.controller.view.addWidgetElement(this); @@ -260,7 +262,16 @@ abstract class WidgetElement extends dom.Element { parentFlutterElement = (parentNode as dom.Element).flutterElement; } - renderObjectElement = adaptor.attachToRenderTree(rootFlutterElement.owner!, (parentFlutterElement ?? rootFlutterElement) as RenderObjectElement, parentFlutterElement == null); + renderObjectElement = adaptor.attachToRenderTree(rootFlutterElement.owner!, + (parentFlutterElement ?? rootFlutterElement) as RenderObjectElement, parentFlutterElement == null); + } + + @override + void dispose() { + super.dispose(); + if (renderObjectElement != null) { + deactivate(); + } } void deactivate() { @@ -274,10 +285,10 @@ abstract class WidgetElement extends dom.Element { } } -class _KrakenAdapterWidget extends StatefulWidget { - final _KrakenAdapterWidgetState _state; +class _WebFAdapterWidget extends StatefulWidget { + final _WebFAdapterWidgetState _state; - _KrakenAdapterWidget(this._state); + _WebFAdapterWidget(this._state); @override State createState() { @@ -285,14 +296,12 @@ class _KrakenAdapterWidget extends StatefulWidget { } } - -class _KrakenAdapterWidgetState extends State<_KrakenAdapterWidget> { +class _WebFAdapterWidgetState extends State<_WebFAdapterWidget> { Map _attributes; final WidgetElement _element; late List _childNodes; - _KrakenAdapterWidgetState(this._element, this._attributes, this._childNodes) { - } + _WebFAdapterWidgetState(this._element, this._attributes, this._childNodes) {} void onAttributeChanged(Map attributes) { if (mounted) { @@ -307,10 +316,11 @@ class _KrakenAdapterWidgetState extends State<_KrakenAdapterWidget> { List convertNodeListToWidgetList(List childNodes) { List children = List.generate(childNodes.length, (index) { if (childNodes[index] is WidgetElement) { - _KrakenAdapterWidgetState state = (childNodes[index] as WidgetElement)._state!; + _WebFAdapterWidgetState state = (childNodes[index] as WidgetElement)._state!; return state.build(context); } else { - return childNodes[index].flutterWidget ?? KrakenElementToWidgetAdaptor(childNodes[index], key: Key(index.toString())); + return childNodes[index].flutterWidget ?? + WebFElementToWidgetAdaptor(childNodes[index], key: Key(index.toString())); } }); diff --git a/webf/lib/webf.dart b/webf/lib/webf.dart new file mode 100644 index 0000000000..80919c60b2 --- /dev/null +++ b/webf/lib/webf.dart @@ -0,0 +1,12 @@ +/* + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +library webf; + +export 'bridge.dart'; +export 'foundation.dart'; +export 'launcher.dart'; +export 'module.dart'; +export 'widget.dart'; diff --git a/webf/lib/widget.dart b/webf/lib/widget.dart index e26d18c397..8595e63a45 100644 --- a/webf/lib/widget.dart +++ b/webf/lib/widget.dart @@ -1,8 +1,9 @@ /* - * Copyright (C) 2019-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -export 'src/widget/kraken.dart'; +export 'src/widget/webf.dart'; export 'src/widget/text_control.dart'; export 'src/widget/widget_to_element_adaptor.dart'; export 'src/widget/element_to_widget_adaptor.dart'; diff --git a/webf/linux/CMakeLists.txt b/webf/linux/CMakeLists.txt index dfb83c79c3..dfadaf7f56 100644 --- a/webf/linux/CMakeLists.txt +++ b/webf/linux/CMakeLists.txt @@ -4,10 +4,10 @@ project(${PROJECT_NAME} LANGUAGES CXX) # This value is used when generating builds using this plugin, so it must # not be changed -set(PLUGIN_NAME "webf") +set(PLUGIN_NAME "webf_plugin") add_library(${PLUGIN_NAME} SHARED - "webf.cc" + "webf_plugin.cc" ) add_library(webf SHARED IMPORTED) diff --git a/webf/linux/include/kraken/kraken_plugin.h b/webf/linux/include/kraken/kraken_plugin.h deleted file mode 100644 index cf5eb7450b..0000000000 --- a/webf/linux/include/kraken/kraken_plugin.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef FLUTTER_PLUGIN_KRAKEN_PLUGIN_H_ -#define FLUTTER_PLUGIN_KRAKEN_PLUGIN_H_ - -#include - -G_BEGIN_DECLS - -#ifdef FLUTTER_PLUGIN_IMPL -#define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default"))) -#else -#define FLUTTER_PLUGIN_EXPORT -#endif - -typedef struct _KrakenPlugin KrakenPlugin; -typedef struct { - GObjectClass parent_class; -} KrakenPluginClass; - -FLUTTER_PLUGIN_EXPORT GType kraken_plugin_get_type(); - -FLUTTER_PLUGIN_EXPORT void kraken_plugin_register_with_registrar( - FlPluginRegistrar* registrar); - -G_END_DECLS - -#endif // FLUTTER_PLUGIN_KRAKEN_PLUGIN_H_ diff --git a/webf/linux/include/webf/webf_plugin.h b/webf/linux/include/webf/webf_plugin.h new file mode 100644 index 0000000000..1ae5579d81 --- /dev/null +++ b/webf/linux/include/webf/webf_plugin.h @@ -0,0 +1,26 @@ +#ifndef FLUTTER_PLUGIN_WEBF_PLUGIN_H_ +#define FLUTTER_PLUGIN_WEBF_PLUGIN_H_ + +#include + +G_BEGIN_DECLS + +#ifdef FLUTTER_PLUGIN_IMPL +#define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default"))) +#else +#define FLUTTER_PLUGIN_EXPORT +#endif + +typedef struct _WebfPlugin WebfPlugin; +typedef struct { + GObjectClass parent_class; +} WebfPluginClass; + +FLUTTER_PLUGIN_EXPORT GType webf_plugin_get_type(); + +FLUTTER_PLUGIN_EXPORT void webf_plugin_register_with_registrar( + FlPluginRegistrar* registrar); + +G_END_DECLS + +#endif // FLUTTER_PLUGIN_WEBF_PLUGIN_H_ diff --git a/webf/linux/webf.cc b/webf/linux/webf_plugin.cc similarity index 60% rename from webf/linux/webf.cc rename to webf/linux/webf_plugin.cc index c8afba4f3f..156db59d58 100644 --- a/webf/linux/webf.cc +++ b/webf/linux/webf_plugin.cc @@ -1,4 +1,4 @@ -#include "include/kraken/kraken_plugin.h" +#include "include/webf/webf_plugin.h" #include #include @@ -6,19 +6,19 @@ #include -#define KRAKEN_PLUGIN(obj) \ - (G_TYPE_CHECK_INSTANCE_CAST((obj), kraken_plugin_get_type(), \ - KrakenPlugin)) +#define WEBF_PLUGIN(obj) \ + (G_TYPE_CHECK_INSTANCE_CAST((obj), webf_plugin_get_type(), \ + WebfPlugin)) -struct _KrakenPlugin { +struct _WebfPlugin { GObject parent_instance; }; -G_DEFINE_TYPE(KrakenPlugin, kraken_plugin, g_object_get_type()) +G_DEFINE_TYPE(WebfPlugin, webf_plugin, g_object_get_type()) // Called when a method call is received from Flutter. -static void kraken_plugin_handle_method_call( - KrakenPlugin* self, +static void webf_plugin_handle_method_call( + WebfPlugin* self, FlMethodCall* method_call) { g_autoptr(FlMethodResponse) response = nullptr; @@ -37,30 +37,30 @@ static void kraken_plugin_handle_method_call( fl_method_call_respond(method_call, response, nullptr); } -static void kraken_plugin_dispose(GObject* object) { - G_OBJECT_CLASS(kraken_plugin_parent_class)->dispose(object); +static void webf_plugin_dispose(GObject* object) { + G_OBJECT_CLASS(webf_plugin_parent_class)->dispose(object); } -static void kraken_plugin_class_init(KrakenPluginClass* klass) { - G_OBJECT_CLASS(klass)->dispose = kraken_plugin_dispose; +static void webf_plugin_class_init(WebfPluginClass* klass) { + G_OBJECT_CLASS(klass)->dispose = webf_plugin_dispose; } -static void kraken_plugin_init(KrakenPlugin* self) {} +static void webf_plugin_init(WebfPlugin* self) {} static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call, gpointer user_data) { - KrakenPlugin* plugin = KRAKEN_PLUGIN(user_data); - kraken_plugin_handle_method_call(plugin, method_call); + WebfPlugin* plugin = WEBF_PLUGIN(user_data); + webf_plugin_handle_method_call(plugin, method_call); } -void kraken_plugin_register_with_registrar(FlPluginRegistrar* registrar) { - KrakenPlugin* plugin = KRAKEN_PLUGIN( - g_object_new(kraken_plugin_get_type(), nullptr)); +void webf_plugin_register_with_registrar(FlPluginRegistrar* registrar) { + WebfPlugin* plugin = WEBF_PLUGIN( + g_object_new(webf_plugin_get_type(), nullptr)); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlMethodChannel) channel = fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar), - "kraken", + "webf", FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler(channel, method_call_cb, g_object_ref(plugin), diff --git a/webf/macos/Classes/Kraken.h b/webf/macos/Classes/WebF.h similarity index 82% rename from webf/macos/Classes/Kraken.h rename to webf/macos/Classes/WebF.h index c8d9a5056d..5a68fccaf3 100644 --- a/webf/macos/Classes/Kraken.h +++ b/webf/macos/Classes/WebF.h @@ -1,12 +1,12 @@ #import -#import "Kraken.h" -#import "KrakenPlugin.h" +#import "WebF.h" +#import "WebFPlugin.h" typedef void(^MethodHandler)(FlutterMethodCall* _Nonnull , FlutterResult _Nonnull); -@interface Kraken : NSObject +@interface WebF : NSObject -+ (Kraken* _Nonnull) instanceByBinaryMessenger: (NSObject* _Nonnull) messenger; ++ (WebF* _Nonnull) instanceByBinaryMessenger: (NSObject* _Nonnull) messenger; @property NSString* _Nullable bundleUrl; @property FlutterEngine* _Nonnull flutterEngine; diff --git a/webf/macos/Classes/Kraken.m b/webf/macos/Classes/WebF.m similarity index 82% rename from webf/macos/Classes/Kraken.m rename to webf/macos/Classes/WebF.m index fb21fc83be..18d648504b 100644 --- a/webf/macos/Classes/Kraken.m +++ b/webf/macos/Classes/WebF.m @@ -1,13 +1,13 @@ #import -#import "Kraken.h" -#import "KrakenPlugin.h" +#import "WebF.h" +#import "WebFPlugin.h" static NSMutableArray *engineList = nil; -static NSMutableArray *instanceList = nil; +static NSMutableArray *instanceList = nil; -@implementation Kraken +@implementation WebF -+ (Kraken*) instanceByBinaryMessenger: (NSObject*) messenger { ++ (WebF*) instanceByBinaryMessenger: (NSObject*) messenger { // Return last instance, multi instance not supported yet. if (instanceList != nil && instanceList.count > 0) { return [instanceList objectAtIndex: instanceList.count - 1]; @@ -18,12 +18,12 @@ + (Kraken*) instanceByBinaryMessenger: (NSObject*) messe - (instancetype)initWithFlutterEngine: (FlutterEngine*) engine { self.flutterEngine = engine; - FlutterMethodChannel *channel = [KrakenPlugin getMethodChannel]; + FlutterMethodChannel *channel = [WebFPlugin getMethodChannel]; if (channel == nil) { NSException* exception = [NSException exceptionWithName:@"InitError" - reason:@"KrakenSDK should init after Flutter's plugin registered." + reason:@"WebFSDK should init after Flutter's plugin registered." userInfo:nil]; @throw exception; } diff --git a/webf/macos/Classes/KrakenPlugin.h b/webf/macos/Classes/WebFPlugin.h similarity index 85% rename from webf/macos/Classes/KrakenPlugin.h rename to webf/macos/Classes/WebFPlugin.h index b1d8f7e65f..7697dd993e 100644 --- a/webf/macos/Classes/KrakenPlugin.h +++ b/webf/macos/Classes/WebFPlugin.h @@ -2,7 +2,7 @@ #define NAME_METHOD_SPLIT @"!!" -@interface KrakenPlugin : NSObject +@interface WebFPlugin : NSObject @property NSObject *registrar; @property FlutterMethodChannel *channel; diff --git a/webf/macos/Classes/KrakenPlugin.m b/webf/macos/Classes/WebFPlugin.m similarity index 76% rename from webf/macos/Classes/KrakenPlugin.m rename to webf/macos/Classes/WebFPlugin.m index cbe965f791..5ed0f2909d 100644 --- a/webf/macos/Classes/KrakenPlugin.m +++ b/webf/macos/Classes/WebFPlugin.m @@ -1,9 +1,9 @@ -#import "Kraken.h" -#import "KrakenPlugin.h" +#import "WebF.h" +#import "WebFPlugin.h" static FlutterMethodChannel *methodChannel = nil; -@implementation KrakenPlugin +@implementation WebFPlugin + (FlutterMethodChannel *) getMethodChannel { return methodChannel; @@ -12,11 +12,11 @@ + (FlutterMethodChannel *) getMethodChannel { + (void)registerWithRegistrar:(NSObject*)registrar { NSObject* messager = [registrar messenger]; FlutterMethodChannel* channel = [FlutterMethodChannel - methodChannelWithName:@"kraken" + methodChannelWithName:@"webf" binaryMessenger:messager]; methodChannel = channel; - KrakenPlugin* instance = [[KrakenPlugin alloc] initWithRegistrar: registrar]; + WebFPlugin* instance = [[WebFPlugin alloc] initWithRegistrar: registrar]; [registrar addMethodCallDelegate:instance channel:channel]; } @@ -28,14 +28,14 @@ - (instancetype) initWithRegistrar: (NSObject*)registrar - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { if ([@"getUrl" isEqualToString:call.method]) { - Kraken* krakenInstance = [Kraken instanceByBinaryMessenger: [self.registrar messenger]]; + WebF* krakenInstance = [WebF instanceByBinaryMessenger: [self.registrar messenger]]; if (krakenInstance != nil) { result([krakenInstance getUrl]); } else { result(nil); } } else if ([@"invokeMethod" isEqualToString: call.method]) { - Kraken* krakenInstance = [Kraken instanceByBinaryMessenger: [self.registrar messenger]]; + WebF* krakenInstance = [WebF instanceByBinaryMessenger: [self.registrar messenger]]; FlutterMethodCall* callWrap = [FlutterMethodCall methodCallWithMethodName: call.arguments[@"method"] arguments: call.arguments[@"args"]]; [krakenInstance _handleMethodCall:callWrap result:result]; } else if ([@"getTemporaryDirectory" isEqualToString: call.method]) { @@ -47,7 +47,7 @@ - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { - (NSString*) getTemporaryDirectory { NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); - return [paths.firstObject stringByAppendingString: @"/Kraken"]; + return [paths.firstObject stringByAppendingString: @"/WebF"]; } @end diff --git a/webf/macos/prepare.sh b/webf/macos/prepare.sh index b00f0e37c1..76f5e539cb 100755 --- a/webf/macos/prepare.sh +++ b/webf/macos/prepare.sh @@ -1,14 +1,14 @@ read_version() { - VERSION_STR=$(cat kraken.podspec | grep s.version | awk '{print $3}') + VERSION_STR=$(cat webf.podspec | grep s.version | awk '{print $3}') END_POS=$(echo ${#VERSION_STR} - 2 | bc) export VERSION=${VERSION_STR:1:$END_POS} } ROOT=$(pwd) -if [ -L "libkraken.dylib" ]; then - rm libkraken.dylib - ln -s $ROOT/../../bridge/build/macos/lib/x86_64/libkraken.dylib +if [ -L "libwebf.dylib" ]; then + rm libwebf.dylib + ln -s $ROOT/../../bridge/build/macos/lib/x86_64/libwebf.dylib fi if [ -L "libquickjs.dylib" ]; then diff --git a/webf/pubspec.yaml b/webf/pubspec.yaml index 8f50b2cb41..fbffb82d32 100644 --- a/webf/pubspec.yaml +++ b/webf/pubspec.yaml @@ -1,28 +1,28 @@ name: webf description: A W3C standard compliant Web rendering engine based on Flutter. -version: 0.1.0 +version: 0.12.0 homepage: https://openwebf.com environment: - sdk: ">=2.15.0 <3.0.0" - flutter: ">=2.5.0" + sdk: ">=2.17.5 <3.0.0" + flutter: ">=3.0.0" dependencies: flutter: sdk: flutter - path: ^1.8.0 # Pure dart module. - meta: ^1.3.0 # Pure dart module. - ffi: ^1.0.0 # Pure dart module. - async: ^2.6.1 # Pure dart module. - quiver: ^3.0.1+1 # Pure dart module. - vector_math: ^2.1.0 # Pure dart module. - connectivity: ^3.0.6 # No AndroidX used. - shared_preferences: ^2.0.6 # No AndroidX used. + path: ^1.8.1 # Pure dart module. + meta: ^1.7.0 # Pure dart module. + ffi: ^2.0.1 # Pure dart module. + async: ^2.8.2 # Pure dart module. + quiver: ^3.1.0 # Pure dart module. + vector_math: ^2.1.2 # Pure dart module. + connectivity_plus: ^2.3.5 # No AndroidX used. + shared_preferences: ^2.0.15 # No AndroidX used. dev_dependencies: flutter_test: sdk: flutter - test: ^1.16.8 + test: ^1.20.2 flutter: # This section identifies this Flutter project as a plugin project. @@ -38,10 +38,10 @@ flutter: platforms: android: package: com.openwebf.webf - pluginClass: KrakenPlugin + pluginClass: WebFPlugin ios: - pluginClass: KrakenPlugin + pluginClass: WebFPlugin macos: - pluginClass: KrakenPlugin + pluginClass: WebFPlugin linux: - pluginClass: KrakenPlugin + pluginClass: WebfPlugin diff --git a/webf/test/local_http_server.dart b/webf/test/local_http_server.dart index affb81173a..a10ca2bcd5 100644 --- a/webf/test/local_http_server.dart +++ b/webf/test/local_http_server.dart @@ -1,6 +1,8 @@ /* - * Copyright (C) 2022-present The Kraken authors. All rights reserved. + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. */ + import 'dart:convert'; import 'dart:io'; import 'dart:math'; @@ -58,7 +60,7 @@ class LocalHttpServer { for (int byte in data) { // space if (byte == 32) { - state ++; + state++; continue; } @@ -83,13 +85,14 @@ class LocalHttpServer { throw FlutterError('Reading local http data, but file not exists: \n${file.absolute.path}'); } - file.readAsBytes() - .then((Uint8List bytes) => utf8.decode(bytes)) - .then((String input) => _format(input)) - .then((String content) => utf8.encode(content)) - .catchError((Object err, StackTrace? stack) => file.readAsBytes()) - .then(socket.add) - .then((_) => socket.close()); + file + .readAsBytes() + .then((Uint8List bytes) => utf8.decode(bytes)) + .then((String input) => _format(input)) + .then((String content) => utf8.encode(content)) + .catchError((Object err, StackTrace? stack) => file.readAsBytes()) + .then(socket.add) + .then((_) => socket.close()); } } }, onError: (Object error, [StackTrace? stackTrace]) { @@ -105,9 +108,6 @@ class LocalHttpServer { } String _format(String input) { - return input - .replaceAll(RegExp(r'CURRENT_TIME', multiLine: true), HttpDate.format(DateTime.now())); + return input.replaceAll(RegExp(r'CURRENT_TIME', multiLine: true), HttpDate.format(DateTime.now())); } } - - diff --git a/webf/test/src/css/style_rule_parser.dart b/webf/test/src/css/style_rule_parser.dart index f83990cd6d..4bf795e406 100644 --- a/webf/test/src/css/style_rule_parser.dart +++ b/webf/test/src/css/style_rule_parser.dart @@ -1,4 +1,9 @@ -import 'package:kraken/css.dart'; +/* + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +import 'package:webf/css.dart'; import 'package:test/test.dart'; void main() { @@ -44,7 +49,8 @@ void main() { }); test('7', () { - CSSStyleRule? styleRule = CSSStyleRuleParser.parse('.foo \t {background: url(data:image/png;base64, CNbyblAAAAHElEQVQI12P4) red}'); + CSSStyleRule? styleRule = + CSSStyleRuleParser.parse('.foo \t {background: url(data:image/png;base64, CNbyblAAAAHElEQVQI12P4) red}'); expect(styleRule!.selectorText, '.foo'); expect(styleRule.style['background'], 'url(data:image/png;base64, CNbyblAAAAHElEQVQI12P4) red'); }); @@ -68,31 +74,31 @@ void main() { }); test('11', () { - CSSStyleRule? styleRule = CSSStyleRuleParser.parse('[hidden] { display: none }'); + CSSStyleRule? styleRule = CSSStyleRuleParser.parse('[hidden] { display: none }'); expect(styleRule!.selectorText, '[hidden]'); expect(styleRule.style['display'], 'none'); }); test('12', () { - CSSStyleRule? styleRule = CSSStyleRuleParser.parse('/**/ div > p { color: rgb(255, 255, 0); } /**/'); + CSSStyleRule? styleRule = CSSStyleRuleParser.parse('/**/ div > p { color: rgb(255, 255, 0); } /**/'); expect(styleRule!.selectorText, 'div > p'); expect(styleRule.style['color'], 'rgb(255, 255, 0)'); }); test('13', () { - CSSStyleRule? styleRule = CSSStyleRuleParser.parse('.foo { background-image: url( "./image (1).jpg" )}'); + CSSStyleRule? styleRule = CSSStyleRuleParser.parse('.foo { background-image: url( "./image (1).jpg" )}'); expect(styleRule!.selectorText, '.foo'); expect(styleRule.style['backgroundImage'], 'url( "./image (1).jpg" )'); }); test('14', () { - CSSStyleRule? styleRule = CSSStyleRuleParser.parse('.foo { .foo{ }; color: red}'); + CSSStyleRule? styleRule = CSSStyleRuleParser.parse('.foo { .foo{ }; color: red}'); expect(styleRule!.selectorText, '.foo'); expect(styleRule.style['color'], 'red'); }); test('15', () { - CSSStyleRule? styleRule = CSSStyleRuleParser.parse(' .foo {}'); + CSSStyleRule? styleRule = CSSStyleRuleParser.parse(' .foo {}'); expect(styleRule!.selectorText, '.foo'); }); }); diff --git a/webf/test/src/css/style_sheet_parser.dart b/webf/test/src/css/style_sheet_parser.dart index ff5000483d..407e50b29a 100644 --- a/webf/test/src/css/style_sheet_parser.dart +++ b/webf/test/src/css/style_sheet_parser.dart @@ -1,4 +1,9 @@ -import 'package:kraken/css.dart'; +/* + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +import 'package:webf/css.dart'; import 'package:test/test.dart'; void main() { @@ -30,7 +35,8 @@ void main() { }); test('4', () { - List rules = CSSStyleSheetParser.parse('.foo {color: red} .bar {background: url(data:image/png;base64...)}'); + List rules = + CSSStyleSheetParser.parse('.foo {color: red} .bar {background: url(data:image/png;base64...)}'); expect(rules.length, 2); expect((rules[0] as CSSStyleRule).selectorText, '.foo'); expect((rules[0] as CSSStyleRule).style['color'], 'red'); diff --git a/webf/test/src/css/values.dart b/webf/test/src/css/values.dart index 7c3718d7b7..71963a938b 100644 --- a/webf/test/src/css/values.dart +++ b/webf/test/src/css/values.dart @@ -1,9 +1,13 @@ -import 'package:kraken/css.dart'; +/* + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +import 'package:webf/css.dart'; import 'package:test/test.dart'; void main() { group('CSSValues', () { - group('CSSFunction', () { var cases = [ 'var(--x)', @@ -12,7 +16,7 @@ void main() { 'device-cmyk(0 81% 81% 30% / .5, rgb(178 34 34))', 'calc(var(--widthA) / 2)', 'url(https://some.com/path), url(https://some.com/path2)' - '''conic-gradient( + '''conic-gradient( hsl(360, 100%, 50%), hsl(315, 100%, 50%), hsl(270, 100%, 50%), diff --git a/webf/test/src/foundation/bundle.dart b/webf/test/src/foundation/bundle.dart index 652678cafd..82c5ffa5ed 100644 --- a/webf/test/src/foundation/bundle.dart +++ b/webf/test/src/foundation/bundle.dart @@ -1,9 +1,14 @@ +/* + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + import 'dart:convert'; -import 'dart:typed_data'; import 'dart:io'; +import 'dart:typed_data'; -import 'package:kraken/foundation.dart'; import 'package:test/test.dart'; +import 'package:webf/foundation.dart'; import '../../local_http_server.dart'; @@ -55,11 +60,11 @@ void main() { expect(bundle.data, bytecode); }); - test('KrakenBundle', () async { + test('WebFBundle', () async { Uint8List bytecode = Uint8List.fromList(List.generate(10, (index) => index, growable: false)); - var bundle = KrakenBundle.fromBytecode(bytecode); + var bundle = WebFBundle.fromBytecode(bytecode); await bundle.resolve(1); - expect(bundle.contentType.mimeType, 'application/vnd.kraken.bc1'); + expect(bundle.contentType.mimeType, 'application/vnd.webf.bc1'); }); }); } diff --git a/webf/test/src/foundation/convert.dart b/webf/test/src/foundation/convert.dart index 9738f5863d..ee7070ab4c 100644 --- a/webf/test/src/foundation/convert.dart +++ b/webf/test/src/foundation/convert.dart @@ -1,6 +1,10 @@ -import 'package:kraken/foundation.dart'; -import 'package:test/test.dart'; +/* + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +import 'package:webf/foundation.dart'; +import 'package:test/test.dart'; void main() { group('Convert', () { diff --git a/webf/test/src/foundation/environment.dart b/webf/test/src/foundation/environment.dart index 0b2dca5062..bd620c300f 100644 --- a/webf/test/src/foundation/environment.dart +++ b/webf/test/src/foundation/environment.dart @@ -1,10 +1,15 @@ -import 'package:kraken/foundation.dart'; +/* + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + import 'package:test/test.dart'; +import 'package:webf/foundation.dart'; void main() { group('environment', () { - test('getKrakenTemporaryPath()', () async { - String tempPath = await getKrakenTemporaryPath(); + test('getWebFTemporaryPath()', () async { + String tempPath = await getWebFTemporaryPath(); expect(tempPath, './temp'); }); }); diff --git a/webf/test/src/foundation/http_cache.dart b/webf/test/src/foundation/http_cache.dart index 4cbae5df52..bea705f9f1 100644 --- a/webf/test/src/foundation/http_cache.dart +++ b/webf/test/src/foundation/http_cache.dart @@ -1,10 +1,16 @@ +/* + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; import 'package:flutter/foundation.dart'; import 'package:test/test.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/foundation.dart'; + import '../../local_http_server.dart'; void main() { @@ -15,38 +21,33 @@ void main() { HttpClient httpClient = HttpClient(); group('HttpCache', () { - test('Simple http request with expires', () async { - var request = await httpClient.openUrl('GET', - server.getUri('json_with_content_length_expires_etag_last_modified')); - KrakenHttpOverrides.setContextHeader(request.headers, contextId); + var request = + await httpClient.openUrl('GET', server.getUri('json_with_content_length_expires_etag_last_modified')); + WebFHttpOverrides.setContextHeader(request.headers, contextId); var response = await request.close(); expect(response.statusCode, 200); - expect(response.headers.value(HttpHeaders.expiresHeader), - 'Mon, 16 Aug 2221 10:17:45 GMT'); + expect(response.headers.value(HttpHeaders.expiresHeader), 'Mon, 16 Aug 2221 10:17:45 GMT'); var data = await consolidateHttpClientResponseBytes(response); var content = jsonDecode(String.fromCharCodes(data)); expect(content, { 'method': 'GET', - 'data': { - 'userName': '12345' - } + 'data': {'userName': '12345'} }); // second request - var requestSecond = await httpClient.openUrl('GET', - server.getUri('json_with_content_length_expires_etag_last_modified')); - KrakenHttpOverrides.setContextHeader(requestSecond.headers, contextId); + var requestSecond = + await httpClient.openUrl('GET', server.getUri('json_with_content_length_expires_etag_last_modified')); + WebFHttpOverrides.setContextHeader(requestSecond.headers, contextId); var responseSecond = await requestSecond.close(); expect(responseSecond.headers.value('cache-hits'), 'HIT'); }); test('Negotiation cache last-modified', () async { // First request to save cache. - var req = await httpClient.openUrl('GET', - server.getUri('plain_text_with_content_length_and_last_modified')); - KrakenHttpOverrides.setContextHeader(req.headers, contextId); + var req = await httpClient.openUrl('GET', server.getUri('plain_text_with_content_length_and_last_modified')); + WebFHttpOverrides.setContextHeader(req.headers, contextId); req.headers.ifModifiedSince = HttpDate.parse('Sun, 15 Mar 2020 11:32:20 GMT'); var res = await req.close(); expect(String.fromCharCodes(await consolidateHttpClientResponseBytes(res)), 'CachedData'); @@ -62,17 +63,15 @@ void main() { // expire time and save new response. test('Update cache last-modified', () async { // First request to save cache. - var req = await httpClient.openUrl('GET', - server.getUri('plain_text_with_current_time_last_modified')); - KrakenHttpOverrides.setContextHeader(req.headers, contextId); + var req = await httpClient.openUrl('GET', server.getUri('plain_text_with_current_time_last_modified')); + WebFHttpOverrides.setContextHeader(req.headers, contextId); req.headers.ifModifiedSince = HttpDate.parse('Sun, 15 Mar 2020 11:32:20 GMT'); var res = await req.close(); expect(String.fromCharCodes(await consolidateHttpClientResponseBytes(res)), 'CachedData'); // Second request and updating cache. - var req2 = await httpClient.openUrl('GET', - server.getUri('plain_text_with_current_time_last_modified')); - KrakenHttpOverrides.setContextHeader(req2.headers, contextId); + var req2 = await httpClient.openUrl('GET', server.getUri('plain_text_with_current_time_last_modified')); + WebFHttpOverrides.setContextHeader(req2.headers, contextId); var res2 = await req2.close(); // Must miss cache, and update cache. @@ -90,9 +89,8 @@ void main() { test('Negotiation cache eTag', () async { // First request to save cache. - var req = await httpClient.openUrl('GET', - server.getUri('plain_text_with_etag_and_content_length')); - KrakenHttpOverrides.setContextHeader(req.headers, contextId); + var req = await httpClient.openUrl('GET', server.getUri('plain_text_with_etag_and_content_length')); + WebFHttpOverrides.setContextHeader(req.headers, contextId); req.headers.set(HttpHeaders.ifNoneMatchHeader, '"foo"'); var res = await req.close(); @@ -107,27 +105,24 @@ void main() { test('HttpCacheMode.NO_CACHE', () async { HttpCacheController.mode = HttpCacheMode.NO_CACHE; - var request = await httpClient.openUrl('GET', - server.getUri('json_with_content_length_expires_etag_last_modified')); - KrakenHttpOverrides.setContextHeader(request.headers, contextId); + var request = + await httpClient.openUrl('GET', server.getUri('json_with_content_length_expires_etag_last_modified')); + WebFHttpOverrides.setContextHeader(request.headers, contextId); var response = await request.close(); expect(response.statusCode, 200); - expect(response.headers.value(HttpHeaders.expiresHeader), - 'Mon, 16 Aug 2221 10:17:45 GMT'); + expect(response.headers.value(HttpHeaders.expiresHeader), 'Mon, 16 Aug 2221 10:17:45 GMT'); var data = await consolidateHttpClientResponseBytes(response); var content = jsonDecode(String.fromCharCodes(data)); expect(content, { 'method': 'GET', - 'data': { - 'userName': '12345' - } + 'data': {'userName': '12345'} }); // second request - var requestSecond = await httpClient.openUrl('GET', - server.getUri('json_with_content_length_expires_etag_last_modified')); - KrakenHttpOverrides.setContextHeader(requestSecond.headers, contextId); + var requestSecond = + await httpClient.openUrl('GET', server.getUri('json_with_content_length_expires_etag_last_modified')); + WebFHttpOverrides.setContextHeader(requestSecond.headers, contextId); var responseSecond = await requestSecond.close(); // Note: This line is different. @@ -137,9 +132,8 @@ void main() { test('HttpCacheMode.CACHE_ONLY', () async { HttpCacheController.mode = HttpCacheMode.CACHE_ONLY; - var request = await httpClient.openUrl('GET', - server.getUri('network')); - KrakenHttpOverrides.setContextHeader(request.headers, contextId); + var request = await httpClient.openUrl('GET', server.getUri('network')); + WebFHttpOverrides.setContextHeader(request.headers, contextId); var error; try { @@ -159,7 +153,7 @@ void main() { // Local request to save cache. var req = await httpClient.openUrl('GET', uri); - KrakenHttpOverrides.setContextHeader(req.headers, contextId); + WebFHttpOverrides.setContextHeader(req.headers, contextId); var res = await req.close(); Uint8List bytes = await consolidateHttpClientResponseBytes(res); expect(bytes.lengthInBytes, res.contentLength); @@ -180,9 +174,8 @@ void main() { test('Cache should contain response headers.', () async { // First request to save cache. - var req = await httpClient.openUrl('GET', - server.getUri('plain_text_with_etag_and_content_length')); - KrakenHttpOverrides.setContextHeader(req.headers, contextId); + var req = await httpClient.openUrl('GET', server.getUri('plain_text_with_etag_and_content_length')); + WebFHttpOverrides.setContextHeader(req.headers, contextId); var res = await req.close(); expect(String.fromCharCodes(await consolidateHttpClientResponseBytes(res)), 'CachedData'); @@ -199,8 +192,7 @@ void main() { }); test('Work with followRedirects: false', () async { - var req = await httpClient.openUrl('GET', - server.getUri('301')); + var req = await httpClient.openUrl('GET', server.getUri('301')); req.followRedirects = false; var res = await req.close(); @@ -209,9 +201,8 @@ void main() { test('Handle gzipped content', () async { // First request to save cache. - var req = await httpClient.openUrl('GET', - server.getUri('js_gzipped')); - KrakenHttpOverrides.setContextHeader(req.headers, contextId); + var req = await httpClient.openUrl('GET', server.getUri('js_gzipped')); + WebFHttpOverrides.setContextHeader(req.headers, contextId); var res = await req.close(); expect(String.fromCharCodes(await consolidateHttpClientResponseBytes(res))[0], '!'); diff --git a/webf/test/src/foundation/http_client.dart b/webf/test/src/foundation/http_client.dart index 8deafd0bd8..defcaa44d4 100644 --- a/webf/test/src/foundation/http_client.dart +++ b/webf/test/src/foundation/http_client.dart @@ -1,12 +1,16 @@ +/* + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + import 'dart:io'; import 'package:test/test.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/foundation.dart'; import '../../local_http_server.dart'; void main() { - group('HttpHeaders', () { test('Simple modification and toString', () async { HttpHeaders headers = createHttpHeaders(); @@ -37,7 +41,6 @@ void main() { expect(headers.toString(), ''); }); - test('Set', () async { HttpHeaders headers = createHttpHeaders(); headers.add('content-type', 'x-application/vnd.foo'); @@ -64,27 +67,24 @@ void main() { HttpClient httpClient = HttpClient(); test('Origin', () async { - var request = await httpClient.openUrl('POST', - server.getUri('plain_text')); - KrakenHttpOverrides.setContextHeader(request.headers, contextId); + var request = await httpClient.openUrl('POST', server.getUri('plain_text')); + WebFHttpOverrides.setContextHeader(request.headers, contextId); await request.close(); assert(request.headers.value('origin') != null); }); test('Referrer', () async { - var request = await httpClient.openUrl('POST', - server.getUri('plain_text')); - KrakenHttpOverrides.setContextHeader(request.headers, contextId); + var request = await httpClient.openUrl('POST', server.getUri('plain_text')); + WebFHttpOverrides.setContextHeader(request.headers, contextId); await request.close(); assert(request.headers.value('referer') != null); }); test('Large content', () async { - var request = await httpClient.openUrl('POST', - server.getUri('plain_text')); - KrakenHttpOverrides.setContextHeader(request.headers, contextId); + var request = await httpClient.openUrl('POST', server.getUri('plain_text')); + WebFHttpOverrides.setContextHeader(request.headers, contextId); // Mocked 3M file. var data = List.generate(3034764, (i) => i); request.headers.set(HttpHeaders.contentLengthHeader, data.length); diff --git a/webf/test/src/foundation/http_client_interceptor.dart b/webf/test/src/foundation/http_client_interceptor.dart index d7006dcd75..b7140d6580 100644 --- a/webf/test/src/foundation/http_client_interceptor.dart +++ b/webf/test/src/foundation/http_client_interceptor.dart @@ -1,8 +1,14 @@ +/* + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + import 'dart:convert'; import 'dart:io'; import 'package:test/test.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/foundation.dart'; + import '../../local_http_server.dart'; const int contextId = 2; @@ -13,9 +19,8 @@ void main() { HttpClient httpClient = HttpClient(); test('beforeRequest', () async { - var request = await httpClient.openUrl('GET', - server.getUri('json_with_content_length')); - KrakenHttpOverrides.setContextHeader(request.headers, contextId); + var request = await httpClient.openUrl('GET', server.getUri('json_with_content_length')); + WebFHttpOverrides.setContextHeader(request.headers, contextId); request.headers.add('x-test-id', 'beforeRequest-001'); var res = await request.close(); @@ -23,16 +28,13 @@ void main() { expect(jsonDecode(String.fromCharCodes(await res.single)), { 'method': 'GET', - 'data': { - 'userName': '12345' - } + 'data': {'userName': '12345'} }); }); test('afterResponse', () async { - var request = await httpClient.openUrl('GET', - server.getUri('json_with_content_length')); - KrakenHttpOverrides.setContextHeader(request.headers, contextId); + var request = await httpClient.openUrl('GET', server.getUri('json_with_content_length')); + WebFHttpOverrides.setContextHeader(request.headers, contextId); request.headers.add('x-test-id', 'afterResponse-001'); var response = await request.close(); @@ -40,9 +42,8 @@ void main() { }); test('shouldInterceptRequest', () async { - var request = await httpClient.openUrl('GET', - server.getUri('json_with_content_length')); - KrakenHttpOverrides.setContextHeader(request.headers, contextId); + var request = await httpClient.openUrl('GET', server.getUri('json_with_content_length')); + WebFHttpOverrides.setContextHeader(request.headers, contextId); request.headers.add('x-test-id', 'shouldInterceptRequest-001'); var response = await request.close(); @@ -61,13 +62,12 @@ class TestHttpClientInterceptor implements HttpClientInterceptor { } @override - Future afterResponse( - HttpClientRequest request, HttpClientResponse response) async { + Future afterResponse(HttpClientRequest request, HttpClientResponse response) async { if (request.headers.value('x-test-id') == 'afterResponse-001') { - return HttpClientStreamResponse(response, initialHeaders: createHttpHeaders( - initialHeaders: { - 'x-test-after-response': ['modified'], - })); + return HttpClientStreamResponse(response, + initialHeaders: createHttpHeaders(initialHeaders: { + 'x-test-after-response': ['modified'], + })); } return response; } diff --git a/webf/test/src/foundation/uri_parser.dart b/webf/test/src/foundation/uri_parser.dart index f247c41af1..6797a32fe3 100644 --- a/webf/test/src/foundation/uri_parser.dart +++ b/webf/test/src/foundation/uri_parser.dart @@ -1,5 +1,10 @@ +/* + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + import 'package:test/test.dart'; -import 'package:kraken/foundation.dart'; +import 'package:webf/foundation.dart'; void main() { group('UriParser', () { @@ -24,9 +29,7 @@ void main() { ]; for (var spec in resolveTests) { - String index = resolveTests.indexOf(spec) - .toString() - .padLeft(3, '0'); + String index = resolveTests.indexOf(spec).toString().padLeft(3, '0'); test('resolve $index', () { Uri base = Uri.parse(spec[0]); diff --git a/webf/test/src/gesture/scroll_physics.dart b/webf/test/src/gesture/scroll_physics.dart index edf05c1eb5..03d1bd2063 100644 --- a/webf/test/src/gesture/scroll_physics.dart +++ b/webf/test/src/gesture/scroll_physics.dart @@ -1,6 +1,12 @@ +/* + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + import 'dart:io' show Platform; -import 'package:kraken/src/gesture/scroll_physics.dart'; + import 'package:test/test.dart'; +import 'package:webf/src/gesture/scroll_physics.dart'; // Only for test. class TestScrollPhysics extends ScrollPhysics {} @@ -10,8 +16,8 @@ void main() { test('createScrollPhysics', () { ScrollPhysics scrollPhysics = ScrollPhysics.createScrollPhysics(); // In test env, that should be macos env. - expect(Platform.operatingSystem, 'macos'); - expect(scrollPhysics.runtimeType.toString(), 'BouncingScrollPhysics'); + expect(Platform.operatingSystem, 'linux'); + expect(scrollPhysics.runtimeType.toString(), 'ClampingScrollPhysics'); }); test('ScrollPhysics Factory', () { diff --git a/webf/test/src/module/fetch.dart b/webf/test/src/module/fetch.dart index 2041e34595..dec02c9d9c 100644 --- a/webf/test/src/module/fetch.dart +++ b/webf/test/src/module/fetch.dart @@ -1,4 +1,9 @@ -import 'package:kraken/module.dart'; +/* + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +import 'package:webf/module.dart'; import 'package:test/test.dart'; import '../../local_http_server.dart'; @@ -9,12 +14,8 @@ void main() { var server = LocalHttpServer.getInstance(); test('Custom Headers', () async { - var request = await fetchModule.getRequest( - server.getUri('plain_text'), - 'POST', - { 'foo': 'bar' }, - null - ); + var request = + await fetchModule.getRequest(server.getUri('plain_text'), 'POST', {'foo': 'bar'}, null); expect(request.uri.path, '/plain_text'); expect(request.method, 'POST'); expect(request.headers.value('foo'), 'bar'); diff --git a/webf/test/kraken_test.dart b/webf/test/webf_test.dart similarity index 87% rename from webf/test/kraken_test.dart rename to webf/test/webf_test.dart index 019a2fe165..2a0cf1c037 100644 --- a/webf/test/kraken_test.dart +++ b/webf/test/webf_test.dart @@ -1,28 +1,28 @@ +/* + * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + import 'dart:io'; -import 'package:flutter/widgets.dart'; import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:kraken/kraken.dart'; +import 'package:webf/webf.dart'; import 'local_http_server.dart'; - +import 'src/css/style_rule_parser.dart' as style_rule_parser; +import 'src/css/style_sheet_parser.dart' as style_sheet_parser; +import 'src/css/values.dart' as css_values; import 'src/foundation/bundle.dart' as bundle; import 'src/foundation/convert.dart' as convert; +import 'src/foundation/environment.dart' as environment; import 'src/foundation/http_cache.dart' as http_cache; import 'src/foundation/http_client.dart' as http_client; import 'src/foundation/http_client_interceptor.dart' as http_client_interceptor; -import 'src/foundation/environment.dart' as environment; import 'src/foundation/uri_parser.dart' as uri_parser; - -import 'src/module/fetch.dart' as fetch; - -import 'src/css/style_rule_parser.dart' as style_rule_parser; -import 'src/css/style_sheet_parser.dart' as style_sheet_parser; -import 'src/css/values.dart' as css_values; - import 'src/gesture/scroll_physics.dart' as scroll_physics; - +import 'src/module/fetch.dart' as fetch; // The main entry for kraken unit test. // Setup all common logic. @@ -36,11 +36,11 @@ void main() { print('Local HTTP Server started at ${httpServer.getUri()}'); // Inject a custom user agent, to avoid reading from bridge. - NavigatorModule.setCustomUserAgent('kraken/test'); + NavigatorModule.setCustomUserAgent('webf/test'); // Work around with path_provider. Directory tempDirectory = Directory('./temp'); - getKrakenMethodChannel().setMockMethodCallHandler((MethodCall methodCall) async { + getWebFMethodChannel().setMockMethodCallHandler((MethodCall methodCall) async { if (methodCall.method == 'getTemporaryDirectory') { return tempDirectory.path; }