From bf89458d032907e07404c2217318445db090f7bb Mon Sep 17 00:00:00 2001 From: Ismail Alam Khan Date: Sun, 7 Mar 2021 04:47:25 +0600 Subject: [PATCH 01/22] Migrated to null safety and made another branch --- example/analysis_options.yaml | 3 + .../res/drawable-v21/launch_background.xml | 12 + .../app/src/main/res/values-night/styles.xml | 18 + .../expander_fab_menu/expander_fab_menu.dart | 17 +- .../lib/demos/path_chart_stress/scene.dart | 29 -- example/linux/.gitignore | 1 + example/linux/CMakeLists.txt | 106 ++++++ example/linux/flutter/CMakeLists.txt | 91 +++++ .../flutter/generated_plugin_registrant.cc | 9 + .../flutter/generated_plugin_registrant.h | 13 + example/linux/flutter/generated_plugins.cmake | 15 + example/linux/main.cc | 6 + example/linux/my_application.cc | 104 ++++++ example/linux/my_application.h | 18 + example/pubspec.yaml | 4 +- example/windows/.gitignore | 17 + example/windows/CMakeLists.txt | 95 ++++++ example/windows/flutter/CMakeLists.txt | 103 ++++++ .../flutter/generated_plugin_registrant.cc | 9 + .../flutter/generated_plugin_registrant.h | 13 + .../windows/flutter/generated_plugins.cmake | 15 + example/windows/runner/CMakeLists.txt | 18 + example/windows/runner/Runner.rc | 121 +++++++ example/windows/runner/flutter_window.cpp | 64 ++++ example/windows/runner/flutter_window.h | 39 +++ example/windows/runner/main.cpp | 42 +++ example/windows/runner/resource.h | 16 + example/windows/runner/resources/app_icon.ico | Bin 0 -> 33772 bytes example/windows/runner/run_loop.cpp | 66 ++++ example/windows/runner/run_loop.h | 40 +++ example/windows/runner/runner.exe.manifest | 20 ++ example/windows/runner/utils.cpp | 64 ++++ example/windows/runner/utils.h | 19 ++ example/windows/runner/win32_window.cpp | 245 ++++++++++++++ example/windows/runner/win32_window.h | 98 ++++++ lib/src/core/scene_config.dart | 23 +- lib/src/core/scene_controller.dart | 48 +-- lib/src/core/scene_painter.dart | 45 +-- lib/src/debug/display_debugger.dart | 8 +- lib/src/display/bitmap.dart | 41 +-- lib/src/display/display_object.dart | 258 +++++++------- lib/src/display/display_object_container.dart | 19 +- lib/src/display/shape.dart | 32 +- lib/src/display/sprite.dart | 12 +- lib/src/display/stage.dart | 75 +++-- lib/src/display/text.dart | 115 ++++--- lib/src/events/callback_params.dart | 8 +- lib/src/events/keyboard_data.dart | 16 +- lib/src/events/mixins.dart | 55 +-- lib/src/events/mps.dart | 44 +-- lib/src/events/pointer_data.dart | 46 +-- lib/src/events/signal.dart | 24 +- lib/src/extensions/display_object.dart | 28 +- lib/src/geom/color_matrix.dart | 32 +- lib/src/geom/gxmatrix.dart | 74 ++--- lib/src/geom/gxrect.dart | 20 +- lib/src/input/input_converter.dart | 22 +- lib/src/input/keyboard_manager.dart | 12 +- lib/src/input/mouse.dart | 10 +- lib/src/input/pointer_manager.dart | 40 +-- lib/src/io/network_image_loader.dart | 116 ++++--- lib/src/io/resource_loader.dart | 53 ++- lib/src/log/trace.dart | 42 +-- lib/src/math.dart | 18 +- lib/src/render/filters/blur_filter.dart | 8 +- lib/src/render/filters/color_filter.dart | 2 +- lib/src/render/filters/composer_filter.dart | 2 +- lib/src/render/filters/dropshadow_filter.dart | 15 +- lib/src/render/filters/glow_filter.dart | 14 +- lib/src/render/graphics.dart | 314 +++++++++--------- lib/src/render/icon.dart | 50 +-- lib/src/render/movie_clip.dart | 16 +- lib/src/render/particles/simple_particle.dart | 46 ++- .../particles/simple_particle_system.dart | 48 +-- lib/src/render/svg_shape.dart | 42 +-- lib/src/textures/sub_texture.dart | 74 ++--- lib/src/textures/texture.dart | 46 +-- lib/src/textures/texture_atlas.dart | 75 ++--- lib/src/ticker/ticker.dart | 18 +- lib/src/tween/src/core/prop_tween.dart | 34 +- .../tween/src/extensions/common_types.dart | 8 +- .../tween/src/extensions/display_object.dart | 98 +++--- .../tween/src/extensions/filter_types.dart | 98 +++--- lib/src/tween/src/gtween.dart | 178 +++++----- lib/src/tween/src/lerps/common_lerps.dart | 8 +- lib/src/tween/src/mixins/tweenable.dart | 38 +-- lib/src/tween/src/wraps/common_wraps.dart | 173 +++++----- lib/src/tween/src/wraps/display_object.dart | 4 +- lib/src/tween/src/wraps/filter_wraps.dart | 110 +++--- lib/src/tween/src/wraps/geom_wraps.dart | 121 ++++--- lib/src/utils/context_utils.dart | 3 +- lib/src/utils/http/_http_io.dart | 15 +- lib/src/utils/http/_http_web.dart | 7 +- lib/src/utils/keyboard_util.dart | 46 ++- lib/src/utils/layout_utils.dart | 23 +- lib/src/utils/list_utils.dart | 10 +- lib/src/utils/matrix_utils.dart | 30 +- lib/src/utils/mixins.dart | 20 +- lib/src/utils/pools.dart | 6 +- lib/src/utils/string_utils.dart | 3 - lib/src/utils/texture_utils.dart | 34 +- lib/src/widgets/graphics_clipper.dart | 2 +- lib/src/widgets/graphx_widget.dart | 38 ++- lib/src/widgets/mps_widget.dart | 14 +- pubspec.lock | 64 ++-- pubspec.yaml | 8 +- 106 files changed, 3165 insertions(+), 1684 deletions(-) create mode 100644 example/analysis_options.yaml create mode 100644 example/android/app/src/main/res/drawable-v21/launch_background.xml create mode 100644 example/android/app/src/main/res/values-night/styles.xml create mode 100644 example/linux/.gitignore create mode 100644 example/linux/CMakeLists.txt create mode 100644 example/linux/flutter/CMakeLists.txt create mode 100644 example/linux/flutter/generated_plugin_registrant.cc create mode 100644 example/linux/flutter/generated_plugin_registrant.h create mode 100644 example/linux/flutter/generated_plugins.cmake create mode 100644 example/linux/main.cc create mode 100644 example/linux/my_application.cc create mode 100644 example/linux/my_application.h create mode 100644 example/windows/.gitignore create mode 100644 example/windows/CMakeLists.txt create mode 100644 example/windows/flutter/CMakeLists.txt create mode 100644 example/windows/flutter/generated_plugin_registrant.cc create mode 100644 example/windows/flutter/generated_plugin_registrant.h create mode 100644 example/windows/flutter/generated_plugins.cmake create mode 100644 example/windows/runner/CMakeLists.txt create mode 100644 example/windows/runner/Runner.rc create mode 100644 example/windows/runner/flutter_window.cpp create mode 100644 example/windows/runner/flutter_window.h create mode 100644 example/windows/runner/main.cpp create mode 100644 example/windows/runner/resource.h create mode 100644 example/windows/runner/resources/app_icon.ico create mode 100644 example/windows/runner/run_loop.cpp create mode 100644 example/windows/runner/run_loop.h create mode 100644 example/windows/runner/runner.exe.manifest create mode 100644 example/windows/runner/utils.cpp create mode 100644 example/windows/runner/utils.h create mode 100644 example/windows/runner/win32_window.cpp create mode 100644 example/windows/runner/win32_window.h diff --git a/example/analysis_options.yaml b/example/analysis_options.yaml new file mode 100644 index 0000000..26f7e43 --- /dev/null +++ b/example/analysis_options.yaml @@ -0,0 +1,3 @@ +analyzer: + errors: + todo: ignore diff --git a/example/android/app/src/main/res/drawable-v21/launch_background.xml b/example/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/example/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/example/android/app/src/main/res/values-night/styles.xml b/example/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..449a9f9 --- /dev/null +++ b/example/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/example/lib/demos/expander_fab_menu/expander_fab_menu.dart b/example/lib/demos/expander_fab_menu/expander_fab_menu.dart index bb9931a..4672c6a 100644 --- a/example/lib/demos/expander_fab_menu/expander_fab_menu.dart +++ b/example/lib/demos/expander_fab_menu/expander_fab_menu.dart @@ -21,6 +21,7 @@ class ExpanderFabMenu extends StatelessWidget { Icons.arrow_back, color: Colors.black, ), + onPressed: () {}, ), ), body: MyMenu( @@ -61,7 +62,6 @@ class _MyMenuState extends State with TickerProviderStateMixin { @override void initState() { super.initState(); - final dur = Duration(seconds: 1); // anim = AnimationController( // vsync: this, // duration: dur, @@ -173,12 +173,10 @@ class MyCoolMenuScene extends GSprite { button = MyButton(); } - GRect _position; double buttonY; GShape curtain; void updatePosition(GRect position) { - _position = position; button.x = position.x + position.width / 2; button.y = buttonY = position.y + position.height / 2; } @@ -220,7 +218,6 @@ class MyCoolMenuScene extends GSprite { } }, ); - } else { curtain.tween( duration: .5, @@ -288,22 +285,22 @@ class MyCoolMenuScene extends GSprite { doc: menuContainer, ); itm.alignPivot(); - itm.alpha=0; + itm.alpha = 0; itm.y = i * 34.0; items.add(itm); } menuContainer.alignPivot(); - menuContainer.setPosition(sw/2,sh/2); + menuContainer.setPosition(sw / 2, sh / 2); } void showMenuNow() { - var len = items.length ; + var len = items.length; for (var i = 0; i < items.length; ++i) { var itm = items[i]; itm.y = i * 34.0; - double ta = isOpen ? 1 : 0 ; - if( isOpen ){ - itm.tween(duration: .45, delay: .25 + ((len-1)-i) * .09, alpha: ta); + double ta = isOpen ? 1 : 0; + if (isOpen) { + itm.tween(duration: .45, delay: .25 + ((len - 1) - i) * .09, alpha: ta); } else { itm.tween(duration: .12, delay: 0, alpha: 0, overwrite: 1); } diff --git a/example/lib/demos/path_chart_stress/scene.dart b/example/lib/demos/path_chart_stress/scene.dart index abc4e92..cf80996 100644 --- a/example/lib/demos/path_chart_stress/scene.dart +++ b/example/lib/demos/path_chart_stress/scene.dart @@ -28,8 +28,6 @@ class PathChartScene extends GSprite { container.x = stage.stageWidth * .8; container.y = stage.stageHeight * .5; - var scaleR = 0.0; - var tw = container.x; stage.onEnterFrame.add((event) { // if (container.width > container.x + 100) { // tw = container.x + 100; @@ -87,8 +85,6 @@ class ChartSection extends GShape { stage.onEnterFrame.add((event) { if (++frameCount % 3 == 0) { addSlot(); - var maxPos = stage.stageWidth * .7; - var tempW = width; pivotX = width; // x = maxPos; // if (tempW > maxPos) { @@ -112,31 +108,6 @@ class ChartSection extends GShape { void addSlot() { ++numQuads; label.text = '$numQuads rects'; - var rects = List.generate(1, (index) { - var pw = Math.randomRange(20, 40); - var ph = Math.randomRange(20, 80); - var py = Math.randomRange( - lastRect.y - ph / 2, lastRect.y + lastRect.height / 2); - final rect = GRect(lastRect.right, py, pw, ph); - myPath = Path.combine( - PathOperation.union, - myPath, - Path()..addRect(rect.toNative()), - ); - - outputPath = myPath; - - // outputPath = Path.combine( - // PathOperation.intersect, - // outputPath, - // maskPath, - // ); - - // lastX += pw; - lastRect = rect; - return rect; - }); - graphics.clear(); graphics.beginFill(color.withOpacity(.3)); graphics.lineStyle(2, color); diff --git a/example/linux/.gitignore b/example/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/example/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/example/linux/CMakeLists.txt b/example/linux/CMakeLists.txt new file mode 100644 index 0000000..290c3e8 --- /dev/null +++ b/example/linux/CMakeLists.txt @@ -0,0 +1,106 @@ +cmake_minimum_required(VERSION 3.10) +project(runner LANGUAGES CXX) + +set(BINARY_NAME "example") +set(APPLICATION_ID "com.example.example") + +cmake_policy(SET CMP0063 NEW) + +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# 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() + +# 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/example/linux/flutter/CMakeLists.txt b/example/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..a1da1b9 --- /dev/null +++ b/example/linux/flutter/CMakeLists.txt @@ -0,0 +1,91 @@ +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) +pkg_check_modules(BLKID REQUIRED IMPORTED_TARGET blkid) +pkg_check_modules(LZMA REQUIRED IMPORTED_TARGET liblzma) + +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 + PkgConfig::BLKID + PkgConfig::LZMA +) +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" + linux-x64 ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/example/linux/flutter/generated_plugin_registrant.cc b/example/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..d38195a --- /dev/null +++ b/example/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,9 @@ +// +// Generated file. Do not edit. +// + +#include "generated_plugin_registrant.h" + + +void fl_register_plugins(FlPluginRegistry* registry) { +} diff --git a/example/linux/flutter/generated_plugin_registrant.h b/example/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..9bf7478 --- /dev/null +++ b/example/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,13 @@ +// +// Generated file. Do not edit. +// + +#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/example/linux/flutter/generated_plugins.cmake b/example/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..51436ae --- /dev/null +++ b/example/linux/flutter/generated_plugins.cmake @@ -0,0 +1,15 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_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) diff --git a/example/linux/main.cc b/example/linux/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/example/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/example/linux/my_application.cc b/example/linux/my_application.cc new file mode 100644 index 0000000..543eaca --- /dev/null +++ b/example/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, "example"); + 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, "example"); + } + + gtk_window_set_default_size(window, 1280, 720); + 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, + nullptr)); +} diff --git a/example/linux/my_application.h b/example/linux/my_application.h new file mode 100644 index 0000000..72271d5 --- /dev/null +++ b/example/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/example/pubspec.yaml b/example/pubspec.yaml index 10259a4..0ffa6c9 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -12,7 +12,7 @@ dependencies: flutter: sdk: flutter flutter_icons: ^1.1.0 - flutter_svg: 0.18.1 + flutter_svg: ^0.21.0-nullsafety.0 graphx: path: ../ dev_dependencies: @@ -39,4 +39,4 @@ flutter: fonts: - family: pressstart fonts: - - asset: assets/fonts/pressstart.ttf \ No newline at end of file + - asset: assets/fonts/pressstart.ttf diff --git a/example/windows/.gitignore b/example/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/example/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/example/windows/CMakeLists.txt b/example/windows/CMakeLists.txt new file mode 100644 index 0000000..abf9040 --- /dev/null +++ b/example/windows/CMakeLists.txt @@ -0,0 +1,95 @@ +cmake_minimum_required(VERSION 3.15) +project(example LANGUAGES CXX) + +set(BINARY_NAME "example") + +cmake_policy(SET CMP0063 NEW) + +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Configure build options. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + 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() +endif() + +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") + +# Flutter library and tool build rules. +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build +add_subdirectory("runner") + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +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() + +# 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. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/example/windows/flutter/CMakeLists.txt b/example/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..b02c548 --- /dev/null +++ b/example/windows/flutter/CMakeLists.txt @@ -0,0 +1,103 @@ +cmake_minimum_required(VERSION 3.15) + +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. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# 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/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app 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. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + windows-x64 $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/example/windows/flutter/generated_plugin_registrant.cc b/example/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..4bfa0f3 --- /dev/null +++ b/example/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,9 @@ +// +// Generated file. Do not edit. +// + +#include "generated_plugin_registrant.h" + + +void RegisterPlugins(flutter::PluginRegistry* registry) { +} diff --git a/example/windows/flutter/generated_plugin_registrant.h b/example/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..9846246 --- /dev/null +++ b/example/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,13 @@ +// +// Generated file. Do not edit. +// + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/example/windows/flutter/generated_plugins.cmake b/example/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..4d10c25 --- /dev/null +++ b/example/windows/flutter/generated_plugins.cmake @@ -0,0 +1,15 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows 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) diff --git a/example/windows/runner/CMakeLists.txt b/example/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..977e38b --- /dev/null +++ b/example/windows/runner/CMakeLists.txt @@ -0,0 +1,18 @@ +cmake_minimum_required(VERSION 3.15) +project(runner LANGUAGES CXX) + +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "run_loop.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) +apply_standard_settings(${BINARY_NAME}) +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/example/windows/runner/Runner.rc b/example/windows/runner/Runner.rc new file mode 100644 index 0000000..51812dc --- /dev/null +++ b/example/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#ifdef FLUTTER_BUILD_NUMBER +#define VERSION_AS_NUMBER FLUTTER_BUILD_NUMBER +#else +#define VERSION_AS_NUMBER 1,0,0 +#endif + +#ifdef FLUTTER_BUILD_NAME +#define VERSION_AS_STRING #FLUTTER_BUILD_NAME +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "A new Flutter project." "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "example" "\0" + VALUE "LegalCopyright", "Copyright (C) 2021 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "example.exe" "\0" + VALUE "ProductName", "example" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/example/windows/runner/flutter_window.cpp b/example/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..c422723 --- /dev/null +++ b/example/windows/runner/flutter_window.cpp @@ -0,0 +1,64 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(RunLoop* run_loop, + const flutter::DartProject& project) + : run_loop_(run_loop), project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + run_loop_->RegisterFlutterInstance(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + run_loop_->UnregisterFlutterInstance(flutter_controller_->engine()); + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opporutunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/example/windows/runner/flutter_window.h b/example/windows/runner/flutter_window.h new file mode 100644 index 0000000..b663ddd --- /dev/null +++ b/example/windows/runner/flutter_window.h @@ -0,0 +1,39 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "run_loop.h" +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow driven by the |run_loop|, hosting a + // Flutter view running |project|. + explicit FlutterWindow(RunLoop* run_loop, + const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The run loop driving events for this window. + RunLoop* run_loop_; + + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/example/windows/runner/main.cpp b/example/windows/runner/main.cpp new file mode 100644 index 0000000..b637809 --- /dev/null +++ b/example/windows/runner/main.cpp @@ -0,0 +1,42 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "run_loop.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + RunLoop run_loop; + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(&run_loop, project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.CreateAndShow(L"example", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + run_loop.Run(); + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/example/windows/runner/resource.h b/example/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/example/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/example/windows/runner/resources/app_icon.ico b/example/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000000000000000000000000000000000000..c04e20caf6370ebb9253ad831cc31de4a9c965f6 GIT binary patch literal 33772 zcmeHQc|26z|35SKE&G-*mXah&B~fFkXr)DEO&hIfqby^T&>|8^_Ub8Vp#`BLl3lbZ zvPO!8k!2X>cg~Elr=IVxo~J*a`+9wR=A83c-k-DFd(XM&UI1VKCqM@V;DDtJ09WB} zRaHKiW(GT00brH|0EeTeKVbpbGZg?nK6-j827q-+NFM34gXjqWxJ*a#{b_apGN<-L_m3#8Z26atkEn& ze87Bvv^6vVmM+p+cQ~{u%=NJF>#(d;8{7Q{^rWKWNtf14H}>#&y7$lqmY6xmZryI& z($uy?c5-+cPnt2%)R&(KIWEXww>Cnz{OUpT>W$CbO$h1= z#4BPMkFG1Y)x}Ui+WXr?Z!w!t_hjRq8qTaWpu}FH{MsHlU{>;08goVLm{V<&`itk~ zE_Ys=D(hjiy+5=?=$HGii=Y5)jMe9|wWoD_K07(}edAxh`~LBorOJ!Cf@f{_gNCC| z%{*04ViE!#>@hc1t5bb+NO>ncf@@Dv01K!NxH$3Eg1%)|wLyMDF8^d44lV!_Sr}iEWefOaL z8f?ud3Q%Sen39u|%00W<#!E=-RpGa+H8}{ulxVl4mwpjaU+%2pzmi{3HM)%8vb*~-M9rPUAfGCSos8GUXp02|o~0BTV2l#`>>aFV&_P$ejS;nGwSVP8 zMbOaG7<7eKD>c12VdGH;?2@q7535sa7MN*L@&!m?L`ASG%boY7(&L5imY#EQ$KrBB z4@_tfP5m50(T--qv1BJcD&aiH#b-QC>8#7Fx@3yXlonJI#aEIi=8&ChiVpc#N=5le zM*?rDIdcpawoc5kizv$GEjnveyrp3sY>+5_R5;>`>erS%JolimF=A^EIsAK zsPoVyyUHCgf0aYr&alx`<)eb6Be$m&`JYSuBu=p8j%QlNNp$-5C{b4#RubPb|CAIS zGE=9OFLP7?Hgc{?k45)84biT0k&-C6C%Q}aI~q<(7BL`C#<6HyxaR%!dFx7*o^laG z=!GBF^cwK$IA(sn9y6>60Rw{mYRYkp%$jH z*xQM~+bp)G$_RhtFPYx2HTsWk80+p(uqv9@I9)y{b$7NK53rYL$ezbmRjdXS?V}fj zWxX_feWoLFNm3MG7pMUuFPs$qrQWO9!l2B(SIuy2}S|lHNbHzoE+M2|Zxhjq9+Ws8c{*}x^VAib7SbxJ*Q3EnY5lgI9 z=U^f3IW6T=TWaVj+2N%K3<%Un;CF(wUp`TC&Y|ZjyFu6co^uqDDB#EP?DV5v_dw~E zIRK*BoY9y-G_ToU2V_XCX4nJ32~`czdjT!zwme zGgJ0nOk3U4@IE5JwtM}pwimLjk{ln^*4HMU%Fl4~n(cnsLB}Ja-jUM>xIB%aY;Nq8 z)Fp8dv1tkqKanv<68o@cN|%thj$+f;zGSO7H#b+eMAV8xH$hLggtt?O?;oYEgbq@= zV(u9bbd12^%;?nyk6&$GPI%|+<_mEpJGNfl*`!KV;VfmZWw{n{rnZ51?}FDh8we_L z8OI9nE31skDqJ5Oa_ybn7|5@ui>aC`s34p4ZEu6-s!%{uU45$Zd1=p$^^dZBh zu<*pDDPLW+c>iWO$&Z_*{VSQKg7=YEpS3PssPn1U!lSm6eZIho*{@&20e4Y_lRklKDTUCKI%o4Pc<|G^Xgu$J^Q|B87U;`c1zGwf^-zH*VQ^x+i^OUWE0yd z;{FJq)2w!%`x7yg@>uGFFf-XJl4H`YtUG%0slGKOlXV`q?RP>AEWg#x!b{0RicxGhS!3$p7 zij;{gm!_u@D4$Ox%>>bPtLJ> zwKtYz?T_DR1jN>DkkfGU^<#6sGz|~p*I{y`aZ>^Di#TC|Z!7j_O1=Wo8thuit?WxR zh9_S>kw^{V^|g}HRUF=dcq>?q(pHxw!8rx4dC6vbQVmIhmICF#zU!HkHpQ>9S%Uo( zMw{eC+`&pb=GZRou|3;Po1}m46H6NGd$t<2mQh}kaK-WFfmj_66_17BX0|j-E2fe3Jat}ijpc53 zJV$$;PC<5aW`{*^Z6e5##^`Ed#a0nwJDT#Qq~^e8^JTA=z^Kl>La|(UQ!bI@#ge{Dzz@61p-I)kc2?ZxFt^QQ}f%ldLjO*GPj(5)V9IyuUakJX=~GnTgZ4$5!3E=V#t`yOG4U z(gphZB6u2zsj=qNFLYShhg$}lNpO`P9xOSnO*$@@UdMYES*{jJVj|9z-}F^riksLK zbsU+4-{281P9e2UjY6tse^&a)WM1MFw;p#_dHhWI7p&U*9TR0zKdVuQed%6{otTsq z$f~S!;wg#Bd9kez=Br{m|66Wv z#g1xMup<0)H;c2ZO6su_ii&m8j&+jJz4iKnGZ&wxoQX|5a>v&_e#6WA!MB_4asTxLRGQCC5cI(em z%$ZfeqP>!*q5kU>a+BO&ln=4Jm>Ef(QE8o&RgLkk%2}4Tf}U%IFP&uS7}&|Q-)`5< z+e>;s#4cJ-z%&-^&!xsYx777Wt(wZY9(3(avmr|gRe4cD+a8&!LY`1^T?7x{E<=kdY9NYw>A;FtTvQ=Y&1M%lyZPl$ss1oY^Sl8we}n}Aob#6 zl4jERwnt9BlSoWb@3HxYgga(752Vu6Y)k4yk9u~Kw>cA5&LHcrvn1Y-HoIuFWg~}4 zEw4bR`mXZQIyOAzo)FYqg?$5W<;^+XX%Uz61{-L6@eP|lLH%|w?g=rFc;OvEW;^qh z&iYXGhVt(G-q<+_j}CTbPS_=K>RKN0&;dubh0NxJyDOHFF;<1k!{k#7b{|Qok9hac z;gHz}6>H6C6RnB`Tt#oaSrX0p-j-oRJ;_WvS-qS--P*8}V943RT6kou-G=A+7QPGQ z!ze^UGxtW3FC0$|(lY9^L!Lx^?Q8cny(rR`es5U;-xBhphF%_WNu|aO<+e9%6LuZq zt(0PoagJG<%hyuf;te}n+qIl_Ej;czWdc{LX^pS>77s9t*2b4s5dvP_!L^3cwlc)E!(!kGrg~FescVT zZCLeua3f4;d;Tk4iXzt}g}O@nlK3?_o91_~@UMIl?@77Qc$IAlLE95#Z=TES>2E%z zxUKpK{_HvGF;5%Q7n&vA?`{%8ohlYT_?(3A$cZSi)MvIJygXD}TS-3UwyUxGLGiJP znblO~G|*uA^|ac8E-w#}uBtg|s_~s&t>-g0X%zIZ@;o_wNMr_;{KDg^O=rg`fhDZu zFp(VKd1Edj%F zWHPl+)FGj%J1BO3bOHVfH^3d1F{)*PL&sRX`~(-Zy3&9UQX)Z;c51tvaI2E*E7!)q zcz|{vpK7bjxix(k&6=OEIBJC!9lTkUbgg?4-yE{9+pFS)$Ar@vrIf`D0Bnsed(Cf? zObt2CJ>BKOl>q8PyFO6w)+6Iz`LW%T5^R`U_NIW0r1dWv6OY=TVF?N=EfA(k(~7VBW(S;Tu5m4Lg8emDG-(mOSSs=M9Q&N8jc^Y4&9RqIsk(yO_P(mcCr}rCs%1MW1VBrn=0-oQN(Xj!k%iKV zb%ricBF3G4S1;+8lzg5PbZ|$Se$)I=PwiK=cDpHYdov2QO1_a-*dL4KUi|g&oh>(* zq$<`dQ^fat`+VW?m)?_KLn&mp^-@d=&7yGDt<=XwZZC=1scwxO2^RRI7n@g-1o8ps z)&+et_~)vr8aIF1VY1Qrq~Xe``KJrQSnAZ{CSq3yP;V*JC;mmCT6oRLSs7=GA?@6g zUooM}@tKtx(^|aKK8vbaHlUQqwE0}>j&~YlN3H#vKGm@u)xxS?n9XrOWUfCRa< z`20Fld2f&;gg7zpo{Adh+mqNntMc-D$N^yWZAZRI+u1T1zWHPxk{+?vcS1D>08>@6 zLhE@`gt1Y9mAK6Z4p|u(5I%EkfU7rKFSM=E4?VG9tI;a*@?6!ey{lzN5=Y-!$WFSe z&2dtO>^0@V4WRc#L&P%R(?@KfSblMS+N+?xUN$u3K4Ys%OmEh+tq}fnU}i>6YHM?< zlnL2gl~sF!j!Y4E;j3eIU-lfa`RsOL*Tt<%EFC0gPzoHfNWAfKFIKZN8}w~(Yi~=q z>=VNLO2|CjkxP}RkutxjV#4fWYR1KNrPYq5ha9Wl+u>ipsk*I(HS@iLnmGH9MFlTU zaFZ*KSR0px>o+pL7BbhB2EC1%PJ{67_ z#kY&#O4@P=OV#-79y_W>Gv2dxL*@G7%LksNSqgId9v;2xJ zrh8uR!F-eU$NMx@S*+sk=C~Dxr9Qn7TfWnTupuHKuQ$;gGiBcU>GF5sWx(~4IP3`f zWE;YFO*?jGwYh%C3X<>RKHC-DZ!*r;cIr}GLOno^3U4tFSSoJp%oHPiSa%nh=Zgn% z14+8v@ygy0>UgEN1bczD6wK45%M>psM)y^)IfG*>3ItX|TzV*0i%@>L(VN!zdKb8S?Qf7BhjNpziA zR}?={-eu>9JDcl*R=OP9B8N$IcCETXah9SUDhr{yrld{G;PnCWRsPD7!eOOFBTWUQ=LrA_~)mFf&!zJX!Oc-_=kT<}m|K52 z)M=G#;p;Rdb@~h5D{q^K;^fX-m5V}L%!wVC2iZ1uu401Ll}#rocTeK|7FAeBRhNdQ zCc2d^aQnQp=MpOmak60N$OgS}a;p(l9CL`o4r(e-nN}mQ?M&isv-P&d$!8|1D1I(3-z!wi zTgoo)*Mv`gC?~bm?S|@}I|m-E2yqPEvYybiD5azInexpK8?9q*$9Yy9-t%5jU8~ym zgZDx>!@ujQ=|HJnwp^wv-FdD{RtzO9SnyfB{mH_(c!jHL*$>0o-(h(eqe*ZwF6Lvu z{7rkk%PEqaA>o+f{H02tzZ@TWy&su?VNw43! z-X+rN`6llvpUms3ZiSt)JMeztB~>9{J8SPmYs&qohxdYFi!ra8KR$35Zp9oR)eFC4 zE;P31#3V)n`w$fZ|4X-|%MX`xZDM~gJyl2W;O$H25*=+1S#%|53>|LyH za@yh+;325%Gq3;J&a)?%7X%t@WXcWL*BaaR*7UEZad4I8iDt7^R_Fd`XeUo256;sAo2F!HcIQKk;h})QxEsPE5BcKc7WyerTchgKmrfRX z!x#H_%cL#B9TWAqkA4I$R^8{%do3Y*&(;WFmJ zU7Dih{t1<{($VtJRl9|&EB?|cJ)xse!;}>6mSO$o5XIx@V|AA8ZcoD88ZM?C*;{|f zZVmf94_l1OmaICt`2sTyG!$^UeTHx9YuUP!omj(r|7zpm5475|yXI=rR>>fteLI+| z)MoiGho0oEt=*J(;?VY0QzwCqw@cVm?d7Y!z0A@u#H?sCJ*ecvyhj& z-F77lO;SH^dmf?L>3i>?Z*U}Em4ZYV_CjgfvzYsRZ+1B!Uo6H6mbS<-FFL`ytqvb& zE7+)2ahv-~dz(Hs+f})z{*4|{)b=2!RZK;PWwOnO=hG7xG`JU5>bAvUbdYd_CjvtHBHgtGdlO+s^9ca^Bv3`t@VRX2_AD$Ckg36OcQRF zXD6QtGfHdw*hx~V(MV-;;ZZF#dJ-piEF+s27z4X1qi5$!o~xBnvf=uopcn7ftfsZc zy@(PuOk`4GL_n(H9(E2)VUjqRCk9kR?w)v@xO6Jm_Mx})&WGEl=GS0#)0FAq^J*o! zAClhvoTsNP*-b~rN{8Yym3g{01}Ep^^Omf=SKqvN?{Q*C4HNNAcrowIa^mf+3PRy! z*_G-|3i8a;+q;iP@~Of_$(vtFkB8yOyWt2*K)vAn9El>=D;A$CEx6b*XF@4y_6M+2 zpeW`RHoI_p(B{%(&jTHI->hmNmZjHUj<@;7w0mx3&koy!2$@cfX{sN19Y}euYJFn& z1?)+?HCkD0MRI$~uB2UWri})0bru_B;klFdwsLc!ne4YUE;t41JqfG# zZJq6%vbsdx!wYeE<~?>o4V`A3?lN%MnKQ`z=uUivQN^vzJ|C;sdQ37Qn?;lpzg})y z)_2~rUdH}zNwX;Tp0tJ78+&I=IwOQ-fl30R79O8@?Ub8IIA(6I`yHn%lARVL`%b8+ z4$8D-|MZZWxc_)vu6@VZN!HsI$*2NOV&uMxBNzIbRgy%ob_ zhwEH{J9r$!dEix9XM7n&c{S(h>nGm?el;gaX0@|QnzFD@bne`el^CO$yXC?BDJ|Qg z+y$GRoR`?ST1z^e*>;!IS@5Ovb7*RlN>BV_UC!7E_F;N#ky%1J{+iixp(dUJj93aK zzHNN>R-oN7>kykHClPnoPTIj7zc6KM(Pnlb(|s??)SMb)4!sMHU^-ntJwY5Big7xv zb1Ew`Xj;|D2kzGja*C$eS44(d&RMU~c_Y14V9_TLTz0J#uHlsx`S6{nhsA0dWZ#cG zJ?`fO50E>*X4TQLv#nl%3GOk*UkAgt=IY+u0LNXqeln3Z zv$~&Li`ZJOKkFuS)dJRA>)b_Da%Q~axwA_8zNK{BH{#}#m}zGcuckz}riDE-z_Ms> zR8-EqAMcfyGJCtvTpaUVQtajhUS%c@Yj}&6Zz;-M7MZzqv3kA7{SuW$oW#=0az2wQ zg-WG@Vb4|D`pl~Il54N7Hmsauc_ne-a!o5#j3WaBBh@Wuefb!QJIOn5;d)%A#s+5% zuD$H=VNux9bE-}1&bcYGZ+>1Fo;3Z@e&zX^n!?JK*adSbONm$XW9z;Q^L>9U!}Toj2WdafJ%oL#h|yWWwyAGxzfrAWdDTtaKl zK4`5tDpPg5>z$MNv=X0LZ0d6l%D{(D8oT@+w0?ce$DZ6pv>{1&Ok67Ix1 zH}3=IEhPJEhItCC8E=`T`N5(k?G=B4+xzZ?<4!~ ze~z6Wk9!CHTI(0rLJ4{JU?E-puc;xusR?>G?;4vt;q~iI9=kDL=z0Rr%O$vU`30X$ zDZRFyZ`(omOy@u|i6h;wtJlP;+}$|Ak|k2dea7n?U1*$T!sXqqOjq^NxLPMmk~&qI zYg0W?yK8T(6+Ea+$YyspKK?kP$+B`~t3^Pib_`!6xCs32!i@pqXfFV6PmBIR<-QW= zN8L{pt0Vap0x`Gzn#E@zh@H)0FfVfA_Iu4fjYZ+umO1LXIbVc$pY+E234u)ttcrl$ z>s92z4vT%n6cMb>=XT6;l0+9e(|CZG)$@C7t7Z7Ez@a)h)!hyuV&B5K%%)P5?Lk|C zZZSVzdXp{@OXSP0hoU-gF8s8Um(#xzjP2Vem zec#-^JqTa&Y#QJ>-FBxd7tf`XB6e^JPUgagB8iBSEps;92KG`!#mvVcPQ5yNC-GEG zTiHEDYfH+0O15}r^+ z#jxj=@x8iNHWALe!P3R67TwmhItn**0JwnzSV2O&KE8KcT+0hWH^OPD1pwiuyx=b@ zNf5Jh0{9X)8;~Es)$t@%(3!OnbY+`@?i{mGX7Yy}8T_*0a6g;kaFPq;*=px5EhO{Cp%1kI<0?*|h8v!6WnO3cCJRF2-CRrU3JiLJnj@6;L)!0kWYAc_}F{2P))3HmCrz zQ&N&gE70;`!6*eJ4^1IR{f6j4(-l&X!tjHxkbHA^Zhrnhr9g{exN|xrS`5Pq=#Xf& zG%P=#ra-TyVFfgW%cZo5OSIwFL9WtXAlFOa+ubmI5t*3=g#Y zF%;70p5;{ZeFL}&}yOY1N1*Q;*<(kTB!7vM$QokF)yr2FlIU@$Ph58$Bz z0J?xQG=MlS4L6jA22eS42g|9*9pX@$#*sUeM(z+t?hr@r5J&D1rx}2pW&m*_`VDCW zUYY@v-;bAO0HqoAgbbiGGC<=ryf96}3pouhy3XJrX+!!u*O_>Si38V{uJmQ&USptX zKp#l(?>%^7;2%h(q@YWS#9;a!JhKlkR#Vd)ERILlgu!Hr@jA@V;sk4BJ-H#p*4EqC zDGjC*tl=@3Oi6)Bn^QwFpul18fpkbpg0+peH$xyPBqb%`$OUhPKyWb32o7clB*9Z< zN=i~NLjavrLtwgJ01bufP+>p-jR2I95|TpmKpQL2!oV>g(4RvS2pK4*ou%m(h6r3A zX#s&`9LU1ZG&;{CkOK!4fLDTnBys`M!vuz>Q&9OZ0hGQl!~!jSDg|~s*w52opC{sB ze|Cf2luD(*G13LcOAGA!s2FjSK8&IE5#W%J25w!vM0^VyQM!t)inj&RTiJ!wXzFgz z3^IqzB7I0L$llljsGq})thBy9UOyjtFO_*hYM_sgcMk>44jeH0V1FDyELc{S1F-;A zS;T^k^~4biG&V*Irq}O;e}j$$+E_#G?HKIn05iP3j|87TkGK~SqG!-KBg5+mN(aLm z8ybhIM`%C19UX$H$KY6JgXbY$0AT%rEpHC;u`rQ$Y=rxUdsc5*Kvc8jaYaO$^)cI6){P6K0r)I6DY4Wr4&B zLQUBraey#0HV|&c4v7PVo3n$zHj99(TZO^3?Ly%C4nYvJTL9eLBLHsM3WKKD>5!B` zQ=BsR3aR6PD(Fa>327E2HAu5TM~Wusc!)>~(gM)+3~m;92Jd;FnSib=M5d6;;5{%R zb4V7DEJ0V!CP-F*oU?gkc>ksUtAYP&V4ND5J>J2^jt*vcFflQWCrB&fLdT%O59PVJ zhid#toR=FNgD!q3&r8#wEBr`!wzvQu5zX?Q>nlSJ4i@WC*CN*-xU66F^V5crWevQ9gsq$I@z1o(a=k7LL~ z7m_~`o;_Ozha1$8Q}{WBehvAlO4EL60y5}8GDrZ< zXh&F}71JbW2A~8KfEWj&UWV#4+Z4p`b{uAj4&WC zha`}X@3~+Iz^WRlOHU&KngK>#j}+_o@LdBC1H-`gT+krWX3-;!)6?{FBp~%20a}FL zFP9%Emqcwa#(`=G>BBZ0qZDQhmZKJg_g8<=bBFKWr!dyg(YkpE+|R*SGpDVU!+VlU zFC54^DLv}`qa%49T>nNiA9Q7Ips#!Xx90tCU2gvK`(F+GPcL=J^>No{)~we#o@&mUb6c$ zCc*<|NJBk-#+{j9xkQ&ujB zI~`#kN~7W!f*-}wkG~Ld!JqZ@tK}eeSnsS5J1fMFXm|`LJx&}5`@dK3W^7#Wnm+_P zBZkp&j1fa2Y=eIjJ0}gh85jt43kaIXXv?xmo@eHrka!Z|vQv12HN#+!I5E z`(fbuW>gFiJL|uXJ!vKt#z3e3HlVdboH7;e#i3(2<)Fg-I@BR!qY#eof3MFZ&*Y@l zI|KJf&ge@p2Dq09Vu$$Qxb7!}{m-iRk@!)%KL)txi3;~Z4Pb}u@GsW;ELiWeG9V51 znX#}B&4Y2E7-H=OpNE@q{%hFLxwIpBF2t{vPREa8_{linXT;#1vMRWjOzLOP$-hf( z>=?$0;~~PnkqY;~K{EM6Vo-T(0K{A0}VUGmu*hR z{tw3hvBN%N3G3Yw`X5Te+F{J`(3w1s3-+1EbnFQKcrgrX1Jqvs@ADGe%M0s$EbK$$ zK)=y=upBc6SjGYAACCcI=Y*6Fi8_jgwZlLxD26fnQfJmb8^gHRN5(TemhX@0e=vr> zg`W}6U>x6VhoA3DqsGGD9uL1DhB3!OXO=k}59TqD@(0Nb{)Ut_luTioK_>7wjc!5C zIr@w}b`Fez3)0wQfKl&bae7;PcTA7%?f2xucM0G)wt_KO!Ewx>F~;=BI0j=Fb4>pp zv}0R^xM4eti~+^+gE$6b81p(kwzuDti(-K9bc|?+pJEl@H+jSYuxZQV8rl8 zjp@M{#%qItIUFN~KcO9Hed*`$5A-2~pAo~K&<-Q+`9`$CK>rzqAI4w~$F%vs9s{~x zg4BP%Gy*@m?;D6=SRX?888Q6peF@_4Z->8wAH~Cn!R$|Hhq2cIzFYqT_+cDourHbY z0qroxJnrZ4Gh+Ay+F`_c%+KRT>y3qw{)89?=hJ@=KO=@ep)aBJ$c!JHfBMJpsP*3G za7|)VJJ8B;4?n{~ldJF7%jmb`-ftIvNd~ekoufG(`K(3=LNc;HBY& z(lp#q8XAD#cIf}k49zX_i`*fO+#!zKA&%T3j@%)R+#yag067CU%yUEe47>wzGU8^` z1EXFT^@I!{J!F8!X?S6ph8J=gUi5tl93*W>7}_uR<2N2~e}FaG?}KPyugQ=-OGEZs z!GBoyYY+H*ANn4?Z)X4l+7H%`17i5~zRlRIX?t)6_eu=g2Q`3WBhxSUeea+M-S?RL zX9oBGKn%a!H+*hx4d2(I!gsi+@SQK%<{X22M~2tMulJoa)0*+z9=-YO+;DFEm5eE1U9b^B(Z}2^9!Qk`!A$wUE z7$Ar5?NRg2&G!AZqnmE64eh^Anss3i!{}%6@Et+4rr!=}!SBF8eZ2*J3ujCWbl;3; z48H~goPSv(8X61fKKdpP!Z7$88NL^Z?j`!^*I?-P4X^pMxyWz~@$(UeAcTSDd(`vO z{~rc;9|GfMJcApU3k}22a!&)k4{CU!e_ny^Y3cO;tOvOMKEyWz!vG(Kp*;hB?d|R3`2X~=5a6#^o5@qn?J-bI8Ppip{-yG z!k|VcGsq!jF~}7DMr49Wap-s&>o=U^T0!Lcy}!(bhtYsPQy z4|EJe{12QL#=c(suQ89Mhw9<`bui%nx7Nep`C&*M3~vMEACmcRYYRGtANq$F%zh&V zc)cEVeHz*Z1N)L7k-(k3np#{GcDh2Q@ya0YHl*n7fl*ZPAsbU-a94MYYtA#&!c`xGIaV;yzsmrjfieTEtqB_WgZp2*NplHx=$O{M~2#i_vJ{ps-NgK zQsxKK_CBM2PP_je+Xft`(vYfXXgIUr{=PA=7a8`2EHk)Ym2QKIforz# tySWtj{oF3N9@_;i*Fv5S)9x^z=nlWP>jpp-9)52ZmLVA=i*%6g{{fxOO~wEK literal 0 HcmV?d00001 diff --git a/example/windows/runner/run_loop.cpp b/example/windows/runner/run_loop.cpp new file mode 100644 index 0000000..2d6636a --- /dev/null +++ b/example/windows/runner/run_loop.cpp @@ -0,0 +1,66 @@ +#include "run_loop.h" + +#include + +#include + +RunLoop::RunLoop() {} + +RunLoop::~RunLoop() {} + +void RunLoop::Run() { + bool keep_running = true; + TimePoint next_flutter_event_time = TimePoint::clock::now(); + while (keep_running) { + std::chrono::nanoseconds wait_duration = + std::max(std::chrono::nanoseconds(0), + next_flutter_event_time - TimePoint::clock::now()); + ::MsgWaitForMultipleObjects( + 0, nullptr, FALSE, static_cast(wait_duration.count() / 1000), + QS_ALLINPUT); + bool processed_events = false; + MSG message; + // All pending Windows messages must be processed; MsgWaitForMultipleObjects + // won't return again for items left in the queue after PeekMessage. + while (::PeekMessage(&message, nullptr, 0, 0, PM_REMOVE)) { + processed_events = true; + if (message.message == WM_QUIT) { + keep_running = false; + break; + } + ::TranslateMessage(&message); + ::DispatchMessage(&message); + // Allow Flutter to process messages each time a Windows message is + // processed, to prevent starvation. + next_flutter_event_time = + std::min(next_flutter_event_time, ProcessFlutterMessages()); + } + // If the PeekMessage loop didn't run, process Flutter messages. + if (!processed_events) { + next_flutter_event_time = + std::min(next_flutter_event_time, ProcessFlutterMessages()); + } + } +} + +void RunLoop::RegisterFlutterInstance( + flutter::FlutterEngine* flutter_instance) { + flutter_instances_.insert(flutter_instance); +} + +void RunLoop::UnregisterFlutterInstance( + flutter::FlutterEngine* flutter_instance) { + flutter_instances_.erase(flutter_instance); +} + +RunLoop::TimePoint RunLoop::ProcessFlutterMessages() { + TimePoint next_event_time = TimePoint::max(); + for (auto instance : flutter_instances_) { + std::chrono::nanoseconds wait_duration = instance->ProcessMessages(); + if (wait_duration != std::chrono::nanoseconds::max()) { + next_event_time = + std::min(next_event_time, TimePoint::clock::now() + wait_duration); + } + } + return next_event_time; +} diff --git a/example/windows/runner/run_loop.h b/example/windows/runner/run_loop.h new file mode 100644 index 0000000..000d362 --- /dev/null +++ b/example/windows/runner/run_loop.h @@ -0,0 +1,40 @@ +#ifndef RUNNER_RUN_LOOP_H_ +#define RUNNER_RUN_LOOP_H_ + +#include + +#include +#include + +// A runloop that will service events for Flutter instances as well +// as native messages. +class RunLoop { + public: + RunLoop(); + ~RunLoop(); + + // Prevent copying + RunLoop(RunLoop const&) = delete; + RunLoop& operator=(RunLoop const&) = delete; + + // Runs the run loop until the application quits. + void Run(); + + // Registers the given Flutter instance for event servicing. + void RegisterFlutterInstance( + flutter::FlutterEngine* flutter_instance); + + // Unregisters the given Flutter instance from event servicing. + void UnregisterFlutterInstance( + flutter::FlutterEngine* flutter_instance); + + private: + using TimePoint = std::chrono::steady_clock::time_point; + + // Processes all currently pending messages for registered Flutter instances. + TimePoint ProcessFlutterMessages(); + + std::set flutter_instances_; +}; + +#endif // RUNNER_RUN_LOOP_H_ diff --git a/example/windows/runner/runner.exe.manifest b/example/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..c977c4a --- /dev/null +++ b/example/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/example/windows/runner/utils.cpp b/example/windows/runner/utils.cpp new file mode 100644 index 0000000..d19bdbb --- /dev/null +++ b/example/windows/runner/utils.cpp @@ -0,0 +1,64 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr); + if (target_length == 0) { + return std::string(); + } + std::string utf8_string; + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, utf8_string.data(), + target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/example/windows/runner/utils.h b/example/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/example/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/example/windows/runner/win32_window.cpp b/example/windows/runner/win32_window.cpp new file mode 100644 index 0000000..c10f08d --- /dev/null +++ b/example/windows/runner/win32_window.cpp @@ -0,0 +1,245 @@ +#include "win32_window.h" + +#include + +#include "resource.h" + +namespace { + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + FreeLibrary(user32_module); + } +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::CreateAndShow(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + return OnCreate(); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} diff --git a/example/windows/runner/win32_window.h b/example/windows/runner/win32_window.h new file mode 100644 index 0000000..17ba431 --- /dev/null +++ b/example/windows/runner/win32_window.h @@ -0,0 +1,98 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates and shows a win32 window with |title| and position and size using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size to will treat the width height passed in to this function + // as logical pixels and scale to appropriate for the default monitor. Returns + // true if the window was created successfully. + bool CreateAndShow(const std::wstring& title, + const Point& origin, + const Size& size); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responsponds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/lib/src/core/scene_config.dart b/lib/src/core/scene_config.dart index 2f39727..fa4f497 100644 --- a/lib/src/core/scene_config.dart +++ b/lib/src/core/scene_config.dart @@ -51,17 +51,17 @@ class SceneConfig { /// re-builds the SceneController (the ScenePainter and the scene class). /// disposes and initializes all the scene. - bool rebuildOnHotReload; + bool? rebuildOnHotReload; /// If the GraphX [SceneController] will use keyboard events. - bool useKeyboard; + bool? useKeyboard; /// If this GraphX [SceneController] will use pointer (touch/mouse) events. - bool usePointer; + bool? usePointer; /// Will be overwritten to `true` if [autoUpdateAndRender] is set on any /// [ScenePainter] layer. - bool useTicker; + bool? useTicker; /// See [CustomPaint.willChange]. /// Rendering caching flag. @@ -71,7 +71,7 @@ class SceneConfig { /// All these flags overrides the value to `true`: /// [autoUpdateRender], [useTicker], [usePointer], [useKeyboard] /// - bool painterWillChange; + bool? painterWillChange; /// Avoids the scene from being disposed by the Widget. /// Meant to be used with `ScenePainter.useOwnCanvas=true` @@ -79,7 +79,7 @@ class SceneConfig { /// Picture (or Image eventually) by other [ScenePainter]s. /// Warning: Experimental /// - bool isPersistent = false; + bool? isPersistent = false; /// Default flag to make the engine update() the Stage and all /// his children (onEnterFrame), needed by [GTween] to run the tweens. @@ -91,7 +91,7 @@ class SceneConfig { /// And, unless you don't need external control over the rendering & update /// pipelines for the scene, or if you use a static scene, /// you should leave it as `true`. - bool autoUpdateRender = true; + bool? autoUpdateRender = true; SceneConfig({ this.rebuildOnHotReload = true, @@ -102,14 +102,19 @@ class SceneConfig { this.autoUpdateRender = true, this.painterWillChange, }) { - if (autoUpdateRender) useTicker = true; + if (autoUpdateRender ?? false) useTicker = true; } /// Utility method used by the [SceneBuilderWidget] to set the flag /// `CustomPaint.willChange` /// bool painterMightChange() { - if (useTicker || autoUpdateRender || usePointer || useKeyboard) return true; + if ((useTicker ?? false) || + (autoUpdateRender ?? false) || + (usePointer ?? false) || + (useKeyboard ?? false)) { + return true; + } return painterWillChange ?? false; } } diff --git a/lib/src/core/scene_controller.dart b/lib/src/core/scene_controller.dart index 1489392..8271623 100644 --- a/lib/src/core/scene_controller.dart +++ b/lib/src/core/scene_controller.dart @@ -19,14 +19,14 @@ class SceneController { /// `stage.onHotReload.add((){ /// // your logic here /// });` - Signal _onHotReload; + Signal? _onHotReload; Signal get onHotReload => _onHotReload ??= Signal(); - ScenePainter backScene, frontScene; + ScenePainter? backScene, frontScene; /// Access the `ticker` (if any) created by this SceneController. - GTicker get ticker { + GTicker? get ticker { if (_ticker == null) { throw 'You need to enable ticker usage with ' 'SceneBuilderWidget( useTicker=true ) or ' @@ -38,19 +38,19 @@ class SceneController { /// Access the keyboard manager instance associated with this /// [SceneController]. - KeyboardManager get keyboard => _keyboard; + KeyboardManager? get keyboard => _keyboard; /// Access the pointer manager instance associated with this /// [SceneController]. - PointerManager get pointer => _pointer; + PointerManager? get pointer => _pointer; - KeyboardManager _keyboard; + KeyboardManager? _keyboard; - PointerManager _pointer; + PointerManager? _pointer; - GTicker _ticker; + GTicker? _ticker; - InputConverter $inputConverter; + InputConverter? $inputConverter; SceneConfig get config => _config; @@ -58,7 +58,7 @@ class SceneController { /// gets widget's global coordinates. /// useful to compute interactions with children Widgets that gets - GRect Function() resolveWindowBounds; + GRect? Function()? resolveWindowBounds; int id = -1; @@ -76,9 +76,9 @@ class SceneController { /// constructor. SceneController({ - GSprite back, - GSprite front, - SceneConfig config, + GSprite? back, + GSprite? front, + SceneConfig? config, }) { assert(back != null || front != null); if (back != null) { @@ -99,9 +99,9 @@ class SceneController { setup(); if (_hasTicker()) { _ticker = GTicker(); - _ticker.onFrame.add(_onTick); + _ticker!.onFrame.add(_onTick); if (_anySceneAutoUpdate()) { - _ticker.resume(); + _ticker!.resume(); } } _initInput(); @@ -129,7 +129,7 @@ class SceneController { } void dispose() { - if (_config.isPersistent) { + if (_config.isPersistent ?? false) { return; } _onHotReload?.removeAll(); @@ -140,25 +140,25 @@ class SceneController { _isInited = false; } - CustomPainter buildBackPainter() => backScene?.buildPainter(); + CustomPainter? buildBackPainter() => backScene?.buildPainter(); - CustomPainter buildFrontPainter() => frontScene?.buildPainter(); + CustomPainter? buildFrontPainter() => frontScene?.buildPainter(); void _initInput() { - if (_config.useKeyboard) { + if (_config.useKeyboard ?? false) { _keyboard ??= KeyboardManager(); } - if (_config.usePointer) { + if (_config.usePointer ?? false) { _pointer ??= PointerManager(); } - if (_config.useKeyboard || _config.usePointer) { + if (_config.useKeyboard ?? false || (_config.usePointer ?? false)) { $inputConverter ??= InputConverter(_pointer, _keyboard); } } void reassembleWidget() { _onHotReload?.dispatch(); - if (_config.rebuildOnHotReload) { + if (_config.rebuildOnHotReload ?? false) { GTween.hotReload(); dispose(); @@ -167,11 +167,11 @@ class SceneController { } } - bool _sceneAutoUpdate(ScenePainter scene) => + bool _sceneAutoUpdate(ScenePainter? scene) => scene?.autoUpdateAndRender ?? false; bool _anySceneAutoUpdate() => _sceneAutoUpdate(backScene) || _sceneAutoUpdate(frontScene); - bool _hasTicker() => _anySceneAutoUpdate() || _config.useTicker; + bool _hasTicker() => _anySceneAutoUpdate() || (_config.useTicker ?? false); } diff --git a/lib/src/core/scene_painter.dart b/lib/src/core/scene_painter.dart index 1dbe1be..caa4412 100644 --- a/lib/src/core/scene_painter.dart +++ b/lib/src/core/scene_painter.dart @@ -7,7 +7,7 @@ import '../../graphx.dart'; class ScenePainter with EventDispatcherMixin { /// Current painter being processed. - static ScenePainter current; + static late ScenePainter current; /// access to SceneController defined in the Widget side. SceneController core; @@ -26,16 +26,16 @@ class ScenePainter with EventDispatcherMixin { /// Warning: Experimental state bool useOwnCanvas = false; bool _ownCanvasNeedsRepaint = false; - Canvas $canvas; + Canvas? $canvas; /// Size of the area available in `CustomPainter::paint()` Size size = Size.zero; /// Scene Layer's stage. The very first DisplayObject where the render /// display list starts. - Stage _stage; + Stage? _stage; - Stage get stage => _stage; + Stage? get stage => _stage; /// Defines when the Scene is ready and stage is accessible to GraphX root. /// Runs on the first "render". @@ -56,17 +56,17 @@ class ScenePainter with EventDispatcherMixin { /// Ticker callback, to access the current frame delta timestamp /// (in millisecond). - EventSignal _onUpdate; + EventSignal? _onUpdate; EventSignal get onUpdate => _onUpdate ??= EventSignal(); - ui.Picture _canvasPicture; + ui.Picture? _canvasPicture; var _mouseMoveInputDetected = false; var _lastMouseX = -1000000.0; var _lastMouseY = -1000000.0; var _lastMouseOut = false; - MouseInputData _lastMouseInput; + MouseInputData? _lastMouseInput; /// constructor. ScenePainter(this.core, this.root) { @@ -81,32 +81,33 @@ class ScenePainter with EventDispatcherMixin { void _paint(Canvas canvas, Size size) { if (this.size != size) { this.size = size; - _stage.$initFrameSize(size); + _stage!.$initFrameSize(size); } $canvas = canvas; if (!_isReady) { _isReady = true; _initMouseInput(); - _stage.addChild(root); + _stage!.addChild(root); _stage?.$onResized?.dispatch(); } if (useOwnCanvas) { _pictureFromCanvas(); } else { - _stage.paint($canvas); + _stage!.paint($canvas); } } void $setup() { makeCurrent(); + /// If needed, can be overridden later by the [root]. - autoUpdateAndRender = core.config.autoUpdateRender; + autoUpdateAndRender = core.config.autoUpdateRender ?? false; } void _createPicture() { final _recorder = ui.PictureRecorder(); final _canvas = Canvas(_recorder); - _stage.paint(_canvas); + _stage!.paint(_canvas); _canvasPicture = _recorder.endRecording(); } @@ -115,7 +116,7 @@ class ScenePainter with EventDispatcherMixin { /// Manages the `update()` and can request to redraw the CustomPainter. void tick(double time) { makeCurrent(); - if (autoUpdateAndRender || time != null) { + if (autoUpdateAndRender) { $currentFrameId++; $runTime += time; $update(time); @@ -134,7 +135,7 @@ class ScenePainter with EventDispatcherMixin { } $currentFrameDeltaTime = deltaTime; $accumulatedFrameDeltaTime += $currentFrameDeltaTime; - _stage.$tick(deltaTime); + _stage!.$tick(deltaTime); if (_hasPointer) { _detectMouseMove(); } @@ -153,9 +154,9 @@ class ScenePainter with EventDispatcherMixin { input.stagePosition.setTo(_lastMouseX, _lastMouseY); input.mouseOut = _lastMouseOut; if (_lastMouseInput != null) { - input.buttonDown = _lastMouseInput.buttonDown; - input.rawEvent = _lastMouseInput.rawEvent; - input.buttonsFlags = _lastMouseInput.buttonsFlags; + input.buttonDown = _lastMouseInput!.buttonDown; + input.rawEvent = _lastMouseInput!.rawEvent; + input.buttonsFlags = _lastMouseInput!.buttonsFlags; } _mouseInputHandler(input); } @@ -181,7 +182,7 @@ class ScenePainter with EventDispatcherMixin { } _lastMouseInput = input; - stage.captureMouseInput(input); + stage!.captureMouseInput(input); } /// Requests a new frame. @@ -200,7 +201,7 @@ class ScenePainter with EventDispatcherMixin { } void _initMouseInput() { - core?.pointer?.onInput?.add(_onInputHandler); + core.pointer?.onInput.add(_onInputHandler); } void _onInputHandler(PointerEventData e) { @@ -232,7 +233,7 @@ class ScenePainter with EventDispatcherMixin { _createPicture(); } if (_canvasPicture != null) { - $canvas.drawPicture(_canvasPicture); + $canvas!.drawPicture(_canvasPicture!); } } @@ -241,13 +242,13 @@ class ScenePainter with EventDispatcherMixin { _isReady = false; size = Size.zero; _stage?.dispose(); - core?.pointer?.onInput?.remove(_onInputHandler); + core.pointer?.onInput.remove(_onInputHandler); _onUpdate?.removeAll(); _onUpdate = null; super.dispose(); } - bool get _hasPointer => core?.pointer?.onInput != null; + bool get _hasPointer => core.pointer?.onInput != null; bool shouldRepaint() => needsRepaint; } diff --git a/lib/src/debug/display_debugger.dart b/lib/src/debug/display_debugger.dart index 9b01fb9..b22ee0d 100644 --- a/lib/src/debug/display_debugger.dart +++ b/lib/src/debug/display_debugger.dart @@ -30,7 +30,7 @@ class DisplayBoundsDebugger { ..strokeWidth = 1; final GDisplayObjectContainer _root; - ui.Canvas canvas; + ui.Canvas? canvas; static final GRect _sHelpRect = GRect(); DisplayBoundsDebugger(GDisplayObjectContainer root) : _root = root; @@ -59,8 +59,8 @@ class DisplayBoundsDebugger { final linePaint = _paint.clone(); linePaint.color = linePaint.color.withOpacity(.3); final rect = _sHelpRect.toNative(); - canvas.drawLine(rect.topLeft, rect.bottomRight, linePaint); - canvas.drawLine(rect.topRight, rect.bottomLeft, linePaint); - canvas.drawRect(rect, _paint); + canvas!.drawLine(rect.topLeft, rect.bottomRight, linePaint); + canvas!.drawLine(rect.topRight, rect.bottomLeft, linePaint); + canvas!.drawRect(rect, _paint); } } diff --git a/lib/src/display/bitmap.dart b/lib/src/display/bitmap.dart index ddad535..4f2a6bf 100644 --- a/lib/src/display/bitmap.dart +++ b/lib/src/display/bitmap.dart @@ -11,12 +11,13 @@ class GBitmap extends GDisplayObject { return '$runtimeType (Bitmap2)$msg'; } - GTexture _texture; - GTexture get texture => _texture; + GTexture? _texture; + GTexture? get texture => _texture; double $originalPivotX = 0, $originalPivotY = 0; + /// TODO: improve this process, make bounds work properly. - bool _hasScale9Grid; - double _buffScaleX, _buffScaleY; + late bool _hasScale9Grid; + double _buffScaleX = 0.0, _buffScaleY = 0.0; final GRect _cachedBounds = GRect(); final _paint = ui.Paint()..filterQuality = ui.FilterQuality.medium; ui.Paint get nativePaint => _paint; @@ -33,28 +34,28 @@ class GBitmap extends GDisplayObject { super.pivotY = value; } - set texture(GTexture value) { + set texture(GTexture? value) { if (_texture == value) return; _texture = value; if (_texture != null) { - pivotX = -_texture.pivotX + $originalPivotX; - pivotY = -_texture.pivotY + $originalPivotY; + pivotX = -_texture!.pivotX! + $originalPivotX; + pivotY = -_texture!.pivotY! + $originalPivotY; } requiresRedraw(); } - GBitmap([GTexture texture]) { + GBitmap([GTexture? texture]) { this.texture = texture; } @override - GRect getBounds(GDisplayObject targetSpace, [GRect out]) { + GRect getBounds(GDisplayObject? targetSpace, [GRect? out]) { out ??= GRect(); final matrix = _sHelperMatrix; matrix.identity(); getTransformationMatrix(targetSpace, matrix); if (texture != null) { - var rect = texture.getBounds(); + var rect = texture!.getBounds()!; out = MatrixUtils.getTransformedBoundsRect( matrix, rect, @@ -74,15 +75,15 @@ class GBitmap extends GDisplayObject { } @override - set colorize(ui.Color value) { + set colorize(ui.Color? value) { if ($colorize == value) return; super.colorize = value; _paint.colorFilter = - $hasColorize ? PainterUtils.getColorize($colorize) : null; + $hasColorize ? PainterUtils.getColorize($colorize!) : null; } @override - set filters(List value) { + set filters(List? value) { if ($filters == value) return; $filters = value; if ($filters == null) { @@ -92,9 +93,9 @@ class GBitmap extends GDisplayObject { } @override - void paint(ui.Canvas canvas) { + void paint(ui.Canvas? canvas) { if (texture == null) return; - _hasScale9Grid = texture.scale9Grid != null; + _hasScale9Grid = texture!.scale9Grid != null; if (_hasScale9Grid) { _adjustScaleGrid(); } @@ -102,9 +103,9 @@ class GBitmap extends GDisplayObject { } @override - void $applyPaint(ui.Canvas canvas) { + void $applyPaint(ui.Canvas? canvas) { if (hasFilters) { - for( var filter in filters ){ + for (var filter in filters!) { filter.update(); filter.resolvePaint(_paint); } @@ -119,9 +120,9 @@ class GBitmap extends GDisplayObject { super.pivotX = $originalPivotX * _buffScaleX; super.pivotY = $originalPivotY * _buffScaleY; _cachedBounds.x = _cachedBounds.y = 0; - _cachedBounds.width = texture.width * _buffScaleX; - _cachedBounds.height = texture.height * _buffScaleY; - texture.scale9GridDest = _cachedBounds; + _cachedBounds.width = texture!.width! * _buffScaleX; + _cachedBounds.height = texture!.height! * _buffScaleY; + texture!.scale9GridDest = _cachedBounds; setScale(1, 1); } } diff --git a/lib/src/display/display_object.dart b/lib/src/display/display_object.dart index f0bfbaf..0831b3e 100644 --- a/lib/src/display/display_object.dart +++ b/lib/src/display/display_object.dart @@ -9,10 +9,10 @@ abstract class GDisplayObject RenderSignalMixin, MouseSignalsMixin, DisplayMasking { - GDisplayObjectContainer $parent; - static GDisplayObject $currentDrag; - static GRect $currentDragBounds; - GPoint _dragCenterOffset; + GDisplayObjectContainer? $parent; + static GDisplayObject? $currentDrag; + static GRect? $currentDragBounds; + late GPoint _dragCenterOffset; /// Lets the user drag the specified sprite. /// The sprite remains draggable until explicitly stopped through a call to @@ -23,7 +23,7 @@ abstract class GDisplayObject /// the user first clicked the sprite (false). /// [bounds] Value relative to the coordinates of the Sprite's parent that /// specify a constraint rectangle for the Sprite. - void startDrag([bool lockCenter = false, GRect bounds]) { + void startDrag([bool lockCenter = false, GRect? bounds]) { if (!inStage || !$hasTouchableArea) { throw 'to drag an object, it has to be visible and enabled in the stage.'; } @@ -33,9 +33,9 @@ abstract class GDisplayObject $currentDragBounds = bounds; _dragCenterOffset = GPoint(); if (lockCenter) { - _dragCenterOffset.setTo(x - parent.mouseX, y - parent.mouseY); + _dragCenterOffset.setTo(x - parent!.mouseX, y - parent!.mouseY); } - stage.onMouseMove.add(_handleDrag); + stage!.onMouseMove.add(_handleDrag); } // DisplayObject get dropTarget { @@ -50,14 +50,14 @@ abstract class GDisplayObject void _handleDrag(MouseInputData input) { if (this != $currentDrag) { - stage?.onMouseMove?.remove(_handleDrag); + stage?.onMouseMove.remove(_handleDrag); } if ($currentDrag == null) { $currentDragBounds = null; return; } - var tx = $currentDrag.parent.mouseX + _dragCenterOffset.x; - var ty = $currentDrag.parent.mouseY + _dragCenterOffset.y; + var tx = $currentDrag!.parent!.mouseX + _dragCenterOffset.x; + var ty = $currentDrag!.parent!.mouseY + _dragCenterOffset.y; final rect = $currentDragBounds; if (rect != null) { tx = tx.clamp(rect.left, rect.right); @@ -68,7 +68,7 @@ abstract class GDisplayObject void stopDrag() { if (this == $currentDrag) { - stage.onMouseMove.remove(_handleDrag); + stage!.onMouseMove.remove(_handleDrag); $currentDrag = null; } } @@ -76,26 +76,26 @@ abstract class GDisplayObject bool $debugBounds = false; bool mouseUseShape = false; - List $filters; + List? $filters; - List get filters => $filters; + List? get filters => $filters; - set filters(List value) => $filters = value; + set filters(List? value) => $filters = value; - GDisplayObject $mouseDownObj; - GDisplayObject $mouseOverObj; + GDisplayObject? $mouseDownObj; + GDisplayObject? $mouseOverObj; double $lastClickTime = -1; bool useCursor = false; - ui.Color $colorize = kColorTransparent; + ui.Color? $colorize = kColorTransparent; - bool get $hasColorize => $colorize != null && $colorize.alpha > 0; + bool get $hasColorize => $colorize != null && $colorize!.alpha > 0; - ui.Color get colorize => $colorize; + ui.Color? get colorize => $colorize; - set colorize(ui.Color value) { + set colorize(ui.Color? value) { if ($colorize == value) return; $colorize = value; requiresRedraw(); @@ -127,7 +127,7 @@ abstract class GDisplayObject } void $dispatchMouseCallback( - MouseInputType type, + MouseInputType? type, GDisplayObject object, MouseInputData input, ) { @@ -198,7 +198,7 @@ abstract class GDisplayObject double get mouseX { if (inStage) { - return globalToLocal(_sHelperPoint.setTo(stage.pointer.mouseX, 0)).x; + return globalToLocal(_sHelperPoint.setTo(stage!.pointer!.mouseX, 0)).x; } else { throw 'To get mouseX object needs to be a descendant of Stage.'; } @@ -206,7 +206,7 @@ abstract class GDisplayObject double get mouseY { if (inStage) { - return globalToLocal(_sHelperPoint.setTo(0, stage.pointer.mouseY)).y; + return globalToLocal(_sHelperPoint.setTo(0, stage!.pointer!.mouseY)).y; } else { throw 'To get mouseY object needs to be a descendant of Stage.'; } @@ -217,14 +217,14 @@ abstract class GDisplayObject throw 'To get mousePosition, the object needs to be in the Stage.'; } return globalToLocal(_sHelperPoint.setTo( - stage.pointer.mouseX, - stage.pointer.mouseY, + stage!.pointer!.mouseX, + stage!.pointer!.mouseY, )); } /// You can store any user defined data in this property for easy access. - Object userData; - String name; + Object? userData; + String? name; double _x = 0, _y = 0, _scaleX = 1, _scaleY = 1, _rotation = 0; double _pivotX = 0, _pivotY = 0; @@ -270,7 +270,7 @@ abstract class GDisplayObject /// ``` /// A display object with no content (such as an empty sprite) has a width /// of 0, even if you try to set width to a different value. - double get width => getBounds($parent, _sHelperRect).width; + double get width => getBounds($parent, _sHelperRect)!.width; /// Indicates the height of the display object, in dp. /// The `height` is calculated based on the bounds of the content of the @@ -287,11 +287,11 @@ abstract class GDisplayObject /// ``` /// A display object with no content (such as an empty sprite) has a height /// of 0, even if you try to set height to a different value. - double get height => getBounds($parent, _sHelperRect).height; + double get height => getBounds($parent, _sHelperRect)!.height; - set width(double value) { + set width(double? value) { if (value == null) throw 'width can not be null'; - double actualW; + double? actualW; var zeroScale = _scaleX < 1e-8 && _scaleX > -1e-8; if (zeroScale) { scaleX = 1.0; @@ -299,12 +299,12 @@ abstract class GDisplayObject } else { actualW = (width / _scaleX).abs(); } - if (actualW != null) scaleX = value / actualW; + scaleX = value / actualW; } - set height(double value) { + set height(double? value) { if (value == null) throw 'height can not be null'; - double actualH; + double? actualH; var zeroScale = _scaleY < 1e-8 && _scaleY > -1e-8; if (zeroScale) { scaleY = 1.0; @@ -312,31 +312,31 @@ abstract class GDisplayObject } else { actualH = (height / _scaleY).abs(); } - if (actualH != null) scaleY = value / actualH; + scaleY = value / actualH; } - set x(double value) { + set x(double? value) { if (value == null) throw 'x can not be null'; if (_x == value) return; _x = value; $setTransformationChanged(); } - set y(double value) { + set y(double? value) { if (value == null) throw 'y can not be null'; if (_y == value) return; _y = value; $setTransformationChanged(); } - set scaleX(double value) { + set scaleX(double? value) { if (value == null) throw 'scaleX can not be null'; if (_scaleX == value) return; _scaleX = value; $setTransformationChanged(); } - set scaleY(double value) { + set scaleY(double? value) { if (value == null) throw 'scaleY can not be null'; if (_scaleY == value) return; _scaleY = value; @@ -345,31 +345,29 @@ abstract class GDisplayObject set pivotX(double value) { if (_pivotX == value) return; - _pivotX = value ?? 0.0; + _pivotX = value; $setTransformationChanged(); } set pivotY(double value) { if (_pivotY == value) return; - _pivotY = value ?? 0.0; + _pivotY = value; $setTransformationChanged(); } set skewX(double value) { - if (value == null) throw 'skewX can not be null'; if (_skewX == value) return; _skewX = value; $setTransformationChanged(); } set skewY(double value) { - if (value == null) throw 'skewY can not be null'; if (_skewY == value) return; _skewY = value; $setTransformationChanged(); } - set rotation(double value) { + set rotation(double? value) { if (value == null) throw 'rotation can not be null'; if (_rotation == value) return; _rotation = value; @@ -377,11 +375,8 @@ abstract class GDisplayObject } set rotationX(double value) { - if (value == null) { - throw 'rotationX can not be null'; - } if (_rotationX == value) return; - _rotationX = value ?? 0.0; + _rotationX = value; if (!_isWarned3d) _warn3d(); $setTransformationChanged(); } @@ -394,21 +389,15 @@ abstract class GDisplayObject } set rotationY(double value) { - if (value == null) { - throw 'rotationY can not be null'; - } if (_rotationY == value) return; - _rotationY = value ?? 0.0; + _rotationY = value; if (!_isWarned3d) _warn3d(); $setTransformationChanged(); } set z(double value) { - if (value == null) { - throw 'z can not be null'; - } if (_z == value) return; - _z = value ?? 0.0; + _z = value; if (!_isWarned3d) _warn3d(); $setTransformationChanged(); } @@ -418,11 +407,8 @@ abstract class GDisplayObject double get alpha => $alpha; set alpha(double value) { - if (value == null) { - throw 'alpha can not be null'; - } if ($alpha != value) { - value ??= 1; + // value ??= 1; $alpha = value.clamp(0.0, 1.0); requiresRedraw(); } @@ -433,8 +419,8 @@ abstract class GDisplayObject bool $matrixDirty = true; bool mouseEnabled = true; - GDisplayObject $maskee; - GShape $mask; + GDisplayObject? $maskee; + GShape? $mask; /// optimization. bool $hasTouchableArea = true; @@ -442,14 +428,14 @@ abstract class GDisplayObject bool get isMask => $maskee != null; - GShape get mask => $mask; + GShape? get mask => $mask; /// can be set on the Shape mask, or the maskee DisplayObject. bool maskInverted = false; - set mask(GShape value) { + set mask(GShape? value) { if ($mask != value) { - if ($mask != null) $mask.$maskee = null; + if ($mask != null) $mask!.$maskee = null; value?.$maskee = this; value?.$hasVisibleArea = false; $mask = value; @@ -512,7 +498,7 @@ abstract class GDisplayObject } void alignPivot([painting.Alignment alignment = painting.Alignment.center]) { - var bounds = getBounds(this, _sHelperRect); + var bounds = getBounds(this, _sHelperRect)!; if (bounds.isEmpty) return; var ax = 0.5 + alignment.x / 2; var ay = 0.5 + alignment.y / 2; @@ -522,24 +508,24 @@ abstract class GDisplayObject /// local bounds /// todo: should be cached. - GRect get bounds => getBounds(this); + GRect? get bounds => getBounds(this); - GRect getBounds(GDisplayObject targetSpace, [GRect out]) { + GRect? getBounds(GDisplayObject? targetSpace, [GRect? out]) { throw 'getBounds() is abstract in DisplayObject'; } - GPoint globalToLocal(GPoint globalPoint, [GPoint out]) { + GPoint globalToLocal(GPoint globalPoint, [GPoint? out]) { getTransformationMatrix(base, _sHelperMatrixAlt); _sHelperMatrixAlt.invert(); return _sHelperMatrixAlt.transformPoint(globalPoint, out); } - GPoint localToGlobal(GPoint localPoint, [GPoint out]) { + GPoint localToGlobal(GPoint localPoint, [GPoint? out]) { getTransformationMatrix(base, _sHelperMatrixAlt); return _sHelperMatrixAlt.transformPoint(localPoint, out); } - GMatrix _transformationMatrix; + GMatrix? _transformationMatrix; GMatrix get transformationMatrix { if (_transformationChanged || _transformationMatrix == null) { @@ -566,10 +552,10 @@ abstract class GDisplayObject skewX, skewY, rotation, - _transformationMatrix, + _transformationMatrix!, ); } - return _transformationMatrix; + return _transformationMatrix!; } set transformationMatrix(GMatrix matrix) { @@ -577,7 +563,7 @@ abstract class GDisplayObject requiresRedraw(); _transformationChanged = false; _transformationMatrix ??= GMatrix(); - _transformationMatrix.copyFrom(matrix); + _transformationMatrix!.copyFrom(matrix); _pivotX = _pivotY = 0; _x = matrix.tx; _y = matrix.ty; @@ -598,8 +584,8 @@ abstract class GDisplayObject } void $updateTransformationMatrices( - double x, - double y, + double? x, + double? y, double pivotX, double pivotY, double scaleX, @@ -618,8 +604,8 @@ abstract class GDisplayObject 0, 0, scaleY, - x - pivotX * scaleX, - y - pivotY * scaleY, + x! - pivotX * scaleX, + y! - pivotY * scaleY, ); } else { final cos = Math.cos(rotation); @@ -628,8 +614,8 @@ abstract class GDisplayObject final b = scaleX * sin; final c = scaleY * -sin; final d = scaleY * cos; - final tx = x - pivotX * a - pivotY * c; - final ty = y - pivotX * b - pivotY * d; + final tx = x! - pivotX * a - pivotY * c; + final ty = y! - pivotX * b - pivotY * d; out.setTo(a, b, c, d, tx, ty); } } else { @@ -637,7 +623,7 @@ abstract class GDisplayObject out.scale(scaleX, scaleY); out.skew(skewX, skewY); // MatrixUtils.skew(out, skewX, skewY); out.rotate(rotation); - out.translate(x, y); + out.translate(x!, y!); if (pivotX != 0 || pivotY != 0) { out.tx = x - out.a * pivotX - out.c * pivotY; out.ty = y - out.b * pivotX - out.d * pivotY; @@ -645,8 +631,8 @@ abstract class GDisplayObject } } - GMatrix getTransformationMatrix(GDisplayObject targetSpace, [GMatrix out]) { - GDisplayObject commonParent, currentObj; + GMatrix getTransformationMatrix(GDisplayObject? targetSpace, [GMatrix? out]) { + GDisplayObject? commonParent, currentObj; out?.identity(); out ??= GMatrix(); if (targetSpace == this) { @@ -659,7 +645,7 @@ abstract class GDisplayObject if (targetSpace == null || targetSpace == base) { currentObj = this; while (currentObj != targetSpace) { - out.concat(currentObj.transformationMatrix); + out.concat(currentObj!.transformationMatrix); currentObj = currentObj.$parent; } return out; @@ -677,7 +663,7 @@ abstract class GDisplayObject /// 2 - move up from this to common parent.```` currentObj = this; while (currentObj != commonParent) { - out.concat(currentObj.transformationMatrix); + out.concat(currentObj!.transformationMatrix); currentObj = currentObj.$parent; } @@ -687,7 +673,7 @@ abstract class GDisplayObject _sHelperMatrix.identity(); currentObj = targetSpace; while (currentObj != commonParent) { - _sHelperMatrix.concat(currentObj.transformationMatrix); + _sHelperMatrix.concat(currentObj!.transformationMatrix); currentObj = currentObj.$parent; } @@ -699,7 +685,7 @@ abstract class GDisplayObject static GDisplayObject _findCommonParent( GDisplayObject obj1, GDisplayObject obj2) { - var current = obj1; + GDisplayObject? current = obj1; /// TODO: use faster Hash access. while (current != null) { @@ -720,20 +706,20 @@ abstract class GDisplayObject return true; } if (maskRect != null) { - final isHit = maskRect.containsPoint(localPoint); + final isHit = maskRect!.containsPoint(localPoint); return maskRectInverted ? !isHit : isHit; } - if ($mask.inStage) { + if ($mask!.inStage) { getTransformationMatrix($mask, _sHelperMatrixAlt); } else { - _sHelperMatrixAlt.copyFrom($mask.transformationMatrix); + _sHelperMatrixAlt.copyFrom($mask!.transformationMatrix); _sHelperMatrixAlt.invert(); } var helperPoint = localPoint == _sHelperPoint ? GPoint() : _sHelperPoint; _sHelperMatrixAlt.transformPoint(localPoint, helperPoint); - final isHit = mask.hitTest(helperPoint) != null; + final isHit = mask!.hitTest(helperPoint) != null; // return maskInverted ? !isHit : isHit; return maskInverted ? !isHit : isHit; } @@ -743,38 +729,38 @@ abstract class GDisplayObject } /// `useShape` is meant to be used by `Shape.graphics`. - GDisplayObject hitTest(GPoint localPoint, [bool useShape = false]) { + GDisplayObject? hitTest(GPoint localPoint, [bool useShape = false]) { if (!$hasTouchableArea || !mouseEnabled) { return null; } if (($mask != null || maskRect != null) && !hitTestMask(localPoint)) { return null; } - if (getBounds(this, _sHelperRect).containsPoint(localPoint)) { + if (getBounds(this, _sHelperRect)!.containsPoint(localPoint)) { return this; } return null; } - GDisplayObjectContainer get parent => $parent; + GDisplayObjectContainer? get parent => $parent; GDisplayObject get base { var current = this; while (current.$parent != null) { - current = current.$parent; + current = current.$parent!; } return current; } bool get inStage => base is Stage; - Stage get stage => base is Stage ? base : null; + Stage? get stage => base is Stage ? base as Stage? : null; - GDisplayObject get root { + GDisplayObject? get root { var current = this; while (current.$parent != null) { if (current.$parent is Stage) return current; - current = current.$parent; + current = current.$parent!; } return null; } @@ -800,7 +786,7 @@ abstract class GDisplayObject void update(double delta) {} bool get hasFilters => filters?.isNotEmpty ?? false; - GRect $debugLastLayerBounds; + GRect? $debugLastLayerBounds; /// quick and dirty way to toggle saveLayer() feature for common /// display objects as well. @@ -808,14 +794,14 @@ abstract class GDisplayObject /// Paint() so no need to use an expensive saveLayer(). bool allowSaveLayer = false; - GRect getFilterBounds([GRect layerBounds, ui.Paint alphaPaint]) { + GRect? getFilterBounds([GRect? layerBounds, ui.Paint? alphaPaint]) { layerBounds ??= getBounds($parent); - if ($filters == null || $filters.isEmpty) { + if ($filters == null || $filters!.isEmpty) { return layerBounds; } - layerBounds = layerBounds.clone(); - GRect resultBounds; - for (var filter in $filters) { + layerBounds = layerBounds!.clone(); + GRect? resultBounds; + for (var filter in $filters!) { resultBounds ??= layerBounds.clone(); if (alphaPaint != null) { filter.update(); @@ -837,7 +823,7 @@ abstract class GDisplayObject /// Do not override this method as it applies the basic /// transformations. Override $applyPaint() if you wanna use /// `Canvas` directly. - void paint(ui.Canvas canvas) { + void paint(ui.Canvas? canvas) { if (!$hasVisibleArea || !visible) { return; } @@ -868,13 +854,13 @@ abstract class GDisplayObject DisplayBoundsDebugger.debugBoundsMode == DebugBoundsMode.internal && ($debugBounds || DisplayBoundsDebugger.debugAll); - GRect _cacheLocalBoundsRect; + GRect? _cacheLocalBoundsRect; if (showDebugBounds || _saveLayer) { // _cacheLocalBoundsRect = bounds.toNative(); _cacheLocalBoundsRect = bounds; } - List _composerFilters; + List? _composerFilters; var filterHidesObject = false; if (_saveLayer) { // TODO: static painter seems to have some issues, try local var later. @@ -890,18 +876,18 @@ abstract class GDisplayObject alphaPaint.maskFilter = null; if ($hasColorize) { alphaPaint.colorFilter = ui.ColorFilter.mode( - $colorize, + $colorize!, ui.BlendMode.srcATop, ); } - ui.Rect nativeLayerBounds; + ui.Rect? nativeLayerBounds; var layerBounds = getBounds($parent); if ($hasFilters) { /// TODO: Find a common implementation for filter bounds. // layerBounds = getFilterBounds(layerBounds, alphaPaint); - layerBounds = layerBounds.clone(); - GRect resultBounds; - for (var filter in $filters) { + layerBounds = layerBounds!.clone(); + GRect? resultBounds; + for (var filter in $filters!) { resultBounds ??= layerBounds.clone(); filter.update(); filter.expandBounds(layerBounds, resultBounds); @@ -917,18 +903,18 @@ abstract class GDisplayObject $debugLastLayerBounds = layerBounds; // canvas.saveLayer(layerBounds.toNative(), alphaPaint); if ($useSaveLayerBounds) { - nativeLayerBounds = layerBounds.toNative(); + nativeLayerBounds = layerBounds!.toNative(); } - canvas.saveLayer(nativeLayerBounds, alphaPaint); + canvas!.saveLayer(nativeLayerBounds, alphaPaint); } if (needSave) { // onPreTransform.dispatch(); - canvas.save(); - var m = transformationMatrix.toNative(); + canvas!.save(); + var m = transformationMatrix.toNative()!; canvas.transform(m.storage); if (_is3D) { /// TODO: experimental, just transforms - m = GMatrix().toNative(); + m = GMatrix().toNative()!; m.setEntry(3, 2, 0.004); m.rotateX(_rotationX); m.rotateY(_rotationY); @@ -940,11 +926,11 @@ abstract class GDisplayObject } if (hasMask) { - canvas.save(); + canvas!.save(); if (maskRect != null) { $applyMaskRect(canvas); } else { - mask.$applyPaint(canvas); + mask!.$applyPaint(canvas); } } @@ -964,22 +950,22 @@ abstract class GDisplayObject $onPostPaint?.dispatch(canvas); if (hasMask) { - canvas.restore(); + canvas!.restore(); } if (showDebugBounds) { final _paint = $debugBoundsPaint ?? _debugPaint; final linePaint = _paint.clone(); linePaint.color = linePaint.color.withOpacity(.3); - final rect = _cacheLocalBoundsRect.toNative(); - canvas.drawLine(rect.topLeft, rect.bottomRight, linePaint); + final rect = _cacheLocalBoundsRect!.toNative(); + canvas!.drawLine(rect.topLeft, rect.bottomRight, linePaint); canvas.drawLine(rect.topRight, rect.bottomLeft, linePaint); canvas.drawRect(rect, _paint); } if (needSave) { - canvas.restore(); + canvas!.restore(); } if (_saveLayer) { - canvas.restore(); + canvas!.restore(); } } @@ -988,11 +974,11 @@ abstract class GDisplayObject ..color = kColorMagenta ..strokeWidth = 1; - ui.Paint $debugBoundsPaint = _debugPaint.clone(); + ui.Paint? $debugBoundsPaint = _debugPaint.clone(); /// override this method for custom drawing using Flutter's API. /// Access `$canvas` from here. - void $applyPaint(ui.Canvas canvas) {} + void $applyPaint(ui.Canvas? canvas) {} @mustCallSuper void dispose() { @@ -1010,7 +996,7 @@ abstract class GDisplayObject } /// internal - void $setParent(GDisplayObjectContainer value) { + void $setParent(GDisplayObjectContainer? value) { var ancestor = value; while (ancestor != this && ancestor != null) { ancestor = ancestor.$parent; @@ -1039,7 +1025,7 @@ abstract class GDisplayObject $setTransformationChanged(); } - void setScale(double scaleX, [double scaleY]) { + void setScale(double scaleX, [double? scaleY]) { _scaleX = scaleX; _scaleY = scaleY ?? scaleX; $setTransformationChanged(); @@ -1051,8 +1037,8 @@ abstract class GDisplayObject /// transformations (x, y, scale, etc) if you intend to use in it's "original" /// form. ui.Picture createPicture( - [void Function(ui.Canvas) prePaintCallback, - void Function(ui.Canvas) postPaintCallback]) { + [void Function(ui.Canvas)? prePaintCallback, + void Function(ui.Canvas)? postPaintCallback]) { final r = ui.PictureRecorder(); final c = ui.Canvas(r); prePaintCallback?.call(c); @@ -1064,22 +1050,22 @@ abstract class GDisplayObject Future createImageTexture([ bool adjustOffset = true, double resolution = 1, - GRect rect, + GRect? rect, ]) async { final img = await createImage(adjustOffset, resolution, rect); var tx = GTexture.fromImage(img, resolution); - tx.pivotX = bounds.x; - tx.pivotY = bounds.y; + tx.pivotX = bounds!.x; + tx.pivotY = bounds!.y; return tx; } Future createImage([ bool adjustOffset = true, double resolution = 1, - GRect rect, + GRect? rect, ]) async { rect ??= getFilterBounds(); //getBounds($parent); - rect = rect.clone(); + rect = rect!.clone(); if (resolution != 1) { rect *= resolution; } @@ -1088,7 +1074,7 @@ abstract class GDisplayObject ui.Picture picture; if (needsAdjust) { picture = createPicture((canvas) { - if (adjustOffset) canvas.translate(-rect.left, -rect.top); + if (adjustOffset) canvas.translate(-rect!.left, -rect.top); if (resolution != 1) canvas.scale(resolution); }, (canvas) { if (adjustOffset) canvas.restore(); diff --git a/lib/src/display/display_object_container.dart b/lib/src/display/display_object_container.dart index 8920d52..8a3a0bf 100644 --- a/lib/src/display/display_object_container.dart +++ b/lib/src/display/display_object_container.dart @@ -41,7 +41,7 @@ abstract class GDisplayObjectContainer extends GDisplayObject { } @override - GRect getBounds(GDisplayObject targetSpace, [GRect out]) { + GRect? getBounds(GDisplayObject? targetSpace, [GRect? out]) { out ??= GRect(); final len = children.length; if (len == 0) { @@ -76,7 +76,7 @@ abstract class GDisplayObjectContainer extends GDisplayObject { return result; } final numChild = children.length; - GDisplayObject target; + GDisplayObject? target; for (var i = numChild - 1; i >= 0; --i) { var child = children[i]; if (child.isMask) continue; @@ -99,7 +99,7 @@ abstract class GDisplayObjectContainer extends GDisplayObject { } @override - GDisplayObject hitTest(GPoint localPoint, [bool useShape = false]) { + GDisplayObject? hitTest(GPoint localPoint, [bool useShape = false]) { if (!$hasTouchableArea || !mouseEnabled || !hitTestMask(localPoint)) { return null; } @@ -133,7 +133,6 @@ abstract class GDisplayObjectContainer extends GDisplayObject { } GDisplayObject addChildAt(GDisplayObject child, int index) { - if (child == null) throw "::child can't be null"; if (index < 0 || index > children.length) { throw RangeError('Invalid child index'); } @@ -209,7 +208,7 @@ abstract class GDisplayObjectContainer extends GDisplayObject { throw RangeError('Invalid child index'); } - GDisplayObject getChildByName(String name) { + GDisplayObject? getChildByName(String name) { for (final child in children) { if (child.name == name) return child; } @@ -237,7 +236,7 @@ abstract class GDisplayObjectContainer extends GDisplayObject { bool get hasChildren => children.isNotEmpty; - bool contains(GDisplayObject child, [bool recursive = true]) { + bool contains(GDisplayObject? child, [bool recursive = true]) { if (!recursive) return children.contains(child); while (child != null) { if (child == this) return true; @@ -267,8 +266,8 @@ abstract class GDisplayObjectContainer extends GDisplayObject { throw 'Invalid child index'; } - GDisplayObject removeChild(GDisplayObject child, [bool dispose = false]) { - if (child == null || child?.$parent != this) return null; + GDisplayObject? removeChild(GDisplayObject child, [bool dispose = false]) { + if (child.$parent != this) return null; final index = getChildIndex(child); if (index > -1) return removeChildAt(index, dispose); throw 'Invalid child index'; @@ -283,7 +282,7 @@ abstract class GDisplayObjectContainer extends GDisplayObject { } @override - void $applyPaint(ui.Canvas canvas) { + void $applyPaint(ui.Canvas? canvas) { if (!$hasVisibleArea) return; for (var child in children) { if (child.$hasVisibleArea) { @@ -304,7 +303,7 @@ abstract class GDisplayObjectContainer extends GDisplayObject { @mustCallSuper void dispose() { for (final child in children) { - child?.dispose(); + child.dispose(); } children.clear(); super.dispose(); diff --git a/lib/src/display/shape.dart b/lib/src/display/shape.dart index 838f553..dbe35c2 100644 --- a/lib/src/display/shape.dart +++ b/lib/src/display/shape.dart @@ -2,7 +2,7 @@ import 'dart:ui' as ui; import '../../graphx.dart'; class GShape extends GDisplayObject { - Graphics _graphics; + Graphics? _graphics; static final _sHelperMatrix = GMatrix(); @override @@ -14,7 +14,7 @@ class GShape extends GDisplayObject { Graphics get graphics => _graphics ??= Graphics(); @override - GRect getBounds(GDisplayObject targetSpace, [GRect out]) { + GRect? getBounds(GDisplayObject? targetSpace, [GRect? out]) { final matrix = _sHelperMatrix; matrix.identity(); getTransformationMatrix(targetSpace, matrix); @@ -33,24 +33,24 @@ class GShape extends GDisplayObject { // }); /// single bounds, all paths as 1 rect. return MatrixUtils.getTransformedBoundsRect( - matrix, _graphics.getBounds(out), out); + matrix, _graphics!.getBounds(out), out); } else { final pos = GDisplayObjectContainer.$sBoundsPoint; matrix.transformCoords(0, 0, pos); - out.setTo(pos.x, pos.y, 0, 0); + out!.setTo(pos.x, pos.y, 0, 0); } return out; } @override - GDisplayObject hitTest(GPoint localPoint, [bool useShape = false]) { + GDisplayObject? hitTest(GPoint localPoint, [bool useShape = false]) { if (!$hasTouchableArea || !mouseEnabled) { return null; } return (_graphics?.hitTest(localPoint, useShape) ?? false) ? this : null; } - static ui.Path _inverseHugePath; + static ui.Path? _inverseHugePath; static void _initInversePath() { if (_inverseHugePath != null) { return; @@ -58,22 +58,22 @@ class GShape extends GDisplayObject { _inverseHugePath = ui.Path(); final w = 100000.0; var r = Pool.getRect(-w / 2, -w / 2, w, w); - _inverseHugePath.addRect(r.toNative()); - _inverseHugePath.close(); + _inverseHugePath!.addRect(r.toNative()); + _inverseHugePath!.close(); } @override - void $applyPaint(ui.Canvas canvas) { + void $applyPaint(ui.Canvas? canvas) { if (isMask && _graphics != null) { GMatrix matrix; - var paths = _graphics.getPaths(); - if (inStage && $maskee.inStage) { + var paths = _graphics!.getPaths(); + if (inStage && $maskee!.inStage) { matrix = getTransformationMatrix($maskee); } else { matrix = transformationMatrix; } - var clipPath = paths.transform(matrix.toNative().storage); - final inverted = maskInverted || $maskee.maskInverted; + var clipPath = paths.transform(matrix.toNative()!.storage); + final inverted = maskInverted || $maskee!.maskInverted; if (inverted) { _initInversePath(); // var invPath = Graphics.stageRectPath; @@ -81,13 +81,13 @@ class GShape extends GDisplayObject { // invPath = invPath.shift(Offset(rect.x, rect.y)); if (SystemUtils.usingSkia) { clipPath = ui.Path.combine( - ui.PathOperation.difference, _inverseHugePath, clipPath); - canvas.clipPath(clipPath); + ui.PathOperation.difference, _inverseHugePath!, clipPath); + canvas!.clipPath(clipPath); } else { trace('Shape.maskInverted is unsupported in the current platform'); } } else { - canvas.clipPath(clipPath); + canvas!.clipPath(clipPath); } } else { _graphics?.isMask = isMask; diff --git a/lib/src/display/sprite.dart b/lib/src/display/sprite.dart index a6dc3b1..12ae3e2 100644 --- a/lib/src/display/sprite.dart +++ b/lib/src/display/sprite.dart @@ -11,31 +11,31 @@ class GSprite extends GDisplayObjectContainer { static final _sHelperMatrix = GMatrix(); - Graphics _graphics; + Graphics? _graphics; Graphics get graphics => _graphics ??= Graphics(); @override - GRect getBounds(GDisplayObject targetSpace, [GRect out]) { + GRect? getBounds(GDisplayObject? targetSpace, [GRect? out]) { out = super.getBounds(targetSpace, out); if (_graphics != null) { _sHelperMatrix.identity(); getTransformationMatrix(targetSpace, _sHelperMatrix); /// single bounds, all paths as 1 rect. - final graphicsBounds = _graphics.getBounds(); + final graphicsBounds = _graphics!.getBounds(); MatrixUtils.getTransformedBoundsRect( _sHelperMatrix, graphicsBounds, graphicsBounds, ); - out.expandToInclude(graphicsBounds); + out!.expandToInclude(graphicsBounds); } return out; } @override - GDisplayObject hitTest(GPoint localPoint, [bool useShape = false]) { + GDisplayObject? hitTest(GPoint localPoint, [bool useShape = false]) { if (!visible || !mouseEnabled) return null; var target = super.hitTest(localPoint); target ??= @@ -44,7 +44,7 @@ class GSprite extends GDisplayObjectContainer { } @override - void $applyPaint(ui.Canvas canvas) { + void $applyPaint(ui.Canvas? canvas) { if (!$hasVisibleArea) return; _graphics?.alpha = worldAlpha; _graphics?.paint(canvas); diff --git a/lib/src/display/stage.dart b/lib/src/display/stage.dart index 7d2797f..791ac7d 100644 --- a/lib/src/display/stage.dart +++ b/lib/src/display/stage.dart @@ -36,9 +36,9 @@ class Stage extends GDisplayObjectContainer return '$runtimeType'; } - ui.Size _size; - ui.Paint _backgroundPaint; - DisplayBoundsDebugger _boundsDebugger; + ui.Size? _size; + ui.Paint? _backgroundPaint; + late DisplayBoundsDebugger _boundsDebugger; /// Shortcut to access the owner [SceneController]. SceneController get controller => scene.core; @@ -47,15 +47,15 @@ class Stage extends GDisplayObjectContainer Signal get onHotReload => controller.onHotReload; /// The `backgroundPaint` hex color. - ui.Color get color => _backgroundPaint?.color; + ui.Color? get color => _backgroundPaint?.color; /// Sets the `backgroundPaint` Color. - set color(ui.Color value) { + set color(ui.Color? value) { if (value == null) { _backgroundPaint = null; } else { _backgroundPaint ??= ui.Paint(); - _backgroundPaint.color = value; + _backgroundPaint!.color = value; } } @@ -77,13 +77,13 @@ class Stage extends GDisplayObjectContainer } @override - void paint(ui.Canvas canvas) { + void paint(ui.Canvas? canvas) { /// scene start painting. if (maskBounds && _stageRectNative != null) { - canvas.clipRect(_stageRectNative); + canvas!.clipRect(_stageRectNative!); } if (_backgroundPaint != null) { - canvas.drawPaint(_backgroundPaint); + canvas!.drawPaint(_backgroundPaint!); } super.paint(canvas); if (DisplayBoundsDebugger.debugBoundsMode == DebugBoundsMode.stage) { @@ -91,11 +91,11 @@ class Stage extends GDisplayObjectContainer _boundsDebugger.render(); } if (showBoundsRect) { - canvas.drawPath(_stageBoundsRectPath, _stageBoundsRectPaint); + canvas!.drawPath(_stageBoundsRectPath, _stageBoundsRectPaint); } } - ui.Path _stageBoundsRectPath = ui.Path(); + final ui.Path _stageBoundsRectPath = ui.Path(); static final ui.Paint _stageBoundsRectPaint = ui.Paint() ..style = ui.PaintingStyle.stroke ..color = kColorBlack @@ -104,20 +104,25 @@ class Stage extends GDisplayObjectContainer final GRect _stageRect = GRect(); GRect get stageRect => _stageRect; - ui.Rect _stageRectNative; + ui.Rect? _stageRectNative; void $initFrameSize(ui.Size value) { if (value != _size) { _size = value; - if (_size.isEmpty) { + if (_size!.isEmpty) { trace( - "WARNING:\n\tStage has size <= 0 in width or height. If you rely on stage size for a responsive layout or rendering, make sure SceneBuilderWidget() has some child, or the parent is defining the constraints."); + // ignore: lines_longer_than_80_chars + "WARNING:\n\tStage has size <= 0 in width or height. " + "If you rely on stage size for a responsive layout or rendering," + " make sure SceneBuilderWidget() has some child," + " or the parent is defining the constraints.", + ); } _stageRectNative = - _stageRect.setTo(0, 0, _size.width, _size.height).toNative(); - _stageBoundsRectPath ??= ui.Path(); + _stageRect.setTo(0, 0, _size!.width, _size!.height).toNative(); + _stageBoundsRectPath; _stageBoundsRectPath.reset(); - _stageBoundsRectPath.addRect(_stageRectNative); + _stageBoundsRectPath.addRect(_stageRectNative!); _stageBoundsRectPath.close(); Graphics.updateStageRect(_stageRect); $onResized?.dispatch(); @@ -126,31 +131,31 @@ class Stage extends GDisplayObjectContainer /// Access the keyboard instance of the owner `SceneController`, /// Only available when [SceneConfig.useKeyboard] is true. - KeyboardManager get keyboard { - if (scene?.core?.keyboard == null) { + KeyboardManager? get keyboard { + if (scene.core.keyboard == null) { throw Exception( 'You need to enable keyboard capture, define useKeyboard=true ' - 'in your SceneController'); + 'in your SceneController'); } - return scene?.core?.keyboard; + return scene.core.keyboard; } /// Access the pointer (mouse or touch info) instance of the /// owner `SceneController`, /// Only available when [SceneConfig.usePointer] is true. - PointerManager get pointer { - if (scene?.core?.pointer == null) { + PointerManager? get pointer { + if (scene.core.pointer == null) { throw 'You need to enable pointer capture, define usePointer=true ' 'in your SceneController'; } - return scene?.core?.pointer; + return scene.core.pointer; } @override bool hitTouch(GPoint localPoint, [bool useShape = false]) => true; @override - GDisplayObject hitTest(GPoint localPoint, [bool useShapes = false]) { + GDisplayObject? hitTest(GPoint localPoint, [bool useShapes = false]) { if (!visible || !mouseEnabled) return null; /// location outside stage area, is not accepted. @@ -184,7 +189,7 @@ class Stage extends GDisplayObjectContainer } } - GRect getStageBounds(GDisplayObject targetSpace, [GRect out]) { + GRect getStageBounds(GDisplayObject targetSpace, [GRect? out]) { out ??= GRect(); out.setTo(0, 0, stageWidth, stageHeight); getTransformationMatrix(targetSpace, _sMatrix); @@ -209,8 +214,8 @@ class Stage extends GDisplayObjectContainer void dispose() { _size = null; _backgroundPaint = null; - scene?.core?.pointer?.dispose(); - scene?.core?.keyboard?.dispose(); + scene.core.pointer?.dispose(); + scene.core.keyboard?.dispose(); $disposeResizeSignals(); $disposeTickerSignals(); $disposeStagePointerSignals(); @@ -224,22 +229,22 @@ class Stage extends GDisplayObjectContainer double get height => throw 'Use `stage.stageHeight` instead.'; @override - set width(double value) => throw 'Cannot set width of stage'; + set width(double? value) => throw 'Cannot set width of stage'; @override - set height(double value) => throw 'Cannot set height of stage'; + set height(double? value) => throw 'Cannot set height of stage'; @override - set x(double value) => throw 'Cannot set x-coordinate of stage'; + set x(double? value) => throw 'Cannot set x-coordinate of stage'; @override - set y(double value) => throw 'Cannot set y-coordinate of stage'; + set y(double? value) => throw 'Cannot set y-coordinate of stage'; @override - set scaleX(double value) => throw 'Cannot scale stage'; + set scaleX(double? value) => throw 'Cannot scale stage'; @override - set scaleY(double value) => throw 'Cannot scale stage'; + set scaleY(double? value) => throw 'Cannot scale stage'; @override set pivotX(double value) => throw 'Cannot pivot stage'; @@ -254,5 +259,5 @@ class Stage extends GDisplayObjectContainer set skewY(double value) => throw 'Cannot skew stage'; @override - set rotation(double value) => throw 'Cannot rotate stage'; + set rotation(double? value) => throw 'Cannot rotate stage'; } diff --git a/lib/src/display/text.dart b/lib/src/display/text.dart index 2bcc1a7..b2cf8c5 100644 --- a/lib/src/display/text.dart +++ b/lib/src/display/text.dart @@ -3,9 +3,9 @@ import 'package:flutter/painting.dart' as painting; import '../../graphx.dart'; class GText extends GDisplayObject { - ui.Paragraph _paragraph; + ui.Paragraph? _paragraph; - Signal _onFontLoaded; + Signal? _onFontLoaded; Signal get onFontLoaded => _onFontLoaded ??= Signal(); @@ -15,7 +15,7 @@ class GText extends GDisplayObject { final _alphaPaint = ui.Paint(); @override - GRect getBounds(GDisplayObject targetSpace, [GRect out]) { + GRect getBounds(GDisplayObject? targetSpace, [GRect? out]) { validate(); out ??= GRect(); out.setTo(0, 0, intrinsicWidth, textHeight); @@ -42,27 +42,27 @@ class GText extends GDisplayObject { // return r; // } - ui.Paragraph get paragraph => _paragraph; + ui.Paragraph? get paragraph => _paragraph; // ui.TextStyle _style; - painting.TextStyle _style; + painting.TextStyle? _style; - double _width; + double _width = 0.0; - ui.ParagraphBuilder _builder; - ui.ParagraphStyle _paragraphStyle; + late ui.ParagraphBuilder _builder; + ui.ParagraphStyle? _paragraphStyle; bool _invalidSize = true; bool _invalidBuilder = true; - String _text; - ui.Color backgroundColor; + String? _text; + ui.Color? backgroundColor; - ui.Color get color { - return _style.color; + ui.Color? get color { + return _style!.color; } - set color(ui.Color value) { - _style = _style.copyWith(color: value); + set color(ui.Color? value) { + _style = _style!.copyWith(color: value); _invalidBuilder = true; // _invalidateBuilder(); } @@ -77,7 +77,7 @@ class GText extends GDisplayObject { String get text => _text ?? ''; - set text(String value) { + set text(String? value) { if (_text == value) return; _text = value ?? ''; _invalidBuilder = true; @@ -88,7 +88,7 @@ class GText extends GDisplayObject { double get width => _width; @override - set width(double value) { + set width(double? value) { if (value == null || _width == value) return; _width = value; _invalidSize = true; @@ -158,15 +158,15 @@ class GText extends GDisplayObject { // } GText({ - String text, - ui.ParagraphStyle paragraphStyle, - painting.TextStyle textStyle, + String? text, + ui.ParagraphStyle? paragraphStyle, + painting.TextStyle? textStyle, double width = double.infinity, }) { - painting.PaintingBinding.instance.systemFonts.addListener(_fontLoaded); + painting.PaintingBinding.instance!.systemFonts.addListener(_fontLoaded); this.text = text; - _width = width ?? double.infinity; + _width = width; _invalidBuilder = true; _invalidSize = true; setTextStyle(textStyle ?? defaultTextStyle); @@ -182,32 +182,32 @@ class GText extends GDisplayObject { @override void dispose() { super.dispose(); - painting.PaintingBinding.instance.systemFonts.removeListener(_fontLoaded); + painting.PaintingBinding.instance!.systemFonts.removeListener(_fontLoaded); _onFontLoaded?.removeAll(); _onFontLoaded = null; } void setTextStyle(painting.TextStyle style) { - if (style == null || _style == style) return; + if (_style == style) return; _style = style; _invalidBuilder = true; } - painting.TextStyle getTextStyle() => _style; + painting.TextStyle? getTextStyle() => _style; - ui.ParagraphStyle getParagraphStyle() => _paragraphStyle; + ui.ParagraphStyle? getParagraphStyle() => _paragraphStyle; void setParagraphStyle(ui.ParagraphStyle style) { - if (style == null || _paragraphStyle == style) return; + if (_paragraphStyle == style) return; _paragraphStyle = style; _invalidBuilder = true; } void _invalidateBuilder() { _paragraphStyle ??= defaultParagraphStyle; - _builder = ui.ParagraphBuilder(_paragraphStyle); + _builder = ui.ParagraphBuilder(_paragraphStyle!); // if (_style != null) _builder.pushStyle(_style); - if (_style != null) _builder.pushStyle(_style.getTextStyle()); + if (_style != null) _builder.pushStyle(_style!.getTextStyle()); _builder.addText(_text ?? ''); _paragraph = _builder.build(); _invalidBuilder = false; @@ -227,14 +227,14 @@ class GText extends GDisplayObject { /// applies the painting after the DisplayObject transformations. /// Should be overriden by subclasses. @override - void $applyPaint(ui.Canvas canvas) { + void $applyPaint(ui.Canvas? canvas) { super.$applyPaint(canvas); if (_text == '') return; validate(); - if (backgroundColor != null && backgroundColor.alpha > 0) { - canvas.drawRect( + if (backgroundColor != null && backgroundColor!.alpha > 0) { + canvas!.drawRect( ui.Rect.fromLTWH(0, 0, intrinsicWidth, textHeight), - ui.Paint()..color = backgroundColor, + ui.Paint()..color = backgroundColor!, ); } if (_paragraph != null) { @@ -243,18 +243,18 @@ class GText extends GDisplayObject { // final alphaPaint = PainterUtils.getAlphaPaint($alpha); // final alphaPaint = _alphaPaint; // var bounds = Rect.fromLTWH(0, 0, textWidth, textHeight); - canvas.saveLayer(null, _alphaPaint); - canvas.drawParagraph(_paragraph, ui.Offset.zero); + canvas!.saveLayer(null, _alphaPaint); + canvas.drawParagraph(_paragraph!, ui.Offset.zero); canvas.restore(); } else { - canvas.drawParagraph(_paragraph, ui.Offset.zero); + canvas!.drawParagraph(_paragraph!, ui.Offset.zero); } } } @override set alpha(double value) { - final changed = value != $alpha && value != null; + final changed = value != $alpha; super.alpha = value; if (changed) { _alphaPaint.color = _alphaPaint.color.withOpacity($alpha); @@ -278,32 +278,31 @@ class GText extends GDisplayObject { /// Factory method to simplify the initialization of a StaticText instance. /// You can pass the parent object directly in the `doc` parameter. static GText build({ - String text, - GDisplayObjectContainer doc, - ui.Color color, + String? text, + GDisplayObjectContainer? doc, + ui.Color? color, double w = double.infinity, - ui.TextDecoration decoration, - ui.Color decorationColor, - ui.TextDecorationStyle decorationStyle, - double decorationThickness, - ui.FontWeight fontWeight, - ui.FontStyle fontStyle, - ui.TextBaseline textBaseline, - String fontFamily, - List fontFamilyFallback, - double fontSize, - double letterSpacing, - double wordSpacing, - double height, - ui.Locale locale, - ui.Paint background, - ui.Paint foreground, - List shadows, - List fontFeatures, + ui.TextDecoration? decoration, + ui.Color? decorationColor, + ui.TextDecorationStyle? decorationStyle, + double? decorationThickness, + ui.FontWeight? fontWeight, + ui.FontStyle? fontStyle, + ui.TextBaseline? textBaseline, + String? fontFamily, + List? fontFamilyFallback, + double? fontSize, + double? letterSpacing, + double? wordSpacing, + double? height, + ui.Locale? locale, + ui.Paint? background, + ui.Paint? foreground, + List? shadows, + List? fontFeatures, ui.TextAlign textAlign = ui.TextAlign.left, ui.TextDirection direction = ui.TextDirection.ltr, }) { - w ??= double.infinity; if (w == double.infinity && textAlign != ui.TextAlign.left) { throw "[StaticText] To use $textAlign you need to specify the width"; } diff --git a/lib/src/events/callback_params.dart b/lib/src/events/callback_params.dart index c1b2874..491c1d0 100644 --- a/lib/src/events/callback_params.dart +++ b/lib/src/events/callback_params.dart @@ -1,14 +1,14 @@ class CallbackParams { - List positional; + List? positional; /// Symbol is represented by the literal # in Dart. /// So, if u need `({String name, int count})` in named parameters. /// You'd use {#name: 'roi', #count: 10}. - Map named; + Map? named; CallbackParams([this.positional, this.named]); - static CallbackParams parse(Object args) { + static CallbackParams? parse(Object? args) { if (args == null) return null; if (args is CallbackParams) return args; @@ -16,7 +16,7 @@ class CallbackParams { if (args is List) { return CallbackParams(args); } else if (args is Map) { - return CallbackParams(null, args); + return CallbackParams(null, args as Map?); } return CallbackParams([args]); diff --git a/lib/src/events/keyboard_data.dart b/lib/src/events/keyboard_data.dart index afa5809..0a30697 100644 --- a/lib/src/events/keyboard_data.dart +++ b/lib/src/events/keyboard_data.dart @@ -4,36 +4,36 @@ import 'package:flutter/widgets.dart'; enum KeyEventType { down, up } class KeyboardEventData { - final KeyEventType type; - final RawKeyEvent rawEvent; + final KeyEventType? type; + final RawKeyEvent? rawEvent; KeyboardEventData({this.type, this.rawEvent}); bool isPressed(LogicalKeyboardKey key) { - return rawEvent.isKeyPressed(key); + return rawEvent!.isKeyPressed(key); } bool isKey(LogicalKeyboardKey key) { - return rawEvent.logicalKey == key; + return rawEvent!.logicalKey == key; } } extension MyKeyEventExt on KeyboardEventData { bool get arrowLeft { // return rawEvent.isKeyPressed(LogicalKeyboardKey.arrowLeft); - return rawEvent.logicalKey == LogicalKeyboardKey.arrowLeft; + return rawEvent!.logicalKey == LogicalKeyboardKey.arrowLeft; } bool get arrowRight { - return rawEvent.logicalKey == LogicalKeyboardKey.arrowRight; + return rawEvent!.logicalKey == LogicalKeyboardKey.arrowRight; // return rawEvent.isKeyPressed(LogicalKeyboardKey.arrowRight); } bool get arrowUp { - return rawEvent.logicalKey == LogicalKeyboardKey.arrowUp; + return rawEvent!.logicalKey == LogicalKeyboardKey.arrowUp; } bool get arrowDown { - return rawEvent.logicalKey == LogicalKeyboardKey.arrowDown; + return rawEvent!.logicalKey == LogicalKeyboardKey.arrowDown; } } diff --git a/lib/src/events/mixins.dart b/lib/src/events/mixins.dart index d5c5753..e62751d 100644 --- a/lib/src/events/mixins.dart +++ b/lib/src/events/mixins.dart @@ -27,7 +27,7 @@ mixin EventDispatcherMixin implements Listenable { } mixin TickerSignalMixin { - EventSignal $onEnterFrame; + EventSignal? $onEnterFrame; EventSignal get onEnterFrame => $onEnterFrame ??= EventSignal(); @@ -39,7 +39,7 @@ mixin TickerSignalMixin { } mixin ResizeSignalMixin { - Signal $onResized; + Signal? $onResized; Signal get onResized => $onResized ??= Signal(); void $disposeResizeSignals() { @@ -49,19 +49,19 @@ mixin ResizeSignalMixin { } mixin DisplayListSignalsMixin { - Signal $onAdded; + Signal? $onAdded; Signal get onAdded => $onAdded ??= Signal(); - Signal $onRemoved; + Signal? $onRemoved; Signal get onRemoved => $onRemoved ??= Signal(); - Signal $onRemovedFromStage; + Signal? $onRemovedFromStage; Signal get onRemovedFromStage => $onRemovedFromStage ??= Signal(); - Signal $onAddedToStage; + Signal? $onAddedToStage; Signal get onAddedToStage => $onAddedToStage ??= Signal(); @@ -78,13 +78,14 @@ mixin DisplayListSignalsMixin { } mixin RenderSignalMixin { - EventSignal $onPrePaint; - EventSignal $onPostPaint; + EventSignal? $onPrePaint; + EventSignal? $onPostPaint; // EventSignal $onPaint; - EventSignal get onPrePaint => $onPrePaint ??= EventSignal(); + EventSignal get onPrePaint => $onPrePaint ??= EventSignal(); - EventSignal get onPostPaint => $onPostPaint ??= EventSignal(); + EventSignal get onPostPaint => + $onPostPaint ??= EventSignal(); // EventSignal get onPaint => $onPaint ??= EventSignal(); @@ -100,8 +101,8 @@ mixin RenderSignalMixin { /// use mouse signal for now. mixin StageMouseSignalsMixin { - EventSignal $onMouseLeave; - EventSignal $onMouseEnter; + EventSignal? $onMouseLeave; + EventSignal? $onMouseEnter; EventSignal get onMouseLeave => $onMouseLeave ??= EventSignal(); EventSignal get onMouseEnter => $onMouseEnter ??= EventSignal(); @@ -116,15 +117,15 @@ mixin StageMouseSignalsMixin { /// use mouse signal for now. mixin MouseSignalsMixin { - EventSignal $onRightMouseDown; - EventSignal $onMouseDoubleClick; - EventSignal $onMouseClick; - EventSignal $onMouseDown; - EventSignal $onMouseUp; - EventSignal $onMouseMove; - EventSignal $onMouseOut; - EventSignal $onMouseOver; - EventSignal $onMouseWheel; + EventSignal? $onRightMouseDown; + EventSignal? $onMouseDoubleClick; + EventSignal? $onMouseClick; + EventSignal? $onMouseDown; + EventSignal? $onMouseUp; + EventSignal? $onMouseMove; + EventSignal? $onMouseOut; + EventSignal? $onMouseOver; + EventSignal? $onMouseWheel; EventSignal get onMouseClick => $onMouseClick ??= EventSignal(); EventSignal get onMouseDoubleClick => @@ -160,12 +161,12 @@ mixin MouseSignalsMixin { } mixin PointerSignalsMixin { - EventSignal $onClick; - EventSignal $onDown; - EventSignal $onUp; - EventSignal $onHover; - EventSignal $onOut; - EventSignal $onScroll; + EventSignal? $onClick; + EventSignal? $onDown; + EventSignal? $onUp; + EventSignal? $onHover; + EventSignal? $onOut; + EventSignal? $onScroll; EventSignal get onClick => $onClick ??= EventSignal(); EventSignal get onDown => $onDown ??= EventSignal(); diff --git a/lib/src/events/mps.dart b/lib/src/events/mps.dart index 045d0a3..741fbf7 100644 --- a/lib/src/events/mps.dart +++ b/lib/src/events/mps.dart @@ -10,15 +10,15 @@ final mps = MPS(); /// - publish(N) = emit(N) /// Accepts a "once()" event like signals. class MPS { - final _cache = >{}; + final _cache = >{}; final _cacheOnce = >{}; void publishParams(String topic, CallbackParams args) { // final subs = _cache[topic]; // subs?.forEach((fn) => Function.apply(fn, args?.positional, args?.named)); - void _send(Function fn) => - Function.apply(fn, args?.positional, args?.named); + void _send(Function? fn) => + Function.apply(fn!, args.positional, args.named); _cache[topic]?.forEach(_send); _cacheOnce[topic]?.forEach(_send); @@ -27,7 +27,7 @@ class MPS { void publish1(String topic, T arg1) { // _cache[topic]?.forEach((fn) => fn.call(arg1)); - void _send(Function fn) => fn.call(arg1); + void _send(Function? fn) => fn!.call(arg1); _cache[topic]?.forEach(_send); _cacheOnce[topic]?.forEach(_send); _cacheOnce.remove(topic); @@ -35,7 +35,7 @@ class MPS { void publish2(String topic, T arg1, S arg2) { // _cache[topic]?.forEach((fn) => fn.call(arg1, arg2)); - void _send(Function fn) => fn.call(arg1, arg2); + void _send(Function? fn) => fn!.call(arg1, arg2); _cache[topic]?.forEach(_send); _cacheOnce[topic]?.forEach(_send); _cacheOnce.remove(topic); @@ -43,7 +43,7 @@ class MPS { void publish(String topic) { // _cache[topic]?.forEach((fn) => fn.call()); - void _send(Function fn) => fn.call(); + void _send(Function? fn) => fn!.call(); _cache[topic]?.forEach(_send); _cacheOnce[topic]?.forEach(_send); _cacheOnce.remove(topic); @@ -72,8 +72,8 @@ class MPS { if (!_cacheOnce.containsKey(topic)) { _cacheOnce[topic] = []; } - if (!_cacheOnce[topic].contains(callback)) { - _cacheOnce[topic].add(callback); + if (!_cacheOnce[topic]!.contains(callback)) { + _cacheOnce[topic]!.add(callback); return true; } return false; @@ -84,16 +84,16 @@ class MPS { _cache[topic] = []; // cache[topic] = LinkedList(); } - if (!_cache[topic].contains(callback)) { + if (!_cache[topic]!.contains(callback)) { // cache[topic].add(Callback(callback)); - _cache[topic].add(callback); + _cache[topic]!.add(callback); return true; } return false; } bool unsubscribe(String topic, Function callback) { - final subs = _cache[topic]; + final subs = _cache[topic]!; return subs.remove(callback); // subs.remove(Callback._hash[callback]); // int len = subs?.length ?? 0; @@ -114,53 +114,53 @@ class MPS { return _cacheOnce[topic]?.length ?? 0; } - void off(String topic, Function callback) { + void off(String topic, Function? callback) { _cache[topic]?.remove(callback); _cacheOnce[topic]?.remove(callback); } MPS emit(String topic) { - void _send(Function fn) => fn.call(); + void _send(Function? fn) => fn!.call(); _cache[topic]?.forEach(_send); _cacheOnce[topic]?.forEach(_send); - _cacheOnce?.remove(topic); + _cacheOnce.remove(topic); return this; } - MPS on(String topic, Function callback) { + MPS on(String topic, Function? callback) { if (!_cache.containsKey(topic)) { _cache[topic] = []; } - if (!_cache[topic].contains(callback)) { - _cache[topic].add(callback); + if (!_cache[topic]!.contains(callback)) { + _cache[topic]!.add(callback); } return this; } void emit1(String topic, T arg1) { - void _send(Function fn) => fn.call(arg1); + void _send(Function? fn) => fn!.call(arg1); _cache[topic]?.forEach(_send); _cacheOnce[topic]?.forEach(_send); _cacheOnce.remove(topic); } void emit2(String topic, T arg1, S arg2) { - void _send(Function fn) => fn.call(arg1, arg2); + void _send(Function? fn) => fn!.call(arg1, arg2); _cache[topic]?.forEach(_send); _cacheOnce[topic]?.forEach(_send); _cacheOnce.remove(topic); } void emit3(String topic, A arg1, B arg2, C arg3) { - void _send(Function fn) => fn.call(arg1, arg2, arg3); + void _send(Function? fn) => fn!.call(arg1, arg2, arg3); _cache[topic]?.forEach(_send); _cacheOnce[topic]?.forEach(_send); _cacheOnce.remove(topic); } void emitParams(String topic, CallbackParams args) { - void _send(Function fn) => - Function.apply(fn, args?.positional, args?.named); + void _send(Function? fn) => + Function.apply(fn!, args.positional, args.named); _cache[topic]?.forEach(_send); _cacheOnce[topic]?.forEach(_send); _cacheOnce.remove(topic); diff --git a/lib/src/events/pointer_data.dart b/lib/src/events/pointer_data.dart index 7ff9fe9..668fcc6 100644 --- a/lib/src/events/pointer_data.dart +++ b/lib/src/events/pointer_data.dart @@ -17,11 +17,11 @@ enum PointerEventType { class PointerEventData { final double stageX; final double stageY; - final PointerEventType type; + final PointerEventType? type; final PointerEvent rawEvent; /// local position in DisplayObject - GPoint localPosition; + late GPoint localPosition; double get localX => localPosition.x; @@ -32,7 +32,7 @@ class PointerEventData { /// 300 milliseconds for double click static int doubleClickTime = 300; - PointerEventData({this.type, this.rawEvent}) + PointerEventData({this.type, required this.rawEvent}) : stageX = rawEvent.localPosition.dx, stageY = rawEvent.localPosition.dy { localPosition = GPoint(stageX, stageY); @@ -40,14 +40,14 @@ class PointerEventData { int get time => rawEvent.timeStamp.inMilliseconds; - Offset get scrollDelta { + Offset? get scrollDelta { if (rawEvent is PointerScrollEvent) { return (rawEvent as PointerScrollEvent).scrollDelta; } return null; } - GPoint get windowPosition => GPoint.fromNative(rawEvent.original.position); + GPoint get windowPosition => GPoint.fromNative(rawEvent.original!.position); GPoint get stagePosition => GPoint.fromNative(rawEvent.localPosition); @@ -66,8 +66,8 @@ class PointerEventData { /// new properties. /// TODO: decide how to name mouse/pointer events. - GDisplayObject target; - GDisplayObject dispatcher; + GDisplayObject? target; + GDisplayObject? dispatcher; bool captured = false; bool mouseOut = false; @@ -127,23 +127,23 @@ class MouseInputData { } /// display objects - GDisplayObject target; - GDisplayObject dispatcher; - MouseInputType type; + GDisplayObject? target; + GDisplayObject? dispatcher; + MouseInputType? type; bool buttonDown = false; bool mouseOut = false; double time = 0; - PointerEventData rawEvent; + PointerEventData? rawEvent; /// defines which button is pressed... - int buttonsFlags; + int? buttonsFlags; bool get isSecondaryDown => - buttonsFlags & kSecondaryButton == kSecondaryButton; + buttonsFlags! & kSecondaryButton == kSecondaryButton; - bool get isPrimaryDown => buttonsFlags & kPrimaryButton == kPrimaryButton; + bool get isPrimaryDown => buttonsFlags! & kPrimaryButton == kPrimaryButton; - bool get isTertiaryDown => buttonsFlags & 0x04 == 0x04; + bool get isTertiaryDown => buttonsFlags! & 0x04 == 0x04; GPoint get stagePosition => _stagePosition; final GPoint _stagePosition = GPoint(); @@ -155,16 +155,16 @@ class MouseInputData { double get localY => localPosition.y; - double get windowX => rawEvent?.rawEvent?.original?.position?.dx ?? 0; + double get windowX => rawEvent?.rawEvent.original?.position.dx ?? 0; - double get windowY => rawEvent?.rawEvent?.original?.position?.dy ?? 0; + double get windowY => rawEvent?.rawEvent.original?.position.dy ?? 0; - double get stageX => _stagePosition?.x ?? 0; + double get stageX => _stagePosition.x; - double get stageY => _stagePosition?.y ?? 0; + double get stageY => _stagePosition.y; GPoint get localDelta { - final d = rawEvent?.rawEvent?.localDelta; + final d = rawEvent?.rawEvent.localDelta; if (d == null) { return _localDelta.setEmpty(); } @@ -172,11 +172,11 @@ class MouseInputData { } static int uniqueId = 0; - int uid; + int? uid; MouseInputData({this.target, this.dispatcher, this.type}); MouseInputData clone( - GDisplayObject target, GDisplayObject dispatcher, MouseInputType type) { + GDisplayObject target, GDisplayObject dispatcher, MouseInputType? type) { var input = MouseInputData( target: target, dispatcher: dispatcher, @@ -205,7 +205,7 @@ class MouseInputData { // } // int get time => rawEvent.rawEvent.timeStamp.inMilliseconds; - static MouseInputType fromNativeType(PointerEventType nativeType) { + static MouseInputType fromNativeType(PointerEventType? nativeType) { if (nativeType == PointerEventType.down) { return MouseInputType.down; } else if (nativeType == PointerEventType.up) { diff --git a/lib/src/events/signal.dart b/lib/src/events/signal.dart index 44c726f..acbc6a7 100644 --- a/lib/src/events/signal.dart +++ b/lib/src/events/signal.dart @@ -17,12 +17,12 @@ class Signal { void add(Function callback) { // if (callback == null || _listenersOnce.contains(callback)) return; - if (callback == null || has(callback)) return; + if (has(callback)) return; _listeners.add(callback); } void addOnce(Function callback) { - if (callback == null || _listeners.contains(callback)) return; + if (_listeners.contains(callback)) return; _listenersOnce.add(callback); } @@ -44,22 +44,22 @@ class Signal { void dispatch() { final len = _listeners.length; for (_iterDispatchers = 0; _iterDispatchers < len; ++_iterDispatchers) { - _listeners[_iterDispatchers]?.call(); + _listeners[_iterDispatchers].call(); } final lenCount = _listenersOnce.length; for (var i = 0; i < lenCount; i++) { - _listenersOnce.removeAt(0)?.call(); + _listenersOnce.removeAt(0).call(); } } void dispatchWithData(dynamic data) { final len = _listeners.length; for (_iterDispatchers = 0; _iterDispatchers < len; ++_iterDispatchers) { - _listeners[_iterDispatchers]?.call(data); + _listeners[_iterDispatchers].call(data); } final lenCount = _listenersOnce.length; for (var i = 0; i < lenCount; i++) { - _listenersOnce.removeAt(i)?.call(data); + _listenersOnce.removeAt(i).call(data); } } } @@ -81,12 +81,12 @@ class EventSignal { bool hasListeners() => _listeners.isNotEmpty || _listenersOnce.isNotEmpty; void add(EventSignalCallback callback) { - if (callback == null || has(callback)) return; + if (has(callback)) return; _listeners.add(callback); } void addOnce(EventSignalCallback callback) { - if (callback == null || _listeners.contains(callback)) return; + if (_listeners.contains(callback)) return; _listenersOnce.add(callback); } @@ -94,9 +94,9 @@ class EventSignal { final idx = _listeners.indexOf(callback); if (idx > -1) { if (idx <= _iterDispatchers) _iterDispatchers--; - _listeners?.removeAt(idx); + _listeners.removeAt(idx); } else { - _listenersOnce?.remove(callback); + _listenersOnce.remove(callback); } } @@ -108,10 +108,10 @@ class EventSignal { void dispatch(T data) { for (var i = 0; i < _listeners.length; ++i) { // if (id > 0) print('Calling ::: $i - ${_listeners.length}'); - _listeners[i]?.call(data); + _listeners[i].call(data); } for (var i = 0; i < _listenersOnce.length; i++) { - _listenersOnce?.removeAt(i)?.call(data); + _listenersOnce.removeAt(i).call(data); } } } diff --git a/lib/src/extensions/display_object.dart b/lib/src/extensions/display_object.dart index 0af3291..5648b78 100644 --- a/lib/src/extensions/display_object.dart +++ b/lib/src/extensions/display_object.dart @@ -3,23 +3,23 @@ import '../../graphx.dart'; extension DisplayObjectHelpers on GDisplayObject { void centerInStage() { if (!inStage) return; - setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); } void setProps({ - Object x, - Object y, - Object scaleX, - Object scaleY, - Object scale, - Object rotation, - Object pivotX, - Object pivotY, - Object width, - Object height, - Object skewX, - Object skewY, - Object alpha, + Object? x, + Object? y, + Object? scaleX, + Object? scaleY, + Object? scale, + Object? rotation, + Object? pivotX, + Object? pivotY, + Object? width, + Object? height, + Object? skewX, + Object? skewY, + Object? alpha, double delay = 0, }) { tween( diff --git a/lib/src/geom/color_matrix.dart b/lib/src/geom/color_matrix.dart index bd3f085..0e7d932 100644 --- a/lib/src/geom/color_matrix.dart +++ b/lib/src/geom/color_matrix.dart @@ -50,11 +50,11 @@ class ColorMatrix { // ignore: non_constant_identifier_names static final int LENGTH = IDENTITY_MATRIX.length; - final _storage = List(25); + final _storage = List.filled(25, null); - ColorMatrix([List matrix]) { + ColorMatrix([List? matrix]) { matrix = _fixMatrix(matrix); - copyMatrix(((matrix.length == LENGTH) ? matrix : IDENTITY_MATRIX)); + copyMatrix(((matrix!.length == LENGTH) ? matrix : IDENTITY_MATRIX)); } // public methods: @@ -77,7 +77,7 @@ class ColorMatrix { } void adjustBrightness(double percent) { - if (percent == null || percent == 0 || percent.isNaN) return; + if (percent == 0 || percent.isNaN) return; if (percent >= -1 && percent <= 1) { percent *= 100; } @@ -96,7 +96,7 @@ class ColorMatrix { } void adjustContrast(double percent) { - if (percent == null || percent == 0 || percent.isNaN) return; + if (percent == 0 || percent.isNaN) return; if (percent >= -1 && percent <= 1) { percent *= 100; } @@ -132,7 +132,7 @@ class ColorMatrix { } void adjustSaturation(double percent) { - if (percent == null || percent == 0 || percent.isNaN) return; + if (percent == 0 || percent.isNaN) return; if (percent >= -1 && percent <= 1) { percent *= 100; } @@ -156,7 +156,7 @@ class ColorMatrix { } void adjustHue(double percent) { - if (percent == null || percent == 0 || percent.isNaN) return; + if (percent == 0 || percent.isNaN) return; if (percent >= -1 && percent <= 1) { percent *= 180; } @@ -192,9 +192,9 @@ class ColorMatrix { ]); } - void concat(List pMatrix) { + void concat(List? pMatrix) { pMatrix = _fixMatrix(pMatrix); - if (pMatrix.length != LENGTH) return; + if (pMatrix!.length != LENGTH) return; multiplyMatrix(pMatrix); } @@ -204,20 +204,20 @@ class ColorMatrix { String toString() => "ColorMatrix [ ${_storage.join(" , ")} ]"; /// return a length 20 array (5x4): - List get storage => + List get storage => _storage.sublist(0, math.min(_storage.length, 20)).toList(); /// private methods: /// copy the specified matrix's values to this matrix: - void copyMatrix(List pMatrix) { + void copyMatrix(List? pMatrix) { for (var i = 0; i < LENGTH; i++) { - _storage[i] = pMatrix[i]; + _storage[i] = pMatrix![i]; } } /// multiplies one matrix against another: - void multiplyMatrix(List pMatrix) { - var col = List(25); + void multiplyMatrix(List? pMatrix) { + var col = List.filled(25, null); for (var i = 0; i < 5; i++) { for (var j = 0; j < 5; j++) { @@ -226,7 +226,7 @@ class ColorMatrix { for (var j = 0; j < 5; j++) { var val = 0.0; for (var k = 0; k < 5; k++) { - val += pMatrix[j + k * 5] * col[k]; + val += pMatrix![j + k * 5]! * col[k]!; } _storage[j + i * 5] = val; } @@ -239,7 +239,7 @@ class ColorMatrix { math.min(pLimit, math.max(-pLimit, pVal)); /// makes sure matrixes are 5x5 (25 long): - List _fixMatrix([List pMatrix]) { + List? _fixMatrix([List? pMatrix]) { if (pMatrix == null) return IDENTITY_MATRIX; if (pMatrix.length < LENGTH) { pMatrix = List.from(pMatrix) diff --git a/lib/src/geom/gxmatrix.dart b/lib/src/geom/gxmatrix.dart index 4983d5c..57fb0f5 100644 --- a/lib/src/geom/gxmatrix.dart +++ b/lib/src/geom/gxmatrix.dart @@ -3,16 +3,16 @@ import 'package:flutter/material.dart'; import 'geom.dart'; class GMatrix { - double a, b, c, d, tx, ty; - Matrix4 _native; + double a = 0.0, b = 0.0, c = 0.0, d = 0.0, tx = 0.0, ty = 0.0; + Matrix4? _native; @override String toString() { return 'GxMatrix {a: $a, b: $b, c: $c, d: $d, tx: $tx, ty: $ty}'; } - Matrix4 toNative() { + Matrix4? toNative() { _native ??= Matrix4.identity(); - _native.setValues(a, b, 0, 0, c, d, 0, 0, 0, 0, 1, 0, tx, ty, 0, 1); + _native!.setValues(a, b, 0, 0, c, d, 0, 0, 0, 0, 1, 0, tx, ty, 0, 1); return _native; } @@ -143,16 +143,16 @@ class GMatrix { GMatrix concat(GMatrix matrix) { double a1, c1, tx1; - a1 = a * matrix.a + b * matrix.c; - b = a * matrix.b + b * matrix.d; + a1 = a * matrix.a+ b* matrix.c; + b = a* matrix.b+ b* matrix.d; a = a1; - c1 = c * matrix.a + d * matrix.c; - d = c * matrix.b + d * matrix.d; + c1 = c* matrix.a+ d* matrix.c; + d = c* matrix.b+ d* matrix.d; c = c1; - tx1 = tx * matrix.a + ty * matrix.c + matrix.tx; - ty = tx * matrix.b + ty * matrix.d + matrix.ty; + tx1 = tx* matrix.a+ ty* matrix.c+ matrix.tx; + ty = tx* matrix.b+ ty* matrix.d+ matrix.ty; tx = tx1; return this; @@ -186,26 +186,26 @@ class GMatrix { //} GMatrix invert() { - var n = a * d - b * c; + var n = a* d- b* c; if (n == 0) { a = b = c = d = 0; tx = -tx; ty = -ty; } else { n = 1 / n; - var a1 = d * n; - d = a * n; + var a1 = d* n; + d = a* n; a = a1; b *= -n; c *= -n; - var tx1 = -a * tx - c * ty; - ty = -b * tx - d * ty; + var tx1 = -a* tx- c* ty; + ty = -b* tx- d* ty; tx = tx1; } return this; } - GMatrix scale(double scaleX, [double scaleY]) { + GMatrix scale(double scaleX, [double? scaleY]) { scaleY ??= scaleX; a *= scaleX; b *= scaleY; @@ -225,12 +225,12 @@ class GMatrix { var sinY = math.sin(skewY); var cosY = math.cos(skewY); setTo( - a * cosY - b * sinX, - a * sinY + b * cosX, - c * cosY - d * sinX, - c * sinY + d * cosX, - tx * cosY - ty * sinX, - tx * sinY + ty * cosX, + a* cosY - b* sinX, + a* sinY + b* cosX, + c* cosY - d* sinX, + c* sinY + d* cosX, + tx* cosY - ty* sinX, + tx* sinY + ty* cosX, ); } @@ -238,16 +238,16 @@ class GMatrix { final cos = math.cos(angle); final sin = math.sin(angle); - var a1 = a * cos - b * sin; - b = a * sin + b * cos; + var a1 = a* cos - b* sin; + b = a* sin + b* cos; a = a1; - var c1 = c * cos - d * sin; - d = c * sin + d * cos; + var c1 = c* cos - d* sin; + d = c* sin + d* cos; c = c1; - var tx1 = tx * cos - ty * sin; - ty = tx * sin + ty * cos; + var tx1 = tx* cos - ty* sin; + ty = tx* sin + ty* cos; tx = tx1; } @@ -257,26 +257,26 @@ class GMatrix { return this; } - GPoint transformPoint(GPoint point, [GPoint out]) { + GPoint transformPoint(GPoint point, [GPoint? out]) { return transformCoords(point.x, point.y, out); } - GPoint transformInversePoint(GPoint point, [GPoint out]) { + GPoint transformInversePoint(GPoint point, [GPoint? out]) { return transformInverseCoords(point.x, point.y, out); } - GPoint transformInverseCoords(double x, double y, [GPoint out]) { + GPoint transformInverseCoords(double x, double y, [GPoint? out]) { out ??= GPoint(); - final id = 1 / ((a * d) + (c * -b)); - out.x = (d * id * x) + (-c * id * y) + (((ty * c) - (tx * d)) * id); - out.y = (a * id * y) + (-b * id * x) + (((-ty * a) + (tx * b)) * id); + final id = 1 / ((a* d) + (c* -b)); + out.x = (d* id * x) + (-c* id * y) + (((ty* c) - (tx* d)) * id); + out.y = (a* id * y) + (-b* id * x) + (((-ty* a) + (tx* b)) * id); return out; } - GPoint transformCoords(double x, double y, [GPoint out]) { + GPoint transformCoords(double x, double y, [GPoint? out]) { out ??= GPoint(); - out.x = a * x + c * y + tx; - out.y = d * y + b * x + ty; + out.x = a* x + c* y + tx; + out.y = d* y + b* x + ty; return out; } } diff --git a/lib/src/geom/gxrect.dart b/lib/src/geom/gxrect.dart index 431d7f7..b11c139 100644 --- a/lib/src/geom/gxrect.dart +++ b/lib/src/geom/gxrect.dart @@ -18,7 +18,7 @@ class GRect { return Rect.fromLTWH(x, y, width, height); } - double x, y, width, height; + double x = 0.0, y = 0.0, width = 0.0, height = 0.0; double get bottom => y + height; @@ -54,10 +54,10 @@ class GRect { return this; } - static List _sHelperPositions; + static List? _sHelperPositions; static final _sHelperPoint = GPoint(); - GRect getBounds(GMatrix matrix, [GRect out]) { + GRect getBounds(GMatrix matrix, [GRect? out]) { out ??= GRect(); var minX = 10000000.0; var maxX = -10000000.0; @@ -74,10 +74,10 @@ class GRect { return out.setTo(minX, minY, maxX - minX, maxY - minY); } - List getPositions([List out]) { + List getPositions([List? out]) { out ??= List.generate(4, (i) => GPoint()); for (var i = 0; i < 4; ++i) { - out[i] ??= GPoint(); + out[i]; } out[2].x = out[0].x = left; out[1].y = out[0].y = top; @@ -181,16 +181,16 @@ class GRect { } /// --- Round Rect implementation --- - GxRectCornerRadius _corners; + GxRectCornerRadius? _corners; bool get hasCorners => _corners?.isNotEmpty ?? false; - GxRectCornerRadius get corners { + GxRectCornerRadius? get corners { _corners ??= GxRectCornerRadius(); return _corners; } - set corners(GxRectCornerRadius value) => _corners = value; + set corners(GxRectCornerRadius? value) => _corners = value; - RRect toRoundNative() => corners.toNative(this); + RRect toRoundNative() => corners!.toNative(this); /// Creates a GxRect from a `RRect` assigning the `GxRectCornerRadius` /// properties from the tr, tl, br, bl radiusX axis. @@ -200,7 +200,7 @@ class GRect { nativeRect.top, nativeRect.width, nativeRect.height, - )..corners.setTo( + )..corners!.setTo( nativeRect.tlRadiusX, nativeRect.trRadiusX, nativeRect.brRadiusX, diff --git a/lib/src/input/input_converter.dart b/lib/src/input/input_converter.dart index a2a3324..8f85cd6 100644 --- a/lib/src/input/input_converter.dart +++ b/lib/src/input/input_converter.dart @@ -8,28 +8,28 @@ import 'keyboard_manager.dart'; import 'pointer_manager.dart'; class InputConverter { - final PointerManager pointer; - final KeyboardManager keyboard; + final PointerManager? pointer; + final KeyboardManager? keyboard; InputConverter(this.pointer, this.keyboard); /// mouse stuffs. void pointerEnter(PointerEnterEvent event) { - pointer.$process(PointerEventData( + pointer!.$process(PointerEventData( type: PointerEventType.enter, rawEvent: event, )); } void pointerExit(PointerExitEvent event) { - pointer.$process(PointerEventData( + pointer!.$process(PointerEventData( type: PointerEventType.exit, rawEvent: event, )); } void pointerHover(PointerHoverEvent event) { - pointer.$process(PointerEventData( + pointer!.$process(PointerEventData( type: PointerEventType.hover, rawEvent: event, )); @@ -38,35 +38,35 @@ class InputConverter { /// touchable stuffs. void pointerSignal(PointerSignalEvent event) { - pointer.$process(PointerEventData( + pointer!.$process(PointerEventData( type: PointerEventType.scroll, rawEvent: event as PointerScrollEvent, )); } void pointerMove(PointerMoveEvent event) { - pointer.$process(PointerEventData( + pointer!.$process(PointerEventData( type: PointerEventType.move, rawEvent: event, )); } void pointerCancel(PointerCancelEvent event) { - pointer.$process(PointerEventData( + pointer!.$process(PointerEventData( type: PointerEventType.cancel, rawEvent: event, )); } void pointerUp(PointerUpEvent event) { - pointer.$process(PointerEventData( + pointer!.$process(PointerEventData( type: PointerEventType.up, rawEvent: event, )); } void pointerDown(PointerDownEvent event) { - pointer.$process(PointerEventData( + pointer!.$process(PointerEventData( type: PointerEventType.down, rawEvent: event, )); @@ -74,7 +74,7 @@ class InputConverter { void handleKey(RawKeyEvent event) { final isDown = event is RawKeyDownEvent; - keyboard.$process(KeyboardEventData( + keyboard!.$process(KeyboardEventData( type: isDown ? KeyEventType.down : KeyEventType.up, rawEvent: event, )); diff --git a/lib/src/input/keyboard_manager.dart b/lib/src/input/keyboard_manager.dart index 43ac18e..06399f2 100644 --- a/lib/src/input/keyboard_manager.dart +++ b/lib/src/input/keyboard_manager.dart @@ -4,7 +4,7 @@ import 'package:flutter/services.dart'; import '../../graphx.dart'; class KeyboardManager { - FocusNode _focusNode; + FocusNode? _focusNode; FocusNode get focusNode => _focusNode ??= FocusNode(); @@ -17,12 +17,12 @@ class KeyboardManager { } EventSignal get onDown => _onDown ??= EventSignal(); - EventSignal _onDown; + EventSignal? _onDown; EventSignal get onUp => _onUp ??= EventSignal(); - EventSignal _onUp; + EventSignal? _onUp; - KeyboardEventData _lastEvent; + KeyboardEventData? _lastEvent; bool isPressed(LogicalKeyboardKey key) { return _lastEvent?.rawEvent?.isKeyPressed(key) ?? false; @@ -39,9 +39,9 @@ class KeyboardManager { void $process(KeyboardEventData event) { _lastEvent = event; if (event.type == KeyEventType.down) { - _onDown?.dispatch(event); + _onDown?.dispatch(event as T); } else { - _onUp?.dispatch(event); + _onUp?.dispatch(event as T); } } } diff --git a/lib/src/input/mouse.dart b/lib/src/input/mouse.dart index 1b7dfb4..317337f 100644 --- a/lib/src/input/mouse.dart +++ b/lib/src/input/mouse.dart @@ -6,14 +6,14 @@ export 'package:flutter/rendering.dart' show SystemMouseCursor; /// Accessible from `pointer_manager.dart` abstract class GMouse { - static SystemMouseCursor _cursor; - static SystemMouseCursor _lastCursor; + static SystemMouseCursor? _cursor; + static SystemMouseCursor? _lastCursor; - static SystemMouseCursor get cursor => _cursor; + static SystemMouseCursor? get cursor => _cursor; static void setClickCursor()=> cursor = SystemMouseCursors.click; - static set cursor(SystemMouseCursor value) { + static set cursor(SystemMouseCursor? value) { value ??= SystemMouseCursors.basic; if (_cursor == value) return; if (_cursor != SystemMouseCursors.none) { @@ -24,7 +24,7 @@ abstract class GMouse { 'activateSystemCursor', { 'device': 1, - 'kind': cursor.kind, + 'kind': cursor!.kind, }, ); } diff --git a/lib/src/input/pointer_manager.dart b/lib/src/input/pointer_manager.dart index c8b7541..9f61dbf 100644 --- a/lib/src/input/pointer_manager.dart +++ b/lib/src/input/pointer_manager.dart @@ -4,9 +4,9 @@ import 'package:flutter/services.dart'; import '../../graphx.dart'; class PointerManager { - SystemMouseCursor get cursor => _cursor; + SystemMouseCursor? get cursor => _cursor; - set cursor(SystemMouseCursor val) { + set cursor(SystemMouseCursor? val) { val ??= SystemMouseCursors.basic; if (_cursor == val) return; if (_cursor != SystemMouseCursors.none) { @@ -19,7 +19,7 @@ class PointerManager { 'activateSystemCursor', { 'device': 1, - 'kind': cursor.kind, + 'kind': cursor!.kind, }, ); } @@ -36,37 +36,37 @@ class PointerManager { cursor = val ? _lastCursor : SystemMouseCursors.none; } - SystemMouseCursor _cursor; - SystemMouseCursor _lastCursor; + SystemMouseCursor? _cursor; + SystemMouseCursor? _lastCursor; EventSignal get onInput => _onInput ??= EventSignal(); - EventSignal _onInput; + EventSignal? _onInput; EventSignal get onDown => _onDown ??= EventSignal(); - EventSignal _onDown; + EventSignal? _onDown; EventSignal get onUp => _onUp ??= EventSignal(); - EventSignal _onUp; + EventSignal? _onUp; EventSignal get onCancel => _onCancel ??= EventSignal(); - EventSignal _onCancel; + EventSignal? _onCancel; EventSignal get onMove => _onMove ??= EventSignal(); - EventSignal _onMove; + EventSignal? _onMove; EventSignal get onScroll => _onScroll ??= EventSignal(); - EventSignal _onScroll; + EventSignal? _onScroll; EventSignal get onHover => _onHover ??= EventSignal(); - EventSignal _onHover; + EventSignal? _onHover; EventSignal get onExit => _onExit ??= EventSignal(); - EventSignal _onExit; + EventSignal? _onExit; EventSignal get onEnter => _onEnter ??= EventSignal(); - EventSignal _onEnter; + EventSignal? _onEnter; - PointerEventData _lastEvent; + PointerEventData? _lastEvent; final Map _signalMapper = {}; PointerManager() { @@ -82,16 +82,16 @@ class PointerManager { _signalMapper[PointerEventType.exit] = () => _onExit; } - bool get isDown => _lastEvent?.rawEvent?.down ?? false; + bool get isDown => _lastEvent?.rawEvent.down ?? false; - double get mouseX => _lastEvent?.rawEvent?.localPosition?.dx ?? 0; + double get mouseX => _lastEvent?.rawEvent.localPosition.dx ?? 0; - double get mouseY => _lastEvent?.rawEvent?.localPosition?.dy ?? 0; + double get mouseY => _lastEvent?.rawEvent.localPosition.dy ?? 0; void $process(PointerEventData event) { final signal = _signalMapper[event.type](); _lastEvent = event; - onInput?.dispatch(event); + onInput.dispatch(event as T); signal?.dispatch(event); } @@ -105,6 +105,6 @@ class PointerManager { _onHover?.removeAll(); _onExit?.removeAll(); _onEnter?.removeAll(); - _lastEvent=null; + _lastEvent = null; } } diff --git a/lib/src/io/network_image_loader.dart b/lib/src/io/network_image_loader.dart index efbd18d..5909a01 100644 --- a/lib/src/io/network_image_loader.dart +++ b/lib/src/io/network_image_loader.dart @@ -11,19 +11,19 @@ class NetworkImageEvent { int bytesLoaded = 0; /// only svg responses. - String svgString; - SvgData svgData; + String? svgString; + SvgData? svgData; - double get percentLoaded => bytesLoaded / contentLength; - Image image; + double get percentLoaded => bytesLoaded / contentLength!; + Image? image; double scale = 1; - GTexture _texture; + GTexture? _texture; final http.BaseResponse response; - GTexture get texture { + GTexture? get texture { if (image == null) return null; - _texture ??= GTexture.fromImage(image, scale); + _texture ??= GTexture.fromImage(image!, scale); return _texture; } @@ -32,10 +32,10 @@ class NetworkImageEvent { bool get isImage => image != null; bool get isSvg => svgString != null; - int get contentLength => response.contentLength; + int? get contentLength => response.contentLength; int get statusCode => response.statusCode; - String get reasonPhrase => response.reasonPhrase; - http.BaseRequest get request => response.request; + String? get reasonPhrase => response.reasonPhrase; + http.BaseRequest? get request => response.request; Map get headers => response.headers; bool get isError => statusCode > 300; @@ -57,12 +57,12 @@ class NetworkImageLoader { static Future load( String url, { - int width, - int height, + int? width, + int? height, double scale = 1, - Function(NetworkImageEvent) onComplete, - Function(NetworkImageEvent) onProgress, - Function(NetworkImageEvent) onError, + Function(NetworkImageEvent)? onComplete, + Function(NetworkImageEvent)? onProgress, + Function(NetworkImageEvent)? onError, }) async { Completer completer = Completer(); var loadedBytes = []; @@ -73,52 +73,60 @@ class NetworkImageLoader { var response = _client.send(_request); void dispatchError(NetworkImageEvent eventData) { if (onError != null) { - onError?.call(eventData); + onError.call(eventData); completer.complete(eventData); } else { completer.completeError(eventData); } } - response.asStream().listen((r) { - var eventData = NetworkImageEvent(r); - eventData.scale = scale; - r.stream.listen((chunk) { - loadedBytes.addAll(chunk); - bytesLoaded += chunk.length; - eventData.bytesLoaded = bytesLoaded; - onProgress?.call(eventData); - }, onError: (error) { - dispatchError(eventData); - }, onDone: () async { - if (eventData.isError) { - dispatchError(eventData); - return null; - } - var bytes = Uint8List.fromList(loadedBytes); - final codec = await instantiateImageCodec( - bytes, - allowUpscaling: false, - targetWidth: width, - targetHeight: height, + response.asStream().listen( + (r) { + var eventData = NetworkImageEvent(r); + eventData.scale = scale; + r.stream.listen( + (chunk) { + loadedBytes.addAll(chunk); + bytesLoaded += chunk.length; + eventData.bytesLoaded = bytesLoaded; + onProgress?.call(eventData); + }, + onError: (error) { + dispatchError(eventData); + }, + onDone: () async { + if (eventData.isError) { + dispatchError(eventData); + return null; + } + var bytes = Uint8List.fromList(loadedBytes); + final codec = await instantiateImageCodec( + bytes, + allowUpscaling: false, + targetWidth: width, + targetHeight: height, + ); + eventData.image = (await codec.getNextFrame()).image; + onComplete?.call(eventData); + completer.complete(eventData); + //TODO fix this + // return eventData; + + // Save the file + // File file = new File('$dir/$filename'); + // final Uint8List bytes = Uint8List(r.contentLength); + // int offset = 0; + // for (List chunk in chunks) { + // bytes.setRange(offset, offset + chunk.length, chunk); + // offset += chunk.length; + // } + // await file.writeAsBytes(bytes); + // return; + }, ); - eventData.image = (await codec.getNextFrame()).image; - onComplete?.call(eventData); - completer.complete(eventData); - return eventData; - // Save the file - // File file = new File('$dir/$filename'); - // final Uint8List bytes = Uint8List(r.contentLength); - // int offset = 0; - // for (List chunk in chunks) { - // bytes.setRange(offset, offset + chunk.length, chunk); - // offset += chunk.length; - // } - // await file.writeAsBytes(bytes); - // return; - }); - }); - return completer.future; + }, + ); + return completer.future as FutureOr; // var result = await client.get(url); // var bytes = result.bodyBytes; // final codec = await instantiateImageCodec( diff --git a/lib/src/io/resource_loader.dart b/lib/src/io/resource_loader.dart index cdcdaf7..40ab762 100644 --- a/lib/src/io/resource_loader.dart +++ b/lib/src/io/resource_loader.dart @@ -9,7 +9,7 @@ import 'network_image_loader.dart'; abstract class ResourceLoader { static Map svgs = {}; - static Map textures = {}; + static Map textures = {}; static Map atlases = {}; static Map gifs = {}; @@ -18,7 +18,7 @@ abstract class ResourceLoader { vo.dispose(); } for (var vo in textures.values) { - vo.dispose(); + vo!.dispose(); } for (var vo in atlases.values) { vo.dispose(); @@ -28,26 +28,26 @@ abstract class ResourceLoader { } } - static GTexture getTexture(String cacheId) { + static GTexture? getTexture(String cacheId) { return textures[cacheId]; } - static SvgData getSvg(String cacheId) { + static SvgData? getSvg(String cacheId) { return svgs[cacheId]; } - static GTextureAtlas getAtlas(String cacheId) { + static GTextureAtlas? getAtlas(String cacheId) { return atlases[cacheId]; } - static GifAtlas getGif(String cacheId) { + static GifAtlas? getGif(String cacheId) { return gifs[cacheId]; } - static Future loadGif( + static Future loadGif( String path, { double resolution = 1.0, - String cacheId, + String? cacheId, }) async { if (cacheId != null && gifs.containsKey(cacheId)) { return gifs[cacheId]; @@ -56,7 +56,6 @@ abstract class ResourceLoader { final data = await rootBundle.load(path); final bytes = Uint8List.view(data.buffer); final codec = await ui.instantiateImageCodec(bytes, allowUpscaling: false); - resolution ??= GTextureUtils.resolution; final atlas = GifAtlas(); atlas.scale = resolution; @@ -73,12 +72,12 @@ abstract class ResourceLoader { return atlas; } - static Future loadNetworkTextureSimple( + static Future loadNetworkTextureSimple( String url, { - int width, - int height, + int? width, + int? height, double resolution = 1.0, - String cacheId, + String? cacheId, }) async { if (cacheId != null && textures.containsKey(cacheId)) { return textures[cacheId]; @@ -123,15 +122,15 @@ abstract class ResourceLoader { // return response.svgData; // } - static Future loadNetworkTexture( + static Future loadNetworkTexture( String url, { - int width, - int height, + int? width, + int? height, double resolution = 1.0, - String cacheId, - Function(NetworkImageEvent) onComplete, - Function(NetworkImageEvent) onProgress, - Function(NetworkImageEvent) onError, + String? cacheId, + Function(NetworkImageEvent)? onComplete, + Function(NetworkImageEvent)? onProgress, + Function(NetworkImageEvent)? onError, }) async { if (cacheId != null && textures.containsKey(cacheId)) { return textures[cacheId]; @@ -151,10 +150,10 @@ abstract class ResourceLoader { return response.texture; } - static Future loadTexture( + static Future loadTexture( String path, [ double resolution = 1.0, - String cacheId, + String? cacheId, ]) async { if (cacheId != null && textures.containsKey(cacheId)) { return textures[cacheId]; @@ -175,11 +174,11 @@ abstract class ResourceLoader { // return svgs[cacheId]; // } - static Future loadTextureAtlas( + static Future loadTextureAtlas( String imagePath, { - String dataPath, + String? dataPath, double resolution = 1.0, - String cacheId, + String? cacheId, }) async { if (cacheId != null && atlases.containsKey(cacheId)) { return atlases[cacheId]; @@ -210,8 +209,8 @@ abstract class ResourceLoader { /// load local assets. static Future loadImage( String path, { - int targetWidth, - int targetHeight, + int? targetWidth, + int? targetHeight, }) async { final data = await rootBundle.load(path); final bytes = Uint8List.view(data.buffer); diff --git a/lib/src/log/trace.dart b/lib/src/log/trace.dart index ce729f8..040c1e9 100644 --- a/lib/src/log/trace.dart +++ b/lib/src/log/trace.dart @@ -17,7 +17,7 @@ String _tagPaddingChar = ', '; /// [tagPaddingCount] should be applied manually if you wanna have a cleaner /// tabulated view. void traceConfig({ - String customTag, + String? customTag, int tagPaddingCount = 0, String tagPaddingChar = ' ', bool showFilename = false, @@ -30,12 +30,12 @@ void traceConfig({ _tagPaddingCount = tagPaddingCount; _tagPaddingChar = tagPaddingChar; _customTag = customTag ?? 'graphx™🌀'; - _showFilename = showFilename ?? false; - _showLinenumber = showLinenumber ?? false; - _showClassname = showClassname ?? false; - _showMethodname = showMethodname ?? false; - _showOutsideTag = showOutsideTag ?? false; - _separator = argsSeparator ?? ', '; + _showFilename = showFilename; + _showLinenumber = showLinenumber; + _showClassname = showClassname; + _showMethodname = showMethodname; + _showOutsideTag = showOutsideTag; + _separator = argsSeparator; _useStack = _showFilename || _showClassname || _showMethodname; } @@ -43,16 +43,17 @@ void traceConfig({ /// `trace` works. It has up to 10 arguments slots so you can pass any type of /// object to be printed. The way trace() shows output in the console can be /// defined with [traceConfig()]. -void trace(Object arg1, [ - Object arg2, - Object arg3, - Object arg4, - Object arg5, - Object arg6, - Object arg7, - Object arg8, - Object arg9, - Object arg10, +void trace( + Object arg1, [ + Object? arg2, + Object? arg3, + Object? arg4, + Object? arg5, + Object? arg6, + Object? arg7, + Object? arg8, + Object? arg9, + Object? arg10, ]) { ++_traceCount; final outputList = [ @@ -118,8 +119,7 @@ String _stackCommon(String stack) { var callLine = locationParts[1]; var filename = filePath.substring( filePath.lastIndexOf('/') + 1, filePath.lastIndexOf('.')); - String methodName, - className = ''; + String methodName, className = ''; var output = ''; //ˇ if (_showFilename) { output += '$filename '; @@ -138,7 +138,7 @@ String _stackCommon(String stack) { className = elements.removeAt(0); methodName = elements.join('.'); methodName = - '${methodName.replaceAll(_anonymousMethodTag, '<⁕>')}$_sufixCall'; + '${methodName.replaceAll(_anonymousMethodTag, '<⁕>')}$_sufixCall'; if (_showClassname) { output += '‣ $className '; } @@ -147,4 +147,4 @@ String _stackCommon(String stack) { } } return output; -} \ No newline at end of file +} diff --git a/lib/src/math.dart b/lib/src/math.dart index c88d7d6..09346ed 100644 --- a/lib/src/math.dart +++ b/lib/src/math.dart @@ -83,6 +83,8 @@ abstract class Math { /// Evaluates `a` and `b` and returns the largest value. static final max = m.max; + // * OLD code + // static final max = m.max as T Function(T, T); /// Evaluates `a` and `b` and returns the smallest value. static final min = m.min; @@ -92,22 +94,22 @@ abstract class Math { /// Returns the ceiling of the specified number or expression. /// Parameter `keepDouble` enforces the return type to be `double`. - static num ceil(double value, [bool keepDouble = true]) { - return keepDouble ? value?.ceilToDouble() : value?.ceil(); + static num? ceil(double value, [bool keepDouble = true]) { + return keepDouble ? value.ceilToDouble() : value.ceil(); } /// Returns the floor of the number or expression specified in the parameter /// `value`. /// Parameter `keepDouble` enforces the return type to be `double`. - static num floor(double value, [bool keepDouble = true]) { - return keepDouble ? value?.floorToDouble() : value?.floor(); + static num? floor(double value, [bool keepDouble = true]) { + return keepDouble ? value.floorToDouble() : value.floor(); } /// Rounds the value of the parameter `value` up or down to the nearest /// integer and returns the value. /// Parameter `keepDouble` enforces the return type to be `double`. - static num round(double value, [bool keepDouble = true]) { - return keepDouble ? value?.roundToDouble() : value?.round(); + static num? round(double value, [bool keepDouble = true]) { + return keepDouble ? value.roundToDouble() : value.round(); } /// Computes and returns an absolute value for the number specified by @@ -147,7 +149,7 @@ abstract class Math { static double randomRangeClamp(num min, num max, num clamp) => (randomRange(min.toDouble(), max.toDouble()) / clamp.toDouble()) .roundToDouble() * - clamp.toDouble(); + clamp.toDouble(); /// Returns a pseudo-random `int` number between parameters `min` and /// `max`, clamping the returned value to `clamp`. @@ -155,7 +157,7 @@ abstract class Math { /// And `min` > `max`. static int randomRangeIntClamp(num min, num max, num clamp) => (randomRangeInt(min.toInt(), max.toInt()) / clamp.toInt()).round() * - clamp.toInt(); + clamp.toInt(); static double norm(num value, num min, num max) { return (value - min) / (max - min); diff --git a/lib/src/render/filters/blur_filter.dart b/lib/src/render/filters/blur_filter.dart index 3e570d9..16f64e6 100644 --- a/lib/src/render/filters/blur_filter.dart +++ b/lib/src/render/filters/blur_filter.dart @@ -17,7 +17,7 @@ class GBaseFilter { void buildFilter() {} bool get isValid => true; - GRect layerBounds; + GRect? layerBounds; void expandBounds(GRect layerBounds, GRect outputBounds) { this.layerBounds = layerBounds; } @@ -51,8 +51,8 @@ class GBlurFilter extends GBaseFilter { this.blurY = blurY; } - ui.MaskFilter _maskFilter; - ui.ImageFilter _imageFilter; + ui.MaskFilter? _maskFilter; + ui.ImageFilter? _imageFilter; final _rect = GRect(); GRect get filterRect => _rect; @@ -76,7 +76,7 @@ class GBlurFilter extends GBaseFilter { /// if it goes under a threshold (I tried .2 and lower), it flickers. /// idk which logic uses, but 1.0 seems like a stable min number for the /// mask. - _maskFilter = ui.MaskFilter.blur(style ?? ui.BlurStyle.inner, maxBlur); + _maskFilter = ui.MaskFilter.blur(style, maxBlur); _imageFilter = ui.ImageFilter.blur(sigmaX: _blurX, sigmaY: _blurY); } diff --git a/lib/src/render/filters/color_filter.dart b/lib/src/render/filters/color_filter.dart index 7359fcd..23ec3e2 100644 --- a/lib/src/render/filters/color_filter.dart +++ b/lib/src/render/filters/color_filter.dart @@ -48,7 +48,7 @@ class GColorFilters { } class GColorMatrixFilter extends GBaseFilter { - ColorFilter colorFilter; + ColorFilter? colorFilter; GColorMatrixFilter(this.colorFilter); diff --git a/lib/src/render/filters/composer_filter.dart b/lib/src/render/filters/composer_filter.dart index ed3fe90..c93eeb6 100644 --- a/lib/src/render/filters/composer_filter.dart +++ b/lib/src/render/filters/composer_filter.dart @@ -9,7 +9,7 @@ class GComposerFilter extends GBaseFilter { @override void resolvePaint(ui.Paint paint) {} - void process(ui.Canvas canvas, Function applyPaint, [int processCount = 1]) { + void process(ui.Canvas? canvas, Function applyPaint, [int processCount = 1]) { /// todo: figure the area. // canvas.saveLayer(null, paint); // canvas.translate(_dx, _dy); diff --git a/lib/src/render/filters/dropshadow_filter.dart b/lib/src/render/filters/dropshadow_filter.dart index 67470e1..b8e2500 100644 --- a/lib/src/render/filters/dropshadow_filter.dart +++ b/lib/src/render/filters/dropshadow_filter.dart @@ -27,7 +27,7 @@ class GDropShadowFilter extends GComposerFilter { Color get color => _color; double _dx = 0, _dy = 0; - set color(Color value) { + set color(Color? value) { if (_color == value) return; _color = value ?? kColorBlack; dirty = true; @@ -41,7 +41,6 @@ class GDropShadowFilter extends GComposerFilter { } set distance(double value) { - value ??= 0; if (_distance == value) return; _distance = value; _calculatePosition(); @@ -81,9 +80,9 @@ class GDropShadowFilter extends GComposerFilter { this.hideObject = hideObject; } - ColorFilter _colorFilter; - MaskFilter _maskFilter; - ImageFilter _imageFilter; + ColorFilter? _colorFilter; + MaskFilter? _maskFilter; + ImageFilter? _imageFilter; final _rect = GRect(); GRect get filterRect => _rect; @@ -117,7 +116,7 @@ class GDropShadowFilter extends GComposerFilter { /// if it goes under a threshold (I tried .2 and lower), it flickers. /// idk which logic uses, but 1.0 seems like a stable min number for the /// mask. - _maskFilter = MaskFilter.blur(style ?? BlurStyle.inner, maxBlur); + _maskFilter = MaskFilter.blur(style, maxBlur); _imageFilter = ImageFilter.blur( sigmaX: Math.max(_blurX, _minBlur), sigmaY: Math.max(_blurY, _minBlur), @@ -132,8 +131,8 @@ class GDropShadowFilter extends GComposerFilter { } @override - void process(Canvas canvas, Function applyPaint, [int processCount = 1]) { - canvas.saveLayer(null, paint); + void process(Canvas? canvas, Function applyPaint, [int processCount = 1]) { + canvas!.saveLayer(null, paint); // final bb = layerBounds.clone(); // bb.inflate(_strength, _strength); canvas.translate(_dx, _dy); diff --git a/lib/src/render/filters/glow_filter.dart b/lib/src/render/filters/glow_filter.dart index 6031658..739fbd5 100644 --- a/lib/src/render/filters/glow_filter.dart +++ b/lib/src/render/filters/glow_filter.dart @@ -23,7 +23,7 @@ class GlowFilter extends GComposerFilter { ui.Color get color => _color; - set color(ui.Color value) { + set color(ui.Color? value) { if (_color == value) return; _color = value ?? kColorBlack; dirty = true; @@ -53,9 +53,9 @@ class GlowFilter extends GComposerFilter { this.hideObject = hideObject; } - ui.ColorFilter _colorFilter; - ui.MaskFilter _maskFilter; - ui.ImageFilter _imageFilter; + ui.ColorFilter? _colorFilter; + ui.MaskFilter? _maskFilter; + ui.ImageFilter? _imageFilter; final _rect = GRect(); @@ -81,7 +81,7 @@ class GlowFilter extends GComposerFilter { maxBlur = Math.max(_blurX, _blurY) / 2; if (maxBlur < 1) maxBlur = 1; } - _maskFilter = ui.MaskFilter.blur(style ?? ui.BlurStyle.normal, maxBlur); + _maskFilter = ui.MaskFilter.blur(style, maxBlur); _imageFilter = ui.ImageFilter.blur(sigmaX: _blurX, sigmaY: _blurY); _colorFilter = ui.ColorFilter.mode( _color.withAlpha(255), @@ -98,13 +98,13 @@ class GlowFilter extends GComposerFilter { // var _iterations = 0; @override - void process(ui.Canvas canvas, Function applyPaint, [int processCount = 1]) { + void process(ui.Canvas? canvas, Function applyPaint, [int processCount = 1]) { // trace('rect is: ', _outBounds); // var a = GxRect(0, 0, layerBounds.width - layerBounds.x, // layerBounds.height - layerBounds.y); // trace(layerBounds, _rect); // canvas.saveLayer(layerBounds.toNative(), paint); - canvas.saveLayer(null, paint); + canvas!.saveLayer(null, paint); applyPaint(canvas); canvas.restore(); if (++processCount <= iterations) { diff --git a/lib/src/render/graphics.dart b/lib/src/render/graphics.dart index a1a71a4..6c28be3 100644 --- a/lib/src/render/graphics.dart +++ b/lib/src/render/graphics.dart @@ -10,17 +10,17 @@ enum GradientType { } class Graphics with RenderUtilMixin implements GxRenderable { - final _drawingQueue = []; - GraphicsDrawingData _currentDrawing = GraphicsDrawingData(null, Path()); + final _drawingQueue = []; + GraphicsDrawingData? _currentDrawing = GraphicsDrawingData(null, Path()); double alpha = 1; static final GMatrix _helperMatrix = GMatrix(); - Graphics mask; + Graphics? mask; bool isMask = false; - Path get _path => _currentDrawing.path; + Path? get _path => _currentDrawing!.path; static final Path stageRectPath = Path(); @@ -31,16 +31,16 @@ class Graphics with RenderUtilMixin implements GxRenderable { void dispose() { mask = null; - _drawingQueue?.clear(); + _drawingQueue.clear(); _currentDrawing = null; } - List get drawingQueue => _drawingQueue; + List get drawingQueue => _drawingQueue; void copyFrom(Graphics other, [bool deepClone = false]) { _drawingQueue.clear(); for (final command in other._drawingQueue) { - _drawingQueue.add(command.clone(deepClone, deepClone)); + _drawingQueue.add(command!.clone(deepClone, deepClone)); } mask = other.mask; alpha = other.alpha; @@ -52,7 +52,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { /// a bigger CPU hit. /// In [Graphics] "paths" are separated by [Paint] drawing commands: /// [beginFill()] and [lineStyle()] - List getAllBounds([List out]) { + List getAllBounds([List? out]) { out ??= []; for (var e in _drawingQueue) { final pathRect = e?.path?.getBounds(); @@ -63,8 +63,8 @@ class Graphics with RenderUtilMixin implements GxRenderable { } @override - GRect getBounds([GRect out]) { - Rect r; + GRect getBounds([GRect? out]) { + Rect? r; for (var e in _drawingQueue) { final pathRect = e?.path?.getBounds(); if (pathRect == null) break; @@ -90,7 +90,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { localPoint.y, ); for (var e in _drawingQueue) { - if (e.path.contains(point)) return true; + if (e!.path!.contains(point)) return true; } return false; } else { @@ -111,7 +111,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { Graphics beginBitmapFill( GTexture texture, [ - GMatrix matrix, + GMatrix? matrix, bool repeat = false, bool smooth = false, ]) { @@ -122,13 +122,13 @@ class Graphics with RenderUtilMixin implements GxRenderable { var tileMode = !repeat ? TileMode.clamp : TileMode.repeated; matrix ??= _helperMatrix; fill.shader = ImageShader( - texture.root, + texture.root!, tileMode, tileMode, - matrix.toNative().storage, + matrix.toNative()!.storage, ); _addFill(fill); - _currentDrawing.shaderTexture = texture; + _currentDrawing!.shaderTexture = texture; return this; } @@ -162,11 +162,11 @@ class Graphics with RenderUtilMixin implements GxRenderable { double thickness = 0.0, Color color = kColorBlack, bool pixelHinting = true, - StrokeCap caps, - StrokeJoin joints, + StrokeCap? caps, + StrokeJoin? joints, double miterLimit = 3.0, ]) { - alpha ??= 1.0; + alpha; alpha = alpha.clamp(0.0, 1.0); final paint = Paint(); paint.style = PaintingStyle.stroke; @@ -188,12 +188,12 @@ class Graphics with RenderUtilMixin implements GxRenderable { Graphics beginGradientFill( GradientType type, List colors, { - List ratios, - Alignment begin, - Alignment end, + List? ratios, + Alignment? begin, + Alignment? end, double rotation = 0, TileMode tileMode = TileMode.clamp, - Rect gradientBox, + Rect? gradientBox, /// only radial double radius = 0.5, @@ -221,9 +221,9 @@ class Graphics with RenderUtilMixin implements GxRenderable { paint.isAntiAlias = true; _addFill(paint); if (gradientBox != null) { - _currentDrawing.fill.shader = gradient.createShader(gradientBox); + _currentDrawing!.fill!.shader = gradient.createShader(gradientBox); } else { - _currentDrawing.gradient = gradient; + _currentDrawing!.gradient = gradient; } return this; } @@ -231,9 +231,9 @@ class Graphics with RenderUtilMixin implements GxRenderable { Gradient _createGradient( GradientType type, List colors, [ - List ratios, - Alignment begin, - Alignment end, + List? ratios, + Alignment? begin, + Alignment? end, double rotation = 0, /// only radial @@ -287,9 +287,9 @@ class Graphics with RenderUtilMixin implements GxRenderable { Graphics lineGradientStyle( GradientType type, List colors, { - List ratios, - Alignment begin, - Alignment end, + List? ratios, + Alignment? begin, + Alignment? end, double rotation = 0, /// only `GradientType.radial` @@ -301,14 +301,14 @@ class Graphics with RenderUtilMixin implements GxRenderable { double sweepEndAngle = 6.2832, /// manually define the bounding box of the Gradient shader. - Rect gradientBox, + Rect? gradientBox, /// when the gradient box is different than the object bounds, you can /// see the `tileMode` behaviour. TileMode tileMode = TileMode.clamp, }) { /// actual paint must be stroke. - assert(_currentDrawing.fill.style == PaintingStyle.stroke); + assert(_currentDrawing!.fill!.style == PaintingStyle.stroke); final gradient = _createGradient( type, @@ -324,48 +324,48 @@ class Graphics with RenderUtilMixin implements GxRenderable { tileMode, ); if (gradientBox != null) { - _currentDrawing.fill.shader = gradient.createShader(gradientBox); + _currentDrawing!.fill!.shader = gradient.createShader(gradientBox); } else { - _currentDrawing.gradient = gradient; + _currentDrawing!.gradient = gradient; } return this; } Graphics lineBitmapStyle( GTexture texture, [ - GMatrix matrix, + GMatrix? matrix, bool repeat = true, bool smooth = false, ]) { /// actual paint must be stroke. - assert(_currentDrawing.fill.style == PaintingStyle.stroke); + assert(_currentDrawing!.fill!.style == PaintingStyle.stroke); if (_holeMode) return this; - final fill = _currentDrawing.fill; + final fill = _currentDrawing!.fill!; fill.isAntiAlias = smooth; var tileMode = !repeat ? TileMode.clamp : TileMode.repeated; matrix ??= _helperMatrix; fill.shader = ImageShader( - texture.root, + texture.root!, tileMode, tileMode, - matrix.toNative().storage, + matrix.toNative()!.storage, ); // _addFill(fill); return this; } Graphics moveTo(double x, double y) { - _path.moveTo(x, y); + _path!.moveTo(x, y); return this; } Graphics lineTo(double x, double y) { - _path.lineTo(x, y); + _path!.lineTo(x, y); return this; } Graphics closePath() { - _path.close(); + _path!.close(); return this; } @@ -377,7 +377,8 @@ class Graphics with RenderUtilMixin implements GxRenderable { double anchorX, double anchorY, ) { - _path.cubicTo(controlX1, controlY1, controlX2, controlY2, anchorX, anchorY); + _path! + .cubicTo(controlX1, controlY1, controlX2, controlY2, anchorX, anchorY); return this; } @@ -387,7 +388,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { double anchorX, double anchorY, ) { - _path.quadraticBezierTo(controlX, controlY, anchorX, anchorY); + _path!.quadraticBezierTo(controlX, controlY, anchorX, anchorY); return this; } @@ -400,9 +401,9 @@ class Graphics with RenderUtilMixin implements GxRenderable { bool relative = false, ]) { if (!relative) { - _path.conicTo(controlX, controlY, anchorX, anchorY, weight); + _path!.conicTo(controlX, controlY, anchorX, anchorY, weight); } else { - _path.relativeConicTo(controlX, controlY, anchorX, anchorY, weight); + _path!.relativeConicTo(controlX, controlY, anchorX, anchorY, weight); } return this; } @@ -410,13 +411,13 @@ class Graphics with RenderUtilMixin implements GxRenderable { Graphics drawCircle(double x, double y, double radius) { final pos = Offset(x, y); final circ = Rect.fromCircle(center: pos, radius: radius); - _path.addOval(circ); + _path!.addOval(circ); return this; } Graphics drawEllipse(double x, double y, double radiusX, double radiusY) { final pos = Offset(x, y); - _path.addOval( + _path!.addOval( Rect.fromCenter( center: pos, width: radiusX * 2, @@ -427,13 +428,13 @@ class Graphics with RenderUtilMixin implements GxRenderable { } Graphics drawGRect(GRect rect) { - _path.addRect(rect.toNative()); + _path!.addRect(rect.toNative()); return this; } Graphics drawRect(double x, double y, double width, double height) { final r = Rect.fromLTWH(x, y, width, height); - _path.addRect(r); + _path!.addRect(r); return this; } @@ -447,7 +448,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { double bottomLeftRadius = 0, double bottomRightRadius = 0, ]) { - _path.addRRect( + _path!.addRRect( RRect.fromLTRBAndCorners( x, y, @@ -468,7 +469,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { double width, double height, double ellipseWidth, [ - double ellipseHeight, + double? ellipseHeight, ]) { final r = RRect.fromLTRBXY( x, @@ -478,17 +479,17 @@ class Graphics with RenderUtilMixin implements GxRenderable { ellipseWidth, ellipseHeight ?? ellipseWidth, ); - _path.addRRect(r); + _path!.addRRect(r); return this; } Graphics drawPoly(List points, [bool closePolygon = true]) { final len = points.length; - final list = List(len); + final list = List.filled(len, null); for (var i = 0; i < len; ++i) { list[i] = points[i].toNative(); } - _path.addPolygon(list, true); + _path!.addPolygon(list as List, true); return this; } @@ -496,7 +497,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { final offset = Offset(x, y); if (modifyPreviousPaths) { for (var command in _drawingQueue) { - command?.path = command?.path?.shift(offset); + command?.path = command.path?.shift(offset); } } else { _currentDrawing?.path = _currentDrawing?.path?.shift(offset); @@ -511,7 +512,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { double startAngle, double sweepAngle, ) { - _path.addArc( + _path!.addArc( Rect.fromCenter( center: Offset(cx, cy), width: radiusX * 2, @@ -533,14 +534,14 @@ class Graphics with RenderUtilMixin implements GxRenderable { ]) { if (sweepAngle == 0) return this; if (!moveTo) { - _path.arcTo( + _path!.arcTo( Rect.fromCircle(center: Offset(cx, cy), radius: radius), startAngle, sweepAngle, false, ); } else { - _path.addArc( + _path!.addArc( Rect.fromCircle(center: Offset(cx, cy), radius: radius), startAngle, sweepAngle, @@ -560,7 +561,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { ]) { if (radius == 0) return this; if (relativeMoveTo) { - _path.arcToPoint( + _path!.arcToPoint( Offset(endX, endY), radius: Radius.circular(radius), clockwise: clockwise, @@ -568,7 +569,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { rotation: rotation, ); } else { - _path.relativeArcToPoint( + _path!.relativeArcToPoint( Offset(endX, endY), radius: Radius.circular(radius), clockwise: clockwise, @@ -587,14 +588,14 @@ class Graphics with RenderUtilMixin implements GxRenderable { int sides, [ double rotation = 0, ]) { - final points = List(sides); + final points = List.filled(sides, null); final rel = 2 * Math.PI / sides; for (var i = 1; i <= sides; ++i) { final px = x + radius * Math.cos(i * rel + rotation); final py = y + radius * Math.sin(i * rel + rotation); points[i - 1] = Offset(px, py); } - _path.addPolygon(points, true); + _path!.addPolygon(points as List, true); return this; } @@ -603,7 +604,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { double y, int points, double radius, [ - double innerRadius, + double? innerRadius, double rotation = 0, ]) { innerRadius ??= radius / 2; @@ -619,7 +620,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { y + (r * Math.sin(a)), )); } - _path.addPolygon(polys, true); + _path!.addPolygon(polys, true); return this; } @@ -640,24 +641,24 @@ class Graphics with RenderUtilMixin implements GxRenderable { Graphics endHole([bool applyToCurrentQueue = false]) { _holeMode = false; // apply to previous elements. - if (!_currentDrawing.isHole) { + if (!_currentDrawing!.isHole) { throw "Can't endHole() without starting a beginHole() command."; // return this; } - final _holePath = _path; + final _holePath = _path!; _holePath.close(); _currentDrawing = _drawingQueue.last; if (!applyToCurrentQueue) { - _currentDrawing.path = Path.combine( + _currentDrawing!.path = Path.combine( PathOperation.difference, - _path, + _path!, _holePath, ); } else { for (final cmd in _drawingQueue) { - cmd.path = Path.combine( + cmd!.path = Path.combine( PathOperation.difference, - cmd.path, + cmd.path!, _holePath, ); } @@ -668,11 +669,11 @@ class Graphics with RenderUtilMixin implements GxRenderable { void paintWithFill(Canvas canvas, Paint fill) { if (!_isVisible) return; for (var graph in _drawingQueue) { - if (graph.hasPicture) { - canvas.drawPicture(graph.picture); + if (graph!.hasPicture) { + canvas.drawPicture(graph.picture!); return; } - canvas.drawPath(graph.path, fill); + canvas.drawPath(graph.path!, fill); } } @@ -681,7 +682,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { if (SystemUtils.usingSkia) { for (var graph in _drawingQueue) { /// unsupported on web. - output = Path.combine(PathOperation.union, output, graph.path); + output = Path.combine(PathOperation.union, output, graph!.path!); } } else { trace('Graphics.getPaths() is unsupported in the current platform.'); @@ -690,11 +691,11 @@ class Graphics with RenderUtilMixin implements GxRenderable { } @override - void paint(Canvas canvas) { + void paint(Canvas? canvas) { // TODO : add mask support. if (isMask) { for (var graph in _drawingQueue) { - canvas.clipPath(graph.path, doAntiAlias: false); + canvas!.clipPath(graph!.path!, doAntiAlias: false); } return; } @@ -703,51 +704,51 @@ class Graphics with RenderUtilMixin implements GxRenderable { // trace("en", _drawingQueue.length); for (var graph in _drawingQueue) { - if (graph.hasPicture) { - canvas.drawPicture(graph.picture); + if (graph!.hasPicture) { + canvas!.drawPicture(graph.picture!); break; } - final fill = graph.fill; + final fill = graph.fill!; final baseColor = fill.color; if (baseColor.alpha == 0) break; /// calculate gradient. if (graph.hasGradient) { - Rect _bounds; + Rect? _bounds; if (graph.hasVertices) { - _bounds = graph.vertices.getBounds(); + _bounds = graph.vertices!.getBounds(); } else { - _bounds = graph.path.getBounds(); + _bounds = graph.path!.getBounds(); } /// TODO: try if this works to change the gradient /// opacity from the Shape. fill.color = baseColor.withOpacity(alpha); - fill.shader = graph.gradient.createShader(_bounds); + fill.shader = graph.gradient!.createShader(_bounds!); } else { if (alpha != 1) { fill.color = baseColor.withOpacity(baseColor.opacity * alpha); } } if (graph.hasVertices) { - if (graph.vertices.uvtData != null && graph.shaderTexture != null) { - graph.vertices.calculateUvt(graph.shaderTexture); + if (graph.vertices!.uvtData != null && graph.shaderTexture != null) { + graph.vertices!.calculateUvt(graph.shaderTexture); } if (fill.style == PaintingStyle.stroke) { - canvas.drawRawPoints( + canvas!.drawRawPoints( ui.PointMode.lines, - graph.vertices.rawPoints, + graph.vertices!.rawPoints!, fill, ); } else { - canvas.drawVertices( - graph.vertices.rawData, - graph.vertices.blendMode ?? BlendMode.src, + canvas!.drawVertices( + graph.vertices!.rawData!, + graph.vertices!.blendMode, fill, ); } } else { - canvas.drawPath(graph.path, fill); + canvas!.drawPath(graph.path!, fill); } fill.color = baseColor; @@ -756,8 +757,8 @@ class Graphics with RenderUtilMixin implements GxRenderable { void _addFill(Paint fill) { /// same type, create path. - Path path; - if (_currentDrawing.isSameType(fill)) { + Path? path; + if (_currentDrawing!.isSameType(fill)) { path = Path(); } else { path = _currentDrawing?.path; @@ -779,11 +780,11 @@ class Graphics with RenderUtilMixin implements GxRenderable { void pushData( GraphicsDrawingData data, [ bool asCurrent = false, - double x, - double y, + double? x, + double? y, ]) { if (x != null && y != null && data.path != null) { - data.path = data.path.shift(Offset(x, y)); + data.path = data.path!.shift(Offset(x, y)); } _drawingQueue.add(data); if (asCurrent) _currentDrawing = data; @@ -792,7 +793,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { /// removes the last `GraphicsDrawingData` from the drawing queue... /// This should be used only if you are operating with `Path` and `Paint` /// directly. - GraphicsDrawingData popData() { + GraphicsDrawingData? popData() { return _drawingQueue.removeLast(); } @@ -815,9 +816,9 @@ class Graphics with RenderUtilMixin implements GxRenderable { Path path, [ double x = 0, double y = 0, - GMatrix transform, + GMatrix? transform, ]) { - _path.addPath( + _path!.addPath( path, Offset(x, y), matrix4: transform?.toNative()?.storage, @@ -830,16 +831,16 @@ class Graphics with RenderUtilMixin implements GxRenderable { /// Doesn't use a Path(), but drawVertices()... Graphics drawTriangles( List vertices, [ - List indices, - List uvtData, - List hexColors, + List? indices, + List? uvtData, + List? hexColors, BlendMode blendMode = BlendMode.src, Culling culling = Culling.positive, ]) { /// will only work if it has a fill. assert(_currentDrawing != null); - assert(_currentDrawing.fill != null); - _currentDrawing.vertices = _GraphVertices( + assert(_currentDrawing!.fill != null); + _currentDrawing!.vertices = _GraphVertices( ui.VertexMode.triangles, vertices, indices, @@ -853,19 +854,19 @@ class Graphics with RenderUtilMixin implements GxRenderable { } class GraphicsDrawingData { - Path path; - Paint fill; + Path? path; + Paint? fill; - Gradient gradient; - ui.Picture picture; + Gradient? gradient; + ui.Picture? picture; bool isHole = false; /// for drawVertices() BlendMode blendMode = BlendMode.src; - _GraphVertices vertices; + _GraphVertices? vertices; /// temporal storage to use with _GraphVertices - GTexture shaderTexture; + GTexture? shaderTexture; bool get hasVertices => vertices != null; @@ -883,7 +884,7 @@ class GraphicsDrawingData { bool clonePath = false, ]) { final _fill = cloneFill ? fill?.clone() : fill; - final _path = clonePath ? (path != null ? Path.from(path) : null) : path; + final _path = clonePath ? (path != null ? Path.from(path!) : null) : path; final _vertices = vertices; return GraphicsDrawingData(_fill, _path) ..gradient = gradient @@ -892,11 +893,11 @@ class GraphicsDrawingData { ..vertices = _vertices; } - bool isSameType(Paint otherFill) => fill?.style == otherFill?.style ?? false; + bool isSameType(Paint otherFill) => fill?.style == otherFill.style; } extension ExtSkiaPaintCustom on Paint { - Paint clone([Paint out]) { + Paint clone([Paint? out]) { out ??= Paint(); out.maskFilter = maskFilter; out.blendMode = blendMode; @@ -919,20 +920,20 @@ extension ExtSkiaPaintCustom on Paint { } class _GraphVertices { - List vertices, uvtData, adjustedUvtData; - List colors, indices; + List? vertices, uvtData, adjustedUvtData; + List? colors, indices; BlendMode blendMode; VertexMode mode; - Path _path; - Rect _bounds; - bool _normalizedUvt; + Path? _path; + Rect? _bounds; + late bool _normalizedUvt; - Float32List _rawPoints; + Float32List? _rawPoints; - Float32List get rawPoints { + Float32List? get rawPoints { if (_rawPoints != null) return _rawPoints; var points = _GraphUtils.getTrianglePoints(this); - _rawPoints = Float32List.fromList(points); + _rawPoints = Float32List.fromList(points as List); return _rawPoints; } @@ -949,14 +950,14 @@ class _GraphVertices { this.culling = Culling.positive, ]) { _normalizedUvt = false; - final len = uvtData.length; + final len = uvtData!.length; if (uvtData != null && len > 6) { for (var i = 0; i < 6; ++i) { - if (uvtData[i] <= 2.0) { + if (uvtData![i]! <= 2.0) { _normalizedUvt = true; } } - if (uvtData[len - 2] <= 2.0 || uvtData[len - 1] <= 2.0) { + if (uvtData![len - 2]! <= 2.0 || uvtData![len - 1]! <= 2.0) { _normalizedUvt = true; } } @@ -968,7 +969,7 @@ class _GraphVertices { _bounds = null; } - Rect getBounds() { + Rect? getBounds() { if (_bounds != null) return _bounds; _bounds = computePath().getBounds(); return _bounds; @@ -976,22 +977,23 @@ class _GraphVertices { Path computePath() => _path ??= _GraphUtils.getPathFromVertices(this); - ui.Vertices _rawData; + ui.Vertices? _rawData; - ui.Vertices get rawData { + ui.Vertices? get rawData { if (_rawData != null) return _rawData; // calculateCulling(); - Float32List _textureCoordinates; - Int32List _colors; - Uint16List _indices; + Float32List? _textureCoordinates; + Int32List? _colors; + Uint16List? _indices; if (uvtData != null && adjustedUvtData != null) { - _textureCoordinates = Float32List.fromList(adjustedUvtData); + _textureCoordinates = + Float32List.fromList(adjustedUvtData as List); } - if (colors != null) _colors = Int32List.fromList(colors); - if (indices != null) _indices = Uint16List.fromList(indices); + if (colors != null) _colors = Int32List.fromList(colors!); + if (indices != null) _indices = Uint16List.fromList(indices!); _rawData = ui.Vertices.raw( VertexMode.triangles, - Float32List.fromList(vertices), + Float32List.fromList(vertices as List), textureCoordinates: _textureCoordinates, colors: _colors, indices: _indices, @@ -999,18 +1001,18 @@ class _GraphVertices { return _rawData; } - void calculateUvt(GTexture shaderTexture) { + void calculateUvt(GTexture? shaderTexture) { if (uvtData == null) return; if (!_normalizedUvt) { adjustedUvtData = uvtData; } else { /// make a ratio of the image size - var imgW = shaderTexture.width; + var imgW = shaderTexture!.width; var imgH = shaderTexture.height; - adjustedUvtData = List(uvtData.length); - for (var i = 0; i < uvtData.length; i += 2) { - adjustedUvtData[i] = uvtData[i] * imgW; - adjustedUvtData[i + 1] = uvtData[i + 1] * imgH; + adjustedUvtData = List.filled(uvtData!.length, null); + for (var i = 0; i < uvtData!.length; i += 2) { + adjustedUvtData![i] = uvtData![i]! * imgW!; + adjustedUvtData![i + 1] = uvtData![i + 1]! * imgH!; } } } @@ -1020,25 +1022,25 @@ class _GraphVertices { var offsetX = 0.0, offsetY = 0.0; var ind = indices; var v = vertices; - var l = indices.length; + var l = indices!.length; while (i < l) { var _a = i; var _b = i + 1; var _c = i + 2; - var iax = ind[_a] * 2; + var iax = ind![_a] * 2; var iay = ind[_a] * 2 + 1; var ibx = ind[_b] * 2; var iby = ind[_b] * 2 + 1; var icx = ind[_c] * 2; var icy = ind[_c] * 2 + 1; - var x1 = v[iax] - offsetX; - var y1 = v[iay] - offsetY; - var x2 = v[ibx] - offsetX; - var y2 = v[iby] - offsetY; - var x3 = v[icx] - offsetX; - var y3 = v[icy] - offsetY; + var x1 = v![iax]! - offsetX; + var y1 = v[iay]! - offsetY; + var x2 = v[ibx]! - offsetX; + var y2 = v[iby]! - offsetY; + var x3 = v[icx]! - offsetX; + var y3 = v[icy]! - offsetY; switch (culling) { case Culling.positive: @@ -1089,23 +1091,23 @@ class _GraphUtils { static Path getPathFromVertices(_GraphVertices v) { var path = _helperPath; path.reset(); - var pos = v.vertices; + var pos = v.vertices!; var len = pos.length; final points = []; for (var i = 0; i < len; i += 2) { - points.add(Offset(pos[i], pos[i + 1])); + points.add(Offset(pos[i]!, pos[i + 1]!)); } path.addPolygon(points, true); return path; } - static List getTrianglePoints(_GraphVertices v) { + static List getTrianglePoints(_GraphVertices v) { var ver = v.vertices; var ind = v.indices; if (ind == null) { /// calculate - var len = ver.length; - var out = List(len * 2); + var len = ver!.length; + var out = List.filled(len * 2, null); var j = 0; for (var i = 0; i < len; i += 6) { out[j++] = ver[i + 0]; @@ -1124,7 +1126,7 @@ class _GraphUtils { return out; } else { var len = ind.length; - var out = List(len * 4); + var out = List.filled(len * 4, null); var j = 0; for (var i = 0; i < len; i += 3) { var i0 = ind[i + 0]; @@ -1133,7 +1135,7 @@ class _GraphUtils { var v0 = i0 * 2; var v1 = i1 * 2; var v2 = i2 * 2; - out[j++] = ver[v0]; + out[j++] = ver![v0]; out[j++] = ver[v0 + 1]; out[j++] = ver[v1]; out[j++] = ver[v1 + 1]; diff --git a/lib/src/render/icon.dart b/lib/src/render/icon.dart index 10e4ddd..27793a5 100644 --- a/lib/src/render/icon.dart +++ b/lib/src/render/icon.dart @@ -9,7 +9,7 @@ class GIcon extends GDisplayObject { final _localBounds = GRect(); @override - GRect getBounds(GDisplayObject targetSpace, [GRect out]) { + GRect getBounds(GDisplayObject? targetSpace, [GRect? out]) { _sHelperMatrix.identity(); getTransformationMatrix(targetSpace, _sHelperMatrix); var r = MatrixUtils.getTransformedBoundsRect( @@ -21,20 +21,20 @@ class GIcon extends GDisplayObject { } @override - GDisplayObject hitTest(GPoint localPoint, [bool useShape = false]) { + GDisplayObject? hitTest(GPoint localPoint, [bool useShape = false]) { if (!visible || !mouseEnabled) return null; return _localBounds.containsPoint(localPoint) ? this : null; } - widgets.IconData _data; - double _size; - ui.Color _color; + widgets.IconData? _data; + double _size = 0.0; + ui.Color? _color; bool _invalidStyle = false; - ui.Color get color => _color; + ui.Color? get color => _color; - set color(ui.Color value) { + set color(ui.Color? value) { if (value == _color) return; _color = value; _invalidStyle = true; @@ -46,14 +46,14 @@ class GIcon extends GDisplayObject { set size(double value) { if (value == _size) return; _size = value; - _localBounds?.setTo(0, 0, size, size); + _localBounds.setTo(0, 0, size, size); _invalidStyle = true; requiresRedraw(); } - widgets.IconData get data => _data; + widgets.IconData? get data => _data; - set data(widgets.IconData value) { + set data(widgets.IconData? value) { if (value == _data) return; _data = value; _invalidStyle = true; @@ -62,7 +62,7 @@ class GIcon extends GDisplayObject { GIcon( widgets.IconData data, [ - ui.Color color = kColorWhite, + ui.Color color = kColorWhite, double size = 24.0, ]) { _data = data; @@ -79,12 +79,12 @@ class GIcon extends GDisplayObject { requiresRedraw(); } - ui.Paragraph _paragraph; - ui.ParagraphBuilder _builder; - ui.TextStyle _style; + ui.Paragraph? _paragraph; + late ui.ParagraphBuilder _builder; + late ui.TextStyle _style; - ui.Paint _paint; - ui.Shadow _shadow; + ui.Paint? _paint; + ui.Shadow? _shadow; void setPaint(ui.Paint value) { _paint = value; @@ -105,24 +105,24 @@ class GIcon extends GDisplayObject { fontSize: _size, fontFamily: _resolveFontFamily(), foreground: _paint, - shadows: _shadow != null ? [_shadow] : null, + shadows: _shadow != null ? [_shadow!] : null, ); _builder = ui.ParagraphBuilder(ui.ParagraphStyle()); // _builder.pop(); _builder.pushStyle(_style); - final charCode = String.fromCharCode(_data.codePoint); + final charCode = String.fromCharCode(_data!.codePoint); _builder.addText(charCode); _paragraph = _builder.build(); - _paragraph.layout(ui.ParagraphConstraints(width: double.infinity)); + _paragraph!.layout(ui.ParagraphConstraints(width: double.infinity)); _invalidStyle = false; } - String _resolveFontFamily() { + String? _resolveFontFamily() { if (data == null) return null; - if (data.fontPackage == null) { - return data.fontFamily; + if (data!.fontPackage == null) { + return data!.fontFamily; } else { - return 'packages/${data.fontPackage}/${data.fontFamily}'; + return 'packages/${data!.fontPackage}/${data!.fontFamily}'; } } @@ -131,14 +131,14 @@ class GIcon extends GDisplayObject { } @override - void $applyPaint(ui.Canvas canvas) { + void $applyPaint(ui.Canvas? canvas) { if (data == null) return; if (_invalidStyle) { _invalidStyle = false; _updateStyle(); } if (_paragraph != null) { - canvas.drawParagraph(_paragraph, ui.Offset.zero); + canvas!.drawParagraph(_paragraph!, ui.Offset.zero); } } } diff --git a/lib/src/render/movie_clip.dart b/lib/src/render/movie_clip.dart index 0ee6b59..75cd0ea 100644 --- a/lib/src/render/movie_clip.dart +++ b/lib/src/render/movie_clip.dart @@ -18,9 +18,9 @@ class GMovieClip extends GBitmap { /// stops the playback when reaching this frame. int targetFrame = -1; - GBitmap bitmap; + GBitmap? bitmap; - Signal _onFramesComplete; + Signal? _onFramesComplete; Signal get onFramesComplete => _onFramesComplete ??= Signal(); @@ -31,16 +31,16 @@ class GMovieClip extends GBitmap { set fps(double value) => speed = 1 / value; - GMovieClip({List frames, double fps = 30}) { + GMovieClip({required List frames, double fps = 30}) { setFrameTextures(frames); this.fps = fps; } - List _frameTextures; + List? _frameTextures; List setFrameTextures(List list) { - _frameTextures = list ?? []; - frameCount = list?.length ?? 0; + _frameTextures = list; + frameCount = list.length; currentFrame = 0; texture = list.isNotEmpty ? list[0] : null; return list; @@ -50,7 +50,7 @@ class GMovieClip extends GBitmap { if (_frameTextures == null) return; currentFrame = frame; currentFrame %= frameCount; - texture = _frameTextures[currentFrame]; + texture = _frameTextures![currentFrame]; } void gotoAndPlay(int frame, {int lastFrame = -1}) { @@ -105,7 +105,7 @@ class GMovieClip extends GBitmap { if (targetFrame > -1 && currentFrame == targetFrame) { playing = false; } - texture = _frameTextures[currentFrame]; + texture = _frameTextures![currentFrame]; } accumulatedTime %= speed; } diff --git a/lib/src/render/particles/simple_particle.dart b/lib/src/render/particles/simple_particle.dart index 3f6a1c0..d9aa684 100644 --- a/lib/src/render/particles/simple_particle.dart +++ b/lib/src/render/particles/simple_particle.dart @@ -1,11 +1,19 @@ -import 'dart:ui' as ui ; +import 'dart:ui' as ui; import '../../../graphx.dart'; class GSimpleParticle { - GSimpleParticle $next; - GSimpleParticle $prev; - - double x, y, rotation, scaleX, scaleY, alpha, red, green, blue; + GSimpleParticle? $next; + GSimpleParticle? $prev; + + double x = 0.0, + y = 0.0, + rotation = 0.0, + scaleX = 0.0, + scaleY = 0.0, + alpha = 0.0, + red = 0.0, + green = 0.0, + blue = 0.0; double velocityX = 0; double velocityY = 0; @@ -19,17 +27,20 @@ class GSimpleParticle { double initialVelocityAngular = 0; double initialAccelerationX = 0; double initialAccelerationY = 0; - double initialAlpha, initialRed, initialBlue, initialGreen; - double endAlpha, endRed, endBlue, endGreen; - double alphaDif, redDif, blueDif, greenDif; - double scaleDif; + double initialAlpha = 0.0, + initialRed = 0.0, + initialBlue = 0.0, + initialGreen = 0.0; + double endAlpha = 0.0, endRed = 0.0, endBlue = 0.0, endGreen = 0.0; + double alphaDif = 0.0, redDif = 0.0, blueDif = 0.0, greenDif = 0.0; + late double scaleDif; double accumulatedEnergy = 0; - GSimpleParticle $nextInstance; + GSimpleParticle? $nextInstance; int id = 0; - GTexture texture; - static GSimpleParticle $availableInstance; + GTexture? texture; + static GSimpleParticle? $availableInstance; static int $instanceCount = 0; ui.Color get color { @@ -53,7 +64,7 @@ class GSimpleParticle { static void precache(int count) { if (count < $instanceCount) return; - var cached = get(); + GSimpleParticle? cached = get(); while ($instanceCount < count) { var n = get(); n.$prev = cached; @@ -62,7 +73,7 @@ class GSimpleParticle { while (cached != null) { var d = cached; cached = d.$prev; - d?.dispose(); + d.dispose(); } } @@ -124,8 +135,7 @@ class GSimpleParticle { if (emitter.dispersionAngle != 0 || emitter.dispersionAngleVariance != 0) { var dispersionAngle = emitter.dispersionAngle; if (emitter.dispersionAngleVariance > 0) { - dispersionAngle += - emitter.dispersionAngleVariance * Math.random(); + dispersionAngle += emitter.dispersionAngleVariance * Math.random(); } var _sin = Math.sin(dispersionAngle); var _cos = Math.cos(dispersionAngle); @@ -215,10 +225,10 @@ class GSimpleParticle { void dispose() { if ($next != null) { - $next.$prev = $prev; + $next!.$prev = $prev; } if ($prev != null) { - $prev.$next = $next; + $prev!.$next = $next; } $next = null; $prev = null; diff --git a/lib/src/render/particles/simple_particle_system.dart b/lib/src/render/particles/simple_particle_system.dart index 78601c3..a941b1f 100644 --- a/lib/src/render/particles/simple_particle_system.dart +++ b/lib/src/render/particles/simple_particle_system.dart @@ -16,7 +16,7 @@ class GSimpleParticleSystem extends GDisplayObject { } @override - GRect getBounds(GDisplayObject targetSpace, [GRect out]) { + GRect getBounds(GDisplayObject? targetSpace, [GRect? out]) { final matrix = _sHelperMatrix; matrix.identity(); getTransformationMatrix(targetSpace, matrix); @@ -73,7 +73,7 @@ class GSimpleParticleSystem extends GDisplayObject { double dispersionAngle = 0; double dispersionAngleVariance = 0; bool paused = false; - GTexture texture; + GTexture? texture; int get initialColor { final r = (initialRed * 0xff).toInt() << 16; @@ -107,8 +107,8 @@ class GSimpleParticleSystem extends GDisplayObject { int $activeParticles = 0; double $lastUpdateTime = 0; - GSimpleParticle $firstParticle; - GSimpleParticle $lastParticle; + GSimpleParticle? $firstParticle; + GSimpleParticle? $lastParticle; void _setInitialParticlePosition(GSimpleParticle p) { p.x = useWorldSpace ? x : 0; @@ -151,12 +151,12 @@ class GSimpleParticleSystem extends GDisplayObject { void _setPivot() { /// used (texture.width)... - particlePivotX = texture.nativeWidth.toDouble() * .5; - particlePivotY = texture.nativeHeight.toDouble() * .5; + particlePivotX = texture!.nativeWidth.toDouble() * .5; + particlePivotY = texture!.nativeHeight.toDouble() * .5; } - double particlePivotX; - double particlePivotY; + double? particlePivotX; + late double particlePivotY; void forceBurst() { var currentEmission = @@ -204,7 +204,7 @@ class GSimpleParticleSystem extends GDisplayObject { } @override - void paint(ui.Canvas canvas) { + void paint(ui.Canvas? canvas) { if (!$hasVisibleArea) return; if (useWorldSpace) { render(canvas); @@ -214,28 +214,28 @@ class GSimpleParticleSystem extends GDisplayObject { } @override - void $applyPaint(ui.Canvas canvas) { + void $applyPaint(ui.Canvas? canvas) { render(canvas); } bool useAlphaOnColorFilter = false; - void Function(ui.Canvas, ui.Paint) drawCallback; + void Function(ui.Canvas?, ui.Paint)? drawCallback; final nativePaint = ui.Paint() ..color = kColorBlack ..filterQuality = ui.FilterQuality.low; - void render(ui.Canvas canvas) { + void render(ui.Canvas? canvas) { if (texture == null) return; var particle = $firstParticle; while (particle != null) { var next = particle.$next; - double tx, ty, sx, sy; + double? tx, ty, sx, sy; tx = particle.x; ty = particle.y; - sx = particle.scaleX / texture.scale; - sy = particle.scaleY / texture.scale; + sx = particle.scaleX/ texture!.scale!; + sy = particle.scaleY/ texture!.scale!; if (useWorldSpace) { sx *= scaleX; sy *= scaleY; @@ -252,20 +252,20 @@ class GSimpleParticleSystem extends GDisplayObject { var filterColor = useAlphaOnColorFilter ? _color : _color.withOpacity(1); nativePaint.colorFilter = ui.ColorFilter.mode(filterColor, particleBlendMode); - canvas.save(); + canvas!.save(); canvas.translate(tx, ty); canvas.rotate(particle.rotation); canvas.scale(sx, sy); - canvas.translate(-particlePivotX, -particlePivotY); + canvas.translate(-particlePivotX!, -particlePivotY); // $canvas.scale(particle.scaleX, particle.scaleY); // $canvas.rotate(particle.rotation); /// render in canvas. if (drawCallback != null) { - drawCallback(canvas, nativePaint); + drawCallback!(canvas, nativePaint); // $canvas.drawImage(texture.source, Offset.zero, nativePaint); } else { - canvas.drawImage(texture.root, ui.Offset.zero, nativePaint); + canvas.drawImage(texture!.root!, ui.Offset.zero, nativePaint); } // $canvas.drawImage(texture.source, Offset(tx, ty), nativePaint); canvas.restore(); @@ -284,7 +284,7 @@ class GSimpleParticleSystem extends GDisplayObject { var p = GSimpleParticle.get(); if ($firstParticle != null) { p.$next = $firstParticle; - $firstParticle.$prev = p; + $firstParticle!.$prev = p; $firstParticle = p; } else { $firstParticle = p; @@ -294,8 +294,8 @@ class GSimpleParticleSystem extends GDisplayObject { } void $deactivateParticle(GSimpleParticle particle) { - if (particle == $lastParticle) $lastParticle = $lastParticle.$prev; - if (particle == $firstParticle) $firstParticle = $firstParticle.$next; + if (particle == $lastParticle) $lastParticle = $lastParticle!.$prev; + if (particle == $firstParticle) $firstParticle = $firstParticle!.$next; particle.dispose(); } @@ -304,7 +304,7 @@ class GSimpleParticleSystem extends GDisplayObject { @override void dispose() { while ($firstParticle != null) { - $deactivateParticle($firstParticle); + $deactivateParticle($firstParticle!); } ScenePainter.current.onUpdate.remove(update); super.dispose(); @@ -312,7 +312,7 @@ class GSimpleParticleSystem extends GDisplayObject { void clear() { while ($firstParticle != null) { - $deactivateParticle($firstParticle); + $deactivateParticle($firstParticle!); } } } diff --git a/lib/src/render/svg_shape.dart b/lib/src/render/svg_shape.dart index 948ed4d..98d896d 100644 --- a/lib/src/render/svg_shape.dart +++ b/lib/src/render/svg_shape.dart @@ -7,7 +7,7 @@ class GSvgShape extends GDisplayObject { static final GMatrix _sHelperMatrix = GMatrix(); static final GPoint _sHelperPoint = GPoint(); - Color _tint; + Color? _tint; /// play nice with Colorization. BlendMode _blendMode = BlendMode.srcATop; @@ -16,9 +16,9 @@ class GSvgShape extends GDisplayObject { bool _invalidColor = false; - Color get tint => _tint; + Color? get tint => _tint; - set tint(Color value) { + set tint(Color? value) { _tint = value; _invalidColor = true; usePaint = true; @@ -41,18 +41,18 @@ class GSvgShape extends GDisplayObject { } bool _isValid = false; - SvgData _data; + SvgData? _data; - SvgData get data => _data; + SvgData? get data => _data; - set data(SvgData value) { + set data(SvgData? value) { if (_data == value) return; _data = value; _isValid = _data?.hasContent ?? false; requiresRedraw(); } - GSvgShape(SvgData data) { + GSvgShape(SvgData? data) { this.data = data; } @@ -66,12 +66,12 @@ class GSvgShape extends GDisplayObject { } @override - GRect getBounds(GDisplayObject targetSpace, [GRect out]) { + GRect? getBounds(GDisplayObject? targetSpace, [GRect? out]) { final matrix = _sHelperMatrix; matrix.identity(); getTransformationMatrix(targetSpace, matrix); if (_isValid) { - var r = _data.size; + var r = _data!.size; out = MatrixUtils.getTransformedBoundsRect( matrix, r, @@ -79,7 +79,7 @@ class GSvgShape extends GDisplayObject { ); } else { matrix.transformCoords(0, 0, _sHelperPoint); - out.setTo(_sHelperPoint.x, _sHelperPoint.y, 0, 0); + out!.setTo(_sHelperPoint.x, _sHelperPoint.y, 0, 0); } return out; } @@ -96,38 +96,38 @@ class GSvgShape extends GDisplayObject { } @override - void paint(Canvas canvas) { + void paint(Canvas? canvas) { if (!_isValid) return; super.paint(canvas); } @override - void $applyPaint(Canvas canvas) { + void $applyPaint(Canvas? canvas) { var _saveLayer = $alpha != 1 || usePaint; if (_saveLayer) { if (_invalidColor) _validateColor(); - final rect = getBounds(this).toNative(); - canvas.saveLayer(rect, _paint); + final rect = getBounds(this)!.toNative(); + canvas!.saveLayer(rect, _paint); } - canvas.drawPicture(_data.picture); + canvas!.drawPicture(_data!.picture!); if (_saveLayer) { canvas.restore(); } } void _validateColor() { - _paint.colorFilter = ColorFilter.mode(_tint, _blendMode); + _paint.colorFilter = ColorFilter.mode(_tint!, _blendMode); _invalidColor = false; } } /// proxy class to flutter_svg class SvgData { - Color color; - GRect viewBox; - GRect size; - Picture picture; - bool hasContent; + Color? color; + GRect? viewBox; + late GRect size; + Picture? picture; + bool? hasContent; SvgData([this.picture]); diff --git a/lib/src/textures/sub_texture.dart b/lib/src/textures/sub_texture.dart index 222671a..9ba852f 100644 --- a/lib/src/textures/sub_texture.dart +++ b/lib/src/textures/sub_texture.dart @@ -2,24 +2,24 @@ import 'dart:ui' as ui; import '../../graphx.dart'; class GSubTexture extends GTexture { - GTexture _parent; - bool _ownsParent; - GRect _region; - GRect _sourceRegion; - bool _rotated; - double _w; - double _h; - double _scale; + GTexture? _parent; + bool? _ownsParent; + GRect? _region; + late GRect _sourceRegion; + bool? _rotated; + double? _w; + double? _h; + double? _scale; /// cache rendering. - ui.Rect _sourceRegionRect; - ui.Rect _destRect; + late ui.Rect _sourceRegionRect; + late ui.Rect _destRect; GSubTexture(GTexture parent, - {GRect region, + {GRect? region, bool ownsParent = false, - GRect frame, - bool rotated, + GRect? frame, + required bool rotated, double scaleModifier = 1}) { $setTo( parent, @@ -32,21 +32,21 @@ class GSubTexture extends GTexture { } void $setTo(GTexture parent, - {GRect region, + {GRect? region, bool ownsParent = false, - GRect frame, - bool rotated, + GRect? frame, + required bool rotated, double scaleModifier = 1}) { _region ??= GRect(); if (region != null) { - _region.copyFrom(region); + _region!.copyFrom(region); } else { /// used (parent.width) - _region.setTo(0, 0, parent.nativeWidth, parent.nativeHeight); + _region!.setTo(0, 0, parent.nativeWidth, parent.nativeHeight); } if (frame != null) { if (this.frame != null) { - this.frame.copyFrom(frame); + this.frame!.copyFrom(frame); } else { this.frame = frame.clone(); } @@ -56,10 +56,10 @@ class GSubTexture extends GTexture { _parent = parent; _ownsParent = ownsParent; _rotated = rotated; - _w = (rotated ? _region.height : _region.width) / scaleModifier; - _h = (rotated ? _region.width : _region.height) / scaleModifier; - _scale = parent.scale * scaleModifier; - _sourceRegion = _region.clone() * scale; + _w = (rotated ? _region!.height : _region!.width)/ scaleModifier; + _h = (rotated ? _region!.width : _region!.height)/ scaleModifier; + _scale = parent.scale! * scaleModifier; + _sourceRegion = _region!.clone() * scale!; /// cache. _sourceRegionRect = _sourceRegion.toNative(); @@ -77,46 +77,46 @@ class GSubTexture extends GTexture { @override void dispose() { - if (_ownsParent) { - _parent.dispose(); + if (_ownsParent!) { + _parent!.dispose(); } super.dispose(); } - GRect get region => _region; + GRect? get region => _region; - bool get rotated => _rotated; + bool? get rotated => _rotated; - bool get ownsParent => _ownsParent; + bool? get ownsParent => _ownsParent; - GTexture get parent => _parent; + GTexture? get parent => _parent; @override - ui.Image get root => _parent.root; + ui.Image? get root => _parent!.root; @override - double get width => _w; + double? get width => _w; @override - double get height => _h; + double? get height => _h; @override - double get nativeWidth => _w * _scale; + double get nativeWidth => _w! * _scale!; @override - double get nativeHeight => _h * _scale; + double get nativeHeight => _h! * _scale!; @override - double get scale => _scale; + double? get scale => _scale; /// no support void updateMatrices() {} @override - void render(ui.Canvas canvas, [ui.Paint paint]) { + void render(ui.Canvas? canvas, [ui.Paint? paint]) { paint ??= GTexture.sDefaultPaint; paint.isAntiAlias = true; - canvas.drawImageRect(root, _sourceRegionRect, _destRect, paint); + canvas!.drawImageRect(root!, _sourceRegionRect, _destRect, paint); // final sub = texture as GSubTexture; // final dest = Rect.fromLTWH( // 0, diff --git a/lib/src/textures/texture.dart b/lib/src/textures/texture.dart index 53ce278..831533b 100644 --- a/lib/src/textures/texture.dart +++ b/lib/src/textures/texture.dart @@ -3,22 +3,22 @@ import 'dart:ui' as ui; import '../../graphx.dart'; class GTexture { - GRect frame; + GRect? frame; // set from the outside. - GRect scale9Grid; - GRect scale9GridDest; + GRect? scale9Grid; + GRect? scale9GridDest; - double get width => nativeWidth; + double? get width => nativeWidth; - double get height => nativeHeight; + double? get height => nativeHeight; - double get nativeWidth => root?.width?.toDouble() ?? 0; + double get nativeWidth => root?.width.toDouble() ?? 0; - double get nativeHeight => root?.height?.toDouble() ?? 0; + double get nativeHeight => root?.height.toDouble() ?? 0; /// when the texture is plain color. - ui.Color color; + ui.Color? color; /// used width. double get frameWidth => frame?.width ?? nativeWidth; @@ -26,13 +26,13 @@ class GTexture { double get frameHeight => frame?.height ?? nativeHeight; /// set this by hand. - double actualWidth, actualHeight; + double? actualWidth, actualHeight; - double pivotX = 0, pivotY = 0; - GRect sourceRect; + double? pivotX = 0, pivotY = 0; + GRect? sourceRect; - double scale = 1; - ui.Image root; + double? scale = 1; + ui.Image? root; /// copy Image data, and properties from other GTexture instance. void copyFrom(GTexture other) { @@ -46,7 +46,7 @@ class GTexture { scale = other.scale; } - GRect getBounds() { + GRect? getBounds() { return sourceRect; } @@ -89,11 +89,11 @@ class GTexture { static ui.Paint sDefaultPaint = ui.Paint(); - void render(ui.Canvas canvas, [ui.Paint paint]) { + void render(ui.Canvas? canvas, [ui.Paint? paint]) { paint ??= sDefaultPaint; if (scale != 1) { - canvas.save(); - canvas.scale(1 / scale); + canvas!.save(); + canvas.scale(1 / scale!); // canvas.drawImage(root, Offset.zero, paint); _drawImage(canvas, paint); canvas.restore(); @@ -102,18 +102,18 @@ class GTexture { } } - void _drawImage(ui.Canvas canvas, ui.Paint paint) { + void _drawImage(ui.Canvas? canvas, ui.Paint paint) { if (scale9Grid != null) { // print('src: $scale9Grid, dst: $scale9GridDest'); - canvas.drawImageNine( - root, - scale9Grid.toNative(), - scale9GridDest.toNative(), + canvas!.drawImageNine( + root!, + scale9Grid!.toNative(), + scale9GridDest!.toNative(), // sourceRect.toNative(), paint, ); } else { - canvas.drawImage(root, ui.Offset.zero, paint); + canvas!.drawImage(root!, ui.Offset.zero, paint); } } diff --git a/lib/src/textures/texture_atlas.dart b/lib/src/textures/texture_atlas.dart index dacd75c..cf95aaa 100644 --- a/lib/src/textures/texture_atlas.dart +++ b/lib/src/textures/texture_atlas.dart @@ -3,16 +3,17 @@ import 'package:xml/xml.dart' as xml; import '../../graphx.dart'; class GTextureAtlas { - GTexture _atlasTexture; - Map _subTextures; - List _subTexturesNames; + GTexture? _atlasTexture; + Map? _subTextures; + List? _subTexturesNames; static final List _names = []; - static bool attrBoolean(xml.XmlElement el, String name, {bool defaultValue}) { + static bool? attrBoolean(xml.XmlElement el, String name, + {bool? defaultValue}) { var val = el.getAttribute(name); if (val == null) return defaultValue; - return StringUtils.parseBoolean(val) ?? defaultValue; + return StringUtils.parseBoolean(val); } static double attrDouble(xml.XmlElement el, String name, @@ -22,11 +23,11 @@ class GTextureAtlas { return double.tryParse(val) ?? defaultValue; } - double _atlasXmlRatio; + late double _atlasXmlRatio; GTextureAtlas( - GTexture texture, [ - Object data, + GTexture? texture, [ + Object? data, double adjustXmlSizesRatio = 1, ]) { _subTextures = {}; @@ -40,7 +41,7 @@ class GTextureAtlas { void parseAtlasData(Object data) { if (data is String) { /// parse json or xml. - if ((data as String).contains('')) { + if (data.contains('')) { data = xml.XmlDocument.parse(data); } } @@ -54,14 +55,14 @@ class GTextureAtlas { /// Parse the XML tree and defines all SubTextures areas. void parseAtlasXml(xml.XmlDocument atlasXml) { - var scale = _atlasTexture.scale; + var scale = _atlasTexture!.scale; var region = GRect(); var frame = GRect(); - final pivots = {}; + final pivots = {}; final nodeList = atlasXml.findAllElements('SubTexture'); for (var subTexture in nodeList) { var name = subTexture.getAttribute('name'); - var x = attrDouble(subTexture, 'x') / scale * _atlasXmlRatio; + var x = attrDouble(subTexture, 'x') / scale! * _atlasXmlRatio; var y = attrDouble(subTexture, 'y') / scale * _atlasXmlRatio; var width = attrDouble(subTexture, 'width') / scale * _atlasXmlRatio; var height = attrDouble(subTexture, 'height') / scale * _atlasXmlRatio; @@ -81,9 +82,9 @@ class GTextureAtlas { region.setTo(x, y, width, height); frame.setTo(frameX, frameY, frameWidth, frameHeight); if (frameWidth > 0 && frameHeight > 0) { - addRegion(name, region, frame, rotated); + addRegion(name, region, frame, rotated!); } else { - addRegion(name, region, null, rotated); + addRegion(name, region, null, rotated!); } if (pivotX != 0 || pivotY != 0) { /// image bind pivot point to texture! @@ -94,12 +95,12 @@ class GTextureAtlas { /// adobe animate workaround. } - void addRegion(String name, GRect region, - [GRect frame, bool rotated = false]) { + void addRegion(String? name, GRect region, + [GRect? frame, bool rotated = false]) { addSubTexture( name, GSubTexture( - _atlasTexture, + _atlasTexture!, region: region, ownsParent: false, frame: frame, @@ -108,31 +109,31 @@ class GTextureAtlas { } void removeRegion(String name) { - var subTexture = _subTextures[name]; + var subTexture = _subTextures![name]; subTexture?.dispose(); - _subTextures.remove(name); + _subTextures!.remove(name); _subTexturesNames = null; } - GTexture get texture => _atlasTexture; + GTexture? get texture => _atlasTexture; bool getRotation(String name) { - return _subTextures[name]?.rotated ?? false; + return _subTextures![name]?.rotated ?? false; } - GRect getFrame(String name) { - return _subTextures[name]?.frame; + GRect? getFrame(String name) { + return _subTextures![name]?.frame; } - GSubTexture getTexture(String name) { - return _subTextures[name]; + GSubTexture? getTexture(String? name) { + return _subTextures![name]; } - GRect getRegion(String name) { - return _subTextures[name]?.region; + GRect? getRegion(String name) { + return _subTextures![name]?.region; } - List getTextures({String prefix, List out}) { + List getTextures({String? prefix, List? out}) { prefix ??= ''; out ??= []; final list = getNames(prefix: prefix, out: _names); @@ -142,29 +143,29 @@ class GTextureAtlas { return out; } - List getNames({String prefix, List out}) { + List getNames({String? prefix, List? out}) { prefix ??= ''; out ??= []; if (_subTexturesNames == null) { _subTexturesNames = []; - for (var name in _subTextures.keys) { - _subTexturesNames.add(name); + for (var name in _subTextures!.keys) { + _subTexturesNames!.add(name); } - _subTexturesNames.sort(); + _subTexturesNames!.sort(); } - for (var name in _subTexturesNames) { - if (name.indexOf(prefix) == 0) { + for (var name in _subTexturesNames!) { + if (name!.indexOf(prefix) == 0) { out.add(name); } } return out; } - void addSubTexture(String name, GSubTexture subTexture) { - if (subTexture.root != _atlasTexture.root) { + void addSubTexture(String? name, GSubTexture subTexture) { + if (subTexture.root != _atlasTexture!.root) { throw 'SubTexture\'s root must be an Atlas Texture.'; } - _subTextures[name] = subTexture; + _subTextures![name] = subTexture; _subTexturesNames = null; } diff --git a/lib/src/ticker/ticker.dart b/lib/src/ticker/ticker.dart index 3ce2bb1..55c030d 100644 --- a/lib/src/ticker/ticker.dart +++ b/lib/src/ticker/ticker.dart @@ -4,11 +4,11 @@ import '../events/events.dart'; class GTicker { GTicker(); - Ticker _ticker; - EventSignal _onFrame; + Ticker? _ticker; + EventSignal? _onFrame; EventSignal get onFrame => _onFrame ??= EventSignal(); - VoidCallback _nextFrameCallback; + VoidCallback? _nextFrameCallback; // ignore: use_setters_to_change_properties void callNextFrame(VoidCallback callback) { @@ -18,8 +18,8 @@ class GTicker { void _createTicker() { if (_ticker != null) return; _ticker = Ticker(_onTick); - _ticker.start(); - _ticker.muted = true; + _ticker!.start(); + _ticker!.muted = true; } bool get isTicking => _ticker?.isTicking ?? false; @@ -47,7 +47,7 @@ class GTicker { double _currentDeltaRatio = 0.0; double frameRate = 60.0; - double _expectedDelta; + late double _expectedDelta; /// enterframe ticker void _onTick(Duration elapsed) { @@ -79,17 +79,17 @@ class GTicker { } } -Stopwatch _stopwatch; +Stopwatch? _stopwatch; void _initTimer() { if (_stopwatch != null) return; _stopwatch = Stopwatch(); - _stopwatch.start(); + _stopwatch!.start(); } int getTimer() { if (_stopwatch == null) { _initTimer(); } - return _stopwatch.elapsedMilliseconds; + return _stopwatch!.elapsedMilliseconds; } diff --git a/lib/src/tween/src/core/prop_tween.dart b/lib/src/tween/src/core/prop_tween.dart index f1685a0..fbbda28 100644 --- a/lib/src/tween/src/core/prop_tween.dart +++ b/lib/src/tween/src/core/prop_tween.dart @@ -2,44 +2,44 @@ part of gtween; class PropTween { /// target or dynamic - GTweenable t; + GTweenable? t; /// property "name" (commonly a String), or value! - Object p; + Object? p; /// start value - double s; + double s = 0.0; /// amount to change, diff between end and start. - double c; + double? c; /// original target object. - Object cObj; + Object? cObj; /// is function - bool f; + bool? f; /// priority in render queue. - int pr; + int? pr; /// target is tween plugin? - bool pg; + bool? pg; // name of original target property. Typically same as `t` - String n; + String? n; /// rounded - bool r; + bool? r; /// linked list next. - PropTween _next, _prev; + PropTween? _next, _prev; PropTween({ - GTweenable target, - Object property, - double start, - double change, - String name, - PropTween next, + GTweenable? target, + Object? property, + double start = 0.0, + double? change, + String? name, + PropTween? next, int priority = 0, }) { t = target; diff --git a/lib/src/tween/src/extensions/common_types.dart b/lib/src/tween/src/extensions/common_types.dart index c68617b..be46317 100644 --- a/lib/src/tween/src/extensions/common_types.dart +++ b/lib/src/tween/src/extensions/common_types.dart @@ -1,9 +1,9 @@ part of gtween; extension GTweenNumExt on num { - GTweenableDouble get twn { - return this is double ? GTweenableDouble(this) : GTweenableInt(this); - } + GTweenableDouble get twn => this is double + ? GTweenableDouble(this as double) + : GTweenableInt(this as int) as GTweenableDouble; } extension GTweenDoubleExt on double { @@ -14,7 +14,7 @@ extension GTweenIntExt on int { GTweenableInt get twn => GTweenableInt(this); } -extension GTweenMapExt on Map { +extension GTweenMapExt on Map { GTweenableMap get twn => GTweenableMap(this); } diff --git a/lib/src/tween/src/extensions/display_object.dart b/lib/src/tween/src/extensions/display_object.dart index c8e3075..49d092a 100644 --- a/lib/src/tween/src/extensions/display_object.dart +++ b/lib/src/tween/src/extensions/display_object.dart @@ -4,36 +4,36 @@ extension GTweenDiplayObjectExt on GDisplayObject { GTweenableDisplayObject get twn => GTweenableDisplayObject(this); GTween tween({ - @required double duration, - Object x, - Object y, - Object scaleX, - Object scaleY, - Object scale, - Object rotation, - Object rotationX, - Object rotationY, - Object pivotX, - Object pivotY, - Object width, - Object height, - Object skewX, - Object skewY, - Color colorize, - Object alpha, - EaseFunction ease, - double delay, - bool useFrames, + required double duration, + Object? x, + Object? y, + Object? scaleX, + Object? scaleY, + Object? scale, + Object? rotation, + Object? rotationX, + Object? rotationY, + Object? pivotX, + Object? pivotY, + Object? width, + Object? height, + Object? skewX, + Object? skewY, + Color? colorize, + Object? alpha, + EaseFunction? ease, + double? delay, + bool? useFrames, int overwrite = 1, - Function onStart, - Object onStartParams, - Function onComplete, - Object onCompleteParams, - Function onUpdate, - Object onUpdateParams, - bool runBackwards, - bool immediateRender, - Map startAt, + Function? onStart, + Object? onStartParams, + Function? onComplete, + Object? onCompleteParams, + Function? onUpdate, + Object? onUpdateParams, + bool? runBackwards, + bool? immediateRender, + Map? startAt, }) { final targetValues = { if (x != null) 'x': x, @@ -79,24 +79,24 @@ extension GTweenDiplayObjectExt on GDisplayObject { /// Shortcut to assign multiple properties and render immeditatly. /// Doesn't wait for the next tick update. void setProps({ - Object x, - Object y, - Object scaleX, - Object scaleY, - Object scale, - Object rotation, - Object pivotX, - Object pivotY, - Object width, - Object height, - Object skewX, - Object skewY, - Object rotationX, - Object rotationY, - Object alpha, - Color colorize, + Object? x, + Object? y, + Object? scaleX, + Object? scaleY, + Object? scale, + Object? rotation, + Object? pivotX, + Object? pivotY, + Object? width, + Object? height, + Object? skewX, + Object? skewY, + Object? rotationX, + Object? rotationY, + Object? alpha, + Color? colorize, double delay = 0, - bool visible, + bool? visible, bool immediateRender = true, }) { if (visible != null) { @@ -105,7 +105,7 @@ extension GTweenDiplayObjectExt on GDisplayObject { tween( duration: 0, delay: delay, - immediateRender: immediateRender ?? true, + immediateRender: immediateRender, x: x, y: y, scaleX: scaleX, @@ -120,8 +120,8 @@ extension GTweenDiplayObjectExt on GDisplayObject { skewX: skewX, skewY: skewY, alpha: alpha, - rotationX:rotationX, - rotationY:rotationY, + rotationX: rotationX, + rotationY: rotationY, ); } } diff --git a/lib/src/tween/src/extensions/filter_types.dart b/lib/src/tween/src/extensions/filter_types.dart index 9f0b099..c5b9f85 100644 --- a/lib/src/tween/src/extensions/filter_types.dart +++ b/lib/src/tween/src/extensions/filter_types.dart @@ -3,22 +3,22 @@ part of gtween; extension GTweenBlurFilterExt on GBlurFilter { GTweenableBlur get twn => GTweenableBlur(this); GTween tween({ - @required double duration, - Object blurX, - Object blurY, - EaseFunction ease, - double delay, - bool useFrames, + required double duration, + Object? blurX, + Object? blurY, + EaseFunction? ease, + double? delay, + bool? useFrames, int overwrite = 1, - VoidCallback onStart, - Object onStartParams, - VoidCallback onComplete, - Object onCompleteParams, - VoidCallback onUpdate, - Object onUpdateParams, - bool runBackwards, - bool immediateRender, - Map startAt, + VoidCallback? onStart, + Object? onStartParams, + VoidCallback? onComplete, + Object? onCompleteParams, + VoidCallback? onUpdate, + Object? onUpdateParams, + bool? runBackwards, + bool? immediateRender, + Map? startAt, }) => twn.tween( duration: duration, @@ -43,25 +43,25 @@ extension GTweenBlurFilterExt on GBlurFilter { extension GTweenDropShadowFilterExt on GDropShadowFilter { GTweenableDropShadowFilter get twn => GTweenableDropShadowFilter(this); GTween tween({ - @required double duration, - Object blurX, - Object blurY, - Object angle, - Object distance, - Color color, - EaseFunction ease, - double delay, - bool useFrames, + required double duration, + Object? blurX, + Object? blurY, + Object? angle, + Object? distance, + Color? color, + EaseFunction? ease, + double? delay, + bool? useFrames, int overwrite = 1, - VoidCallback onStart, - Object onStartParams, - VoidCallback onComplete, - Object onCompleteParams, - VoidCallback onUpdate, - Object onUpdateParams, - bool runBackwards, - bool immediateRender, - Map startAt, + VoidCallback? onStart, + Object? onStartParams, + VoidCallback? onComplete, + Object? onCompleteParams, + VoidCallback? onUpdate, + Object? onUpdateParams, + bool? runBackwards, + bool? immediateRender, + Map? startAt, }) { return twn.tween( duration: duration, @@ -90,23 +90,23 @@ extension GTweenDropShadowFilterExt on GDropShadowFilter { extension GTweenGlowFilterExt on GlowFilter { GTweenableGlowFilter get twn => GTweenableGlowFilter(this); GTween tween({ - @required double duration, - Object blurX, - Object blurY, - Color color, - EaseFunction ease, - double delay, - bool useFrames, + required double duration, + Object? blurX, + Object? blurY, + Color? color, + EaseFunction? ease, + double? delay, + bool? useFrames, int overwrite = 1, - VoidCallback onStart, - Object onStartParams, - VoidCallback onComplete, - Object onCompleteParams, - VoidCallback onUpdate, - Object onUpdateParams, - bool runBackwards, - bool immediateRender, - Map startAt, + VoidCallback? onStart, + Object? onStartParams, + VoidCallback? onComplete, + Object? onCompleteParams, + VoidCallback? onUpdate, + Object? onUpdateParams, + bool? runBackwards, + bool? immediateRender, + Map? startAt, }) { return twn.tween( duration: duration, diff --git a/lib/src/tween/src/gtween.dart b/lib/src/tween/src/gtween.dart index d3d9dde..0904072 100644 --- a/lib/src/tween/src/gtween.dart +++ b/lib/src/tween/src/gtween.dart @@ -1,20 +1,20 @@ part of gtween; class GVars { - EaseFunction ease; - double delay; - bool useFrames; - int overwrite; - Function onStart; - CallbackParams onStartParams; - Function onComplete; - CallbackParams onCompleteParams; - Function onUpdate; - CallbackParams onUpdateParams; - bool runBackwards; - bool immediateRender; - - Map startAt; + EaseFunction? ease; + double? delay; + bool? useFrames; + int? overwrite; + Function? onStart; + CallbackParams? onStartParams; + Function? onComplete; + CallbackParams? onCompleteParams; + Function? onUpdate; + CallbackParams? onUpdateParams; + bool? runBackwards; + bool? immediateRender; + + Map? startAt; /// TODO: maybe in future use vars from this object. // Map vars; @@ -27,9 +27,9 @@ class GVars { this.onStart, this.onComplete, this.onUpdate, - Object onStartParams, - Object onCompleteParams, - Object onUpdateParams, + Object? onStartParams, + Object? onCompleteParams, + Object? onUpdateParams, this.runBackwards, this.immediateRender, this.startAt, @@ -50,13 +50,13 @@ class GVars { void _setTween(GTween gTween) { if (onStartParams != null) { - _setCallbackParams(gTween, onStartParams); + _setCallbackParams(gTween, onStartParams!); } if (onCompleteParams != null) { - _setCallbackParams(gTween, onCompleteParams); + _setCallbackParams(gTween, onCompleteParams!); } if (onUpdateParams != null) { - _setCallbackParams(gTween, onUpdateParams); + _setCallbackParams(gTween, onUpdateParams!); } // onStartParams?._setTween(gTween); // onCompleteParams?._setTween(gTween); @@ -101,7 +101,7 @@ class GTween { /// [GTweenableDouble.wrap, GTweenableInt.wrap, GTweenableList] /// ); /// ``` - static void registerCommonWraps([List otherWraps]) { + static void registerCommonWraps([List? otherWraps]) { if (initialized) return; GTween.registerWrap(GTweenableDisplayObject.wrap); GTween.registerWrap(GTweenableMap.wrap); @@ -127,7 +127,7 @@ class GTween { /// or make GTicker global... being able to track unique refresh frames /// is a must. static void processTick(double elapsed) { - final ts = SchedulerBinding.instance.currentFrameTimeStamp; + final ts = SchedulerBinding.instance!.currentFrameTimeStamp; if (_lastFrameTimeStamp == ts) return; GTween.ticker.dispatch(elapsed); _lastFrameTimeStamp = ts; @@ -147,36 +147,36 @@ class GTween { static void registerWrap(GxAnimatableBuilder builder) => _tweenableBuilders.add(builder); - static Map _reservedProps; - static GTween _first; - static GTween _last; + static Map? _reservedProps; + static GTween? _first; + static GTween? _last; - double _duration; - Map vars; - GVars nanoVars; - double _startTime; + double? _duration; + Map? vars; + late GVars nanoVars; + late double _startTime; - Object target; + Object? target; /// the real target - Object _animatableTarget; + Object? _animatableTarget; - bool _useFrames; - double ratio = 0; + late bool _useFrames; + double? ratio = 0; - Function _ease; + Function? _ease; // Ease _rawEase; bool _inited = false; - PropTween _firstPT; - GTween _next; - GTween _prev; - List _targets; + PropTween? _firstPT; + GTween? _next; + GTween? _prev; + List? _targets; bool _gc = false; - GTween(this.target, double duration, this.vars, [GVars myVars]) { + GTween(this.target, double duration, this.vars, [GVars? myVars]) { if (_reservedProps == null) { _reservedProps = { 'delay': 1, @@ -206,7 +206,7 @@ class GTween { var targetList = target as List; if (targetList.first is Map || targetList.first is GTweenable) { - _targets = List.of(target); + _targets = List.of(target as Iterable); } /// TODO : add wrap support. @@ -217,7 +217,7 @@ class GTween { /// no process. } else { /// target can be a Function. - GTweenable result; + GTweenable? result; for (final builder in _tweenableBuilders) { result = builder(target); if (result != null) { @@ -243,13 +243,13 @@ class GTween { } _prev = _last; if (_last != null) { - _last._next = this; + _last!._next = this; } else { _first = this; } _last = this; - if (nanoVars.immediateRender || + if (nanoVars.immediateRender! || (duration == 0 && nanoVars.delay == 0 && nanoVars.immediateRender != false)) { @@ -264,18 +264,18 @@ class GTween { // GTween.to(target, 0, nanoVars.startAt.vars, nanoVars.startAt); } if (_targets != null) { - var i = _targets.length; + var i = _targets!.length; while (--i > -1) { - _initProps(_targets[i]); + _initProps(_targets![i]); } } else { _initProps(target); } - if (nanoVars.runBackwards) { + if (nanoVars.runBackwards!) { var pt = _firstPT; while (pt != null) { - pt.s += pt.c; - pt.c = -pt.c; + pt.s += pt.c!; + pt.c = -pt.c!; pt = pt._next; } } @@ -283,20 +283,21 @@ class GTween { } /// initialiazes the PropTween to be used in the target Object. - void _initProps(Object target) { + void _initProps(Object? target) { if (target == null) return; - for (final key in vars.keys) { + for (final key in vars!.keys) { final prop = '$key'; - if (!_reservedProps.containsKey(prop)) { - _firstPT = PropTween(target: target, property: key, next: _firstPT); + if (!_reservedProps!.containsKey(prop)) { + _firstPT = PropTween( + target: target as GTweenable?, property: key, next: _firstPT); var startVal = _getStartValue(target, key); - _firstPT.s = startVal; - var endValue = _getEndValue(vars, key, _firstPT.s); - _firstPT.cObj = vars[key]; - _firstPT.c = endValue; - _firstPT.t.setTweenProp(_firstPT); - if (_firstPT._next != null) { - _firstPT._next._prev = _firstPT; + _firstPT!.s = startVal; + var endValue = _getEndValue(vars!, key, _firstPT!.s); + _firstPT!.cObj = vars![key]; + _firstPT!.c = endValue; + _firstPT!.t!.setTweenProp(_firstPT!); + if (_firstPT!._next != null) { + _firstPT!._next!._prev = _firstPT; } } } @@ -304,15 +305,15 @@ class GTween { /// Can be tweening a List asMap(), so `prop` is better to be /// dynamic. - double _getEndValue(Map pvars, dynamic prop, double start) { + double? _getEndValue(Map pvars, dynamic prop, double? start) { dynamic val = pvars[prop]; if (val is num) { - double v = val + 0.0; - return v - start; + var v = val + 0.0; + return v - start!; } else if (val is String) { if (val.length > 2 && val[1] == '=') { var multiplier = double.tryParse('${val[0]}1') ?? 1; - var factor = double.tryParse(val.substring(2)); + var factor = double.tryParse(val.substring(2))!; return multiplier * factor; } else { return double.tryParse(val); @@ -322,11 +323,11 @@ class GTween { } void _setCurrentValue(PropTween pt, double ratio) { - var value = pt.c * ratio + pt.s; + var value = pt.c! * ratio + pt.s; if (pt.t is GTweenable) { - pt.t.setProperty(pt.p, value); + pt.t!.setProperty(pt.p, value); } else { - pt.t[pt.p] = value; + pt.t![pt.p as String] = value; } } @@ -339,13 +340,13 @@ class GTween { throw 'error'; } - void _render(double time) { + void _render(double? time) { if (!_inited) { _init(); time = 0; } var prevTime = time; - if (time >= _duration) { + if (time! >= _duration!) { time = _duration; ratio = 1; } else if (time <= 0) { @@ -355,12 +356,12 @@ class GTween { ratio = 0; } else { // ratio = _ease.getRatio(time / _duration); - ratio = _ease(time / _duration); + ratio = _ease!(time / _duration!); } var pt = _firstPT; while (pt != null) { - _setCurrentValue(pt, ratio); + _setCurrentValue(pt, ratio!); pt = pt._next; } _signal(nanoVars.onUpdate, nanoVars.onUpdateParams); @@ -374,17 +375,17 @@ class GTween { } } - void _signal(Function callback, CallbackParams params) { + void _signal(Function? callback, CallbackParams? params) { if (callback != null) { /// It's a very slow approach. Function.apply(callback, params?.positional, params?.named); } } - Object _getAnimatable(Object searchTarget) { + Object? _getAnimatable(Object searchTarget) { if (_animatableTarget == searchTarget) return target; if (_targets != null) { - for (var t in _targets) { + for (var t in _targets!) { if (t is GTweenable) { if (t.target == searchTarget) return t; } @@ -393,7 +394,7 @@ class GTween { return null; } - void kill([Object tg]) { + void kill([Object? tg]) { tg ??= _targets ?? target; var pt = _firstPT; if (tg is List) { @@ -407,22 +408,22 @@ class GTween { return; } } else if (_targets != null) { - var i = _targets.length; + var i = _targets!.length; if (tg is! GTweenable) { - tg = _getAnimatable(tg); + tg = _getAnimatable(tg!); } while (--i > -1) { - if (tg == _targets[i]) { - _targets.removeAt(i); + if (tg == _targets![i]) { + _targets!.removeAt(i); } } while (pt != null) { if (pt.t == tg) { if (pt._next != null) { - pt._next._prev = pt._prev; + pt._next!._prev = pt._prev; } if (pt._prev != null) { - pt._prev._next = pt._next; + pt._prev!._next = pt._next; } else { _firstPT = pt._next; } @@ -430,15 +431,15 @@ class GTween { pt = pt._next; } } - if (_targets == null || _targets.isEmpty) { + if (_targets == null || _targets!.isEmpty) { _gc = true; if (_prev != null) { - _prev._next = _next; + _prev!._next = _next; } else if (this == _first) { _first = _next; } if (_next != null) { - _next._prev = _prev; + _next!._prev = _prev; } else if (this == _last) { _last = _prev; } @@ -462,7 +463,8 @@ class GTween { } /// Shortcut to start a tween on an `target`. - static GTween to(Object target, double duration, Map vars, [GVars nanoVars]) { + static GTween to(Object? target, double duration, Map? vars, + [GVars? nanoVars]) { nanoVars ??= GVars(); return GTween(target, duration, vars, nanoVars); } @@ -470,7 +472,7 @@ class GTween { /// Shortcut to start a tween on an `target`, start from the end values /// to the start values, this option flips the tweens. static GTween from(Object target, double duration, Map vars, - [GVars nanoVars]) { + [GVars? nanoVars]) { nanoVars ??= GVars(); nanoVars.runBackwards = true; nanoVars.immediateRender ??= true; @@ -483,7 +485,7 @@ class GTween { static GTween delayedCall( double delay, Function callback, { - Object params, + Object? params, bool useFrames = false, }) { var props = GVars() @@ -519,7 +521,7 @@ class GTween { } /// Removes a Tween based on the the target object. - static void killTweensOf(Object target) { + static void killTweensOf(Object? target) { var t = _first; while (t != null) { var next = t._next; @@ -533,4 +535,4 @@ class GTween { } } -typedef GxAnimatableBuilder = GTweenable Function(Object target); +typedef GxAnimatableBuilder = GTweenable? Function(Object? target); diff --git a/lib/src/tween/src/lerps/common_lerps.dart b/lib/src/tween/src/lerps/common_lerps.dart index 1a905b1..283cfed 100644 --- a/lib/src/tween/src/lerps/common_lerps.dart +++ b/lib/src/tween/src/lerps/common_lerps.dart @@ -1,16 +1,16 @@ part of gtween; -class GTweenLerpColor extends GTweenLerpProp { +class GTweenLerpColor extends GTweenLerpProp { GTweenLerpColor({ - GTweenSetProp setProp, - GTweenGetProp getProp, + GTweenSetProp? setProp, + GTweenGetProp? getProp, }) : super( setProp: setProp, getProp: getProp, ); @override - Color resolve(double ratio) { + Color? resolve(double ratio) { final value = Color.lerp(from, to, ratio); setProp?.call(value); return value; diff --git a/lib/src/tween/src/mixins/tweenable.dart b/lib/src/tween/src/mixins/tweenable.dart index 68f8430..1fe63c6 100644 --- a/lib/src/tween/src/mixins/tweenable.dart +++ b/lib/src/tween/src/mixins/tweenable.dart @@ -4,16 +4,16 @@ typedef GTweenSetProp = void Function(T targetValue); typedef GTweenGetProp = T Function(); class GTweenLerpProp { - T from; - T to; - String name; + T? from; + T? to; + String? name; - GTweenSetProp setProp; - GTweenGetProp getProp; + GTweenSetProp? setProp; + GTweenGetProp? getProp; GTweenLerpProp({this.setProp, this.getProp}); - T resolve(double ratio) => null; + T? resolve(double ratio) => null; } /// Base interface used by [GTween] to animate properties. @@ -26,11 +26,11 @@ mixin GTweenable { /// Also used by [GTween] to reference internally the "_nativeTarget" instead /// of the [GTweenable] instance. So you can "kill" the tween by [GTweenable] /// or using the actual object that you plan to Tween. - Object target; + Object? target; /// override to know which properties will change. void setTweenProp(PropTween tweenProp) { - final lerpObj = _lerps[tweenProp.p]; + final lerpObj = _lerps[tweenProp.p as String]; if (lerpObj == null) return; lerpObj.to = tweenProp.cObj; tweenProp.c = 1.0; @@ -42,7 +42,7 @@ mixin GTweenable { @override String toString() => '[GTweenable] $target'; - Map> _accessors; + Map>? _accessors; /// Lerps are special objects that are not `double` like /// Color, Rect, etc. @@ -53,35 +53,35 @@ mixin GTweenable { void initProps() => _accessors = getTweenableAccessors(); /// implement in class. - Map> getTweenableAccessors() => null; + Map>? getTweenableAccessors() => null; - void setProperty(Object prop, double value) { - if (_lerps[prop] != null) { - _lerps[prop].resolve(value); + void setProperty(Object? prop, double value) { + if (_lerps[prop as String] != null) { + _lerps[prop]!.resolve(value); // TODO: add setLerp(prop, value) function to be override? } else { if (_accessors == null) initProps(); - _accessors[prop][1](value); + _accessors![prop]![1](value); } } double getProperty(Object prop) { if (_lerps.containsKey(prop)) { - _lerps[prop]?.from = _lerps[prop]?.getProp(); + _lerps[prop as String]?.from = _lerps[prop]?.getProp!(); // TODO: add initLerp(prop) to read the initial value from `target` ? return 0.0; } if (_accessors == null) initProps(); - return _accessors[prop][0](); + return _accessors![prop]![0](); } /// when tween is disposed. void dispose() { - _lerps?.clear(); + _lerps.clear(); // _lerps = null; } - double operator [](String key) => getProperty(key); + double? operator [](String key) => getProperty(key); - void operator []=(String key, double value) => setProperty(key, value); + void operator []=(String? key, double value) => setProperty(key, value); } diff --git a/lib/src/tween/src/wraps/common_wraps.dart b/lib/src/tween/src/wraps/common_wraps.dart index dbc6abb..cd993b6 100644 --- a/lib/src/tween/src/wraps/common_wraps.dart +++ b/lib/src/tween/src/wraps/common_wraps.dart @@ -4,40 +4,39 @@ part of gtween; abstract class CommonTweenWraps { /// TODO: check performance to use a Custom mapping type. /// Lerps (like Color) are managed separately. - static Map> displayObject(GDisplayObject o) { + static Map> displayObject(GDisplayObject? o) { return { - 'x': [() => o.x, (v) => o.x = v], - 'y': [() => o.y, (v) => o.y = v], - 'scaleX': [() => o.scaleX, (v) => o.scaleX = v], - 'scaleY': [() => o.scaleY, (v) => o.scaleY = v], - 'scale': [() => o.scale, (v) => o.scale = v], - 'rotation': [() => o.rotation, (v) => o.rotation = v], - 'rotationX': [() => o.rotationX, (v) => o.rotationX = v], - 'rotationY': [() => o.rotationY, (v) => o.rotationY = v], - 'pivotX': [() => o.pivotX, (v) => o.pivotX = v], - 'pivotY': [() => o.pivotY, (v) => o.pivotY = v], - 'width': [() => o.width, (v) => o.width = v], - 'height': [() => o.height, (v) => o.height = v], - 'skewX': [() => o.skewX, (v) => o.skewX = v], - 'skewY': [() => o.skewY, (v) => o.skewY = v], - 'alpha': [() => o.alpha, (v) => o.alpha = v], + 'x': [() => o!.x, (v) => o!.x = v], + 'y': [() => o!.y, (v) => o!.y = v], + 'scaleX': [() => o!.scaleX, (v) => o!.scaleX = v], + 'scaleY': [() => o!.scaleY, (v) => o!.scaleY = v], + 'scale': [() => o!.scale, (v) => o!.scale = v], + 'rotation': [() => o!.rotation, (v) => o!.rotation = v], + 'rotationX': [() => o!.rotationX, (v) => o!.rotationX = v], + 'rotationY': [() => o!.rotationY, (v) => o!.rotationY = v], + 'pivotX': [() => o!.pivotX, (v) => o!.pivotX = v], + 'pivotY': [() => o!.pivotY, (v) => o!.pivotY = v], + 'width': [() => o!.width, (v) => o!.width = v], + 'height': [() => o!.height, (v) => o!.height = v], + 'skewX': [() => o!.skewX, (v) => o!.skewX = v], + 'skewY': [() => o!.skewY, (v) => o!.skewY = v], + 'alpha': [() => o!.alpha, (v) => o!.alpha = v], }; } } class GTweenableDouble with GTweenable, SingleValueTweenMixin { - static GTweenable wrap(Object target) => + static GTweenable? wrap(Object? target) => target is double ? GTweenableDouble(target) : null; - double value; + double? value; GTweenableDouble(double target) { value = this.target = target; } @override - Map> getTweenableAccessors() => - { + Map> getTweenableAccessors() => { 'value': [() => value, (v) => value = v], }; @@ -46,21 +45,20 @@ class GTweenableDouble with GTweenable, SingleValueTweenMixin { } class GTweenableInt with GTweenable, SingleValueTweenMixin { - static GTweenable wrap(Object target) => + static GTweenable? wrap(Object? target) => target is int ? GTweenableInt(target) : null; - int value; + int? value; GTweenableInt(int target) { value = this.target = target; } @override - Map> getTweenableAccessors() => - { + Map> getTweenableAccessors() => { 'value': [ - () => value + .0, - (v) => value = v.round(), + () => value! + .0, + (v) => value = v.round(), ], }; @@ -69,17 +67,17 @@ class GTweenableInt with GTweenable, SingleValueTweenMixin { } class GTweenableMap with GTweenable { - static GTweenable wrap(Object target) => - target is Map ? GTweenableMap(target) : null; + static GTweenable? wrap(Object? target) => + target is Map ? GTweenableMap(target) : null; - Map value; + late Map value; GTweenableMap(Map target) { value = this.target = target; } @override - void setProperty(Object prop, double val) { + void setProperty(Object? prop, double val) { value[prop] = convertFromDouble(value[prop], val); } @@ -88,24 +86,23 @@ class GTweenableMap with GTweenable { return convertToDouble(value[prop]); } - GTween tween(Map targetMap, { - @required double duration, - EaseFunction ease, - double delay, - bool useFrames, - int overwrite, - VoidCallback onStart, - Object onStartParams, - VoidCallback onComplete, - Object onCompleteParams, - VoidCallback onUpdate, - Object onUpdateParams, - bool runBackwards, - bool immediateRender, - Map startAt, + GTween tween( + Map targetMap, { + required double duration, + EaseFunction? ease, + double? delay, + bool? useFrames, + int? overwrite, + VoidCallback? onStart, + Object? onStartParams, + VoidCallback? onComplete, + Object? onCompleteParams, + VoidCallback? onUpdate, + Object? onUpdateParams, + bool? runBackwards, + bool? immediateRender, + Map? startAt, }) { - assert(targetMap != null); - targetMap.removeWhere((k, v) => !value.containsKey(k)); if (targetMap.isEmpty) { throw ''' @@ -136,20 +133,20 @@ tween(targetMap) Map can't be empty. Or there are no matching keys with the twee } class GTweenableList with GTweenable { - static GTweenable wrap(Object target) { + static GTweenable? wrap(Object? target) { if (target is! List) return null; return GTweenableList(target); } - List value; + late List value; GTweenableList(List target) { value = this.target = target; } @override - void setProperty(Object prop, double val) { - final index = int.tryParse('$prop'); + void setProperty(Object? prop, double val) { + final index = int.tryParse('$prop')!; value[index] = convertFromDouble(value[index], val); } @@ -158,23 +155,23 @@ class GTweenableList with GTweenable { return convertToDouble(value[int.parse('$prop')]); } - GTween tween(List targetList, { - @required double duration, - EaseFunction ease, - double delay, - bool useFrames, - int overwrite, - VoidCallback onStart, - Object onStartParams, - VoidCallback onComplete, - Object onCompleteParams, - VoidCallback onUpdate, - Object onUpdateParams, - bool runBackwards, - bool immediateRender, - Map startAt, + GTween tween( + List targetList, { + required double duration, + EaseFunction? ease, + double? delay, + bool? useFrames, + int? overwrite, + VoidCallback? onStart, + Object? onStartParams, + VoidCallback? onComplete, + Object? onCompleteParams, + VoidCallback? onUpdate, + Object? onUpdateParams, + bool? runBackwards, + bool? immediateRender, + Map? startAt, }) { - assert(targetList != null); targetList.removeWhere((element) => element is! num); if (targetList.isEmpty) { throw ''' @@ -207,7 +204,7 @@ tween(targetList) List can't be empty. Or values inside of it where not a number } } -Object convertFromDouble(Object originalValue, double val) { +Object convertFromDouble(Object? originalValue, double val) { if (originalValue is int) { return val.toInt(); } else if (originalValue is String) { @@ -217,35 +214,35 @@ Object convertFromDouble(Object originalValue, double val) { } } -double convertToDouble(Object val) { +double convertToDouble(Object? val) { if (val is int) { return val + .0; } else if (val is String) { - return double.tryParse(val); + return double.tryParse(val) as double; } - return val; + return val as double; } mixin SingleValueTweenMixin { - Object getValue; + Object? getValue; - GTween tween(Object value, { - @required double duration, - EaseFunction ease, - double delay, - bool useFrames, - int overwrite, - Function onStart, - Object onStartParams, - Function onComplete, - Object onCompleteParams, - Function onUpdate, - Object onUpdateParams, - bool runBackwards, - bool immediateRender, - Map startAt, + GTween tween( + Object value, { + required double duration, + EaseFunction? ease, + double? delay, + bool? useFrames, + int? overwrite, + Function? onStart, + Object? onStartParams, + Function? onComplete, + Object? onCompleteParams, + Function? onUpdate, + Object? onUpdateParams, + bool? runBackwards, + bool? immediateRender, + Map? startAt, }) { - assert(value != null); return GTween.to( this, duration, diff --git a/lib/src/tween/src/wraps/display_object.dart b/lib/src/tween/src/wraps/display_object.dart index 428b8fe..8216359 100644 --- a/lib/src/tween/src/wraps/display_object.dart +++ b/lib/src/tween/src/wraps/display_object.dart @@ -1,7 +1,7 @@ part of gtween; class GTweenableDisplayObject with GTweenable { - static GTweenable wrap(Object target) { + static GTweenable? wrap(Object? target) { if (target is! GDisplayObject) return null; return GTweenableDisplayObject(target); } @@ -20,5 +20,5 @@ class GTweenableDisplayObject with GTweenable { @override Map> getTweenableAccessors() => - CommonTweenWraps.displayObject(target); + CommonTweenWraps.displayObject(target as GDisplayObject?); } diff --git a/lib/src/tween/src/wraps/filter_wraps.dart b/lib/src/tween/src/wraps/filter_wraps.dart index cd3031f..e600fc5 100644 --- a/lib/src/tween/src/wraps/filter_wraps.dart +++ b/lib/src/tween/src/wraps/filter_wraps.dart @@ -1,12 +1,12 @@ part of gtween; class GTweenableBlur with GTweenable { - static GTweenable wrap(Object target) { + static GTweenable? wrap(Object target) { if (target is! GBlurFilter) return null; return GTweenableBlur(target); } - GBlurFilter value; + late GBlurFilter value; GTweenableBlur(GBlurFilter target) { value = this.target = target; @@ -19,22 +19,22 @@ class GTweenableBlur with GTweenable { }; GTween tween({ - @required double duration, - Object blurX, - Object blurY, - EaseFunction ease, - double delay, - bool useFrames, + required double duration, + Object? blurX, + Object? blurY, + EaseFunction? ease, + double? delay, + bool? useFrames, int overwrite = 1, - VoidCallback onStart, - Object onStartParams, - VoidCallback onComplete, - Object onCompleteParams, - VoidCallback onUpdate, - Object onUpdateParams, - bool runBackwards, - bool immediateRender, - Map startAt, + VoidCallback? onStart, + Object? onStartParams, + VoidCallback? onComplete, + Object? onCompleteParams, + VoidCallback? onUpdate, + Object? onUpdateParams, + bool? runBackwards, + bool? immediateRender, + Map? startAt, }) { final targetMap = { if (blurX != null) 'blurX': blurX, @@ -63,12 +63,12 @@ class GTweenableBlur with GTweenable { } class GTweenableDropShadowFilter with GTweenable { - static GTweenable wrap(Object target) { + static GTweenable? wrap(Object target) { if (target is! GDropShadowFilter) return null; return GTweenableDropShadowFilter(target); } - GDropShadowFilter value; + late GDropShadowFilter value; GTweenableDropShadowFilter(GDropShadowFilter target) { value = this.target = target; @@ -91,25 +91,25 @@ class GTweenableDropShadowFilter with GTweenable { }; GTween tween({ - @required double duration, - Object blurX, - Object blurY, - Object angle, - Object distance, - Color color, - EaseFunction ease, - double delay, - bool useFrames, + required double duration, + Object? blurX, + Object? blurY, + Object? angle, + Object? distance, + Color? color, + EaseFunction? ease, + double? delay, + bool? useFrames, int overwrite = 1, - VoidCallback onStart, - Object onStartParams, - VoidCallback onComplete, - Object onCompleteParams, - VoidCallback onUpdate, - Object onUpdateParams, - bool runBackwards, - bool immediateRender, - Map startAt, + VoidCallback? onStart, + Object? onStartParams, + VoidCallback? onComplete, + Object? onCompleteParams, + VoidCallback? onUpdate, + Object? onUpdateParams, + bool? runBackwards, + bool? immediateRender, + Map? startAt, }) { final targetMap = { if (blurX != null) 'blurX': blurX, @@ -141,12 +141,12 @@ class GTweenableDropShadowFilter with GTweenable { } class GTweenableGlowFilter with GTweenable { - static GTweenable wrap(Object target) { + static GTweenable? wrap(Object target) { if (target is! GlowFilter) return null; return GTweenableGlowFilter(target); } - GlowFilter value; + late GlowFilter value; GTweenableGlowFilter(GlowFilter target) { value = this.target = target; @@ -167,23 +167,23 @@ class GTweenableGlowFilter with GTweenable { }; GTween tween({ - @required double duration, - Object blurX, - Object blurY, - Color color, - EaseFunction ease, - double delay, - bool useFrames, + required double duration, + Object? blurX, + Object? blurY, + Color? color, + EaseFunction? ease, + double? delay, + bool? useFrames, int overwrite = 1, - VoidCallback onStart, - Object onStartParams, - VoidCallback onComplete, - Object onCompleteParams, - VoidCallback onUpdate, - Object onUpdateParams, - bool runBackwards, - bool immediateRender, - Map startAt, + VoidCallback? onStart, + Object? onStartParams, + VoidCallback? onComplete, + Object? onCompleteParams, + VoidCallback? onUpdate, + Object? onUpdateParams, + bool? runBackwards, + bool? immediateRender, + Map? startAt, }) { final targetMap = { if (blurX != null) 'blurX': blurX, diff --git a/lib/src/tween/src/wraps/geom_wraps.dart b/lib/src/tween/src/wraps/geom_wraps.dart index 534d169..323ab7c 100644 --- a/lib/src/tween/src/wraps/geom_wraps.dart +++ b/lib/src/tween/src/wraps/geom_wraps.dart @@ -1,12 +1,12 @@ part of gtween; class GTweenablePoint with GTweenable { - static GTweenable wrap(Object target) { + static GTweenable? wrap(Object target) { if (target is! GPoint) return null; return GTweenablePoint(target); } - GPoint value; + late GPoint value; GTweenablePoint(GPoint target) { value = this.target = target; @@ -19,23 +19,23 @@ class GTweenablePoint with GTweenable { }; GTween tween({ - @required double duration, - Object x, - Object y, - GPoint to, - EaseFunction ease, - double delay, - bool useFrames, - int overwrite, - VoidCallback onStart, - Object onStartParams, - VoidCallback onComplete, - Object onCompleteParams, - VoidCallback onUpdate, - Object onUpdateParams, - bool runBackwards, - bool immediateRender, - Map startAt, + required double duration, + Object? x, + Object? y, + GPoint? to, + EaseFunction? ease, + double? delay, + bool? useFrames, + int? overwrite, + VoidCallback? onStart, + Object? onStartParams, + VoidCallback? onComplete, + Object? onCompleteParams, + VoidCallback? onUpdate, + Object? onUpdateParams, + bool? runBackwards, + bool? immediateRender, + Map? startAt, }) { if ((x != null || y != null) && to != null) { throw ''' @@ -71,12 +71,12 @@ GTween Can't use 'x, y' AND 'to' arguments for GxPoint tween. Choose one'''; } class GTweenableRect with GTweenable { - static GTweenable wrap(Object target) { + static GTweenable? wrap(Object target) { if (target is! GRect) return null; return GTweenableRect(target); } - GRect value; + late GRect value; GTweenableRect(GRect target) { value = this.target = target; @@ -91,25 +91,25 @@ class GTweenableRect with GTweenable { }; GTween tween( - {@required double duration, - Object x, - Object y, - Object width, - Object height, - GRect to, - EaseFunction ease, - double delay, - bool useFrames, - int overwrite, - VoidCallback onStart, - Object onStartParams, - VoidCallback onComplete, - Object onCompleteParams, - VoidCallback onUpdate, - Object onUpdateParams, - bool runBackwards, - bool immediateRender, - Map startAt}) { + {required double duration, + Object? x, + Object? y, + Object? width, + Object? height, + GRect? to, + EaseFunction? ease, + double? delay, + bool? useFrames, + int? overwrite, + VoidCallback? onStart, + Object? onStartParams, + VoidCallback? onComplete, + Object? onCompleteParams, + VoidCallback? onUpdate, + Object? onUpdateParams, + bool? runBackwards, + bool? immediateRender, + Map? startAt}) { if ((x != null || y != null || width != null || height != null) && to != null) { throw "GTween Can't use 'x, y, width, height' AND 'to' arguments to " @@ -151,14 +151,14 @@ class GTweenableRect with GTweenable { } class GTweenableColor with GTweenable { - static GTweenable wrap(Object target) { + static GTweenable? wrap(Object target) { if (target is! Color) return null; return GTweenableColor(target); } - Color value; - PropTween _propTween; - Color _targetColor; + Color? value; + late PropTween _propTween; + Color? _targetColor; @override void setTweenProp(PropTween tweenProp) { @@ -171,29 +171,28 @@ class GTweenableColor with GTweenable { } @override - void setProperty(Object prop, double val) { - value = Color.lerp(target, _targetColor, val); + void setProperty(Object? prop, double val) { + value = Color.lerp(target as Color?, _targetColor, val); } @override double getProperty(Object prop) => 0.0; // start value, from 0-1 GTween tween(Color color, - {@required double duration, - EaseFunction ease, - double delay, - bool useFrames, - int overwrite, - VoidCallback onStart, - Object onStartParams, - VoidCallback onComplete, - Object onCompleteParams, - VoidCallback onUpdate, - Object onUpdateParams, - bool runBackwards, - bool immediateRender, - Map startAt}) { - assert(color != null); + {required double duration, + EaseFunction? ease, + double? delay, + bool? useFrames, + int? overwrite, + VoidCallback? onStart, + Object? onStartParams, + VoidCallback? onComplete, + Object? onCompleteParams, + VoidCallback? onUpdate, + Object? onUpdateParams, + bool? runBackwards, + bool? immediateRender, + Map? startAt}) { _targetColor = color; return GTween.to( this, diff --git a/lib/src/utils/context_utils.dart b/lib/src/utils/context_utils.dart index 43919cc..55b2a93 100644 --- a/lib/src/utils/context_utils.dart +++ b/lib/src/utils/context_utils.dart @@ -4,7 +4,8 @@ import '../../graphx.dart'; abstract class ContextUtils { /// todo: validate RenderObject Type. - static GRect getRenderObjectBounds(BuildContext context) { + static GRect? getRenderObjectBounds(BuildContext context) { + trace(context); final box = context.findRenderObject() as RenderBox; return GRect.fromNative(box.localToGlobal(Offset.zero) & box.size); } diff --git a/lib/src/utils/http/_http_io.dart b/lib/src/utils/http/_http_io.dart index a51c649..8b19dce 100644 --- a/lib/src/utils/http/_http_io.dart +++ b/lib/src/utils/http/_http_io.dart @@ -3,17 +3,18 @@ import 'dart:typed_data'; import 'package:flutter/foundation.dart'; -/// Fetches an HTTP resource from the specified [url] using the specified [headers]. -Future httpGet(String url, {Map headers}) async { - final HttpClient httpClient = HttpClient(); - final Uri uri = Uri.base.resolve(url); - final HttpClientRequest request = await httpClient.getUrl(uri); +/// Fetches an HTTP resource from the specified +/// [url] using the specified [headers]. +Future httpGet(String url, {Map? headers}) async { + final httpClient = HttpClient(); + final uri = Uri.base.resolve(url); + final request = await httpClient.getUrl(uri); if (headers != null) { - headers.forEach((String key, String value) { + headers.forEach((key, value) { request.headers.add(key, value); }); } - final HttpClientResponse response = await request.close(); + final response = await request.close(); if (response.statusCode != HttpStatus.ok) { throw HttpException('Could not get network asset', uri: uri); diff --git a/lib/src/utils/http/_http_web.dart b/lib/src/utils/http/_http_web.dart index 236b087..0347135 100644 --- a/lib/src/utils/http/_http_web.dart +++ b/lib/src/utils/http/_http_web.dart @@ -1,9 +1,10 @@ import 'dart:html' as html; import 'dart:typed_data'; -/// Fetches an HTTP resource from the specified [url] using the specified [headers]. -Future httpGet(String url, {Map headers}) async { - final html.HttpRequest request = await html.HttpRequest.request(url, +/// Fetches an HTTP resource from the specified +/// [url] using the specified [headers]. +Future httpGet(String url, {Map? headers}) async { + final request = await html.HttpRequest.request(url, requestHeaders: headers, responseType: 'arraybuffer'); if (request.status != html.HttpStatus.ok) { throw 'Could not get network asset: "$url"'; diff --git a/lib/src/utils/keyboard_util.dart b/lib/src/utils/keyboard_util.dart index 1f9b6ba..214a1c3 100644 --- a/lib/src/utils/keyboard_util.dart +++ b/lib/src/utils/keyboard_util.dart @@ -152,9 +152,11 @@ class GKeyboard { static const copy = GKeyboard._(LogicalKeyboardKey.copy); static const paste = GKeyboard._(LogicalKeyboardKey.paste); static const find = GKeyboard._(LogicalKeyboardKey.find); - static const audioVolumeMute = GKeyboard._(LogicalKeyboardKey.audioVolumeMute); + static const audioVolumeMute = + GKeyboard._(LogicalKeyboardKey.audioVolumeMute); static const audioVolumeUp = GKeyboard._(LogicalKeyboardKey.audioVolumeUp); - static const audioVolumeDown = GKeyboard._(LogicalKeyboardKey.audioVolumeDown); + static const audioVolumeDown = + GKeyboard._(LogicalKeyboardKey.audioVolumeDown); static const numpadComma = GKeyboard._(LogicalKeyboardKey.numpadComma); static const intlRo = GKeyboard._(LogicalKeyboardKey.intlRo); static const kanaMode = GKeyboard._(LogicalKeyboardKey.kanaMode); @@ -168,17 +170,20 @@ class GKeyboard { static const lang5 = GKeyboard._(LogicalKeyboardKey.lang5); static const abort = GKeyboard._(LogicalKeyboardKey.abort); static const props = GKeyboard._(LogicalKeyboardKey.props); - static const numpadParenLeft = GKeyboard._(LogicalKeyboardKey.numpadParenLeft); + static const numpadParenLeft = + GKeyboard._(LogicalKeyboardKey.numpadParenLeft); static const numpadParenRight = GKeyboard._(LogicalKeyboardKey.numpadParenRight); - static const numpadBackspace = GKeyboard._(LogicalKeyboardKey.numpadBackspace); + static const numpadBackspace = + GKeyboard._(LogicalKeyboardKey.numpadBackspace); static const numpadMemoryStore = GKeyboard._(LogicalKeyboardKey.numpadMemoryStore); static const numpadMemoryRecall = GKeyboard._(LogicalKeyboardKey.numpadMemoryRecall); static const numpadMemoryClear = GKeyboard._(LogicalKeyboardKey.numpadMemoryClear); - static const numpadMemoryAdd = GKeyboard._(LogicalKeyboardKey.numpadMemoryAdd); + static const numpadMemoryAdd = + GKeyboard._(LogicalKeyboardKey.numpadMemoryAdd); static const numpadMemorySubtract = GKeyboard._(LogicalKeyboardKey.numpadMemorySubtract); static const numpadSignChange = @@ -246,13 +251,15 @@ class GKeyboard { static const launchControlPanel = GKeyboard._(LogicalKeyboardKey.launchControlPanel); static const selectTask = GKeyboard._(LogicalKeyboardKey.selectTask); - static const launchDocuments = GKeyboard._(LogicalKeyboardKey.launchDocuments); + static const launchDocuments = + GKeyboard._(LogicalKeyboardKey.launchDocuments); static const spellCheck = GKeyboard._(LogicalKeyboardKey.spellCheck); static const launchKeyboardLayout = GKeyboard._(LogicalKeyboardKey.launchKeyboardLayout); static const launchScreenSaver = GKeyboard._(LogicalKeyboardKey.launchScreenSaver); - static const launchAssistant = GKeyboard._(LogicalKeyboardKey.launchAssistant); + static const launchAssistant = + GKeyboard._(LogicalKeyboardKey.launchAssistant); static const launchAudioBrowser = GKeyboard._(LogicalKeyboardKey.launchAudioBrowser); static const newKey = GKeyboard._(LogicalKeyboardKey.newKey); @@ -296,8 +303,10 @@ class GKeyboard { static const gameButtonA = GKeyboard._(LogicalKeyboardKey.gameButtonA); static const gameButtonB = GKeyboard._(LogicalKeyboardKey.gameButtonB); static const gameButtonC = GKeyboard._(LogicalKeyboardKey.gameButtonC); - static const gameButtonLeft1 = GKeyboard._(LogicalKeyboardKey.gameButtonLeft1); - static const gameButtonLeft2 = GKeyboard._(LogicalKeyboardKey.gameButtonLeft2); + static const gameButtonLeft1 = + GKeyboard._(LogicalKeyboardKey.gameButtonLeft1); + static const gameButtonLeft2 = + GKeyboard._(LogicalKeyboardKey.gameButtonLeft2); static const gameButtonMode = GKeyboard._(LogicalKeyboardKey.gameButtonMode); static const gameButtonRight1 = GKeyboard._(LogicalKeyboardKey.gameButtonRight1); @@ -305,7 +314,8 @@ class GKeyboard { GKeyboard._(LogicalKeyboardKey.gameButtonRight2); static const gameButtonSelect = GKeyboard._(LogicalKeyboardKey.gameButtonSelect); - static const gameButtonStart = GKeyboard._(LogicalKeyboardKey.gameButtonStart); + static const gameButtonStart = + GKeyboard._(LogicalKeyboardKey.gameButtonStart); static const gameButtonThumbLeft = GKeyboard._(LogicalKeyboardKey.gameButtonThumbLeft); static const gameButtonThumbRight = @@ -328,15 +338,15 @@ class GKeyboard { alt: () => isDown(altLeft) || isDown(altRight), }; - static Stage _stage; + static Stage? _stage; static bool justReleased(GKeyboard key) { - return _justReleased[key] != null; + return _justReleased[key as LogicalKeyboardKey] != null; } static bool isDown(GKeyboard key) { if (_metaKeys.containsKey(key)) { - return _metaKeys[key](); + return _metaKeys[key]!(); } return _pressed[key.value] ?? false; } @@ -344,17 +354,17 @@ class GKeyboard { /// Initializer of the Keyboard utility class. static void init(Stage stage) { _stage = stage; - _stage.keyboard.onDown.add(_onKey); - _stage.keyboard.onUp.add(_onKey); + _stage!.keyboard!.onDown.add(_onKey); + _stage!.keyboard!.onUp.add(_onKey); } static void dispose() { - _stage?.keyboard?.onDown?.remove(_onKey); - _stage?.keyboard?.onUp?.remove(_onKey); + _stage?.keyboard?.onDown.remove(_onKey); + _stage?.keyboard?.onUp.remove(_onKey); } static void _onKey(KeyboardEventData input) { - final k = input.rawEvent.logicalKey; + final k = input.rawEvent!.logicalKey; if (input.type == KeyEventType.down) { _pressed[k] = true; } else { diff --git a/lib/src/utils/layout_utils.dart b/lib/src/utils/layout_utils.dart index d2280d2..3b046e0 100644 --- a/lib/src/utils/layout_utils.dart +++ b/lib/src/utils/layout_utils.dart @@ -22,25 +22,24 @@ class LayoutUtils { static void objectFit( GDisplayObject object, { BoxFit fit = BoxFit.cover, - double objW, - double objH, - @required double canvasW, - @required double canvasH, + double? objW, + double? objH, + required double canvasW, + required double canvasH, bool reposition = false, }) { - assert(canvasW != null && canvasH != null); if (objW == null || objH == null) { /// calculate real objects bounds. if (object is GBitmap) { - objW ??= object.texture.width; - objH ??= object.texture.height; + objW ??= object.texture!.width; + objH ??= object.texture!.height; } else { - final bounds = object.bounds; + final bounds = object.bounds!; objW ??= bounds.width; objH ??= bounds.height; } } - var r1 = objW / objH; + var r1 = objW! / objH!; var r2 = canvasW / canvasH; if (fit == BoxFit.scaleDown) { @@ -143,7 +142,7 @@ class LayoutUtils { double gapX = 0, double gapY = 0, int rows = 0, - @required int cols, + required int cols, double width = 0, double height = 0, double startX = 0, @@ -203,7 +202,7 @@ class LayoutUtils { width = maxW; } - final parent = items?.first?.parent as GSprite; + final parent = items.first.parent as GSprite?; final hasSize = width > 0 && height > 0; if (debug && parent != null && hasSize) { final g = parent.graphics; @@ -303,7 +302,7 @@ class LayoutUtils { height = maxH; } - final parent = items?.first?.parent as GSprite; + final parent = items.first.parent as GSprite?; final hasSize = width > 0 && height > 0; if (debug && parent != null && hasSize) { final g = parent.graphics; diff --git a/lib/src/utils/list_utils.dart b/lib/src/utils/list_utils.dart index 74a68aa..bbf604f 100644 --- a/lib/src/utils/list_utils.dart +++ b/lib/src/utils/list_utils.dart @@ -1,10 +1,12 @@ - - import '../../graphx.dart'; abstract class ListUtils { - static void mergeSort(List input, SortChildrenCallback compare, - int startIndex, int len, List buffer) { + static void mergeSort( + List input, + SortChildrenCallback compare, + int startIndex, + int len, + List buffer) { if (len > 1) { int i, endIndex = startIndex + len, diff --git a/lib/src/utils/matrix_utils.dart b/lib/src/utils/matrix_utils.dart index 722cbe3..4f38be5 100644 --- a/lib/src/utils/matrix_utils.dart +++ b/lib/src/utils/matrix_utils.dart @@ -9,30 +9,30 @@ abstract class MatrixUtils { var sinY = Math.sin(skewY); var cosY = Math.cos(skewY); matrix.setTo( - matrix.a * cosY - matrix.b * sinX, - matrix.a * sinY + matrix.b * cosX, - matrix.c * cosY - matrix.d * sinX, - matrix.c * sinY + matrix.d * cosX, - matrix.tx * cosY - matrix.ty * sinX, - matrix.tx * sinY + matrix.ty * cosX, + matrix.a* cosY - matrix.b* sinX, + matrix.a* sinY + matrix.b* cosX, + matrix.c* cosY - matrix.d* sinX, + matrix.c* sinY + matrix.d* cosX, + matrix.tx* cosY - matrix.ty* sinX, + matrix.tx* sinY + matrix.ty* cosX, ); } static GRect getTransformedBoundsRect(GMatrix matrix, GRect rect, - [GRect out]) { + [GRect? out]) { out ??= GRect(); var minX = 10000000.0; var maxX = -10000000.0; var minY = 10000000.0; var maxY = -10000000.0; - var tx1 = matrix.a * rect.x + matrix.c * rect.y + matrix.tx; - var ty1 = matrix.d * rect.y + matrix.b * rect.x + matrix.ty; - var tx2 = matrix.a * rect.x + matrix.c * rect.bottom + matrix.tx; - var ty2 = matrix.d * rect.bottom + matrix.b * rect.x + matrix.ty; - var tx3 = matrix.a * rect.right + matrix.c * rect.y + matrix.tx; - var ty3 = matrix.d * rect.y + matrix.b * rect.right + matrix.ty; - var tx4 = matrix.a * rect.right + matrix.c * rect.bottom + matrix.tx; - var ty4 = matrix.d * rect.bottom + matrix.b * rect.right + matrix.ty; + var tx1 = matrix.a* rect.x+ matrix.c* rect.y+ matrix.tx; + var ty1 = matrix.d* rect.y+ matrix.b* rect.x+ matrix.ty; + var tx2 = matrix.a* rect.x+ matrix.c* rect.bottom + matrix.tx; + var ty2 = matrix.d* rect.bottom + matrix.b* rect.x+ matrix.ty; + var tx3 = matrix.a* rect.right + matrix.c* rect.y+ matrix.tx; + var ty3 = matrix.d* rect.y+ matrix.b* rect.right + matrix.ty; + var tx4 = matrix.a* rect.right + matrix.c* rect.bottom + matrix.tx; + var ty4 = matrix.d* rect.bottom + matrix.b* rect.right + matrix.ty; if (minX > tx1) minX = tx1; if (minX > tx2) minX = tx2; if (minX > tx3) minX = tx3; diff --git a/lib/src/utils/mixins.dart b/lib/src/utils/mixins.dart index 1dbfb1e..3f22f07 100644 --- a/lib/src/utils/mixins.dart +++ b/lib/src/utils/mixins.dart @@ -3,7 +3,7 @@ import 'dart:ui'; import '../../graphx.dart'; mixin RenderUtilMixin { - Picture createPicture([void Function(Canvas) prePaintCallback]) { + Picture createPicture([void Function(Canvas)? prePaintCallback]) { final r = PictureRecorder(); final c = Canvas(r); prePaintCallback?.call(c); @@ -53,14 +53,14 @@ mixin RenderUtilMixin { final width = adjustOffset ? rect.width.toInt() : rect.right.toInt(); final height = adjustOffset ? rect.height.toInt() : rect.bottom.toInt(); final output = await picture.toImage(width, height); - picture?.dispose(); + picture.dispose(); return output; } } mixin DisplayMasking { - GRect maskRect; - double maskRectCornerRadius; + GRect? maskRect; + double? maskRectCornerRadius; bool maskRectInverted = false; /// Direct scissor rect masking, more optimized than using @@ -78,15 +78,15 @@ mixin DisplayMasking { /// By default GxRect has no corners, so is only implemented to make use /// of `RRect` clipping. /// - void $applyMaskRect(Canvas c) { - if (maskRect.hasCorners) { - c.clipRRect( - maskRect.toRoundNative(), + void $applyMaskRect(Canvas? c) { + if (maskRect!.hasCorners) { + c!.clipRRect( + maskRect!.toRoundNative(), doAntiAlias: true, ); } else { - c.clipRect( - maskRect.toNative(), + c!.clipRect( + maskRect!.toNative(), clipOp: maskRectInverted ? ClipOp.difference : ClipOp.intersect, doAntiAlias: true, ); diff --git a/lib/src/utils/pools.dart b/lib/src/utils/pools.dart index 11b227f..940a896 100644 --- a/lib/src/utils/pools.dart +++ b/lib/src/utils/pools.dart @@ -17,7 +17,7 @@ mixin Pool { /// Remember to NOT KEEP any references to the object after moving it to /// the pool. static void putPoint(GPoint point) { - if (point != null) _points.add(point); + _points.add(point); } static GMatrix getMatrix([ @@ -33,7 +33,7 @@ mixin Pool { } static void putMatrix(GMatrix matrix) { - if (matrix != null) _matrices.add(matrix); + _matrices.add(matrix); } static GRect getRect([ @@ -47,6 +47,6 @@ mixin Pool { } static void putRect(GRect rect) { - if (rect != null) _rectangles.add(rect); + _rectangles.add(rect); } } diff --git a/lib/src/utils/string_utils.dart b/lib/src/utils/string_utils.dart index df31939..309f7de 100644 --- a/lib/src/utils/string_utils.dart +++ b/lib/src/utils/string_utils.dart @@ -1,8 +1,5 @@ class StringUtils { static bool parseBoolean(String value) { - if (value == null) { - return false; - } return value == 'true' || value == 'TRUE' || value == 'True' || diff --git a/lib/src/utils/texture_utils.dart b/lib/src/utils/texture_utils.dart index ba1d104..1e6533e 100644 --- a/lib/src/utils/texture_utils.dart +++ b/lib/src/utils/texture_utils.dart @@ -10,25 +10,25 @@ mixin GTextureUtils { static void scale9Rect( GTexture tx, double x, { - double y, - double w, - double h, + double? y, + double? w, + double? h, bool adjustScale = false, }) { y ??= x; w ??= -x; h ??= -y; if (adjustScale) { - x *= tx.scale; - y *= tx.scale; - w *= tx.scale; - h *= tx.scale; + x *= tx.scale!; + y *= tx.scale!; + w *= tx.scale!; + h *= tx.scale!; } if (w < 0) { - w = tx.width + w * 2; + w = tx.width! + w * 2; } if (h < 0) { - h = tx.height + h * 2; + h = tx.height! + h * 2; } var out = GRect(x, y, w, h); tx.scale9Grid = out; @@ -39,7 +39,7 @@ mixin GTextureUtils { double radius = 20, double x = 0, double y = 0, - String id, + String? id, }) async { _g.clear()..beginFill(color).drawCircle(x, y, radius); return await _drawShape(id); @@ -51,7 +51,7 @@ mixin GTextureUtils { double y = 0, double w = 20, double h = 20, - String id, + String? id, }) async { _g.clear()..beginFill(color).drawRect(x, y, w, h); return (await _drawShape(id)); @@ -64,7 +64,7 @@ mixin GTextureUtils { double w = 20, double h = 20, double r = 8, - String id, + String? id, }) async { _g.clear()..beginFill(color).drawRoundRect(x, y, w, h, r); return (await _drawShape(id)); @@ -75,7 +75,7 @@ mixin GTextureUtils { double w = 20, double h = 20, double rotation = 0, - String id, + String? id, }) async { _g.clear() .beginFill(color) @@ -88,7 +88,7 @@ mixin GTextureUtils { return tx; } - static Future _drawShape([String id]) async { + static Future _drawShape([String? id]) async { final tx = await _helperShape.createImageTexture( true, GTextureUtils.resolution, @@ -102,15 +102,15 @@ mixin GTextureUtils { static List getRectAtlasFromGTexture( GTexture base, int w, { - int h, + int? h, int padding = 0, double scale = 1, }) { h ??= w; /// create SubTextures from the main Texture. - var cols = base.sourceRect.width / w; - var rows = base.sourceRect.height / h; + var cols = base.sourceRect!.width/ w; + var rows = base.sourceRect!.height/ h; var total = cols * rows; var output = []; final _w = w.toDouble(); diff --git a/lib/src/widgets/graphics_clipper.dart b/lib/src/widgets/graphics_clipper.dart index 3b62592..a70438d 100644 --- a/lib/src/widgets/graphics_clipper.dart +++ b/lib/src/widgets/graphics_clipper.dart @@ -40,7 +40,7 @@ abstract class GraphicsClipper extends CustomClipper { final m = Pool.getMatrix(); m.setTransform( x, y, pivotX, pivotY, scaleX, scaleY, skewX, skewY, rotation); - final result = p.transform(m.toNative().storage); + final result = p.transform(m.toNative()!.storage); Pool.putMatrix(m); return result; } diff --git a/lib/src/widgets/graphx_widget.dart b/lib/src/widgets/graphx_widget.dart index e2797eb..9b68d43 100644 --- a/lib/src/widgets/graphx_widget.dart +++ b/lib/src/widgets/graphx_widget.dart @@ -5,9 +5,9 @@ import '../../graphx.dart'; import '../core/core.dart'; class SceneBuilderWidget extends StatefulWidget { - final Widget child; + final Widget? child; - final SceneController Function() builder; + final SceneController Function()? builder; /// Rendering caching flag. /// See [CustomPaint.willChange] @@ -22,7 +22,7 @@ class SceneBuilderWidget extends StatefulWidget { final HitTestBehavior pointerBehaviour; const SceneBuilderWidget({ - Key key, + Key? key, this.builder, this.child, this.painterIsComplex = true, @@ -35,18 +35,20 @@ class SceneBuilderWidget extends StatefulWidget { } class _SceneBuilderWidgetState extends State { - SceneController _controller; + SceneController? _controller; @override void initState() { super.initState(); - _controller = widget.builder(); - _controller.resolveWindowBounds = _getRenderObjectWindowBounds; - _controller.$init(); + _controller = widget.builder!(); + + _controller!.resolveWindowBounds = _getRenderObjectWindowBounds; + _controller!.$init(); } - GRect _getRenderObjectWindowBounds() { + GRect? _getRenderObjectWindowBounds() { if (!mounted) return null; + trace(context); return ContextUtils.getRenderObjectBounds(context); } @@ -59,7 +61,7 @@ class _SceneBuilderWidgetState extends State { @override void reassemble() { super.reassemble(); - _controller.reassembleWidget(); + _controller!.reassembleWidget(); } // @override @@ -71,17 +73,17 @@ class _SceneBuilderWidgetState extends State { @override Widget build(BuildContext context) { Widget child = CustomPaint( - painter: _controller.buildBackPainter(), - foregroundPainter: _controller.buildFrontPainter(), + painter: _controller!.buildBackPainter(), + foregroundPainter: _controller!.buildFrontPainter(), isComplex: widget.painterIsComplex, - willChange: _controller.config.painterMightChange(), + willChange: _controller!.config.painterMightChange(), child: widget.child ?? Container(), ); - var converter = _controller.$inputConverter; - if (_controller.config.usePointer) { + var converter = _controller!.$inputConverter; + if (_controller!.config.usePointer ?? false) { child = MouseRegion( - onEnter: converter.pointerEnter, + onEnter: converter!.pointerEnter, onExit: converter.pointerExit, onHover: converter.pointerHover, cursor: MouseCursor.defer, @@ -97,12 +99,12 @@ class _SceneBuilderWidgetState extends State { ), ); } - if (_controller.config.useKeyboard) { + if (_controller!.config.useKeyboard ?? false) { child = RawKeyboardListener( - onKey: converter.handleKey, + onKey: converter!.handleKey, autofocus: true, includeSemantics: false, - focusNode: converter.keyboard.focusNode, + focusNode: converter.keyboard!.focusNode, child: child, ); } diff --git a/lib/src/widgets/mps_widget.dart b/lib/src/widgets/mps_widget.dart index a7ff7bf..7c6abee 100644 --- a/lib/src/widgets/mps_widget.dart +++ b/lib/src/widgets/mps_widget.dart @@ -5,7 +5,7 @@ import '../../graphx.dart'; typedef MPSFunctionBuilder = Widget Function( BuildContext context, MPSEvent event, - Widget child, + Widget? child, ); /// [MPSBuilder] allows you to subscribe to multiple MinPubSub topics. @@ -18,16 +18,16 @@ typedef MPSFunctionBuilder = Widget Function( /// or 1 parameter[T] `ems.emit1(topic, value)`. Data is captured and sent as /// 2nd parameter ([MPSEvent] event object) in the [build] function. class MPSBuilder extends StatefulWidget { - final Widget child; + final Widget? child; final MPS mps; final MPSFunctionBuilder builder; final List topics; const MPSBuilder({ - Key key, - @required this.builder, - @required this.topics, - @required this.mps, + Key? key, + required this.builder, + required this.topics, + required this.mps, this.child, }) : super(key: key); @@ -79,7 +79,7 @@ class _MPSBuilderState extends State> { /// Model object passed as 2nd argument in [MPSBuilder.builder]. class MPSEvent { final String type; - final T data; + final T? data; factory MPSEvent.empty() => const MPSEvent(''); diff --git a/pubspec.lock b/pubspec.lock index 20d2c0b..9d3f47d 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -7,63 +7,49 @@ packages: name: async url: "https://pub.dartlang.org" source: hosted - version: "2.5.0-nullsafety.3" + version: "2.5.0" boolean_selector: dependency: transitive description: name: boolean_selector url: "https://pub.dartlang.org" source: hosted - version: "2.1.0-nullsafety.3" + version: "2.1.0" characters: dependency: transitive description: name: characters url: "https://pub.dartlang.org" source: hosted - version: "1.1.0-nullsafety.5" + version: "1.1.0" charcode: dependency: transitive description: name: charcode url: "https://pub.dartlang.org" source: hosted - version: "1.2.0-nullsafety.3" + version: "1.2.0" clock: dependency: transitive description: name: clock url: "https://pub.dartlang.org" source: hosted - version: "1.1.0-nullsafety.3" + version: "1.1.0" collection: dependency: transitive description: name: collection url: "https://pub.dartlang.org" source: hosted - version: "1.15.0-nullsafety.5" - convert: - dependency: transitive - description: - name: convert - url: "https://pub.dartlang.org" - source: hosted - version: "2.1.1" - effective_dart: - dependency: "direct dev" - description: - name: effective_dart - url: "https://pub.dartlang.org" - source: hosted - version: "1.3.0" + version: "1.15.0" fake_async: dependency: transitive description: name: fake_async url: "https://pub.dartlang.org" source: hosted - version: "1.2.0-nullsafety.3" + version: "1.2.0" flutter: dependency: "direct main" description: flutter @@ -80,49 +66,49 @@ packages: name: http url: "https://pub.dartlang.org" source: hosted - version: "0.12.2" + version: "0.13.0" http_parser: dependency: transitive description: name: http_parser url: "https://pub.dartlang.org" source: hosted - version: "3.1.4" + version: "4.0.0" matcher: dependency: transitive description: name: matcher url: "https://pub.dartlang.org" source: hosted - version: "0.12.10-nullsafety.3" + version: "0.12.10" meta: dependency: transitive description: name: meta url: "https://pub.dartlang.org" source: hosted - version: "1.3.0-nullsafety.6" + version: "1.3.0" path: dependency: transitive description: name: path url: "https://pub.dartlang.org" source: hosted - version: "1.8.0-nullsafety.3" + version: "1.8.0" pedantic: - dependency: "direct dev" + dependency: transitive description: name: pedantic url: "https://pub.dartlang.org" source: hosted - version: "1.9.2" + version: "1.11.0" petitparser: dependency: transitive description: name: petitparser url: "https://pub.dartlang.org" source: hosted - version: "3.1.0" + version: "4.0.2" sky_engine: dependency: transitive description: flutter @@ -134,62 +120,62 @@ packages: name: source_span url: "https://pub.dartlang.org" source: hosted - version: "1.8.0-nullsafety.4" + version: "1.8.0" stack_trace: dependency: transitive description: name: stack_trace url: "https://pub.dartlang.org" source: hosted - version: "1.10.0-nullsafety.6" + version: "1.10.0" stream_channel: dependency: transitive description: name: stream_channel url: "https://pub.dartlang.org" source: hosted - version: "2.1.0-nullsafety.3" + version: "2.1.0" string_scanner: dependency: transitive description: name: string_scanner url: "https://pub.dartlang.org" source: hosted - version: "1.1.0-nullsafety.3" + version: "1.1.0" term_glyph: dependency: transitive description: name: term_glyph url: "https://pub.dartlang.org" source: hosted - version: "1.2.0-nullsafety.3" + version: "1.2.0" test_api: dependency: transitive description: name: test_api url: "https://pub.dartlang.org" source: hosted - version: "0.2.19-nullsafety.6" + version: "0.2.19" typed_data: dependency: transitive description: name: typed_data url: "https://pub.dartlang.org" source: hosted - version: "1.3.0-nullsafety.5" + version: "1.3.0" vector_math: dependency: transitive description: name: vector_math url: "https://pub.dartlang.org" source: hosted - version: "2.1.0-nullsafety.5" + version: "2.1.0" xml: dependency: "direct main" description: name: xml url: "https://pub.dartlang.org" source: hosted - version: "4.5.1" + version: "5.0.2" sdks: - dart: ">=2.12.0-0.0 <3.0.0" + dart: ">=2.12.0 <3.0.0" diff --git a/pubspec.yaml b/pubspec.yaml index 59151e0..f0c8587 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -4,17 +4,15 @@ version: 0.9.9 homepage: https://github.com/roipeker/graphx environment: - sdk: ">=2.9.1 <3.0.0" + sdk: '>=2.12.0 <3.0.0' dependencies: flutter: sdk: flutter - xml: ^4.5.1 - http: ^0.12.2 + xml: ^5.0.0-nullsafety.1 + http: ^0.13.0-nullsafety.0 # flutter_svg: 0.19.0 dev_dependencies: - pedantic: ^1.9.2 flutter_test: sdk: flutter - effective_dart: ^1.3.0 From 0b79ae93383c2fcfc5fd235f9c3cd872c6db356b Mon Sep 17 00:00:00 2001 From: shariful2011 <67656229+IsmailAlamKhan@users.noreply.github.com> Date: Sat, 13 Mar 2021 14:29:48 +0600 Subject: [PATCH 02/22] fixed the graphx_widget for the null_check operator error --- lib/src/render/graphics.dart | 2 +- lib/src/widgets/graphx_widget.dart | 28 ++++++++++++++-------------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/lib/src/render/graphics.dart b/lib/src/render/graphics.dart index 6c28be3..1d3a5d6 100644 --- a/lib/src/render/graphics.dart +++ b/lib/src/render/graphics.dart @@ -588,7 +588,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { int sides, [ double rotation = 0, ]) { - final points = List.filled(sides, null); + final points = List.filled(sides, Offset(0, 0)); final rel = 2 * Math.PI / sides; for (var i = 1; i <= sides; ++i) { final px = x + radius * Math.cos(i * rel + rotation); diff --git a/lib/src/widgets/graphx_widget.dart b/lib/src/widgets/graphx_widget.dart index 9b68d43..dd5f4d0 100644 --- a/lib/src/widgets/graphx_widget.dart +++ b/lib/src/widgets/graphx_widget.dart @@ -7,7 +7,7 @@ import '../core/core.dart'; class SceneBuilderWidget extends StatefulWidget { final Widget? child; - final SceneController Function()? builder; + final SceneController Function() builder; /// Rendering caching flag. /// See [CustomPaint.willChange] @@ -23,7 +23,7 @@ class SceneBuilderWidget extends StatefulWidget { const SceneBuilderWidget({ Key? key, - this.builder, + required this.builder, this.child, this.painterIsComplex = true, this.mouseOpaque = true, @@ -35,15 +35,15 @@ class SceneBuilderWidget extends StatefulWidget { } class _SceneBuilderWidgetState extends State { - SceneController? _controller; + late SceneController _controller; @override void initState() { super.initState(); - _controller = widget.builder!(); + _controller = widget.builder(); - _controller!.resolveWindowBounds = _getRenderObjectWindowBounds; - _controller!.$init(); + _controller.resolveWindowBounds = _getRenderObjectWindowBounds; + _controller.$init(); } GRect? _getRenderObjectWindowBounds() { @@ -54,14 +54,14 @@ class _SceneBuilderWidgetState extends State { @override void dispose() { - _controller?.dispose(); + _controller.dispose(); super.dispose(); } @override void reassemble() { super.reassemble(); - _controller!.reassembleWidget(); + _controller.reassembleWidget(); } // @override @@ -73,15 +73,15 @@ class _SceneBuilderWidgetState extends State { @override Widget build(BuildContext context) { Widget child = CustomPaint( - painter: _controller!.buildBackPainter(), - foregroundPainter: _controller!.buildFrontPainter(), + painter: _controller.buildBackPainter(), + foregroundPainter: _controller.buildFrontPainter(), isComplex: widget.painterIsComplex, - willChange: _controller!.config.painterMightChange(), + willChange: _controller.config.painterMightChange(), child: widget.child ?? Container(), ); - var converter = _controller!.$inputConverter; - if (_controller!.config.usePointer ?? false) { + var converter = _controller.$inputConverter; + if (_controller.config.usePointer ?? false) { child = MouseRegion( onEnter: converter!.pointerEnter, onExit: converter.pointerExit, @@ -99,7 +99,7 @@ class _SceneBuilderWidgetState extends State { ), ); } - if (_controller!.config.useKeyboard ?? false) { + if (_controller.config.useKeyboard ?? false) { child = RawKeyboardListener( onKey: converter!.handleKey, autofocus: true, From b951329a18a5b48998144faeee48c092130f214c Mon Sep 17 00:00:00 2001 From: shariful2011 Date: Sat, 13 Mar 2021 15:44:30 +0600 Subject: [PATCH 03/22] another small fix for the graphx_widget converter --- lib/src/widgets/graphx_widget.dart | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/lib/src/widgets/graphx_widget.dart b/lib/src/widgets/graphx_widget.dart index dd5f4d0..0d77d6d 100644 --- a/lib/src/widgets/graphx_widget.dart +++ b/lib/src/widgets/graphx_widget.dart @@ -83,19 +83,19 @@ class _SceneBuilderWidgetState extends State { var converter = _controller.$inputConverter; if (_controller.config.usePointer ?? false) { child = MouseRegion( - onEnter: converter!.pointerEnter, - onExit: converter.pointerExit, - onHover: converter.pointerHover, + onEnter: converter?.pointerEnter, + onExit: converter?.pointerExit, + onHover: converter?.pointerHover, cursor: MouseCursor.defer, opaque: widget.mouseOpaque, child: Listener( child: child, behavior: widget.pointerBehaviour, - onPointerDown: converter.pointerDown, - onPointerUp: converter.pointerUp, - onPointerCancel: converter.pointerCancel, - onPointerMove: converter.pointerMove, - onPointerSignal: converter.pointerSignal, + onPointerDown: converter?.pointerDown, + onPointerUp: converter?.pointerUp, + onPointerCancel: converter?.pointerCancel, + onPointerMove: converter?.pointerMove, + onPointerSignal: converter?.pointerSignal, ), ); } @@ -104,7 +104,7 @@ class _SceneBuilderWidgetState extends State { onKey: converter!.handleKey, autofocus: true, includeSemantics: false, - focusNode: converter.keyboard!.focusNode, + focusNode: converter.keyboard?.focusNode ?? FocusNode(), child: child, ); } From b512710970a335f75c2e689dd8c5805f53a20506 Mon Sep 17 00:00:00 2001 From: Ismail Alam Khan Date: Sun, 14 Mar 2021 22:00:17 +0600 Subject: [PATCH 04/22] removed the trace when calling ContextUtils.getRenderObjectBounds --- lib/src/utils/context_utils.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/src/utils/context_utils.dart b/lib/src/utils/context_utils.dart index 55b2a93..ee83862 100644 --- a/lib/src/utils/context_utils.dart +++ b/lib/src/utils/context_utils.dart @@ -5,7 +5,6 @@ import '../../graphx.dart'; abstract class ContextUtils { /// todo: validate RenderObject Type. static GRect? getRenderObjectBounds(BuildContext context) { - trace(context); final box = context.findRenderObject() as RenderBox; return GRect.fromNative(box.localToGlobal(Offset.zero) & box.size); } From 14f393c891b7132faf568c72fbc43b29a871ab72 Mon Sep 17 00:00:00 2001 From: Ismail Alam Khan Date: Tue, 16 Mar 2021 03:24:13 +0600 Subject: [PATCH 05/22] Fix for the GText conflict --- lib/src/display/text.dart | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/src/display/text.dart b/lib/src/display/text.dart index b2cf8c5..36bf55c 100644 --- a/lib/src/display/text.dart +++ b/lib/src/display/text.dart @@ -302,6 +302,8 @@ class GText extends GDisplayObject { List? fontFeatures, ui.TextAlign textAlign = ui.TextAlign.left, ui.TextDirection direction = ui.TextDirection.ltr, + String? ellipsis, + int? maxLines, }) { if (w == double.infinity && textAlign != ui.TextAlign.left) { throw "[StaticText] To use $textAlign you need to specify the width"; @@ -332,6 +334,8 @@ class GText extends GDisplayObject { width: w, textStyle: style, paragraphStyle: ui.ParagraphStyle( + maxLines: maxLines, + ellipsis: ellipsis, textAlign: textAlign, textDirection: direction, ), From 0f7662d0cb2f13b14b9322624f5c613c4be3258a Mon Sep 17 00:00:00 2001 From: Ismail Alam Khan Date: Tue, 16 Mar 2021 03:40:24 +0600 Subject: [PATCH 06/22] Another fix for GText confilct --- lib/src/display/text.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/src/display/text.dart b/lib/src/display/text.dart index 36bf55c..0b3bf2c 100644 --- a/lib/src/display/text.dart +++ b/lib/src/display/text.dart @@ -298,12 +298,12 @@ class GText extends GDisplayObject { ui.Locale? locale, ui.Paint? background, ui.Paint? foreground, + String? ellipsis, + int? maxLines, List? shadows, List? fontFeatures, ui.TextAlign textAlign = ui.TextAlign.left, ui.TextDirection direction = ui.TextDirection.ltr, - String? ellipsis, - int? maxLines, }) { if (w == double.infinity && textAlign != ui.TextAlign.left) { throw "[StaticText] To use $textAlign you need to specify the width"; From 6550a9e57d3f187842b2a761d846b1cdf0c56f40 Mon Sep 17 00:00:00 2001 From: Ismail Alam Khan Date: Tue, 16 Mar 2021 03:41:37 +0600 Subject: [PATCH 07/22] same as previous commit --- lib/src/display/text.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/src/display/text.dart b/lib/src/display/text.dart index 0b3bf2c..2fba00b 100644 --- a/lib/src/display/text.dart +++ b/lib/src/display/text.dart @@ -298,8 +298,8 @@ class GText extends GDisplayObject { ui.Locale? locale, ui.Paint? background, ui.Paint? foreground, - String? ellipsis, int? maxLines, + String? ellipsis, List? shadows, List? fontFeatures, ui.TextAlign textAlign = ui.TextAlign.left, From e416dbc6fc501805a9fc04b9a992383f2f23d5cf Mon Sep 17 00:00:00 2001 From: Ismail Alam Khan Date: Tue, 16 Mar 2021 03:42:52 +0600 Subject: [PATCH 08/22] same as before --- lib/src/display/text.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/src/display/text.dart b/lib/src/display/text.dart index 2fba00b..0b3bf2c 100644 --- a/lib/src/display/text.dart +++ b/lib/src/display/text.dart @@ -298,8 +298,8 @@ class GText extends GDisplayObject { ui.Locale? locale, ui.Paint? background, ui.Paint? foreground, - int? maxLines, String? ellipsis, + int? maxLines, List? shadows, List? fontFeatures, ui.TextAlign textAlign = ui.TextAlign.left, From 778fe9b7026dec00a56b59b0e39a9540551ab6ad Mon Sep 17 00:00:00 2001 From: Ismail Alam Khan Date: Tue, 16 Mar 2021 13:36:34 +0600 Subject: [PATCH 09/22] added the gtween addition --- lib/src/tween/src/gtween.dart | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/src/tween/src/gtween.dart b/lib/src/tween/src/gtween.dart index b6d4f1d..c84dccc 100644 --- a/lib/src/tween/src/gtween.dart +++ b/lib/src/tween/src/gtween.dart @@ -520,16 +520,16 @@ class GTween { } } - static bool isTweening(Object target){ + static bool isTweening(Object target) { var t = _first; while (t != null) { var next = t._next; if (t.target == target || t._animatableTarget == target) { - return true ; + return true; } t = next; } - return false ; + return false; } /// Removes a Tween based on the the target object. From 45292fcc22453e3fa8641c1b217d700535b87202 Mon Sep 17 00:00:00 2001 From: Ismail Alam Khan Date: Wed, 17 Mar 2021 01:34:03 +0600 Subject: [PATCH 10/22] fixed the duplicate prop on text --- lib/src/display/text.dart | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/src/display/text.dart b/lib/src/display/text.dart index 6b62448..0b3bf2c 100644 --- a/lib/src/display/text.dart +++ b/lib/src/display/text.dart @@ -338,8 +338,6 @@ class GText extends GDisplayObject { ellipsis: ellipsis, textAlign: textAlign, textDirection: direction, - maxLines: maxLines, - ellipsis: ellipsis, ), ); doc?.addChild(tf); From c75233b86991e088050559692f5f0aefec99de6e Mon Sep 17 00:00:00 2001 From: Ismail Alam Khan Date: Tue, 23 Mar 2021 03:15:18 +0600 Subject: [PATCH 11/22] migrated the examples to null-safety --- ...resso_roast_vintage_2.png => espresso.png} | Bin .../lib/demos/altitude_indicator/scene.dart | 48 ++++----- .../demos/ball_line_collision/scene/ball.dart | 14 +-- .../ball_line_collision/scene/scene.dart | 14 ++- example/lib/demos/bookmark_button/scene.dart | 30 +++--- .../lib/demos/breakout/scene/game_scene.dart | 46 ++++----- example/lib/demos/breakout/scene/hud.dart | 50 ++++----- example/lib/demos/breakout/scene/objects.dart | 12 +-- example/lib/demos/card_rotation/scene.dart | 16 +-- .../lib/demos/chart_bezier/bezier_points.dart | 37 ++++--- .../chart_bezier/curved_graph_scene.dart | 32 +++--- .../lib/demos/chart_mountain/chart_data.dart | 6 +- .../chart_mountain/scene/chart_graph.dart | 24 ++--- .../chart_mountain/scene/chart_scene.dart | 10 +- .../chart_mountain/scene/chart_title.dart | 8 +- .../lib/demos/chart_mountain/scene/utils.dart | 2 +- .../demos/color_picker/picker_container.dart | 2 +- .../demos/color_picker/scene/hue_scene.dart | 46 ++++----- .../demos/color_picker/scene/value_scene.dart | 33 +++--- example/lib/demos/color_picker/utils.dart | 4 +- .../scene/bubble_preloader.dart | 19 ++-- .../demos/colorful_loader/scene/scene.dart | 8 +- example/lib/demos/dialer/dialer_scene.dart | 8 +- example/lib/demos/dna_3d/scene.dart | 12 +-- .../drawing_pad/draw_pad_scene.dart | 18 ++-- .../drawing_pad_bezier/drawing_pad/pad.dart | 34 +++--- .../drawing_pad_bezier/drawing_pad/point.dart | 6 +- .../dripping_iv/scene/dripping_scene.dart | 31 +++--- example/lib/demos/elastic_band/scene.dart | 16 +-- .../expander_fab_menu/expander_fab_menu.dart | 42 ++++---- .../lib/demos/fb_reactions/fb_reactions.dart | 28 ++--- example/lib/demos/fb_reactions/model.dart | 4 +- .../demos/fb_reactions/scene/menu_item.dart | 30 +++--- .../demos/fb_reactions/scene/menu_scene.dart | 36 +++---- example/lib/demos/feeling_switch/scene.dart | 8 +- example/lib/demos/flower_gradient/scene.dart | 4 +- .../lib/demos/gauge_meter/gauge_scene.dart | 22 ++-- example/lib/demos/globe_3d/scene.dart | 11 +- .../demos/glowing_circle/glowing_scene.dart | 8 +- example/lib/demos/heart_reaction/scene.dart | 11 +- example/lib/demos/isma_chart/data.dart | 4 +- .../demos/isma_chart/scene/chart_cell.dart | 9 +- .../demos/isma_chart/scene/chart_scene.dart | 22 ++-- .../demos/isma_chart/scene/chart_sprite.dart | 22 ++-- .../demos/isma_chart/scene/dot_button.dart | 11 +- example/lib/demos/jelly_thing/scene.dart | 39 ++++--- example/lib/demos/lined_button/scene.dart | 46 ++++----- example/lib/demos/lungs/scene.dart | 7 +- example/lib/demos/mouse_repulsion/scene.dart | 18 ++-- example/lib/demos/murat_coffee/scene.dart | 12 +-- .../demos/nico_loading_indicator/scene.dart | 16 +-- .../demos/nokia_snake/game_page_widget.dart | 2 +- example/lib/demos/nokia_snake/game_scene.dart | 22 ++-- .../nokia_snake/mobile_button_widget.dart | 8 +- .../lib/demos/nokia_snake/nokia_snake.dart | 4 +- example/lib/demos/page_indicator/dot.dart | 34 +++--- example/lib/demos/page_indicator/scene.dart | 24 ++--- .../lib/demos/path_chart_stress/scene.dart | 14 +-- example/lib/demos/pie_chart/scene.dart | 20 ++-- example/lib/demos/pizza_box/scene.dart | 15 ++- example/lib/demos/raster_draw/scene.dart | 20 ++-- .../demos/rating_star/scene/rating_scene.dart | 14 +-- example/lib/demos/rating_star/scene/star.dart | 40 ++++---- .../run_hero_canvas/scene/hero_scene.dart | 35 ++++--- .../simple_interactions_scene.dart | 16 +-- .../simple_interactions/ui/my_button.dart | 16 ++- .../demos/simple_radial_menu/circ_menu.dart | 18 ++-- .../simple_shape/simple_shapes_scene.dart | 2 +- .../lib/demos/simple_toast/simple_toast.dart | 8 +- example/lib/demos/simple_toast/toast.dart | 32 +++--- .../lib/demos/simple_tween/simple_tween.dart | 2 +- .../simple_tween/simple_tween_scene.dart | 34 +++--- .../sorting_button/scene/root_scene.dart | 11 +- .../scene/sorting_button_scene.dart | 86 ++++++++-------- .../spiral_loader/spiral_loader_scene.dart | 12 +-- .../demos/splash_intro/scene/logo_drawer.dart | 14 ++- .../splash_intro/scene/splash_scene.dart | 42 ++++---- .../demos/submit_button/scene/my_button.dart | 24 ++--- .../lib/demos/submit_button/scene/scene.dart | 2 +- example/lib/demos/svg_icons/test_icons.dart | 2 +- .../lib/demos/svg_icons/test_svg_scene.dart | 27 +++-- example/lib/demos/trigrid/scene/scene.dart | 46 ++++----- example/lib/demos/trigrid/scene/tri_grid.dart | 24 ++--- .../demos/universo_flutter_intro/scene.dart | 38 +++---- example/lib/demos/xmas/xmas.dart | 4 +- example/lib/demos/xmas/xmas_scene.dart | 20 ++-- example/lib/main.dart | 9 ++ example/lib/utils/base_scene.dart | 2 +- example/lib/utils/demo_scene_widget.dart | 12 +-- example/lib/utils/svg_utils.dart | 86 ++++++++-------- example/pubspec.yaml | 3 +- lib/src/render/graphics.dart | 12 +-- lib/src/tween/src/wraps/common_wraps.dart | 2 +- lib/src/utils/svg_utils.dart | 97 +++++++++--------- pubspec.lock | 22 ++++ pubspec.yaml | 4 +- 96 files changed, 998 insertions(+), 979 deletions(-) rename example/assets/murat_coffee/{espresso_roast_vintage_2.png => espresso.png} (100%) diff --git a/example/assets/murat_coffee/espresso_roast_vintage_2.png b/example/assets/murat_coffee/espresso.png similarity index 100% rename from example/assets/murat_coffee/espresso_roast_vintage_2.png rename to example/assets/murat_coffee/espresso.png diff --git a/example/lib/demos/altitude_indicator/scene.dart b/example/lib/demos/altitude_indicator/scene.dart index 8f8f0e4..e930567 100644 --- a/example/lib/demos/altitude_indicator/scene.dart +++ b/example/lib/demos/altitude_indicator/scene.dart @@ -16,17 +16,17 @@ class AltitudIndicatorScene extends GSprite { /// inner circle. GSprite rotatorCircle = GSprite(); - GSprite movable; + GSprite? movable; double innerCircSeparation = 50.0; double outlineThickness1 = 18.0; double outlineThickness2 = 10.0; - double meterSize; + late double meterSize; final redColor = const Color(0xffDA5537); double valueMeterGap = 34.0; - double innerCircleSize; + late double innerCircleSize; - double get minStageSize => Math.min(stage.stageWidth, stage.stageHeight); + double get minStageSize => Math.min(stage!.stageWidth, stage!.stageHeight); @override void addedToStage() { @@ -43,12 +43,14 @@ class AltitudIndicatorScene extends GSprite { .endFill(); addChild(mainMask); mainContainer.mask = mainMask; + /// center pivot in the current bounding box of scene. alignPivot(); - stage.onResized.add(() { + stage!.onResized.add(() { /// position the scene in the middle of screen. - setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); + /// scale % accordingly. scale = minStageSize / meterSize; }); @@ -85,10 +87,10 @@ class AltitudIndicatorScene extends GSprite { createOutsideLines(); /// create some movement for the airplane! - stage.onEnterFrame.add(onEnterFrame); + stage!.onEnterFrame.add(onEnterFrame); } - bool isPressed(LogicalKeyboardKey key) => stage.keyboard.isPressed(key); + bool isPressed(LogicalKeyboardKey key) => stage!.keyboard!.isPressed(key); int getDirY() { if (isPressed(LogicalKeyboardKey.arrowDown)) { @@ -113,9 +115,9 @@ class AltitudIndicatorScene extends GSprite { var dirX = getDirX(); if (dirY != 0) { - movable.y += 1.2 * dirY; + movable!.y += 1.2 * dirY; } else { - movable.y += (-movable.y) / 20; + movable!.y += (-movable!.y) / 20; } if (dirX != 0) { @@ -126,16 +128,16 @@ class AltitudIndicatorScene extends GSprite { } var maxRangeY = valueMeterGap * 2; - if (movable.y > maxRangeY) { - movable.y = maxRangeY; - } else if (movable.y < -maxRangeY) { - movable.y = -maxRangeY; + if (movable!.y > maxRangeY) { + movable!.y = maxRangeY; + } else if (movable!.y < -maxRangeY) { + movable!.y = -maxRangeY; } // rotatorCircle.rotation += .01; } - GSprite drawRotator() { + GSprite? drawRotator() { /// background first. movable = GSprite(); @@ -150,9 +152,9 @@ class AltitudIndicatorScene extends GSprite { ground.alignPivot(Alignment.topCenter); line.alignPivot(Alignment.center); - movable.addChild(sky); - movable.addChild(ground); - movable.addChild(line); + movable!.addChild(sky); + movable!.addChild(ground); + movable!.addChild(line); /// another option to draw background. // var rotatorBackground = GShape(); @@ -173,12 +175,12 @@ class AltitudIndicatorScene extends GSprite { // movable.addChild(rotatorBackground); var elements = buildRotatorElements(); - movable.addChild(elements); - rotatorCircle.addChild(movable); + movable!.addChild(elements); + rotatorCircle.addChild(movable!); /// the red arrow should always stay in the same position... /// re-parent the element to the rotator circle. - var arrow = elements.getChildByName('arrow'); + var arrow = elements.getChildByName('arrow')!; rotatorCircle.addChild(arrow); return movable; } @@ -329,7 +331,7 @@ class AltitudIndicatorScene extends GSprite { GShape _buildLine({ double thickness = 3.0, - double rotationDegrees, + required double rotationDegrees, }) { var line = GShape(); line.graphics.lineStyle(thickness, kColorWhite); @@ -337,7 +339,7 @@ class AltitudIndicatorScene extends GSprite { line.graphics.lineTo((innerCircleSize + innerCircSeparation) / 2, 0); line.pivotX = line.width; line.rotation = deg2rad(rotationDegrees); - linesContainer?.addChild(line); + linesContainer.addChild(line); return line; } diff --git a/example/lib/demos/ball_line_collision/scene/ball.dart b/example/lib/demos/ball_line_collision/scene/ball.dart index d111020..cb091c3 100644 --- a/example/lib/demos/ball_line_collision/scene/ball.dart +++ b/example/lib/demos/ball_line_collision/scene/ball.dart @@ -3,20 +3,20 @@ import 'package:graphx/graphx.dart'; class Ball extends GShape { double radius, vx, vy; - Color color; + Color? color; Ball({ - double x, - double y, - this.radius, - this.vx, - this.vy, + double? x, + double? y, + required this.radius, + required this.vx, + required this.vy, this.color, }) { this.x = x; this.y = y; graphics - .beginFill(color.withOpacity(.8)) + .beginFill(color!.withOpacity(.8)) .lineStyle(6, kColorBlack) .drawCircle(0, 0, radius) .endFill() diff --git a/example/lib/demos/ball_line_collision/scene/scene.dart b/example/lib/demos/ball_line_collision/scene/scene.dart index 619bcf4..a7e4f4c 100644 --- a/example/lib/demos/ball_line_collision/scene/scene.dart +++ b/example/lib/demos/ball_line_collision/scene/scene.dart @@ -4,17 +4,15 @@ /// /// web demo: https://roi-graphx-balls-collision.surge.sh/#/ - import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; import 'ball.dart'; class CollisionScene extends GSprite { + double get sw => stage!.stageWidth; - double get sw => stage.stageWidth; - - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; /// lazy with the types :P var lines = []; @@ -37,12 +35,12 @@ class CollisionScene extends GSprite { addChild(ball); balls.add(ball); }); - stage.onMouseDown.add(_onMouseDown); + stage!.onMouseDown.add(_onMouseDown); } void _onMouseDown(input) { - stage.onMouseUp.addOnce((input) => stage.onMouseMove.removeAll()); - stage.onMouseMove.add((input) => points.add([mouseX, mouseY, 0.0])); + stage!.onMouseUp.addOnce((input) => stage!.onMouseMove.removeAll()); + stage!.onMouseMove.add((input) => points.add([mouseX, mouseY, 0.0])); points = >[ [mouseX, mouseY, 0.0] ]; @@ -133,4 +131,4 @@ class CollisionScene extends GSprite { } } } -} \ No newline at end of file +} diff --git a/example/lib/demos/bookmark_button/scene.dart b/example/lib/demos/bookmark_button/scene.dart index 14e7945..a7998a3 100644 --- a/example/lib/demos/bookmark_button/scene.dart +++ b/example/lib/demos/bookmark_button/scene.dart @@ -7,15 +7,15 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class BookmarkButton extends GSprite { - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; - GShape bg; - GText label; + double get sh => stage!.stageHeight; + late GShape bg; + late GText label; bool isOn = false; - static List _gifFrames; - GMovieClip bookmarkIco; - GDropShadowFilter shadow; + static List? _gifFrames; + late GMovieClip bookmarkIco; + GDropShadowFilter? shadow; /// remove if not in debug? (hot reload). @override @@ -27,7 +27,7 @@ class BookmarkButton extends GSprite { @override void addedToStage() { - stage.color = Color(0xffEDEFFB); + stage!.color = Color(0xffEDEFFB); bg = addChild(GShape()) as GShape; shadow = GDropShadowFilter( 6, @@ -37,7 +37,7 @@ class BookmarkButton extends GSprite { Color(0xffA4AADB).withOpacity(.43), ); bg.$useSaveLayerBounds = false; - bg.filters = [shadow]; + bg.filters = [shadow!]; label = GText.build( text: 'Bookmark', color: Colors.black.withOpacity(.7), @@ -49,10 +49,10 @@ class BookmarkButton extends GSprite { label.setPosition(sw - label.textWidth - 32, (sh - label.textHeight) / 2); _loadTexture(); onMouseDown.add((e) { - shadow.tween(duration: .3, blurX: 2, blurY: 2, distance: 1); + shadow!.tween(duration: .3, blurX: 2, blurY: 2, distance: 1); bg.tween(duration: .3, scale: .95); - stage.onMouseUp.addOnce((e) { - shadow.tween(duration: .5, blurX: 6, blurY: 6, distance: 6); + stage!.onMouseUp.addOnce((e) { + shadow!.tween(duration: .5, blurX: 6, blurY: 6, distance: 6); bg.tween(duration: .5, scale: 1); }); }); @@ -69,14 +69,14 @@ class BookmarkButton extends GSprite { Future _loadTexture() async { if (_gifFrames == null) { - var atlas = await ResourceLoader.loadGif( + var atlas = await (ResourceLoader.loadGif( 'assets/bookmark_button/bookmark.gif', resolution: 2, - cacheId: 'bookmark'); + cacheId: 'bookmark') as Future); _gifFrames = atlas.textureFrames; } bookmarkIco = - addChild(GMovieClip(frames: _gifFrames, fps: 50)) as GMovieClip; + addChild(GMovieClip(frames: _gifFrames!, fps: 50)) as GMovieClip; bookmarkIco.repeatable = false; bookmarkIco.alignPivot(); bookmarkIco.setPosition(label.x / 2 + 2, sh / 2); diff --git a/example/lib/demos/breakout/scene/game_scene.dart b/example/lib/demos/breakout/scene/game_scene.dart index 35e632f..082fd98 100644 --- a/example/lib/demos/breakout/scene/game_scene.dart +++ b/example/lib/demos/breakout/scene/game_scene.dart @@ -9,7 +9,7 @@ class BreakoutAtari extends GSprite { static const double gameW = 160; static const double gameH = 192; - static BreakoutAtari instance; + static late BreakoutAtari instance; final bricks = []; @@ -26,22 +26,22 @@ class BreakoutAtari extends GSprite { double brickH = 12.0; final wallW = 4.0; - int cols, rows; - double totalBrickSep; + int cols = 0, rows = 0; + late double totalBrickSep; - Paddle paddle; - Ball ball; - GSprite bicksContainer; - HUD hud; + late Paddle paddle; + late Ball ball; + late GSprite bicksContainer; + late HUD hud; bool movingLeft = false; bool movingRight = false; bool _isGameOver = false; int brokenBricksCount = 0; - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; BreakoutAtari() { instance = this; @@ -122,18 +122,18 @@ class BreakoutAtari extends GSprite { _updatePause(); } }); - stage.onMouseDown.add((event) { + stage!.onMouseDown.add((event) { isDragging = true; stagePressX = mouseX; paddlePressX = paddle.x; - stage.onMouseUp.addOnce((event) { + stage!.onMouseUp.addOnce((event) { isDragging = false; }); }); // stage.color = Colors.black.value; // stage.showBoundsRect = true; - stage.maskBounds = true; - stage.keyboard.onUp.add((input) { + stage!.maskBounds = true; + stage!.keyboard!.onUp.add((input) { if (input.isKey(LogicalKeyboardKey.escape)) { isPaused = !isPaused; mps.emit1(GameEvents.action, isPaused); @@ -146,7 +146,7 @@ class BreakoutAtari extends GSprite { } }); - stage.keyboard.onDown.add((input) { + stage!.keyboard!.onDown.add((input) { if (input.arrowLeft || input.isKey(LogicalKeyboardKey.keyA)) { movingLeft = true; } else if (input.arrowRight || input.isKey(LogicalKeyboardKey.keyD)) { @@ -195,8 +195,8 @@ class BreakoutAtari extends GSprite { paddle.y = gameH - paddle.h - 10; alignPivot(); - stage.onResized.add(() { - var graphBounds = bounds; + stage!.onResized.add(() { + var graphBounds = bounds!; var r1 = sw / sh; var r2 = graphBounds.width / graphBounds.height; if (r1 < r2) { @@ -217,7 +217,7 @@ class BreakoutAtari extends GSprite { if (isDragging) { paddle.x = paddlePressX + (mouseX - stagePressX); } else { - var thrust = stage.keyboard.isShiftPressed ? 2.0 : 1.0; + var thrust = stage!.keyboard!.isShiftPressed ? 2.0 : 1.0; if (movingLeft) { paddle.vx = -paddle.speed; } else if (movingRight) { @@ -261,7 +261,7 @@ class BreakoutAtari extends GSprite { bricks.forEach((b) { if (!collides(b, ball)) return; removeBricks.add(b); - hud.showPoints(b.points, b.getBounds(this)); + hud.showPoints(b.points, b.getBounds(this)!); b.removeFromParent(); /// check speed @@ -295,8 +295,8 @@ class BreakoutAtari extends GSprite { } bool collides(GDisplayObject obj1, GDisplayObject obj2) { - var bounds1 = obj1.getBounds(this); - var bounds2 = obj2.getBounds(this); + var bounds1 = obj1.getBounds(this)!; + var bounds2 = obj2.getBounds(this)!; return bounds1.intersects(bounds2); } @@ -322,11 +322,11 @@ class BreakoutAtari extends GSprite { void _updatePause() { hud.showPause(isPaused); - final ticker = stage.scene.core.ticker; + final ticker = stage!.scene.core.ticker; if (isPaused) { - ticker.callNextFrame(ticker.pause); + ticker!.callNextFrame(ticker.pause); } else { - ticker.resume(); + ticker!.resume(); } } } diff --git a/example/lib/demos/breakout/scene/hud.dart b/example/lib/demos/breakout/scene/hud.dart index 389bfcc..b9149a0 100644 --- a/example/lib/demos/breakout/scene/hud.dart +++ b/example/lib/demos/breakout/scene/hud.dart @@ -7,7 +7,7 @@ import 'game_scene.dart'; class HUD extends GSprite { // ignore: non_constant_identifier_names - GText _score_tf, _balls_tf, _gameState_tf, _speedUp_tf; + GText? _score_tf, _balls_tf, _gameState_tf, _speedUp_tf; final w = BreakoutAtari.gameW; final h = BreakoutAtari.gameH; @@ -20,15 +20,15 @@ class HUD extends GSprite { var titleScore = _getText('SCORE', 4); titleScore.setPosition(textMargin, textMargin); _score_tf = _getText('0', 6); - _score_tf.setPosition(textMargin, 10); + _score_tf!.setPosition(textMargin, 10); var titleBall = _getText('BALL', 4); titleBall.alignPivot(Alignment.topRight); titleBall.setPosition(w - textMargin, textMargin); _balls_tf = _getText('3/3', 6); - _balls_tf.alignPivot(Alignment.topRight); - _balls_tf.setPosition(titleBall.x, 10); + _balls_tf!.alignPivot(Alignment.topRight); + _balls_tf!.setPosition(titleBall.x, 10); _gameState_tf = GText( text: 'GAME OVER', @@ -40,13 +40,13 @@ class HUD extends GSprite { ), paragraphStyle: ParagraphStyle(textAlign: TextAlign.center), ); - _gameState_tf.y = (h - _gameState_tf.textHeight) / 2; - addChild(_gameState_tf); + _gameState_tf!.y = (h - _gameState_tf!.textHeight) / 2; + addChild(_gameState_tf!); _speedUp_tf = _getText('SPEED UP!', 10); - _speedUp_tf.alignPivot(); - _speedUp_tf.setPosition(w / 2, h / 2); - _speedUp_tf.alpha = 0; + _speedUp_tf!.alignPivot(); + _speedUp_tf!.setPosition(w / 2, h / 2); + _speedUp_tf!.alpha = 0; setGameOver(false); } @@ -102,13 +102,13 @@ class HUD extends GSprite { void speedUp() { final offset = 10.0; GTween.killTweensOf(_speedUp_tf); - _speedUp_tf.y = h / 2; - _speedUp_tf.alpha = 0; - _speedUp_tf.tween(duration: .15, alpha: 1); - _speedUp_tf.tween(duration: 1.2, delay: .15, y: h / 2 - offset, alpha: 0); + _speedUp_tf!.y = h / 2; + _speedUp_tf!.alpha = 0; + _speedUp_tf!.tween(duration: .15, alpha: 1); + _speedUp_tf!.tween(duration: 1.2, delay: .15, y: h / 2 - offset, alpha: 0); } - GText _getText(String label, double size, [Shadow shadow]) { + GText _getText(String label, double size, [Shadow? shadow]) { var tf = GText( text: label, textStyle: TextStyle( @@ -124,32 +124,32 @@ class HUD extends GSprite { void showPause(bool isPaused) { if (isPaused) { - _gameState_tf.text = 'PAUSED'; - _gameState_tf.visible = true; + _gameState_tf!.text = 'PAUSED'; + _gameState_tf!.visible = true; } else { - _gameState_tf.visible = false; + _gameState_tf!.visible = false; } } void showWin() { - _gameState_tf.text = 'YOU WIN!'; - _gameState_tf.visible = true; + _gameState_tf!.text = 'YOU WIN!'; + _gameState_tf!.visible = true; } void setBalls(int numBalls, int maxBalls) { - _balls_tf.text = '$numBalls/$maxBalls'; - _balls_tf.alignPivot(Alignment.topRight); + _balls_tf!.text = '$numBalls/$maxBalls'; + _balls_tf!.alignPivot(Alignment.topRight); } void setScore(int points) { - _score_tf.text = '$points'; + _score_tf!.text = '$points'; } void setGameOver(bool flag) { - _gameState_tf.visible = false; + _gameState_tf!.visible = false; if (flag) { - _gameState_tf.text = 'GAME OVER'; - _gameState_tf.visible = true; + _gameState_tf!.text = 'GAME OVER'; + _gameState_tf!.visible = true; } } } diff --git a/example/lib/demos/breakout/scene/objects.dart b/example/lib/demos/breakout/scene/objects.dart index 3e9d43d..6b607f2 100644 --- a/example/lib/demos/breakout/scene/objects.dart +++ b/example/lib/demos/breakout/scene/objects.dart @@ -2,10 +2,10 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; abstract class GameObj extends GShape { - double w, h; - Color color; + double w = 0, h = 0; + Color? color; - void init(double w, double h, Color color) { + void init(double w, double h, Color? color) { this.w = w; this.h = h; this.color = color; @@ -28,7 +28,7 @@ class Ball extends GameObj { @override void _draw() { - graphics.beginFill(color).drawCircle(0, 0, w / 2).endFill(); + graphics.beginFill(color!).drawCircle(0, 0, w / 2).endFill(); } } @@ -38,7 +38,7 @@ class Paddle extends GameObj { @override void _draw() { - graphics.beginFill(color).drawRect(0, 0, w, h).endFill(); + graphics.beginFill(color!).drawRect(0, 0, w, h).endFill(); } } @@ -47,6 +47,6 @@ class Brick extends GameObj { @override void _draw() { - graphics.beginFill(color).drawRect(0, 0, w, h).endFill(); + graphics.beginFill(color!).drawRect(0, 0, w, h).endFill(); } } diff --git a/example/lib/demos/card_rotation/scene.dart b/example/lib/demos/card_rotation/scene.dart index 9b9cfa1..814a7ea 100644 --- a/example/lib/demos/card_rotation/scene.dart +++ b/example/lib/demos/card_rotation/scene.dart @@ -11,7 +11,7 @@ import 'package:graphx/graphx.dart'; class CardRotation3dScene extends GSprite { @override void addedToStage() { - stage.color = Color(0xffF8F6F4); + stage!.color = Color(0xffF8F6F4); initUi(); } @@ -103,7 +103,7 @@ Just 89.- THB''', 0x9E7878, 12.0, FontWeight.normal, 20 / 12); cardItemParent.mouseChildren = false; cardItemParent.useCursor = true; - stage.onEnterFrame.add((event) { + stage!.onEnterFrame.add((event) { var dx = cardItemParent.mouseX; var dy = cardItemParent.mouseY; var angle = Math.atan2(dy, dx); @@ -126,7 +126,7 @@ Just 89.- THB''', 0x9E7878, 12.0, FontWeight.normal, 20 / 12); ease: GEase.easeOutExpo, ); - stage.onMouseUp.addOnce((event) { + stage!.onMouseUp.addOnce((event) { cardItemParent.tween( duration: 1.2, scale: 1, @@ -144,13 +144,13 @@ Just 89.- THB''', 0x9E7878, 12.0, FontWeight.normal, 20 / 12); }); cardItemParent.alignPivot(); - stage.onResized.add(() { - cardItemParent.x = stage.stageWidth / 2; - cardItemParent.y = stage.stageHeight / 2; + stage!.onResized.add(() { + cardItemParent.x = stage!.stageWidth / 2; + cardItemParent.y = stage!.stageHeight / 2; }); - cardItemParent.x = stage.stageWidth / 2; - cardItemParent.y = stage.stageHeight / 2; + cardItemParent.x = stage!.stageWidth / 2; + cardItemParent.y = stage!.stageHeight / 2; // cardItemParent.rotationX = .2; } diff --git a/example/lib/demos/chart_bezier/bezier_points.dart b/example/lib/demos/chart_bezier/bezier_points.dart index f39a772..8092542 100644 --- a/example/lib/demos/chart_bezier/bezier_points.dart +++ b/example/lib/demos/chart_bezier/bezier_points.dart @@ -1,8 +1,8 @@ import 'package:graphx/graphx.dart'; class _BezierControlPoint { - GPoint prev; - GPoint next; + GPoint? prev; + GPoint? next; _BezierControlPoint([this.prev, this.next]) { prev ??= GPoint(); @@ -16,14 +16,13 @@ void bezierCurveThrough( Graphics g, List points, [ double tension = .25, - List output, + List? output, ]) { - tension ??= .25; var len = points.length; if (len == 2) { output?.addAll([points[0], points[1]]); - g?.moveTo(points[0].x, points[0].y); - g?.lineTo(points[1].x, points[1].y); + g.moveTo(points[0].x, points[0].y); + g.lineTo(points[1].x, points[1].y); return; } @@ -50,41 +49,41 @@ void bezierCurveThrough( var cnx = pi.x + dx * dn * tension; var cny = pi.y + dy * dn * tension; - cpoints[i].prev.setTo(cpx, cpy); - cpoints[i].next.setTo(cnx, cny); + cpoints[i].prev!.setTo(cpx, cpy); + cpoints[i].next!.setTo(cnx, cny); } /// end points cpoints[0].next = GPoint( - (points[0].x + cpoints[1].prev.x) / 2, - (points[0].y + cpoints[1].prev.y) / 2, + (points[0].x + cpoints[1].prev!.x) / 2, + (points[0].y + cpoints[1].prev!.y) / 2, ); cpoints[len - 1].prev = GPoint( - (points[len - 1].x + cpoints[len - 2].next.x) / 2, - (points[len - 1].y + cpoints[len - 2].next.y) / 2, + (points[len - 1].x + cpoints[len - 2].next!.x) / 2, + (points[len - 1].y + cpoints[len - 2].next!.y) / 2, ); /// draw? - g?.moveTo(points[0].x, points[0].y); + g.moveTo(points[0].x, points[0].y); output?.add(points[0]); for (var i = 1; i < len; ++i) { var p = points[i]; var cp = cpoints[i]; var cpp = cpoints[i - 1]; - g?.cubicCurveTo(cpp.next.x, cpp.next.y, cp.prev.x, cp.prev.y, p.x, p.y); + g.cubicCurveTo(cpp.next!.x, cpp.next!.y, cp.prev!.x, cp.prev!.y, p.x, p.y); output?.addAll([cpp.next, cp.prev, p]); } cpoints.clear(); } -void bezierCurveThroughDraw(Graphics g, List points) { - g.moveTo(points[0].x, points[0].y); +void bezierCurveThroughDraw(Graphics g, List points) { + g.moveTo(points[0]!.x, points[0]!.y); final len = points.length; for (var i = 1; i < len; i += 3) { - final p0 = points[i]; - final p1 = points[i + 1]; - final p2 = points[i + 2]; + final p0 = points[i]!; + final p1 = points[i + 1]!; + final p2 = points[i + 2]!; g.cubicCurveTo(p0.x, p0.y, p1.x, p1.y, p2.x, p2.y); } } diff --git a/example/lib/demos/chart_bezier/curved_graph_scene.dart b/example/lib/demos/chart_bezier/curved_graph_scene.dart index 52cf9c5..6164415 100644 --- a/example/lib/demos/chart_bezier/curved_graph_scene.dart +++ b/example/lib/demos/chart_bezier/curved_graph_scene.dart @@ -5,17 +5,17 @@ import 'bezier_points.dart'; class CurvedGraphScene extends GSprite { List graphPositions = [.2, .4, .9, .3, .6, .7, .9, .3]; - List bezierPoints; + List? bezierPoints; - double get graphW => stage.stageWidth; - double get graphH => stage.stageHeight; + double get graphW => stage!.stageWidth; + double get graphH => stage!.stageHeight; - GSprite graph, dots; - GShape lines, filled; - List coords; + late GSprite graph, dots; + late GShape lines, filled; + late List coords; - GTweenableList myTweenList; - List lastPercents; + late GTweenableList myTweenList; + late List lastPercents; GShape drawCircle(double px, double py) { var sh = GShape(); @@ -29,7 +29,7 @@ class CurvedGraphScene extends GSprite { void addedToStage() { bezierPoints = []; // stage.color = Colors.black; - stage.maskBounds=true; + stage!.maskBounds = true; graph = GSprite(); dots = GSprite(); @@ -54,7 +54,7 @@ class CurvedGraphScene extends GSprite { lastPercents = List.from(graphPositions); myTweenList = lastPercents.twn; randomNumbers(); - stage.onMouseClick.add((e) => randomNumbers()); + stage!.onMouseClick.add((e) => randomNumbers()); } void randomNumbers() { @@ -84,16 +84,16 @@ class CurvedGraphScene extends GSprite { newValues, duration: 2, onUpdate: () { - final values = myTweenList.value as List; + final values = myTweenList.value as List; renderPositions(values); }, ease: GEase.fastLinearToSlowEaseIn, ); } - void renderPositions(List percents) { + void renderPositions(List percents) { for (var i = 0; i < percents.length; ++i) { - coords[i].y = percents[i] * graphH; + coords[i].y = percents[i]! * graphH; dots.getChildAt(i).y = coords[i].y; } lines.graphics.clear(); @@ -106,7 +106,7 @@ class CurvedGraphScene extends GSprite { ], ratios: [.1, 1], ); - bezierPoints.clear(); + bezierPoints!.clear(); bezierCurveThrough(lines.graphics, coords, .25, bezierPoints); filled.graphics.clear(); @@ -120,11 +120,11 @@ class CurvedGraphScene extends GSprite { begin: Alignment.topCenter, end: Alignment.bottomCenter, ); - bezierCurveThroughDraw(filled.graphics, bezierPoints); + bezierCurveThroughDraw(filled.graphics, bezierPoints!); filled.graphics .lineTo(graphW, graphH) .lineTo(0, graphH) - .lineTo(bezierPoints[0].x, bezierPoints[0].y) + .lineTo(bezierPoints![0]!.x, bezierPoints![0]!.y) .endFill(); } } diff --git a/example/lib/demos/chart_mountain/chart_data.dart b/example/lib/demos/chart_mountain/chart_data.dart index 58eeacc..78e1458 100644 --- a/example/lib/demos/chart_mountain/chart_data.dart +++ b/example/lib/demos/chart_mountain/chart_data.dart @@ -11,8 +11,8 @@ const sampleGraphData = [ ]; class GraphModel { - final List data; - final Color color; - final String name; + final List? data; + final Color? color; + final String? name; const GraphModel({this.data, this.color, this.name}); } diff --git a/example/lib/demos/chart_mountain/scene/chart_graph.dart b/example/lib/demos/chart_mountain/scene/chart_graph.dart index c8ce3a0..8870636 100644 --- a/example/lib/demos/chart_mountain/scene/chart_graph.dart +++ b/example/lib/demos/chart_mountain/scene/chart_graph.dart @@ -4,9 +4,9 @@ import '../chart_data.dart'; import 'utils.dart'; class MyGraph extends GSprite { - GShape graph; - GSprite chartContainer, titlesContainer; - GShape background; + GShape? graph; + GSprite? chartContainer, titlesContainer; + late GShape background; double minValueY = 0, maxValueY = 160, stepY = 20; List xRange = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul']; @@ -14,12 +14,12 @@ class MyGraph extends GSprite { double graphW = 295; double graphH = 209; - double lineSepY, lineSepX; - int numLinesY, numLinesX; + double lineSepY = 0.0, lineSepX = 0.0; + int numLinesY = 0, numLinesX = 0; double minAlpha = .7; double maxAlpha = 1.0; - final List data; + final List? data; MyGraph({this.data}); @override @@ -28,7 +28,7 @@ class MyGraph extends GSprite { addChild(background); chartContainer = GSprite(); - addChild(chartContainer); + addChild(chartContainer!); numLinesY = ((minValueY + (maxValueY - minValueY)) ~/ stepY) + 1; numLinesX = xRange.length; @@ -70,18 +70,18 @@ class MyGraph extends GSprite { }); }); - chartContainer.addChild(graph); + chartContainer?.addChild(graph); drawChart(data, graph, 1); return graph; } - void drawChart(GraphModel data, GShape graph, [double percent = 1]) { + void drawChart(GraphModel data, GShape graph, [double? percent = 1]) { var g = graph.graphics; g.clear(); - g.beginFill(data.color); - var list = data.data; + g.beginFill(data.color!); + var list = data.data!; for (var i = 0; i < list.length; ++i) { - final valuePercent = list[i] / maxValueY * percent; + final valuePercent = list[i] / maxValueY * percent!; final relY = graphH - valuePercent * graphH; var px = i * lineSepX; if (i == 0) { diff --git a/example/lib/demos/chart_mountain/scene/chart_scene.dart b/example/lib/demos/chart_mountain/scene/chart_scene.dart index 671bae7..7269a44 100644 --- a/example/lib/demos/chart_mountain/scene/chart_scene.dart +++ b/example/lib/demos/chart_mountain/scene/chart_scene.dart @@ -6,16 +6,16 @@ import 'chart_graph.dart'; import 'chart_title.dart'; class SampleMountainChart extends GSprite { - MyGraph graph; - GraphTitle titles; + late MyGraph graph; + late GraphTitle titles; - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; @override void addedToStage() { - stage.showBoundsRect = true; + stage!.showBoundsRect = true; graph = MyGraph(data: sampleGraphData); graph.x = 40; graph.y = 20; diff --git a/example/lib/demos/chart_mountain/scene/chart_title.dart b/example/lib/demos/chart_mountain/scene/chart_title.dart index e573557..920fc94 100644 --- a/example/lib/demos/chart_mountain/scene/chart_title.dart +++ b/example/lib/demos/chart_mountain/scene/chart_title.dart @@ -4,19 +4,19 @@ import '../chart_data.dart'; import 'utils.dart'; class GraphTitle extends GSprite { - final List data; + final List? data; GraphTitle({this.data}); @override void addedToStage() { - for (var i = 0; i < data.length; ++i) { - final vo = data[i]; + for (var i = 0; i < data!.length; ++i) { + final vo = data![i]; var item = GSprite(); addChild(item); var quad = GShape(); item.addChild(quad); - quad.graphics.beginFill(vo.color).drawRect(0, 0, 7, 7).endFill(); + quad.graphics.beginFill(vo.color!).drawRect(0, 0, 7, 7).endFill(); quad.y = 3; var title = createLabel(vo.name); item.addChild(title); diff --git a/example/lib/demos/chart_mountain/scene/utils.dart b/example/lib/demos/chart_mountain/scene/utils.dart index be8f3e0..d6fc7a9 100644 --- a/example/lib/demos/chart_mountain/scene/utils.dart +++ b/example/lib/demos/chart_mountain/scene/utils.dart @@ -1,4 +1,4 @@ import 'package:graphx/graphx.dart'; -GText createLabel(String text) => +GText createLabel(String? text) => GText.build(text: text, fontSize: 10, color: kColorBlack); diff --git a/example/lib/demos/color_picker/picker_container.dart b/example/lib/demos/color_picker/picker_container.dart index af3b718..2cc1b90 100644 --- a/example/lib/demos/color_picker/picker_container.dart +++ b/example/lib/demos/color_picker/picker_container.dart @@ -27,7 +27,7 @@ class PickerContainer extends StatelessWidget { child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - ValueListenableBuilder( + ValueListenableBuilder( valueListenable: pickerNotifier, builder: (ctx, value, _) => Container( width: 40, diff --git a/example/lib/demos/color_picker/scene/hue_scene.dart b/example/lib/demos/color_picker/scene/hue_scene.dart index 2ffecc8..36a0a2b 100644 --- a/example/lib/demos/color_picker/scene/hue_scene.dart +++ b/example/lib/demos/color_picker/scene/hue_scene.dart @@ -4,13 +4,13 @@ import 'package:graphx/graphx.dart'; import '../utils.dart'; class HueScene extends GSprite { - GShape colorSelector; - GShape arrowSelector; - GShape lineSelector; - Color _selectedColor; + late GShape colorSelector; + late GShape arrowSelector; + GShape? lineSelector; + Color? _selectedColor; - double sw, sh; - ByteData colorsBytes; + double sw = 0.0, sh = 0.0; + ByteData? colorsBytes; HueScene() { // config(usePointer: true, autoUpdateAndRender: true); @@ -22,8 +22,8 @@ class HueScene extends GSprite { var hvsList = List.generate(numHues, (index) { return HSVColor.fromAHSV(1, index / numHues * 360, 1, 1).toColor(); }); - sw = stage.stageWidth; - sh = stage.stageHeight; + sw = stage!.stageWidth; + sh = stage!.stageHeight; colorSelector = GShape(); colorSelector.graphics @@ -40,9 +40,9 @@ class HueScene extends GSprite { arrowSelector = GShape(); lineSelector = GShape(); - lineSelector.graphics.beginFill(kColorWhite).drawRect(0, 0, sw, 10); - lineSelector.alignPivot(Alignment.center); - lineSelector.x = sw / 2; + lineSelector!.graphics.beginFill(kColorWhite).drawRect(0, 0, sw, 10); + lineSelector!.alignPivot(Alignment.center); + lineSelector!.x = sw / 2; /// create the arrow GShape first arrowSelector.graphics.beginFill(kColorBlack).drawPolygonFaces( @@ -67,24 +67,24 @@ class HueScene extends GSprite { addChild(colorSelector); addChild(arrowSelector); - addChild(lineSelector); - lineSelector.alpha = 0; + addChild(lineSelector!); + lineSelector!.alpha = 0; mouseChildren = false; - lineSelector.scaleX = 0; - stage.onMouseDown.add((input) { + lineSelector!.scaleX = 0; + stage!.onMouseDown.add((input) { // lineSelector.y = sh / 2; GTween.killTweensOf(lineSelector); - lineSelector.height = 8; - lineSelector.tween( + lineSelector!.height = 8; + lineSelector!.tween( duration: .8, height: 2, scaleX: 1, alpha: 1, ease: GEase.easeOutExpo, ); - stage.onMouseUp.addOnce((input) { - lineSelector.tween( + stage!.onMouseUp.addOnce((input) { + lineSelector!.tween( duration: .8, scaleX: 0, height: 0, @@ -92,7 +92,7 @@ class HueScene extends GSprite { }); _updatePosition(); }); - stage.onMouseMove.add(_onMouseMove); + stage!.onMouseMove.add(_onMouseMove); /// get the image bytes from capturing the GShape snapshot. /// so we can get the colors from the bytes List. @@ -109,13 +109,13 @@ class HueScene extends GSprite { } void _updatePosition() { - lineSelector.y = arrowSelector.y = mouseY.clamp(0.0, sh - 1); + lineSelector!.y = arrowSelector.y = mouseY.clamp(0.0, sh - 1); updateColor(); } void updateColor() { _selectedColor = getPixelColor( - colorsBytes, + colorsBytes!, sw.toInt(), sh.toInt(), 0, @@ -123,6 +123,6 @@ class HueScene extends GSprite { ); /// emit the event to update the UI. - pickerMPS.emit1(ColorPickerEmitter.changeHue, _selectedColor); + pickerMPS.emit1(ColorPickerEmitter.changeHue, _selectedColor); } } diff --git a/example/lib/demos/color_picker/scene/value_scene.dart b/example/lib/demos/color_picker/scene/value_scene.dart index 10e2394..35ad9b4 100644 --- a/example/lib/demos/color_picker/scene/value_scene.dart +++ b/example/lib/demos/color_picker/scene/value_scene.dart @@ -4,21 +4,21 @@ import 'package:graphx/graphx.dart'; import '../utils.dart'; class ValueScene extends GSprite { - GShape bgColor; - GShape bgBrightness; - GShape bgValue; - GSprite colorsContainer; - ByteData colorsBytes; - GShape selector; - Color _selectedColor; - double sw, sh; + late GShape bgColor; + late GShape bgBrightness; + late GShape bgValue; + late GSprite colorsContainer; + ByteData? colorsBytes; + late GShape selector; + Color? _selectedColor; + double sw = 0.0, sh = 0.0; ValueScene(); @override void addedToStage() { - sw = stage.stageWidth; - sh = stage.stageHeight; + sw = stage!.stageWidth; + sh = stage!.stageHeight; bgColor = GShape(); bgColor.graphics @@ -52,16 +52,16 @@ class ValueScene extends GSprite { addChild(selector); mouseChildren = false; - stage.onMouseDown.add((e) { + stage!.onMouseDown.add((e) { _updateColor(); selector.tween(duration: .4, scale: 1.5); GMouse.hide(); - stage.onMouseUp.addOnce((e) { + stage!.onMouseUp.addOnce((e) { GMouse.show(); selector.tween(duration: .3, scale: 1); }); }); - stage.onMouseMove.add(_handleMouseMove); + stage!.onMouseMove.add(_handleMouseMove); pickerMPS.on(ColorPickerEmitter.changeHue, handleChangeHue); } @@ -77,7 +77,8 @@ class ValueScene extends GSprite { updateColor(); } - void drawGradient(Graphics graphics, {Color color, bool isHorizontal}) { + void drawGradient(Graphics graphics, + {required Color color, required bool isHorizontal}) { var from = isHorizontal ? Alignment.centerLeft : Alignment.bottomCenter; var to = isHorizontal ? Alignment.centerRight : Alignment.topCenter; graphics @@ -109,7 +110,7 @@ class ValueScene extends GSprite { void updateColor() { if (colorsBytes == null) return; _selectedColor = getPixelColor( - colorsBytes, + colorsBytes!, sw.toInt(), sh.toInt(), selector.x.toInt(), @@ -117,7 +118,7 @@ class ValueScene extends GSprite { ); /// emit the event to update the UI. - pickerNotifier.value = _selectedColor; + pickerNotifier.value = _selectedColor!; // pickerMPS.emit1(ColorPickerEmitter.changeValue, _selectedColor); } } diff --git a/example/lib/demos/color_picker/utils.dart b/example/lib/demos/color_picker/utils.dart index 13e9bad..25b8814 100644 --- a/example/lib/demos/color_picker/utils.dart +++ b/example/lib/demos/color_picker/utils.dart @@ -31,9 +31,9 @@ Color getPixelColor( return Color.fromARGB(a, r, g, b); } -Future getImageBytes(GDisplayObject object) async { +Future getImageBytes(GDisplayObject object) async { var texture = await object.createImageTexture(true, 1); - var data = texture.root.toByteData(format: ImageByteFormat.rawRgba); + var data = texture.root!.toByteData(format: ImageByteFormat.rawRgba); // texture?.dispose(); // texture = null; return data; diff --git a/example/lib/demos/colorful_loader/scene/bubble_preloader.dart b/example/lib/demos/colorful_loader/scene/bubble_preloader.dart index 73edcbc..172db2f 100644 --- a/example/lib/demos/colorful_loader/scene/bubble_preloader.dart +++ b/example/lib/demos/colorful_loader/scene/bubble_preloader.dart @@ -2,7 +2,6 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class BubblePreloader extends GSprite { - static const gradientColors = [ Color(0xFF9874D3), Color(0xFF6E7CCC), @@ -13,9 +12,9 @@ class BubblePreloader extends GSprite { ]; double w, h; - GShape bg, percentMask, bgGradient; - GSprite percentContainer, bubblesContainer; - double borderRadius, percent = 0.25, gradientShift = 0.0; + GShape? bg, percentMask, bgGradient; + late GSprite percentContainer, bubblesContainer; + double borderRadius = 0.0, percent = 0.25, gradientShift = 0.0; Color bgColor = const Color(0xffDEE0E3); int numBubbles = 50; @@ -37,11 +36,11 @@ class BubblePreloader extends GSprite { bgGradient = GShape(); percentMask = GShape(); - percentContainer.addChild(bgGradient); + percentContainer.addChild(bgGradient!); percentContainer.addChild(bubblesContainer); - addChild(bg); + addChild(bg!); addChild(percentContainer); - addChild(percentMask); + addChild(percentMask!); percentContainer.mask = percentMask; _drawBack(); @@ -96,7 +95,7 @@ class BubblePreloader extends GSprite { } void _drawMask() { - percentMask.graphics + percentMask!.graphics .clear() .beginFill(bgColor) .drawRoundRect(0, 0, w * percent, h, borderRadius) @@ -114,7 +113,7 @@ class BubblePreloader extends GSprite { } void _drawBack() { - bg.graphics + bg!.graphics .beginFill(bgColor) .drawRoundRect(0, 0, w, h, borderRadius) .endFill(); @@ -125,7 +124,7 @@ class BubblePreloader extends GSprite { gradientShift %= 3; var a1 = -1.0 - gradientShift; var a2 = 4.0 - gradientShift; - bgGradient.graphics + bgGradient!.graphics .clear() .beginGradientFill( GradientType.linear, diff --git a/example/lib/demos/colorful_loader/scene/scene.dart b/example/lib/demos/colorful_loader/scene/scene.dart index f6fdb63..27b5a4e 100644 --- a/example/lib/demos/colorful_loader/scene/scene.dart +++ b/example/lib/demos/colorful_loader/scene/scene.dart @@ -11,7 +11,7 @@ import 'bubble_preloader.dart'; /// just a wrapper scene class. class ColorLoaderScene extends GSprite { - BubblePreloader loader; + late BubblePreloader loader; @override void addedToStage() { @@ -21,11 +21,11 @@ class ColorLoaderScene extends GSprite { loader = BubblePreloader(w: 385, h: 14); addChild(loader); - stage.onResized.add(_handleStageResize); + stage!.onResized.add(_handleStageResize); } void _handleStageResize() { - loader.x = (stage.stageWidth - loader.w) / 2; - loader.y = (stage.stageHeight - loader.h) / 2; + loader.x = (stage!.stageWidth - loader.w) / 2; + loader.y = (stage!.stageHeight - loader.h) / 2; } } diff --git a/example/lib/demos/dialer/dialer_scene.dart b/example/lib/demos/dialer/dialer_scene.dart index 37e83e1..7b185ca 100644 --- a/example/lib/demos/dialer/dialer_scene.dart +++ b/example/lib/demos/dialer/dialer_scene.dart @@ -12,7 +12,7 @@ import 'package:graphx/graphx.dart'; const pinkColor = Color(0xffDD3D5C); class DialerScene extends GSprite { - Dialer dialer; + late Dialer dialer; @override void addedToStage() { @@ -26,11 +26,11 @@ class Dialer extends GSprite { double radius = 700 / 2; bool isPressed = false; GPoint pressed = GPoint(); - GShape bg; + late GShape bg; double prevRot = 0.0; double pressRot = 0.0; - Dialer([GSprite doc]) { + Dialer([GSprite? doc]) { _draw(); doc?.addChild(this); @@ -42,7 +42,7 @@ class Dialer extends GSprite { pressed.setTo(mouseX, mouseY); prevRot = bg.rotation; pressRot = Math.atan2(mouseY, mouseX); //bg.rotation; - stage.onMouseUp.add( + stage!.onMouseUp.add( (event) => isPressed = false, ); }); diff --git a/example/lib/demos/dna_3d/scene.dart b/example/lib/demos/dna_3d/scene.dart index 4bd0423..48bd668 100644 --- a/example/lib/demos/dna_3d/scene.dart +++ b/example/lib/demos/dna_3d/scene.dart @@ -2,14 +2,14 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class DnaScene extends GSprite { - double spiralRadius, centerX, centerY, centerZ; + double spiralRadius = 0.0, centerX = 0.0, centerY = 0.0, centerZ = 0.0; double fl = 150; - List dots; + late List dots; @override void addedToStage() async { - stage.color = Colors.white; + stage!.color = Colors.white; dots = List.generate(80, (index) { var dot = Dot(); addChild(dot); @@ -22,8 +22,8 @@ class DnaScene extends GSprite { @override void update(double delta) { super.update(delta); - centerX = stage.stageWidth / 2; - centerY = stage.stageHeight / 2; + centerX = stage!.stageWidth / 2; + centerY = stage!.stageHeight / 2; centerZ = 100.0; spiralRadius = (mouseX - centerX) / 4; @@ -47,7 +47,7 @@ class DnaScene extends GSprite { /// we just make a class to store the basic properties /// for the calculations. class Dot extends GShape { - double py, angle, speed = 5; + double py = 0.0, angle = 0.0, speed = 5; Dot() { graphics.beginFill(kColorBlack).drawCircle(0, 0, 10).endFill(); diff --git a/example/lib/demos/drawing_pad_bezier/drawing_pad/draw_pad_scene.dart b/example/lib/demos/drawing_pad_bezier/drawing_pad/draw_pad_scene.dart index 893f6ee..08aba9f 100644 --- a/example/lib/demos/drawing_pad_bezier/drawing_pad/draw_pad_scene.dart +++ b/example/lib/demos/drawing_pad_bezier/drawing_pad/draw_pad_scene.dart @@ -6,9 +6,9 @@ import 'pad.dart'; class DrawPadScene extends GSprite { int colorCount = 0; - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; double targetRot = 0; double opacity = 1.0; @@ -20,9 +20,9 @@ class DrawPadScene extends GSprite { @override void addedToStage() async { - stage.onHotReload.addOnce(() { - stage.onMouseScroll.removeAll(); - stage.onMouseMove.removeAll(); + stage!.onHotReload.addOnce(() { + stage!.onMouseScroll.removeAll(); + stage!.onMouseMove.removeAll(); mps.offAll('color'); mps.offAll('clear'); }); @@ -35,11 +35,11 @@ class DrawPadScene extends GSprite { pad.onBegin = GMouse.hide; pad.onEnd = GMouse.show; - stage.onMouseScroll.add((event) { + stage!.onMouseScroll.add((event) { var dir = event.scrollDelta.y; if (dir == 0) return; dir = dir < 0 ? 1 : -1; - if (stage.keyboard.isShiftPressed) { + if (stage!.keyboard!.isShiftPressed) { pad.minW += (dir * .1); pad.minW = pad.minW.clamp(minRad, maxRad); } else { @@ -47,13 +47,13 @@ class DrawPadScene extends GSprite { pad.maxW = pad.maxW.clamp(minRad, maxRad); } }); - stage.onResized.add(() => pad.resize(sw, sh)); + stage!.onResized.add(() => pad.resize(sw, sh)); pad.minW = .2; pad.maxW = 12.2; mps.on('alpha', (double alpha) { opacity = alpha; - pad.canvas.alpha = alpha; + pad.canvas!.alpha = alpha; }); mps.on('color', (Color color) { pad.penColor = color; diff --git a/example/lib/demos/drawing_pad_bezier/drawing_pad/pad.dart b/example/lib/demos/drawing_pad_bezier/drawing_pad/pad.dart index 94be25c..87ec134 100644 --- a/example/lib/demos/drawing_pad_bezier/drawing_pad/pad.dart +++ b/example/lib/demos/drawing_pad_bezier/drawing_pad/pad.dart @@ -15,24 +15,24 @@ class Pad extends GSprite { Color penColor = Color(0xff000000); Color backgroundColor = Colors.black; - Function onBegin, onEnd, onUpdate; + Function? onBegin, onEnd, onUpdate; final List _lastPoints = []; double _lastVelocity = 0; double _lastWidth = 0; - GShape _canvas; + GShape? _canvas; - GShape _bg; + late GShape _bg; - GShape get canvas => _canvas; - Graphics _g; + GShape? get canvas => _canvas; + late Graphics _g; double w, h; Pad({this.w = 300, this.h = 200}) { _canvas = GShape(); _bg = GShape(); addChild(_bg); - addChild(_canvas); - _g = _canvas.graphics; + addChild(_canvas!); + _g = _canvas!.graphics; clear(); on(); } @@ -51,11 +51,7 @@ class Pad extends GSprite { .beginFill(backgroundColor) .drawRect(0, 0, w, h) .endFill(); - _g - .clear() - .beginFill(baseTransparent) - .drawRect(0, 0, w, h) - .endFill(); + _g.clear().beginFill(baseTransparent).drawRect(0, 0, w, h).endFill(); _data.clear(); _reset(); _isEmpty = true; @@ -76,7 +72,7 @@ class Pad extends GSprite { void off() { onMouseDown.remove(_handleMouseDown); onMouseMove.remove(_handleMouseMove); - stage?.onMouseUp?.remove(_handleMouseUp); + stage?.onMouseUp.remove(_handleMouseUp); } void on() { @@ -85,7 +81,7 @@ class Pad extends GSprite { } _handleMouseDown(MouseInputData input) { - stage.onMouseUp.addOnce(_handleMouseUp); + stage!.onMouseUp.addOnce(_handleMouseUp); _isMouseDown = true; _strokeBegin(input); } @@ -125,15 +121,15 @@ class Pad extends GSprite { return; } - final mx = _canvas.mouseX; - final my = _canvas.mouseY; + final mx = _canvas!.mouseX; + final my = _canvas!.mouseY; final point = _createPoint(mx, my); final lastPointData = _data.last; var lastPoints = lastPointData.points; var lastPoint = lastPoints.isNotEmpty ? lastPoints.last : null; var hasLastPoint = lastPoint != null; var isLastPointTooClose = - hasLastPoint ? point.distanceTo(lastPoint) <= minDist : false; + hasLastPoint ? point.distanceTo(lastPoint!) <= minDist : false; final color = lastPointData.color; if (!hasLastPoint || !(hasLastPoint && isLastPointTooClose)) { @@ -150,7 +146,7 @@ class Pad extends GSprite { PadPoint _createPoint(double px, double py) => PadPoint(px, py, getTimer()); - BezierDraw _addPoint(PadPoint point) { + BezierDraw? _addPoint(PadPoint point) { _lastPoints.add(point); if (_lastPoints.length > 2) { if (_lastPoints.length == 3) { @@ -231,7 +227,7 @@ class Pad extends GSprite { class _StrokeData { Color color; - List points; + late List points; _StrokeData(this.color) { points = []; diff --git a/example/lib/demos/drawing_pad_bezier/drawing_pad/point.dart b/example/lib/demos/drawing_pad_bezier/drawing_pad/point.dart index 88e8b43..4bc48b9 100644 --- a/example/lib/demos/drawing_pad_bezier/drawing_pad/point.dart +++ b/example/lib/demos/drawing_pad_bezier/drawing_pad/point.dart @@ -4,8 +4,8 @@ import 'package:graphx/graphx.dart'; class PadPoint { double x, y; - int time; - PadPoint(this.x, this.y, [int time]) { + int? time; + PadPoint(this.x, this.y, [int? time]) { this.time = time ?? getTimer(); } @@ -15,7 +15,7 @@ class PadPoint { } double velocityForm(PadPoint start) => - time != start.time ? distanceTo(start) / (time - start.time) : 0.0; + time != start.time ? distanceTo(start) / (time! - start.time!) : 0.0; PadPoint operator -(PadPoint other) => PadPoint(x - other.x, y - other.y); PadPoint operator +(PadPoint other) => PadPoint(x + other.x, y + other.y); diff --git a/example/lib/demos/dripping_iv/scene/dripping_scene.dart b/example/lib/demos/dripping_iv/scene/dripping_scene.dart index a101a32..dffe144 100644 --- a/example/lib/demos/dripping_iv/scene/dripping_scene.dart +++ b/example/lib/demos/dripping_iv/scene/dripping_scene.dart @@ -1,17 +1,16 @@ -import '../../../utils/svg_utils.dart'; import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; import 'svgs.dart'; class DrippingScene extends GSprite { - GSvgShape drop; + late GSvgShape drop; double tubeW = 38, tubeH = 157, tubeOffset = 4.0; - GSprite tubeContainer; - GShape water, tubeMask; + late GSprite tubeContainer; + GShape? water, tubeMask; @override Future addedToStage() async { - stage.color = Colors.red; + stage!.color = Colors.red; var dropData = await SvgUtils.svgDataFromString(dropSvg); var tubeData = await SvgUtils.svgDataFromString(tubeSvgString); final waterColor = Colors.white; @@ -19,16 +18,16 @@ class DrippingScene extends GSprite { var tube = GSvgShape(tubeData); addChild(tube); tubeMask = GShape(); - tubeMask.setPosition(13, 29); - tubeMask.graphics + tubeMask!.setPosition(13, 29); + tubeMask!.graphics .beginFill(Colors.white.withOpacity(.2)) .drawRoundRect(tubeOffset, tubeOffset, tubeW - tubeOffset * 2, tubeH - tubeOffset * 2, tubeW / 2) .endFill(); - addChild(tubeMask); + addChild(tubeMask!); tubeContainer = GSprite(); - tubeContainer.setPosition(tubeMask.x, tubeMask.y); + tubeContainer.setPosition(tubeMask!.x, tubeMask!.y); tubeContainer.mask = tubeMask; addChild(tubeContainer); @@ -39,12 +38,12 @@ class DrippingScene extends GSprite { tubeContainer.addChild(drop); water = GShape(); - water.graphics + water!.graphics .beginFill(waterColor.withOpacity(.5)) .drawRect(0, 0, tubeW, 30); - water.alignPivot(Alignment.bottomLeft); - water.y = tubeH; - tubeContainer.addChild(water); + water!.alignPivot(Alignment.bottomLeft); + water!.y = tubeH; + tubeContainer.addChild(water!); addParticles(); // moveWater(); @@ -52,7 +51,7 @@ class DrippingScene extends GSprite { /// This shouldnt be needed... if u wrap in a Sized widget. alignPivot(); - setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); } void resetDripping() { @@ -63,10 +62,10 @@ class DrippingScene extends GSprite { } void moveWater() { - double targetH = water.height > 10 ? 5 : tubeH / 2; + double targetH = water!.height > 10 ? 5 : tubeH / 2; /// toggle water box height up and down... - water.tween( + water!.tween( duration: 6, height: targetH, ease: GEase.linearToEaseOut, diff --git a/example/lib/demos/elastic_band/scene.dart b/example/lib/demos/elastic_band/scene.dart index c7b2e0f..8e40506 100644 --- a/example/lib/demos/elastic_band/scene.dart +++ b/example/lib/demos/elastic_band/scene.dart @@ -13,14 +13,14 @@ class ElasticBandScene extends GSprite { @override void addedToStage() { - stage.onMouseDown.add(_handleMouseDown); + stage!.onMouseDown.add(_handleMouseDown); _handleUp(null); } void _handleMouseDown(e) { isPressed = true; - stage.onMouseMove.add(_handleMouseMove); - stage.onMouseUp.addOnce(_handleUp); + stage!.onMouseMove.add(_handleMouseMove); + stage!.onMouseUp.addOnce(_handleUp); } void _handleMouseMove(e) { @@ -28,11 +28,11 @@ class ElasticBandScene extends GSprite { } void _handleUp(e) { - stage.onMouseMove.remove(_handleMouseMove); + stage!.onMouseMove.remove(_handleMouseMove); isPressed = false; tweenPoint( - stage.stageWidth / 2, - stage.stageHeight / 2, + stage!.stageWidth / 2, + stage!.stageHeight / 2, 1, GEase.elasticOut, ); @@ -53,8 +53,8 @@ class ElasticBandScene extends GSprite { } void drawLine() { - var sw = stage.stageWidth; - var sh = stage.stageHeight; + var sw = stage!.stageWidth; + var sh = stage!.stageHeight; var cx = sw / 2; graphics diff --git a/example/lib/demos/expander_fab_menu/expander_fab_menu.dart b/example/lib/demos/expander_fab_menu/expander_fab_menu.dart index 4672c6a..fe5d8b3 100644 --- a/example/lib/demos/expander_fab_menu/expander_fab_menu.dart +++ b/example/lib/demos/expander_fab_menu/expander_fab_menu.dart @@ -44,9 +44,9 @@ class ExpanderFabMenu extends StatelessWidget { } class MyMenu extends StatefulWidget { - final Widget child; + final Widget? child; - const MyMenu({Key key, this.child}) : super(key: key); + const MyMenu({Key? key, this.child}) : super(key: key); @override _MyMenuState createState() => _MyMenuState(); @@ -55,7 +55,7 @@ class MyMenu extends StatefulWidget { class _MyMenuState extends State with TickerProviderStateMixin { bool isOpen = false; - AnimationController anim; + AnimationController? anim; final GlobalKey mySuperKey = GlobalKey(); final menuScene = MyCoolMenuScene(); @@ -69,14 +69,14 @@ class _MyMenuState extends State with TickerProviderStateMixin { // anim.addListener(() { // setState(() {}); // }); - WidgetsBinding.instance.addPostFrameCallback((timeStamp) { + WidgetsBinding.instance!.addPostFrameCallback((timeStamp) { getPosition(); }); } void getPosition() { - var ro = mySuperKey.currentContext.findRenderObject() as RenderBox; - var menuRO = context.findRenderObject() as RenderBox; + var ro = mySuperKey.currentContext!.findRenderObject() as RenderBox; + var menuRO = context.findRenderObject() as RenderBox?; var position = ro.localToGlobal(Offset.zero, ancestor: menuRO); menuScene.updatePosition(GRect.fromNative(position & ro.size)); } @@ -95,7 +95,7 @@ class _MyMenuState extends State with TickerProviderStateMixin { // color: Colors.red, child: Column( children: [ - Expanded(child: widget.child), + Expanded(child: widget.child!), Container( height: 60, decoration: BoxDecoration(color: Colors.white, boxShadow: [ @@ -165,7 +165,7 @@ class _MyMenuState extends State with TickerProviderStateMixin { } class MyCoolMenuScene extends GSprite { - MyButton button; + late MyButton button; bool isOpen = false; @@ -173,15 +173,15 @@ class MyCoolMenuScene extends GSprite { button = MyButton(); } - double buttonY; - GShape curtain; + double? buttonY; + late GShape curtain; void updatePosition(GRect position) { button.x = position.x + position.width / 2; button.y = buttonY = position.y + position.height / 2; } - GSprite menuContainer; + GSprite? menuContainer; @override void addedToStage() { @@ -190,7 +190,7 @@ class MyCoolMenuScene extends GSprite { addChild(curtain); menuContainer = GSprite(); - addChild(menuContainer); + addChild(menuContainer!); _buildMenu(); addChild(button); @@ -235,17 +235,17 @@ class MyCoolMenuScene extends GSprite { }); } - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; - var twnCurtainY = 0.0; + double get sh => stage!.stageHeight; + double? twnCurtainY = 0.0; bool bounceCurtain = false; _bounceCurtain() { if (bounceCurtain) return; bounceCurtain = true; - final myTween = twnCurtainY.twn; + final myTween = twnCurtainY!.twn; myTween.tween( sh, duration: 1, @@ -267,7 +267,7 @@ class MyCoolMenuScene extends GSprite { // g.lineStyle(2, Colors.black); g.beginFill(Colors.red); g.moveTo(0, sh); - g.curveTo(button.x, sh, button.x, twnCurtainY); + g.curveTo(button.x, sh, button.x, twnCurtainY!); g.curveTo(button.x, sh, sw, sh); g.lineTo(sw, 0).lineTo(0, 0).closePath(); } @@ -289,8 +289,8 @@ class MyCoolMenuScene extends GSprite { itm.y = i * 34.0; items.add(itm); } - menuContainer.alignPivot(); - menuContainer.setPosition(sw / 2, sh / 2); + menuContainer!.alignPivot(); + menuContainer!.setPosition(sw / 2, sh / 2); } void showMenuNow() { @@ -309,8 +309,8 @@ class MyCoolMenuScene extends GSprite { } class MyButton extends GSprite { - GShape bg; - GIcon icon; + late GShape bg; + late GIcon icon; double radius = 20; @override diff --git a/example/lib/demos/fb_reactions/fb_reactions.dart b/example/lib/demos/fb_reactions/fb_reactions.dart index 5840af6..b240406 100644 --- a/example/lib/demos/fb_reactions/fb_reactions.dart +++ b/example/lib/demos/fb_reactions/fb_reactions.dart @@ -56,9 +56,9 @@ class FacebookReactionsMain extends StatelessWidget { } class InnerCardItem extends StatelessWidget { - final PostVo data; + final PostVo? data; - const InnerCardItem({Key key, this.data}) : super(key: key); + const InnerCardItem({Key? key, this.data}) : super(key: key); @override Widget build(BuildContext context) { @@ -82,14 +82,14 @@ class InnerCardItem extends StatelessWidget { radius: 24, /// dev channel // foregroundImage: NetworkImage(data.profileImageUrl), - child: Text(data.username[0].toUpperCase()), + child: Text(data!.username[0].toUpperCase()), ), const SizedBox(width: 8), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - data.username, + data!.username, style: const TextStyle( fontSize: 13, fontWeight: FontWeight.bold, @@ -97,7 +97,7 @@ class InnerCardItem extends StatelessWidget { ), const SizedBox(height: 4), Text( - data.time, + data!.time, style: const TextStyle( fontSize: 10, color: Colors.black38, @@ -111,7 +111,7 @@ class InnerCardItem extends StatelessWidget { const SizedBox(height: 8), Text( - data.title, + data!.title, style: const TextStyle( fontWeight: FontWeight.bold, fontSize: 15, @@ -133,7 +133,7 @@ class InnerCardItem extends StatelessWidget { ), clipBehavior: Clip.antiAlias, child: Image.network( - data.imageUrl, + data!.imageUrl, height: 240, fit: BoxFit.cover, ), @@ -143,12 +143,12 @@ class InnerCardItem extends StatelessWidget { Row( children: [ - _IconReaction.likes(count: data.numLikes), + _IconReaction.likes(count: data!.numLikes), const SizedBox(width: 12), - _IconReaction.comments(count: data.numComments), + _IconReaction.comments(count: data!.numComments), Spacer(), Text( - data.shares, + data!.shares, style: const TextStyle( fontSize: 10, color: Colors.black, @@ -167,12 +167,12 @@ class InnerCardItem extends StatelessWidget { } class _IconReaction extends StatelessWidget { - final IconData iconData; + final IconData? iconData; final Color color; - final int count; + final int? count; const _IconReaction({ - Key key, + Key? key, this.iconData, this.color = Colors.black, this.count, @@ -194,7 +194,7 @@ class _IconReaction extends StatelessWidget { children: [ Icon( iconData, - color: color ?? Colors.black, + color: color, size: 16, ), const SizedBox(width: 2), diff --git a/example/lib/demos/fb_reactions/model.dart b/example/lib/demos/fb_reactions/model.dart index 7a7c3c8..5ae47af 100644 --- a/example/lib/demos/fb_reactions/model.dart +++ b/example/lib/demos/fb_reactions/model.dart @@ -39,8 +39,8 @@ class PostVo { final String imageUrl; final String time; - int numLikes, numComments; - String shares; + int? numLikes, numComments; + late String shares; PostVo._( this.username, diff --git a/example/lib/demos/fb_reactions/scene/menu_item.dart b/example/lib/demos/fb_reactions/scene/menu_item.dart index aa7211b..0a9194d 100644 --- a/example/lib/demos/fb_reactions/scene/menu_item.dart +++ b/example/lib/demos/fb_reactions/scene/menu_item.dart @@ -3,11 +3,11 @@ import 'package:graphx/graphx.dart'; //// each face class MenuItem extends GSprite { - double size, targetTooltipY; - GSprite pill; - GShape bg, msk; - GText label; - GMovieClip emoji; + double? size, targetTooltipY; + late GSprite pill; + GShape? bg, msk; + late GText label; + late GMovieClip emoji; MenuItem([this.size = 60]) { _init(); @@ -18,16 +18,16 @@ class MenuItem extends GSprite { /// bg is the emoji face. bg = GShape(); - addChild(bg); - bg.graphics + addChild(bg!); + bg!.graphics .beginFill(Colors.black.withOpacity(.5)) - .drawCircle(0, 0, size / 2) + .drawCircle(0, 0, size! / 2) .endFill(); msk = GShape(); - addChild(msk); - msk.graphics.copyFrom(bg.graphics); - msk.mouseEnabled = false; + addChild(msk!); + msk!.graphics.copyFrom(bg!.graphics); + msk!.mouseEnabled = false; emoji = GMovieClip(frames: []); addChild(emoji); mouseChildren = false; @@ -50,7 +50,7 @@ class MenuItem extends GSprite { pill.mouseEnabled = false; pill.scale = .75; pill.addChild(label); - targetTooltipY = -size * .9; + targetTooltipY = -size! * .9; } void showTooltip(bool flag) { @@ -69,7 +69,7 @@ class MenuItem extends GSprite { pill.scale = .75; pill.addChild(label); pill.alignPivot(); - targetTooltipY = -size * .9; + targetTooltipY = -size! * .9; } void drawBackground() { @@ -87,9 +87,9 @@ class MenuItem extends GSprite { } void _setGifAtlas(String gifId) { - final myAtlas = ResourceLoader.getGif(gifId); + final myAtlas = ResourceLoader.getGif(gifId)!; emoji.setFrameTextures(myAtlas.textureFrames); - emoji.width = size + 2; + emoji.width = size! + 2; emoji.mask = bg; emoji.scaleY = emoji.scaleX; emoji.mouseEnabled = false; diff --git a/example/lib/demos/fb_reactions/scene/menu_scene.dart b/example/lib/demos/fb_reactions/scene/menu_scene.dart index 3f8e714..db880d1 100644 --- a/example/lib/demos/fb_reactions/scene/menu_scene.dart +++ b/example/lib/demos/fb_reactions/scene/menu_scene.dart @@ -36,34 +36,34 @@ class MenuScene extends GSprite { 'assets/fb_reactions/angry.gif', ), ]; - List _items; + late List _items; - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; /// calculated based on bigSize and menuW - double itemSize; - double bigSizeScale; + double? itemSize; + double? bigSizeScale; double bigSize = 120.0; int numItems = emotions.length; - GShape bg; - GSprite menuContainer; + late GShape bg; + late GSprite menuContainer; double menuWidth = 400; double itemSep = 10; double bgPadding = 20; - MenuItem currentItem; + MenuItem? currentItem; @override Future addedToStage() async { final availableMenuW = (menuWidth - bgPadding * 2 - (numItems - 1) * itemSep); itemSize = (availableMenuW - bigSize) / (numItems - 1); - bigSizeScale = bigSize / itemSize; + bigSizeScale = bigSize / itemSize!; - final bgH = itemSize + bgPadding * 2; + final bgH = itemSize! + bgPadding * 2; menuContainer = GSprite(); addChild(menuContainer); bg = GShape(); @@ -98,7 +98,7 @@ class MenuScene extends GSprite { rotation: 0, ease: GEase.elasticOut); - stage.onMouseUp.addOnce((event) { + stage!.onMouseUp.addOnce((event) { menuContainer.tween( duration: .5, delay: .2, @@ -145,26 +145,26 @@ class MenuScene extends GSprite { var prevX = bgPadding; for (var i = 0; i < _items.length; ++i) { var itm = _items[i]; - var size2 = itm.size / 2; + var size2 = itm.size! / 2; itm.y = bgPadding + size2; size2 *= itm.scale; itm.x = prevX + size2; prevX += size2 * 2 + itemSep; - itm.onMouseOver.add((signal) => _selectItem(signal.target as MenuItem)); + itm.onMouseOver.add((signal) => _selectItem(signal.target as MenuItem?)); } } - void _selectItem(MenuItem item) { + void _selectItem(MenuItem? item) { if (item == currentItem) return; if (currentItem != null) { - currentItem.showTooltip(false); + currentItem!.showTooltip(false); GTween.killTweensOf(currentItem); - currentItem.tween(duration: .3, scale: 1); + currentItem!.tween(duration: .3, scale: 1); } currentItem = item; - currentItem.showTooltip(true); + currentItem!.showTooltip(true); GTween.killTweensOf(currentItem); - currentItem.tween( + currentItem!.tween( duration: .3, scale: bigSizeScale, onUpdate: positionItems, diff --git a/example/lib/demos/feeling_switch/scene.dart b/example/lib/demos/feeling_switch/scene.dart index fe1e2c4..856240e 100644 --- a/example/lib/demos/feeling_switch/scene.dart +++ b/example/lib/demos/feeling_switch/scene.dart @@ -2,13 +2,13 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class FeelingSwitch extends GSprite { - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; @override void addedToStage() { - stage.color = const Color(0xffF7F7F7); + stage!.color = const Color(0xffF7F7F7); var container = GSprite(); var tw = 100.0; var th = 40.0; @@ -100,7 +100,7 @@ class FeelingSwitch extends GSprite { toggle(); }); - stage.onResized.add(() { + stage!.onResized.add(() { var sc = sw / tw; container.scale = sc; container.setPosition(sw / 2, sh / 2); diff --git a/example/lib/demos/flower_gradient/scene.dart b/example/lib/demos/flower_gradient/scene.dart index 893c64c..44d8bf2 100644 --- a/example/lib/demos/flower_gradient/scene.dart +++ b/example/lib/demos/flower_gradient/scene.dart @@ -10,7 +10,7 @@ class FlowerScene extends GSprite { void createFlower() { var flower = GSprite(); addChild(flower); - flower.setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + flower.setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); var numLines = 8; @@ -28,7 +28,7 @@ class FlowerScene extends GSprite { shape.name = 's$i'; var color1 = Colors.primaries[i % Colors.primaries.length]; - var color2 = Color.lerp(color1, Colors.black, .4); + var color2 = Color.lerp(color1, Colors.black, .4)!; shape.graphics.beginGradientFill( GradientType.linear, diff --git a/example/lib/demos/gauge_meter/gauge_scene.dart b/example/lib/demos/gauge_meter/gauge_scene.dart index 489fac0..63a3e72 100644 --- a/example/lib/demos/gauge_meter/gauge_scene.dart +++ b/example/lib/demos/gauge_meter/gauge_scene.dart @@ -6,20 +6,20 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class GaugeMeterScene extends GSprite { - GSprite container; - GShape nailMeter; - GText labelValue; + late GSprite container; + late GShape nailMeter; + late GText labelValue; double swipeAngle = Math.PI * .8; - double offsetAngle; + late double offsetAngle; Color nailColor = Colors.redAccent; String letterValue = 'A'; int gaugeSteps = 7; double maxValue = 90; - double stepValueDeg; + late double stepValueDeg; - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; @override void addedToStage() { @@ -34,7 +34,7 @@ class GaugeMeterScene extends GSprite { var curve = GShape(); container.addChild(curve); var bigRadius = 214 / 2; - final baseColor = Color.lerp(nailColor, Colors.black, .6); + final baseColor = Color.lerp(nailColor, Colors.black, .6)!; offsetAngle = -(Math.PI / 2) - swipeAngle / 2; var g = curve.graphics; @@ -94,7 +94,7 @@ class GaugeMeterScene extends GSprite { // big value text. var labelA = GText( - text: letterValue ?? 'V', + text: letterValue, textStyle: TextStyle( fontSize: 25, fontWeight: FontWeight.bold, @@ -136,8 +136,8 @@ class GaugeMeterScene extends GSprite { // adjust size // container.scale = .5; // container.$debugBounds = true; - stage.onResized.add(() { - var graphBounds = container.bounds; + stage!.onResized.add(() { + var graphBounds = container.bounds!; var r1 = sw / sh; var r2 = graphBounds.width / graphBounds.height; if (r1 < r2) { diff --git a/example/lib/demos/globe_3d/scene.dart b/example/lib/demos/globe_3d/scene.dart index 6abea19..3c85cd5 100644 --- a/example/lib/demos/globe_3d/scene.dart +++ b/example/lib/demos/globe_3d/scene.dart @@ -4,10 +4,10 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class Globe3dScene extends GSprite { - List vertices; - List uvData; - List indices; - GSprite world; + late List vertices; + late List uvData; + late List indices; + late GSprite world; double centerZ = 500; int cols = 20, rows = 20; double fl = 1000; @@ -72,6 +72,7 @@ class Globe3dScene extends GSprite { } world.graphics.clear(); world.graphics.beginFill(Colors.black38); + /// TODO: fix issues with z ordering. // world.graphics.beginBitmapFill(texture); world.graphics.lineStyle(0, Color(0xffff00ff)); @@ -88,7 +89,7 @@ class Globe3dScene extends GSprite { @override void update(double delta) { super.update(delta); - world.setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + world.setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); draw(); } } diff --git a/example/lib/demos/glowing_circle/glowing_scene.dart b/example/lib/demos/glowing_circle/glowing_scene.dart index ab7fdda..00a0c66 100644 --- a/example/lib/demos/glowing_circle/glowing_scene.dart +++ b/example/lib/demos/glowing_circle/glowing_scene.dart @@ -11,7 +11,7 @@ extension MyGlowingExt on Widget { double endScaleInterval = 0.8, double circleInterval = .2, double replayDelay = .2, - Function(Graphics graphics, Size size) graphicBuilder, + Function(Graphics graphics, Size size)? graphicBuilder, }) { return SceneBuilderWidget( builder: () => SceneController( @@ -34,7 +34,7 @@ class MyGlowingEffect extends GSprite { final Color color; final double duration, circleInterval, replayDelay; final double startScale, endScale, endScaleInterval; - final Function(Graphics graphics, Size size) graphicBuilder; + final Function(Graphics graphics, Size size)? graphicBuilder; MyGlowingEffect({ this.color = const Color(0x8842A5F5), @@ -56,8 +56,8 @@ class MyGlowingEffect extends GSprite { final circles = List.generate(4, (index) { var shape = GShape(); addChild(shape); - final size = Size(stage.stageWidth, stage.stageHeight); - shape.setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + final size = Size(stage!.stageWidth, stage!.stageHeight); + shape.setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); if (graphicBuilder == null) { drawCircle(shape.graphics, size, color); } else { diff --git a/example/lib/demos/heart_reaction/scene.dart b/example/lib/demos/heart_reaction/scene.dart index 51177de..6135161 100644 --- a/example/lib/demos/heart_reaction/scene.dart +++ b/example/lib/demos/heart_reaction/scene.dart @@ -1,17 +1,16 @@ import 'package:graphx/graphx.dart'; -import '../../utils/svg_utils.dart'; import '../../utils/utils.dart'; import 'assets.dart'; class HeartScene extends GSprite { HeartScene({this.key}); - double get h => stage.stageHeight; + double get h => stage!.stageHeight; - double get w => stage.stageWidth; - SvgData svg; - final GlobalKey key; + double get w => stage!.stageWidth; + SvgData? svg; + final GlobalKey? key; @override Future addedToStage() async { @@ -21,7 +20,7 @@ class HeartScene extends GSprite { } void _heartRain() { - final _grect = ContextUtils.getRenderObjectBounds(key.currentContext); + final _grect = ContextUtils.getRenderObjectBounds(key!.currentContext!)!; var isUp = _grect.y < h / 2; var maxDuration = 0.0; List.generate( diff --git a/example/lib/demos/isma_chart/data.dart b/example/lib/demos/isma_chart/data.dart index c57b3f6..39cb034 100644 --- a/example/lib/demos/isma_chart/data.dart +++ b/example/lib/demos/isma_chart/data.dart @@ -13,7 +13,7 @@ final valueTextStyle = TextStyle( fontWeight: FontWeight.w600, ); -List cfrData; +late List cfrData; Future loadJson() async { // var id = 'assets/isma_chart/chart_data.json'; @@ -29,7 +29,7 @@ void buildData() { } class DotDataModel { - double value; + double? value; String year = '2020'; String value2 = '11'; String name = 'Ismail'; diff --git a/example/lib/demos/isma_chart/scene/chart_cell.dart b/example/lib/demos/isma_chart/scene/chart_cell.dart index d4dfad3..55c4cf3 100644 --- a/example/lib/demos/isma_chart/scene/chart_cell.dart +++ b/example/lib/demos/isma_chart/scene/chart_cell.dart @@ -1,4 +1,3 @@ - import 'dart:ui'; import 'package:flutter/material.dart'; @@ -7,11 +6,11 @@ import 'package:graphx/graphx.dart'; import '../data.dart'; class ChartTableCell extends GSprite { - double w, h; + double w = 0.0, h = 0.0; double cellH = 12; - double cellW; + late double cellW; - ChartTableCell([GSprite doc]) { + ChartTableCell([GSprite? doc]) { doc?.addChild(this); } @@ -40,7 +39,7 @@ class ChartTableCell extends GSprite { } } - void initDraw({double w, double h}) { + void initDraw({required double w, required double h}) { this.w = w; this.h = h; graphics diff --git a/example/lib/demos/isma_chart/scene/chart_scene.dart b/example/lib/demos/isma_chart/scene/chart_scene.dart index 0d2d65d..14c7a52 100644 --- a/example/lib/demos/isma_chart/scene/chart_scene.dart +++ b/example/lib/demos/isma_chart/scene/chart_scene.dart @@ -7,21 +7,21 @@ import 'chart_cell.dart'; import 'chart_sprite.dart'; class ChartScene extends GSprite { - GSprite boxCFR1; - GSprite boxCFR2; - ChartTableCell boxCell; - Chart boxLineChart; + late GSprite boxCFR1; + late GSprite boxCFR2; + late ChartTableCell boxCell; + late Chart boxLineChart; - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; - double get chartH => stage.stageHeight - monthYearBarH; + double get chartH => stage!.stageHeight - monthYearBarH; double monthYearBarH = 26; - GText cfr1; - GText monthYear; - GSprite cfr2; + late GText cfr1; + late GText monthYear; + late GSprite cfr2; double valuesYW = 17; @@ -97,7 +97,7 @@ class ChartScene extends GSprite { boxLineChart.x = boxCell.x; } - GSprite valuesYContainer; + late GSprite valuesYContainer; void _buildYValues() { valuesYContainer = GSprite(); diff --git a/example/lib/demos/isma_chart/scene/chart_sprite.dart b/example/lib/demos/isma_chart/scene/chart_sprite.dart index a8b9f24..1d017ba 100644 --- a/example/lib/demos/isma_chart/scene/chart_sprite.dart +++ b/example/lib/demos/isma_chart/scene/chart_sprite.dart @@ -4,23 +4,23 @@ import 'package:graphx/graphx.dart'; import 'dot_button.dart'; class Chart extends GSprite { - double w, h; - int cols, rows; - GShape chartLine; + double w = 0.0, h = 0.0; + int cols = 0, rows = 0; + late GShape chartLine; - Chart([GSprite doc]) { + Chart([GSprite? doc]) { doc?.addChild(this); chartLine = GShape(); addChild(chartLine); } - double rowsSep; + double? rowsSep; void initDraw({ - double w, - double h, - int cols, - int rows, + required double w, + required double h, + int cols = 0, + int rows = 0, // double rowsSep, }) { this.w = w; @@ -35,8 +35,8 @@ class Chart extends GSprite { _drawGrid(); } - double maxValueY; - double colSep, rowSep, colOffset; + late double maxValueY; + double colSep = 0.0, rowSep = 0.0, colOffset = 0.0; void _drawGrid() { colSep = w / cols; diff --git a/example/lib/demos/isma_chart/scene/dot_button.dart b/example/lib/demos/isma_chart/scene/dot_button.dart index 36c3b54..25f830e 100644 --- a/example/lib/demos/isma_chart/scene/dot_button.dart +++ b/example/lib/demos/isma_chart/scene/dot_button.dart @@ -1,17 +1,16 @@ - import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; import '../data.dart'; class DotButton extends GSprite { - GShape bg, bgOver; + late GShape bg, bgOver; - DotDataModel model; + DotDataModel? model; void setValue(double value) { model = DotDataModel(); - model.value = value; + model!.value = value; } @override @@ -42,8 +41,8 @@ class DotButton extends GSprite { onMouseOver.add((event) { bgOver.tween(duration: .5, scale: 2); - final rect = bg.getBounds(stage); - model.coordinate.setTo( + final rect = bg.getBounds(stage)!; + model!.coordinate.setTo( rect.x + rect.width / 2, rect.y + rect.height / 2, ); diff --git a/example/lib/demos/jelly_thing/scene.dart b/example/lib/demos/jelly_thing/scene.dart index b4861d7..40c51fe 100644 --- a/example/lib/demos/jelly_thing/scene.dart +++ b/example/lib/demos/jelly_thing/scene.dart @@ -12,31 +12,30 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class JellyDotsScene extends GSprite { - List points; + List? points; int totalPoints = 120; double size = 18; double mouseRadius = 80.0, mouseStrength = .06, stiffness = .05; bool outlineJelly = false; - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; void _toggleVisible(Dot d) => d.visible = !d.visible; @override void addedToStage() { - stage.keyboard.onDown.add((event) { + stage!.keyboard!.onDown.add((event) { if (event.isKey(LogicalKeyboardKey.keyD)) { - points.forEach(_toggleVisible); + points!.forEach(_toggleVisible); } else if (event.isKey(LogicalKeyboardKey.keyO)) { outlineJelly = !outlineJelly; } else if (event.isKey(LogicalKeyboardKey.keyR)) { - for (var dot in points) { + for (var dot in points!) { dot.x = dot.px = dot.ox; dot.y = dot.py = dot.oy; dot.vx = dot.vy = 0; - } } }); @@ -63,7 +62,7 @@ class JellyDotsScene extends GSprite { @override void update(double delta) { super.update(delta); - if (stage.pointer.isDown) { + if (stage!.pointer!.isDown) { size = 20; stiffness = .15; } else { @@ -71,13 +70,13 @@ class JellyDotsScene extends GSprite { stiffness = .05; } for (var i = 0; i < totalPoints - 1; ++i) { - var p0 = points[i]; + var p0 = points![i]; for (var j = i + 1; j < totalPoints; ++j) { - var p1 = points[j]; + var p1 = points![j]; compare(p0, p1, j == i + 1); } } - compare(points[totalPoints - 1], points[0], true); + compare(points![totalPoints - 1], points![0], true); updatePoints(); draw(graphics); } @@ -86,7 +85,7 @@ class JellyDotsScene extends GSprite { /// save touch coordinates, to avoid the matrix transformation. var mx = mouseX; var my = mouseY; - for (var dot in points) { + for (var dot in points!) { var dx = dot.x - mx; var dy = dot.y - my; var dist = Math.sqrt(dx * dx + dy * dy); @@ -138,15 +137,15 @@ class JellyDotsScene extends GSprite { } /// get the middle points to get a smooth cubic bezier... - var pa = points[0]; - var pz = points.last; + var pa = points![0]; + var pz = points!.last; var mid1x = (pz.x + pa.x) / 2; var mid1y = (pz.y + pa.y) / 2; g.moveTo(mid1x, mid1y); - for (var i = 0; i < points.length - 1; ++i) { - var p0 = points[i]; - var p1 = points[i + 1]; + for (var i = 0; i < points!.length - 1; ++i) { + var p0 = points![i]; + var p1 = points![i + 1]; g.curveTo( p0.x, p0.y, @@ -163,10 +162,10 @@ class JellyDotsScene extends GSprite { /// dot (point) reference. class Dot extends GShape { - double ox, oy; - double px, py, vx = 0, vy = 0, friction = .9; + double ox = 0, oy = 0; + double px = 0, py = 0, vx = 0, vy = 0, friction = .9; - Dot({this.px, this.py}) { + Dot({required this.px, required this.py}) { graphics .beginFill(Colors.yellowAccent) .lineStyle(2, Colors.green.withOpacity(.5)) diff --git a/example/lib/demos/lined_button/scene.dart b/example/lib/demos/lined_button/scene.dart index 89fe2e6..b614c26 100644 --- a/example/lib/demos/lined_button/scene.dart +++ b/example/lib/demos/lined_button/scene.dart @@ -8,28 +8,28 @@ final stageColor = Colors.grey.shade800; class LinedButtonScene extends GSprite { @override void addedToStage() { - stage.color = stageColor; + stage!.color = stageColor; var btn = LineButton(120, 60); addChild(btn); - btn.x = stage.stageWidth / 2; - btn.y = stage.stageHeight / 2; + btn.x = stage!.stageWidth / 2; + btn.y = stage!.stageHeight / 2; } } class LineButton extends GSprite { double w, h; - Path _oriPath; - PathMetric _metrics; + late Path _oriPath; + late PathMetric _metrics; final _tweenTf = 0.0.twn; final _tweenBg1 = 0.0.twn; final _tweenBg2 = 0.0.twn; final _stageColorTween = stageColor.twn; - GShape bg; - GShape bg2; - GShape bgBounds; - GText tf; + late GShape bg; + late GShape bg2; + late GShape bgBounds; + GText? tf; bool isOver = false; LineButton([this.w = 100, this.h = 50]) { @@ -62,10 +62,10 @@ class LineButton extends GSprite { addChild(bg); addChild(bg2); addChild(bgBounds); - addChild(tf); + addChild(tf!); // mouseChildren = false; - tf.mouseEnabled = bg.mouseEnabled = bg2.mouseEnabled = false; + tf!.mouseEnabled = bg.mouseEnabled = bg2.mouseEnabled = false; // bgBounds.mouseUseShape = false; bgBounds.mouseEnabled = true; bgBounds.useCursor = true; @@ -73,9 +73,9 @@ class LineButton extends GSprite { bgBounds.onMouseDown.add((e) { GTween.killTweensOf(tf); GTween.killTweensOf(_openLink); - tf.tween(duration: .3, scale: .88); - stage.onMouseUp.addOnce((e) { - tf.tween( + tf!.tween(duration: .3, scale: .88); + stage!.onMouseUp.addOnce((e) { + tf!.tween( duration: .5, scale: 1, ease: GEase.elasticOut, @@ -94,8 +94,8 @@ class LineButton extends GSprite { }); }); alignPivot(); - tf.alignPivot(); - tf.setPosition(w / 2, h / 2); + tf!.alignPivot(); + tf!.setPosition(w / 2, h / 2); } void _openLink() { @@ -117,7 +117,7 @@ class LineButton extends GSprite { enters ? Colors.grey.shade900 : stageColor, ease: GEase.easeOutSine, duration: 1.1, - onUpdate: () => stage.color = _stageColorTween.value, + onUpdate: () => stage!.color = _stageColorTween.value, ); _tweenTf.tween(value, duration: .4, onUpdate: _drawText); @@ -136,12 +136,12 @@ class LineButton extends GSprite { } void _setStyle({ - FontWeight fontWeight, - double letterSpacing, - Color color, - double fontSize, + FontWeight? fontWeight, + double? letterSpacing, + Color? color, + double? fontSize, }) { - tf.setTextStyle( + tf!.setTextStyle( TextStyle( fontWeight: fontWeight, fontSize: fontSize, @@ -181,6 +181,6 @@ class LineButton extends GSprite { color: Colors.white, fontSize: 18, ); - tf.alignPivot(); + tf!.alignPivot(); } } diff --git a/example/lib/demos/lungs/scene.dart b/example/lib/demos/lungs/scene.dart index 7668db4..b09323e 100644 --- a/example/lib/demos/lungs/scene.dart +++ b/example/lib/demos/lungs/scene.dart @@ -1,4 +1,3 @@ -import 'package:exampleGraphx/utils/svg_utils.dart'; import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; @@ -38,7 +37,7 @@ class LungsScene extends GSprite { traquea.y = traquea.pivotY; double totalDuration = 2; - var baseY = stage.stageHeight / 2; + var baseY = stage!.stageHeight / 2; bool isExpanded = false; void _twnTrackea() { @@ -94,8 +93,8 @@ class LungsScene extends GSprite { lung.alignPivot(); lung.setPosition( - stage.stageWidth / 2, - stage.stageHeight / 2, + stage!.stageWidth / 2, + stage!.stageHeight / 2, ); } } diff --git a/example/lib/demos/mouse_repulsion/scene.dart b/example/lib/demos/mouse_repulsion/scene.dart index 1ad864b..fd0b5c1 100644 --- a/example/lib/demos/mouse_repulsion/scene.dart +++ b/example/lib/demos/mouse_repulsion/scene.dart @@ -8,14 +8,14 @@ class MouseRepulsionScene extends GSprite { var dots = []; double spring = .015, stiff = .02, damp = .95, radius = 150.0; - double radiusSq; + late double radiusSq; - double xoffset, yoffset; - GSprite container; - GShape mouseRadiusShape; + double? xoffset, yoffset; + late GSprite container; + late GShape mouseRadiusShape; - double get sw => stage.stageWidth; - double get sh => stage.stageHeight; + double get sw => stage!.stageWidth; + double get sh => stage!.stageHeight; @override void addedToStage() { @@ -34,8 +34,8 @@ class MouseRepulsionScene extends GSprite { var total = cols * rows; dots = List.generate(total, (index) { var d = GraphPoint(); - var idx = index % cols ?? 0; - var idy = index ~/ cols ?? 0; + var idx = index % cols; + var idy = index ~/ cols; if (index == 0) { d.tx = d.x = 0; d.ty = d.y = 0; @@ -62,7 +62,7 @@ class MouseRepulsionScene extends GSprite { container.x = (sw - cols * sep) / 2; container.y = (sh - rows * sep) / 2; - if (stage.pointer.isDown) { + if (stage!.pointer!.isDown) { radius = 60; } else { radius = 150; diff --git a/example/lib/demos/murat_coffee/scene.dart b/example/lib/demos/murat_coffee/scene.dart index bd6707a..89432e6 100644 --- a/example/lib/demos/murat_coffee/scene.dart +++ b/example/lib/demos/murat_coffee/scene.dart @@ -9,7 +9,7 @@ class CoffeeItemScene extends GSprite { var product = _ProductSerious(); // product = _ProductPlayful(); product.loadImage(imageUrl); - product.setPosition(stage.stageWidth / 4, 0); + product.setPosition(stage!.stageWidth / 4, 0); addChild(product); } } @@ -30,9 +30,9 @@ class _ProductSerious extends _ProductPlayful { } class _ProductPlayful extends GSprite { - String url; - GBitmap image; - GShape shadow; + late String url; + late GBitmap image; + late GShape shadow; double shadowY = 0.0; double imageY = 0.0; @@ -57,8 +57,8 @@ class _ProductPlayful extends GSprite { ..graphics.beginFill(kColorBlack).drawCircle(0, 0, itmW / 2).endFill(); shadow.filters = [GBlurFilter(8, 8)]; shadow.scaleY = .2; - shadowY = shadow.y = image.bounds.height + shadow.height; - shadow.x = image.bounds.width / 2; + shadowY = shadow.y = image.bounds!.height + shadow.height; + shadow.x = image.bounds!.width / 2; addChild(image); addChild(shadow); diff --git a/example/lib/demos/nico_loading_indicator/scene.dart b/example/lib/demos/nico_loading_indicator/scene.dart index 7694d41..37ef363 100644 --- a/example/lib/demos/nico_loading_indicator/scene.dart +++ b/example/lib/demos/nico_loading_indicator/scene.dart @@ -6,7 +6,7 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class CustomLoadingIndicator extends StatelessWidget { - const CustomLoadingIndicator({Key key}) : super(key: key); + const CustomLoadingIndicator({Key? key}) : super(key: key); @override Widget build(BuildContext context) { @@ -17,8 +17,8 @@ class CustomLoadingIndicator extends StatelessWidget { } class CustomLoadingIndicatorSprite extends GSprite { - GShape fillSquare; - GSprite corners; + late GShape fillSquare; + late GSprite corners; static const expandTo = 60.0; static const colapseTo = 45.0; @@ -36,9 +36,9 @@ class CustomLoadingIndicatorSprite extends GSprite { @override void addedToStage() { - stage.onResized.add((){ - x = stage.stageWidth / 2; - y = stage.stageHeight / 2; + stage!.onResized.add((){ + x = stage!.stageWidth / 2; + y = stage!.stageHeight / 2; }); corners = GSprite(); @@ -88,7 +88,7 @@ class CustomLoadingIndicatorSprite extends GSprite { } void positionCorners() { - final size = currentSize / 2; + final size = currentSize! / 2; corners.children[0].x = -size; corners.children[0].y = -size; @@ -119,5 +119,5 @@ class CustomLoadingIndicatorSprite extends GSprite { addChild(fillSquare); } - double get currentSize => _currentSizeCorner.value; + double? get currentSize => _currentSizeCorner.value; } diff --git a/example/lib/demos/nokia_snake/game_page_widget.dart b/example/lib/demos/nokia_snake/game_page_widget.dart index 95a4b67..ae85960 100644 --- a/example/lib/demos/nokia_snake/game_page_widget.dart +++ b/example/lib/demos/nokia_snake/game_page_widget.dart @@ -9,7 +9,7 @@ import 'nokia_snake.dart'; class GamePage extends StatefulWidget { final int speed; - const GamePage({Key key, @required this.speed}) : super(key: key); + const GamePage({Key? key, required this.speed}) : super(key: key); @override _GamePageState createState() => _GamePageState(); diff --git a/example/lib/demos/nokia_snake/game_scene.dart b/example/lib/demos/nokia_snake/game_scene.dart index 08a63fa..d017b5e 100644 --- a/example/lib/demos/nokia_snake/game_scene.dart +++ b/example/lib/demos/nokia_snake/game_scene.dart @@ -13,11 +13,11 @@ class SnakeGameScene extends GSprite { GRect foodRect = GRect(); - double get sw => stage.stageWidth ?? 0; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight ?? 0; + double get sh => stage!.stageHeight; - GText scoreSt; + late GText scoreSt; final List> snake = >[ [0, 0], [0, 0], @@ -41,7 +41,7 @@ class SnakeGameScene extends GSprite { @override void addedToStage() { // stage.color = boardBackground; - stage.maskBounds = true; + stage!.maskBounds = true; mps.on('RESET', gameOver); mps.on('COMMAND', changeState); scoreSt = GText.build( @@ -55,7 +55,7 @@ class SnakeGameScene extends GSprite { scoreSt.setPosition(20.0, 20.0); generateFood(); resetSnake(); - stage.keyboard.onDown.add(onKeyDown); + stage!.keyboard!.onDown.add(onKeyDown); } @override @@ -194,20 +194,20 @@ class SnakeGameScene extends GSprite { } void _togglePause() { - if (stage.controller.ticker.isTicking) { + if (stage!.controller.ticker!.isTicking) { scoreSt.text = 'PAUSED'; - stage.controller.ticker.callNextFrame(() { - stage.controller.ticker.pause(); + stage!.controller.ticker!.callNextFrame(() { + stage!.controller.ticker!.pause(); }); } else { _updateScore(); - stage.controller.ticker.resume(); + stage!.controller.ticker!.resume(); } mps.publish1('Score', scoreSt.text); } void onKeyDown(KeyboardEventData event) { - final key = event.rawEvent.logicalKey; + final key = event.rawEvent!.logicalKey; if (key == Keys.LEFT_KEY) { changeState(SnakeCommands.left); } @@ -249,7 +249,7 @@ class SnakeGameScene extends GSprite { } } - void changeState([SnakeCommands command]) { + void changeState([SnakeCommands? command]) { if (command == SnakeCommands.pause) { _togglePause(); } diff --git a/example/lib/demos/nokia_snake/mobile_button_widget.dart b/example/lib/demos/nokia_snake/mobile_button_widget.dart index 344e3a5..666e3d9 100644 --- a/example/lib/demos/nokia_snake/mobile_button_widget.dart +++ b/example/lib/demos/nokia_snake/mobile_button_widget.dart @@ -4,12 +4,12 @@ import 'package:flutter/rendering.dart'; class MobileControlButton extends StatelessWidget { const MobileControlButton({ - Key key, + Key? key, this.icon, this.onPressed, }) : super(key: key); - final IconData icon; - final Function onPressed; + final IconData? icon; + final Function? onPressed; MobileControlButton.left(this.onPressed) : icon = Icons.keyboard_arrow_left_outlined; @@ -28,7 +28,7 @@ class MobileControlButton extends StatelessWidget { return MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( - onTap: onPressed, + onTap: onPressed as void Function()?, child: CircleAvatar( backgroundColor: Theme.of(context).accentColor.withOpacity(.4), child: Icon( diff --git a/example/lib/demos/nokia_snake/nokia_snake.dart b/example/lib/demos/nokia_snake/nokia_snake.dart index 028ea37..5538a34 100644 --- a/example/lib/demos/nokia_snake/nokia_snake.dart +++ b/example/lib/demos/nokia_snake/nokia_snake.dart @@ -11,7 +11,7 @@ import 'package:graphx/graphx.dart'; import 'game_page_widget.dart'; class NokiaSnakeMain extends StatefulWidget { - const NokiaSnakeMain({Key key}) : super(key: key); + const NokiaSnakeMain({Key? key}) : super(key: key); @override _NokiaSnakeMainState createState() => _NokiaSnakeMainState(); @@ -85,7 +85,7 @@ class _NokiaSnakeMainState extends State { }, trailing: PopupMenuButton( initialValue: speed, - onSelected: (value) => setState(() { + onSelected: (dynamic value) => setState(() { speed = value; }), itemBuilder: (_) => levels diff --git a/example/lib/demos/page_indicator/dot.dart b/example/lib/demos/page_indicator/dot.dart index 2633c4e..1d8dd08 100644 --- a/example/lib/demos/page_indicator/dot.dart +++ b/example/lib/demos/page_indicator/dot.dart @@ -6,38 +6,38 @@ import 'package:graphx/graphx.dart'; class PageDot extends GShape { int id; - double _baseSize; + double? _baseSize; - Color _color; + Color? _color; - Color get color => _color; + Color? get color => _color; - set color(Color value) { + set color(Color? value) { if (value == _color) return; _color = value; _invalidateDraw(); } - Color _targetColor; + Color? _targetColor; - Color get targetColor => _targetColor; + Color? get targetColor => _targetColor; - GTweenableColor _colorTween; + GTweenableColor? _colorTween; bool _invalidColor = false; - set targetColor(Color value) { + set targetColor(Color? value) { if (value == _color) return; _targetColor = value; _invalidColor = true; } - double _size; - double targetSize; + double? _size; + double? targetSize; - double get size => _size; + double get size => _size!; set size(double value) { - if (value < _baseSize) value = _baseSize; + if (value < _baseSize!) value = _baseSize!; if (value == _size) return; _size = value; _invalidateDraw(); @@ -53,8 +53,8 @@ class PageDot extends GShape { void _draw() { graphics .clear() - .beginFill(_color) - .drawRoundRect(0, 0, _size, _baseSize, _baseSize / 2) + .beginFill(_color!) + .drawRoundRect(0, 0, _size!, _baseSize!, _baseSize! / 2) .endFill(); } @@ -107,9 +107,9 @@ class PageDot extends GShape { if (_colorTween != null) { GTween.killTweensOf(_colorTween); } - _colorTween = _color.twn; - _colorTween.tween(_targetColor, duration: .3, onUpdate: () { - color = _colorTween.value; + _colorTween = _color!.twn; + _colorTween!.tween(_targetColor!, duration: .3, onUpdate: () { + color = _colorTween!.value; }); } } diff --git a/example/lib/demos/page_indicator/scene.dart b/example/lib/demos/page_indicator/scene.dart index 7dab822..4b29b73 100644 --- a/example/lib/demos/page_indicator/scene.dart +++ b/example/lib/demos/page_indicator/scene.dart @@ -10,7 +10,7 @@ import 'dot.dart'; class PageIndicatorPaged extends BaseScene { PageIndicatorPaged(); - List _dots; + late List _dots; static const double dotSize = 13; static const double dotPreW = 18; static const double dotSelectedW = 34; @@ -18,8 +18,8 @@ class PageIndicatorPaged extends BaseScene { static const dotSelectedColor = Colors.red; static const dotPreColor = Colors.blue; - GSprite container; - GSprite scrollContainer; + late GSprite container; + late GSprite scrollContainer; int _currentIndex = 0; final int _visibleItems = 5; @@ -76,8 +76,8 @@ class PageIndicatorPaged extends BaseScene { /// -- end masking. /// only for testing. - stage.keyboard.focusNode.requestFocus(); - stage.keyboard.onDown.add((event) { + stage!.keyboard!.focusNode.requestFocus(); + stage!.keyboard!.onDown.add((event) { if (event.arrowLeft) { moveDir(-1); } else if (event.arrowRight) { @@ -85,7 +85,7 @@ class PageIndicatorPaged extends BaseScene { } }); - stage.onResized.add(() { + stage!.onResized.add(() { var ratioScale = sw / _allDotsWidth; scale = ratioScale; @@ -155,17 +155,17 @@ class PageIndicatorPaged extends BaseScene { /// the expensize "colorize". nextDot?.targetColor = dotPreColor; prevDot?.targetColor = dotPreColor; - currDot?.targetSize = dotSelectedW; - currDot?.targetColor = dotSelectedColor; + currDot.targetSize = dotSelectedW; + currDot.targetColor = dotSelectedColor; } void _layoutDots() { var lastX = 0.0; for (var i = 0; i < _dots.length; ++i) { var dot = _dots[i]; - var sizeDistance = dot.targetSize - dot.size; + var sizeDistance = dot.targetSize! - dot.size; if (sizeDistance.abs() < .1) { - dot.size = dot.targetSize; + dot.size = dot.targetSize!; } else { dot.size += sizeDistance / dotSizeEase; } @@ -183,12 +183,12 @@ class PageIndicatorPaged extends BaseScene { return _dots[_currentIndex]; } - PageDot get prevDot { + PageDot? get prevDot { if (_currentIndex == 0) return null; return _dots[_currentIndex - 1]; } - PageDot get nextDot { + PageDot? get nextDot { if (_currentIndex >= _numItems - 1) return null; return _dots[_currentIndex + 1]; } diff --git a/example/lib/demos/path_chart_stress/scene.dart b/example/lib/demos/path_chart_stress/scene.dart index cf80996..1a893ef 100644 --- a/example/lib/demos/path_chart_stress/scene.dart +++ b/example/lib/demos/path_chart_stress/scene.dart @@ -20,15 +20,15 @@ class PathChartScene extends GSprite { var label = section.label; var idx = colors.indexOf(c); if (idx == 0) { - addChild(label); + addChild(label!); label.x = 30; label.y = 80 + 20.0 * idx; } }); - container.x = stage.stageWidth * .8; - container.y = stage.stageHeight * .5; - stage.onEnterFrame.add((event) { + container.x = stage!.stageWidth * .8; + container.y = stage!.stageHeight * .5; + stage!.onEnterFrame.add((event) { // if (container.width > container.x + 100) { // tw = container.x + 100; // container.width = tw; @@ -70,7 +70,7 @@ class ChartSection extends GShape { // List.generate(19, (index) => addSlot()); } - GText label; + GText? label; int frameCount = 0; double targetX = 0; Path maskPath = Path(); @@ -82,7 +82,7 @@ class ChartSection extends GShape { label = GText.build( text: 'color', color: color, fontSize: 14, fontWeight: FontWeight.bold); - stage.onEnterFrame.add((event) { + stage!.onEnterFrame.add((event) { if (++frameCount % 3 == 0) { addSlot(); pivotX = width; @@ -107,7 +107,7 @@ class ChartSection extends GShape { void addSlot() { ++numQuads; - label.text = '$numQuads rects'; + label!.text = '$numQuads rects'; graphics.clear(); graphics.beginFill(color.withOpacity(.3)); graphics.lineStyle(2, color); diff --git a/example/lib/demos/pie_chart/scene.dart b/example/lib/demos/pie_chart/scene.dart index 825af35..a8e9a1e 100644 --- a/example/lib/demos/pie_chart/scene.dart +++ b/example/lib/demos/pie_chart/scene.dart @@ -14,7 +14,7 @@ class PieChartScene extends GSprite { lineContainer.mouseChildren = false; lineContainer.mouseEnabled = false; - var sw2 = stage.stageWidth / 2; + var sw2 = stage!.stageWidth / 2; var numPieces = 5; var data = List.generate(numPieces, (index) => Math.randomRange(10, 50)); var total = data.reduce((value, element) => value + element); @@ -23,11 +23,11 @@ class PieChartScene extends GSprite { var totalRad = deg2rad(360); var currentAngle = 0.0; - GSprite currentPiece; + GSprite? currentPiece; for (var i = 0; i < numPieces; ++i) { var color = Colors.primaries[(i) % Colors.primaries.length].value; var color1 = Color(color); - var color2 = Color.lerp(color1, Colors.black, .8); + var color2 = Color.lerp(color1, Colors.black, .8)!; var percent = data[i] / total; var myAngle = percent * totalRad; var pieceLine = GSprite(); @@ -54,22 +54,22 @@ class PieChartScene extends GSprite { piece.userData = pieceLine; piece.mouseChildren = false; piece.onMouseOver.add((e) { - GDisplayObject line; + GDisplayObject? line; if (currentPiece != null) { - line = currentPiece.userData as GDisplayObject; + line = currentPiece!.userData as GDisplayObject?; GTween.killTweensOf(currentPiece); GTween.killTweensOf(line); - currentPiece.tween(duration: .35, scale: 1, ease: GEase.easeInBack); - line.tween(duration: .35, scale: 1, ease: GEase.easeInBack); + currentPiece!.tween(duration: .35, scale: 1, ease: GEase.easeInBack); + line!.tween(duration: .35, scale: 1, ease: GEase.easeInBack); } // var p = e.target; currentPiece = piece; - line = currentPiece.userData as GDisplayObject; + line = currentPiece!.userData as GDisplayObject?; // e.target.scale = 1.4; GTween.killTweensOf(line); GTween.killTweensOf(piece); piece.tween(duration: .35, scale: .9, ease: GEase.easeOutExpo); - line.tween(duration: .35, scale: .9, ease: GEase.easeOutExpo); + line!.tween(duration: .35, scale: .9, ease: GEase.easeOutExpo); }); var percentText = (percent * 100.0).toStringAsPrecision(2); @@ -115,6 +115,6 @@ class PieChartScene extends GSprite { extension MyObject on GDisplayObject { void centerInStage() { if (!inStage) return; - setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); } } diff --git a/example/lib/demos/pizza_box/scene.dart b/example/lib/demos/pizza_box/scene.dart index 52593ce..f0b669f 100644 --- a/example/lib/demos/pizza_box/scene.dart +++ b/example/lib/demos/pizza_box/scene.dart @@ -4,20 +4,19 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class PizzaBoxScene extends GSprite { + double get sw => stage!.stageWidth; + double get sh => stage!.stageHeight; - double get sw => stage.stageWidth; - double get sh => stage.stageHeight; - - GBitmap pizza; - GSprite container, pizzaContainer; + late GBitmap pizza; + late GSprite container, pizzaContainer; double boxS = 80; bool isOpen = true; - GShape sideTop, sideBottom; - GTexture pizzaTexture; + late GShape sideTop, sideBottom; + GTexture? pizzaTexture; @override void addedToStage() async { - stage.color = Colors.grey.shade50; + stage!.color = Colors.grey.shade50; pizzaTexture = await ResourceLoader.loadTexture('assets/pizza_box/pizza.png', 2); run(); diff --git a/example/lib/demos/raster_draw/scene.dart b/example/lib/demos/raster_draw/scene.dart index 771e2a0..4bf9399 100644 --- a/example/lib/demos/raster_draw/scene.dart +++ b/example/lib/demos/raster_draw/scene.dart @@ -3,9 +3,9 @@ import 'package:graphx/graphx.dart'; import '../../utils/utils.dart'; class DrawingScene extends GSprite { - GShape drawer; - GSprite container; - GBitmap captured; + late GShape drawer; + late GSprite container; + late GBitmap captured; @override void addedToStage() { @@ -15,7 +15,7 @@ class DrawingScene extends GSprite { /// capturing the snapshot. container.graphics .beginFill(Colors.red.withOpacity(0)) - .drawRect(0, 0, stage.stageWidth, stage.stageHeight) + .drawRect(0, 0, stage!.stageWidth, stage!.stageHeight) .endFill(); drawer = GShape(); captured = GBitmap(); @@ -28,13 +28,13 @@ class DrawingScene extends GSprite { container.addChild(drawer); /// keep the stage clipped to the Widget size. - stage.maskBounds = true; + stage!.maskBounds = true; /// shows a border around the stage area (for debug). - stage.showBoundsRect = true; + stage!.showBoundsRect = true; /// listen to mouse/touch events. - stage.onMouseDown.add(_onDown); + stage!.onMouseDown.add(_onDown); } /// basic draw line command from the previous point. @@ -52,7 +52,7 @@ class DrawingScene extends GSprite { /// refresh the GBitmap with the new texture. captured.texture = texture; - stage.onMouseMove.remove(_onMove); + stage!.onMouseMove.remove(_onMove); /// after capturing the Texture, we clear the drawn line... to start fresh. /// and not overload the CPU. @@ -67,7 +67,7 @@ class DrawingScene extends GSprite { kColorBlack.withOpacity(Math.randomRange(.4, 1)), ); drawer.graphics.moveTo(mouseX, mouseY); - stage.onMouseMove.add(_onMove); - stage.onMouseUp.addOnce(_onRelease); + stage!.onMouseMove.add(_onMove); + stage!.onMouseUp.addOnce(_onRelease); } } diff --git a/example/lib/demos/rating_star/scene/rating_scene.dart b/example/lib/demos/rating_star/scene/rating_scene.dart index 344d990..5427e0b 100644 --- a/example/lib/demos/rating_star/scene/rating_scene.dart +++ b/example/lib/demos/rating_star/scene/rating_scene.dart @@ -8,15 +8,15 @@ const Color kStarColor = Color(0xFFFCC915); const Color kUnselectedSColor = Color(0xFF7F86AC); class RatingStarsScene extends GSprite { - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; - List stars; - GSprite container; + double get sh => stage!.stageHeight; + late List stars; + late GSprite container; @override void addedToStage() { - stage.color = kBgColor; + stage!.color = kBgColor; container = GSprite(); addChild(container); stars = List.generate( @@ -35,7 +35,7 @@ class RatingStarsScene extends GSprite { }, ); container.alignPivot(); - final bb = container.bounds; + final bb = container.bounds!; container.graphics.beginFill(kColorTransparent).drawGRect(bb).endFill(); container.onMouseOut.add((event) { if (container.hitTouch(GPoint( @@ -46,7 +46,7 @@ class RatingStarsScene extends GSprite { stars[i].hoverState(false); } }); - stage.onResized.add(() { + stage!.onResized.add(() { container.setPosition(sw / 2, sh / 2); }); } diff --git a/example/lib/demos/rating_star/scene/star.dart b/example/lib/demos/rating_star/scene/star.dart index 1d32036..7c48f09 100644 --- a/example/lib/demos/rating_star/scene/star.dart +++ b/example/lib/demos/rating_star/scene/star.dart @@ -8,19 +8,19 @@ class Star extends GSprite { double dotSize = 10; bool active = false; - GShape _star; + late GShape _star; - GSprite _broken; + GSprite? _broken; - GShape _dot; + late GShape _dot; Star() { _initUi(); mouseChildren = false; } - static GTexture _tx1; - static GTexture _tx2; + static GTexture? _tx1; + static GTexture? _tx2; Future createTemplate() async { var st = GShape(); @@ -77,7 +77,7 @@ class Star extends GSprite { await createTemplate(); } _broken = GSprite(); - addChild(_broken); + addChild(_broken!); var bmp1 = GBitmap(_tx1); var bmp2 = GBitmap(_tx2); // bmp1.nativePaint.filterQuality = FilterQuality.medium; @@ -86,18 +86,18 @@ class Star extends GSprite { bmp1.pivotY = 24; bmp2.pivotX = 11; bmp2.pivotY = 24; - _broken.addChild(bmp1); - _broken.addChild(bmp2); - _broken.visible = false; + _broken!.addChild(bmp1); + _broken!.addChild(bmp2); + _broken!.visible = false; /// manual adjustment. - _broken.pivotX = bmp2.pivotX - 3; - _broken.pivotY = -3; + _broken!.pivotX = bmp2.pivotX - 3; + _broken!.pivotY = -3; } _handleDown(e) { if (!_selected) return; - stage.onMouseUp.addOnce(_handleUp); + stage!.onMouseUp.addOnce(_handleUp); _star.tween(duration: .24, scale: .86, overwrite: 0); } @@ -119,14 +119,14 @@ class Star extends GSprite { final _color = kUnselectedSColor.withAlpha(0); - _broken.setProps( + _broken!.setProps( y: 0, alpha: 1, visible: true, colorize: _color, ); - var p1 = _broken.children[0]; - var p2 = _broken.children[1]; + var p1 = _broken!.children[0]; + var p2 = _broken!.children[1]; p1.setProps(rotation: 0, y: 0); p2.setProps(rotation: 0, y: 0); @@ -144,7 +144,7 @@ class Star extends GSprite { ease: GEase.easeOutQuad, ); - _broken.tween( + _broken!.tween( duration: .3, delay: .1, colorize: kUnselectedSColor, @@ -152,13 +152,13 @@ class Star extends GSprite { ); var blur = GBlurFilter(0, 0); - _broken.filters = [blur]; + _broken!.filters = [blur]; var a = 0.0.twn; a.tween(8, duration: .5, delay: .16, onUpdate: () { blur.blurY = blur.blurX = a.value; }); - _broken.tween( + _broken!.tween( duration: .6, overwrite: 0, y: 50, @@ -167,7 +167,7 @@ class Star extends GSprite { alpha: 0, ease: GEase.easeInCubic, onComplete: () { - _broken.visible = false; + _broken!.visible = false; _star.visible = false; }, ); @@ -179,7 +179,7 @@ class Star extends GSprite { ); } else { GTween.killTweensOf(_broken); - _broken.visible = false; + _broken!.visible = false; _star.setProps(y: 0, rotation: 0, scale: 0, visible: true); _dot.tween(duration: .6, scale: 0); _star.tween( diff --git a/example/lib/demos/run_hero_canvas/scene/hero_scene.dart b/example/lib/demos/run_hero_canvas/scene/hero_scene.dart index 4fe3e74..e1df437 100644 --- a/example/lib/demos/run_hero_canvas/scene/hero_scene.dart +++ b/example/lib/demos/run_hero_canvas/scene/hero_scene.dart @@ -6,20 +6,20 @@ import 'package:graphx/graphx.dart'; class PainterRawScene extends GSprite { @override Future addedToStage() async { - stage.color = Colors.black; - stage.maskBounds = true; + stage!.color = Colors.black; + stage!.maskBounds = true; /// load assets! await _loadAssets(); addChild(ParallaxView()); - stage.keyboard.onDown.add((e) { + stage!.keyboard!.onDown.add((e) { if (e.isKey(LogicalKeyboardKey.space)) { mps.emit('jump'); } }); - stage.onMouseDown.add((event) { + stage!.onMouseDown.add((event) { mps.emit('jump'); }); } @@ -33,7 +33,10 @@ class PainterRawScene extends GSprite { await ResourceLoader.loadTexture( 'assets/run_hero/parallax/layer_03.png', 2, 'l3'); await ResourceLoader.loadTexture( - 'assets/run_hero/parallax/layer_04.png', 2, 'l4',); + 'assets/run_hero/parallax/layer_04.png', + 2, + 'l4', + ); await ResourceLoader.loadGif( 'assets/run_hero/run_outline.gif', resolution: 1, @@ -48,13 +51,13 @@ class PainterRawScene extends GSprite { } class ParallaxView extends GDisplayObjectContainer { - List layers = []; + List layers = []; List matrices = []; List paintings = []; final jumpY = 0.0.twn; int heroFrame = 0; - GifAtlas hero; + GifAtlas? hero; final gradientPaint = Paint(); final heroPaint = Paint(); @@ -90,11 +93,11 @@ class ParallaxView extends GDisplayObjectContainer { @override void addedToStage() { gradientPaint.blendMode = BlendMode.color; - final gradCenter = Offset(stage.stageWidth / 2, stage.stageHeight / 2); + final gradCenter = Offset(stage!.stageWidth / 2, stage!.stageHeight / 2); final gradMatrix = Matrix4.identity()..scale(.9); gradientPaint.shader = ui.Gradient.radial( gradCenter, - stage.stageWidth, + stage!.stageWidth, [Colors.red.withOpacity(.3), Colors.blue.withOpacity(1)], [0.1, .9], TileMode.clamp, @@ -105,9 +108,9 @@ class ParallaxView extends GDisplayObjectContainer { void heroState(String id) => hero = ResourceLoader.getGif(id); @override - void $applyPaint(Canvas canvas) { - canvas.save(); - canvas.scale(1 / (layers[0].scale)); + void $applyPaint(Canvas? canvas) { + canvas!.save(); + canvas.scale(1 / layers[0]!.scale!); matrices[0].translate(-.5); matrices[1].translate(-.8); matrices[2].translate(-3.0); @@ -125,7 +128,7 @@ class ParallaxView extends GDisplayObjectContainer { void drawLayer(Canvas canvas, int index) { paintings[index].shader = ImageShader( - layers[index].root, + layers[index]!.root!, TileMode.repeated, TileMode.mirror, matrices[index].storage, @@ -135,9 +138,9 @@ class ParallaxView extends GDisplayObjectContainer { void drawHero(Canvas canvas) { if (++heroFrame % 4 == 0) { - hero.nextFrame(); + hero!.nextFrame(); } - var img = hero.root; + var img = hero!.root!; // heroPaint.invertColors = true; // heroPaint.blendMode = BlendMode.colorDodge; var heroScale = 2.0; @@ -145,7 +148,7 @@ class ParallaxView extends GDisplayObjectContainer { canvas.save(); canvas.translate(300.0, floorY); canvas.scale(heroScale); - canvas.translate(-hero.width / 2, -hero.height); + canvas.translate(-hero!.width! / 2, -hero!.height!); canvas.drawImage(img, Offset(0, 0), heroPaint); canvas.restore(); } diff --git a/example/lib/demos/simple_interactions/simple_interactions_scene.dart b/example/lib/demos/simple_interactions/simple_interactions_scene.dart index 71e6e23..9f13ee4 100644 --- a/example/lib/demos/simple_interactions/simple_interactions_scene.dart +++ b/example/lib/demos/simple_interactions/simple_interactions_scene.dart @@ -5,7 +5,7 @@ import 'package:graphx/graphx.dart'; import 'ui/my_button.dart'; class SimpleInteractionsScene extends GSprite { - GShape ball; + late GShape ball; @override void addedToStage() { @@ -18,9 +18,9 @@ class SimpleInteractionsScene extends GSprite { /// internally. // button.onMouseDown.add((e) => print("mouse down on button! $e")); - stage.onResized.add(() { - button.x = stage.stageWidth / 2; - button.y = stage.stageHeight / 2; + stage!.onResized.add(() { + button.x = stage!.stageWidth / 2; + button.y = stage!.stageHeight / 2; }); _initBall(); @@ -38,8 +38,8 @@ class SimpleInteractionsScene extends GSprite { ball.x = 100; ball.y = 100; - stage.keyboard.onDown.add(_onKeyboardDown); - stage.keyboard.onUp.add(_onKeyboardUp); + stage!.keyboard!.onDown.add(_onKeyboardDown); + stage!.keyboard!.onUp.add(_onKeyboardUp); } /// Only the stage has access to keyboard events. @@ -55,7 +55,7 @@ class SimpleInteractionsScene extends GSprite { /// for access modifiers keys, is better to check the raw event itself. /// as multiple physical keys have the same behaviour (shift, command, /// alt, etc) but different key codes. - if (event.rawEvent.isShiftPressed) { + if (event.rawEvent!.isShiftPressed) { pixelsToMove = 30.0; } @@ -71,7 +71,7 @@ class SimpleInteractionsScene extends GSprite { if (event.isKey(LogicalKeyboardKey.arrowUp)) { // arrow key UP ball.y -= pixelsToMove; - } else if (event.rawEvent.logicalKey == LogicalKeyboardKey.arrowDown) { + } else if (event.rawEvent!.logicalKey == LogicalKeyboardKey.arrowDown) { // arrow key DOWN ball.y += pixelsToMove; } diff --git a/example/lib/demos/simple_interactions/ui/my_button.dart b/example/lib/demos/simple_interactions/ui/my_button.dart index 893614b..041e2c0 100644 --- a/example/lib/demos/simple_interactions/ui/my_button.dart +++ b/example/lib/demos/simple_interactions/ui/my_button.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import 'package:flutter_icons/flutter_icons.dart'; import 'package:graphx/graphx.dart'; class MyButton extends GSprite { @@ -8,19 +7,19 @@ class MyButton extends GSprite { double h = 80; // backwards background (black) - GShape bg; + late GShape bg; // filled background that changes with [_fillPercent] (yellow) - GShape fillBg; + late GShape fillBg; // the light bulb icon that toggles when clicking the button - GIcon icon; + GIcon icon = GIcon(Icons.ac_unit); bool _isTouching = false; bool _isOn = false; double _fillPercent = 0.0; - GText _fillText; + late GText _fillText; MyButton() { _init(); @@ -35,7 +34,6 @@ class MyButton extends GSprite { fillBg = GShape(); _dragBackground(fillBg.graphics, Colors.yellow.shade800); - icon = GIcon(null); _updateIcon(); icon.alignPivot(); @@ -104,7 +102,7 @@ class MyButton extends GSprite { /// Handler for pointer down (mouse or touch). void _onMouseDown(MouseInputData input) { scale = .94; - stage.onMouseUp.addOnce(_onStageRelease); + stage!.onMouseUp.addOnce(_onStageRelease); } /// Handler for mouse scroll wheel (only desktop). @@ -155,10 +153,10 @@ class MyButton extends GSprite { /// update the [icon.data] and icon's color, based on [_isOn] current state. void _updateIcon() { if (_isOn) { - icon.data = Feather.sun; + icon.data = Icons.brightness_7_outlined; icon.color = Colors.yellow; } else { - icon.data = Feather.moon; + icon.data = Icons.brightness_2_outlined; icon.color = Colors.white; } } diff --git a/example/lib/demos/simple_radial_menu/circ_menu.dart b/example/lib/demos/simple_radial_menu/circ_menu.dart index 09bd7d3..df376d9 100644 --- a/example/lib/demos/simple_radial_menu/circ_menu.dart +++ b/example/lib/demos/simple_radial_menu/circ_menu.dart @@ -36,14 +36,14 @@ class SimpleRadialMenuScene extends GSprite { var container = GSprite(); addChild(container); - items?.clear(); + items.clear(); var mainCircle = createCircle( label: 'MAIN', size: itemSize * 1.5, iconData: Icons.menu, onPressed: toggleMenu, ); - container.setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + container.setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); var numItems = icons.length; var angleStep = Math.PI * 2 / numItems; var angleOffset = -Math.PI / 2; @@ -68,10 +68,10 @@ class SimpleRadialMenuScene extends GSprite { } GSprite createCircle({ - String label, - double size, - IconData iconData, - Function(MouseInputData input) onPressed, + String? label, + required double size, + required IconData iconData, + Function(MouseInputData input)? onPressed, }) { var item = GSprite(); var text = GText( @@ -114,11 +114,11 @@ class SimpleRadialMenuScene extends GSprite { isOpen = !isOpen; for (var i = 0; i < items.length; ++i) { final itm = items[i]; - var point = itm.userData as GPoint; + var point = itm.userData as GPoint?; itm.tween( duration: .3, - x: isOpen ? point.x : 0, - y: isOpen ? point.y : 0, + x: isOpen ? point!.x : 0, + y: isOpen ? point!.y : 0, ); // itm.x = isOpen ? point.x : 0; // itm.y = isOpen ? point.y : 0; diff --git a/example/lib/demos/simple_shape/simple_shapes_scene.dart b/example/lib/demos/simple_shape/simple_shapes_scene.dart index 8b5a098..cac5422 100644 --- a/example/lib/demos/simple_shape/simple_shapes_scene.dart +++ b/example/lib/demos/simple_shape/simple_shapes_scene.dart @@ -2,7 +2,7 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class SimpleShapesScene extends GSprite { - GShape triangle; + late GShape triangle; @override void addedToStage() { diff --git a/example/lib/demos/simple_toast/simple_toast.dart b/example/lib/demos/simple_toast/simple_toast.dart index 139b448..aba105b 100644 --- a/example/lib/demos/simple_toast/simple_toast.dart +++ b/example/lib/demos/simple_toast/simple_toast.dart @@ -18,8 +18,8 @@ class SimpleToastMain extends StatelessWidget { } class MyHomePage extends StatefulWidget { - MyHomePage({Key key, this.title}) : super(key: key); - final String title; + MyHomePage({Key? key, this.title}) : super(key: key); + final String? title; @override _MyHomePageState createState() => _MyHomePageState(); @@ -27,7 +27,7 @@ class MyHomePage extends StatefulWidget { class _MyHomePageState extends State { int _counter = 0; - double bottom; + double? bottom; final tec = TextEditingController(); void _incrementCounter() { @@ -56,7 +56,7 @@ class _MyHomePageState extends State { // sendKeyboardOpenEvent(); return Scaffold( appBar: AppBar( - title: Text(widget.title), + title: Text(widget.title!), ), body: Center( child: Column( diff --git a/example/lib/demos/simple_toast/toast.dart b/example/lib/demos/simple_toast/toast.dart index 62fff4a..8195d0f 100644 --- a/example/lib/demos/simple_toast/toast.dart +++ b/example/lib/demos/simple_toast/toast.dart @@ -6,13 +6,13 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class ToastScene extends GSprite { - GSprite container; - GShape bg; - GSprite button; - GShape buttonGShape; - GText text; - GText buttonText; - GIcon myIcon; + late GSprite container; + late GShape bg; + late GSprite button; + late GShape buttonGShape; + late GText text; + late GText buttonText; + late GIcon myIcon; @override void addedToStage() { @@ -27,7 +27,7 @@ class ToastScene extends GSprite { .drawRoundRect( 0, 0, - stage.stageWidth - 20, + stage!.stageWidth - 20, 60, 10, ) @@ -43,7 +43,7 @@ class ToastScene extends GSprite { final paragraphStyle = ParagraphStyle(maxLines: 2, ellipsis: '...'); text = GText( text: '', - width: stage.stageWidth - 150, + width: stage!.stageWidth - 150, paragraphStyle: paragraphStyle, textStyle: TextStyle(fontSize: 18, color: Colors.white), ) @@ -51,7 +51,7 @@ class ToastScene extends GSprite { ..y = 13; buttonText = GText( text: 'Increment', - width: stage.stageWidth - 150, + width: stage!.stageWidth - 150, paragraphStyle: paragraphStyle, textStyle: TextStyle(fontSize: 14, color: Colors.white), ) @@ -60,7 +60,7 @@ class ToastScene extends GSprite { addChild(container); container ..x = 10 - ..y = stage.stageHeight + 20 + ..y = stage!.stageHeight + 20 ..addChild(bg) ..addChild(text) ..addChild(myIcon) @@ -71,9 +71,9 @@ class ToastScene extends GSprite { void _onShowSnackbar(Map value) { text.text = value['text']; bg.colorize = value['color']; - bg.width = stage.stageWidth - 20; + bg.width = stage!.stageWidth - 20; button - ..x = stage.stageWidth - 120 + ..x = stage!.stageWidth - 120 ..y = 10 ..onMouseClick(value['onMouseClick']); @@ -82,7 +82,7 @@ class ToastScene extends GSprite { void _changeSnackDirection(double bottom) { final open = bottom != 0; - if (container.y <= stage.stageHeight) { + if (container.y <= stage!.stageHeight) { if (open) { show(bottom); } else { @@ -92,7 +92,7 @@ class ToastScene extends GSprite { } void show(double bottom) { - var targetY = (stage.stageHeight - container.height - 10) - bottom; + var targetY = (stage!.stageHeight - container.height - 10) - bottom; container.tween( y: targetY, duration: 1, @@ -111,7 +111,7 @@ class ToastScene extends GSprite { container.tween( duration: 1, ease: GEase.elasticIn, - y: stage.stageHeight + 20, + y: stage!.stageHeight + 20, ); GTween.delayedCall(.8, () { bg.tween( diff --git a/example/lib/demos/simple_tween/simple_tween.dart b/example/lib/demos/simple_tween/simple_tween.dart index 606855d..c1f738c 100644 --- a/example/lib/demos/simple_tween/simple_tween.dart +++ b/example/lib/demos/simple_tween/simple_tween.dart @@ -69,7 +69,7 @@ class _TweenMenu extends StatelessWidget { ); } - Widget _addButton({String label, IconData icon, VoidCallback onPressed}) { + Widget _addButton({required String label, IconData? icon, VoidCallback? onPressed}) { return TextButton( // color: Colors.red, child: Row( diff --git a/example/lib/demos/simple_tween/simple_tween_scene.dart b/example/lib/demos/simple_tween/simple_tween_scene.dart index d9a64f8..c4a9d00 100644 --- a/example/lib/demos/simple_tween/simple_tween_scene.dart +++ b/example/lib/demos/simple_tween/simple_tween_scene.dart @@ -7,21 +7,21 @@ import 'tween_controller.dart'; class SimpleTweenScene extends GSprite { final TweenSceneController controller; - MyBox box; - GSprite centeredContainer; + MyBox? box; + late GSprite centeredContainer; SimpleTweenScene(this.controller); @override void addedToStage() { /// we can colorize the background of the scene. - stage.color = Colors.grey.shade300; + stage!.color = Colors.grey.shade300; /// by default the Canvas drawing in Flutter has no "masking", you can paint /// anywhere on the screen (outside the stage size ). /// so to know which area is available to us, we can mask the stage, like /// culling, all objects outside the stage size, will not be visible. - stage.maskBounds = true; + stage!.maskBounds = true; /// use this Sprite to keep the box always centered in the stage. centeredContainer = GSprite(); @@ -30,13 +30,13 @@ class SimpleTweenScene extends GSprite { /// add the box as child of the container (will inherit all the /// transformations from the parent). - centeredContainer.addChild(box); + centeredContainer.addChild(box!); // add the container to the root scene. addChild(centeredContainer); /// now the box is drawn from the top left corner drawRect(0,0,width,height) /// so we can change the pivots so it centers itself in the parent - box.alignPivot(Alignment.center); + box!.alignPivot(Alignment.center); controller.onRotate.add(_rotateBox); controller.onScale.add(_scaleBox); @@ -46,10 +46,10 @@ class SimpleTweenScene extends GSprite { _initCounter(); /// listen for stage resize events. - stage.onResized.add(_onStageResize); + stage!.onResized.add(_onStageResize); } - GText counterText; + late GText counterText; /// There's support for several native types in GTween. /// double, int, Map, List, DisplayObject, GxPoint, GxRect.. @@ -87,13 +87,13 @@ class SimpleTweenScene extends GSprite { void _moveBox(int dir) { if (dir == 0) { - box.tween(duration: .5, x: 0, ease: GEase.elasticOut); + box!.tween(duration: .5, x: 0, ease: GEase.elasticOut); } else { final relativeMove = 10.0 * dir; /// using Strings we can tween any value relative to the current value /// of the object. - box.tween(duration: .5, x: '$relativeMove'); + box!.tween(duration: .5, x: '$relativeMove'); } } @@ -101,19 +101,19 @@ class SimpleTweenScene extends GSprite { /// kill any running tweens on `box` GTween.killTweensOf(box); - box.tween( + box!.tween( duration: 1, scaleX: 2, ease: GEase.bounceOut, ); - box.tween( + box!.tween( duration: 1, scaleY: 3, delay: .4, ease: GEase.bounceOut, onComplete: () { - box.tween( + box!.tween( duration: .4, scale: 1, // scale modifies scaleX, scaleY proportionally. ease: GEase.easeOutBack, @@ -125,12 +125,12 @@ class SimpleTweenScene extends GSprite { /// kill any running tweens on `box` GTween.killTweensOf(box); - box.tween( + box!.tween( duration: 1.5, rotation: Math.PI_2, // radians, or use `deg2rad(360)` ease: GEase.easeInOutExpo, onComplete: () { - box.tween( + box!.tween( duration: .5, rotation: 0, // radians, or use `deg2rad(360)` ease: GEase.easeOutBack, @@ -142,8 +142,8 @@ class SimpleTweenScene extends GSprite { void _onStageResize() { /// center in the Stage. centeredContainer.setPosition( - stage.stageWidth / 2, - stage.stageHeight / 2, + stage!.stageWidth / 2, + stage!.stageHeight / 2, ); } } diff --git a/example/lib/demos/sorting_button/scene/root_scene.dart b/example/lib/demos/sorting_button/scene/root_scene.dart index 6c3e20b..0c2f399 100644 --- a/example/lib/demos/sorting_button/scene/root_scene.dart +++ b/example/lib/demos/sorting_button/scene/root_scene.dart @@ -1,4 +1,5 @@ import 'package:exampleGraphx/utils/utils.dart'; + /// roipeker 2021 /// just wrap ur app with this, to emit "global" events (and close the dropdown) @@ -9,8 +10,8 @@ import 'package:exampleGraphx/utils/utils.dart'; import 'package:graphx/graphx.dart'; class RootWidget extends StatelessWidget { - final Widget child; - const RootWidget({Key key, this.child}) : super(key: key); + final Widget? child; + const RootWidget({Key? key, this.child}) : super(key: key); @override Widget build(BuildContext context) { @@ -24,15 +25,15 @@ class RootWidget extends StatelessWidget { class RootScene extends GSprite { @override void dispose() { - stage?.onMouseDown?.removeAll(); + stage?.onMouseDown.removeAll(); mps.offAll('windowMouseDown'); super.dispose(); } @override void addedToStage() { - stage.onMouseDown.add((event) { - mps.emit1('windowMouseDown', event.rawEvent.windowPosition); + stage!.onMouseDown.add((event) { + mps.emit1('windowMouseDown', event.rawEvent!.windowPosition); }); } } diff --git a/example/lib/demos/sorting_button/scene/sorting_button_scene.dart b/example/lib/demos/sorting_button/scene/sorting_button_scene.dart index 8102e8b..ab167b9 100644 --- a/example/lib/demos/sorting_button/scene/sorting_button_scene.dart +++ b/example/lib/demos/sorting_button/scene/sorting_button_scene.dart @@ -8,27 +8,27 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class SortingButtonScene extends GSprite { - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; @override void dispose() { - stage?.onMouseDown?.removeAll(); + stage?.onMouseDown.removeAll(); super.dispose(); } @override void addedToStage() { - stage.color = const Color(0xffdededede); + stage!.color = const Color(0xffdededede); var btn = SortingButton(195, 50); /// as we need to detect global touches on the window, we listen the event /// from a "root" scene on top of MaterialApp. var lastPress = 0; - stage.onMouseDown.add((event) { + stage!.onMouseDown.add((event) { lastPress = getTimer(); - if (!btn.bounds.containsPoint(btn.mousePosition)) { + if (!btn.bounds!.containsPoint(btn.mousePosition)) { if (btn.isOpen) btn.closeDropdown(); } }); @@ -52,18 +52,18 @@ class SortingButton extends GSprite { ]; double w, h; - GSprite options; - GShape bg, menuMask, clickArea; - GText label, sortBy; - GIcon arrow; + late GSprite options; + GShape? bg, menuMask, clickArea; + late GText label, sortBy; + late GIcon arrow; double labelPaddingX = 18; - double labelMaxW; + late double labelMaxW; bool isOpen = false; double optionH = 40; double optionSep = 0; - double menuOpenH; + late double menuOpenH; final tweenMenuSize = 0.0.twn; int _selectedIndex = -1; final highlighColor = const Color(0xff99979D); @@ -93,15 +93,15 @@ class SortingButton extends GSprite { menuMask = GShape(); bg = GShape(); clickArea = GShape(); - addChild(bg); - addChild(menuMask); - addChild(clickArea); + addChild(bg!); + addChild(menuMask!); + addChild(clickArea!); tweenMenuSize.value = h; - drawBackground(bg.graphics, h, 5, Colors.black); - drawBackground(menuMask.graphics, h, 5, Colors.black); - drawBackground(clickArea.graphics, h, 0, Colors.red.withOpacity(.4)); + drawBackground(bg!.graphics, h, 5, Colors.black); + drawBackground(menuMask!.graphics, h, 5, Colors.black); + drawBackground(clickArea!.graphics, h, 0, Colors.red.withOpacity(.4)); - clickArea.alpha = 0; + clickArea!.alpha = 0; arrow = GIcon(Icons.arrow_back_ios, Colors.white, 14); arrow.alignPivot(Alignment.centerLeft); @@ -132,14 +132,14 @@ class SortingButton extends GSprite { ); sortBy.mouseEnabled = false; arrow.mouseEnabled = - label.mouseEnabled = menuMask.mouseEnabled = bg.mouseEnabled = false; + label.mouseEnabled = menuMask!.mouseEnabled = bg!.mouseEnabled = false; options = GSprite(); addChild(options); options.y = h; options.mask = menuMask; _createOptions(); - clickArea.onMouseDown.add(_onMousePress); + clickArea!.onMouseDown.add(_onMousePress); _selectItem(0); } @@ -152,7 +152,7 @@ class SortingButton extends GSprite { } var offset = 14.0; - bg.tween( + bg!.tween( duration: .25, width: w + offset, height: h + offset, @@ -161,12 +161,12 @@ class SortingButton extends GSprite { ease: GEase.easeOutQuart, overwrite: 0, ); - stage.onMouseUp.addOnce(_onMouseUp); + stage!.onMouseUp.addOnce(_onMouseUp); } void _onMouseUp(MouseInputData event) { GTween.killTweensOf(_delayedOpen); - bg.tween( + bg!.tween( duration: 1.3, width: w, height: h, @@ -181,7 +181,7 @@ class SortingButton extends GSprite { void _delayedOpen() { GTween.killTweensOf(bg); - bg.setProps(scale: 1, x: 0, y: 0); + bg!.setProps(scale: 1, x: 0, y: 0); GTween.killTweensOf(tweenMenuSize); openDropdown(); } @@ -190,16 +190,16 @@ class SortingButton extends GSprite { if (_selectedIndex == idx) return; if (_selectedIndex > -1) { var o = items[_selectedIndex]; - var dot = o.getChildByName('dot'); - var label = o.getChildByName('label'); + var dot = o.getChildByName('dot')!; + var label = o.getChildByName('label')!; dot.tween(duration: .2, x: labelPaddingX / 2, alpha: 0); label.tween(duration: .2, x: labelPaddingX); } _selectedIndex = idx; if (_selectedIndex > -1) { var o = items[_selectedIndex]; - var dot = o.getChildByName('dot'); - var label = o.getChildByName('label'); + var dot = o.getChildByName('dot')!; + var label = o.getChildByName('label')!; dot.tween(duration: .4, x: labelPaddingX, alpha: 1); label.tween(duration: .4, x: labelPaddingX + 10); } @@ -223,13 +223,13 @@ class SortingButton extends GSprite { arrow.tween(duration: .6, alpha: 1, overwrite: 0); sortBy.tween(duration: .8, alpha: 1); _writeLabel(dataModel[_selectedIndex]); - bg.tween(duration: .4, y: 0); + bg!.tween(duration: .4, y: 0); }); /// make background bounce a few times. void _bounceBg() { - var ty = bg.y > 0 ? -1.5 : 3; - bg.tween( + var ty = bg!.y > 0 ? -1.5 : 3; + bg!.tween( duration: .16, y: ty, onComplete: _bounceBg, @@ -302,7 +302,7 @@ class SortingButton extends GSprite { }); itm.onMouseDown.add((event) { subBg.tween(duration: .3, alpha: .5); - stage.onMouseUp.addOnce((event) { + stage!.onMouseUp.addOnce((event) { if (event.dispatcher == itm) { subBg.tween(duration: .3, alpha: .25); _selectItem(i); @@ -337,8 +337,8 @@ class SortingButton extends GSprite { duration: .7, ease: GEase.fastLinearToSlowEaseIn, onUpdate: () { - drawBackground(bg.graphics, tweenMenuSize.value, 5); - drawBackground(menuMask.graphics, tweenMenuSize.value, 5); + drawBackground(bg!.graphics, tweenMenuSize.value, 5); + drawBackground(menuMask!.graphics, tweenMenuSize.value, 5); }, ); final len = items.length; @@ -357,7 +357,7 @@ class SortingButton extends GSprite { void openDropdown() { if (isOpen) return; isOpen = true; - bg.setProps(scale: 1, x: 0, y: 0); + bg!.setProps(scale: 1, x: 0, y: 0); arrow.tween( duration: .4, rotation: deg2rad(isOpen ? 90 : 360.0 - 90), @@ -369,8 +369,8 @@ class SortingButton extends GSprite { duration: 2, ease: GEase.fastLinearToSlowEaseIn, onUpdate: () { - drawBackground(bg.graphics, tweenMenuSize.value, 5); - drawBackground(menuMask.graphics, tweenMenuSize.value, 5); + drawBackground(bg!.graphics, tweenMenuSize.value, 5); + drawBackground(menuMask!.graphics, tweenMenuSize.value, 5); }, ); @@ -387,14 +387,14 @@ class SortingButton extends GSprite { } GText createLabel({ - String text, - double targetW, - double containerH, + String? text, + required double targetW, + double? containerH, double letterSpacing = 0.2, - double fontSize, + double? fontSize, Color color = Colors.white, FontWeight weight = FontWeight.w600, - GSprite doc, + GSprite? doc, }) { var tf = GText( text: text, diff --git a/example/lib/demos/spiral_loader/spiral_loader_scene.dart b/example/lib/demos/spiral_loader/spiral_loader_scene.dart index bceda80..1a6b0a0 100644 --- a/example/lib/demos/spiral_loader/spiral_loader_scene.dart +++ b/example/lib/demos/spiral_loader/spiral_loader_scene.dart @@ -2,12 +2,12 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class DnaScene extends GSprite { - double spiralRadius, centerX, centerY, centerZ; + double spiralRadius = 0.0, centerX = 0.0, centerY = 0.0, centerZ = 0.0; double fl = 120; - List dots; - Bar bar; - GSprite container; + late List dots; + late Bar bar; + late GSprite container; double sizeCounter = 0; @override @@ -25,7 +25,7 @@ class DnaScene extends GSprite { bar = Bar(); container.addChild(bar); bar.x = 30; - container.y = stage.stageHeight / 2; + container.y = stage!.stageHeight / 2; } @override @@ -33,7 +33,7 @@ class DnaScene extends GSprite { super.update(delta); sizeCounter += delta; - centerX = stage.stageWidth / 2; + centerX = stage!.stageWidth / 2; centerY = 0; //stage.stageHeight / 2; centerZ = 160.0; bar.pz = centerZ; diff --git a/example/lib/demos/splash_intro/scene/logo_drawer.dart b/example/lib/demos/splash_intro/scene/logo_drawer.dart index b2e9160..a916719 100644 --- a/example/lib/demos/splash_intro/scene/logo_drawer.dart +++ b/example/lib/demos/splash_intro/scene/logo_drawer.dart @@ -12,17 +12,15 @@ import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:graphx/graphx.dart'; -import '../../../utils/svg_utils.dart'; - /// GSprite that will hold a SVG path drawing with a /// filled and outlined version... and the ability to partially /// draw the outlined based on percentage. class LogoDrawer extends GSprite { - List _metricsList; - Path _rootPath; + late List _metricsList; + late Path _rootPath; - GShape line; - GShape fill; + late GShape line; + late GShape fill; LogoDrawer() { _init(); @@ -53,11 +51,11 @@ class LogoDrawer extends GSprite { drawPercent(1); } - void drawPercent(double percent) { + void drawPercent(double? percent) { line.graphics.clear(); line.graphics.lineStyle(1, Colors.white); for (var m in _metricsList) { - line.graphics.drawPath(m.extractPath(0, m.length * percent)); + line.graphics.drawPath(m.extractPath(0, m.length * percent!)); } line.graphics.endFill(); } diff --git a/example/lib/demos/splash_intro/scene/splash_scene.dart b/example/lib/demos/splash_intro/scene/splash_scene.dart index 9ac1de9..f241540 100644 --- a/example/lib/demos/splash_intro/scene/splash_scene.dart +++ b/example/lib/demos/splash_intro/scene/splash_scene.dart @@ -18,22 +18,22 @@ abstract class DemoEvents { } class SplashScene extends GSprite { - GSprite logoContainer; - GShape splashCircle; - LogoDrawer graphxLogo, byLogo, roipekerLogo, flutterLogo; + GSprite? logoContainer; + late GShape splashCircle; + late LogoDrawer graphxLogo, byLogo, roipekerLogo, flutterLogo; @override void addedToStage() { visible = false; - stage.onResized.add(_handleStageResize); + stage!.onResized.add(_handleStageResize); mps.on(DemoEvents.reset, _showDemo); loadSvg(); } void _handleStageResize() { /// keep the logo centered. - logoContainer?.x = stage.stageWidth / 2; - logoContainer?.y = stage.stageHeight / 2; + logoContainer?.x = stage!.stageWidth / 2; + logoContainer?.y = stage!.stageHeight / 2; } void _showDemo() { @@ -41,12 +41,12 @@ class SplashScene extends GSprite { splashCircle.graphics.clear(); splashCircle.graphics.beginFill(Colors.redAccent); - splashCircle.graphics.drawCircle(0, 0, stage.stageWidth); + splashCircle.graphics.drawCircle(0, 0, stage!.stageWidth); splashCircle.graphics.endFill(); splashCircle.scale = 0; - stage.color = kColorTransparent; - stage.addChild(splashCircle); - splashCircle.setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + stage!.color = kColorTransparent; + stage!.addChild(splashCircle); + splashCircle.setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); splashCircle.tween( duration: 1, @@ -64,7 +64,7 @@ class SplashScene extends GSprite { splashCircle = GShape(); logoContainer = GSprite(); - addChild(logoContainer); + addChild(logoContainer!); graphxLogo = await buildLogo(graphxSvgString); byLogo = await buildLogo(bySvgString); @@ -121,15 +121,15 @@ class SplashScene extends GSprite { roipekerLogo.line.visible = true; flutterLogo.line.visible = true; - logoContainer.alignPivot(); - logoContainer.x = stage.stageWidth / 2; - logoContainer.y = stage.stageHeight / 2; + logoContainer!.alignPivot(); + logoContainer!.x = stage!.stageWidth / 2; + logoContainer!.y = stage!.stageHeight / 2; } void _runDemo() { mps.emit1(DemoEvents.run, true); visible = true; - stage.color = Colors.redAccent; + stage!.color = Colors.redAccent; _resetObjects(); var t1 = 0.0.twn; var t2 = 0.0.twn; @@ -251,11 +251,11 @@ class SplashScene extends GSprite { void _showGlobalMask() { splashCircle.graphics.clear(); splashCircle.graphics.beginFill(Colors.white); - splashCircle.graphics.drawCircle(0, 0, stage.stageWidth); + splashCircle.graphics.drawCircle(0, 0, stage!.stageWidth); splashCircle.graphics.endFill(); - stage.addChild(splashCircle); + stage!.addChild(splashCircle); splashCircle.scale = 0.1; - splashCircle.setPosition(stage.stageWidth / 2, stage.stageHeight / 2); + splashCircle.setPosition(stage!.stageWidth / 2, stage!.stageHeight / 2); splashCircle.tween( duration: .45, scale: 1, @@ -268,8 +268,8 @@ class SplashScene extends GSprite { } void showFlutter() { - stage.addChild(splashCircle); - stage.color = kColorTransparent; + stage!.addChild(splashCircle); + stage!.color = kColorTransparent; splashCircle.tween( duration: .4, scale: 0, @@ -321,7 +321,7 @@ class SplashScene extends GSprite { Future buildLogo(String word) async { var logo = LogoDrawer(); await logo.parseSvg(word); - logoContainer.addChild(logo); + logoContainer!.addChild(logo); return logo; } } diff --git a/example/lib/demos/submit_button/scene/my_button.dart b/example/lib/demos/submit_button/scene/my_button.dart index 4a23a91..60c03b9 100644 --- a/example/lib/demos/submit_button/scene/my_button.dart +++ b/example/lib/demos/submit_button/scene/my_button.dart @@ -3,15 +3,15 @@ import 'package:graphx/graphx.dart'; class MyButton extends GSprite { double w, h; - GShape bg, border1, border2; - GIcon successIco; + late GShape bg, border1, border2; + late GIcon successIco; - GText label; + late GText label; final Color mainColor = const Color(0xff58A993); final Color greyColor = const Color(0xffE3E3E3); final tweenWidth = 0.0.twn; - double currentW; - double percentLoaded = 0.0; + double? currentW; + double? percentLoaded = 0.0; double lineThickness = 4; MyButton(this.w, this.h) { @@ -53,7 +53,7 @@ class MyButton extends GSprite { void _onMousePress(event) { bg.tween(duration: .3, colorize: mainColor); label.tween(duration: .2, colorize: Colors.white, scale: .9); - stage.onMouseUp.addOnce(_onMouseUp); + stage!.onMouseUp.addOnce(_onMouseUp); } void _onMouseUp(event) { @@ -85,7 +85,7 @@ class MyButton extends GSprite { void setToProgress() { percentLoaded = 0; - final tweenProgress = percentLoaded.twn; + final tweenProgress = percentLoaded!.twn; tweenProgress.tween( 1.0, duration: 1.3, @@ -138,7 +138,7 @@ class MyButton extends GSprite { border2.graphics .clear() .lineStyle(lineThickness, mainColor) - .arc(0, 0, radius, -Math.PI / 2, Math.PI_2 * percentLoaded) + .arc(0, 0, radius, -Math.PI / 2, Math.PI_2 * percentLoaded!) .endFill(); } @@ -146,22 +146,22 @@ class MyButton extends GSprite { bg.graphics .clear() .beginFill(Colors.white) - .drawRoundRect(-currentW / 2, -h / 2, currentW, h, h / 2) + .drawRoundRect(-currentW! / 2, -h / 2, currentW!, h, h / 2) .endFill(); var lineWOffset = lineThickness / 2; border1.graphics .clear() .beginFill(kColorTransparent) .drawRoundRect( - -currentW / 2 - lineWOffset, + -currentW! / 2 - lineWOffset, -h / 2 - lineWOffset, - currentW + lineWOffset * 2, + currentW! + lineWOffset * 2, h + lineWOffset * 2, h / 2, ) .endFill() .lineStyle(lineThickness, mainColor) - .drawRoundRect(-currentW / 2, -h / 2, currentW, h, h / 2) + .drawRoundRect(-currentW! / 2, -h / 2, currentW!, h, h / 2) .endFill(); bg.alignPivot(); border1.alignPivot(); diff --git a/example/lib/demos/submit_button/scene/scene.dart b/example/lib/demos/submit_button/scene/scene.dart index 43da541..9f81fce 100644 --- a/example/lib/demos/submit_button/scene/scene.dart +++ b/example/lib/demos/submit_button/scene/scene.dart @@ -7,7 +7,7 @@ import 'my_button.dart'; class SubmitButtonScene extends GSprite { @override void addedToStage() { - var btn = MyButton(stage.stageWidth, stage.stageHeight); + var btn = MyButton(stage!.stageWidth, stage!.stageHeight); addChild(btn); } } diff --git a/example/lib/demos/svg_icons/test_icons.dart b/example/lib/demos/svg_icons/test_icons.dart index 96fbe99..3bdf542 100644 --- a/example/lib/demos/svg_icons/test_icons.dart +++ b/example/lib/demos/svg_icons/test_icons.dart @@ -44,7 +44,7 @@ class TestIcons extends GSprite { begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [Colors.red, Colors.blue], - ).createShader(icon3.bounds.toNative()); + ).createShader(icon3.bounds!.toNative()); // take the bounding box from the icon. // GraphX has a nifty method to check bounding boxes. // icon3.$debugBounds = true; diff --git a/example/lib/demos/svg_icons/test_svg_scene.dart b/example/lib/demos/svg_icons/test_svg_scene.dart index ecd5432..098f860 100644 --- a/example/lib/demos/svg_icons/test_svg_scene.dart +++ b/example/lib/demos/svg_icons/test_svg_scene.dart @@ -2,15 +2,14 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; import '../../assets/svg_icons.dart'; -import '../../utils/svg_utils.dart'; class TestSvgScene extends GSprite { final groundHeight = 100.0; - GSprite trees, ground; + late GSprite trees, ground; @override void addedToStage() { - stage.color = Colors.lightBlueAccent.shade100; + stage!.color = Colors.lightBlueAccent.shade100; _init(); } @@ -23,8 +22,8 @@ class TestSvgScene extends GSprite { addChild(trees); addChild(ground); - trees.y = stage.stageHeight - groundHeight; - ground.y = stage.stageHeight - groundHeight; + trees.y = stage!.stageHeight - groundHeight; + ground.y = stage!.stageHeight - groundHeight; _drawTrees(); _drawGround(); @@ -35,9 +34,9 @@ class TestSvgScene extends GSprite { // add the sun. var sun = getSvgIcon(SvgId.cloudy); sun.alignPivot(); - sun.width = stage.stageWidth / 2; + sun.width = stage!.stageWidth / 2; sun.scaleY = sun.scaleX; - sun.setPosition(stage.stageWidth / 2, sun.height / 2); + sun.setPosition(stage!.stageWidth / 2, sun.height / 2); addChild(sun); } @@ -77,7 +76,7 @@ class TestSvgScene extends GSprite { // .beginFill(0xFFE477) // .beginFill(0xFCF2B6) .beginFill(Colors.green) - .drawRect(0, 0, stage.stageWidth, groundHeight) + .drawRect(0, 0, stage!.stageWidth, groundHeight) .endFill(); /// add some ground objects. @@ -86,7 +85,7 @@ class TestSvgScene extends GSprite { var obj = getSvgIcon(objectId); obj.alignPivot(Alignment.bottomCenter); obj.y = Math.randomRange(20, groundHeight); - obj.x = Math.randomRange(20, stage.stageWidth - 20); + obj.x = Math.randomRange(20, stage!.stageWidth - 20); obj.scale = Math.randomRange(.8, 1.5); if (objectId == SvgId.snail) { /// DisplayObjects has a userData property so u can save custom stuffs @@ -109,7 +108,7 @@ class TestSvgScene extends GSprite { /// if the snail is outside the stage area... move it to the /// other side of the screen. - if (snail.x > stage.stageWidth) { + if (snail.x > stage!.stageWidth) { snail.x = -100; } @@ -120,7 +119,7 @@ class TestSvgScene extends GSprite { onComplete: () => _tweenSnail(snail), ); - double originalScale = snail.userData; + double originalScale = snail.userData as double; /// scale down 80% snail.tween( @@ -144,7 +143,7 @@ class TestSvgScene extends GSprite { addChild(leaf); - var px = Math.randomRange(10, stage.stageWidth - 10); + var px = Math.randomRange(10, stage!.stageWidth - 10); leaf.setPosition(px, -10); final rndPivot = Math.randomBool() ? Alignment.bottomCenter : Alignment.topCenter; @@ -167,7 +166,7 @@ class TestSvgScene extends GSprite { } } - void _tweenLeaf({int dir, GDisplayObject leaf}) { + void _tweenLeaf({required int dir, required GDisplayObject leaf}) { final randomRotation = Math.randomRange(10, 45.0) * dir; final randomDuration = Math.randomRange(.75, 1); final randomSkew = Math.randomRange(.1, .3) * -dir; @@ -177,7 +176,7 @@ class TestSvgScene extends GSprite { skewX: randomSkew, skewY: -randomSkew / 2, onComplete: () { - if (leaf.y > stage.stageHeight) { + if (leaf.y > stage!.stageHeight) { print('Leaf outside of stage, remove and dispose it.'); leaf.removeFromParent(true); } else { diff --git a/example/lib/demos/trigrid/scene/scene.dart b/example/lib/demos/trigrid/scene/scene.dart index 0b81eb5..e8f3741 100644 --- a/example/lib/demos/trigrid/scene/scene.dart +++ b/example/lib/demos/trigrid/scene/scene.dart @@ -16,30 +16,30 @@ class DrawTriangleGridScene extends GSprite { double sep = 50 / res; int cols = 5 * res, rows = 4 * res; double spring = .0025, stiff = .02, damp = .98, radius = targetRadius; - double radiusSq; + late double radiusSq; - List dots; - TriangleGrid triGrid; - GSprite container; + late List dots; + TriangleGrid? triGrid; + late GSprite container; @override Future addedToStage() async { - stage.color = Colors.grey.shade800; + stage!.color = Colors.grey.shade800; container = GSprite(); addChild(container); mouseChildren = false; - var texture = await ResourceLoader.loadTexture( - 'assets/trigrid/cute_dog.png', 1, 'dog'); + var texture = await (ResourceLoader.loadTexture( + 'assets/trigrid/cute_dog.png', 1, 'dog') as Future); - cols = texture.width ~/ sep; - rows = texture.height ~/ sep; + cols = texture.width! ~/ sep; + rows = texture.height! ~/ sep; var total = cols * rows; dots = List.generate(total, (index) { var d = GraphPoint(); - var idx = index % cols ?? 0; - var idy = index ~/ cols ?? 0; + var idx = index % cols; + var idy = index ~/ cols; if (index == 0) { d.tx = d.x = 0; d.ty = d.y = 0; @@ -53,21 +53,21 @@ class DrawTriangleGridScene extends GSprite { triGrid = TriangleGrid(res: sep, cols: cols, rows: rows); /// show the triangles lines - triGrid.debugTriangles = true; + triGrid!.debugTriangles = true; - container.addChildAt(triGrid, 0); - triGrid.texture = texture; - triGrid.draw(); + container.addChildAt(triGrid!, 0); + triGrid!.texture = texture; + triGrid!.draw(); } void adjustContainer() { /// resize container based on the image dimensions. - var tw = triGrid.texture.width; - var th = triGrid.texture.height; - var scaleTo = stage.stageHeight / th; + var tw = triGrid!.texture!.width!; + var th = triGrid!.texture!.height!; + var scaleTo = stage!.stageHeight / th; container.y = 0; container.scale = scaleTo; - container.x = (stage.stageWidth - (tw * scaleTo)) / 2; + container.x = (stage!.stageWidth - (tw * scaleTo)) / 2; } @override @@ -80,14 +80,14 @@ class DrawTriangleGridScene extends GSprite { } void renderPoints() { - var ver = triGrid.vertices; + var ver = triGrid!.vertices; var j = 0; for (var i = 0; i < dots.length; ++i) { var d = dots[i]; - ver[j++] = d.x; + ver![j++] = d.x; ver[j++] = d.y; } - triGrid.draw(); + triGrid!.draw(); } void updatePoints() { @@ -97,7 +97,7 @@ class DrawTriangleGridScene extends GSprite { // container.x = (sw - cols * sep) / 2; // container.y = (sh - rows * sep) / 2; - if (stage.pointer.isDown) { + if (stage!.pointer!.isDown) { radius = -targetRadius / 4; } else { radius = targetRadius; diff --git a/example/lib/demos/trigrid/scene/tri_grid.dart b/example/lib/demos/trigrid/scene/tri_grid.dart index 0d10474..b5f2a27 100644 --- a/example/lib/demos/trigrid/scene/tri_grid.dart +++ b/example/lib/demos/trigrid/scene/tri_grid.dart @@ -7,10 +7,10 @@ class TriangleGrid extends GShape { int rows, cols; bool debugTriangles = false; - GTexture texture; + GTexture? texture; TriangleGrid({ - GSprite doc, + GSprite? doc, this.res = 10, this.cols = 5, this.rows = 5, @@ -20,22 +20,22 @@ class TriangleGrid extends GShape { draw(); } - List vertices; - List uvData; - List indices; + List? vertices; + List? uvData; + List? indices; void draw() { graphics.clear(); if (texture != null) { graphics - .beginBitmapFill(texture, null, false, true) - .drawTriangles(vertices, indices, uvData) + .beginBitmapFill(texture!, null, false, true) + .drawTriangles(vertices!, indices, uvData) .endFill(); } if (debugTriangles) { graphics .lineStyle(0, Colors.white30) - .drawTriangles(vertices, indices, uvData) + .drawTriangles(vertices!, indices, uvData) .endFill(); } } @@ -48,18 +48,18 @@ class TriangleGrid extends GShape { for (var c = 0; c < total; ++c) { var i = c ~/ cols; var j = c % cols; - vertices.addAll([j * res, i * res]); - uvData.addAll([ + vertices!.addAll([j * res, i * res]); + uvData!.addAll([ j / (cols - 1), i / (rows - 1), ]); if (i < rows - 1 && j < cols - 1) { ///first tri - indices.addAll([i * cols + j, i * cols + j + 1, (i + 1) * cols + j]); + indices!.addAll([i * cols + j, i * cols + j + 1, (i + 1) * cols + j]); ///first tri - indices.addAll( + indices!.addAll( [i * cols + j + 1, (i + 1) * cols + j + 1, (i + 1) * cols + j]); } } diff --git a/example/lib/demos/universo_flutter_intro/scene.dart b/example/lib/demos/universo_flutter_intro/scene.dart index d1d4f67..2188cf8 100644 --- a/example/lib/demos/universo_flutter_intro/scene.dart +++ b/example/lib/demos/universo_flutter_intro/scene.dart @@ -4,21 +4,21 @@ import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; class UniversoFlutterScene extends GSprite { - GSprite logo, fLogo; - GShape planetCirc, ringBack, ringFront; - GShape fLogo1, fLogo2, fLogo3; + late GSprite logo, fLogo; + late GShape planetCirc, ringBack, ringFront; + GShape? fLogo1, fLogo2, fLogo3; @override void addedToStage() { - stage.color = Color(0xff212121); - stage.maskBounds = true; - stage.showBoundsRect = true; + stage!.color = Color(0xff212121); + stage!.maskBounds = true; + stage!.showBoundsRect = true; _buildLogo(); } - double get sw => stage.stageWidth; + double get sw => stage!.stageWidth; - double get sh => stage.stageHeight; + double get sh => stage!.stageHeight; void _buildLogo() { _buildStars(); @@ -52,8 +52,8 @@ class UniversoFlutterScene extends GSprite { fLogo1 = _buildPill(fLogo, 144, fH); fLogo2 = _buildPill(fLogo, 97, fH); fLogo3 = _buildPill(fLogo, 97, fH); - fLogo2.rotation = deg2rad(90); - fLogo2.y = fLogo3.y = 54; + fLogo2!.rotation = deg2rad(90); + fLogo2!.y = fLogo3!.y = 54; fLogo.alignPivot(); fLogo.y -= 54; @@ -137,9 +137,9 @@ class UniversoFlutterScene extends GSprite { fLogo.setProps(rotation: 0); - fLogo1.setProps(scaleX: 0.5, scaleY: .7, alpha: 0, rotation: 1.9); - fLogo2.setProps(scaleX: 0.2, scaleY: .5, alpha: 0, rotation: 0); - fLogo3.setProps(scaleX: 0.6, scaleY: .2, alpha: 0, rotation: rot); + fLogo1!.setProps(scaleX: 0.5, scaleY: .7, alpha: 0, rotation: 1.9); + fLogo2!.setProps(scaleX: 0.2, scaleY: .5, alpha: 0, rotation: 0); + fLogo3!.setProps(scaleX: 0.6, scaleY: .2, alpha: 0, rotation: rot); logo.tween(duration: 1.6, scale: 1, rotation: 0, ease: GEase.easeInOutCirc); planetCirc.tween(duration: 2.5, alpha: 1, ease: GEase.easeInSine); @@ -158,14 +158,14 @@ class UniversoFlutterScene extends GSprite { alpha: 1, ); - fLogo1.tween( + fLogo1!.tween( duration: .4, delay: .4, scale: 1, alpha: 1, overwrite: 0, ); - fLogo1.tween( + fLogo1!.tween( duration: .8, delay: .6, rotation: 0, @@ -173,14 +173,14 @@ class UniversoFlutterScene extends GSprite { overwrite: 0, ); - fLogo2.tween( + fLogo2!.tween( delay: .9, duration: .4, scale: 1, alpha: 1, overwrite: 0, ); - fLogo2.tween( + fLogo2!.tween( delay: .9, duration: .7, rotation: rot, @@ -188,14 +188,14 @@ class UniversoFlutterScene extends GSprite { overwrite: 0, ); - fLogo3.tween( + fLogo3!.tween( delay: 1, duration: .5, scale: 1, alpha: 1, overwrite: 0, ); - fLogo3.tween( + fLogo3!.tween( delay: 1, duration: .7, rotation: 0, diff --git a/example/lib/demos/xmas/xmas.dart b/example/lib/demos/xmas/xmas.dart index 9658465..42edeef 100644 --- a/example/lib/demos/xmas/xmas.dart +++ b/example/lib/demos/xmas/xmas.dart @@ -9,7 +9,7 @@ import 'package:graphx/graphx.dart'; import 'xmas_scene.dart'; class XmasMain extends StatefulWidget { - XmasMain({Key key}) : super(key: key); + XmasMain({Key? key}) : super(key: key); @override _XmasMainState createState() => _XmasMainState(); } @@ -47,7 +47,7 @@ class _XmasMainState extends State { ), Text( '$_counter', - style: Theme.of(context).textTheme.headline4.copyWith( + style: Theme.of(context).textTheme.headline4!.copyWith( shadows: [ Shadow( color: Colors.black.withOpacity(.7), diff --git a/example/lib/demos/xmas/xmas_scene.dart b/example/lib/demos/xmas/xmas_scene.dart index 2b214a0..29f458f 100644 --- a/example/lib/demos/xmas/xmas_scene.dart +++ b/example/lib/demos/xmas/xmas_scene.dart @@ -10,9 +10,9 @@ import 'package:graphx/graphx.dart'; class SnowScene extends GSprite { int numTextureVariants = 6; int numFlakes = 100; - final List _textures = []; - List flakes; - Timer _snowDirectionTimer; + final List _textures = []; + List flakes = []; + late Timer _snowDirectionTimer; @override Future addedToStage() async { @@ -28,8 +28,8 @@ class SnowScene extends GSprite { var flake = Snowflake(texture); addChild(flake); flake.setPosition( - Math.randomRange(0, stage.stageWidth), - Math.randomRange(0, stage.stageHeight), + Math.randomRange(0, stage!.stageWidth), + Math.randomRange(0, stage!.stageHeight), ); return flake; }); @@ -59,12 +59,12 @@ class SnowScene extends GSprite { flake.y += flake.velY; /// check the stage bounds (Scaffold::body) - if (flake.y > stage.stageHeight) { + if (flake.y > stage!.stageHeight) { flake.y = -flake.height; } if (flake.x < -flake.width) { - flake.x = stage.stageWidth; - } else if (flake.x > stage.stageWidth) { + flake.x = stage!.stageWidth; + } else if (flake.x > stage!.stageWidth) { flake.x = -flake.width; } }); @@ -89,10 +89,10 @@ class Snowflake extends GBitmap { minVelY = .5, maxVelY = 2.5; - double velY, velX; + double velY = 0.0, velX = 0.0; /// GBitmap requires the Texture in the constructor. - Snowflake(GTexture texture) : super(texture) { + Snowflake(GTexture? texture) : super(texture) { _init(); } diff --git a/example/lib/main.dart b/example/lib/main.dart index 6bdee0c..906222a 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -36,7 +36,10 @@ void main() { // home: SimpleRadialMenuMain(), // home: MuratCoffeeMain(), // home: PieChartMain(), + + //TODO doesn't work // home: ChartBezierMain(), + // home: RunHeroCanvasMain(), // home: ElasticBandMain(), // home: FlowerGradientMain(), @@ -47,14 +50,20 @@ void main() { // home: PizzaBoxMain(), // home: DrawingPadBezierMain(), // home: IsmaChartMain(), + + //TODO doesn't work // home: TriGridMain(), + // home: NicoLoadingIndicatorMain(), // home: FeelingSwitchMain(), // home: MouseRepulsionMain(), // home: Globe3dMain(), // home: LungsAnimationMain(), // home: PathChartStressTestMain(), + + //TODO doesn't work // home: ExpanderFabMenu(), + home: PageIndicatorMain(), ), ); diff --git a/example/lib/utils/base_scene.dart b/example/lib/utils/base_scene.dart index 88f09ce..af361cd 100644 --- a/example/lib/utils/base_scene.dart +++ b/example/lib/utils/base_scene.dart @@ -4,7 +4,7 @@ class BaseScene extends GSprite { double get sw => stage?.stageWidth ?? 0; double get sh => stage?.stageHeight ?? 0; - BaseScene([GSprite doc]) { + BaseScene([GSprite? doc]) { doc?.addChild(this); } } diff --git a/example/lib/utils/demo_scene_widget.dart b/example/lib/utils/demo_scene_widget.dart index 860001b..9e3d71b 100644 --- a/example/lib/utils/demo_scene_widget.dart +++ b/example/lib/utils/demo_scene_widget.dart @@ -4,13 +4,13 @@ import 'package:graphx/graphx.dart'; class DemoSingleSceneWidget extends StatelessWidget { final GSprite root; final String title; - final Widget child; - final SceneConfig config; + final Widget? child; + final SceneConfig? config; const DemoSingleSceneWidget({ - Key key, - @required this.root, - @required this.title, + Key? key, + required this.root, + required this.title, this.config, this.child, }) : super(key: key); @@ -19,7 +19,7 @@ class DemoSingleSceneWidget extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text(title ?? 'GraphX demo'), + title: Text(title), ), /// takes the entire body area. diff --git a/example/lib/utils/svg_utils.dart b/example/lib/utils/svg_utils.dart index d9f75ae..57f0c9a 100644 --- a/example/lib/utils/svg_utils.dart +++ b/example/lib/utils/svg_utils.dart @@ -1,48 +1,48 @@ -import 'dart:ui' as ui; +// import 'dart:ui' as ui; -import 'package:flutter_svg/flutter_svg.dart' as svg; -import 'package:graphx/graphx.dart'; +// import 'package:flutter_svg/flutter_svg.dart' as svg; +// import 'package:graphx/graphx.dart'; -/// Utilities to work with `flutter_svg`. -class SvgUtils { - static Future svgStringToSvgDrawable(String rawSvg) async { - return await svg.svg.fromSvgString(rawSvg, rawSvg); - } +// /// Utilities to work with `flutter_svg`. +// class SvgUtils { +// static Future svgStringToSvgDrawable(String rawSvg) async { +// return await svg.svg.fromSvgString(rawSvg, rawSvg); +// } - static Future svgStringToPicture(String rawSvg) async { - final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); - return svgRoot.toPicture(); - } +// static Future svgStringToPicture(String rawSvg) async { +// final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); +// return svgRoot.toPicture(); +// } - static void svgStringToCanvas( - String rawSvg, - ui.Canvas canvas, { - bool scaleCanvas = true, - bool clipCanvas = true, - ui.Size scaleCanvasSize, - }) async { - final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); - if (scaleCanvas) { - svgRoot.scaleCanvasToViewBox(canvas, scaleCanvasSize); - } - if (clipCanvas) { - svgRoot.clipCanvasToViewBox(canvas); - } - svgRoot.draw(canvas, null); - } +// static void svgStringToCanvas( +// String rawSvg, +// ui.Canvas canvas, { +// bool scaleCanvas = true, +// bool clipCanvas = true, +// ui.Size? scaleCanvasSize, +// }) async { +// final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); +// if (scaleCanvas) { +// svgRoot.scaleCanvasToViewBox(canvas, scaleCanvasSize!); +// } +// if (clipCanvas) { +// svgRoot.clipCanvasToViewBox(canvas); +// } +// svgRoot.draw(canvas, null); +// } - static Future svgDataFromString(String rawSvg) async { - final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); - var obj = SvgData(); - obj.hasContent = svgRoot.hasDrawableContent; - obj.picture = svgRoot.toPicture(); - obj.viewBox = GRect.fromNative(svgRoot.viewport.viewBoxRect); - obj.size = GRect( - 0, - 0, - svgRoot.viewport.size.width, - svgRoot.viewport.size.height, - ); - return obj; - } -} +// static Future svgDataFromString(String rawSvg) async { +// final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); +// var obj = SvgData(); +// obj.hasContent = svgRoot.hasDrawableContent; +// obj.picture = svgRoot.toPicture(); +// obj.viewBox = GRect.fromNative(svgRoot.viewport.viewBoxRect); +// obj.size = GRect( +// 0, +// 0, +// svgRoot.viewport.size.width, +// svgRoot.viewport.size.height, +// ); +// return obj; +// } +// } diff --git a/example/pubspec.yaml b/example/pubspec.yaml index 0ffa6c9..b75cf6d 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -6,12 +6,11 @@ publish_to: "none" version: 1.0.0+22 environment: - sdk: ">=2.7.0 <3.0.0" + sdk: '>=2.12.0 <3.0.0' dependencies: flutter: sdk: flutter - flutter_icons: ^1.1.0 flutter_svg: ^0.21.0-nullsafety.0 graphx: path: ../ diff --git a/lib/src/render/graphics.dart b/lib/src/render/graphics.dart index 1d3a5d6..7e1478d 100644 --- a/lib/src/render/graphics.dart +++ b/lib/src/render/graphics.dart @@ -588,14 +588,14 @@ class Graphics with RenderUtilMixin implements GxRenderable { int sides, [ double rotation = 0, ]) { - final points = List.filled(sides, Offset(0, 0)); + final points = List.filled(sides, Offset(0, 0)); final rel = 2 * Math.PI / sides; for (var i = 1; i <= sides; ++i) { final px = x + radius * Math.cos(i * rel + rotation); final py = y + radius * Math.sin(i * rel + rotation); points[i - 1] = Offset(px, py); } - _path!.addPolygon(points as List, true); + _path!.addPolygon(points, true); return this; } @@ -743,7 +743,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { } else { canvas!.drawVertices( graph.vertices!.rawData!, - graph.vertices!.blendMode, + graph.vertices!.blendMode!, fill, ); } @@ -834,7 +834,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { List? indices, List? uvtData, List? hexColors, - BlendMode blendMode = BlendMode.src, + BlendMode? blendMode = BlendMode.src, Culling culling = Culling.positive, ]) { /// will only work if it has a fill. @@ -922,8 +922,8 @@ extension ExtSkiaPaintCustom on Paint { class _GraphVertices { List? vertices, uvtData, adjustedUvtData; List? colors, indices; - BlendMode blendMode; - VertexMode mode; + BlendMode? blendMode; + VertexMode? mode; Path? _path; Rect? _bounds; late bool _normalizedUvt; diff --git a/lib/src/tween/src/wraps/common_wraps.dart b/lib/src/tween/src/wraps/common_wraps.dart index cd993b6..c16b212 100644 --- a/lib/src/tween/src/wraps/common_wraps.dart +++ b/lib/src/tween/src/wraps/common_wraps.dart @@ -29,7 +29,7 @@ class GTweenableDouble with GTweenable, SingleValueTweenMixin { static GTweenable? wrap(Object? target) => target is double ? GTweenableDouble(target) : null; - double? value; + double value = 0.0; GTweenableDouble(double target) { value = this.target = target; diff --git a/lib/src/utils/svg_utils.dart b/lib/src/utils/svg_utils.dart index b0f6ab6..af191a6 100644 --- a/lib/src/utils/svg_utils.dart +++ b/lib/src/utils/svg_utils.dart @@ -1,48 +1,49 @@ -// import 'package:flutter_svg/flutter_svg.dart' as svg; -// -// import '../../graphx.dart'; -// -// /// Utilities to work with `flutter_svg`. -// class SvgUtils { -// static Future -// svgStringToSvgDrawable(String rawSvg) async { -// return await svg.svg.fromSvgString(rawSvg, rawSvg); -// } -// -// static Future svgStringToPicture(String rawSvg) async { -// final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); -// return svgRoot.toPicture(); -// } -// -// static void svgStringToCanvas( -// String rawSvg, -// Canvas canvas, { -// bool scaleCanvas = true, -// bool clipCanvas = true, -// Size scaleCanvasSize, -// }) async { -// final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); -// if (scaleCanvas) { -// svgRoot.scaleCanvasToViewBox(canvas, scaleCanvasSize); -// } -// if (clipCanvas) { -// svgRoot.clipCanvasToViewBox(canvas); -// } -// svgRoot.draw(canvas, null); -// } -// -// static Future svgDataFromString(String rawSvg) async { -// final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); -// var obj = SvgData(); -// obj.hasContent = svgRoot.hasDrawableContent; -// obj.picture = svgRoot.toPicture(); -// obj.viewBox = GxRect.fromNative(svgRoot.viewport.viewBoxRect); -// obj.size = GxRect( -// 0, -// 0, -// svgRoot.viewport.size.width, -// svgRoot.viewport.size.height, -// ); -// return obj; -// } -// } +import 'dart:ui'; + +import 'package:flutter_svg/flutter_svg.dart' as svg; + +import '../../graphx.dart'; + +/// Utilities to work with `flutter_svg`. +class SvgUtils { + static Future svgStringToSvgDrawable(String rawSvg) async { + return await svg.svg.fromSvgString(rawSvg, rawSvg); + } + + static Future svgStringToPicture(String rawSvg) async { + final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); + return svgRoot.toPicture(); + } + + static void svgStringToCanvas( + String rawSvg, + Canvas canvas, { + bool scaleCanvas = true, + bool clipCanvas = true, + required Size scaleCanvasSize, + }) async { + final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); + if (scaleCanvas) { + svgRoot.scaleCanvasToViewBox(canvas, scaleCanvasSize); + } + if (clipCanvas) { + svgRoot.clipCanvasToViewBox(canvas); + } + svgRoot.draw(canvas, Rect.zero); + } + + static Future svgDataFromString(String rawSvg) async { + final svgRoot = await svg.svg.fromSvgString(rawSvg, rawSvg); + var obj = SvgData(); + obj.hasContent = svgRoot.hasDrawableContent; + obj.picture = svgRoot.toPicture(); + obj.viewBox = GRect.fromNative(svgRoot.viewport.viewBoxRect); + obj.size = GRect( + 0, + 0, + svgRoot.viewport.size.width, + svgRoot.viewport.size.height, + ); + return obj; + } +} diff --git a/pubspec.lock b/pubspec.lock index 9d3f47d..7efaa62 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -55,6 +55,13 @@ packages: description: flutter source: sdk version: "0.0.0" + flutter_svg: + dependency: "direct main" + description: + name: flutter_svg + url: "https://pub.dartlang.org" + source: hosted + version: "0.21.0-nullsafety.0" flutter_test: dependency: "direct dev" description: flutter @@ -95,6 +102,20 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.8.0" + path_drawing: + dependency: transitive + description: + name: path_drawing + url: "https://pub.dartlang.org" + source: hosted + version: "0.5.0-nullsafety.0" + path_parsing: + dependency: transitive + description: + name: path_parsing + url: "https://pub.dartlang.org" + source: hosted + version: "0.2.0-nullsafety.0" pedantic: dependency: transitive description: @@ -179,3 +200,4 @@ packages: version: "5.0.2" sdks: dart: ">=2.12.0 <3.0.0" + flutter: ">=1.24.0-7.0" diff --git a/pubspec.yaml b/pubspec.yaml index f0c8587..5b7ff0a 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -4,14 +4,14 @@ version: 0.9.9 homepage: https://github.com/roipeker/graphx environment: - sdk: '>=2.12.0 <3.0.0' + sdk: ">=2.12.0 <3.0.0" dependencies: flutter: sdk: flutter xml: ^5.0.0-nullsafety.1 http: ^0.13.0-nullsafety.0 -# flutter_svg: 0.19.0 + flutter_svg: ^0.21.0-nullsafety.0 dev_dependencies: flutter_test: From bc12fda7c6e973d57a2e437a2f1b501db944c523 Mon Sep 17 00:00:00 2001 From: Roi Peker Date: Thu, 25 Mar 2021 20:42:55 -0300 Subject: [PATCH 12/22] critical fixes for null-safety. -several core fixes for null-safety. -fixed the non-working examples. -added some comments in the README. -increased the version. --- CHANGELOG.md | 5 + README.md | 11 +- .../lib/demos/chart_bezier/bezier_points.dart | 36 +- .../chart_bezier/curved_graph_scene.dart | 42 +- .../expander_fab_menu/expander_fab_menu.dart | 70 +--- example/lib/demos/mouse_repulsion/scene.dart | 2 +- .../simple_interactions/ui/my_button.dart | 4 +- example/lib/demos/trigrid/scene/scene.dart | 46 ++- example/lib/demos/trigrid/scene/tri_grid.dart | 26 +- example/lib/main.dart | 7 - example/pubspec.yaml | 2 +- example/readme.md | 16 + lib/src/core/scene_config.dart | 25 +- lib/src/core/scene_controller.dart | 57 +-- lib/src/core/scene_painter.dart | 8 +- lib/src/display/stage.dart | 4 +- lib/src/display/text.dart | 2 +- lib/src/input/input_converter.dart | 24 +- lib/src/log/trace.dart | 20 +- lib/src/render/graphics.dart | 365 +++++++++--------- lib/src/tween/src/gtween.dart | 90 +++-- lib/src/tween/src/mixins/tweenable.dart | 24 +- lib/src/tween/src/wraps/common_wraps.dart | 6 +- lib/src/widgets/graphx_widget.dart | 25 +- pubspec.lock | 2 +- pubspec.yaml | 6 +- 26 files changed, 461 insertions(+), 464 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82b79ae..ac4744f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +## [1.0.0-nullsafety.0] +- initial migration to null-safety +- fix non-working examples. +- fix a bug with GText layout. + ## [0.9.9] - major fix for `GTween` when running lots of SceneControllers instances. - fix stage dispose exception with keyboard/pointer. diff --git a/README.md b/README.md index 49899f1..db81ac5 100644 --- a/README.md +++ b/README.md @@ -20,12 +20,21 @@ To get some extended, boring explanations, and eventually some sample codes, che --- -[Try Graphx on Dart Pad](https://dartpad.dev/21b6670a42d32e37440192e19279e71b?) +[Try Graphx (0.0.9) on Dart Pad](https://dartpad.dev/21b6670a42d32e37440192e19279e71b?) + +#### news! + +- WIP Support for [null-safety](https://github.com/roipeker/graphx/tree/null-safety) + +- Support for HotReload #### prototyping GraphX is all about visuals, here you have some screen captures of random prototypes I've been doing, while developing and testing graphx. +For your GraphX scene to support **Hot Reload**, you should initialize your variables and DisplayObjects inside `addedToStage`, and optionally clean them in `dispose`. + + [![artificial horizon](https://media.giphy.com/media/NMG8gfpJxFiu1eALZo/giphy.gif)](https://media.giphy.com/media/NMG8gfpJxFiu1eALZo/source.mp4) [![parallax game](https://media.giphy.com/media/RIrvhfZoDtal41Tb4e/giphy-downsized.gif)](https://media.giphy.com/media/RIrvhfZoDtal41Tb4e/source.mp4) [![charts pie color 2](https://media.giphy.com/media/pQdeurUOAqWdZuxxUK/giphy.gif)](https://media.giphy.com/media/pQdeurUOAqWdZuxxUK/source.mp4) diff --git a/example/lib/demos/chart_bezier/bezier_points.dart b/example/lib/demos/chart_bezier/bezier_points.dart index 8092542..936856c 100644 --- a/example/lib/demos/chart_bezier/bezier_points.dart +++ b/example/lib/demos/chart_bezier/bezier_points.dart @@ -1,12 +1,10 @@ import 'package:graphx/graphx.dart'; class _BezierControlPoint { - GPoint? prev; - GPoint? next; - - _BezierControlPoint([this.prev, this.next]) { - prev ??= GPoint(); - next ??= GPoint(); + late GPoint prev, next; + _BezierControlPoint() { + prev = GPoint(); + next = GPoint(); } } @@ -16,7 +14,7 @@ void bezierCurveThrough( Graphics g, List points, [ double tension = .25, - List? output, + List? output, ]) { var len = points.length; if (len == 2) { @@ -49,19 +47,19 @@ void bezierCurveThrough( var cnx = pi.x + dx * dn * tension; var cny = pi.y + dy * dn * tension; - cpoints[i].prev!.setTo(cpx, cpy); - cpoints[i].next!.setTo(cnx, cny); + cpoints[i].prev.setTo(cpx, cpy); + cpoints[i].next.setTo(cnx, cny); } /// end points cpoints[0].next = GPoint( - (points[0].x + cpoints[1].prev!.x) / 2, - (points[0].y + cpoints[1].prev!.y) / 2, + (points[0].x + cpoints[1].prev.x) / 2, + (points[0].y + cpoints[1].prev.y) / 2, ); cpoints[len - 1].prev = GPoint( - (points[len - 1].x + cpoints[len - 2].next!.x) / 2, - (points[len - 1].y + cpoints[len - 2].next!.y) / 2, + (points[len - 1].x + cpoints[len - 2].next.x) / 2, + (points[len - 1].y + cpoints[len - 2].next.y) / 2, ); /// draw? @@ -71,19 +69,19 @@ void bezierCurveThrough( var p = points[i]; var cp = cpoints[i]; var cpp = cpoints[i - 1]; - g.cubicCurveTo(cpp.next!.x, cpp.next!.y, cp.prev!.x, cp.prev!.y, p.x, p.y); + g.cubicCurveTo(cpp.next.x, cpp.next.y, cp.prev.x, cp.prev.y, p.x, p.y); output?.addAll([cpp.next, cp.prev, p]); } cpoints.clear(); } -void bezierCurveThroughDraw(Graphics g, List points) { - g.moveTo(points[0]!.x, points[0]!.y); +void bezierCurveThroughDraw(Graphics g, List points) { + g.moveTo(points[0].x, points[0].y); final len = points.length; for (var i = 1; i < len; i += 3) { - final p0 = points[i]!; - final p1 = points[i + 1]!; - final p2 = points[i + 2]!; + final p0 = points[i]; + final p1 = points[i + 1]; + final p2 = points[i + 2]; g.cubicCurveTo(p0.x, p0.y, p1.x, p1.y, p2.x, p2.y); } } diff --git a/example/lib/demos/chart_bezier/curved_graph_scene.dart b/example/lib/demos/chart_bezier/curved_graph_scene.dart index 6164415..0adb454 100644 --- a/example/lib/demos/chart_bezier/curved_graph_scene.dart +++ b/example/lib/demos/chart_bezier/curved_graph_scene.dart @@ -5,9 +5,10 @@ import 'bezier_points.dart'; class CurvedGraphScene extends GSprite { List graphPositions = [.2, .4, .9, .3, .6, .7, .9, .3]; - List? bezierPoints; + List bezierPoints = []; double get graphW => stage!.stageWidth; + double get graphH => stage!.stageHeight; late GSprite graph, dots; @@ -17,25 +18,13 @@ class CurvedGraphScene extends GSprite { late GTweenableList myTweenList; late List lastPercents; - GShape drawCircle(double px, double py) { - var sh = GShape(); - dots.addChild(sh); - sh.graphics.beginFill(Colors.red).drawCircle(0, 0, 2).endFill(); - sh.setPosition(px, py); - return sh; - } - @override void addedToStage() { - bezierPoints = []; - // stage.color = Colors.black; stage!.maskBounds = true; - graph = GSprite(); dots = GSprite(); lines = GShape(); filled = GShape(); - addChild(filled); addChild(lines); addChild(graph); @@ -58,7 +47,6 @@ class CurvedGraphScene extends GSprite { } void randomNumbers() { - var newValues = lastPercents.map((e) => Math.random()).toList(); for (var i = 0; i < dots.children.length; ++i) { var dot = dots.children[i]; dot.tween( @@ -80,24 +68,26 @@ class CurvedGraphScene extends GSprite { colorize: Colors.red, ); } + final newValues = lastPercents.map((e) => Math.random()).toList(); myTweenList.tween( newValues, duration: 2, onUpdate: () { - final values = myTweenList.value as List; + final values = myTweenList.value as List; renderPositions(values); }, ease: GEase.fastLinearToSlowEaseIn, ); } - void renderPositions(List percents) { + void renderPositions(List percents) { for (var i = 0; i < percents.length; ++i) { - coords[i].y = percents[i]! * graphH; - dots.getChildAt(i).y = coords[i].y; + coords[i].y = percents[i] * graphH; + final dot = dots.getChildAt(i); + dot.y = coords[i].y; } lines.graphics.clear(); - lines.graphics.lineStyle(1, Colors.black); + lines.graphics.lineStyle(1, Colors.blue); lines.graphics.lineGradientStyle( GradientType.linear, [ @@ -106,7 +96,7 @@ class CurvedGraphScene extends GSprite { ], ratios: [.1, 1], ); - bezierPoints!.clear(); + bezierPoints.clear(); bezierCurveThrough(lines.graphics, coords, .25, bezierPoints); filled.graphics.clear(); @@ -120,11 +110,19 @@ class CurvedGraphScene extends GSprite { begin: Alignment.topCenter, end: Alignment.bottomCenter, ); - bezierCurveThroughDraw(filled.graphics, bezierPoints!); + bezierCurveThroughDraw(filled.graphics, bezierPoints); filled.graphics .lineTo(graphW, graphH) .lineTo(0, graphH) - .lineTo(bezierPoints![0]!.x, bezierPoints![0]!.y) + .lineTo(bezierPoints[0].x, bezierPoints[0].y) .endFill(); } + + GShape drawCircle(double px, double py) { + var sh = GShape(); + dots.addChild(sh); + sh.graphics.beginFill(Colors.red).drawCircle(0, 0, 2).endFill(); + sh.setPosition(px, py); + return sh; + } } diff --git a/example/lib/demos/expander_fab_menu/expander_fab_menu.dart b/example/lib/demos/expander_fab_menu/expander_fab_menu.dart index fe5d8b3..233af38 100644 --- a/example/lib/demos/expander_fab_menu/expander_fab_menu.dart +++ b/example/lib/demos/expander_fab_menu/expander_fab_menu.dart @@ -62,13 +62,7 @@ class _MyMenuState extends State with TickerProviderStateMixin { @override void initState() { super.initState(); - // anim = AnimationController( - // vsync: this, - // duration: dur, - // ); - // anim.addListener(() { - // setState(() {}); - // }); + menuScene.requestPositionCallback = getPosition; WidgetsBinding.instance!.addPostFrameCallback((timeStamp) { getPosition(); }); @@ -116,10 +110,6 @@ class _MyMenuState extends State with TickerProviderStateMixin { color: Colors.transparent, key: mySuperKey, ), - // Visibility( - // visible: !isOpen, - // child: myFav(), - // ), baseButton, baseButton, ], @@ -134,54 +124,29 @@ class _MyMenuState extends State with TickerProviderStateMixin { ), ); } - -// Widget buildAnimFab() { -// print(isOpen); -// print(anim.value); -// print(pos); -// if (!isOpen) {} -// return Positioned( -// top: pos.dy * (1 - anim.value), -// left: pos.dx, -// child: IconButton( -// // key: mySuperKey, -// icon: Icon( -// Icons.accessibility, -// color: Colors.red, -// ), -// // backgroundColor: Colors.white, -// onPressed: () { -// isOpen = !isOpen; -// trace('pressed', isOpen); -// if (isOpen) { -// anim.forward(); -// } else { -// anim.reverse(); -// } -// }, -// ), -// ); -// } } class MyCoolMenuScene extends GSprite { - late MyButton button; - bool isOpen = false; + late VoidCallback requestPositionCallback; + late MyButton button; + double? buttonY; + late GShape curtain; + late GSprite menuContainer; MyCoolMenuScene() { button = MyButton(); } - double? buttonY; - late GShape curtain; void updatePosition(GRect position) { button.x = position.x + position.width / 2; - button.y = buttonY = position.y + position.height / 2; + buttonY = position.y + position.height / 2; + if( !isOpen ){ + button.y = buttonY; + } } - GSprite? menuContainer; @override void addedToStage() { @@ -190,10 +155,18 @@ class MyCoolMenuScene extends GSprite { addChild(curtain); menuContainer = GSprite(); - addChild(menuContainer!); + addChild(menuContainer); _buildMenu(); addChild(button); + stage!.onResized.add((){ + requestPositionCallback.call(); + menuContainer.setPosition(sw / 2, sh / 2); + if( isOpen ){ + _renderCurt(); + } + }); + button.onMouseClick.add((event) { isOpen = !isOpen; button.open(isOpen); @@ -262,7 +235,6 @@ class MyCoolMenuScene extends GSprite { void _renderCurt() { final g = curtain.graphics; - g.clear(); // g.lineStyle(2, Colors.black); g.beginFill(Colors.red); @@ -289,8 +261,8 @@ class MyCoolMenuScene extends GSprite { itm.y = i * 34.0; items.add(itm); } - menuContainer!.alignPivot(); - menuContainer!.setPosition(sw / 2, sh / 2); + menuContainer.alignPivot(); + menuContainer.setPosition(sw / 2, sh / 2); } void showMenuNow() { diff --git a/example/lib/demos/mouse_repulsion/scene.dart b/example/lib/demos/mouse_repulsion/scene.dart index fd0b5c1..78d0c7c 100644 --- a/example/lib/demos/mouse_repulsion/scene.dart +++ b/example/lib/demos/mouse_repulsion/scene.dart @@ -22,7 +22,7 @@ class MouseRepulsionScene extends GSprite { mouseChildren = false; mouseRadiusShape = GShape(); radiusSq = radius * radius; - sep = 6; + sep = 12; cols = 70; rows = 60; diff --git a/example/lib/demos/simple_interactions/ui/my_button.dart b/example/lib/demos/simple_interactions/ui/my_button.dart index 041e2c0..e03dc6e 100644 --- a/example/lib/demos/simple_interactions/ui/my_button.dart +++ b/example/lib/demos/simple_interactions/ui/my_button.dart @@ -153,10 +153,10 @@ class MyButton extends GSprite { /// update the [icon.data] and icon's color, based on [_isOn] current state. void _updateIcon() { if (_isOn) { - icon.data = Icons.brightness_7_outlined; + icon.data = Icons.wb_incandescent; icon.color = Colors.yellow; } else { - icon.data = Icons.brightness_2_outlined; + icon.data = Icons.wb_incandescent_outlined; icon.color = Colors.white; } } diff --git a/example/lib/demos/trigrid/scene/scene.dart b/example/lib/demos/trigrid/scene/scene.dart index e8f3741..e151d34 100644 --- a/example/lib/demos/trigrid/scene/scene.dart +++ b/example/lib/demos/trigrid/scene/scene.dart @@ -5,7 +5,7 @@ import 'point.dart'; import 'tri_grid.dart'; class DrawTriangleGridScene extends GSprite { - static const int res = 6; + static const int res = 3; static const double targetRadius = 120; /// draw triangle parameters. @@ -19,8 +19,10 @@ class DrawTriangleGridScene extends GSprite { late double radiusSq; late List dots; - TriangleGrid? triGrid; + late TriangleGrid triGrid; late GSprite container; + bool inited = false; + double textureW = 0, textureH = 0; @override Future addedToStage() async { @@ -29,15 +31,22 @@ class DrawTriangleGridScene extends GSprite { container = GSprite(); addChild(container); mouseChildren = false; - var texture = await (ResourceLoader.loadTexture( - 'assets/trigrid/cute_dog.png', 1, 'dog') as Future); - - cols = texture.width! ~/ sep; - rows = texture.height! ~/ sep; + final texture = await ResourceLoader.loadTexture( + 'assets/trigrid/cute_dog.png', 1, 'dog'); + if (texture == null) { + throw "We have an error loading the image"; + } + textureW = texture.width!; + textureH = texture.height!; + cols = textureW ~/ sep; + rows = textureH ~/ sep; var total = cols * rows; + /// these are the points that we MOVE to update the grid. dots = List.generate(total, (index) { var d = GraphPoint(); + /// uncomment this to see the DOTS. + // container.addChild(d); var idx = index % cols; var idy = index ~/ cols; if (index == 0) { @@ -53,17 +62,17 @@ class DrawTriangleGridScene extends GSprite { triGrid = TriangleGrid(res: sep, cols: cols, rows: rows); /// show the triangles lines - triGrid!.debugTriangles = true; - - container.addChildAt(triGrid!, 0); - triGrid!.texture = texture; - triGrid!.draw(); + // triGrid.debugTriangles = true; + container.addChildAt(triGrid, 0); + triGrid.texture = texture; + triGrid.draw(); + inited = true; } void adjustContainer() { /// resize container based on the image dimensions. - var tw = triGrid!.texture!.width!; - var th = triGrid!.texture!.height!; + var tw = textureW; + var th = textureH; var scaleTo = stage!.stageHeight / th; container.y = 0; container.scale = scaleTo; @@ -73,21 +82,22 @@ class DrawTriangleGridScene extends GSprite { @override void update(double delta) { super.update(delta); - if (triGrid == null) return; + if (!inited) return; + // return; adjustContainer(); updatePoints(); renderPoints(); } void renderPoints() { - var ver = triGrid!.vertices; + var ver = triGrid.vertices; var j = 0; for (var i = 0; i < dots.length; ++i) { var d = dots[i]; - ver![j++] = d.x; + ver[j++] = d.x; ver[j++] = d.y; } - triGrid!.draw(); + triGrid.draw(); } void updatePoints() { diff --git a/example/lib/demos/trigrid/scene/tri_grid.dart b/example/lib/demos/trigrid/scene/tri_grid.dart index b5f2a27..8a3f01a 100644 --- a/example/lib/demos/trigrid/scene/tri_grid.dart +++ b/example/lib/demos/trigrid/scene/tri_grid.dart @@ -1,4 +1,3 @@ - import 'package:flutter/material.dart'; import 'package:graphx/graphx.dart'; @@ -7,6 +6,10 @@ class TriangleGrid extends GShape { int rows, cols; bool debugTriangles = false; + late List vertices; + late List uvData; + late List indices; + GTexture? texture; TriangleGrid({ @@ -20,22 +23,18 @@ class TriangleGrid extends GShape { draw(); } - List? vertices; - List? uvData; - List? indices; - void draw() { graphics.clear(); if (texture != null) { graphics .beginBitmapFill(texture!, null, false, true) - .drawTriangles(vertices!, indices, uvData) + .drawTriangles(vertices, indices, uvData) .endFill(); } if (debugTriangles) { graphics .lineStyle(0, Colors.white30) - .drawTriangles(vertices!, indices, uvData) + .drawTriangles(vertices, indices, uvData) .endFill(); } } @@ -48,18 +47,17 @@ class TriangleGrid extends GShape { for (var c = 0; c < total; ++c) { var i = c ~/ cols; var j = c % cols; - vertices!.addAll([j * res, i * res]); - uvData!.addAll([ + vertices.addAll([j * res, i * res]); + uvData.addAll([ j / (cols - 1), i / (rows - 1), ]); - if (i < rows - 1 && j < cols - 1) { - ///first tri - indices!.addAll([i * cols + j, i * cols + j + 1, (i + 1) * cols + j]); + ///first triangle + indices.addAll([i * cols + j, i * cols + j + 1, (i + 1) * cols + j]); - ///first tri - indices!.addAll( + ///second triangle + indices.addAll( [i * cols + j + 1, (i + 1) * cols + j + 1, (i + 1) * cols + j]); } } diff --git a/example/lib/main.dart b/example/lib/main.dart index 906222a..8a62164 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -37,7 +37,6 @@ void main() { // home: MuratCoffeeMain(), // home: PieChartMain(), - //TODO doesn't work // home: ChartBezierMain(), // home: RunHeroCanvasMain(), @@ -50,20 +49,14 @@ void main() { // home: PizzaBoxMain(), // home: DrawingPadBezierMain(), // home: IsmaChartMain(), - - //TODO doesn't work // home: TriGridMain(), - // home: NicoLoadingIndicatorMain(), // home: FeelingSwitchMain(), // home: MouseRepulsionMain(), // home: Globe3dMain(), // home: LungsAnimationMain(), // home: PathChartStressTestMain(), - - //TODO doesn't work // home: ExpanderFabMenu(), - home: PageIndicatorMain(), ), ); diff --git a/example/pubspec.yaml b/example/pubspec.yaml index b75cf6d..e5bce67 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -3,7 +3,7 @@ description: Graphx rendering prototype examples publish_to: "none" -version: 1.0.0+22 +version: 1.0.0+23 environment: sdk: '>=2.12.0 <3.0.0' diff --git a/example/readme.md b/example/readme.md index e69de29..d4da51f 100644 --- a/example/readme.md +++ b/example/readme.md @@ -0,0 +1,16 @@ +Here you will find an exhaustive list of experiments made with GraphX. + +Some are more complicated than others, but overall is a good resource to learn the "real world" API that GraphX provides. + +Be WARNED: the examples are (mostly) pretty raw, a direct copy of codes I did during the last couple of months as +quick prototypes for experiments while sketching the package. + +Remember, GraphX should be considered WIP. As stated in the root README file, I mostly used it to play, prototype +and have fun creating random stuffs, and that's the spirit of it :) + +Although you are free to use it in production apps (some users are, myself as well), beware that you might find +some bugs, even more in this null-safety branch. + +I truly hope you enjoy using the package, as I much as I do. + +Sincerely, roipeker. \ No newline at end of file diff --git a/lib/src/core/scene_config.dart b/lib/src/core/scene_config.dart index fa4f497..9f474d8 100644 --- a/lib/src/core/scene_config.dart +++ b/lib/src/core/scene_config.dart @@ -51,17 +51,17 @@ class SceneConfig { /// re-builds the SceneController (the ScenePainter and the scene class). /// disposes and initializes all the scene. - bool? rebuildOnHotReload; + late bool rebuildOnHotReload; /// If the GraphX [SceneController] will use keyboard events. - bool? useKeyboard; + late bool useKeyboard; /// If this GraphX [SceneController] will use pointer (touch/mouse) events. - bool? usePointer; + late bool usePointer; /// Will be overwritten to `true` if [autoUpdateAndRender] is set on any /// [ScenePainter] layer. - bool? useTicker; + bool useTicker = false; /// See [CustomPaint.willChange]. /// Rendering caching flag. @@ -71,7 +71,7 @@ class SceneConfig { /// All these flags overrides the value to `true`: /// [autoUpdateRender], [useTicker], [usePointer], [useKeyboard] /// - bool? painterWillChange; + late bool painterWillChange; /// Avoids the scene from being disposed by the Widget. /// Meant to be used with `ScenePainter.useOwnCanvas=true` @@ -79,7 +79,7 @@ class SceneConfig { /// Picture (or Image eventually) by other [ScenePainter]s. /// Warning: Experimental /// - bool? isPersistent = false; + late bool isPersistent; /// Default flag to make the engine update() the Stage and all /// his children (onEnterFrame), needed by [GTween] to run the tweens. @@ -91,7 +91,7 @@ class SceneConfig { /// And, unless you don't need external control over the rendering & update /// pipelines for the scene, or if you use a static scene, /// you should leave it as `true`. - bool? autoUpdateRender = true; + late bool autoUpdateRender; SceneConfig({ this.rebuildOnHotReload = true, @@ -100,21 +100,18 @@ class SceneConfig { this.useTicker = false, this.isPersistent = false, this.autoUpdateRender = true, - this.painterWillChange, + this.painterWillChange = true, }) { - if (autoUpdateRender ?? false) useTicker = true; + if (autoUpdateRender) useTicker = true; } /// Utility method used by the [SceneBuilderWidget] to set the flag /// `CustomPaint.willChange` /// bool painterMightChange() { - if ((useTicker ?? false) || - (autoUpdateRender ?? false) || - (usePointer ?? false) || - (useKeyboard ?? false)) { + if (useTicker || autoUpdateRender || usePointer || useKeyboard) { return true; } - return painterWillChange ?? false; + return painterWillChange; } } diff --git a/lib/src/core/scene_controller.dart b/lib/src/core/scene_controller.dart index 8271623..22ed664 100644 --- a/lib/src/core/scene_controller.dart +++ b/lib/src/core/scene_controller.dart @@ -38,19 +38,18 @@ class SceneController { /// Access the keyboard manager instance associated with this /// [SceneController]. - KeyboardManager? get keyboard => _keyboard; + KeyboardManager get keyboard => _keyboard; /// Access the pointer manager instance associated with this /// [SceneController]. - PointerManager? get pointer => _pointer; + PointerManager get pointer => _pointer; - KeyboardManager? _keyboard; - - PointerManager? _pointer; + late KeyboardManager _keyboard; + late PointerManager _pointer; GTicker? _ticker; - InputConverter? $inputConverter; + late InputConverter $inputConverter; SceneConfig get config => _config; @@ -65,13 +64,13 @@ class SceneController { bool _isInited = false; set config(SceneConfig sceneConfig) { - _config.rebuildOnHotReload = sceneConfig.rebuildOnHotReload ?? true; - _config.autoUpdateRender = sceneConfig.autoUpdateRender ?? true; - _config.isPersistent = sceneConfig.isPersistent ?? false; - _config.painterWillChange = sceneConfig.painterWillChange ?? true; - _config.useKeyboard = sceneConfig.useKeyboard ?? false; - _config.usePointer = sceneConfig.usePointer ?? false; - _config.useTicker = sceneConfig.useTicker ?? false; + _config.rebuildOnHotReload = sceneConfig.rebuildOnHotReload; + _config.autoUpdateRender = sceneConfig.autoUpdateRender; + _config.isPersistent = sceneConfig.isPersistent; + _config.painterWillChange = sceneConfig.painterWillChange; + _config.useKeyboard = sceneConfig.useKeyboard; + _config.usePointer = sceneConfig.usePointer; + _config.useTicker = sceneConfig.useTicker; } /// constructor. @@ -87,7 +86,7 @@ class SceneController { if (front != null) { frontScene = ScenePainter(this, front); } - this.config = config ?? SceneConfig.defaultConfig; + this.config = config??SceneConfig.defaultConfig; } /// WARNING: Internal method @@ -109,7 +108,7 @@ class SceneController { } void setup() { - if (!GTween.initialized) { + if (!GTween.initializedCommonWraps) { GTween.registerCommonWraps(); } backScene?.$setup(); @@ -129,7 +128,7 @@ class SceneController { } void dispose() { - if (_config.isPersistent ?? false) { + if (_config.isPersistent) { return; } _onHotReload?.removeAll(); @@ -145,20 +144,24 @@ class SceneController { CustomPainter? buildFrontPainter() => frontScene?.buildPainter(); void _initInput() { - if (_config.useKeyboard ?? false) { - _keyboard ??= KeyboardManager(); - } - if (_config.usePointer ?? false) { - _pointer ??= PointerManager(); - } - if (_config.useKeyboard ?? false || (_config.usePointer ?? false)) { - $inputConverter ??= InputConverter(_pointer, _keyboard); - } + // if (_config.useKeyboard) { + // _keyboard ??= KeyboardManager(); + // } + // if (_config.usePointer) { + // _pointer ??= PointerManager(); + // } + + _keyboard = KeyboardManager(); + _pointer = PointerManager(); + // if (_config.useKeyboard ?? false || (_config.usePointer ?? false)) { + // trace("CREATE INPUT!"); + // } + $inputConverter = InputConverter(_pointer, _keyboard); } void reassembleWidget() { _onHotReload?.dispatch(); - if (_config.rebuildOnHotReload ?? false) { + if (_config.rebuildOnHotReload) { GTween.hotReload(); dispose(); @@ -173,5 +176,5 @@ class SceneController { bool _anySceneAutoUpdate() => _sceneAutoUpdate(backScene) || _sceneAutoUpdate(frontScene); - bool _hasTicker() => _anySceneAutoUpdate() || (_config.useTicker ?? false); + bool _hasTicker() => _anySceneAutoUpdate() || _config.useTicker; } diff --git a/lib/src/core/scene_painter.dart b/lib/src/core/scene_painter.dart index caa4412..edca8a8 100644 --- a/lib/src/core/scene_painter.dart +++ b/lib/src/core/scene_painter.dart @@ -101,7 +101,7 @@ class ScenePainter with EventDispatcherMixin { makeCurrent(); /// If needed, can be overridden later by the [root]. - autoUpdateAndRender = core.config.autoUpdateRender ?? false; + autoUpdateAndRender = core.config.autoUpdateRender; } void _createPicture() { @@ -201,7 +201,7 @@ class ScenePainter with EventDispatcherMixin { } void _initMouseInput() { - core.pointer?.onInput.add(_onInputHandler); + core.pointer.onInput.add(_onInputHandler); } void _onInputHandler(PointerEventData e) { @@ -242,13 +242,13 @@ class ScenePainter with EventDispatcherMixin { _isReady = false; size = Size.zero; _stage?.dispose(); - core.pointer?.onInput.remove(_onInputHandler); + core.pointer.onInput.remove(_onInputHandler); _onUpdate?.removeAll(); _onUpdate = null; super.dispose(); } - bool get _hasPointer => core.pointer?.onInput != null; + bool get _hasPointer => core.pointer.onInput != null; bool shouldRepaint() => needsRepaint; } diff --git a/lib/src/display/stage.dart b/lib/src/display/stage.dart index 791ac7d..0ef8659 100644 --- a/lib/src/display/stage.dart +++ b/lib/src/display/stage.dart @@ -214,8 +214,8 @@ class Stage extends GDisplayObjectContainer void dispose() { _size = null; _backgroundPaint = null; - scene.core.pointer?.dispose(); - scene.core.keyboard?.dispose(); + scene.core.pointer.dispose(); + scene.core.keyboard.dispose(); $disposeResizeSignals(); $disposeTickerSignals(); $disposeStagePointerSignals(); diff --git a/lib/src/display/text.dart b/lib/src/display/text.dart index 0b3bf2c..afb42e3 100644 --- a/lib/src/display/text.dart +++ b/lib/src/display/text.dart @@ -218,7 +218,7 @@ class GText extends GDisplayObject { void _layout() { //// Web has a bug for double.infinity for text layout. - var paragraphWidth = !SystemUtils.usingSkia ? _maxTextWidthForWeb : _width; + final paragraphWidth = _width.isInfinite && !SystemUtils.usingSkia ? _maxTextWidthForWeb : _width; _paragraph?.layout(ui.ParagraphConstraints(width: paragraphWidth)); _invalidSize = false; } diff --git a/lib/src/input/input_converter.dart b/lib/src/input/input_converter.dart index 8f85cd6..f7249f8 100644 --- a/lib/src/input/input_converter.dart +++ b/lib/src/input/input_converter.dart @@ -2,34 +2,34 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; +import '../../graphx.dart'; import '../events/keyboard_data.dart'; import '../events/pointer_data.dart'; import 'keyboard_manager.dart'; import 'pointer_manager.dart'; class InputConverter { - final PointerManager? pointer; - final KeyboardManager? keyboard; - + final PointerManager pointer; + final KeyboardManager keyboard; InputConverter(this.pointer, this.keyboard); /// mouse stuffs. void pointerEnter(PointerEnterEvent event) { - pointer!.$process(PointerEventData( + pointer.$process(PointerEventData( type: PointerEventType.enter, rawEvent: event, )); } void pointerExit(PointerExitEvent event) { - pointer!.$process(PointerEventData( + pointer.$process(PointerEventData( type: PointerEventType.exit, rawEvent: event, )); } void pointerHover(PointerHoverEvent event) { - pointer!.$process(PointerEventData( + pointer.$process(PointerEventData( type: PointerEventType.hover, rawEvent: event, )); @@ -38,35 +38,35 @@ class InputConverter { /// touchable stuffs. void pointerSignal(PointerSignalEvent event) { - pointer!.$process(PointerEventData( + pointer.$process(PointerEventData( type: PointerEventType.scroll, rawEvent: event as PointerScrollEvent, )); } void pointerMove(PointerMoveEvent event) { - pointer!.$process(PointerEventData( + pointer.$process(PointerEventData( type: PointerEventType.move, rawEvent: event, )); } void pointerCancel(PointerCancelEvent event) { - pointer!.$process(PointerEventData( + pointer.$process(PointerEventData( type: PointerEventType.cancel, rawEvent: event, )); } void pointerUp(PointerUpEvent event) { - pointer!.$process(PointerEventData( + pointer.$process(PointerEventData( type: PointerEventType.up, rawEvent: event, )); } void pointerDown(PointerDownEvent event) { - pointer!.$process(PointerEventData( + pointer.$process(PointerEventData( type: PointerEventType.down, rawEvent: event, )); @@ -74,7 +74,7 @@ class InputConverter { void handleKey(RawKeyEvent event) { final isDown = event is RawKeyDownEvent; - keyboard!.$process(KeyboardEventData( + keyboard.$process(KeyboardEventData( type: isDown ? KeyEventType.down : KeyEventType.up, rawEvent: event, )); diff --git a/lib/src/log/trace.dart b/lib/src/log/trace.dart index 040c1e9..ca64378 100644 --- a/lib/src/log/trace.dart +++ b/lib/src/log/trace.dart @@ -44,16 +44,16 @@ void traceConfig({ /// object to be printed. The way trace() shows output in the console can be /// defined with [traceConfig()]. void trace( - Object arg1, [ - Object? arg2, - Object? arg3, - Object? arg4, - Object? arg5, - Object? arg6, - Object? arg7, - Object? arg8, - Object? arg9, - Object? arg10, + dynamic arg1, [ + dynamic? arg2, + dynamic? arg3, + dynamic? arg4, + dynamic? arg5, + dynamic? arg6, + dynamic? arg7, + dynamic? arg8, + dynamic? arg9, + dynamic? arg10, ]) { ++_traceCount; final outputList = [ diff --git a/lib/src/render/graphics.dart b/lib/src/render/graphics.dart index 7e1478d..f109280 100644 --- a/lib/src/render/graphics.dart +++ b/lib/src/render/graphics.dart @@ -1,6 +1,8 @@ import 'dart:typed_data'; import 'dart:ui' as ui; + import 'package:flutter/painting.dart'; + import '../../graphx.dart'; enum GradientType { @@ -109,8 +111,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics beginBitmapFill( - GTexture texture, [ + Graphics beginBitmapFill(GTexture texture, [ GMatrix? matrix, bool repeat = false, bool smooth = false, @@ -144,7 +145,8 @@ class Graphics with RenderUtilMixin implements GxRenderable { } Graphics drawPicture(ui.Picture picture) { - _drawingQueue.add(GraphicsDrawingData()..picture = picture); + _drawingQueue.add(GraphicsDrawingData() + ..picture = picture); return this; } @@ -185,24 +187,23 @@ class Graphics with RenderUtilMixin implements GxRenderable { /// For [GradientType.radial], `end` is used for [RadialGradient.focal], check /// the [RadialGradient] docs to understand the relation with [focalRadius] - Graphics beginGradientFill( - GradientType type, - List colors, { - List? ratios, - Alignment? begin, - Alignment? end, - double rotation = 0, - TileMode tileMode = TileMode.clamp, - Rect? gradientBox, - - /// only radial - double radius = 0.5, - double focalRadius = 0.0, - - /// only sweep - double sweepStartAngle = 0.0, - double sweepEndAngle = 6.2832, - }) { + Graphics beginGradientFill(GradientType type, + List colors, { + List? ratios, + Alignment? begin, + Alignment? end, + double rotation = 0, + TileMode tileMode = TileMode.clamp, + Rect? gradientBox, + + /// only radial + double radius = 0.5, + double focalRadius = 0.0, + + /// only sweep + double sweepStartAngle = 0.0, + double sweepEndAngle = 6.2832, + }) { final gradient = _createGradient( type, colors, @@ -228,23 +229,22 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Gradient _createGradient( - GradientType type, - List colors, [ - List? ratios, - Alignment? begin, - Alignment? end, - double rotation = 0, - - /// only radial - double radius = 0.5, - double focalRadius = 0.0, - - /// only sweep - double sweepStartAngle = 0.0, - double sweepEndAngle = 6.2832, - TileMode tileMode = TileMode.clamp, - ]) { + Gradient _createGradient(GradientType type, + List colors, [ + List? ratios, + Alignment? begin, + Alignment? end, + double rotation = 0, + + /// only radial + double radius = 0.5, + double focalRadius = 0.0, + + /// only sweep + double sweepStartAngle = 0.0, + double sweepEndAngle = 6.2832, + TileMode tileMode = TileMode.clamp, + ]) { final transform = GradientRotation(rotation); if (type == GradientType.radial) { return RadialGradient( @@ -284,29 +284,28 @@ class Graphics with RenderUtilMixin implements GxRenderable { /// Also for `GradientType.radial`, `Alignment end` represents the focalPoint. /// So make sure to increase the `radius` if you use a focalPoint alignment /// different than the center (meaning `begin!=end`). - Graphics lineGradientStyle( - GradientType type, - List colors, { - List? ratios, - Alignment? begin, - Alignment? end, - double rotation = 0, - - /// only `GradientType.radial` - double radius = 0.5, - double focalRadius = 0.0, - - /// only `GradientType.sweep` - double sweepStartAngle = 0.0, - double sweepEndAngle = 6.2832, - - /// manually define the bounding box of the Gradient shader. - Rect? gradientBox, - - /// when the gradient box is different than the object bounds, you can - /// see the `tileMode` behaviour. - TileMode tileMode = TileMode.clamp, - }) { + Graphics lineGradientStyle(GradientType type, + List colors, { + List? ratios, + Alignment? begin, + Alignment? end, + double rotation = 0, + + /// only `GradientType.radial` + double radius = 0.5, + double focalRadius = 0.0, + + /// only `GradientType.sweep` + double sweepStartAngle = 0.0, + double sweepEndAngle = 6.2832, + + /// manually define the bounding box of the Gradient shader. + Rect? gradientBox, + + /// when the gradient box is different than the object bounds, you can + /// see the `tileMode` behaviour. + TileMode tileMode = TileMode.clamp, + }) { /// actual paint must be stroke. assert(_currentDrawing!.fill!.style == PaintingStyle.stroke); @@ -331,8 +330,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics lineBitmapStyle( - GTexture texture, [ + Graphics lineBitmapStyle(GTexture texture, [ GMatrix? matrix, bool repeat = true, bool smooth = false, @@ -369,37 +367,32 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics cubicCurveTo( - double controlX1, - double controlY1, - double controlX2, - double controlY2, - double anchorX, - double anchorY, - ) { + Graphics cubicCurveTo(double controlX1, + double controlY1, + double controlX2, + double controlY2, + double anchorX, + double anchorY,) { _path! .cubicTo(controlX1, controlY1, controlX2, controlY2, anchorX, anchorY); return this; } - Graphics curveTo( - double controlX, - double controlY, - double anchorX, - double anchorY, - ) { + Graphics curveTo(double controlX, + double controlY, + double anchorX, + double anchorY,) { _path!.quadraticBezierTo(controlX, controlY, anchorX, anchorY); return this; } - Graphics conicCurveTo( - double controlX, - double controlY, - double anchorX, - double anchorY, - double weight, [ - bool relative = false, - ]) { + Graphics conicCurveTo(double controlX, + double controlY, + double anchorX, + double anchorY, + double weight, [ + bool relative = false, + ]) { if (!relative) { _path!.conicTo(controlX, controlY, anchorX, anchorY, weight); } else { @@ -438,16 +431,15 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics drawRoundRectComplex( - double x, - double y, - double width, - double height, [ - double topLeftRadius = 0, - double topRightRadius = 0, - double bottomLeftRadius = 0, - double bottomRightRadius = 0, - ]) { + Graphics drawRoundRectComplex(double x, + double y, + double width, + double height, [ + double topLeftRadius = 0, + double topRightRadius = 0, + double bottomLeftRadius = 0, + double bottomRightRadius = 0, + ]) { _path!.addRRect( RRect.fromLTRBAndCorners( x, @@ -463,14 +455,13 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics drawRoundRect( - double x, - double y, - double width, - double height, - double ellipseWidth, [ - double? ellipseHeight, - ]) { + Graphics drawRoundRect(double x, + double y, + double width, + double height, + double ellipseWidth, [ + double? ellipseHeight, + ]) { final r = RRect.fromLTRBXY( x, y, @@ -504,14 +495,12 @@ class Graphics with RenderUtilMixin implements GxRenderable { } } - Graphics arcOval( - double cx, - double cy, - double radiusX, - double radiusY, - double startAngle, - double sweepAngle, - ) { + Graphics arcOval(double cx, + double cy, + double radiusX, + double radiusY, + double startAngle, + double sweepAngle,) { _path!.addArc( Rect.fromCenter( center: Offset(cx, cy), @@ -524,14 +513,13 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics arc( - double cx, - double cy, - double radius, - double startAngle, - double sweepAngle, [ - bool moveTo = false, - ]) { + Graphics arc(double cx, + double cy, + double radius, + double startAngle, + double sweepAngle, [ + bool moveTo = false, + ]) { if (sweepAngle == 0) return this; if (!moveTo) { _path!.arcTo( @@ -550,15 +538,14 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics arcToPoint( - double endX, - double endY, - double radius, [ - double rotation = 0.0, - bool largeArc = false, - bool clockwise = true, - bool relativeMoveTo = false, - ]) { + Graphics arcToPoint(double endX, + double endY, + double radius, [ + double rotation = 0.0, + bool largeArc = false, + bool clockwise = true, + bool relativeMoveTo = false, + ]) { if (radius == 0) return this; if (relativeMoveTo) { _path!.arcToPoint( @@ -581,13 +568,12 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics drawPolygonFaces( - double x, - double y, - double radius, - int sides, [ - double rotation = 0, - ]) { + Graphics drawPolygonFaces(double x, + double y, + double radius, + int sides, [ + double rotation = 0, + ]) { final points = List.filled(sides, Offset(0, 0)); final rel = 2 * Math.PI / sides; for (var i = 1; i <= sides; ++i) { @@ -599,14 +585,13 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } - Graphics drawStar( - double x, - double y, - int points, - double radius, [ - double? innerRadius, - double rotation = 0, - ]) { + Graphics drawStar(double x, + double y, + int points, + double radius, [ + double? innerRadius, + double rotation = 0, + ]) { innerRadius ??= radius / 2; final startAngle = (-1 * Math.PI1_2) + rotation; final len = points * 2; @@ -629,7 +614,8 @@ class Graphics with RenderUtilMixin implements GxRenderable { Graphics beginHole() { if (_holeMode) return this; _holeMode = true; - _currentDrawing = GraphicsDrawingData(null, Path())..isHole = true; + _currentDrawing = GraphicsDrawingData(null, Path()) + ..isHole = true; return this; } @@ -702,7 +688,6 @@ class Graphics with RenderUtilMixin implements GxRenderable { _constrainAlpha(); if (!_isVisible) return; - // trace("en", _drawingQueue.length); for (var graph in _drawingQueue) { if (graph!.hasPicture) { canvas!.drawPicture(graph.picture!); @@ -777,8 +762,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { /// This should be used only if you are operating with `Path` and `Paint` /// directly. /// `x` and `y` can shift the Path coordinates. - void pushData( - GraphicsDrawingData data, [ + void pushData(GraphicsDrawingData data, [ bool asCurrent = false, double? x, double? y, @@ -812,8 +796,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { /// Appends a native `Path` to the current drawing path, /// `x` and `y` can offset the target position, while `transform` can be used /// to rotated, scale, translate, the given shape. - Graphics drawPath( - Path path, [ + Graphics drawPath(Path path, [ double x = 0, double y = 0, GMatrix? transform, @@ -821,7 +804,9 @@ class Graphics with RenderUtilMixin implements GxRenderable { _path!.addPath( path, Offset(x, y), - matrix4: transform?.toNative()?.storage, + matrix4: transform + ?.toNative() + ?.storage, ); return this; } @@ -829,8 +814,7 @@ class Graphics with RenderUtilMixin implements GxRenderable { /// Draw a bunch of triangles in the Canvas, only supports /// solid fill or image (not a stroke). /// Doesn't use a Path(), but drawVertices()... - Graphics drawTriangles( - List vertices, [ + Graphics drawTriangles(List vertices, [ List? indices, List? uvtData, List? hexColors, @@ -920,7 +904,8 @@ extension ExtSkiaPaintCustom on Paint { } class _GraphVertices { - List? vertices, uvtData, adjustedUvtData; + List vertices; + List?uvtData, adjustedUvtData; List? colors, indices; BlendMode? blendMode; VertexMode? mode; @@ -940,24 +925,23 @@ class _GraphVertices { Culling culling; /// check if uvt requires normalization. - _GraphVertices( - this.mode, - this.vertices, [ - this.indices, - this.uvtData, - this.colors, - this.blendMode = BlendMode.src, - this.culling = Culling.positive, - ]) { + _GraphVertices(this.mode, + this.vertices, [ + this.indices, + this.uvtData, + this.colors, + this.blendMode = BlendMode.src, + this.culling = Culling.positive, + ]) { _normalizedUvt = false; - final len = uvtData!.length; + final len = uvtData?.length ?? 0; if (uvtData != null && len > 6) { for (var i = 0; i < 6; ++i) { - if (uvtData![i]! <= 2.0) { + if (uvtData![i] <= 2.0) { _normalizedUvt = true; } } - if (uvtData![len - 2]! <= 2.0 || uvtData![len - 1]! <= 2.0) { + if (uvtData![len - 2] <= 2.0 || uvtData![len - 1] <= 2.0) { _normalizedUvt = true; } } @@ -1007,19 +991,20 @@ class _GraphVertices { adjustedUvtData = uvtData; } else { /// make a ratio of the image size - var imgW = shaderTexture!.width; - var imgH = shaderTexture.height; - adjustedUvtData = List.filled(uvtData!.length, null); + final imgW = shaderTexture!.width ?? 0; + final imgH = shaderTexture.height ?? 0; + adjustedUvtData = List.filled(uvtData!.length, 0.0); for (var i = 0; i < uvtData!.length; i += 2) { - adjustedUvtData![i] = uvtData![i]! * imgW!; - adjustedUvtData![i + 1] = uvtData![i + 1]! * imgH!; + adjustedUvtData![i] = uvtData![i] * imgW; + adjustedUvtData![i + 1] = uvtData![i + 1] * imgH; } } } void calculateCulling() { var i = 0; - var offsetX = 0.0, offsetY = 0.0; + var offsetX = 0.0, + offsetY = 0.0; var ind = indices; var v = vertices; var l = indices!.length; @@ -1035,12 +1020,12 @@ class _GraphVertices { var icx = ind[_c] * 2; var icy = ind[_c] * 2 + 1; - var x1 = v![iax]! - offsetX; - var y1 = v[iay]! - offsetY; - var x2 = v[ibx]! - offsetX; - var y2 = v[iby]! - offsetY; - var x3 = v[icx]! - offsetX; - var y3 = v[icy]! - offsetY; + var x1 = v[iax] - offsetX; + var y1 = v[iay] - offsetY; + var x2 = v[ibx] - offsetX; + var y2 = v[iby] - offsetY; + var x3 = v[icx] - offsetX; + var y3 = v[icy] - offsetY; switch (culling) { case Culling.positive: @@ -1067,14 +1052,12 @@ class _GraphVertices { } class _GraphUtils { - static bool isCCW( - double x1, - double y1, - double x2, - double y2, - double x3, - double y3, - ) => + static bool isCCW(double x1, + double y1, + double x2, + double y2, + double x3, + double y3,) => ((x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)) < 0; // static List colorsFromHex(List colors, List alphas) { @@ -1091,11 +1074,11 @@ class _GraphUtils { static Path getPathFromVertices(_GraphVertices v) { var path = _helperPath; path.reset(); - var pos = v.vertices!; + final pos = v.vertices; var len = pos.length; final points = []; for (var i = 0; i < len; i += 2) { - points.add(Offset(pos[i]!, pos[i + 1]!)); + points.add(Offset(pos[i], pos[i + 1])); } path.addPolygon(points, true); return path; @@ -1106,8 +1089,8 @@ class _GraphUtils { var ind = v.indices; if (ind == null) { /// calculate - var len = ver!.length; - var out = List.filled(len * 2, null); + var len = ver.length; + var out = List.filled(len * 2, 0.0); var j = 0; for (var i = 0; i < len; i += 6) { out[j++] = ver[i + 0]; @@ -1126,7 +1109,7 @@ class _GraphUtils { return out; } else { var len = ind.length; - var out = List.filled(len * 4, null); + var out = List.filled(len * 4, 0.0); var j = 0; for (var i = 0; i < len; i += 3) { var i0 = ind[i + 0]; @@ -1135,7 +1118,7 @@ class _GraphUtils { var v0 = i0 * 2; var v1 = i1 * 2; var v2 = i2 * 2; - out[j++] = ver![v0]; + out[j++] = ver[v0]; out[j++] = ver[v0 + 1]; out[j++] = ver[v1]; out[j++] = ver[v1 + 1]; diff --git a/lib/src/tween/src/gtween.dart b/lib/src/tween/src/gtween.dart index c84dccc..74a4394 100644 --- a/lib/src/tween/src/gtween.dart +++ b/lib/src/tween/src/gtween.dart @@ -102,7 +102,7 @@ class GTween { /// ); /// ``` static void registerCommonWraps([List? otherWraps]) { - if (initialized) return; + if (initializedCommonWraps) return; GTween.registerWrap(GTweenableDisplayObject.wrap); GTween.registerWrap(GTweenableMap.wrap); GTween.registerWrap(GTweenableDouble.wrap); @@ -111,7 +111,7 @@ class GTween { GTween.registerWrap(GTweenableList.wrap); // GTween.registerWrap(GTweenableColor.wrap); otherWraps?.forEach(GTween.registerWrap); - initialized = true; + initializedCommonWraps = true; } static void hotReload() { @@ -133,8 +133,8 @@ class GTween { _lastFrameTimeStamp = ts; } - static bool initialized = false; - + static bool initializedEngine = false; + static bool initializedCommonWraps = false; static double _time = 0; static double _frame = 0; @@ -147,11 +147,29 @@ class GTween { static void registerWrap(GxAnimatableBuilder builder) => _tweenableBuilders.add(builder); - static Map? _reservedProps; + static void _initEngine() { + initializedEngine = true; + _time = getTimer() / 1000; + _frame = 0; + ticker.add(_updateRoot); + } + + static final Map _reservedProps = { + 'delay': 1, + 'ease': 1, + 'usedFrames': 1, + 'overwrite': 1, + 'onComplete': 1, + 'runBackwards': 1, + 'immediateRender': 1, + 'onUpdate': 1, + 'startAt': 1, + }; + static GTween? _first; static GTween? _last; - double? _duration; + late double _duration; Map? vars; late GVars nanoVars; late double _startTime; @@ -164,7 +182,7 @@ class GTween { late bool _useFrames; double? ratio = 0; - Function? _ease; + late Function _ease; // Ease _rawEase; bool _inited = false; @@ -177,22 +195,7 @@ class GTween { bool _gc = false; GTween(this.target, double duration, this.vars, [GVars? myVars]) { - if (_reservedProps == null) { - _reservedProps = { - 'delay': 1, - 'ease': 1, - 'usedFrames': 1, - 'overwrite': 1, - 'onComplete': 1, - 'runBackwards': 1, - 'immediateRender': 1, - 'onUpdate': 1, - 'startAt': 1, - }; - _time = getTimer() / 1000; - _frame = 0; - ticker.add(_updateRoot); - } + if (!GTween.initializedEngine) GTween._initEngine(); nanoVars = myVars ?? GVars(); nanoVars.defaults(); @@ -230,7 +233,7 @@ class GTween { } // _rawEase = nanoVars.ease; // _ease = _rawEase?.getRatio; - _ease = nanoVars.ease; + _ease = nanoVars.ease ?? GTween.defaultEase; _useFrames = nanoVars.useFrames ?? false; _startTime = (_useFrames ? _frame : _time) + (nanoVars.delay ?? 0); @@ -241,19 +244,19 @@ class GTween { killTweensOf(target); } } - _prev = _last; - if (_last != null) { - _last!._next = this; + _prev = GTween._last; + if (GTween._last != null) { + GTween._last!._next = this; } else { - _first = this; + GTween._first = this; } - _last = this; + GTween._last = this; if (nanoVars.immediateRender! || (duration == 0 && nanoVars.delay == 0 && nanoVars.immediateRender != false)) { - _render(0); + _render(0.0); } } @@ -287,10 +290,13 @@ class GTween { if (target == null) return; for (final key in vars!.keys) { final prop = '$key'; - if (!_reservedProps!.containsKey(prop)) { + if (!GTween._reservedProps.containsKey(prop)) { _firstPT = PropTween( - target: target as GTweenable?, property: key, next: _firstPT); - var startVal = _getStartValue(target, key); + target: target as GTweenable, + property: key, + next: _firstPT, + ); + final startVal = _getStartValue(target, key); _firstPT!.s = startVal; var endValue = _getEndValue(vars!, key, _firstPT!.s); _firstPT!.cObj = vars![key]; @@ -325,7 +331,7 @@ class GTween { void _setCurrentValue(PropTween pt, double ratio) { var value = pt.c! * ratio + pt.s; if (pt.t is GTweenable) { - pt.t!.setProperty(pt.p, value); + pt.t!.setProperty(pt.p!, value); } else { pt.t![pt.p as String] = value; } @@ -337,16 +343,16 @@ class GTween { } else if (t is Map) { return t[prop]; } - throw 'error'; + throw 'GTween Error: property not found.'; } - void _render(double? time) { + void _render(double time) { if (!_inited) { _init(); - time = 0; + time = 0.0; } var prevTime = time; - if (time! >= _duration!) { + if (time >= _duration) { time = _duration; ratio = 1; } else if (time <= 0) { @@ -356,7 +362,7 @@ class GTween { ratio = 0; } else { // ratio = _ease.getRatio(time / _duration); - ratio = _ease!(time / _duration!); + ratio = _ease(time / _duration); } var pt = _firstPT; @@ -508,11 +514,11 @@ class GTween { _frame += 1; // _time = getTimer() * .001; if (delta <= 0) delta = .016; - _time += delta * timeScale; - var tween = _first; + GTween._time += delta * GTween.timeScale; + var tween = GTween._first; while (tween != null) { var next = tween._next; - var t = tween._useFrames ? _frame : _time; + double t = tween._useFrames ? GTween._frame : GTween._time; if (t >= tween._startTime && !tween._gc) { tween._render(t - tween._startTime); } diff --git a/lib/src/tween/src/mixins/tweenable.dart b/lib/src/tween/src/mixins/tweenable.dart index 1fe63c6..04561cf 100644 --- a/lib/src/tween/src/mixins/tweenable.dart +++ b/lib/src/tween/src/mixins/tweenable.dart @@ -30,8 +30,9 @@ mixin GTweenable { /// override to know which properties will change. void setTweenProp(PropTween tweenProp) { - final lerpObj = _lerps[tweenProp.p as String]; - if (lerpObj == null) return; + final key = '${tweenProp.p}'; + if( !_lerps.containsKey(key)) return ; + final lerpObj = _lerps[key]!; lerpObj.to = tweenProp.cObj; tweenProp.c = 1.0; } @@ -55,14 +56,21 @@ mixin GTweenable { /// implement in class. Map>? getTweenableAccessors() => null; - void setProperty(Object? prop, double value) { - if (_lerps[prop as String] != null) { - _lerps[prop]!.resolve(value); - // TODO: add setLerp(prop, value) function to be override? + void setProperty(Object prop, double value) { + final key = '$prop'; + if (_lerps.containsKey(key)){ + _lerps[key]?.resolve(value); } else { if (_accessors == null) initProps(); - _accessors![prop]![1](value); + _accessors![key]![1](value); } + // if (_lerps[prop as String] != null) { + // _lerps[prop]!.resolve(value); + // // TODO: add setLerp(prop, value) function to be override? + // } else { + // if (_accessors == null) initProps(); + // _accessors![prop]![1](value); + // } } double getProperty(Object prop) { @@ -83,5 +91,5 @@ mixin GTweenable { double? operator [](String key) => getProperty(key); - void operator []=(String? key, double value) => setProperty(key, value); + void operator []=(String key, double value) => setProperty(key, value); } diff --git a/lib/src/tween/src/wraps/common_wraps.dart b/lib/src/tween/src/wraps/common_wraps.dart index c16b212..527c40e 100644 --- a/lib/src/tween/src/wraps/common_wraps.dart +++ b/lib/src/tween/src/wraps/common_wraps.dart @@ -145,14 +145,16 @@ class GTweenableList with GTweenable { } @override - void setProperty(Object? prop, double val) { + void setProperty(Object prop, double val) { final index = int.tryParse('$prop')!; value[index] = convertFromDouble(value[index], val); } @override double getProperty(Object prop) { - return convertToDouble(value[int.parse('$prop')]); + final idx = int.parse('$prop'); + final output = convertToDouble(value[idx]); + return output; } GTween tween( diff --git a/lib/src/widgets/graphx_widget.dart b/lib/src/widgets/graphx_widget.dart index 0d77d6d..7e322d8 100644 --- a/lib/src/widgets/graphx_widget.dart +++ b/lib/src/widgets/graphx_widget.dart @@ -48,7 +48,6 @@ class _SceneBuilderWidgetState extends State { GRect? _getRenderObjectWindowBounds() { if (!mounted) return null; - trace(context); return ContextUtils.getRenderObjectBounds(context); } @@ -81,30 +80,30 @@ class _SceneBuilderWidgetState extends State { ); var converter = _controller.$inputConverter; - if (_controller.config.usePointer ?? false) { + if (_controller.config.usePointer) { child = MouseRegion( - onEnter: converter?.pointerEnter, - onExit: converter?.pointerExit, - onHover: converter?.pointerHover, + onEnter: converter.pointerEnter, + onExit: converter.pointerExit, + onHover: converter.pointerHover, cursor: MouseCursor.defer, opaque: widget.mouseOpaque, child: Listener( child: child, behavior: widget.pointerBehaviour, - onPointerDown: converter?.pointerDown, - onPointerUp: converter?.pointerUp, - onPointerCancel: converter?.pointerCancel, - onPointerMove: converter?.pointerMove, - onPointerSignal: converter?.pointerSignal, + onPointerDown: converter.pointerDown, + onPointerUp: converter.pointerUp, + onPointerCancel: converter.pointerCancel, + onPointerMove: converter.pointerMove, + onPointerSignal: converter.pointerSignal, ), ); } - if (_controller.config.useKeyboard ?? false) { + if (_controller.config.useKeyboard) { child = RawKeyboardListener( - onKey: converter!.handleKey, + onKey: converter.handleKey, autofocus: true, includeSemantics: false, - focusNode: converter.keyboard?.focusNode ?? FocusNode(), + focusNode: converter.keyboard.focusNode, child: child, ); } diff --git a/pubspec.lock b/pubspec.lock index 7efaa62..1aa1395 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -73,7 +73,7 @@ packages: name: http url: "https://pub.dartlang.org" source: hosted - version: "0.13.0" + version: "0.13.1" http_parser: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 5b7ff0a..bc79318 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: graphx description: Render API on top of CustomPainter to power-up your Flutter apps to the next level. -version: 0.9.9 +version: 1.0.0-nullsafety.0 homepage: https://github.com/roipeker/graphx environment: @@ -9,8 +9,8 @@ environment: dependencies: flutter: sdk: flutter - xml: ^5.0.0-nullsafety.1 - http: ^0.13.0-nullsafety.0 + xml: ^5.0.2 + http: ^0.13.1 flutter_svg: ^0.21.0-nullsafety.0 dev_dependencies: From 2bb46ec580beafbad4cbd69d8436c24786199b8a Mon Sep 17 00:00:00 2001 From: Roi Peker Date: Thu, 25 Mar 2021 23:01:38 -0300 Subject: [PATCH 13/22] Update graphics.dart - fixes an error in `Graphics.drawPoly()`. --- lib/src/render/graphics.dart | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/src/render/graphics.dart b/lib/src/render/graphics.dart index f109280..a57e17c 100644 --- a/lib/src/render/graphics.dart +++ b/lib/src/render/graphics.dart @@ -474,13 +474,17 @@ class Graphics with RenderUtilMixin implements GxRenderable { return this; } + /// Draws a complex polygon from a List of `GPoint`. + /// Is similar to use [moveTo] and [lineTo] methods but in one command.. + /// [closePolygon] will close the shape (defaults to `true`). + /// See dart:ui [Path.addPolygon]. Graphics drawPoly(List points, [bool closePolygon = true]) { final len = points.length; - final list = List.filled(len, null); + final list = List.filled(len, Offset.zero); for (var i = 0; i < len; ++i) { list[i] = points[i].toNative(); } - _path!.addPolygon(list as List, true); + _path!.addPolygon(list, true); return this; } From 348a86b63bf222641d48ffe9f8f1d5b7dba6fa57 Mon Sep 17 00:00:00 2001 From: Misko Lee Date: Thu, 27 May 2021 20:46:27 +0800 Subject: [PATCH 14/22] 1. support long press like flutter --- README.md | 7 ++++ lib/src/core/scene_painter.dart | 1 + lib/src/display/display_object.dart | 35 +++++++++++++++++-- lib/src/display/stage.dart | 2 ++ lib/src/events/mixins.dart | 9 +++++ lib/src/events/signal.dart | 13 ++++++++ lib/src/render/graphics.dart | 1 - pubspec.lock | 52 ++++++++++++++--------------- 8 files changed, 91 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 8e50741..907e16f 100644 --- a/README.md +++ b/README.md @@ -213,9 +213,16 @@ There are a bunch of signals to listen on each object... taken from AS3, and JS. - onMouseOver - onMouseOut - onMouseScroll +- onLongPress(Duration duration,double distance) They all emit a `MouseInputData` with all the needed info inside, like stage coordinates, or translated local coordinates, which "mouse" button is pressed, etc. +Specially on event `onLongPress`, the handler register function differcent others, it’s includes two params for configure the event, one of `Duration duration`, it’s mean keep press how long for trigg the event, another is `distance`. + +Why need `distance` ? + +Beacuse of human can not keep static on screen, so, we are always trigged event `MouseMove`, but event `LongPress` will be cancelled automaticlly other event happed. It’s also mean when I pressed screen and other event happed before `duration`, So, it’s NOT LONG PRESS. + --- ### Demos. diff --git a/lib/src/core/scene_painter.dart b/lib/src/core/scene_painter.dart index 1dbe1be..7370b45 100644 --- a/lib/src/core/scene_painter.dart +++ b/lib/src/core/scene_painter.dart @@ -41,6 +41,7 @@ class ScenePainter with EventDispatcherMixin { /// Runs on the first "render". bool _isReady = false; + bool get isReady => _isReady; /// Automatically manage the `tick()` and `render()` requests. diff --git a/lib/src/display/display_object.dart b/lib/src/display/display_object.dart index f0bfbaf..4531d81 100644 --- a/lib/src/display/display_object.dart +++ b/lib/src/display/display_object.dart @@ -1,6 +1,8 @@ +import 'dart:async'; import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart' as painting; +import 'package:graphx/src/events/events.dart'; import '../../graphx.dart'; abstract class GDisplayObject @@ -13,7 +15,7 @@ abstract class GDisplayObject static GDisplayObject $currentDrag; static GRect $currentDragBounds; GPoint _dragCenterOffset; - + MouseInputData _lastMouseInput; /// Lets the user drag the specified sprite. /// The sprite remains draggable until explicitly stopped through a call to /// the Sprite.stopDrag() method, or until another sprite is made draggable. @@ -75,6 +77,7 @@ abstract class GDisplayObject bool $debugBounds = false; bool mouseUseShape = false; + Timer _longPressTimer; List $filters; @@ -138,6 +141,15 @@ abstract class GDisplayObject $onMouseWheel?.dispatch(mouseInput); break; case MouseInputType.down: + if(_longPressTimer != null) { + _longPressTimer.cancel(); + _longPressTimer = null; + } + if($onLongPress != null) { + _longPressTimer = Timer($onLongPress.configure[EventSignalConfKey.LongPressDuration], () { + $onLongPress?.dispatch(mouseInput); + }); + } $mouseDownObj = object; $onMouseDown?.dispatch(mouseInput); break; @@ -146,14 +158,29 @@ abstract class GDisplayObject // $onRightMouseDown?.dispatch(mouseInput); // break; case MouseInputType.move: + if(_lastMouseInput != null && $onLongPress != null) { + // ignore: lines_longer_than_80_chars + if((_lastMouseInput.localX - input.localX).abs() > + // ignore: lines_longer_than_80_chars + $onLongPress.configure[EventSignalConfKey.LongPressShakingDistance] || + (_lastMouseInput.localY - input.localY).abs() > + // ignore: lines_longer_than_80_chars + $onLongPress.configure[EventSignalConfKey.LongPressShakingDistance] + ) { + _longPressTimer?.cancel(); + _longPressTimer = null; + } + } $onMouseMove?.dispatch(mouseInput); break; case MouseInputType.up: + _longPressTimer?.cancel(); + _longPressTimer = null; + if ($mouseDownObj == object && ($onMouseClick != null || $onMouseDoubleClick != null)) { var mouseClickInput = input.clone(this, object, MouseInputType.up); $onMouseClick?.dispatch(mouseClickInput); - if ($lastClickTime > 0 && input.time - $lastClickTime < MouseInputData.doubleClickTime) { $onMouseDoubleClick?.dispatch(mouseClickInput); @@ -166,6 +193,7 @@ abstract class GDisplayObject $onMouseUp?.dispatch(mouseInput); break; case MouseInputType.over: + _longPressTimer?.cancel(); $mouseOverObj = object; if (useCursor && GMouse.isShowing()) { GMouse.setClickCursor(); @@ -173,6 +201,8 @@ abstract class GDisplayObject $onMouseOver?.dispatch(mouseInput); break; case MouseInputType.out: + _longPressTimer?.cancel(); + _longPressTimer = null; $mouseOverObj = null; if (useCursor && GMouse.isShowing()) { GMouse.cursor = null; @@ -184,6 +214,7 @@ abstract class GDisplayObject } } $parent?.$dispatchMouseCallback(type, object, input); + _lastMouseInput = input.clone(this, object, type); } /// todo: add caching to local bounds (Rect). diff --git a/lib/src/display/stage.dart b/lib/src/display/stage.dart index 7d2797f..cf78d18 100644 --- a/lib/src/display/stage.dart +++ b/lib/src/display/stage.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:ui' as ui; import '../../graphx.dart'; @@ -40,6 +41,7 @@ class Stage extends GDisplayObjectContainer ui.Paint _backgroundPaint; DisplayBoundsDebugger _boundsDebugger; + /// Shortcut to access the owner [SceneController]. SceneController get controller => scene.core; diff --git a/lib/src/events/mixins.dart b/lib/src/events/mixins.dart index d5c5753..1cc2ca2 100644 --- a/lib/src/events/mixins.dart +++ b/lib/src/events/mixins.dart @@ -125,6 +125,7 @@ mixin MouseSignalsMixin { EventSignal $onMouseOut; EventSignal $onMouseOver; EventSignal $onMouseWheel; + EventSignal $onLongPress; EventSignal get onMouseClick => $onMouseClick ??= EventSignal(); EventSignal get onMouseDoubleClick => @@ -137,6 +138,12 @@ mixin MouseSignalsMixin { EventSignal get onMouseOut => $onMouseOut ??= EventSignal(); EventSignal get onMouseScroll => $onMouseWheel ??= EventSignal(); + EventSignal onLongPress([Duration duration = + const Duration(milliseconds: 600),double distance = 1]) { + $onLongPress = EventSignal.longPress(duration,distance); + return $onLongPress; + } + void $disposePointerSignals() { $onRightMouseDown?.removeAll(); $onRightMouseDown = null; @@ -156,6 +163,8 @@ mixin MouseSignalsMixin { $onMouseOut = null; $onMouseWheel?.removeAll(); $onMouseWheel = null; + $onLongPress?.removeAll(); + $onLongPress = null; } } diff --git a/lib/src/events/signal.dart b/lib/src/events/signal.dart index 44c726f..56f2252 100644 --- a/lib/src/events/signal.dart +++ b/lib/src/events/signal.dart @@ -64,7 +64,20 @@ class Signal { } } +enum EventSignalConfKey { + LongPressDuration, + LongPressShakingDistance, +} + class EventSignal { + Map configure = {}; + EventSignal(); + factory EventSignal.longPress(Duration duration,double distance) { + var signal = EventSignal(); + signal.configure[EventSignalConfKey.LongPressDuration] = duration; + signal.configure[EventSignalConfKey.LongPressShakingDistance] = distance; + return signal; + } void call(EventSignalCallback callback) { add(callback); } diff --git a/lib/src/render/graphics.dart b/lib/src/render/graphics.dart index a1a71a4..a6fadce 100644 --- a/lib/src/render/graphics.dart +++ b/lib/src/render/graphics.dart @@ -700,7 +700,6 @@ class Graphics with RenderUtilMixin implements GxRenderable { } _constrainAlpha(); if (!_isVisible) return; - // trace("en", _drawingQueue.length); for (var graph in _drawingQueue) { if (graph.hasPicture) { diff --git a/pubspec.lock b/pubspec.lock index b2b92c7..02abaed 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,63 +5,63 @@ packages: dependency: transitive description: name: async - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "2.5.0" boolean_selector: dependency: transitive description: name: boolean_selector - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.0" characters: dependency: transitive description: name: characters - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.1.0" charcode: dependency: transitive description: name: charcode - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.2.0" clock: dependency: transitive description: name: clock - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.1.0" collection: dependency: transitive description: name: collection - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.15.0" convert: dependency: transitive description: name: convert - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.1" effective_dart: dependency: "direct dev" description: name: effective_dart - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.3.1" fake_async: dependency: transitive description: name: fake_async - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.2.0" flutter: @@ -78,49 +78,49 @@ packages: dependency: "direct main" description: name: http - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted - version: "0.13.1" + version: "0.13.3" http_parser: dependency: transitive description: name: http_parser - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "4.0.0" matcher: dependency: transitive description: name: matcher - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "0.12.10" meta: dependency: transitive description: name: meta - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.3.0" path: dependency: transitive description: name: path - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.8.0" pedantic: dependency: "direct dev" description: name: pedantic - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.11.0" petitparser: dependency: transitive description: name: petitparser - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "3.1.0" sky_engine: @@ -132,63 +132,63 @@ packages: dependency: transitive description: name: source_span - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.8.0" stack_trace: dependency: transitive description: name: stack_trace - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.10.0" stream_channel: dependency: transitive description: name: stream_channel - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.0" string_scanner: dependency: transitive description: name: string_scanner - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.1.0" term_glyph: dependency: transitive description: name: term_glyph - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.2.0" test_api: dependency: transitive description: name: test_api - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "0.2.19" typed_data: dependency: transitive description: name: typed_data - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.3.0" vector_math: dependency: transitive description: name: vector_math - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.0" xml: dependency: "direct main" description: name: xml - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "4.5.1" sdks: From 21a3ced9f2b892be9a4e6e41b766ae4874f63883 Mon Sep 17 00:00:00 2001 From: Misko Lee Date: Tue, 1 Jun 2021 01:03:15 +0800 Subject: [PATCH 15/22] fix bug: update event.type to long press --- lib/src/display/display_object.dart | 1 + lib/src/events/pointer_data.dart | 1 + 2 files changed, 2 insertions(+) diff --git a/lib/src/display/display_object.dart b/lib/src/display/display_object.dart index 4531d81..85e0e0a 100644 --- a/lib/src/display/display_object.dart +++ b/lib/src/display/display_object.dart @@ -147,6 +147,7 @@ abstract class GDisplayObject } if($onLongPress != null) { _longPressTimer = Timer($onLongPress.configure[EventSignalConfKey.LongPressDuration], () { + mouseInput.type = MouseInputType.longPress; $onLongPress?.dispatch(mouseInput); }); } diff --git a/lib/src/events/pointer_data.dart b/lib/src/events/pointer_data.dart index 7ff9fe9..8e74773 100644 --- a/lib/src/events/pointer_data.dart +++ b/lib/src/events/pointer_data.dart @@ -97,6 +97,7 @@ enum MouseInputType { click, still, wheel, + longPress, /// check button directly with: isPrimaryDown, isSecondaryDown... // rightDown, From bb5dd6f980d152a3a3dc8f16d9c17b086dea1993 Mon Sep 17 00:00:00 2001 From: Misko Lee Date: Tue, 1 Jun 2021 18:08:53 +0800 Subject: [PATCH 16/22] 1. keep event signal stateless. --- README.md | 9 +++------ lib/src/display/display_object.dart | 11 ++++++----- lib/src/events/mixins.dart | 7 +------ lib/src/events/signal.dart | 13 ------------- 4 files changed, 10 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 907e16f..1e42fde 100644 --- a/README.md +++ b/README.md @@ -213,15 +213,12 @@ There are a bunch of signals to listen on each object... taken from AS3, and JS. - onMouseOver - onMouseOut - onMouseScroll -- onLongPress(Duration duration,double distance) +- onLongPress They all emit a `MouseInputData` with all the needed info inside, like stage coordinates, or translated local coordinates, which "mouse" button is pressed, etc. -Specially on event `onLongPress`, the handler register function differcent others, it’s includes two params for configure the event, one of `Duration duration`, it’s mean keep press how long for trigg the event, another is `distance`. - -Why need `distance` ? - -Beacuse of human can not keep static on screen, so, we are always trigged event `MouseMove`, but event `LongPress` will be cancelled automaticlly other event happed. It’s also mean when I pressed screen and other event happed before `duration`, So, it’s NOT LONG PRESS. +Class `DisplayObject` has two param to control the `LongPress` event how to works. +one of `longPressDuration`, another is `longPressDistance`. --- diff --git a/lib/src/display/display_object.dart b/lib/src/display/display_object.dart index 85e0e0a..c5bab5d 100644 --- a/lib/src/display/display_object.dart +++ b/lib/src/display/display_object.dart @@ -16,6 +16,9 @@ abstract class GDisplayObject static GRect $currentDragBounds; GPoint _dragCenterOffset; MouseInputData _lastMouseInput; + Duration longPressDelay = Duration(milliseconds: 600); + double longPressDistance = 1.0; + /// Lets the user drag the specified sprite. /// The sprite remains draggable until explicitly stopped through a call to /// the Sprite.stopDrag() method, or until another sprite is made draggable. @@ -146,7 +149,7 @@ abstract class GDisplayObject _longPressTimer = null; } if($onLongPress != null) { - _longPressTimer = Timer($onLongPress.configure[EventSignalConfKey.LongPressDuration], () { + _longPressTimer = Timer(longPressDelay, () { mouseInput.type = MouseInputType.longPress; $onLongPress?.dispatch(mouseInput); }); @@ -162,11 +165,9 @@ abstract class GDisplayObject if(_lastMouseInput != null && $onLongPress != null) { // ignore: lines_longer_than_80_chars if((_lastMouseInput.localX - input.localX).abs() > - // ignore: lines_longer_than_80_chars - $onLongPress.configure[EventSignalConfKey.LongPressShakingDistance] || + longPressDistance || (_lastMouseInput.localY - input.localY).abs() > - // ignore: lines_longer_than_80_chars - $onLongPress.configure[EventSignalConfKey.LongPressShakingDistance] + longPressDistance ) { _longPressTimer?.cancel(); _longPressTimer = null; diff --git a/lib/src/events/mixins.dart b/lib/src/events/mixins.dart index 1cc2ca2..c3bad68 100644 --- a/lib/src/events/mixins.dart +++ b/lib/src/events/mixins.dart @@ -137,12 +137,7 @@ mixin MouseSignalsMixin { EventSignal get onMouseOver => $onMouseOver ??= EventSignal(); EventSignal get onMouseOut => $onMouseOut ??= EventSignal(); EventSignal get onMouseScroll => $onMouseWheel ??= EventSignal(); - - EventSignal onLongPress([Duration duration = - const Duration(milliseconds: 600),double distance = 1]) { - $onLongPress = EventSignal.longPress(duration,distance); - return $onLongPress; - } + EventSignal get onLongPress => $onLongPress ??= EventSignal(); void $disposePointerSignals() { $onRightMouseDown?.removeAll(); diff --git a/lib/src/events/signal.dart b/lib/src/events/signal.dart index 56f2252..44c726f 100644 --- a/lib/src/events/signal.dart +++ b/lib/src/events/signal.dart @@ -64,20 +64,7 @@ class Signal { } } -enum EventSignalConfKey { - LongPressDuration, - LongPressShakingDistance, -} - class EventSignal { - Map configure = {}; - EventSignal(); - factory EventSignal.longPress(Duration duration,double distance) { - var signal = EventSignal(); - signal.configure[EventSignalConfKey.LongPressDuration] = duration; - signal.configure[EventSignalConfKey.LongPressShakingDistance] = distance; - return signal; - } void call(EventSignalCallback callback) { add(callback); } From edf534981b9334efb295c7b331998a0914b63c97 Mon Sep 17 00:00:00 2001 From: Misko Lee Date: Sun, 18 Jul 2021 13:32:14 +0800 Subject: [PATCH 17/22] 1. fix null-safety --- lib/src/display/display_object.dart | 8 ++-- pubspec.lock | 72 ++++++++++++++--------------- 2 files changed, 40 insertions(+), 40 deletions(-) diff --git a/lib/src/display/display_object.dart b/lib/src/display/display_object.dart index 45d4d7c..16bd20d 100644 --- a/lib/src/display/display_object.dart +++ b/lib/src/display/display_object.dart @@ -80,7 +80,7 @@ abstract class GDisplayObject bool $debugBounds = false; bool mouseUseShape = false; - Timer _longPressTimer; + Timer? _longPressTimer; List? $filters; @@ -145,7 +145,7 @@ abstract class GDisplayObject break; case MouseInputType.down: if(_longPressTimer != null) { - _longPressTimer.cancel(); + _longPressTimer?.cancel(); _longPressTimer = null; } if($onLongPress != null) { @@ -164,9 +164,9 @@ abstract class GDisplayObject case MouseInputType.move: if(_lastMouseInput != null && $onLongPress != null) { // ignore: lines_longer_than_80_chars - if((_lastMouseInput.localX - input.localX).abs() > + if((_lastMouseInput!.localX - input.localX).abs() > longPressDistance || - (_lastMouseInput.localY - input.localY).abs() > + (_lastMouseInput!.localY - input.localY).abs() > longPressDistance ) { _longPressTimer?.cancel(); diff --git a/pubspec.lock b/pubspec.lock index 1aa1395..174accc 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,49 +5,49 @@ packages: dependency: transitive description: name: async - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.5.0" + version: "2.6.1" boolean_selector: dependency: transitive description: name: boolean_selector - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.0" characters: dependency: transitive description: name: characters - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.1.0" charcode: dependency: transitive description: name: charcode - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.2.0" clock: dependency: transitive description: name: clock - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.1.0" collection: dependency: transitive description: name: collection - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.15.0" fake_async: dependency: transitive description: name: fake_async - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.2.0" flutter: @@ -59,9 +59,9 @@ packages: dependency: "direct main" description: name: flutter_svg - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted - version: "0.21.0-nullsafety.0" + version: "0.21.0+1" flutter_test: dependency: "direct dev" description: flutter @@ -71,65 +71,65 @@ packages: dependency: "direct main" description: name: http - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted - version: "0.13.1" + version: "0.13.3" http_parser: dependency: transitive description: name: http_parser - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "4.0.0" matcher: dependency: transitive description: name: matcher - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "0.12.10" meta: dependency: transitive description: name: meta - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.3.0" path: dependency: transitive description: name: path - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.8.0" path_drawing: dependency: transitive description: name: path_drawing - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted - version: "0.5.0-nullsafety.0" + version: "0.5.1" path_parsing: dependency: transitive description: name: path_parsing - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted - version: "0.2.0-nullsafety.0" + version: "0.2.1" pedantic: dependency: transitive description: name: pedantic - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted - version: "1.11.0" + version: "1.11.1" petitparser: dependency: transitive description: name: petitparser - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted - version: "4.0.2" + version: "4.1.0" sky_engine: dependency: transitive description: flutter @@ -139,65 +139,65 @@ packages: dependency: transitive description: name: source_span - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted - version: "1.8.0" + version: "1.8.1" stack_trace: dependency: transitive description: name: stack_trace - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.10.0" stream_channel: dependency: transitive description: name: stream_channel - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.0" string_scanner: dependency: transitive description: name: string_scanner - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.1.0" term_glyph: dependency: transitive description: name: term_glyph - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.2.0" test_api: dependency: transitive description: name: test_api - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted - version: "0.2.19" + version: "0.3.0" typed_data: dependency: transitive description: name: typed_data - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "1.3.0" vector_math: dependency: transitive description: name: vector_math - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.0" xml: dependency: "direct main" description: name: xml - url: "https://pub.dartlang.org" + url: "https://pub.flutter-io.cn" source: hosted - version: "5.0.2" + version: "5.1.2" sdks: dart: ">=2.12.0 <3.0.0" flutter: ">=1.24.0-7.0" From cad40777dc0b31e55be0f4baff78a49842d2c55b Mon Sep 17 00:00:00 2001 From: Misko Lee Date: Wed, 1 Sep 2021 21:05:53 +0800 Subject: [PATCH 18/22] 1. disable drag event to parent --- lib/src/core/scene_controller.dart | 15 ++++++++++++ lib/src/widgets/graphx_widget.dart | 38 ++++++++++++++++++------------ 2 files changed, 38 insertions(+), 15 deletions(-) diff --git a/lib/src/core/scene_controller.dart b/lib/src/core/scene_controller.dart index 22ed664..bb9a2f8 100644 --- a/lib/src/core/scene_controller.dart +++ b/lib/src/core/scene_controller.dart @@ -25,6 +25,19 @@ class SceneController { ScenePainter? backScene, frontScene; + MouseCursor? _currentCursor; + + + MouseCursor? get currentCursor => _currentCursor; + + // ignore: unnecessary_getters_setters + set currentCursor(MouseCursor? value) { + _currentCursor = value; + if(onUpdate != null) { + onUpdate!(); + } + } + /// Access the `ticker` (if any) created by this SceneController. GTicker? get ticker { if (_ticker == null) { @@ -47,6 +60,8 @@ class SceneController { late KeyboardManager _keyboard; late PointerManager _pointer; + Function? onUpdate; + GTicker? _ticker; late InputConverter $inputConverter; diff --git a/lib/src/widgets/graphx_widget.dart b/lib/src/widgets/graphx_widget.dart index 7e322d8..49ab30e 100644 --- a/lib/src/widgets/graphx_widget.dart +++ b/lib/src/widgets/graphx_widget.dart @@ -41,9 +41,13 @@ class _SceneBuilderWidgetState extends State { void initState() { super.initState(); _controller = widget.builder(); - _controller.resolveWindowBounds = _getRenderObjectWindowBounds; _controller.$init(); + _controller.onUpdate = ((){ + setState(() { + print("Update ....."); + }); + }); } GRect? _getRenderObjectWindowBounds() { @@ -81,21 +85,25 @@ class _SceneBuilderWidgetState extends State { var converter = _controller.$inputConverter; if (_controller.config.usePointer) { - child = MouseRegion( - onEnter: converter.pointerEnter, - onExit: converter.pointerExit, - onHover: converter.pointerHover, - cursor: MouseCursor.defer, - opaque: widget.mouseOpaque, - child: Listener( - child: child, - behavior: widget.pointerBehaviour, - onPointerDown: converter.pointerDown, - onPointerUp: converter.pointerUp, - onPointerCancel: converter.pointerCancel, - onPointerMove: converter.pointerMove, - onPointerSignal: converter.pointerSignal, + child = GestureDetector( + child: MouseRegion( + onEnter: converter.pointerEnter, + onExit: converter.pointerExit, + onHover: converter.pointerHover, + cursor: MouseCursor.defer, + opaque: widget.mouseOpaque, + child: Listener( + child: child, + behavior: widget.pointerBehaviour, + onPointerDown: converter.pointerDown, + onPointerUp: converter.pointerUp, + onPointerCancel: converter.pointerCancel, + onPointerMove: converter.pointerMove, + onPointerSignal: converter.pointerSignal, + ), ), + onVerticalDragUpdate: (d){}, + onHorizontalDragUpdate: (d){}, ); } if (_controller.config.useKeyboard) { From 1940d1400ab8fc31cf16d9b6b93050014b210b10 Mon Sep 17 00:00:00 2001 From: Misko Lee Date: Fri, 3 Sep 2021 17:12:59 +0800 Subject: [PATCH 19/22] 1. update keyboard --- lib/src/utils/keyboard_util.dart | 73 ++++++++++++++++---------------- 1 file changed, 36 insertions(+), 37 deletions(-) diff --git a/lib/src/utils/keyboard_util.dart b/lib/src/utils/keyboard_util.dart index 214a1c3..0c7acac 100644 --- a/lib/src/utils/keyboard_util.dart +++ b/lib/src/utils/keyboard_util.dart @@ -4,7 +4,7 @@ import '../../graphx.dart'; /// Utility class to work easily with keyboard events. class GKeyboard { - final LogicalKeyboardKey value; + final KeyboardKey value; const GKeyboard._(this.value); @@ -13,25 +13,24 @@ class GKeyboard { static const right = GKeyboard._(LogicalKeyboardKey.arrowRight); static const down = GKeyboard._(LogicalKeyboardKey.arrowDown); - static const none = GKeyboard._(LogicalKeyboardKey.none); static const hyper = GKeyboard._(LogicalKeyboardKey.hyper); static const superKey = GKeyboard._(LogicalKeyboardKey.superKey); static const fnLock = GKeyboard._(LogicalKeyboardKey.fnLock); static const suspend = GKeyboard._(LogicalKeyboardKey.suspend); static const resume = GKeyboard._(LogicalKeyboardKey.resume); - static const turbo = GKeyboard._(LogicalKeyboardKey.turbo); + static const turbo = GKeyboard._(PhysicalKeyboardKey.turbo); static const privacyScreenToggle = - GKeyboard._(LogicalKeyboardKey.privacyScreenToggle); + GKeyboard._(PhysicalKeyboardKey.privacyScreenToggle); static const sleep = GKeyboard._(LogicalKeyboardKey.sleep); static const wakeUp = GKeyboard._(LogicalKeyboardKey.wakeUp); static const displayToggleIntExt = - GKeyboard._(LogicalKeyboardKey.displayToggleIntExt); - static const usbReserved = GKeyboard._(LogicalKeyboardKey.usbReserved); + GKeyboard._(PhysicalKeyboardKey.displayToggleIntExt); + static const usbReserved = GKeyboard._(PhysicalKeyboardKey.usbReserved); static const usbErrorRollOver = - GKeyboard._(LogicalKeyboardKey.usbErrorRollOver); - static const usbPostFail = GKeyboard._(LogicalKeyboardKey.usbPostFail); + GKeyboard._(PhysicalKeyboardKey.usbErrorRollOver); + static const usbPostFail = GKeyboard._(PhysicalKeyboardKey.usbPostFail); static const usbErrorUndefined = - GKeyboard._(LogicalKeyboardKey.usbErrorUndefined); + GKeyboard._(PhysicalKeyboardKey.usbErrorUndefined); static const keyA = GKeyboard._(LogicalKeyboardKey.keyA); static const keyB = GKeyboard._(LogicalKeyboardKey.keyB); static const keyC = GKeyboard._(LogicalKeyboardKey.keyC); @@ -175,22 +174,22 @@ class GKeyboard { static const numpadParenRight = GKeyboard._(LogicalKeyboardKey.numpadParenRight); static const numpadBackspace = - GKeyboard._(LogicalKeyboardKey.numpadBackspace); + GKeyboard._(PhysicalKeyboardKey.numpadBackspace); static const numpadMemoryStore = - GKeyboard._(LogicalKeyboardKey.numpadMemoryStore); + GKeyboard._(PhysicalKeyboardKey.numpadMemoryStore); static const numpadMemoryRecall = - GKeyboard._(LogicalKeyboardKey.numpadMemoryRecall); + GKeyboard._(PhysicalKeyboardKey.numpadMemoryRecall); static const numpadMemoryClear = - GKeyboard._(LogicalKeyboardKey.numpadMemoryClear); + GKeyboard._(PhysicalKeyboardKey.numpadMemoryClear); static const numpadMemoryAdd = - GKeyboard._(LogicalKeyboardKey.numpadMemoryAdd); + GKeyboard._(PhysicalKeyboardKey.numpadMemoryAdd); static const numpadMemorySubtract = - GKeyboard._(LogicalKeyboardKey.numpadMemorySubtract); + GKeyboard._(PhysicalKeyboardKey.numpadMemorySubtract); static const numpadSignChange = - GKeyboard._(LogicalKeyboardKey.numpadSignChange); - static const numpadClear = GKeyboard._(LogicalKeyboardKey.numpadClear); + GKeyboard._(PhysicalKeyboardKey.numpadSignChange); + static const numpadClear = GKeyboard._(PhysicalKeyboardKey.numpadClear); static const numpadClearEntry = - GKeyboard._(LogicalKeyboardKey.numpadClearEntry); + GKeyboard._(PhysicalKeyboardKey.numpadClearEntry); static const controlLeft = GKeyboard._(LogicalKeyboardKey.controlLeft); static const shiftLeft = GKeyboard._(LogicalKeyboardKey.shiftLeft); static const altLeft = GKeyboard._(LogicalKeyboardKey.altLeft); @@ -205,17 +204,17 @@ class GKeyboard { static const brightnessUp = GKeyboard._(LogicalKeyboardKey.brightnessUp); static const brightnessDown = GKeyboard._(LogicalKeyboardKey.brightnessDown); static const brightnessToggle = - GKeyboard._(LogicalKeyboardKey.brightnessToggle); + GKeyboard._(PhysicalKeyboardKey.brightnessToggle); static const brightnessMinimum = - GKeyboard._(LogicalKeyboardKey.brightnessMinimum); + GKeyboard._(PhysicalKeyboardKey.brightnessMinimum); static const brightnessMaximum = - GKeyboard._(LogicalKeyboardKey.brightnessMaximum); - static const brightnessAuto = GKeyboard._(LogicalKeyboardKey.brightnessAuto); - static const kbdIllumUp = GKeyboard._(LogicalKeyboardKey.kbdIllumUp); - static const kbdIllumDown = GKeyboard._(LogicalKeyboardKey.kbdIllumDown); + GKeyboard._(PhysicalKeyboardKey.brightnessMaximum); + static const brightnessAuto = GKeyboard._(PhysicalKeyboardKey.brightnessAuto); + static const kbdIllumUp = GKeyboard._(PhysicalKeyboardKey.kbdIllumUp); + static const kbdIllumDown = GKeyboard._(PhysicalKeyboardKey.kbdIllumDown); static const mediaLast = GKeyboard._(LogicalKeyboardKey.mediaLast); static const launchPhone = GKeyboard._(LogicalKeyboardKey.launchPhone); - static const programGuide = GKeyboard._(LogicalKeyboardKey.programGuide); + static const programGuide = GKeyboard._(PhysicalKeyboardKey.programGuide); static const exit = GKeyboard._(LogicalKeyboardKey.exit); static const channelUp = GKeyboard._(LogicalKeyboardKey.channelUp); static const channelDown = GKeyboard._(LogicalKeyboardKey.channelDown); @@ -233,8 +232,8 @@ class GKeyboard { static const mediaPlayPause = GKeyboard._(LogicalKeyboardKey.mediaPlayPause); static const speechInputToggle = GKeyboard._(LogicalKeyboardKey.speechInputToggle); - static const bassBoost = GKeyboard._(LogicalKeyboardKey.bassBoost); - static const mediaSelect = GKeyboard._(LogicalKeyboardKey.mediaSelect); + static const bassBoost = GKeyboard._(PhysicalKeyboardKey.bassBoost); + static const mediaSelect = GKeyboard._(PhysicalKeyboardKey.mediaSelect); static const launchWordProcessor = GKeyboard._(LogicalKeyboardKey.launchWordProcessor); static const launchSpreadsheet = @@ -242,26 +241,26 @@ class GKeyboard { static const launchMail = GKeyboard._(LogicalKeyboardKey.launchMail); static const launchContacts = GKeyboard._(LogicalKeyboardKey.launchContacts); static const launchCalendar = GKeyboard._(LogicalKeyboardKey.launchCalendar); - static const launchApp2 = GKeyboard._(LogicalKeyboardKey.launchApp2); - static const launchApp1 = GKeyboard._(LogicalKeyboardKey.launchApp1); + static const launchApp2 = GKeyboard._(PhysicalKeyboardKey.launchApp2); + static const launchApp1 = GKeyboard._(PhysicalKeyboardKey.launchApp1); static const launchInternetBrowser = - GKeyboard._(LogicalKeyboardKey.launchInternetBrowser); + GKeyboard._(PhysicalKeyboardKey.launchInternetBrowser); static const logOff = GKeyboard._(LogicalKeyboardKey.logOff); - static const lockScreen = GKeyboard._(LogicalKeyboardKey.lockScreen); + static const lockScreen = GKeyboard._(PhysicalKeyboardKey.lockScreen); static const launchControlPanel = GKeyboard._(LogicalKeyboardKey.launchControlPanel); - static const selectTask = GKeyboard._(LogicalKeyboardKey.selectTask); + static const selectTask = GKeyboard._(PhysicalKeyboardKey.selectTask); static const launchDocuments = - GKeyboard._(LogicalKeyboardKey.launchDocuments); + GKeyboard._(PhysicalKeyboardKey.launchDocuments); static const spellCheck = GKeyboard._(LogicalKeyboardKey.spellCheck); static const launchKeyboardLayout = - GKeyboard._(LogicalKeyboardKey.launchKeyboardLayout); + GKeyboard._(PhysicalKeyboardKey.launchKeyboardLayout); static const launchScreenSaver = GKeyboard._(LogicalKeyboardKey.launchScreenSaver); static const launchAssistant = GKeyboard._(LogicalKeyboardKey.launchAssistant); static const launchAudioBrowser = - GKeyboard._(LogicalKeyboardKey.launchAudioBrowser); + GKeyboard._(PhysicalKeyboardKey.launchAudioBrowser); static const newKey = GKeyboard._(LogicalKeyboardKey.newKey); static const close = GKeyboard._(LogicalKeyboardKey.close); static const save = GKeyboard._(LogicalKeyboardKey.save); @@ -282,8 +281,8 @@ class GKeyboard { static const mailForward = GKeyboard._(LogicalKeyboardKey.mailForward); static const mailSend = GKeyboard._(LogicalKeyboardKey.mailSend); static const keyboardLayoutSelect = - GKeyboard._(LogicalKeyboardKey.keyboardLayoutSelect); - static const showAllWindows = GKeyboard._(LogicalKeyboardKey.showAllWindows); + GKeyboard._(PhysicalKeyboardKey.keyboardLayoutSelect); + static const showAllWindows = GKeyboard._(PhysicalKeyboardKey.showAllWindows); static const gameButton1 = GKeyboard._(LogicalKeyboardKey.gameButton1); static const gameButton2 = GKeyboard._(LogicalKeyboardKey.gameButton2); static const gameButton3 = GKeyboard._(LogicalKeyboardKey.gameButton3); From 616a02ca6b48eb334c94f783ac389ad8d0677cb9 Mon Sep 17 00:00:00 2001 From: Misko Lee Date: Mon, 13 Sep 2021 13:11:26 +0800 Subject: [PATCH 20/22] 1. add custom mouse cursor --- lib/src/widgets/graphx_widget.dart | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/src/widgets/graphx_widget.dart b/lib/src/widgets/graphx_widget.dart index 49ab30e..b78db3f 100644 --- a/lib/src/widgets/graphx_widget.dart +++ b/lib/src/widgets/graphx_widget.dart @@ -90,7 +90,8 @@ class _SceneBuilderWidgetState extends State { onEnter: converter.pointerEnter, onExit: converter.pointerExit, onHover: converter.pointerHover, - cursor: MouseCursor.defer, + cursor: _controller.currentCursor == null ? MouseCursor.defer + : _controller.currentCursor!, opaque: widget.mouseOpaque, child: Listener( child: child, From f61877a93436f604ceec474a9d3d9b27556f61fd Mon Sep 17 00:00:00 2001 From: Misko Lee Date: Mon, 13 Sep 2021 14:14:34 +0800 Subject: [PATCH 21/22] 1. add custom mouse cursor --- lib/src/widgets/graphx_widget.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/src/widgets/graphx_widget.dart b/lib/src/widgets/graphx_widget.dart index b78db3f..ae4390c 100644 --- a/lib/src/widgets/graphx_widget.dart +++ b/lib/src/widgets/graphx_widget.dart @@ -91,7 +91,7 @@ class _SceneBuilderWidgetState extends State { onExit: converter.pointerExit, onHover: converter.pointerHover, cursor: _controller.currentCursor == null ? MouseCursor.defer - : _controller.currentCursor!, +: _controller.currentCursor!, opaque: widget.mouseOpaque, child: Listener( child: child, From 05d3ca4c58eb7cb3b58a5a765d916dd94c6eed56 Mon Sep 17 00:00:00 2001 From: Misko Lee Date: Mon, 16 May 2022 00:44:55 +0800 Subject: [PATCH 22/22] 1. support flutter 3.0 --- lib/src/display/text.dart | 4 ++-- lib/src/events/pointer_data.dart | 4 ++-- lib/src/input/input_converter.dart | 8 ++++++++ lib/src/tween/src/gtween.dart | 2 +- 4 files changed, 13 insertions(+), 5 deletions(-) diff --git a/lib/src/display/text.dart b/lib/src/display/text.dart index afb42e3..efab7af 100644 --- a/lib/src/display/text.dart +++ b/lib/src/display/text.dart @@ -163,7 +163,7 @@ class GText extends GDisplayObject { painting.TextStyle? textStyle, double width = double.infinity, }) { - painting.PaintingBinding.instance!.systemFonts.addListener(_fontLoaded); + painting.PaintingBinding.instance.systemFonts.addListener(_fontLoaded); this.text = text; _width = width; @@ -182,7 +182,7 @@ class GText extends GDisplayObject { @override void dispose() { super.dispose(); - painting.PaintingBinding.instance!.systemFonts.removeListener(_fontLoaded); + painting.PaintingBinding.instance.systemFonts.removeListener(_fontLoaded); _onFontLoaded?.removeAll(); _onFontLoaded = null; } diff --git a/lib/src/events/pointer_data.dart b/lib/src/events/pointer_data.dart index 195dda7..93baab3 100644 --- a/lib/src/events/pointer_data.dart +++ b/lib/src/events/pointer_data.dart @@ -19,7 +19,7 @@ class PointerEventData { final double stageY; final PointerEventType? type; final PointerEvent rawEvent; - + int pointer = 0; /// local position in DisplayObject late GPoint localPosition; @@ -32,7 +32,7 @@ class PointerEventData { /// 300 milliseconds for double click static int doubleClickTime = 300; - PointerEventData({this.type, required this.rawEvent}) + PointerEventData({this.type,this.pointer = 0, required this.rawEvent}) : stageX = rawEvent.localPosition.dx, stageY = rawEvent.localPosition.dy { localPosition = GPoint(stageX, stageY); diff --git a/lib/src/input/input_converter.dart b/lib/src/input/input_converter.dart index f7249f8..fc7f100 100644 --- a/lib/src/input/input_converter.dart +++ b/lib/src/input/input_converter.dart @@ -17,6 +17,7 @@ class InputConverter { void pointerEnter(PointerEnterEvent event) { pointer.$process(PointerEventData( type: PointerEventType.enter, + pointer: event.pointer, rawEvent: event, )); } @@ -24,6 +25,7 @@ class InputConverter { void pointerExit(PointerExitEvent event) { pointer.$process(PointerEventData( type: PointerEventType.exit, + pointer: event.pointer, rawEvent: event, )); } @@ -31,6 +33,7 @@ class InputConverter { void pointerHover(PointerHoverEvent event) { pointer.$process(PointerEventData( type: PointerEventType.hover, + pointer: event.pointer, rawEvent: event, )); } @@ -40,6 +43,7 @@ class InputConverter { void pointerSignal(PointerSignalEvent event) { pointer.$process(PointerEventData( type: PointerEventType.scroll, + pointer: event.pointer, rawEvent: event as PointerScrollEvent, )); } @@ -47,6 +51,7 @@ class InputConverter { void pointerMove(PointerMoveEvent event) { pointer.$process(PointerEventData( type: PointerEventType.move, + pointer: event.pointer, rawEvent: event, )); } @@ -54,6 +59,7 @@ class InputConverter { void pointerCancel(PointerCancelEvent event) { pointer.$process(PointerEventData( type: PointerEventType.cancel, + pointer: event.pointer, rawEvent: event, )); } @@ -61,6 +67,7 @@ class InputConverter { void pointerUp(PointerUpEvent event) { pointer.$process(PointerEventData( type: PointerEventType.up, + pointer: event.pointer, rawEvent: event, )); } @@ -68,6 +75,7 @@ class InputConverter { void pointerDown(PointerDownEvent event) { pointer.$process(PointerEventData( type: PointerEventType.down, + pointer: event.pointer, rawEvent: event, )); } diff --git a/lib/src/tween/src/gtween.dart b/lib/src/tween/src/gtween.dart index 74a4394..a5843ae 100644 --- a/lib/src/tween/src/gtween.dart +++ b/lib/src/tween/src/gtween.dart @@ -127,7 +127,7 @@ class GTween { /// or make GTicker global... being able to track unique refresh frames /// is a must. static void processTick(double elapsed) { - final ts = SchedulerBinding.instance!.currentFrameTimeStamp; + final ts = SchedulerBinding.instance.currentFrameTimeStamp; if (_lastFrameTimeStamp == ts) return; GTween.ticker.dispatch(elapsed); _lastFrameTimeStamp = ts;