diff --git a/.github/.cspell/words_dictionary.txt b/.github/.cspell/words_dictionary.txt index 97c485b5000..97ec56af3d9 100644 --- a/.github/.cspell/words_dictionary.txt +++ b/.github/.cspell/words_dictionary.txt @@ -1,14 +1,17 @@ # actual english words (or common abbreviations) missing from CSpell bilinearly bloodlust +cicd collidable collidables gamepads +genhtml grayscale hoverable Hoverables inactives layouting +mocktail NTSC orientable platformer diff --git a/.gitignore b/.gitignore index 3c82a340d55..bd11efd7c41 100644 --- a/.gitignore +++ b/.gitignore @@ -32,6 +32,9 @@ ios/ macos/ windows/ linux/ +!packages/flame_studio/linux/ +!packages/flame_studio/macos/ +!packages/flame_studio/windows/ desktop/ **/build/ coverage/ @@ -55,6 +58,7 @@ examples/**/.gitignore **/example/web .metadata +!packages/flame_studio/.metadata # FVM .fvm/ diff --git a/packages/flame_bloc/example/pubspec.yaml b/packages/flame_bloc/example/pubspec.yaml index ddb091a5eb8..826a412b7e3 100644 --- a/packages/flame_bloc/example/pubspec.yaml +++ b/packages/flame_bloc/example/pubspec.yaml @@ -11,12 +11,12 @@ environment: flutter: ">=3.47.0" dependencies: - equatable: ^2.0.5 + equatable: ^3.0.0 flame: ^2.0.0-dev.1 flame_bloc: ^2.0.0-dev.1 flutter: sdk: flutter - flutter_bloc: ^8.1.2 + flutter_bloc: ^9.1.1 material_ui: ^1.0.0 dev_dependencies: diff --git a/packages/flame_studio/.gitignore b/packages/flame_studio/.gitignore new file mode 100644 index 00000000000..79f7ecabd5c --- /dev/null +++ b/packages/flame_studio/.gitignore @@ -0,0 +1,48 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release + +# Widget Preview related +.widget_preview/ diff --git a/packages/flame_studio/.metadata b/packages/flame_studio/.metadata new file mode 100644 index 00000000000..9b4fcbb40a9 --- /dev/null +++ b/packages/flame_studio/.metadata @@ -0,0 +1,36 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "6a19cca56475dbfba1478ee68d7bd0c2ef891da1" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + - platform: linux + create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + - platform: macos + create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + - platform: windows + create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/flame_studio/AGENTS.md b/packages/flame_studio/AGENTS.md new file mode 100644 index 00000000000..6050f32bf28 --- /dev/null +++ b/packages/flame_studio/AGENTS.md @@ -0,0 +1,121 @@ + +# Flame Studio — Agent Guide + +This guide applies only to `packages/flame_studio/`, not to the rest of the Flame monorepo. + +A **Flutter desktop app** (macOS, Windows, Linux) for visually creating +[Flame](https://flame-engine.org) components: users compose and tweak +components on a canvas and the editor produces reusable Flame component +definitions/code. + +Read this file first, then the doc relevant to your task: + +| Doc | When to read it | +| --- | --- | +| [docs/architecture.md](docs/architecture.md) | Before adding any feature, bloc, client or repository | +| [docs/conventions.md](docs/conventions.md) | Before writing Dart code (naming, barrels, style, lints) | +| [docs/testing.md](docs/testing.md) | Before writing or changing tests | +| [docs/ci.md](docs/ci.md) | When touching `.github/` or when CI fails | + + +## Golden rules + +1. **Follow VGV layered architecture** (data → repository → business logic → + presentation). A layer only talks to the layer directly beneath it. See + [docs/architecture.md](docs/architecture.md). +2. **Everything lives in `lib/`, with no internal packages.** Feature folders + have `bloc/` and `view/`, data clients live in `lib/clients/` and repositories + in `lib/repositories/`. This differs from VGV on purpose, see + [docs/architecture.md](docs/architecture.md). +3. **State management is `bloc`/`flutter_bloc`.** No `setState` for anything + beyond purely ephemeral widget state (hover, focus, animation controllers). +4. **Lints are `flame_lint` (with DCM), `very_good_analysis` and `bloc_lint`.** Code must pass `flutter analyze` with + zero issues — never silence a lint project-wide to make it pass. +5. **Every change ships with tests.** Aim for **≥ 50% line coverage** + (deliberately lower than VGV's usual 100%). Don't chase 100%, but test + blocs, repositories and non-trivial widgets. +6. **Desktop only.** Do not add `android/`, `ios/` or `web/` targets unless + explicitly asked. + + +## Commands + +```sh +melos bootstrap # install deps, from the monorepo root +flutter analyze # must report "No issues found!" +dart format lib test # format (CI fails on unformatted code) +flutter test --coverage --test-randomize-ordering-seed random +flutter run -d macos # or -d windows / -d linux +``` + +Before finishing a task, run **analyze, format and test** and make sure all +three pass. + + +## Current state + +- Features: `home` (open project + recent projects), `project` (dashboard: + list/add/edit/delete components; adding asks for a name and a component + type), `project_settings` (settings dialog: generated code output path, + stored in `/.flame_studio/settings.json`), `palette` (dialog to + manage the project's named colors, stored in + `/.flame_studio/palette.json` and generated as `GamePalette` in + `palette.generated.dart`; paint colors can be picked from it and their + generated code references `GamePalette.`; colors in use can't be + renamed or removed — see "Palette" in + [docs/architecture.md](docs/architecture.md)) and `component_editor` + (a top bar below the app bar for project-wide actions — the palette + button —, component tree on the left to add/remove/select/rename nested children, + live Flame preview in the center, with a toolbar above it whose toggle + highlights the selected node with a magenta border, another toggle + shows/hides the hitbox outlines, and whose zoom + controls (also Cmd/Ctrl + `=`/`-`/`0`) zoom the preview — the zoom is an + app-wide preference per component, in `editor_preferences_repository`, + never in the component's JSON —, properties of the selected node on the + right, explicit save with button or Cmd/Ctrl+S, unsaved-changes prompt when + leaving). **Saving also generates the component's Dart code** in the + settings' output path, with a getter for every child — see "Code + generation" in [docs/architecture.md](docs/architecture.md). Clients and repositories: `key_value_storage_client`, + `file_system_client`, `project_repository`, `editor_preferences_repository`, `component_repository` + (components stored in `/.flame_studio/components/.json`) — + see "Existing modules" in [docs/architecture.md](docs/architecture.md). +- Component types: `polygon` (a Flame `PolygonComponent`: position, anchor + and angle — children only —, vertices and paint; no size, which is the + vertices' bounding box; it starts as a triangle or a square, and its + vertices are edited in the vertices editor dialog, `lib/vertices_editor/`, + by dragging, adding from edge midpoints and deleting, with its own zoom + (not remembered) — see "Polygons" in + [docs/architecture.md](docs/architecture.md)), `rectangle` (position, anchor and angle — edited only on + children —, size, and paint with color and fill style), `position` (a plain Flame + `PositionComponent`: position, anchor and angle — children only — and size; draws nothing + itself, useful as a container) and `circle` (a Flame `CircleComponent`: + position, anchor and angle — children only —, radius, and paint; the radius is its own + `ComponentRadius` property, since Flame circles take a radius, not a + size) and the hitboxes `rectangleHitbox`, `circleHitbox` and + `polygonHitbox` (Flame's `RectangleHitbox`, `CircleHitbox` and + `PolygonHitbox`: their shape's geometry plus a `ComponentCollision` — + collision type and solid —, no paint; children only, never roots, and + with no children of their own; outlined in orange dashes in the preview, + shown/hidden by a toolbar toggle — see "Hitboxes" in + [docs/architecture.md](docs/architecture.md)). Components can have children + (see "Component tree" in [docs/architecture.md](docs/architecture.md)). Properties are shared between types through capability interfaces — + see "Component types & shared properties" in + [docs/architecture.md](docs/architecture.md) before adding a type or + property. +- `bloc`, `flutter_bloc`, `equatable`, `flame` (**2.0.0-dev** — the + generated code targets Flame 2; `flame_test` is on the matching 3.0.0-dev), + `dart_style` (formats the + generated code, in `component_repository`), `flex_color_picker` + (pinned to 3.x: 4.x depends on the standalone `material_ui` package, whose + `MaterialLocalizations` don't match `flutter/material`), `bloc_test`, + `flame_test`, `mocktail`, `flame_lint` and `bloc_lint` are dependencies. +- Toolchain: Flutter stable 3.47 / Dart 3.13. Dart 3.13 lints prefer primary + constructors (`class const Foo({super.key}) extends Bar {`) — `dart fix --apply` + handles it. + + +## Commits & PRs + +- PR titles (and commits) follow [Conventional Commits](https://www.conventionalcommits.org): + `feat:`, `fix:`, `docs:`, `refactor:`, `test:`, `chore:`, `ci:`. CI checks this. +- Keep docs in `docs/` up to date when you change architecture or conventions. diff --git a/packages/flame_studio/README.md b/packages/flame_studio/README.md index 2391e56a94b..ecfb5b5ef32 100644 --- a/packages/flame_studio/README.md +++ b/packages/flame_studio/README.md @@ -1 +1,49 @@ -# Flame Studio + +

+ + flame + +

+ +

+A desktop app to create Flame components visually. +

+ +

+ + + +

+ +--- + + + +# flame_studio + +A Flutter desktop app (macOS, Windows, Linux) to create +[Flame](https://flame-engine.org) components visually. + + +## Getting started + +```sh +melos bootstrap # from the root of the monorepo +cd packages/flame_studio +flutter run -d macos # or windows / linux +``` + + +## Development + +```sh +flutter analyze +dart format lib test +flutter test --coverage --test-randomize-ordering-seed random +``` + +The project follows the layers of the +[VGV layered architecture](https://engineering.verygood.ventures/architecture/architecture/), +keeping them all in `lib/` instead of in internal packages. +See [`docs/`](docs/) for architecture, conventions, testing and CI details, and +[`AGENTS.md`](AGENTS.md) for the agent guide. diff --git a/packages/flame_studio/analysis_options.yaml b/packages/flame_studio/analysis_options.yaml index c378b45f27b..0359c6cc2af 100644 --- a/packages/flame_studio/analysis_options.yaml +++ b/packages/flame_studio/analysis_options.yaml @@ -1,11 +1,12 @@ -include: package:flame_lint/analysis_options_with_dcm.yaml +include: + - package:flame_lint/analysis_options_with_dcm.yaml + - package:very_good_analysis/analysis_options.yaml + - package:bloc_lint/recommended.yaml analyzer: exclude: - build/** - - android/** - - ios/** - - web/** - - windows/** - - macos/** - linux/** + - macos/** + - windows/** + - "**/*.g.dart" diff --git a/packages/flame_studio/assets/logo_flame.png b/packages/flame_studio/assets/logo_flame.png deleted file mode 100644 index 58b92c86283..00000000000 Binary files a/packages/flame_studio/assets/logo_flame.png and /dev/null differ diff --git a/packages/flame_studio/docs/architecture.md b/packages/flame_studio/docs/architecture.md new file mode 100644 index 00000000000..bada289749a --- /dev/null +++ b/packages/flame_studio/docs/architecture.md @@ -0,0 +1,440 @@ + +# Architecture + +This project follows the layers of the +[Very Good Ventures layered architecture](https://engineering.verygood.ventures/architecture/architecture/), +with one deliberate difference: the data and repository layers live in `lib/`, not in internal +packages. This is a standalone app, so each layer is a folder and there are no packages under +`packages/flame_studio`. Nothing enforces the boundaries between layers, so keep to the rules below. + + +## Layers + +Data flows **bottom up**. Each layer has a single responsibility and may only +depend on the layer **directly beneath it**. + +```text +┌─────────────────────────────────────┬──────────────────────────────────────┐ +│ Presentation (lib//view) │ Flutter widgets, no business logic │ +├─────────────────────────────────────┼──────────────────────────────────────┤ +│ Business logic (lib//bloc) │ Blocs/Cubits, no Flutter imports │ +├─────────────────────────────────────┼──────────────────────────────────────┤ +│ Repository (lib/repositories) │ Domain rules, composes data clients │ +├─────────────────────────────────────┼──────────────────────────────────────┤ +│ Data (lib/clients) │ Raw I/O: file system, serialization │ +└─────────────────────────────────────┴──────────────────────────────────────┘ +``` + + +### Data layer — `lib/clients/` + +- Talks to the outside world: file system, JSON/YAML (de)serialization of + project files, clipboard, OS dialogs, asset loading, process execution. +- No domain or business logic. Should be reusable in an unrelated project. +- Returns raw/DTO models specific to that source. + + +### Repository layer — `lib/repositories/_repository/` + +- One repository per domain. Composes one or more data clients and exposes + **domain models**. +- Pure Dart: **no Flutter imports**, and **no dependency on other + repositories**. +- Hides *how* data is fetched/stored. If a data client changes, only its + repository should change. + + +### Business logic layer — `lib//bloc/` + +- Blocs/Cubits that compose repositories and turn user intents into states. +- **No Flutter SDK imports** (no `package:flutter/...`) and **no direct + dependency on other blocs**. If two blocs need to coordinate, do it through + a shared repository (e.g. a stream) or from the presentation layer. +- Repositories are injected via the constructor. + + +### Presentation layer — `lib//view/` (+ `widgets/`) + +- Widgets only. Reads bloc state and dispatches events — nothing else. +- Never touches a data client or repository method directly (repositories are + only *provided* via `RepositoryProvider` and passed into blocs). + + +### Leakage examples (don't) + +- A widget reading a file from disk or calling a `*Client`. +- A bloc knowing file paths/formats — that belongs in the repository/client. +- A repository importing `package:flutter/...` or another repository. + + +## Project structure + +```text +flame_studio/ +├── lib/ +│ ├── main.dart # entry point: builds repositories, runApp(App) +│ ├── app/ +│ │ ├── app.dart # barrel +│ │ └── view/ +│ │ └── app.dart # MaterialApp, providers, theme +│ ├── widgets/ # widgets shared by several features (e.g. ZoomControls) +│ ├── clients/ +│ │ ├── clients.dart # barrel +│ │ └── _client.dart +│ ├── repositories/ +│ │ ├── repositories.dart # barrel +│ │ └── _repository/ +│ │ ├── models/ +│ │ │ └── models.dart # barrel +│ │ └── _repository.dart +│ └── / # e.g. canvas, component_tree, inspector +│ ├── .dart # barrel: exports bloc/ and view/ +│ ├── bloc/ +│ │ ├── _bloc.dart +│ │ ├── _event.dart # part of _bloc.dart +│ │ └── _state.dart # part of _bloc.dart +│ ├── view/ +│ │ ├── _page.dart # provides the bloc +│ │ ├── _view.dart # consumes the bloc +│ │ └── view.dart # barrel +│ └── widgets/ # feature-private widgets (optional) +│ └── widgets.dart # barrel +└── test/ # mirrors lib/ + ├── helpers/ # pumpApp and shared test utilities + ├── app/view/app_test.dart + └── / + ├── bloc/_bloc_test.dart + └── view/_page_test.dart +``` + + +### Page / View split + +Each feature's `view/` has a `Page` that creates and provides the bloc +(`BlocProvider(create: (context) => FeatureBloc(repository: context.read()))`) +and a `View` that only consumes it. Tests of the view can then inject +a mock bloc without touching repositories. + + +## Existing modules + +| Layer | Module | Responsibility | +| --- | --- | --- | +| Data | `lib/clients/key_value_storage_client.dart` | Generic string key-value storage (`shared_preferences`) | +| Data | `lib/clients/file_system_client.dart` | Native directory picker (`file_selector`), directory/file existence, list/read/write/delete files | +| Repository | `lib/repositories/editor_preferences_repository/` | App-wide editor preferences (`shared_preferences`, through `key_value_storage_client`), not stored in the project: the preview zoom of each component, keyed by project path + component name (`component_zoom::`), clamped to `minZoom`–`maxZoom`; the `ZoomLevels` the editor canvases step through | +| Repository | `lib/repositories/project_repository/` | `Project` and `ProjectSettings` models; pick/open projects; last 10 recent projects; read/write project settings (`/.flame_studio/settings.json`) and pick a project-relative output folder | +| Repository | `lib/repositories/component_repository/` | Sealed `Component` model (one subclass per `ComponentType`), shared property models (`ComponentPosition`, `ComponentSize`, `ComponentPaint`, `ComponentVertices`…), the `PolygonShape` presets new polygons start with, the hitbox types and their `ComponentCollision`, capability interfaces and the `ComponentTree` extension for nested children (including child name validation); list/create/save/delete a project's components (one JSON file each in `/.flame_studio/components/`); `ComponentCodeGenerator` and writing/deleting the generated Dart code (see "Code generation"); the project's `Palette` (`/.flame_studio/palette.json`) and its `PaletteCodeGenerator` (see "Palette") | +| Bloc + view | `lib/home/` | Landing screen: "Open project" button and recent projects list | +| Bloc + view | `lib/project/` | Project dashboard: lists components, add (name + type dialog → editor), edit, delete (with confirmation; also deletes the generated code), settings icon (opens the settings dialog). Pushed from home with `ProjectPage.route` | +| Bloc + view | `lib/component_editor/` | Component editor, `ComponentEditorPage.route(project, component)`: a top bar (`EditorTopBar`, below the app bar, above the three panels) for project-wide actions (the palette button), component tree (left, add/remove children — not under hitboxes —, root selected by default), Flame preview (center, magenta border around the selected node; a toolbar above it toggles that highlight and the hitbox outlines, and has the zoom controls; it scrolls horizontally when the preview is narrow), properties panel for the selected node (right; children also get a Name field), save button + Cmd/Ctrl+S (also generates the Dart code), unsaved-changes marker in the title, `PopScope` prompt (cancel / discard / save) when leaving with unsaved changes | +| Bloc + view | `lib/vertices_editor/` | Vertices editor dialog, `VerticesEditorDialog.show(context, vertices:, paint:)`: a `CustomPaint` canvas (`VerticesCanvas`, `VerticesPainter`) where the user drags vertices, adds one from the "+" handle in the middle of an edge, and deletes the selected one (Delete/Backspace, context menu or button; at least 3 are kept). A side bar (`VerticesList`) has X/Y fields per vertex to type exact coordinates, and a delete button per row; selecting a row or focusing its fields selects the vertex. `VerticesEditorCubit` edits a working copy; Apply returns it normalized, Cancel/Esc returns `null`. `VerticesViewTransform` maps local coordinates to the canvas (fitted once when the dialog opens) and does the hit testing. The canvas zooms (`ZoomControls` next to the title, Cmd/Ctrl + `=`/`-`/`0`) relative to that fit, around its center (`VerticesViewTransform.zoomed`); the zoom is held by the cubit and not remembered | +| Bloc + view | `lib/palette/` | Palette dialog, `PaletteDialog.show(context, project:, component:)` (opened from the editor's top bar; returns the saved `Palette` or `null`): add, rename, change and remove named colors; colors used by a component (including the unsaved edits of the open one) can't be renamed or removed. `PaletteBloc` saves the palette and generates its code | +| Bloc + view | `lib/project_settings/` | Project settings dialog, `ProjectSettingsDialog.show(context, project)`: output path for generated Dart code (default `lib/components`, text field + Browse) | + +The macOS app sandbox is **disabled** (both entitlements files) so that plain +folder paths in the recent projects list can be reopened after a restart. + + +## Component types & shared properties + +Many Flame components share properties (every `PositionComponent` has a size, +many components have a paint). Each property is therefore built **once** and +component types only declare which ones they have: + +| Piece | Where | Example | +| --- | --- | --- | +| Value object (Equatable, JSON, defaults) | `lib/repositories/component_repository/models/` | `ComponentPosition`, `ComponentAnchor`, `ComponentAngle`, `ComponentSize`, `ComponentRadius`, `ComponentVertices`, `ComponentPaint`, `ComponentCollision` | +| Capability interface | `lib/repositories/component_repository/models/component_capabilities.dart` | `PositionedComponent`, `AnchoredComponent`, `RotatedComponent`, `SizedComponent`, `RadiusComponent`, `VerticesComponent`, `PaintedComponent`, `HitboxComponent` | +| Component type | `ComponentType` enum + a subclass in `component.dart`'s library (`part` file) | `RectangleComponent implements PositionedComponent, AnchoredComponent, RotatedComponent, SizedComponent, PaintedComponent`, `PositionComponent implements PositionedComponent, AnchoredComponent, RotatedComponent, SizedComponent`, `CircleComponent implements PositionedComponent, AnchoredComponent, RotatedComponent, RadiusComponent, PaintedComponent`, `PolygonComponent implements PositionedComponent, AnchoredComponent, RotatedComponent, VerticesComponent, PaintedComponent`, and the hitboxes, which swap the paint for a `HitboxComponent`: `RectangleHitboxComponent`, `CircleHitboxComponent`, `PolygonHitboxComponent` | +| Bloc event | `lib/component_editor/bloc/` | `ComponentEditorSizeChanged` (edits the selected node if it is a `SizedComponent`) | +| Editor widget (`value` + `onChanged`, bloc-agnostic) | `lib/component_editor/widgets/property_editors/` | `PositionEditor`, `AnchorEditor`, `AngleEditor`, `SizeEditor`, `RadiusEditor`, `VerticesEditor` (a button that opens the vertices editor dialog), `PaintEditor`, `CollisionEditor`, built from `NumberField`, `ColorField`, `EnumField` | +| Panel wiring | `lib/component_editor/widgets/properties_panel.dart` | `if (component case SizedComponent c) SizeEditor(...)` | +| Flame mapping | `lib/component_editor/widgets/preview/flame_mapping.dart` | `applyPosition`, `applyAnchor`, `applyAngle`, `applySize`, `applyRadius`, `applyPaint`, `applyCollision`, `buildFlameComponent` | +| Code generation | `lib/repositories/component_repository/code_generation/` | `ComponentCodeGenerator._flameClass` / `_arguments`, `flameMemberNames` in `dart_names.dart` | + +**Adding a component type:** add a `ComponentType` value, a `Component` +subclass implementing the right capabilities (reuse the value objects' JSON; +its private `_fromJson` reads only its own properties, `Component.fromJson` +reads the children for every type), and cases in +`Component.create`/`Component.fromJson`, +`buildFlameComponent`, `ComponentCodeGenerator._flameClass` and +`flameMemberNames` (the public members of its Flame class, which child +getters must not override), and an icon in `ComponentTreePanel.iconFor`. The panel, bloc, preview and generated code +pick up its properties automatically. + +**Adding a property:** add the value object and capability interface, a bloc +event, an editor widget, a branch in `PropertiesPanel`, in +`applyProperties` and in `ComponentCodeGenerator._arguments` (the generated +code must match the preview), then implement the capability on the types +that have it. + + +### Polygons + +A `PolygonComponent` is shaped by its `ComponentVertices`: points in the +component's local coordinates, in order, at least 3 (Flame asserts it). +Its Flame size is the bounding box of the vertices (Flame's +`shrinkToBounds`), so polygons have **no size property**. New polygons +start as a triangle or a square (`PolygonShape`, picked in the add +component dialog and in the tree's add-child menu); concave and +self-intersecting shapes are allowed. + +Flame moves the vertices so that the top left of their bounding box is +at the origin, so the vertices editor stores them normalized +(`ComponentVertices.normalized`) and the stored data matches what Flame +renders. A Flame polygon can't change its number of vertices and can't be +given new ones from outside (`refreshVertices` is protected), so +`haveSameShape` is false when a polygon's vertices change and the preview +rebuilds it. Flame also changes the list it is given, so the preview and +the generated code always pass a new, non-const list, as the first +(positional) constructor argument. + + +### Hitboxes + +`RectangleHitboxComponent`, `CircleHitboxComponent` and +`PolygonHitboxComponent` are Flame's `RectangleHitbox`, `CircleHitbox` and +`PolygonHitbox`: the geometry of their shape (size, radius or vertices, so +the shared editors, highlight and polygon rules apply) without a paint, +plus a `ComponentCollision` (`HitboxComponent`): the collision type +(`HitboxCollisionType`, mirroring Flame's `CollisionType`) and `isSolid`. +The generated code imports `package:flame/collisions.dart` when the tree has +a hitbox, and omits `collisionType`/`isSolid` at Flame's defaults (active, +not solid). + +- **Children only, and leaves.** Flame throws when a hitbox has no + `PositionComponent` ancestor, so `createComponent` rejects hitbox roots + (`ArgumentError`) and the add component dialog doesn't offer them; + `addChildAt` throws under a hitbox, the editor bloc ignores + `ComponentEditorChildAdded` while one is selected and the tree's add + button is disabled. +- **Preview.** Hitboxes draw nothing, so the preview builds + `PreviewRectangleHitbox`, `PreviewCircleHitbox` and `PreviewPolygonHitbox` + (`preview_hitboxes.dart`, sharing the `PreviewHitbox` mixin): the real + Flame hitboxes with an **orange dashed outline**. The preview game has no + collision detection, so they never collide. The toolbar's "Show + hitboxes" toggle (`ComponentEditorState.areHitboxesVisible`, on by + default, not persisted) hides them through Flame's `HasVisibility` + (`ComponentPreviewGame.areHitboxesVisible`). The vertices editor draws + polygon hitboxes with the same orange stroke. +- **Fill-parent gotcha.** Flame's `RectangleHitbox`/`CircleHitbox` fill + their parent when built without a size/radius and without a position. + The preview hitboxes are built with a zero size/radius, and the + generated children always pass a position and a size/radius. + + +### Component tree + +Like in Flame, every `Component` has `children` (stored nested in the same +JSON file). A node is addressed by its **path**, the list of child indices +from the root (`[]` is the root); `ComponentTree` (`nodeAt`, `updateNodeAt`, +`addChildAt`, `removeNodeAt`, `uniqueChildName`) does all the immutable tree +edits. The editor state holds `selectedPath`, and every property event edits +`selectedNode`. New children get a unique default name such as `rectangle1`. + +The position, the anchor and the angle are only edited on children +(`PropertiesPanel` hides them for the root, which is placed by whoever uses +it). In the preview the root is centered with a center anchor and no +rotation (its stored position, anchor and angle are ignored); children use +their own anchor (`ComponentAnchor`, Flame's default top left unless +edited: one of Flame's nine named anchors or a custom `x`/`y`) and angle +(`ComponentAngle`, stored in radians like Flame, edited in degrees by +`AngleEditor`) and are positioned relative to their parent. The selection +highlight is rotated with the selected node. `ComponentPreviewGame.show` +updates the Flame components in place while the tree shape is unchanged +(`haveSameShape`) and rebuilds them otherwise. + +Position components draw nothing in Flame, so the preview builds them as +`PreviewPositionComponent`, a `PositionComponent` with a faint dashed +outline, to keep them visible while unselected. The outline is preview +only: the generated code uses a plain `PositionComponent`. The dashes are +drawn by the shared helpers in `dashed_outline.dart`, also used by the +hitboxes. + +The preview highlights the selected node with a magenta border while +`isSelectionHighlighted` is on (the toolbar toggle; on by default, not +persisted). Only nodes with a size (`SizedComponent`) or a radius +(`RadiusComponent`, whose Flame size is the circle's bounding box) or +vertices (`VerticesComponent`, highlighted around their bounding box) are +highlighted. The +border is drawn by `SelectionHighlight`, a world-level overlay that targets +the Flame component found with `flameNodeAt`, rather than a child of it: +that keeps it above overlapping siblings and keeps the Flame children +matching the component tree. + +The preview can be zoomed (`ComponentEditorState.zoom`) with the zoom +out / percentage (reset to 100%) / zoom in controls on the right of the +toolbar, or with Cmd/Ctrl + `=`, `-` and `0`. Zooming in and out steps +through `ZoomLevels` (10% to 800%, in `editor_preferences_repository`). +The controls and shortcuts are the shared `ZoomControls` and +`zoomShortcuts` in `lib/widgets/`, also used by the vertices editor. The zoom is an +**editor preference, not component data**: it is remembered per component +in `EditorPreferencesRepository` (loaded on `ComponentEditorStarted`, +stored on every change) and never written to the component's JSON, so it +doesn't mark unsaved changes. `ComponentPreviewGame.zoom` sets the +camera's `viewfinder.zoom`, which zooms around the root at the center of +the screen; `SelectionHighlight` divides its stroke width by the zoom so +the border keeps the same width on screen. + +Domain models avoid `dart:ui`: colors are ARGB `int`s and `PaintStyle` mirrors +`PaintingStyle`. Conversion to Flame/Flutter types happens only in +`flame_mapping.dart`. Flame's own `Component`/`RectangleComponent` clash with +the domain names, so import Flame with a prefix +(`import 'package:flame/components.dart' as flame;`). + +The preview `GameWidget` is created with `autofocus: false`: a focused +`GameWidget` marks every key event as handled, which would swallow the editor +shortcuts. Widget tests that show the preview can't use `pumpAndSettle` (the +game loop never settles), so use `tester.pumpRouteTransition()` from +`test/helpers`. + + +### Palette + +A project has one `Palette`: an ordered list of named colors +(`PaletteColor`), stored in `/.flame_studio/palette.json` and read +and written by `ComponentRepository` (`getPalette`, `savePalette`, +`writePaletteCode`). It lives in `component_repository` because component +code references it, components can't take its file name, and "in use" is +computed from the components; a separate repository would have to depend on +this one. + +- **Names** are their generated member names, so they are validated like + child names (`Palette.validateColorName`, `PaletteColorNameError`): a valid + identifier, not a keyword, unique after camelCase normalization. +- **Paints reference colors by name**: `ComponentPaint.paletteColor`. Its + `color` keeps the value the palette color had when it was picked, as a + fallback when the palette doesn't have it (`resolvedColor(palette)`). + `withColor` (picked by hand) clears the reference; `withPaletteColor` + sets it. `paletteColor` is only written to JSON when set. +- **Editing**: `ColorField` gets a palette button (a menu of the colors) + when it is given a palette and `onPaletteColorSelected`; `PaintEditor` + wires it. The editor bloc loads the palette on `ComponentEditorStarted` + and gets the saved one from the dialog with + `ComponentEditorPaletteChanged`; the preview draws + `component.withPaletteColorsResolved(palette)`. Palette changes are not + component changes (`hasChanges` is unaffected). +- **Colors in use can't be renamed or removed** (`PaletteState.usersOf`, + `ComponentTree.usedPaletteColors`); their value can change. That keeps + every reference in saved components and generated code valid. +- **Code**: `PaletteCodeGenerator` writes + `/palette.generated.dart` with + `abstract final class GamePalette { static const primary = Color(…); }` + (no `$` prefix: generated component classes all have one, so they never + clash). Component code uses `Paint()..color = GamePalette.primary` and + imports `palette.generated.dart` for colors the palette has; missing ones + fall back to the inline value. `writeComponentCode` also rewrites the + palette file when the component uses it, so the import always resolves + (e.g. after the output path changed), and `isComponentCodeUpToDate` + compares against code generated with the current palette. Components named + `palette` (any name whose file is `palette`) are rejected on creation, and + an older one's code is never written over the palette's + (`GeneratedFileConflictException`). + + +### Code generation + +Saving a component in the editor also writes its Dart code to +`//.generated.dart` (`outputPath` comes from +the project settings, default `lib/components`). There is no separate +"generate" action. `ComponentEditorBloc` composes both repositories: it +saves the JSON with `ComponentRepository.saveComponent`, reads the settings +with `ProjectRepository.getSettings` and calls +`ComponentRepository.writeComponentCode`. If only the code fails, the +component still counts as saved (`codeConflict` / `codeFailure` statuses, +shown as a snackbar). `ProjectBloc` deletes the generated file along with +the component. + +`ComponentCodeGenerator` (pure, formatted with `dart_style` at language +version 3.8) generates code for **Flame 2.0.0-dev** (the version the app +itself uses, so the preview matches). When upgrading Flame, refresh the +member lists in `dart_names.dart` (`flameMemberNames`). It generates: + +- the root as a public class named in PascalCase after the component, + with the `$` prefix of generated code (`player_ship` → `$PlayerShip`), + extending its Flame class (games subclass it: + `class PlayerShip extends $PlayerShip`), with a + `{super.position, super.angle, super.anchor, super.priority}` constructor + (the root's stored position, angle and anchor are ignored, like in the + preview); +- the children's anchor as an `anchor:` argument, `Anchor.` for + Flame's named anchors (`ComponentAnchor.presetName`) and `Anchor(x, y)` + otherwise, omitted for the default top left (so files generated before + anchors existed stay up to date); +- the children's angle as an `angle:` argument in radians, omitted when it + is `0`; +- **a `final` field (a getter) for every child on the component it is + inside**, named in camelCase after the child (`left_arm` → `leftArm`), + added in the constructor body; +- a class `$` (e.g. `$PlayerShipHead`) for every child that + has children of its own, so the nested children get getters too + (`player.head.eye`); leaf children are plain Flame components. + +Every generated file starts with `ComponentCodeGenerator.header`. +`dart:ui` is only imported when a node of the tree has a paint (an unused +import is a warning that `ignore_for_file: type=lint` doesn't hide). The +repository never overwrites or deletes a file without it +(`GeneratedFileConflictException`), so hand-written code in the output +folder is safe. + +Child names are the getter names, so the Name field validates them with +`ComponentTree.validateChildName` (`ChildNameError`): a valid identifier +that isn't a keyword, not a member of the parent's Flame class (`size`, +`position`, `paint`, …), and unique in the tree after camelCase +normalization. Root names are validated on creation: the class name must +be a valid identifier, and no other component may generate the same file. +Thanks to the `$` prefix, generated classes never shadow Flame types. + +Generated classes are public, so **class names must also be unique across +the project** (a library importing two files that declare `$PlayerShipHead` +won't compile). `ComponentTree.generatedClassNames` lists the classes a +component reserves: its root class and `$` for **every** child, +even leaves (which only get a class once they have children), so adding a +grandchild never causes a clash. The class names live in `dart_names.dart` +(`dartRootClassName`, `dartChildClassName`), shared by the generator and +the validation. `createComponent` throws `ComponentClassConflictException` +when the new root class is reserved by another component (e.g. `AB` vs +`a_b`, or `player_ship_head` vs the `head` child of `player_ship`). The +editor loads the other components' classes on `ComponentEditorStarted` +(`ComponentEditorState.takenClassNames`), and both `validateChildName` +(`ChildNameError.conflict`) and `uniqueChildName` take them into account. +Saving reloads the other components and checks the whole tree again +(catching names typed before they loaded). **A component whose classes +clash is not saved at all** (`classConflict` status; the changes stay +pending): its code wouldn't compile, and its JSON would reserve classes +that other components own. Clashes that already existed (e.g. `AB` and +`a_b` created before this check) are reported when the editor opens. +`takenClassNames` maps every class to the component that generates it, so +the snackbar says how to fix each clash: rename the clashing children; or, +when the root class clashes (`ComponentEditorState.rootClassOwner`), rename +the child of the other component that generates it, or delete one of the +two components if both roots generate it (components can't be renamed). + +`isCodeOutdated` is true when the generated code doesn't match the saved +component: `ComponentEditorStarted` checks it with +`ComponentRepository.isComponentCodeUpToDate` (missing, stale or +hand-written file), and saves that don't generate the code (`codeConflict`, +`codeFailure`) set it. `canSave` then lets the user save without changes, +e.g. after deleting the other component or moving a hand-written file out +of the way. Save states are built from the current state, so edits made +while saving are kept; edits keep the `saving` status, so no second save +starts meanwhile, and `ComponentEditorStarted` drops its results if a save +started while it was loading (the save's are newer). The leave prompt's +"save" only leaves once nothing is unsaved. + + +## Domain sketch (expected, not yet built) + +These are **likely** candidates as the editor grows; confirm with the user +before creating them. + +| Layer | Candidate | Responsibility | +| --- | --- | --- | +| Repository | `component_repository` (exists) | More component types and properties (scale, sprites…), undo/redo-friendly immutable models | +| Bloc | `component_tree/`, `canvas/` | Selection, canvas interactions | +| Presentation | same features | Desktop layout: tree panel, Flame canvas preview (`GameWidget`), inspector panel | + +The live Flame preview is presentation: the `GameWidget`/`FlameGame` used to +render the component being edited lives in the view layer and is driven by +bloc state; it must not own the source of truth for the component. diff --git a/packages/flame_studio/docs/ci.md b/packages/flame_studio/docs/ci.md new file mode 100644 index 00000000000..f7ac048f584 --- /dev/null +++ b/packages/flame_studio/docs/ci.md @@ -0,0 +1,20 @@ +# CI + +Flame Studio has no workflow of its own: it is checked by `.github/workflows/cicd.yml`, like the +other packages of the monorepo. + +| Job | What it checks | +| ------------------------------ | -------------------------------------------------- | +| `format` | Everything is formatted (`melos run format-check`) | +| `analyze`, `analyze-latest` | No analyzer issues, infos included | +| `dcm` | The DCM rules from `flame_lint` | +| `test` | Tests pass (`melos run test:select`) | +| `markdown-lint` | The Markdown files follow the repository rules | + +Notes: + +- CI doesn't run `bloc lint` or enforce a coverage minimum, so run `bloc lint .` locally, after + `dart pub global activate bloc_tools`, when changing blocs. +- The repository-wide spell check also covers this folder. Add legitimate project words to the + sorted dictionaries in `.github/.cspell/` instead of rewording code. +- PR titles are validated by `title-validation.yml`. diff --git a/packages/flame_studio/docs/conventions.md b/packages/flame_studio/docs/conventions.md new file mode 100644 index 00000000000..8d73eaf7685 --- /dev/null +++ b/packages/flame_studio/docs/conventions.md @@ -0,0 +1,67 @@ +# Code Conventions + + +## Lints + +- `flame_lint` (with its DCM rules) is the base of `analysis_options.yaml`, with + `very_good_analysis` and `bloc_lint` on top. Zero analyzer issues is required. +- Fix lints rather than ignore them. A line-level + `// ignore: ` is acceptable only with a short comment explaining why. +- Run `dart fix --apply` for mechanical fixes. +- Public APIs need doc comments (`public_member_api_docs`). Use the + `{@template}` / `{@macro}` pattern for widgets and classes: + + ```dart + /// {@template my_widget} + /// Short description. + /// {@endtemplate} + class const MyWidget({super.key}) extends StatelessWidget { + /// {@macro my_widget} + this; + } + ``` + + +## Naming & files + +- Files and folders: `snake_case`. One public class per file, file named after it. +- Feature folders are named after the feature (`inspector/`, not `screens/inspector/`). +- Blocs: `_bloc.dart` with `_event.dart` and + `_state.dart` as `part` files. Cubits: `_cubit.dart` + + `_state.dart`. +- Events are past tense, describing what happened: `ComponentSelected`, + `PropertyChanged`. Prefix with the feature if ambiguous. +- Widgets: `Page` provides dependencies, `View` renders. + + +## Barrel files + +- Every folder with public members has a barrel (`view/view.dart`, + `widgets/widgets.dart`, `models/models.dart`) and every feature has + `/.dart` exporting `bloc/` and `view/`. +- Import other features through their barrel, never deep paths. +- Clients and repositories are imported through `clients/clients.dart` and + `repositories/repositories.dart`. + + +## Imports + +- Use `package:` imports (enforced by `always_use_package_imports`). +- The bloc layer must not import `package:flutter/...`. + + +## State + +- States and events are immutable and value-comparable (`equatable` or + sealed classes with `==`). Prefer a single state class with a `status` enum + plus `copyWith` for features with loading/error states. +- Keep the component model immutable; edits produce new instances (this + keeps undo/redo straightforward). + + +## Desktop specifics + +- Design for mouse + keyboard: hover states, right-click context menus, + keyboard shortcuts (`Shortcuts`/`Actions`), resizable panels. +- No platform-specific code in blocs/repositories; isolate it in data + clients. diff --git a/packages/flame_studio/docs/testing.md b/packages/flame_studio/docs/testing.md new file mode 100644 index 00000000000..4887d556976 --- /dev/null +++ b/packages/flame_studio/docs/testing.md @@ -0,0 +1,48 @@ + +# Testing + + +## Coverage target + +Aim for **at least 50% line coverage**. CI doesn't enforce it, and it is intentionally below VGV's +usual 100%. Prioritize: + +1. **Repositories and data clients** — pure Dart, cheap to test, high value. +2. **Blocs/Cubits** — every event handler and resulting state. +3. **Widgets** with logic (conditional rendering, dispatching events). + +Trivial layout widgets and generated code may go untested. + + +## Layout + +- Tests mirror the source tree: `lib/inspector/bloc/inspector_bloc.dart` → + `test/inspector/bloc/inspector_bloc_test.dart`. +- Shared helpers live in `test/helpers/` (import `../helpers/helpers.dart`). + Use `tester.pumpApp(widget)` so widgets get the same providers/theme as in + the app; extend `pumpApp` as new providers are added. + + +## Tools (add when first needed) + +- `bloc_test` — `blocTest(...)` for blocs/cubits. +- `mocktail` — mocks for repositories (`class _MockComponentRepository extends Mock implements ComponentRepository {}`) + and blocs (`MockBloc`/`MockCubit` from `bloc_test`). + + +## Style + +- Group by the unit under test: `group(MyBloc, () { ... })`. +- Test descriptions read as sentences: `'emits [loading, success] when ...'`. +- Each test sets up its own state; tests run in random order + (`--test-randomize-ordering-seed random`), so no shared mutable state. +- Mock the layer directly beneath the unit under test — never deeper. + + +## Running + +```sh +flutter test --coverage --test-randomize-ordering-seed random +# optional: view report (requires lcov) +genhtml coverage/lcov.info -o coverage/ && open coverage/index.html +``` diff --git a/packages/flame_studio/example/main.dart b/packages/flame_studio/example/main.dart deleted file mode 100644 index d577e83e7cc..00000000000 --- a/packages/flame_studio/example/main.dart +++ /dev/null @@ -1,96 +0,0 @@ -import 'dart:math'; - -import 'package:flame/components.dart'; -import 'package:flame/game.dart'; -import 'package:flame_studio/flame_studio.dart'; -import 'package:flutter/widgets.dart'; - -void main() { - runFlameStudio( - Container( - color: const Color(0xFF1F2933), - child: GameWidget(game: ExampleGame()), - ), - ); -} - -/// A small scene to try out the studio with: a player with nested -/// components, a crate, a text label and a couple of moving coins. -class ExampleGame() extends FlameGame { - @override - Color backgroundColor() => const Color(0x00000000); - - @override - void onLoad() { - addAll([ - Player(position: Vector2(200, 300)), - Crate(position: Vector2(470, 220)), - Coin(restPosition: Vector2(330, 480), phase: 0), - Coin(restPosition: Vector2(330, 540), phase: pi), - Label(), - ]); - } -} - -class Player({required super.position}) extends RectangleComponent { - this - : super( - size: Vector2.all(72), - anchor: Anchor.center, - paint: Paint()..color = const Color(0xFF26A69A), - children: [ - Eye(position: Vector2(22, 26)), - Eye(position: Vector2(50, 26)), - ], - ); -} - -class Eye({required super.position}) extends CircleComponent { - this - : super( - radius: 6, - anchor: Anchor.center, - paint: Paint()..color = const Color(0xFFFFFFFF), - ); -} - -class Crate({required super.position}) extends RectangleComponent { - this - : super( - size: Vector2.all(56), - anchor: Anchor.center, - paint: Paint()..color = const Color(0xFF8D6E63), - ); -} - -/// A coin that moves from side to side around [restPosition]. -class Coin({ - required final Vector2 restPosition, - required final double phase, -}) extends CircleComponent { - this - : super( - radius: 12, - anchor: Anchor.center, - position: restPosition.clone(), - paint: Paint()..color = const Color(0xFFFFD54F), - ); - - double _time = 0; - - @override - void update(double dt) { - super.update(dt); - _time += dt; - position.x = restPosition.x + 160 * sin(_time * 1.5 + phase); - } -} - -class Label() extends TextComponent { - this - : super( - text: 'Flame Studio', - position: Vector2(332, 40), - anchor: Anchor.topCenter, - ); -} diff --git a/packages/flame_studio/lib/app/app.dart b/packages/flame_studio/lib/app/app.dart new file mode 100644 index 00000000000..f23ab3c8645 --- /dev/null +++ b/packages/flame_studio/lib/app/app.dart @@ -0,0 +1 @@ +export 'view/app.dart'; diff --git a/packages/flame_studio/lib/app/view/app.dart b/packages/flame_studio/lib/app/view/app.dart new file mode 100644 index 00000000000..158e01d55eb --- /dev/null +++ b/packages/flame_studio/lib/app/view/app.dart @@ -0,0 +1,40 @@ +import 'package:flame_studio/home/home.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template app} +/// The root widget of the Flame Studio. +/// {@endtemplate} +class const App({ + /// The repository used to open projects. + required final ProjectRepository projectRepository, + + /// The repository used to manage the components of a project. + required final ComponentRepository componentRepository, + + /// The repository used to keep the editor preferences. + required final EditorPreferencesRepository editorPreferencesRepository, + super.key, +}) extends StatelessWidget { + /// {@macro app} + this; + + @override + Widget build(BuildContext context) { + return MultiRepositoryProvider( + providers: [ + RepositoryProvider.value(value: projectRepository), + RepositoryProvider.value(value: componentRepository), + RepositoryProvider.value(value: editorPreferencesRepository), + ], + child: MaterialApp( + title: 'Flame Studio', + theme: ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepOrange), + ), + home: const HomePage(), + ), + ); + } +} diff --git a/packages/flame_studio/lib/clients/clients.dart b/packages/flame_studio/lib/clients/clients.dart new file mode 100644 index 00000000000..8c3c8e31cc5 --- /dev/null +++ b/packages/flame_studio/lib/clients/clients.dart @@ -0,0 +1,2 @@ +export 'file_system_client.dart'; +export 'key_value_storage_client.dart'; diff --git a/packages/flame_studio/lib/clients/file_system_client.dart b/packages/flame_studio/lib/clients/file_system_client.dart new file mode 100644 index 00000000000..b48e0f50f30 --- /dev/null +++ b/packages/flame_studio/lib/clients/file_system_client.dart @@ -0,0 +1,65 @@ +import 'dart:io'; + +import 'package:file_selector/file_selector.dart' as file_selector; + +/// Signature of a function that opens a native directory picker and returns +/// the selected path, or `null` if the user cancelled. +typedef DirectoryPicker = Future Function(); + +/// {@template file_system_client} +/// A client for interacting with the local file system. +/// {@endtemplate} +class FileSystemClient({DirectoryPicker? directoryPicker}) { + /// {@macro file_system_client} + this; + + final DirectoryPicker _directoryPicker = + directoryPicker ?? file_selector.getDirectoryPath; + + /// Opens a native dialog to pick a directory. + /// + /// Returns the selected path, or `null` if the dialog was cancelled. + Future pickDirectory() => _directoryPicker(); + + /// Whether a directory exists at [path]. + Future directoryExists(String path) async => + Directory(path).existsSync(); + + /// Whether a file exists at [path]. + Future fileExists(String path) async => File(path).existsSync(); + + /// Returns the paths of the files directly inside [directoryPath]. + /// + /// When [extension] is given (e.g. `.json`), only files ending with it are + /// returned. Returns an empty list if the directory does not exist. + Future> listFiles( + String directoryPath, { + String? extension, + }) async { + final directory = Directory(directoryPath); + if (!directory.existsSync()) { + return const []; + } + + return [ + await for (final entity in directory.list()) + if (entity is File && + (extension == null || entity.path.endsWith(extension))) + entity.path, + ]; + } + + /// Reads the file at [path] as a string. + Future readFile(String path) => File(path).readAsString(); + + /// Writes [contents] to the file at [path], creating any missing parent + /// directories. + Future writeFile(String path, String contents) async { + final file = File(path); + await file.parent.create(recursive: true); + await file.writeAsString(contents); + } + + /// Deletes the file at [path]. + Future deleteFile(String path) => File(path).delete(); +} diff --git a/packages/flame_studio/lib/clients/key_value_storage_client.dart b/packages/flame_studio/lib/clients/key_value_storage_client.dart new file mode 100644 index 00000000000..e3a7dc29f6f --- /dev/null +++ b/packages/flame_studio/lib/clients/key_value_storage_client.dart @@ -0,0 +1,19 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +/// {@template key_value_storage_client} +/// A client that persists string values under string keys. +/// {@endtemplate} +class KeyValueStorageClient({SharedPreferencesAsync? preferences}) { + /// {@macro key_value_storage_client} + this; + + final SharedPreferencesAsync _preferences = + preferences ?? SharedPreferencesAsync(); + + /// Returns the value stored under [key], or `null` if there is none. + Future read(String key) => _preferences.getString(key); + + /// Stores [value] under [key], replacing any previous value. + Future write(String key, String value) => + _preferences.setString(key, value); +} diff --git a/packages/flame_studio/lib/component_editor/bloc/component_editor_bloc.dart b/packages/flame_studio/lib/component_editor/bloc/component_editor_bloc.dart new file mode 100644 index 00000000000..841050d18cf --- /dev/null +++ b/packages/flame_studio/lib/component_editor/bloc/component_editor_bloc.dart @@ -0,0 +1,470 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flame_studio/repositories/repositories.dart'; + +part 'component_editor_event.dart'; +part 'component_editor_state.dart'; + +/// {@template component_editor_bloc} +/// Edits a [Component] of a [Project], including the tree of components +/// inside it, and saves it. +/// +/// Saving also generates the Dart code of the component in the output +/// folder of the project settings. +/// +/// Property events edit the selected node of the tree (the root by +/// default). They are handled through the capability interfaces +/// ([PositionedComponent], [SizedComponent], [PaintedComponent], ...), so +/// they work for every component type that has that property. +/// {@endtemplate} +class ComponentEditorBloc({ + required final Project _project, + required Component component, + required final ComponentRepository _componentRepository, + required final ProjectRepository _projectRepository, + required final EditorPreferencesRepository _editorPreferencesRepository, +}) extends Bloc { + /// {@macro component_editor_bloc} + this + : super( + ComponentEditorState(component: component, savedComponent: component), + ) { + on(_onStarted); + on(_onNodeSelected); + on(_onChildAdded); + on(_onNodeRemoved); + on(_onNameChanged); + on(_onPositionChanged); + on(_onAnchorChanged); + on(_onAngleChanged); + on(_onSizeChanged); + on(_onRadiusChanged); + on(_onVerticesChanged); + on(_onPaintChanged); + on(_onCollisionChanged); + on(_onPaletteChanged); + on(_onSelectionHighlightToggled); + on(_onHitboxesVisibilityToggled); + on(_onZoomedIn); + on(_onZoomedOut); + on(_onZoomReset); + on(_onSaveRequested); + } + + /// How many saves were requested, so slower work started before a save + /// doesn't overwrite what the save found. + int _saves = 0; + + /// Whether a [ComponentEditorPaletteChanged] was handled. + bool _isPaletteChanged = false; + + /// Whether the user zoomed, so the stored zoom loaded on start doesn't + /// replace the newer one. + bool _isZoomChanged = false; + + /// The status after an edit: edits are allowed while saving, but must not + /// end the save, or another save could run at the same time. + ComponentEditorStatus get _editedStatus => + state.status == ComponentEditorStatus.saving + ? ComponentEditorStatus.saving + : ComponentEditorStatus.ready; + + Future _onStarted( + ComponentEditorStarted event, + Emitter emit, + ) async { + // A save that started meanwhile loads the same things again, and its + // results are newer. + final saves = _saves; + bool isSaving() => + _saves != saves || state.status == ComponentEditorStatus.saving; + + try { + final zoom = await _editorPreferencesRepository.getComponentZoom( + projectPath: _project.path, + componentName: state.component.name, + ); + if (!_isZoomChanged && zoom != state.zoom) { + emit(state.copyWith(zoom: zoom)); + } + } on Exception { + // The preview keeps the default zoom. + } + + try { + final palette = await _componentRepository.getPalette(_project.path); + // A palette changed meanwhile is newer. + if (!_isPaletteChanged && palette != state.palette) { + emit(state.copyWith(palette: palette)); + } + } on Exception { + // Paints keep the last known value of their palette colors. + } + + try { + final taken = await _loadTakenClassNames(); + if (isSaving()) { + return; + } + emit(state.copyWith(takenClassNames: taken)); + // Clashes from before names were checked across components. + if (state.conflictingClassNames.isNotEmpty) { + emit(state.copyWith(status: ComponentEditorStatus.classConflict)); + } + } on Exception { + // Names are still validated inside the tree, and against the other + // components when saving. + } + + try { + final settings = await _projectRepository.getSettings(_project); + final isUpToDate = await _componentRepository.isComponentCodeUpToDate( + _project.path, + settings.outputPath, + state.savedComponent, + ); + if (isSaving()) { + return; + } + emit(state.copyWith(isCodeOutdated: !isUpToDate)); + } on Exception { + // Saving still needs changes then. + } + } + + /// The [ComponentTree.generatedClassNames] of the other components of + /// the project, with the component that generates each one. + Future> _loadTakenClassNames() async { + final components = await _componentRepository.getComponents(_project.path); + final name = state.component.name; + return { + for (final other in components) + if (other.name != name) + for (final className in other.generatedClassNames) className: other, + }; + } + + void _onNodeSelected( + ComponentEditorNodeSelected event, + Emitter emit, + ) { + if (!state.component.hasNodeAt(event.path)) { + return; + } + emit(state.copyWith(selectedPath: event.path)); + } + + void _onChildAdded( + ComponentEditorChildAdded event, + Emitter emit, + ) { + // Hitboxes can't have children. + if (state.selectedNode is HitboxComponent) { + return; + } + final component = state.component; + final parentPath = state.selectedPath; + final child = Component.create( + component.uniqueChildName( + event.type, + takenClassNames: state.takenClassNames.keys.toSet(), + ), + event.type, + polygonShape: event.polygonShape, + ); + emit( + state.copyWith( + status: _editedStatus, + component: component.addChildAt(parentPath, child), + selectedPath: [ + ...parentPath, + component.nodeAt(parentPath).children.length, + ], + ), + ); + } + + void _onNodeRemoved( + ComponentEditorNodeRemoved event, + Emitter emit, + ) { + final path = event.path; + if (path.isEmpty || !state.component.hasNodeAt(path)) { + return; + } + emit( + state.copyWith( + status: _editedStatus, + component: state.component.removeNodeAt(path), + selectedPath: path.sublist(0, path.length - 1), + ), + ); + } + + void _onNameChanged( + ComponentEditorNameChanged event, + Emitter emit, + ) { + final path = state.selectedPath; + if (path.isEmpty) { + return; + } + final error = state.component.validateChildName( + path, + event.name, + takenClassNames: state.takenClassNames.keys.toSet(), + ); + if (error != null) { + return; + } + _editSelected(emit, (node) => node.copyWithName(event.name)); + } + + void _onPositionChanged( + ComponentEditorPositionChanged event, + Emitter emit, + ) { + _editSelected(emit, (node) { + if (node case final PositionedComponent node) { + return node.copyWithPosition(event.position); + } + return node; + }); + } + + void _onAnchorChanged( + ComponentEditorAnchorChanged event, + Emitter emit, + ) { + _editSelected(emit, (node) { + if (node case final AnchoredComponent node) { + return node.copyWithAnchor(event.anchor); + } + return node; + }); + } + + void _onAngleChanged( + ComponentEditorAngleChanged event, + Emitter emit, + ) { + _editSelected(emit, (node) { + if (node case final RotatedComponent node) { + return node.copyWithAngle(event.angle); + } + return node; + }); + } + + void _onSizeChanged( + ComponentEditorSizeChanged event, + Emitter emit, + ) { + _editSelected(emit, (node) { + if (node case final SizedComponent node) { + return node.copyWithSize(event.size); + } + return node; + }); + } + + void _onRadiusChanged( + ComponentEditorRadiusChanged event, + Emitter emit, + ) { + _editSelected(emit, (node) { + if (node case final RadiusComponent node) { + return node.copyWithRadius(event.radius); + } + return node; + }); + } + + void _onVerticesChanged( + ComponentEditorVerticesChanged event, + Emitter emit, + ) { + _editSelected(emit, (node) { + if (node case final VerticesComponent node) { + return node.copyWithVertices(event.vertices); + } + return node; + }); + } + + void _onPaintChanged( + ComponentEditorPaintChanged event, + Emitter emit, + ) { + _editSelected(emit, (node) { + if (node case final PaintedComponent node) { + return node.copyWithPaint(event.paint); + } + return node; + }); + } + + void _onCollisionChanged( + ComponentEditorCollisionChanged event, + Emitter emit, + ) { + _editSelected(emit, (node) { + if (node case final HitboxComponent node) { + return node.copyWithCollision(event.collision); + } + return node; + }); + } + + void _onPaletteChanged( + ComponentEditorPaletteChanged event, + Emitter emit, + ) { + _isPaletteChanged = true; + emit(state.copyWith(palette: event.palette)); + } + + /// Replaces the selected node with the result of [edit]. + void _editSelected( + Emitter emit, + Component Function(Component node) edit, + ) { + final component = state.component.updateNodeAt(state.selectedPath, edit); + if (component == state.component) { + return; + } + emit(state.copyWith(status: _editedStatus, component: component)); + } + + void _onSelectionHighlightToggled( + ComponentEditorSelectionHighlightToggled event, + Emitter emit, + ) { + emit(state.copyWith(isSelectionHighlighted: !state.isSelectionHighlighted)); + } + + void _onHitboxesVisibilityToggled( + ComponentEditorHitboxesVisibilityToggled event, + Emitter emit, + ) { + emit(state.copyWith(areHitboxesVisible: !state.areHitboxesVisible)); + } + + Future _onZoomedIn( + ComponentEditorZoomedIn event, + Emitter emit, + ) async { + final zoom = state.nextZoom; + if (zoom != null) { + await _zoom(emit, zoom); + } + } + + Future _onZoomedOut( + ComponentEditorZoomedOut event, + Emitter emit, + ) async { + final zoom = state.previousZoom; + if (zoom != null) { + await _zoom(emit, zoom); + } + } + + Future _onZoomReset( + ComponentEditorZoomReset event, + Emitter emit, + ) => _zoom(emit, EditorPreferencesRepository.defaultZoom); + + /// Shows the preview at [zoom] and remembers it for this component. + Future _zoom(Emitter emit, double zoom) async { + _isZoomChanged = true; + emit(state.copyWith(zoom: zoom)); + try { + await _editorPreferencesRepository.setComponentZoom( + projectPath: _project.path, + componentName: state.component.name, + zoom: zoom, + ); + } on Exception { + // The zoom is only a convenience: it is just not remembered. + } + } + + Future _onSaveRequested( + ComponentEditorSaveRequested event, + Emitter emit, + ) async { + if (!state.canSave) { + return; + } + _saves++; + final component = state.component; + emit(state.copyWith(status: ComponentEditorStatus.saving)); + + // Names are validated as they are typed, but the other components may + // not have been loaded yet, or may clash with this one already. A + // component whose classes clash is not saved: its code wouldn't + // compile, and its file would reserve classes other components own. + final Map taken; + try { + taken = await _loadTakenClassNames(); + } on Exception { + emit(state.copyWith(status: ComponentEditorStatus.failure)); + return; + } + if (component.generatedClassNames.any(taken.containsKey)) { + final conflict = state.copyWith( + status: ComponentEditorStatus.classConflict, + takenClassNames: taken, + ); + // Clashing children may have been renamed while loading. + emit( + conflict.conflictingClassNames.isEmpty + ? conflict.copyWith(status: ComponentEditorStatus.ready) + : conflict, + ); + return; + } + + try { + await _componentRepository.saveComponent(_project.path, component); + } on Exception { + emit( + state.copyWith( + status: ComponentEditorStatus.failure, + takenClassNames: taken, + ), + ); + return; + } + + // The component is saved even if its code can't be generated; it can + // then be saved again, without changes, to generate the code. States + // are built from the current state, which keeps edits made while + // saving. + void emitSaved(ComponentEditorStatus status) { + emit( + state.copyWith( + status: status, + savedComponent: component, + takenClassNames: taken, + isCodeOutdated: status != ComponentEditorStatus.saved, + ), + ); + } + + try { + final settings = await _projectRepository.getSettings(_project); + await _componentRepository.writeComponentCode( + _project.path, + settings.outputPath, + component, + ); + emitSaved(ComponentEditorStatus.saved); + } on GeneratedFileConflictException { + emitSaved(ComponentEditorStatus.codeConflict); + } on Exception { + emitSaved(ComponentEditorStatus.codeFailure); + } + } +} diff --git a/packages/flame_studio/lib/component_editor/bloc/component_editor_event.dart b/packages/flame_studio/lib/component_editor/bloc/component_editor_event.dart new file mode 100644 index 00000000000..81984e57ed3 --- /dev/null +++ b/packages/flame_studio/lib/component_editor/bloc/component_editor_event.dart @@ -0,0 +1,223 @@ +part of 'component_editor_bloc.dart'; + +/// Base class for [ComponentEditorBloc] events. +sealed class const ComponentEditorEvent() extends Equatable { + /// Creates a [ComponentEditorEvent]. + this; + + @override + List get props => []; +} + +/// The editor opened: the other components of the project should be +/// loaded, so the names of children can be checked against their classes. +final class const ComponentEditorStarted() extends ComponentEditorEvent { + /// Creates a [ComponentEditorStarted] event. + this; +} + +/// The user selected the node at [path] in the component tree. +final class const ComponentEditorNodeSelected( + /// The path of the node, see [ComponentTree]. + final List path, +) extends ComponentEditorEvent { + /// Creates a [ComponentEditorNodeSelected] event. + this; + + @override + List get props => [path]; +} + +/// The user added a component of [type] inside the selected node. +/// +/// Polygons start with the vertices of [polygonShape]. +final class const ComponentEditorChildAdded( + /// The type of the new component. + final ComponentType type, { + + /// The shape of the new component, if it is a polygon. + final PolygonShape polygonShape = PolygonShape.triangle, +}) extends ComponentEditorEvent { + /// Creates a [ComponentEditorChildAdded] event. + this; + + @override + List get props => [type, polygonShape]; +} + +/// The user removed the node at [path] from the component tree. +/// +/// The root cannot be removed. +final class const ComponentEditorNodeRemoved( + /// The path of the node, see [ComponentTree]. + final List path, +) extends ComponentEditorEvent { + /// Creates a [ComponentEditorNodeRemoved] event. + this; + + @override + List get props => [path]; +} + +/// The user renamed the selected node. +/// +/// The root can't be renamed, and names rejected by +/// [ComponentTree.validateChildName] are ignored. +final class const ComponentEditorNameChanged( + /// The new name. + final String name, +) extends ComponentEditorEvent { + /// Creates a [ComponentEditorNameChanged] event. + this; + + @override + List get props => [name]; +} + +/// The user edited the position of the selected [PositionedComponent]. +final class const ComponentEditorPositionChanged( + /// The new position. + final ComponentPosition position, +) extends ComponentEditorEvent { + /// Creates a [ComponentEditorPositionChanged] event. + this; + + @override + List get props => [position]; +} + +/// The user edited the size of the selected [SizedComponent]. +final class const ComponentEditorSizeChanged( + /// The new size. + final ComponentSize size, +) extends ComponentEditorEvent { + /// Creates a [ComponentEditorSizeChanged] event. + this; + + @override + List get props => [size]; +} + +/// The user edited the anchor of the selected [AnchoredComponent]. +final class const ComponentEditorAnchorChanged( + /// The new anchor. + final ComponentAnchor anchor, +) extends ComponentEditorEvent { + /// Creates a [ComponentEditorAnchorChanged] event. + this; + + @override + List get props => [anchor]; +} + +/// The user edited the angle of the selected [RotatedComponent]. +final class const ComponentEditorAngleChanged( + /// The new angle. + final ComponentAngle angle, +) extends ComponentEditorEvent { + /// Creates a [ComponentEditorAngleChanged] event. + this; + + @override + List get props => [angle]; +} + +/// The user edited the radius of the selected [RadiusComponent]. +final class const ComponentEditorRadiusChanged( + /// The new radius. + final ComponentRadius radius, +) extends ComponentEditorEvent { + /// Creates a [ComponentEditorRadiusChanged] event. + this; + + @override + List get props => [radius]; +} + +/// The user edited the vertices of the selected [VerticesComponent]. +final class const ComponentEditorVerticesChanged( + /// The new vertices. + final ComponentVertices vertices, +) extends ComponentEditorEvent { + /// Creates a [ComponentEditorVerticesChanged] event. + this; + + @override + List get props => [vertices]; +} + +/// The user edited the paint of the selected [PaintedComponent]. +final class const ComponentEditorPaintChanged( + /// The new paint. + final ComponentPaint paint, +) extends ComponentEditorEvent { + /// Creates a [ComponentEditorPaintChanged] event. + this; + + @override + List get props => [paint]; +} + +/// The palette of the project changed, e.g. in the palette dialog. +final class const ComponentEditorPaletteChanged( + /// The new palette. + final Palette palette, +) extends ComponentEditorEvent { + /// Creates a [ComponentEditorPaletteChanged] event. + this; + + @override + List get props => [palette]; +} + +/// The user edited the collision of the selected [HitboxComponent]. +final class const ComponentEditorCollisionChanged( + /// The new collision. + final ComponentCollision collision, +) extends ComponentEditorEvent { + /// Creates a [ComponentEditorCollisionChanged] event. + this; + + @override + List get props => [collision]; +} + +/// The user toggled the highlight of the selected node in the preview. +final class const ComponentEditorSelectionHighlightToggled() + extends ComponentEditorEvent { + /// Creates a [ComponentEditorSelectionHighlightToggled] event. + this; +} + +/// The user toggled the outlines of the hitboxes in the preview. +final class const ComponentEditorHitboxesVisibilityToggled() + extends ComponentEditorEvent { + /// Creates a [ComponentEditorHitboxesVisibilityToggled] event. + this; +} + +/// The user zoomed in the preview, to the next of +/// [ZoomLevels]. +final class const ComponentEditorZoomedIn() extends ComponentEditorEvent { + /// Creates a [ComponentEditorZoomedIn] event. + this; +} + +/// The user zoomed out the preview, to the previous of +/// [ZoomLevels]. +final class const ComponentEditorZoomedOut() extends ComponentEditorEvent { + /// Creates a [ComponentEditorZoomedOut] event. + this; +} + +/// The user reset the zoom of the preview to 100%. +final class const ComponentEditorZoomReset() extends ComponentEditorEvent { + /// Creates a [ComponentEditorZoomReset] event. + this; +} + +/// The user asked to save the component. +final class const ComponentEditorSaveRequested() extends ComponentEditorEvent { + /// Creates a [ComponentEditorSaveRequested] event. + this; +} diff --git a/packages/flame_studio/lib/component_editor/bloc/component_editor_state.dart b/packages/flame_studio/lib/component_editor/bloc/component_editor_state.dart new file mode 100644 index 00000000000..c5264bfd84a --- /dev/null +++ b/packages/flame_studio/lib/component_editor/bloc/component_editor_state.dart @@ -0,0 +1,169 @@ +part of 'component_editor_bloc.dart'; + +/// The status of the [ComponentEditorBloc]. +enum ComponentEditorStatus() { + /// The component can be edited. + ready, + + /// The component is being saved. + saving, + + /// The component was saved and its code generated. + saved, + + /// The component was saved, but its code was not generated because a + /// file that was not generated by the editor is in the way. + codeConflict, + + /// The component can't be saved because some of its classes are + /// generated for other components too; see + /// [ComponentEditorState.conflictingClassNames] and + /// [ComponentEditorState.rootClassOwner]. + classConflict, + + /// The component was saved, but generating its code failed. + codeFailure, + + /// Something went wrong while saving. + failure; + + /// Whether the component was saved, even if its code was not generated. + bool get isSaved => + this == saved || this == codeConflict || this == codeFailure; +} + +/// {@template component_editor_state} +/// The state of the [ComponentEditorBloc]. +/// {@endtemplate} +final class const ComponentEditorState({ + /// The component being edited, including unsaved changes. + required final Component component, + + /// The component as it was last saved. + required final Component savedComponent, + + /// The current status. + final ComponentEditorStatus status = ComponentEditorStatus.ready, + + /// The path of the selected node of the [component] tree, see + /// [ComponentTree]. The root, the empty path, is selected by default. + final List selectedPath = const [], + + /// The classes generated for the other components of the project, which + /// the children of [component] must not generate again (see + /// [ComponentTree.generatedClassNames]), with the component that + /// generates each one. + final Map takenClassNames = const {}, + + /// Whether the generated code doesn't match [savedComponent]: it was + /// missing or outdated when the editor opened, or the last save didn't + /// generate it (see [ComponentEditorStatus.codeConflict] and + /// [ComponentEditorStatus.codeFailure]). + /// + /// The component can then be saved without changes, to generate the + /// code once whatever was in the way is fixed. + final bool isCodeOutdated = false, + + /// Whether the preview highlights the selected node, when it has a size + /// or a radius (see [SizedComponent] and [RadiusComponent]). + final bool isSelectionHighlighted = true, + + /// Whether the preview outlines the hitboxes ([HitboxComponent]), which + /// draw nothing themselves. + final bool areHitboxesVisible = true, + + /// The palette of the project, whose colors paints can use (see + /// [ComponentPaint.paletteColor]). + final Palette palette = const Palette(), + + /// The zoom of the preview, `1` being the actual size. + /// + /// It is an editor preference, remembered for each component, not part + /// of the [component]. + final double zoom = EditorPreferencesRepository.defaultZoom, +}) extends Equatable { + /// {@macro component_editor_state} + this; + + /// The zoom after zooming in (see [ZoomLevels.next]), or `null` if + /// [zoom] is the largest one. + double? get nextZoom => ZoomLevels.next(zoom); + + /// The zoom after zooming out (see [ZoomLevels.previous]), or `null` if + /// [zoom] is the smallest one. + double? get previousZoom => ZoomLevels.previous(zoom); + + /// Whether the component can be saved: it has changes or its code is + /// outdated, and it is not being saved already. + bool get canSave => + (hasChanges || isCodeOutdated) && status != ComponentEditorStatus.saving; + + /// The classes of [component] that are generated for other components + /// too, with the component that generates each one; see + /// [takenClassNames]. + Map get conflictingClassNames => { + for (final className in component.generatedClassNames) + if (takenClassNames.containsKey(className)) + className: takenClassNames[className]!, + }; + + /// The other component that generates the class of the root [component] + /// too, if any. + /// + /// Renaming children here can't fix this clash, and components can't be + /// renamed: a child of the other component must be renamed, or, if the + /// clash is between the two roots, one of the components deleted. + Component? get rootClassOwner => + takenClassNames[component.generatedClassName]; + + /// The selected node of the [component] tree. + Component get selectedNode => component.nodeAt(selectedPath); + + /// Whether the selected node is the root [component]. + bool get isRootSelected => selectedPath.isEmpty; + + /// Whether [component] has changes that were not saved yet. + bool get hasChanges => component != savedComponent; + + /// Returns a copy of this state with the given fields replaced. + ComponentEditorState copyWith({ + ComponentEditorStatus? status, + Component? component, + Component? savedComponent, + List? selectedPath, + Map? takenClassNames, + bool? isCodeOutdated, + bool? isSelectionHighlighted, + bool? areHitboxesVisible, + Palette? palette, + double? zoom, + }) { + return ComponentEditorState( + status: status ?? this.status, + component: component ?? this.component, + savedComponent: savedComponent ?? this.savedComponent, + selectedPath: selectedPath ?? this.selectedPath, + takenClassNames: takenClassNames ?? this.takenClassNames, + isCodeOutdated: isCodeOutdated ?? this.isCodeOutdated, + isSelectionHighlighted: + isSelectionHighlighted ?? this.isSelectionHighlighted, + areHitboxesVisible: areHitboxesVisible ?? this.areHitboxesVisible, + palette: palette ?? this.palette, + zoom: zoom ?? this.zoom, + ); + } + + @override + List get props => [ + status, + component, + savedComponent, + selectedPath, + takenClassNames, + isCodeOutdated, + isSelectionHighlighted, + areHitboxesVisible, + palette, + zoom, + ]; +} diff --git a/packages/flame_studio/lib/component_editor/component_editor.dart b/packages/flame_studio/lib/component_editor/component_editor.dart new file mode 100644 index 00000000000..8d32cf01700 --- /dev/null +++ b/packages/flame_studio/lib/component_editor/component_editor.dart @@ -0,0 +1,2 @@ +export 'bloc/component_editor_bloc.dart'; +export 'view/view.dart'; diff --git a/packages/flame_studio/lib/component_editor/view/component_editor_page.dart b/packages/flame_studio/lib/component_editor/view/component_editor_page.dart new file mode 100644 index 00000000000..bc62866204b --- /dev/null +++ b/packages/flame_studio/lib/component_editor/view/component_editor_page.dart @@ -0,0 +1,43 @@ +import 'package:flame_studio/component_editor/bloc/component_editor_bloc.dart'; +import 'package:flame_studio/component_editor/view/component_editor_view.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template component_editor_page} +/// The editor screen for a [Component] of a [Project]. +/// {@endtemplate} +class const ComponentEditorPage({ + /// The project the component belongs to. + required final Project project, + + /// The component being edited. + required final Component component, + super.key, +}) extends StatelessWidget { + /// {@macro component_editor_page} + this; + + /// Creates a route to the [ComponentEditorPage] for [component]. + static Route route(Project project, Component component) { + return MaterialPageRoute( + builder: (_) => + ComponentEditorPage(project: project, component: component), + ); + } + + @override + Widget build(BuildContext context) { + return BlocProvider( + create: (context) => ComponentEditorBloc( + project: project, + component: component, + componentRepository: context.read(), + projectRepository: context.read(), + editorPreferencesRepository: context + .read(), + )..add(const ComponentEditorStarted()), + child: ComponentEditorView(project: project), + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/view/component_editor_view.dart b/packages/flame_studio/lib/component_editor/view/component_editor_view.dart new file mode 100644 index 00000000000..fc85c7c1e5c --- /dev/null +++ b/packages/flame_studio/lib/component_editor/view/component_editor_view.dart @@ -0,0 +1,228 @@ +import 'dart:async'; + +import 'package:flame_studio/component_editor/bloc/component_editor_bloc.dart'; +import 'package:flame_studio/component_editor/widgets/widgets.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flame_studio/widgets/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template component_editor_view} +/// Shows the tree of the component being edited on the left, its preview +/// in the center, below a toolbar, and the properties of the selected node +/// on the right, below a top bar with the project actions (such as the +/// palette). +/// +/// Changes are saved with the save button or Cmd/Ctrl+S. The preview zooms +/// in with Cmd/Ctrl+=, out with Cmd/Ctrl+- and back to 100% with +/// Cmd/Ctrl+0. +/// {@endtemplate} +class const ComponentEditorView({ + /// The project the component belongs to. + required final Project project, + super.key, +}) extends StatelessWidget { + /// {@macro component_editor_view} + this; + + /// Width of the component tree panel. + static const treePanelWidth = 240.0; + + /// Width of the properties panel. + static const propertiesPanelWidth = 320.0; + + @override + Widget build(BuildContext context) { + final bloc = context.read(); + void save() => bloc.add(const ComponentEditorSaveRequested()); + void zoomIn() => bloc.add(const ComponentEditorZoomedIn()); + void zoomOut() => bloc.add(const ComponentEditorZoomedOut()); + void resetZoom() => bloc.add(const ComponentEditorZoomReset()); + + return BlocListener( + listenWhen: (previous, current) => previous.status != current.status, + listener: (context, state) { + final message = switch (state.status) { + ComponentEditorStatus.failure => 'Could not save the component', + ComponentEditorStatus.codeConflict => + 'Saved, but the code was not generated: a file that was not ' + 'generated by the editor is in the way', + ComponentEditorStatus.classConflict => _classConflictMessage(state), + ComponentEditorStatus.codeFailure => + 'Saved, but the code could not be generated', + _ => null, + }; + if (message != null) { + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar(SnackBar(content: Text(message))); + } + }, + child: CallbackShortcuts( + bindings: { + const SingleActivator(LogicalKeyboardKey.keyS, meta: true): save, + const SingleActivator(LogicalKeyboardKey.keyS, control: true): save, + ...zoomShortcuts( + onZoomIn: zoomIn, + onZoomOut: zoomOut, + onReset: resetZoom, + ), + }, + child: _UnsavedChangesGuard( + child: Focus( + autofocus: true, + child: Scaffold( + appBar: AppBar( + title: const _Title(), + actions: [_SaveButton(onPressed: save)], + ), + body: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + EditorTopBar(project: project), + const Divider(height: 1), + const Expanded( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SizedBox( + width: treePanelWidth, + child: ComponentTreePanel(), + ), + VerticalDivider(width: 1), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + EditorToolbar(), + Divider(height: 1), + Expanded(child: ComponentPreview()), + ], + ), + ), + VerticalDivider(width: 1), + SizedBox( + width: propertiesPanelWidth, + child: PropertiesPanel(), + ), + ], + ), + ), + ], + ), + ), + ), + ), + ), + ); + } + + /// Tells how to fix each clash: children can be renamed here, but the + /// root can't (and neither can components), so a clash of the root class + /// must be fixed in the other component, or by deleting one of the two. + static String _classConflictMessage(ComponentEditorState state) { + final rootClass = state.component.generatedClassName; + final rootOwner = state.rootClassOwner; + final childClashes = [ + for (final MapEntry(key: className, value: owner) + in state.conflictingClassNames.entries) + if (className != rootClass) + '$className (also generated by "${owner.name}")', + ]; + final rootFix = switch (rootOwner) { + null => null, + Component(:final name, :final generatedClassName) + when generatedClassName == rootClass => + '"$name" generates the same class, $rootClass: delete one of the ' + 'two components.', + Component(:final name) => + 'A child of "$name" generates $rootClass, the class of this ' + 'component: rename that child.', + }; + final childrenFix = childClashes.isEmpty + ? null + : 'Rename the children that generate ${childClashes.join(', ')}.'; + return ["This component can't be saved.", ?rootFix, ?childrenFix].join(' '); + } +} + +/// Asks what to do with unsaved changes before the editor is left. +class const _UnsavedChangesGuard({required final Widget child}) + extends StatelessWidget { + @override + Widget build(BuildContext context) { + final hasChanges = context.select( + (bloc) => bloc.state.hasChanges, + ); + return PopScope( + canPop: !hasChanges, + onPopInvokedWithResult: (didPop, _) { + if (!didPop) { + unawaited(_confirmLeave(context)); + } + }, + child: child, + ); + } + + Future _confirmLeave(BuildContext context) async { + final bloc = context.read(); + final navigator = Navigator.of(context); + + final decision = await UnsavedChangesDialog.show(context); + switch (decision) { + case UnsavedChangesDecision.cancel: + return; + case UnsavedChangesDecision.discard: + navigator.pop(); + case UnsavedChangesDecision.save: + // A save that finished while the dialog was open saved everything. + if (!bloc.state.hasChanges) { + return navigator.pop(); + } + bloc.add(const ComponentEditorSaveRequested()); + // Edits keep the saving status, so the first other status is the + // result of the save (or of the one already running). + final state = await bloc.stream.firstWhere( + (state) => state.status != ComponentEditorStatus.saving, + orElse: () => bloc.state, + ); + // The editor was closed meanwhile. + if (bloc.isClosed) { + return; + } + // When not saved the editor stays open and shows the error. Edits + // made while saving keep it open too, so they are not lost. + if (state.status.isSaved && !state.hasChanges) { + navigator.pop(); + } + } + } +} + +class const _Title() extends StatelessWidget { + @override + Widget build(BuildContext context) { + final (name, hasChanges) = context + .select( + (bloc) => (bloc.state.component.name, bloc.state.hasChanges), + ); + return Text(hasChanges ? '$name •' : name); + } +} + +class const _SaveButton({required final VoidCallback onPressed}) + extends StatelessWidget { + @override + Widget build(BuildContext context) { + final canSave = context.select( + (bloc) => bloc.state.canSave, + ); + return IconButton( + tooltip: 'Save', + icon: const Icon(Icons.save_outlined), + onPressed: canSave ? onPressed : null, + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/view/view.dart b/packages/flame_studio/lib/component_editor/view/view.dart new file mode 100644 index 00000000000..c421f8c06ae --- /dev/null +++ b/packages/flame_studio/lib/component_editor/view/view.dart @@ -0,0 +1,2 @@ +export 'component_editor_page.dart'; +export 'component_editor_view.dart'; diff --git a/packages/flame_studio/lib/component_editor/widgets/component_preview.dart b/packages/flame_studio/lib/component_editor/widgets/component_preview.dart new file mode 100644 index 00000000000..18710dc09a1 --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/component_preview.dart @@ -0,0 +1,78 @@ +import 'package:flame/game.dart'; +import 'package:flame_studio/component_editor/bloc/component_editor_bloc.dart'; +import 'package:flame_studio/component_editor/widgets/preview/preview.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template component_preview} +/// Renders the component being edited with Flame, at +/// [ComponentEditorState.zoom], highlighting the selected node unless +/// [ComponentEditorState.isSelectionHighlighted] is off, and outlining the +/// hitboxes unless [ComponentEditorState.areHitboxesVisible] is off. +/// +/// Paints that use palette colors are drawn with their current value in +/// [ComponentEditorState.palette]. +/// {@endtemplate} +class const ComponentPreview({super.key}) extends StatefulWidget { + /// {@macro component_preview} + this; + + @override + State createState() => _ComponentPreviewState(); +} + +class _ComponentPreviewState() extends State { + late final ComponentPreviewGame _game = _createGame( + context.read().state, + ); + + static ComponentPreviewGame _createGame(ComponentEditorState state) { + return ComponentPreviewGame( + component: _previewed(state), + highlightedPath: _highlightedPath(state), + zoom: state.zoom, + areHitboxesVisible: state.areHitboxesVisible, + ); + } + + static Component _previewed(ComponentEditorState state) => + state.component.withPaletteColorsResolved(state.palette); + + static List? _highlightedPath(ComponentEditorState state) => + state.isSelectionHighlighted ? state.selectedPath : null; + + @override + Widget build(BuildContext context) { + return MultiBlocListener( + listeners: [ + BlocListener( + listenWhen: (previous, current) => previous.zoom != current.zoom, + listener: (context, state) => _game.zoom = state.zoom, + ), + BlocListener( + listenWhen: (previous, current) => + previous.areHitboxesVisible != current.areHitboxesVisible, + listener: (context, state) => + _game.areHitboxesVisible = state.areHitboxesVisible, + ), + BlocListener( + listenWhen: (previous, current) => + previous.component != current.component || + previous.palette != current.palette || + previous.selectedPath != current.selectedPath || + previous.isSelectionHighlighted != current.isSelectionHighlighted, + // A single call, so a removed node and the new selection are shown + // together. + listener: (context, state) => _game.show( + _previewed(state), + highlightedPath: _highlightedPath(state), + ), + ), + ], + // The preview takes no keyboard input; without this the game widget + // would grab focus and swallow the editor shortcuts (e.g. Cmd+S). + child: GameWidget(game: _game, autofocus: false), + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/component_tree_panel.dart b/packages/flame_studio/lib/component_editor/widgets/component_tree_panel.dart new file mode 100644 index 00000000000..87ee9e312d8 --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/component_tree_panel.dart @@ -0,0 +1,129 @@ +import 'package:flame_studio/component_editor/bloc/component_editor_bloc.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template component_tree_panel} +/// Shows the component being edited and the components inside it as a +/// tree. +/// +/// Tapping a node selects it, so the properties panel edits it. New +/// components are added inside the selected node, unless it is a hitbox, +/// which can't have children. +/// {@endtemplate} +class const ComponentTreePanel({super.key}) extends StatelessWidget { + /// {@macro component_tree_panel} + this; + + @override + Widget build(BuildContext context) { + final (component, selectedPath) = context + .select)>( + (bloc) => (bloc.state.component, bloc.state.selectedPath), + ); + final bloc = context.read(); + final nodes = _flatten(component, const []).toList(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 8, 8), + child: Row( + children: [ + Expanded( + child: Text( + 'Components', + style: Theme.of(context).textTheme.titleSmall, + ), + ), + PopupMenuButton( + tooltip: 'Add child', + icon: const Icon(Icons.add), + enabled: component.nodeAt(selectedPath) is! HitboxComponent, + onSelected: bloc.add, + itemBuilder: (_) => [ + for (final type in ComponentType.values) + if (type.hasVertices) + // One entry per shape a new polygon can start with. + for (final shape in PolygonShape.values) + PopupMenuItem( + value: ComponentEditorChildAdded( + type, + polygonShape: shape, + ), + child: ListTile( + leading: Icon(iconFor(type)), + title: Text( + '${type.label} (${shape.label.toLowerCase()})', + ), + ), + ) + else + PopupMenuItem( + value: ComponentEditorChildAdded(type), + child: ListTile( + leading: Icon(iconFor(type)), + title: Text(type.label), + ), + ), + ], + ), + IconButton( + tooltip: 'Remove', + icon: const Icon(Icons.delete_outline), + onPressed: selectedPath.isEmpty + ? null + : () => bloc.add(ComponentEditorNodeRemoved(selectedPath)), + ), + ], + ), + ), + const Divider(height: 1), + Expanded( + child: ListView( + children: [ + for (final (path, node) in nodes) + ListTile( + key: ValueKey(path.join('.')), + dense: true, + selected: listEquals(path, selectedPath), + contentPadding: EdgeInsetsDirectional.only( + start: 16.0 + path.length * 16, + end: 16, + ), + leading: Icon(iconFor(node.type), size: 18), + title: Text(node.name), + onTap: () => bloc.add(ComponentEditorNodeSelected(path)), + ), + ], + ), + ), + ], + ); + } + + /// The icon shown for components of [type]. + static IconData iconFor(ComponentType type) { + return switch (type) { + ComponentType.rectangle => Icons.crop_square, + ComponentType.position => Icons.crop_free, + ComponentType.circle => Icons.circle_outlined, + ComponentType.polygon => Icons.pentagon_outlined, + ComponentType.rectangleHitbox => Icons.select_all, + ComponentType.circleHitbox => Icons.track_changes, + ComponentType.polygonHitbox => Icons.hexagon_outlined, + }; + } + + static Iterable<(List, Component)> _flatten( + Component node, + List path, + ) sync* { + yield (path, node); + for (final (index, child) in node.children.indexed) { + yield* _flatten(child, [...path, index]); + } + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/editor_toolbar.dart b/packages/flame_studio/lib/component_editor/widgets/editor_toolbar.dart new file mode 100644 index 00000000000..705c56de52c --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/editor_toolbar.dart @@ -0,0 +1,126 @@ +import 'package:flame_studio/component_editor/bloc/component_editor_bloc.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flame_studio/widgets/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template editor_toolbar} +/// The bar above the preview, with the preview options: the selection +/// highlight, the hitboxes outlines and the zoom. +/// {@endtemplate} +class const EditorToolbar({super.key}) extends StatelessWidget { + /// {@macro editor_toolbar} + this; + + /// Height of the toolbar. + static const height = 40.0; + + @override + Widget build(BuildContext context) { + final isSelectionHighlighted = context.select( + (bloc) => bloc.state.isSelectionHighlighted, + ); + final areHitboxesVisible = context.select( + (bloc) => bloc.state.areHitboxesVisible, + ); + final bloc = context.read(); + final colorScheme = Theme.of(context).colorScheme; + return ColoredBox( + color: colorScheme.surfaceContainer, + child: SizedBox( + height: height, + // Scrolls rather than overflows when the preview is narrow. + child: LayoutBuilder( + builder: (context, constraints) => SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: ConstrainedBox( + constraints: BoxConstraints(minWidth: constraints.maxWidth), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + _ToolbarToggle( + tooltip: 'Highlight selection', + icon: Icons.highlight_alt, + isSelected: isSelectionHighlighted, + onPressed: () => bloc.add( + const ComponentEditorSelectionHighlightToggled(), + ), + ), + _ToolbarToggle( + tooltip: 'Show hitboxes', + icon: Icons.border_style, + isSelected: areHitboxesVisible, + onPressed: () => bloc.add( + const ComponentEditorHitboxesVisibilityToggled(), + ), + ), + ], + ), + const _EditorZoomControls(), + ], + ), + ), + ), + ), + ), + ), + ); + } +} + +class const _ToolbarToggle({ + required final String tooltip, + required final IconData icon, + required final bool isSelected, + required final VoidCallback onPressed, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final colorScheme = Theme.of(context).colorScheme; + return IconButton( + tooltip: tooltip, + iconSize: 20, + isSelected: isSelected, + icon: Icon(icon), + // Selected toggles get a filled background, so it's clear at a glance + // whether they are on. + style: ButtonStyle( + backgroundColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.selected) + ? colorScheme.primaryContainer + : null, + ), + foregroundColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.selected) + ? colorScheme.onPrimaryContainer + : colorScheme.onSurfaceVariant, + ), + ), + onPressed: onPressed, + ); + } +} + +class const _EditorZoomControls() extends StatelessWidget { + @override + Widget build(BuildContext context) { + final zoom = context.select( + (bloc) => bloc.state.zoom, + ); + final bloc = context.read(); + return ZoomControls( + zoom: zoom, + onZoomOut: ZoomLevels.previous(zoom) == null + ? null + : () => bloc.add(const ComponentEditorZoomedOut()), + onZoomIn: ZoomLevels.next(zoom) == null + ? null + : () => bloc.add(const ComponentEditorZoomedIn()), + onReset: () => bloc.add(const ComponentEditorZoomReset()), + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/editor_top_bar.dart b/packages/flame_studio/lib/component_editor/widgets/editor_top_bar.dart new file mode 100644 index 00000000000..0f84387c8e8 --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/editor_top_bar.dart @@ -0,0 +1,57 @@ +import 'package:flame_studio/component_editor/bloc/component_editor_bloc.dart'; +import 'package:flame_studio/palette/palette.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template editor_top_bar} +/// The bar below the app bar, above the editor panels, with the actions +/// that concern the whole project, such as managing its palette. +/// {@endtemplate} +class const EditorTopBar({ + /// The project the edited component belongs to. + required final Project project, + super.key, +}) extends StatelessWidget { + /// {@macro editor_top_bar} + this; + + /// Height of the bar. + static const height = 40.0; + + Future _openPalette(BuildContext context) async { + final bloc = context.read(); + final palette = await PaletteDialog.show( + context, + project: project, + component: bloc.state.component, + ); + // The editor may have been closed meanwhile. + if (palette != null && context.mounted) { + bloc.add(ComponentEditorPaletteChanged(palette)); + } + } + + @override + Widget build(BuildContext context) { + final colorScheme = Theme.of(context).colorScheme; + return ColoredBox( + color: colorScheme.surfaceContainer, + child: SizedBox( + height: height, + child: Row( + children: [ + const SizedBox(width: 8), + IconButton( + tooltip: 'Palette', + iconSize: 20, + color: colorScheme.onSurfaceVariant, + icon: const Icon(Icons.palette_outlined), + onPressed: () => _openPalette(context), + ), + ], + ), + ), + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/preview/component_preview_game.dart b/packages/flame_studio/lib/component_editor/widgets/preview/component_preview_game.dart new file mode 100644 index 00000000000..497a1458beb --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/preview/component_preview_game.dart @@ -0,0 +1,125 @@ +import 'package:flame/components.dart' as flame; +import 'package:flame/game.dart'; +import 'package:flame_studio/component_editor/widgets/preview/flame_mapping.dart'; +import 'package:flame_studio/component_editor/widgets/preview/preview_hitboxes.dart'; +import 'package:flame_studio/component_editor/widgets/preview/selection_highlight.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/painting.dart'; + +/// {@template component_preview_game} +/// A Flame game that renders a [Component] and its children, centered on +/// screen and scaled by [zoom], and highlights one of them. Hitboxes are +/// outlined while [areHitboxesVisible]. +/// +/// The game only renders: the component being edited is owned by the +/// `ComponentEditorBloc` and pushed here with [show]. +/// {@endtemplate} +class ComponentPreviewGame({ + required var Component _component, + var List? _highlightedPath, + var double _zoom = 1, + var bool _areHitboxesVisible = true, +}) extends FlameGame { + /// {@macro component_preview_game} + this; + + late flame.PositionComponent _preview; + + /// The Flame component currently rendering the previewed root + /// [Component]. Its children render the [Component] children. + flame.PositionComponent get preview => _preview; + + /// Draws the border around the highlighted node. + final highlight = SelectionHighlight(); + + /// How much the preview is scaled, `1` being the actual size. It zooms + /// around the center of the screen, where the root is. + double get zoom => _zoom; + set zoom(double value) { + _zoom = value; + if (isLoaded) { + _applyZoom(); + } + } + + /// Whether the hitboxes are outlined (see [PreviewHitbox]). + bool get areHitboxesVisible => _areHitboxesVisible; + set areHitboxesVisible(bool value) { + _areHitboxesVisible = value; + if (isLoaded) { + _applyHitboxesVisibility(); + } + } + + @override + Color backgroundColor() => const Color(0xFF1E1E1E); + + @override + void onLoad() { + world.add(highlight); + _applyZoom(); + _rebuild(); + } + + /// Renders [component] instead of the current one, highlighting the node + /// at [highlightedPath] (see [ComponentTree]), if any. + /// + /// Only nodes with a size, a radius or vertices ([SizedComponent], + /// [RadiusComponent], [VerticesComponent]) are highlighted. + /// + /// The existing Flame components are updated in place, unless components + /// were added, removed or changed type, or polygons got new vertices (see + /// [haveSameShape]). + void show(Component component, {List? highlightedPath}) { + final previous = _component; + _component = component; + _highlightedPath = highlightedPath; + if (!isLoaded) { + return; + } + if (haveSameShape(previous, component)) { + applyTree(_preview, component); + _updateHighlight(); + } else { + _rebuild(); + } + } + + void _applyZoom() { + camera.viewfinder.zoom = _zoom; + highlight.zoom = _zoom; + } + + void _rebuild() { + if (isLoaded) { + _preview.removeFromParent(); + } + _preview = buildFlameComponent(_component); + world.add(_preview); + _applyHitboxesVisibility(); + _updateHighlight(); + } + + void _applyHitboxesVisibility() { + for (final hitbox + in _preview.descendants(includeSelf: true).whereType()) { + hitbox.isVisible = _areHitboxesVisible; + } + } + + void _updateHighlight() { + final path = _highlightedPath; + highlight.target = + path != null && + _component.hasNodeAt(path) && + _hasBounds(_component.nodeAt(path)) + ? flameNodeAt(_preview, path) + : null; + } + + static bool _hasBounds(Component node) { + return node is SizedComponent || + node is RadiusComponent || + node is VerticesComponent; + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/preview/dashed_outline.dart b/packages/flame_studio/lib/component_editor/widgets/preview/dashed_outline.dart new file mode 100644 index 00000000000..322288d7a99 --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/preview/dashed_outline.dart @@ -0,0 +1,48 @@ +import 'dart:math' as math; + +import 'package:flutter/painting.dart'; + +/// The length of each dash of the preview outlines, and of the gap after +/// it. +const dashLength = 4.0; + +/// Draws the closed outline through [points] on [canvas] with [paint], as a +/// dashed line. +void drawDashedPolygon(Canvas canvas, List points, Paint paint) { + for (var i = 0; i < points.length; i++) { + _drawDashedLine(canvas, points[i], points[(i + 1) % points.length], paint); + } +} + +/// Draws a circle of [radius] around [center] on [canvas] with [paint], as +/// a dashed line. +void drawDashedCircle( + Canvas canvas, + Offset center, + double radius, + Paint paint, +) { + if (radius <= 0) { + return; + } + final circumference = 2 * math.pi * radius; + // A whole number of dashes and gaps, so the last gap closes the circle. + final dashes = math.max(1, (circumference / (dashLength * 2)).round()); + final step = 2 * math.pi / dashes; + final rect = Rect.fromCircle(center: center, radius: radius); + for (var i = 0; i < dashes; i++) { + canvas.drawArc(rect, i * step, step / 2, false, paint); + } +} + +void _drawDashedLine(Canvas canvas, Offset from, Offset to, Paint paint) { + final length = (to - from).distance; + if (length == 0) { + return; + } + final direction = (to - from) / length; + for (var start = 0.0; start < length; start += dashLength * 2) { + final end = math.min(start + dashLength, length); + canvas.drawLine(from + direction * start, from + direction * end, paint); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/preview/flame_mapping.dart b/packages/flame_studio/lib/component_editor/widgets/preview/flame_mapping.dart new file mode 100644 index 00000000000..b95df15e07a --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/preview/flame_mapping.dart @@ -0,0 +1,192 @@ +import 'package:flame/collisions.dart' as flame; +import 'package:flame/components.dart' as flame; +import 'package:flame_studio/component_editor/widgets/preview/preview_hitboxes.dart'; +import 'package:flame_studio/component_editor/widgets/preview/preview_position_component.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/painting.dart'; + +/// Builds the Flame component that previews the root [component], with its +/// children. +/// +/// The root is anchored at its center, at the origin of the world, so it +/// is centered on screen; its stored position is ignored because the root +/// is placed by whoever uses it, and it is not rotated for the same reason. +/// Children use their own anchor (Flame's default top left one unless +/// edited) and angle, and are positioned relative to their parent, like in +/// the generated code. +flame.PositionComponent buildFlameComponent(Component component) { + return _placeRoot(_build(component)); +} + +flame.PositionComponent _placeRoot(flame.PositionComponent root) { + root + ..anchor = flame.Anchor.center + ..angle = 0 + ..position.setZero(); + return root; +} + +flame.PositionComponent _build(Component component) { + final target = switch (component) { + RectangleComponent() => flame.RectangleComponent(), + CircleComponent() => flame.CircleComponent(), + PolygonComponent(:final vertices) => flame.PolygonComponent( + _vectors(vertices), + ), + // Outlined, since a plain PositionComponent would be invisible. + PositionComponent() => PreviewPositionComponent(), + // Hitboxes draw nothing either, so they are outlined too. + RectangleHitboxComponent() => PreviewRectangleHitbox(), + CircleHitboxComponent() => PreviewCircleHitbox(), + PolygonHitboxComponent(:final vertices) => PreviewPolygonHitbox( + _vectors(vertices), + ), + }; + applyProperties(target, component); + // Children added before mounting are stored right away, in order. + component.children.map(_build).forEach(target.add); + return target; +} + +/// A new list of the [vertices], since Flame changes the list it is given. +List _vectors(ComponentVertices vertices) => [ + for (final vertex in vertices.vertices) flame.Vector2(vertex.x, vertex.y), +]; + +/// Whether [a] and [b] have the same types arranged in the same tree, so +/// that the Flame components built for [a] can be updated to show [b]. +/// +/// Polygons with different vertices don't have the same shape: a Flame +/// polygon can't change its number of vertices, nor be given new ones from +/// outside. +bool haveSameShape(Component a, Component b) { + if (a.type != b.type || a.children.length != b.children.length) { + return false; + } + if ((a, b) case (final VerticesComponent a, final VerticesComponent b) + when a.vertices != b.vertices) { + return false; + } + for (var i = 0; i < a.children.length; i++) { + if (!haveSameShape(a.children[i], b.children[i])) { + return false; + } + } + return true; +} + +/// Applies the properties of the root [component] and of all of its +/// children to [target] and its children, which must have been built by +/// [buildFlameComponent] for a component of the same shape (see +/// [haveSameShape]). +/// +/// Like in [buildFlameComponent], the root stays centered. +void applyTree(flame.PositionComponent target, Component component) { + _placeRoot(_applyNode(target, component)); +} + +flame.PositionComponent _applyNode( + flame.PositionComponent target, + Component component, +) { + applyProperties(target, component); + final children = target.children.whereType(); + for (final (index, child) in children.indexed) { + _applyNode(child, component.children[index]); + } + return target; +} + +/// The Flame component at [path] in the tree built by +/// [buildFlameComponent] from [root] (see `ComponentTree` for paths). +flame.PositionComponent flameNodeAt( + flame.PositionComponent root, + List path, +) { + var node = root; + for (final index in path) { + node = node.children.whereType().elementAt(index); + } + return node; +} + +/// Applies every property [component] has to [target]. +/// +/// New shared properties should be wired here so that every component type +/// that has them is previewed correctly. +T applyProperties( + T target, + Component component, +) { + if (component case final PositionedComponent positioned) { + applyPosition(target, positioned.position); + } + if (component case final AnchoredComponent anchored) { + applyAnchor(target, anchored.anchor); + } + if (component case final RotatedComponent rotated) { + applyAngle(target, rotated.angle); + } + if (component case final SizedComponent sized) { + applySize(target, sized.size); + } + if (component case final RadiusComponent round + when target is flame.CircleComponent) { + applyRadius(target as flame.CircleComponent, round.radius); + } + if (component case final PaintedComponent painted + when target is flame.HasPaint) { + applyPaint(target as flame.HasPaint, painted.paint); + } + if (component case final HitboxComponent hitbox + when target is flame.ShapeHitbox) { + applyCollision(target as flame.ShapeHitbox, hitbox.collision); + } + return target; +} + +/// Applies [position] to [target]. +void applyPosition(flame.PositionComponent target, ComponentPosition position) { + target.position.setValues(position.x, position.y); +} + +/// Applies [anchor] to [target]. +void applyAnchor(flame.PositionComponent target, ComponentAnchor anchor) { + target.anchor = flame.Anchor(anchor.x, anchor.y); +} + +/// Applies [angle] to [target]. +void applyAngle(flame.PositionComponent target, ComponentAngle angle) { + target.angle = angle.radians; +} + +/// Applies [size] to [target]. +void applySize(flame.PositionComponent target, ComponentSize size) { + target.size.setValues(size.width, size.height); +} + +/// Applies [radius] to [target], which also sets its size. +void applyRadius(flame.CircleComponent target, ComponentRadius radius) { + target.radius = radius.radius; +} + +/// Applies [paint] to [target]. +void applyPaint(flame.HasPaint target, ComponentPaint paint) { + target.paint + ..color = Color(paint.color) + ..style = switch (paint.style) { + PaintStyle.fill => PaintingStyle.fill, + PaintStyle.stroke => PaintingStyle.stroke, + }; +} + +/// Applies [collision] to [target]. +void applyCollision(flame.ShapeHitbox target, ComponentCollision collision) { + target + ..collisionType = switch (collision.type) { + HitboxCollisionType.active => flame.CollisionType.active, + HitboxCollisionType.passive => flame.CollisionType.passive, + HitboxCollisionType.inactive => flame.CollisionType.inactive, + } + ..isSolid = collision.isSolid; +} diff --git a/packages/flame_studio/lib/component_editor/widgets/preview/preview.dart b/packages/flame_studio/lib/component_editor/widgets/preview/preview.dart new file mode 100644 index 00000000000..5ba9f683b23 --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/preview/preview.dart @@ -0,0 +1,6 @@ +export 'component_preview_game.dart'; +export 'dashed_outline.dart'; +export 'flame_mapping.dart'; +export 'preview_hitboxes.dart'; +export 'preview_position_component.dart'; +export 'selection_highlight.dart'; diff --git a/packages/flame_studio/lib/component_editor/widgets/preview/preview_hitboxes.dart b/packages/flame_studio/lib/component_editor/widgets/preview/preview_hitboxes.dart new file mode 100644 index 00000000000..d969236f8e0 --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/preview/preview_hitboxes.dart @@ -0,0 +1,82 @@ +import 'package:flame/collisions.dart' as flame; +import 'package:flame/components.dart' as flame; +import 'package:flame_studio/component_editor/widgets/preview/dashed_outline.dart'; +import 'package:flutter/painting.dart'; + +/// {@template preview_hitbox} +/// A Flame hitbox in the preview. +/// +/// Hitboxes draw nothing themselves, so the preview outlines them with an +/// orange dashed line, hidden with [isVisible] when the user hides the +/// hitboxes. The outline only exists in the preview: the generated code +/// uses Flame's hitboxes. +/// +/// The preview game has no collision detection, so these hitboxes never +/// collide. +/// {@endtemplate} +mixin PreviewHitbox on flame.PositionComponent, flame.HasVisibility { + /// The color of the outline. + static const color = Color(0xFFFF9800); + + /// The paint of the outline. + static final paint = Paint() + ..color = color + ..style = PaintingStyle.stroke + ..strokeWidth = 1; +} + +/// {@macro preview_hitbox} +class PreviewRectangleHitbox() + extends flame.RectangleHitbox + with flame.HasVisibility, PreviewHitbox { + /// {@macro preview_hitbox} + /// + /// It is given a size, otherwise Flame would make it fill its parent. + this : super(size: flame.Vector2.zero()); + + @override + void render(Canvas canvas) { + final rect = size.toRect(); + drawDashedPolygon(canvas, [ + rect.topLeft, + rect.topRight, + rect.bottomRight, + rect.bottomLeft, + ], PreviewHitbox.paint); + } +} + +/// {@macro preview_hitbox} +class PreviewCircleHitbox() + extends flame.CircleHitbox + with flame.HasVisibility, PreviewHitbox { + /// {@macro preview_hitbox} + /// + /// It is given a radius, otherwise Flame would make it fill its parent. + this : super(radius: 0); + + @override + void render(Canvas canvas) { + drawDashedCircle( + canvas, + (size / 2).toOffset(), + radius, + PreviewHitbox.paint, + ); + } +} + +/// {@macro preview_hitbox} +class PreviewPolygonHitbox(super.vertices) + extends flame.PolygonHitbox + with flame.HasVisibility, PreviewHitbox { + /// {@macro preview_hitbox} + this; + + @override + void render(Canvas canvas) { + drawDashedPolygon(canvas, [ + for (final vertex in vertices) vertex.toOffset(), + ], PreviewHitbox.paint); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/preview/preview_position_component.dart b/packages/flame_studio/lib/component_editor/widgets/preview/preview_position_component.dart new file mode 100644 index 00000000000..e5c820e85db --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/preview/preview_position_component.dart @@ -0,0 +1,35 @@ +import 'package:flame/components.dart' as flame; +import 'package:flame_studio/component_editor/widgets/preview/dashed_outline.dart'; +import 'package:flutter/painting.dart'; + +/// {@template preview_position_component} +/// The Flame component that previews a position component. +/// +/// A `PositionComponent` draws nothing itself, so the preview outlines it +/// with a faint dashed line, letting users see it while it isn't selected. +/// The outline only exists in the preview: the generated code uses a plain +/// `PositionComponent`. +/// {@endtemplate} +class PreviewPositionComponent() extends flame.PositionComponent { + /// {@macro preview_position_component} + this; + + /// The color of the outline. + static const color = Color(0x66FFFFFF); + + static final _paint = Paint() + ..color = color + ..style = PaintingStyle.stroke + ..strokeWidth = 1; + + @override + void render(Canvas canvas) { + final rect = size.toRect(); + drawDashedPolygon(canvas, [ + rect.topLeft, + rect.topRight, + rect.bottomRight, + rect.bottomLeft, + ], _paint); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/preview/selection_highlight.dart b/packages/flame_studio/lib/component_editor/widgets/preview/selection_highlight.dart new file mode 100644 index 00000000000..4762bdc7fed --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/preview/selection_highlight.dart @@ -0,0 +1,63 @@ +import 'package:flame/components.dart' as flame; +import 'package:flutter/painting.dart'; + +/// {@template selection_highlight} +/// Draws a thick magenta border around [target], the Flame component of +/// the node selected in the editor. +/// +/// It is added to the world, above everything else, instead of to +/// [target]: that keeps it on top of overlapping siblings, and the +/// children of the previewed components match the component tree. +/// {@endtemplate} +class SelectionHighlight() extends flame.Component { + /// {@macro selection_highlight} + this : super(priority: 1 << 30); + + /// The color of the border. + static const color = Color(0xFFFF00FF); + + /// The width of the border on screen, whatever the [zoom]. + static const strokeWidth = 4.0; + + final _paint = Paint() + ..color = color + ..style = PaintingStyle.stroke + ..strokeWidth = strokeWidth; + + /// The component to highlight, if any. + flame.PositionComponent? target; + + /// The zoom of the camera, which scales the border too: it is drawn + /// thinner when zoomed in, so it keeps the same width on screen. + double get zoom => _zoom; + double _zoom = 1; + set zoom(double value) { + _zoom = value; + _paint.strokeWidth = worldStrokeWidth; + } + + /// The width of the border in world coordinates. + double get worldStrokeWidth => strokeWidth / _zoom; + + @override + void render(Canvas canvas) { + final target = this.target; + if (target == null || !target.isMounted) { + return; + } + // Rotated with the component (and its ancestors), around its top left + // corner. + final topLeft = target.absoluteTopLeftPosition; + final size = target.absoluteScaledSize; + canvas + ..save() + ..translate(topLeft.x, topLeft.y) + ..rotate(target.absoluteAngle) + // Drawn outside of the component, so it doesn't hide its own edges. + ..drawRect( + Rect.fromLTWH(0, 0, size.x, size.y).inflate(worldStrokeWidth / 2), + _paint, + ) + ..restore(); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/properties_panel.dart b/packages/flame_studio/lib/component_editor/widgets/properties_panel.dart new file mode 100644 index 00000000000..6f1c59bd9dc --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/properties_panel.dart @@ -0,0 +1,130 @@ +import 'package:flame_studio/component_editor/bloc/component_editor_bloc.dart'; +import 'package:flame_studio/component_editor/widgets/preview/preview_hitboxes.dart'; +import 'package:flame_studio/component_editor/widgets/property_editors/property_editors.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template properties_panel} +/// Lists an editor for every property of the node selected in the +/// component tree. +/// +/// Editors are picked from the capabilities the node implements, so a new +/// component type gets them without changes here. The name, the position, +/// the anchor and the angle are only edited on children: the root name is +/// its file and class name, and the root is placed by whoever uses it. +/// {@endtemplate} +class const PropertiesPanel({super.key}) extends StatelessWidget { + /// {@macro properties_panel} + this; + + @override + Widget build(BuildContext context) { + final (component, selectedPath, palette) = context + .select, Palette)>( + (bloc) => ( + bloc.state.selectedNode, + bloc.state.selectedPath, + bloc.state.palette, + ), + ); + final bloc = context.read(); + final isRoot = selectedPath.isEmpty; + + return ListView( + // Fresh fields for every node, so edits never leak between nodes. + key: ValueKey(selectedPath.join('.')), + children: [ + if (!isRoot) + PropertySection( + title: 'Name', + children: [ + NameField( + value: component.name, + validator: (name) => _nameError( + bloc.state.component.validateChildName( + selectedPath, + name, + takenClassNames: bloc.state.takenClassNames.keys.toSet(), + ), + ), + onChanged: (name) => bloc.add(ComponentEditorNameChanged(name)), + ), + ], + ), + if (component case final PositionedComponent positioned when !isRoot) + PositionEditor( + value: positioned.position, + onChanged: (position) => + bloc.add(ComponentEditorPositionChanged(position)), + ), + if (component case final AnchoredComponent anchored when !isRoot) + AnchorEditor( + value: anchored.anchor, + onChanged: (anchor) => + bloc.add(ComponentEditorAnchorChanged(anchor)), + ), + if (component case final RotatedComponent rotated when !isRoot) + AngleEditor( + value: rotated.angle, + onChanged: (angle) => bloc.add(ComponentEditorAngleChanged(angle)), + ), + if (component case final SizedComponent sized) + SizeEditor( + value: sized.size, + onChanged: (size) => bloc.add(ComponentEditorSizeChanged(size)), + ), + if (component case final RadiusComponent round) + RadiusEditor( + value: round.radius, + onChanged: (radius) => + bloc.add(ComponentEditorRadiusChanged(radius)), + ), + if (component case final VerticesComponent polygon) + VerticesEditor( + value: polygon.vertices, + paint: switch (component) { + PaintedComponent(:final paint) => paint.copyWith( + color: paint.resolvedColor(palette), + ), + // Drawn like in the preview. + HitboxComponent() => ComponentPaint( + color: PreviewHitbox.color.toARGB32(), + style: PaintStyle.stroke, + ), + _ => const ComponentPaint(), + }, + onChanged: (vertices) => + bloc.add(ComponentEditorVerticesChanged(vertices)), + ), + if (component case final PaintedComponent painted) + PaintEditor( + value: painted.paint, + palette: palette, + onChanged: (paint) => bloc.add(ComponentEditorPaintChanged(paint)), + ), + if (component case final HitboxComponent hitbox) + CollisionEditor( + value: hitbox.collision, + onChanged: (collision) => + bloc.add(ComponentEditorCollisionChanged(collision)), + ), + ], + ); + } + + static String? _nameError(ChildNameError? error) { + return switch (error) { + null => null, + ChildNameError.invalid => + 'Use a valid Dart identifier: letters, digits and underscores, ' + 'not starting with a digit, and not a keyword', + ChildNameError.reserved => + 'Already a member of the parent component in Flame', + ChildNameError.duplicate => 'Another component already uses this name', + ChildNameError.conflict => + 'Generates the same class as a part of another component of the ' + 'project', + }; + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/property_editors/anchor_editor.dart b/packages/flame_studio/lib/component_editor/widgets/property_editors/anchor_editor.dart new file mode 100644 index 00000000000..aefccad8154 --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/property_editors/anchor_editor.dart @@ -0,0 +1,92 @@ +import 'package:flame_studio/component_editor/widgets/property_editors/number_field.dart'; +import 'package:flame_studio/component_editor/widgets/property_editors/property_section.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; + +/// {@template anchor_editor} +/// Edits a [ComponentAnchor]. Used by every [AnchoredComponent] inside +/// another component. +/// +/// A 3x3 grid picks one of Flame's named anchors, and the X and Y fields +/// set a custom one. +/// {@endtemplate} +class const AnchorEditor({ + /// The current anchor. + required final ComponentAnchor value, + + /// Called with the edited anchor. + required final ValueChanged onChanged, + super.key, +}) extends StatelessWidget { + /// {@macro anchor_editor} + this; + + @override + Widget build(BuildContext context) { + final presets = ComponentAnchor.presets.entries.toList(); + return PropertySection( + title: 'Anchor', + children: [ + Row( + spacing: 12, + children: [ + Column( + children: [ + for (var row = 0; row < 3; row++) + Row( + children: [ + for (final MapEntry(key: name, value: preset) + in presets.skip(row * 3).take(3)) + _PresetButton( + name: name, + isSelected: preset == value, + onPressed: () => onChanged(preset), + ), + ], + ), + ], + ), + Expanded( + child: Column( + spacing: 12, + children: [ + NumberField( + label: 'X', + value: value.x, + min: null, + onChanged: (x) => onChanged(value.copyWith(x: x)), + ), + NumberField( + label: 'Y', + value: value.y, + min: null, + onChanged: (y) => onChanged(value.copyWith(y: y)), + ), + ], + ), + ), + ], + ), + ], + ); + } +} + +class const _PresetButton({ + required final String name, + required final bool isSelected, + required final VoidCallback onPressed, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + return IconButton( + tooltip: name, + isSelected: isSelected, + visualDensity: VisualDensity.compact, + iconSize: 16, + icon: const Icon(Icons.circle_outlined), + selectedIcon: const Icon(Icons.circle), + onPressed: onPressed, + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/property_editors/angle_editor.dart b/packages/flame_studio/lib/component_editor/widgets/property_editors/angle_editor.dart new file mode 100644 index 00000000000..7e72883bdc9 --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/property_editors/angle_editor.dart @@ -0,0 +1,38 @@ +import 'package:flame_studio/component_editor/widgets/property_editors/number_field.dart'; +import 'package:flame_studio/component_editor/widgets/property_editors/property_section.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; + +/// {@template angle_editor} +/// Edits a [ComponentAngle], in degrees. Used by every [RotatedComponent] +/// inside another component. +/// {@endtemplate} +class const AngleEditor({ + /// The current angle. + required final ComponentAngle value, + + /// Called with the edited angle. + required final ValueChanged onChanged, + super.key, +}) extends StatelessWidget { + /// {@macro angle_editor} + this; + + @override + Widget build(BuildContext context) { + return PropertySection( + title: 'Angle', + children: [ + NumberField( + label: 'Degrees', + // Rounded, so that converting the typed degrees to radians and + // back gives the same number, and the field keeps the user input. + value: double.parse(value.degrees.toStringAsFixed(6)), + min: null, + onChanged: (degrees) => + onChanged(ComponentAngle.fromDegrees(degrees)), + ), + ], + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/property_editors/collision_editor.dart b/packages/flame_studio/lib/component_editor/widgets/property_editors/collision_editor.dart new file mode 100644 index 00000000000..56ad5cd3250 --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/property_editors/collision_editor.dart @@ -0,0 +1,44 @@ +import 'package:flame_studio/component_editor/widgets/property_editors/enum_field.dart'; +import 'package:flame_studio/component_editor/widgets/property_editors/property_section.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; + +/// {@template collision_editor} +/// Edits a [ComponentCollision]: the collision type and whether the hitbox +/// is solid. +/// {@endtemplate} +class const CollisionEditor({ + /// The collision being edited. + required final ComponentCollision value, + + /// Called with the updated collision. + required final ValueChanged onChanged, + super.key, +}) extends StatelessWidget { + /// {@macro collision_editor} + this; + + @override + Widget build(BuildContext context) { + return PropertySection( + title: 'Collision', + children: [ + EnumField( + label: 'Type', + values: HitboxCollisionType.values, + value: value.type, + labelOf: (type) => type.label, + onChanged: (type) => onChanged(value.copyWith(type: type)), + ), + SwitchListTile( + title: const Text('Solid'), + subtitle: const Text('Also collides with hitboxes inside it'), + contentPadding: EdgeInsets.zero, + dense: true, + value: value.isSolid, + onChanged: (isSolid) => onChanged(value.copyWith(isSolid: isSolid)), + ), + ], + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/property_editors/color_field.dart b/packages/flame_studio/lib/component_editor/widgets/property_editors/color_field.dart new file mode 100644 index 00000000000..9eaae1cc48f --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/property_editors/color_field.dart @@ -0,0 +1,145 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flex_color_picker/flex_color_picker.dart'; +import 'package:flutter/material.dart'; + +/// {@template color_field} +/// Shows a color swatch and its hex code; tapping it opens a color picker. +/// +/// When [onPaletteColorSelected] is given and the [palette] has colors, a +/// button next to it lists them, so a palette color can be picked instead. +/// A [paletteColor] in use is shown by name. +/// +/// Colors are 32 bit ARGB values. +/// {@endtemplate} +class const ColorField({ + /// The field label. + required final String label, + + /// The current color, as a 32 bit ARGB value. + /// + /// When [paletteColor] is in the [palette], its value is shown instead. + required final int value, + + /// Called with the color the user picked by hand. + required final ValueChanged onChanged, + + /// The colors that can be picked by name. + final Palette palette = const Palette(), + + /// The name of the [palette] color in use, if any. + final String? paletteColor, + + /// Called with the name of the [palette] color the user picked. + final ValueChanged? onPaletteColorSelected, + super.key, +}) extends StatelessWidget { + /// {@macro color_field} + this; + + int get _color => palette.colorOf(paletteColor) ?? value; + + Future _pick(BuildContext context) async { + final color = await showColorPickerDialog( + context, + Color(_color), + title: Text(label), + pickersEnabled: const { + ColorPickerType.primary: true, + ColorPickerType.accent: false, + ColorPickerType.wheel: true, + }, + enableOpacity: true, + showColorCode: true, + colorCodeHasColor: true, + constraints: const BoxConstraints(minWidth: 320, maxWidth: 320), + ); + // A cancelled picker returns the color it opened with, so the same + // color is no change (and keeps the palette color). + final picked = color.toARGB32(); + if (picked != _color) { + onChanged(picked); + } + } + + @override + Widget build(BuildContext context) { + final color = _color; + final hex = '#${_hex(color)}'; + final name = palette.contains(paletteColor) ? paletteColor : null; + final onPaletteColorSelected = this.onPaletteColorSelected; + return Row( + children: [ + Expanded( + child: InkWell( + onTap: () => _pick(context), + borderRadius: BorderRadius.circular(4), + child: InputDecorator( + decoration: InputDecoration(labelText: label, isDense: true), + child: Row( + spacing: 8, + children: [ + ColorSwatchBox(color: color), + Flexible( + child: Text( + name == null ? hex : '$name · $hex', + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ), + ), + ), + if (onPaletteColorSelected != null && palette.colors.isNotEmpty) + MenuAnchor( + menuChildren: [ + for (final PaletteColor(name: colorName, :color) + in palette.colors) + MenuItemButton( + leadingIcon: ColorSwatchBox(color: color), + trailingIcon: colorName == name + ? const Icon(Icons.check, size: 18) + : null, + onPressed: () => onPaletteColorSelected(colorName), + child: Text(colorName), + ), + ], + builder: (context, controller, _) => IconButton( + tooltip: 'Pick from palette', + icon: const Icon(Icons.palette_outlined), + onPressed: () => + controller.isOpen ? controller.close() : controller.open(), + ), + ), + ], + ); + } + + static String _hex(int color) => + color.toRadixString(16).padLeft(8, '0').toUpperCase(); +} + +/// {@template color_swatch_box} +/// A small rounded square filled with [color]. +/// {@endtemplate} +class const ColorSwatchBox({ + /// The color, as a 32 bit ARGB value. + required final int color, + super.key, +}) extends StatelessWidget { + /// {@macro color_swatch_box} + this; + + @override + Widget build(BuildContext context) { + return Container( + width: 20, + height: 20, + decoration: BoxDecoration( + color: Color(color), + border: Border.all(color: Theme.of(context).dividerColor), + borderRadius: BorderRadius.circular(4), + ), + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/property_editors/enum_field.dart b/packages/flame_studio/lib/component_editor/widgets/property_editors/enum_field.dart new file mode 100644 index 00000000000..77cea3055ef --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/property_editors/enum_field.dart @@ -0,0 +1,45 @@ +import 'package:flutter/material.dart'; + +/// {@template enum_field} +/// Picks one of [values] with a segmented button. +/// {@endtemplate} +class const EnumField({ + /// The field label. + required final String label, + + /// The values to choose from. + required final List values, + + /// The selected value. + required final T value, + + /// Returns the text shown for a value. + required final String Function(T value) labelOf, + + /// Called with the value the user picked. + required final ValueChanged onChanged, + super.key, +}) extends StatelessWidget { + /// {@macro enum_field} + this; + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + spacing: 4, + children: [ + Text(label, style: Theme.of(context).textTheme.bodySmall), + SegmentedButton( + showSelectedIcon: false, + segments: [ + for (final value in values) + ButtonSegment(value: value, label: Text(labelOf(value))), + ], + selected: {value}, + onSelectionChanged: (selection) => onChanged(selection.single), + ), + ], + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/property_editors/name_field.dart b/packages/flame_studio/lib/component_editor/widgets/property_editors/name_field.dart new file mode 100644 index 00000000000..f24ab14c57f --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/property_editors/name_field.dart @@ -0,0 +1,106 @@ +import 'package:flutter/material.dart'; + +/// Returns why a name can't be used, or `null` if it can. +typedef NameValidator = String? Function(String name); + +/// {@template name_field} +/// A text field that edits a name. +/// +/// Every edit accepted by [validator] is committed with [onChanged] as the +/// user types. Rejected input shows the [validator] message, is not +/// committed, and is reverted to the last valid name when the field is +/// submitted or loses focus. +/// {@endtemplate} +class const NameField({ + /// The current name. + required final String value, + + /// Checks the typed name. + required final NameValidator validator, + + /// Called with the new name whenever the user types a valid one. + required final ValueChanged onChanged, + + /// The field label. + final String label = 'Name', + super.key, +}) extends StatefulWidget { + /// {@macro name_field} + this; + + @override + State createState() => _NameFieldState(); +} + +class _NameFieldState() extends State { + late final _controller = TextEditingController(text: widget.value); + final _focusNode = FocusNode(); + late String _committed; + String? _error; + + @override + void initState() { + super.initState(); + _committed = widget.value; + _focusNode.addListener(_onFocusChanged); + } + + @override + void didUpdateWidget(NameField oldWidget) { + super.didUpdateWidget(oldWidget); + // Names this field committed itself come back here; rewriting the text + // for them would move the cursor. + if (widget.value != oldWidget.value && widget.value != _committed) { + _committed = widget.value; + _controller.text = widget.value; + _error = null; + } + } + + @override + void dispose() { + _focusNode.dispose(); + _controller.dispose(); + super.dispose(); + } + + void _onFocusChanged() { + if (!_focusNode.hasFocus) { + _revertInvalid(); + } + } + + void _revertInvalid() { + if (_error == null) { + return; + } + _controller.text = _committed; + setState(() => _error = null); + } + + void _onTextChanged(String name) { + final error = name == _committed ? null : widget.validator(name); + setState(() => _error = error); + if (error != null || name == _committed) { + return; + } + _committed = name; + widget.onChanged(name); + } + + @override + Widget build(BuildContext context) { + return TextField( + controller: _controller, + focusNode: _focusNode, + decoration: InputDecoration( + labelText: widget.label, + errorText: _error, + errorMaxLines: 2, + isDense: true, + ), + onChanged: _onTextChanged, + onSubmitted: (_) => _revertInvalid(), + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/property_editors/number_field.dart b/packages/flame_studio/lib/component_editor/widgets/property_editors/number_field.dart new file mode 100644 index 00000000000..7aa7e5022cb --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/property_editors/number_field.dart @@ -0,0 +1,113 @@ +import 'package:flutter/material.dart'; + +/// {@template number_field} +/// A text field that edits a number, by default a non-negative one. +/// +/// Every valid edit is committed with [onChanged] as the user types. +/// Invalid input, including numbers below [min], is not committed, and is +/// reverted to the last valid value when the field is submitted or loses +/// focus. +/// {@endtemplate} +class const NumberField({ + /// The field label. + required final String label, + + /// The current value. + required final double value, + + /// Called with the new value whenever the user types a valid number. + required final ValueChanged onChanged, + + /// The smallest accepted value, or `null` to accept any number. + final double? min = 0, + super.key, +}) extends StatefulWidget { + /// {@macro number_field} + this; + + @override + State createState() => _NumberFieldState(); +} + +class _NumberFieldState() extends State { + late final _controller = TextEditingController(text: _format(widget.value)); + final _focusNode = FocusNode(); + late double _committed; + + @override + void initState() { + super.initState(); + _committed = widget.value; + _focusNode.addListener(_onFocusChanged); + } + + @override + void didUpdateWidget(NumberField oldWidget) { + super.didUpdateWidget(oldWidget); + // Values this field committed itself come back here; rewriting the + // text for them would move the cursor and drop input like "1.50". + if (widget.value != oldWidget.value && widget.value != _committed) { + _committed = widget.value; + _controller.text = _format(widget.value); + } + } + + @override + void dispose() { + _focusNode.dispose(); + _controller.dispose(); + super.dispose(); + } + + void _onFocusChanged() { + if (!_focusNode.hasFocus) { + _revertInvalid(); + } + } + + /// Parses the text, or returns `null` if it is not an accepted number. + double? _parse() { + final value = double.tryParse(_controller.text.trim()); + final min = widget.min; + if (value == null || (min != null && value < min)) { + return null; + } + return value; + } + + void _revertInvalid() { + if (_parse() == null) { + _controller.text = _format(_committed); + } + } + + void _onTextChanged(String _) { + final value = _parse(); + if (value == null || value == _committed) { + return; + } + _committed = value; + widget.onChanged(value); + } + + static String _format(double value) { + return value == value.truncateToDouble() + ? value.toInt().toString() + : value.toString(); + } + + @override + Widget build(BuildContext context) { + return TextField( + controller: _controller, + focusNode: _focusNode, + keyboardType: TextInputType.numberWithOptions( + decimal: true, + signed: widget.min == null || widget.min! < 0, + ), + decoration: InputDecoration(labelText: widget.label, isDense: true), + onChanged: _onTextChanged, + onSubmitted: (_) => _revertInvalid(), + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/property_editors/paint_editor.dart b/packages/flame_studio/lib/component_editor/widgets/property_editors/paint_editor.dart new file mode 100644 index 00000000000..68c6ca6aa04 --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/property_editors/paint_editor.dart @@ -0,0 +1,54 @@ +import 'package:flame_studio/component_editor/widgets/property_editors/color_field.dart'; +import 'package:flame_studio/component_editor/widgets/property_editors/enum_field.dart'; +import 'package:flame_studio/component_editor/widgets/property_editors/property_section.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; + +/// {@template paint_editor} +/// Edits a [ComponentPaint]. Used by every [PaintedComponent]. +/// +/// Its color is picked by hand or from the [palette]. +/// {@endtemplate} +class const PaintEditor({ + /// The current paint. + required final ComponentPaint value, + + /// Called with the edited paint. + required final ValueChanged onChanged, + + /// The palette of the project. + final Palette palette = const Palette(), + super.key, +}) extends StatelessWidget { + /// {@macro paint_editor} + this; + + @override + Widget build(BuildContext context) { + return PropertySection( + title: 'Paint', + children: [ + ColorField( + label: 'Color', + value: value.color, + palette: palette, + paletteColor: value.paletteColor, + onChanged: (color) => onChanged(value.withColor(color)), + onPaletteColorSelected: (name) => onChanged( + value.withPaletteColor(name, palette.colorOf(name) ?? value.color), + ), + ), + EnumField( + label: 'Style', + values: PaintStyle.values, + value: value.style, + labelOf: (style) => switch (style) { + PaintStyle.fill => 'Fill', + PaintStyle.stroke => 'Stroke', + }, + onChanged: (style) => onChanged(value.copyWith(style: style)), + ), + ], + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/property_editors/position_editor.dart b/packages/flame_studio/lib/component_editor/widgets/property_editors/position_editor.dart new file mode 100644 index 00000000000..7a361d45012 --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/property_editors/position_editor.dart @@ -0,0 +1,50 @@ +import 'package:flame_studio/component_editor/widgets/property_editors/number_field.dart'; +import 'package:flame_studio/component_editor/widgets/property_editors/property_section.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; + +/// {@template position_editor} +/// Edits a [ComponentPosition]. Used by every [PositionedComponent] inside +/// another component. +/// {@endtemplate} +class const PositionEditor({ + /// The current position. + required final ComponentPosition value, + + /// Called with the edited position. + required final ValueChanged onChanged, + super.key, +}) extends StatelessWidget { + /// {@macro position_editor} + this; + + @override + Widget build(BuildContext context) { + return PropertySection( + title: 'Position', + children: [ + Row( + spacing: 12, + children: [ + Expanded( + child: NumberField( + label: 'X', + value: value.x, + min: null, + onChanged: (x) => onChanged(value.copyWith(x: x)), + ), + ), + Expanded( + child: NumberField( + label: 'Y', + value: value.y, + min: null, + onChanged: (y) => onChanged(value.copyWith(y: y)), + ), + ), + ], + ), + ], + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/property_editors/property_editors.dart b/packages/flame_studio/lib/component_editor/widgets/property_editors/property_editors.dart new file mode 100644 index 00000000000..751a4b7f4cd --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/property_editors/property_editors.dart @@ -0,0 +1,13 @@ +export 'anchor_editor.dart'; +export 'angle_editor.dart'; +export 'collision_editor.dart'; +export 'color_field.dart'; +export 'enum_field.dart'; +export 'name_field.dart'; +export 'number_field.dart'; +export 'paint_editor.dart'; +export 'position_editor.dart'; +export 'property_section.dart'; +export 'radius_editor.dart'; +export 'size_editor.dart'; +export 'vertices_editor.dart'; diff --git a/packages/flame_studio/lib/component_editor/widgets/property_editors/property_section.dart b/packages/flame_studio/lib/component_editor/widgets/property_editors/property_section.dart new file mode 100644 index 00000000000..753d6809cd3 --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/property_editors/property_section.dart @@ -0,0 +1,31 @@ +import 'package:flutter/material.dart'; + +/// {@template property_section} +/// A titled group of property fields in the properties panel. +/// {@endtemplate} +class const PropertySection({ + /// The name of the property. + required final String title, + + /// The fields that edit the property. + required final List children, + super.key, +}) extends StatelessWidget { + /// {@macro property_section} + this; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + spacing: 12, + children: [ + Text(title, style: Theme.of(context).textTheme.titleSmall), + ...children, + ], + ), + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/property_editors/radius_editor.dart b/packages/flame_studio/lib/component_editor/widgets/property_editors/radius_editor.dart new file mode 100644 index 00000000000..fe027f1d35a --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/property_editors/radius_editor.dart @@ -0,0 +1,33 @@ +import 'package:flame_studio/component_editor/widgets/property_editors/number_field.dart'; +import 'package:flame_studio/component_editor/widgets/property_editors/property_section.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; + +/// {@template radius_editor} +/// Edits a [ComponentRadius]. Used by every [RadiusComponent]. +/// {@endtemplate} +class const RadiusEditor({ + /// The current radius. + required final ComponentRadius value, + + /// Called with the edited radius. + required final ValueChanged onChanged, + super.key, +}) extends StatelessWidget { + /// {@macro radius_editor} + this; + + @override + Widget build(BuildContext context) { + return PropertySection( + title: 'Radius', + children: [ + NumberField( + label: 'Radius', + value: value.radius, + onChanged: (radius) => onChanged(value.copyWith(radius: radius)), + ), + ], + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/property_editors/size_editor.dart b/packages/flame_studio/lib/component_editor/widgets/property_editors/size_editor.dart new file mode 100644 index 00000000000..28a133b7b4f --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/property_editors/size_editor.dart @@ -0,0 +1,48 @@ +import 'package:flame_studio/component_editor/widgets/property_editors/number_field.dart'; +import 'package:flame_studio/component_editor/widgets/property_editors/property_section.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; + +/// {@template size_editor} +/// Edits a [ComponentSize]. Used by every [SizedComponent]. +/// {@endtemplate} +class const SizeEditor({ + /// The current size. + required final ComponentSize value, + + /// Called with the edited size. + required final ValueChanged onChanged, + super.key, +}) extends StatelessWidget { + /// {@macro size_editor} + this; + + @override + Widget build(BuildContext context) { + return PropertySection( + title: 'Size', + children: [ + Row( + spacing: 12, + children: [ + Expanded( + child: NumberField( + label: 'Width', + value: value.width, + onChanged: (width) => onChanged(value.copyWith(width: width)), + ), + ), + Expanded( + child: NumberField( + label: 'Height', + value: value.height, + onChanged: (height) => + onChanged(value.copyWith(height: height)), + ), + ), + ], + ), + ], + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/property_editors/vertices_editor.dart b/packages/flame_studio/lib/component_editor/widgets/property_editors/vertices_editor.dart new file mode 100644 index 00000000000..9d81c47c336 --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/property_editors/vertices_editor.dart @@ -0,0 +1,59 @@ +import 'package:flame_studio/component_editor/widgets/property_editors/property_section.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flame_studio/vertices_editor/vertices_editor.dart'; +import 'package:flutter/material.dart'; + +/// {@template vertices_editor} +/// Edits a [ComponentVertices] in a [VerticesEditorDialog]. Used by every +/// [VerticesComponent]. +/// {@endtemplate} +class const VerticesEditor({ + /// The current vertices. + required final ComponentVertices value, + + /// Called with the edited vertices. + required final ValueChanged onChanged, + + /// The paint the dialog draws the polygon with. + final ComponentPaint paint = const ComponentPaint(), + super.key, +}) extends StatelessWidget { + /// {@macro vertices_editor} + this; + + Future _edit(BuildContext context) async { + final vertices = await VerticesEditorDialog.show( + context, + vertices: value, + paint: paint, + ); + if (vertices != null && vertices != value) { + onChanged(vertices); + } + } + + @override + Widget build(BuildContext context) { + final bounds = value.bounds; + return PropertySection( + title: 'Vertices', + children: [ + Text( + '${value.vertices.length} vertices, ' + '${_number(bounds.width)} × ${_number(bounds.height)}', + ), + OutlinedButton.icon( + icon: const Icon(Icons.edit_outlined), + label: const Text('Edit vertices'), + onPressed: () => _edit(context), + ), + ], + ); + } + + static String _number(double value) { + return value == value.truncateToDouble() + ? value.toInt().toString() + : value.toStringAsFixed(1); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/unsaved_changes_dialog.dart b/packages/flame_studio/lib/component_editor/widgets/unsaved_changes_dialog.dart new file mode 100644 index 00000000000..2f0a06a4c7e --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/unsaved_changes_dialog.dart @@ -0,0 +1,60 @@ +import 'package:flutter/material.dart'; + +/// What the user chose in the [UnsavedChangesDialog]. +enum UnsavedChangesDecision() { + /// Stay in the editor. + cancel, + + /// Leave without saving. + discard, + + /// Save, then leave. + save, +} + +/// {@template unsaved_changes_dialog} +/// Asks the user what to do with unsaved changes when leaving the editor. +/// {@endtemplate} +class const UnsavedChangesDialog({super.key}) extends StatelessWidget { + /// {@macro unsaved_changes_dialog} + this; + + /// Shows the dialog and returns the user's decision. + /// + /// Dismissing the dialog counts as [UnsavedChangesDecision.cancel]. + static Future show(BuildContext context) async { + final decision = await showDialog( + context: context, + builder: (_) => const UnsavedChangesDialog(), + ); + return decision ?? UnsavedChangesDecision.cancel; + } + + @override + Widget build(BuildContext context) { + void pop(UnsavedChangesDecision decision) => + Navigator.of(context).pop(decision); + + return AlertDialog( + title: const Text('Unsaved changes'), + content: const Text( + 'This component has changes that were not saved. ' + 'Do you want to save them before leaving?', + ), + actions: [ + TextButton( + onPressed: () => pop(UnsavedChangesDecision.cancel), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () => pop(UnsavedChangesDecision.discard), + child: const Text('Discard'), + ), + FilledButton( + onPressed: () => pop(UnsavedChangesDecision.save), + child: const Text('Save'), + ), + ], + ); + } +} diff --git a/packages/flame_studio/lib/component_editor/widgets/widgets.dart b/packages/flame_studio/lib/component_editor/widgets/widgets.dart new file mode 100644 index 00000000000..566c2e06ed5 --- /dev/null +++ b/packages/flame_studio/lib/component_editor/widgets/widgets.dart @@ -0,0 +1,8 @@ +export 'component_preview.dart'; +export 'component_tree_panel.dart'; +export 'editor_toolbar.dart'; +export 'editor_top_bar.dart'; +export 'preview/preview.dart'; +export 'properties_panel.dart'; +export 'property_editors/property_editors.dart'; +export 'unsaved_changes_dialog.dart'; diff --git a/packages/flame_studio/lib/flame_studio.dart b/packages/flame_studio/lib/flame_studio.dart deleted file mode 100644 index 76f3cfc5fae..00000000000 --- a/packages/flame_studio/lib/flame_studio.dart +++ /dev/null @@ -1 +0,0 @@ -export 'src/run_flame_studio.dart' show runFlameStudio; diff --git a/packages/flame_studio/lib/home/bloc/home_bloc.dart b/packages/flame_studio/lib/home/bloc/home_bloc.dart new file mode 100644 index 00000000000..cfda5e1832a --- /dev/null +++ b/packages/flame_studio/lib/home/bloc/home_bloc.dart @@ -0,0 +1,83 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flame_studio/repositories/repositories.dart'; + +part 'home_event.dart'; +part 'home_state.dart'; + +/// {@template home_bloc} +/// Loads the recent projects and opens projects from the home screen. +/// {@endtemplate} +class HomeBloc({required final ProjectRepository _projectRepository}) + extends Bloc { + /// {@macro home_bloc} + this : super(const HomeState()) { + on(_onRecentProjectsRequested); + on(_onOpenProjectRequested); + on(_onRecentProjectSelected); + } + + Future _onRecentProjectsRequested( + HomeRecentProjectsRequested event, + Emitter emit, + ) async { + emit(state.copyWith(status: HomeStatus.loading)); + try { + final recentProjects = await _projectRepository.getRecentProjects(); + emit( + state.copyWith( + status: HomeStatus.ready, + recentProjects: recentProjects, + ), + ); + } on Exception { + emit(state.copyWith(status: HomeStatus.failure)); + } + } + + Future _onOpenProjectRequested( + HomeOpenProjectRequested event, + Emitter emit, + ) async { + try { + final project = await _projectRepository.pickProject(); + if (project == null) { + return; + } + await _openProject(project, emit); + } on Exception { + emit(state.copyWith(status: HomeStatus.failure)); + } + } + + Future _onRecentProjectSelected( + HomeRecentProjectSelected event, + Emitter emit, + ) async { + try { + await _openProject(event.project, emit); + } on Exception { + emit(state.copyWith(status: HomeStatus.failure)); + } + } + + Future _openProject(Project project, Emitter emit) async { + try { + await _projectRepository.openProject(project); + emit( + state.copyWith( + status: HomeStatus.opened, + openedProject: project, + recentProjects: await _projectRepository.getRecentProjects(), + ), + ); + } on ProjectNotFoundException { + emit( + state.copyWith( + status: HomeStatus.projectNotFound, + recentProjects: await _projectRepository.getRecentProjects(), + ), + ); + } + } +} diff --git a/packages/flame_studio/lib/home/bloc/home_event.dart b/packages/flame_studio/lib/home/bloc/home_event.dart new file mode 100644 index 00000000000..8180c902c7b --- /dev/null +++ b/packages/flame_studio/lib/home/bloc/home_event.dart @@ -0,0 +1,34 @@ +part of 'home_bloc.dart'; + +/// Base class for [HomeBloc] events. +sealed class const HomeEvent() extends Equatable { + /// Creates a [HomeEvent]. + this; + + @override + List get props => []; +} + +/// The recent projects should be (re)loaded. +final class const HomeRecentProjectsRequested() extends HomeEvent { + /// Creates a [HomeRecentProjectsRequested] event. + this; +} + +/// The user asked to pick a project folder to open. +final class const HomeOpenProjectRequested() extends HomeEvent { + /// Creates a [HomeOpenProjectRequested] event. + this; +} + +/// The user selected one of the recent projects. +final class const HomeRecentProjectSelected( + /// The selected project. + final Project project, +) extends HomeEvent { + /// Creates a [HomeRecentProjectSelected] event. + this; + + @override + List get props => [project]; +} diff --git a/packages/flame_studio/lib/home/bloc/home_state.dart b/packages/flame_studio/lib/home/bloc/home_state.dart new file mode 100644 index 00000000000..14e3ee9fd4a --- /dev/null +++ b/packages/flame_studio/lib/home/bloc/home_state.dart @@ -0,0 +1,55 @@ +part of 'home_bloc.dart'; + +/// The status of the [HomeBloc]. +enum HomeStatus() { + /// Nothing has been loaded yet. + initial, + + /// The recent projects are being loaded. + loading, + + /// The recent projects are loaded. + ready, + + /// A project was opened; see [HomeState.openedProject]. + opened, + + /// The selected project folder no longer exists. + projectNotFound, + + /// Something went wrong. + failure, +} + +/// {@template home_state} +/// The state of the [HomeBloc]. +/// {@endtemplate} +final class const HomeState({ + /// The current status. + final HomeStatus status = HomeStatus.initial, + + /// The recently opened projects, most recent first. + final List recentProjects = const [], + + /// The last opened project. + final Project? openedProject, +}) extends Equatable { + /// {@macro home_state} + this; + + /// Returns a copy of this state with the given fields replaced. + HomeState copyWith({ + HomeStatus? status, + List? recentProjects, + Project? openedProject, + }) { + return HomeState( + status: status ?? this.status, + recentProjects: recentProjects ?? this.recentProjects, + openedProject: openedProject ?? this.openedProject, + ); + } + + @override + List get props => [status, recentProjects, openedProject]; +} diff --git a/packages/flame_studio/lib/home/home.dart b/packages/flame_studio/lib/home/home.dart new file mode 100644 index 00000000000..3468ef3b9b4 --- /dev/null +++ b/packages/flame_studio/lib/home/home.dart @@ -0,0 +1,2 @@ +export 'bloc/home_bloc.dart'; +export 'view/view.dart'; diff --git a/packages/flame_studio/lib/home/view/home_page.dart b/packages/flame_studio/lib/home/view/home_page.dart new file mode 100644 index 00000000000..e61541c9b61 --- /dev/null +++ b/packages/flame_studio/lib/home/view/home_page.dart @@ -0,0 +1,21 @@ +import 'package:flame_studio/home/home.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template home_page} +/// The screen shown when no project is open. +/// {@endtemplate} +class const HomePage({super.key}) extends StatelessWidget { + /// {@macro home_page} + this; + + @override + Widget build(BuildContext context) { + return BlocProvider( + create: (context) => + HomeBloc(projectRepository: context.read()) + ..add(const HomeRecentProjectsRequested()), + child: const HomeView(), + ); + } +} diff --git a/packages/flame_studio/lib/home/view/home_view.dart b/packages/flame_studio/lib/home/view/home_view.dart new file mode 100644 index 00000000000..5835c810dce --- /dev/null +++ b/packages/flame_studio/lib/home/view/home_view.dart @@ -0,0 +1,108 @@ +import 'dart:async'; + +import 'package:flame_studio/home/home.dart'; +import 'package:flame_studio/home/widgets/widgets.dart'; +import 'package:flame_studio/project/project.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template home_view} +/// Shows the open project button and the recent projects. +/// {@endtemplate} +class const HomeView({super.key}) extends StatelessWidget { + /// {@macro home_view} + this; + + @override + Widget build(BuildContext context) { + return BlocListener( + listener: (context, state) { + switch (state.status) { + case HomeStatus.opened: + unawaited(_openProject(context, state.openedProject!)); + case HomeStatus.projectNotFound: + _showMessage(context, 'Project folder not found'); + case HomeStatus.failure: + _showMessage(context, 'Something went wrong'); + case HomeStatus.initial || HomeStatus.loading || HomeStatus.ready: + break; + } + }, + child: Scaffold( + body: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 480), + child: Padding( + padding: const EdgeInsets.all(32), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + 'Flame Studio', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.headlineMedium, + ), + const SizedBox(height: 32), + FilledButton.icon( + onPressed: () => context.read().add( + const HomeOpenProjectRequested(), + ), + icon: const Icon(Icons.folder_open), + label: const Text('Open project'), + ), + const SizedBox(height: 32), + Text( + 'Recent projects', + style: Theme.of(context).textTheme.titleMedium, + ), + const SizedBox(height: 8), + const Flexible(child: _RecentProjects()), + ], + ), + ), + ), + ), + ), + ); + } + + Future _openProject(BuildContext context, Project project) async { + final bloc = context.read(); + await Navigator.of(context).push(ProjectPage.route(project)); + bloc.add(const HomeRecentProjectsRequested()); + } + + void _showMessage(BuildContext context, String message) { + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar(SnackBar(content: Text(message))); + } +} + +class const _RecentProjects() extends StatelessWidget { + @override + Widget build(BuildContext context) { + final recentProjects = context.select>( + (bloc) => bloc.state.recentProjects, + ); + + if (recentProjects.isEmpty) { + return const Text('No recent projects'); + } + + return ListView( + shrinkWrap: true, + children: [ + for (final project in recentProjects) + RecentProjectTile( + project: project, + onTap: () => context.read().add( + HomeRecentProjectSelected(project), + ), + ), + ], + ); + } +} diff --git a/packages/flame_studio/lib/home/view/view.dart b/packages/flame_studio/lib/home/view/view.dart new file mode 100644 index 00000000000..53cf2b9b3e0 --- /dev/null +++ b/packages/flame_studio/lib/home/view/view.dart @@ -0,0 +1,2 @@ +export 'home_page.dart'; +export 'home_view.dart'; diff --git a/packages/flame_studio/lib/home/widgets/recent_project_tile.dart b/packages/flame_studio/lib/home/widgets/recent_project_tile.dart new file mode 100644 index 00000000000..d021081a55e --- /dev/null +++ b/packages/flame_studio/lib/home/widgets/recent_project_tile.dart @@ -0,0 +1,27 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; + +/// {@template recent_project_tile} +/// A list entry for a recently opened [Project]. +/// {@endtemplate} +class const RecentProjectTile({ + /// The project shown by this tile. + required final Project project, + + /// Called when the tile is tapped. + required final VoidCallback onTap, + super.key, +}) extends StatelessWidget { + /// {@macro recent_project_tile} + this; + + @override + Widget build(BuildContext context) { + return ListTile( + leading: const Icon(Icons.folder_outlined), + title: Text(project.name), + subtitle: Text(project.path), + onTap: onTap, + ); + } +} diff --git a/packages/flame_studio/lib/home/widgets/widgets.dart b/packages/flame_studio/lib/home/widgets/widgets.dart new file mode 100644 index 00000000000..0e204afc65f --- /dev/null +++ b/packages/flame_studio/lib/home/widgets/widgets.dart @@ -0,0 +1 @@ +export 'recent_project_tile.dart'; diff --git a/packages/flame_studio/lib/main.dart b/packages/flame_studio/lib/main.dart new file mode 100644 index 00000000000..14ba916c730 --- /dev/null +++ b/packages/flame_studio/lib/main.dart @@ -0,0 +1,28 @@ +import 'package:flame_studio/app/app.dart'; +import 'package:flame_studio/clients/clients.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/widgets.dart'; + +void main() { + WidgetsFlutterBinding.ensureInitialized(); + + final fileSystem = FileSystemClient(); + final storage = KeyValueStorageClient(); + + final projectRepository = ProjectRepository( + storage: storage, + fileSystem: fileSystem, + ); + final componentRepository = ComponentRepository(fileSystem: fileSystem); + final editorPreferencesRepository = EditorPreferencesRepository( + storage: storage, + ); + + runApp( + App( + projectRepository: projectRepository, + componentRepository: componentRepository, + editorPreferencesRepository: editorPreferencesRepository, + ), + ); +} diff --git a/packages/flame_studio/lib/palette/bloc/palette_bloc.dart b/packages/flame_studio/lib/palette/bloc/palette_bloc.dart new file mode 100644 index 00000000000..22945dd51c2 --- /dev/null +++ b/packages/flame_studio/lib/palette/bloc/palette_bloc.dart @@ -0,0 +1,190 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flame_studio/repositories/repositories.dart'; + +part 'palette_event.dart'; +part 'palette_state.dart'; + +/// {@template palette_bloc} +/// Loads, edits and saves the [Palette] of a [Project]. +/// +/// Saving also generates the Dart code of the palette in the output folder +/// of the project settings. +/// +/// Colors used by a component, including the unsaved changes of the +/// [Component] being edited, can't be renamed or removed; their value can +/// still change. +/// {@endtemplate} +class PaletteBloc({ + required final Project _project, + required final Component _editedComponent, + required final ComponentRepository _componentRepository, + required final ProjectRepository _projectRepository, +}) extends Bloc { + /// {@macro palette_bloc} + this : super(const PaletteState()) { + on(_onStarted); + on(_onColorAdded); + on(_onColorRenamed); + on(_onColorValueChanged); + on(_onColorRemoved); + on(_onSaveRequested); + } + + /// The next [PaletteEntry.id]. + int _nextId = 0; + + Future _onStarted( + PaletteStarted event, + Emitter emit, + ) async { + emit(state.copyWith(status: PaletteStatus.loading)); + try { + final palette = await _componentRepository.getPalette(_project.path); + final components = [ + for (final component in await _componentRepository.getComponents( + _project.path, + )) + if (component.name != _editedComponent.name) component, + _editedComponent, + ]..sort((a, b) => a.name.compareTo(b.name)); + final usage = >{}; + for (final component in components) { + for (final color in component.usedPaletteColors) { + (usage[color] ??= []).add(component.name); + } + } + emit( + state.copyWith( + status: PaletteStatus.ready, + savedPalette: palette, + usage: usage, + entries: [ + for (final color in palette.colors) + PaletteEntry(id: _nextId++, color: color, savedName: color.name), + ], + ), + ); + } on Exception { + emit(state.copyWith(status: PaletteStatus.failure)); + } + } + + void _onColorAdded(PaletteColorAdded event, Emitter emit) { + if (!state.isEditable) { + return; + } + final color = PaletteColor( + name: state.palette.uniqueColorName(), + color: ComponentPaint.defaultColor, + ); + emit( + state.copyWith( + status: PaletteStatus.ready, + entries: [ + ...state.entries, + PaletteEntry(id: _nextId++, color: color), + ], + ), + ); + } + + void _onColorRenamed(PaletteColorRenamed event, Emitter emit) { + // Invalid names are kept, so the user can fix them; they prevent saving. + _editEntry(emit, event.id, (entry) { + if (state.usersOf(entry).isNotEmpty) { + return entry; + } + return entry.copyWith(color: entry.color.copyWith(name: event.name)); + }); + } + + void _onColorValueChanged( + PaletteColorValueChanged event, + Emitter emit, + ) { + _editEntry( + emit, + event.id, + (entry) => + entry.copyWith(color: entry.color.copyWith(color: event.color)), + ); + } + + void _onColorRemoved(PaletteColorRemoved event, Emitter emit) { + if (!state.isEditable) { + return; + } + final entries = [ + for (final entry in state.entries) + if (entry.id != event.id || state.usersOf(entry).isNotEmpty) entry, + ]; + if (entries.length == state.entries.length) { + return; + } + emit(state.copyWith(status: PaletteStatus.ready, entries: entries)); + } + + void _editEntry( + Emitter emit, + int id, + PaletteEntry Function(PaletteEntry entry) edit, + ) { + if (!state.isEditable) { + return; + } + final entries = state.entries + .map((entry) => entry.id == id ? edit(entry) : entry) + .toList(); + emit(state.copyWith(status: PaletteStatus.ready, entries: entries)); + } + + Future _onSaveRequested( + PaletteSaveRequested event, + Emitter emit, + ) async { + if (!state.canSave) { + return; + } + final palette = state.palette; + emit(state.copyWith(status: PaletteStatus.saving)); + try { + await _componentRepository.savePalette(_project.path, palette); + } on Exception { + emit(state.copyWith(status: PaletteStatus.failure)); + return; + } + + // Saved colors are now referenced by their current name. + void emitSaved(PaletteStatus status) { + emit( + state.copyWith( + status: status, + savedPalette: palette, + entries: [ + for (final entry in state.entries) + PaletteEntry( + id: entry.id, + color: entry.color, + savedName: entry.color.name, + ), + ], + ), + ); + } + + try { + final settings = await _projectRepository.getSettings(_project); + await _componentRepository.writePaletteCode( + _project.path, + settings.outputPath, + palette, + ); + emitSaved(PaletteStatus.saved); + } on GeneratedFileConflictException { + emitSaved(PaletteStatus.codeConflict); + } on Exception { + emitSaved(PaletteStatus.codeFailure); + } + } +} diff --git a/packages/flame_studio/lib/palette/bloc/palette_event.dart b/packages/flame_studio/lib/palette/bloc/palette_event.dart new file mode 100644 index 00000000000..3a0880c6def --- /dev/null +++ b/packages/flame_studio/lib/palette/bloc/palette_event.dart @@ -0,0 +1,70 @@ +part of 'palette_bloc.dart'; + +/// An event of the [PaletteBloc]. +sealed class const PaletteEvent() extends Equatable { + /// Creates a [PaletteEvent]. + this; + + @override + List get props => []; +} + +/// The palette dialog was opened. +final class const PaletteStarted() extends PaletteEvent { + /// Creates a [PaletteStarted] event. + this; +} + +/// The user added a color. +final class const PaletteColorAdded() extends PaletteEvent { + /// Creates a [PaletteColorAdded] event. + this; +} + +/// The user renamed the color of the entry with [id]. +final class const PaletteColorRenamed( + /// The [PaletteEntry.id] of the color. + final int id, + + /// The new name. + final String name, +) extends PaletteEvent { + /// Creates a [PaletteColorRenamed] event. + this; + + @override + List get props => [id, name]; +} + +/// The user changed the value of the color of the entry with [id]. +final class const PaletteColorValueChanged( + /// The [PaletteEntry.id] of the color. + final int id, + + /// The new value, as a 32 bit ARGB value. + final int color, +) extends PaletteEvent { + /// Creates a [PaletteColorValueChanged] event. + this; + + @override + List get props => [id, color]; +} + +/// The user removed the color of the entry with [id]. +final class const PaletteColorRemoved( + /// The [PaletteEntry.id] of the color. + final int id, +) extends PaletteEvent { + /// Creates a [PaletteColorRemoved] event. + this; + + @override + List get props => [id]; +} + +/// The user asked to save the palette. +final class const PaletteSaveRequested() extends PaletteEvent { + /// Creates a [PaletteSaveRequested] event. + this; +} diff --git a/packages/flame_studio/lib/palette/bloc/palette_state.dart b/packages/flame_studio/lib/palette/bloc/palette_state.dart new file mode 100644 index 00000000000..93cc78cf3db --- /dev/null +++ b/packages/flame_studio/lib/palette/bloc/palette_state.dart @@ -0,0 +1,125 @@ +part of 'palette_bloc.dart'; + +/// The status of the [PaletteBloc]. +enum PaletteStatus() { + /// Nothing has been loaded yet. + initial, + + /// The palette is being loaded. + loading, + + /// The palette can be edited. + ready, + + /// The palette is being saved. + saving, + + /// The palette was saved and its code generated. + saved, + + /// The palette was saved, but its code was not generated because a file + /// that was not generated by the editor is in the way. + codeConflict, + + /// The palette was saved, but generating its code failed. + codeFailure, + + /// Something went wrong while loading or saving. + failure; + + /// Whether the palette was saved, even if its code was not generated. + bool get isSaved => + this == saved || this == codeConflict || this == codeFailure; +} + +/// {@template palette_entry} +/// A color of the palette being edited. +/// {@endtemplate} +final class const PaletteEntry({ + /// Identifies the entry while it is edited, even when renamed. + required final int id, + + /// The color, with the name and value being edited. + required final PaletteColor color, + + /// The name of the color in the saved palette, or `null` for a color + /// added since. Components reference colors by this name. + final String? savedName, +}) extends Equatable { + /// {@macro palette_entry} + this; + + /// Returns a copy of this entry with [color] replaced. + PaletteEntry copyWith({PaletteColor? color}) { + return PaletteEntry( + id: id, + color: color ?? this.color, + savedName: savedName, + ); + } + + @override + List get props => [id, color, savedName]; +} + +/// {@template palette_state} +/// The state of the [PaletteBloc]. +/// {@endtemplate} +final class const PaletteState({ + /// The current status. + final PaletteStatus status = PaletteStatus.initial, + + /// The colors being edited, in order. + final List entries = const [], + + /// The palette as it was last saved. + final Palette savedPalette = const Palette(), + + /// The names of the components that use each palette color. + final Map> usage = const {}, +}) extends Equatable { + /// {@macro palette_state} + this; + + /// The palette being edited. + Palette get palette => + Palette(colors: [for (final entry in entries) entry.color]); + + /// Whether the palette has changes that were not saved yet. + bool get hasChanges => palette != savedPalette; + + /// Whether the palette is loaded and not being saved. + bool get isEditable => + status != PaletteStatus.initial && + status != PaletteStatus.loading && + status != PaletteStatus.saving; + + /// Whether the palette can be saved: every name is valid (see + /// [Palette.validateColorName]) and it is not loading or being saved. + bool get canSave => isEditable && palette.isValid; + + /// The names of the components that use the color of [entry]. A color in + /// use can't be renamed or removed, which would break their references. + List usersOf(PaletteEntry entry) { + final savedName = entry.savedName; + return savedName == null ? const [] : usage[savedName] ?? const []; + } + + /// Returns a copy of this state with the given fields replaced. + PaletteState copyWith({ + PaletteStatus? status, + List? entries, + Palette? savedPalette, + Map>? usage, + }) { + return PaletteState( + status: status ?? this.status, + entries: entries ?? this.entries, + savedPalette: savedPalette ?? this.savedPalette, + usage: usage ?? this.usage, + ); + } + + @override + List get props => [status, entries, savedPalette, usage]; +} diff --git a/packages/flame_studio/lib/palette/palette.dart b/packages/flame_studio/lib/palette/palette.dart new file mode 100644 index 00000000000..75da65d6790 --- /dev/null +++ b/packages/flame_studio/lib/palette/palette.dart @@ -0,0 +1,2 @@ +export 'bloc/palette_bloc.dart'; +export 'view/view.dart'; diff --git a/packages/flame_studio/lib/palette/view/palette_dialog.dart b/packages/flame_studio/lib/palette/view/palette_dialog.dart new file mode 100644 index 00000000000..bcc4f8e4e8f --- /dev/null +++ b/packages/flame_studio/lib/palette/view/palette_dialog.dart @@ -0,0 +1,47 @@ +import 'package:flame_studio/palette/palette.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template palette_dialog} +/// A dialog to manage the [Palette] of a [Project]. +/// {@endtemplate} +class const PaletteDialog({ + /// The project whose palette is edited. + required final Project project, + + /// The component being edited. + required final Component component, + super.key, +}) extends StatelessWidget { + /// {@macro palette_dialog} + this; + + /// Shows the palette dialog of [project], opened while editing + /// [component], whose unsaved palette colors count as used. + /// + /// Returns the saved palette, or `null` if it was not saved. + static Future show( + BuildContext context, { + required Project project, + required Component component, + }) { + return showDialog( + context: context, + builder: (_) => PaletteDialog(project: project, component: component), + ); + } + + @override + Widget build(BuildContext context) { + return BlocProvider( + create: (context) => PaletteBloc( + project: project, + editedComponent: component, + componentRepository: context.read(), + projectRepository: context.read(), + )..add(const PaletteStarted()), + child: const PaletteView(), + ); + } +} diff --git a/packages/flame_studio/lib/palette/view/palette_view.dart b/packages/flame_studio/lib/palette/view/palette_view.dart new file mode 100644 index 00000000000..9bba2b6265d --- /dev/null +++ b/packages/flame_studio/lib/palette/view/palette_view.dart @@ -0,0 +1,184 @@ +import 'package:flame_studio/component_editor/widgets/property_editors/color_field.dart'; +import 'package:flame_studio/palette/palette.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template palette_view} +/// Lists the colors of the palette to add, rename, change and remove +/// them, and pops with the palette once it is saved. +/// +/// Colors used by components can't be renamed or removed. +/// {@endtemplate} +class const PaletteView({super.key}) extends StatelessWidget { + /// {@macro palette_view} + this; + + @override + Widget build(BuildContext context) { + return BlocConsumer( + listenWhen: (previous, current) => previous.status != current.status, + listener: (context, state) { + if (!state.status.isSaved) { + return; + } + final message = switch (state.status) { + PaletteStatus.codeConflict => + 'Palette saved, but its code was not generated: a file that was ' + 'not generated by the editor is in the way', + PaletteStatus.codeFailure => + 'Palette saved, but its code could not be generated', + _ => null, + }; + if (message != null) { + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar(SnackBar(content: Text(message))); + } + Navigator.of(context).pop(state.palette); + }, + builder: (context, state) { + final bloc = context.read(); + final loading = + state.status == PaletteStatus.initial || + state.status == PaletteStatus.loading; + + return AlertDialog( + title: const Text('Palette'), + content: SizedBox( + width: 520, + child: loading + ? const Center( + heightFactor: 1, + child: CircularProgressIndicator(), + ) + : Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (state.entries.isEmpty) + const Padding( + padding: EdgeInsets.symmetric(vertical: 16), + child: Text( + 'No colors yet. Named colors added here can be ' + 'picked in any color field.', + ), + ), + Flexible( + child: ListView( + shrinkWrap: true, + children: [ + for (final (index, entry) in state.entries.indexed) + _PaletteEntryRow( + key: ValueKey(entry.id), + entry: entry, + users: state.usersOf(entry), + error: state.palette.validateColorName( + index, + entry.color.name, + ), + ), + ], + ), + ), + const SizedBox(height: 8), + Align( + alignment: AlignmentDirectional.centerStart, + child: TextButton.icon( + icon: const Icon(Icons.add), + label: const Text('Add color'), + onPressed: state.isEditable + ? () => bloc.add(const PaletteColorAdded()) + : null, + ), + ), + if (state.status == PaletteStatus.failure) + Text( + 'Something went wrong', + style: TextStyle( + color: Theme.of(context).colorScheme.error, + ), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: state.canSave + ? () => bloc.add(const PaletteSaveRequested()) + : null, + child: const Text('Save'), + ), + ], + ); + }, + ); + } +} + +class const _PaletteEntryRow({ + required final PaletteEntry entry, + + /// The components that use the color. + required final List users, + required final PaletteColorNameError? error, + super.key, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final bloc = context.read(); + final inUse = users.isNotEmpty; + final usedBy = 'Used by ${users.join(', ')}'; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 8, + children: [ + Expanded( + child: TextFormField( + initialValue: entry.color.name, + readOnly: inUse, + decoration: InputDecoration( + labelText: 'Name', + isDense: true, + helperText: inUse ? usedBy : null, + // A color in use can't be renamed, so the other one with + // the same name shows the error. + errorText: switch (inUse ? null : error) { + null => null, + PaletteColorNameError.invalid => + 'Must be a valid Dart identifier', + PaletteColorNameError.duplicate => + 'Another color has this name', + }, + ), + onChanged: (name) => + bloc.add(PaletteColorRenamed(entry.id, name)), + ), + ), + SizedBox( + width: 180, + child: ColorField( + label: 'Color', + value: entry.color.color, + onChanged: (color) => + bloc.add(PaletteColorValueChanged(entry.id, color)), + ), + ), + IconButton( + tooltip: inUse ? "$usedBy, so it can't be removed" : 'Remove', + icon: const Icon(Icons.delete_outline), + onPressed: inUse + ? null + : () => bloc.add(PaletteColorRemoved(entry.id)), + ), + ], + ), + ); + } +} diff --git a/packages/flame_studio/lib/palette/view/view.dart b/packages/flame_studio/lib/palette/view/view.dart new file mode 100644 index 00000000000..c845f69c555 --- /dev/null +++ b/packages/flame_studio/lib/palette/view/view.dart @@ -0,0 +1,2 @@ +export 'palette_dialog.dart'; +export 'palette_view.dart'; diff --git a/packages/flame_studio/lib/project/bloc/project_bloc.dart b/packages/flame_studio/lib/project/bloc/project_bloc.dart new file mode 100644 index 00000000000..d030eaa913e --- /dev/null +++ b/packages/flame_studio/lib/project/bloc/project_bloc.dart @@ -0,0 +1,100 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flame_studio/repositories/repositories.dart'; + +part 'project_event.dart'; +part 'project_state.dart'; + +/// {@template project_bloc} +/// Lists, creates and deletes the components of an open [Project]. +/// +/// Deleting a component also deletes its generated code. +/// {@endtemplate} +class ProjectBloc({ + required final Project _project, + required final ComponentRepository _componentRepository, + required final ProjectRepository _projectRepository, +}) extends Bloc { + /// {@macro project_bloc} + this : super(const ProjectState()) { + on(_onComponentsRequested); + on(_onComponentCreateRequested); + on(_onComponentDeleteRequested); + } + + Future _onComponentsRequested( + ProjectComponentsRequested event, + Emitter emit, + ) async { + emit(state.copyWith(status: ProjectStatus.loading)); + try { + emit( + state.copyWith( + status: ProjectStatus.ready, + components: await _getComponents(), + ), + ); + } on Exception { + emit(state.copyWith(status: ProjectStatus.failure)); + } + } + + Future _onComponentCreateRequested( + ProjectComponentCreateRequested event, + Emitter emit, + ) async { + try { + final component = await _componentRepository.createComponent( + _project.path, + event.name, + event.type, + polygonShape: event.polygonShape, + ); + emit( + state.copyWith( + status: ProjectStatus.created, + createdComponent: component, + components: await _getComponents(), + ), + ); + } on InvalidComponentNameException { + emit(state.copyWith(status: ProjectStatus.invalidName)); + } on ComponentAlreadyExistsException { + emit(state.copyWith(status: ProjectStatus.alreadyExists)); + } on ComponentClassConflictException catch (e) { + emit( + state.copyWith( + status: ProjectStatus.classConflict, + conflictingComponent: e.conflictingComponent, + ), + ); + } on Exception { + emit(state.copyWith(status: ProjectStatus.failure)); + } + } + + Future _onComponentDeleteRequested( + ProjectComponentDeleteRequested event, + Emitter emit, + ) async { + try { + final settings = await _projectRepository.getSettings(_project); + await _componentRepository.deleteComponent( + _project.path, + event.component, + outputPath: settings.outputPath, + ); + emit( + state.copyWith( + status: ProjectStatus.ready, + components: await _getComponents(), + ), + ); + } on Exception { + emit(state.copyWith(status: ProjectStatus.failure)); + } + } + + Future> _getComponents() => + _componentRepository.getComponents(_project.path); +} diff --git a/packages/flame_studio/lib/project/bloc/project_event.dart b/packages/flame_studio/lib/project/bloc/project_event.dart new file mode 100644 index 00000000000..6dffe549d33 --- /dev/null +++ b/packages/flame_studio/lib/project/bloc/project_event.dart @@ -0,0 +1,48 @@ +part of 'project_bloc.dart'; + +/// Base class for [ProjectBloc] events. +sealed class const ProjectEvent() extends Equatable { + /// Creates a [ProjectEvent]. + this; + + @override + List get props => []; +} + +/// The project components should be (re)loaded. +final class const ProjectComponentsRequested() extends ProjectEvent { + /// Creates a [ProjectComponentsRequested] event. + this; +} + +/// The user asked to create a component of [type] called [name]. +/// +/// Polygons start with the vertices of [polygonShape]. +final class const ProjectComponentCreateRequested( + /// The name of the component to create. + final String name, + + /// The type of the component to create. + final ComponentType type, { + + /// The shape of the component to create, if it is a polygon. + final PolygonShape polygonShape = PolygonShape.triangle, +}) extends ProjectEvent { + /// Creates a [ProjectComponentCreateRequested] event. + this; + + @override + List get props => [name, type, polygonShape]; +} + +/// The user confirmed that [component] should be deleted. +final class const ProjectComponentDeleteRequested( + /// The component to delete. + final Component component, +) extends ProjectEvent { + /// Creates a [ProjectComponentDeleteRequested] event. + this; + + @override + List get props => [component]; +} diff --git a/packages/flame_studio/lib/project/bloc/project_state.dart b/packages/flame_studio/lib/project/bloc/project_state.dart new file mode 100644 index 00000000000..8f9ddbf9be3 --- /dev/null +++ b/packages/flame_studio/lib/project/bloc/project_state.dart @@ -0,0 +1,77 @@ +part of 'project_bloc.dart'; + +/// The status of the [ProjectBloc]. +enum ProjectStatus() { + /// Nothing has been loaded yet. + initial, + + /// The components are being loaded. + loading, + + /// The components are loaded. + ready, + + /// A component was created; see [ProjectState.createdComponent]. + created, + + /// The requested component name is not a valid identifier. + invalidName, + + /// A component with the requested name already exists. + alreadyExists, + + /// The class generated for the requested name is already generated for + /// another component; see [ProjectState.conflictingComponent]. + classConflict, + + /// Something went wrong. + failure, +} + +/// {@template project_state} +/// The state of the [ProjectBloc]. +/// {@endtemplate} +final class const ProjectState({ + /// The current status. + final ProjectStatus status = ProjectStatus.initial, + + /// The project components, sorted by name. + final List components = const [], + + /// The last created component. + final Component? createdComponent, + + /// The name of the component that already generates the class of the + /// last rejected name. Only set while the status is + /// [ProjectStatus.classConflict]. + final String? conflictingComponent, +}) extends Equatable { + /// {@macro project_state} + this; + + /// Returns a copy of this state with the given fields replaced. + ProjectState copyWith({ + ProjectStatus? status, + List? components, + Component? createdComponent, + String? conflictingComponent, + }) { + return ProjectState( + status: status ?? this.status, + components: components ?? this.components, + createdComponent: createdComponent ?? this.createdComponent, + conflictingComponent: + (status ?? this.status) == ProjectStatus.classConflict + ? conflictingComponent ?? this.conflictingComponent + : null, + ); + } + + @override + List get props => [ + status, + components, + createdComponent, + conflictingComponent, + ]; +} diff --git a/packages/flame_studio/lib/project/project.dart b/packages/flame_studio/lib/project/project.dart new file mode 100644 index 00000000000..42b4c2c2a99 --- /dev/null +++ b/packages/flame_studio/lib/project/project.dart @@ -0,0 +1,2 @@ +export 'bloc/project_bloc.dart'; +export 'view/view.dart'; diff --git a/packages/flame_studio/lib/project/view/project_page.dart b/packages/flame_studio/lib/project/view/project_page.dart new file mode 100644 index 00000000000..750d410e08b --- /dev/null +++ b/packages/flame_studio/lib/project/view/project_page.dart @@ -0,0 +1,35 @@ +import 'package:flame_studio/project/project.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template project_page} +/// The dashboard of an open [Project], listing its components. +/// {@endtemplate} +class const ProjectPage({ + /// The open project. + required final Project project, + super.key, +}) extends StatelessWidget { + /// {@macro project_page} + this; + + /// Creates a route to the [ProjectPage] for [project]. + static Route route(Project project) { + return MaterialPageRoute( + builder: (_) => ProjectPage(project: project), + ); + } + + @override + Widget build(BuildContext context) { + return BlocProvider( + create: (context) => ProjectBloc( + project: project, + componentRepository: context.read(), + projectRepository: context.read(), + )..add(const ProjectComponentsRequested()), + child: ProjectView(project: project), + ); + } +} diff --git a/packages/flame_studio/lib/project/view/project_view.dart b/packages/flame_studio/lib/project/view/project_view.dart new file mode 100644 index 00000000000..7bc62bc7a8b --- /dev/null +++ b/packages/flame_studio/lib/project/view/project_view.dart @@ -0,0 +1,173 @@ +import 'dart:async'; + +import 'package:flame_studio/component_editor/component_editor.dart'; +import 'package:flame_studio/project/project.dart'; +import 'package:flame_studio/project/widgets/widgets.dart'; +import 'package:flame_studio/project_settings/project_settings.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template project_view} +/// Lists the components of [project] and lets the user add, edit and +/// delete them. +/// {@endtemplate} +class const ProjectView({ + /// The open project. + required final Project project, + super.key, +}) extends StatelessWidget { + /// {@macro project_view} + this; + + @override + Widget build(BuildContext context) { + return BlocListener( + listener: (context, state) { + switch (state.status) { + case ProjectStatus.created: + unawaited(_editComponent(context, state.createdComponent!)); + case ProjectStatus.invalidName: + _showMessage( + context, + 'Component names must start with a letter or underscore and ' + 'contain only letters, digits and underscores', + ); + case ProjectStatus.alreadyExists: + _showMessage(context, 'A component with that name already exists'); + case ProjectStatus.classConflict: + _showMessage( + context, + 'That name generates the same class as a part of the ' + '"${state.conflictingComponent}" component', + ); + case ProjectStatus.failure: + _showMessage(context, 'Something went wrong'); + case ProjectStatus.initial || + ProjectStatus.loading || + ProjectStatus.ready: + break; + } + }, + child: Scaffold( + appBar: AppBar( + title: Text(project.name), + actions: [ + IconButton( + tooltip: 'Settings', + icon: const Icon(Icons.settings_outlined), + onPressed: () => ProjectSettingsDialog.show(context, project), + ), + ], + ), + body: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 720), + child: Padding( + padding: const EdgeInsets.all(32), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Expanded( + child: Text( + 'Components', + style: Theme.of(context).textTheme.titleLarge, + ), + ), + TextButton.icon( + onPressed: () => _addComponent(context), + icon: const Icon(Icons.add), + label: const Text('Add component'), + ), + ], + ), + const SizedBox(height: 8), + Expanded( + child: _Components( + onEdit: (component) => _editComponent(context, component), + onDelete: (component) => + _deleteComponent(context, component), + ), + ), + ], + ), + ), + ), + ), + ), + ); + } + + Future _addComponent(BuildContext context) async { + final bloc = context.read(); + final result = await AddComponentDialog.show(context); + if (result == null) { + return; + } + bloc.add( + ProjectComponentCreateRequested( + result.name, + result.type, + polygonShape: result.polygonShape, + ), + ); + } + + Future _editComponent(BuildContext context, Component component) async { + final bloc = context.read(); + await Navigator.of(context) + .push(ComponentEditorPage.route(project, component)); + bloc.add(const ProjectComponentsRequested()); + } + + Future _deleteComponent( + BuildContext context, + Component component, + ) async { + final bloc = context.read(); + final confirmed = await DeleteComponentDialog.show(context, component); + if (!confirmed) { + return; + } + bloc.add(ProjectComponentDeleteRequested(component)); + } + + void _showMessage(BuildContext context, String message) { + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar(SnackBar(content: Text(message))); + } +} + +class const _Components({ + required final ValueChanged onEdit, + required final ValueChanged onDelete, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final state = context.select)>( + (bloc) => (bloc.state.status, bloc.state.components), + ); + final (status, components) = state; + + if (components.isEmpty) { + if (status == ProjectStatus.initial || status == ProjectStatus.loading) { + return const Center(child: CircularProgressIndicator()); + } + return const Text('No components yet'); + } + + return ListView( + children: [ + for (final component in components) + ComponentTile( + component: component, + onEdit: () => onEdit(component), + onDelete: () => onDelete(component), + ), + ], + ); + } +} diff --git a/packages/flame_studio/lib/project/view/view.dart b/packages/flame_studio/lib/project/view/view.dart new file mode 100644 index 00000000000..c0259138e90 --- /dev/null +++ b/packages/flame_studio/lib/project/view/view.dart @@ -0,0 +1,2 @@ +export 'project_page.dart'; +export 'project_view.dart'; diff --git a/packages/flame_studio/lib/project/widgets/add_component_dialog.dart b/packages/flame_studio/lib/project/widgets/add_component_dialog.dart new file mode 100644 index 00000000000..a43f5a1e749 --- /dev/null +++ b/packages/flame_studio/lib/project/widgets/add_component_dialog.dart @@ -0,0 +1,126 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; + +/// The name, type and, for polygons, shape entered in the +/// [AddComponentDialog]. +typedef AddComponentResult = ({ + String name, + ComponentType type, + PolygonShape polygonShape, +}); + +/// {@template add_component_dialog} +/// Asks the user for the name and type of a new component, and for the +/// shape it starts with if it is a polygon. +/// +/// Pops with the entered [AddComponentResult], or `null` if cancelled. +/// {@endtemplate} +class const AddComponentDialog({super.key}) extends StatefulWidget { + /// {@macro add_component_dialog} + this; + + /// Shows the dialog and returns the entered name and type, or `null` if + /// cancelled. + static Future show(BuildContext context) { + return showDialog( + context: context, + builder: (_) => const AddComponentDialog(), + ); + } + + @override + State createState() => _AddComponentDialogState(); +} + +class _AddComponentDialogState() extends State { + final _controller = TextEditingController(); + ComponentType _type = ComponentType.values.first; + PolygonShape _polygonShape = PolygonShape.triangle; + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + void _submit() { + final name = _controller.text.trim(); + if (name.isEmpty) { + return; + } + Navigator.of(context) + .pop((name: name, type: _type, polygonShape: _polygonShape)); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: const Text('Add component'), + content: SizedBox( + width: 320, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + spacing: 16, + children: [ + TextField( + controller: _controller, + autofocus: true, + decoration: const InputDecoration( + labelText: 'Name', + hintText: 'PlayerComponent', + ), + onSubmitted: (_) => _submit(), + ), + DropdownMenu( + label: const Text('Type'), + expandedInsets: EdgeInsets.zero, + initialSelection: _type, + requestFocusOnTap: false, + onSelected: (type) { + if (type != null) { + setState(() => _type = type); + } + }, + dropdownMenuEntries: [ + // Hitboxes can only be children. + for (final type in ComponentType.values) + if (!type.isHitbox) + DropdownMenuEntry(value: type, label: type.label), + ], + ), + if (_type.hasVertices) + DropdownMenu( + label: const Text('Shape'), + expandedInsets: EdgeInsets.zero, + initialSelection: _polygonShape, + requestFocusOnTap: false, + onSelected: (shape) { + if (shape != null) { + setState(() => _polygonShape = shape); + } + }, + dropdownMenuEntries: [ + for (final shape in PolygonShape.values) + DropdownMenuEntry(value: shape, label: shape.label), + ], + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Cancel'), + ), + ValueListenableBuilder( + valueListenable: _controller, + builder: (context, value, _) => FilledButton( + onPressed: value.text.trim().isEmpty ? null : _submit, + child: const Text('Create'), + ), + ), + ], + ); + } +} diff --git a/packages/flame_studio/lib/project/widgets/component_tile.dart b/packages/flame_studio/lib/project/widgets/component_tile.dart new file mode 100644 index 00000000000..67504afa01d --- /dev/null +++ b/packages/flame_studio/lib/project/widgets/component_tile.dart @@ -0,0 +1,44 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; + +/// {@template component_tile} +/// A list entry for a project [Component], with edit and delete actions. +/// {@endtemplate} +class const ComponentTile({ + /// The component shown by this tile. + required final Component component, + + /// Called when the user wants to edit the component. + required final VoidCallback onEdit, + + /// Called when the user wants to delete the component. + required final VoidCallback onDelete, + super.key, +}) extends StatelessWidget { + /// {@macro component_tile} + this; + + @override + Widget build(BuildContext context) { + return ListTile( + leading: const Icon(Icons.widgets_outlined), + title: Text(component.name), + onTap: onEdit, + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + tooltip: 'Edit', + icon: const Icon(Icons.edit_outlined), + onPressed: onEdit, + ), + IconButton( + tooltip: 'Delete', + icon: const Icon(Icons.delete_outline), + onPressed: onDelete, + ), + ], + ), + ); + } +} diff --git a/packages/flame_studio/lib/project/widgets/delete_component_dialog.dart b/packages/flame_studio/lib/project/widgets/delete_component_dialog.dart new file mode 100644 index 00000000000..1f4d40cc2f0 --- /dev/null +++ b/packages/flame_studio/lib/project/widgets/delete_component_dialog.dart @@ -0,0 +1,47 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; + +/// {@template delete_component_dialog} +/// Asks the user to confirm the deletion of a [Component]. +/// +/// Pops with `true` when confirmed. +/// {@endtemplate} +class const DeleteComponentDialog({ + /// The component to delete. + required final Component component, + super.key, +}) extends StatelessWidget { + /// {@macro delete_component_dialog} + this; + + /// Shows the dialog and returns whether the deletion was confirmed. + static Future show(BuildContext context, Component component) async { + final confirmed = await showDialog( + context: context, + builder: (_) => DeleteComponentDialog(component: component), + ); + return confirmed ?? false; + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: const Text('Delete component'), + content: Text('Delete "${component.name}"? This cannot be undone.'), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: const Text('Cancel'), + ), + FilledButton( + style: FilledButton.styleFrom( + backgroundColor: Theme.of(context).colorScheme.error, + foregroundColor: Theme.of(context).colorScheme.onError, + ), + onPressed: () => Navigator.of(context).pop(true), + child: const Text('Delete'), + ), + ], + ); + } +} diff --git a/packages/flame_studio/lib/project/widgets/widgets.dart b/packages/flame_studio/lib/project/widgets/widgets.dart new file mode 100644 index 00000000000..3ebf96c63b3 --- /dev/null +++ b/packages/flame_studio/lib/project/widgets/widgets.dart @@ -0,0 +1,3 @@ +export 'add_component_dialog.dart'; +export 'component_tile.dart'; +export 'delete_component_dialog.dart'; diff --git a/packages/flame_studio/lib/project_settings/bloc/project_settings_bloc.dart b/packages/flame_studio/lib/project_settings/bloc/project_settings_bloc.dart new file mode 100644 index 00000000000..947ca8a5bd7 --- /dev/null +++ b/packages/flame_studio/lib/project_settings/bloc/project_settings_bloc.dart @@ -0,0 +1,97 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flame_studio/repositories/repositories.dart'; + +part 'project_settings_event.dart'; +part 'project_settings_state.dart'; + +/// {@template project_settings_bloc} +/// Loads, edits and saves the settings of a [Project]. +/// {@endtemplate} +class ProjectSettingsBloc({ + required final Project _project, + required final ProjectRepository _projectRepository, +}) extends Bloc { + /// {@macro project_settings_bloc} + this : super(const ProjectSettingsState()) { + on(_onRequested); + on(_onOutputPathChanged); + on(_onBrowseRequested); + on(_onSubmitted); + } + + Future _onRequested( + ProjectSettingsRequested event, + Emitter emit, + ) async { + emit(state.copyWith(status: ProjectSettingsStatus.loading)); + try { + final settings = await _projectRepository.getSettings(_project); + emit( + state.copyWith( + status: ProjectSettingsStatus.ready, + outputPath: settings.outputPath, + ), + ); + } on Exception { + emit(state.copyWith(status: ProjectSettingsStatus.failure)); + } + } + + void _onOutputPathChanged( + ProjectSettingsOutputPathChanged event, + Emitter emit, + ) { + emit( + state.copyWith( + status: ProjectSettingsStatus.ready, + outputPath: event.outputPath, + ), + ); + } + + Future _onBrowseRequested( + ProjectSettingsBrowseRequested event, + Emitter emit, + ) async { + try { + final outputPath = await _projectRepository.pickOutputPath(_project); + if (outputPath == null) { + return; + } + emit( + state.copyWith( + status: ProjectSettingsStatus.ready, + outputPath: outputPath, + ), + ); + } on InvalidOutputPathException { + emit(state.copyWith(status: ProjectSettingsStatus.invalidOutputPath)); + } on Exception { + emit(state.copyWith(status: ProjectSettingsStatus.failure)); + } + } + + Future _onSubmitted( + ProjectSettingsSubmitted event, + Emitter emit, + ) async { + emit(state.copyWith(status: ProjectSettingsStatus.saving)); + try { + final settings = await _projectRepository.saveSettings( + _project, + ProjectSettings(outputPath: state.outputPath), + ); + emit( + state.copyWith( + status: ProjectSettingsStatus.saved, + outputPath: settings.outputPath, + ), + ); + } on InvalidOutputPathException { + emit(state.copyWith(status: ProjectSettingsStatus.invalidOutputPath)); + } on Exception { + emit(state.copyWith(status: ProjectSettingsStatus.failure)); + } + } +} diff --git a/packages/flame_studio/lib/project_settings/bloc/project_settings_event.dart b/packages/flame_studio/lib/project_settings/bloc/project_settings_event.dart new file mode 100644 index 00000000000..59d2660ea4c --- /dev/null +++ b/packages/flame_studio/lib/project_settings/bloc/project_settings_event.dart @@ -0,0 +1,41 @@ +part of 'project_settings_bloc.dart'; + +/// Base class for [ProjectSettingsBloc] events. +sealed class const ProjectSettingsEvent() extends Equatable { + /// Creates a [ProjectSettingsEvent]. + this; + + @override + List get props => []; +} + +/// The project settings should be loaded. +final class const ProjectSettingsRequested() extends ProjectSettingsEvent { + /// Creates a [ProjectSettingsRequested] event. + this; +} + +/// The user edited the output path. +final class const ProjectSettingsOutputPathChanged( + /// The new output path. + final String outputPath, +) extends ProjectSettingsEvent { + /// Creates a [ProjectSettingsOutputPathChanged] event. + this; + + @override + List get props => [outputPath]; +} + +/// The user asked to pick the output path with the folder picker. +final class const ProjectSettingsBrowseRequested() + extends ProjectSettingsEvent { + /// Creates a [ProjectSettingsBrowseRequested] event. + this; +} + +/// The user asked to save the settings. +final class const ProjectSettingsSubmitted() extends ProjectSettingsEvent { + /// Creates a [ProjectSettingsSubmitted] event. + this; +} diff --git a/packages/flame_studio/lib/project_settings/bloc/project_settings_state.dart b/packages/flame_studio/lib/project_settings/bloc/project_settings_state.dart new file mode 100644 index 00000000000..6bd147fc0a2 --- /dev/null +++ b/packages/flame_studio/lib/project_settings/bloc/project_settings_state.dart @@ -0,0 +1,54 @@ +part of 'project_settings_bloc.dart'; + +/// The status of the [ProjectSettingsBloc]. +enum ProjectSettingsStatus() { + /// Nothing has been loaded yet. + initial, + + /// The settings are being loaded. + loading, + + /// The settings are loaded and can be edited. + ready, + + /// The settings are being saved. + saving, + + /// The settings were saved. + saved, + + /// The output path is not a folder inside the project. + invalidOutputPath, + + /// Something went wrong. + failure, +} + +/// {@template project_settings_state} +/// The state of the [ProjectSettingsBloc]. +/// {@endtemplate} +final class const ProjectSettingsState({ + /// The current status. + final ProjectSettingsStatus status = ProjectSettingsStatus.initial, + + /// Folder, relative to the project folder, where the generated Dart source + /// code is written. + final String outputPath = ProjectSettings.defaultOutputPath, +}) extends Equatable { + /// {@macro project_settings_state} + this; + + /// Returns a copy of this state with the given fields replaced. + ProjectSettingsState copyWith({ + ProjectSettingsStatus? status, + String? outputPath, + }) { + return ProjectSettingsState( + status: status ?? this.status, + outputPath: outputPath ?? this.outputPath, + ); + } + + @override + List get props => [status, outputPath]; +} diff --git a/packages/flame_studio/lib/project_settings/project_settings.dart b/packages/flame_studio/lib/project_settings/project_settings.dart new file mode 100644 index 00000000000..8cec0183077 --- /dev/null +++ b/packages/flame_studio/lib/project_settings/project_settings.dart @@ -0,0 +1,2 @@ +export 'bloc/project_settings_bloc.dart'; +export 'view/view.dart'; diff --git a/packages/flame_studio/lib/project_settings/view/project_settings_dialog.dart b/packages/flame_studio/lib/project_settings/view/project_settings_dialog.dart new file mode 100644 index 00000000000..304fc76c277 --- /dev/null +++ b/packages/flame_studio/lib/project_settings/view/project_settings_dialog.dart @@ -0,0 +1,35 @@ +import 'package:flame_studio/project_settings/project_settings.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template project_settings_dialog} +/// A dialog to edit the settings of a [Project]. +/// {@endtemplate} +class const ProjectSettingsDialog({ + /// The project whose settings are edited. + required final Project project, + super.key, +}) extends StatelessWidget { + /// {@macro project_settings_dialog} + this; + + /// Shows the settings dialog of [project]. + static Future show(BuildContext context, Project project) { + return showDialog( + context: context, + builder: (_) => ProjectSettingsDialog(project: project), + ); + } + + @override + Widget build(BuildContext context) { + return BlocProvider( + create: (context) => ProjectSettingsBloc( + project: project, + projectRepository: context.read(), + )..add(const ProjectSettingsRequested()), + child: const ProjectSettingsView(), + ); + } +} diff --git a/packages/flame_studio/lib/project_settings/view/project_settings_view.dart b/packages/flame_studio/lib/project_settings/view/project_settings_view.dart new file mode 100644 index 00000000000..fd8787dfa33 --- /dev/null +++ b/packages/flame_studio/lib/project_settings/view/project_settings_view.dart @@ -0,0 +1,107 @@ +import 'package:flame_studio/project_settings/project_settings.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template project_settings_view} +/// Lets the user edit the project settings and pops once they are saved. +/// {@endtemplate} +class const ProjectSettingsView({super.key}) extends StatefulWidget { + /// {@macro project_settings_view} + this; + + @override + State createState() => _ProjectSettingsViewState(); +} + +class _ProjectSettingsViewState() extends State { + late final TextEditingController _controller; + + @override + void initState() { + super.initState(); + _controller = TextEditingController( + text: context.read().state.outputPath, + ); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return BlocConsumer( + listener: (context, state) { + if (state.status == ProjectSettingsStatus.saved) { + Navigator.of(context).pop(); + } else if (state.outputPath != _controller.text) { + _controller.text = state.outputPath; + } + }, + builder: (context, state) { + final bloc = context.read(); + final status = state.status; + final loading = + status == ProjectSettingsStatus.initial || + status == ProjectSettingsStatus.loading; + final canSave = + !loading && + status != ProjectSettingsStatus.saving && + state.outputPath.trim().isNotEmpty; + + return AlertDialog( + title: const Text('Project settings'), + content: SizedBox( + width: 480, + child: loading + ? const Center( + heightFactor: 1, + child: CircularProgressIndicator(), + ) + : TextField( + controller: _controller, + autofocus: true, + decoration: InputDecoration( + labelText: 'Generated code path', + helperText: 'Relative to the project folder', + errorText: switch (status) { + ProjectSettingsStatus.invalidOutputPath => + 'Must be a folder inside the project', + ProjectSettingsStatus.failure => 'Something went wrong', + _ => null, + }, + suffixIcon: IconButton( + tooltip: 'Browse', + icon: const Icon(Icons.folder_open), + onPressed: () => + bloc.add(const ProjectSettingsBrowseRequested()), + ), + ), + onChanged: (value) => + bloc.add(ProjectSettingsOutputPathChanged(value)), + onSubmitted: (_) { + if (canSave) { + bloc.add(const ProjectSettingsSubmitted()); + } + }, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: canSave + ? () => bloc.add(const ProjectSettingsSubmitted()) + : null, + child: const Text('Save'), + ), + ], + ); + }, + ); + } +} diff --git a/packages/flame_studio/lib/project_settings/view/view.dart b/packages/flame_studio/lib/project_settings/view/view.dart new file mode 100644 index 00000000000..1b672ea84d0 --- /dev/null +++ b/packages/flame_studio/lib/project_settings/view/view.dart @@ -0,0 +1,2 @@ +export 'project_settings_dialog.dart'; +export 'project_settings_view.dart'; diff --git a/packages/flame_studio/lib/repositories/component_repository/code_generation/code_generation.dart b/packages/flame_studio/lib/repositories/component_repository/code_generation/code_generation.dart new file mode 100644 index 00000000000..0ec6db54f26 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/code_generation/code_generation.dart @@ -0,0 +1,2 @@ +export 'component_code_generator.dart'; +export 'palette_code_generator.dart'; diff --git a/packages/flame_studio/lib/repositories/component_repository/code_generation/component_code_generator.dart b/packages/flame_studio/lib/repositories/component_repository/code_generation/component_code_generator.dart new file mode 100644 index 00000000000..041a99623b7 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/code_generation/component_code_generator.dart @@ -0,0 +1,230 @@ +import 'package:dart_style/dart_style.dart'; +import 'package:flame_studio/repositories/component_repository/code_generation/dart_names.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:pub_semver/pub_semver.dart'; + +/// {@template component_code_generator} +/// Generates the Dart source of a [Component] and its children. +/// +/// The root becomes a public class, named after the component with the +/// `$` prefix of generated code (`player` becomes `$Player`), that extends +/// the Flame class of its type, so games can subclass it +/// (`class Player extends $Player`). Every child is exposed through a +/// getter, named after the child, on the component it is inside. Children +/// that have children of their own get a generated class too, so their +/// children have getters as well; the others are plain Flame components. +/// +/// Every component type has a case in [generate], and every property is +/// written the same way `flame_mapping.dart` applies it to the preview. +/// {@endtemplate} +class const ComponentCodeGenerator() { + /// {@macro component_code_generator} + this; + + /// The first line of every generated file. + static const header = '// GENERATED CODE - DO NOT MODIFY BY HAND.'; + + static final _formatter = DartFormatter(languageVersion: Version(3, 8, 0)); + + /// The extension of every generated file. + static const fileExtension = '.generated.dart'; + + /// The name of the file generated for [component], such as + /// `player_ship.generated.dart`. + String fileName(Component component) { + return '${dartFileName(component.name)}$fileExtension'; + } + + /// Returns the formatted Dart source of [component]. + /// + /// Paints that use a color of [palette] reference its generated class + /// (see [PaletteCodeGenerator]); the others, including those whose + /// palette color no longer exists, use their color value. + String generate(Component component, {Palette palette = const Palette()}) { + final rootClass = dartRootClassName(component.name); + final buffer = StringBuffer() + ..writeln(header) + ..writeln('// Generated by Flame Studio.') + ..writeln() + ..writeln('// coverage:ignore-file') + ..writeln('// ignore_for_file: type=lint') + ..writeln(); + // `dart:ui` is only needed for paints; an unused import is a warning. + if (component.nodes.any((node) => node is PaintedComponent)) { + buffer + ..writeln("import 'dart:ui';") + ..writeln(); + } + if (component.nodes.any((node) => node is HitboxComponent)) { + buffer.writeln("import 'package:flame/collisions.dart';"); + } + buffer.writeln("import 'package:flame/components.dart';"); + if (component.usedPaletteColors.any(palette.contains)) { + buffer.writeln("import '${PaletteCodeGenerator.fileName}';"); + } + buffer.writeln(); + + _writeClass( + buffer, + component, + palette: palette, + rootName: component.name, + className: rootClass, + doc: 'The `${component.name}` component.', + parameters: '{super.position, super.angle, super.anchor, super.priority}', + arguments: _arguments(component, palette, withPosition: false), + ); + for (final node in component.nodes.skip(1)) { + if (node.children.isEmpty) { + continue; + } + _writeClass( + buffer, + node, + palette: palette, + rootName: component.name, + className: dartChildClassName(component.name, node.name), + doc: 'The `${node.name}` child component of [$rootClass].', + parameters: '', + arguments: _arguments(node, palette, withPosition: true), + ); + } + return _formatter.format(buffer.toString()); + } + + void _writeClass( + StringBuffer buffer, + Component component, { + required Palette palette, + required String rootName, + required String className, + required String doc, + required String parameters, + required List arguments, + }) { + final children = component.children; + buffer + ..writeln('/// $doc') + ..writeln('class $className extends ${_flameClass(component)} {') + ..writeln(' /// Creates a [$className].') + ..write(' $className($parameters)') + ..write(' : super(${_list(arguments)})'); + + if (children.isEmpty) { + buffer.writeln(';'); + } else { + final getters = children.map((child) => dartMemberName(child.name)); + buffer.writeln( + children.length == 1 + ? ' { add(${getters.single}); }' + : ' { addAll([${_list(getters)}]); }', + ); + } + + for (final child in children) { + final type = child.children.isEmpty + ? _flameClass(child) + : dartChildClassName(rootName, child.name); + final value = child.children.isEmpty + ? '$type(${_list(_arguments(child, palette, withPosition: true))})' + : '$type()'; + buffer + ..writeln() + ..writeln(' /// The `${child.name}` child component.') + ..writeln(' final $type ${dartMemberName(child.name)} = $value;'); + } + buffer + ..writeln('}') + ..writeln(); + } + + static String _flameClass(Component component) { + return switch (component) { + RectangleComponent() => 'RectangleComponent', + PositionComponent() => 'PositionComponent', + CircleComponent() => 'CircleComponent', + PolygonComponent() => 'PolygonComponent', + RectangleHitboxComponent() => 'RectangleHitbox', + CircleHitboxComponent() => 'CircleHitbox', + PolygonHitboxComponent() => 'PolygonHitbox', + }; + } + + /// The arguments of the Flame constructor, one per property. The root + /// position, angle and anchor are left to whoever uses the component. + static List _arguments( + Component component, + Palette palette, { + required bool withPosition, + }) { + return [ + // Positional, so it comes first. Not const: Flame changes the list. + if (component case final VerticesComponent c) + '[${c.vertices.vertices.map((v) => _vector(v.x, v.y)).join(', ')}]', + if (component case final PositionedComponent c when withPosition) + 'position: ${_vector(c.position.x, c.position.y)}', + // Flame already defaults to no rotation and the top left anchor. + if (component case final RotatedComponent c + when withPosition && c.angle != ComponentAngle.zero) + 'angle: ${_number(c.angle.radians)}', + if (component case final AnchoredComponent c + when withPosition && c.anchor != ComponentAnchor.topLeft) + 'anchor: ${_anchor(c.anchor)}', + if (component case final SizedComponent c) + 'size: ${_vector(c.size.width, c.size.height)}', + if (component case final RadiusComponent c) + 'radius: ${_number(c.radius.radius)}', + if (component case final PaintedComponent c) + 'paint: ${_paint(c.paint, palette)}', + // Flame defaults to active, non solid hitboxes. + if (component case final HitboxComponent c + when c.collision.type != HitboxCollisionType.active) + 'collisionType: CollisionType.${c.collision.type.name}', + if (component case HitboxComponent( + collision: ComponentCollision(isSolid: true), + )) + 'isSolid: true', + ]; + } + + /// Joins [items] with trailing commas, so the formatter splits them one + /// per line when they don't fit. + static String _list(Iterable items) { + return items.map((item) => '$item,').join(); + } + + static String _vector(double x, double y) { + return 'Vector2(${_number(x)}, ${_number(y)})'; + } + + static String _number(double value) { + return value == value.truncateToDouble() + ? value.toInt().toString() + : value.toString(); + } + + static String _anchor(ComponentAnchor anchor) { + final name = anchor.presetName; + return name != null + ? 'Anchor.$name' + : 'Anchor(${_number(anchor.x)}, ${_number(anchor.y)})'; + } + + /// The `Color` constant of a 32 bit ARGB [color]. + static String colorLiteral(int color) { + final hex = color.toRadixString(16).toUpperCase().padLeft(8, '0'); + return 'Color(0x$hex)'; + } + + static String _paint(ComponentPaint paint, Palette palette) { + final paletteColor = paint.paletteColor; + final color = paletteColor != null && palette.contains(paletteColor) + ? PaletteCodeGenerator.reference(paletteColor) + : 'const ${colorLiteral(paint.color)}'; + return [ + 'Paint()', + '..color = $color', + if (paint.style == PaintStyle.stroke) '..style = PaintingStyle.stroke', + ].join(); + } +} diff --git a/packages/flame_studio/lib/repositories/component_repository/code_generation/dart_names.dart b/packages/flame_studio/lib/repositories/component_repository/code_generation/dart_names.dart new file mode 100644 index 00000000000..06dec9fe3c7 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/code_generation/dart_names.dart @@ -0,0 +1,279 @@ +import 'package:flame_studio/repositories/repositories.dart'; + +final _identifier = RegExp(r'^[A-Za-z_][A-Za-z0-9_]*$'); + +/// Whether [name] is a valid Dart identifier. +bool isDartIdentifier(String name) => _identifier.hasMatch(name); + +/// The name of the class generated for a component called [name]: +/// `player_ship` and `playerShip` become `PlayerShip`. +String dartClassName(String name) { + return [ + for (final word in name.split('_')) + if (word.isNotEmpty) word[0].toUpperCase() + word.substring(1), + ].join(); +} + +/// The name of the class generated for a root component called [name], +/// with the `$` prefix of generated code: `player_ship` becomes +/// `$PlayerShip`. +/// +/// The prefix keeps generated classes from clashing with the classes of +/// the game (or Flame's), which can subclass them. +String dartRootClassName(String name) => '\$${dartClassName(name)}'; + +/// The name of the class generated for a child component called +/// [childName] of the root component called [rootName]: the `head` of +/// `player_ship` becomes `$PlayerShipHead`. +/// +/// Only children that have children of their own get a class. +String dartChildClassName(String rootName, String childName) { + return '${dartRootClassName(rootName)}${dartClassName(childName)}'; +} + +/// The name of the getter generated for a child component called [name]: +/// `left_arm` and `LeftArm` become `leftArm`. +String dartMemberName(String name) { + final className = dartClassName(name); + if (className.isEmpty) { + return className; + } + return className[0].toLowerCase() + className.substring(1); +} + +/// The name, without extension, of the file generated for a component +/// called [name]: `PlayerShip` and `playerShip` become `player_ship`. +String dartFileName(String name) { + return name + .replaceAllMapped( + RegExp('([a-z0-9])([A-Z])'), + (match) => '${match[1]}_${match[2]}', + ) + .toLowerCase() + .split('_') + .where((word) => word.isNotEmpty) + .join('_'); +} + +/// Whether [name] is a Dart keyword, which can't be used as a member name. +bool isDartKeyword(String name) => _keywords.contains(name); + +/// The names of the members a generated class inherits from the Flame class +/// of [type]. Getters of children must not use them. +Set flameMemberNames(ComponentType type) { + return switch (type) { + ComponentType.rectangle => _rectangleComponentMembers, + ComponentType.position => _positionComponentMembers, + ComponentType.circle => _circleComponentMembers, + ComponentType.polygon => _polygonComponentMembers, + // Hitboxes have no children, so no getters: the members of their shape + // are enough. + ComponentType.rectangleHitbox => _rectangleComponentMembers, + ComponentType.circleHitbox => _circleComponentMembers, + ComponentType.polygonHitbox => _polygonComponentMembers, + }; +} + +const _keywords = { + // Reserved words. + 'assert', 'break', 'case', 'catch', 'class', 'const', 'continue', + 'default', 'do', 'else', 'enum', 'extends', 'false', 'final', 'finally', + 'for', 'if', 'in', 'is', 'new', 'null', 'rethrow', 'return', 'super', + 'switch', 'this', 'throw', 'true', 'try', 'var', 'void', 'while', 'with', + // Built-in identifiers and contextual keywords. + 'abstract', 'as', 'async', 'await', 'base', 'covariant', 'deferred', + 'dynamic', 'export', 'extension', 'external', 'factory', 'get', 'hide', + 'implements', 'import', 'interface', 'late', 'library', 'mixin', 'of', + 'on', 'operator', 'part', 'required', 'sealed', 'set', 'show', 'static', + 'sync', 'typedef', 'when', 'yield', +}; + +/// Public members of Flame's `PositionComponent` (Flame 2.0.0-dev.1), +/// including the inherited ones. +const _positionComponentMembers = { + 'absoluteAngle', + 'absoluteAngleWithoutReflection', + 'absoluteCenter', + 'absolutePosition', + 'absolutePositionOf', + 'absolutePositionOfAnchor', + 'absoluteScale', + 'absoluteScaledSize', + 'absoluteToLocal', + 'absoluteTopLeftPosition', + 'add', + 'addAll', + 'addToParent', + 'afterChildrenRendered', + 'ancestors', + 'anchor', + 'angle', + 'angleTo', + 'center', + 'children', + 'componentsAtLocation', + 'componentsAtPoint', + 'contains', + 'containsLocalPoint', + 'containsPoint', + 'createComponentList', + 'debugColor', + 'debugCoordinatesPrecision', + 'debugMode', + 'debugPaint', + 'debugTextPaint', + 'decorator', + 'descendants', + 'distance', + 'findGame', + 'findParent', + 'findRenderContext', + 'findRootGame', + 'firstChild', + 'flipHorizontally', + 'flipHorizontallyAroundCenter', + 'flipVertically', + 'flipVerticallyAroundCenter', + 'handleHotReload', + 'handleResize', + 'hasChildren', + 'hashCode', + 'height', + 'isFlippedHorizontally', + 'isFlippedVertically', + 'isLoaded', + 'isLoading', + 'isMounted', + 'isMounting', + 'isRemoved', + 'isRemoving', + 'key', + 'lastChild', + 'loadSettled', + 'loaded', + 'localToParent', + 'lookAt', + 'mounted', + 'nativeAngle', + 'noSuchMethod', + 'onChildrenChanged', + 'onGameResize', + 'onHotReload', + 'onLoad', + 'onMount', + 'onParentResize', + 'onRemove', + 'parent', + 'parentToLocal', + 'position', + 'positionOf', + 'positionOfAnchor', + 'priority', + 'propagateToChildren', + 'rebalanceChildren', + 'remove', + 'removeAll', + 'removeFromParent', + 'removeWhere', + 'removed', + 'render', + 'renderChild', + 'renderContext', + 'renderDebugMode', + 'renderTree', + 'renderTreeWithoutDecorator', + 'runtimeType', + 'scale', + 'scaledSize', + 'setByRect', + 'setLoaded', + 'setMounted', + 'setRemoved', + 'size', + 'toAbsoluteRect', + 'toLocal', + 'toRect', + 'toString', + 'topLeftPosition', + 'transform', + 'transformMatrix', + 'update', + 'updateTree', + 'width', + 'x', + 'y', +}; + +/// Public members of Flame's `RectangleComponent` (Flame 2.0.0-dev.1), +/// including the inherited ones. It adds no public instance members to +/// `PolygonComponent`. +const Set _rectangleComponentMembers = _polygonComponentMembers; + +/// Public members of Flame's `PolygonComponent` (Flame 2.0.0-dev.1), +/// including the inherited ones: the `PositionComponent` ones, plus those +/// of `HasPaint` and `ShapeComponent`. +const Set _polygonComponentMembers = { + ..._positionComponentMembers, + 'deletePaint', + 'getAlpha', + 'getEdge', + 'getOpacity', + 'getPaint', + 'getVertex', + 'globalVertices', + 'hasPaintLayers', + 'hue', + 'isSolid', + 'makeOpaque', + 'makeTransparent', + 'manuallyPositioned', + 'onChanged', + 'opacity', + 'opacityProviderOf', + 'opacityProviderOfList', + 'paint', + 'paintLayers', + 'paintLayersInternal', + 'possibleIntersectionVertices', + 'refreshVertices', + 'renderShape', + 'setAlpha', + 'setColor', + 'setOpacity', + 'setPaint', + 'shrinkToBounds', + 'tint', + 'vertices', +}; + +/// Public members of Flame's `CircleComponent` (Flame 2.0.0-dev.1), +/// including the inherited ones: the `PositionComponent` ones, plus those +/// of `HasPaint` and `ShapeComponent`. +const Set _circleComponentMembers = { + ..._positionComponentMembers, + 'deletePaint', + 'getAlpha', + 'getOpacity', + 'getPaint', + 'hasPaintLayers', + 'hue', + 'isSolid', + 'lineSegmentIntersections', + 'makeOpaque', + 'makeTransparent', + 'onChanged', + 'opacity', + 'opacityProviderOf', + 'opacityProviderOfList', + 'paint', + 'paintLayers', + 'paintLayersInternal', + 'radius', + 'renderShape', + 'scaledRadius', + 'setAlpha', + 'setColor', + 'setOpacity', + 'setPaint', + 'tint', +}; diff --git a/packages/flame_studio/lib/repositories/component_repository/code_generation/palette_code_generator.dart b/packages/flame_studio/lib/repositories/component_repository/code_generation/palette_code_generator.dart new file mode 100644 index 00000000000..424c69610fe --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/code_generation/palette_code_generator.dart @@ -0,0 +1,59 @@ +import 'package:dart_style/dart_style.dart'; +import 'package:flame_studio/repositories/component_repository/code_generation/dart_names.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:pub_semver/pub_semver.dart'; + +/// {@template palette_code_generator} +/// Generates the Dart source of a [Palette]: a class with a `Color` +/// constant for every color, which the code of the components that use +/// them references (`GamePalette.primary`). +/// +/// Generated component classes all start with `$`, so [className] never +/// clashes with them. +/// {@endtemplate} +class const PaletteCodeGenerator() { + /// {@macro palette_code_generator} + this; + + /// The name of the generated class. + static const className = 'GamePalette'; + + /// The name, without extension, of the generated file. Components can't + /// use it (see [ComponentRepository.createComponent]). + static const baseName = 'palette'; + + /// The name of the generated file, in the output folder of the project, + /// next to the code of the components. + static const fileName = '$baseName${ComponentCodeGenerator.fileExtension}'; + + static final _formatter = DartFormatter(languageVersion: Version(3, 8, 0)); + + /// The expression of the color called [name] in the generated code. + static String reference(String name) => '$className.${dartMemberName(name)}'; + + /// Returns the formatted Dart source of [palette]. + String generate(Palette palette) { + final buffer = StringBuffer() + ..writeln(ComponentCodeGenerator.header) + ..writeln('// Generated by Flame Studio.') + ..writeln() + ..writeln('// coverage:ignore-file') + ..writeln('// ignore_for_file: type=lint') + ..writeln() + ..writeln("import 'dart:ui';") + ..writeln() + ..writeln('/// The colors of the game palette.') + ..writeln('abstract final class $className {'); + for (final PaletteColor(:name, :color) in palette.colors) { + buffer + ..writeln(' /// The `$name` color.') + ..writeln( + ' static const ${dartMemberName(name)} = ' + '${ComponentCodeGenerator.colorLiteral(color)};', + ) + ..writeln(); + } + buffer.writeln('}'); + return _formatter.format(buffer.toString()); + } +} diff --git a/packages/flame_studio/lib/repositories/component_repository/component_repository.dart b/packages/flame_studio/lib/repositories/component_repository/component_repository.dart new file mode 100644 index 00000000000..ba7b4eeb2bb --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/component_repository.dart @@ -0,0 +1,327 @@ +import 'dart:convert'; + +import 'package:flame_studio/clients/clients.dart'; +import 'package:flame_studio/repositories/component_repository/code_generation/dart_names.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:path/path.dart' as p; + +/// {@template invalid_component_name_exception} +/// Thrown when creating a [Component] with a name that is not a valid +/// identifier. +/// {@endtemplate} +class const InvalidComponentNameException( + /// The rejected name. + final String name, +) implements Exception { + /// {@macro invalid_component_name_exception} + this; +} + +/// {@template component_already_exists_exception} +/// Thrown when creating a [Component] whose name is already taken. +/// {@endtemplate} +class const ComponentAlreadyExistsException( + /// The name that is already taken. + final String name, +) implements Exception { + /// {@macro component_already_exists_exception} + this; +} + +/// {@template component_class_conflict_exception} +/// Thrown when creating a [Component] whose generated class would have the +/// same name as a class generated for another component, such as `AB` and +/// `a_b`, or `player_ship_head` and the `head` child of `player_ship`. +/// {@endtemplate} +class const ComponentClassConflictException( + /// The rejected name. + final String name, + + /// The name of the component that already generates the class. + final String conflictingComponent, +) implements Exception { + /// {@macro component_class_conflict_exception} + this; +} + +/// {@template generated_file_conflict_exception} +/// Thrown when the code of a [Component] would overwrite a file that was +/// not generated by the editor. +/// {@endtemplate} +class const GeneratedFileConflictException( + /// The path of the file that was kept. + final String path, +) implements Exception { + /// {@macro generated_file_conflict_exception} + this; +} + +/// {@template invalid_palette_exception} +/// Thrown when saving a [Palette] with a color name that can't be used, +/// see [Palette.validateColorName]. +/// {@endtemplate} +class const InvalidPaletteException( + /// The rejected palette. + final Palette palette, +) implements Exception { + /// {@macro invalid_palette_exception} + this; +} + +/// {@template component_repository} +/// Lists, creates, saves and deletes the components of a project. +/// +/// Each component is stored as `.json` inside the +/// [componentsDirectory] of the project folder, and its Dart code is +/// generated by the [ComponentCodeGenerator] inside the output folder of +/// the project. +/// +/// The [Palette] shared by the components is stored in the [paletteFile] +/// of the project folder, and its Dart code is generated by the +/// [PaletteCodeGenerator] in the same output folder as the components. +/// {@endtemplate} +class ComponentRepository({ + required final FileSystemClient _fileSystem, + final ComponentCodeGenerator _codeGenerator = const ComponentCodeGenerator(), + final PaletteCodeGenerator _paletteCodeGenerator = + const PaletteCodeGenerator(), +}) { + /// {@macro component_repository} + this; + + /// Folder, relative to the project folder, where components are stored. + static const componentsDirectory = '.flame_studio/components'; + + /// File, relative to the project folder, where the palette is stored. + static const paletteFile = '.flame_studio/palette.json'; + + static final _validName = RegExp(r'^[A-Za-z_][A-Za-z0-9_]*$'); + + /// Returns the components of the project at [projectPath], sorted by name. + /// + /// Component files that cannot be read are skipped. + Future> getComponents(String projectPath) async { + final files = await _fileSystem.listFiles( + _directory(projectPath), + extension: '.json', + ); + + final components = []; + for (final file in files) { + try { + final json = jsonDecode(await _fileSystem.readFile(file)); + components.add(Component.fromJson(json as Map)); + } on Object { + continue; + } + } + return components..sort((a, b) => a.name.compareTo(b.name)); + } + + /// Creates a component of [type] called [name], with default properties, + /// in the project at [projectPath]. Polygons start with the vertices of + /// [polygonShape]. + /// + /// Throws an [InvalidComponentNameException] if [name] is not a valid + /// identifier or doesn't make a valid class name (such as `_1`), or if + /// its code would take the place of the palette's (`palette`), or a + /// [ComponentAlreadyExistsException] if a component with that name, or + /// one that generates the same file (such as `playerShip` and + /// `PlayerShip`), already exists. Throws a + /// [ComponentClassConflictException] if another component already + /// generates its class (see [ComponentTree.generatedClassNames]). + /// + /// Hitboxes ([ComponentType.isHitbox]) can only be children, so [type] + /// can't be one: that throws an [ArgumentError]. + Future createComponent( + String projectPath, + String name, + ComponentType type, { + PolygonShape polygonShape = PolygonShape.triangle, + }) async { + if (type.isHitbox) { + throw ArgumentError.value(type, 'type', 'Hitboxes can only be children'); + } + final className = dartClassName(name); + final fileName = dartFileName(name); + if (!_validName.hasMatch(name) || + !isDartIdentifier(className) || + fileName == PaletteCodeGenerator.baseName) { + throw InvalidComponentNameException(name); + } + + final existing = await _fileSystem.listFiles( + _directory(projectPath), + extension: '.json', + ); + if (existing.any( + (file) => dartFileName(p.basenameWithoutExtension(file)) == fileName, + )) { + throw ComponentAlreadyExistsException(name); + } + + final rootClass = dartRootClassName(name); + for (final other in await getComponents(projectPath)) { + if (other.generatedClassNames.contains(rootClass)) { + throw ComponentClassConflictException(name, other.name); + } + } + + final component = Component.create(name, type, polygonShape: polygonShape); + await _write(projectPath, component); + return component; + } + + /// Saves [component] in the project at [projectPath], replacing the + /// previously stored version. + Future saveComponent(String projectPath, Component component) { + return _write(projectPath, component); + } + + /// Writes the Dart code of [component] to the folder [outputPath], + /// relative to the project at [projectPath], replacing the previously + /// generated code. + /// + /// Paints that use colors of the project's palette reference them, so + /// the code of the palette is written too, keeping the reference valid. + /// + /// Throws a [GeneratedFileConflictException] if the file exists but was + /// not generated by the editor, or is the palette's (a component named + /// `palette` created before the name was reserved); it is never + /// overwritten. + Future writeComponentCode( + String projectPath, + String outputPath, + Component component, + ) async { + final path = _codeFile(projectPath, outputPath, component); + if (_codeGenerator.fileName(component) == PaletteCodeGenerator.fileName) { + throw GeneratedFileConflictException(path); + } + await _writeGenerated(path, () async { + final palette = await getPalette(projectPath); + if (component.usedPaletteColors.any(palette.contains)) { + await writePaletteCode(projectPath, outputPath, palette); + } + return _codeGenerator.generate(component, palette: palette); + }); + } + + /// Returns the palette of the project at [projectPath]. + /// + /// Returns an empty palette if none was saved or the stored data is + /// unreadable. + Future getPalette(String projectPath) async { + final path = p.join(projectPath, paletteFile); + try { + if (!await _fileSystem.fileExists(path)) { + return const Palette(); + } + return Palette.fromJson(jsonDecode(await _fileSystem.readFile(path))); + } on Object { + return const Palette(); + } + } + + /// Saves [palette] as the palette of the project at [projectPath]. + /// + /// Throws an [InvalidPaletteException] if a color has a name that can't + /// be used (see [Palette.validateColorName]). + Future savePalette(String projectPath, Palette palette) async { + if (!palette.isValid) { + throw InvalidPaletteException(palette); + } + await _fileSystem.writeFile( + p.join(projectPath, paletteFile), + jsonEncode(palette.toJson()), + ); + } + + /// Writes the Dart code of [palette] to the folder [outputPath], relative + /// to the project at [projectPath], replacing the previously generated + /// code. + /// + /// Throws a [GeneratedFileConflictException] if the file exists but was + /// not generated by the editor; it is never overwritten. + Future writePaletteCode( + String projectPath, + String outputPath, + Palette palette, + ) { + return _writeGenerated( + p.join(projectPath, outputPath, PaletteCodeGenerator.fileName), + () async => _paletteCodeGenerator.generate(palette), + ); + } + + /// Writes the code built by [generate] to [path], unless a file that was + /// not generated by the editor is there. + Future _writeGenerated( + String path, + Future Function() generate, + ) async { + if (await _fileSystem.fileExists(path) && !await _isGenerated(path)) { + throw GeneratedFileConflictException(path); + } + await _fileSystem.writeFile(path, await generate()); + } + + /// Whether the folder [outputPath], relative to the project at + /// [projectPath], holds the code currently generated for [component]. + /// + /// It doesn't when the code was never generated, was generated for an + /// older version of the component, or the file in its place was not + /// generated by the editor. + Future isComponentCodeUpToDate( + String projectPath, + String outputPath, + Component component, + ) async { + final path = _codeFile(projectPath, outputPath, component); + if (!await _fileSystem.fileExists(path)) { + return false; + } + final palette = await getPalette(projectPath); + return await _fileSystem.readFile(path) == + _codeGenerator.generate(component, palette: palette); + } + + /// Deletes [component] from the project at [projectPath], along with its + /// generated code in the folder [outputPath]. + /// + /// A file in place of the generated code that was not generated by the + /// editor is kept. + Future deleteComponent( + String projectPath, + Component component, { + required String outputPath, + }) async { + await _fileSystem.deleteFile(_file(projectPath, component.name)); + final code = _codeFile(projectPath, outputPath, component); + if (await _fileSystem.fileExists(code) && await _isGenerated(code)) { + await _fileSystem.deleteFile(code); + } + } + + Future _isGenerated(String path) async { + final contents = await _fileSystem.readFile(path); + return contents.startsWith(ComponentCodeGenerator.header); + } + + String _codeFile(String projectPath, String outputPath, Component component) { + return p.join(projectPath, outputPath, _codeGenerator.fileName(component)); + } + + Future _write(String projectPath, Component component) { + return _fileSystem.writeFile( + _file(projectPath, component.name), + jsonEncode(component.toJson()), + ); + } + + String _directory(String projectPath) => + p.join(projectPath, componentsDirectory); + + String _file(String projectPath, String name) => + p.join(_directory(projectPath), '$name.json'); +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/circle_component.dart b/packages/flame_studio/lib/repositories/component_repository/models/circle_component.dart new file mode 100644 index 00000000000..e2a0813cf29 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/circle_component.dart @@ -0,0 +1,113 @@ +part of 'component.dart'; + +/// {@template circle_component} +/// A circle with a position, an anchor, an angle, a radius and a paint. +/// {@endtemplate} +final class const CircleComponent({ + required super.name, + @override final ComponentPosition position = const ComponentPosition(), + @override final ComponentAnchor anchor = ComponentAnchor.topLeft, + @override final ComponentAngle angle = ComponentAngle.zero, + @override final ComponentRadius radius = const ComponentRadius(), + @override final ComponentPaint paint = const ComponentPaint(), + super.children, +}) extends Component + implements + PositionedComponent, + AnchoredComponent, + RotatedComponent, + RadiusComponent, + PaintedComponent { + /// {@macro circle_component} + this; + + /// Reads the properties of a [CircleComponent] from its JSON + /// representation. Use [Component.fromJson], which also reads the + /// children. + factory _fromJson(Map json) { + return CircleComponent( + name: json['name'] as String, + position: ComponentPosition.fromJson(json['position']), + anchor: ComponentAnchor.fromJson(json['anchor']), + angle: ComponentAngle.fromJson(json['angle']), + radius: ComponentRadius.fromJson(json['radius']), + paint: ComponentPaint.fromJson(json['paint']), + ); + } + + @override + ComponentType get type => ComponentType.circle; + + @override + CircleComponent copyWithPosition(ComponentPosition position) { + return _copyWith(position: position); + } + + @override + CircleComponent copyWithAnchor(ComponentAnchor anchor) { + return _copyWith(anchor: anchor); + } + + @override + CircleComponent copyWithAngle(ComponentAngle angle) { + return _copyWith(angle: angle); + } + + @override + CircleComponent copyWithRadius(ComponentRadius radius) { + return _copyWith(radius: radius); + } + + @override + CircleComponent copyWithPaint(ComponentPaint paint) { + return _copyWith(paint: paint); + } + + @override + CircleComponent copyWithName(String name) => _copyWith(name: name); + + @override + CircleComponent copyWithChildren(List children) { + return _copyWith(children: children); + } + + CircleComponent _copyWith({ + String? name, + ComponentPosition? position, + ComponentAnchor? anchor, + ComponentAngle? angle, + ComponentRadius? radius, + ComponentPaint? paint, + List? children, + }) { + return CircleComponent( + name: name ?? this.name, + position: position ?? this.position, + anchor: anchor ?? this.anchor, + angle: angle ?? this.angle, + radius: radius ?? this.radius, + paint: paint ?? this.paint, + children: children ?? this.children, + ); + } + + @override + Map toJson() => { + ...super.toJson(), + 'position': position.toJson(), + 'anchor': anchor.toJson(), + 'angle': angle.toJson(), + 'radius': radius.toJson(), + 'paint': paint.toJson(), + }; + + @override + List get props => [ + ...super.props, + position, + anchor, + angle, + radius, + paint, + ]; +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/circle_hitbox_component.dart b/packages/flame_studio/lib/repositories/component_repository/models/circle_hitbox_component.dart new file mode 100644 index 00000000000..4e32b5894ae --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/circle_hitbox_component.dart @@ -0,0 +1,114 @@ +part of 'component.dart'; + +/// {@template circle_hitbox_component} +/// A round hitbox with a position, an anchor, an angle, a radius and a +/// collision. +/// {@endtemplate} +final class const CircleHitboxComponent({ + required super.name, + @override final ComponentPosition position = const ComponentPosition(), + @override final ComponentAnchor anchor = ComponentAnchor.topLeft, + @override final ComponentAngle angle = ComponentAngle.zero, + @override final ComponentRadius radius = const ComponentRadius(), + @override final ComponentCollision collision = const ComponentCollision(), + super.children, +}) extends Component + implements + PositionedComponent, + AnchoredComponent, + RotatedComponent, + RadiusComponent, + HitboxComponent { + /// {@macro circle_hitbox_component} + this; + + /// Reads the properties of a [CircleHitboxComponent] from its JSON + /// representation. Use [Component.fromJson], which also reads the + /// children. + factory _fromJson(Map json) { + return CircleHitboxComponent( + name: json['name'] as String, + position: ComponentPosition.fromJson(json['position']), + anchor: ComponentAnchor.fromJson(json['anchor']), + angle: ComponentAngle.fromJson(json['angle']), + radius: ComponentRadius.fromJson(json['radius']), + collision: ComponentCollision.fromJson(json['collision']), + ); + } + + @override + ComponentType get type => ComponentType.circleHitbox; + + @override + CircleHitboxComponent copyWithPosition(ComponentPosition position) { + return _copyWith(position: position); + } + + @override + CircleHitboxComponent copyWithAnchor(ComponentAnchor anchor) { + return _copyWith(anchor: anchor); + } + + @override + CircleHitboxComponent copyWithAngle(ComponentAngle angle) { + return _copyWith(angle: angle); + } + + @override + CircleHitboxComponent copyWithRadius(ComponentRadius radius) { + return _copyWith(radius: radius); + } + + @override + CircleHitboxComponent copyWithCollision(ComponentCollision collision) { + return _copyWith(collision: collision); + } + + @override + CircleHitboxComponent copyWithName(String name) => _copyWith(name: name); + + @override + CircleHitboxComponent copyWithChildren(List children) { + return _copyWith(children: children); + } + + CircleHitboxComponent _copyWith({ + String? name, + ComponentPosition? position, + ComponentAnchor? anchor, + ComponentAngle? angle, + ComponentRadius? radius, + ComponentCollision? collision, + List? children, + }) { + return CircleHitboxComponent( + name: name ?? this.name, + position: position ?? this.position, + anchor: anchor ?? this.anchor, + angle: angle ?? this.angle, + radius: radius ?? this.radius, + collision: collision ?? this.collision, + children: children ?? this.children, + ); + } + + @override + Map toJson() => { + ...super.toJson(), + 'position': position.toJson(), + 'anchor': anchor.toJson(), + 'angle': angle.toJson(), + 'radius': radius.toJson(), + 'collision': collision.toJson(), + }; + + @override + List get props => [ + ...super.props, + position, + anchor, + angle, + radius, + collision, + ]; +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/component.dart b/packages/flame_studio/lib/repositories/component_repository/models/component.dart new file mode 100644 index 00000000000..85e2cf2f412 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/component.dart @@ -0,0 +1,105 @@ +import 'package:equatable/equatable.dart'; +import 'package:flame_studio/repositories/repositories.dart'; + +part 'circle_component.dart'; +part 'circle_hitbox_component.dart'; +part 'polygon_component.dart'; +part 'polygon_hitbox_component.dart'; +part 'position_component.dart'; +part 'rectangle_component.dart'; +part 'rectangle_hitbox_component.dart'; + +/// {@template component} +/// A Flame component definition that belongs to a project. +/// +/// Each subclass is one [ComponentType]. The properties a component has are +/// declared through capability interfaces such as [SizedComponent] and +/// [PaintedComponent], so that editors can be shared between types. +/// +/// Like in Flame, a component can have [children]; see [ComponentTree] to +/// navigate and edit them. +/// {@endtemplate} +sealed class const Component({ + /// The component name. + /// + /// The root component name is used as its class name. + required final String name, + + /// The components added to this one. + final List children = const [], +}) extends Equatable { + /// {@macro component} + this; + + /// Creates a component of [type] called [name] with default properties. + /// + /// Polygons and polygon hitboxes start with the vertices of + /// [polygonShape]. + factory create( + String name, + ComponentType type, { + PolygonShape polygonShape = PolygonShape.triangle, + }) { + return switch (type) { + ComponentType.rectangle => RectangleComponent(name: name), + ComponentType.position => PositionComponent(name: name), + ComponentType.circle => CircleComponent(name: name), + ComponentType.polygon => PolygonComponent( + name: name, + vertices: ComponentVertices(polygonShape.vertices), + ), + ComponentType.rectangleHitbox => RectangleHitboxComponent(name: name), + ComponentType.circleHitbox => CircleHitboxComponent(name: name), + ComponentType.polygonHitbox => PolygonHitboxComponent( + name: name, + vertices: ComponentVertices(polygonShape.vertices), + ), + }; + } + + /// Creates a [Component] from its JSON representation. + /// + /// Components saved without a type are read as rectangles. The children + /// are read here, for every type, so subtypes only read their own + /// properties. + factory fromJson(Map json) { + final type = ComponentType.fromKey(json['type']) ?? ComponentType.rectangle; + final component = switch (type) { + ComponentType.rectangle => RectangleComponent._fromJson(json), + ComponentType.position => PositionComponent._fromJson(json), + ComponentType.circle => CircleComponent._fromJson(json), + ComponentType.polygon => PolygonComponent._fromJson(json), + ComponentType.rectangleHitbox => RectangleHitboxComponent._fromJson(json), + ComponentType.circleHitbox => CircleHitboxComponent._fromJson(json), + ComponentType.polygonHitbox => PolygonHitboxComponent._fromJson(json), + }; + return component.copyWithChildren(_childrenFromJson(json['children'])); + } + + static List _childrenFromJson(Object? json) { + return [ + if (json is List) + for (final child in json) + if (child is Map) Component.fromJson(child), + ]; + } + + /// The type of this component. + ComponentType get type; + + /// Returns a copy of this component called [name]. + Component copyWithName(String name); + + /// Returns a copy of this component with [children] replaced. + Component copyWithChildren(List children); + + /// Converts this component to its JSON representation. + Map toJson() => { + 'name': name, + 'type': type.key, + 'children': [for (final child in children) child.toJson()], + }; + + @override + List get props => [name, type, children]; +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/component_anchor.dart b/packages/flame_studio/lib/repositories/component_repository/models/component_anchor.dart new file mode 100644 index 00000000000..ede6430bc56 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/component_anchor.dart @@ -0,0 +1,98 @@ +import 'package:equatable/equatable.dart'; + +/// {@template component_anchor} +/// The anchor property shared by every position based component. +/// +/// Mirrors Flame's `Anchor`: the point of the component, relative to its +/// size, that is placed at its position. `(0, 0)` is the top left corner +/// (Flame's default) and `(1, 1)` the bottom right one. Values outside of +/// that range are allowed, like in Flame. +/// {@endtemplate} +class const ComponentAnchor({ + /// The horizontal coordinate, relative to the width. + final double x = 0, + + /// The vertical coordinate, relative to the height. + final double y = 0, +}) extends Equatable { + /// {@macro component_anchor} + this; + + /// Creates a [ComponentAnchor] from its JSON representation. + /// + /// Missing or invalid values fall back to `0`, so components saved without + /// an anchor are anchored at their top left corner. + factory fromJson(Object? json) { + final map = json is Map ? json : const {}; + return ComponentAnchor( + x: _readCoordinate(map['x']), + y: _readCoordinate(map['y']), + ); + } + + /// The top left corner, Flame's default anchor. + static const topLeft = ComponentAnchor(); + + /// The center of the top edge. + static const topCenter = ComponentAnchor(x: 0.5); + + /// The top right corner. + static const topRight = ComponentAnchor(x: 1); + + /// The center of the left edge. + static const centerLeft = ComponentAnchor(y: 0.5); + + /// The center of the component. + static const center = ComponentAnchor(x: 0.5, y: 0.5); + + /// The center of the right edge. + static const centerRight = ComponentAnchor(x: 1, y: 0.5); + + /// The bottom left corner. + static const bottomLeft = ComponentAnchor(y: 1); + + /// The center of the bottom edge. + static const bottomCenter = ComponentAnchor(x: 0.5, y: 1); + + /// The bottom right corner. + static const bottomRight = ComponentAnchor(x: 1, y: 1); + + /// Flame's named anchors by name, row by row from the top left corner. + static const Map presets = { + 'topLeft': topLeft, + 'topCenter': topCenter, + 'topRight': topRight, + 'centerLeft': centerLeft, + 'center': center, + 'centerRight': centerRight, + 'bottomLeft': bottomLeft, + 'bottomCenter': bottomCenter, + 'bottomRight': bottomRight, + }; + + /// The name of the Flame anchor equal to this one (such as `center`), or + /// `null` for a custom anchor. + String? get presetName { + for (final MapEntry(:key, :value) in presets.entries) { + if (value == this) { + return key; + } + } + return null; + } + + /// Returns a copy of this anchor with the given fields replaced. + ComponentAnchor copyWith({double? x, double? y}) { + return ComponentAnchor(x: x ?? this.x, y: y ?? this.y); + } + + /// Converts this anchor to its JSON representation. + Map toJson() => {'x': x, 'y': y}; + + static double _readCoordinate(Object? value) { + return value is num ? value.toDouble() : 0; + } + + @override + List get props => [x, y]; +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/component_angle.dart b/packages/flame_studio/lib/repositories/component_repository/models/component_angle.dart new file mode 100644 index 00000000000..18aadca652c --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/component_angle.dart @@ -0,0 +1,49 @@ +import 'dart:math' as math; + +import 'package:equatable/equatable.dart'; + +/// {@template component_angle} +/// The angle property shared by every position based component. +/// +/// Mirrors Flame's `angle`: the rotation of the component around its +/// anchor, in radians, clockwise. The editor shows it in [degrees]. +/// {@endtemplate} +class const ComponentAngle({ + /// The angle, in radians. + final double radians = 0, +}) extends Equatable { + /// {@macro component_angle} + this; + + /// Creates a [ComponentAngle] of [degrees]. + factory fromDegrees(double degrees) { + return ComponentAngle(radians: degrees * math.pi / 180); + } + + /// Creates a [ComponentAngle] from its JSON representation. + /// + /// A missing or invalid value falls back to `0`, so components saved + /// without an angle are not rotated. + factory fromJson(Object? json) { + final map = json is Map ? json : const {}; + final radians = map['radians']; + return ComponentAngle(radians: radians is num ? radians.toDouble() : 0); + } + + /// No rotation, Flame's default angle. + static const zero = ComponentAngle(); + + /// The angle, in degrees. + double get degrees => radians * 180 / math.pi; + + /// Returns a copy of this angle with the given fields replaced. + ComponentAngle copyWith({double? radians}) { + return ComponentAngle(radians: radians ?? this.radians); + } + + /// Converts this angle to its JSON representation. + Map toJson() => {'radians': radians}; + + @override + List get props => [radians]; +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/component_capabilities.dart b/packages/flame_studio/lib/repositories/component_repository/models/component_capabilities.dart new file mode 100644 index 00000000000..f908cd5e477 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/component_capabilities.dart @@ -0,0 +1,121 @@ +import 'package:flame_studio/repositories/repositories.dart'; + +/// A [Component] that has a [ComponentPosition]. +/// +/// Implemented by every component type backed by a Flame +/// `PositionComponent`. The position is only edited on child components: +/// the root is placed by whoever uses it. +abstract interface class PositionedComponent() { + /// Creates a [PositionedComponent]. + this; + + /// The position of the component, relative to its parent. + ComponentPosition get position; + + /// Returns a copy of this component with [position] replaced. + Component copyWithPosition(ComponentPosition position); +} + +/// A [Component] that has a [ComponentAnchor]. +/// +/// Implemented by every component type backed by a Flame +/// `PositionComponent`. Like the position, the anchor is only edited on +/// child components: the root is placed by whoever uses it. +abstract interface class AnchoredComponent() { + /// Creates an [AnchoredComponent]. + this; + + /// The point of the component that is placed at its position. + ComponentAnchor get anchor; + + /// Returns a copy of this component with [anchor] replaced. + Component copyWithAnchor(ComponentAnchor anchor); +} + +/// A [Component] that has a [ComponentAngle]. +/// +/// Implemented by every component type backed by a Flame +/// `PositionComponent`. Like the position, the angle is only edited on +/// child components: the root is placed by whoever uses it. +abstract interface class RotatedComponent() { + /// Creates a [RotatedComponent]. + this; + + /// The rotation of the component around its anchor. + ComponentAngle get angle; + + /// Returns a copy of this component with [angle] replaced. + Component copyWithAngle(ComponentAngle angle); +} + +/// A [Component] that has a [ComponentSize]. +/// +/// Implemented by every component type backed by a Flame +/// `PositionComponent`. +abstract interface class SizedComponent() { + /// Creates a [SizedComponent]. + this; + + /// The size of the component. + ComponentSize get size; + + /// Returns a copy of this component with [size] replaced. + Component copyWithSize(ComponentSize size); +} + +/// A [Component] that draws with a [ComponentPaint]. +abstract interface class PaintedComponent() { + /// Creates a [PaintedComponent]. + this; + + /// The paint of the component. + ComponentPaint get paint; + + /// Returns a copy of this component with [paint] replaced. + Component copyWithPaint(ComponentPaint paint); +} + +/// A [Component] that has a [ComponentRadius]. +/// +/// Implemented by round component types, such as circles, whose Flame size +/// is derived from the radius. +abstract interface class RadiusComponent() { + /// Creates a [RadiusComponent]. + this; + + /// The radius of the component. + ComponentRadius get radius; + + /// Returns a copy of this component with [radius] replaced. + Component copyWithRadius(ComponentRadius radius); +} + +/// A [Component] that has [ComponentVertices]. +/// +/// Implemented by polygon component types, whose Flame size is the +/// bounding box of the vertices. +abstract interface class VerticesComponent() { + /// Creates a [VerticesComponent]. + this; + + /// The vertices of the component. + ComponentVertices get vertices; + + /// Returns a copy of this component with [vertices] replaced. + Component copyWithVertices(ComponentVertices vertices); +} + +/// A [Component] that is a Flame hitbox, with a [ComponentCollision]. +/// +/// Hitboxes are only children, and have no children of their own: Flame +/// requires a hitbox to be inside a `PositionComponent`. +abstract interface class HitboxComponent() { + /// Creates a [HitboxComponent]. + this; + + /// How the hitbox collides with others. + ComponentCollision get collision; + + /// Returns a copy of this component with [collision] replaced. + Component copyWithCollision(ComponentCollision collision); +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/component_collision.dart b/packages/flame_studio/lib/repositories/component_repository/models/component_collision.dart new file mode 100644 index 00000000000..a4afdcd01c5 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/component_collision.dart @@ -0,0 +1,72 @@ +import 'package:equatable/equatable.dart'; + +/// Which other hitboxes a hitbox collides with. +/// +/// Mirrors Flame's `CollisionType` without depending on Flame. +enum HitboxCollisionType({ + /// Human readable name. + required final String label, +}) { + /// Collides with active and passive hitboxes. + active(label: 'Active'), + + /// Collides with active hitboxes only. + passive(label: 'Passive'), + + /// Doesn't collide with any hitbox. + inactive(label: 'Inactive'); + + /// Returns the type called [name], or `null` if there is none. + static HitboxCollisionType? fromName(Object? name) { + for (final type in values) { + if (type.name == name) { + return type; + } + } + return null; + } +} + +/// {@template component_collision} +/// The collision property shared by every hitbox: its collision [type] and +/// whether it [isSolid]. +/// {@endtemplate} +class const ComponentCollision({ + /// Which other hitboxes the hitbox collides with. + final HitboxCollisionType type = HitboxCollisionType.active, + + /// Whether the hitbox also collides with hitboxes fully inside it, rather + /// than only with those crossing its edges. + final bool isSolid = false, +}) extends Equatable { + /// {@macro component_collision} + this; + + /// Creates a [ComponentCollision] from its JSON representation. + /// + /// Missing or invalid values fall back to their defaults. + factory fromJson(Object? json) { + final map = json is Map ? json : const {}; + final isSolid = map['isSolid']; + return ComponentCollision( + type: + HitboxCollisionType.fromName(map['type']) ?? + HitboxCollisionType.active, + isSolid: isSolid is bool && isSolid, + ); + } + + /// Returns a copy of this collision with the given fields replaced. + ComponentCollision copyWith({HitboxCollisionType? type, bool? isSolid}) { + return ComponentCollision( + type: type ?? this.type, + isSolid: isSolid ?? this.isSolid, + ); + } + + /// Converts this collision to its JSON representation. + Map toJson() => {'type': type.name, 'isSolid': isSolid}; + + @override + List get props => [type, isSolid]; +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/component_paint.dart b/packages/flame_studio/lib/repositories/component_repository/models/component_paint.dart new file mode 100644 index 00000000000..559146b6f88 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/component_paint.dart @@ -0,0 +1,78 @@ +import 'package:equatable/equatable.dart'; +import 'package:flame_studio/repositories/repositories.dart'; + +/// {@template component_paint} +/// The paint property shared by every component that draws with a paint. +/// +/// Its color is either picked by hand or a [paletteColor] of the project's +/// [Palette], in which case [color] keeps its last known value, used when +/// the palette doesn't have it. +/// {@endtemplate} +class const ComponentPaint({ + /// The color as a 32 bit ARGB value. + /// + /// When [paletteColor] is set, the value it had when it was last picked. + final int color = defaultColor, + + /// Whether the shape is filled or stroked. + final PaintStyle style = PaintStyle.fill, + + /// The name of the [Palette] color this paint uses, or `null` when its + /// [color] was picked by hand. + final String? paletteColor, +}) extends Equatable { + /// {@macro component_paint} + this; + + /// Creates a [ComponentPaint] from its JSON representation. + /// + /// Missing or invalid values fall back to their defaults. + factory fromJson(Object? json) { + final map = json is Map ? json : const {}; + final color = map['color']; + final paletteColor = map['paletteColor']; + return ComponentPaint( + color: color is int ? color : defaultColor, + style: PaintStyle.fromName(map['style']) ?? PaintStyle.fill, + paletteColor: paletteColor is String ? paletteColor : null, + ); + } + + /// The default [color]: opaque white. + static const defaultColor = 0xFFFFFFFF; + + /// The color to draw with: the [paletteColor] in [palette], or [color] + /// when there is none. + int resolvedColor(Palette palette) => palette.colorOf(paletteColor) ?? color; + + /// Returns a copy of this paint with the given fields replaced. + ComponentPaint copyWith({int? color, PaintStyle? style}) { + return ComponentPaint( + color: color ?? this.color, + style: style ?? this.style, + paletteColor: paletteColor, + ); + } + + /// Returns a copy of this paint with [color] picked by hand, which no + /// longer uses a palette color. + ComponentPaint withColor(int color) { + return ComponentPaint(color: color, style: style); + } + + /// Returns a copy of this paint that uses the palette color called + /// [name], whose current value is [color]. + ComponentPaint withPaletteColor(String name, int color) { + return ComponentPaint(color: color, style: style, paletteColor: name); + } + + /// Converts this paint to its JSON representation. + Map toJson() => { + 'color': color, + 'style': style.name, + 'paletteColor': ?paletteColor, + }; + + @override + List get props => [color, style, paletteColor]; +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/component_position.dart b/packages/flame_studio/lib/repositories/component_repository/models/component_position.dart new file mode 100644 index 00000000000..4e84464c249 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/component_position.dart @@ -0,0 +1,43 @@ +import 'package:equatable/equatable.dart'; + +/// {@template component_position} +/// The position property shared by every position based component. +/// +/// The position is relative to the parent component. +/// {@endtemplate} +class const ComponentPosition({ + /// The horizontal coordinate. + final double x = 0, + + /// The vertical coordinate. + final double y = 0, +}) extends Equatable { + /// {@macro component_position} + this; + + /// Creates a [ComponentPosition] from its JSON representation. + /// + /// Missing or invalid values fall back to `0`. + factory fromJson(Object? json) { + final map = json is Map ? json : const {}; + return ComponentPosition( + x: _readCoordinate(map['x']), + y: _readCoordinate(map['y']), + ); + } + + /// Returns a copy of this position with the given fields replaced. + ComponentPosition copyWith({double? x, double? y}) { + return ComponentPosition(x: x ?? this.x, y: y ?? this.y); + } + + /// Converts this position to its JSON representation. + Map toJson() => {'x': x, 'y': y}; + + static double _readCoordinate(Object? value) { + return value is num ? value.toDouble() : 0; + } + + @override + List get props => [x, y]; +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/component_radius.dart b/packages/flame_studio/lib/repositories/component_repository/models/component_radius.dart new file mode 100644 index 00000000000..e704df487bf --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/component_radius.dart @@ -0,0 +1,38 @@ +import 'package:equatable/equatable.dart'; + +/// {@template component_radius} +/// The radius property shared by every round component. +/// {@endtemplate} +class const ComponentRadius({ + /// The radius. + final double radius = defaultValue, +}) extends Equatable { + /// {@macro component_radius} + this; + + /// Creates a [ComponentRadius] from its JSON representation. + /// + /// A missing or invalid value falls back to [defaultValue]. + factory fromJson(Object? json) { + final map = json is Map ? json : const {}; + final radius = map['radius']; + return ComponentRadius( + radius: radius is num && radius >= 0 ? radius.toDouble() : defaultValue, + ); + } + + /// The default [radius], so that a default circle is as big as a default + /// rectangle. + static const defaultValue = 25.0; + + /// Returns a copy of this radius with the given fields replaced. + ComponentRadius copyWith({double? radius}) { + return ComponentRadius(radius: radius ?? this.radius); + } + + /// Converts this radius to its JSON representation. + Map toJson() => {'radius': radius}; + + @override + List get props => [radius]; +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/component_size.dart b/packages/flame_studio/lib/repositories/component_repository/models/component_size.dart new file mode 100644 index 00000000000..de606ad79d1 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/component_size.dart @@ -0,0 +1,47 @@ +import 'package:equatable/equatable.dart'; + +/// {@template component_size} +/// The size property shared by every position based component. +/// {@endtemplate} +class const ComponentSize({ + /// The width. + final double width = defaultValue, + + /// The height. + final double height = defaultValue, +}) extends Equatable { + /// {@macro component_size} + this; + + /// Creates a [ComponentSize] from its JSON representation. + /// + /// Missing or invalid values fall back to [defaultValue]. + factory fromJson(Object? json) { + final map = json is Map ? json : const {}; + return ComponentSize( + width: _readDimension(map['width']), + height: _readDimension(map['height']), + ); + } + + /// The default [width] and [height]. + static const defaultValue = 50.0; + + /// Returns a copy of this size with the given fields replaced. + ComponentSize copyWith({double? width, double? height}) { + return ComponentSize( + width: width ?? this.width, + height: height ?? this.height, + ); + } + + /// Converts this size to its JSON representation. + Map toJson() => {'width': width, 'height': height}; + + static double _readDimension(Object? value) { + return value is num && value >= 0 ? value.toDouble() : defaultValue; + } + + @override + List get props => [width, height]; +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/component_tree.dart b/packages/flame_studio/lib/repositories/component_repository/models/component_tree.dart new file mode 100644 index 00000000000..bae59e53b98 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/component_tree.dart @@ -0,0 +1,235 @@ +import 'package:flame_studio/repositories/component_repository/code_generation/dart_names.dart'; +import 'package:flame_studio/repositories/repositories.dart'; + +/// Why a name can't be used for a child component, see +/// [ComponentTree.validateChildName]. +enum ChildNameError() { + /// The name is not a valid Dart identifier, or its getter would be a + /// Dart keyword. + invalid, + + /// The getter of the child would clash with a member of its parent's + /// Flame class, such as `size` or `position`. + reserved, + + /// Another component of the tree already uses the name. + duplicate, + + /// The class generated for the child would have the same name as a class + /// generated for another component of the project, see + /// [ComponentTree.generatedClassNames]. + conflict, +} + +/// Navigates and edits the tree formed by a [Component] and its children. +/// +/// A node of the tree is addressed by its path: the index of each child to +/// follow from the root. The root itself is the empty path. +extension ComponentTree on Component { + /// Returns the node at [path]. + /// + /// Throws a [RangeError] if there is no node at [path]. + Component nodeAt(List path) { + var node = this; + for (final index in path) { + node = node.children[index]; + } + return node; + } + + /// Whether there is a node at [path]. + bool hasNodeAt(List path) { + var node = this; + for (final index in path) { + if (index < 0 || index >= node.children.length) { + return false; + } + node = node.children[index]; + } + return true; + } + + /// Returns a copy of this tree where the node at [path] is replaced by the + /// result of [update]. + /// + /// Throws a [RangeError] if there is no node at [path]. + Component updateNodeAt( + List path, + Component Function(Component node) update, + ) { + if (path.isEmpty) { + return update(this); + } + final [index, ...rest] = path; + final children = [...this.children]; + children[index] = children[index].updateNodeAt(rest, update); + return copyWithChildren(children); + } + + /// Returns a copy of this tree with [child] added as the last child of the + /// node at [path]. + /// + /// Hitboxes ([HitboxComponent]) can't have children, and can't be added + /// to another hitbox. + Component addChildAt(List path, Component child) { + if (nodeAt(path) is HitboxComponent) { + throw ArgumentError.value(path, 'path', 'Hitboxes cannot have children'); + } + return updateNodeAt( + path, + (node) => node.copyWithChildren([...node.children, child]), + ); + } + + /// Returns a copy of this tree without the node at [path]. + /// + /// The root (the empty [path]) cannot be removed. + Component removeNodeAt(List path) { + if (path.isEmpty) { + throw ArgumentError.value(path, 'path', 'The root cannot be removed'); + } + final parent = path.sublist(0, path.length - 1); + return updateNodeAt( + parent, + (node) => node.copyWithChildren([...node.children]..removeAt(path.last)), + ); + } + + /// This component followed by all of its descendants, depth first. + Iterable get nodes sync* { + yield this; + for (final child in children) { + yield* child.nodes; + } + } + + /// The names of the [Palette] colors the nodes of this tree paint with. + Set get usedPaletteColors { + return { + for (final node in nodes) + if (node case PaintedComponent( + paint: ComponentPaint(:final String paletteColor), + )) + paletteColor, + }; + } + + /// Returns a copy of this tree whose paints have the current value of + /// their palette color in [palette] as their color (see + /// [ComponentPaint.resolvedColor]), which is what they draw with. + Component withPaletteColorsResolved(Palette palette) { + final node = switch (this) { + final PaintedComponent painted when painted.paint.paletteColor != null => + painted.copyWithPaint( + painted.paint.copyWith(color: painted.paint.resolvedColor(palette)), + ), + final node => node, + }; + if (children.isEmpty) { + return node; + } + return node.copyWithChildren([ + for (final child in node.children) + child.withPaletteColorsResolved(palette), + ]); + } + + /// The name of the class generated for this component as the root of its + /// tree, such as `$PlayerShip`. + String get generatedClassName => dartRootClassName(name); + + /// The names of the classes this component reserves in the generated + /// code: the class of the root, and the class of every child. + /// + /// Only children that have children of their own get a class, but every + /// child reserves one, so adding children to a node never makes its class + /// clash with the classes of another component. Generated classes are + /// public, so the classes of two components of a project must not share + /// names, or a library importing both wouldn't compile. + Set get generatedClassNames { + return { + generatedClassName, + for (final node in nodes.skip(1)) dartChildClassName(name, node.name), + }; + } + + /// Returns a name for a new [type] node that no node of the tree uses + /// yet, such as `rectangle1`, and whose class is not one of + /// [takenClassNames] (see [generatedClassNames]). + String uniqueChildName( + ComponentType type, { + Set takenClassNames = const {}, + }) { + final names = {for (final node in nodes) dartMemberName(node.name)}; + var index = 1; + while (names.contains('${type.key}$index') || + takenClassNames.contains( + dartChildClassName(name, '${type.key}$index'), + )) { + index++; + } + return '${type.key}$index'; + } + + /// Returns why the node at [path] can't be renamed to [name], or `null` + /// if it can. + /// + /// The name of a child becomes the name of its getter in the generated + /// code, so it must be a valid getter of its parent and unique in the + /// tree, ignoring the differences the generated code ignores (`left_arm` + /// and `leftArm` are the same name). Its class must not be one of + /// [takenClassNames], the [generatedClassNames] of the other components + /// of the project. The root (the empty [path]) is not a child and can't + /// be validated. + ChildNameError? validateChildName( + List path, + String name, { + Set takenClassNames = const {}, + }) { + if (path.isEmpty) { + throw ArgumentError.value(path, 'path', 'The root is not a child'); + } + final getter = dartMemberName(name); + if (!isDartIdentifier(name) || + !isDartIdentifier(getter) || + isDartKeyword(getter)) { + return ChildNameError.invalid; + } + final parent = nodeAt(path.sublist(0, path.length - 1)); + if (flameMemberNames(parent.type).contains(getter)) { + return ChildNameError.reserved; + } + final taken = _getterNames(const [], except: path); + if (taken.contains(getter)) { + return ChildNameError.duplicate; + } + final className = dartChildClassName(this.name, name); + return takenClassNames.contains(className) ? ChildNameError.conflict : null; + } + + /// The getter names of this node, at [path], and its descendants, except + /// the node at [except]. + Iterable _getterNames( + List path, { + required List except, + }) sync* { + if (!_samePath(path, except)) { + yield dartMemberName(name); + } + for (final (index, child) in children.indexed) { + yield* child._getterNames([...path, index], except: except); + } + } + + static bool _samePath(List a, List b) { + if (a.length != b.length) { + return false; + } + for (var i = 0; i < a.length; i++) { + if (a[i] != b[i]) { + return false; + } + } + return true; + } +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/component_type.dart b/packages/flame_studio/lib/repositories/component_repository/models/component_type.dart new file mode 100644 index 00000000000..72a02c85a42 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/component_type.dart @@ -0,0 +1,53 @@ +/// The kinds of components the editor can create. +/// +/// Each value maps to a Flame component class. +enum ComponentType({ + /// The value stored in the component JSON. + required final String key, + + /// Human readable name. + required final String label, +}) { + /// A rectangle, backed by Flame's `RectangleComponent`. + rectangle(key: 'rectangle', label: 'Rectangle'), + + /// A plain component that draws nothing itself, backed by Flame's + /// `PositionComponent`. + position(key: 'position', label: 'Position'), + + /// A circle, backed by Flame's `CircleComponent`. + circle(key: 'circle', label: 'Circle'), + + /// A polygon, backed by Flame's `PolygonComponent`. + polygon(key: 'polygon', label: 'Polygon'), + + /// A rectangular hitbox, backed by Flame's `RectangleHitbox`. + rectangleHitbox(key: 'rectangleHitbox', label: 'Rectangle hitbox'), + + /// A round hitbox, backed by Flame's `CircleHitbox`. + circleHitbox(key: 'circleHitbox', label: 'Circle hitbox'), + + /// A polygonal hitbox, backed by Flame's `PolygonHitbox`. + polygonHitbox(key: 'polygonHitbox', label: 'Polygon hitbox'); + + /// Returns the type stored under [key], or `null` if there is none. + static ComponentType? fromKey(Object? key) { + for (final type in values) { + if (type.key == key) { + return type; + } + } + return null; + } + + /// Whether components of this type are hitboxes, which can only be + /// children and have no children of their own (see `HitboxComponent`). + bool get isHitbox => switch (this) { + rectangleHitbox || circleHitbox || polygonHitbox => true, + rectangle || position || circle || polygon => false, + }; + + /// Whether components of this type are shaped by vertices, and start + /// with a `PolygonShape`. + bool get hasVertices => this == polygon || this == polygonHitbox; +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/component_vertices.dart b/packages/flame_studio/lib/repositories/component_repository/models/component_vertices.dart new file mode 100644 index 00000000000..346c99d759c --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/component_vertices.dart @@ -0,0 +1,110 @@ +import 'dart:math' as math; + +import 'package:equatable/equatable.dart'; + +/// {@template component_vertex} +/// A vertex of a [ComponentVertices], in the local coordinates of its +/// component. +/// {@endtemplate} +class const ComponentVertex( + /// The horizontal coordinate. + final double x, + + /// The vertical coordinate. + final double y, +) extends Equatable { + /// {@macro component_vertex} + this; + + /// Converts this vertex to its JSON representation. + Map toJson() => {'x': x, 'y': y}; + + @override + List get props => [x, y]; +} + +/// {@template component_vertices} +/// The vertices property shared by every polygon based component. +/// +/// The vertices are in the local coordinates of the component, and the +/// component size is their bounding box. Like Flame, a polygon needs at +/// least [minLength] vertices. +/// {@endtemplate} +class const ComponentVertices([ + /// The vertices, in order. + final List vertices = defaultValue, +]) extends Equatable { + /// {@macro component_vertices} + this; + + /// Creates a [ComponentVertices] from its JSON representation. + /// + /// Missing or invalid values, or fewer than [minLength] valid vertices, + /// fall back to [defaultValue]. + factory fromJson(Object? json) { + final map = json is Map ? json : const {}; + final list = map['vertices']; + final vertices = [ + if (list is List) + for (final Object? vertex in list) + if (vertex case {'x': final num x, 'y': final num y}) + ComponentVertex(x.toDouble(), y.toDouble()), + ]; + return ComponentVertices( + vertices.length >= minLength ? vertices : defaultValue, + ); + } + + /// The fewest vertices a polygon can have. + static const minLength = 3; + + /// A triangle as big as a default rectangle. + static const triangle = [ + ComponentVertex(25, 0), + ComponentVertex(50, 50), + ComponentVertex(0, 50), + ]; + + /// A square as big as a default rectangle. + static const square = [ + ComponentVertex(0, 0), + ComponentVertex(50, 0), + ComponentVertex(50, 50), + ComponentVertex(0, 50), + ]; + + /// The default [vertices], a [triangle]. + static const List defaultValue = triangle; + + /// The width and height of the bounding box of the [vertices]. + ({double width, double height}) get bounds { + final xs = vertices.map((vertex) => vertex.x); + final ys = vertices.map((vertex) => vertex.y); + return ( + width: xs.reduce(math.max) - xs.reduce(math.min), + height: ys.reduce(math.max) - ys.reduce(math.min), + ); + } + + /// Returns these vertices moved so that the top left corner of their + /// bounding box is at the origin, like Flame places them. + ComponentVertices normalized() { + final left = vertices.map((vertex) => vertex.x).reduce(math.min); + final top = vertices.map((vertex) => vertex.y).reduce(math.min); + if (left == 0 && top == 0) { + return this; + } + return ComponentVertices([ + for (final vertex in vertices) + ComponentVertex(vertex.x - left, vertex.y - top), + ]); + } + + /// Converts these vertices to their JSON representation. + Map toJson() => { + 'vertices': [for (final vertex in vertices) vertex.toJson()], + }; + + @override + List get props => [vertices]; +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/models.dart b/packages/flame_studio/lib/repositories/component_repository/models/models.dart new file mode 100644 index 00000000000..5b69950f834 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/models.dart @@ -0,0 +1,15 @@ +export 'component.dart'; +export 'component_anchor.dart'; +export 'component_angle.dart'; +export 'component_capabilities.dart'; +export 'component_collision.dart'; +export 'component_paint.dart'; +export 'component_position.dart'; +export 'component_radius.dart'; +export 'component_size.dart'; +export 'component_tree.dart'; +export 'component_type.dart'; +export 'component_vertices.dart'; +export 'paint_style.dart'; +export 'palette.dart'; +export 'polygon_shape.dart'; diff --git a/packages/flame_studio/lib/repositories/component_repository/models/paint_style.dart b/packages/flame_studio/lib/repositories/component_repository/models/paint_style.dart new file mode 100644 index 00000000000..457acc51585 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/paint_style.dart @@ -0,0 +1,20 @@ +/// How a paint is applied to a shape. +/// +/// Mirrors `PaintingStyle` from `dart:ui` without depending on Flutter. +enum PaintStyle() { + /// Fills the shape. + fill, + + /// Draws only the outline of the shape. + stroke; + + /// Returns the style called [name], or `null` if there is none. + static PaintStyle? fromName(Object? name) { + for (final style in values) { + if (style.name == name) { + return style; + } + } + return null; + } +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/palette.dart b/packages/flame_studio/lib/repositories/component_repository/models/palette.dart new file mode 100644 index 00000000000..c6b3caf697e --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/palette.dart @@ -0,0 +1,138 @@ +import 'package:equatable/equatable.dart'; +import 'package:flame_studio/repositories/component_repository/code_generation/dart_names.dart'; + +/// Why a name can't be used for a [PaletteColor], see +/// [Palette.validateColorName]. +enum PaletteColorNameError() { + /// The name is not a valid Dart identifier, or its member would be a + /// Dart keyword. + invalid, + + /// Another color of the palette already uses the name. + duplicate, +} + +/// {@template palette_color} +/// A named color of a [Palette]. +/// {@endtemplate} +class const PaletteColor({ + /// The name of the color, which names its member in the generated code. + required final String name, + + /// The color as a 32 bit ARGB value. + required final int color, +}) extends Equatable { + /// {@macro palette_color} + this; + + /// Returns a copy of this color with the given fields replaced. + PaletteColor copyWith({String? name, int? color}) { + return PaletteColor(name: name ?? this.name, color: color ?? this.color); + } + + /// Converts this color to its JSON representation. + Map toJson() => {'name': name, 'color': color}; + + @override + List get props => [name, color]; +} + +/// {@template palette} +/// The named colors of a project, shared by its components. +/// +/// Its Dart code is a class with a constant for every color, which the +/// code of the components that use them references. +/// {@endtemplate} +class const Palette({ + /// The colors, in the order they are shown and generated. + final List colors = const [], +}) extends Equatable { + /// {@macro palette} + this; + + /// Creates a [Palette] from its JSON representation. + /// + /// Invalid entries are skipped, and so are names already taken. + factory fromJson(Object? json) { + final list = json is Map ? json['colors'] : null; + final colors = []; + if (list is List) { + for (final Object? entry in list) { + if (entry case {'name': final String name, 'color': final int color} + when Palette(colors: colors) + .validateColorName(colors.length, name) == + null) { + colors.add(PaletteColor(name: name, color: color)); + } + } + } + return Palette(colors: colors); + } + + /// The value of the color called [name], or `null` if there is none. + int? colorOf(String? name) { + for (final color in colors) { + if (color.name == name) { + return color.color; + } + } + return null; + } + + /// Whether the palette has a color called [name]. + bool contains(String? name) => colorOf(name) != null; + + /// Checks whether [name] can be used for the color at [index] (which may + /// be [colors]' length, for a new color). + /// + /// Returns `null` when it can. The name must be a valid Dart identifier + /// whose member is not a keyword, and no other color may have the same + /// member name (`main_color` and `mainColor` are both `mainColor`). + PaletteColorNameError? validateColorName(int index, String name) { + final member = dartMemberName(name); + if (!isDartIdentifier(name) || + !isDartIdentifier(member) || + isDartKeyword(member)) { + return PaletteColorNameError.invalid; + } + for (final (i, color) in colors.indexed) { + if (i != index && dartMemberName(color.name) == member) { + return PaletteColorNameError.duplicate; + } + } + return null; + } + + /// Whether every color has a valid name, see [validateColorName]. + bool get isValid { + for (final (index, color) in colors.indexed) { + if (validateColorName(index, color.name) != null) { + return false; + } + } + return true; + } + + /// A name for a new color that no color uses yet: `color1`, `color2`… + String uniqueColorName() { + for (var i = 1; ; i++) { + final name = 'color$i'; + if (validateColorName(colors.length, name) == null) { + return name; + } + } + } + + /// Returns a copy of this palette with [colors] replaced. + Palette copyWith({List? colors}) { + return Palette(colors: colors ?? this.colors); + } + + /// Converts this palette to its JSON representation. + Map toJson() => { + 'colors': [for (final color in colors) color.toJson()], + }; + + @override + List get props => [colors]; +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/polygon_component.dart b/packages/flame_studio/lib/repositories/component_repository/models/polygon_component.dart new file mode 100644 index 00000000000..5dec2ea7b47 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/polygon_component.dart @@ -0,0 +1,115 @@ +part of 'component.dart'; + +/// {@template polygon_component} +/// A polygon with a position, an anchor, an angle, vertices and a paint. +/// +/// Its size is the bounding box of its vertices. +/// {@endtemplate} +final class const PolygonComponent({ + required super.name, + @override final ComponentPosition position = const ComponentPosition(), + @override final ComponentAnchor anchor = ComponentAnchor.topLeft, + @override final ComponentAngle angle = ComponentAngle.zero, + @override final ComponentVertices vertices = const ComponentVertices(), + @override final ComponentPaint paint = const ComponentPaint(), + super.children, +}) extends Component + implements + PositionedComponent, + AnchoredComponent, + RotatedComponent, + VerticesComponent, + PaintedComponent { + /// {@macro polygon_component} + this; + + /// Reads the properties of a [PolygonComponent] from its JSON + /// representation. Use [Component.fromJson], which also reads the + /// children. + factory _fromJson(Map json) { + return PolygonComponent( + name: json['name'] as String, + position: ComponentPosition.fromJson(json['position']), + anchor: ComponentAnchor.fromJson(json['anchor']), + angle: ComponentAngle.fromJson(json['angle']), + vertices: ComponentVertices.fromJson(json['vertices']), + paint: ComponentPaint.fromJson(json['paint']), + ); + } + + @override + ComponentType get type => ComponentType.polygon; + + @override + PolygonComponent copyWithPosition(ComponentPosition position) { + return _copyWith(position: position); + } + + @override + PolygonComponent copyWithAnchor(ComponentAnchor anchor) { + return _copyWith(anchor: anchor); + } + + @override + PolygonComponent copyWithAngle(ComponentAngle angle) { + return _copyWith(angle: angle); + } + + @override + PolygonComponent copyWithVertices(ComponentVertices vertices) { + return _copyWith(vertices: vertices); + } + + @override + PolygonComponent copyWithPaint(ComponentPaint paint) { + return _copyWith(paint: paint); + } + + @override + PolygonComponent copyWithName(String name) => _copyWith(name: name); + + @override + PolygonComponent copyWithChildren(List children) { + return _copyWith(children: children); + } + + PolygonComponent _copyWith({ + String? name, + ComponentPosition? position, + ComponentAnchor? anchor, + ComponentAngle? angle, + ComponentVertices? vertices, + ComponentPaint? paint, + List? children, + }) { + return PolygonComponent( + name: name ?? this.name, + position: position ?? this.position, + anchor: anchor ?? this.anchor, + angle: angle ?? this.angle, + vertices: vertices ?? this.vertices, + paint: paint ?? this.paint, + children: children ?? this.children, + ); + } + + @override + Map toJson() => { + ...super.toJson(), + 'position': position.toJson(), + 'anchor': anchor.toJson(), + 'angle': angle.toJson(), + 'vertices': vertices.toJson(), + 'paint': paint.toJson(), + }; + + @override + List get props => [ + ...super.props, + position, + anchor, + angle, + vertices, + paint, + ]; +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/polygon_hitbox_component.dart b/packages/flame_studio/lib/repositories/component_repository/models/polygon_hitbox_component.dart new file mode 100644 index 00000000000..9d81a712492 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/polygon_hitbox_component.dart @@ -0,0 +1,116 @@ +part of 'component.dart'; + +/// {@template polygon_hitbox_component} +/// A polygonal hitbox with a position, an anchor, an angle, vertices and a +/// collision. +/// +/// Its size is the bounding box of its vertices. +/// {@endtemplate} +final class const PolygonHitboxComponent({ + required super.name, + @override final ComponentPosition position = const ComponentPosition(), + @override final ComponentAnchor anchor = ComponentAnchor.topLeft, + @override final ComponentAngle angle = ComponentAngle.zero, + @override final ComponentVertices vertices = const ComponentVertices(), + @override final ComponentCollision collision = const ComponentCollision(), + super.children, +}) extends Component + implements + PositionedComponent, + AnchoredComponent, + RotatedComponent, + VerticesComponent, + HitboxComponent { + /// {@macro polygon_hitbox_component} + this; + + /// Reads the properties of a [PolygonHitboxComponent] from its JSON + /// representation. Use [Component.fromJson], which also reads the + /// children. + factory _fromJson(Map json) { + return PolygonHitboxComponent( + name: json['name'] as String, + position: ComponentPosition.fromJson(json['position']), + anchor: ComponentAnchor.fromJson(json['anchor']), + angle: ComponentAngle.fromJson(json['angle']), + vertices: ComponentVertices.fromJson(json['vertices']), + collision: ComponentCollision.fromJson(json['collision']), + ); + } + + @override + ComponentType get type => ComponentType.polygonHitbox; + + @override + PolygonHitboxComponent copyWithPosition(ComponentPosition position) { + return _copyWith(position: position); + } + + @override + PolygonHitboxComponent copyWithAnchor(ComponentAnchor anchor) { + return _copyWith(anchor: anchor); + } + + @override + PolygonHitboxComponent copyWithAngle(ComponentAngle angle) { + return _copyWith(angle: angle); + } + + @override + PolygonHitboxComponent copyWithVertices(ComponentVertices vertices) { + return _copyWith(vertices: vertices); + } + + @override + PolygonHitboxComponent copyWithCollision(ComponentCollision collision) { + return _copyWith(collision: collision); + } + + @override + PolygonHitboxComponent copyWithName(String name) => _copyWith(name: name); + + @override + PolygonHitboxComponent copyWithChildren(List children) { + return _copyWith(children: children); + } + + PolygonHitboxComponent _copyWith({ + String? name, + ComponentPosition? position, + ComponentAnchor? anchor, + ComponentAngle? angle, + ComponentVertices? vertices, + ComponentCollision? collision, + List? children, + }) { + return PolygonHitboxComponent( + name: name ?? this.name, + position: position ?? this.position, + anchor: anchor ?? this.anchor, + angle: angle ?? this.angle, + vertices: vertices ?? this.vertices, + collision: collision ?? this.collision, + children: children ?? this.children, + ); + } + + @override + Map toJson() => { + ...super.toJson(), + 'position': position.toJson(), + 'anchor': anchor.toJson(), + 'angle': angle.toJson(), + 'vertices': vertices.toJson(), + 'collision': collision.toJson(), + }; + + @override + List get props => [ + ...super.props, + position, + anchor, + angle, + vertices, + collision, + ]; +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/polygon_shape.dart b/packages/flame_studio/lib/repositories/component_repository/models/polygon_shape.dart new file mode 100644 index 00000000000..b2fa53f2af4 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/polygon_shape.dart @@ -0,0 +1,16 @@ +import 'package:flame_studio/repositories/repositories.dart'; + +/// The shapes a new polygon can start with. +enum PolygonShape({ + /// Human readable name. + required final String label, + + /// The vertices of the shape. + required final List vertices, +}) { + /// Three vertices, see [ComponentVertices.triangle]. + triangle(label: 'Triangle', vertices: ComponentVertices.triangle), + + /// Four vertices, see [ComponentVertices.square]. + square(label: 'Square', vertices: ComponentVertices.square), +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/position_component.dart b/packages/flame_studio/lib/repositories/component_repository/models/position_component.dart new file mode 100644 index 00000000000..11d65b5d9f1 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/position_component.dart @@ -0,0 +1,96 @@ +part of 'component.dart'; + +/// {@template position_component} +/// A plain component with a position, an anchor and a size, that draws +/// nothing itself: a container for its children. +/// {@endtemplate} +final class const PositionComponent({ + required super.name, + @override final ComponentPosition position = const ComponentPosition(), + @override final ComponentAnchor anchor = ComponentAnchor.topLeft, + @override final ComponentAngle angle = ComponentAngle.zero, + @override final ComponentSize size = const ComponentSize(), + super.children, +}) extends Component + implements + PositionedComponent, + AnchoredComponent, + RotatedComponent, + SizedComponent { + /// {@macro position_component} + this; + + /// Reads the properties of a [PositionComponent] from its JSON + /// representation. Use [Component.fromJson], which also reads the + /// children. + factory _fromJson(Map json) { + return PositionComponent( + name: json['name'] as String, + position: ComponentPosition.fromJson(json['position']), + anchor: ComponentAnchor.fromJson(json['anchor']), + angle: ComponentAngle.fromJson(json['angle']), + size: ComponentSize.fromJson(json['size']), + ); + } + + @override + ComponentType get type => ComponentType.position; + + @override + PositionComponent copyWithPosition(ComponentPosition position) { + return _copyWith(position: position); + } + + @override + PositionComponent copyWithAnchor(ComponentAnchor anchor) { + return _copyWith(anchor: anchor); + } + + @override + PositionComponent copyWithAngle(ComponentAngle angle) { + return _copyWith(angle: angle); + } + + @override + PositionComponent copyWithSize(ComponentSize size) { + return _copyWith(size: size); + } + + @override + PositionComponent copyWithName(String name) => _copyWith(name: name); + + @override + PositionComponent copyWithChildren(List children) { + return _copyWith(children: children); + } + + PositionComponent _copyWith({ + String? name, + ComponentPosition? position, + ComponentAnchor? anchor, + ComponentAngle? angle, + ComponentSize? size, + List? children, + }) { + return PositionComponent( + name: name ?? this.name, + position: position ?? this.position, + anchor: anchor ?? this.anchor, + angle: angle ?? this.angle, + size: size ?? this.size, + children: children ?? this.children, + ); + } + + @override + Map toJson() => { + ...super.toJson(), + 'position': position.toJson(), + 'anchor': anchor.toJson(), + 'angle': angle.toJson(), + 'size': size.toJson(), + }; + + @override + List get props => [...super.props, position, anchor, angle, size]; +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/rectangle_component.dart b/packages/flame_studio/lib/repositories/component_repository/models/rectangle_component.dart new file mode 100644 index 00000000000..ef4119b6449 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/rectangle_component.dart @@ -0,0 +1,113 @@ +part of 'component.dart'; + +/// {@template rectangle_component} +/// A rectangle with a position, an anchor, an angle, a size and a paint. +/// {@endtemplate} +final class const RectangleComponent({ + required super.name, + @override final ComponentPosition position = const ComponentPosition(), + @override final ComponentAnchor anchor = ComponentAnchor.topLeft, + @override final ComponentAngle angle = ComponentAngle.zero, + @override final ComponentSize size = const ComponentSize(), + @override final ComponentPaint paint = const ComponentPaint(), + super.children, +}) extends Component + implements + PositionedComponent, + AnchoredComponent, + RotatedComponent, + SizedComponent, + PaintedComponent { + /// {@macro rectangle_component} + this; + + /// Reads the properties of a [RectangleComponent] from its JSON + /// representation. Use [Component.fromJson], which also reads the + /// children. + factory _fromJson(Map json) { + return RectangleComponent( + name: json['name'] as String, + position: ComponentPosition.fromJson(json['position']), + anchor: ComponentAnchor.fromJson(json['anchor']), + angle: ComponentAngle.fromJson(json['angle']), + size: ComponentSize.fromJson(json['size']), + paint: ComponentPaint.fromJson(json['paint']), + ); + } + + @override + ComponentType get type => ComponentType.rectangle; + + @override + RectangleComponent copyWithPosition(ComponentPosition position) { + return _copyWith(position: position); + } + + @override + RectangleComponent copyWithAnchor(ComponentAnchor anchor) { + return _copyWith(anchor: anchor); + } + + @override + RectangleComponent copyWithAngle(ComponentAngle angle) { + return _copyWith(angle: angle); + } + + @override + RectangleComponent copyWithSize(ComponentSize size) { + return _copyWith(size: size); + } + + @override + RectangleComponent copyWithPaint(ComponentPaint paint) { + return _copyWith(paint: paint); + } + + @override + RectangleComponent copyWithName(String name) => _copyWith(name: name); + + @override + RectangleComponent copyWithChildren(List children) { + return _copyWith(children: children); + } + + RectangleComponent _copyWith({ + String? name, + ComponentPosition? position, + ComponentAnchor? anchor, + ComponentAngle? angle, + ComponentSize? size, + ComponentPaint? paint, + List? children, + }) { + return RectangleComponent( + name: name ?? this.name, + position: position ?? this.position, + anchor: anchor ?? this.anchor, + angle: angle ?? this.angle, + size: size ?? this.size, + paint: paint ?? this.paint, + children: children ?? this.children, + ); + } + + @override + Map toJson() => { + ...super.toJson(), + 'position': position.toJson(), + 'anchor': anchor.toJson(), + 'angle': angle.toJson(), + 'size': size.toJson(), + 'paint': paint.toJson(), + }; + + @override + List get props => [ + ...super.props, + position, + anchor, + angle, + size, + paint, + ]; +} diff --git a/packages/flame_studio/lib/repositories/component_repository/models/rectangle_hitbox_component.dart b/packages/flame_studio/lib/repositories/component_repository/models/rectangle_hitbox_component.dart new file mode 100644 index 00000000000..facc5237bd6 --- /dev/null +++ b/packages/flame_studio/lib/repositories/component_repository/models/rectangle_hitbox_component.dart @@ -0,0 +1,114 @@ +part of 'component.dart'; + +/// {@template rectangle_hitbox_component} +/// A rectangular hitbox with a position, an anchor, an angle, a size and a +/// collision. +/// {@endtemplate} +final class const RectangleHitboxComponent({ + required super.name, + @override final ComponentPosition position = const ComponentPosition(), + @override final ComponentAnchor anchor = ComponentAnchor.topLeft, + @override final ComponentAngle angle = ComponentAngle.zero, + @override final ComponentSize size = const ComponentSize(), + @override final ComponentCollision collision = const ComponentCollision(), + super.children, +}) extends Component + implements + PositionedComponent, + AnchoredComponent, + RotatedComponent, + SizedComponent, + HitboxComponent { + /// {@macro rectangle_hitbox_component} + this; + + /// Reads the properties of a [RectangleHitboxComponent] from its JSON + /// representation. Use [Component.fromJson], which also reads the + /// children. + factory _fromJson(Map json) { + return RectangleHitboxComponent( + name: json['name'] as String, + position: ComponentPosition.fromJson(json['position']), + anchor: ComponentAnchor.fromJson(json['anchor']), + angle: ComponentAngle.fromJson(json['angle']), + size: ComponentSize.fromJson(json['size']), + collision: ComponentCollision.fromJson(json['collision']), + ); + } + + @override + ComponentType get type => ComponentType.rectangleHitbox; + + @override + RectangleHitboxComponent copyWithPosition(ComponentPosition position) { + return _copyWith(position: position); + } + + @override + RectangleHitboxComponent copyWithAnchor(ComponentAnchor anchor) { + return _copyWith(anchor: anchor); + } + + @override + RectangleHitboxComponent copyWithAngle(ComponentAngle angle) { + return _copyWith(angle: angle); + } + + @override + RectangleHitboxComponent copyWithSize(ComponentSize size) { + return _copyWith(size: size); + } + + @override + RectangleHitboxComponent copyWithCollision(ComponentCollision collision) { + return _copyWith(collision: collision); + } + + @override + RectangleHitboxComponent copyWithName(String name) => _copyWith(name: name); + + @override + RectangleHitboxComponent copyWithChildren(List children) { + return _copyWith(children: children); + } + + RectangleHitboxComponent _copyWith({ + String? name, + ComponentPosition? position, + ComponentAnchor? anchor, + ComponentAngle? angle, + ComponentSize? size, + ComponentCollision? collision, + List? children, + }) { + return RectangleHitboxComponent( + name: name ?? this.name, + position: position ?? this.position, + anchor: anchor ?? this.anchor, + angle: angle ?? this.angle, + size: size ?? this.size, + collision: collision ?? this.collision, + children: children ?? this.children, + ); + } + + @override + Map toJson() => { + ...super.toJson(), + 'position': position.toJson(), + 'anchor': anchor.toJson(), + 'angle': angle.toJson(), + 'size': size.toJson(), + 'collision': collision.toJson(), + }; + + @override + List get props => [ + ...super.props, + position, + anchor, + angle, + size, + collision, + ]; +} diff --git a/packages/flame_studio/lib/repositories/editor_preferences_repository/editor_preferences_repository.dart b/packages/flame_studio/lib/repositories/editor_preferences_repository/editor_preferences_repository.dart new file mode 100644 index 00000000000..31be889e72f --- /dev/null +++ b/packages/flame_studio/lib/repositories/editor_preferences_repository/editor_preferences_repository.dart @@ -0,0 +1,60 @@ +import 'package:flame_studio/clients/clients.dart'; +import 'package:flame_studio/repositories/editor_preferences_repository/models/models.dart'; + +/// {@template editor_preferences_repository} +/// Keeps the preferences of the editor, which belong to the app rather than +/// to a project, such as the zoom of the preview of each component. +/// {@endtemplate} +class EditorPreferencesRepository({ + required final KeyValueStorageClient _storage, +}) { + /// {@macro editor_preferences_repository} + this; + + /// The zoom of a component whose zoom was never changed. + static const defaultZoom = 1.0; + + /// The smallest zoom. + static const double minZoom = ZoomLevels.min; + + /// The largest zoom. + static const double maxZoom = ZoomLevels.max; + + /// Storage key under which the zoom of the component named + /// [componentName] of the project at [projectPath] is persisted. + static String componentZoomKey(String projectPath, String componentName) => + 'component_zoom:$projectPath:$componentName'; + + /// Returns the zoom of the preview of the component named [componentName] + /// of the project at [projectPath], between [minZoom] and [maxZoom]. + /// + /// Returns [defaultZoom] if nothing was stored or the stored value is + /// unreadable. + Future getComponentZoom({ + required String projectPath, + required String componentName, + }) async { + final raw = await _storage.read( + componentZoomKey(projectPath, componentName), + ); + final zoom = raw == null ? null : double.tryParse(raw); + if (zoom == null || !zoom.isFinite) { + return defaultZoom; + } + return zoom.clamp(minZoom, maxZoom); + } + + /// Stores [zoom], clamped between [minZoom] and [maxZoom], as the zoom of + /// the preview of the component named [componentName] of the project at + /// [projectPath]. + Future setComponentZoom({ + required String projectPath, + required String componentName, + required double zoom, + }) { + return _storage.write( + componentZoomKey(projectPath, componentName), + zoom.clamp(minZoom, maxZoom).toString(), + ); + } +} diff --git a/packages/flame_studio/lib/repositories/editor_preferences_repository/models/models.dart b/packages/flame_studio/lib/repositories/editor_preferences_repository/models/models.dart new file mode 100644 index 00000000000..9a59538fc41 --- /dev/null +++ b/packages/flame_studio/lib/repositories/editor_preferences_repository/models/models.dart @@ -0,0 +1 @@ +export 'zoom_levels.dart'; diff --git a/packages/flame_studio/lib/repositories/editor_preferences_repository/models/zoom_levels.dart b/packages/flame_studio/lib/repositories/editor_preferences_repository/models/zoom_levels.dart new file mode 100644 index 00000000000..78f06a50abf --- /dev/null +++ b/packages/flame_studio/lib/repositories/editor_preferences_repository/models/zoom_levels.dart @@ -0,0 +1,51 @@ +/// The zooms an editor canvas steps through when zooming in and out, `1` +/// being the actual size. +abstract final class ZoomLevels() { + /// Creates a [ZoomLevels]. + this; + + /// The smallest zoom. + static const min = 0.1; + + /// The largest zoom. + static const max = 8.0; + + /// Every level, from [min] to [max]. + static const List all = [ + min, + 0.25, + 0.5, + 0.75, + 1, + 1.5, + 2, + 3, + 4, + 6, + max, + ]; + + static const _tolerance = 1e-6; + + /// The zoom after zooming in from [zoom], or `null` if it is [max] + /// already. A zoom between two levels goes to the larger one. + static double? next(double zoom) { + for (final level in all) { + if (level > zoom + _tolerance) { + return level; + } + } + return null; + } + + /// The zoom after zooming out from [zoom], or `null` if it is [min] + /// already. A zoom between two levels goes to the smaller one. + static double? previous(double zoom) { + for (final level in all.reversed) { + if (level < zoom - _tolerance) { + return level; + } + } + return null; + } +} diff --git a/packages/flame_studio/lib/repositories/project_repository/models/models.dart b/packages/flame_studio/lib/repositories/project_repository/models/models.dart new file mode 100644 index 00000000000..edc619ae81d --- /dev/null +++ b/packages/flame_studio/lib/repositories/project_repository/models/models.dart @@ -0,0 +1,2 @@ +export 'project.dart'; +export 'project_settings.dart'; diff --git a/packages/flame_studio/lib/repositories/project_repository/models/project.dart b/packages/flame_studio/lib/repositories/project_repository/models/project.dart new file mode 100644 index 00000000000..2b3dbada1ff --- /dev/null +++ b/packages/flame_studio/lib/repositories/project_repository/models/project.dart @@ -0,0 +1,31 @@ +import 'package:equatable/equatable.dart'; + +/// {@template project} +/// A project opened in the editor, identified by its folder [path]. +/// {@endtemplate} +class const Project({ + /// Absolute path to the project folder. + required final String path, +}) extends Equatable { + /// {@macro project} + this; + + /// Creates a [Project] from its JSON representation. + factory fromJson(Map json) { + return Project(path: json['path'] as String); + } + + /// The project name, which is the name of its folder. + String get name { + final segments = path + .split(RegExp(r'[/\\]')) + .where((segment) => segment.isNotEmpty); + return segments.isEmpty ? path : segments.last; + } + + /// Converts this project to its JSON representation. + Map toJson() => {'path': path}; + + @override + List get props => [path]; +} diff --git a/packages/flame_studio/lib/repositories/project_repository/models/project_settings.dart b/packages/flame_studio/lib/repositories/project_repository/models/project_settings.dart new file mode 100644 index 00000000000..b026d62f367 --- /dev/null +++ b/packages/flame_studio/lib/repositories/project_repository/models/project_settings.dart @@ -0,0 +1,37 @@ +import 'package:equatable/equatable.dart'; + +/// {@template project_settings} +/// The settings of a project. +/// {@endtemplate} +class const ProjectSettings({ + /// Folder, relative to the project folder, where the generated Dart source + /// code is written. + final String outputPath = defaultOutputPath, +}) extends Equatable { + /// {@macro project_settings} + this; + + /// Creates a [ProjectSettings] from its JSON representation. + /// + /// Missing or invalid values fall back to their defaults. + factory fromJson(Map json) { + final outputPath = json['outputPath']; + return ProjectSettings( + outputPath: outputPath is String ? outputPath : defaultOutputPath, + ); + } + + /// The default [outputPath]. + static const defaultOutputPath = 'lib/components'; + + /// Returns a copy of these settings with the given fields replaced. + ProjectSettings copyWith({String? outputPath}) { + return ProjectSettings(outputPath: outputPath ?? this.outputPath); + } + + /// Converts these settings to their JSON representation. + Map toJson() => {'outputPath': outputPath}; + + @override + List get props => [outputPath]; +} diff --git a/packages/flame_studio/lib/repositories/project_repository/project_repository.dart b/packages/flame_studio/lib/repositories/project_repository/project_repository.dart new file mode 100644 index 00000000000..120f3bc8bc0 --- /dev/null +++ b/packages/flame_studio/lib/repositories/project_repository/project_repository.dart @@ -0,0 +1,175 @@ +import 'dart:convert'; + +import 'package:flame_studio/clients/clients.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:path/path.dart' as p; + +/// {@template project_not_found_exception} +/// Thrown when opening a [Project] whose folder no longer exists. +/// {@endtemplate} +class const ProjectNotFoundException( + /// The project that could not be found. + final Project project, +) implements Exception { + /// {@macro project_not_found_exception} + this; +} + +/// {@template invalid_output_path_exception} +/// Thrown when an output path is not a folder inside the project. +/// {@endtemplate} +class const InvalidOutputPathException( + /// The rejected path. + final String path, +) implements Exception { + /// {@macro invalid_output_path_exception} + this; +} + +/// {@template project_repository} +/// Opens projects, keeps track of the most recently opened ones and manages +/// their settings. +/// +/// The settings of a project are stored in its [settingsFile]. +/// {@endtemplate} +class ProjectRepository({ + required final KeyValueStorageClient _storage, + required final FileSystemClient _fileSystem, +}) { + /// {@macro project_repository} + this; + + /// Storage key under which recent projects are persisted. + static const recentProjectsKey = 'recent_projects'; + + /// Maximum number of recent projects that are kept. + static const maxRecentProjects = 10; + + /// File, relative to the project folder, where its settings are stored. + static const settingsFile = '.flame_studio/settings.json'; + + /// Returns the recently opened projects, most recent first. + /// + /// Returns an empty list if nothing was stored or the stored data is + /// unreadable. + Future> getRecentProjects() async { + final raw = await _storage.read(recentProjectsKey); + if (raw == null) { + return const []; + } + try { + final decoded = jsonDecode(raw) as List; + return [ + for (final json in decoded) + Project.fromJson(json as Map), + ]; + } on Object { + return const []; + } + } + + /// Asks the user to pick a project folder. + /// + /// Returns `null` if the user cancelled. + Future pickProject() async { + final path = await _fileSystem.pickDirectory(); + return path == null ? null : Project(path: path); + } + + /// Opens [project], moving it to the top of the recent projects. + /// + /// Throws a [ProjectNotFoundException] if the project folder no longer + /// exists, in which case it is removed from the recent projects. + Future openProject(Project project) async { + final recentProjects = (await getRecentProjects()) + .where((recent) => recent != project) + .toList(); + + if (!await _fileSystem.directoryExists(project.path)) { + await _saveRecentProjects(recentProjects); + throw ProjectNotFoundException(project); + } + + await _saveRecentProjects( + [project, ...recentProjects].take(maxRecentProjects).toList(), + ); + } + + /// Returns the settings of [project]. + /// + /// Returns the default settings if none were saved or the stored data is + /// unreadable. + Future getSettings(Project project) async { + final path = _settingsPath(project); + try { + if (!await _fileSystem.fileExists(path)) { + return const ProjectSettings(); + } + final json = jsonDecode(await _fileSystem.readFile(path)); + return ProjectSettings.fromJson(json as Map); + } on Object { + return const ProjectSettings(); + } + } + + /// Saves the [settings] of [project] and returns them normalized. + /// + /// Throws an [InvalidOutputPathException] if the output path is not a + /// folder inside the project. + Future saveSettings( + Project project, + ProjectSettings settings, + ) async { + final normalized = settings.copyWith( + outputPath: _normalizeOutputPath(settings.outputPath), + ); + await _fileSystem.writeFile( + _settingsPath(project), + jsonEncode(normalized.toJson()), + ); + return normalized; + } + + /// Asks the user to pick the output folder of [project]. + /// + /// Returns the picked folder relative to the project folder, or `null` if + /// the user cancelled. Throws an [InvalidOutputPathException] if the picked + /// folder is not inside the project. + Future pickOutputPath(Project project) async { + final picked = await _fileSystem.pickDirectory(); + if (picked == null) { + return null; + } + if (!p.isWithin(project.path, picked)) { + throw InvalidOutputPathException(picked); + } + return _normalizeOutputPath(p.relative(picked, from: project.path)); + } + + /// Normalizes a project-relative [path] using `/` as separator. + /// + /// Throws an [InvalidOutputPathException] if [path] is empty, absolute or + /// points outside the project. + String _normalizeOutputPath(String path) { + final trimmed = path.trim(); + if (trimmed.isEmpty || + p.isAbsolute(trimmed) || + p.posix.isAbsolute(trimmed)) { + throw InvalidOutputPathException(path); + } + final segments = p.split(p.normalize(trimmed)); + if (segments.first == '.' || segments.first == '..') { + throw InvalidOutputPathException(path); + } + return segments.join('/'); + } + + String _settingsPath(Project project) => p.join(project.path, settingsFile); + + Future _saveRecentProjects(List projects) { + return _storage.write( + recentProjectsKey, + jsonEncode([for (final project in projects) project.toJson()]), + ); + } +} diff --git a/packages/flame_studio/lib/repositories/repositories.dart b/packages/flame_studio/lib/repositories/repositories.dart new file mode 100644 index 00000000000..9543ed29743 --- /dev/null +++ b/packages/flame_studio/lib/repositories/repositories.dart @@ -0,0 +1,7 @@ +export 'component_repository/code_generation/code_generation.dart'; +export 'component_repository/component_repository.dart'; +export 'component_repository/models/models.dart'; +export 'editor_preferences_repository/editor_preferences_repository.dart'; +export 'editor_preferences_repository/models/models.dart'; +export 'project_repository/models/models.dart'; +export 'project_repository/project_repository.dart'; diff --git a/packages/flame_studio/lib/src/core/component_tree.dart b/packages/flame_studio/lib/src/core/component_tree.dart deleted file mode 100644 index 141273a4c5f..00000000000 --- a/packages/flame_studio/lib/src/core/component_tree.dart +++ /dev/null @@ -1,77 +0,0 @@ -import 'dart:async'; - -import 'package:flame/components.dart' show Component; -import 'package:flame_studio/src/core/game_controller.dart'; -import 'package:flutter/foundation.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -final componentTreeProvider = - NotifierProvider( - ComponentTreeObserver.new, - ); - -@immutable -class const ComponentTreeNode._( - final Component component, - final List? children, -) { - factory ComponentTreeNode.fromComponent(Component component) { - return ComponentTreeNode._( - component, - component.hasChildren - ? component.children.map(ComponentTreeNode.fromComponent).toList() - : null, - ); - } - - String get name => component.runtimeType.toString(); - bool get hasChildren => children?.isNotEmpty ?? false; - - @override - bool operator ==(Object other) => - other is ComponentTreeNode && - component == other.component && - listEquals(children, other.children); - - @override - int get hashCode => Object.hash(component, children); -} - -@immutable -// ignore: prefer_const_constructors_in_immutables -class ComponentTreeState(Component? rootComponent) { - final ComponentTreeNode? root = rootComponent == null - ? null - : ComponentTreeNode.fromComponent(rootComponent); - - @override - bool operator ==(Object other) => - other is ComponentTreeState && root == other.root; - - @override - int get hashCode => root?.hashCode ?? 0; -} - -/// Periodically takes a snapshot of the component tree of the current game. -/// -/// Listeners are only notified when the structure of the tree changes. -class ComponentTreeObserver() extends Notifier { - static const Duration refreshFrequency = Duration(milliseconds: 300); - - @override - ComponentTreeState build() { - final game = ref.watch(gameControllerProvider.select((s) => s.game)); - final root = switch (game) { - final Component component => component, - _ => null, - }; - if (root != null) { - final timer = Timer.periodic( - refreshFrequency, - (_) => state = ComponentTreeState(root), - ); - ref.onDispose(timer.cancel); - } - return ComponentTreeState(root); - } -} diff --git a/packages/flame_studio/lib/src/core/game_controller.dart b/packages/flame_studio/lib/src/core/game_controller.dart deleted file mode 100644 index d3e433dd3fe..00000000000 --- a/packages/flame_studio/lib/src/core/game_controller.dart +++ /dev/null @@ -1,110 +0,0 @@ -import 'dart:async'; - -import 'package:flame/game.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -final gameControllerProvider = NotifierProvider( - GameController.new, -); - -@immutable -class const GameState({final Game? game, final bool paused = false}) { - GameState copyWith({ - Game? game, - bool? paused, - }) { - return GameState( - game: game ?? this.game, - paused: paused ?? this.paused, - ); - } - - @override - bool operator ==(Object other) => - other is GameState && game == other.game && paused == other.paused; - - @override - int get hashCode => Object.hash(game, paused); -} - -/// Keeps track of the [Game] running inside the studio, and allows to pause, -/// resume and step it. -/// -/// The game is discovered by searching the widget tree for a [GameWidget], -/// which is repeated periodically so that games which are attached later (for -/// example after a menu screen) or replaced are picked up as well. -class GameController() extends Notifier { - static const Duration pollFrequency = Duration(milliseconds: 500); - - @override - GameState build() { - WidgetsFlutterBinding.ensureInitialized(); - final timer = Timer.periodic(pollFrequency, (_) => _poll()); - ref.onDispose(timer.cancel); - WidgetsBinding.instance.addPostFrameCallback((_) { - if (ref.mounted) { - _poll(); - } - }); - return const GameState(); - } - - bool get isPaused => state.paused; - - void useGame(Game? game) { - state = GameState(game: game, paused: game?.isPaused ?? false); - } - - void pauseGame() { - state.game!.pauseEngine(); - state = state.copyWith(paused: true); - } - - void resumeGame() { - state.game!.resumeEngine(); - state = state.copyWith(paused: false); - } - - void stepGame() { - state.game!.stepEngine(); - } - - /// Repaints the game, so that changes made from the studio are visible even - /// while the game is paused. - void repaint() { - final game = state.game; - if (game != null && game.isAttached) { - game.renderBox.markNeedsPaint(); - } - } - - void _poll() { - final game = state.game; - if (game == null || !game.isAttached) { - final newGame = _findGame(); - if (newGame != game) { - useGame(newGame); - } - } else if (game.isPaused != state.paused) { - // The game may pause or resume itself. - state = state.copyWith(paused: game.isPaused); - } - } - - static Game? _findGame() { - Game? game; - void visitor(Element element) { - if (element.widget is GameWidget) { - final dynamic state = (element as StatefulElement).state; - // ignore: avoid_dynamic_calls - game = state.currentGame as Game; - } else { - element.visitChildElements(visitor); - } - } - - WidgetsBinding.instance.rootElement?.visitChildElements(visitor); - return game; - } -} diff --git a/packages/flame_studio/lib/src/core/gizmo/canvas_mapping.dart b/packages/flame_studio/lib/src/core/gizmo/canvas_mapping.dart deleted file mode 100644 index 2af9175620d..00000000000 --- a/packages/flame_studio/lib/src/core/gizmo/canvas_mapping.dart +++ /dev/null @@ -1,137 +0,0 @@ -import 'package:flame/camera.dart' show Viewfinder, Viewport; -import 'package:flame/components.dart' - show - CameraComponent, - Component, - CoordinateTransform, - PositionComponent, - Vector2, - World; -import 'package:flame/game.dart' show FlameGame; -import 'package:flutter/foundation.dart'; - -/// Converts [point] from the local coordinate space of [component] into the -/// canvas space of the game, which is in logical pixels relative to the -/// top-left corner of the game widget. -/// -/// This follows the same transforms that are applied when rendering the -/// component. A [World] is only rendered through the cameras that look at it, -/// so for components inside of a world the [camera] to map through must be -/// given; see [camerasFor]. -/// -/// Returns null when the point can't be mapped, for example when the component -/// is in a world that [camera] doesn't look at. -Vector2? localToCanvas( - Component component, - Vector2 point, { - CameraComponent? camera, -}) { - var result = point.clone(); - final visitedWorlds = {}; - Component? current = component; - while (current != null) { - switch (current) { - case PositionComponent(): - result = current.positionOf(result); - case World(): - if (camera == null || - camera.world != current || - !visitedWorlds.add(current)) { - return null; - } - result = camera.localToGlobal(result); - current = camera; - case Viewfinder(parent: final CameraComponent parentCamera): - // The viewfinder is rendered within the viewport of its camera. - result = parentCamera.localToGlobal(result); - current = parentCamera; - case Viewport(parent: final CameraComponent parentCamera): - result = current.localToGlobal(result); - current = parentCamera; - case final CoordinateTransform transform: - final parentPoint = transform.localToParent(result); - if (parentPoint == null) { - return null; - } - result = parentPoint; - default: - } - current = current.parent; - } - return result; -} - -/// The cameras through which [component] is rendered. -/// -/// Contains a single null value when the component is not in a [World], as it -/// is rendered without going through a camera. Only cameras that are direct -/// children of the game are considered. -List camerasFor(Component component) { - final world = component.ancestors(includeSelf: true).whereType(); - if (world.isEmpty) { - return const [null]; - } - final game = component.findGame(); - if (game is! FlameGame) { - return const []; - } - return game.children - .whereType() - .where((camera) => camera.world == world.first) - .toList(); -} - -/// The linear part of the transform from the parent space of a component, -/// where its position and angle live, into the canvas space of the game. -/// -/// The transform is given by the images of the parent's unit vectors, which -/// are the columns `(a, b)` and `(c, d)` of its matrix. -@immutable -class const ParentToCanvas._( - final double a, - final double b, - final double c, - final double d, -) { - /// The transform of the parent of [component], as seen through [camera]. - /// - /// Returns null when the parent space can't be mapped to the canvas, or is - /// degenerate (for example, scaled to zero). - static ParentToCanvas? of( - PositionComponent component, { - CameraComponent? camera, - }) { - final parent = component.parent; - if (parent == null) { - return null; - } - final origin = localToCanvas(parent, Vector2.zero(), camera: camera); - final unitX = localToCanvas(parent, Vector2(1, 0), camera: camera); - final unitY = localToCanvas(parent, Vector2(0, 1), camera: camera); - if (origin == null || unitX == null || unitY == null) { - return null; - } - final transform = ParentToCanvas._( - unitX.x - origin.x, - unitX.y - origin.y, - unitY.x - origin.x, - unitY.y - origin.y, - ); - return transform.determinant.abs() < 1e-12 ? null : transform; - } - - double get determinant => a * d - c * b; - - /// Whether the transform mirrors the parent space, which reverses the - /// direction of rotations. - bool get isMirrored => determinant < 0; - - /// Converts a distance in the canvas space into the parent space. - Vector2 canvasToParent(Vector2 delta) { - final determinant = this.determinant; - return Vector2( - (d * delta.x - c * delta.y) / determinant, - (a * delta.y - b * delta.x) / determinant, - ); - } -} diff --git a/packages/flame_studio/lib/src/core/gizmo/gizmo_drag.dart b/packages/flame_studio/lib/src/core/gizmo/gizmo_drag.dart deleted file mode 100644 index 6fff88a8c47..00000000000 --- a/packages/flame_studio/lib/src/core/gizmo/gizmo_drag.dart +++ /dev/null @@ -1,18 +0,0 @@ -import 'package:flame/components.dart' show Vector2; - -/// A change to a component made by dragging a handle of its gizmo. -/// -/// Drags are measured in the canvas space of the game. What the drag needs to -/// know about the component is captured when it starts, so that it keeps -/// following the pointer even when the drag moves the camera, for example a -/// camera that follows the component. -abstract interface class GizmoDrag() { - /// Applies the drag, where [canvasDelta] is the distance between the start - /// of the drag and the current pointer position in canvas space. - /// - /// When [snap] is true, the result is rounded to convenient values. - void update(Vector2 canvasDelta, {bool snap = false}); - - /// Restores the component to how it was when the drag started. - void cancel(); -} diff --git a/packages/flame_studio/lib/src/core/gizmo/gizmo_geometry.dart b/packages/flame_studio/lib/src/core/gizmo/gizmo_geometry.dart deleted file mode 100644 index 1eaf310d65d..00000000000 --- a/packages/flame_studio/lib/src/core/gizmo/gizmo_geometry.dart +++ /dev/null @@ -1,173 +0,0 @@ -import 'dart:ui'; - -import 'package:flame/components.dart' - show CameraComponent, PositionComponent, Vector2; -import 'package:flame_studio/src/core/gizmo/canvas_mapping.dart'; -import 'package:flutter/foundation.dart'; - -/// The parts of a gizmo that can be dragged. -/// -/// What dragging a handle does depends on the tool in use: for example, the x -/// handle moves the component along its local x axis with the move tool, and -/// scales it along that axis with the scale tool. -enum GizmoHandle() { - /// The handle on the local x axis. - x, - - /// The handle on the local y axis. - y, - - /// The square between the axes, which affects both axes at once. - free, - - /// The ring around the anchor, used for rotating. - ring, -} - -/// The outline, anchor and axes of a [PositionComponent] in the canvas space -/// of the game, as seen through a single [camera]. -/// -/// The outline is given by its four [corners] rather than by a rectangle, so -/// that rotations, scaling and flips of the component and its ancestors are -/// all represented. The handles have a fixed size in canvas space, regardless -/// of the size and zoom level of the component. -@immutable -class const GizmoGeometry({ - required final List corners, - required final Offset anchor, - required final Offset xAxis, - required final Offset yAxis, - final CameraComponent? camera, -}) { - static const double axisLength = 40.0; - static const double freeHandleStart = 8.0; - static const double freeHandleEnd = 18.0; - static const double ringRadius = 50.0; - - /// How far from a handle, in logical pixels, a pointer may be to grab it. - static const double handleTolerance = 6.0; - - /// The geometry of [component] for each camera that renders it. - static List of(PositionComponent component) { - return [ - for (final camera in camerasFor(component)) ?_compute(component, camera), - ]; - } - - static GizmoGeometry? _compute( - PositionComponent component, - CameraComponent? camera, - ) { - Offset? map(double x, double y) { - final point = localToCanvas(component, Vector2(x, y), camera: camera); - return point == null ? null : Offset(point.x, point.y); - } - - final width = component.size.x; - final height = component.size.y; - final anchorX = component.anchor.x * width; - final anchorY = component.anchor.y * height; - final topLeft = map(0, 0); - final topRight = map(width, 0); - final bottomRight = map(width, height); - final bottomLeft = map(0, height); - final anchor = map(anchorX, anchorY); - final xEnd = map(anchorX + 1, anchorY); - final yEnd = map(anchorX, anchorY + 1); - if (topLeft == null || - topRight == null || - bottomRight == null || - bottomLeft == null || - anchor == null || - xEnd == null || - yEnd == null) { - return null; - } - return GizmoGeometry( - corners: [topLeft, topRight, bottomRight, bottomLeft], - anchor: anchor, - xAxis: _direction(xEnd - anchor), - yAxis: _direction(yEnd - anchor), - camera: camera, - ); - } - - static Offset _direction(Offset offset) { - final distance = offset.distance; - return distance == 0 ? Offset.zero : offset / distance; - } - - Offset get xAxisEnd => anchor + xAxis * axisLength; - - Offset get yAxisEnd => anchor + yAxis * axisLength; - - /// The corners of the square handle that moves the component freely. - List get freeHandleCorners => [ - anchor + xAxis * freeHandleStart + yAxis * freeHandleStart, - anchor + xAxis * freeHandleEnd + yAxis * freeHandleStart, - anchor + xAxis * freeHandleEnd + yAxis * freeHandleEnd, - anchor + xAxis * freeHandleStart + yAxis * freeHandleEnd, - ]; - - /// The handle at [point], which is in canvas space, if any. - /// - /// When [ring] is true, only the rotation ring is considered, otherwise - /// only the axes and the square between them are. - GizmoHandle? handleAt(Offset point, {bool ring = false}) { - final offset = point - anchor; - if (ring) { - final isOnRing = (offset.distance - ringRadius).abs() <= handleTolerance; - return isOnRing ? GizmoHandle.ring : null; - } - // The coordinates of the point along each axis, and its distance from it. - final alongX = _dot(offset, xAxis); - final alongY = _dot(offset, yAxis); - final fromX = _cross(xAxis, offset).abs(); - final fromY = _cross(yAxis, offset).abs(); - - const tolerance = handleTolerance; - bool isWithin(double value, double start, double end) => - value >= start - tolerance / 2 && value <= end + tolerance / 2; - - if (xAxis != Offset.zero && - yAxis != Offset.zero && - isWithin(alongX, freeHandleStart, freeHandleEnd) && - isWithin(alongY, freeHandleStart, freeHandleEnd)) { - return GizmoHandle.free; - } - final onX = - xAxis != Offset.zero && - fromX <= tolerance && - isWithin(alongX, 0, axisLength); - final onY = - yAxis != Offset.zero && - fromY <= tolerance && - isWithin(alongY, 0, axisLength); - if (onX && onY) { - return fromX <= fromY ? GizmoHandle.x : GizmoHandle.y; - } - return onX ? GizmoHandle.x : (onY ? GizmoHandle.y : null); - } - - /// Whether [point], which is in canvas space, is inside of the outline. - bool containsPoint(Offset point) { - return (Path()..addPolygon(corners, true)).contains(point); - } - - static double _dot(Offset a, Offset b) => a.dx * b.dx + a.dy * b.dy; - - static double _cross(Offset a, Offset b) => a.dx * b.dy - a.dy * b.dx; - - @override - bool operator ==(Object other) => - other is GizmoGeometry && - listEquals(corners, other.corners) && - anchor == other.anchor && - xAxis == other.xAxis && - yAxis == other.yAxis && - camera == other.camera; - - @override - int get hashCode => - Object.hash(Object.hashAll(corners), anchor, xAxis, yAxis, camera); -} diff --git a/packages/flame_studio/lib/src/core/gizmo/move_drag.dart b/packages/flame_studio/lib/src/core/gizmo/move_drag.dart deleted file mode 100644 index 8f568ab8a3c..00000000000 --- a/packages/flame_studio/lib/src/core/gizmo/move_drag.dart +++ /dev/null @@ -1,108 +0,0 @@ -import 'package:flame/components.dart' - show CameraComponent, PositionComponent, Vector2; -import 'package:flame_studio/src/core/gizmo/canvas_mapping.dart'; -import 'package:flame_studio/src/core/gizmo/gizmo_drag.dart'; -import 'package:flame_studio/src/core/gizmo/gizmo_geometry.dart'; -import 'package:flame_studio/src/core/snap_settings.dart'; - -/// Moves a [component] by dragging one of the handles of its gizmo. -/// -/// The drag is converted into the space of the component's parent, where its -/// position lives. Dragging an axis handle only moves the component along that -/// axis. -/// -/// Snapping places the component on a grid with cells of [snapStep] units in -/// the parent space. When dragging along an axis that isn't parallel to the -/// axes of the parent, the distance moved is snapped instead, so that the -/// component stays on the axis. -class MoveDrag._( - final PositionComponent component, - final double snapStep, - this._startPosition, - this._parentToCanvas, - this._axis, -) implements GizmoDrag { - final Vector2 _startPosition; - final ParentToCanvas _parentToCanvas; - - /// The direction of the dragged axis in the parent space, or null when the - /// drag is not constrained to an axis. - final Vector2? _axis; - - /// Starts dragging [handle] of [component], as seen through [camera]. - /// - /// Returns null when the component's parent space can't be mapped to the - /// canvas, or is degenerate (for example, scaled to zero). - static MoveDrag? start( - PositionComponent component, - GizmoHandle handle, { - required double snapStep, - CameraComponent? camera, - }) { - final parentToCanvas = ParentToCanvas.of(component, camera: camera); - if (parentToCanvas == null) { - return null; - } - Vector2? axis; - if (handle == GizmoHandle.x || handle == GizmoHandle.y) { - final localAxis = handle == GizmoHandle.x ? Vector2(1, 0) : Vector2(0, 1); - axis = - component.positionOf(localAxis) - - component.positionOf(Vector2.zero()); - if (axis.length2 == 0) { - return null; - } - axis.normalize(); - } - return MoveDrag._( - component, - snapStep, - component.position.clone(), - parentToCanvas, - axis, - ); - } - - @override - void update(Vector2 canvasDelta, {bool snap = false}) { - final delta = _parentToCanvas.canvasToParent(canvasDelta); - final axis = _axis; - if (axis == null) { - final position = _startPosition + delta; - if (snap) { - position.setValues( - snapTo(position.x, snapStep), - snapTo(position.y, snapStep), - ); - } - component.position = position; - return; - } - var distance = delta.dot(axis); - if (snap && _isParallel(axis.y)) { - final x = snapTo(_startPosition.x + distance * axis.x, snapStep); - component.position = Vector2(x, _startPosition.y); - return; - } - if (snap && _isParallel(axis.x)) { - final y = snapTo(_startPosition.y + distance * axis.y, snapStep); - component.position = Vector2(_startPosition.x, y); - return; - } - if (snap) { - distance = snapTo(distance, snapStep); - } - component.position = _startPosition + axis * distance; - } - - /// Whether an axis whose other coordinate is [otherCoordinate] is parallel - /// to one of the axes of the parent. - static bool _isParallel(double otherCoordinate) { - return otherCoordinate.abs() < 1e-9; - } - - @override - void cancel() { - component.position = _startPosition; - } -} diff --git a/packages/flame_studio/lib/src/core/gizmo/rotate_drag.dart b/packages/flame_studio/lib/src/core/gizmo/rotate_drag.dart deleted file mode 100644 index 2a63be138a2..00000000000 --- a/packages/flame_studio/lib/src/core/gizmo/rotate_drag.dart +++ /dev/null @@ -1,77 +0,0 @@ -import 'dart:ui'; - -import 'package:flame/components.dart' show PositionComponent, Vector2; -import 'package:flame_studio/src/core/gizmo/canvas_mapping.dart'; -import 'package:flame_studio/src/core/gizmo/gizmo_drag.dart'; -import 'package:flame_studio/src/core/gizmo/gizmo_geometry.dart'; -import 'package:flame_studio/src/core/snap_settings.dart'; - -/// Rotates a [component] around its anchor by dragging the ring of its gizmo. -/// -/// The component turns by the angle that the pointer sweeps around the anchor. -/// Snapping rounds the angle of the component to multiples of [snapStep], -/// which is in radians. -class RotateDrag._( - final PositionComponent component, - final double snapStep, - this._startAngle, - this._anchor, - this._startPoint, - this._direction, -) implements GizmoDrag { - final double _startAngle; - final Offset _anchor; - final Offset _startPoint; - - /// 1 when rotations on the canvas match rotations of the component, and -1 - /// when the parent space is mirrored. - final double _direction; - - /// Starts rotating [component], whose gizmo is [geometry], from - /// [startPoint] in canvas space. - /// - /// Returns null when the component's parent space can't be mapped to the - /// canvas, or when [startPoint] is at the anchor. - static RotateDrag? start( - PositionComponent component, - GizmoGeometry geometry, - Offset startPoint, { - required double snapStep, - }) { - final parentToCanvas = ParentToCanvas.of( - component, - camera: geometry.camera, - ); - if (parentToCanvas == null || startPoint == geometry.anchor) { - return null; - } - return RotateDrag._( - component, - snapStep, - component.angle, - geometry.anchor, - startPoint, - parentToCanvas.isMirrored ? -1 : 1, - ); - } - - @override - void update(Vector2 canvasDelta, {bool snap = false}) { - final point = _startPoint + Offset(canvasDelta.x, canvasDelta.y); - if (point == _anchor) { - return; - } - final sweep = - (point - _anchor).direction - (_startPoint - _anchor).direction; - var angle = _startAngle + _direction * sweep; - if (snap) { - angle = snapTo(angle, snapStep); - } - component.angle = angle; - } - - @override - void cancel() { - component.angle = _startAngle; - } -} diff --git a/packages/flame_studio/lib/src/core/gizmo/scale_drag.dart b/packages/flame_studio/lib/src/core/gizmo/scale_drag.dart deleted file mode 100644 index e65db40b832..00000000000 --- a/packages/flame_studio/lib/src/core/gizmo/scale_drag.dart +++ /dev/null @@ -1,74 +0,0 @@ -import 'dart:ui'; - -import 'package:flame/components.dart' show PositionComponent, Vector2; -import 'package:flame_studio/src/core/gizmo/gizmo_drag.dart'; -import 'package:flame_studio/src/core/gizmo/gizmo_geometry.dart'; -import 'package:flame_studio/src/core/snap_settings.dart'; - -/// Scales a [component] by dragging the handles of its gizmo. -/// -/// The axis handles scale along their axis and the square between them scales -/// both axes uniformly. Dragging a handle away from the anchor by the length of -/// an axis handle doubles the scale. Snapping rounds the scale along the -/// dragged axes to multiples of [snapStep]. -class ScaleDrag._( - final PositionComponent component, - final GizmoHandle handle, - final double snapStep, - this._startScale, - this._direction, -) implements GizmoDrag { - final Vector2 _startScale; - - /// The direction in canvas space in which dragging grows the component. - final Offset _direction; - - /// Starts dragging [handle] of [component], whose gizmo is [geometry]. - /// - /// Returns null for handles that don't scale, or when the direction of the - /// handle is degenerate. - static ScaleDrag? start( - PositionComponent component, - GizmoHandle handle, - GizmoGeometry geometry, { - required double snapStep, - }) { - final direction = switch (handle) { - GizmoHandle.x => geometry.xAxis, - GizmoHandle.y => geometry.yAxis, - GizmoHandle.free => geometry.xAxis + geometry.yAxis, - GizmoHandle.ring => Offset.zero, - }; - if (direction == Offset.zero) { - return null; - } - return ScaleDrag._( - component, - handle, - snapStep, - component.scale.clone(), - direction / direction.distance, - ); - } - - @override - void update(Vector2 canvasDelta, {bool snap = false}) { - final distance = - canvasDelta.x * _direction.dx + canvasDelta.y * _direction.dy; - final factor = 1 + distance / GizmoGeometry.axisLength; - double scaled(double value) { - final result = value * factor; - return snap ? snapTo(result, snapStep) : result; - } - - component.scale = Vector2( - handle == GizmoHandle.y ? _startScale.x : scaled(_startScale.x), - handle == GizmoHandle.x ? _startScale.y : scaled(_startScale.y), - ); - } - - @override - void cancel() { - component.scale = _startScale; - } -} diff --git a/packages/flame_studio/lib/src/core/hierarchy_expansion.dart b/packages/flame_studio/lib/src/core/hierarchy_expansion.dart deleted file mode 100644 index ae3c087bd2c..00000000000 --- a/packages/flame_studio/lib/src/core/hierarchy_expansion.dart +++ /dev/null @@ -1,36 +0,0 @@ -import 'package:flame/components.dart' show Component; -import 'package:flame_studio/src/core/game_controller.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -/// The components that are expanded in the Hierarchy. -/// -/// This lives outside of the Hierarchy panel so that it survives switching -/// tabs, and so that other panels can reveal a component in the Hierarchy. -final hierarchyExpansionProvider = - NotifierProvider>( - HierarchyExpansion.new, - ); - -class HierarchyExpansion() extends Notifier> { - @override - Set build() { - final game = ref.watch(gameControllerProvider.select((s) => s.game)); - return {if (game case final Component root) root}; - } - - void toggle(Component component) { - if (state.contains(component)) { - state = {...state}..remove(component); - } else { - state = {...state, component}; - } - } - - /// Expands all ancestors of [component], so that it becomes visible. - void reveal(Component component) { - final ancestors = component.ancestors().toList(); - if (!state.containsAll(ancestors)) { - state = {...state, ...ancestors}; - } - } -} diff --git a/packages/flame_studio/lib/src/core/inspector/component_inspectors.dart b/packages/flame_studio/lib/src/core/inspector/component_inspectors.dart deleted file mode 100644 index 752264ab110..00000000000 --- a/packages/flame_studio/lib/src/core/inspector/component_inspectors.dart +++ /dev/null @@ -1,161 +0,0 @@ -import 'dart:math'; - -import 'package:flame/components.dart' - show Component, HasPaint, HasVisibility, PositionComponent, TextComponent; -import 'package:flame_studio/src/core/inspector/inspector_property.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -/// The inspectors used to build the sections of the Inspector panel. -final componentInspectorsProvider = Provider>( - (ref) => defaultComponentInspectors, -); - -const List defaultComponentInspectors = [ - inspectComponent, - inspectPositionComponent, - inspectRendering, - inspectTextComponent, -]; - -InspectorSection inspectComponent(Component component) { - return InspectorSection('Component', [ - StringProperty( - 'Type', - () => component.runtimeType.toString(), - description: 'The class of the component', - ), - StringProperty( - 'State', - () => _lifecycleState(component), - description: 'Where the component is in its lifecycle', - ), - IntProperty( - 'Priority', - () => component.priority, - setValue: (value) => component.priority = value, - description: - 'The order of the component among its siblings. Components with a ' - 'higher priority are updated and rendered after, so on top of, the ' - 'ones with a lower priority', - ), - IntProperty( - 'Children', - () => component.children.length, - description: 'The number of direct children of the component', - ), - BoolProperty( - 'Debug mode', - () => component.debugMode, - // Children only inherit the debug mode of their parent when they are - // mounted, so it is applied to the whole subtree here. Otherwise it would - // have no visible effect on components that don't render anything, like - // the game or the world. - setValue: (value) { - for (final descendant in component.descendants(includeSelf: true)) { - descendant.debugMode = value; - } - }, - description: - 'Draws debug information, like the bounding box and position, for ' - 'the component and all of its descendants', - ), - ]); -} - -InspectorSection? inspectPositionComponent(Component component) { - if (component is! PositionComponent) { - return null; - } - return InspectorSection('Transform', [ - Vector2Property( - 'Position', - () => component.position, - setValue: (value) => component.position = value, - description: - "The position of the component's anchor, in the coordinate space of " - 'its parent', - ), - Vector2Property( - 'Size', - () => component.size, - setValue: (value) => component.size = value, - description: 'The size of the component, before scaling', - ), - Vector2Property( - 'Scale', - () => component.scale, - setValue: (value) => component.scale = value, - step: 0.01, - description: - 'How much the component and its children are stretched along each ' - 'of its axes. Negative values flip them', - ), - DoubleProperty( - 'Angle (°)', - () => component.angle * 180 / pi, - setValue: (value) => component.angle = value * pi / 180, - description: - 'The rotation of the component around its anchor, clockwise, in ' - 'degrees', - ), - AnchorProperty( - 'Anchor', - () => component.anchor, - setValue: (value) => component.anchor = value, - description: - 'The point of the component that is placed at its position, and ' - 'around which it rotates and scales', - ), - ]); -} - -InspectorSection? inspectRendering(Component component) { - final properties = >[ - if (component is HasVisibility) - BoolProperty( - 'Visible', - () => component.isVisible, - setValue: (value) => component.isVisible = value, - description: 'Whether the component and its children are rendered', - ), - if (component is HasPaint) - DoubleProperty( - 'Opacity', - () => component.opacity, - setValue: (value) => component.opacity = value, - step: 0.01, - min: 0, - max: 1, - description: - 'How opaque the paint of the component is, from 0 (invisible) to 1', - ), - ]; - return properties.isEmpty ? null : InspectorSection('Rendering', properties); -} - -InspectorSection? inspectTextComponent(Component component) { - if (component is! TextComponent) { - return null; - } - return InspectorSection('Text', [ - StringProperty( - 'Text', - () => component.text, - setValue: (value) => component.text = value, - description: 'The text that is rendered by the component', - ), - ]); -} - -String _lifecycleState(Component component) { - if (component.isRemoving) { - return 'Removing'; - } - if (component.isMounted) { - return 'Mounted'; - } - if (component.isLoaded) { - return 'Loaded'; - } - return component.isLoading ? 'Loading' : 'Detached'; -} diff --git a/packages/flame_studio/lib/src/core/inspector/inspector_property.dart b/packages/flame_studio/lib/src/core/inspector/inspector_property.dart deleted file mode 100644 index eac4244bb37..00000000000 --- a/packages/flame_studio/lib/src/core/inspector/inspector_property.dart +++ /dev/null @@ -1,80 +0,0 @@ -import 'package:flame/components.dart' show Anchor, Component, Vector2; - -/// Builds the [InspectorSection] for a [component], or returns null when the -/// component is not of the kind this inspector is interested in. -/// -/// The Inspector panel shows one section for each inspector that returns a -/// non-null section, in order. -typedef ComponentInspector = InspectorSection? Function(Component component); - -/// A titled group of properties shown in the Inspector, similar to the -/// component sections of the Unity inspector. -class InspectorSection( - final String title, - final List> properties, -); - -/// A single value of a component, shown and possibly edited in the Inspector. -/// -/// The [getValue] callback is invoked every time the Inspector refreshes, so -/// that the shown value is kept in sync with the running game. When [setValue] -/// is null, the property is read-only. The [description] is shown as the -/// tooltip of the property. -sealed class InspectorProperty( - final String label, - final T Function() getValue, { - final void Function(T value)? setValue, - final String? description, -}) { - bool get isReadOnly => setValue == null; -} - -/// A floating point number. Dragging the label horizontally changes the value -/// by [step] per logical pixel. -class DoubleProperty( - super.label, - super.getValue, { - super.setValue, - super.description, - final double step = 1.0, - final double? min, - final double? max, -}) extends InspectorProperty; - -class IntProperty( - super.label, - super.getValue, { - super.setValue, - super.description, -}) extends InspectorProperty; - -class BoolProperty( - super.label, - super.getValue, { - super.setValue, - super.description, -}) extends InspectorProperty; - -class StringProperty( - super.label, - super.getValue, { - super.setValue, - super.description, -}) extends InspectorProperty; - -/// A [Vector2] value. The value passed to `setValue` is always a new vector, -/// so it is safe to keep a reference to it. -class Vector2Property( - super.label, - super.getValue, { - super.setValue, - super.description, - final double step = 1.0, -}) extends InspectorProperty; - -class AnchorProperty( - super.label, - super.getValue, { - super.setValue, - super.description, -}) extends InspectorProperty; diff --git a/packages/flame_studio/lib/src/core/selection.dart b/packages/flame_studio/lib/src/core/selection.dart deleted file mode 100644 index 24f4de51412..00000000000 --- a/packages/flame_studio/lib/src/core/selection.dart +++ /dev/null @@ -1,25 +0,0 @@ -import 'package:flame/components.dart' show Component; -import 'package:flame_studio/src/core/game_controller.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -/// The component that is currently selected in the studio. -/// -/// This is shared by all panels: the Hierarchy changes it, and the Inspector -/// shows its properties. The selection is cleared whenever the game changes. -final selectedComponentProvider = - NotifierProvider( - SelectionController.new, - ); - -class SelectionController() extends Notifier { - @override - Component? build() { - ref.watch(gameControllerProvider.select((s) => s.game)); - return null; - } - - // ignore: use_setters_to_change_properties - void select(Component? component) => state = component; - - void clear() => state = null; -} diff --git a/packages/flame_studio/lib/src/core/snap_settings.dart b/packages/flame_studio/lib/src/core/snap_settings.dart deleted file mode 100644 index e88f9f80374..00000000000 --- a/packages/flame_studio/lib/src/core/snap_settings.dart +++ /dev/null @@ -1,27 +0,0 @@ -import 'dart:math'; - -import 'package:flutter/foundation.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -/// The increments that the gizmo tools snap to while Shift is held. -final snapSettingsProvider = Provider((ref) => const SnapSettings()); - -@immutable -class const SnapSettings({ - /// The size of the grid that moved components snap to, in the units of - /// their parent. - final double moveStep = 8.0, - - /// The angle that rotations snap to multiples of, in radians. - final double rotateStep = pi / 12, - - /// The value that scales snap to multiples of. - final double scaleStep = 0.1, -}) { - double get rotateStepDegrees => rotateStep * 180 / pi; -} - -/// Rounds [value] to the nearest multiple of [step]. -double snapTo(double value, double step) { - return (value / step).roundToDouble() * step; -} diff --git a/packages/flame_studio/lib/src/core/theme.dart b/packages/flame_studio/lib/src/core/theme.dart deleted file mode 100644 index a2bbcd7a0fe..00000000000 --- a/packages/flame_studio/lib/src/core/theme.dart +++ /dev/null @@ -1,46 +0,0 @@ -import 'dart:ui'; - -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -final textDirectionProvider = Provider((ref) => TextDirection.ltr); - -final themeProvider = Provider((ref) => Theme()); - -class Theme() { - final Color backdropColor = const Color(0xFF484848); - final Color toolbarColor = const Color(0xFF303030); - final Color panelColor = const Color(0xFF383838); - - final double buttonRadius = 5.0; - final Color buttonColor = const Color(0xFF404040); - final Color buttonHoverColor = const Color(0xFF606060); - final Color buttonActiveColor = const Color(0xFFA0A0A0); - final Color buttonToggledColor = const Color(0xFF8A5A1E); - final Color buttonDisabledColor = const Color(0x44404040); - final Color buttonTextColor = const Color(0xFFffd78d); - final Color buttonHoverTextColor = const Color(0xffffe95d); - final Color buttonActiveTextColor = const Color(0xffffffff); - final Color buttonDisabledTextColor = const Color(0x16ffffff); - - final double fontSize = 12.0; - final Color textColor = const Color(0xFFE6E6E6); - final Color dimTextColor = const Color(0xFF9A9A9A); - final Color accentColor = const Color(0xFFC78938); - final Color hoverColor = const Color(0x14FFFFFF); - final Color tooltipColor = const Color(0xF0202020); - - final double tabBarHeight = 26.0; - final Color tabBarColor = const Color(0xFF2C2C2C); - final Color sectionHeaderColor = const Color(0xFF424242); - - final double rowHeight = 22.0; - final Color fieldColor = const Color(0xFF2A2A2A); - final Color fieldBorderColor = const Color(0xFF505050); - - final Color gizmoColor = const Color(0xFFFFA726); - final Color gizmoXAxisColor = const Color(0xFFE5534B); - final Color gizmoYAxisColor = const Color(0xFF57AB5A); - final Color gizmoRotationColor = const Color(0xFF4A90E2); - final Color gizmoActiveColor = const Color(0xFFFFEB3B); - final Color gizmoHaloColor = const Color(0xB3000000); -} diff --git a/packages/flame_studio/lib/src/core/viewport_tool.dart b/packages/flame_studio/lib/src/core/viewport_tool.dart deleted file mode 100644 index 4fd697c3159..00000000000 --- a/packages/flame_studio/lib/src/core/viewport_tool.dart +++ /dev/null @@ -1,84 +0,0 @@ -import 'package:flame/components.dart' - show Component, PositionComponent, Vector2; -import 'package:flame_studio/src/core/gizmo/gizmo_geometry.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -/// What happens when the user interacts with the game view. -enum ViewportTool() { - /// Pointer events are handled by the game, as if the studio wasn't there. - interact, - - /// Clicking on the game selects the component under the pointer. The game - /// does not receive the pointer events. - select, - - /// Like [select], and dragging the selected component or the handles of its - /// gizmo moves it. - move, - - /// Like [select], and dragging the ring of the gizmo rotates the selected - /// component around its anchor. - rotate, - - /// Like [select], and dragging the handles of the gizmo scales the selected - /// component. - scale, -} - -final viewportToolProvider = - NotifierProvider( - ViewportToolController.new, - ); - -class ViewportToolController() extends Notifier { - @override - ViewportTool build() => ViewportTool.interact; - - // ignore: use_setters_to_change_properties - void use(ViewportTool tool) => state = tool; -} - -/// The gizmo handle under the pointer, or being dragged, if any. -final activeGizmoHandleProvider = - NotifierProvider( - ActiveGizmoHandleController.new, - ); - -class ActiveGizmoHandleController() extends Notifier { - @override - GizmoHandle? build() { - ref.watch(viewportToolProvider); - return null; - } - - // ignore: use_setters_to_change_properties - void set(GizmoHandle? handle) => state = handle; -} - -/// The components that can be selected at [canvasPoint], which is in the -/// canvas space of the game rooted at [root], with the topmost first. -List selectableComponentsAt( - Component root, - Vector2 canvasPoint, -) { - return root - .componentsAtPoint(canvasPoint) - .whereType() - .toList(); -} - -/// Picks which of the [candidates] to select when clicking on them. -/// -/// This is the topmost candidate, unless the [current] selection is one of -/// them, in which case it is the one below it. Clicking repeatedly at the same -/// point thus cycles through all the overlapping components. -PositionComponent? pickNext( - List candidates, - Component? current, -) { - if (candidates.isEmpty) { - return null; - } - final index = current is PositionComponent ? candidates.indexOf(current) : -1; - return candidates[(index + 1) % candidates.length]; -} diff --git a/packages/flame_studio/lib/src/run_flame_studio.dart b/packages/flame_studio/lib/src/run_flame_studio.dart deleted file mode 100644 index 20591be1198..00000000000 --- a/packages/flame_studio/lib/src/run_flame_studio.dart +++ /dev/null @@ -1,16 +0,0 @@ -import 'package:flame_studio/src/widgets/flame_studio.dart'; -import 'package:flutter/widgets.dart'; - -void runFlameStudio(Widget app, {bool enabled = true}) { - var allowRun = true; - assert(() { - if (enabled) { - runApp(FlameStudio(app)); - allowRun = false; - } - return true; - }()); - if (allowRun) { - runApp(app); - } -} diff --git a/packages/flame_studio/lib/src/widgets/common/disclosure_triangle.dart b/packages/flame_studio/lib/src/widgets/common/disclosure_triangle.dart deleted file mode 100644 index a49ac33c824..00000000000 --- a/packages/flame_studio/lib/src/widgets/common/disclosure_triangle.dart +++ /dev/null @@ -1,42 +0,0 @@ -import 'package:flutter/widgets.dart'; - -/// A small triangle pointing right when collapsed and down when expanded. -class const DisclosureTriangle({ - required final bool isExpanded, - required final Color color, - super.key, -}) extends StatelessWidget { - @override - Widget build(BuildContext context) { - return CustomPaint( - size: const Size(16, 16), - painter: _TrianglePainter(isExpanded: isExpanded, color: color), - ); - } -} - -class _TrianglePainter({ - required final bool isExpanded, - required final Color color, -}) extends CustomPainter { - @override - void paint(Canvas canvas, Size size) { - canvas.translate(size.width / 2, size.height / 2); - final path = isExpanded - ? (Path() - ..moveTo(-4, -2) - ..lineTo(4, -2) - ..lineTo(0, 3) - ..close()) - : (Path() - ..moveTo(-2, -4) - ..lineTo(3, 0) - ..lineTo(-2, 4) - ..close()); - canvas.drawPath(path, Paint()..color = color); - } - - @override - bool shouldRepaint(_TrianglePainter old) => - isExpanded != old.isExpanded || color != old.color; -} diff --git a/packages/flame_studio/lib/src/widgets/common/studio_text_field.dart b/packages/flame_studio/lib/src/widgets/common/studio_text_field.dart deleted file mode 100644 index 0d692de4264..00000000000 --- a/packages/flame_studio/lib/src/widgets/common/studio_text_field.dart +++ /dev/null @@ -1,126 +0,0 @@ -import 'package:flame_studio/src/core/theme.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -/// A single-line text field in the style of the studio. -/// -/// It is built on top of [EditableText], so that the studio does not depend on -/// the Material library. While the field is not focused it shows [value]. -/// Edits are reported through [onChanged] as they are typed, and through -/// [onSubmitted] when the user presses Enter or the field loses focus. Pressing -/// Escape discards the edit. -class const StudioTextField({ - required final String value, - final ValueChanged? onChanged, - final ValueChanged? onSubmitted, - final String? placeholder, - final bool selectAllOnFocus = false, - super.key, -}) extends ConsumerStatefulWidget { - @override - ConsumerState createState() => _StudioTextFieldState(); -} - -class _StudioTextFieldState() extends ConsumerState { - late final TextEditingController _controller = TextEditingController( - text: widget.value, - ); - final FocusNode _focusNode = FocusNode(); - - @override - void initState() { - super.initState(); - _focusNode.addListener(_handleFocusChange); - } - - @override - void didUpdateWidget(StudioTextField oldWidget) { - super.didUpdateWidget(oldWidget); - if (!_focusNode.hasFocus && _controller.text != widget.value) { - _controller.text = widget.value; - } - } - - @override - void dispose() { - _focusNode.dispose(); - _controller.dispose(); - super.dispose(); - } - - void _handleFocusChange() { - if (_focusNode.hasFocus) { - if (widget.selectAllOnFocus) { - _controller.selection = TextSelection( - baseOffset: 0, - extentOffset: _controller.text.length, - ); - } - } else if (_controller.text != widget.value) { - widget.onSubmitted?.call(_controller.text); - } - setState(() {}); - } - - void _cancel() { - _controller.text = widget.value; - _focusNode.unfocus(); - } - - @override - Widget build(BuildContext context) { - final theme = ref.watch(themeProvider); - final textStyle = TextStyle( - color: theme.textColor, - fontSize: theme.fontSize, - ); - final placeholder = widget.placeholder; - - return CallbackShortcuts( - bindings: {const SingleActivator(LogicalKeyboardKey.escape): _cancel}, - child: MouseRegion( - cursor: SystemMouseCursors.text, - child: Container( - height: theme.rowHeight - 2, - padding: const EdgeInsets.symmetric(horizontal: 4), - alignment: Alignment.centerLeft, - decoration: BoxDecoration( - color: theme.fieldColor, - border: Border.all( - color: _focusNode.hasFocus - ? theme.accentColor - : theme.fieldBorderColor, - ), - borderRadius: BorderRadius.circular(3), - ), - child: Stack( - alignment: Alignment.centerLeft, - children: [ - if (placeholder != null) - ValueListenableBuilder( - valueListenable: _controller, - builder: (context, value, _) => value.text.isEmpty - ? Text( - placeholder, - style: textStyle.copyWith(color: theme.dimTextColor), - ) - : const SizedBox.shrink(), - ), - EditableText( - controller: _controller, - focusNode: _focusNode, - style: textStyle, - cursorColor: theme.accentColor, - backgroundCursorColor: theme.dimTextColor, - selectionColor: theme.accentColor.withAlpha(0x80), - cursorWidth: 1.0, - onChanged: widget.onChanged, - ), - ], - ), - ), - ), - ); - } -} diff --git a/packages/flame_studio/lib/src/widgets/common/studio_tooltip.dart b/packages/flame_studio/lib/src/widgets/common/studio_tooltip.dart deleted file mode 100644 index 187710a3f54..00000000000 --- a/packages/flame_studio/lib/src/widgets/common/studio_tooltip.dart +++ /dev/null @@ -1,162 +0,0 @@ -import 'dart:async'; - -import 'package:flame_studio/src/core/theme.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -/// The tooltip that is currently shown, if any. -/// -/// The studio doesn't have an [Overlay], so tooltips are requested through -/// this provider and drawn by the [TooltipLayer], which sits on top of the -/// whole studio. -final tooltipProvider = NotifierProvider( - TooltipController.new, -); - -/// A tooltip with [message], shown below the widget that is linked to [link]. -/// -/// It is aligned with the left edge of that widget, or with its right edge -/// when [alignRight] is true, to keep it inside of the window. -@immutable -class const TooltipRequest({ - required final String message, - required final LayerLink link, - final bool alignRight = false, -}); - -class TooltipController() extends Notifier { - @override - TooltipRequest? build() => null; - - // ignore: use_setters_to_change_properties - void show(TooltipRequest request) => state = request; - - /// Hides the tooltip, if it is the one linked to [link]. - void hide(LayerLink link) { - if (state?.link == link) { - state = null; - } - } -} - -/// Shows [message] in a tooltip when the pointer hovers over [child] for a -/// moment. The tooltip is hidden when the pointer leaves or presses [child]. -class const StudioTooltip({ - required final String message, - required final Widget child, - super.key, -}) extends ConsumerStatefulWidget { - static const Duration delay = Duration(milliseconds: 500); - - @override - ConsumerState createState() => _StudioTooltipState(); -} - -class _StudioTooltipState() extends ConsumerState { - final LayerLink _link = LayerLink(); - Timer? _timer; - - @override - void dispose() { - // The tooltip layer stops showing the tooltip once its link is gone. - _timer?.cancel(); - super.dispose(); - } - - void _scheduleShow() { - _timer?.cancel(); - _timer = Timer(StudioTooltip.delay, _show); - } - - void _show() { - final box = context.findRenderObject(); - if (!mounted || box is! RenderBox || !box.attached) { - return; - } - final center = box.localToGlobal(box.size.center(Offset.zero)); - final windowWidth = MediaQuery.maybeSizeOf(context)?.width; - ref - .read(tooltipProvider.notifier) - .show( - TooltipRequest( - message: widget.message, - link: _link, - alignRight: windowWidth != null && center.dx > windowWidth / 2, - ), - ); - } - - void _hide() { - _timer?.cancel(); - ref.read(tooltipProvider.notifier).hide(_link); - } - - @override - Widget build(BuildContext context) { - return CompositedTransformTarget( - link: _link, - child: MouseRegion( - onEnter: (_) => _scheduleShow(), - onExit: (_) => _hide(), - child: Listener( - onPointerDown: (_) => _hide(), - child: widget.child, - ), - ), - ); - } -} - -/// Draws the tooltip requested through the [tooltipProvider]. -/// -/// It must cover the whole studio and be above everything else in it. It -/// doesn't take part in hit testing. -class const TooltipLayer({super.key}) extends ConsumerWidget { - static const double maxWidth = 280.0; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final request = ref.watch(tooltipProvider); - if (request == null) { - return const SizedBox.shrink(); - } - final theme = ref.watch(themeProvider); - final alignment = request.alignRight - ? (Alignment.bottomRight, Alignment.topRight) - : (Alignment.bottomLeft, Alignment.topLeft); - return IgnorePointer( - child: Stack( - children: [ - Positioned( - left: 0, - top: 0, - child: CompositedTransformFollower( - link: request.link, - showWhenUnlinked: false, - targetAnchor: alignment.$1, - followerAnchor: alignment.$2, - offset: const Offset(0, 4), - child: Container( - constraints: const BoxConstraints(maxWidth: maxWidth), - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5), - decoration: BoxDecoration( - color: theme.tooltipColor, - border: Border.all(color: theme.fieldBorderColor), - borderRadius: BorderRadius.circular(4), - boxShadow: const [ - BoxShadow( - blurRadius: 6, - color: Color(0x80000000), - offset: Offset(0, 2), - ), - ], - ), - child: Text(request.message), - ), - ), - ), - ], - ), - ); - } -} diff --git a/packages/flame_studio/lib/src/widgets/dock/dock_layout.dart b/packages/flame_studio/lib/src/widgets/dock/dock_layout.dart deleted file mode 100644 index 06dbcfebc1f..00000000000 --- a/packages/flame_studio/lib/src/widgets/dock/dock_layout.dart +++ /dev/null @@ -1,79 +0,0 @@ -import 'package:flame_studio/src/widgets/panels/hierarchy_view.dart'; -import 'package:flame_studio/src/widgets/panels/inspector_view.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -enum DockSide() { - left, - right, -} - -/// A tab that can be shown inside of a dock, such as the Hierarchy. -@immutable -class const DockTab({ - required final String title, - required final String tooltip, - required final WidgetBuilder builder, -}); - -/// The tabs shown in each dock, in order. -final dockTabsProvider = Provider.family, DockSide>( - (ref, side) => switch (side) { - DockSide.left => [ - DockTab( - title: 'Hierarchy', - tooltip: 'The tree of components in the game', - builder: (_) => const HierarchyView(), - ), - ], - DockSide.right => [ - DockTab( - title: 'Inspector', - tooltip: 'The properties of the selected component', - builder: (_) => const InspectorView(), - ), - ], - }, -); - -final dockProvider = - NotifierProvider.family( - DockController.new, - ); - -@immutable -class const DockState({required final double width, final int activeTab = 0}) { - DockState copyWith({double? width, int? activeTab}) { - return DockState( - width: width ?? this.width, - activeTab: activeTab ?? this.activeTab, - ); - } - - @override - bool operator ==(Object other) => - other is DockState && - width == other.width && - activeTab == other.activeTab; - - @override - int get hashCode => Object.hash(width, activeTab); -} - -class DockController(final DockSide side) extends Notifier { - static const minWidth = 200.0; - static const maxWidth = 500.0; - - @override - DockState build() { - return DockState(width: side == DockSide.left ? 260.0 : 300.0); - } - - void setWidth(double value) { - state = state.copyWith(width: value.clamp(minWidth, maxWidth)); - } - - void selectTab(int index) { - state = state.copyWith(activeTab: index); - } -} diff --git a/packages/flame_studio/lib/src/widgets/dock/dock_panel.dart b/packages/flame_studio/lib/src/widgets/dock/dock_panel.dart deleted file mode 100644 index 4c98f5e5f34..00000000000 --- a/packages/flame_studio/lib/src/widgets/dock/dock_panel.dart +++ /dev/null @@ -1,154 +0,0 @@ -import 'package:flame_studio/src/core/theme.dart'; -import 'package:flame_studio/src/widgets/common/studio_tooltip.dart'; -import 'package:flame_studio/src/widgets/dock/dock_layout.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -/// A resizable panel on one [side] of the studio, showing one of its tabs at -/// a time. -class const DockPanel(final DockSide side, {super.key}) extends ConsumerWidget { - static const double _gripWidth = 6.0; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final theme = ref.watch(themeProvider); - final dock = ref.watch(dockProvider(side)); - final tabs = ref.watch(dockTabsProvider(side)); - final activeTab = dock.activeTab.clamp(0, tabs.length - 1); - final isLeft = side == DockSide.left; - - return Container( - constraints: BoxConstraints.tightFor(width: dock.width), - decoration: BoxDecoration( - boxShadow: [ - BoxShadow( - blurRadius: 4.0, - color: const Color(0xA1000000), - offset: Offset(isLeft ? 2 : -2, 0), - ), - ], - color: theme.panelColor, - ), - child: Stack( - children: [ - Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _TabBar(side, tabs, activeTab), - Expanded( - child: KeyedSubtree( - key: ValueKey(tabs[activeTab].title), - child: Builder(builder: tabs[activeTab].builder), - ), - ), - ], - ), - Positioned( - top: 0, - bottom: 0, - left: isLeft ? null : 0, - right: isLeft ? 0 : null, - width: _gripWidth, - child: _DockGrip(side), - ), - ], - ), - ); - } -} - -class const _TabBar( - final DockSide side, - final List tabs, - final int activeTab, -) extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final theme = ref.watch(themeProvider); - return Container( - height: theme.tabBarHeight, - color: theme.tabBarColor, - child: Row( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - for (var i = 0; i < tabs.length; i++) - _Tab( - tabs[i], - isActive: i == activeTab, - onTap: () => ref.read(dockProvider(side).notifier).selectTab(i), - ), - ], - ), - ); - } -} - -class const _Tab( - final DockTab tab, { - required final bool isActive, - required final VoidCallback onTap, -}) extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final theme = ref.watch(themeProvider); - return StudioTooltip( - message: tab.tooltip, - child: MouseRegion( - cursor: SystemMouseCursors.click, - child: GestureDetector( - onTap: onTap, - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 12), - alignment: Alignment.center, - decoration: isActive - ? BoxDecoration( - color: theme.panelColor, - border: Border( - top: BorderSide(color: theme.accentColor, width: 2), - ), - ) - : null, - child: Text( - tab.title, - style: TextStyle( - color: isActive ? theme.textColor : theme.dimTextColor, - ), - ), - ), - ), - ), - ); - } -} - -/// The handle on the inner edge of a dock, used to resize it. -class const _DockGrip(final DockSide side) extends ConsumerStatefulWidget { - @override - ConsumerState<_DockGrip> createState() => _DockGripState(); -} - -class _DockGripState() extends ConsumerState<_DockGrip> { - double _startWidth = 0; - double _startX = 0; - - @override - Widget build(BuildContext context) { - final side = widget.side; - return MouseRegion( - cursor: SystemMouseCursors.resizeLeftRight, - child: GestureDetector( - behavior: HitTestBehavior.opaque, - onHorizontalDragStart: (details) { - _startWidth = ref.read(dockProvider(side)).width; - _startX = details.globalPosition.dx; - }, - onHorizontalDragUpdate: (details) { - final delta = details.globalPosition.dx - _startX; - ref - .read(dockProvider(side).notifier) - .setWidth(_startWidth + (side == DockSide.left ? delta : -delta)); - }, - ), - ); - } -} diff --git a/packages/flame_studio/lib/src/widgets/flame_studio.dart b/packages/flame_studio/lib/src/widgets/flame_studio.dart deleted file mode 100644 index 8a21a258059..00000000000 --- a/packages/flame_studio/lib/src/widgets/flame_studio.dart +++ /dev/null @@ -1,13 +0,0 @@ -import 'package:flame_studio/src/widgets/ui_scaffold.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -class const FlameStudio(final Widget child, {super.key}) - extends StatelessWidget { - @override - Widget build(BuildContext context) { - return ProviderScope( - child: UiScaffold(gameApp: child), - ); - } -} diff --git a/packages/flame_studio/lib/src/widgets/panels/hierarchy_view.dart b/packages/flame_studio/lib/src/widgets/panels/hierarchy_view.dart deleted file mode 100644 index 58c4ed472e7..00000000000 --- a/packages/flame_studio/lib/src/widgets/panels/hierarchy_view.dart +++ /dev/null @@ -1,210 +0,0 @@ -import 'package:flame/components.dart' show Component; -import 'package:flame_studio/src/core/component_tree.dart'; -import 'package:flame_studio/src/core/hierarchy_expansion.dart'; -import 'package:flame_studio/src/core/selection.dart'; -import 'package:flame_studio/src/core/theme.dart'; -import 'package:flame_studio/src/widgets/common/disclosure_triangle.dart'; -import 'package:flame_studio/src/widgets/common/studio_text_field.dart'; -import 'package:flame_studio/src/widgets/common/studio_tooltip.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -/// Shows the component tree of the game, and allows to select a component. -/// -/// When the filter is not empty, only the components whose type name contains -/// the filter are shown, together with their ancestors. -class const HierarchyView({super.key}) extends ConsumerStatefulWidget { - static const double indentWidth = 14.0; - - @override - ConsumerState createState() => _HierarchyViewState(); -} - -class _HierarchyViewState() extends ConsumerState { - String _filter = ''; - - @override - Widget build(BuildContext context) { - final theme = ref.watch(themeProvider); - final root = ref.watch(componentTreeProvider).root; - final expanded = ref.watch(hierarchyExpansionProvider); - final selected = ref.watch(selectedComponentProvider); - ref.listen(selectedComponentProvider, (_, component) { - if (component != null) { - ref.read(hierarchyExpansionProvider.notifier).reveal(component); - } - }); - - final rows = <_RowData>[]; - if (root != null) { - final query = _filter.trim().toLowerCase(); - if (query.isEmpty) { - _flatten(root, 0, expanded, rows); - } else { - _flattenFiltered(root, 0, query, rows); - } - } - - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Padding( - padding: const EdgeInsets.all(6), - child: StudioTooltip( - message: - 'Only show the components whose type contains this text, ' - 'together with their ancestors', - child: StudioTextField( - value: _filter, - placeholder: 'Filter', - onChanged: (value) => setState(() => _filter = value), - ), - ), - ), - Expanded( - child: root == null - ? Center( - child: Text( - 'Waiting for a game…', - style: TextStyle(color: theme.dimTextColor), - ), - ) - : ListView.builder( - itemCount: rows.length, - itemExtent: theme.rowHeight, - itemBuilder: (context, index) { - final row = rows[index]; - return _HierarchyRow( - row, - isSelected: row.node.component == selected, - canToggle: _filter.trim().isEmpty, - key: ObjectKey(row.node.component), - ); - }, - ), - ), - ], - ); - } - - static void _flatten( - ComponentTreeNode node, - int depth, - Set expanded, - List<_RowData> out, - ) { - final isExpanded = expanded.contains(node.component); - out.add(_RowData(node, depth, isExpanded: isExpanded)); - if (isExpanded && node.hasChildren) { - for (final child in node.children!) { - _flatten(child, depth + 1, expanded, out); - } - } - } - - /// Adds [node] to [out] if it or any of its descendants matches the [query], - /// and returns whether it was added. - static bool _flattenFiltered( - ComponentTreeNode node, - int depth, - String query, - List<_RowData> out, - ) { - final index = out.length; - var hasMatchingChild = false; - out.add(_RowData(node, depth, isExpanded: false)); - for (final child in node.children ?? const []) { - hasMatchingChild |= _flattenFiltered(child, depth + 1, query, out); - } - if (!hasMatchingChild && !node.name.toLowerCase().contains(query)) { - out.removeRange(index, out.length); - return false; - } - out[index] = _RowData(node, depth, isExpanded: hasMatchingChild); - return true; - } -} - -class const _RowData( - final ComponentTreeNode node, - final int depth, { - required final bool isExpanded, -}); - -class const _HierarchyRow( - final _RowData row, { - required final bool isSelected, - required final bool canToggle, - super.key, -}) extends ConsumerStatefulWidget { - @override - ConsumerState<_HierarchyRow> createState() => _HierarchyRowState(); -} - -class _HierarchyRowState() extends ConsumerState<_HierarchyRow> { - bool _isHovered = false; - - @override - Widget build(BuildContext context) { - final theme = ref.watch(themeProvider); - final row = widget.row; - final node = row.node; - - Widget expander = const SizedBox(width: 16); - if (node.hasChildren) { - expander = DisclosureTriangle( - isExpanded: row.isExpanded, - color: widget.isSelected ? theme.textColor : theme.dimTextColor, - ); - if (widget.canToggle) { - expander = GestureDetector( - onTap: () => ref - .read(hierarchyExpansionProvider.notifier) - .toggle(node.component), - child: expander, - ); - } - } - - return MouseRegion( - cursor: SystemMouseCursors.click, - onEnter: (_) => setState(() => _isHovered = true), - onExit: (_) => setState(() => _isHovered = false), - child: GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () => - ref.read(selectedComponentProvider.notifier).select(node.component), - child: Container( - color: widget.isSelected - ? theme.accentColor - : (_isHovered ? theme.hoverColor : null), - padding: EdgeInsets.only( - left: 4 + row.depth * HierarchyView.indentWidth, - right: 8, - ), - child: Row( - children: [ - expander, - Expanded( - child: Text( - node.name, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - if (node.hasChildren && !row.isExpanded) - Text( - '${node.children!.length}', - style: TextStyle( - color: widget.isSelected - ? theme.textColor - : theme.dimTextColor, - ), - ), - ], - ), - ), - ), - ); - } -} diff --git a/packages/flame_studio/lib/src/widgets/panels/inspector/property_editors.dart b/packages/flame_studio/lib/src/widgets/panels/inspector/property_editors.dart deleted file mode 100644 index 171bc1166cb..00000000000 --- a/packages/flame_studio/lib/src/widgets/panels/inspector/property_editors.dart +++ /dev/null @@ -1,306 +0,0 @@ -import 'package:flame/components.dart' show Anchor, Vector2; -import 'package:flame_studio/src/core/theme.dart'; -import 'package:flame_studio/src/widgets/common/studio_text_field.dart'; -import 'package:flame_studio/src/widgets/common/studio_tooltip.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -/// Formats [value] with up to three decimals, without trailing zeros. -String formatNumber(double value) { - if (!value.isFinite) { - return value.toString(); - } - final text = value.toStringAsFixed(3).replaceFirst(RegExp(r'\.?0+$'), ''); - return text == '-0' ? '0' : text; -} - -/// A label that changes a numeric value when dragged horizontally, like the -/// field labels in the Unity inspector. -/// -/// When [onDrag] is null, this is a plain label. -class const ScrubLabel( - final String text, { - final ValueChanged? onDrag, - final String? tooltip, - super.key, -}) extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final theme = ref.watch(themeProvider); - final label = Text( - text, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(color: theme.dimTextColor), - ); - final onDrag = this.onDrag; - final result = onDrag == null - ? label - : MouseRegion( - cursor: SystemMouseCursors.resizeLeftRight, - child: GestureDetector( - behavior: HitTestBehavior.opaque, - onHorizontalDragUpdate: (details) => onDrag(details.delta.dx), - child: label, - ), - ); - final tooltip = this.tooltip; - return tooltip == null - ? result - : StudioTooltip(message: tooltip, child: result); - } -} - -class const ReadOnlyValue(final String text, {super.key}) - extends StatelessWidget { - @override - Widget build(BuildContext context) { - return Align( - alignment: Alignment.centerLeft, - child: Text(text, maxLines: 1, overflow: TextOverflow.ellipsis), - ); - } -} - -/// Shows a number, which can be edited when [onSubmitted] is not null. -/// -/// Input that is not a valid number is discarded. -class const NumberField( - final double value, { - final ValueChanged? onSubmitted, - final bool isInteger = false, - super.key, -}) extends StatelessWidget { - @override - Widget build(BuildContext context) { - final text = isInteger ? value.round().toString() : formatNumber(value); - final onSubmitted = this.onSubmitted; - if (onSubmitted == null) { - return ReadOnlyValue(text); - } - return StudioTextField( - value: text, - selectAllOnFocus: true, - onSubmitted: (text) { - final number = double.tryParse(text.trim()); - if (number != null && number.isFinite) { - onSubmitted(number); - } - }, - ); - } -} - -/// Edits the two components of a [Vector2], each with its own [ScrubLabel]. -class const Vector2Field( - final Vector2 value, { - final ValueChanged? onChanged, - final double step = 1.0, - super.key, -}) extends StatelessWidget { - @override - Widget build(BuildContext context) { - final onChanged = this.onChanged; - final x = value.x; - final y = value.y; - final setX = onChanged == null - ? null - : (double newX) => onChanged(Vector2(newX, y)); - final setY = onChanged == null - ? null - : (double newY) => onChanged(Vector2(x, newY)); - - return Row( - children: [ - ScrubLabel( - 'X', - onDrag: setX == null ? null : (dx) => setX(x + dx * step), - ), - const SizedBox(width: 4), - Expanded(child: NumberField(x, onSubmitted: setX)), - const SizedBox(width: 8), - ScrubLabel( - 'Y', - onDrag: setY == null ? null : (dx) => setY(y + dx * step), - ), - const SizedBox(width: 4), - Expanded(child: NumberField(y, onSubmitted: setY)), - ], - ); - } -} - -class const StudioCheckbox({ - required final bool value, - final ValueChanged? onChanged, - super.key, -}) extends ConsumerWidget { - static const double _size = 14.0; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final theme = ref.watch(themeProvider); - final onChanged = this.onChanged; - final box = CustomPaint( - size: const Size.square(_size), - painter: _CheckboxPainter( - isChecked: value, - fillColor: onChanged == null ? theme.dimTextColor : theme.accentColor, - borderColor: theme.fieldBorderColor, - backgroundColor: theme.fieldColor, - ), - ); - return Align( - alignment: Alignment.centerLeft, - child: onChanged == null - ? box - : MouseRegion( - cursor: SystemMouseCursors.click, - child: GestureDetector( - onTap: () => onChanged(!value), - child: box, - ), - ), - ); - } -} - -class _CheckboxPainter({ - required final bool isChecked, - required final Color fillColor, - required final Color borderColor, - required final Color backgroundColor, -}) extends CustomPainter { - @override - void paint(Canvas canvas, Size size) { - final rect = RRect.fromRectAndRadius( - Offset.zero & size, - const Radius.circular(3), - ); - canvas.drawRRect( - rect, - Paint()..color = isChecked ? fillColor : backgroundColor, - ); - if (isChecked) { - final check = Path() - ..moveTo(size.width * 0.22, size.height * 0.52) - ..lineTo(size.width * 0.42, size.height * 0.72) - ..lineTo(size.width * 0.78, size.height * 0.3); - canvas.drawPath( - check, - Paint() - ..color = const Color(0xFFFFFFFF) - ..style = PaintingStyle.stroke - ..strokeWidth = 2, - ); - } else { - canvas.drawRRect( - rect.deflate(0.5), - Paint() - ..color = borderColor - ..style = PaintingStyle.stroke, - ); - } - } - - @override - bool shouldRepaint(_CheckboxPainter old) => - isChecked != old.isChecked || - fillColor != old.fillColor || - borderColor != old.borderColor || - backgroundColor != old.backgroundColor; -} - -/// Picks one of the nine predefined anchors from a 3x3 grid. Custom anchors -/// are shown, but can only be replaced by one of the predefined ones. -class const AnchorPicker( - final Anchor value, { - final ValueChanged? onChanged, - super.key, -}) extends ConsumerWidget { - static const List> _grid = [ - [Anchor.topLeft, Anchor.topCenter, Anchor.topRight], - [Anchor.centerLeft, Anchor.center, Anchor.centerRight], - [Anchor.bottomLeft, Anchor.bottomCenter, Anchor.bottomRight], - ]; - static const double _cellSize = 6.0; - static const double _gap = 1.0; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final theme = ref.watch(themeProvider); - final onChanged = this.onChanged; - return Row( - children: [ - Column( - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - for (final row in _grid) - Padding( - padding: const EdgeInsets.all(_gap / 2), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - for (final anchor in row) - Padding( - padding: const EdgeInsets.symmetric( - horizontal: _gap / 2, - ), - child: _AnchorCell( - anchor.toString(), - size: _cellSize, - isSelected: anchor == value, - color: anchor == value - ? theme.accentColor - : theme.dimTextColor, - onTap: onChanged == null - ? null - : () => onChanged(anchor), - ), - ), - ], - ), - ), - ], - ), - const SizedBox(width: 8), - Expanded(child: ReadOnlyValue(value.toString())), - ], - ); - } -} - -class const _AnchorCell( - final String name, { - required final double size, - required final bool isSelected, - required final Color color, - required final VoidCallback? onTap, -}) extends StatelessWidget { - @override - Widget build(BuildContext context) { - final cell = Semantics( - label: name, - selected: isSelected, - child: Container( - width: size, - height: size, - decoration: BoxDecoration( - color: isSelected ? color : null, - border: Border.all(color: color, width: 0.5), - ), - ), - ); - final onTap = this.onTap; - return StudioTooltip( - message: name, - child: onTap == null - ? cell - : MouseRegion( - cursor: SystemMouseCursors.click, - child: GestureDetector(onTap: onTap, child: cell), - ), - ); - } -} diff --git a/packages/flame_studio/lib/src/widgets/panels/inspector_view.dart b/packages/flame_studio/lib/src/widgets/panels/inspector_view.dart deleted file mode 100644 index 6965be78f1b..00000000000 --- a/packages/flame_studio/lib/src/widgets/panels/inspector_view.dart +++ /dev/null @@ -1,280 +0,0 @@ -import 'dart:async'; - -import 'package:flame/components.dart' show Component; -import 'package:flame_studio/src/core/game_controller.dart'; -import 'package:flame_studio/src/core/inspector/component_inspectors.dart'; -import 'package:flame_studio/src/core/inspector/inspector_property.dart'; -import 'package:flame_studio/src/core/selection.dart'; -import 'package:flame_studio/src/core/theme.dart'; -import 'package:flame_studio/src/widgets/common/disclosure_triangle.dart'; -import 'package:flame_studio/src/widgets/common/studio_text_field.dart'; -import 'package:flame_studio/src/widgets/common/studio_tooltip.dart'; -import 'package:flame_studio/src/widgets/panels/inspector/property_editors.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -/// Shows the properties of the selected component, grouped into sections. -/// -/// The view refreshes periodically so that the values follow the running -/// game. -class const InspectorView({super.key}) extends ConsumerStatefulWidget { - static const Duration refreshFrequency = Duration(milliseconds: 100); - - @override - ConsumerState createState() => _InspectorViewState(); -} - -class _InspectorViewState() extends ConsumerState { - late final Timer _timer; - final Set _collapsedSections = {}; - - @override - void initState() { - super.initState(); - _timer = Timer.periodic(InspectorView.refreshFrequency, (_) { - if (ref.read(selectedComponentProvider) != null) { - setState(() {}); - } - }); - } - - @override - void dispose() { - _timer.cancel(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - final theme = ref.watch(themeProvider); - final component = ref.watch(selectedComponentProvider); - if (component == null) { - return Center( - child: Padding( - padding: const EdgeInsets.all(16), - child: Text( - 'Select a component in the Hierarchy to inspect it.', - textAlign: TextAlign.center, - style: TextStyle(color: theme.dimTextColor), - ), - ), - ); - } - - final sections = [ - for (final inspector in ref.watch(componentInspectorsProvider)) - ?inspector(component), - ]; - return ListView( - padding: EdgeInsets.zero, - children: [ - _Header(component), - for (final section in sections) ...[ - _SectionHeader( - section.title, - isCollapsed: _collapsedSections.contains(section.title), - onTap: () => setState(() { - if (!_collapsedSections.remove(section.title)) { - _collapsedSections.add(section.title); - } - }), - ), - if (!_collapsedSections.contains(section.title)) - Padding( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), - child: Column( - children: [ - for (final property in section.properties) - _PropertyRow(property), - ], - ), - ), - ], - ], - ); - } -} - -class const _Header(final Component component) extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final theme = ref.watch(themeProvider); - return Padding( - padding: const EdgeInsets.fromLTRB(8, 8, 8, 6), - child: Row( - children: [ - Expanded( - child: Text( - component.runtimeType.toString(), - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: theme.fontSize + 2, - fontWeight: FontWeight.bold, - ), - ), - ), - StudioTooltip( - message: - 'The identity hash code of the component, which tells apart ' - 'components of the same type', - child: Text( - '#${component.hashCode.toRadixString(16)}', - style: TextStyle(color: theme.dimTextColor), - ), - ), - ], - ), - ); - } -} - -class const _SectionHeader( - final String title, { - required final bool isCollapsed, - required final VoidCallback onTap, -}) extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final theme = ref.watch(themeProvider); - return MouseRegion( - cursor: SystemMouseCursors.click, - child: GestureDetector( - onTap: onTap, - child: Container( - height: theme.rowHeight, - color: theme.sectionHeaderColor, - padding: const EdgeInsets.symmetric(horizontal: 4), - child: Row( - children: [ - DisclosureTriangle( - isExpanded: !isCollapsed, - color: theme.dimTextColor, - ), - Text(title, style: const TextStyle(fontWeight: FontWeight.bold)), - ], - ), - ), - ), - ); - } -} - -/// Wraps the setter of a property, so that the game is repainted after each -/// edit. -typedef _EditCallback = ValueChanged? Function(ValueChanged? setValue); - -class const _PropertyRow(final InspectorProperty property) - extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final theme = ref.watch(themeProvider); - final gameController = ref.read(gameControllerProvider.notifier); - ValueChanged? edit(ValueChanged? setValue) { - if (setValue == null) { - return null; - } - return (value) { - setValue(value); - gameController.repaint(); - }; - } - - // The properties are matched by their concrete type, so that their - // callbacks are accessed with the precise type of their values. - final (ValueChanged? onDrag, Widget editor) = switch (property) { - final DoubleProperty p => _doubleEditor(p, edit), - final IntProperty p => _intEditor(p, edit), - final BoolProperty p => ( - null, - StudioCheckbox(value: p.getValue(), onChanged: edit(p.setValue)), - ), - final StringProperty p => ( - null, - p.setValue == null - ? ReadOnlyValue(p.getValue()) - : StudioTextField( - value: p.getValue(), - onSubmitted: edit(p.setValue), - ), - ), - final Vector2Property p => ( - null, - Vector2Field(p.getValue(), onChanged: edit(p.setValue), step: p.step), - ), - final AnchorProperty p => ( - null, - AnchorPicker(p.getValue(), onChanged: edit(p.setValue)), - ), - }; - - return SizedBox( - height: theme.rowHeight + 2, - child: Row( - children: [ - Expanded( - flex: 2, - child: ScrubLabel( - property.label, - onDrag: onDrag, - tooltip: _tooltip( - property.description, - isDraggable: onDrag != null, - ), - ), - ), - const SizedBox(width: 4), - Expanded(flex: 3, child: editor), - ], - ), - ); - } - - static String? _tooltip(String? description, {required bool isDraggable}) { - if (!isDraggable) { - return description; - } - const hint = 'Drag the label sideways to change the value.'; - return description == null ? hint : '$description.\n$hint'; - } - - static (ValueChanged?, Widget) _doubleEditor( - DoubleProperty p, - _EditCallback edit, - ) { - final setValue = edit(p.setValue); - if (setValue == null) { - return (null, NumberField(p.getValue())); - } - void set(double value) { - setValue( - value.clamp(p.min ?? double.negativeInfinity, p.max ?? double.infinity), - ); - } - - return ( - (dx) => set(p.getValue() + dx * p.step), - NumberField(p.getValue(), onSubmitted: set), - ); - } - - static (ValueChanged?, Widget) _intEditor( - IntProperty p, - _EditCallback edit, - ) { - final setValue = edit(p.setValue); - final value = p.getValue().toDouble(); - if (setValue == null) { - return (null, NumberField(value, isInteger: true)); - } - return ( - // Dragging changes the value by one for every 4 logical pixels. - (dx) => setValue(p.getValue() + (dx / 4).round()), - NumberField( - value, - isInteger: true, - onSubmitted: (value) => setValue(value.round()), - ), - ); - } -} diff --git a/packages/flame_studio/lib/src/widgets/studio_chrome.dart b/packages/flame_studio/lib/src/widgets/studio_chrome.dart deleted file mode 100644 index 65ce1bfe1cb..00000000000 --- a/packages/flame_studio/lib/src/widgets/studio_chrome.dart +++ /dev/null @@ -1,31 +0,0 @@ -import 'package:flame_studio/src/core/theme.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -/// Provides the ambient widgets that the studio UI relies on. -/// -/// The studio does not run inside of a [WidgetsApp], so that the game can -/// bring its own app. This widget is used to wrap each part of the studio UI -/// (but never the game) with what a [WidgetsApp] would otherwise provide. -class const StudioChrome({required final Widget child, super.key}) - extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final theme = ref.watch(themeProvider); - return Directionality( - textDirection: ref.watch(textDirectionProvider), - child: MediaQuery.fromView( - view: View.of(context), - child: DefaultTextEditingShortcuts( - child: DefaultTextStyle( - style: TextStyle( - color: theme.textColor, - fontSize: theme.fontSize, - ), - child: child, - ), - ), - ), - ); - } -} diff --git a/packages/flame_studio/lib/src/widgets/toolbar/flame_studio_toolbar.dart b/packages/flame_studio/lib/src/widgets/toolbar/flame_studio_toolbar.dart deleted file mode 100644 index ec92e09443d..00000000000 --- a/packages/flame_studio/lib/src/widgets/toolbar/flame_studio_toolbar.dart +++ /dev/null @@ -1,71 +0,0 @@ -import 'package:flame_studio/src/core/theme.dart'; -import 'package:flame_studio/src/core/viewport_tool.dart'; -import 'package:flame_studio/src/widgets/toolbar/next_frame_button.dart'; -import 'package:flame_studio/src/widgets/toolbar/pause_button.dart'; -import 'package:flame_studio/src/widgets/toolbar/start_button.dart'; -import 'package:flame_studio/src/widgets/toolbar/viewport_tool_button.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -final toolbarHeightProvider = Provider((ref) => 28.0); - -class const FlameStudioToolbar({super.key}) extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - const middleButtons = [ - StartButton(), - PauseButton(), - NextFrameButton(), - ]; - - final height = ref.watch(toolbarHeightProvider); - final gap = height * 0.1; - - return Container( - constraints: BoxConstraints.tightFor(height: height), - decoration: BoxDecoration( - boxShadow: const [ - BoxShadow( - color: Color(0x66000000), - offset: Offset(0, 3), - blurRadius: 7.0, - ), - BoxShadow( - color: Color(0xbf000000), - offset: Offset(0, 1), - blurRadius: 2.0, - ), - ], - color: ref.watch(themeProvider).toolbarColor, - ), - child: Row( - textDirection: TextDirection.ltr, - children: [ - Padding( - padding: EdgeInsets.fromLTRB(gap * 2, gap, gap * 10, gap * 2), - child: Image.asset( - 'assets/logo_flame.png', - package: 'flame_studio', - fit: BoxFit.scaleDown, - // When flame_studio is itself the app (as in its example), its - // assets are not prefixed with the package name. - errorBuilder: (_, _, _) => Image.asset( - 'assets/logo_flame.png', - fit: BoxFit.scaleDown, - ), - ), - ), - for (final tool in ViewportTool.values) - Padding( - padding: EdgeInsets.all(gap), - child: ViewportToolButton(tool), - ), - Expanded(child: Container()), - for (final button in middleButtons) - Padding(padding: EdgeInsets.all(gap), child: button), - Expanded(child: Container()), - ], - ), - ); - } -} diff --git a/packages/flame_studio/lib/src/widgets/toolbar/next_frame_button.dart b/packages/flame_studio/lib/src/widgets/toolbar/next_frame_button.dart deleted file mode 100644 index 12a15e6e290..00000000000 --- a/packages/flame_studio/lib/src/widgets/toolbar/next_frame_button.dart +++ /dev/null @@ -1,25 +0,0 @@ -import 'package:flame_studio/src/core/game_controller.dart'; -import 'package:flame_studio/src/widgets/toolbar/toolbar_button.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -class const NextFrameButton({super.key}) extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final gameState = ref.watch(gameControllerProvider); - - return ToolbarButton( - icon: Path() - ..moveTo(-4, 5) - ..lineTo(-4, -5) - ..lineTo(1, 0) - ..close() - ..addRect(const Rect.fromLTWH(1, -4.5, 3, 9)), - disabled: !gameState.paused, - tooltip: 'Advance the paused game by a single frame', - onClick: () { - ref.read(gameControllerProvider.notifier).stepGame(); - }, - ); - } -} diff --git a/packages/flame_studio/lib/src/widgets/toolbar/pause_button.dart b/packages/flame_studio/lib/src/widgets/toolbar/pause_button.dart deleted file mode 100644 index f7d42275248..00000000000 --- a/packages/flame_studio/lib/src/widgets/toolbar/pause_button.dart +++ /dev/null @@ -1,22 +0,0 @@ -import 'package:flame_studio/src/core/game_controller.dart'; -import 'package:flame_studio/src/widgets/toolbar/toolbar_button.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -class const PauseButton({super.key}) extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final gameState = ref.watch(gameControllerProvider); - - return ToolbarButton( - icon: Path() - ..addRect(const Rect.fromLTRB(-4, -4.5, -1, 4.5)) - ..addRect(const Rect.fromLTRB(1, -4.5, 4, 4.5)), - disabled: gameState.paused, - tooltip: 'Pause the game', - onClick: () { - ref.read(gameControllerProvider.notifier).pauseGame(); - }, - ); - } -} diff --git a/packages/flame_studio/lib/src/widgets/toolbar/start_button.dart b/packages/flame_studio/lib/src/widgets/toolbar/start_button.dart deleted file mode 100644 index dc066b85a9e..00000000000 --- a/packages/flame_studio/lib/src/widgets/toolbar/start_button.dart +++ /dev/null @@ -1,24 +0,0 @@ -import 'package:flame_studio/src/core/game_controller.dart'; -import 'package:flame_studio/src/widgets/toolbar/toolbar_button.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -class const StartButton({super.key}) extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final gameState = ref.watch(gameControllerProvider); - - return ToolbarButton( - icon: Path() - ..moveTo(-2.5, 5) - ..lineTo(-2.5, -5) - ..lineTo(6, 0) - ..close(), - disabled: !gameState.paused, - tooltip: 'Resume the game', - onClick: () { - ref.read(gameControllerProvider.notifier).resumeGame(); - }, - ); - } -} diff --git a/packages/flame_studio/lib/src/widgets/toolbar/toolbar_button.dart b/packages/flame_studio/lib/src/widgets/toolbar/toolbar_button.dart deleted file mode 100644 index b0c1ace3689..00000000000 --- a/packages/flame_studio/lib/src/widgets/toolbar/toolbar_button.dart +++ /dev/null @@ -1,146 +0,0 @@ -import 'package:flame_studio/src/core/theme.dart'; -import 'package:flame_studio/src/widgets/common/studio_tooltip.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -class const ToolbarButton({ - required final Path icon, - final String? tooltip, - final void Function()? onClick, - final bool disabled = false, - final bool toggled = false, - super.key, -}) extends ConsumerStatefulWidget { - @override - ToolbarButtonState createState() => ToolbarButtonState(); -} - -class ToolbarButtonState() extends ConsumerState { - bool _isHovered = false; - bool _isActive = false; - - @override - Widget build(BuildContext context) { - final painter = CustomPaint( - painter: _ToolbarButtonPainter( - widget.icon, - ref.watch(themeProvider), - isDisabled: widget.disabled, - isToggled: widget.toggled, - isHovered: _isHovered, - isActive: _isActive, - ), - ); - - final tooltip = widget.tooltip; - final button = AspectRatio( - aspectRatio: 1.25, - child: widget.disabled - ? painter - : MouseRegion( - onEnter: (_) => setState(() => _isHovered = true), - onExit: (_) => setState(() => _isHovered = false), - cursor: SystemMouseCursors.click, - child: GestureDetector( - onTapDown: (_) => setState(() => _isActive = true), - onTapCancel: () => setState(() => _isActive = false), - onTapUp: (_) { - if (_isActive) { - widget.onClick?.call(); - } - setState(() => _isActive = false); - }, - child: painter, - ), - ), - ); - return tooltip == null - ? button - : StudioTooltip(message: tooltip, child: button); - } - - @override - void didUpdateWidget(ToolbarButton oldWidget) { - super.didUpdateWidget(oldWidget); - if (widget.icon != oldWidget.icon || - widget.disabled != oldWidget.disabled) { - _isActive = false; - _isHovered = false; - } - } -} - -enum _ToolbarButtonRenderState() { - disabled, - active, - toggled, - hovered, - normal, -} - -class _ToolbarButtonPainter( - final Path icon, - final Theme theme, { - required final bool isDisabled, - required final bool isToggled, - required final bool isHovered, - required final bool isActive, -}) extends CustomPainter { - @override - void paint(Canvas canvas, Size size) { - final scale = size.height / 20.0; - canvas.save(); - canvas.scale(size.height / 20.0); - - final renderState = _renderState; - - final radius = Radius.circular(theme.buttonRadius); - final color = switch (renderState) { - _ToolbarButtonRenderState.disabled => theme.buttonDisabledColor, - _ToolbarButtonRenderState.active => theme.buttonActiveColor, - _ToolbarButtonRenderState.toggled => theme.buttonToggledColor, - _ToolbarButtonRenderState.hovered => theme.buttonHoverColor, - _ToolbarButtonRenderState.normal => theme.buttonColor, - }; - canvas.drawRRect( - RRect.fromLTRBR(0, 0, size.width / scale, 20.0, radius), - Paint()..color = color, - ); - - final textColor = switch (renderState) { - _ToolbarButtonRenderState.disabled => theme.buttonDisabledTextColor, - _ToolbarButtonRenderState.active => theme.buttonActiveTextColor, - _ToolbarButtonRenderState.toggled => theme.buttonActiveTextColor, - _ToolbarButtonRenderState.hovered => theme.buttonHoverTextColor, - _ToolbarButtonRenderState.normal => theme.buttonTextColor, - }; - canvas.translate(size.width / scale / 2, 10); - canvas.drawPath(icon, Paint()..color = textColor); - canvas.restore(); - } - - @override - bool shouldRepaint(_ToolbarButtonPainter old) { - return isHovered != old.isHovered || - isActive != old.isActive || - isDisabled != old.isDisabled || - isToggled != old.isToggled || - icon != old.icon; - } - - _ToolbarButtonRenderState get _renderState { - if (isDisabled) { - return _ToolbarButtonRenderState.disabled; - } - if (isActive) { - return _ToolbarButtonRenderState.active; - } - if (isToggled) { - return _ToolbarButtonRenderState.toggled; - } - if (isHovered) { - return _ToolbarButtonRenderState.hovered; - } - return _ToolbarButtonRenderState.normal; - } -} diff --git a/packages/flame_studio/lib/src/widgets/toolbar/viewport_tool_button.dart b/packages/flame_studio/lib/src/widgets/toolbar/viewport_tool_button.dart deleted file mode 100644 index 459cf95a6ed..00000000000 --- a/packages/flame_studio/lib/src/widgets/toolbar/viewport_tool_button.dart +++ /dev/null @@ -1,131 +0,0 @@ -import 'dart:math'; - -import 'package:flame_studio/src/core/snap_settings.dart'; -import 'package:flame_studio/src/core/viewport_tool.dart'; -import 'package:flame_studio/src/widgets/panels/inspector/property_editors.dart'; -import 'package:flame_studio/src/widgets/toolbar/toolbar_button.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -/// Switches the game view to [tool], and shows whether it is in use. -class const ViewportToolButton(final ViewportTool tool, {super.key}) - extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final currentTool = ref.watch(viewportToolProvider); - return ToolbarButton( - icon: _icon(tool), - tooltip: _tooltip(tool, ref.watch(snapSettingsProvider)), - toggled: currentTool == tool, - onClick: () => ref.read(viewportToolProvider.notifier).use(tool), - ); - } - - static String _tooltip(ViewportTool tool, SnapSettings snap) { - return switch (tool) { - ViewportTool.interact => - 'Interact: the game receives the mouse input, as if the studio ' - "wasn't there", - ViewportTool.select => - 'Select: click on a component in the game to select it. Click again ' - 'to cycle through overlapping components', - ViewportTool.move => - 'Move: drag the arrows to move along an axis, or the square or the ' - 'component itself to move freely. Hold Shift to snap to a grid ' - 'of ${formatNumber(snap.moveStep)} units', - ViewportTool.rotate => - 'Rotate: drag the ring to rotate around the anchor. Hold Shift to snap ' - 'to multiples of ${formatNumber(snap.rotateStepDegrees)}°', - ViewportTool.scale => - 'Scale: drag the axis handles to scale along an axis, or the square to ' - 'scale uniformly. Hold Shift to snap to multiples of ' - '${formatNumber(snap.scaleStep)}', - }; - } - - static Path _icon(ViewportTool tool) { - return switch (tool) { - // A mouse pointer. - ViewportTool.interact => - Path() - ..moveTo(-3, -5) - ..lineTo(-3, 4) - ..lineTo(-0.8, 1.8) - ..lineTo(1.2, 5) - ..lineTo(2.8, 4.2) - ..lineTo(0.9, 1.1) - ..lineTo(3.8, 1.1) - ..close(), - // A selection frame around a point. - ViewportTool.select => - Path() - ..fillType = PathFillType.evenOdd - ..addRect(const Rect.fromLTRB(-5, -4, 5, 4)) - ..addRect(const Rect.fromLTRB(-4, -3, 4, 3)) - ..addRect(const Rect.fromLTRB(-1.5, -1.5, 1.5, 1.5)), - // Arrows pointing in all four directions. - ViewportTool.move => - Path() - ..addRect(const Rect.fromLTRB(-3.5, -0.6, 3.5, 0.6)) - ..addRect(const Rect.fromLTRB(-0.6, -3.5, 0.6, 3.5)) - ..addPolygon(const [ - Offset(0, -5.5), - Offset(-2, -3), - Offset(2, -3), - ], true) - ..addPolygon(const [ - Offset(0, 5.5), - Offset(-2, 3), - Offset(2, 3), - ], true) - ..addPolygon(const [ - Offset(-5.5, 0), - Offset(-3, -2), - Offset(-3, 2), - ], true) - ..addPolygon(const [ - Offset(5.5, 0), - Offset(3, -2), - Offset(3, 2), - ], true), - ViewportTool.rotate => _rotateIcon(), - // A frame with a filled corner. - ViewportTool.scale => - Path() - ..addRect(const Rect.fromLTRB(-5, -5, 5, -4)) - ..addRect(const Rect.fromLTRB(4, -5, 5, 5)) - ..addRect(const Rect.fromLTRB(-5, 4, 5, 5)) - ..addRect(const Rect.fromLTRB(-5, -5, -4, 5)) - ..addRect(const Rect.fromLTRB(-5, 0, 0, 5)), - }; - } - - /// A circular arrow. - static Path _rotateIcon() { - const start = -0.8 * pi; - const sweep = 1.5 * pi; - const end = start + sweep; - final arc = Path() - ..arcTo( - Rect.fromCircle(center: Offset.zero, radius: 4.6), - start, - sweep, - true, - ) - ..arcTo( - Rect.fromCircle(center: Offset.zero, radius: 3.4), - end, - -sweep, - false, - ) - ..close(); - final tip = Offset(cos(end), sin(end)) * 4; - final tangent = Offset(-sin(end), cos(end)); - final normal = Offset(cos(end), sin(end)); - return arc..addPolygon([ - tip + tangent * 2.2, - tip + normal * 2.2, - tip - normal * 2.2, - ], true); - } -} diff --git a/packages/flame_studio/lib/src/widgets/ui_scaffold.dart b/packages/flame_studio/lib/src/widgets/ui_scaffold.dart deleted file mode 100644 index c72cfefa77b..00000000000 --- a/packages/flame_studio/lib/src/widgets/ui_scaffold.dart +++ /dev/null @@ -1,72 +0,0 @@ -import 'package:flame_studio/src/core/theme.dart'; -import 'package:flame_studio/src/widgets/common/studio_tooltip.dart'; -import 'package:flame_studio/src/widgets/dock/dock_layout.dart'; -import 'package:flame_studio/src/widgets/dock/dock_panel.dart'; -import 'package:flame_studio/src/widgets/studio_chrome.dart'; -import 'package:flame_studio/src/widgets/toolbar/flame_studio_toolbar.dart'; -import 'package:flame_studio/src/widgets/viewport/gizmo_overlay.dart'; -import 'package:flame_studio/src/widgets/viewport/viewport_tool_layer.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -class const UiScaffold({required final Widget gameApp, super.key}) - extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final toolbarHeight = ref.watch(toolbarHeightProvider); - final leftWidth = ref.watch( - dockProvider(DockSide.left).select((dock) => dock.width), - ); - final rightWidth = ref.watch( - dockProvider(DockSide.right).select((dock) => dock.width), - ); - return Container( - color: ref.watch(themeProvider).backdropColor, - child: Stack( - textDirection: ref.watch(textDirectionProvider), - children: [ - Positioned.fill( - child: Padding( - padding: EdgeInsets.fromLTRB( - leftWidth + 20, - toolbarHeight + 20, - rightWidth + 20, - 20, - ), - child: ClipRect( - child: Stack( - fit: StackFit.expand, - textDirection: ref.watch(textDirectionProvider), - children: [ - gameApp, - const IgnorePointer(child: GizmoOverlay()), - const ViewportToolLayer(), - ], - ), - ), - ), - ), - Positioned( - left: 0, - top: toolbarHeight, - bottom: 0, - child: const StudioChrome(child: DockPanel(DockSide.left)), - ), - Positioned( - right: 0, - top: toolbarHeight, - bottom: 0, - child: const StudioChrome(child: DockPanel(DockSide.right)), - ), - const Positioned( - left: 0, - top: 0, - right: 0, - child: StudioChrome(child: FlameStudioToolbar()), - ), - const Positioned.fill(child: StudioChrome(child: TooltipLayer())), - ], - ), - ); - } -} diff --git a/packages/flame_studio/lib/src/widgets/viewport/gizmo_overlay.dart b/packages/flame_studio/lib/src/widgets/viewport/gizmo_overlay.dart deleted file mode 100644 index 7864cf55d0a..00000000000 --- a/packages/flame_studio/lib/src/widgets/viewport/gizmo_overlay.dart +++ /dev/null @@ -1,313 +0,0 @@ -import 'package:flame/components.dart' show Component, PositionComponent; -import 'package:flame_studio/src/core/game_controller.dart'; -import 'package:flame_studio/src/core/gizmo/gizmo_geometry.dart'; -import 'package:flame_studio/src/core/selection.dart'; -import 'package:flame_studio/src/core/theme.dart'; -import 'package:flame_studio/src/core/viewport_tool.dart'; -import 'package:flutter/foundation.dart'; -import 'package:flutter/scheduler.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -/// Draws a gizmo on top of the game for the selected component, showing its -/// outline, its anchor and the directions of its local axes, together with -/// the handles of the tool in use. -/// -/// The overlay must cover the game widget, but may be larger than it. The -/// gizmo is updated every frame while a [PositionComponent] is selected. -class const GizmoOverlay({super.key}) extends ConsumerStatefulWidget { - @override - ConsumerState createState() => _GizmoOverlayState(); -} - -class _GizmoOverlayState() - extends ConsumerState - with SingleTickerProviderStateMixin { - late final Ticker _ticker = createTicker((_) => _update()); - List _geometry = const []; - - @override - void initState() { - super.initState(); - ref.listenManual( - selectedComponentProvider, - (_, component) => _handleSelectionChange(component), - fireImmediately: true, - ); - } - - @override - void dispose() { - _ticker.dispose(); - super.dispose(); - } - - void _handleSelectionChange(Component? component) { - if (component is PositionComponent) { - if (!_ticker.isActive) { - _ticker.start(); - } - } else { - _ticker.stop(); - if (_geometry.isNotEmpty) { - setState(() => _geometry = const []); - } - } - } - - void _update() { - final component = ref.read(selectedComponentProvider); - final geometry = component is PositionComponent && component.isMounted - ? GizmoGeometry.of(component) - : const []; - if (!listEquals(geometry, _geometry)) { - setState(() => _geometry = geometry); - } - } - - @override - Widget build(BuildContext context) { - final game = ref.watch(gameControllerProvider.select((s) => s.game)); - final tool = ref.watch(viewportToolProvider); - return _GizmoPaint( - geometry: _geometry, - gameBox: (game?.isAttached ?? false) ? game!.renderBox : null, - theme: ref.watch(themeProvider), - tool: tool, - activeHandle: ref.watch(activeGizmoHandleProvider), - ); - } -} - -class const _GizmoPaint({ - required final List geometry, - required final RenderBox? gameBox, - required final Theme theme, - required final ViewportTool tool, - required final GizmoHandle? activeHandle, -}) extends LeafRenderObjectWidget { - @override - RenderObject createRenderObject(BuildContext context) { - return _RenderGizmo() - ..geometry = geometry - ..gameBox = gameBox - ..theme = theme - ..tool = tool - ..activeHandle = activeHandle; - } - - @override - void updateRenderObject(BuildContext context, _RenderGizmo renderObject) { - renderObject - ..geometry = geometry - ..gameBox = gameBox - ..theme = theme - ..tool = tool - ..activeHandle = activeHandle; - } -} - -/// Paints the gizmos, converting their points from the canvas space of the -/// game into the local space of this render box. -class _RenderGizmo() extends RenderBox { - static const double arrowSize = 6.0; - static const double anchorRadius = 4.0; - - List _geometry = const []; - RenderBox? _gameBox; - Theme? _theme; - ViewportTool _tool = ViewportTool.interact; - GizmoHandle? _activeHandle; - - set geometry(List value) { - if (!identical(_geometry, value)) { - _geometry = value; - markNeedsPaint(); - } - } - - set gameBox(RenderBox? value) { - if (_gameBox != value) { - _gameBox = value; - markNeedsPaint(); - } - } - - set theme(Theme value) { - if (_theme != value) { - _theme = value; - markNeedsPaint(); - } - } - - set tool(ViewportTool value) { - if (_tool != value) { - _tool = value; - markNeedsPaint(); - } - } - - set activeHandle(GizmoHandle? value) { - if (_activeHandle != value) { - _activeHandle = value; - markNeedsPaint(); - } - } - - @override - bool get sizedByParent => true; - - @override - Size computeDryLayout(BoxConstraints constraints) => constraints.biggest; - - @override - void paint(PaintingContext context, Offset offset) { - final gameBox = _gameBox; - final theme = _theme; - if (_geometry.isEmpty || - gameBox == null || - !gameBox.attached || - theme == null) { - return; - } - Offset toLocal(Offset canvasPoint) { - return globalToLocal(gameBox.localToGlobal(canvasPoint)) + offset; - } - - Color handleColor(GizmoHandle handle, Color color) { - return handle == _activeHandle ? theme.gizmoActiveColor : color; - } - - final canvas = context.canvas; - for (final gizmo in _geometry) { - final outline = Path() - ..addPolygon(gizmo.corners.map(toLocal).toList(), true); - canvas.drawPath( - outline, - Paint()..color = theme.gizmoColor.withAlpha(0x22), - ); - _stroke(canvas, outline, theme.gizmoColor, 1.5); - - final anchor = toLocal(gizmo.anchor); - final isRotating = _tool == ViewportTool.rotate; - final isScaling = _tool == ViewportTool.scale; - if (isRotating) { - final radius = - (toLocal(gizmo.anchor + const Offset(GizmoGeometry.ringRadius, 0)) - - anchor) - .distance; - _stroke( - canvas, - Path()..addOval(Rect.fromCircle(center: anchor, radius: radius)), - handleColor(GizmoHandle.ring, theme.gizmoRotationColor), - 2, - ); - if (gizmo.xAxis != Offset.zero) { - // Shows the current angle of the component. - final end = toLocal( - gizmo.anchor + gizmo.xAxis * GizmoGeometry.ringRadius, - ); - _stroke( - canvas, - Path() - ..moveTo(anchor.dx, anchor.dy) - ..lineTo(end.dx, end.dy), - theme.gizmoXAxisColor, - 1.5, - ); - } - } - final showsFreeHandle = _tool == ViewportTool.move || isScaling; - if (showsFreeHandle && gizmo.xAxis != Offset.zero) { - final color = handleColor(GizmoHandle.free, theme.gizmoColor); - final square = Path() - ..addPolygon(gizmo.freeHandleCorners.map(toLocal).toList(), true); - _fill(canvas, square, color.withAlpha(0xAA)); - _stroke(canvas, square, color, 1); - } - if (!isRotating) { - for (final (handle, axis, end, color) in [ - (GizmoHandle.x, gizmo.xAxis, gizmo.xAxisEnd, theme.gizmoXAxisColor), - (GizmoHandle.y, gizmo.yAxis, gizmo.yAxisEnd, theme.gizmoYAxisColor), - ]) { - if (axis != Offset.zero) { - _drawAxis( - canvas, - anchor, - toLocal(end), - handleColor(handle, color), - boxed: isScaling, - ); - } - } - } - final anchorCircle = Path() - ..addOval(Rect.fromCircle(center: anchor, radius: anchorRadius)); - _fill(canvas, anchorCircle, const Color(0xFFFFFFFF)); - _stroke(canvas, anchorCircle, theme.gizmoColor, 1.5); - } - } - - /// Strokes [path] over a dark halo, so that it stands out on any background. - void _stroke(Canvas canvas, Path path, Color color, double width) { - canvas.drawPath( - path, - Paint() - ..color = _theme!.gizmoHaloColor - ..style = PaintingStyle.stroke - ..strokeJoin = StrokeJoin.round - ..strokeWidth = width + 2, - ); - canvas.drawPath( - path, - Paint() - ..color = color - ..style = PaintingStyle.stroke - ..strokeWidth = width, - ); - } - - /// Fills [path] over a dark halo, so that it stands out on any background. - void _fill(Canvas canvas, Path path, Color color) { - canvas.drawPath( - path, - Paint() - ..color = _theme!.gizmoHaloColor - ..style = PaintingStyle.stroke - ..strokeJoin = StrokeJoin.round - ..strokeWidth = 2, - ); - canvas.drawPath(path, Paint()..color = color); - } - - /// Draws an axis from [start] to [end], ending in an arrow head, or in a - /// square when [boxed], which is the handle of the scale tool. - void _drawAxis( - Canvas canvas, - Offset start, - Offset end, - Color color, { - required bool boxed, - }) { - final direction = end - start; - final distance = direction.distance; - if (distance == 0) { - return; - } - final unit = direction / distance; - final normal = Offset(-unit.dy, unit.dx) * (arrowSize / 2); - final headBase = end - unit * arrowSize; - _stroke( - canvas, - Path() - ..moveTo(start.dx, start.dy) - ..lineTo(headBase.dx, headBase.dy), - color, - 2, - ); - final head = boxed - ? [headBase + normal, end + normal, end - normal, headBase - normal] - : [end, headBase + normal, headBase - normal]; - _fill(canvas, Path()..addPolygon(head, true), color); - } -} diff --git a/packages/flame_studio/lib/src/widgets/viewport/viewport_tool_layer.dart b/packages/flame_studio/lib/src/widgets/viewport/viewport_tool_layer.dart deleted file mode 100644 index 06a24766b42..00000000000 --- a/packages/flame_studio/lib/src/widgets/viewport/viewport_tool_layer.dart +++ /dev/null @@ -1,258 +0,0 @@ -import 'package:collection/collection.dart'; -import 'package:flame/components.dart' - show Component, PositionComponent, Vector2; -import 'package:flame_studio/src/core/game_controller.dart'; -import 'package:flame_studio/src/core/gizmo/canvas_mapping.dart'; -import 'package:flame_studio/src/core/gizmo/gizmo_drag.dart'; -import 'package:flame_studio/src/core/gizmo/gizmo_geometry.dart'; -import 'package:flame_studio/src/core/gizmo/move_drag.dart'; -import 'package:flame_studio/src/core/gizmo/rotate_drag.dart'; -import 'package:flame_studio/src/core/gizmo/scale_drag.dart'; -import 'package:flame_studio/src/core/selection.dart'; -import 'package:flame_studio/src/core/snap_settings.dart'; -import 'package:flame_studio/src/core/viewport_tool.dart'; -import 'package:flutter/gestures.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -/// Covers the game while a tool other than [ViewportTool.interact] is in use, -/// handling the pointer events for that tool and keeping them from the game. -/// -/// With the interact tool this layer is empty, so that the pointer events -/// reach the game. -class const ViewportToolLayer({super.key}) extends ConsumerStatefulWidget { - @override - ConsumerState createState() => _ViewportToolLayerState(); -} - -class _ViewportToolLayerState() extends ConsumerState { - MouseCursor _cursor = SystemMouseCursors.precise; - - /// Where the pointer went down, in global coordinates. Drags are measured - /// from this point, so that the drag slop doesn't offset the component. - Offset? _downPosition; - Offset? _lastPosition; - GizmoDrag? _drag; - - @override - void initState() { - super.initState(); - HardwareKeyboard.instance.addHandler(_handleKeyEvent); - } - - @override - void dispose() { - HardwareKeyboard.instance.removeHandler(_handleKeyEvent); - super.dispose(); - } - - /// Applies the drag again when Shift is pressed or released, so that - /// snapping toggles without having to move the pointer. - bool _handleKeyEvent(KeyEvent event) { - final lastPosition = _lastPosition; - final isShift = - event.logicalKey == LogicalKeyboardKey.shiftLeft || - event.logicalKey == LogicalKeyboardKey.shiftRight; - if (_drag != null && lastPosition != null && isShift) { - _updateDrag(lastPosition); - } - return false; - } - - @override - Widget build(BuildContext context) { - final tool = ref.watch(viewportToolProvider); - if (tool == ViewportTool.interact) { - return const SizedBox.shrink(); - } - final canDrag = tool != ViewportTool.select; - return MouseRegion( - cursor: _cursor, - onHover: canDrag ? (event) => _hover(event.position) : null, - onExit: (_) => _setActiveHandle(null), - child: GestureDetector( - behavior: HitTestBehavior.opaque, - dragStartBehavior: DragStartBehavior.down, - onTapUp: (details) => _select(details.globalPosition), - onPanDown: canDrag - ? (details) => _downPosition = details.globalPosition - : null, - onPanStart: canDrag ? (_) => _startDrag() : null, - onPanUpdate: canDrag - ? (details) => _updateDrag(details.globalPosition) - : null, - onPanEnd: canDrag ? (_) => _endDrag() : null, - onPanCancel: canDrag ? _endDrag : null, - ), - ); - } - - /// The root component of the game, and [globalPosition] in its canvas space. - (Component, Offset)? _toCanvas(Offset globalPosition) { - final game = ref.read(gameControllerProvider).game; - if (game == null || !game.isAttached || game is! Component) { - return null; - } - return ( - game as Component, - game.renderBox.globalToLocal(globalPosition), - ); - } - - /// The handle of the selected component's gizmo at [canvasPoint], and the - /// gizmo it belongs to. - (GizmoGeometry, GizmoHandle)? _handleAt(Offset canvasPoint) { - final selected = ref.read(selectedComponentProvider); - final tool = ref.read(viewportToolProvider); - if (selected is! PositionComponent || - tool == ViewportTool.interact || - tool == ViewportTool.select) { - return null; - } - for (final geometry in GizmoGeometry.of(selected)) { - final handle = geometry.handleAt( - canvasPoint, - ring: tool == ViewportTool.rotate, - ); - if (handle != null) { - return (geometry, handle); - } - } - return null; - } - - void _setActiveHandle(GizmoHandle? handle) { - ref.read(activeGizmoHandleProvider.notifier).set(handle); - } - - void _select(Offset globalPosition) { - final target = _toCanvas(globalPosition); - if (target == null) { - return; - } - final (root, point) = target; - if (_handleAt(point) != null) { - // Clicking a handle keeps the selection. - return; - } - final candidates = selectableComponentsAt( - root, - Vector2(point.dx, point.dy), - ); - ref - .read(selectedComponentProvider.notifier) - .select(pickNext(candidates, ref.read(selectedComponentProvider))); - } - - void _hover(Offset globalPosition) { - final target = _toCanvas(globalPosition); - final handle = target == null ? null : _handleAt(target.$2)?.$2; - _setActiveHandle(handle); - final cursor = handle == null - ? SystemMouseCursors.precise - : switch (ref.read(viewportToolProvider)) { - ViewportTool.rotate => SystemMouseCursors.grab, - ViewportTool.scale => SystemMouseCursors.resizeUpLeftDownRight, - _ => SystemMouseCursors.move, - }; - if (cursor != _cursor) { - setState(() => _cursor = cursor); - } - } - - void _startDrag() { - final downPosition = _downPosition; - final target = downPosition == null ? null : _toCanvas(downPosition); - if (target == null) { - return; - } - final (root, point) = target; - final tool = ref.read(viewportToolProvider); - final snapSettings = ref.read(snapSettingsProvider); - final hit = _handleAt(point); - if (hit != null) { - final component = - ref.read(selectedComponentProvider)! as PositionComponent; - final (geometry, handle) = hit; - _drag = switch (tool) { - ViewportTool.rotate => RotateDrag.start( - component, - geometry, - point, - snapStep: snapSettings.rotateStep, - ), - ViewportTool.scale => ScaleDrag.start( - component, - handle, - geometry, - snapStep: snapSettings.scaleStep, - ), - _ => MoveDrag.start( - component, - handle, - camera: geometry.camera, - snapStep: snapSettings.moveStep, - ), - }; - _setActiveHandle(handle); - } else if (tool == ViewportTool.move) { - // Dragging a component moves it freely, selecting it if needed. - final selected = ref.read(selectedComponentProvider); - final candidates = selectableComponentsAt( - root, - Vector2(point.dx, point.dy), - ); - final picked = candidates.contains(selected) - ? selected! as PositionComponent - : candidates.firstOrNull; - if (picked == null) { - return; - } - ref.read(selectedComponentProvider.notifier).select(picked); - final camera = - GizmoGeometry.of(picked) - .firstWhereOrNull((geometry) => geometry.containsPoint(point)) - ?.camera ?? - camerasFor(picked).firstOrNull; - _drag = MoveDrag.start( - picked, - GizmoHandle.free, - camera: camera, - snapStep: snapSettings.moveStep, - ); - _setActiveHandle(GizmoHandle.free); - } - } - - void _updateDrag(Offset globalPosition) { - final drag = _drag; - final downPosition = _downPosition; - final game = ref.read(gameControllerProvider).game; - if (drag == null || - downPosition == null || - game == null || - !game.isAttached) { - return; - } - _lastPosition = globalPosition; - final gameBox = game.renderBox; - final delta = - gameBox.globalToLocal(globalPosition) - - gameBox.globalToLocal(downPosition); - drag.update( - Vector2(delta.dx, delta.dy), - snap: HardwareKeyboard.instance.isShiftPressed, - ); - ref.read(gameControllerProvider.notifier).repaint(); - } - - void _endDrag() { - if (_drag != null) { - _setActiveHandle(null); - } - _drag = null; - _downPosition = null; - _lastPosition = null; - } -} diff --git a/packages/flame_studio/lib/vertices_editor/bloc/vertices_editor_cubit.dart b/packages/flame_studio/lib/vertices_editor/bloc/vertices_editor_cubit.dart new file mode 100644 index 00000000000..591c93578d3 --- /dev/null +++ b/packages/flame_studio/lib/vertices_editor/bloc/vertices_editor_cubit.dart @@ -0,0 +1,94 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flame_studio/repositories/repositories.dart'; + +part 'vertices_editor_state.dart'; + +/// {@template vertices_editor_cubit} +/// Edits a working copy of the vertices of a polygon, which the vertices +/// editor dialog returns when the user applies the changes. +/// +/// Also holds the zoom of the canvas, which is not remembered: the dialog +/// opens fitting the polygon again every time. +/// {@endtemplate} +class VerticesEditorCubit(ComponentVertices vertices) + extends Cubit { + /// {@macro vertices_editor_cubit} + this : super(VerticesEditorState(initial: vertices)); + + /// Selects the vertex at [index], or nothing if it is `null`. + void vertexSelected(int? index) { + emit(state.copyWith(selectedIndex: () => index)); + } + + /// Moves the vertex at [index] to [x], [y]. + void vertexMoved(int index, double x, double y) { + emit( + state.copyWith( + vertices: [...state.vertices]..[index] = ComponentVertex(x, y), + ), + ); + } + + /// Adds a vertex at [x], [y] on the edge that starts at the vertex at + /// [edgeIndex], and selects it. + void vertexInserted(int edgeIndex, double x, double y) { + final index = edgeIndex + 1; + emit( + state.copyWith( + vertices: [...state.vertices]..insert(index, ComponentVertex(x, y)), + selectedIndex: () => index, + ), + ); + } + + /// Removes the selected vertex, unless the polygon would have fewer than + /// [ComponentVertices.minLength] vertices. + void selectedVertexDeleted() { + final index = state.selectedIndex; + if (index != null) { + vertexDeleted(index); + } + } + + /// Removes the vertex at [index], unless the polygon would have fewer + /// than [ComponentVertices.minLength] vertices. The selection stays on + /// the same vertex, or is cleared if it was the removed one. + void vertexDeleted(int index) { + if (!state.canDelete) { + return; + } + final selected = state.selectedIndex; + emit( + state.copyWith( + vertices: [...state.vertices]..removeAt(index), + selectedIndex: () => switch (selected) { + null => null, + _ when selected == index => null, + _ when selected > index => selected - 1, + _ => selected, + }, + ), + ); + } + + /// Zooms the canvas in to the next of the [ZoomLevels], if any. + void zoomedIn() { + final zoom = ZoomLevels.next(state.zoom); + if (zoom != null) { + emit(state.copyWith(zoom: zoom)); + } + } + + /// Zooms the canvas out to the previous of the [ZoomLevels], if any. + void zoomedOut() { + final zoom = ZoomLevels.previous(state.zoom); + if (zoom != null) { + emit(state.copyWith(zoom: zoom)); + } + } + + /// Resets the zoom of the canvas, showing the polygon as it was fitted + /// when the dialog opened. + void zoomReset() => emit(state.copyWith(zoom: 1)); +} diff --git a/packages/flame_studio/lib/vertices_editor/bloc/vertices_editor_state.dart b/packages/flame_studio/lib/vertices_editor/bloc/vertices_editor_state.dart new file mode 100644 index 00000000000..9518a93aae5 --- /dev/null +++ b/packages/flame_studio/lib/vertices_editor/bloc/vertices_editor_state.dart @@ -0,0 +1,62 @@ +part of 'vertices_editor_cubit.dart'; + +/// The state of the [VerticesEditorCubit]. +final class VerticesEditorState extends Equatable { + /// Creates a [VerticesEditorState] editing [initial]. + // ignore: use_primary_constructors, can't be const, which a primary one asks. + new({ + required this.initial, + List? vertices, + this.selectedIndex, + this.zoom = 1, + }) : vertices = vertices ?? initial.vertices; + + /// The vertices the editor opened with. + final ComponentVertices initial; + + /// The edited vertices, in order. + final List vertices; + + /// The index of the selected vertex in [vertices], if any. + final int? selectedIndex; + + /// The zoom of the canvas, relative to the scale that fits the polygon + /// in it (see `VerticesViewTransform.fit`), around its center. + final double zoom; + + /// Whether the canvas can zoom in further. + bool get canZoomIn => ZoomLevels.next(zoom) != null; + + /// Whether the canvas can zoom out further. + bool get canZoomOut => ZoomLevels.previous(zoom) != null; + + /// Whether a vertex can be deleted: a polygon needs at least + /// [ComponentVertices.minLength] vertices. + bool get canDelete => vertices.length > ComponentVertices.minLength; + + /// Whether the vertices were edited. + bool get hasChanges => result != initial.normalized(); + + /// The edited vertices, placed like Flame places them (see + /// [ComponentVertices.normalized]). + ComponentVertices get result => ComponentVertices(vertices).normalized(); + + /// Returns a copy of this state with the given fields replaced. + VerticesEditorState copyWith({ + List? vertices, + int? Function()? selectedIndex, + double? zoom, + }) { + return VerticesEditorState( + initial: initial, + vertices: vertices ?? this.vertices, + selectedIndex: selectedIndex != null + ? selectedIndex() + : this.selectedIndex, + zoom: zoom ?? this.zoom, + ); + } + + @override + List get props => [initial, vertices, selectedIndex, zoom]; +} diff --git a/packages/flame_studio/lib/vertices_editor/vertices_editor.dart b/packages/flame_studio/lib/vertices_editor/vertices_editor.dart new file mode 100644 index 00000000000..aba9592c166 --- /dev/null +++ b/packages/flame_studio/lib/vertices_editor/vertices_editor.dart @@ -0,0 +1,2 @@ +export 'bloc/vertices_editor_cubit.dart'; +export 'view/view.dart'; diff --git a/packages/flame_studio/lib/vertices_editor/view/vertices_editor_dialog.dart b/packages/flame_studio/lib/vertices_editor/view/vertices_editor_dialog.dart new file mode 100644 index 00000000000..b62d85d8135 --- /dev/null +++ b/packages/flame_studio/lib/vertices_editor/view/vertices_editor_dialog.dart @@ -0,0 +1,41 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flame_studio/vertices_editor/bloc/vertices_editor_cubit.dart'; +import 'package:flame_studio/vertices_editor/view/vertices_editor_view.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template vertices_editor_dialog} +/// A dialog to edit the vertices of a polygon on a canvas. +/// {@endtemplate} +class const VerticesEditorDialog({ + /// The vertices the dialog opens with. + required final ComponentVertices vertices, + + /// The paint the polygon is drawn with. + required final ComponentPaint paint, + super.key, +}) extends StatelessWidget { + /// {@macro vertices_editor_dialog} + this; + + /// Shows the dialog editing [vertices], drawn with [paint], and returns + /// the applied vertices, or `null` if the user cancelled. + static Future show( + BuildContext context, { + required ComponentVertices vertices, + required ComponentPaint paint, + }) { + return showDialog( + context: context, + builder: (_) => VerticesEditorDialog(vertices: vertices, paint: paint), + ); + } + + @override + Widget build(BuildContext context) { + return BlocProvider( + create: (_) => VerticesEditorCubit(vertices), + child: VerticesEditorView(paint: paint), + ); + } +} diff --git a/packages/flame_studio/lib/vertices_editor/view/vertices_editor_view.dart b/packages/flame_studio/lib/vertices_editor/view/vertices_editor_view.dart new file mode 100644 index 00000000000..c183280f804 --- /dev/null +++ b/packages/flame_studio/lib/vertices_editor/view/vertices_editor_view.dart @@ -0,0 +1,137 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flame_studio/vertices_editor/bloc/vertices_editor_cubit.dart'; +import 'package:flame_studio/vertices_editor/widgets/widgets.dart'; +import 'package:flame_studio/widgets/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template vertices_editor_view} +/// The content of the `VerticesEditorDialog`: the canvas, the list of +/// vertices to type their coordinates, the selected vertex, the zoom of +/// the canvas (also Cmd/Ctrl + `=`, `-` and `0`) and the buttons that apply +/// or discard the changes. +/// {@endtemplate} +class const VerticesEditorView({ + /// The paint the polygon is drawn with. + required final ComponentPaint paint, + super.key, +}) extends StatelessWidget { + /// {@macro vertices_editor_view} + this; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final state = context.watch().state; + final selectedIndex = state.selectedIndex; + final cubit = context.read(); + + return CallbackShortcuts( + bindings: zoomShortcuts( + onZoomIn: cubit.zoomedIn, + onZoomOut: cubit.zoomedOut, + onReset: cubit.zoomReset, + ), + child: Dialog( + clipBehavior: Clip.antiAlias, + child: SizedBox( + width: 1080, + height: 600, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(24, 20, 16, 12), + child: Row( + children: [ + Expanded( + child: Text( + 'Edit vertices', + style: theme.textTheme.titleLarge, + ), + ), + ZoomControls( + zoom: state.zoom, + onZoomIn: state.canZoomIn ? cubit.zoomedIn : null, + onZoomOut: state.canZoomOut ? cubit.zoomedOut : null, + onReset: cubit.zoomReset, + ), + ], + ), + ), + Expanded( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + child: ClipRect(child: VerticesCanvas(paint: paint)), + ), + const VerticalDivider(width: 1), + const SizedBox(width: 280, child: VerticesList()), + ], + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(24, 12, 16, 16), + child: Row( + spacing: 8, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + selectedIndex == null + ? '${state.vertices.length} vertices' + : _describe( + selectedIndex, + state.vertices[selectedIndex], + ), + ), + Text( + 'Drag to move · click + on an edge to add · ' + 'Delete to remove · type exact values on the right', + style: theme.textTheme.bodySmall, + ), + ], + ), + ), + IconButton( + tooltip: 'Delete vertex', + icon: const Icon(Icons.delete_outline), + onPressed: selectedIndex != null && state.canDelete + ? context + .read() + .selectedVertexDeleted + : null, + ), + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () => Navigator.of( + context, + ).pop(context.read().state.result), + child: const Text('Apply'), + ), + ], + ), + ), + ], + ), + ), + ), + ); + } + + static String _describe(int index, ComponentVertex vertex) { + return 'Vertex ${index + 1}: (${_number(vertex.x)}, ${_number(vertex.y)})'; + } + + static String _number(double value) { + return value == value.truncateToDouble() + ? value.toInt().toString() + : value.toStringAsFixed(1); + } +} diff --git a/packages/flame_studio/lib/vertices_editor/view/view.dart b/packages/flame_studio/lib/vertices_editor/view/view.dart new file mode 100644 index 00000000000..b7e6c361c46 --- /dev/null +++ b/packages/flame_studio/lib/vertices_editor/view/view.dart @@ -0,0 +1,2 @@ +export 'vertices_editor_dialog.dart'; +export 'vertices_editor_view.dart'; diff --git a/packages/flame_studio/lib/vertices_editor/widgets/vertices_canvas.dart b/packages/flame_studio/lib/vertices_editor/widgets/vertices_canvas.dart new file mode 100644 index 00000000000..91fb8cceccd --- /dev/null +++ b/packages/flame_studio/lib/vertices_editor/widgets/vertices_canvas.dart @@ -0,0 +1,195 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flame_studio/vertices_editor/bloc/vertices_editor_cubit.dart'; +import 'package:flame_studio/vertices_editor/widgets/vertices_painter.dart'; +import 'package:flame_studio/vertices_editor/widgets/vertices_view_transform.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template vertices_canvas} +/// The canvas of the vertices editor, where the user drags the vertices of +/// the polygon, adds vertices from the middle of its edges and deletes the +/// selected vertex with Delete or Backspace, or from its context menu. +/// {@endtemplate} +class const VerticesCanvas({ + /// The paint the polygon is drawn with. + required final ComponentPaint paint, + super.key, +}) extends StatefulWidget { + /// {@macro vertices_canvas} + this; + + /// The background of the canvas, the same as the preview's. + static const backgroundColor = Color(0xFF000000); + + @override + State createState() => _VerticesCanvasState(); +} + +class _VerticesCanvasState() extends State { + final _focusNode = FocusNode(debugLabel: 'VerticesCanvas'); + + // Computed once, so the polygon doesn't move while it is edited. The + // zoom is applied on top of it. + VerticesViewTransform? _fitted; + int? _hoveredEdge; + int? _draggedIndex; + MouseCursor _cursor = MouseCursor.defer; + + VerticesEditorCubit get _cubit => context.read(); + + List get _vertices => _cubit.state.vertices; + + @override + void dispose() { + _focusNode.dispose(); + super.dispose(); + } + + void _onTapUp(TapUpDetails details, VerticesViewTransform transform) { + _focusNode.requestFocus(); + final point = details.localPosition; + final vertex = transform.vertexAt(_vertices, point); + if (vertex != null) { + _cubit.vertexSelected(vertex); + } else if (transform.midpointAt(_vertices, point) case final edge?) { + _insertAtMidpoint(edge, transform); + } else { + _cubit.vertexSelected(null); + } + } + + void _onPanStart(DragStartDetails details, VerticesViewTransform transform) { + _focusNode.requestFocus(); + final point = details.localPosition; + final vertex = transform.vertexAt(_vertices, point); + if (vertex != null) { + _cubit.vertexSelected(vertex); + _draggedIndex = vertex; + } else if (transform.midpointAt(_vertices, point) case final edge?) { + _insertAtMidpoint(edge, transform); + _draggedIndex = edge + 1; + } + } + + void _onPanUpdate( + DragUpdateDetails details, + VerticesViewTransform transform, + ) { + final index = _draggedIndex; + if (index == null) { + return; + } + final vertex = transform.toLocal(details.localPosition); + _cubit.vertexMoved(index, vertex.x, vertex.y); + } + + void _insertAtMidpoint(int edge, VerticesViewTransform transform) { + final vertex = transform.toLocal(transform.midpointOf(_vertices, edge)); + _cubit.vertexInserted(edge, vertex.x, vertex.y); + setState(() => _hoveredEdge = null); + } + + void _onHover(PointerHoverEvent event, VerticesViewTransform transform) { + final point = event.localPosition; + final edge = transform.edgeNear(_vertices, point); + final cursor = transform.vertexAt(_vertices, point) != null + ? SystemMouseCursors.move + : transform.midpointAt(_vertices, point) != null + ? SystemMouseCursors.click + : MouseCursor.defer; + if (edge != _hoveredEdge || cursor != _cursor) { + setState(() { + _hoveredEdge = edge; + _cursor = cursor; + }); + } + } + + Future _onSecondaryTapUp( + TapUpDetails details, + VerticesViewTransform transform, + ) async { + final vertex = transform.vertexAt(_vertices, details.localPosition); + if (vertex == null) { + return; + } + _cubit.vertexSelected(vertex); + final overlay = + Overlay.of(context).context.findRenderObject()! as RenderBox; + final position = details.globalPosition; + final delete = await showMenu( + context: context, + position: RelativeRect.fromRect( + position & Size.zero, + Offset.zero & overlay.size, + ), + items: [ + PopupMenuItem( + value: true, + enabled: _cubit.state.canDelete, + child: const Text('Delete vertex'), + ), + ], + ); + if (delete ?? false) { + _cubit.selectedVertexDeleted(); + } + } + + @override + Widget build(BuildContext context) { + final state = context.watch().state; + return CallbackShortcuts( + bindings: { + const SingleActivator(LogicalKeyboardKey.delete): + _cubit.selectedVertexDeleted, + const SingleActivator(LogicalKeyboardKey.backspace): + _cubit.selectedVertexDeleted, + }, + child: Focus( + focusNode: _focusNode, + autofocus: true, + child: ColoredBox( + color: VerticesCanvas.backgroundColor, + child: LayoutBuilder( + builder: (context, constraints) { + final size = constraints.biggest; + final transform = (_fitted ??= VerticesViewTransform.fit( + state.initial.vertices, + size, + )).zoomed(state.zoom, size.center(Offset.zero)); + return MouseRegion( + cursor: _cursor, + onHover: (event) => _onHover(event, transform), + onExit: (_) => setState(() => _hoveredEdge = null), + child: GestureDetector( + // Drags start where the pointer went down, on the handle. + dragStartBehavior: DragStartBehavior.down, + onTapUp: (details) => _onTapUp(details, transform), + onSecondaryTapUp: (details) => + _onSecondaryTapUp(details, transform), + onPanStart: (details) => _onPanStart(details, transform), + onPanUpdate: (details) => _onPanUpdate(details, transform), + onPanEnd: (_) => _draggedIndex = null, + onPanCancel: () => _draggedIndex = null, + child: CustomPaint( + size: constraints.biggest, + painter: VerticesPainter( + vertices: state.vertices, + transform: transform, + polygonPaint: widget.paint, + selectedIndex: state.selectedIndex, + hoveredEdge: _draggedIndex == null ? _hoveredEdge : null, + ), + ), + ), + ); + }, + ), + ), + ), + ); + } +} diff --git a/packages/flame_studio/lib/vertices_editor/widgets/vertices_list.dart b/packages/flame_studio/lib/vertices_editor/widgets/vertices_list.dart new file mode 100644 index 00000000000..e0ce0cf2549 --- /dev/null +++ b/packages/flame_studio/lib/vertices_editor/widgets/vertices_list.dart @@ -0,0 +1,90 @@ +import 'package:flame_studio/component_editor/widgets/property_editors/number_field.dart'; +import 'package:flame_studio/vertices_editor/bloc/vertices_editor_cubit.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// {@template vertices_list} +/// The side bar of the vertices editor: a row per vertex, with fields to +/// type its exact coordinates and a button to delete it. +/// +/// Selecting a row, or focusing one of its fields, selects its vertex on +/// the canvas, and vice versa. +/// {@endtemplate} +class const VerticesList({super.key}) extends StatelessWidget { + /// {@macro vertices_list} + this; + + @override + Widget build(BuildContext context) { + final state = context.watch().state; + final cubit = context.read(); + final theme = Theme.of(context); + + return ListView.builder( + padding: const EdgeInsets.symmetric(vertical: 8), + itemCount: state.vertices.length, + itemBuilder: (context, index) { + final vertex = state.vertices[index]; + final isSelected = index == state.selectedIndex; + // Fresh fields when vertices are added or removed, so no field + // keeps the text of the vertex that used to be at its index. + return Material( + key: ValueKey('${state.vertices.length}-$index'), + color: isSelected + ? theme.colorScheme.secondaryContainer + : Colors.transparent, + child: InkWell( + onTap: () => cubit.vertexSelected(index), + child: Focus( + canRequestFocus: false, + skipTraversal: true, + onFocusChange: (focused) { + if (focused) { + cubit.vertexSelected(index); + } + }, + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 4, 8), + child: Row( + spacing: 8, + children: [ + SizedBox( + width: 24, + child: Text( + '${index + 1}', + style: theme.textTheme.labelLarge, + ), + ), + Expanded( + child: NumberField( + label: 'X', + value: vertex.x, + min: null, + onChanged: (x) => cubit.vertexMoved(index, x, vertex.y), + ), + ), + Expanded( + child: NumberField( + label: 'Y', + value: vertex.y, + min: null, + onChanged: (y) => cubit.vertexMoved(index, vertex.x, y), + ), + ), + IconButton( + tooltip: 'Delete vertex ${index + 1}', + icon: const Icon(Icons.remove_circle_outline), + onPressed: state.canDelete + ? () => cubit.vertexDeleted(index) + : null, + ), + ], + ), + ), + ), + ), + ); + }, + ); + } +} diff --git a/packages/flame_studio/lib/vertices_editor/widgets/vertices_painter.dart b/packages/flame_studio/lib/vertices_editor/widgets/vertices_painter.dart new file mode 100644 index 00000000000..b2e624b3572 --- /dev/null +++ b/packages/flame_studio/lib/vertices_editor/widgets/vertices_painter.dart @@ -0,0 +1,132 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flame_studio/vertices_editor/widgets/vertices_view_transform.dart'; +import 'package:flutter/material.dart'; + +/// {@template vertices_painter} +/// Draws the polygon edited in the vertices editor with its own paint, its +/// bounding box, the origin of its local coordinates, and the handles that +/// move its vertices and add new ones. +/// {@endtemplate} +class const VerticesPainter({ + /// The vertices of the polygon. + required final List vertices, + + /// Where the vertices are drawn. + required final VerticesViewTransform transform, + + /// The paint of the polygon. + required final ComponentPaint polygonPaint, + + /// The index of the selected vertex, if any. + final int? selectedIndex, + + /// The index of the edge (by its first vertex) under the pointer, whose + /// midpoint handle adds a vertex. + final int? hoveredEdge, +}) extends CustomPainter { + /// {@macro vertices_painter} + this; + + /// The color of the handles, the guides and the selection. + static const accentColor = Color(0xFFFF00FF); + + /// The color of the guides. + static const guideColor = Color(0x66FFFFFF); + + /// The radius of the vertex handles. + static const handleRadius = 6.0; + + @override + void paint(Canvas canvas, Size size) { + final guide = Paint() + ..color = guideColor + ..style = PaintingStyle.stroke; + + // The origin of the local coordinates. + final origin = transform.toCanvas(const ComponentVertex(0, 0)); + canvas + ..drawLine(Offset(origin.dx, 0), Offset(origin.dx, size.height), guide) + ..drawLine(Offset(0, origin.dy), Offset(size.width, origin.dy), guide); + + // The bounding box, which is the size of the component. + final bounds = VerticesViewTransform.boundsOf(vertices); + canvas.drawRect( + Rect.fromPoints( + transform.toCanvas(ComponentVertex(bounds.left, bounds.top)), + transform.toCanvas(ComponentVertex(bounds.right, bounds.bottom)), + ), + guide, + ); + + final path = Path() + ..addPolygon(vertices.map(transform.toCanvas).toList(), true); + canvas + ..drawPath( + path, + Paint() + ..color = Color(polygonPaint.color) + ..style = switch (polygonPaint.style) { + PaintStyle.fill => PaintingStyle.fill, + PaintStyle.stroke => PaintingStyle.stroke, + }, + ) + // The edges, which stay visible whatever the paint is. + ..drawPath( + path, + Paint() + ..color = accentColor.withValues(alpha: 0.6) + ..style = PaintingStyle.stroke, + ); + + if (hoveredEdge case final edge? when edge < vertices.length) { + _paintAddHandle(canvas, transform.midpointOf(vertices, edge)); + } + + for (final (index, vertex) in vertices.indexed) { + final center = transform.toCanvas(vertex); + canvas + ..drawCircle( + center, + handleRadius, + Paint()..color = index == selectedIndex ? accentColor : Colors.white, + ) + ..drawCircle( + center, + handleRadius, + Paint() + ..color = accentColor + ..style = PaintingStyle.stroke + ..strokeWidth = 2, + ); + } + } + + void _paintAddHandle(Canvas canvas, Offset center) { + const arm = handleRadius - 2; + final stroke = Paint() + ..color = Colors.white + ..style = PaintingStyle.stroke + ..strokeWidth = 2; + canvas + ..drawCircle(center, handleRadius, Paint()..color = accentColor) + ..drawLine( + center - const Offset(arm, 0), + center + const Offset(arm, 0), + stroke, + ) + ..drawLine( + center - const Offset(0, arm), + center + const Offset(0, arm), + stroke, + ); + } + + @override + bool shouldRepaint(VerticesPainter oldDelegate) { + return oldDelegate.vertices != vertices || + oldDelegate.transform != transform || + oldDelegate.polygonPaint != polygonPaint || + oldDelegate.selectedIndex != selectedIndex || + oldDelegate.hoveredEdge != hoveredEdge; + } +} diff --git a/packages/flame_studio/lib/vertices_editor/widgets/vertices_view_transform.dart b/packages/flame_studio/lib/vertices_editor/widgets/vertices_view_transform.dart new file mode 100644 index 00000000000..a8537e8c51c --- /dev/null +++ b/packages/flame_studio/lib/vertices_editor/widgets/vertices_view_transform.dart @@ -0,0 +1,149 @@ +import 'dart:math' as math; +import 'dart:ui'; + +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/foundation.dart'; + +/// {@template vertices_view_transform} +/// Maps the local coordinates of a polygon to the vertices canvas and +/// back, and finds the handles under a point of the canvas. +/// {@endtemplate} +@immutable +class const VerticesViewTransform({ + /// The canvas pixels per local unit. + final double scale = 1, + + /// Where the local origin is on the canvas. + final Offset offset = Offset.zero, +}) { + /// {@macro vertices_view_transform} + this; + + /// A transform that centers [vertices] in a canvas of [size], scaled down + /// only if they don't fit within [padding] of its edges. + factory fit( + List vertices, + Size size, { + double padding = 48, + }) { + final bounds = boundsOf(vertices); + final available = Size( + math.max(size.width - padding * 2, 1), + math.max(size.height - padding * 2, 1), + ); + final scale = [ + 1.0, + if (bounds.width > 0) available.width / bounds.width, + if (bounds.height > 0) available.height / bounds.height, + ].reduce(math.min); + return VerticesViewTransform( + scale: scale, + offset: size.center(Offset.zero) - bounds.center * scale, + ); + } + + /// This transform scaled by [zoom] around [center], a point of the + /// canvas that stays where it is. + VerticesViewTransform zoomed(double zoom, Offset center) { + return VerticesViewTransform( + scale: scale * zoom, + offset: center - (center - offset) * zoom, + ); + } + + @override + bool operator ==(Object other) => + other is VerticesViewTransform && + other.scale == scale && + other.offset == offset; + + @override + int get hashCode => Object.hash(scale, offset); + + /// The radius around a handle within which the pointer hits it. + static const hitRadius = 10.0; + + /// The bounding box of [vertices], in local coordinates. + static Rect boundsOf(List vertices) { + final xs = vertices.map((vertex) => vertex.x); + final ys = vertices.map((vertex) => vertex.y); + return Rect.fromLTRB( + xs.reduce(math.min), + ys.reduce(math.min), + xs.reduce(math.max), + ys.reduce(math.max), + ); + } + + /// Where [vertex] is on the canvas. + Offset toCanvas(ComponentVertex vertex) { + return Offset(vertex.x, vertex.y) * scale + offset; + } + + /// The vertex at [point] of the canvas, rounded to whole local units. + ComponentVertex toLocal(Offset point) { + final local = (point - offset) / scale; + return ComponentVertex(local.dx.roundToDouble(), local.dy.roundToDouble()); + } + + /// The middle of the edge that starts at the vertex at [index], on the + /// canvas. + Offset midpointOf(List vertices, int index) { + final from = toCanvas(vertices[index]); + final to = toCanvas(vertices[(index + 1) % vertices.length]); + return Offset.lerp(from, to, 0.5)!; + } + + /// The index of the vertex whose handle is at [point], if any. The + /// closest one wins. + int? vertexAt(List vertices, Offset point) { + return _closest( + vertices.length, + (index) => (toCanvas(vertices[index]) - point).distance, + ); + } + + /// The index of the edge (by its first vertex) whose midpoint handle is + /// at [point], if any. + int? midpointAt(List vertices, Offset point) { + return _closest( + vertices.length, + (index) => (midpointOf(vertices, index) - point).distance, + ); + } + + /// The index of the edge (by its first vertex) that passes near + /// [point], if any. + int? edgeNear(List vertices, Offset point) { + return _closest(vertices.length, (index) { + final from = toCanvas(vertices[index]); + final to = toCanvas(vertices[(index + 1) % vertices.length]); + return _distanceToSegment(point, from, to); + }); + } + + static int? _closest(int length, double Function(int index) distanceOf) { + int? closest; + var closestDistance = hitRadius; + for (var index = 0; index < length; index++) { + final distance = distanceOf(index); + if (distance <= closestDistance) { + closest = index; + closestDistance = distance; + } + } + return closest; + } + + static double _distanceToSegment(Offset point, Offset from, Offset to) { + final segment = to - from; + final lengthSquared = segment.distanceSquared; + if (lengthSquared == 0) { + return (point - from).distance; + } + final delta = point - from; + final t = ((delta.dx * segment.dx + delta.dy * segment.dy) / lengthSquared) + .clamp(0.0, 1.0); + return (point - (from + segment * t)).distance; + } +} diff --git a/packages/flame_studio/lib/vertices_editor/widgets/widgets.dart b/packages/flame_studio/lib/vertices_editor/widgets/widgets.dart new file mode 100644 index 00000000000..b5271606f30 --- /dev/null +++ b/packages/flame_studio/lib/vertices_editor/widgets/widgets.dart @@ -0,0 +1,4 @@ +export 'vertices_canvas.dart'; +export 'vertices_list.dart'; +export 'vertices_painter.dart'; +export 'vertices_view_transform.dart'; diff --git a/packages/flame_studio/lib/widgets/widgets.dart b/packages/flame_studio/lib/widgets/widgets.dart new file mode 100644 index 00000000000..6ea3d4f254b --- /dev/null +++ b/packages/flame_studio/lib/widgets/widgets.dart @@ -0,0 +1 @@ +export 'zoom_controls.dart'; diff --git a/packages/flame_studio/lib/widgets/zoom_controls.dart b/packages/flame_studio/lib/widgets/zoom_controls.dart new file mode 100644 index 00000000000..751c00585cc --- /dev/null +++ b/packages/flame_studio/lib/widgets/zoom_controls.dart @@ -0,0 +1,99 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +/// {@template zoom_controls} +/// Zoom out and zoom in buttons around the current [zoom], as a +/// percentage, which resets it to 100% when pressed. +/// +/// A `null` callback disables its button, e.g. at the smallest or largest +/// zoom. +/// {@endtemplate} +class const ZoomControls({ + /// The current zoom, `1` being the actual size. + required final double zoom, + + /// Called when the user zooms in. + required final VoidCallback? onZoomIn, + + /// Called when the user zooms out. + required final VoidCallback? onZoomOut, + + /// Called when the user resets the zoom to 100%. + required final VoidCallback? onReset, + super.key, +}) extends StatelessWidget { + /// {@macro zoom_controls} + this; + + @override + Widget build(BuildContext context) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + tooltip: 'Zoom out', + iconSize: 20, + visualDensity: VisualDensity.compact, + icon: const Icon(Icons.zoom_out), + onPressed: onZoomOut, + ), + Tooltip( + message: 'Reset zoom', + child: TextButton( + style: TextButton.styleFrom( + visualDensity: VisualDensity.compact, + minimumSize: const Size(56, 32), + padding: const EdgeInsets.symmetric(horizontal: 8), + ), + onPressed: onReset, + child: Text('${(zoom * 100).round()}%'), + ), + ), + IconButton( + tooltip: 'Zoom in', + iconSize: 20, + visualDensity: VisualDensity.compact, + icon: const Icon(Icons.zoom_in), + onPressed: onZoomIn, + ), + ], + ); + } +} + +/// The zoom keyboard shortcuts, for a `CallbackShortcuts`: Cmd/Ctrl + `=` +/// (or `+`) zooms in, Cmd/Ctrl + `-` zooms out and Cmd/Ctrl + `0` resets +/// the zoom. +Map zoomShortcuts({ + required VoidCallback onZoomIn, + required VoidCallback onZoomOut, + required VoidCallback onReset, +}) { + return { + for (final key in [ + LogicalKeyboardKey.equal, + LogicalKeyboardKey.add, + LogicalKeyboardKey.numpadAdd, + ]) ...{ + SingleActivator(key, meta: true): onZoomIn, + SingleActivator(key, control: true): onZoomIn, + // `+` is Shift+= on most keyboards. + SingleActivator(key, meta: true, shift: true): onZoomIn, + SingleActivator(key, control: true, shift: true): onZoomIn, + }, + for (final key in [ + LogicalKeyboardKey.minus, + LogicalKeyboardKey.numpadSubtract, + ]) ...{ + SingleActivator(key, meta: true): onZoomOut, + SingleActivator(key, control: true): onZoomOut, + }, + for (final key in [ + LogicalKeyboardKey.digit0, + LogicalKeyboardKey.numpad0, + ]) ...{ + SingleActivator(key, meta: true): onReset, + SingleActivator(key, control: true): onReset, + }, + }; +} diff --git a/packages/flame_studio/linux/.gitignore b/packages/flame_studio/linux/.gitignore new file mode 100644 index 00000000000..d3896c98444 --- /dev/null +++ b/packages/flame_studio/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/packages/flame_studio/linux/CMakeLists.txt b/packages/flame_studio/linux/CMakeLists.txt new file mode 100644 index 00000000000..49d30543b87 --- /dev/null +++ b/packages/flame_studio/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "flame_studio") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "xyz.bluefire.flame_studio") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration 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. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +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() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +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) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/packages/flame_studio/linux/flutter/CMakeLists.txt b/packages/flame_studio/linux/flutter/CMakeLists.txt new file mode 100644 index 00000000000..d5bd01648a9 --- /dev/null +++ b/packages/flame_studio/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/packages/flame_studio/linux/flutter/generated_plugin_registrant.cc b/packages/flame_studio/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 00000000000..64a0ecea40d --- /dev/null +++ b/packages/flame_studio/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); + file_selector_plugin_register_with_registrar(file_selector_linux_registrar); +} diff --git a/packages/flame_studio/linux/flutter/generated_plugin_registrant.h b/packages/flame_studio/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 00000000000..e0f0a47bc08 --- /dev/null +++ b/packages/flame_studio/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/flame_studio/linux/flutter/generated_plugins.cmake b/packages/flame_studio/linux/flutter/generated_plugins.cmake new file mode 100644 index 00000000000..a630fa93c7d --- /dev/null +++ b/packages/flame_studio/linux/flutter/generated_plugins.cmake @@ -0,0 +1,25 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + file_selector_linux +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/packages/flame_studio/linux/runner/CMakeLists.txt b/packages/flame_studio/linux/runner/CMakeLists.txt new file mode 100644 index 00000000000..e97dabc7028 --- /dev/null +++ b/packages/flame_studio/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/packages/flame_studio/linux/runner/main.cc b/packages/flame_studio/linux/runner/main.cc new file mode 100644 index 00000000000..e7c5c543703 --- /dev/null +++ b/packages/flame_studio/linux/runner/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/packages/flame_studio/linux/runner/my_application.cc b/packages/flame_studio/linux/runner/my_application.cc new file mode 100644 index 00000000000..21ffb79f3d4 --- /dev/null +++ b/packages/flame_studio/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#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) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// 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, "flame_studio"); + 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, "flame_studio"); + } + + gtk_window_set_default_size(window, 1280, 720); + + 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); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(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 GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// 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_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/packages/flame_studio/linux/runner/my_application.h b/packages/flame_studio/linux/runner/my_application.h new file mode 100644 index 00000000000..db16367a77d --- /dev/null +++ b/packages/flame_studio/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#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/packages/flame_studio/macos/.gitignore b/packages/flame_studio/macos/.gitignore new file mode 100644 index 00000000000..746adbb6b9e --- /dev/null +++ b/packages/flame_studio/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/packages/flame_studio/macos/Flutter/Flutter-Debug.xcconfig b/packages/flame_studio/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 00000000000..c2efd0b608b --- /dev/null +++ b/packages/flame_studio/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/flame_studio/macos/Flutter/Flutter-Release.xcconfig b/packages/flame_studio/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 00000000000..c2efd0b608b --- /dev/null +++ b/packages/flame_studio/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/flame_studio/macos/Flutter/GeneratedPluginRegistrant.swift b/packages/flame_studio/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 00000000000..ab1fdba8bdc --- /dev/null +++ b/packages/flame_studio/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import file_selector_macos +import shared_preferences_foundation + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) +} diff --git a/packages/flame_studio/macos/Runner.xcodeproj/project.pbxproj b/packages/flame_studio/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 00000000000..42d315b19c0 --- /dev/null +++ b/packages/flame_studio/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,729 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* flame_studio.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "flame_studio.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* flame_studio.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* flame_studio.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = xyz.bluefire.flameStudio.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/flame_studio.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/flame_studio"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = xyz.bluefire.flameStudio.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/flame_studio.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/flame_studio"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = xyz.bluefire.flameStudio.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/flame_studio.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/flame_studio"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/packages/flame_studio/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/packages/flame_studio/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000000..18d981003d6 --- /dev/null +++ b/packages/flame_studio/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/packages/flame_studio/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/packages/flame_studio/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 00000000000..5526d66d4d1 --- /dev/null +++ b/packages/flame_studio/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/flame_studio/macos/Runner.xcworkspace/contents.xcworkspacedata b/packages/flame_studio/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000000..1d526a16ed0 --- /dev/null +++ b/packages/flame_studio/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/packages/flame_studio/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/packages/flame_studio/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000000..18d981003d6 --- /dev/null +++ b/packages/flame_studio/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/packages/flame_studio/macos/Runner/AppDelegate.swift b/packages/flame_studio/macos/Runner/AppDelegate.swift new file mode 100644 index 00000000000..b3c17614122 --- /dev/null +++ b/packages/flame_studio/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000000..a2ec33f19f1 --- /dev/null +++ b/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 00000000000..82b6f9d9a33 Binary files /dev/null and b/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 00000000000..13b35eba55c Binary files /dev/null and b/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 00000000000..0a3f5fa40fb Binary files /dev/null and b/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 00000000000..bdb57226d5f Binary files /dev/null and b/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 00000000000..f083318e09c Binary files /dev/null and b/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 00000000000..326c0e72c9d Binary files /dev/null and b/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 00000000000..2f1632cfddf Binary files /dev/null and b/packages/flame_studio/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/packages/flame_studio/macos/Runner/Base.lproj/MainMenu.xib b/packages/flame_studio/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 00000000000..80e867a4e06 --- /dev/null +++ b/packages/flame_studio/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/flame_studio/macos/Runner/Configs/AppInfo.xcconfig b/packages/flame_studio/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 00000000000..c9f929d0c32 --- /dev/null +++ b/packages/flame_studio/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = flame_studio + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = xyz.bluefire.flameStudio + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 xyz.bluefire. All rights reserved. diff --git a/packages/flame_studio/macos/Runner/Configs/Debug.xcconfig b/packages/flame_studio/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 00000000000..36b0fd9464f --- /dev/null +++ b/packages/flame_studio/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/packages/flame_studio/macos/Runner/Configs/Release.xcconfig b/packages/flame_studio/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 00000000000..dff4f49561c --- /dev/null +++ b/packages/flame_studio/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/packages/flame_studio/macos/Runner/Configs/Warnings.xcconfig b/packages/flame_studio/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 00000000000..42bcbf4780b --- /dev/null +++ b/packages/flame_studio/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/packages/flame_studio/macos/Runner/DebugProfile.entitlements b/packages/flame_studio/macos/Runner/DebugProfile.entitlements new file mode 100644 index 00000000000..4eac53fe0f7 --- /dev/null +++ b/packages/flame_studio/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/packages/flame_studio/macos/Runner/Info.plist b/packages/flame_studio/macos/Runner/Info.plist new file mode 100644 index 00000000000..4789daa6a44 --- /dev/null +++ b/packages/flame_studio/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/packages/flame_studio/macos/Runner/MainFlutterWindow.swift b/packages/flame_studio/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 00000000000..3cc05eb2349 --- /dev/null +++ b/packages/flame_studio/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/packages/flame_studio/macos/Runner/Release.entitlements b/packages/flame_studio/macos/Runner/Release.entitlements new file mode 100644 index 00000000000..6631ffa6f24 --- /dev/null +++ b/packages/flame_studio/macos/Runner/Release.entitlements @@ -0,0 +1,6 @@ + + + + + + diff --git a/packages/flame_studio/macos/RunnerTests/RunnerTests.swift b/packages/flame_studio/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 00000000000..61f3bd1fc50 --- /dev/null +++ b/packages/flame_studio/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/packages/flame_studio/pubspec.yaml b/packages/flame_studio/pubspec.yaml index 39b9b4b15de..97938c9c0e2 100644 --- a/packages/flame_studio/pubspec.yaml +++ b/packages/flame_studio/pubspec.yaml @@ -1,8 +1,8 @@ name: flame_studio resolution: workspace -description: An IDE-like environment for developing and debugging Flame games. -version: 0.0.0 +description: "Create Flame components visually." publish_to: none +version: 1.0.0+1 homepage: https://github.com/flame-engine/flame/tree/main/packages/flame_studio funding: - https://opencollective.com/blue-fire @@ -14,20 +14,28 @@ environment: flutter: ">=3.47.0" dependencies: - collection: ^1.17.1 + bloc: ^9.2.1 + dart_style: ^3.1.14 + equatable: ^3.0.0 + file_selector: ^1.1.0 flame: ^2.0.0-dev.1 + flex_color_picker: ^3.8.0 flutter: sdk: flutter - flutter_riverpod: ^3.0.3 - meta: ^1.12.0 + flutter_bloc: ^9.1.1 + path: ^1.9.0 + pub_semver: ^2.2.1 + shared_preferences: ^2.5.6 dev_dependencies: + bloc_lint: ^0.4.3 + bloc_test: ^10.0.0 flame_lint: ^1.5.0-dev.1 flame_test: ^3.0.0-dev.1 flutter_test: sdk: flutter - test: any + mocktail: ^1.0.4 + very_good_analysis: ^11.0.0 flutter: - assets: - - assets/logo_flame.png + uses-material-design: true diff --git a/packages/flame_studio/test/app/view/app_test.dart b/packages/flame_studio/test/app/view/app_test.dart new file mode 100644 index 00000000000..8dd74f5ff6a --- /dev/null +++ b/packages/flame_studio/test/app/view/app_test.dart @@ -0,0 +1,32 @@ +import 'package:flame_studio/app/app.dart'; +import 'package:flame_studio/home/home.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockProjectRepository() extends Mock implements ProjectRepository; + +class _MockComponentRepository() extends Mock implements ComponentRepository; + +class _MockEditorPreferencesRepository() + extends Mock + implements EditorPreferencesRepository; + +void main() { + group(App, () { + testWidgets('renders the home view', (tester) async { + final projectRepository = _MockProjectRepository(); + when(projectRepository.getRecentProjects).thenAnswer((_) async => []); + + await tester.pumpWidget( + App( + projectRepository: projectRepository, + componentRepository: _MockComponentRepository(), + editorPreferencesRepository: _MockEditorPreferencesRepository(), + ), + ); + + expect(find.byType(HomeView), findsOneWidget); + }); + }); +} diff --git a/packages/flame_studio/test/clients/file_system_client_test.dart b/packages/flame_studio/test/clients/file_system_client_test.dart new file mode 100644 index 00000000000..16d5e66a245 --- /dev/null +++ b/packages/flame_studio/test/clients/file_system_client_test.dart @@ -0,0 +1,118 @@ +import 'dart:io'; + +import 'package:flame_studio/clients/clients.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Directory _createTempDirectory() { + final directory = Directory.systemTemp.createTempSync(); + addTearDown(() => directory.deleteSync(recursive: true)); + return directory; +} + +void main() { + group(FileSystemClient, () { + test('can be instantiated without a directory picker', () { + expect(FileSystemClient.new, returnsNormally); + }); + + group('pickDirectory', () { + test('returns the picked path', () async { + final client = FileSystemClient(directoryPicker: () async => '/a/b'); + + expect(await client.pickDirectory(), equals('/a/b')); + }); + + test('returns null when cancelled', () async { + final client = FileSystemClient(directoryPicker: () async => null); + + expect(await client.pickDirectory(), isNull); + }); + }); + + group('directoryExists', () { + test('returns true for an existing directory', () async { + final directory = Directory.systemTemp.createTempSync(); + addTearDown(() => directory.deleteSync(recursive: true)); + + expect( + await FileSystemClient().directoryExists(directory.path), + isTrue, + ); + }); + + test('returns false for a missing directory', () async { + final directory = Directory.systemTemp.createTempSync()..deleteSync(); + + expect( + await FileSystemClient().directoryExists(directory.path), + isFalse, + ); + }); + }); + + group('fileExists', () { + test('returns whether the file exists', () async { + final directory = _createTempDirectory(); + final file = File('${directory.path}/a.txt')..writeAsStringSync('a'); + + expect(await FileSystemClient().fileExists(file.path), isTrue); + expect( + await FileSystemClient().fileExists('${directory.path}/b.txt'), + isFalse, + ); + }); + }); + + group('listFiles', () { + test('returns an empty list for a missing directory', () async { + final directory = Directory.systemTemp.createTempSync()..deleteSync(); + + expect(await FileSystemClient().listFiles(directory.path), isEmpty); + }); + + test('returns only files, filtered by extension', () async { + final directory = _createTempDirectory(); + File('${directory.path}/a.json').writeAsStringSync('{}'); + File('${directory.path}/b.txt').writeAsStringSync('b'); + Directory('${directory.path}/c.json').createSync(); + + expect( + await FileSystemClient().listFiles(directory.path), + unorderedEquals([ + '${directory.path}/a.json', + '${directory.path}/b.txt', + ]), + ); + expect( + await FileSystemClient().listFiles( + directory.path, + extension: '.json', + ), + equals(['${directory.path}/a.json']), + ); + }); + }); + + group('writeFile and readFile', () { + test('creates parent directories and round-trips contents', () async { + final directory = _createTempDirectory(); + final path = '${directory.path}/nested/dir/a.txt'; + + await FileSystemClient().writeFile(path, 'hello'); + + expect(await FileSystemClient().readFile(path), equals('hello')); + }); + }); + + group('deleteFile', () { + test('deletes the file', () async { + final directory = _createTempDirectory(); + final file = File('${directory.path}/a.txt')..writeAsStringSync('a'); + + await FileSystemClient().deleteFile(file.path); + + expect(file.existsSync(), isFalse); + }); + }); + }); +} diff --git a/packages/flame_studio/test/clients/key_value_storage_client_test.dart b/packages/flame_studio/test/clients/key_value_storage_client_test.dart new file mode 100644 index 00000000000..81daafdcfb7 --- /dev/null +++ b/packages/flame_studio/test/clients/key_value_storage_client_test.dart @@ -0,0 +1,44 @@ +import 'package:flame_studio/clients/clients.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class _MockSharedPreferencesAsync() + extends Mock + implements SharedPreferencesAsync; + +void main() { + group(KeyValueStorageClient, () { + late SharedPreferencesAsync preferences; + late KeyValueStorageClient client; + + setUp(() { + preferences = _MockSharedPreferencesAsync(); + client = KeyValueStorageClient(preferences: preferences); + }); + + group('read', () { + test('returns the stored value', () async { + when(() => preferences.getString('key')).thenAnswer((_) async => 'v'); + + expect(await client.read('key'), equals('v')); + }); + + test('returns null when nothing is stored', () async { + when(() => preferences.getString('key')).thenAnswer((_) async => null); + + expect(await client.read('key'), isNull); + }); + }); + + group('write', () { + test('stores the value', () async { + when(() => preferences.setString('key', 'v')).thenAnswer((_) async {}); + + await client.write('key', 'v'); + + verify(() => preferences.setString('key', 'v')).called(1); + }); + }); + }); +} diff --git a/packages/flame_studio/test/component_editor/bloc/component_editor_bloc_test.dart b/packages/flame_studio/test/component_editor/bloc/component_editor_bloc_test.dart new file mode 100644 index 00000000000..a5874880177 --- /dev/null +++ b/packages/flame_studio/test/component_editor/bloc/component_editor_bloc_test.dart @@ -0,0 +1,1235 @@ +import 'dart:async'; + +import 'package:bloc_test/bloc_test.dart'; +import 'package:flame_studio/component_editor/component_editor.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockComponentRepository() extends Mock implements ComponentRepository; + +class _MockProjectRepository() extends Mock implements ProjectRepository; + +class _MockEditorPreferencesRepository() + extends Mock + implements EditorPreferencesRepository; + +void main() { + setUpAll( + () => registerFallbackValue(const RectangleComponent(name: 'Fallback')), + ); + + group(ComponentEditorBloc, () { + const project = Project(path: '/projects/my_game'); + const component = RectangleComponent(name: 'Player'); + const size = ComponentSize(width: 10, height: 20); + const paint = ComponentPaint(color: 0xFFFF0000, style: PaintStyle.stroke); + const edited = RectangleComponent(name: 'Player', size: size); + const palette = Palette( + colors: [PaletteColor(name: 'primary', color: 0xFF00FF00)], + ); + + late ComponentRepository componentRepository; + late ProjectRepository projectRepository; + late EditorPreferencesRepository editorPreferencesRepository; + + void stubStoredZoom(double zoom) { + when( + () => editorPreferencesRepository.getComponentZoom( + projectPath: project.path, + componentName: component.name, + ), + ).thenAnswer((_) async => zoom); + } + + setUp(() { + editorPreferencesRepository = _MockEditorPreferencesRepository(); + stubStoredZoom(EditorPreferencesRepository.defaultZoom); + when( + () => editorPreferencesRepository.setComponentZoom( + projectPath: any(named: 'projectPath'), + componentName: any(named: 'componentName'), + zoom: any(named: 'zoom'), + ), + ).thenAnswer((_) async {}); + componentRepository = _MockComponentRepository(); + projectRepository = _MockProjectRepository(); + when( + () => projectRepository.getSettings(project), + ).thenAnswer((_) async => const ProjectSettings(outputPath: 'lib/game')); + when(() => componentRepository.getPalette(project.path)) + .thenAnswer((_) async => const Palette()); + }); + + ComponentEditorBloc buildBloc() => ComponentEditorBloc( + project: project, + component: component, + componentRepository: componentRepository, + projectRepository: projectRepository, + editorPreferencesRepository: editorPreferencesRepository, + ); + + test('initial state has no changes', () { + final state = buildBloc().state; + + expect( + state, + equals( + const ComponentEditorState( + component: component, + savedComponent: component, + ), + ), + ); + expect(state.hasChanges, isFalse); + }); + + blocTest( + 'ComponentEditorSizeChanged updates the size', + build: buildBloc, + act: (bloc) => bloc.add(const ComponentEditorSizeChanged(size)), + expect: () => [ + isA() + .having((s) => s.component, 'component', edited) + .having((s) => s.hasChanges, 'hasChanges', isTrue), + ], + ); + + blocTest( + 'ComponentEditorAnchorChanged updates the anchor', + build: buildBloc, + act: (bloc) => + bloc.add(const ComponentEditorAnchorChanged(ComponentAnchor.center)), + expect: () => const [ + ComponentEditorState( + component: RectangleComponent( + name: 'Player', + anchor: ComponentAnchor.center, + ), + savedComponent: component, + ), + ], + ); + + blocTest( + 'ComponentEditorAngleChanged updates the angle', + build: buildBloc, + act: (bloc) => bloc.add( + const ComponentEditorAngleChanged(ComponentAngle(radians: 1)), + ), + expect: () => const [ + ComponentEditorState( + component: RectangleComponent( + name: 'Player', + angle: ComponentAngle(radians: 1), + ), + savedComponent: component, + ), + ], + ); + + group('ComponentEditorVerticesChanged', () { + const vertices = ComponentVertices(ComponentVertices.square); + const polygon = PolygonComponent(name: 'Player'); + + blocTest( + 'updates the vertices of a polygon', + build: () => ComponentEditorBloc( + project: project, + component: polygon, + componentRepository: componentRepository, + projectRepository: projectRepository, + editorPreferencesRepository: editorPreferencesRepository, + ), + act: (bloc) => bloc.add(const ComponentEditorVerticesChanged(vertices)), + expect: () => const [ + ComponentEditorState( + component: PolygonComponent(name: 'Player', vertices: vertices), + savedComponent: polygon, + ), + ], + ); + + blocTest( + 'ignores components without vertices', + build: buildBloc, + act: (bloc) => bloc.add(const ComponentEditorVerticesChanged(vertices)), + expect: () => const [], + ); + }); + + group('ComponentEditorRadiusChanged', () { + const radius = ComponentRadius(radius: 10); + const circle = CircleComponent(name: 'Player'); + + blocTest( + 'updates the radius of a circle', + build: () => ComponentEditorBloc( + project: project, + component: circle, + componentRepository: componentRepository, + projectRepository: projectRepository, + editorPreferencesRepository: editorPreferencesRepository, + ), + act: (bloc) => bloc.add(const ComponentEditorRadiusChanged(radius)), + expect: () => const [ + ComponentEditorState( + component: CircleComponent(name: 'Player', radius: radius), + savedComponent: circle, + ), + ], + ); + + blocTest( + 'ignores components without a radius', + build: buildBloc, + act: (bloc) => bloc.add(const ComponentEditorRadiusChanged(radius)), + expect: () => const [], + ); + }); + + blocTest( + 'ComponentEditorPaintChanged updates the paint', + build: buildBloc, + act: (bloc) => bloc.add(const ComponentEditorPaintChanged(paint)), + expect: () => const [ + ComponentEditorState( + component: RectangleComponent(name: 'Player', paint: paint), + savedComponent: component, + ), + ], + ); + + group('ComponentEditorCollisionChanged', () { + const collision = ComponentCollision(isSolid: true); + const hitbox = CircleHitboxComponent(name: 'Player'); + + blocTest( + 'updates the collision of a hitbox', + build: () => ComponentEditorBloc( + project: project, + component: hitbox, + componentRepository: componentRepository, + projectRepository: projectRepository, + editorPreferencesRepository: editorPreferencesRepository, + ), + act: (bloc) => + bloc.add(const ComponentEditorCollisionChanged(collision)), + expect: () => const [ + ComponentEditorState( + component: CircleHitboxComponent( + name: 'Player', + collision: collision, + ), + savedComponent: hitbox, + ), + ], + ); + + blocTest( + 'ignores components that are not hitboxes', + build: buildBloc, + act: (bloc) => + bloc.add(const ComponentEditorCollisionChanged(collision)), + expect: () => const [], + ); + }); + + test('shows the hitboxes by default', () { + expect(buildBloc().state.areHitboxesVisible, isTrue); + }); + + blocTest( + 'ComponentEditorHitboxesVisibilityToggled toggles the hitboxes', + build: buildBloc, + act: (bloc) => bloc + ..add(const ComponentEditorHitboxesVisibilityToggled()) + ..add(const ComponentEditorHitboxesVisibilityToggled()), + expect: () => const [ + ComponentEditorState( + component: component, + savedComponent: component, + areHitboxesVisible: false, + ), + ComponentEditorState(component: component, savedComponent: component), + ], + ); + + test('highlights the selection by default', () { + expect(buildBloc().state.isSelectionHighlighted, isTrue); + }); + + blocTest( + 'ComponentEditorSelectionHighlightToggled toggles the highlight', + build: buildBloc, + act: (bloc) => bloc + ..add(const ComponentEditorSelectionHighlightToggled()) + ..add(const ComponentEditorSelectionHighlightToggled()), + expect: () => const [ + ComponentEditorState( + component: component, + savedComponent: component, + isSelectionHighlighted: false, + ), + ComponentEditorState(component: component, savedComponent: component), + ], + ); + + group('zoom', () { + void verifyZoomStored(double zoom) { + verify( + () => editorPreferencesRepository.setComponentZoom( + projectPath: project.path, + componentName: component.name, + zoom: zoom, + ), + ).called(1); + } + + blocTest( + 'ComponentEditorZoomedIn steps to the next level and stores it', + build: buildBloc, + act: (bloc) => bloc.add(const ComponentEditorZoomedIn()), + expect: () => [ + isA() + .having((s) => s.zoom, 'zoom', 1.5) + .having((s) => s.hasChanges, 'hasChanges', isFalse) + .having((s) => s.status, 'status', ComponentEditorStatus.ready), + ], + verify: (_) => verifyZoomStored(1.5), + ); + + blocTest( + 'ComponentEditorZoomedOut steps to the previous level and stores it', + build: buildBloc, + act: (bloc) => bloc.add(const ComponentEditorZoomedOut()), + expect: () => [ + isA().having((s) => s.zoom, 'zoom', 0.75), + ], + verify: (_) => verifyZoomStored(0.75), + ); + + blocTest( + 'steps from a zoom between levels to the nearest ones', + build: buildBloc, + seed: () => const ComponentEditorState( + component: component, + savedComponent: component, + zoom: 1.2, + ), + act: (bloc) => bloc + ..add(const ComponentEditorZoomedIn()) + ..add(const ComponentEditorZoomReset()) + ..add(const ComponentEditorZoomedOut()), + expect: () => [ + isA().having((s) => s.zoom, 'zoom', 1.5), + isA().having((s) => s.zoom, 'zoom', 1), + isA().having((s) => s.zoom, 'zoom', 0.75), + ], + ); + + blocTest( + 'does not zoom past the largest and smallest levels', + build: buildBloc, + seed: () => const ComponentEditorState( + component: component, + savedComponent: component, + zoom: EditorPreferencesRepository.maxZoom, + ), + act: (bloc) => bloc.add(const ComponentEditorZoomedIn()), + expect: () => const [], + verify: (bloc) { + expect(bloc.state.nextZoom, isNull); + expect( + const ComponentEditorState( + component: component, + savedComponent: component, + zoom: EditorPreferencesRepository.minZoom, + ).previousZoom, + isNull, + ); + }, + ); + + blocTest( + 'ComponentEditorZoomReset goes back to 100% and stores it', + build: buildBloc, + seed: () => const ComponentEditorState( + component: component, + savedComponent: component, + zoom: 3, + ), + act: (bloc) => bloc.add(const ComponentEditorZoomReset()), + expect: () => const [ + ComponentEditorState(component: component, savedComponent: component), + ], + verify: (_) => verifyZoomStored(1), + ); + + blocTest( + 'still zooms when the zoom cannot be stored', + setUp: () => when( + () => editorPreferencesRepository.setComponentZoom( + projectPath: any(named: 'projectPath'), + componentName: any(named: 'componentName'), + zoom: any(named: 'zoom'), + ), + ).thenThrow(Exception('oops')), + build: buildBloc, + act: (bloc) => bloc.add(const ComponentEditorZoomedIn()), + expect: () => [ + isA().having((s) => s.zoom, 'zoom', 1.5), + ], + ); + }); + + test('rootClassOwner is the other component generating the root ' + 'class', () { + const aB = RectangleComponent(name: 'a_b'); + const aBHead = RectangleComponent(name: 'a_b_head'); + const state = ComponentEditorState( + component: RectangleComponent( + name: 'AB', + children: [RectangleComponent(name: 'head')], + ), + savedComponent: component, + takenClassNames: {r'$AB': aB, r'$ABHead': aBHead, r'$X': aB}, + ); + + expect(state.rootClassOwner, equals(aB)); + expect( + state.conflictingClassNames, + equals({r'$AB': aB, r'$ABHead': aBHead}), + ); + }); + + group(ComponentEditorStarted, () { + const enemy = RectangleComponent(name: 'Enemy'); + const ship = RectangleComponent( + name: 'Ship', + children: [RectangleComponent(name: 'wing')], + ); + + void stubComponents(List components) { + when(() => componentRepository.getComponents(project.path)) + .thenAnswer((_) async => components); + } + + void stubUpToDate({required bool isUpToDate}) { + when( + () => componentRepository.isComponentCodeUpToDate( + project.path, + 'lib/game', + component, + ), + ).thenAnswer((_) async => isUpToDate); + } + + blocTest( + 'loads the stored zoom of the component', + setUp: () { + stubStoredZoom(2); + stubComponents(const []); + stubUpToDate(isUpToDate: true); + }, + build: buildBloc, + act: (bloc) => bloc.add(const ComponentEditorStarted()), + expect: () => const [ + ComponentEditorState( + component: component, + savedComponent: component, + zoom: 2, + ), + ], + ); + + blocTest( + 'keeps a zoom changed while the stored one loads', + setUp: () { + final completer = Completer(); + when( + () => editorPreferencesRepository.getComponentZoom( + projectPath: project.path, + componentName: component.name, + ), + ).thenAnswer((_) => completer.future); + stubComponents(const []); + stubUpToDate(isUpToDate: true); + Future.delayed(Duration.zero, () => completer.complete(4)); + }, + build: buildBloc, + act: (bloc) => bloc + ..add(const ComponentEditorStarted()) + ..add(const ComponentEditorZoomedIn()), + wait: const Duration(milliseconds: 10), + expect: () => [ + isA().having((s) => s.zoom, 'zoom', 1.5), + ], + ); + + blocTest( + 'keeps the default zoom when the stored one cannot be loaded', + setUp: () { + when( + () => editorPreferencesRepository.getComponentZoom( + projectPath: project.path, + componentName: component.name, + ), + ).thenThrow(Exception('oops')); + stubComponents(const []); + stubUpToDate(isUpToDate: true); + }, + build: buildBloc, + act: (bloc) => bloc.add(const ComponentEditorStarted()), + verify: (bloc) => + expect(bloc.state.zoom, EditorPreferencesRepository.defaultZoom), + ); + + blocTest( + 'loads the classes of the other components', + setUp: () { + stubComponents(const [enemy, component, ship]); + stubUpToDate(isUpToDate: true); + }, + build: buildBloc, + act: (bloc) => bloc.add(const ComponentEditorStarted()), + expect: () => const [ + ComponentEditorState( + component: component, + savedComponent: component, + takenClassNames: { + r'$Enemy': enemy, + r'$Ship': ship, + r'$ShipWing': ship, + }, + ), + ], + ); + + blocTest( + 'reports clashes that already exist', + setUp: () { + stubComponents(const [RectangleComponent(name: 'player_')]); + stubUpToDate(isUpToDate: true); + }, + build: buildBloc, + act: (bloc) => bloc.add(const ComponentEditorStarted()), + skip: 1, + expect: () => [ + isA() + .having( + (s) => s.status, + 'status', + ComponentEditorStatus.classConflict, + ) + .having( + (s) => s.rootClassOwner?.name, + 'rootClassOwner', + 'player_', + ), + ], + ); + + blocTest( + 'marks missing or outdated code, so it can be saved without changes', + setUp: () { + stubComponents(const []); + stubUpToDate(isUpToDate: false); + }, + build: buildBloc, + act: (bloc) => bloc.add(const ComponentEditorStarted()), + // The other components are loaded first. + skip: 1, + expect: () => [ + isA() + .having((s) => s.isCodeOutdated, 'isCodeOutdated', isTrue) + .having((s) => s.canSave, 'canSave', isTrue), + ], + ); + + test('does not overwrite what a save found meanwhile', () async { + stubComponents(const []); + final isUpToDate = Completer(); + when( + () => componentRepository.isComponentCodeUpToDate( + project.path, + 'lib/game', + component, + ), + ).thenAnswer((_) => isUpToDate.future); + when(() => componentRepository.saveComponent(project.path, edited)) + .thenAnswer((_) async {}); + when( + () => componentRepository.writeComponentCode( + project.path, + 'lib/game', + edited, + ), + ).thenAnswer((_) async {}); + + final bloc = buildBloc()..add(const ComponentEditorStarted()); + await Future.delayed(Duration.zero); + bloc + ..add(const ComponentEditorSizeChanged(size)) + ..add(const ComponentEditorSaveRequested()); + await Future.delayed(Duration.zero); + expect(bloc.state.status, ComponentEditorStatus.saved); + + // The check was for the code of the component before the save. + isUpToDate.complete(false); + await Future.delayed(Duration.zero); + + expect(bloc.state.isCodeOutdated, isFalse); + await bloc.close(); + }); + + blocTest( + 'emits nothing when nothing can be loaded', + setUp: () { + when(() => componentRepository.getComponents(project.path)) + .thenThrow(Exception()); + when(() => projectRepository.getSettings(project)) + .thenThrow(Exception()); + }, + build: buildBloc, + act: (bloc) => bloc.add(const ComponentEditorStarted()), + expect: () => const [], + ); + + blocTest( + 'loads the palette', + setUp: () { + stubComponents(const []); + stubUpToDate(isUpToDate: true); + when(() => componentRepository.getPalette(project.path)) + .thenAnswer((_) async => palette); + }, + build: buildBloc, + act: (bloc) => bloc.add(const ComponentEditorStarted()), + expect: () => const [ + ComponentEditorState( + component: component, + savedComponent: component, + palette: palette, + ), + ], + ); + + blocTest( + 'keeps a palette changed while loading', + setUp: () { + stubComponents(const []); + stubUpToDate(isUpToDate: true); + when(() => componentRepository.getPalette(project.path)) + .thenAnswer((_) async => const Palette()); + }, + build: buildBloc, + act: (bloc) => bloc + ..add(const ComponentEditorPaletteChanged(palette)) + ..add(const ComponentEditorStarted()), + expect: () => const [ + ComponentEditorState( + component: component, + savedComponent: component, + palette: palette, + ), + ], + ); + + blocTest( + 'keeps an empty palette when it can not be loaded', + setUp: () { + stubComponents(const []); + stubUpToDate(isUpToDate: true); + when(() => componentRepository.getPalette(project.path)) + .thenThrow(Exception()); + }, + build: buildBloc, + act: (bloc) => bloc.add(const ComponentEditorStarted()), + verify: (bloc) => expect(bloc.state.palette, equals(const Palette())), + ); + }); + + blocTest( + 'ComponentEditorPaletteChanged replaces the palette without changes', + build: buildBloc, + act: (bloc) => bloc.add(const ComponentEditorPaletteChanged(palette)), + expect: () => const [ + ComponentEditorState( + component: component, + savedComponent: component, + palette: palette, + ), + ], + verify: (bloc) => expect(bloc.state.hasChanges, isFalse), + ); + + group('component tree', () { + const child = RectangleComponent(name: 'rectangle1'); + const tree = RectangleComponent(name: 'Player', children: [child]); + const treeState = ComponentEditorState( + component: tree, + savedComponent: tree, + ); + + test('selects the root by default', () { + final state = buildBloc().state; + + expect(state.selectedPath, isEmpty); + expect(state.isRootSelected, isTrue); + expect(state.selectedNode, equals(component)); + }); + + blocTest( + 'ComponentEditorNodeSelected selects the node', + build: buildBloc, + seed: () => treeState, + act: (bloc) => bloc.add(const ComponentEditorNodeSelected([0])), + expect: () => [ + isA() + .having((s) => s.selectedPath, 'selectedPath', [0]) + .having((s) => s.selectedNode, 'selectedNode', child) + .having((s) => s.hasChanges, 'hasChanges', isFalse), + ], + ); + + blocTest( + 'ComponentEditorNodeSelected ignores paths that do not exist', + build: buildBloc, + seed: () => treeState, + act: (bloc) => bloc.add(const ComponentEditorNodeSelected([3])), + expect: () => const [], + ); + + blocTest( + 'ComponentEditorChildAdded adds no child to a hitbox', + build: buildBloc, + seed: () => const ComponentEditorState( + component: RectangleComponent( + name: 'Player', + children: [RectangleHitboxComponent(name: 'rectangleHitbox1')], + ), + savedComponent: tree, + selectedPath: [0], + ), + act: (bloc) => + bloc.add(const ComponentEditorChildAdded(ComponentType.rectangle)), + expect: () => const [], + ); + + blocTest( + 'ComponentEditorChildAdded adds a child to the selected node and ' + 'selects it', + build: buildBloc, + seed: () => treeState.copyWith(selectedPath: [0]), + act: (bloc) => + bloc.add(const ComponentEditorChildAdded(ComponentType.rectangle)), + expect: () => const [ + ComponentEditorState( + component: RectangleComponent( + name: 'Player', + children: [ + RectangleComponent( + name: 'rectangle1', + children: [RectangleComponent(name: 'rectangle2')], + ), + ], + ), + savedComponent: tree, + selectedPath: [0, 0], + ), + ], + ); + + blocTest( + 'ComponentEditorChildAdded adds polygons with the picked shape', + build: buildBloc, + act: (bloc) => bloc.add( + const ComponentEditorChildAdded( + ComponentType.polygon, + polygonShape: PolygonShape.square, + ), + ), + expect: () => [ + isA().having( + (s) => s.selectedNode, + 'selectedNode', + const PolygonComponent( + name: 'polygon1', + vertices: ComponentVertices(ComponentVertices.square), + ), + ), + ], + ); + + blocTest( + 'ComponentEditorChildAdded skips names whose class is taken', + build: buildBloc, + seed: () => const ComponentEditorState( + component: component, + savedComponent: component, + takenClassNames: { + r'$PlayerRectangle1': RectangleComponent(name: 'player_rectangle1'), + }, + ), + act: (bloc) => + bloc.add(const ComponentEditorChildAdded(ComponentType.rectangle)), + expect: () => [ + isA().having( + (s) => s.selectedNode.name, + 'selectedNode.name', + 'rectangle2', + ), + ], + ); + + blocTest( + 'ComponentEditorNodeRemoved removes the node and selects its parent', + build: buildBloc, + seed: () => treeState.copyWith(selectedPath: [0]), + act: (bloc) => bloc.add(const ComponentEditorNodeRemoved([0])), + expect: () => const [ + ComponentEditorState( + component: RectangleComponent(name: 'Player'), + savedComponent: tree, + ), + ], + ); + + blocTest( + 'ComponentEditorNodeRemoved never removes the root', + build: buildBloc, + seed: () => treeState, + act: (bloc) => bloc.add(const ComponentEditorNodeRemoved([])), + expect: () => const [], + ); + + blocTest( + 'property changes edit the selected node', + build: buildBloc, + seed: () => treeState.copyWith(selectedPath: [0]), + act: (bloc) => bloc + ..add(const ComponentEditorPositionChanged(ComponentPosition(x: 5))) + ..add(const ComponentEditorSizeChanged(size)) + ..add(const ComponentEditorPaintChanged(paint)), + skip: 2, + expect: () => const [ + ComponentEditorState( + component: RectangleComponent( + name: 'Player', + children: [ + RectangleComponent( + name: 'rectangle1', + position: ComponentPosition(x: 5), + size: size, + paint: paint, + ), + ], + ), + savedComponent: tree, + selectedPath: [0], + ), + ], + ); + + blocTest( + 'property changes that change nothing emit nothing', + build: buildBloc, + seed: () => treeState, + act: (bloc) => + bloc.add(const ComponentEditorSizeChanged(ComponentSize())), + expect: () => const [], + ); + }); + + group(ComponentEditorSaveRequested, () { + const playerHead = RectangleComponent(name: 'player_head'); + + setUp( + () => + when(() => componentRepository.getComponents(project.path)) + .thenAnswer((_) async => const [component]), + ); + + void stubSave() { + when(() => componentRepository.saveComponent(project.path, edited)) + .thenAnswer((_) async {}); + } + + void stubCode(Future Function(Invocation) answer) { + when( + () => componentRepository.writeComponentCode( + project.path, + 'lib/game', + edited, + ), + ).thenAnswer(answer); + } + + blocTest( + 'saves the component, generates its code and clears the changes', + setUp: () { + stubSave(); + stubCode((_) async {}); + }, + build: buildBloc, + seed: () => const ComponentEditorState( + component: edited, + savedComponent: component, + ), + act: (bloc) => bloc.add(const ComponentEditorSaveRequested()), + expect: () => const [ + ComponentEditorState( + status: ComponentEditorStatus.saving, + component: edited, + savedComponent: component, + ), + ComponentEditorState( + status: ComponentEditorStatus.saved, + component: edited, + savedComponent: edited, + ), + ], + verify: (_) { + verify(() => componentRepository.saveComponent(project.path, edited)) + .called(1); + verify( + () => componentRepository.writeComponentCode( + project.path, + 'lib/game', + edited, + ), + ).called(1); + }, + ); + + for (final (exception, status) in [ + ( + const GeneratedFileConflictException('/projects/my_game/x.dart'), + ComponentEditorStatus.codeConflict, + ), + (Exception(), ComponentEditorStatus.codeFailure), + ]) { + blocTest( + 'emits $status, with the changes saved, when generating the code ' + 'throws ${exception.runtimeType}', + setUp: () { + stubSave(); + stubCode((_) async => throw exception); + }, + build: buildBloc, + seed: () => const ComponentEditorState( + component: edited, + savedComponent: component, + ), + act: (bloc) => bloc.add(const ComponentEditorSaveRequested()), + expect: () => [ + const ComponentEditorState( + status: ComponentEditorStatus.saving, + component: edited, + savedComponent: component, + ), + ComponentEditorState( + status: status, + component: edited, + savedComponent: edited, + isCodeOutdated: true, + ), + ], + ); + } + + blocTest( + 'emits classConflict, and saves nothing, when another component ' + 'generates one of its classes', + setUp: () => + when(() => componentRepository.getComponents(project.path)) + .thenAnswer((_) async => const [component, playerHead]), + build: buildBloc, + // The other components were not loaded when the child was named. + seed: () => const ComponentEditorState( + component: RectangleComponent( + name: 'Player', + children: [RectangleComponent(name: 'head')], + ), + savedComponent: component, + ), + act: (bloc) => bloc.add(const ComponentEditorSaveRequested()), + skip: 1, + expect: () => [ + isA() + .having( + (s) => s.status, + 'status', + ComponentEditorStatus.classConflict, + ) + .having((s) => s.hasChanges, 'hasChanges', isTrue) + .having((s) => s.canSave, 'canSave', isTrue) + .having((s) => s.conflictingClassNames, 'conflictingClassNames', { + r'$PlayerHead': playerHead, + }) + .having((s) => s.rootClassOwner, 'rootClassOwner', isNull), + ], + verify: (_) { + verifyNever(() => componentRepository.saveComponent(any(), any())); + verifyNever( + () => componentRepository.writeComponentCode(any(), any(), any()), + ); + }, + ); + + blocTest( + 'emits failure when the other components cannot be loaded', + setUp: () => + when(() => componentRepository.getComponents(project.path)) + .thenThrow(Exception()), + build: buildBloc, + seed: () => const ComponentEditorState( + component: edited, + savedComponent: component, + ), + act: (bloc) => bloc.add(const ComponentEditorSaveRequested()), + skip: 1, + expect: () => const [ + ComponentEditorState( + status: ComponentEditorStatus.failure, + component: edited, + savedComponent: component, + ), + ], + verify: (_) => + verifyNever(() => componentRepository.saveComponent(any(), any())), + ); + + blocTest( + 'edits made while saving keep saving, so no other save starts', + setUp: () { + stubSave(); + stubCode((_) async {}); + }, + build: buildBloc, + seed: () => const ComponentEditorState( + component: edited, + savedComponent: component, + ), + act: (bloc) => bloc + ..add(const ComponentEditorSaveRequested()) + ..add(const ComponentEditorPaintChanged(paint)) + ..add(const ComponentEditorSaveRequested()), + wait: Duration.zero, + verify: (bloc) { + verify(() => componentRepository.saveComponent(project.path, any())) + .called(1); + expect(bloc.state.status, ComponentEditorStatus.saved); + expect(bloc.state.hasChanges, isTrue); + }, + ); + + test('goes back to ready when the clashing child is renamed while ' + 'loading', () async { + final components = Completer>(); + when(() => componentRepository.getComponents(project.path)) + .thenAnswer((_) => components.future); + const tree = RectangleComponent( + name: 'Player', + children: [RectangleComponent(name: 'head')], + ); + final bloc = buildBloc() + ..emit( + const ComponentEditorState( + component: tree, + savedComponent: component, + selectedPath: [0], + ), + ) + ..add(const ComponentEditorSaveRequested()); + await Future.delayed(Duration.zero); + bloc.add(const ComponentEditorNameChanged('eye')); + await Future.delayed(Duration.zero); + components.complete(const [playerHead]); + await Future.delayed(Duration.zero); + + expect(bloc.state.status, ComponentEditorStatus.ready); + expect(bloc.state.selectedNode.name, 'eye'); + verifyNever(() => componentRepository.saveComponent(any(), any())); + await bloc.close(); + }); + + blocTest( + 'keeps edits made while saving', + setUp: () { + stubSave(); + stubCode((_) async {}); + }, + build: buildBloc, + seed: () => const ComponentEditorState( + component: edited, + savedComponent: component, + ), + act: (bloc) => bloc + ..add(const ComponentEditorSaveRequested()) + ..add(const ComponentEditorPaintChanged(paint)), + wait: Duration.zero, + skip: 2, + expect: () => [ + isA() + .having((s) => s.status, 'status', ComponentEditorStatus.saved) + .having((s) => s.savedComponent, 'savedComponent', edited) + .having( + (s) => s.component, + 'component', + const RectangleComponent( + name: 'Player', + size: size, + paint: paint, + ), + ) + .having((s) => s.hasChanges, 'hasChanges', isTrue), + ], + ); + + blocTest( + 'emits failure when saving fails', + setUp: () => + when(() => componentRepository.saveComponent(project.path, edited)) + .thenThrow(Exception()), + build: buildBloc, + seed: () => const ComponentEditorState( + component: edited, + savedComponent: component, + ), + act: (bloc) => bloc.add(const ComponentEditorSaveRequested()), + expect: () => const [ + ComponentEditorState( + status: ComponentEditorStatus.saving, + component: edited, + savedComponent: component, + ), + ComponentEditorState( + status: ComponentEditorStatus.failure, + component: edited, + savedComponent: component, + ), + ], + ); + + blocTest( + 'saves again without changes to generate outdated code', + setUp: () { + stubSave(); + stubCode((_) async {}); + }, + build: buildBloc, + seed: () => const ComponentEditorState( + status: ComponentEditorStatus.classConflict, + component: edited, + savedComponent: edited, + isCodeOutdated: true, + ), + act: (bloc) => bloc.add(const ComponentEditorSaveRequested()), + skip: 1, + expect: () => const [ + ComponentEditorState( + status: ComponentEditorStatus.saved, + component: edited, + savedComponent: edited, + ), + ], + verify: (_) => verify( + () => componentRepository.writeComponentCode( + project.path, + 'lib/game', + edited, + ), + ).called(1), + ); + + blocTest( + 'does nothing while saving', + build: buildBloc, + seed: () => const ComponentEditorState( + status: ComponentEditorStatus.saving, + component: edited, + savedComponent: component, + ), + act: (bloc) => bloc.add(const ComponentEditorSaveRequested()), + expect: () => const [], + ); + + blocTest( + 'does nothing without changes', + build: buildBloc, + act: (bloc) => bloc.add(const ComponentEditorSaveRequested()), + expect: () => const [], + verify: (_) => + verifyNever(() => componentRepository.saveComponent(any(), any())), + ); + }); + + group(ComponentEditorNameChanged, () { + const named = RectangleComponent( + name: 'Player', + children: [ + RectangleComponent(name: 'rectangle1'), + RectangleComponent(name: 'rectangle2'), + ], + ); + + blocTest( + 'renames the selected child', + build: buildBloc, + seed: () => const ComponentEditorState( + component: named, + savedComponent: named, + selectedPath: [1], + ), + act: (bloc) => bloc.add(const ComponentEditorNameChanged('head')), + expect: () => [ + isA().having( + (s) => s.component.nodeAt(const [1]).name, + 'name', + 'head', + ), + ], + ); + + for (final name in ['rectangle1', 'size', '1head']) { + blocTest( + 'ignores the rejected name "$name"', + build: buildBloc, + seed: () => const ComponentEditorState( + component: named, + savedComponent: named, + selectedPath: [1], + ), + act: (bloc) => bloc.add(ComponentEditorNameChanged(name)), + expect: () => const [], + ); + } + + blocTest( + 'ignores a name whose class another component generates', + build: buildBloc, + seed: () => const ComponentEditorState( + component: named, + savedComponent: named, + selectedPath: [1], + takenClassNames: { + r'$PlayerHead': RectangleComponent(name: 'player_head'), + }, + ), + act: (bloc) => bloc.add(const ComponentEditorNameChanged('head')), + expect: () => const [], + ); + + blocTest( + 'does not rename the root', + build: buildBloc, + seed: () => + const ComponentEditorState(component: named, savedComponent: named), + act: (bloc) => bloc.add(const ComponentEditorNameChanged('Enemy')), + expect: () => const [], + ); + }); + }); +} diff --git a/packages/flame_studio/test/component_editor/view/component_editor_page_test.dart b/packages/flame_studio/test/component_editor/view/component_editor_page_test.dart new file mode 100644 index 00000000000..4138f0aec59 --- /dev/null +++ b/packages/flame_studio/test/component_editor/view/component_editor_page_test.dart @@ -0,0 +1,1138 @@ +import 'dart:async'; + +import 'package:bloc_test/bloc_test.dart'; +import 'package:flame/game.dart'; +import 'package:flame_studio/component_editor/component_editor.dart'; +import 'package:flame_studio/component_editor/widgets/widgets.dart'; +import 'package:flame_studio/palette/palette.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +import '../../helpers/helpers.dart'; + +class _MockComponentRepository() extends Mock implements ComponentRepository; + +class _MockProjectRepository() extends Mock implements ProjectRepository; + +class _MockComponentEditorBloc() + extends MockBloc + implements ComponentEditorBloc; + +void main() { + const project = Project(path: '/projects/my_game'); + const component = RectangleComponent(name: 'Player'); + const edited = RectangleComponent( + name: 'Player', + size: ComponentSize(width: 10), + ); + + setUpAll(() => registerFallbackValue(const ComponentEditorSaveRequested())); + + group(ComponentEditorPage, () { + testWidgets('route shows the editor for the component', (tester) async { + final componentRepository = _MockComponentRepository(); + final projectRepository = _MockProjectRepository(); + when(() => componentRepository.getComponents(project.path)) + .thenAnswer((_) async => const [component]); + when(() => componentRepository.getPalette(project.path)) + .thenAnswer((_) async => const Palette()); + when(() => projectRepository.getSettings(project)) + .thenAnswer((_) async => const ProjectSettings()); + when( + () => componentRepository.isComponentCodeUpToDate( + project.path, + const ProjectSettings().outputPath, + component, + ), + ).thenAnswer((_) async => true); + await tester.pumpApp( + componentRepository: componentRepository, + projectRepository: projectRepository, + Builder( + builder: (context) => TextButton( + onPressed: () => + Navigator.of(context) + .push(ComponentEditorPage.route(project, component)), + child: const Text('open'), + ), + ), + ); + + await tester.tap(find.text('open')); + await tester.pumpRouteTransition(); + + expect(find.byType(ComponentEditorView), findsOneWidget); + expect(find.widgetWithText(AppBar, 'Player'), findsOneWidget); + verify(() => componentRepository.getComponents(project.path)).called(1); + }); + }); + + group(ComponentEditorView, () { + late ComponentEditorBloc bloc; + + setUp(() { + bloc = _MockComponentEditorBloc(); + when(() => bloc.state).thenReturn( + const ComponentEditorState( + component: component, + savedComponent: component, + ), + ); + }); + + Widget buildSubject() => BlocProvider.value( + value: bloc, + child: const ComponentEditorView(project: project), + ); + + testWidgets('shows the preview and the property editors', (tester) async { + await tester.pumpApp(buildSubject()); + + expect(find.byType(ComponentPreview), findsOneWidget); + expect(find.byType(GameWidget), findsOneWidget); + expect(find.byType(SizeEditor), findsOneWidget); + expect(find.byType(PaintEditor), findsOneWidget); + }); + + group('highlight toggle', () { + IconButton toggle(WidgetTester tester) => tester.widget( + find.ancestor( + of: find.byIcon(Icons.highlight_alt), + matching: find.byType(IconButton), + ), + ); + + testWidgets('is selected while highlighting', (tester) async { + await tester.pumpApp(buildSubject()); + + expect(toggle(tester).isSelected, isTrue); + }); + + testWidgets('is not selected while not highlighting', (tester) async { + when(() => bloc.state).thenReturn( + const ComponentEditorState( + component: component, + savedComponent: component, + isSelectionHighlighted: false, + ), + ); + await tester.pumpApp(buildSubject()); + + expect(toggle(tester).isSelected, isFalse); + }); + + testWidgets('is filled only when selected', (tester) async { + await tester.pumpApp(buildSubject()); + final colorScheme = Theme.of(tester.element(find.byType(EditorToolbar))) + .colorScheme; + final background = toggle(tester).style!.backgroundColor!; + + expect( + background.resolve({WidgetState.selected}), + equals(colorScheme.primaryContainer), + ); + expect(background.resolve({}), isNull); + }); + }); + + testWidgets('toolbar sits above the preview only', (tester) async { + await tester.pumpApp(buildSubject()); + + final toolbar = tester.getRect(find.byType(EditorToolbar)); + final preview = tester.getRect(find.byType(ComponentPreview)); + expect(toolbar.left, equals(preview.left)); + expect(toolbar.width, equals(preview.width)); + expect(toolbar.bottom, lessThanOrEqualTo(preview.top)); + }); + + testWidgets('top bar sits above the panels', (tester) async { + await tester.pumpApp(buildSubject()); + + final topBar = tester.getRect(find.byType(EditorTopBar)); + final tree = tester.getRect(find.byType(ComponentTreePanel)); + final properties = tester.getRect(find.byType(PropertiesPanel)); + expect(topBar.left, equals(tree.left)); + expect(topBar.right, equals(properties.right)); + expect(topBar.bottom, lessThanOrEqualTo(tree.top)); + }); + + testWidgets('top bar opens the palette and passes on the saved palette', ( + tester, + ) async { + const palette = Palette( + colors: [PaletteColor(name: 'color1', color: 0xFFFFFFFF)], + ); + final componentRepository = _MockComponentRepository(); + final projectRepository = _MockProjectRepository(); + when(() => componentRepository.getPalette(project.path)) + .thenAnswer((_) async => const Palette()); + when(() => componentRepository.getComponents(project.path)) + .thenAnswer((_) async => const [component]); + when(() => componentRepository.savePalette(project.path, palette)) + .thenAnswer((_) async {}); + when(() => projectRepository.getSettings(project)) + .thenAnswer((_) async => const ProjectSettings()); + when( + () => componentRepository.writePaletteCode( + project.path, + const ProjectSettings().outputPath, + palette, + ), + ).thenAnswer((_) async {}); + await tester.pumpApp( + buildSubject(), + componentRepository: componentRepository, + projectRepository: projectRepository, + ); + + await tester.tap(find.byTooltip('Palette')); + await tester.pumpRouteTransition(); + expect(find.byType(PaletteView), findsOneWidget); + + await tester.tap(find.text('Add color')); + await tester.pump(); + await tester.tap(find.text('Save')); + await tester.pumpRouteTransition(); + + expect(find.byType(PaletteView), findsNothing); + verify(() => bloc.add(const ComponentEditorPaletteChanged(palette))) + .called(1); + }); + + testWidgets('dispatches highlight toggles', (tester) async { + await tester.pumpApp(buildSubject()); + + await tester.tap(find.byTooltip('Highlight selection')); + + verify(() => bloc.add(const ComponentEditorSelectionHighlightToggled())) + .called(1); + }); + + group('hitboxes toggle', () { + IconButton toggle(WidgetTester tester) => tester.widget( + find.ancestor( + of: find.byIcon(Icons.border_style), + matching: find.byType(IconButton), + ), + ); + + testWidgets('is selected while the hitboxes are shown', (tester) async { + await tester.pumpApp(buildSubject()); + + expect(toggle(tester).isSelected, isTrue); + }); + + testWidgets('dispatches hitboxes toggles', (tester) async { + await tester.pumpApp(buildSubject()); + + await tester.tap(find.byTooltip('Show hitboxes')); + + verify(() => bloc.add(const ComponentEditorHitboxesVisibilityToggled())) + .called(1); + }); + + testWidgets('preview outlines the hitboxes while shown', (tester) async { + const withHitbox = PositionComponent( + name: 'Player', + children: [RectangleHitboxComponent(name: 'rectangleHitbox1')], + ); + const state = ComponentEditorState( + component: withHitbox, + savedComponent: withHitbox, + ); + final states = StreamController(); + whenListen(bloc, states.stream, initialState: state); + await tester.pumpApp(buildSubject()); + await tester.pump(); + final game = tester + .widget>( + find.byType(GameWidget), + ) + .game!; + PreviewHitbox hitbox() => + game.preview.children.whereType().single; + expect(hitbox().isVisible, isTrue); + + states.add(state.copyWith(areHitboxesVisible: false)); + await tester.pump(); + + expect(game.areHitboxesVisible, isFalse); + expect(hitbox().isVisible, isFalse); + await states.close(); + }); + }); + + testWidgets('preview highlights the selection while enabled', ( + tester, + ) async { + const state = ComponentEditorState( + component: component, + savedComponent: component, + ); + final states = StreamController(); + whenListen(bloc, states.stream, initialState: state); + await tester.pumpApp(buildSubject()); + await tester.pump(); + final game = tester + .widget>( + find.byType(GameWidget), + ) + .game!; + expect(game.highlight.target, same(game.preview)); + + states.add(state.copyWith(isSelectionHighlighted: false)); + await tester.pump(); + + expect(game.highlight.target, isNull); + await states.close(); + }); + + group('zoom', () { + testWidgets('dispatches zooms from the toolbar', (tester) async { + await tester.pumpApp(buildSubject()); + + await tester.tap(find.byTooltip('Zoom in')); + await tester.tap(find.byTooltip('Zoom out')); + await tester.tap(find.text('100%')); + + verify(() => bloc.add(const ComponentEditorZoomedIn())).called(1); + verify(() => bloc.add(const ComponentEditorZoomedOut())).called(1); + verify(() => bloc.add(const ComponentEditorZoomReset())).called(1); + }); + + testWidgets('shows the zoom and disables zooming past the limits', ( + tester, + ) async { + when(() => bloc.state).thenReturn( + const ComponentEditorState( + component: component, + savedComponent: component, + zoom: 8, + ), + ); + await tester.pumpApp(buildSubject()); + + expect(find.text('800%'), findsOneWidget); + IconButton button(String tooltip) => tester.widget( + find.ancestor( + of: find.byTooltip(tooltip), + matching: find.byType(IconButton), + ), + ); + expect(button('Zoom in').onPressed, isNull); + expect(button('Zoom out').onPressed, isNotNull); + }); + + for (final (control, key, event) in [ + ( + LogicalKeyboardKey.metaLeft, + LogicalKeyboardKey.equal, + const ComponentEditorZoomedIn(), + ), + ( + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.minus, + const ComponentEditorZoomedOut(), + ), + ( + LogicalKeyboardKey.metaLeft, + LogicalKeyboardKey.digit0, + const ComponentEditorZoomReset(), + ), + ]) { + testWidgets('dispatches $event with ${control.keyLabel}+' + '${key.keyLabel}', (tester) async { + await tester.pumpApp(buildSubject()); + await tester.pump(); + + await tester.sendKeyDownEvent(control); + await tester.sendKeyEvent(key); + await tester.sendKeyUpEvent(control); + + verify(() => bloc.add(event)).called(1); + }); + } + + testWidgets('zooms the preview', (tester) async { + const state = ComponentEditorState( + component: component, + savedComponent: component, + zoom: 2, + ); + final states = StreamController(); + whenListen(bloc, states.stream, initialState: state); + await tester.pumpApp(buildSubject()); + await tester.pump(); + final game = tester + .widget>( + find.byType(GameWidget), + ) + .game!; + expect(game.camera.viewfinder.zoom, 2); + + states.add(state.copyWith(zoom: 0.5)); + await tester.pump(); + + expect(game.camera.viewfinder.zoom, 0.5); + await states.close(); + }); + }); + + testWidgets('dispatches size changes', (tester) async { + await tester.pumpApp(buildSubject()); + + await tester.enterText(find.widgetWithText(TextField, 'Width'), '10'); + await tester.testTextInput.receiveAction(TextInputAction.done); + + verify( + () => bloc.add( + const ComponentEditorSizeChanged(ComponentSize(width: 10)), + ), + ).called(1); + }); + + testWidgets('edits the vertices of polygons', (tester) async { + const polygon = PolygonComponent(name: 'Player'); + when(() => bloc.state).thenReturn( + const ComponentEditorState(component: polygon, savedComponent: polygon), + ); + await tester.pumpApp(buildSubject()); + + expect(find.byType(SizeEditor), findsNothing); + expect(find.byType(VerticesEditor), findsOneWidget); + expect(find.byType(PaintEditor), findsOneWidget); + }); + + testWidgets('edits the radius of circles', (tester) async { + const circle = CircleComponent(name: 'Player'); + when(() => bloc.state).thenReturn( + const ComponentEditorState(component: circle, savedComponent: circle), + ); + await tester.pumpApp(buildSubject()); + + expect(find.byType(SizeEditor), findsNothing); + expect(find.byType(PaintEditor), findsOneWidget); + await tester.enterText(find.widgetWithText(TextField, 'Radius'), '10'); + await tester.testTextInput.receiveAction(TextInputAction.done); + + verify( + () => bloc.add( + const ComponentEditorRadiusChanged(ComponentRadius(radius: 10)), + ), + ).called(1); + }); + + testWidgets('dispatches paint changes', (tester) async { + await tester.pumpApp(buildSubject()); + + await tester.tap(find.text('Stroke')); + + verify( + () => bloc.add( + const ComponentEditorPaintChanged( + ComponentPaint(style: PaintStyle.stroke), + ), + ), + ).called(1); + }); + + group('component tree', () { + const child = RectangleComponent( + name: 'rectangle1', + position: ComponentPosition(x: 5, y: 6), + ); + const tree = RectangleComponent(name: 'Player', children: [child]); + + void stubTree({List selectedPath = const []}) { + when(() => bloc.state).thenReturn( + ComponentEditorState( + component: tree, + savedComponent: tree, + selectedPath: selectedPath, + takenClassNames: const { + r'$PlayerEye': RectangleComponent(name: 'player_eye'), + }, + ), + ); + } + + testWidgets('lists the root and its children', (tester) async { + stubTree(); + await tester.pumpApp(buildSubject()); + + final panel = find.byType(ComponentTreePanel); + expect(panel, findsOneWidget); + expect( + find.descendant(of: panel, matching: find.text('Player')), + findsOneWidget, + ); + expect( + find.descendant(of: panel, matching: find.text('rectangle1')), + findsOneWidget, + ); + final root = tester.widget( + find.widgetWithText(ListTile, 'Player'), + ); + expect(root.selected, isTrue); + }); + + testWidgets('selects a node when tapped', (tester) async { + stubTree(); + await tester.pumpApp(buildSubject()); + + await tester.tap(find.text('rectangle1')); + + verify(() => bloc.add(const ComponentEditorNodeSelected([0]))) + .called(1); + }); + + testWidgets('adds a child of the picked type', (tester) async { + stubTree(); + await tester.pumpApp(buildSubject()); + + await tester.tap(find.byTooltip('Add child')); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + await tester.tap(find.text('Rectangle')); + + verify( + () => bloc.add( + const ComponentEditorChildAdded(ComponentType.rectangle), + ), + ).called(1); + }); + + testWidgets('adds polygons with the picked shape', (tester) async { + stubTree(); + await tester.pumpApp(buildSubject()); + + await tester.tap(find.byTooltip('Add child')); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(find.text('Polygon (triangle)'), findsOneWidget); + await tester.tap(find.text('Polygon (square)')); + + verify( + () => bloc.add( + const ComponentEditorChildAdded( + ComponentType.polygon, + polygonShape: PolygonShape.square, + ), + ), + ).called(1); + }); + + testWidgets('adds hitboxes, with the picked shape for polygons', ( + tester, + ) async { + stubTree(); + await tester.pumpApp(buildSubject()); + + await tester.tap(find.byTooltip('Add child')); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(find.text('Rectangle hitbox'), findsOneWidget); + expect(find.text('Circle hitbox'), findsOneWidget); + expect(find.text('Polygon hitbox (triangle)'), findsOneWidget); + await tester.tap(find.text('Polygon hitbox (square)')); + + verify( + () => bloc.add( + const ComponentEditorChildAdded( + ComponentType.polygonHitbox, + polygonShape: PolygonShape.square, + ), + ), + ).called(1); + }); + + testWidgets('edits the collision of a hitbox, which has no paint and ' + 'no children', (tester) async { + const withHitbox = PositionComponent( + name: 'Player', + children: [CircleHitboxComponent(name: 'circleHitbox1')], + ); + when(() => bloc.state).thenReturn( + const ComponentEditorState( + component: withHitbox, + savedComponent: withHitbox, + selectedPath: [0], + ), + ); + await tester.pumpApp(buildSubject()); + + expect( + tester + .widget>( + find.byType(PopupMenuButton), + ) + .enabled, + isFalse, + ); + + await tester.scrollUntilVisible( + find.byType(CollisionEditor), + 100, + scrollable: find + .descendant( + of: find.byType(PropertiesPanel), + matching: find.byType(Scrollable), + ) + .first, + ); + expect(find.byType(RadiusEditor), findsOneWidget); + expect(find.byType(PaintEditor), findsNothing); + tester + .widget(find.byType(CollisionEditor)) + .onChanged(const ComponentCollision(isSolid: true)); + + verify( + () => bloc.add( + const ComponentEditorCollisionChanged( + ComponentCollision(isSolid: true), + ), + ), + ).called(1); + }); + + testWidgets('cannot remove the root', (tester) async { + stubTree(); + await tester.pumpApp(buildSubject()); + + final remove = tester.widget( + find.widgetWithIcon(IconButton, Icons.delete_outline), + ); + expect(remove.onPressed, isNull); + }); + + testWidgets('removes the selected child', (tester) async { + stubTree(selectedPath: [0]); + await tester.pumpApp(buildSubject()); + + await tester.tap(find.byTooltip('Remove')); + + verify(() => bloc.add(const ComponentEditorNodeRemoved([0]))).called(1); + }); + + testWidgets('hides the position, the anchor and the angle of the root', ( + tester, + ) async { + stubTree(); + await tester.pumpApp(buildSubject()); + + expect(find.byType(PositionEditor), findsNothing); + expect(find.byType(AnchorEditor), findsNothing); + expect(find.byType(AngleEditor), findsNothing); + expect(find.byType(SizeEditor), findsOneWidget); + }); + + testWidgets('hides the name of the root', (tester) async { + stubTree(); + await tester.pumpApp(buildSubject()); + + expect(find.byType(NameField), findsNothing); + }); + + testWidgets('renames a selected child', (tester) async { + stubTree(selectedPath: [0]); + await tester.pumpApp(buildSubject()); + + final field = find.byType(NameField); + expect( + find.descendant(of: field, matching: find.text('rectangle1')), + findsOneWidget, + ); + + await tester.enterText(field, 'head'); + + verify(() => bloc.add(const ComponentEditorNameChanged('head'))) + .called(1); + }); + + for (final (name, message) in [ + ('1head', 'Use a valid Dart identifier'), + ('size', 'Already a member of the parent component in Flame'), + ('Player', 'Another component already uses this name'), + ('eye', 'Generates the same class as a part of another component'), + ]) { + testWidgets('rejects the child name "$name"', (tester) async { + stubTree(selectedPath: [0]); + await tester.pumpApp(buildSubject()); + + await tester.enterText(find.byType(NameField), name); + await tester.pump(); + + expect(find.textContaining(message), findsOneWidget); + verifyNever(() => bloc.add(ComponentEditorNameChanged(name))); + }); + } + + testWidgets('edits the position of a selected child', (tester) async { + stubTree(selectedPath: [0]); + await tester.pumpApp(buildSubject()); + + expect(find.byType(PositionEditor), findsOneWidget); + expect(find.widgetWithText(TextField, '5'), findsOneWidget); + + await tester.enterText( + find.descendant( + of: find.byType(PositionEditor), + matching: find.widgetWithText(TextField, 'X'), + ), + '-10', + ); + await tester.testTextInput.receiveAction(TextInputAction.done); + + verify( + () => bloc.add( + const ComponentEditorPositionChanged( + ComponentPosition(x: -10, y: 6), + ), + ), + ).called(1); + }); + + testWidgets('edits the anchor of a selected child', (tester) async { + stubTree(selectedPath: [0]); + await tester.pumpApp(buildSubject()); + + await tester.tap(find.byTooltip('center')); + + verify( + () => bloc.add( + const ComponentEditorAnchorChanged(ComponentAnchor.center), + ), + ).called(1); + }); + + testWidgets('edits the angle of a selected child', (tester) async { + stubTree(selectedPath: [0]); + await tester.pumpApp(buildSubject()); + + await tester.enterText( + find.widgetWithText(TextField, 'Degrees'), + '180', + ); + await tester.testTextInput.receiveAction(TextInputAction.done); + + verify( + () => bloc.add( + ComponentEditorAngleChanged(ComponentAngle.fromDegrees(180)), + ), + ).called(1); + }); + }); + + testWidgets('disables save without changes', (tester) async { + await tester.pumpApp(buildSubject()); + + final save = tester.widget( + find.widgetWithIcon(IconButton, Icons.save_outlined), + ); + expect(save.onPressed, isNull); + expect(find.widgetWithText(AppBar, 'Player'), findsOneWidget); + }); + + testWidgets('saves without changes when the code is outdated', ( + tester, + ) async { + when(() => bloc.state).thenReturn( + const ComponentEditorState( + status: ComponentEditorStatus.classConflict, + component: component, + savedComponent: component, + isCodeOutdated: true, + ), + ); + await tester.pumpApp(buildSubject()); + + expect(find.text('Player •'), findsNothing); + await tester.tap(find.byTooltip('Save')); + + verify(() => bloc.add(const ComponentEditorSaveRequested())).called(1); + }); + + group('with changes', () { + setUp(() { + when(() => bloc.state).thenReturn( + const ComponentEditorState( + component: edited, + savedComponent: component, + ), + ); + }); + + testWidgets('marks the title', (tester) async { + await tester.pumpApp(buildSubject()); + + expect(find.text('Player •'), findsOneWidget); + }); + + testWidgets('saves with the save button', (tester) async { + await tester.pumpApp(buildSubject()); + + await tester.tap(find.byTooltip('Save')); + + verify(() => bloc.add(const ComponentEditorSaveRequested())).called(1); + }); + + testWidgets('saves with the keyboard shortcut', (tester) async { + await tester.pumpApp(buildSubject()); + await tester.pump(); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyS); + await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); + + verify(() => bloc.add(const ComponentEditorSaveRequested())).called(1); + }); + }); + + testWidgets('shows a message when saving fails', (tester) async { + whenListen( + bloc, + Stream.value( + const ComponentEditorState( + status: ComponentEditorStatus.failure, + component: edited, + savedComponent: component, + ), + ), + initialState: const ComponentEditorState( + component: edited, + savedComponent: component, + ), + ); + + await tester.pumpApp(buildSubject()); + await tester.pump(); + + expect(find.text('Could not save the component'), findsOneWidget); + }); + + const playerHead = RectangleComponent(name: 'player_head'); + const playerRoot = RectangleComponent(name: 'player_'); + const owner = RectangleComponent( + name: 'pla', + children: [RectangleComponent(name: 'yer')], + ); + for (final (description, takenClassNames, messages) in [ + ( + 'children', + { + r'$PlayerHead': playerHead, + r'$Enemy': const RectangleComponent(name: 'Enemy'), + }, + [ + r'Rename the children that generate $PlayerHead', + r'$PlayerHead (also generated by "player_head").', + ], + ), + ( + 'the root, with another root', + {r'$Player': playerRoot}, + [ + r'"player_" generates the same class, $Player', + 'delete one of the two components.', + ], + ), + ( + 'the root, with a child of another component', + {r'$Player': owner}, + [r'A child of "pla" generates $Player', 'rename that child.'], + ), + ( + 'the root and children', + {r'$Player': playerRoot, r'$PlayerHead': playerHead}, + [ + 'delete one of the two components', + r'Rename the children that generate $PlayerHead', + ], + ), + ]) { + testWidgets('tells how to fix a classConflict of $description', ( + tester, + ) async { + const tree = RectangleComponent( + name: 'Player', + children: [RectangleComponent(name: 'head')], + ); + whenListen( + bloc, + Stream.value( + ComponentEditorState( + status: ComponentEditorStatus.classConflict, + component: tree, + savedComponent: tree, + takenClassNames: takenClassNames, + ), + ), + initialState: const ComponentEditorState( + component: tree, + savedComponent: component, + ), + ); + + await tester.pumpApp(buildSubject()); + await tester.pump(); + + for (final message in messages) { + expect(find.textContaining(message), findsOneWidget); + } + if (takenClassNames.containsKey(r'$PlayerHead')) { + return; + } + expect(find.textContaining('Rename the children'), findsNothing); + }); + } + + for (final (status, message) in [ + (ComponentEditorStatus.codeConflict, 'a file that was not generated'), + (ComponentEditorStatus.codeFailure, 'the code could not be generated'), + ]) { + testWidgets('shows a message for $status', (tester) async { + whenListen( + bloc, + Stream.value( + ComponentEditorState( + status: status, + component: edited, + savedComponent: edited, + ), + ), + initialState: const ComponentEditorState( + component: edited, + savedComponent: component, + ), + ); + + await tester.pumpApp(buildSubject()); + await tester.pump(); + + expect(find.textContaining(message), findsOneWidget); + }); + } + }); + + group('leaving the editor', () { + const unsaved = ComponentEditorState( + component: edited, + savedComponent: component, + ); + + late ComponentEditorBloc bloc; + late StreamController states; + + setUp(() { + bloc = _MockComponentEditorBloc(); + states = StreamController.broadcast(); + whenListen(bloc, states.stream, initialState: unsaved); + when(() => bloc.isClosed).thenReturn(false); + }); + + tearDown(() => states.close()); + + Future openEditor(WidgetTester tester) async { + await tester.pumpApp( + Builder( + builder: (context) => TextButton( + onPressed: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => BlocProvider.value( + value: bloc, + child: const ComponentEditorView(project: project), + ), + ), + ), + child: const Text('open'), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pumpRouteTransition(); + } + + Future leave(WidgetTester tester) async { + await tester.pageBack(); + await tester.pumpRouteTransition(); + } + + testWidgets('leaves directly without changes', (tester) async { + whenListen( + bloc, + const Stream.empty(), + initialState: const ComponentEditorState( + component: component, + savedComponent: component, + ), + ); + await openEditor(tester); + + await leave(tester); + + expect(find.byType(UnsavedChangesDialog), findsNothing); + expect(find.byType(ComponentEditorView), findsNothing); + }); + + testWidgets('asks before leaving with changes', (tester) async { + await openEditor(tester); + + await leave(tester); + + expect(find.byType(UnsavedChangesDialog), findsOneWidget); + }); + + testWidgets('stays when cancelled', (tester) async { + await openEditor(tester); + await leave(tester); + + await tester.tap(find.text('Cancel')); + await tester.pumpRouteTransition(); + + expect(find.byType(UnsavedChangesDialog), findsNothing); + expect(find.byType(ComponentEditorView), findsOneWidget); + }); + + testWidgets('leaves without saving when discarded', (tester) async { + await openEditor(tester); + await leave(tester); + + await tester.tap(find.text('Discard')); + await tester.pumpRouteTransition(); + + expect(find.byType(ComponentEditorView), findsNothing); + verifyNever(() => bloc.add(any())); + }); + + testWidgets('saves and leaves when saving succeeds', (tester) async { + await openEditor(tester); + await leave(tester); + + await tester.tap(find.text('Save')); + await tester.pump(); + verify(() => bloc.add(const ComponentEditorSaveRequested())).called(1); + + states.add( + const ComponentEditorState( + status: ComponentEditorStatus.saved, + component: edited, + savedComponent: edited, + ), + ); + await tester.pumpRouteTransition(); + + expect(find.byType(ComponentEditorView), findsNothing); + }); + + testWidgets('leaves when saved without generating the code', ( + tester, + ) async { + await openEditor(tester); + await leave(tester); + + await tester.tap(find.text('Save')); + await tester.pump(); + states.add( + const ComponentEditorState( + status: ComponentEditorStatus.codeFailure, + component: edited, + savedComponent: edited, + ), + ); + await tester.pumpRouteTransition(); + + expect(find.byType(ComponentEditorView), findsNothing); + }); + + testWidgets('leaves when a save finished while asking', (tester) async { + await openEditor(tester); + await leave(tester); + + states.add( + const ComponentEditorState( + status: ComponentEditorStatus.saved, + component: edited, + savedComponent: edited, + ), + ); + await tester.pump(); + await tester.tap(find.text('Save')); + await tester.pumpRouteTransition(); + + expect(find.byType(ComponentEditorView), findsNothing); + verifyNever(() => bloc.add(const ComponentEditorSaveRequested())); + }); + + testWidgets('stays when the clash was fixed while saving', (tester) async { + await openEditor(tester); + await leave(tester); + + await tester.tap(find.text('Save')); + await tester.pump(); + states + ..add(unsaved.copyWith(status: ComponentEditorStatus.saving)) + ..add(unsaved.copyWith(status: ComponentEditorStatus.ready)); + await tester.pumpRouteTransition(); + + expect(find.byType(ComponentEditorView), findsOneWidget); + }); + + testWidgets('stays when edited while saving', (tester) async { + await openEditor(tester); + await leave(tester); + + await tester.tap(find.text('Save')); + await tester.pump(); + states.add( + const ComponentEditorState( + status: ComponentEditorStatus.saved, + component: component, + savedComponent: edited, + ), + ); + await tester.pumpRouteTransition(); + + expect(find.byType(ComponentEditorView), findsOneWidget); + }); + + testWidgets('stays when the classes clash', (tester) async { + await openEditor(tester); + await leave(tester); + + await tester.tap(find.text('Save')); + await tester.pump(); + states.add( + unsaved.copyWith( + status: ComponentEditorStatus.classConflict, + takenClassNames: { + r'$Player': const RectangleComponent(name: 'player_'), + }, + ), + ); + await tester.pumpRouteTransition(); + + expect(find.byType(ComponentEditorView), findsOneWidget); + expect( + find.textContaining("This component can't be saved."), + findsOneWidget, + ); + }); + + testWidgets('stays when saving fails', (tester) async { + await openEditor(tester); + await leave(tester); + + await tester.tap(find.text('Save')); + await tester.pump(); + states.add(unsaved.copyWith(status: ComponentEditorStatus.failure)); + await tester.pumpRouteTransition(); + + expect(find.byType(ComponentEditorView), findsOneWidget); + expect(find.text('Could not save the component'), findsOneWidget); + }); + }); +} diff --git a/packages/flame_studio/test/component_editor/widgets/preview/component_preview_game_test.dart b/packages/flame_studio/test/component_editor/widgets/preview/component_preview_game_test.dart new file mode 100644 index 00000000000..1571c27ceeb --- /dev/null +++ b/packages/flame_studio/test/component_editor/widgets/preview/component_preview_game_test.dart @@ -0,0 +1,633 @@ +import 'package:flame/collisions.dart' as flame; +import 'package:flame/components.dart' as flame; +import 'package:flame_studio/component_editor/widgets/widgets.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flame_test/flame_test.dart'; +import 'package:flutter/painting.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockCanvas() extends Mock implements Canvas; + +void main() { + setUpAll(() { + registerFallbackValue(Offset.zero); + registerFallbackValue(Rect.zero); + registerFallbackValue(Paint()); + }); + + const component = RectangleComponent( + name: 'Player', + size: ComponentSize(width: 10, height: 20), + paint: ComponentPaint(color: 0xFFFF0000, style: PaintStyle.stroke), + ); + + group(ComponentPreviewGame, () { + testWithGame( + 'renders the component at the center of the world', + () => ComponentPreviewGame(component: component), + (game) async { + await game.ready(); + + final preview = game.preview as flame.RectangleComponent; + expect(game.world.children, contains(preview)); + expect(preview.anchor, equals(flame.Anchor.center)); + expect(preview.size, equals(flame.Vector2(10, 20))); + expect(preview.paint.color, equals(const Color(0xFFFF0000))); + expect(preview.paint.style, equals(PaintingStyle.stroke)); + }, + ); + + testWithGame( + 'show updates the component in place', + () => ComponentPreviewGame(component: component), + (game) async { + await game.ready(); + final preview = game.preview; + + game.show( + component.copyWithSize(const ComponentSize(width: 30, height: 40)), + ); + + expect(game.preview, same(preview)); + expect(preview.size, equals(flame.Vector2(30, 40))); + }, + ); + + testWithGame( + 'renders position components with a preview-only outline', + () => ComponentPreviewGame( + component: const PositionComponent( + name: 'Player', + size: ComponentSize(width: 10, height: 20), + children: [ + PositionComponent( + name: 'position1', + position: ComponentPosition(x: 5, y: 6), + size: ComponentSize(width: 1, height: 2), + ), + ], + ), + ), + (game) async { + await game.ready(); + + final preview = game.preview; + expect(preview, isA()); + expect(preview.size, equals(flame.Vector2(10, 20))); + final child = preview.children.single as flame.PositionComponent; + expect(child, isA()); + expect(child.position, equals(flame.Vector2(5, 6))); + expect(child.size, equals(flame.Vector2(1, 2))); + }, + ); + + testWithGame( + 'renders circles with their radius and paint', + () => ComponentPreviewGame( + component: const CircleComponent( + name: 'Player', + radius: ComponentRadius(radius: 10), + paint: ComponentPaint(color: 0xFF00FF00), + children: [ + CircleComponent( + name: 'circle1', + position: ComponentPosition(x: 5, y: 6), + radius: ComponentRadius(radius: 2), + ), + ], + ), + ), + (game) async { + await game.ready(); + + final preview = game.preview as flame.CircleComponent; + expect(preview.radius, equals(10)); + expect(preview.size, equals(flame.Vector2(20, 20))); + expect(preview.paint.color, equals(const Color(0xFF00FF00))); + final child = preview.children.single as flame.CircleComponent; + expect(child.position, equals(flame.Vector2(5, 6))); + expect(child.radius, equals(2)); + + game.show( + const CircleComponent( + name: 'Player', + radius: ComponentRadius(radius: 15), + children: [CircleComponent(name: 'circle1')], + ), + highlightedPath: [0], + ); + + expect(game.preview, same(preview)); + expect(preview.radius, equals(15)); + expect(game.highlight.target, same(child)); + }, + ); + + group('hitboxes', () { + const hitboxes = PositionComponent( + name: 'Player', + children: [ + RectangleHitboxComponent( + name: 'rectangleHitbox1', + position: ComponentPosition(x: 1, y: 2), + size: ComponentSize(width: 10, height: 20), + collision: ComponentCollision( + type: HitboxCollisionType.passive, + isSolid: true, + ), + ), + CircleHitboxComponent( + name: 'circleHitbox1', + radius: ComponentRadius(radius: 5), + ), + PolygonHitboxComponent( + name: 'polygonHitbox1', + vertices: ComponentVertices(ComponentVertices.square), + ), + ], + ); + + testWithGame( + 'renders hitboxes as Flame hitboxes with a preview-only outline', + () => ComponentPreviewGame(component: hitboxes), + (game) async { + await game.ready(); + + final [rectangle, circle, polygon] = game.preview.children.toList(); + expect(rectangle, isA()); + rectangle as PreviewRectangleHitbox; + // Keeps its own size rather than filling its parent. + expect(rectangle.size, equals(flame.Vector2(10, 20))); + expect(rectangle.position, equals(flame.Vector2(1, 2))); + expect(rectangle.collisionType, equals(flame.CollisionType.passive)); + expect(rectangle.isSolid, isTrue); + expect(circle, isA()); + // Keeps its own radius rather than filling its parent. + expect((circle as PreviewCircleHitbox).radius, equals(5)); + expect(circle.collisionType, equals(flame.CollisionType.active)); + expect(polygon, isA()); + for (final hitbox in [rectangle, circle, polygon]) { + expect((hitbox as PreviewHitbox).isVisible, isTrue); + } + }, + ); + + testWithGame( + 'areHitboxesVisible hides the hitboxes, also after a rebuild', + () => ComponentPreviewGame(component: hitboxes), + (game) async { + await game.ready(); + + game.areHitboxesVisible = false; + expect( + game.preview.children.whereType().map( + (hitbox) => hitbox.isVisible, + ), + everyElement(isFalse), + ); + + game.show(hitboxes.removeNodeAt(const [0])); + await game.ready(); + expect( + game.preview.children.whereType(), + everyElement( + isA().having( + (h) => h.isVisible, + 'isVisible', + false, + ), + ), + ); + }, + ); + + testWithGame( + 'starts with the hitboxes hidden', + () => ComponentPreviewGame( + component: hitboxes, + areHitboxesVisible: false, + ), + (game) async { + await game.ready(); + + expect(game.areHitboxesVisible, isFalse); + expect( + game.preview.children.whereType().map( + (hitbox) => hitbox.isVisible, + ), + everyElement(isFalse), + ); + }, + ); + }); + + group('with children', () { + const child = RectangleComponent( + name: 'rectangle1', + position: ComponentPosition(x: 5, y: 6), + size: ComponentSize(width: 1, height: 2), + ); + final tree = component.copyWithChildren(const [child]); + + testWithGame( + 'renders the children relative to their parent', + () => ComponentPreviewGame(component: tree), + (game) async { + await game.ready(); + + final children = game.preview.children + .whereType() + .toList(); + expect(children, hasLength(1)); + expect(children.single.anchor, equals(flame.Anchor.topLeft)); + expect(children.single.position, equals(flame.Vector2(5, 6))); + expect(children.single.size, equals(flame.Vector2(1, 2))); + }, + ); + + testWithGame( + 'anchors the children with their anchor', + () => ComponentPreviewGame( + component: component.copyWithChildren([ + child.copyWithAnchor(const ComponentAnchor(x: 0.25, y: 1)), + ]), + ), + (game) async { + await game.ready(); + + final rendered = game.preview.children + .whereType() + .single; + expect(rendered.anchor, equals(const flame.Anchor(0.25, 1))); + }, + ); + + testWithGame( + 'rotates the children with their angle', + () => ComponentPreviewGame( + component: component.copyWithChildren([ + child.copyWithAngle(const ComponentAngle(radians: 1)), + ]), + ), + (game) async { + await game.ready(); + + final rendered = game.preview.children + .whereType() + .single; + expect(rendered.angle, equals(1)); + }, + ); + + testWithGame( + 'show updates the children in place', + () => ComponentPreviewGame(component: tree), + (game) async { + await game.ready(); + final preview = game.preview; + + game.show( + component.copyWithChildren([ + child.copyWithPosition(const ComponentPosition(x: -3)), + ]), + ); + + expect(game.preview, same(preview)); + final rendered = preview.children + .whereType() + .single; + expect(rendered.position, equals(flame.Vector2(-3, 0))); + }, + ); + + testWithGame( + 'show rebuilds when children are added', + () => ComponentPreviewGame(component: component), + (game) async { + await game.ready(); + final preview = game.preview; + + game.show(tree); + await game.ready(); + + expect(game.preview, isNot(same(preview))); + expect(game.world.children, isNot(contains(preview))); + expect(game.preview.children, hasLength(1)); + }, + ); + }); + + testWithGame( + 'renders polygons with their vertices', + () => ComponentPreviewGame( + component: const PolygonComponent( + name: 'Player', + children: [ + PolygonComponent( + name: 'polygon1', + vertices: ComponentVertices(ComponentVertices.square), + ), + ], + ), + highlightedPath: [0], + ), + (game) async { + await game.ready(); + + final preview = game.preview as flame.PolygonComponent; + expect(preview.vertices, hasLength(3)); + expect(preview.size, equals(flame.Vector2(50, 50))); + final child = flameNodeAt(preview, [0]) as flame.PolygonComponent; + expect(child.vertices, hasLength(4)); + expect(game.highlight.target, same(child)); + }, + ); + + testWithGame( + 'rebuilds polygons whose vertices changed', + () => ComponentPreviewGame( + component: const PolygonComponent(name: 'Player'), + ), + (game) async { + await game.ready(); + final preview = game.preview; + + game.show( + const PolygonComponent( + name: 'Player', + vertices: ComponentVertices(ComponentVertices.square), + ), + ); + await game.ready(); + + expect(game.preview, isNot(same(preview))); + expect((game.preview as flame.PolygonComponent).vertices, hasLength(4)); + }, + ); + + group('highlight', () { + const child = RectangleComponent(name: 'rectangle1'); + final tree = component.copyWithChildren(const [child]); + + testWithGame( + 'targets the root', + () => ComponentPreviewGame(component: component, highlightedPath: []), + (game) async { + await game.ready(); + + expect(game.world.children, contains(game.highlight)); + expect(game.highlight.target, same(game.preview)); + }, + ); + + testWithGame( + 'targets nothing without a path', + () => ComponentPreviewGame(component: component), + (game) async { + await game.ready(); + + expect(game.highlight.target, isNull); + }, + ); + + testWithGame( + 'follows the highlighted path', + () => ComponentPreviewGame(component: tree, highlightedPath: []), + (game) async { + await game.ready(); + + game.show(tree, highlightedPath: [0]); + expect(game.highlight.target, same(flameNodeAt(game.preview, [0]))); + + game.show(tree); + expect(game.highlight.target, isNull); + }, + ); + + testWithGame( + 'targets the rebuilt component', + () => ComponentPreviewGame(component: component, highlightedPath: []), + (game) async { + await game.ready(); + + game.show(tree, highlightedPath: [0]); + await game.ready(); + + final rendered = game.preview.children + .whereType() + .single; + expect(game.highlight.target, same(rendered)); + }, + ); + + testWithGame( + 'ignores paths outside of the tree', + () => ComponentPreviewGame(component: component, highlightedPath: [3]), + (game) async { + await game.ready(); + + expect(game.highlight.target, isNull); + }, + ); + }); + + group('zoom', () { + testWithGame( + 'zooms the camera when loaded', + () => ComponentPreviewGame(component: component, zoom: 2), + (game) async { + await game.ready(); + + expect(game.zoom, 2); + expect(game.camera.viewfinder.zoom, 2); + expect(game.highlight.zoom, 2); + }, + ); + + testWithGame( + 'zooms the camera when changed', + () => ComponentPreviewGame(component: component), + (game) async { + await game.ready(); + + game.zoom = 4; + + expect(game.camera.viewfinder.zoom, 4); + expect(game.highlight.zoom, 4); + }, + ); + + test('keeps the zoom for later when changed before loading', () { + final game = ComponentPreviewGame(component: component)..zoom = 3; + + expect(game.zoom, 3); + expect(game.isLoaded, isFalse); + }); + }); + + test('haveSameShape compares the types and the tree', () { + const child = RectangleComponent(name: 'rectangle1'); + + expect( + haveSameShape( + component, + component.copyWithSize(const ComponentSize(width: 1)), + ), + isTrue, + ); + expect( + haveSameShape(component, component.copyWithChildren(const [child])), + isFalse, + ); + const polygon = PolygonComponent(name: 'Player'); + expect( + haveSameShape( + polygon, + polygon.copyWithPaint(const ComponentPaint(color: 0xFF000000)), + ), + isTrue, + ); + expect( + haveSameShape( + polygon, + polygon.copyWithVertices( + const ComponentVertices(ComponentVertices.square), + ), + ), + isFalse, + ); + }); + + testWithGame( + 'keeps the root centered and not rotated whatever its stored ' + 'position, anchor and angle', + () => ComponentPreviewGame( + component: component + .copyWithPosition(const ComponentPosition(x: 100, y: 100)) + .copyWithAnchor(ComponentAnchor.bottomRight) + .copyWithAngle(const ComponentAngle(radians: 1)), + ), + (game) async { + await game.ready(); + expect(game.preview.position, equals(flame.Vector2.zero())); + expect(game.preview.anchor, equals(flame.Anchor.center)); + expect(game.preview.angle, equals(0)); + + game.show( + component.copyWithPosition(const ComponentPosition(x: 7, y: 8)), + ); + expect(game.preview.position, equals(flame.Vector2.zero())); + }, + ); + + test('show before loading keeps the component for later', () { + final game = ComponentPreviewGame(component: component) + ..show(component.copyWithSize(const ComponentSize(width: 1))); + + expect(game.isLoaded, isFalse); + }); + }); + + group(SelectionHighlight, () { + test('keeps the same border width on screen at any zoom', () { + final highlight = SelectionHighlight(); + expect(highlight.worldStrokeWidth, SelectionHighlight.strokeWidth); + + highlight.zoom = 2; + + expect(highlight.worldStrokeWidth, SelectionHighlight.strokeWidth / 2); + }); + + testWithGame( + 'draws the border with the zoomed width', + () => ComponentPreviewGame( + component: component, + highlightedPath: [], + zoom: 2, + ), + (game) async { + await game.ready(); + final canvas = _MockCanvas(); + + game.highlight.render(canvas); + + final captured = verify( + () => canvas.drawRect(captureAny(), captureAny()), + ).captured; + expect(captured[0], const Rect.fromLTWH(0, 0, 10, 20).inflate(1)); + expect((captured[1] as Paint).strokeWidth, 2); + }, + ); + }); + + group(PreviewPositionComponent, () { + test('draws a dashed outline around its size', () { + final canvas = _MockCanvas(); + // Edges of 16 and 8 hold two and one 4px dashes respectively. + PreviewPositionComponent() + ..size.setValues(16, 8) + ..render(canvas); + + final starts = verify(() => canvas.drawLine(captureAny(), any(), any())) + .captured; + expect(starts, hasLength(6)); + expect(starts.first, equals(Offset.zero)); + }); + + test('draws nothing without a size', () { + final canvas = _MockCanvas(); + PreviewPositionComponent().render(canvas); + + verifyNever(() => canvas.drawLine(any(), any(), any())); + }); + }); + + group('preview hitboxes', () { + test('rectangle hitboxes draw a dashed outline around their size', () { + final canvas = _MockCanvas(); + PreviewRectangleHitbox() + ..size.setValues(16, 8) + ..render(canvas); + + verify(() => canvas.drawLine(any(), any(), PreviewHitbox.paint)) + .called(6); + }); + + test('circle hitboxes draw a dashed circle', () { + final canvas = _MockCanvas(); + // A circumference of 16 pi (about 50) holds six 4px dashes and gaps. + PreviewCircleHitbox() + ..radius = 8 + ..render(canvas); + + verify( + () => canvas.drawArc(any(), any(), any(), false, PreviewHitbox.paint), + ).called(6); + }); + + test('polygon hitboxes draw a dashed outline along their vertices', () { + final canvas = _MockCanvas(); + // Edges of 4, 4 and about 5.7 hold one 4px dash each. + PreviewPolygonHitbox([ + flame.Vector2.zero(), + flame.Vector2(4, 0), + flame.Vector2(0, 4), + ]).render(canvas); + + verify(() => canvas.drawLine(any(), any(), PreviewHitbox.paint)) + .called(3); + }); + }); + + group('applyPaint', () { + test('maps the fill style', () { + final target = flame.RectangleComponent(); + + applyPaint(target, const ComponentPaint(color: 0xFF00FF00)); + + expect(target.paint.color, equals(const Color(0xFF00FF00))); + expect(target.paint.style, equals(PaintingStyle.fill)); + }); + }); +} diff --git a/packages/flame_studio/test/component_editor/widgets/property_editors/anchor_editor_test.dart b/packages/flame_studio/test/component_editor/widgets/property_editors/anchor_editor_test.dart new file mode 100644 index 00000000000..f5ffd6855d4 --- /dev/null +++ b/packages/flame_studio/test/component_editor/widgets/property_editors/anchor_editor_test.dart @@ -0,0 +1,73 @@ +import 'package:flame_studio/component_editor/widgets/widgets.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(AnchorEditor, () { + late List changes; + + setUp(() => changes = []); + + Future pumpSubject( + WidgetTester tester, { + ComponentAnchor value = ComponentAnchor.topLeft, + }) => tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: AnchorEditor(value: value, onChanged: changes.add), + ), + ), + ); + + testWidgets('has a button for every Flame anchor', (tester) async { + await pumpSubject(tester); + + for (final name in ComponentAnchor.presets.keys) { + expect(find.byTooltip(name), findsOneWidget); + } + }); + + testWidgets('selects the button of the current anchor', (tester) async { + await pumpSubject(tester, value: ComponentAnchor.bottomCenter); + + bool isSelected(String name) => tester + .widget( + find.ancestor( + of: find.byTooltip(name), + matching: find.byType(IconButton), + ), + ) + .isSelected!; + + expect(isSelected('bottomCenter'), isTrue); + expect(isSelected('topLeft'), isFalse); + }); + + testWidgets('picks a Flame anchor', (tester) async { + await pumpSubject(tester); + + await tester.tap(find.byTooltip('centerRight')); + + expect(changes, equals([ComponentAnchor.centerRight])); + }); + + testWidgets('edits a custom x', (tester) async { + await pumpSubject(tester, value: ComponentAnchor.center); + + await tester.enterText(find.widgetWithText(TextField, 'X'), '0.25'); + await tester.testTextInput.receiveAction(TextInputAction.done); + + expect(changes, equals([const ComponentAnchor(x: 0.25, y: 0.5)])); + }); + + testWidgets('edits a custom y', (tester) async { + await pumpSubject(tester, value: ComponentAnchor.center); + + await tester.enterText(find.widgetWithText(TextField, 'Y'), '-1'); + await tester.testTextInput.receiveAction(TextInputAction.done); + + expect(changes, equals([const ComponentAnchor(x: 0.5, y: -1)])); + }); + }); +} diff --git a/packages/flame_studio/test/component_editor/widgets/property_editors/angle_editor_test.dart b/packages/flame_studio/test/component_editor/widgets/property_editors/angle_editor_test.dart new file mode 100644 index 00000000000..2f300097ef3 --- /dev/null +++ b/packages/flame_studio/test/component_editor/widgets/property_editors/angle_editor_test.dart @@ -0,0 +1,49 @@ +import 'package:flame_studio/component_editor/widgets/widgets.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(AngleEditor, () { + late List changes; + + setUp(() => changes = []); + + Future pumpSubject( + WidgetTester tester, { + ComponentAngle value = ComponentAngle.zero, + }) => tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: AngleEditor(value: value, onChanged: changes.add), + ), + ), + ); + + testWidgets('shows the angle in degrees', (tester) async { + await pumpSubject(tester, value: ComponentAngle.fromDegrees(45)); + + expect(find.widgetWithText(TextField, '45'), findsOneWidget); + }); + + testWidgets('edits the angle in degrees', (tester) async { + await pumpSubject(tester); + + await tester.enterText(find.widgetWithText(TextField, 'Degrees'), '-90'); + await tester.testTextInput.receiveAction(TextInputAction.done); + + expect(changes, equals([ComponentAngle.fromDegrees(-90)])); + }); + + testWidgets('keeps the typed degrees when the edited angle comes back', ( + tester, + ) async { + await pumpSubject(tester); + + await tester.enterText(find.widgetWithText(TextField, 'Degrees'), '45'); + await pumpSubject(tester, value: changes.single); + + expect(find.widgetWithText(TextField, '45'), findsOneWidget); + }); + }); +} diff --git a/packages/flame_studio/test/component_editor/widgets/property_editors/collision_editor_test.dart b/packages/flame_studio/test/component_editor/widgets/property_editors/collision_editor_test.dart new file mode 100644 index 00000000000..d1a141946bd --- /dev/null +++ b/packages/flame_studio/test/component_editor/widgets/property_editors/collision_editor_test.dart @@ -0,0 +1,42 @@ +import 'package:flame_studio/component_editor/widgets/widgets.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(CollisionEditor, () { + Future> pump(WidgetTester tester) async { + final changes = []; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: CollisionEditor( + value: const ComponentCollision(), + onChanged: changes.add, + ), + ), + ), + ); + return changes; + } + + testWidgets('edits the collision type', (tester) async { + final changes = await pump(tester); + + await tester.tap(find.text('Passive')); + + expect( + changes, + equals([const ComponentCollision(type: HitboxCollisionType.passive)]), + ); + }); + + testWidgets('edits whether the hitbox is solid', (tester) async { + final changes = await pump(tester); + + await tester.tap(find.text('Solid')); + + expect(changes, equals([const ComponentCollision(isSolid: true)])); + }); + }); +} diff --git a/packages/flame_studio/test/component_editor/widgets/property_editors/name_field_test.dart b/packages/flame_studio/test/component_editor/widgets/property_editors/name_field_test.dart new file mode 100644 index 00000000000..f8d7bd9f1a1 --- /dev/null +++ b/packages/flame_studio/test/component_editor/widgets/property_editors/name_field_test.dart @@ -0,0 +1,91 @@ +import 'package:flame_studio/component_editor/widgets/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(NameField, () { + late List changes; + + setUp(() => changes = []); + + String? validator(String name) => + name.isEmpty || name == 'size' ? 'Invalid' : null; + + Widget buildSubject(String value) => MaterialApp( + home: Scaffold( + body: Column( + children: [ + NameField( + value: value, + validator: validator, + onChanged: changes.add, + ), + const TextField(key: Key('other')), + ], + ), + ), + ); + + testWidgets('commits every valid edit while typing', (tester) async { + await tester.pumpWidget(buildSubject('head')); + + for (final input in ['h', 'he', '', 'size', 'hea']) { + await tester.enterText(find.byType(NameField), input); + } + + expect(changes, equals(['h', 'he', 'hea'])); + }); + + testWidgets('shows the error of rejected names', (tester) async { + await tester.pumpWidget(buildSubject('head')); + + await tester.enterText(find.byType(NameField), 'size'); + await tester.pump(); + expect(find.text('Invalid'), findsOneWidget); + + await tester.enterText(find.byType(NameField), 'eye'); + await tester.pump(); + expect(find.text('Invalid'), findsNothing); + }); + + testWidgets('accepts going back to the current name', (tester) async { + await tester.pumpWidget(buildSubject('head')); + + await tester.enterText(find.byType(NameField), 'size'); + await tester.enterText(find.byType(NameField), 'head'); + await tester.pump(); + + expect(find.text('Invalid'), findsNothing); + expect(changes, isEmpty); + }); + + testWidgets('shows names changed elsewhere', (tester) async { + await tester.pumpWidget(buildSubject('head')); + + await tester.pumpWidget(buildSubject('eye')); + + expect(find.text('eye'), findsOneWidget); + }); + + testWidgets('reverts rejected input when losing focus', (tester) async { + await tester.pumpWidget(buildSubject('head')); + + await tester.enterText(find.byType(NameField), 'size'); + await tester.tap(find.byKey(const Key('other'))); + await tester.pump(); + + expect(find.text('head'), findsOneWidget); + expect(find.text('Invalid'), findsNothing); + }); + + testWidgets('reverts rejected input when submitted', (tester) async { + await tester.pumpWidget(buildSubject('head')); + + await tester.enterText(find.byType(NameField), ''); + await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.pump(); + + expect(find.text('head'), findsOneWidget); + }); + }); +} diff --git a/packages/flame_studio/test/component_editor/widgets/property_editors/number_field_test.dart b/packages/flame_studio/test/component_editor/widgets/property_editors/number_field_test.dart new file mode 100644 index 00000000000..03279128e5b --- /dev/null +++ b/packages/flame_studio/test/component_editor/widgets/property_editors/number_field_test.dart @@ -0,0 +1,113 @@ +import 'package:flame_studio/component_editor/widgets/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(NumberField, () { + late List changes; + + setUp(() => changes = []); + + Widget buildSubject(double value) => MaterialApp( + home: Scaffold( + body: Column( + children: [ + NumberField(label: 'Width', value: value, onChanged: changes.add), + const TextField(key: Key('other')), + ], + ), + ), + ); + + testWidgets('shows whole numbers without decimals', (tester) async { + await tester.pumpWidget(buildSubject(50)); + expect(find.text('50'), findsOneWidget); + + await tester.pumpWidget(buildSubject(12.5)); + expect(find.text('12.5'), findsOneWidget); + }); + + testWidgets('commits every valid edit while typing', (tester) async { + await tester.pumpWidget(buildSubject(50)); + + for (final input in ['1', '12', '12.', '12.5', '12.', '']) { + await tester.enterText(find.byType(NumberField), input); + } + + expect(changes, equals([1, 12, 12.5, 12])); + }); + + testWidgets('keeps the typed text when its value comes back', ( + tester, + ) async { + await tester.pumpWidget(buildSubject(50)); + + await tester.enterText(find.byType(NumberField), '1.50'); + await tester.pumpWidget(buildSubject(1.5)); + + expect(find.text('1.50'), findsOneWidget); + }); + + testWidgets('shows values changed elsewhere', (tester) async { + await tester.pumpWidget(buildSubject(50)); + + await tester.pumpWidget(buildSubject(20)); + + expect(find.text('20'), findsOneWidget); + }); + + testWidgets('reverts invalid input when losing focus', (tester) async { + await tester.pumpWidget(buildSubject(50)); + + await tester.enterText(find.byType(NumberField), '10'); + await tester.enterText(find.byType(NumberField), 'abc'); + await tester.tap(find.byKey(const Key('other'))); + await tester.pump(); + + expect(find.text('10'), findsOneWidget); + expect(changes, equals([10])); + }); + + testWidgets('reverts invalid input', (tester) async { + await tester.pumpWidget(buildSubject(50)); + + for (final input in ['abc', '-1']) { + await tester.enterText(find.byType(NumberField), input); + await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.pump(); + + expect(find.text('50'), findsOneWidget); + } + expect(changes, isEmpty); + }); + + testWidgets('accepts negative numbers without a minimum', (tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: NumberField( + label: 'X', + value: 0, + min: null, + onChanged: changes.add, + ), + ), + ), + ); + + await tester.enterText(find.byType(NumberField), '-12.5'); + await tester.testTextInput.receiveAction(TextInputAction.done); + + expect(changes, equals([-12.5])); + }); + + testWidgets('does not commit an unchanged value', (tester) async { + await tester.pumpWidget(buildSubject(50)); + + await tester.enterText(find.byType(NumberField), '50.0'); + await tester.testTextInput.receiveAction(TextInputAction.done); + + expect(changes, isEmpty); + }); + }); +} diff --git a/packages/flame_studio/test/component_editor/widgets/property_editors/paint_editor_test.dart b/packages/flame_studio/test/component_editor/widgets/property_editors/paint_editor_test.dart new file mode 100644 index 00000000000..b4ebc33104a --- /dev/null +++ b/packages/flame_studio/test/component_editor/widgets/property_editors/paint_editor_test.dart @@ -0,0 +1,157 @@ +import 'package:flame_studio/component_editor/widgets/widgets.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flex_color_picker/flex_color_picker.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(PaintEditor, () { + late List changes; + + setUp(() => changes = []); + + Future pumpSubject(WidgetTester tester) => tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: PaintEditor( + value: const ComponentPaint(color: 0xFF112233), + onChanged: changes.add, + ), + ), + ), + ); + + testWidgets('shows the color hex code', (tester) async { + await pumpSubject(tester); + + expect(find.text('#FF112233'), findsOneWidget); + }); + + testWidgets('edits the style', (tester) async { + await pumpSubject(tester); + + await tester.tap(find.text('Stroke')); + + expect( + changes, + equals([ + const ComponentPaint(color: 0xFF112233, style: PaintStyle.stroke), + ]), + ); + }); + + testWidgets('opens a color picker for the color', (tester) async { + await pumpSubject(tester); + + await tester.tap(find.byType(ColorField)); + await tester.pumpAndSettle(); + + expect(find.byType(ColorPicker), findsOneWidget); + }); + + testWidgets('keeps the color when the picker is cancelled', (tester) async { + await pumpSubject(tester); + + await tester.tap(find.byType(ColorField)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + + expect(changes, isEmpty); + }); + + group('palette', () { + const palette = Palette( + colors: [ + PaletteColor(name: 'primary', color: 0xFFFF0000), + PaletteColor(name: 'accent', color: 0xFF00FF00), + ], + ); + + Future pumpWithPalette( + WidgetTester tester, { + ComponentPaint value = const ComponentPaint(color: 0xFF112233), + }) => tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: PaintEditor( + value: value, + palette: palette, + onChanged: changes.add, + ), + ), + ), + ); + + testWidgets('has no palette button without colors', (tester) async { + await pumpSubject(tester); + + expect(find.byTooltip('Pick from palette'), findsNothing); + }); + + testWidgets('picks a palette color', (tester) async { + await pumpWithPalette(tester); + + await tester.tap(find.byTooltip('Pick from palette')); + await tester.pumpAndSettle(); + await tester.tap(find.text('accent')); + await tester.pumpAndSettle(); + + expect( + changes, + equals([ + const ComponentPaint(color: 0xFF00FF00, paletteColor: 'accent'), + ]), + ); + }); + + testWidgets('shows the palette color by name, with its value', ( + tester, + ) async { + await pumpWithPalette( + tester, + value: const ComponentPaint( + color: 0xFF112233, + paletteColor: 'primary', + ), + ); + + expect(find.text('primary · #FFFF0000'), findsOneWidget); + + await tester.tap(find.byTooltip('Pick from palette')); + await tester.pumpAndSettle(); + expect(find.byIcon(Icons.check), findsOneWidget); + }); + + testWidgets('shows the last value of a missing palette color', ( + tester, + ) async { + await pumpWithPalette( + tester, + value: const ComponentPaint(color: 0xFF112233, paletteColor: 'gone'), + ); + + expect(find.text('#FF112233'), findsOneWidget); + }); + + testWidgets('keeps the palette color when the picker is cancelled', ( + tester, + ) async { + await pumpWithPalette( + tester, + value: const ComponentPaint( + color: 0xFF112233, + paletteColor: 'primary', + ), + ); + + await tester.tap(find.byType(ColorField)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + + expect(changes, isEmpty); + }); + }); + }); +} diff --git a/packages/flame_studio/test/component_editor/widgets/property_editors/position_editor_test.dart b/packages/flame_studio/test/component_editor/widgets/property_editors/position_editor_test.dart new file mode 100644 index 00000000000..fc5d57db3eb --- /dev/null +++ b/packages/flame_studio/test/component_editor/widgets/property_editors/position_editor_test.dart @@ -0,0 +1,41 @@ +import 'package:flame_studio/component_editor/widgets/widgets.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(PositionEditor, () { + late List changes; + + setUp(() => changes = []); + + Future pumpSubject(WidgetTester tester) => tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: PositionEditor( + value: const ComponentPosition(x: 10, y: 20), + onChanged: changes.add, + ), + ), + ), + ); + + testWidgets('edits x', (tester) async { + await pumpSubject(tester); + + await tester.enterText(find.widgetWithText(TextField, 'X'), '-30'); + await tester.testTextInput.receiveAction(TextInputAction.done); + + expect(changes, equals([const ComponentPosition(x: -30, y: 20)])); + }); + + testWidgets('edits y', (tester) async { + await pumpSubject(tester); + + await tester.enterText(find.widgetWithText(TextField, 'Y'), '40'); + await tester.testTextInput.receiveAction(TextInputAction.done); + + expect(changes, equals([const ComponentPosition(x: 10, y: 40)])); + }); + }); +} diff --git a/packages/flame_studio/test/component_editor/widgets/property_editors/radius_editor_test.dart b/packages/flame_studio/test/component_editor/widgets/property_editors/radius_editor_test.dart new file mode 100644 index 00000000000..94939b916b5 --- /dev/null +++ b/packages/flame_studio/test/component_editor/widgets/property_editors/radius_editor_test.dart @@ -0,0 +1,27 @@ +import 'package:flame_studio/component_editor/widgets/widgets.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(RadiusEditor, () { + testWidgets('edits the radius', (tester) async { + final changes = []; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RadiusEditor( + value: const ComponentRadius(radius: 10), + onChanged: changes.add, + ), + ), + ), + ); + + await tester.enterText(find.widgetWithText(TextField, 'Radius'), '30'); + await tester.testTextInput.receiveAction(TextInputAction.done); + + expect(changes, equals([const ComponentRadius(radius: 30)])); + }); + }); +} diff --git a/packages/flame_studio/test/component_editor/widgets/property_editors/size_editor_test.dart b/packages/flame_studio/test/component_editor/widgets/property_editors/size_editor_test.dart new file mode 100644 index 00000000000..3b51ffd953e --- /dev/null +++ b/packages/flame_studio/test/component_editor/widgets/property_editors/size_editor_test.dart @@ -0,0 +1,41 @@ +import 'package:flame_studio/component_editor/widgets/widgets.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(SizeEditor, () { + late List changes; + + setUp(() => changes = []); + + Future pumpSubject(WidgetTester tester) => tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizeEditor( + value: const ComponentSize(width: 10, height: 20), + onChanged: changes.add, + ), + ), + ), + ); + + testWidgets('edits the width', (tester) async { + await pumpSubject(tester); + + await tester.enterText(find.widgetWithText(TextField, 'Width'), '30'); + await tester.testTextInput.receiveAction(TextInputAction.done); + + expect(changes, equals([const ComponentSize(width: 30, height: 20)])); + }); + + testWidgets('edits the height', (tester) async { + await pumpSubject(tester); + + await tester.enterText(find.widgetWithText(TextField, 'Height'), '40'); + await tester.testTextInput.receiveAction(TextInputAction.done); + + expect(changes, equals([const ComponentSize(width: 10, height: 40)])); + }); + }); +} diff --git a/packages/flame_studio/test/component_editor/widgets/property_editors/vertices_editor_test.dart b/packages/flame_studio/test/component_editor/widgets/property_editors/vertices_editor_test.dart new file mode 100644 index 00000000000..f51c090e31c --- /dev/null +++ b/packages/flame_studio/test/component_editor/widgets/property_editors/vertices_editor_test.dart @@ -0,0 +1,79 @@ +import 'package:flame_studio/component_editor/widgets/widgets.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flame_studio/vertices_editor/vertices_editor.dart'; +import 'package:flame_studio/vertices_editor/widgets/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(VerticesEditor, () { + Future> pumpEditor(WidgetTester tester) async { + final changes = []; + tester.view.physicalSize = const Size(1200, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: VerticesEditor( + value: const ComponentVertices(), + onChanged: changes.add, + ), + ), + ), + ); + return changes; + } + + testWidgets('shows the number of vertices and the size', (tester) async { + await pumpEditor(tester); + + expect(find.text('3 vertices, 50 × 50'), findsOneWidget); + }); + + testWidgets('edits the vertices in the dialog', (tester) async { + final changes = await pumpEditor(tester); + + await tester.tap(find.text('Edit vertices')); + await tester.pumpAndSettle(); + expect(find.byType(VerticesEditorDialog), findsOneWidget); + + // Adds a vertex in the middle of the first edge, then applies. + tester + .element(find.byType(VerticesCanvas)) + .read() + .vertexInserted(0, 40, 20); + await tester.tap(find.text('Apply')); + await tester.pumpAndSettle(); + + expect(changes, hasLength(1)); + expect(changes.single.vertices, hasLength(4)); + }); + + testWidgets('keeps the vertices when the dialog is cancelled', ( + tester, + ) async { + final changes = await pumpEditor(tester); + + await tester.tap(find.text('Edit vertices')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + + expect(find.byType(VerticesEditorDialog), findsNothing); + expect(changes, isEmpty); + }); + + testWidgets('does not report unchanged vertices', (tester) async { + final changes = await pumpEditor(tester); + + await tester.tap(find.text('Edit vertices')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Apply')); + await tester.pumpAndSettle(); + + expect(changes, isEmpty); + }); + }); +} diff --git a/packages/flame_studio/test/flame_studio_test.dart b/packages/flame_studio/test/flame_studio_test.dart deleted file mode 100644 index f963350bc4b..00000000000 --- a/packages/flame_studio/test/flame_studio_test.dart +++ /dev/null @@ -1,313 +0,0 @@ -import 'dart:math'; - -import 'package:flame/components.dart'; -import 'package:flame/game.dart'; -import 'package:flame_studio/src/core/inspector/component_inspectors.dart'; -import 'package:flame_studio/src/core/viewport_tool.dart'; -import 'package:flame_studio/src/widgets/common/studio_tooltip.dart'; -import 'package:flame_studio/src/widgets/flame_studio.dart'; -import 'package:flame_studio/src/widgets/panels/inspector/property_editors.dart'; -import 'package:flame_studio/src/widgets/toolbar/viewport_tool_button.dart'; -import 'package:flame_studio/src/widgets/viewport/gizmo_overlay.dart'; -import 'package:flame_test/flame_test.dart'; -import 'package:flutter/gestures.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('FlameStudio', () { - late _Player player; - late FlameGame game; - - Future pumpStudio(WidgetTester tester) async { - tester.view.physicalSize = const Size(1600, 900); - tester.view.devicePixelRatio = 1.0; - addTearDown(tester.view.reset); - - player = _Player(); - game = FlameGame(children: [player, _Enemy()]); - await tester.pumpWidget(FlameStudio(GameWidget(game: game))); - // Let the game load, the studio find it, and the tree refresh. - for (var i = 0; i < 5; i++) { - await tester.pump(const Duration(milliseconds: 300)); - } - } - - Future disposeStudio(WidgetTester tester) async { - // Disposes the providers, which cancels their timers. - await tester.pumpWidget(const SizedBox()); - } - - testWidgets('shows the Hierarchy and Inspector tabs', (tester) async { - await pumpStudio(tester); - - expect(find.text('Hierarchy'), findsOneWidget); - expect(find.text('Inspector'), findsOneWidget); - expect(find.text('FlameGame'), findsOneWidget); - expect(find.text('_Player'), findsOneWidget); - expect(find.text('_Enemy'), findsOneWidget); - expect( - find.text('Select a component in the Hierarchy to inspect it.'), - findsOneWidget, - ); - - await disposeStudio(tester); - }); - - testWidgets('selecting a component shows it in the Inspector', ( - tester, - ) async { - await pumpStudio(tester); - - await tester.tap(find.text('_Player')); - await tester.pump(const Duration(milliseconds: 100)); - - expect(find.text('Transform'), findsOneWidget); - expect(find.text('Position'), findsOneWidget); - expect(find.text('10'), findsOneWidget); - expect(find.text('20'), findsOneWidget); - - await disposeStudio(tester); - }); - - testWidgets('editing a value in the Inspector changes the component', ( - tester, - ) async { - await pumpStudio(tester); - await tester.tap(find.text('_Player')); - await tester.pump(const Duration(milliseconds: 100)); - - // `find.text` also matches the text of an EditableText. - final xField = find.text('10'); - await tester.tap(xField); - await tester.pump(); - await tester.enterText(xField, '42'); - await tester.testTextInput.receiveAction(TextInputAction.done); - await tester.pump(const Duration(milliseconds: 100)); - - expect(player.x, 42); - expect(find.text('42'), findsOneWidget); - - await disposeStudio(tester); - }); - - testWidgets('draws a gizmo for the selected component', (tester) async { - await pumpStudio(tester); - final overlay = find.byType(GizmoOverlay); - expect(tester.renderObject(overlay), paintsNothing); - - await tester.tap(find.text('_Player')); - await tester.pump(const Duration(milliseconds: 100)); - await tester.pump(const Duration(milliseconds: 16)); - - expect(tester.renderObject(overlay), paints..path()); - - await disposeStudio(tester); - }); - - testWidgets('the select tool selects components in the game view', ( - tester, - ) async { - await pumpStudio(tester); - final playerCenter = game.renderBox.localToGlobal(const Offset(18, 28)); - - // With the interact tool, the click goes to the game. - await tester.tapAt(playerCenter); - await tester.pump(); - expect(find.text('Transform'), findsNothing); - - await tester.tap( - find.byWidgetPredicate( - (widget) => - widget is ViewportToolButton && - widget.tool == ViewportTool.select, - ), - ); - await tester.pump(); - await tester.tapAt(playerCenter); - await tester.pump(const Duration(milliseconds: 100)); - - expect(find.text('Transform'), findsOneWidget); - expect(find.text('10'), findsOneWidget); - - await disposeStudio(tester); - }); - - testWidgets('the move tool moves components by dragging them', ( - tester, - ) async { - await pumpStudio(tester); - final playerCenter = game.renderBox.localToGlobal(const Offset(18, 28)); - - await tester.tap( - find.byWidgetPredicate( - (widget) => - widget is ViewportToolButton && widget.tool == ViewportTool.move, - ), - ); - await tester.pump(); - await tester.dragFrom(playerCenter, const Offset(30, 10)); - await tester.pump(const Duration(milliseconds: 100)); - - expect(player.position, closeToVector(Vector2(40, 30))); - expect(find.text('Transform'), findsOneWidget); - - await disposeStudio(tester); - }); - - testWidgets('pressing Shift while dragging snaps right away', ( - tester, - ) async { - await pumpStudio(tester); - final playerCenter = game.renderBox.localToGlobal(const Offset(18, 28)); - await tester.tap( - find.byWidgetPredicate( - (widget) => - widget is ViewportToolButton && widget.tool == ViewportTool.move, - ), - ); - await tester.pump(); - - final gesture = await tester.startGesture(playerCenter); - for (var i = 0; i < 10; i++) { - await gesture.moveBy(const Offset(3, 1)); - await tester.pump(); - } - expect(player.position, closeToVector(Vector2(40, 30))); - - await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); - expect(player.position, closeToVector(Vector2(40, 32))); - - await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); - expect(player.position, closeToVector(Vector2(40, 30))); - - await gesture.up(); - await disposeStudio(tester); - }); - - testWidgets('the rotate tool rotates components with the ring', ( - tester, - ) async { - await pumpStudio(tester); - // The anchor of the player is its top-left corner, at (10, 20). - final ringPoint = game.renderBox.localToGlobal(const Offset(60, 20)); - - await tester.tap( - find.byWidgetPredicate( - (widget) => - widget is ViewportToolButton && - widget.tool == ViewportTool.rotate, - ), - ); - await tester.tap(find.text('_Player')); - await tester.pump(); - await tester.dragFrom(ringPoint, const Offset(-50, 50)); - await tester.pump(const Duration(milliseconds: 100)); - - expect(player.angle, closeTo(pi / 2, 1e-9)); - expect(player.position, closeToVector(Vector2(10, 20))); - - await disposeStudio(tester); - }); - - testWidgets('shows tooltips when hovering over buttons', (tester) async { - await pumpStudio(tester); - final moveButton = find.byWidgetPredicate( - (widget) => - widget is ViewportToolButton && widget.tool == ViewportTool.move, - ); - final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); - await mouse.addPointer(location: Offset.zero); - addTearDown(mouse.removePointer); - - await mouse.moveTo(tester.getCenter(moveButton)); - await tester.pump(const Duration(milliseconds: 100)); - expect(find.textContaining('Move: drag the arrows'), findsNothing); - - await tester.pump(StudioTooltip.delay); - expect(find.textContaining('Move: drag the arrows'), findsOneWidget); - - await mouse.moveTo(Offset.zero); - await tester.pump(); - expect(find.textContaining('Move: drag the arrows'), findsNothing); - - await disposeStudio(tester); - }); - - testWidgets('debug mode is applied to all descendants', (tester) async { - await pumpStudio(tester); - await tester.tap(find.text('FlameGame')); - await tester.pump(const Duration(milliseconds: 100)); - - await tester.tap( - find.descendant( - of: find.byType(StudioCheckbox), - matching: find.byType(CustomPaint), - ), - ); - await tester.pump(const Duration(milliseconds: 100)); - - expect(player.debugMode, isTrue); - - await disposeStudio(tester); - }); - - testWidgets('the Hierarchy filter hides non-matching components', ( - tester, - ) async { - await pumpStudio(tester); - - final filter = find.ancestor( - of: find.text('Filter'), - matching: find.byType(Stack), - ); - await tester.enterText( - find.descendant(of: filter.first, matching: find.byType(EditableText)), - 'enemy', - ); - await tester.pump(); - - expect(find.text('_Enemy'), findsOneWidget); - expect(find.text('_Player'), findsNothing); - expect(find.text('FlameGame'), findsOneWidget); - - await disposeStudio(tester); - }); - }); - - group('inspectors', () { - test('describe all of their properties', () { - final component = TextComponent(); - for (final inspector in defaultComponentInspectors) { - for (final property in [...?inspector(component)?.properties]) { - expect(property.description, isNotNull, reason: property.label); - } - } - }); - - test('only PositionComponents have a Transform section', () { - expect(inspectPositionComponent(Component()), isNull); - expect(inspectPositionComponent(PositionComponent()), isNotNull); - }); - - test('Rendering section depends on the mixins of the component', () { - expect(inspectRendering(Component()), isNull); - final section = inspectRendering(RectangleComponent())!; - expect(section.properties.map((p) => p.label), ['Opacity']); - }); - }); - - test('formatNumber', () { - expect(formatNumber(10), '10'); - expect(formatNumber(1.5), '1.5'); - expect(formatNumber(1.23456), '1.235'); - expect(formatNumber(-0.0001), '0'); - }); -} - -class _Player() extends PositionComponent { - this : super(position: Vector2(10, 20), size: Vector2.all(16)); -} - -class _Enemy() extends PositionComponent; diff --git a/packages/flame_studio/test/gizmo_test.dart b/packages/flame_studio/test/gizmo_test.dart deleted file mode 100644 index d76fc184296..00000000000 --- a/packages/flame_studio/test/gizmo_test.dart +++ /dev/null @@ -1,147 +0,0 @@ -import 'dart:math'; - -import 'package:flame/components.dart'; -import 'package:flame_studio/src/core/gizmo/canvas_mapping.dart'; -import 'package:flame_studio/src/core/gizmo/gizmo_geometry.dart'; -import 'package:flame_test/flame_test.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - // The game is 800x600, and the viewfinder of the default camera is anchored - // at the center, so that the world origin is at (400, 300) on the canvas. - group('localToCanvas', () { - testWithFlameGame('maps world components through the camera', ( - game, - ) async { - final component = PositionComponent( - position: Vector2(110, 60), - size: Vector2.all(10), - ); - game.world.add(component); - await game.ready(); - game.camera.viewfinder - ..position = Vector2(100, 50) - ..zoom = 2; - - final point = localToCanvas( - component, - Vector2(5, 0), - camera: game.camera, - ); - expect(point, closeToVector(Vector2(430, 320))); - }); - - testWithFlameGame('applies the transforms of all ancestors', (game) async { - final child = PositionComponent(position: Vector2(10, 0)); - final parent = PositionComponent( - position: Vector2(20, 0), - angle: pi / 2, - scale: Vector2.all(2), - children: [child], - ); - game.world.add(parent); - await game.ready(); - - final point = localToCanvas(child, Vector2.zero(), camera: game.camera); - expect(point, closeToVector(Vector2(420, 320))); - }); - - testWithFlameGame('maps viewport components without the viewfinder', ( - game, - ) async { - final hud = PositionComponent(position: Vector2(5, 7)); - game.camera.viewport.add(hud); - await game.ready(); - game.camera.viewfinder.zoom = 2; - - expect(localToCanvas(hud, Vector2(1, 1)), closeToVector(Vector2(6, 8))); - }); - - testWithFlameGame('maps viewfinder components through the camera', ( - game, - ) async { - final component = PositionComponent(position: Vector2(10, 0)); - game.camera.viewfinder.add(component); - await game.ready(); - game.camera.viewfinder.zoom = 2; - - expect( - localToCanvas(component, Vector2.zero()), - closeToVector(Vector2(420, 300)), - ); - }); - - testWithFlameGame('maps components outside of worlds directly', ( - game, - ) async { - final component = PositionComponent(position: Vector2(3, 4)); - game.add(component); - await game.ready(); - - expect( - localToCanvas(component, Vector2.zero()), - closeToVector(Vector2(3, 4)), - ); - }); - - testWithFlameGame('returns null for a camera of another world', ( - game, - ) async { - final component = PositionComponent(); - final otherWorld = World(); - final otherCamera = CameraComponent(world: otherWorld); - game.world.add(component); - game.addAll([otherWorld, otherCamera]); - await game.ready(); - - expect(localToCanvas(component, Vector2.zero()), isNull); - expect( - localToCanvas(component, Vector2.zero(), camera: otherCamera), - isNull, - ); - }); - }); - - group('camerasFor', () { - testWithFlameGame('finds the cameras looking at the world', (game) async { - final component = PositionComponent(); - final hud = PositionComponent(); - final secondCamera = CameraComponent(world: game.world); - game.world.add(component); - game.camera.viewport.add(hud); - game.add(secondCamera); - await game.ready(); - - expect(camerasFor(component), [game.camera, secondCamera]); - expect(camerasFor(hud), [null]); - }); - }); - - group('GizmoGeometry', () { - testWithFlameGame('describes the outline, anchor and axes', (game) async { - final component = PositionComponent( - position: Vector2(0, 0), - size: Vector2(20, 10), - anchor: Anchor.center, - angle: pi / 2, - ); - game.world.add(component); - await game.ready(); - - final geometry = GizmoGeometry.of(component).single; - expect(geometry.anchor, _closeToOffset(const Offset(400, 300))); - expect(geometry.xAxis, _closeToOffset(const Offset(0, 1))); - expect(geometry.yAxis, _closeToOffset(const Offset(-1, 0))); - // Rotated by 90 degrees, the 20x10 outline becomes 10x20. - expect(geometry.corners[0], _closeToOffset(const Offset(405, 290))); - expect(geometry.corners[2], _closeToOffset(const Offset(395, 310))); - }); - }); -} - -Matcher _closeToOffset(Offset expected) { - return predicate( - (offset) => (offset - expected).distance < 1e-6, - 'is close to $expected', - ); -} diff --git a/packages/flame_studio/test/helpers/helpers.dart b/packages/flame_studio/test/helpers/helpers.dart new file mode 100644 index 00000000000..b15fe650a4f --- /dev/null +++ b/packages/flame_studio/test/helpers/helpers.dart @@ -0,0 +1 @@ +export 'pump_app.dart'; diff --git a/packages/flame_studio/test/helpers/pump_app.dart b/packages/flame_studio/test/helpers/pump_app.dart new file mode 100644 index 00000000000..19b6e2e246a --- /dev/null +++ b/packages/flame_studio/test/helpers/pump_app.dart @@ -0,0 +1,70 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockProjectRepository() extends Mock implements ProjectRepository; + +class _MockComponentRepository() extends Mock implements ComponentRepository; + +class _MockEditorPreferencesRepository() + extends Mock + implements EditorPreferencesRepository { + this { + when( + () => getComponentZoom( + projectPath: any(named: 'projectPath'), + componentName: any(named: 'componentName'), + ), + ).thenAnswer((_) async => EditorPreferencesRepository.defaultZoom); + when( + () => setComponentZoom( + projectPath: any(named: 'projectPath'), + componentName: any(named: 'componentName'), + zoom: any(named: 'zoom'), + ), + ).thenAnswer((_) async {}); + } +} + +extension PumpApp on WidgetTester { + /// Pumps [widget] wrapped in the app-level dependencies (theme, providers). + /// + /// Add repository/bloc providers here as they are introduced so that every + /// widget test gets the same environment. + Future pumpApp( + Widget widget, { + ProjectRepository? projectRepository, + ComponentRepository? componentRepository, + EditorPreferencesRepository? editorPreferencesRepository, + }) { + return pumpWidget( + MultiRepositoryProvider( + providers: [ + RepositoryProvider.value( + value: projectRepository ?? _MockProjectRepository(), + ), + RepositoryProvider.value( + value: componentRepository ?? _MockComponentRepository(), + ), + RepositoryProvider.value( + value: + editorPreferencesRepository ?? + _MockEditorPreferencesRepository(), + ), + ], + child: MaterialApp(home: widget), + ), + ); + } + + /// Pumps frames until a route transition has finished. + /// + /// Use instead of `pumpAndSettle` when the route contains a `GameWidget`, + /// whose game loop never settles. + Future pumpRouteTransition() async { + await pump(); + await pump(const Duration(seconds: 1)); + } +} diff --git a/packages/flame_studio/test/home/bloc/home_bloc_test.dart b/packages/flame_studio/test/home/bloc/home_bloc_test.dart new file mode 100644 index 00000000000..ba71f9dfe57 --- /dev/null +++ b/packages/flame_studio/test/home/bloc/home_bloc_test.dart @@ -0,0 +1,148 @@ +import 'package:bloc_test/bloc_test.dart'; +import 'package:flame_studio/home/home.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockProjectRepository() extends Mock implements ProjectRepository; + +void main() { + group(HomeBloc, () { + const projectA = Project(path: '/a'); + const projectB = Project(path: '/b'); + + late ProjectRepository projectRepository; + + setUpAll(() => registerFallbackValue(projectA)); + + setUp(() { + projectRepository = _MockProjectRepository(); + }); + + HomeBloc buildBloc() => HomeBloc(projectRepository: projectRepository); + + test('initial state is HomeState', () { + expect(buildBloc().state, equals(const HomeState())); + }); + + group(HomeRecentProjectsRequested, () { + blocTest( + 'emits [loading, ready] with the recent projects', + setUp: () => + when(projectRepository.getRecentProjects) + .thenAnswer((_) async => [projectA]), + build: buildBloc, + act: (bloc) => bloc.add(const HomeRecentProjectsRequested()), + expect: () => const [ + HomeState(status: HomeStatus.loading), + HomeState(status: HomeStatus.ready, recentProjects: [projectA]), + ], + ); + + blocTest( + 'emits [loading, failure] when loading fails', + setUp: () => + when(projectRepository.getRecentProjects).thenThrow(Exception()), + build: buildBloc, + act: (bloc) => bloc.add(const HomeRecentProjectsRequested()), + expect: () => const [ + HomeState(status: HomeStatus.loading), + HomeState(status: HomeStatus.failure), + ], + ); + }); + + group(HomeOpenProjectRequested, () { + blocTest( + 'emits nothing when the picker is cancelled', + setUp: () => + when(projectRepository.pickProject).thenAnswer((_) async => null), + build: buildBloc, + act: (bloc) => bloc.add(const HomeOpenProjectRequested()), + expect: () => const [], + verify: (_) => verifyNever(() => projectRepository.openProject(any())), + ); + + blocTest( + 'opens the picked project', + setUp: () { + when(projectRepository.pickProject).thenAnswer((_) async => projectA); + when(() => projectRepository.openProject(projectA)) + .thenAnswer((_) async {}); + when(projectRepository.getRecentProjects) + .thenAnswer((_) async => [projectA]); + }, + build: buildBloc, + act: (bloc) => bloc.add(const HomeOpenProjectRequested()), + expect: () => const [ + HomeState( + status: HomeStatus.opened, + openedProject: projectA, + recentProjects: [projectA], + ), + ], + ); + + blocTest( + 'emits failure when picking fails', + setUp: () => when(projectRepository.pickProject).thenThrow(Exception()), + build: buildBloc, + act: (bloc) => bloc.add(const HomeOpenProjectRequested()), + expect: () => const [HomeState(status: HomeStatus.failure)], + ); + }); + + group(HomeRecentProjectSelected, () { + blocTest( + 'opens the selected project', + setUp: () { + when(() => projectRepository.openProject(projectB)) + .thenAnswer((_) async {}); + when(projectRepository.getRecentProjects) + .thenAnswer((_) async => [projectB, projectA]); + }, + build: buildBloc, + act: (bloc) => bloc.add(const HomeRecentProjectSelected(projectB)), + expect: () => const [ + HomeState( + status: HomeStatus.opened, + openedProject: projectB, + recentProjects: [projectB, projectA], + ), + ], + ); + + blocTest( + 'emits projectNotFound with the refreshed recent projects', + setUp: () { + when(() => projectRepository.openProject(projectB)) + .thenThrow(const ProjectNotFoundException(projectB)); + when(projectRepository.getRecentProjects) + .thenAnswer((_) async => [projectA]); + }, + build: buildBloc, + seed: () => const HomeState( + status: HomeStatus.ready, + recentProjects: [projectA, projectB], + ), + act: (bloc) => bloc.add(const HomeRecentProjectSelected(projectB)), + expect: () => const [ + HomeState( + status: HomeStatus.projectNotFound, + recentProjects: [projectA], + ), + ], + ); + + blocTest( + 'emits failure when opening fails', + setUp: () => + when(() => projectRepository.openProject(projectB)) + .thenThrow(Exception()), + build: buildBloc, + act: (bloc) => bloc.add(const HomeRecentProjectSelected(projectB)), + expect: () => const [HomeState(status: HomeStatus.failure)], + ); + }); + }); +} diff --git a/packages/flame_studio/test/home/view/home_page_test.dart b/packages/flame_studio/test/home/view/home_page_test.dart new file mode 100644 index 00000000000..1e72ab34ac0 --- /dev/null +++ b/packages/flame_studio/test/home/view/home_page_test.dart @@ -0,0 +1,161 @@ +import 'package:bloc_test/bloc_test.dart'; +import 'package:flame_studio/home/home.dart'; +import 'package:flame_studio/home/widgets/widgets.dart'; +import 'package:flame_studio/project/project.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +import '../../helpers/helpers.dart'; + +class _MockProjectRepository() extends Mock implements ProjectRepository; + +class _MockComponentRepository() extends Mock implements ComponentRepository; + +class _MockHomeBloc() + extends MockBloc + implements HomeBloc; + +void main() { + const project = Project(path: '/projects/my_game'); + + group(HomePage, () { + testWidgets('loads the recent projects', (tester) async { + final projectRepository = _MockProjectRepository(); + when(projectRepository.getRecentProjects) + .thenAnswer((_) async => [project]); + + await tester.pumpApp( + const HomePage(), + projectRepository: projectRepository, + ); + await tester.pumpAndSettle(); + + expect(find.byType(HomeView), findsOneWidget); + expect(find.text('my_game'), findsOneWidget); + }); + }); + + group(HomeView, () { + late HomeBloc homeBloc; + + setUp(() { + homeBloc = _MockHomeBloc(); + when(() => homeBloc.state).thenReturn(const HomeState()); + }); + + Widget buildSubject() => + BlocProvider.value(value: homeBloc, child: const HomeView()); + + testWidgets('shows an empty message without recent projects', ( + tester, + ) async { + await tester.pumpApp(buildSubject()); + + expect(find.text('No recent projects'), findsOneWidget); + }); + + testWidgets('shows the recent projects', (tester) async { + when(() => homeBloc.state).thenReturn( + const HomeState( + status: HomeStatus.ready, + recentProjects: [ + project, + Project(path: '/other'), + ], + ), + ); + + await tester.pumpApp(buildSubject()); + + expect(find.byType(RecentProjectTile), findsNWidgets(2)); + expect(find.text('my_game'), findsOneWidget); + expect(find.text('/projects/my_game'), findsOneWidget); + }); + + testWidgets('adds HomeOpenProjectRequested when tapping open', ( + tester, + ) async { + await tester.pumpApp(buildSubject()); + + await tester.tap(find.text('Open project')); + + verify(() => homeBloc.add(const HomeOpenProjectRequested())).called(1); + }); + + testWidgets('adds HomeRecentProjectSelected when tapping a recent', ( + tester, + ) async { + when(() => homeBloc.state).thenReturn( + const HomeState(status: HomeStatus.ready, recentProjects: [project]), + ); + + await tester.pumpApp(buildSubject()); + await tester.tap(find.byType(RecentProjectTile)); + + verify(() => homeBloc.add(const HomeRecentProjectSelected(project))) + .called(1); + }); + + testWidgets( + 'navigates to the project and reloads recent projects when coming back', + (tester) async { + whenListen( + homeBloc, + Stream.value( + const HomeState(status: HomeStatus.opened, openedProject: project), + ), + ); + + final componentRepository = _MockComponentRepository(); + when(() => componentRepository.getComponents(project.path)) + .thenAnswer((_) async => []); + + await tester.pumpApp( + buildSubject(), + componentRepository: componentRepository, + ); + await tester.pumpAndSettle(); + + expect(find.byType(ProjectPage), findsOneWidget); + + await tester.pageBack(); + await tester.pumpAndSettle(); + + expect(find.byType(ProjectPage), findsNothing); + verify(() => homeBloc.add(const HomeRecentProjectsRequested())) + .called(1); + }, + ); + + testWidgets('shows a message when the project is not found', ( + tester, + ) async { + whenListen( + homeBloc, + Stream.value(const HomeState(status: HomeStatus.projectNotFound)), + initialState: const HomeState(), + ); + + await tester.pumpApp(buildSubject()); + await tester.pump(); + + expect(find.text('Project folder not found'), findsOneWidget); + }); + + testWidgets('shows a message on failure', (tester) async { + whenListen( + homeBloc, + Stream.value(const HomeState(status: HomeStatus.failure)), + initialState: const HomeState(), + ); + + await tester.pumpApp(buildSubject()); + await tester.pump(); + + expect(find.text('Something went wrong'), findsOneWidget); + }); + }); +} diff --git a/packages/flame_studio/test/move_drag_test.dart b/packages/flame_studio/test/move_drag_test.dart deleted file mode 100644 index 13276b609db..00000000000 --- a/packages/flame_studio/test/move_drag_test.dart +++ /dev/null @@ -1,178 +0,0 @@ -import 'dart:math'; - -import 'package:flame/components.dart'; -import 'package:flame_studio/src/core/gizmo/gizmo_geometry.dart'; -import 'package:flame_studio/src/core/gizmo/move_drag.dart'; -import 'package:flame_test/flame_test.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('GizmoGeometry.handleAt', () { - const geometry = GizmoGeometry( - corners: [], - anchor: Offset(100, 100), - xAxis: Offset(1, 0), - yAxis: Offset(0, 1), - ); - - test('finds the handles near the pointer', () { - expect(geometry.handleAt(const Offset(130, 102)), GizmoHandle.x); - expect(geometry.handleAt(const Offset(98, 130)), GizmoHandle.y); - expect(geometry.handleAt(const Offset(113, 113)), GizmoHandle.free); - expect(geometry.handleAt(const Offset(200, 200)), isNull); - expect(geometry.handleAt(const Offset(150, 100)), isNull); - }); - - test('picks the nearest axis where they meet', () { - expect(geometry.handleAt(const Offset(104, 101)), GizmoHandle.x); - expect(geometry.handleAt(const Offset(101, 104)), GizmoHandle.y); - }); - }); - - group('MoveDrag', () { - testWithFlameGame('converts canvas drags through the camera', ( - game, - ) async { - final component = PositionComponent(position: Vector2(10, 20)); - game.world.add(component); - await game.ready(); - game.camera.viewfinder.zoom = 2; - - final drag = MoveDrag.start( - component, - GizmoHandle.free, - camera: game.camera, - snapStep: 8, - )!; - drag.update(Vector2(20, 10)); - expect(component.position, closeToVector(Vector2(20, 25))); - - drag.update(Vector2(-4, 0)); - expect(component.position, closeToVector(Vector2(8, 20))); - - drag.cancel(); - expect(component.position, closeToVector(Vector2(10, 20))); - }); - - testWithFlameGame('constrains drags to the dragged axis', (game) async { - final component = PositionComponent(angle: pi / 2); - game.world.add(component); - await game.ready(); - - // Rotated by 90 degrees, the local x axis points down. - MoveDrag.start( - component, - GizmoHandle.x, - camera: game.camera, - snapStep: 8, - )!.update(Vector2(20, 10)); - expect(component.position, closeToVector(Vector2(0, 10))); - - MoveDrag.start( - component, - GizmoHandle.y, - camera: game.camera, - snapStep: 8, - )!.update(Vector2(20, 10)); - expect(component.position, closeToVector(Vector2(20, 10))); - }); - - testWithFlameGame('accounts for the transforms of the parent', ( - game, - ) async { - final component = PositionComponent(); - final parent = PositionComponent( - angle: pi / 2, - scale: Vector2.all(2), - children: [component], - ); - game.world.add(parent); - await game.ready(); - - MoveDrag.start( - component, - GizmoHandle.free, - camera: game.camera, - snapStep: 8, - )!.update(Vector2(10, 0)); - // Moving right on the canvas is moving up in the rotated parent, and - // the parent's scale halves the distance. - expect(component.position, closeToVector(Vector2(0, -5))); - }); - - testWithFlameGame('snaps the position to a grid', (game) async { - final component = PositionComponent(position: Vector2(1.5, 2.5)); - game.world.add(component); - await game.ready(); - final drag = MoveDrag.start( - component, - GizmoHandle.free, - camera: game.camera, - snapStep: 8, - )!; - - drag.update(Vector2(10, 3), snap: true); - expect(component.position, closeToVector(Vector2(8, 8))); - - drag.update(Vector2(10, 3)); - expect(component.position, closeToVector(Vector2(11.5, 5.5))); - }); - - testWithFlameGame('snaps the moved coordinate along a parallel axis', ( - game, - ) async { - final component = PositionComponent(position: Vector2(1.5, 2.5)); - game.world.add(component); - await game.ready(); - - MoveDrag.start( - component, - GizmoHandle.x, - camera: game.camera, - snapStep: 8, - )!.update(Vector2(13, 3), snap: true); - expect(component.position, closeToVector(Vector2(16, 2.5))); - }); - - testWithFlameGame('snaps the distance along a rotated axis', (game) async { - final component = PositionComponent( - position: Vector2(1.5, 2.5), - angle: pi / 4, - ); - game.world.add(component); - await game.ready(); - - MoveDrag.start( - component, - GizmoHandle.x, - camera: game.camera, - snapStep: 8, - )!.update(Vector2(10, 10), snap: true); - // The distance moved along the axis, 14.1, snaps to 16. - expect( - component.position, - closeToVector(Vector2(1.5, 2.5) + Vector2.all(16 / sqrt2)), - ); - }); - - testWithFlameGame('cannot drag components whose parent is degenerate', ( - game, - ) async { - final component = PositionComponent(); - game.world.add( - PositionComponent(scale: Vector2.zero(), children: [component]), - ); - await game.ready(); - - expect( - MoveDrag.start( - component, - GizmoHandle.free, - camera: game.camera, - snapStep: 8, - ), - isNull, - ); - }); - }); -} diff --git a/packages/flame_studio/test/palette/bloc/palette_bloc_test.dart b/packages/flame_studio/test/palette/bloc/palette_bloc_test.dart new file mode 100644 index 00000000000..09a382517bc --- /dev/null +++ b/packages/flame_studio/test/palette/bloc/palette_bloc_test.dart @@ -0,0 +1,240 @@ +import 'package:bloc_test/bloc_test.dart'; +import 'package:flame_studio/palette/palette.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockComponentRepository() extends Mock implements ComponentRepository; + +class _MockProjectRepository() extends Mock implements ProjectRepository; + +void main() { + setUpAll(() => registerFallbackValue(const Palette())); + + group(PaletteBloc, () { + const project = Project(path: '/projects/my_game'); + const primary = PaletteColor(name: 'primary', color: 0xFFFF0000); + const accent = PaletteColor(name: 'accent', color: 0xFF00FF00); + const palette = Palette(colors: [primary, accent]); + // Saved without colors, but uses `primary` in the editor. + const edited = RectangleComponent( + name: 'Player', + paint: ComponentPaint(paletteColor: 'primary'), + ); + const enemy = RectangleComponent( + name: 'Enemy', + paint: ComponentPaint(paletteColor: 'primary'), + ); + const loaded = PaletteState( + status: PaletteStatus.ready, + savedPalette: palette, + usage: { + 'primary': ['Enemy', 'Player'], + }, + entries: [ + PaletteEntry(id: 0, color: primary, savedName: 'primary'), + PaletteEntry(id: 1, color: accent, savedName: 'accent'), + ], + ); + + late ComponentRepository componentRepository; + late ProjectRepository projectRepository; + + setUp(() { + componentRepository = _MockComponentRepository(); + projectRepository = _MockProjectRepository(); + when(() => componentRepository.getPalette(project.path)) + .thenAnswer((_) async => palette); + when(() => componentRepository.getComponents(project.path)).thenAnswer( + (_) async => const [enemy, RectangleComponent(name: 'Player')], + ); + when( + () => projectRepository.getSettings(project), + ).thenAnswer((_) async => const ProjectSettings(outputPath: 'lib/game')); + when(() => componentRepository.savePalette(any(), any())) + .thenAnswer((_) async {}); + when(() => componentRepository.writePaletteCode(any(), any(), any())) + .thenAnswer((_) async {}); + }); + + PaletteBloc buildBloc() => PaletteBloc( + project: project, + editedComponent: edited, + componentRepository: componentRepository, + projectRepository: projectRepository, + ); + + /// A bloc whose palette was loaded, with entries 0 and 1. + Future loadedBloc() async { + final bloc = buildBloc()..add(const PaletteStarted()); + await bloc.stream.firstWhere((s) => s.status == PaletteStatus.ready); + return bloc; + } + + blocTest( + 'PaletteStarted loads the palette and which components use it, with ' + 'the unsaved changes of the edited component', + build: buildBloc, + act: (bloc) => bloc.add(const PaletteStarted()), + expect: () => const [PaletteState(status: PaletteStatus.loading), loaded], + verify: (bloc) { + expect(bloc.state.palette, equals(palette)); + expect(bloc.state.hasChanges, isFalse); + expect(bloc.state.usersOf(bloc.state.entries[0]), ['Enemy', 'Player']); + expect(bloc.state.usersOf(bloc.state.entries[1]), isEmpty); + }, + ); + + blocTest( + 'PaletteStarted fails when the palette can not be loaded', + setUp: () => + when(() => componentRepository.getPalette(project.path)) + .thenThrow(Exception()), + build: buildBloc, + act: (bloc) => bloc.add(const PaletteStarted()), + expect: () => const [ + PaletteState(status: PaletteStatus.loading), + PaletteState(status: PaletteStatus.failure), + ], + ); + + test('ignores edits before loading', () async { + final bloc = buildBloc() + ..add(const PaletteColorAdded()) + ..add(const PaletteColorRemoved(0)) + ..add(const PaletteColorValueChanged(0, 1)); + await pumpEventQueue(); + + expect(bloc.state, equals(const PaletteState())); + expect(bloc.state.canSave, isFalse); + }); + + test('PaletteColorAdded adds a white color with a unique name', () async { + final bloc = await loadedBloc(); + bloc.add(const PaletteColorAdded()); + await pumpEventQueue(); + + expect( + bloc.state.entries.last, + equals( + const PaletteEntry( + id: 2, + color: PaletteColor(name: 'color1', color: 0xFFFFFFFF), + ), + ), + ); + expect(bloc.state.hasChanges, isTrue); + expect(bloc.state.usersOf(bloc.state.entries.last), isEmpty); + }); + + test('PaletteColorRenamed renames colors that are not used', () async { + final bloc = await loadedBloc(); + bloc + ..add(const PaletteColorRenamed(1, 'highlight')) + ..add(const PaletteColorRenamed(0, 'main')); + await pumpEventQueue(); + + expect( + bloc.state.palette.colors.map((c) => c.name), + equals(['primary', 'highlight']), + ); + }); + + test( + 'PaletteColorRenamed keeps invalid names, which prevent saving', + () async { + final bloc = await loadedBloc(); + bloc.add(const PaletteColorRenamed(1, 'primary')); + await pumpEventQueue(); + + expect(bloc.state.palette.colors.last.name, equals('primary')); + expect(bloc.state.canSave, isFalse); + }, + ); + + test('PaletteColorValueChanged changes any color', () async { + final bloc = await loadedBloc(); + bloc.add(const PaletteColorValueChanged(0, 0xFF0000FF)); + await pumpEventQueue(); + + expect(bloc.state.palette.colorOf('primary'), equals(0xFF0000FF)); + }); + + test('PaletteColorRemoved removes colors that are not used', () async { + final bloc = await loadedBloc(); + bloc + ..add(const PaletteColorRemoved(0)) + ..add(const PaletteColorRemoved(1)); + await pumpEventQueue(); + + expect(bloc.state.palette, equals(const Palette(colors: [primary]))); + }); + + test('PaletteSaveRequested saves the palette and its code', () async { + final bloc = await loadedBloc(); + bloc + ..add(const PaletteColorRenamed(1, 'highlight')) + ..add(const PaletteSaveRequested()); + await bloc.stream.firstWhere((s) => s.status == PaletteStatus.saved); + + const saved = Palette( + colors: [ + primary, + PaletteColor(name: 'highlight', color: 0xFF00FF00), + ], + ); + verify(() => componentRepository.savePalette(project.path, saved)) + .called(1); + verify( + () => componentRepository.writePaletteCode( + project.path, + 'lib/game', + saved, + ), + ).called(1); + expect(bloc.state.savedPalette, equals(saved)); + expect(bloc.state.entries.last.savedName, equals('highlight')); + expect(bloc.state.hasChanges, isFalse); + }); + + test('PaletteSaveRequested does nothing with invalid names', () async { + final bloc = await loadedBloc(); + bloc + ..add(const PaletteColorRenamed(1, 'class')) + ..add(const PaletteSaveRequested()); + await pumpEventQueue(); + + verifyNever(() => componentRepository.savePalette(any(), any())); + }); + + for (final (exception, status) in [ + (const GeneratedFileConflictException('x'), PaletteStatus.codeConflict), + (Exception(), PaletteStatus.codeFailure), + ]) { + test('PaletteSaveRequested reports $status when the code is not ' + 'generated', () async { + when(() => componentRepository.writePaletteCode(any(), any(), any())) + .thenThrow(exception); + final bloc = await loadedBloc(); + bloc.add(const PaletteSaveRequested()); + await pumpEventQueue(); + + expect(bloc.state.status, equals(status)); + expect(bloc.state.status.isSaved, isTrue); + }); + } + + test('PaletteSaveRequested fails when the palette is not saved', () async { + when(() => componentRepository.savePalette(any(), any())) + .thenThrow(Exception()); + final bloc = await loadedBloc(); + bloc.add(const PaletteSaveRequested()); + await pumpEventQueue(); + + expect(bloc.state.status, equals(PaletteStatus.failure)); + verifyNever( + () => componentRepository.writePaletteCode(any(), any(), any()), + ); + }); + }); +} diff --git a/packages/flame_studio/test/palette/view/palette_dialog_test.dart b/packages/flame_studio/test/palette/view/palette_dialog_test.dart new file mode 100644 index 00000000000..9e87b6c8fb5 --- /dev/null +++ b/packages/flame_studio/test/palette/view/palette_dialog_test.dart @@ -0,0 +1,222 @@ +import 'dart:async'; + +import 'package:bloc_test/bloc_test.dart'; +import 'package:flame_studio/palette/palette.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +import '../../helpers/helpers.dart'; + +class _MockComponentRepository() extends Mock implements ComponentRepository; + +class _MockPaletteBloc() + extends MockBloc + implements PaletteBloc; + +void main() { + const project = Project(path: '/projects/my_game'); + const component = RectangleComponent(name: 'Player'); + const primary = PaletteColor(name: 'primary', color: 0xFFFF0000); + const accent = PaletteColor(name: 'accent', color: 0xFF00FF00); + + setUpAll(() => registerFallbackValue(const PaletteStarted())); + + group(PaletteDialog, () { + testWidgets('show opens the dialog with the stored palette', ( + tester, + ) async { + final componentRepository = _MockComponentRepository(); + when(() => componentRepository.getPalette(project.path)) + .thenAnswer((_) async => const Palette(colors: [primary])); + when(() => componentRepository.getComponents(project.path)) + .thenAnswer((_) async => const []); + + await tester.pumpApp( + Builder( + builder: (context) => TextButton( + onPressed: () => PaletteDialog.show( + context, + project: project, + component: component, + ), + child: const Text('open'), + ), + ), + componentRepository: componentRepository, + ); + + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + + expect(find.byType(PaletteView), findsOneWidget); + expect(find.widgetWithText(TextFormField, 'primary'), findsOneWidget); + }); + }); + + group(PaletteView, () { + const ready = PaletteState( + status: PaletteStatus.ready, + savedPalette: Palette(colors: [primary, accent]), + usage: { + 'primary': ['Enemy', 'Player'], + }, + entries: [ + PaletteEntry(id: 0, color: primary, savedName: 'primary'), + PaletteEntry(id: 1, color: accent, savedName: 'accent'), + ], + ); + + late PaletteBloc bloc; + + setUp(() { + bloc = _MockPaletteBloc(); + when(() => bloc.state).thenReturn(ready); + }); + + Widget buildSubject() => Scaffold( + body: BlocProvider.value(value: bloc, child: const PaletteView()), + ); + + testWidgets('shows a progress indicator while loading', (tester) async { + when(() => bloc.state) + .thenReturn(const PaletteState(status: PaletteStatus.loading)); + await tester.pumpApp(buildSubject()); + + expect(find.byType(CircularProgressIndicator), findsOneWidget); + }); + + testWidgets('explains an empty palette', (tester) async { + when(() => bloc.state) + .thenReturn(const PaletteState(status: PaletteStatus.ready)); + await tester.pumpApp(buildSubject()); + + expect(find.textContaining('No colors yet'), findsOneWidget); + }); + + testWidgets('locks the colors used by components', (tester) async { + await tester.pumpApp(buildSubject()); + + expect(find.text('Used by Enemy, Player'), findsOneWidget); + final fields = tester + .widgetList(find.byType(TextField)) + .toList(); + expect(fields[0].readOnly, isTrue); + expect(fields[1].readOnly, isFalse); + + final removeButtons = tester + .widgetList( + find.widgetWithIcon(IconButton, Icons.delete_outline), + ) + .toList(); + expect(removeButtons[0].onPressed, isNull); + expect(removeButtons[1].onPressed, isNotNull); + }); + + testWidgets('dispatches edits', (tester) async { + await tester.pumpApp(buildSubject()); + + await tester.enterText(find.byType(TextField).last, 'highlight'); + await tester.tap( + find.widgetWithIcon(IconButton, Icons.delete_outline).last, + ); + await tester.tap(find.text('Add color')); + await tester.tap(find.text('Save')); + + verify(() => bloc.add(const PaletteColorRenamed(1, 'highlight'))) + .called(1); + verify(() => bloc.add(const PaletteColorRemoved(1))).called(1); + verify(() => bloc.add(const PaletteColorAdded())).called(1); + verify(() => bloc.add(const PaletteSaveRequested())).called(1); + }); + + testWidgets('shows name errors and disables saving', (tester) async { + when(() => bloc.state).thenReturn( + ready.copyWith( + entries: const [ + PaletteEntry(id: 0, color: primary, savedName: 'primary'), + PaletteEntry(id: 1, color: PaletteColor(name: 'primary', color: 0)), + PaletteEntry(id: 2, color: PaletteColor(name: '1st', color: 0)), + ], + ), + ); + await tester.pumpApp(buildSubject()); + + expect(find.text('Another color has this name'), findsOneWidget); + expect(find.text('Must be a valid Dart identifier'), findsOneWidget); + expect( + tester.widget(find.byType(FilledButton)).onPressed, + isNull, + ); + }); + + testWidgets('shows a failure', (tester) async { + when(() => bloc.state) + .thenReturn(ready.copyWith(status: PaletteStatus.failure)); + await tester.pumpApp(buildSubject()); + + expect(find.text('Something went wrong'), findsOneWidget); + }); + + for (final (status, message) in [ + (PaletteStatus.saved, null), + (PaletteStatus.codeConflict, 'not generated by the editor'), + (PaletteStatus.codeFailure, 'could not be generated'), + ]) { + testWidgets('pops with the palette when $status', (tester) async { + final saved = ready.copyWith(status: status); + whenListen(bloc, Stream.value(saved), initialState: ready); + Palette? result; + + await tester.pumpApp( + Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () async => result = await showDialog( + context: context, + builder: (_) => BlocProvider.value( + value: bloc, + child: const PaletteView(), + ), + ), + child: const Text('open'), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + + expect(find.byType(PaletteView), findsNothing); + expect(result, equals(saved.palette)); + if (message != null) { + expect(find.textContaining(message), findsOneWidget); + } + }); + } + + testWidgets('cancel pops without a palette', (tester) async { + Palette? result = const Palette(colors: [primary]); + await tester.pumpApp( + Builder( + builder: (context) => TextButton( + onPressed: () async => result = await showDialog( + context: context, + builder: (_) => + BlocProvider.value(value: bloc, child: const PaletteView()), + ), + child: const Text('open'), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + + expect(result, isNull); + }); + }); +} diff --git a/packages/flame_studio/test/project/bloc/project_bloc_test.dart b/packages/flame_studio/test/project/bloc/project_bloc_test.dart new file mode 100644 index 00000000000..334cd64477a --- /dev/null +++ b/packages/flame_studio/test/project/bloc/project_bloc_test.dart @@ -0,0 +1,277 @@ +import 'package:bloc_test/bloc_test.dart'; +import 'package:flame_studio/project/project.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockComponentRepository() extends Mock implements ComponentRepository; + +class _MockProjectRepository() extends Mock implements ProjectRepository; + +void main() { + group(ProjectBloc, () { + const project = Project(path: '/projects/my_game'); + const player = RectangleComponent(name: 'Player'); + const enemy = RectangleComponent(name: 'Enemy'); + + late ComponentRepository componentRepository; + late ProjectRepository projectRepository; + + setUp(() { + componentRepository = _MockComponentRepository(); + projectRepository = _MockProjectRepository(); + when( + () => projectRepository.getSettings(project), + ).thenAnswer((_) async => const ProjectSettings(outputPath: 'lib/game')); + }); + + ProjectBloc buildBloc() => ProjectBloc( + project: project, + componentRepository: componentRepository, + projectRepository: projectRepository, + ); + + test('initial state is ProjectState', () { + expect(buildBloc().state, equals(const ProjectState())); + }); + + group(ProjectComponentsRequested, () { + blocTest( + 'emits [loading, ready] with the components', + setUp: () => + when(() => componentRepository.getComponents(project.path)) + .thenAnswer((_) async => [enemy, player]), + build: buildBloc, + act: (bloc) => bloc.add(const ProjectComponentsRequested()), + expect: () => const [ + ProjectState(status: ProjectStatus.loading), + ProjectState( + status: ProjectStatus.ready, + components: [enemy, player], + ), + ], + ); + + blocTest( + 'emits [loading, failure] when loading fails', + setUp: () => + when(() => componentRepository.getComponents(project.path)) + .thenThrow(Exception()), + build: buildBloc, + act: (bloc) => bloc.add(const ProjectComponentsRequested()), + expect: () => const [ + ProjectState(status: ProjectStatus.loading), + ProjectState(status: ProjectStatus.failure), + ], + ); + }); + + group(ProjectComponentCreateRequested, () { + blocTest( + 'creates polygons with the requested shape', + setUp: () { + when( + () => componentRepository.createComponent( + project.path, + 'Player', + ComponentType.polygon, + polygonShape: PolygonShape.square, + ), + ).thenAnswer((_) async => const PolygonComponent(name: 'Player')); + when(() => componentRepository.getComponents(project.path)) + .thenAnswer((_) async => []); + }, + build: buildBloc, + act: (bloc) => bloc.add( + const ProjectComponentCreateRequested( + 'Player', + ComponentType.polygon, + polygonShape: PolygonShape.square, + ), + ), + verify: (_) => verify( + () => componentRepository.createComponent( + project.path, + 'Player', + ComponentType.polygon, + polygonShape: PolygonShape.square, + ), + ).called(1), + ); + + blocTest( + 'emits created with the new component and reloaded components', + setUp: () { + when( + () => componentRepository.createComponent( + project.path, + 'Player', + ComponentType.rectangle, + ), + ).thenAnswer((_) async => player); + when(() => componentRepository.getComponents(project.path)) + .thenAnswer((_) async => [player]); + }, + build: buildBloc, + act: (bloc) => bloc.add( + const ProjectComponentCreateRequested( + 'Player', + ComponentType.rectangle, + ), + ), + expect: () => const [ + ProjectState( + status: ProjectStatus.created, + components: [player], + createdComponent: player, + ), + ], + ); + + blocTest( + 'emits invalidName when the name is invalid', + setUp: () => when( + () => componentRepository.createComponent( + project.path, + '1', + ComponentType.rectangle, + ), + ).thenThrow(const InvalidComponentNameException('1')), + build: buildBloc, + act: (bloc) => bloc.add( + const ProjectComponentCreateRequested('1', ComponentType.rectangle), + ), + expect: () => const [ProjectState(status: ProjectStatus.invalidName)], + ); + + blocTest( + 'emits alreadyExists when the name is taken', + setUp: () => when( + () => componentRepository.createComponent( + project.path, + 'Player', + ComponentType.rectangle, + ), + ).thenThrow(const ComponentAlreadyExistsException('Player')), + build: buildBloc, + act: (bloc) => bloc.add( + const ProjectComponentCreateRequested( + 'Player', + ComponentType.rectangle, + ), + ), + expect: () => const [ProjectState(status: ProjectStatus.alreadyExists)], + ); + + blocTest( + 'emits classConflict when the class of the name is taken', + setUp: () => + when( + () => componentRepository.createComponent( + project.path, + 'player_ship_head', + ComponentType.rectangle, + ), + ).thenThrow( + const ComponentClassConflictException( + 'player_ship_head', + 'player_ship', + ), + ), + build: buildBloc, + act: (bloc) => bloc.add( + const ProjectComponentCreateRequested( + 'player_ship_head', + ComponentType.rectangle, + ), + ), + expect: () => const [ + ProjectState( + status: ProjectStatus.classConflict, + conflictingComponent: 'player_ship', + ), + ], + ); + + test('conflictingComponent is cleared when the status changes', () { + const state = ProjectState( + status: ProjectStatus.classConflict, + conflictingComponent: 'player_ship', + ); + + expect(state.copyWith().conflictingComponent, equals('player_ship')); + expect( + state.copyWith(status: ProjectStatus.ready).conflictingComponent, + isNull, + ); + }); + + blocTest( + 'emits failure when creating fails', + setUp: () => when( + () => componentRepository.createComponent( + project.path, + 'Player', + ComponentType.rectangle, + ), + ).thenThrow(Exception()), + build: buildBloc, + act: (bloc) => bloc.add( + const ProjectComponentCreateRequested( + 'Player', + ComponentType.rectangle, + ), + ), + expect: () => const [ProjectState(status: ProjectStatus.failure)], + ); + }); + + group(ProjectComponentDeleteRequested, () { + blocTest( + 'deletes the component and its code and emits the reloaded ' + 'components', + setUp: () { + when( + () => componentRepository.deleteComponent( + project.path, + player, + outputPath: 'lib/game', + ), + ).thenAnswer((_) async {}); + when(() => componentRepository.getComponents(project.path)) + .thenAnswer((_) async => [enemy]); + }, + build: buildBloc, + seed: () => const ProjectState( + status: ProjectStatus.ready, + components: [enemy, player], + ), + act: (bloc) => bloc.add(const ProjectComponentDeleteRequested(player)), + expect: () => const [ + ProjectState(status: ProjectStatus.ready, components: [enemy]), + ], + verify: (_) => verify( + () => componentRepository.deleteComponent( + project.path, + player, + outputPath: 'lib/game', + ), + ).called(1), + ); + + blocTest( + 'emits failure when deleting fails', + setUp: () => when( + () => componentRepository.deleteComponent( + project.path, + player, + outputPath: 'lib/game', + ), + ).thenThrow(Exception()), + build: buildBloc, + act: (bloc) => bloc.add(const ProjectComponentDeleteRequested(player)), + expect: () => const [ProjectState(status: ProjectStatus.failure)], + ); + }); + }); +} diff --git a/packages/flame_studio/test/project/view/project_page_test.dart b/packages/flame_studio/test/project/view/project_page_test.dart new file mode 100644 index 00000000000..57499d54bf8 --- /dev/null +++ b/packages/flame_studio/test/project/view/project_page_test.dart @@ -0,0 +1,413 @@ +import 'package:bloc_test/bloc_test.dart'; +import 'package:flame_studio/component_editor/component_editor.dart'; +import 'package:flame_studio/project/project.dart'; +import 'package:flame_studio/project/widgets/widgets.dart'; +import 'package:flame_studio/project_settings/project_settings.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +import '../../helpers/helpers.dart'; + +class _MockComponentRepository() extends Mock implements ComponentRepository; + +class _MockProjectRepository() extends Mock implements ProjectRepository; + +class _MockProjectBloc() + extends MockBloc + implements ProjectBloc; + +void main() { + const project = Project(path: '/projects/my_game'); + const player = RectangleComponent(name: 'Player'); + + setUpAll(() => registerFallbackValue(const ProjectComponentsRequested())); + + group(ProjectPage, () { + testWidgets('loads the components', (tester) async { + final componentRepository = _MockComponentRepository(); + when(() => componentRepository.getComponents(project.path)) + .thenAnswer((_) async => [player]); + + await tester.pumpApp( + const ProjectPage(project: project), + componentRepository: componentRepository, + ); + await tester.pumpAndSettle(); + + expect(find.byType(ProjectView), findsOneWidget); + expect(find.text('Player'), findsOneWidget); + }); + + testWidgets('route can be pushed and popped', (tester) async { + final componentRepository = _MockComponentRepository(); + when(() => componentRepository.getComponents(project.path)) + .thenAnswer((_) async => []); + + await tester.pumpApp( + Builder( + builder: (context) => TextButton( + onPressed: () => + Navigator.of(context).push(ProjectPage.route(project)), + child: const Text('open'), + ), + ), + componentRepository: componentRepository, + ); + + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.byType(ProjectPage), findsOneWidget); + + await tester.pageBack(); + await tester.pumpAndSettle(); + expect(find.byType(ProjectPage), findsNothing); + }); + }); + + group(ProjectView, () { + late ProjectBloc projectBloc; + late ComponentRepository componentRepository; + late ProjectRepository projectRepository; + + setUp(() { + // The editor opened from the view loads the components and checks + // the generated code too. + componentRepository = _MockComponentRepository(); + projectRepository = _MockProjectRepository(); + when(() => componentRepository.getComponents(project.path)) + .thenAnswer((_) async => [player]); + when(() => componentRepository.getPalette(project.path)) + .thenAnswer((_) async => const Palette()); + when(() => projectRepository.getSettings(project)) + .thenAnswer((_) async => const ProjectSettings()); + when( + () => componentRepository.isComponentCodeUpToDate( + project.path, + const ProjectSettings().outputPath, + player, + ), + ).thenAnswer((_) async => true); + projectBloc = _MockProjectBloc(); + when(() => projectBloc.state) + .thenReturn(const ProjectState(status: ProjectStatus.ready)); + }); + + Widget buildSubject() => BlocProvider.value( + value: projectBloc, + child: const ProjectView(project: project), + ); + + testWidgets('shows the project name', (tester) async { + await tester.pumpApp(buildSubject()); + + expect(find.text('my_game'), findsOneWidget); + }); + + testWidgets('shows a progress indicator while loading', (tester) async { + when(() => projectBloc.state) + .thenReturn(const ProjectState(status: ProjectStatus.loading)); + + await tester.pumpApp(buildSubject()); + + expect(find.byType(CircularProgressIndicator), findsOneWidget); + }); + + testWidgets('shows an empty message without components', (tester) async { + await tester.pumpApp(buildSubject()); + + expect(find.text('No components yet'), findsOneWidget); + }); + + testWidgets('shows the components', (tester) async { + when(() => projectBloc.state).thenReturn( + const ProjectState( + status: ProjectStatus.ready, + components: [ + RectangleComponent(name: 'Enemy'), + player, + ], + ), + ); + + await tester.pumpApp(buildSubject()); + + expect(find.byType(ComponentTile), findsNWidgets(2)); + expect(find.text('Enemy'), findsOneWidget); + expect(find.text('Player'), findsOneWidget); + }); + + testWidgets('opens the settings', (tester) async { + final projectRepository = _MockProjectRepository(); + when(() => projectRepository.getSettings(project)) + .thenAnswer((_) async => const ProjectSettings()); + + await tester.pumpApp( + buildSubject(), + projectRepository: projectRepository, + ); + + await tester.tap(find.byTooltip('Settings')); + await tester.pumpAndSettle(); + + expect(find.byType(ProjectSettingsDialog), findsOneWidget); + }); + + testWidgets( + 'opens the editor on edit and reloads components when coming back', + (tester) async { + when(() => projectBloc.state).thenReturn( + const ProjectState(status: ProjectStatus.ready, components: [player]), + ); + + await tester.pumpApp( + buildSubject(), + componentRepository: componentRepository, + projectRepository: projectRepository, + ); + await tester.tap(find.byTooltip('Edit')); + await tester.pumpRouteTransition(); + + expect(find.byType(ComponentEditorPage), findsOneWidget); + + await tester.pageBack(); + await tester.pumpRouteTransition(); + + verify(() => projectBloc.add(const ProjectComponentsRequested())) + .called(1); + }, + ); + + group('delete', () { + setUp(() { + when(() => projectBloc.state).thenReturn( + const ProjectState(status: ProjectStatus.ready, components: [player]), + ); + }); + + testWidgets('asks for confirmation and deletes when confirmed', ( + tester, + ) async { + await tester.pumpApp(buildSubject()); + await tester.tap(find.byTooltip('Delete')); + await tester.pumpAndSettle(); + + expect(find.byType(DeleteComponentDialog), findsOneWidget); + + await tester.tap(find.widgetWithText(FilledButton, 'Delete')); + await tester.pumpAndSettle(); + + verify( + () => projectBloc.add(const ProjectComponentDeleteRequested(player)), + ).called(1); + }); + + testWidgets('does nothing when cancelled', (tester) async { + await tester.pumpApp(buildSubject()); + await tester.tap(find.byTooltip('Delete')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + + expect(find.byType(DeleteComponentDialog), findsNothing); + verifyNever(() => projectBloc.add(any())); + }); + }); + + group('add', () { + testWidgets('creates a component with the entered name', (tester) async { + await tester.pumpApp(buildSubject()); + await tester.tap(find.text('Add component')); + await tester.pumpAndSettle(); + + await tester.enterText( + find.widgetWithText(TextField, 'Name'), + ' Player ', + ); + await tester.pump(); + await tester.tap(find.text('Create')); + await tester.pumpAndSettle(); + + verify( + () => projectBloc.add( + const ProjectComponentCreateRequested( + 'Player', + ComponentType.rectangle, + ), + ), + ).called(1); + }); + + testWidgets('submits with the keyboard', (tester) async { + await tester.pumpApp(buildSubject()); + await tester.tap(find.text('Add component')); + await tester.pumpAndSettle(); + + await tester.enterText( + find.widgetWithText(TextField, 'Name'), + 'Player', + ); + await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.pumpAndSettle(); + + verify( + () => projectBloc.add( + const ProjectComponentCreateRequested( + 'Player', + ComponentType.rectangle, + ), + ), + ).called(1); + }); + + testWidgets('offers the component types', (tester) async { + await tester.pumpApp(buildSubject()); + await tester.tap(find.text('Add component')); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(DropdownMenu)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Rectangle').last); + await tester.pumpAndSettle(); + + expect(find.text('Rectangle'), findsWidgets); + }); + + testWidgets('does not offer hitboxes, which are only children', ( + tester, + ) async { + await tester.pumpApp(buildSubject()); + await tester.tap(find.text('Add component')); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(DropdownMenu)); + await tester.pumpAndSettle(); + + expect(find.text('Polygon'), findsWidgets); + expect(find.text('Rectangle hitbox'), findsNothing); + expect(find.text('Circle hitbox'), findsNothing); + expect(find.text('Polygon hitbox'), findsNothing); + }); + + testWidgets('asks for the shape of polygons', (tester) async { + await tester.pumpApp(buildSubject()); + await tester.tap(find.text('Add component')); + await tester.pumpAndSettle(); + expect(find.byType(DropdownMenu), findsNothing); + + await tester.enterText(find.widgetWithText(TextField, 'Name'), 'Ship'); + await tester.tap(find.byType(DropdownMenu)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Polygon').last); + await tester.pumpAndSettle(); + await tester.tap(find.byType(DropdownMenu)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Square').last); + await tester.pumpAndSettle(); + await tester.tap(find.text('Create')); + await tester.pumpAndSettle(); + + verify( + () => projectBloc.add( + const ProjectComponentCreateRequested( + 'Ship', + ComponentType.polygon, + polygonShape: PolygonShape.square, + ), + ), + ).called(1); + }); + + testWidgets('disables create while the name is empty', (tester) async { + await tester.pumpApp(buildSubject()); + await tester.tap(find.text('Add component')); + await tester.pumpAndSettle(); + + final create = tester.widget( + find.widgetWithText(FilledButton, 'Create'), + ); + expect(create.onPressed, isNull); + + await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.pumpAndSettle(); + expect(find.byType(AddComponentDialog), findsOneWidget); + }); + + testWidgets('does nothing when cancelled', (tester) async { + await tester.pumpApp(buildSubject()); + await tester.tap(find.text('Add component')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + + expect(find.byType(AddComponentDialog), findsNothing); + verifyNever(() => projectBloc.add(any())); + }); + }); + + testWidgets('opens the editor when a component is created', (tester) async { + whenListen( + projectBloc, + Stream.value( + const ProjectState( + status: ProjectStatus.created, + components: [player], + createdComponent: player, + ), + ), + initialState: const ProjectState(status: ProjectStatus.ready), + ); + + await tester.pumpApp( + buildSubject(), + componentRepository: componentRepository, + projectRepository: projectRepository, + ); + await tester.pumpRouteTransition(); + + expect(find.byType(ComponentEditorPage), findsOneWidget); + expect(find.widgetWithText(AppBar, 'Player'), findsOneWidget); + }); + + testWidgets('shows the conflicting component on classConflict', ( + tester, + ) async { + whenListen( + projectBloc, + Stream.value( + const ProjectState( + status: ProjectStatus.classConflict, + conflictingComponent: 'player_ship', + ), + ), + initialState: const ProjectState(status: ProjectStatus.ready), + ); + + await tester.pumpApp(buildSubject()); + await tester.pump(); + + expect(find.textContaining('"player_ship" component'), findsOneWidget); + }); + + for (final (status, message) in [ + (ProjectStatus.invalidName, 'Component names must start'), + (ProjectStatus.alreadyExists, 'A component with that name already'), + (ProjectStatus.failure, 'Something went wrong'), + ]) { + testWidgets('shows a message on ${status.name}', (tester) async { + whenListen( + projectBloc, + Stream.value(ProjectState(status: status)), + initialState: const ProjectState(status: ProjectStatus.ready), + ); + + await tester.pumpApp(buildSubject()); + await tester.pump(); + + expect(find.textContaining(message), findsOneWidget); + }); + } + }); +} diff --git a/packages/flame_studio/test/project_settings/bloc/project_settings_bloc_test.dart b/packages/flame_studio/test/project_settings/bloc/project_settings_bloc_test.dart new file mode 100644 index 00000000000..e819c2feac8 --- /dev/null +++ b/packages/flame_studio/test/project_settings/bloc/project_settings_bloc_test.dart @@ -0,0 +1,203 @@ +import 'package:bloc_test/bloc_test.dart'; +import 'package:flame_studio/project_settings/project_settings.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockProjectRepository() extends Mock implements ProjectRepository; + +void main() { + group(ProjectSettingsBloc, () { + const project = Project(path: '/projects/my_game'); + const ready = ProjectSettingsState(status: ProjectSettingsStatus.ready); + + late ProjectRepository projectRepository; + + setUpAll(() => registerFallbackValue(const ProjectSettings())); + + setUp(() { + projectRepository = _MockProjectRepository(); + }); + + ProjectSettingsBloc buildBloc() => ProjectSettingsBloc( + project: project, + projectRepository: projectRepository, + ); + + test('initial state is ProjectSettingsState', () { + expect(buildBloc().state, equals(const ProjectSettingsState())); + }); + + group(ProjectSettingsRequested, () { + blocTest( + 'emits [loading, ready] with the stored output path', + setUp: () => when(() => projectRepository.getSettings(project)) + .thenAnswer( + (_) async => const ProjectSettings(outputPath: 'lib/game'), + ), + build: buildBloc, + act: (bloc) => bloc.add(const ProjectSettingsRequested()), + expect: () => const [ + ProjectSettingsState(status: ProjectSettingsStatus.loading), + ProjectSettingsState( + status: ProjectSettingsStatus.ready, + outputPath: 'lib/game', + ), + ], + ); + + blocTest( + 'emits [loading, failure] when loading fails', + setUp: () => + when(() => projectRepository.getSettings(project)) + .thenThrow(Exception()), + build: buildBloc, + act: (bloc) => bloc.add(const ProjectSettingsRequested()), + expect: () => const [ + ProjectSettingsState(status: ProjectSettingsStatus.loading), + ProjectSettingsState(status: ProjectSettingsStatus.failure), + ], + ); + }); + + group(ProjectSettingsOutputPathChanged, () { + blocTest( + 'updates the output path and clears errors', + build: buildBloc, + seed: () => const ProjectSettingsState( + status: ProjectSettingsStatus.invalidOutputPath, + ), + act: (bloc) => bloc.add(const ProjectSettingsOutputPathChanged('lib')), + expect: () => const [ + ProjectSettingsState( + status: ProjectSettingsStatus.ready, + outputPath: 'lib', + ), + ], + ); + }); + + group(ProjectSettingsBrowseRequested, () { + blocTest( + 'emits the picked output path', + setUp: () => + when(() => projectRepository.pickOutputPath(project)) + .thenAnswer((_) async => 'lib/game'), + build: buildBloc, + seed: () => ready, + act: (bloc) => bloc.add(const ProjectSettingsBrowseRequested()), + expect: () => const [ + ProjectSettingsState( + status: ProjectSettingsStatus.ready, + outputPath: 'lib/game', + ), + ], + ); + + blocTest( + 'emits nothing when cancelled', + setUp: () => + when(() => projectRepository.pickOutputPath(project)) + .thenAnswer((_) async => null), + build: buildBloc, + seed: () => ready, + act: (bloc) => bloc.add(const ProjectSettingsBrowseRequested()), + expect: () => const [], + ); + + blocTest( + 'emits invalidOutputPath when picking a folder outside the project', + setUp: () => + when(() => projectRepository.pickOutputPath(project)) + .thenThrow(const InvalidOutputPathException('/other')), + build: buildBloc, + seed: () => ready, + act: (bloc) => bloc.add(const ProjectSettingsBrowseRequested()), + expect: () => const [ + ProjectSettingsState(status: ProjectSettingsStatus.invalidOutputPath), + ], + ); + + blocTest( + 'emits failure when picking fails', + setUp: () => + when(() => projectRepository.pickOutputPath(project)) + .thenThrow(Exception()), + build: buildBloc, + seed: () => ready, + act: (bloc) => bloc.add(const ProjectSettingsBrowseRequested()), + expect: () => const [ + ProjectSettingsState(status: ProjectSettingsStatus.failure), + ], + ); + }); + + group(ProjectSettingsSubmitted, () { + const seed = ProjectSettingsState( + status: ProjectSettingsStatus.ready, + outputPath: 'lib/./game', + ); + const saving = ProjectSettingsState( + status: ProjectSettingsStatus.saving, + outputPath: 'lib/./game', + ); + + blocTest( + 'emits [saving, saved] with the normalized output path', + setUp: () => + when( + () => projectRepository.saveSettings( + project, + const ProjectSettings(outputPath: 'lib/./game'), + ), + ).thenAnswer( + (_) async => const ProjectSettings(outputPath: 'lib/game'), + ), + build: buildBloc, + seed: () => seed, + act: (bloc) => bloc.add(const ProjectSettingsSubmitted()), + expect: () => const [ + saving, + ProjectSettingsState( + status: ProjectSettingsStatus.saved, + outputPath: 'lib/game', + ), + ], + ); + + blocTest( + 'emits [saving, invalidOutputPath] when the path is invalid', + setUp: () => + when(() => projectRepository.saveSettings(project, any())) + .thenThrow(const InvalidOutputPathException('lib/./game')), + build: buildBloc, + seed: () => seed, + act: (bloc) => bloc.add(const ProjectSettingsSubmitted()), + expect: () => const [ + saving, + ProjectSettingsState( + status: ProjectSettingsStatus.invalidOutputPath, + outputPath: 'lib/./game', + ), + ], + ); + + blocTest( + 'emits [saving, failure] when saving fails', + setUp: () => + when(() => projectRepository.saveSettings(project, any())) + .thenThrow(Exception()), + build: buildBloc, + seed: () => seed, + act: (bloc) => bloc.add(const ProjectSettingsSubmitted()), + expect: () => const [ + saving, + ProjectSettingsState( + status: ProjectSettingsStatus.failure, + outputPath: 'lib/./game', + ), + ], + ); + }); + }); +} diff --git a/packages/flame_studio/test/project_settings/view/project_settings_dialog_test.dart b/packages/flame_studio/test/project_settings/view/project_settings_dialog_test.dart new file mode 100644 index 00000000000..fb96701d571 --- /dev/null +++ b/packages/flame_studio/test/project_settings/view/project_settings_dialog_test.dart @@ -0,0 +1,215 @@ +import 'dart:async'; + +import 'package:bloc_test/bloc_test.dart'; +import 'package:flame_studio/project_settings/project_settings.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +import '../../helpers/helpers.dart'; + +class _MockProjectRepository() extends Mock implements ProjectRepository; + +class _MockProjectSettingsBloc() + extends MockBloc + implements ProjectSettingsBloc; + +void main() { + const project = Project(path: '/projects/my_game'); + + setUpAll(() => registerFallbackValue(const ProjectSettingsRequested())); + + group(ProjectSettingsDialog, () { + testWidgets('show opens the dialog with the stored settings', ( + tester, + ) async { + final projectRepository = _MockProjectRepository(); + when( + () => projectRepository.getSettings(project), + ).thenAnswer((_) async => const ProjectSettings(outputPath: 'lib/game')); + + await tester.pumpApp( + Builder( + builder: (context) => TextButton( + onPressed: () => ProjectSettingsDialog.show(context, project), + child: const Text('open'), + ), + ), + projectRepository: projectRepository, + ); + + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + + expect(find.byType(ProjectSettingsView), findsOneWidget); + expect(find.text('Project settings'), findsOneWidget); + expect(find.widgetWithText(TextField, 'lib/game'), findsOneWidget); + }); + }); + + group(ProjectSettingsView, () { + const ready = ProjectSettingsState(status: ProjectSettingsStatus.ready); + + late ProjectSettingsBloc bloc; + + setUp(() { + bloc = _MockProjectSettingsBloc(); + when(() => bloc.state).thenReturn(ready); + }); + + Widget buildSubject() => + BlocProvider.value(value: bloc, child: const ProjectSettingsView()); + + /// Pumps the view inside a dialog so that popping can be observed. + Future pumpDialog(WidgetTester tester) async { + await tester.pumpApp( + Builder( + builder: (context) => TextButton( + onPressed: () => showDialog( + context: context, + builder: (_) => buildSubject(), + ), + child: const Text('open'), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + } + + testWidgets('shows a progress indicator while loading', (tester) async { + when(() => bloc.state).thenReturn( + const ProjectSettingsState(status: ProjectSettingsStatus.loading), + ); + + await tester.pumpApp(buildSubject()); + + expect(find.byType(CircularProgressIndicator), findsOneWidget); + expect(find.byType(TextField), findsNothing); + final save = tester.widget( + find.widgetWithText(FilledButton, 'Save'), + ); + expect(save.onPressed, isNull); + }); + + testWidgets('shows the output path', (tester) async { + await tester.pumpApp(buildSubject()); + + expect(find.widgetWithText(TextField, 'lib/components'), findsOneWidget); + }); + + testWidgets('dispatches changes to the output path', (tester) async { + await tester.pumpApp(buildSubject()); + + await tester.enterText(find.byType(TextField), 'lib/game'); + + verify(() => bloc.add(const ProjectSettingsOutputPathChanged('lib/game'))) + .called(1); + }); + + testWidgets('updates the text field when the output path changes', ( + tester, + ) async { + whenListen( + bloc, + Stream.value( + const ProjectSettingsState( + status: ProjectSettingsStatus.ready, + outputPath: 'lib/picked', + ), + ), + initialState: ready, + ); + + await tester.pumpApp(buildSubject()); + await tester.pump(); + + expect(find.widgetWithText(TextField, 'lib/picked'), findsOneWidget); + }); + + testWidgets('browses for the output path', (tester) async { + await tester.pumpApp(buildSubject()); + + await tester.tap(find.byTooltip('Browse')); + + verify(() => bloc.add(const ProjectSettingsBrowseRequested())).called(1); + }); + + testWidgets('saves on tap', (tester) async { + await tester.pumpApp(buildSubject()); + + await tester.tap(find.text('Save')); + + verify(() => bloc.add(const ProjectSettingsSubmitted())).called(1); + }); + + testWidgets('saves with the keyboard', (tester) async { + await tester.pumpApp(buildSubject()); + + await tester.showKeyboard(find.byType(TextField)); + await tester.testTextInput.receiveAction(TextInputAction.done); + + verify(() => bloc.add(const ProjectSettingsSubmitted())).called(1); + }); + + testWidgets('disables save while the output path is empty', (tester) async { + when(() => bloc.state).thenReturn( + const ProjectSettingsState( + status: ProjectSettingsStatus.ready, + outputPath: ' ', + ), + ); + + await tester.pumpApp(buildSubject()); + await tester.showKeyboard(find.byType(TextField)); + await tester.testTextInput.receiveAction(TextInputAction.done); + + final save = tester.widget( + find.widgetWithText(FilledButton, 'Save'), + ); + expect(save.onPressed, isNull); + verifyNever(() => bloc.add(const ProjectSettingsSubmitted())); + }); + + for (final (status, message) in [ + (ProjectSettingsStatus.invalidOutputPath, 'Must be a folder inside'), + (ProjectSettingsStatus.failure, 'Something went wrong'), + ]) { + testWidgets('shows an error on ${status.name}', (tester) async { + when(() => bloc.state).thenReturn(ProjectSettingsState(status: status)); + + await tester.pumpApp(buildSubject()); + + expect(find.textContaining(message), findsOneWidget); + }); + } + + testWidgets('closes when saved', (tester) async { + final controller = StreamController(); + whenListen(bloc, controller.stream, initialState: ready); + + await pumpDialog(tester); + expect(find.byType(ProjectSettingsView), findsOneWidget); + + controller.add( + const ProjectSettingsState(status: ProjectSettingsStatus.saved), + ); + await tester.pumpAndSettle(); + + expect(find.byType(ProjectSettingsView), findsNothing); + await controller.close(); + }); + + testWidgets('closes on cancel', (tester) async { + await pumpDialog(tester); + + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + + expect(find.byType(ProjectSettingsView), findsNothing); + verifyNever(() => bloc.add(any())); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/code_generation/component_code_generator_test.dart b/packages/flame_studio/test/repositories/component_repository/code_generation/component_code_generator_test.dart new file mode 100644 index 00000000000..53789556153 --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/code_generation/component_code_generator_test.dart @@ -0,0 +1,529 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const _header = ''' +// GENERATED CODE - DO NOT MODIFY BY HAND. +// Generated by Flame Studio. + +// coverage:ignore-file +// ignore_for_file: type=lint + +import 'dart:ui'; + +import 'package:flame/components.dart'; + +'''; + +void main() { + group(ComponentCodeGenerator, () { + const generator = ComponentCodeGenerator(); + + test('fileName is the snake_case name of the component', () { + expect( + generator.fileName(const RectangleComponent(name: 'PlayerShip')), + equals('player_ship.generated.dart'), + ); + }); + + test('generates a root without children', () { + expect( + generator.generate( + const RectangleComponent( + name: 'player', + // The root position is set by whoever uses the component. + position: ComponentPosition(x: 5, y: 5), + size: ComponentSize(width: 10, height: 20.5), + ), + ), + equals(''' +$_header/// The `player` component. +class \$Player extends RectangleComponent { + /// Creates a [\$Player]. + \$Player({super.position, super.angle, super.anchor, super.priority}) + : super( + size: Vector2(10, 20.5), + paint: Paint()..color = const Color(0xFFFFFFFF), + ); +} +'''), + ); + }); + + test('generates a getter for every child, and a class for children ' + 'with children', () { + expect( + generator.generate( + const RectangleComponent( + name: 'player', + children: [ + RectangleComponent( + name: 'head', + position: ComponentPosition(x: 10), + paint: ComponentPaint( + color: 0x8000FF00, + style: PaintStyle.stroke, + ), + children: [ + RectangleComponent( + name: 'eye', + size: ComponentSize(width: 5, height: 5), + ), + ], + ), + RectangleComponent( + name: 'left_arm', + position: ComponentPosition(x: -4, y: 30), + ), + ], + ), + ), + equals(''' +$_header/// The `player` component. +class \$Player extends RectangleComponent { + /// Creates a [\$Player]. + \$Player({super.position, super.angle, super.anchor, super.priority}) + : super( + size: Vector2(50, 50), + paint: Paint()..color = const Color(0xFFFFFFFF), + ) { + addAll([head, leftArm]); + } + + /// The `head` child component. + final \$PlayerHead head = \$PlayerHead(); + + /// The `left_arm` child component. + final RectangleComponent leftArm = RectangleComponent( + position: Vector2(-4, 30), + size: Vector2(50, 50), + paint: Paint()..color = const Color(0xFFFFFFFF), + ); +} + +/// The `head` child component of [\$Player]. +class \$PlayerHead extends RectangleComponent { + /// Creates a [\$PlayerHead]. + \$PlayerHead() + : super( + position: Vector2(10, 0), + size: Vector2(50, 50), + paint: Paint() + ..color = const Color(0x8000FF00) + ..style = PaintingStyle.stroke, + ) { + add(eye); + } + + /// The `eye` child component. + final RectangleComponent eye = RectangleComponent( + position: Vector2(0, 0), + size: Vector2(5, 5), + paint: Paint()..color = const Color(0xFFFFFFFF), + ); +} +'''), + ); + }); + + test('generates position components without paints', () { + expect( + generator.generate( + const PositionComponent( + name: 'player', + size: ComponentSize(width: 10, height: 20), + children: [ + PositionComponent( + name: 'body', + position: ComponentPosition(x: 1, y: 2), + ), + ], + ), + ), + equals(r''' +// GENERATED CODE - DO NOT MODIFY BY HAND. +// Generated by Flame Studio. + +// coverage:ignore-file +// ignore_for_file: type=lint + +import 'package:flame/components.dart'; + +/// The `player` component. +class $Player extends PositionComponent { + /// Creates a [$Player]. + $Player({super.position, super.angle, super.anchor, super.priority}) + : super(size: Vector2(10, 20)) { + add(body); + } + + /// The `body` child component. + final PositionComponent body = PositionComponent( + position: Vector2(1, 2), + size: Vector2(50, 50), + ); +} +'''), + ); + }); + + test('generates circles with a radius instead of a size', () { + expect( + generator.generate( + const CircleComponent( + name: 'ball', + radius: ComponentRadius(radius: 10), + children: [ + CircleComponent( + name: 'core', + position: ComponentPosition(x: 1, y: 2), + radius: ComponentRadius(radius: 2.5), + paint: ComponentPaint( + color: 0xFFFF0000, + style: PaintStyle.stroke, + ), + ), + ], + ), + ), + equals(''' +$_header/// The `ball` component. +class \$Ball extends CircleComponent { + /// Creates a [\$Ball]. + \$Ball({super.position, super.angle, super.anchor, super.priority}) + : super(radius: 10, paint: Paint()..color = const Color(0xFFFFFFFF)) { + add(core); + } + + /// The `core` child component. + final CircleComponent core = CircleComponent( + position: Vector2(1, 2), + radius: 2.5, + paint: Paint() + ..color = const Color(0xFFFF0000) + ..style = PaintingStyle.stroke, + ); +} +'''), + ); + }); + + test('generates polygons with their vertices', () { + expect( + generator.generate( + const PolygonComponent( + name: 'ship', + children: [ + PolygonComponent( + name: 'wing', + position: ComponentPosition(x: 1, y: 2), + vertices: ComponentVertices([ + ComponentVertex(0, 0), + ComponentVertex(10, 0), + ComponentVertex(0, 2.5), + ]), + ), + ], + ), + ), + equals(''' +$_header/// The `ship` component. +class \$Ship extends PolygonComponent { + /// Creates a [\$Ship]. + \$Ship({super.position, super.angle, super.anchor, super.priority}) + : super([ + Vector2(25, 0), + Vector2(50, 50), + Vector2(0, 50), + ], paint: Paint()..color = const Color(0xFFFFFFFF)) { + add(wing); + } + + /// The `wing` child component. + final PolygonComponent wing = PolygonComponent( + [Vector2(0, 0), Vector2(10, 0), Vector2(0, 2.5)], + position: Vector2(1, 2), + paint: Paint()..color = const Color(0xFFFFFFFF), + ); +} +'''), + ); + }); + + test('generates the angle of children, but not of the root', () { + expect( + generator.generate( + const PositionComponent( + name: 'player', + // The root angle is set by whoever uses the component. + angle: ComponentAngle(radians: 1), + children: [ + PositionComponent( + name: 'head', + angle: ComponentAngle(radians: 0.5), + children: [ + PositionComponent( + name: 'eye', + angle: ComponentAngle(radians: 2), + ), + ], + ), + PositionComponent(name: 'body'), + ], + ), + ), + equals(r''' +// GENERATED CODE - DO NOT MODIFY BY HAND. +// Generated by Flame Studio. + +// coverage:ignore-file +// ignore_for_file: type=lint + +import 'package:flame/components.dart'; + +/// The `player` component. +class $Player extends PositionComponent { + /// Creates a [$Player]. + $Player({super.position, super.angle, super.anchor, super.priority}) + : super(size: Vector2(50, 50)) { + addAll([head, body]); + } + + /// The `head` child component. + final $PlayerHead head = $PlayerHead(); + + /// The `body` child component. + final PositionComponent body = PositionComponent( + position: Vector2(0, 0), + size: Vector2(50, 50), + ); +} + +/// The `head` child component of [$Player]. +class $PlayerHead extends PositionComponent { + /// Creates a [$PlayerHead]. + $PlayerHead() + : super(position: Vector2(0, 0), angle: 0.5, size: Vector2(50, 50)) { + add(eye); + } + + /// The `eye` child component. + final PositionComponent eye = PositionComponent( + position: Vector2(0, 0), + angle: 2, + size: Vector2(50, 50), + ); +} +'''), + ); + }); + + test('generates the anchor of children, but not of the root', () { + expect( + generator.generate( + const PositionComponent( + name: 'player', + // The root anchor is set by whoever uses the component. + anchor: ComponentAnchor.center, + children: [ + PositionComponent( + name: 'head', + anchor: ComponentAnchor.bottomCenter, + children: [ + PositionComponent( + name: 'eye', + anchor: ComponentAnchor(x: 0.25, y: 1), + ), + ], + ), + PositionComponent(name: 'body'), + ], + ), + ), + equals(r''' +// GENERATED CODE - DO NOT MODIFY BY HAND. +// Generated by Flame Studio. + +// coverage:ignore-file +// ignore_for_file: type=lint + +import 'package:flame/components.dart'; + +/// The `player` component. +class $Player extends PositionComponent { + /// Creates a [$Player]. + $Player({super.position, super.angle, super.anchor, super.priority}) + : super(size: Vector2(50, 50)) { + addAll([head, body]); + } + + /// The `head` child component. + final $PlayerHead head = $PlayerHead(); + + /// The `body` child component. + final PositionComponent body = PositionComponent( + position: Vector2(0, 0), + size: Vector2(50, 50), + ); +} + +/// The `head` child component of [$Player]. +class $PlayerHead extends PositionComponent { + /// Creates a [$PlayerHead]. + $PlayerHead() + : super( + position: Vector2(0, 0), + anchor: Anchor.bottomCenter, + size: Vector2(50, 50), + ) { + add(eye); + } + + /// The `eye` child component. + final PositionComponent eye = PositionComponent( + position: Vector2(0, 0), + anchor: Anchor(0.25, 1), + size: Vector2(50, 50), + ); +} +'''), + ); + }); + + test('generates hitboxes with their collision, importing the Flame ' + 'collisions', () { + expect( + generator.generate( + const PositionComponent( + name: 'player', + children: [ + RectangleHitboxComponent(name: 'body'), + CircleHitboxComponent( + name: 'head', + position: ComponentPosition(x: 1, y: 2), + radius: ComponentRadius(radius: 5), + collision: ComponentCollision( + type: HitboxCollisionType.passive, + isSolid: true, + ), + ), + PolygonHitboxComponent( + name: 'tail', + vertices: ComponentVertices([ + ComponentVertex(0, 0), + ComponentVertex(10, 0), + ComponentVertex(0, 10), + ]), + collision: ComponentCollision( + type: HitboxCollisionType.inactive, + ), + ), + ], + ), + ), + equals(r''' +// GENERATED CODE - DO NOT MODIFY BY HAND. +// Generated by Flame Studio. + +// coverage:ignore-file +// ignore_for_file: type=lint + +import 'package:flame/collisions.dart'; +import 'package:flame/components.dart'; + +/// The `player` component. +class $Player extends PositionComponent { + /// Creates a [$Player]. + $Player({super.position, super.angle, super.anchor, super.priority}) + : super(size: Vector2(50, 50)) { + addAll([body, head, tail]); + } + + /// The `body` child component. + final RectangleHitbox body = RectangleHitbox( + position: Vector2(0, 0), + size: Vector2(50, 50), + ); + + /// The `head` child component. + final CircleHitbox head = CircleHitbox( + position: Vector2(1, 2), + radius: 5, + collisionType: CollisionType.passive, + isSolid: true, + ); + + /// The `tail` child component. + final PolygonHitbox tail = PolygonHitbox( + [Vector2(0, 0), Vector2(10, 0), Vector2(0, 10)], + position: Vector2(0, 0), + collisionType: CollisionType.inactive, + ); +} +'''), + ); + }); + + test('imports dart:ui when any node has a paint', () { + expect( + generator.generate( + const PositionComponent( + name: 'player', + children: [RectangleComponent(name: 'body')], + ), + ), + allOf( + startsWith(_header), + contains('final RectangleComponent body = RectangleComponent('), + ), + ); + }); + + test('pads colors to 8 hex digits', () { + expect( + generator.generate( + const RectangleComponent( + name: 'Ghost', + paint: ComponentPaint(color: 0x00000001), + ), + ), + contains('const Color(0x00000001)'), + ); + }); + + test('references the palette for palette colors', () { + const palette = Palette( + colors: [PaletteColor(name: 'dark_grey', color: 0xFF333333)], + ); + + final code = generator.generate( + const RectangleComponent( + name: 'Player', + paint: ComponentPaint(paletteColor: 'dark_grey'), + children: [ + CircleComponent( + name: 'eye', + paint: ComponentPaint(color: 0xFF0000FF), + ), + ], + ), + palette: palette, + ); + + expect(code, contains("import 'palette.generated.dart';")); + expect(code, contains('paint: Paint()..color = GamePalette.darkGrey')); + expect(code, contains('const Color(0xFF0000FF)')); + }); + + test('uses the color value when the palette color is missing', () { + final code = generator.generate( + const RectangleComponent( + name: 'Player', + paint: ComponentPaint(color: 0xFF00FF00, paletteColor: 'missing'), + ), + ); + + expect(code, isNot(contains('palette.generated.dart'))); + expect(code, contains('const Color(0xFF00FF00)')); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/code_generation/dart_names_test.dart b/packages/flame_studio/test/repositories/component_repository/code_generation/dart_names_test.dart new file mode 100644 index 00000000000..b7f08f9d669 --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/code_generation/dart_names_test.dart @@ -0,0 +1,90 @@ +import 'package:flame_studio/repositories/component_repository/code_generation/dart_names.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('dartClassName', () { + test('converts names to PascalCase', () { + expect(dartClassName('player'), equals('Player')); + expect(dartClassName('player_ship'), equals('PlayerShip')); + expect(dartClassName('playerShip'), equals('PlayerShip')); + expect(dartClassName('PlayerShip'), equals('PlayerShip')); + expect(dartClassName('_player__ship_'), equals('PlayerShip')); + expect(dartClassName('_'), isEmpty); + }); + }); + + test('dartRootClassName adds the generated code prefix', () { + expect(dartRootClassName('player_ship'), equals(r'$PlayerShip')); + }); + + test('dartChildClassName prefixes the child with the root class', () { + expect(dartChildClassName('player_ship', 'head'), r'$PlayerShipHead'); + expect(dartChildClassName('player', 'ship_head'), r'$PlayerShipHead'); + }); + + group('dartMemberName', () { + test('converts names to camelCase', () { + expect(dartMemberName('head'), equals('head')); + expect(dartMemberName('Head'), equals('head')); + expect(dartMemberName('left_arm'), equals('leftArm')); + expect(dartMemberName('leftArm'), equals('leftArm')); + expect(dartMemberName('__'), isEmpty); + }); + }); + + group('dartFileName', () { + test('converts names to snake_case', () { + expect(dartFileName('player'), equals('player')); + expect(dartFileName('PlayerShip'), equals('player_ship')); + expect(dartFileName('playerShip'), equals('player_ship')); + expect(dartFileName('player_ship'), equals('player_ship')); + expect(dartFileName('ship2Wing'), equals('ship2_wing')); + expect(dartFileName('_Player'), equals('player')); + }); + }); + + test('isDartIdentifier', () { + expect(isDartIdentifier('head'), isTrue); + expect(isDartIdentifier('_head1'), isTrue); + expect(isDartIdentifier('1head'), isFalse); + expect(isDartIdentifier('my head'), isFalse); + expect(isDartIdentifier(''), isFalse); + }); + + test('isDartKeyword', () { + expect(isDartKeyword('class'), isTrue); + expect(isDartKeyword('late'), isTrue); + expect(isDartKeyword('head'), isFalse); + }); + + test('flameMemberNames lists inherited Flame members', () { + expect( + flameMemberNames(ComponentType.rectangle), + containsAll(['size', 'position', 'paint', 'children', 'parent']), + ); + expect( + flameMemberNames(ComponentType.position), + containsAll(['size', 'position', 'children', 'parent']), + ); + expect(flameMemberNames(ComponentType.position), isNot(contains('paint'))); + expect( + flameMemberNames(ComponentType.circle), + containsAll(['radius', 'paint', 'isSolid']), + ); + expect( + flameMemberNames(ComponentType.circle), + containsAll(flameMemberNames(ComponentType.position)), + ); + expect(flameMemberNames(ComponentType.circle), isNot(contains('vertices'))); + expect( + flameMemberNames(ComponentType.polygon), + containsAll(['vertices', 'paint', 'refreshVertices', 'size']), + ); + expect(flameMemberNames(ComponentType.polygon), isNot(contains('radius'))); + expect( + flameMemberNames(ComponentType.rectangle), + containsAll(flameMemberNames(ComponentType.position)), + ); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/code_generation/palette_code_generator_test.dart b/packages/flame_studio/test/repositories/component_repository/code_generation/palette_code_generator_test.dart new file mode 100644 index 00000000000..8425d7fad9b --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/code_generation/palette_code_generator_test.dart @@ -0,0 +1,57 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(PaletteCodeGenerator, () { + const generator = PaletteCodeGenerator(); + + test('fileName is next to the generated components', () { + expect(PaletteCodeGenerator.fileName, equals('palette.generated.dart')); + }); + + test('reference is the camelCase member of the class', () { + expect( + PaletteCodeGenerator.reference('dark_grey'), + equals('GamePalette.darkGrey'), + ); + }); + + test('generates a constant for every color', () { + expect( + generator.generate( + const Palette( + colors: [ + PaletteColor(name: 'primary', color: 0xFFFF0000), + PaletteColor(name: 'dark_grey', color: 0x00333333), + ], + ), + ), + equals(''' +// GENERATED CODE - DO NOT MODIFY BY HAND. +// Generated by Flame Studio. + +// coverage:ignore-file +// ignore_for_file: type=lint + +import 'dart:ui'; + +/// The colors of the game palette. +abstract final class GamePalette { + /// The `primary` color. + static const primary = Color(0xFFFF0000); + + /// The `dark_grey` color. + static const darkGrey = Color(0x00333333); +} +'''), + ); + }); + + test('generates an empty class for an empty palette', () { + expect( + generator.generate(const Palette()), + contains('abstract final class GamePalette {}'), + ); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/component_repository_test.dart b/packages/flame_studio/test/repositories/component_repository/component_repository_test.dart new file mode 100644 index 00000000000..ec59c16c730 --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/component_repository_test.dart @@ -0,0 +1,526 @@ +import 'dart:convert'; + +import 'package:flame_studio/clients/clients.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:path/path.dart' as p; + +class _MockFileSystemClient() extends Mock implements FileSystemClient; + +void main() { + group(ComponentRepository, () { + const projectPath = '/projects/my_game'; + final directory = p.join( + projectPath, + ComponentRepository.componentsDirectory, + ); + String fileOf(String name) => p.join(directory, '$name.json'); + + late FileSystemClient fileSystem; + late ComponentRepository repository; + + final paletteFile = p.join(projectPath, ComponentRepository.paletteFile); + final paletteCodeFile = p.join( + projectPath, + 'lib/components', + PaletteCodeGenerator.fileName, + ); + const palette = Palette( + colors: [PaletteColor(name: 'primary', color: 0xFFFF0000)], + ); + + setUp(() { + fileSystem = _MockFileSystemClient(); + repository = ComponentRepository(fileSystem: fileSystem); + when(() => fileSystem.fileExists(paletteFile)) + .thenAnswer((_) async => false); + }); + + group('getComponents', () { + test('returns the components sorted by name', () async { + when(() => fileSystem.listFiles(directory, extension: '.json')) + .thenAnswer((_) async => [fileOf('Player'), fileOf('Enemy')]); + when(() => fileSystem.readFile(fileOf('Player'))) + .thenAnswer((_) async => jsonEncode({'name': 'Player'})); + when(() => fileSystem.readFile(fileOf('Enemy'))) + .thenAnswer((_) async => jsonEncode({'name': 'Enemy'})); + + expect( + await repository.getComponents(projectPath), + equals(const [ + RectangleComponent(name: 'Enemy'), + RectangleComponent(name: 'Player'), + ]), + ); + }); + + test('skips unreadable files', () async { + when(() => fileSystem.listFiles(directory, extension: '.json')) + .thenAnswer((_) async => [fileOf('Player'), fileOf('Broken')]); + when(() => fileSystem.readFile(fileOf('Player'))) + .thenAnswer((_) async => jsonEncode({'name': 'Player'})); + when(() => fileSystem.readFile(fileOf('Broken'))) + .thenAnswer((_) async => 'not json'); + + expect( + await repository.getComponents(projectPath), + equals(const [RectangleComponent(name: 'Player')]), + ); + }); + }); + + group('createComponent', () { + test('writes the component file and returns the component', () async { + when(() => fileSystem.listFiles(directory, extension: '.json')) + .thenAnswer((_) async => [fileOf('Enemy')]); + when(() => fileSystem.readFile(fileOf('Enemy'))) + .thenAnswer((_) async => jsonEncode({'name': 'Enemy'})); + when(() => fileSystem.writeFile(any(), any())).thenAnswer((_) async {}); + + expect( + await repository.createComponent( + projectPath, + 'Player', + ComponentType.rectangle, + ), + equals(const RectangleComponent(name: 'Player')), + ); + verify( + () => fileSystem.writeFile( + fileOf('Player'), + jsonEncode(const RectangleComponent(name: 'Player').toJson()), + ), + ).called(1); + }); + + test('throws an ArgumentError for hitboxes', () async { + await expectLater( + repository.createComponent( + projectPath, + 'Player', + ComponentType.rectangleHitbox, + ), + throwsArgumentError, + ); + verifyNever(() => fileSystem.writeFile(any(), any())); + }); + + test('creates polygons with the given shape', () async { + when(() => fileSystem.listFiles(directory, extension: '.json')) + .thenAnswer((_) async => []); + when(() => fileSystem.writeFile(any(), any())).thenAnswer((_) async {}); + + expect( + await repository.createComponent( + projectPath, + 'Player', + ComponentType.polygon, + polygonShape: PolygonShape.square, + ), + equals( + const PolygonComponent( + name: 'Player', + vertices: ComponentVertices(ComponentVertices.square), + ), + ), + ); + }); + + for (final name in [ + '', + '1Player', + 'My Player', + 'a/b', + '../x', + '_', + '_1', + // Its code would take the place of the palette's. + 'palette', + 'Palette', + ]) { + test('throws InvalidComponentNameException for "$name"', () { + expect( + () => repository.createComponent( + projectPath, + name, + ComponentType.rectangle, + ), + throwsA(isA()), + ); + }); + } + + for (final name in ['Player', 'player', 'PLAYER']) { + test('throws ComponentAlreadyExistsException for "$name" ' + 'when Player exists', () { + when(() => fileSystem.listFiles(directory, extension: '.json')) + .thenAnswer((_) async => [fileOf('Player')]); + + expect( + () => repository.createComponent( + projectPath, + name, + ComponentType.rectangle, + ), + throwsA(isA()), + ); + }); + } + }); + + for (final (name, existing) in [ + ('AB', const RectangleComponent(name: 'a_b')), + ( + 'player_ship_head', + const RectangleComponent( + name: 'player_ship', + children: [RectangleComponent(name: 'head')], + ), + ), + ]) { + test('createComponent throws ComponentClassConflictException for ' + '"$name" when ${existing.name} generates its class', () async { + when(() => fileSystem.listFiles(directory, extension: '.json')) + .thenAnswer((_) async => [fileOf(existing.name)]); + when(() => fileSystem.readFile(fileOf(existing.name))) + .thenAnswer((_) async => jsonEncode(existing.toJson())); + + await expectLater( + repository.createComponent( + projectPath, + name, + ComponentType.rectangle, + ), + throwsA( + isA() + .having((e) => e.name, 'name', name) + .having( + (e) => e.conflictingComponent, + 'conflictingComponent', + existing.name, + ), + ), + ); + verifyNever(() => fileSystem.writeFile(any(), any())); + }); + } + + group('saveComponent', () { + test('writes the component file', () async { + when(() => fileSystem.writeFile(any(), any())).thenAnswer((_) async {}); + const component = RectangleComponent( + name: 'Player', + size: ComponentSize(width: 10, height: 20), + ); + + await repository.saveComponent(projectPath, component); + + verify( + () => fileSystem.writeFile( + fileOf('Player'), + jsonEncode(component.toJson()), + ), + ).called(1); + }); + }); + + group('writeComponentCode', () { + const component = RectangleComponent(name: 'PlayerShip'); + const generator = ComponentCodeGenerator(); + final codeFile = p.join( + projectPath, + 'lib/components', + 'player_ship.generated.dart', + ); + + setUp(() { + when(() => fileSystem.writeFile(any(), any())).thenAnswer((_) async {}); + }); + + test('writes the generated code to the output folder', () async { + when(() => fileSystem.fileExists(codeFile)) + .thenAnswer((_) async => false); + + await repository.writeComponentCode( + projectPath, + 'lib/components', + component, + ); + + verify( + () => fileSystem.writeFile(codeFile, generator.generate(component)), + ).called(1); + }); + + test('replaces previously generated code', () async { + when(() => fileSystem.fileExists(codeFile)) + .thenAnswer((_) async => true); + when(() => fileSystem.readFile(codeFile)) + .thenAnswer((_) async => '${ComponentCodeGenerator.header}\n'); + + await repository.writeComponentCode( + projectPath, + 'lib/components', + component, + ); + + verify( + () => fileSystem.writeFile(codeFile, generator.generate(component)), + ).called(1); + }); + + test('throws GeneratedFileConflictException and keeps a file that was ' + 'not generated', () async { + when(() => fileSystem.fileExists(codeFile)) + .thenAnswer((_) async => true); + when(() => fileSystem.readFile(codeFile)) + .thenAnswer((_) async => 'class PlayerShip {}'); + + await expectLater( + repository.writeComponentCode( + projectPath, + 'lib/components', + component, + ), + throwsA( + isA().having( + (e) => e.path, + 'path', + codeFile, + ), + ), + ); + verifyNever(() => fileSystem.writeFile(any(), any())); + }); + + test('throws GeneratedFileConflictException for a component whose ' + 'code would replace the palette', () async { + await expectLater( + repository.writeComponentCode( + projectPath, + 'lib/components', + const RectangleComponent(name: 'palette'), + ), + throwsA(isA()), + ); + verifyNever(() => fileSystem.writeFile(any(), any())); + }); + + test('references the palette and writes its code when the component ' + 'uses it', () async { + const painted = RectangleComponent( + name: 'PlayerShip', + paint: ComponentPaint(paletteColor: 'primary'), + ); + when(() => fileSystem.fileExists(paletteFile)) + .thenAnswer((_) async => true); + when(() => fileSystem.readFile(paletteFile)) + .thenAnswer((_) async => jsonEncode(palette.toJson())); + when(() => fileSystem.fileExists(codeFile)) + .thenAnswer((_) async => false); + when(() => fileSystem.fileExists(paletteCodeFile)) + .thenAnswer((_) async => false); + + await repository.writeComponentCode( + projectPath, + 'lib/components', + painted, + ); + + verify( + () => fileSystem.writeFile( + paletteCodeFile, + const PaletteCodeGenerator().generate(palette), + ), + ).called(1); + verify( + () => fileSystem.writeFile( + codeFile, + generator.generate(painted, palette: palette), + ), + ).called(1); + }); + }); + + group('getPalette', () { + test('returns the stored palette', () async { + when(() => fileSystem.fileExists(paletteFile)) + .thenAnswer((_) async => true); + when(() => fileSystem.readFile(paletteFile)) + .thenAnswer((_) async => jsonEncode(palette.toJson())); + + expect(await repository.getPalette(projectPath), equals(palette)); + }); + + test('returns an empty palette when none was saved', () async { + expect( + await repository.getPalette(projectPath), + equals(const Palette()), + ); + }); + + test('returns an empty palette when unreadable', () async { + when(() => fileSystem.fileExists(paletteFile)) + .thenAnswer((_) async => true); + when(() => fileSystem.readFile(paletteFile)) + .thenAnswer((_) async => 'not json'); + + expect( + await repository.getPalette(projectPath), + equals(const Palette()), + ); + }); + }); + + group('savePalette', () { + test('writes the palette file', () async { + when(() => fileSystem.writeFile(any(), any())).thenAnswer((_) async {}); + + await repository.savePalette(projectPath, palette); + + verify( + () => fileSystem.writeFile(paletteFile, jsonEncode(palette.toJson())), + ).called(1); + }); + + test('throws InvalidPaletteException for invalid names', () async { + await expectLater( + repository.savePalette( + projectPath, + const Palette(colors: [PaletteColor(name: 'class', color: 0)]), + ), + throwsA(isA()), + ); + verifyNever(() => fileSystem.writeFile(any(), any())); + }); + }); + + group('writePaletteCode', () { + setUp(() { + when(() => fileSystem.writeFile(any(), any())).thenAnswer((_) async {}); + }); + + test('writes the generated code to the output folder', () async { + when(() => fileSystem.fileExists(paletteCodeFile)) + .thenAnswer((_) async => false); + + await repository.writePaletteCode( + projectPath, + 'lib/components', + palette, + ); + + verify( + () => fileSystem.writeFile( + paletteCodeFile, + const PaletteCodeGenerator().generate(palette), + ), + ).called(1); + }); + + test('throws GeneratedFileConflictException and keeps a file that was ' + 'not generated', () async { + when(() => fileSystem.fileExists(paletteCodeFile)) + .thenAnswer((_) async => true); + when(() => fileSystem.readFile(paletteCodeFile)) + .thenAnswer((_) async => 'class GamePalette {}'); + + await expectLater( + repository.writePaletteCode(projectPath, 'lib/components', palette), + throwsA(isA()), + ); + verifyNever(() => fileSystem.writeFile(any(), any())); + }); + }); + + group('isComponentCodeUpToDate', () { + const component = RectangleComponent(name: 'PlayerShip'); + const generator = ComponentCodeGenerator(); + final codeFile = p.join( + projectPath, + 'lib/components', + 'player_ship.generated.dart', + ); + + Future isUpToDate() => repository.isComponentCodeUpToDate( + projectPath, + 'lib/components', + component, + ); + + test('is false without generated code', () async { + when(() => fileSystem.fileExists(codeFile)) + .thenAnswer((_) async => false); + + expect(await isUpToDate(), isFalse); + }); + + test('is true when the file holds the current code', () async { + when(() => fileSystem.fileExists(codeFile)) + .thenAnswer((_) async => true); + when(() => fileSystem.readFile(codeFile)) + .thenAnswer((_) async => generator.generate(component)); + + expect(await isUpToDate(), isTrue); + }); + + test('is false when the file holds other code', () async { + when(() => fileSystem.fileExists(codeFile)) + .thenAnswer((_) async => true); + when(() => fileSystem.readFile(codeFile)) + .thenAnswer((_) async => '// hand-written'); + + expect(await isUpToDate(), isFalse); + }); + }); + + group('deleteComponent', () { + const component = RectangleComponent(name: 'Player'); + final codeFile = p.join(projectPath, 'lib/game', 'player.generated.dart'); + + setUp(() { + when(() => fileSystem.deleteFile(any())).thenAnswer((_) async {}); + }); + + Future delete() => repository.deleteComponent( + projectPath, + component, + outputPath: 'lib/game', + ); + + test('deletes the component file and its generated code', () async { + when(() => fileSystem.fileExists(codeFile)) + .thenAnswer((_) async => true); + when(() => fileSystem.readFile(codeFile)) + .thenAnswer((_) async => '${ComponentCodeGenerator.header}\n'); + + await delete(); + + verify(() => fileSystem.deleteFile(fileOf('Player'))).called(1); + verify(() => fileSystem.deleteFile(codeFile)).called(1); + }); + + test('works when there is no generated code', () async { + when(() => fileSystem.fileExists(codeFile)) + .thenAnswer((_) async => false); + + await delete(); + + verify(() => fileSystem.deleteFile(fileOf('Player'))).called(1); + verifyNever(() => fileSystem.deleteFile(codeFile)); + }); + + test('keeps a file that was not generated', () async { + when(() => fileSystem.fileExists(codeFile)) + .thenAnswer((_) async => true); + when(() => fileSystem.readFile(codeFile)) + .thenAnswer((_) async => 'class Player {}'); + + await delete(); + + verifyNever(() => fileSystem.deleteFile(codeFile)); + }); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/circle_component_test.dart b/packages/flame_studio/test/repositories/component_repository/models/circle_component_test.dart new file mode 100644 index 00000000000..dc9f7adf0bb --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/circle_component_test.dart @@ -0,0 +1,159 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(CircleComponent, () { + const component = CircleComponent( + name: 'Player', + position: ComponentPosition(x: 1, y: 2), + anchor: ComponentAnchor.center, + angle: ComponentAngle(radians: 1.5), + radius: ComponentRadius(radius: 10), + paint: ComponentPaint(color: 0xFF00FF00, style: PaintStyle.stroke), + children: [RectangleComponent(name: 'rectangle1')], + ); + + test('supports value equality', () { + expect( + const CircleComponent(name: 'Player'), + equals(const CircleComponent(name: 'Player')), + ); + expect(component, isNot(equals(const CircleComponent(name: 'Player')))); + }); + + test('is a circle with a position, a radius and a paint', () { + expect(component.type, equals(ComponentType.circle)); + expect(component, isA()); + expect(component, isA()); + expect(component, isA()); + expect(component, isA()); + expect(component, isNot(isA())); + expect(component, isA()); + }); + + test('round-trips through JSON', () { + expect(Component.fromJson(component.toJson()), equals(component)); + }); + + test('toJson includes the type, properties and children', () { + expect( + component.toJson(), + equals({ + 'name': 'Player', + 'type': 'circle', + 'children': [ + { + 'name': 'rectangle1', + 'type': 'rectangle', + 'children': [], + 'position': {'x': 0.0, 'y': 0.0}, + 'anchor': {'x': 0.0, 'y': 0.0}, + 'angle': {'radians': 0.0}, + 'size': {'width': 50.0, 'height': 50.0}, + 'paint': {'color': 0xFFFFFFFF, 'style': 'fill'}, + }, + ], + 'position': {'x': 1.0, 'y': 2.0}, + 'anchor': {'x': 0.5, 'y': 0.5}, + 'angle': {'radians': 1.5}, + 'radius': {'radius': 10.0}, + 'paint': {'color': 0xFF00FF00, 'style': 'stroke'}, + }), + ); + }); + + test('copyWithPosition replaces only the position', () { + const position = ComponentPosition(x: 5, y: 6); + final copy = component.copyWithPosition(position); + + expect(copy.position, equals(position)); + expect( + copy.toJson()..remove('position'), + equals(component.toJson()..remove('position')), + ); + }); + + test('copyWithAnchor replaces only the anchor', () { + const anchor = ComponentAnchor(x: 0.25, y: 1); + final copy = component.copyWithAnchor(anchor); + + expect(copy.anchor, equals(anchor)); + expect( + copy.toJson()..remove('anchor'), + equals(component.toJson()..remove('anchor')), + ); + }); + + test('is anchored at its top left corner when saved without an ' + 'anchor', () { + final json = component.toJson()..remove('anchor'); + + expect( + (Component.fromJson(json) as AnchoredComponent).anchor, + equals(ComponentAnchor.topLeft), + ); + }); + + test('copyWithAngle replaces only the angle', () { + const angle = ComponentAngle(radians: 3); + final copy = component.copyWithAngle(angle); + + expect(copy.angle, equals(angle)); + expect( + copy.toJson()..remove('angle'), + equals(component.toJson()..remove('angle')), + ); + }); + + test('is not rotated when saved without an angle', () { + final json = component.toJson()..remove('angle'); + + expect( + (Component.fromJson(json) as RotatedComponent).angle, + equals(ComponentAngle.zero), + ); + }); + + test('copyWithRadius replaces only the radius', () { + const radius = ComponentRadius(radius: 3); + final copy = component.copyWithRadius(radius); + + expect(copy.radius, equals(radius)); + expect( + copy.toJson()..remove('radius'), + equals(component.toJson()..remove('radius')), + ); + }); + + test('copyWithPaint replaces only the paint', () { + const paint = ComponentPaint(color: 0xFF0000FF); + final copy = component.copyWithPaint(paint); + + expect(copy.paint, equals(paint)); + expect( + copy.toJson()..remove('paint'), + equals(component.toJson()..remove('paint')), + ); + }); + + test('copyWithName replaces only the name', () { + final copy = component.copyWithName('Enemy'); + + expect(copy.name, equals('Enemy')); + expect( + copy.toJson()..remove('name'), + equals(component.toJson()..remove('name')), + ); + }); + + test('copyWithChildren replaces only the children', () { + final copy = component.copyWithChildren(const []); + + expect(copy.children, isEmpty); + expect( + copy.toJson()..remove('children'), + equals(component.toJson()..remove('children')), + ); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/circle_hitbox_component_test.dart b/packages/flame_studio/test/repositories/component_repository/models/circle_hitbox_component_test.dart new file mode 100644 index 00000000000..58a62fb955b --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/circle_hitbox_component_test.dart @@ -0,0 +1,165 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(CircleHitboxComponent, () { + const component = CircleHitboxComponent( + name: 'Player', + position: ComponentPosition(x: 1, y: 2), + anchor: ComponentAnchor.center, + angle: ComponentAngle(radians: 1.5), + radius: ComponentRadius(radius: 10), + collision: ComponentCollision( + type: HitboxCollisionType.passive, + isSolid: true, + ), + children: [RectangleComponent(name: 'rectangle1')], + ); + + test('supports value equality', () { + expect( + const CircleHitboxComponent(name: 'Player'), + equals(const CircleHitboxComponent(name: 'Player')), + ); + expect( + component, + isNot(equals(const CircleHitboxComponent(name: 'Player'))), + ); + }); + + test('is a circle hitbox with a position, a radius and a collision', () { + expect(component.type, equals(ComponentType.circleHitbox)); + expect(component, isA()); + expect(component, isA()); + expect(component, isA()); + expect(component, isA()); + expect(component, isNot(isA())); + expect(component, isA()); + }); + + test('round-trips through JSON', () { + expect(Component.fromJson(component.toJson()), equals(component)); + }); + + test('toJson includes the type, properties and children', () { + expect( + component.toJson(), + equals({ + 'name': 'Player', + 'type': 'circleHitbox', + 'children': [ + { + 'name': 'rectangle1', + 'type': 'rectangle', + 'children': [], + 'position': {'x': 0.0, 'y': 0.0}, + 'anchor': {'x': 0.0, 'y': 0.0}, + 'angle': {'radians': 0.0}, + 'size': {'width': 50.0, 'height': 50.0}, + 'paint': {'color': 0xFFFFFFFF, 'style': 'fill'}, + }, + ], + 'position': {'x': 1.0, 'y': 2.0}, + 'anchor': {'x': 0.5, 'y': 0.5}, + 'angle': {'radians': 1.5}, + 'radius': {'radius': 10.0}, + 'collision': {'type': 'passive', 'isSolid': true}, + }), + ); + }); + + test('copyWithPosition replaces only the position', () { + const position = ComponentPosition(x: 5, y: 6); + final copy = component.copyWithPosition(position); + + expect(copy.position, equals(position)); + expect( + copy.toJson()..remove('position'), + equals(component.toJson()..remove('position')), + ); + }); + + test('copyWithAnchor replaces only the anchor', () { + const anchor = ComponentAnchor(x: 0.25, y: 1); + final copy = component.copyWithAnchor(anchor); + + expect(copy.anchor, equals(anchor)); + expect( + copy.toJson()..remove('anchor'), + equals(component.toJson()..remove('anchor')), + ); + }); + + test('is anchored at its top left corner when saved without an ' + 'anchor', () { + final json = component.toJson()..remove('anchor'); + + expect( + (Component.fromJson(json) as AnchoredComponent).anchor, + equals(ComponentAnchor.topLeft), + ); + }); + + test('copyWithAngle replaces only the angle', () { + const angle = ComponentAngle(radians: 3); + final copy = component.copyWithAngle(angle); + + expect(copy.angle, equals(angle)); + expect( + copy.toJson()..remove('angle'), + equals(component.toJson()..remove('angle')), + ); + }); + + test('is not rotated when saved without an angle', () { + final json = component.toJson()..remove('angle'); + + expect( + (Component.fromJson(json) as RotatedComponent).angle, + equals(ComponentAngle.zero), + ); + }); + + test('copyWithRadius replaces only the radius', () { + const radius = ComponentRadius(radius: 3); + final copy = component.copyWithRadius(radius); + + expect(copy.radius, equals(radius)); + expect( + copy.toJson()..remove('radius'), + equals(component.toJson()..remove('radius')), + ); + }); + + test('copyWithCollision replaces only the collision', () { + const collision = ComponentCollision(isSolid: true); + final copy = component.copyWithCollision(collision); + + expect(copy.collision, equals(collision)); + expect( + copy.toJson()..remove('collision'), + equals(component.toJson()..remove('collision')), + ); + }); + + test('copyWithName replaces only the name', () { + final copy = component.copyWithName('Enemy'); + + expect(copy.name, equals('Enemy')); + expect( + copy.toJson()..remove('name'), + equals(component.toJson()..remove('name')), + ); + }); + + test('copyWithChildren replaces only the children', () { + final copy = component.copyWithChildren(const []); + + expect(copy.children, isEmpty); + expect( + copy.toJson()..remove('children'), + equals(component.toJson()..remove('children')), + ); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/component_anchor_test.dart b/packages/flame_studio/test/repositories/component_repository/models/component_anchor_test.dart new file mode 100644 index 00000000000..668fef4c734 --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/component_anchor_test.dart @@ -0,0 +1,55 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(ComponentAnchor, () { + test('top left, the default, is the origin', () { + expect(ComponentAnchor.topLeft.x, equals(0)); + expect(ComponentAnchor.topLeft.y, equals(0)); + expect( + const RectangleComponent(name: 'player').anchor, + equals(ComponentAnchor.topLeft), + ); + }); + + test('has the nine Flame anchors, row by row', () { + expect( + ComponentAnchor.presets.values, + equals([ + for (final y in [0.0, 0.5, 1.0]) + for (final x in [0.0, 0.5, 1.0]) ComponentAnchor(x: x, y: y), + ]), + ); + }); + + test('presetName is the name of the Flame anchor, if any', () { + expect(ComponentAnchor.center.presetName, equals('center')); + expect( + ComponentAnchor.center.copyWith(x: 1).presetName, + equals('centerRight'), + ); + expect(const ComponentAnchor(x: 0.25).presetName, isNull); + }); + + test('round-trips through JSON, including custom values', () { + const anchor = ComponentAnchor(x: -0.5, y: 1.25); + + expect(ComponentAnchor.fromJson(anchor.toJson()), equals(anchor)); + }); + + test('fromJson falls back to the top left corner for invalid values', () { + expect( + ComponentAnchor.fromJson(const {'x': 'a', 'y': 1}), + equals(ComponentAnchor.bottomLeft), + ); + expect(ComponentAnchor.fromJson(null), equals(ComponentAnchor.topLeft)); + }); + + test('copyWith replaces the given fields', () { + expect( + ComponentAnchor.center.copyWith(y: 1), + equals(ComponentAnchor.bottomCenter), + ); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/component_angle_test.dart b/packages/flame_studio/test/repositories/component_repository/models/component_angle_test.dart new file mode 100644 index 00000000000..a3b682a05f5 --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/component_angle_test.dart @@ -0,0 +1,66 @@ +import 'dart:math' as math; + +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(ComponentAngle, () { + test('defaults to no rotation', () { + expect(ComponentAngle.zero.radians, equals(0)); + expect(ComponentAngle.zero.degrees, equals(0)); + }); + + test('supports value equality', () { + expect( + const ComponentAngle(radians: 1), + equals(const ComponentAngle(radians: 1)), + ); + expect( + const ComponentAngle(radians: 1), + isNot(equals(const ComponentAngle(radians: 2))), + ); + }); + + test('converts between degrees and radians', () { + expect(ComponentAngle.fromDegrees(180).radians, equals(math.pi)); + expect(const ComponentAngle(radians: math.pi / 2).degrees, equals(90)); + }); + + test('round-trips through JSON', () { + const angle = ComponentAngle(radians: 1.5); + + expect(ComponentAngle.fromJson(angle.toJson()), equals(angle)); + expect(angle.toJson(), equals({'radians': 1.5})); + }); + + test('falls back to no rotation for missing or invalid values', () { + expect(ComponentAngle.fromJson(null), equals(ComponentAngle.zero)); + expect( + ComponentAngle.fromJson(const {}), + equals(ComponentAngle.zero), + ); + expect( + ComponentAngle.fromJson(const {'radians': 'a lot'}), + equals(ComponentAngle.zero), + ); + }); + + test('accepts integer values', () { + expect( + ComponentAngle.fromJson(const {'radians': 2}), + equals(const ComponentAngle(radians: 2)), + ); + }); + + test('copyWith replaces the given fields', () { + expect( + const ComponentAngle(radians: 1).copyWith(radians: 2), + equals(const ComponentAngle(radians: 2)), + ); + expect( + const ComponentAngle(radians: 1).copyWith(), + equals(const ComponentAngle(radians: 1)), + ); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/component_collision_test.dart b/packages/flame_studio/test/repositories/component_repository/models/component_collision_test.dart new file mode 100644 index 00000000000..9f8e5b86a2f --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/component_collision_test.dart @@ -0,0 +1,63 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(ComponentCollision, () { + test('defaults to an active hitbox that is not solid', () { + const collision = ComponentCollision(); + + expect(collision.type, equals(HitboxCollisionType.active)); + expect(collision.isSolid, isFalse); + }); + + test('round-trips through JSON', () { + const collision = ComponentCollision( + type: HitboxCollisionType.inactive, + isSolid: true, + ); + + expect(collision.toJson(), equals({'type': 'inactive', 'isSolid': true})); + expect( + ComponentCollision.fromJson(collision.toJson()), + equals(collision), + ); + }); + + test('fromJson falls back to the defaults', () { + expect(ComponentCollision.fromJson(null), const ComponentCollision()); + expect( + ComponentCollision.fromJson(const {'type': 'bouncy', 'isSolid': 1}), + const ComponentCollision(), + ); + }); + + test('copyWith replaces only the given fields', () { + const collision = ComponentCollision(type: HitboxCollisionType.passive); + + expect( + collision.copyWith(isSolid: true), + const ComponentCollision( + type: HitboxCollisionType.passive, + isSolid: true, + ), + ); + expect( + collision.copyWith(type: HitboxCollisionType.active), + const ComponentCollision(), + ); + }); + }); + + group(HitboxCollisionType, () { + test('fromName returns the matching type', () { + expect( + HitboxCollisionType.fromName('passive'), + equals(HitboxCollisionType.passive), + ); + }); + + test('fromName returns null for unknown names', () { + expect(HitboxCollisionType.fromName('bouncy'), isNull); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/component_paint_test.dart b/packages/flame_studio/test/repositories/component_repository/models/component_paint_test.dart new file mode 100644 index 00000000000..ea5a84bb0dc --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/component_paint_test.dart @@ -0,0 +1,104 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(ComponentPaint, () { + test('defaults to a white fill', () { + const paint = ComponentPaint(); + + expect(paint.color, equals(0xFFFFFFFF)); + expect(paint.style, equals(PaintStyle.fill)); + }); + + test('round-trips through JSON', () { + const paint = ComponentPaint(color: 0x80FF0000, style: PaintStyle.stroke); + + expect(ComponentPaint.fromJson(paint.toJson()), equals(paint)); + }); + + test('falls back to defaults for missing or invalid values', () { + expect(ComponentPaint.fromJson(null), equals(const ComponentPaint())); + expect( + ComponentPaint.fromJson(const {'color': 'red', 'style': 'dotted'}), + equals(const ComponentPaint()), + ); + }); + + test('copyWith replaces the given fields', () { + expect( + const ComponentPaint().copyWith(color: 0xFF000000), + equals(const ComponentPaint(color: 0xFF000000)), + ); + expect( + const ComponentPaint().copyWith(style: PaintStyle.stroke), + equals(const ComponentPaint(style: PaintStyle.stroke)), + ); + }); + + test('round-trips a palette color through JSON', () { + const paint = ComponentPaint(color: 0xFF00FF00, paletteColor: 'primary'); + + expect(paint.toJson()['paletteColor'], equals('primary')); + expect(ComponentPaint.fromJson(paint.toJson()), equals(paint)); + }); + + test('omits the palette color from JSON when unset', () { + expect(const ComponentPaint().toJson(), isNot(contains('paletteColor'))); + }); + + test('copyWith keeps the palette color', () { + expect( + const ComponentPaint(paletteColor: 'primary') + .copyWith(style: PaintStyle.stroke) + .paletteColor, + equals('primary'), + ); + }); + + test('withColor replaces the palette color by a color', () { + expect( + const ComponentPaint( + paletteColor: 'primary', + style: PaintStyle.stroke, + ).withColor(0xFF000000), + equals( + const ComponentPaint(color: 0xFF000000, style: PaintStyle.stroke), + ), + ); + }); + + test('withPaletteColor uses a palette color', () { + expect( + const ComponentPaint().withPaletteColor('primary', 0xFF00FF00), + equals( + const ComponentPaint(color: 0xFF00FF00, paletteColor: 'primary'), + ), + ); + }); + + test('resolvedColor reads the palette color, or falls back', () { + const palette = Palette( + colors: [PaletteColor(name: 'primary', color: 0xFF0000FF)], + ); + + expect( + const ComponentPaint( + color: 0xFF00FF00, + paletteColor: 'primary', + ).resolvedColor(palette), + equals(0xFF0000FF), + ); + expect( + const ComponentPaint( + color: 0xFF00FF00, + paletteColor: 'missing', + ).resolvedColor(palette), + equals(0xFF00FF00), + ); + expect( + const ComponentPaint(color: 0xFF00FF00).resolvedColor(palette), + equals(0xFF00FF00), + ); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/component_position_test.dart b/packages/flame_studio/test/repositories/component_repository/models/component_position_test.dart new file mode 100644 index 00000000000..d63d3709e89 --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/component_position_test.dart @@ -0,0 +1,37 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(ComponentPosition, () { + test('defaults to the origin', () { + const position = ComponentPosition(); + + expect(position.x, equals(0)); + expect(position.y, equals(0)); + }); + + test('round-trips through JSON, including negative values', () { + const position = ComponentPosition(x: -10, y: 20.5); + + expect(ComponentPosition.fromJson(position.toJson()), equals(position)); + }); + + test('fromJson falls back to the origin for invalid values', () { + expect( + ComponentPosition.fromJson(const {'x': 'a'}), + equals(const ComponentPosition()), + ); + expect( + ComponentPosition.fromJson(null), + equals(const ComponentPosition()), + ); + }); + + test('copyWith replaces the given fields', () { + expect( + const ComponentPosition(x: 1, y: 2).copyWith(y: 3), + equals(const ComponentPosition(x: 1, y: 3)), + ); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/component_radius_test.dart b/packages/flame_studio/test/repositories/component_repository/models/component_radius_test.dart new file mode 100644 index 00000000000..ced0a42457b --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/component_radius_test.dart @@ -0,0 +1,46 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(ComponentRadius, () { + test('defaults to 25', () { + expect(const ComponentRadius().radius, equals(25)); + }); + + test('round-trips through JSON', () { + const radius = ComponentRadius(radius: 12.5); + + expect(ComponentRadius.fromJson(radius.toJson()), equals(radius)); + }); + + test('reads integers', () { + expect( + ComponentRadius.fromJson(const {'radius': 10}), + equals(const ComponentRadius(radius: 10)), + ); + }); + + test('falls back to the default for missing or invalid values', () { + expect(ComponentRadius.fromJson(null), equals(const ComponentRadius())); + expect( + ComponentRadius.fromJson(const {'radius': 'big'}), + equals(const ComponentRadius()), + ); + expect( + ComponentRadius.fromJson(const {'radius': -1}), + equals(const ComponentRadius()), + ); + }); + + test('copyWith replaces the given fields', () { + expect( + const ComponentRadius().copyWith(radius: 1), + equals(const ComponentRadius(radius: 1)), + ); + expect( + const ComponentRadius(radius: 1).copyWith(), + equals(const ComponentRadius(radius: 1)), + ); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/component_size_test.dart b/packages/flame_studio/test/repositories/component_repository/models/component_size_test.dart new file mode 100644 index 00000000000..a9c61031a1f --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/component_size_test.dart @@ -0,0 +1,45 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(ComponentSize, () { + test('defaults to 50x50', () { + const size = ComponentSize(); + + expect(size.width, equals(50)); + expect(size.height, equals(50)); + }); + + test('round-trips through JSON', () { + const size = ComponentSize(width: 12.5, height: 4); + + expect(ComponentSize.fromJson(size.toJson()), equals(size)); + }); + + test('reads integers', () { + expect( + ComponentSize.fromJson(const {'width': 10, 'height': 20}), + equals(const ComponentSize(width: 10, height: 20)), + ); + }); + + test('falls back to defaults for missing or invalid values', () { + expect(ComponentSize.fromJson(null), equals(const ComponentSize())); + expect( + ComponentSize.fromJson(const {'width': 'wide', 'height': -1}), + equals(const ComponentSize()), + ); + }); + + test('copyWith replaces the given fields', () { + expect( + const ComponentSize().copyWith(width: 1), + equals(const ComponentSize(width: 1)), + ); + expect( + const ComponentSize().copyWith(height: 2), + equals(const ComponentSize(height: 2)), + ); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/component_test.dart b/packages/flame_studio/test/repositories/component_repository/models/component_test.dart new file mode 100644 index 00000000000..2518f6fcc47 --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/component_test.dart @@ -0,0 +1,168 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(Component, () { + group('create', () { + test('creates a rectangle with default properties', () { + expect( + Component.create('Player', ComponentType.rectangle), + equals(const RectangleComponent(name: 'Player')), + ); + }); + + test('creates a position component with default properties', () { + expect( + Component.create('Player', ComponentType.position), + equals(const PositionComponent(name: 'Player')), + ); + }); + + test('creates a circle with default properties', () { + expect( + Component.create('Player', ComponentType.circle), + equals(const CircleComponent(name: 'Player')), + ); + }); + + test('creates a triangle polygon by default', () { + expect( + Component.create('Player', ComponentType.polygon), + equals(const PolygonComponent(name: 'Player')), + ); + }); + + test('creates a polygon with the given shape', () { + expect( + Component.create( + 'Player', + ComponentType.polygon, + polygonShape: PolygonShape.square, + ), + equals( + const PolygonComponent( + name: 'Player', + vertices: ComponentVertices(ComponentVertices.square), + ), + ), + ); + }); + + test('creates hitboxes with default properties', () { + expect( + Component.create('hitbox', ComponentType.rectangleHitbox), + equals(const RectangleHitboxComponent(name: 'hitbox')), + ); + expect( + Component.create('hitbox', ComponentType.circleHitbox), + equals(const CircleHitboxComponent(name: 'hitbox')), + ); + expect( + Component.create( + 'hitbox', + ComponentType.polygonHitbox, + polygonShape: PolygonShape.square, + ), + equals( + const PolygonHitboxComponent( + name: 'hitbox', + vertices: ComponentVertices(ComponentVertices.square), + ), + ), + ); + }); + }); + + group('fromJson', () { + test('reads hitboxes', () { + expect( + Component.fromJson(const {'name': 'a', 'type': 'rectangleHitbox'}), + equals(const RectangleHitboxComponent(name: 'a')), + ); + expect( + Component.fromJson(const {'name': 'a', 'type': 'circleHitbox'}), + equals(const CircleHitboxComponent(name: 'a')), + ); + expect( + Component.fromJson(const {'name': 'a', 'type': 'polygonHitbox'}), + equals(const PolygonHitboxComponent(name: 'a')), + ); + }); + + test('reads a polygon', () { + expect( + Component.fromJson(const {'name': 'Player', 'type': 'polygon'}), + equals(const PolygonComponent(name: 'Player')), + ); + }); + + test('reads a circle', () { + expect( + Component.fromJson(const { + 'name': 'Player', + 'type': 'circle', + 'radius': {'radius': 10.0}, + }), + equals( + const CircleComponent( + name: 'Player', + radius: ComponentRadius(radius: 10), + ), + ), + ); + }); + + test('reads a rectangle', () { + expect( + Component.fromJson(const {'name': 'Player', 'type': 'rectangle'}), + isA(), + ); + }); + + test('reads a position component with children of other types', () { + expect( + Component.fromJson(const { + 'name': 'Player', + 'type': 'position', + 'size': {'width': 10.0, 'height': 20.0}, + 'children': [ + {'name': 'rectangle1', 'type': 'rectangle'}, + ], + }), + equals( + const PositionComponent( + name: 'Player', + size: ComponentSize(width: 10, height: 20), + children: [RectangleComponent(name: 'rectangle1')], + ), + ), + ); + }); + + test('reads the children and skips invalid ones', () { + expect( + Component.fromJson(const { + 'name': 'Player', + 'children': [ + {'name': 'rectangle1', 'type': 'rectangle'}, + 'invalid', + ], + }), + equals( + const RectangleComponent( + name: 'Player', + children: [RectangleComponent(name: 'rectangle1')], + ), + ), + ); + }); + + test('reads components without a type as rectangles', () { + expect( + Component.fromJson(const {'name': 'Player'}), + equals(const RectangleComponent(name: 'Player')), + ); + }); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/component_tree_test.dart b/packages/flame_studio/test/repositories/component_repository/models/component_tree_test.dart new file mode 100644 index 00000000000..04179021bdc --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/component_tree_test.dart @@ -0,0 +1,252 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('ComponentTree', () { + const grandchild = RectangleComponent(name: 'rectangle3'); + const tree = RectangleComponent( + name: 'Player', + children: [ + RectangleComponent(name: 'rectangle1', children: [grandchild]), + RectangleComponent(name: 'rectangle2'), + ], + ); + + test('nodeAt follows the path from the root', () { + expect(tree.nodeAt(const []), same(tree)); + expect(tree.nodeAt(const [1]).name, equals('rectangle2')); + expect(tree.nodeAt(const [0, 0]), equals(grandchild)); + expect(() => tree.nodeAt(const [5]), throwsRangeError); + }); + + test('hasNodeAt tells whether the path exists', () { + expect(tree.hasNodeAt(const []), isTrue); + expect(tree.hasNodeAt(const [0, 0]), isTrue); + expect(tree.hasNodeAt(const [0, 1]), isFalse); + expect(tree.hasNodeAt(const [-1]), isFalse); + }); + + test('updateNodeAt replaces only the node at the path', () { + const size = ComponentSize(width: 1); + final updated = tree.updateNodeAt(const [ + 0, + 0, + ], (node) => (node as SizedComponent).copyWithSize(size)); + + expect((updated.nodeAt(const [0, 0]) as SizedComponent).size, size); + expect(updated.nodeAt(const [1]), equals(tree.nodeAt(const [1]))); + expect(updated.name, equals('Player')); + }); + + test('addChildAt appends a child to the node at the path', () { + const child = RectangleComponent(name: 'rectangle4'); + final updated = tree.addChildAt(const [1], child); + + expect(updated.nodeAt(const [1]).children, equals([child])); + }); + + test('addChildAt throws when the node is a hitbox', () { + const withHitbox = RectangleComponent( + name: 'Player', + children: [RectangleHitboxComponent(name: 'rectangleHitbox1')], + ); + + expect( + () => withHitbox.addChildAt(const [ + 0, + ], const RectangleComponent(name: 'rectangle1')), + throwsArgumentError, + ); + }); + + test('removeNodeAt removes the node and its children', () { + final updated = tree.removeNodeAt(const [0]); + + expect(updated.children.map((c) => c.name), equals(['rectangle2'])); + expect(() => tree.removeNodeAt(const []), throwsArgumentError); + }); + + test('nodes lists the tree depth first', () { + expect( + tree.nodes.map((node) => node.name), + equals(['Player', 'rectangle1', 'rectangle3', 'rectangle2']), + ); + }); + + test('usedPaletteColors lists the palette colors of every node', () { + expect(tree.usedPaletteColors, isEmpty); + expect( + const RectangleComponent( + name: 'Player', + paint: ComponentPaint(paletteColor: 'primary'), + children: [ + PositionComponent( + name: 'body', + children: [ + CircleComponent( + name: 'eye', + paint: ComponentPaint(paletteColor: 'accent'), + ), + RectangleComponent( + name: 'arm', + paint: ComponentPaint(paletteColor: 'primary'), + ), + ], + ), + ], + ).usedPaletteColors, + equals({'primary', 'accent'}), + ); + }); + + test('withPaletteColorsResolved sets the palette values as colors', () { + const palette = Palette( + colors: [PaletteColor(name: 'primary', color: 0xFF0000FF)], + ); + final resolved = const RectangleComponent( + name: 'Player', + paint: ComponentPaint(color: 0xFF000000, paletteColor: 'primary'), + children: [ + PositionComponent( + name: 'body', + children: [ + CircleComponent( + name: 'eye', + paint: ComponentPaint(paletteColor: 'primary'), + ), + RectangleComponent( + name: 'arm', + paint: ComponentPaint(color: 0xFF00FF00), + ), + ], + ), + ], + ).withPaletteColorsResolved(palette); + + int colorAt(List path) => + (resolved.nodeAt(path) as PaintedComponent).paint.color; + expect(colorAt(const []), equals(0xFF0000FF)); + expect(colorAt(const [0, 0]), equals(0xFF0000FF)); + expect(colorAt(const [0, 1]), equals(0xFF00FF00)); + expect(tree.withPaletteColorsResolved(palette), equals(tree)); + }); + + test('uniqueChildName picks the first name that is not taken', () { + expect( + tree.uniqueChildName(ComponentType.rectangle), + equals('rectangle4'), + ); + expect( + const RectangleComponent( + name: 'Player', + children: [RectangleComponent(name: 'rectangle2')], + ).uniqueChildName(ComponentType.rectangle), + equals('rectangle1'), + ); + }); + + test('uniqueChildName ignores names that generate the same getter', () { + expect( + const RectangleComponent( + name: 'Player', + children: [RectangleComponent(name: 'Rectangle1')], + ).uniqueChildName(ComponentType.rectangle), + equals('rectangle2'), + ); + }); + + test('uniqueChildName skips names whose class is taken', () { + expect( + const RectangleComponent(name: 'Player').uniqueChildName( + ComponentType.rectangle, + takenClassNames: {r'$PlayerRectangle1', r'$PlayerRectangle2'}, + ), + equals('rectangle3'), + ); + }); + + test('generatedClassName is the class of the root', () { + expect(tree.generatedClassName, equals(r'$Player')); + }); + + test('generatedClassNames reserves a class for the root and every ' + 'child', () { + expect( + tree.generatedClassNames, + equals({ + r'$Player', + r'$PlayerRectangle1', + r'$PlayerRectangle3', + r'$PlayerRectangle2', + }), + ); + }); + + group('validateChildName', () { + test('accepts a free name, and the current name of the node', () { + expect(tree.validateChildName(const [0], 'head'), isNull); + expect(tree.validateChildName(const [0], 'rectangle1'), isNull); + expect(tree.validateChildName(const [0, 0], 'left_arm'), isNull); + }); + + for (final name in ['', '1head', 'my head', 'class', '_', 'a-b']) { + test('rejects "$name" as invalid', () { + expect( + tree.validateChildName(const [0], name), + equals(ChildNameError.invalid), + ); + }); + } + + for (final name in ['size', 'Position', 'paint', 'children', 'parent']) { + test('rejects "$name" as reserved', () { + expect( + tree.validateChildName(const [0], name), + equals(ChildNameError.reserved), + ); + }); + } + + test('accepts the members of other Flame classes', () { + const container = PositionComponent( + name: 'Player', + children: [RectangleComponent(name: 'rectangle1')], + ); + expect(container.validateChildName(const [0], 'paint'), isNull); + expect( + container.validateChildName(const [0], 'size'), + equals(ChildNameError.reserved), + ); + }); + + for (final name in ['rectangle2', 'Rectangle3', 'player']) { + test('rejects "$name" as duplicate', () { + expect( + tree.validateChildName(const [0], name), + equals(ChildNameError.duplicate), + ); + }); + } + + for (final name in ['ship_head', 'shipHead', 'ShipHead']) { + test('rejects "$name" when its class is taken', () { + expect( + tree.validateChildName( + const [0], + name, + takenClassNames: {r'$PlayerShipHead'}, + ), + equals(ChildNameError.conflict), + ); + }); + } + + test('throws for the root', () { + expect( + () => tree.validateChildName(const [], 'head'), + throwsArgumentError, + ); + }); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/component_type_test.dart b/packages/flame_studio/test/repositories/component_repository/models/component_type_test.dart new file mode 100644 index 00000000000..eeaed99b932 --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/component_type_test.dart @@ -0,0 +1,61 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(ComponentType, () { + test('fromKey returns the matching type', () { + expect( + ComponentType.fromKey('rectangle'), + equals(ComponentType.rectangle), + ); + expect(ComponentType.fromKey('position'), equals(ComponentType.position)); + expect(ComponentType.fromKey('circle'), equals(ComponentType.circle)); + expect(ComponentType.fromKey('polygon'), equals(ComponentType.polygon)); + expect( + ComponentType.fromKey('rectangleHitbox'), + equals(ComponentType.rectangleHitbox), + ); + expect( + ComponentType.fromKey('circleHitbox'), + equals(ComponentType.circleHitbox), + ); + expect( + ComponentType.fromKey('polygonHitbox'), + equals(ComponentType.polygonHitbox), + ); + }); + + test('isHitbox is true only for hitboxes', () { + expect( + ComponentType.values.where((type) => type.isHitbox), + equals([ + ComponentType.rectangleHitbox, + ComponentType.circleHitbox, + ComponentType.polygonHitbox, + ]), + ); + }); + + test('hasVertices is true for polygons and polygon hitboxes', () { + expect( + ComponentType.values.where((type) => type.hasVertices), + equals([ComponentType.polygon, ComponentType.polygonHitbox]), + ); + }); + + test('fromKey returns null for unknown keys', () { + expect(ComponentType.fromKey('triangle'), isNull); + expect(ComponentType.fromKey(null), isNull); + }); + }); + + group(PaintStyle, () { + test('fromName returns the matching style', () { + expect(PaintStyle.fromName('stroke'), equals(PaintStyle.stroke)); + }); + + test('fromName returns null for unknown names', () { + expect(PaintStyle.fromName('dotted'), isNull); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/component_vertices_test.dart b/packages/flame_studio/test/repositories/component_repository/models/component_vertices_test.dart new file mode 100644 index 00000000000..aa8250eccc2 --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/component_vertices_test.dart @@ -0,0 +1,107 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(ComponentVertices, () { + test('defaults to a triangle', () { + expect( + const ComponentVertices().vertices, + equals(ComponentVertices.triangle), + ); + }); + + test('round-trips through JSON', () { + const vertices = ComponentVertices([ + ComponentVertex(1, 2), + ComponentVertex(3.5, 4), + ComponentVertex(-5, 6), + ]); + + expect(ComponentVertices.fromJson(vertices.toJson()), equals(vertices)); + }); + + test('fromJson skips invalid vertices', () { + expect( + ComponentVertices.fromJson(const { + 'vertices': [ + {'x': 0, 'y': 0}, + {'x': 'a', 'y': 0}, + 'invalid', + {'x': 1, 'y': 0}, + {'x': 1, 'y': 1}, + ], + }), + equals( + const ComponentVertices([ + ComponentVertex(0, 0), + ComponentVertex(1, 0), + ComponentVertex(1, 1), + ]), + ), + ); + }); + + test('fromJson falls back to the default with fewer than 3 vertices', () { + expect( + ComponentVertices.fromJson(const { + 'vertices': [ + {'x': 0, 'y': 0}, + {'x': 1, 'y': 0}, + ], + }), + equals(const ComponentVertices()), + ); + expect( + ComponentVertices.fromJson(null), + equals(const ComponentVertices()), + ); + expect( + ComponentVertices.fromJson(const {'vertices': 'invalid'}), + equals(const ComponentVertices()), + ); + }); + + test('bounds is the size of the bounding box', () { + const vertices = ComponentVertices([ + ComponentVertex(-10, 5), + ComponentVertex(20, 0), + ComponentVertex(0, 40), + ]); + + expect(vertices.bounds, equals((width: 30.0, height: 40.0))); + }); + + test('normalized moves the bounding box to the origin', () { + const vertices = ComponentVertices([ + ComponentVertex(-10, 5), + ComponentVertex(20, 10), + ComponentVertex(0, 40), + ]); + + expect( + vertices.normalized(), + equals( + const ComponentVertices([ + ComponentVertex(0, 0), + ComponentVertex(30, 5), + ComponentVertex(10, 35), + ]), + ), + ); + expect( + const ComponentVertices().normalized(), + same(const ComponentVertices()), + ); + }); + }); + + group(PolygonShape, () { + test('has the vertices of its shape', () { + expect( + PolygonShape.triangle.vertices, + equals(ComponentVertices.triangle), + ); + expect(PolygonShape.square.vertices, hasLength(4)); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/palette_test.dart b/packages/flame_studio/test/repositories/component_repository/models/palette_test.dart new file mode 100644 index 00000000000..744e3badba4 --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/palette_test.dart @@ -0,0 +1,133 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(PaletteColor, () { + test('copyWith replaces the given fields', () { + const color = PaletteColor(name: 'primary', color: 0xFF000000); + + expect( + color.copyWith(name: 'accent'), + equals(const PaletteColor(name: 'accent', color: 0xFF000000)), + ); + expect( + color.copyWith(color: 0xFFFFFFFF), + equals(const PaletteColor(name: 'primary', color: 0xFFFFFFFF)), + ); + }); + }); + + group(Palette, () { + const palette = Palette( + colors: [ + PaletteColor(name: 'primary', color: 0xFFFF0000), + PaletteColor(name: 'dark_grey', color: 0xFF333333), + ], + ); + + test('round-trips through JSON', () { + expect(Palette.fromJson(palette.toJson()), equals(palette)); + }); + + test('falls back to an empty palette for invalid JSON', () { + expect(Palette.fromJson(null), equals(const Palette())); + expect(Palette.fromJson(const {'colors': 'red'}), const Palette()); + }); + + test('skips invalid entries and taken names', () { + expect( + Palette.fromJson(const { + 'colors': [ + {'name': 'primary', 'color': 1}, + {'name': 'primary', 'color': 2}, + {'name': 'class', 'color': 3}, + {'name': 'accent', 'color': 'red'}, + 'accent', + {'name': 'accent', 'color': 4}, + ], + }), + equals( + const Palette( + colors: [ + PaletteColor(name: 'primary', color: 1), + PaletteColor(name: 'accent', color: 4), + ], + ), + ), + ); + }); + + test('colorOf returns the color with the given name', () { + expect(palette.colorOf('dark_grey'), equals(0xFF333333)); + expect(palette.colorOf('missing'), isNull); + expect(palette.colorOf(null), isNull); + expect(palette.contains('primary'), isTrue); + expect(palette.contains('missing'), isFalse); + }); + + group('validateColorName', () { + test('accepts unique identifiers', () { + expect(palette.validateColorName(2, 'accent'), isNull); + // A color keeps its own name. + expect(palette.validateColorName(0, 'primary'), isNull); + }); + + test('rejects invalid names and keywords', () { + expect( + palette.validateColorName(2, '1st'), + equals(PaletteColorNameError.invalid), + ); + expect( + palette.validateColorName(2, ''), + equals(PaletteColorNameError.invalid), + ); + expect( + palette.validateColorName(2, 'class'), + equals(PaletteColorNameError.invalid), + ); + expect( + palette.validateColorName(2, '_'), + equals(PaletteColorNameError.invalid), + ); + }); + + test('rejects names with the same member as another color', () { + expect( + palette.validateColorName(2, 'darkGrey'), + equals(PaletteColorNameError.duplicate), + ); + expect( + palette.validateColorName(1, 'primary'), + equals(PaletteColorNameError.duplicate), + ); + }); + }); + + test('isValid checks every name', () { + expect(palette.isValid, isTrue); + expect( + const Palette( + colors: [ + PaletteColor(name: 'a', color: 0), + PaletteColor(name: 'a', color: 0), + ], + ).isValid, + isFalse, + ); + }); + + test('uniqueColorName returns the first free name', () { + expect(const Palette().uniqueColorName(), equals('color1')); + expect( + const Palette(colors: [PaletteColor(name: 'color1', color: 0)]) + .uniqueColorName(), + equals('color2'), + ); + }); + + test('copyWith replaces the colors', () { + expect(palette.copyWith(colors: const []), equals(const Palette())); + expect(palette.copyWith(), equals(palette)); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/polygon_component_test.dart b/packages/flame_studio/test/repositories/component_repository/models/polygon_component_test.dart new file mode 100644 index 00000000000..f6b88e9919b --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/polygon_component_test.dart @@ -0,0 +1,167 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(PolygonComponent, () { + const component = PolygonComponent( + name: 'Player', + position: ComponentPosition(x: 1, y: 2), + anchor: ComponentAnchor.center, + angle: ComponentAngle(radians: 1.5), + vertices: ComponentVertices(ComponentVertices.square), + paint: ComponentPaint(color: 0xFF00FF00, style: PaintStyle.stroke), + children: [RectangleComponent(name: 'rectangle1')], + ); + + test('supports value equality', () { + expect( + const PolygonComponent(name: 'Player'), + equals(const PolygonComponent(name: 'Player')), + ); + expect(component, isNot(equals(const PolygonComponent(name: 'Player')))); + }); + + test('is a polygon with a position, vertices and a paint', () { + expect(component.type, equals(ComponentType.polygon)); + expect(component, isA()); + expect(component, isA()); + expect(component, isA()); + expect(component, isA()); + expect(component, isNot(isA())); + expect(component, isNot(isA())); + expect(component, isA()); + }); + + test('round-trips through JSON', () { + expect(Component.fromJson(component.toJson()), equals(component)); + }); + + test('toJson includes the type, properties and children', () { + expect( + component.toJson(), + equals({ + 'name': 'Player', + 'type': 'polygon', + 'children': [ + { + 'name': 'rectangle1', + 'type': 'rectangle', + 'children': [], + 'position': {'x': 0.0, 'y': 0.0}, + 'anchor': {'x': 0.0, 'y': 0.0}, + 'angle': {'radians': 0.0}, + 'size': {'width': 50.0, 'height': 50.0}, + 'paint': {'color': 0xFFFFFFFF, 'style': 'fill'}, + }, + ], + 'position': {'x': 1.0, 'y': 2.0}, + 'anchor': {'x': 0.5, 'y': 0.5}, + 'angle': {'radians': 1.5}, + 'vertices': { + 'vertices': [ + {'x': 0.0, 'y': 0.0}, + {'x': 50.0, 'y': 0.0}, + {'x': 50.0, 'y': 50.0}, + {'x': 0.0, 'y': 50.0}, + ], + }, + 'paint': {'color': 0xFF00FF00, 'style': 'stroke'}, + }), + ); + }); + + test('copyWithPosition replaces only the position', () { + const position = ComponentPosition(x: 5, y: 6); + final copy = component.copyWithPosition(position); + + expect(copy.position, equals(position)); + expect( + copy.toJson()..remove('position'), + equals(component.toJson()..remove('position')), + ); + }); + + test('copyWithAnchor replaces only the anchor', () { + const anchor = ComponentAnchor(x: 0.25, y: 1); + final copy = component.copyWithAnchor(anchor); + + expect(copy.anchor, equals(anchor)); + expect( + copy.toJson()..remove('anchor'), + equals(component.toJson()..remove('anchor')), + ); + }); + + test('is anchored at its top left corner when saved without an ' + 'anchor', () { + final json = component.toJson()..remove('anchor'); + + expect( + (Component.fromJson(json) as AnchoredComponent).anchor, + equals(ComponentAnchor.topLeft), + ); + }); + + test('copyWithAngle replaces only the angle', () { + const angle = ComponentAngle(radians: 3); + final copy = component.copyWithAngle(angle); + + expect(copy.angle, equals(angle)); + expect( + copy.toJson()..remove('angle'), + equals(component.toJson()..remove('angle')), + ); + }); + + test('is not rotated when saved without an angle', () { + final json = component.toJson()..remove('angle'); + + expect( + (Component.fromJson(json) as RotatedComponent).angle, + equals(ComponentAngle.zero), + ); + }); + + test('copyWithVertices replaces only the vertices', () { + const vertices = ComponentVertices(); + final copy = component.copyWithVertices(vertices); + + expect(copy.vertices, equals(vertices)); + expect( + copy.toJson()..remove('vertices'), + equals(component.toJson()..remove('vertices')), + ); + }); + + test('copyWithPaint replaces only the paint', () { + const paint = ComponentPaint(color: 0xFF0000FF); + final copy = component.copyWithPaint(paint); + + expect(copy.paint, equals(paint)); + expect( + copy.toJson()..remove('paint'), + equals(component.toJson()..remove('paint')), + ); + }); + + test('copyWithName replaces only the name', () { + final copy = component.copyWithName('Enemy'); + + expect(copy.name, equals('Enemy')); + expect( + copy.toJson()..remove('name'), + equals(component.toJson()..remove('name')), + ); + }); + + test('copyWithChildren replaces only the children', () { + final copy = component.copyWithChildren(const []); + + expect(copy.children, isEmpty); + expect( + copy.toJson()..remove('children'), + equals(component.toJson()..remove('children')), + ); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/polygon_hitbox_component_test.dart b/packages/flame_studio/test/repositories/component_repository/models/polygon_hitbox_component_test.dart new file mode 100644 index 00000000000..ee92120adca --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/polygon_hitbox_component_test.dart @@ -0,0 +1,173 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(PolygonHitboxComponent, () { + const component = PolygonHitboxComponent( + name: 'Player', + position: ComponentPosition(x: 1, y: 2), + anchor: ComponentAnchor.center, + angle: ComponentAngle(radians: 1.5), + vertices: ComponentVertices(ComponentVertices.square), + collision: ComponentCollision( + type: HitboxCollisionType.passive, + isSolid: true, + ), + children: [RectangleComponent(name: 'rectangle1')], + ); + + test('supports value equality', () { + expect( + const PolygonHitboxComponent(name: 'Player'), + equals(const PolygonHitboxComponent(name: 'Player')), + ); + expect( + component, + isNot(equals(const PolygonHitboxComponent(name: 'Player'))), + ); + }); + + test('is a polygon hitbox with a position, vertices and a collision', () { + expect(component.type, equals(ComponentType.polygonHitbox)); + expect(component, isA()); + expect(component, isA()); + expect(component, isA()); + expect(component, isA()); + expect(component, isNot(isA())); + expect(component, isNot(isA())); + expect(component, isA()); + }); + + test('round-trips through JSON', () { + expect(Component.fromJson(component.toJson()), equals(component)); + }); + + test('toJson includes the type, properties and children', () { + expect( + component.toJson(), + equals({ + 'name': 'Player', + 'type': 'polygonHitbox', + 'children': [ + { + 'name': 'rectangle1', + 'type': 'rectangle', + 'children': [], + 'position': {'x': 0.0, 'y': 0.0}, + 'anchor': {'x': 0.0, 'y': 0.0}, + 'angle': {'radians': 0.0}, + 'size': {'width': 50.0, 'height': 50.0}, + 'paint': {'color': 0xFFFFFFFF, 'style': 'fill'}, + }, + ], + 'position': {'x': 1.0, 'y': 2.0}, + 'anchor': {'x': 0.5, 'y': 0.5}, + 'angle': {'radians': 1.5}, + 'vertices': { + 'vertices': [ + {'x': 0.0, 'y': 0.0}, + {'x': 50.0, 'y': 0.0}, + {'x': 50.0, 'y': 50.0}, + {'x': 0.0, 'y': 50.0}, + ], + }, + 'collision': {'type': 'passive', 'isSolid': true}, + }), + ); + }); + + test('copyWithPosition replaces only the position', () { + const position = ComponentPosition(x: 5, y: 6); + final copy = component.copyWithPosition(position); + + expect(copy.position, equals(position)); + expect( + copy.toJson()..remove('position'), + equals(component.toJson()..remove('position')), + ); + }); + + test('copyWithAnchor replaces only the anchor', () { + const anchor = ComponentAnchor(x: 0.25, y: 1); + final copy = component.copyWithAnchor(anchor); + + expect(copy.anchor, equals(anchor)); + expect( + copy.toJson()..remove('anchor'), + equals(component.toJson()..remove('anchor')), + ); + }); + + test('is anchored at its top left corner when saved without an ' + 'anchor', () { + final json = component.toJson()..remove('anchor'); + + expect( + (Component.fromJson(json) as AnchoredComponent).anchor, + equals(ComponentAnchor.topLeft), + ); + }); + + test('copyWithAngle replaces only the angle', () { + const angle = ComponentAngle(radians: 3); + final copy = component.copyWithAngle(angle); + + expect(copy.angle, equals(angle)); + expect( + copy.toJson()..remove('angle'), + equals(component.toJson()..remove('angle')), + ); + }); + + test('is not rotated when saved without an angle', () { + final json = component.toJson()..remove('angle'); + + expect( + (Component.fromJson(json) as RotatedComponent).angle, + equals(ComponentAngle.zero), + ); + }); + + test('copyWithVertices replaces only the vertices', () { + const vertices = ComponentVertices(); + final copy = component.copyWithVertices(vertices); + + expect(copy.vertices, equals(vertices)); + expect( + copy.toJson()..remove('vertices'), + equals(component.toJson()..remove('vertices')), + ); + }); + + test('copyWithCollision replaces only the collision', () { + const collision = ComponentCollision(isSolid: true); + final copy = component.copyWithCollision(collision); + + expect(copy.collision, equals(collision)); + expect( + copy.toJson()..remove('collision'), + equals(component.toJson()..remove('collision')), + ); + }); + + test('copyWithName replaces only the name', () { + final copy = component.copyWithName('Enemy'); + + expect(copy.name, equals('Enemy')); + expect( + copy.toJson()..remove('name'), + equals(component.toJson()..remove('name')), + ); + }); + + test('copyWithChildren replaces only the children', () { + final copy = component.copyWithChildren(const []); + + expect(copy.children, isEmpty); + expect( + copy.toJson()..remove('children'), + equals(component.toJson()..remove('children')), + ); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/position_component_test.dart b/packages/flame_studio/test/repositories/component_repository/models/position_component_test.dart new file mode 100644 index 00000000000..b7e91c646ab --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/position_component_test.dart @@ -0,0 +1,149 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(PositionComponent, () { + const component = PositionComponent( + name: 'Player', + position: ComponentPosition(x: 1, y: 2), + anchor: ComponentAnchor.center, + angle: ComponentAngle(radians: 1.5), + size: ComponentSize(width: 10, height: 20), + children: [RectangleComponent(name: 'rectangle1')], + ); + + test('supports value equality', () { + expect( + const PositionComponent(name: 'Player'), + equals(const PositionComponent(name: 'Player')), + ); + expect(component, isNot(equals(const PositionComponent(name: 'Player')))); + expect( + const PositionComponent(name: 'Player'), + isNot(equals(const RectangleComponent(name: 'Player'))), + ); + }); + + test('is a position component with a position and a size', () { + expect(component.type, equals(ComponentType.position)); + expect(component, isA()); + expect(component, isA()); + expect(component, isA()); + expect(component, isA()); + expect(component, isNot(isA())); + }); + + test('round-trips through JSON', () { + expect(Component.fromJson(component.toJson()), equals(component)); + }); + + test('toJson includes the type, properties and children', () { + expect( + component.toJson(), + equals({ + 'name': 'Player', + 'type': 'position', + 'children': [ + { + 'name': 'rectangle1', + 'type': 'rectangle', + 'children': [], + 'position': {'x': 0.0, 'y': 0.0}, + 'anchor': {'x': 0.0, 'y': 0.0}, + 'angle': {'radians': 0.0}, + 'size': {'width': 50.0, 'height': 50.0}, + 'paint': {'color': 0xFFFFFFFF, 'style': 'fill'}, + }, + ], + 'position': {'x': 1.0, 'y': 2.0}, + 'anchor': {'x': 0.5, 'y': 0.5}, + 'angle': {'radians': 1.5}, + 'size': {'width': 10.0, 'height': 20.0}, + }), + ); + }); + + test('copyWithPosition replaces only the position', () { + const position = ComponentPosition(x: 5, y: 6); + final copy = component.copyWithPosition(position); + + expect(copy.position, equals(position)); + expect( + copy.toJson()..remove('position'), + equals(component.toJson()..remove('position')), + ); + }); + + test('copyWithAnchor replaces only the anchor', () { + const anchor = ComponentAnchor(x: 0.25, y: 1); + final copy = component.copyWithAnchor(anchor); + + expect(copy.anchor, equals(anchor)); + expect( + copy.toJson()..remove('anchor'), + equals(component.toJson()..remove('anchor')), + ); + }); + + test('is anchored at its top left corner when saved without an ' + 'anchor', () { + final json = component.toJson()..remove('anchor'); + + expect( + (Component.fromJson(json) as AnchoredComponent).anchor, + equals(ComponentAnchor.topLeft), + ); + }); + + test('copyWithAngle replaces only the angle', () { + const angle = ComponentAngle(radians: 3); + final copy = component.copyWithAngle(angle); + + expect(copy.angle, equals(angle)); + expect( + copy.toJson()..remove('angle'), + equals(component.toJson()..remove('angle')), + ); + }); + + test('is not rotated when saved without an angle', () { + final json = component.toJson()..remove('angle'); + + expect( + (Component.fromJson(json) as RotatedComponent).angle, + equals(ComponentAngle.zero), + ); + }); + + test('copyWithSize replaces only the size', () { + const size = ComponentSize(width: 1, height: 2); + final copy = component.copyWithSize(size); + + expect(copy.size, equals(size)); + expect( + copy.toJson()..remove('size'), + equals(component.toJson()..remove('size')), + ); + }); + + test('copyWithName replaces only the name', () { + final copy = component.copyWithName('Enemy'); + + expect(copy.name, equals('Enemy')); + expect( + copy.toJson()..remove('name'), + equals(component.toJson()..remove('name')), + ); + }); + + test('copyWithChildren replaces only the children', () { + final copy = component.copyWithChildren(const []); + + expect(copy.children, isEmpty); + expect( + copy.toJson()..remove('children'), + equals(component.toJson()..remove('children')), + ); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/rectangle_component_test.dart b/packages/flame_studio/test/repositories/component_repository/models/rectangle_component_test.dart new file mode 100644 index 00000000000..30f2a3aa28d --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/rectangle_component_test.dart @@ -0,0 +1,161 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(RectangleComponent, () { + const component = RectangleComponent( + name: 'Player', + position: ComponentPosition(x: 1, y: 2), + anchor: ComponentAnchor.center, + angle: ComponentAngle(radians: 1.5), + size: ComponentSize(width: 10, height: 20), + paint: ComponentPaint(color: 0xFF00FF00, style: PaintStyle.stroke), + children: [RectangleComponent(name: 'rectangle1')], + ); + + test('supports value equality', () { + expect( + const RectangleComponent(name: 'Player'), + equals(const RectangleComponent(name: 'Player')), + ); + expect( + component, + isNot(equals(const RectangleComponent(name: 'Player'))), + ); + }); + + test('is a rectangle with a position, a size and a paint', () { + expect(component.type, equals(ComponentType.rectangle)); + expect(component, isA()); + expect(component, isA()); + expect(component, isA()); + expect(component, isA()); + expect(component, isA()); + }); + + test('round-trips through JSON', () { + expect(Component.fromJson(component.toJson()), equals(component)); + }); + + test('toJson includes the type, properties and children', () { + expect( + component.toJson(), + equals({ + 'name': 'Player', + 'type': 'rectangle', + 'children': [ + { + 'name': 'rectangle1', + 'type': 'rectangle', + 'children': [], + 'position': {'x': 0.0, 'y': 0.0}, + 'anchor': {'x': 0.0, 'y': 0.0}, + 'angle': {'radians': 0.0}, + 'size': {'width': 50.0, 'height': 50.0}, + 'paint': {'color': 0xFFFFFFFF, 'style': 'fill'}, + }, + ], + 'position': {'x': 1.0, 'y': 2.0}, + 'anchor': {'x': 0.5, 'y': 0.5}, + 'angle': {'radians': 1.5}, + 'size': {'width': 10.0, 'height': 20.0}, + 'paint': {'color': 0xFF00FF00, 'style': 'stroke'}, + }), + ); + }); + + test('copyWithPosition replaces only the position', () { + const position = ComponentPosition(x: 5, y: 6); + final copy = component.copyWithPosition(position); + + expect(copy.position, equals(position)); + expect( + copy.toJson()..remove('position'), + equals(component.toJson()..remove('position')), + ); + }); + + test('copyWithAnchor replaces only the anchor', () { + const anchor = ComponentAnchor(x: 0.25, y: 1); + final copy = component.copyWithAnchor(anchor); + + expect(copy.anchor, equals(anchor)); + expect( + copy.toJson()..remove('anchor'), + equals(component.toJson()..remove('anchor')), + ); + }); + + test('is anchored at its top left corner when saved without an ' + 'anchor', () { + final json = component.toJson()..remove('anchor'); + + expect( + (Component.fromJson(json) as AnchoredComponent).anchor, + equals(ComponentAnchor.topLeft), + ); + }); + + test('copyWithAngle replaces only the angle', () { + const angle = ComponentAngle(radians: 3); + final copy = component.copyWithAngle(angle); + + expect(copy.angle, equals(angle)); + expect( + copy.toJson()..remove('angle'), + equals(component.toJson()..remove('angle')), + ); + }); + + test('is not rotated when saved without an angle', () { + final json = component.toJson()..remove('angle'); + + expect( + (Component.fromJson(json) as RotatedComponent).angle, + equals(ComponentAngle.zero), + ); + }); + + test('copyWithSize replaces only the size', () { + const size = ComponentSize(width: 1, height: 2); + final copy = component.copyWithSize(size); + + expect(copy.size, equals(size)); + expect( + copy.toJson()..remove('size'), + equals(component.toJson()..remove('size')), + ); + }); + + test('copyWithPaint replaces only the paint', () { + const paint = ComponentPaint(color: 0xFF0000FF); + final copy = component.copyWithPaint(paint); + + expect(copy.paint, equals(paint)); + expect( + copy.toJson()..remove('paint'), + equals(component.toJson()..remove('paint')), + ); + }); + + test('copyWithName replaces only the name', () { + final copy = component.copyWithName('Enemy'); + + expect(copy.name, equals('Enemy')); + expect( + copy.toJson()..remove('name'), + equals(component.toJson()..remove('name')), + ); + }); + + test('copyWithChildren replaces only the children', () { + final copy = component.copyWithChildren(const []); + + expect(copy.children, isEmpty); + expect( + copy.toJson()..remove('children'), + equals(component.toJson()..remove('children')), + ); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/component_repository/models/rectangle_hitbox_component_test.dart b/packages/flame_studio/test/repositories/component_repository/models/rectangle_hitbox_component_test.dart new file mode 100644 index 00000000000..67da31da2c0 --- /dev/null +++ b/packages/flame_studio/test/repositories/component_repository/models/rectangle_hitbox_component_test.dart @@ -0,0 +1,164 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(RectangleHitboxComponent, () { + const component = RectangleHitboxComponent( + name: 'Player', + position: ComponentPosition(x: 1, y: 2), + anchor: ComponentAnchor.center, + angle: ComponentAngle(radians: 1.5), + size: ComponentSize(width: 10, height: 20), + collision: ComponentCollision( + type: HitboxCollisionType.passive, + isSolid: true, + ), + children: [RectangleComponent(name: 'rectangle1')], + ); + + test('supports value equality', () { + expect( + const RectangleHitboxComponent(name: 'Player'), + equals(const RectangleHitboxComponent(name: 'Player')), + ); + expect( + component, + isNot(equals(const RectangleHitboxComponent(name: 'Player'))), + ); + }); + + test('is a rectangle hitbox with a position, a size and a collision', () { + expect(component.type, equals(ComponentType.rectangleHitbox)); + expect(component, isA()); + expect(component, isA()); + expect(component, isA()); + expect(component, isA()); + expect(component, isA()); + }); + + test('round-trips through JSON', () { + expect(Component.fromJson(component.toJson()), equals(component)); + }); + + test('toJson includes the type, properties and children', () { + expect( + component.toJson(), + equals({ + 'name': 'Player', + 'type': 'rectangleHitbox', + 'children': [ + { + 'name': 'rectangle1', + 'type': 'rectangle', + 'children': [], + 'position': {'x': 0.0, 'y': 0.0}, + 'anchor': {'x': 0.0, 'y': 0.0}, + 'angle': {'radians': 0.0}, + 'size': {'width': 50.0, 'height': 50.0}, + 'paint': {'color': 0xFFFFFFFF, 'style': 'fill'}, + }, + ], + 'position': {'x': 1.0, 'y': 2.0}, + 'anchor': {'x': 0.5, 'y': 0.5}, + 'angle': {'radians': 1.5}, + 'size': {'width': 10.0, 'height': 20.0}, + 'collision': {'type': 'passive', 'isSolid': true}, + }), + ); + }); + + test('copyWithPosition replaces only the position', () { + const position = ComponentPosition(x: 5, y: 6); + final copy = component.copyWithPosition(position); + + expect(copy.position, equals(position)); + expect( + copy.toJson()..remove('position'), + equals(component.toJson()..remove('position')), + ); + }); + + test('copyWithAnchor replaces only the anchor', () { + const anchor = ComponentAnchor(x: 0.25, y: 1); + final copy = component.copyWithAnchor(anchor); + + expect(copy.anchor, equals(anchor)); + expect( + copy.toJson()..remove('anchor'), + equals(component.toJson()..remove('anchor')), + ); + }); + + test('is anchored at its top left corner when saved without an ' + 'anchor', () { + final json = component.toJson()..remove('anchor'); + + expect( + (Component.fromJson(json) as AnchoredComponent).anchor, + equals(ComponentAnchor.topLeft), + ); + }); + + test('copyWithAngle replaces only the angle', () { + const angle = ComponentAngle(radians: 3); + final copy = component.copyWithAngle(angle); + + expect(copy.angle, equals(angle)); + expect( + copy.toJson()..remove('angle'), + equals(component.toJson()..remove('angle')), + ); + }); + + test('is not rotated when saved without an angle', () { + final json = component.toJson()..remove('angle'); + + expect( + (Component.fromJson(json) as RotatedComponent).angle, + equals(ComponentAngle.zero), + ); + }); + + test('copyWithSize replaces only the size', () { + const size = ComponentSize(width: 1, height: 2); + final copy = component.copyWithSize(size); + + expect(copy.size, equals(size)); + expect( + copy.toJson()..remove('size'), + equals(component.toJson()..remove('size')), + ); + }); + + test('copyWithCollision replaces only the collision', () { + const collision = ComponentCollision(isSolid: true); + final copy = component.copyWithCollision(collision); + + expect(copy.collision, equals(collision)); + expect( + copy.toJson()..remove('collision'), + equals(component.toJson()..remove('collision')), + ); + }); + + test('copyWithName replaces only the name', () { + final copy = component.copyWithName('Enemy'); + + expect(copy.name, equals('Enemy')); + expect( + copy.toJson()..remove('name'), + equals(component.toJson()..remove('name')), + ); + }); + + test('copyWithChildren replaces only the children', () { + final copy = component.copyWithChildren(const []); + + expect(copy.children, isEmpty); + expect( + copy.toJson()..remove('children'), + equals(component.toJson()..remove('children')), + ); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/editor_preferences_repository/editor_preferences_repository_test.dart b/packages/flame_studio/test/repositories/editor_preferences_repository/editor_preferences_repository_test.dart new file mode 100644 index 00000000000..2d04042507a --- /dev/null +++ b/packages/flame_studio/test/repositories/editor_preferences_repository/editor_preferences_repository_test.dart @@ -0,0 +1,109 @@ +import 'package:flame_studio/clients/clients.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockKeyValueStorageClient() + extends Mock + implements KeyValueStorageClient; + +void main() { + group(EditorPreferencesRepository, () { + const projectPath = '/projects/game'; + const componentName = 'player'; + final key = EditorPreferencesRepository.componentZoomKey( + projectPath, + componentName, + ); + + late KeyValueStorageClient storage; + late EditorPreferencesRepository repository; + + setUp(() { + storage = _MockKeyValueStorageClient(); + repository = EditorPreferencesRepository(storage: storage); + + when(() => storage.write(any(), any())).thenAnswer((_) async {}); + }); + + test('componentZoomKey differs per project and component', () { + expect({ + EditorPreferencesRepository.componentZoomKey('/a', 'player'), + EditorPreferencesRepository.componentZoomKey('/b', 'player'), + EditorPreferencesRepository.componentZoomKey('/a', 'enemy'), + }, hasLength(3)); + }); + + group('getComponentZoom', () { + Future get() => repository.getComponentZoom( + projectPath: projectPath, + componentName: componentName, + ); + + test('returns the default zoom when nothing is stored', () async { + when(() => storage.read(key)).thenAnswer((_) async => null); + + expect(await get(), EditorPreferencesRepository.defaultZoom); + }); + + test('returns the stored zoom', () async { + when(() => storage.read(key)).thenAnswer((_) async => '2.5'); + + expect(await get(), 2.5); + }); + + test( + 'returns the default zoom when the stored value is unreadable', + () async { + when(() => storage.read(key)).thenAnswer((_) async => 'big'); + + expect(await get(), EditorPreferencesRepository.defaultZoom); + }, + ); + + test( + 'returns the default zoom when the stored value is not finite', + () async { + when(() => storage.read(key)).thenAnswer((_) async => 'NaN'); + + expect(await get(), EditorPreferencesRepository.defaultZoom); + }, + ); + + test('clamps the stored zoom', () async { + when(() => storage.read(key)).thenAnswer((_) async => '100'); + expect(await get(), EditorPreferencesRepository.maxZoom); + + when(() => storage.read(key)).thenAnswer((_) async => '0'); + expect(await get(), EditorPreferencesRepository.minZoom); + }); + }); + + group('setComponentZoom', () { + test('stores the zoom under the component key', () async { + await repository.setComponentZoom( + projectPath: projectPath, + componentName: componentName, + zoom: 1.5, + ); + + verify(() => storage.write(key, '1.5')).called(1); + }); + + test('clamps the zoom', () async { + await repository.setComponentZoom( + projectPath: projectPath, + componentName: componentName, + zoom: 50, + ); + + verify( + () => storage.write( + key, + EditorPreferencesRepository.maxZoom.toString(), + ), + ).called(1); + }); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/editor_preferences_repository/models/zoom_levels_test.dart b/packages/flame_studio/test/repositories/editor_preferences_repository/models/zoom_levels_test.dart new file mode 100644 index 00000000000..12b0540682e --- /dev/null +++ b/packages/flame_studio/test/repositories/editor_preferences_repository/models/zoom_levels_test.dart @@ -0,0 +1,25 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(ZoomLevels, () { + test('levels go from min to max, in order', () { + expect(ZoomLevels.all.first, ZoomLevels.min); + expect(ZoomLevels.all.last, ZoomLevels.max); + expect(ZoomLevels.all, orderedEquals([...ZoomLevels.all]..sort())); + expect(ZoomLevels.all, contains(1)); + }); + + test('next steps to the next level', () { + expect(ZoomLevels.next(1), 1.5); + expect(ZoomLevels.next(1.2), 1.5); + expect(ZoomLevels.next(ZoomLevels.max), isNull); + }); + + test('previous steps to the previous level', () { + expect(ZoomLevels.previous(1), 0.75); + expect(ZoomLevels.previous(1.2), 1); + expect(ZoomLevels.previous(ZoomLevels.min), isNull); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/project_repository/models/project_settings_test.dart b/packages/flame_studio/test/repositories/project_repository/models/project_settings_test.dart new file mode 100644 index 00000000000..4ee147d899f --- /dev/null +++ b/packages/flame_studio/test/repositories/project_repository/models/project_settings_test.dart @@ -0,0 +1,39 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(ProjectSettings, () { + test('defaults the output path to lib/components', () { + expect(const ProjectSettings().outputPath, 'lib/components'); + }); + + test('supports value equality', () { + expect( + const ProjectSettings(outputPath: 'lib/a'), + equals(const ProjectSettings(outputPath: 'lib/a')), + ); + }); + + test('copyWith replaces the given fields', () { + expect( + const ProjectSettings().copyWith(outputPath: 'lib/a'), + const ProjectSettings(outputPath: 'lib/a'), + ); + expect(const ProjectSettings().copyWith(), const ProjectSettings()); + }); + + test('round-trips through JSON', () { + const settings = ProjectSettings(outputPath: 'lib/a'); + + expect(ProjectSettings.fromJson(settings.toJson()), settings); + }); + + test('fromJson falls back to defaults for missing values', () { + expect(ProjectSettings.fromJson(const {}), const ProjectSettings()); + expect( + ProjectSettings.fromJson(const {'outputPath': 1}), + const ProjectSettings(), + ); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/project_repository/models/project_test.dart b/packages/flame_studio/test/repositories/project_repository/models/project_test.dart new file mode 100644 index 00000000000..c14751d57c7 --- /dev/null +++ b/packages/flame_studio/test/repositories/project_repository/models/project_test.dart @@ -0,0 +1,35 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(Project, () { + test('supports value equality', () { + expect(const Project(path: '/a'), equals(const Project(path: '/a'))); + expect(const Project(path: '/a'), isNot(const Project(path: '/b'))); + }); + + group('name', () { + test('is the last path segment', () { + expect(const Project(path: '/a/my_game').name, equals('my_game')); + }); + + test('ignores trailing separators', () { + expect(const Project(path: '/a/my_game/').name, equals('my_game')); + }); + + test('supports Windows paths', () { + expect(const Project(path: r'C:\a\my_game').name, equals('my_game')); + }); + + test('falls back to the path when there are no segments', () { + expect(const Project(path: '/').name, equals('/')); + }); + }); + + test('round trips through JSON', () { + const project = Project(path: '/a/my_game'); + + expect(Project.fromJson(project.toJson()), equals(project)); + }); + }); +} diff --git a/packages/flame_studio/test/repositories/project_repository/project_repository_test.dart b/packages/flame_studio/test/repositories/project_repository/project_repository_test.dart new file mode 100644 index 00000000000..da4d7f111d5 --- /dev/null +++ b/packages/flame_studio/test/repositories/project_repository/project_repository_test.dart @@ -0,0 +1,245 @@ +import 'dart:convert'; + +import 'package:flame_studio/clients/clients.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockKeyValueStorageClient() + extends Mock + implements KeyValueStorageClient; + +class _MockFileSystemClient() extends Mock implements FileSystemClient; + +String _encode(List paths) => + jsonEncode([for (final path in paths) Project(path: path).toJson()]); + +void main() { + group(ProjectRepository, () { + const key = ProjectRepository.recentProjectsKey; + + late KeyValueStorageClient storage; + late FileSystemClient fileSystem; + late ProjectRepository repository; + + setUp(() { + storage = _MockKeyValueStorageClient(); + fileSystem = _MockFileSystemClient(); + repository = ProjectRepository(storage: storage, fileSystem: fileSystem); + + when(() => storage.write(any(), any())).thenAnswer((_) async {}); + when(() => fileSystem.directoryExists(any())) + .thenAnswer((_) async => true); + }); + + group('getRecentProjects', () { + test('returns an empty list when nothing is stored', () async { + when(() => storage.read(key)).thenAnswer((_) async => null); + + expect(await repository.getRecentProjects(), isEmpty); + }); + + test('returns an empty list when stored data is corrupt', () async { + when(() => storage.read(key)).thenAnswer((_) async => 'not json'); + + expect(await repository.getRecentProjects(), isEmpty); + }); + + test('returns the stored projects', () async { + when(() => storage.read(key)) + .thenAnswer((_) async => _encode(['/a', '/b'])); + + expect( + await repository.getRecentProjects(), + equals(const [Project(path: '/a'), Project(path: '/b')]), + ); + }); + }); + + group('pickProject', () { + test('returns the picked project', () async { + when(() => fileSystem.pickDirectory()).thenAnswer((_) async => '/a'); + + expect(await repository.pickProject(), const Project(path: '/a')); + }); + + test('returns null when cancelled', () async { + when(() => fileSystem.pickDirectory()).thenAnswer((_) async => null); + + expect(await repository.pickProject(), isNull); + }); + }); + + group('openProject', () { + test('adds the project to the top of the recent projects', () async { + when(() => storage.read(key)).thenAnswer((_) async => _encode(['/a'])); + + await repository.openProject(const Project(path: '/b')); + + verify(() => storage.write(key, _encode(['/b', '/a']))).called(1); + }); + + test('moves an already recent project to the top', () async { + when(() => storage.read(key)) + .thenAnswer((_) async => _encode(['/a', '/b', '/c'])); + + await repository.openProject(const Project(path: '/b')); + + verify(() => storage.write(key, _encode(['/b', '/a', '/c']))).called(1); + }); + + test( + 'keeps at most ${ProjectRepository.maxRecentProjects} projects', + () async { + final paths = [for (var i = 0; i < 10; i++) '/$i']; + when(() => storage.read(key)).thenAnswer((_) async => _encode(paths)); + + await repository.openProject(const Project(path: '/new')); + + verify(() => storage.write(key, _encode(['/new', ...paths.take(9)]))) + .called(1); + }, + ); + + test( + 'removes the project and throws when its folder does not exist', + () async { + when(() => storage.read(key)) + .thenAnswer((_) async => _encode(['/a', '/b'])); + when(() => fileSystem.directoryExists('/b')) + .thenAnswer((_) async => false); + + await expectLater( + repository.openProject(const Project(path: '/b')), + throwsA( + isA().having( + (e) => e.project, + 'project', + const Project(path: '/b'), + ), + ), + ); + verify(() => storage.write(key, _encode(['/a']))).called(1); + }, + ); + }); + group('settings', () { + const project = Project(path: '/projects/my_game'); + const settingsPath = '/projects/my_game/.flame_studio/settings.json'; + + setUp(() { + when(() => fileSystem.writeFile(any(), any())).thenAnswer((_) async {}); + }); + + group('getSettings', () { + test('returns the defaults when no settings were saved', () async { + when(() => fileSystem.fileExists(settingsPath)) + .thenAnswer((_) async => false); + + expect( + await repository.getSettings(project), + const ProjectSettings(), + ); + }); + + test('returns the defaults when the settings are corrupt', () async { + when(() => fileSystem.fileExists(settingsPath)) + .thenAnswer((_) async => true); + when(() => fileSystem.readFile(settingsPath)) + .thenAnswer((_) async => 'not json'); + + expect( + await repository.getSettings(project), + const ProjectSettings(), + ); + }); + + test('returns the saved settings', () async { + when(() => fileSystem.fileExists(settingsPath)) + .thenAnswer((_) async => true); + when(() => fileSystem.readFile(settingsPath)) + .thenAnswer((_) async => '{"outputPath":"lib/game"}'); + + expect( + await repository.getSettings(project), + const ProjectSettings(outputPath: 'lib/game'), + ); + }); + }); + + group('saveSettings', () { + test('writes the normalized settings', () async { + final saved = await repository.saveSettings( + project, + const ProjectSettings(outputPath: ' lib/./game/components/ '), + ); + + expect( + saved, + const ProjectSettings(outputPath: 'lib/game/components'), + ); + verify( + () => fileSystem.writeFile( + settingsPath, + '{"outputPath":"lib/game/components"}', + ), + ).called(1); + }); + + for (final path in [ + '', + ' ', + '.', + 'lib/..', + '..', + '../other', + '/abs', + ]) { + test('throws for "$path"', () async { + await expectLater( + repository.saveSettings( + project, + ProjectSettings(outputPath: path), + ), + throwsA( + isA().having( + (e) => e.path, + 'path', + path, + ), + ), + ); + verifyNever(() => fileSystem.writeFile(any(), any())); + }); + } + }); + + group('pickOutputPath', () { + test('returns null when cancelled', () async { + when(() => fileSystem.pickDirectory()).thenAnswer((_) async => null); + + expect(await repository.pickOutputPath(project), isNull); + }); + + test('returns the picked folder relative to the project', () async { + when(() => fileSystem.pickDirectory()) + .thenAnswer((_) async => '/projects/my_game/lib/game'); + + expect(await repository.pickOutputPath(project), 'lib/game'); + }); + + for (final picked in ['/projects/other', '/projects/my_game']) { + test('throws when picking "$picked"', () async { + when(() => fileSystem.pickDirectory()) + .thenAnswer((_) async => picked); + + await expectLater( + repository.pickOutputPath(project), + throwsA(isA()), + ); + }); + } + }); + }); + }); +} diff --git a/packages/flame_studio/test/rotate_scale_drag_test.dart b/packages/flame_studio/test/rotate_scale_drag_test.dart deleted file mode 100644 index 7765ea76abf..00000000000 --- a/packages/flame_studio/test/rotate_scale_drag_test.dart +++ /dev/null @@ -1,179 +0,0 @@ -import 'dart:math'; - -import 'package:flame/components.dart'; -import 'package:flame/game.dart'; -import 'package:flame_studio/src/core/gizmo/gizmo_geometry.dart'; -import 'package:flame_studio/src/core/gizmo/rotate_drag.dart'; -import 'package:flame_studio/src/core/gizmo/scale_drag.dart'; -import 'package:flame_test/flame_test.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('GizmoGeometry.handleAt', () { - const geometry = GizmoGeometry( - corners: [], - anchor: Offset(100, 100), - xAxis: Offset(1, 0), - yAxis: Offset(0, 1), - ); - - test('only finds the ring when rotating', () { - expect( - geometry.handleAt(const Offset(150, 102), ring: true), - GizmoHandle.ring, - ); - expect( - geometry.handleAt(const Offset(100, 47), ring: true), - GizmoHandle.ring, - ); - expect(geometry.handleAt(const Offset(130, 100), ring: true), isNull); - expect(geometry.handleAt(const Offset(150, 100)), isNull); - }); - }); - - group('RotateDrag', () { - late PositionComponent component; - late GizmoGeometry geometry; - - Future setUpComponent(FlameGame game, {Vector2? parentScale}) async { - component = PositionComponent(anchor: Anchor.center); - game.world.add( - PositionComponent(scale: parentScale, children: [component]), - ); - await game.ready(); - geometry = GizmoGeometry.of(component).single; - } - - testWithFlameGame('rotates by the angle swept around the anchor', ( - game, - ) async { - await setUpComponent(game); - final drag = RotateDrag.start( - component, - geometry, - geometry.anchor + const Offset(50, 0), - snapStep: pi / 12, - )!; - - drag.update(Vector2(-50, 50)); - expect(component.angle, closeTo(pi / 2, 1e-9)); - - drag.update(Vector2(-50, -50)); - expect(component.angle, closeTo(-pi / 2, 1e-9)); - - drag.cancel(); - expect(component.angle, 0); - }); - - testWithFlameGame('snaps to multiples of 15 degrees', (game) async { - await setUpComponent(game); - final drag = RotateDrag.start( - component, - geometry, - geometry.anchor + const Offset(50, 0), - snapStep: pi / 12, - )!; - - // Sweeps about 21.8 degrees. - drag.update(Vector2(0, 20), snap: true); - expect(component.angle, closeTo(pi / 12, 1e-9)); - }); - - testWithFlameGame('rotates the other way in a mirrored parent', ( - game, - ) async { - await setUpComponent(game, parentScale: Vector2(-1, 1)); - RotateDrag.start( - component, - geometry, - geometry.anchor + const Offset(50, 0), - snapStep: pi / 12, - )!.update(Vector2(-50, 50)); - expect(component.angle, closeTo(-pi / 2, 1e-9)); - }); - }); - - group('ScaleDrag', () { - late PositionComponent component; - late GizmoGeometry geometry; - - Future setUpComponent(FlameGame game) async { - component = PositionComponent(size: Vector2.all(10)); - game.world.add(component); - await game.ready(); - geometry = GizmoGeometry.of(component).single; - } - - testWithFlameGame('scales along the dragged axis', (game) async { - await setUpComponent(game); - - ScaleDrag.start( - component, - GizmoHandle.x, - geometry, - snapStep: 0.1, - )!.update(Vector2(40, 30)); - expect(component.scale, closeToVector(Vector2(2, 1))); - - ScaleDrag.start( - component, - GizmoHandle.y, - geometry, - snapStep: 0.1, - )!.update(Vector2(40, -20)); - expect(component.scale, closeToVector(Vector2(2, 0.5))); - }); - - testWithFlameGame('scales uniformly with the square handle', (game) async { - await setUpComponent(game); - final drag = ScaleDrag.start( - component, - GizmoHandle.free, - geometry, - snapStep: 0.1, - )!; - - drag.update(Vector2.all(20 * sqrt2)); - expect(component.scale, closeToVector(Vector2.all(2))); - - drag.cancel(); - expect(component.scale, closeToVector(Vector2.all(1))); - }); - - testWithFlameGame('snaps to multiples of 0.1', (game) async { - await setUpComponent(game); - ScaleDrag.start( - component, - GizmoHandle.x, - geometry, - snapStep: 0.1, - )!.update(Vector2(5, 0), snap: true); - expect(component.scale, closeToVector(Vector2(1.1, 1))); - }); - - testWithFlameGame('only snaps the dragged axes', (game) async { - await setUpComponent(game); - component.scale = Vector2(1.23, 1.37); - ScaleDrag.start( - component, - GizmoHandle.x, - geometry, - snapStep: 0.1, - )!.update(Vector2.zero(), snap: true); - expect(component.scale, closeToVector(Vector2(1.2, 1.37))); - }); - - testWithFlameGame('does not scale with the ring', (game) async { - await setUpComponent(game); - expect( - ScaleDrag.start( - component, - GizmoHandle.ring, - geometry, - snapStep: 0.1, - ), - isNull, - ); - }); - }); -} diff --git a/packages/flame_studio/test/vertices_editor/bloc/vertices_editor_cubit_test.dart b/packages/flame_studio/test/vertices_editor/bloc/vertices_editor_cubit_test.dart new file mode 100644 index 00000000000..486995b2100 --- /dev/null +++ b/packages/flame_studio/test/vertices_editor/bloc/vertices_editor_cubit_test.dart @@ -0,0 +1,211 @@ +import 'package:bloc_test/bloc_test.dart'; +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flame_studio/vertices_editor/vertices_editor.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(VerticesEditorCubit, () { + const triangle = ComponentVertices(); + const square = ComponentVertices(ComponentVertices.square); + + test('starts editing the given vertices, with nothing selected', () { + final state = VerticesEditorCubit(square).state; + + expect(state.vertices, equals(square.vertices)); + expect(state.selectedIndex, isNull); + expect(state.hasChanges, isFalse); + expect(state.canDelete, isTrue); + }); + + test('cannot delete vertices of a triangle', () { + expect(VerticesEditorCubit(triangle).state.canDelete, isFalse); + }); + + blocTest( + 'vertexSelected selects and unselects vertices', + build: () => VerticesEditorCubit(triangle), + act: (cubit) => cubit + ..vertexSelected(1) + ..vertexSelected(null), + expect: () => [ + VerticesEditorState(initial: triangle, selectedIndex: 1), + VerticesEditorState(initial: triangle), + ], + ); + + blocTest( + 'vertexMoved moves a vertex', + build: () => VerticesEditorCubit(triangle), + act: (cubit) => cubit.vertexMoved(1, 60, 70), + expect: () => [ + VerticesEditorState( + initial: triangle, + vertices: const [ + ComponentVertex(25, 0), + ComponentVertex(60, 70), + ComponentVertex(0, 50), + ], + ), + ], + verify: (cubit) => expect(cubit.state.hasChanges, isTrue), + ); + + blocTest( + 'vertexInserted adds a vertex after the start of the edge and ' + 'selects it', + build: () => VerticesEditorCubit(triangle), + act: (cubit) => cubit.vertexInserted(2, 10, 20), + expect: () => [ + VerticesEditorState( + initial: triangle, + vertices: const [ + ...ComponentVertices.triangle, + ComponentVertex(10, 20), + ], + selectedIndex: 3, + ), + ], + ); + + blocTest( + 'selectedVertexDeleted removes the selected vertex', + build: () => VerticesEditorCubit(square), + seed: () => VerticesEditorState(initial: square, selectedIndex: 0), + act: (cubit) => cubit.selectedVertexDeleted(), + expect: () => [ + VerticesEditorState( + initial: square, + vertices: ComponentVertices.square.sublist(1), + ), + ], + ); + + blocTest( + 'selectedVertexDeleted keeps at least 3 vertices', + build: () => VerticesEditorCubit(triangle), + seed: () => VerticesEditorState(initial: triangle, selectedIndex: 0), + act: (cubit) => cubit.selectedVertexDeleted(), + expect: () => const [], + ); + + blocTest( + 'vertexDeleted keeps the selection on the same vertex', + build: () => VerticesEditorCubit(square), + seed: () => VerticesEditorState(initial: square, selectedIndex: 2), + act: (cubit) => cubit + ..vertexDeleted(0) + ..vertexDeleted(2), + expect: () => [ + VerticesEditorState( + initial: square, + vertices: ComponentVertices.square.sublist(1), + selectedIndex: 1, + ), + ], + ); + + blocTest( + 'vertexDeleted keeps vertices after the selected one selected', + build: () => VerticesEditorCubit(square), + seed: () => VerticesEditorState(initial: square, selectedIndex: 0), + act: (cubit) => cubit.vertexDeleted(3), + expect: () => [ + VerticesEditorState( + initial: square, + vertices: ComponentVertices.square.sublist(0, 3), + selectedIndex: 0, + ), + ], + ); + + blocTest( + 'selectedVertexDeleted does nothing without a selection', + build: () => VerticesEditorCubit(square), + act: (cubit) => cubit.selectedVertexDeleted(), + expect: () => const [], + ); + + test('result places the vertices like Flame does', () { + final cubit = VerticesEditorCubit(triangle)..vertexMoved(0, -10, -20); + + expect( + cubit.state.result, + equals( + const ComponentVertices([ + ComponentVertex(0, 0), + ComponentVertex(60, 70), + ComponentVertex(10, 70), + ]), + ), + ); + }); + + test('moving the whole shape is not a change', () { + final cubit = VerticesEditorCubit(triangle); + for (final (index, vertex) in triangle.vertices.indexed) { + cubit.vertexMoved(index, vertex.x + 5, vertex.y + 5); + } + + expect(cubit.state.hasChanges, isFalse); + }); + + group('zoom', () { + test('starts at 100%', () { + final state = VerticesEditorCubit(square).state; + + expect(state.zoom, equals(1)); + expect(state.canZoomIn, isTrue); + expect(state.canZoomOut, isTrue); + }); + + blocTest( + 'zoomedIn, zoomedOut and zoomReset change the zoom', + build: () => VerticesEditorCubit(square), + act: (cubit) => cubit + ..zoomedIn() + ..zoomedIn() + ..zoomReset() + ..zoomedOut(), + expect: () => [ + isA().having((s) => s.zoom, 'zoom', 1.5), + isA().having((s) => s.zoom, 'zoom', 2), + isA().having((s) => s.zoom, 'zoom', 1), + isA().having((s) => s.zoom, 'zoom', 0.75), + ], + ); + + blocTest( + 'does not zoom past the largest and smallest levels', + build: () => VerticesEditorCubit(square), + seed: () => VerticesEditorState(initial: square, zoom: 8), + act: (cubit) => cubit.zoomedIn(), + expect: () => const [], + verify: (cubit) { + expect(cubit.state.canZoomIn, isFalse); + expect( + VerticesEditorState(initial: square, zoom: 0.1).canZoomOut, + isFalse, + ); + }, + ); + + blocTest( + 'zooming keeps the edits', + build: () => VerticesEditorCubit(square), + act: (cubit) => cubit + ..vertexMoved(0, 5, 5) + ..zoomedIn(), + skip: 1, + expect: () => [ + isA() + .having((s) => s.zoom, 'zoom', 1.5) + .having( + (s) => s.vertices.first, + 'vertex', + const ComponentVertex(5, 5), + ), + ], + ); + }); + }); +} diff --git a/packages/flame_studio/test/vertices_editor/view/vertices_editor_dialog_test.dart b/packages/flame_studio/test/vertices_editor/view/vertices_editor_dialog_test.dart new file mode 100644 index 00000000000..8a1608e7154 --- /dev/null +++ b/packages/flame_studio/test/vertices_editor/view/vertices_editor_dialog_test.dart @@ -0,0 +1,370 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flame_studio/vertices_editor/vertices_editor.dart'; +import 'package:flame_studio/vertices_editor/widgets/widgets.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(VerticesEditorDialog, () { + const square = ComponentVertices(ComponentVertices.square); + + late ComponentVertices? result; + + Future openDialog( + WidgetTester tester, { + ComponentVertices vertices = square, + }) async { + result = null; + tester.view.physicalSize = const Size(1200, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) => TextButton( + onPressed: () async { + result = await VerticesEditorDialog.show( + context, + vertices: vertices, + paint: const ComponentPaint(style: PaintStyle.stroke), + ); + }, + child: const Text('Open'), + ), + ), + ), + ); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + } + + Finder canvas() => find.descendant( + of: find.byType(VerticesCanvas), + matching: find.byType(CustomPaint), + ); + + /// Where the local [vertex] is on the screen. + Offset onScreen( + WidgetTester tester, + ComponentVertex vertex, { + List initial = ComponentVertices.square, + }) { + final transform = VerticesViewTransform.fit( + initial, + tester.getSize(canvas()), + ); + return tester.getTopLeft(canvas()) + transform.toCanvas(vertex); + } + + Future apply(WidgetTester tester) async { + await tester.tap(find.text('Apply')); + await tester.pumpAndSettle(); + } + + testWidgets('shows the number of vertices', (tester) async { + await openDialog(tester); + + expect(find.text('Edit vertices'), findsOneWidget); + expect(find.text('4 vertices'), findsOneWidget); + }); + + testWidgets('returns null when cancelled', (tester) async { + await openDialog(tester); + + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + + expect(find.byType(VerticesEditorDialog), findsNothing); + expect(result, isNull); + }); + + group('zoom', () { + VerticesViewTransform transform(WidgetTester tester) => + (tester.widget(canvas()).painter! as VerticesPainter) + .transform; + + testWidgets('zooms the canvas with the buttons', (tester) async { + await openDialog(tester); + final fitted = transform(tester); + expect(find.text('100%'), findsOneWidget); + + await tester.tap(find.byTooltip('Zoom in')); + await tester.pump(); + expect(find.text('150%'), findsOneWidget); + expect(transform(tester).scale, equals(fitted.scale * 1.5)); + + await tester.tap(find.byTooltip('Zoom out')); + await tester.tap(find.byTooltip('Zoom out')); + await tester.pump(); + expect(find.text('75%'), findsOneWidget); + + await tester.tap(find.text('75%')); + await tester.pump(); + expect(transform(tester), equals(fitted)); + }); + + testWidgets('zooms the canvas with the keyboard', (tester) async { + await openDialog(tester); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.equal); + await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); + await tester.pump(); + expect(find.text('150%'), findsOneWidget); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.minus); + await tester.sendKeyEvent(LogicalKeyboardKey.minus); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pump(); + expect(find.text('75%'), findsOneWidget); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.digit0); + await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); + await tester.pump(); + expect(find.text('100%'), findsOneWidget); + }); + + testWidgets('drags vertices on the zoomed canvas', (tester) async { + await openDialog(tester); + await tester.tap(find.byTooltip('Zoom in')); + await tester.tap(find.byTooltip('Zoom in')); + await tester.pump(); + final zoomed = transform(tester); + + // 2x zoom: 60 pixels are 30 local units. + await tester.dragFrom( + tester.getTopLeft(canvas()) + + zoomed.toCanvas(const ComponentVertex(50, 50)), + const Offset(60, 20), + ); + await tester.pump(); + await apply(tester); + + expect(result!.vertices[2], equals(const ComponentVertex(80, 60))); + }); + }); + + testWidgets('selects a vertex when it is tapped', (tester) async { + await openDialog(tester); + + await tester.tapAt(onScreen(tester, const ComponentVertex(50, 0))); + await tester.pump(); + expect(find.text('Vertex 2: (50, 0)'), findsOneWidget); + + await tester.tapAt(onScreen(tester, const ComponentVertex(25, 25))); + await tester.pump(); + expect(find.text('4 vertices'), findsOneWidget); + }); + + testWidgets('moves a vertex when it is dragged', (tester) async { + await openDialog(tester); + + await tester.dragFrom( + onScreen(tester, const ComponentVertex(50, 50)), + const Offset(30, 10), + ); + await tester.pump(); + await apply(tester); + + expect( + result, + equals( + const ComponentVertices([ + ComponentVertex(0, 0), + ComponentVertex(50, 0), + ComponentVertex(80, 60), + ComponentVertex(0, 50), + ]), + ), + ); + }); + + testWidgets('adds a vertex when the middle of an edge is tapped', ( + tester, + ) async { + await openDialog(tester); + + await tester.tapAt(onScreen(tester, const ComponentVertex(25, 0))); + await tester.pump(); + expect(find.text('Vertex 2: (25, 0)'), findsOneWidget); + await apply(tester); + + expect(result!.vertices, hasLength(5)); + expect(result!.vertices[1], equals(const ComponentVertex(25, 0))); + }); + + testWidgets('adds and moves a vertex dragged from the middle of an ' + 'edge', (tester) async { + await openDialog(tester); + + await tester.dragFrom( + onScreen(tester, const ComponentVertex(25, 0)), + const Offset(0, -20), + ); + await tester.pump(); + await apply(tester); + + expect(result!.vertices, hasLength(5)); + expect(result!.vertices[1], equals(const ComponentVertex(25, 0))); + expect(result!.vertices[0], equals(const ComponentVertex(0, 20))); + }); + + testWidgets('shows the add handle of hovered edges', (tester) async { + await openDialog(tester); + + final gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + addTearDown(gesture.removePointer); + await gesture.addPointer(location: Offset.zero); + await gesture.moveTo(onScreen(tester, const ComponentVertex(10, 0))); + await tester.pump(); + + final painter = tester.widget(canvas()).painter!; + expect((painter as VerticesPainter).hoveredEdge, equals(0)); + + await gesture.moveTo(onScreen(tester, const ComponentVertex(0, 0))); + await tester.pump(); + await gesture.moveTo(Offset.zero); + await tester.pump(); + }); + + testWidgets('deletes the selected vertex with the keyboard', ( + tester, + ) async { + await openDialog(tester); + + await tester.tapAt(onScreen(tester, const ComponentVertex(50, 0))); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.delete); + await tester.pump(); + expect(find.text('3 vertices'), findsOneWidget); + + // A triangle can't lose a vertex. + await tester.tapAt(onScreen(tester, const ComponentVertex(0, 0))); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + await tester.pump(); + final delete = tester.widget( + find.widgetWithIcon(IconButton, Icons.delete_outline), + ); + expect(delete.onPressed, isNull); + await apply(tester); + + expect( + result, + equals( + const ComponentVertices([ + ComponentVertex(0, 0), + ComponentVertex(50, 50), + ComponentVertex(0, 50), + ]), + ), + ); + }); + + testWidgets('deletes the selected vertex with the button', (tester) async { + await openDialog(tester); + + await tester.tapAt(onScreen(tester, const ComponentVertex(0, 0))); + await tester.pump(); + await tester.tap(find.byTooltip('Delete vertex')); + await tester.pump(); + + expect(find.text('3 vertices'), findsOneWidget); + }); + + group('side bar', () { + Finder field(int index, String label) => find.descendant( + of: find.byKey(ValueKey('4-$index')), + matching: find.widgetWithText(TextField, label), + ); + + testWidgets('lists the coordinates of every vertex', (tester) async { + await openDialog(tester); + + expect(find.byType(VerticesList), findsOneWidget); + expect(find.widgetWithText(TextField, 'X'), findsNWidgets(4)); + expect( + tester.widget(field(1, 'X')).controller!.text, + equals('50'), + ); + }); + + testWidgets('moves a vertex to the typed coordinates', (tester) async { + await openDialog(tester); + + await tester.enterText(field(2, 'X'), '62.5'); + await tester.enterText(field(2, 'Y'), '-10'); + await tester.pump(); + expect(find.text('Vertex 3: (62.5, -10)'), findsOneWidget); + await apply(tester); + + expect( + result, + equals( + const ComponentVertices([ + ComponentVertex(0, 10), + ComponentVertex(50, 10), + ComponentVertex(62.5, 0), + ComponentVertex(0, 60), + ]), + ), + ); + }); + + testWidgets('selects the vertex of the tapped row', (tester) async { + await openDialog(tester); + + await tester.tap(find.text('4')); + await tester.pump(); + + expect(find.text('Vertex 4: (0, 50)'), findsOneWidget); + }); + + testWidgets('follows the vertices dragged on the canvas', (tester) async { + await openDialog(tester); + + await tester.dragFrom( + onScreen(tester, const ComponentVertex(50, 50)), + const Offset(30, 10), + ); + await tester.pump(); + + expect( + tester.widget(field(2, 'X')).controller!.text, + equals('80'), + ); + }); + + testWidgets('deletes a vertex from its row', (tester) async { + await openDialog(tester); + + await tester.tap(find.byTooltip('Delete vertex 1')); + await tester.pump(); + + expect(find.text('3 vertices'), findsOneWidget); + final delete = tester.widget( + find.widgetWithIcon(IconButton, Icons.remove_circle_outline).first, + ); + expect(delete.onPressed, isNull); + }); + }); + + testWidgets('deletes a vertex from its context menu', (tester) async { + await openDialog(tester); + + await tester.tapAt( + onScreen(tester, const ComponentVertex(0, 50)), + buttons: kSecondaryButton, + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Delete vertex').last); + await tester.pumpAndSettle(); + + expect(find.text('3 vertices'), findsOneWidget); + }); + }); +} diff --git a/packages/flame_studio/test/vertices_editor/widgets/vertices_view_transform_test.dart b/packages/flame_studio/test/vertices_editor/widgets/vertices_view_transform_test.dart new file mode 100644 index 00000000000..9f22cb94295 --- /dev/null +++ b/packages/flame_studio/test/vertices_editor/widgets/vertices_view_transform_test.dart @@ -0,0 +1,87 @@ +import 'package:flame_studio/repositories/repositories.dart'; +import 'package:flame_studio/vertices_editor/widgets/widgets.dart'; +import 'package:flutter/painting.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(VerticesViewTransform, () { + const square = ComponentVertices.square; + + test('fit centers vertices that fit without scaling them', () { + final transform = VerticesViewTransform.fit(square, const Size(400, 300)); + + expect(transform.scale, equals(1)); + expect( + transform.toCanvas(const ComponentVertex(25, 25)), + equals(const Offset(200, 150)), + ); + }); + + test('fit scales down vertices that do not fit', () { + final transform = VerticesViewTransform.fit(const [ + ComponentVertex(0, 0), + ComponentVertex(1000, 0), + ComponentVertex(0, 100), + ], const Size(596, 400)); + + expect(transform.scale, equals(0.5)); + expect( + transform.toCanvas(const ComponentVertex(500, 50)), + equals(const Offset(298, 200)), + ); + }); + + test('toLocal is the inverse of toCanvas, rounded', () { + const transform = VerticesViewTransform(scale: 2, offset: Offset(10, 20)); + + expect( + transform.toCanvas(const ComponentVertex(5, 5)), + equals(const Offset(20, 30)), + ); + expect( + transform.toLocal(const Offset(20.8, 29.2)), + equals(const ComponentVertex(5, 5)), + ); + }); + + test('zoomed scales around the center, which stays in place', () { + const transform = VerticesViewTransform(scale: 2, offset: Offset(10, 20)); + const center = Offset(100, 100); + final zoomed = transform.zoomed(3, center); + + expect(zoomed.scale, equals(6)); + // The local point under the center doesn't move. + final local = (center - transform.offset) / transform.scale; + expect(zoomed.toCanvas(ComponentVertex(local.dx, local.dy)), center); + expect(transform.zoomed(1, center), equals(transform)); + }); + + group('hit testing', () { + const transform = VerticesViewTransform(); + + test('vertexAt finds the closest handle within the hit radius', () { + expect(transform.vertexAt(square, const Offset(48, 3)), equals(1)); + expect(transform.vertexAt(square, const Offset(25, 25)), isNull); + }); + + test('midpointAt finds the middle of edges', () { + expect(transform.midpointOf(square, 3), equals(const Offset(0, 25))); + expect(transform.midpointAt(square, const Offset(2, 24)), equals(3)); + expect(transform.midpointAt(square, Offset.zero), isNull); + }); + + test('edgeNear finds edges near the point', () { + expect(transform.edgeNear(square, const Offset(40, 52)), equals(2)); + expect(transform.edgeNear(square, const Offset(25, 25)), isNull); + expect( + transform.edgeNear(const [ + ComponentVertex(0, 0), + ComponentVertex(0, 0), + ComponentVertex(50, 50), + ], const Offset(-3, -4)), + isNotNull, + ); + }); + }); + }); +} diff --git a/packages/flame_studio/test/viewport_tool_test.dart b/packages/flame_studio/test/viewport_tool_test.dart deleted file mode 100644 index e44f51ae839..00000000000 --- a/packages/flame_studio/test/viewport_tool_test.dart +++ /dev/null @@ -1,51 +0,0 @@ -import 'package:flame/components.dart'; -import 'package:flame_studio/src/core/viewport_tool.dart'; -import 'package:flame_test/flame_test.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('selectableComponentsAt', () { - testWithFlameGame('returns the components under the point, topmost first', ( - game, - ) async { - final bottom = PositionComponent(size: Vector2.all(100)); - final top = PositionComponent(size: Vector2.all(10), priority: 1); - final elsewhere = PositionComponent( - position: Vector2(50, 50), - size: Vector2.all(10), - ); - game.world.addAll([bottom, top, elsewhere]); - await game.ready(); - - // The world origin is at the center of the 800x600 canvas. - expect(selectableComponentsAt(game, Vector2(405, 305)), [top, bottom]); - expect(selectableComponentsAt(game, Vector2(455, 355)), [ - elsewhere, - bottom, - ]); - expect(selectableComponentsAt(game, Vector2(10, 10)), isEmpty); - }); - }); - - group('pickNext', () { - final first = PositionComponent(); - final second = PositionComponent(); - final third = PositionComponent(); - final candidates = [first, second, third]; - - test('picks the topmost component', () { - expect(pickNext(candidates, null), first); - expect(pickNext(candidates, PositionComponent()), first); - }); - - test('cycles through the candidates', () { - expect(pickNext(candidates, first), second); - expect(pickNext(candidates, second), third); - expect(pickNext(candidates, third), first); - }); - - test('picks nothing without candidates', () { - expect(pickNext([], first), isNull); - }); - }); -} diff --git a/packages/flame_studio/test/widgets/zoom_controls_test.dart b/packages/flame_studio/test/widgets/zoom_controls_test.dart new file mode 100644 index 00000000000..d3d04448a28 --- /dev/null +++ b/packages/flame_studio/test/widgets/zoom_controls_test.dart @@ -0,0 +1,98 @@ +import 'package:flame_studio/widgets/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(ZoomControls, () { + Future pump( + WidgetTester tester, { + double zoom = 1, + VoidCallback? onZoomIn, + VoidCallback? onZoomOut, + VoidCallback? onReset, + }) { + return tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ZoomControls( + zoom: zoom, + onZoomIn: onZoomIn, + onZoomOut: onZoomOut, + onReset: onReset, + ), + ), + ), + ); + } + + testWidgets('shows the zoom as a percentage', (tester) async { + await pump(tester, zoom: 0.25); + + expect(find.text('25%'), findsOneWidget); + }); + + testWidgets('calls the callbacks', (tester) async { + final calls = []; + await pump( + tester, + onZoomIn: () => calls.add('in'), + onZoomOut: () => calls.add('out'), + onReset: () => calls.add('reset'), + ); + + await tester.tap(find.byTooltip('Zoom in')); + await tester.tap(find.byTooltip('Zoom out')); + await tester.tap(find.text('100%')); + + expect(calls, equals(['in', 'out', 'reset'])); + }); + + testWidgets('disables the buttons without callbacks', (tester) async { + await pump(tester); + + for (final tooltip in ['Zoom in', 'Zoom out']) { + final button = tester.widget( + find.ancestor( + of: find.byTooltip(tooltip), + matching: find.byType(IconButton), + ), + ); + expect(button.onPressed, isNull); + } + }); + }); + + group('zoomShortcuts', () { + testWidgets('binds Cmd and Ctrl with =, +, - and 0', (tester) async { + final calls = []; + await tester.pumpWidget( + CallbackShortcuts( + bindings: zoomShortcuts( + onZoomIn: () => calls.add('in'), + onZoomOut: () => calls.add('out'), + onReset: () => calls.add('reset'), + ), + child: const Focus(autofocus: true, child: SizedBox()), + ), + ); + + for (final modifier in [ + LogicalKeyboardKey.metaLeft, + LogicalKeyboardKey.controlLeft, + ]) { + await tester.sendKeyDownEvent(modifier); + await tester.sendKeyEvent(LogicalKeyboardKey.equal); + await tester.sendKeyEvent(LogicalKeyboardKey.minus); + await tester.sendKeyEvent(LogicalKeyboardKey.digit0); + await tester.sendKeyEvent(LogicalKeyboardKey.numpadAdd); + await tester.sendKeyUpEvent(modifier); + } + + expect( + calls, + equals(['in', 'out', 'reset', 'in', 'in', 'out', 'reset', 'in']), + ); + }); + }); +} diff --git a/packages/flame_studio/windows/.gitignore b/packages/flame_studio/windows/.gitignore new file mode 100644 index 00000000000..d492d0d98c8 --- /dev/null +++ b/packages/flame_studio/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/packages/flame_studio/windows/CMakeLists.txt b/packages/flame_studio/windows/CMakeLists.txt new file mode 100644 index 00000000000..3339e3e3e9d --- /dev/null +++ b/packages/flame_studio/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(flame_studio LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "flame_studio") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +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() +# Define settings for the Profile build mode. +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. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +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() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +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() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/packages/flame_studio/windows/flutter/CMakeLists.txt b/packages/flame_studio/windows/flutter/CMakeLists.txt new file mode 100644 index 00000000000..903f4899d6f --- /dev/null +++ b/packages/flame_studio/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +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") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === 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" + ${FLUTTER_TARGET_PLATFORM} $ + 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/packages/flame_studio/windows/flutter/generated_plugin_registrant.cc b/packages/flame_studio/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 00000000000..77ab7a09ab6 --- /dev/null +++ b/packages/flame_studio/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FileSelectorWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FileSelectorWindows")); +} diff --git a/packages/flame_studio/windows/flutter/generated_plugin_registrant.h b/packages/flame_studio/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 00000000000..dc139d85a93 --- /dev/null +++ b/packages/flame_studio/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/flame_studio/windows/flutter/generated_plugins.cmake b/packages/flame_studio/windows/flutter/generated_plugins.cmake new file mode 100644 index 00000000000..277a56f870d --- /dev/null +++ b/packages/flame_studio/windows/flutter/generated_plugins.cmake @@ -0,0 +1,25 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + file_selector_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +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) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/packages/flame_studio/windows/runner/CMakeLists.txt b/packages/flame_studio/windows/runner/CMakeLists.txt new file mode 100644 index 00000000000..394917c053a --- /dev/null +++ b/packages/flame_studio/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/packages/flame_studio/windows/runner/Runner.rc b/packages/flame_studio/windows/runner/Runner.rc new file mode 100644 index 00000000000..5be29746b22 --- /dev/null +++ b/packages/flame_studio/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 +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#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", "xyz.bluefire" "\0" + VALUE "FileDescription", "flame_studio" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "flame_studio" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 xyz.bluefire. All rights reserved." "\0" + VALUE "OriginalFilename", "flame_studio.exe" "\0" + VALUE "ProductName", "flame_studio" "\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/packages/flame_studio/windows/runner/flutter_window.cpp b/packages/flame_studio/windows/runner/flutter_window.cpp new file mode 100644 index 00000000000..955ee3038f9 --- /dev/null +++ b/packages/flame_studio/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : 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()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + 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 opportunity 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/packages/flame_studio/windows/runner/flutter_window.h b/packages/flame_studio/windows/runner/flutter_window.h new file mode 100644 index 00000000000..6da0652f05f --- /dev/null +++ b/packages/flame_studio/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(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 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/packages/flame_studio/windows/runner/main.cpp b/packages/flame_studio/windows/runner/main.cpp new file mode 100644 index 00000000000..5152fcd28a8 --- /dev/null +++ b/packages/flame_studio/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.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); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"flame_studio", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/packages/flame_studio/windows/runner/resource.h b/packages/flame_studio/windows/runner/resource.h new file mode 100644 index 00000000000..66a65d1e4a7 --- /dev/null +++ b/packages/flame_studio/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/packages/flame_studio/windows/runner/resources/app_icon.ico b/packages/flame_studio/windows/runner/resources/app_icon.ico new file mode 100644 index 00000000000..c04e20caf63 Binary files /dev/null and b/packages/flame_studio/windows/runner/resources/app_icon.ico differ diff --git a/packages/flame_studio/windows/runner/runner.exe.manifest b/packages/flame_studio/windows/runner/runner.exe.manifest new file mode 100644 index 00000000000..153653e8d67 --- /dev/null +++ b/packages/flame_studio/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/packages/flame_studio/windows/runner/utils.cpp b/packages/flame_studio/windows/runner/utils.cpp new file mode 100644 index 00000000000..3cb71466549 --- /dev/null +++ b/packages/flame_studio/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#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(); + } + // First, find the length of the string with a safe upper bound (CWE-126). + // UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING. + int input_length = static_cast(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS)); + // Now use that bounded length to determine the required buffer size. + // When an explicit length is passed, WideCharToMultiByte does not include + // the null terminator in its returned size. + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || static_cast(target_length) > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/packages/flame_studio/windows/runner/utils.h b/packages/flame_studio/windows/runner/utils.h new file mode 100644 index 00000000000..3879d547557 --- /dev/null +++ b/packages/flame_studio/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/packages/flame_studio/windows/runner/win32_window.cpp b/packages/flame_studio/windows/runner/win32_window.cpp new file mode 100644 index 00000000000..60608d0fe5b --- /dev/null +++ b/packages/flame_studio/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// 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 registrar 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::Create(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, + 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; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// 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; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + 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. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/packages/flame_studio/windows/runner/win32_window.h b/packages/flame_studio/windows/runner/win32_window.h new file mode 100644 index 00000000000..e901dde684e --- /dev/null +++ b/packages/flame_studio/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#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 a win32 window with |title| that is positioned and sized 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 this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // 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 + // responds 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; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + 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/pubspec.yaml b/pubspec.yaml index e71779f9897..d5ced95a81b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -3,7 +3,8 @@ repository: https://github.com/flame-engine/flame workspace: - doc/flame/examples - doc/tutorials/**/app - - packages/** + - packages/* + - packages/*/* - examples - examples/games/**