From 907166f4a7ee82fa2cc0f61e0584848d67431083 Mon Sep 17 00:00:00 2001 From: Pascal Garber Date: Tue, 24 Nov 2026 13:23:06 +0100 Subject: [PATCH 1/2] feat(engine): find where each flag is used --- apps/maker-gjs/src/services/flags-edit.ts | 8 +- .../src/services/project-store.spec.ts | 8 +- apps/maker-gjs/src/services/project-store.ts | 4 +- .../engine/src/format/flag-usages.spec.ts | 164 ++++++++++++++++++ packages/engine/src/format/flag-usages.ts | 128 ++++++++++++++ packages/engine/src/format/index.ts | 1 + .../engine/src/format/migrate-flags.spec.ts | 14 +- packages/engine/src/format/migrate-flags.ts | 32 ---- .../engine/src/sync/project-operations.ts | 2 +- packages/engine/src/test.mts | 2 + 10 files changed, 310 insertions(+), 53 deletions(-) create mode 100644 packages/engine/src/format/flag-usages.spec.ts create mode 100644 packages/engine/src/format/flag-usages.ts diff --git a/apps/maker-gjs/src/services/flags-edit.ts b/apps/maker-gjs/src/services/flags-edit.ts index cf7a24a2..bfa013ac 100644 --- a/apps/maker-gjs/src/services/flags-edit.ts +++ b/apps/maker-gjs/src/services/flags-edit.ts @@ -3,7 +3,7 @@ import { type FlagKind, type FlagUsage, defaultFlagInitial, - findFlagUsage, + findFlagUsages, newFlagId, } from '@pixelrpg/engine' @@ -33,9 +33,9 @@ export function newFlag(list: readonly FlagData[], name: string, kind: FlagKind /** Where `flagId` is referenced, across the library and every loaded map. */ export function flagUsage( - data: Parameters[0], - maps: Parameters[1], + data: Parameters[0], + maps: Parameters[1], flagId: string, ): FlagUsage[] { - return findFlagUsage(data, maps, flagId) + return findFlagUsages(data, maps).get(flagId) ?? [] } diff --git a/apps/maker-gjs/src/services/project-store.spec.ts b/apps/maker-gjs/src/services/project-store.spec.ts index 8d37f228..3dee6fd1 100644 --- a/apps/maker-gjs/src/services/project-store.spec.ts +++ b/apps/maker-gjs/src/services/project-store.spec.ts @@ -1270,7 +1270,13 @@ export default async () => { store.setCollabSession(session) const refused = store.removeFlag('has-key') - expect(refused).toStrictEqual({ removed: false, reason: 'in-use', usage: [{ where: 'entity', id: 'door' }] }) + expect(refused.removed).toBe(false) + expect(refused.removed === false && refused.reason === 'in-use' ? refused.usage[0] : null).toMatchObject({ + flagId: 'has-key', + access: 'write', + entityId: 'door', + mapId: null, + }) expect(data.flags).toHaveLength(1) expect(session.sent).toHaveLength(0) diff --git a/apps/maker-gjs/src/services/project-store.ts b/apps/maker-gjs/src/services/project-store.ts index 862014f5..46932e1b 100644 --- a/apps/maker-gjs/src/services/project-store.ts +++ b/apps/maker-gjs/src/services/project-store.ts @@ -25,7 +25,7 @@ import { FLAG_UPSERT_KIND, type FlagData, type FlagKind, - findFlagUsage, + findFlagUsages, type CreditEntry, effectiveComponentRegistry, projectHasSimpleViewHiddenContent, @@ -540,7 +540,7 @@ export class ProjectStore { const data = this.data const previous = data?.flags?.find((f) => f.id === flagId) if (!data || !previous) return { removed: false, reason: 'unknown' } - const usage = findFlagUsage(data, this.mapDatas(), flagId) + const usage = findFlagUsages(data, this.mapDatas()).get(flagId) ?? [] if (usage.length > 0) return { removed: false, reason: 'in-use', usage } applyFlagRemove(data, flagId) this._persistProject() diff --git a/packages/engine/src/format/flag-usages.spec.ts b/packages/engine/src/format/flag-usages.spec.ts new file mode 100644 index 00000000..8ecfac96 --- /dev/null +++ b/packages/engine/src/format/flag-usages.spec.ts @@ -0,0 +1,164 @@ +import { describe, expect, it } from '@gjsify/unit' + +import blankStarter from '../../../../games/blank-starter/game-project.json' with { type: 'json' } +import zeldaLike from '../../../../games/zelda-like/game-project.json' with { type: 'json' } +import blankScene from '../../../../games/blank-starter/maps/blank-scene.json' with { type: 'json' } +import kokiri from '../../../../games/zelda-like/maps/kokiri-forest.json' with { type: 'json' } +import treeHouse from '../../../../games/zelda-like/maps/tree-house.json' with { type: 'json' } +import treeHouseCozy from '../../../../games/zelda-like/maps/tree-house-cozy.json' with { type: 'json' } +import type { GameProjectData, MapData } from '../types' +import { findFlagUsages } from './flag-usages' + +const setFlag = (flag: string) => ({ + type: 'actions', + actions: [{ id: 'a', type: 'set-flag', flag, value: true }], +}) + +function project(): GameProjectData { + return { + entityLibrary: [ + { + id: 'door', + name: 'Door', + components: [ + setFlag('key'), + { + type: 'actions', + actions: [{ id: 'c', type: 'change-counter', flag: 'coins', amount: 1 }], + }, + ], + states: [ + { id: 'open', when: { flag: 'key' }, components: [] }, + { + id: 'locked', + when: { + type: 'all', + of: [ + { type: 'counter', flag: 'coins', op: '>', value: 2 }, + { flag: 'key', equals: false }, + ], + }, + components: [], + }, + { + id: 'never', + when: { type: 'not', of: { type: 'flag-is', flag: 'moon' } }, + components: [], + }, + ], + }, + ], + } as unknown as GameProjectData +} + +const map = { + id: 'm', + objectPlacements: [ + { + id: 'sign', + defId: 'door', + overrides: { + components: [ + { + type: 'actions', + actions: [ + { id: 'x', type: 'show-text', text: 'hi' }, + { + id: 'y', + type: 'ask', + prompt: 'q', + options: [ + { + id: 'o', + label: 'a', + actions: [{ id: 'z', type: 'set-flag', flag: 'mood', value: 'x' }], + }, + ], + }, + ], + }, + ], + }, + }, + { + id: 'chest', + inline: { + id: 'chest-def', + name: 'C', + components: [], + states: [ + { + id: 's', + when: { type: 'any', of: [{ flag: 'moon' }] }, + components: [], + }, + ], + }, + }, + ], +} as unknown as MapData + +export default async () => { + await describe('findFlagUsages', async () => { + await it('reads shorthand, nested conditions and writes from the library', async () => { + const usages = findFlagUsages(project(), []) + expect(usages.get('key')!.map((u) => [u.access, u.via, u.stateIndex, u.actionIndex])).toStrictEqual([ + ['write', 'set-flag', null, 0], + ['read', 'condition', 0, null], + ['read', 'condition', 1, null], + ]) + expect(usages.get('coins')!.map((u) => [u.access, u.via, u.stateIndex, u.actionIndex])).toStrictEqual([ + ['write', 'change-counter', null, 0], + ['read', 'condition', 1, null], + ]) + expect(usages.get('moon')!.map((u) => u.stateIndex)).toStrictEqual([2]) + expect(usages.get('door')).toBe(undefined) + expect(usages.get('key')![0]).toMatchObject({ + mapId: null, + placementId: null, + entityId: 'door', + }) + }) + + await it('carries map and placement ids, nested ask answers and inline definitions', async () => { + const usages = findFlagUsages(project(), [map]) + expect(usages.get('mood')).toStrictEqual([ + { + flagId: 'mood', + access: 'write', + via: 'set-flag', + mapId: 'm', + placementId: 'sign', + entityId: 'door', + stateIndex: null, + actionIndex: 1, + }, + ]) + const moon = usages.get('moon')!.filter((u) => u.mapId === 'm') + expect(moon).toStrictEqual([ + { + flagId: 'moon', + access: 'read', + via: 'condition', + mapId: 'm', + placementId: 'chest', + entityId: 'chest-def', + stateIndex: 0, + actionIndex: null, + }, + ]) + }) + + await it('finds nothing in the shipped games, which name no flags', async () => { + expect( + findFlagUsages( + zeldaLike as unknown as GameProjectData, + [kokiri, treeHouse, treeHouseCozy] as unknown as MapData[], + ).size, + ).toBe(0) + expect( + findFlagUsages(blankStarter as unknown as GameProjectData, [blankScene] as unknown as MapData[]).size, + ).toBe(0) + }) + }) +} diff --git a/packages/engine/src/format/flag-usages.ts b/packages/engine/src/format/flag-usages.ts new file mode 100644 index 00000000..b7b43f84 --- /dev/null +++ b/packages/engine/src/format/flag-usages.ts @@ -0,0 +1,128 @@ +import type { ActionData } from '../types/data/ActionData.ts' +import type { ComponentData, EntityDefinition } from '../types/data/EntityDefinition.ts' +import type { GameProjectData } from '../types/data/GameProjectData.ts' +import type { MapData } from '../types/data/MapData.ts' + +/** + * "Where is this flag used?" — one pure pass over a project that lists + * every place a flag is read or written, so the editor can show the list + * and refuse to remove a flag something still names. This is the single + * source of truth: the removal check and the "Used in" list both read it. + */ + +/** How a place touches the flag: a condition reads it, an action writes it. */ +export type FlagAccess = 'read' | 'write' + +/** Which piece of data names the flag. */ +export type FlagUsageVia = 'condition' | 'set-flag' | 'change-counter' + +/** One place that reads or writes one flag. */ +export interface FlagUsage { + flagId: string + access: FlagAccess + via: FlagUsageVia + /** The map holding the placement; `null` for a library definition. */ + mapId: string | null + /** The placement; `null` for a library definition. */ + placementId: string | null + /** The definition: the library entry, a placement's `defId`, or its inline definition. */ + entityId: string + /** Index into the definition's `states`; `null` for the base components (or an override). */ + stateIndex: number | null + /** Index of the action in its `actions` list (a nested `ask` answer reports the `ask`'s index); `null` for a condition. */ + actionIndex: number | null +} + +type Emit = ( + flagId: string, + access: FlagAccess, + via: FlagUsageVia, + stateIndex: number | null, + actionIndex: number | null, +) => void + +function walkActions(actions: unknown, stateIndex: number | null, emit: Emit, outerIndex: number | null): void { + if (!Array.isArray(actions)) return + actions.forEach((raw: ActionData | null, i) => { + if (raw == null || typeof raw !== 'object') return + const index = outerIndex ?? i + if (raw.type === 'set-flag' && typeof raw.flag === 'string') emit(raw.flag, 'write', 'set-flag', stateIndex, index) + else if (raw.type === 'change-counter' && typeof raw.flag === 'string') { + emit(raw.flag, 'write', 'change-counter', stateIndex, index) + } else if (raw.type === 'ask' && Array.isArray(raw.options)) { + for (const option of raw.options) walkActions(option?.actions, stateIndex, emit, index) + } + }) +} + +function walkComponents(components: readonly ComponentData[] | undefined, stateIndex: number | null, emit: Emit): void { + for (const component of components ?? []) { + if (component?.type === 'actions') { + walkActions((component as { actions?: unknown }).actions, stateIndex, emit, null) + } + } +} + +/** The shorthand, each typed leaf, and the leaves inside all / any / not. */ +function walkCondition(when: unknown, stateIndex: number, emit: Emit): void { + if (when == null || typeof when !== 'object') return + const c = when as { type?: unknown; of?: unknown; flag?: unknown } + if (c.type === 'all' || c.type === 'any') { + if (Array.isArray(c.of)) for (const leaf of c.of) walkCondition(leaf, stateIndex, emit) + return + } + if (c.type === 'not') { + walkCondition(c.of, stateIndex, emit) + return + } + if (typeof c.flag === 'string') emit(c.flag, 'read', 'condition', stateIndex, null) +} + +function walkDefinition(def: EntityDefinition | undefined, emit: Emit): void { + if (!def) return + walkComponents(def.components, null, emit) + def.states?.forEach((state, i) => { + walkCondition(state.when, i, emit) + walkComponents(state.components, i, emit) + }) +} + +/** + * Every flag usage in the project, grouped by flag id (in the order found: + * library definitions first, then each map's placements). Flags nothing + * names are absent from the result. + */ +export function findFlagUsages( + data: Pick, + maps: readonly Pick[], +): Map { + const out = new Map() + const collector = + (mapId: string | null, placementId: string | null, entityId: string): Emit => + (flagId, access, via, stateIndex, actionIndex) => { + if (flagId.length === 0) return + const list = out.get(flagId) ?? [] + list.push({ + flagId, + access, + via, + mapId, + placementId, + entityId, + stateIndex, + actionIndex, + }) + out.set(flagId, list) + } + + for (const def of data.entityLibrary ?? []) walkDefinition(def, collector(null, null, def.id)) + for (const map of maps) { + for (const placement of map.objectPlacements ?? []) { + const entityId = placement.defId ?? placement.inline?.id ?? placement.id + const emit = collector(map.id, placement.id, entityId) + walkDefinition(placement.inline, emit) + walkComponents(placement.overrides?.components, null, emit) + } + } + return out +} diff --git a/packages/engine/src/format/index.ts b/packages/engine/src/format/index.ts index e7cdbce9..d955ec7c 100644 --- a/packages/engine/src/format/index.ts +++ b/packages/engine/src/format/index.ts @@ -1,5 +1,6 @@ // Auto-generated by `gjsify barrels` — do not edit by hand. +export * from './flag-usages' export * from './GameProjectFormat' export * from './MapFormat' export * from './migrate-dialogue' diff --git a/packages/engine/src/format/migrate-flags.spec.ts b/packages/engine/src/format/migrate-flags.spec.ts index 2c8e3a42..f3119b1e 100644 --- a/packages/engine/src/format/migrate-flags.spec.ts +++ b/packages/engine/src/format/migrate-flags.spec.ts @@ -10,7 +10,7 @@ import { initialFlagValues } from '../components/game-save-state.component' import type { GameProjectData, MapData } from '../types' import { flagIdFromName } from '../types' import { GameProjectFormat } from './GameProjectFormat' -import { findFlagUsage, migrateMapFlags, migrateProjectFlags } from './migrate-flags' +import { migrateMapFlags, migrateProjectFlags } from './migrate-flags' /** A project as an older editor wrote it: flags are the free text a author typed. */ function oldProject(): GameProjectData { @@ -146,18 +146,6 @@ export default async () => { expect(migrateMapFlags(project, map)).toBe(false) expect(JSON.stringify([project, map])).toBe(after) }) - - await it('finds where a flag is used', async () => { - const project = migrateProjectFlags(oldProject()) - const map = oldMap() - migrateMapFlags(project, map) - const usage = findFlagUsage(project, [map], flagIdFromName('Has Key')) - expect(usage).toStrictEqual([ - { where: 'entity', id: 'door' }, - { where: 'map', id: 'm' }, - ]) - expect(findFlagUsage(project, [map], 'nope')).toStrictEqual([]) - }) }) await describe('shipped games', async () => { diff --git a/packages/engine/src/format/migrate-flags.ts b/packages/engine/src/format/migrate-flags.ts index a5dbce15..2057a21e 100644 --- a/packages/engine/src/format/migrate-flags.ts +++ b/packages/engine/src/format/migrate-flags.ts @@ -126,35 +126,3 @@ export function migrateMapFlags(project: GameProjectData, map: MapData): boolean if (flags.length !== before) project.flags = flags return rewritten || flags.length !== before } - -/** Where a flag is referenced; used to refuse removing one that is in use. */ -export interface FlagUsage { - /** `'entity'`: a library definition; `'map'`: a placement on that map. */ - where: 'entity' | 'map' - /** The entity id or the map id. */ - id: string -} - -/** Every definition and map that references `flagId`, each listed once. */ -export function findFlagUsage( - data: Pick, - maps: readonly Pick[], - flagId: string, -): FlagUsage[] { - const out: FlagUsage[] = [] - for (const def of data.entityLibrary ?? []) { - let hit = false - visitDefinitionFlagRefs(def, (ref) => { - if (ref.holder.flag === flagId) hit = true - }) - if (hit) out.push({ where: 'entity', id: def.id }) - } - for (const map of maps) { - let hit = false - visitMapFlagRefs(map, (ref) => { - if (ref.holder.flag === flagId) hit = true - }) - if (hit) out.push({ where: 'map', id: map.id }) - } - return out -} diff --git a/packages/engine/src/sync/project-operations.ts b/packages/engine/src/sync/project-operations.ts index a8ecb66e..cb5e0c7c 100644 --- a/packages/engine/src/sync/project-operations.ts +++ b/packages/engine/src/sync/project-operations.ts @@ -530,7 +530,7 @@ export function applyFlagUpsert(data: GameProjectData, flag: unknown): FlagData /** * Drop the flag with this id IN PLACE. Idempotent; `false` when there was * none. References are NOT checked here — the editing side refuses a used - * flag (`findFlagUsage`) before it sends the op. + * flag (`findFlagUsages`) before it sends the op. */ export function applyFlagRemove(data: GameProjectData, flagId: string): boolean { const at = (data.flags ?? []).findIndex((f) => f.id === flagId) diff --git a/packages/engine/src/test.mts b/packages/engine/src/test.mts index 108c5bfa..f42b7355 100644 --- a/packages/engine/src/test.mts +++ b/packages/engine/src/test.mts @@ -38,6 +38,7 @@ import entitySpawnPlacementSuite from './entity/spawn-placement.spec.js' import entityValidateSuite from './entity/validate.spec.js' import characterAnimationsSuite from './format/character-animations.spec.js' import creditsValidationSuite from './format/credits-validation.spec.js' +import flagUsagesSuite from './format/flag-usages.spec.js' import migrateFlagsSuite from './format/migrate-flags.spec.js' import flagOperationsSuite from './sync/flag-operations.spec.js' import objectSystemValidationSuite from './format/object-system-validation.spec.js' @@ -162,6 +163,7 @@ run({ entityPlacementOverridesSuite, entitySpawnPlacementSuite, creditsValidationSuite, + flagUsagesSuite, migrateFlagsSuite, flagOperationsSuite, objectSystemValidationSuite, From bd0173cb36db31f3f8606666d823607ac8790cdb Mon Sep 17 00:00:00 2001 From: Pascal Garber Date: Tue, 24 Nov 2026 13:23:07 +0100 Subject: [PATCH 2/2] feat(maker): list where each flag is used --- .../maker-gjs/src/services/game-controller.ts | 25 +++++ .../src/services/game-flags.model.spec.ts | 91 +++++++++++++++++++ .../src/services/game-flags.model.ts | 79 ++++++++++++++++ apps/maker-gjs/src/services/game-section.ts | 2 +- apps/maker-gjs/src/test.mts | 2 + .../src/widgets/application-window.ts | 20 +++- apps/maker-gjs/src/widgets/game-view.blp | 59 ++++++++++++ apps/maker-gjs/src/widgets/game-view.ts | 39 +++++++- apps/maker-gjs/src/widgets/game/flags-list.ts | 60 ++++++++++++ docs/concepts/game-systems.md | 2 +- packages/translations/de.po | 45 +++++++++ packages/translations/org.pixelrpg.maker.pot | 45 +++++++++ scripts/capture-views.py | 45 ++++++++- 13 files changed, 509 insertions(+), 5 deletions(-) create mode 100644 apps/maker-gjs/src/services/game-flags.model.spec.ts create mode 100644 apps/maker-gjs/src/services/game-flags.model.ts create mode 100644 apps/maker-gjs/src/widgets/game/flags-list.ts diff --git a/apps/maker-gjs/src/services/game-controller.ts b/apps/maker-gjs/src/services/game-controller.ts index 017518f1..dd205561 100644 --- a/apps/maker-gjs/src/services/game-controller.ts +++ b/apps/maker-gjs/src/services/game-controller.ts @@ -12,6 +12,7 @@ import type { HeroOption, StartMapOption } from '../widgets/game/game-dialogs.ts import type { GameView, GameViewModel, LanguageRow } from '../widgets/game-view.ts' import { listCharacterViewModels } from './cast-controller-view-model.ts' import { buildGameCheckup } from './game-checkup.model.ts' +import { buildFlagRows } from './game-flags.model.ts' import { buildGameRulesModel } from './game-rules-model.ts' import { collectAtlasTeleports } from './project-loader.ts' import type { ProjectStore } from './project-store.ts' @@ -56,6 +57,10 @@ export interface CreditRemoveHost { reportCreditRemoved(name: string, undo: () => void): void /** "Test in": the language a test run speaks (`undefined` = the project default). */ setTestLocale(locale: string | undefined): void + /** A flag was removed: a toast whose Undo runs `undo`. */ + reportFlagRemoved(name: string, undo: () => void): void + /** A flag was kept because `count` places still name it. */ + reportFlagInUse(name: string, count: number): void } export class GameController { @@ -77,6 +82,7 @@ export class GameController { this.store.setLanguages(languages) }, setTestLocale: (locale) => host.setTestLocale(locale), + removeFlag: (flagId) => this._removeFlag(flagId, host), }) store.on('project-changed', (project) => { if (!project) { @@ -114,6 +120,24 @@ export class GameController { store.on('credits-changed', () => { if (this.store.project) this._rebuild() }) + // New, renamed or removed flags; map and library edits that change + // what uses them already re-render through their own events. + store.on('flags-changed', () => { + if (this.store.project) this._rebuild() + }) + } + + private _removeFlag(flagId: string, host: CreditRemoveHost): void { + const result = this.store.removeFlag(flagId) + if (result.removed) { + const previous = result.previous + host.reportFlagRemoved(previous.name, () => { + this.store.upsertFlag(previous) + }) + } else if ('reason' in result && result.reason === 'in-use') { + const name = this.store.flags().find((f) => f.id === flagId)?.name ?? flagId + host.reportFlagInUse(name, result.usage.length) + } } /** Persist a single project-metadata field edit (no row re-render). */ @@ -197,6 +221,7 @@ export class GameController { projectResource: resource, credits: this.store.credits(), languages: languageRows(data, maps), + flags: buildFlagRows({ project: data, maps, characterIds: characters.map((c) => c.id) }), } this.view.setData(model) } diff --git a/apps/maker-gjs/src/services/game-flags.model.spec.ts b/apps/maker-gjs/src/services/game-flags.model.spec.ts new file mode 100644 index 00000000..55086ec1 --- /dev/null +++ b/apps/maker-gjs/src/services/game-flags.model.spec.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from '@gjsify/unit' +import type { GameProjectData, MapData } from '@pixelrpg/engine' + +import { buildFlagRows } from './game-flags.model.ts' + +const project = { + flags: [ + { id: 'key', name: 'Has key', kind: 'yes-no' }, + { id: 'idle', name: 'Idle', kind: 'yes-no' }, + ], + entityLibrary: [ + { + id: 'door', + name: 'Door', + components: [ + { + type: 'actions', + actions: [{ id: 'a', type: 'set-flag', flag: 'key', value: true }], + }, + ], + states: [{ id: 's', when: { flag: 'ghost' }, components: [] }], + }, + { + id: 'hero', + name: 'Hero', + components: [], + states: [{ id: 's', when: { flag: 'key' }, components: [] }], + }, + ], +} as unknown as GameProjectData + +const maps = [ + { + id: 'm', + name: 'Forest', + objectPlacements: [ + { + id: 'p1', + defId: 'door', + overrides: { + name: 'Front door', + components: [ + { + type: 'actions', + actions: [{ id: 'b', type: 'set-flag', flag: 'key', value: true }], + }, + ], + }, + }, + ], + }, +] as unknown as MapData[] + +export default async () => { + await describe('buildFlagRows', async () => { + await it('keeps named flags first and appends unnamed used ids', async () => { + const rows = buildFlagRows({ project, maps, characterIds: ['hero'] }) + expect(rows.map((r) => r.id)).toStrictEqual(['key', 'idle', 'ghost']) + }) + + await it('leaves an unused flag with no usages', async () => { + const rows = buildFlagRows({ project, maps, characterIds: ['hero'] }) + expect(rows[1].usages.length).toBe(0) + }) + + await it('names placements by override and links by kind', async () => { + const key = buildFlagRows({ project, maps, characterIds: ['hero'] })[0].usages + const placed = key.find((u) => u.access === 'write' && u.mapName === 'Forest')! + expect(placed.thingName).toBe('Front door') + expect(placed.link).toStrictEqual({ + action: 'win.focus-placement', + target: ['m', 'p1'], + }) + const lib = key.find((u) => u.thingName === 'Hero')! + expect(lib.access).toBe('read') + expect(lib.link).toStrictEqual({ + action: 'win.open-character', + target: 'hero', + }) + const obj = buildFlagRows({ + project, + maps: [], + characterIds: ['hero'], + })[0].usages.find((u) => u.thingName === 'Door')! + expect(obj.link).toStrictEqual({ + action: 'win.open-object', + target: 'door', + }) + }) + }) +} diff --git a/apps/maker-gjs/src/services/game-flags.model.ts b/apps/maker-gjs/src/services/game-flags.model.ts new file mode 100644 index 00000000..e72e6e57 --- /dev/null +++ b/apps/maker-gjs/src/services/game-flags.model.ts @@ -0,0 +1,79 @@ +import { type FlagAccess, type FlagData, type FlagKind, type MapData, findFlagUsages } from '@pixelrpg/engine' +import type { GameProjectData } from '@pixelrpg/engine' + +import type { CheckupLink } from './game-checkup.model.ts' + +/** + * The Game page's Flags section as facts: one row per flag with every + * place that reads or writes it. String-free like `game-checkup.model.ts`; + * `widgets/game/flags-list.ts` owns the words. + */ + +/** One place a flag is used, with where a tap goes. */ +export interface FlagUsageRow { + /** Unique within its flag (a flag can be used twice by one thing). */ + readonly key: string + readonly access: FlagAccess + /** The thing's name (a placement's own name wins over its definition's). */ + readonly thingName: string + /** The map it stands on, or `null` for a library thing not placed here. */ + readonly mapName: string | null + readonly link: CheckupLink | null +} + +/** One flag and its usages. */ +export interface FlagRow { + readonly id: string + readonly name: string + readonly kind: FlagKind + readonly usages: readonly FlagUsageRow[] +} + +export interface FlagsModelInput { + readonly project: Pick + readonly maps: readonly MapData[] + /** Ids of library entries that are characters: their tap opens the Cast. */ + readonly characterIds: readonly string[] +} + +/** Every flag, named flags first by their order in the project; unnamed ids a project still uses follow. */ +export function buildFlagRows(input: FlagsModelInput): FlagRow[] { + const { project, maps, characterIds } = input + const usages = findFlagUsages(project, maps) + const defs = new Map((project.entityLibrary ?? []).map((d) => [d.id, d])) + const mapById = new Map(maps.map((m) => [m.id, m])) + const characters = new Set(characterIds) + + const rowFor = (flag: Pick): FlagRow => { + const list = usages.get(flag.id) ?? [] + return { + id: flag.id, + name: flag.name, + kind: flag.kind, + usages: list.map((u, i) => { + const map = u.mapId ? mapById.get(u.mapId) : undefined + const placement = map?.objectPlacements?.find((p) => p.id === u.placementId) + const def = defs.get(u.entityId) + const thingName = placement?.overrides?.name?.trim() || def?.name || u.entityId + const link: CheckupLink | null = + u.mapId && u.placementId + ? { action: 'win.focus-placement', target: [u.mapId, u.placementId] } + : defs.has(u.entityId) + ? { action: characters.has(u.entityId) ? 'win.open-character' : 'win.open-object', target: u.entityId } + : null + return { + key: `${u.mapId ?? ''}/${u.placementId ?? u.entityId}/${u.stateIndex ?? ''}/${u.actionIndex ?? ''}/${u.access}/${i}`, + access: u.access, + thingName, + mapName: map ? map.name?.trim() || map.id : null, + link, + } + }), + } + } + + const rows = (project.flags ?? []).map(rowFor) + const known = new Set(rows.map((r) => r.id)) + for (const id of usages.keys()) if (!known.has(id)) rows.push(rowFor({ id, name: id, kind: 'yes-no' })) + return rows +} diff --git a/apps/maker-gjs/src/services/game-section.ts b/apps/maker-gjs/src/services/game-section.ts index 6404d9ed..3cf99429 100644 --- a/apps/maker-gjs/src/services/game-section.ts +++ b/apps/maker-gjs/src/services/game-section.ts @@ -3,7 +3,7 @@ * title card with "Play from the start", which is what most visits are * for. Shared by `GameView` and the `win.game-section` action. */ -export const GAME_SECTIONS = ['start', 'rules', 'languages', 'checkup', 'about'] as const +export const GAME_SECTIONS = ['start', 'rules', 'languages', 'flags', 'checkup', 'about'] as const /** One of the Game page's sections. */ export type GameSection = (typeof GAME_SECTIONS)[number] diff --git a/apps/maker-gjs/src/test.mts b/apps/maker-gjs/src/test.mts index ca500298..aabd3232 100644 --- a/apps/maker-gjs/src/test.mts +++ b/apps/maker-gjs/src/test.mts @@ -20,6 +20,7 @@ import serialQueueSuite from './services/serial-queue.spec.js' import sceneNavigatorSuite from './services/scene-navigator.spec.js' import engineStateSyncSuite from './services/engine-state-sync.spec.js' import gameCheckupModelSuite from './services/game-checkup.model.spec.js' +import gameFlagsModelSuite from './services/game-flags.model.spec.js' import gameRulesModelSuite from './services/game-rules-model.spec.js' import gvariantSuite from './services/gvariant.spec.js' import lanDiscoverySuite from './services/lan-discovery.spec.js' @@ -118,6 +119,7 @@ run({ entityTemplatesSuite, entityVisualsSuite, gameCheckupModelSuite, + gameFlagsModelSuite, gameRulesModelSuite, gvariantSuite, instanceIdSuite, diff --git a/apps/maker-gjs/src/widgets/application-window.ts b/apps/maker-gjs/src/widgets/application-window.ts index 3a0393d2..247b96f5 100644 --- a/apps/maker-gjs/src/widgets/application-window.ts +++ b/apps/maker-gjs/src/widgets/application-window.ts @@ -24,7 +24,7 @@ import { SignalScope, type Tile, } from '@pixelrpg/gjs' -import { gettext as _ } from 'gettext' +import { gettext as _, ngettext } from 'gettext' import { installWindowAccels, WINDOW_SHORTCUTS } from '../actions/accels.ts' import { installBackActions } from '../actions/back-actions.ts' import { installCastActions } from '../actions/cast-actions.ts' @@ -1894,6 +1894,24 @@ export class ApplicationWindow extends Adw.ApplicationWindow implements EntityDe this._showUndoToast(_('Removed “%s”').replace('%s', name), undo) } + /** {@link CreditRemoveHost} — a flag was removed; Undo puts it back. */ + reportFlagRemoved(name: string, undo: () => void): void { + this._showUndoToast(_('Removed flag “%s”').replace('%s', name), undo) + } + + /** {@link CreditRemoveHost} — a used flag stays; the Flags list says where. */ + reportFlagInUse(name: string, count: number): void { + this._showToast( + ngettext( + '“%s” is still used in %d place. See Game › Flags.', + '“%s” is still used in %d places. See Game › Flags.', + count, + ) + .replace('%s', name) + .replace('%d', String(count)), + ) + } + /** {@link AnimationClearHost} — a cell was emptied; Undo restores its pictures. */ reportAnimationCleared(animationId: string, undo: () => void): void { this._showUndoToast(_('Cleared “%s”').replace('%s', animationId), undo) diff --git a/apps/maker-gjs/src/widgets/game-view.blp b/apps/maker-gjs/src/widgets/game-view.blp index a4b3ad2e..97902492 100644 --- a/apps/maker-gjs/src/widgets/game-view.blp +++ b/apps/maker-gjs/src/widgets/game-view.blp @@ -121,6 +121,27 @@ template $PixelRpgGameView : $PixelRpgResponsiveEditorView { }; } + Gtk.ListBoxRow { + child: Gtk.Box { + spacing: 12; + margin-top: 8; + margin-bottom: 8; + margin-start: 6; + margin-end: 6; + + Gtk.Image { + icon-name: "view-list-symbolic"; + } + + Gtk.Label { + label: _("Flags"); + xalign: 0; + hexpand: true; + ellipsize: end; + } + }; + } + Gtk.ListBoxRow { child: Gtk.Box { spacing: 12; @@ -385,6 +406,44 @@ template $PixelRpgGameView : $PixelRpgResponsiveEditorView { }; } + Gtk.StackPage { + name: "flags"; + + child: Gtk.ScrolledWindow { + hscrollbar-policy: never; + + Adw.Clamp { + maximum-size: 600; + tightening-threshold: 500; + + Gtk.Box { + orientation: vertical; + spacing: 24; + margin-top: 18; + margin-bottom: 24; + margin-start: 12; + margin-end: 12; + + Gtk.ListBox flags_list { + selection-mode: none; + + styles [ + "boxed-list", + ] + } + + // Shown instead of the list while the game has no flags. + Adw.StatusPage flags_empty { + icon-name: "view-list-symbolic"; + title: _("No flags yet"); + description: _("A flag is something your game remembers. It shows up here once you use one."); + visible: false; + } + } + } + }; + } + Gtk.StackPage { name: "checkup"; diff --git a/apps/maker-gjs/src/widgets/game-view.ts b/apps/maker-gjs/src/widgets/game-view.ts index b62dc4ad..116e3fcc 100644 --- a/apps/maker-gjs/src/widgets/game-view.ts +++ b/apps/maker-gjs/src/widgets/game-view.ts @@ -8,6 +8,7 @@ import { MapPreview, ProjectMenuButton, RosterChip, SignalScope } from '@pixelrp import { gettext as _, ngettext } from 'gettext' import type { CheckupLink, CheckupRow } from '../services/game-checkup.model.ts' +import type { FlagRow } from '../services/game-flags.model.ts' import type { GameRuleRow, GameRulesModel } from '../services/game-rules-model.ts' import { DEFAULT_GAME_SECTION, GAME_SECTIONS, type GameSection, isGameSection } from '../services/game-section.ts' import { @@ -23,6 +24,7 @@ import { } from '../services/credits-edit.ts' import { addLanguage, makeDefaultLanguage, removeLanguage } from '../services/languages-edit.ts' import { buildCheckupRow } from './game/checkup-list.ts' +import { buildFlagRow } from './game/flags-list.ts' import { CREDIT_ROLE_LABELS, presentCreditDialog } from './game/credit-dialog.ts' import { confirmRuleSwitchOff, @@ -48,6 +50,7 @@ const SECTION_TITLES: Record string> = { start: () => _('Start'), rules: () => _('Rules'), languages: () => _('Languages'), + flags: () => _('Flags'), checkup: () => _('Checkup'), about: () => _('About'), } @@ -81,6 +84,8 @@ export interface GameViewModel { credits: readonly CreditEntry[] /** The game's languages, default first, each with its count of missing texts. */ languages: readonly LanguageRow[] + /** Every flag with the places that read or write it. */ + flags: readonly FlagRow[] } /** One language of the game as the Languages section shows it. */ @@ -111,6 +116,8 @@ export interface GameViewCallbacks { setLanguages: (languages: ProjectLanguages) => void /** The language a test run speaks; session state, `undefined` = the project default. */ setTestLocale: (locale: string | undefined) => void + /** Remove one flag; the controller refuses a used one and tells the user why. */ + removeFlag: (flagId: string) => void } /** @@ -133,6 +140,8 @@ export class GameView extends ResponsiveEditorView { declare _cover: Adw.Bin declare _name_row: Adw.EntryRow declare _checkup_list: Gtk.ListBox + declare _flags_list: Gtk.ListBox + declare _flags_empty: Adw.StatusPage declare _start_map_row: Adw.ActionRow declare _hero_row: Adw.ActionRow declare _game_rules: Adw.PreferencesGroup @@ -174,6 +183,8 @@ export class GameView extends ResponsiveEditorView { 'cover', 'name_row', 'checkup_list', + 'flags_list', + 'flags_empty', 'start_map_row', 'hero_row', 'game_rules', @@ -195,7 +206,7 @@ export class GameView extends ResponsiveEditorView { section: GObject.ParamSpec.string( 'section', 'Section', - 'The open section: start, rules, languages, checkup or about', + 'The open section: start, rules, languages, flags, checkup or about', GObject.ParamFlags.READWRITE, DEFAULT_GAME_SECTION, ), @@ -362,6 +373,7 @@ export class GameView extends ResponsiveEditorView { this._setCheckup(model?.checkup ?? []) this._setCredits(model?.credits ?? []) this._setLanguages(model?.languages ?? []) + this._setFlags(model?.flags ?? []) // Rebuilt inside the loading fence so the freshly-created switches // don't echo their initial value back as a user edit. this._setGameRules(model?.gameRules ?? null) @@ -447,6 +459,31 @@ export class GameView extends ResponsiveEditorView { this.activate_action(link.action, GLib.Variant.new_tuple(target.map((id) => GLib.Variant.new_string(id)))) } + // ──────────────────────────────────────────────────────────── + // Flags + // ──────────────────────────────────────────────────────────── + + /** Rebuild the Flags list: one expandable row per flag, its usages inside. */ + private _setFlags(rows: readonly FlagRow[]): void { + let child = this._flags_list.get_first_child() + while (child) { + const next = child.get_next_sibling() + this._flags_list.remove(child) + child = next + } + for (const row of rows) { + this._flags_list.append( + buildFlagRow( + row, + (link) => this._activateLink(link), + () => this._callbacks?.removeFlag(row.id), + ), + ) + } + this._flags_list.set_visible(rows.length > 0) + this._flags_empty.set_visible(rows.length === 0) + } + // ──────────────────────────────────────────────────────────── // Start // ──────────────────────────────────────────────────────────── diff --git a/apps/maker-gjs/src/widgets/game/flags-list.ts b/apps/maker-gjs/src/widgets/game/flags-list.ts new file mode 100644 index 00000000..5f88ea14 --- /dev/null +++ b/apps/maker-gjs/src/widgets/game/flags-list.ts @@ -0,0 +1,60 @@ +import Adw from '@girs/adw-1' +import Gtk from '@girs/gtk-4.0' +import { gettext as _, ngettext } from 'gettext' + +import type { CheckupLink } from '../../services/game-checkup.model.ts' +import type { FlagRow, FlagUsageRow } from '../../services/game-flags.model.ts' + +/** "Used in 3 places" / "Not used yet" — the count shown in the flag's row. */ +export function flagUsageSummary(count: number): string { + if (count === 0) return _('Not used yet') + return ngettext('Used in %d place', 'Used in %d places', count).replace('%d', String(count)) +} + +function usageRow(usage: FlagUsageRow, onOpen: (link: CheckupLink) => void): Adw.ActionRow { + const reads = usage.access === 'read' + const subtitle = usage.mapName + ? reads + ? _('Checks it, on %s').replace('%s', usage.mapName) + : _('Changes it, on %s').replace('%s', usage.mapName) + : reads + ? _('Checks it') + : _('Changes it') + const row = new Adw.ActionRow({ + title: usage.thingName, + subtitle, + useMarkup: false, + titleLines: 1, + subtitleLines: 1, + activatable: usage.link !== null, + }) + if (usage.link) { + const link = usage.link + row.add_suffix(new Gtk.Image({ iconName: 'go-next-symbolic', valign: Gtk.Align.CENTER })) + row.connect('activated', () => onOpen(link)) + } + return row +} + +/** + * One flag as an expandable row: the count in the subtitle, the places + * that read or write it inside. A flag nothing uses says so and offers + * its removal; a used one is refused by the store, which names this list. + */ +export function buildFlagRow(row: FlagRow, onOpen: (link: CheckupLink) => void, onRemove: () => void): Adw.ExpanderRow { + const expander = new Adw.ExpanderRow({ + title: row.name, + subtitle: flagUsageSummary(row.usages.length), + useMarkup: false, + titleLines: 1, + subtitleLines: 1, + }) + for (const usage of row.usages) expander.add_row(usageRow(usage, onOpen)) + if (row.usages.length === 0) { + const remove = new Adw.ButtonRow({ title: _('Remove flag') }) + remove.add_css_class('destructive-action') + remove.connect('activated', onRemove) + expander.add_row(remove) + } + return expander +} diff --git a/docs/concepts/game-systems.md b/docs/concepts/game-systems.md index 1d914b4b..81972d8f 100644 --- a/docs/concepts/game-systems.md +++ b/docs/concepts/game-systems.md @@ -112,7 +112,7 @@ The model is built in `apps/maker-gjs/src/services/game-rules-model.ts` (pure, u The base layer's payload this round is the thing that makes the simple view able to build a real game: a key sets a flag, a locked door opens only when that flag is set. -- **Flags are project data** (`GameProjectData.flags`: `id`, `name`, `kind`, `initial`, `scope`); every `set-flag` and `when` names the flag's **id**. A playthrough starts from each flag's `initial`. `scope: 'thing'` is stored but behaves like `'game'` until the world/player/thing split. Old projects migrate on load (`format/migrate-flags.ts`); removing a flag a door, chest or state still names is refused. +- **Flags are project data** (`GameProjectData.flags`: `id`, `name`, `kind`, `initial`, `scope`); every `set-flag` and `when` names the flag's **id**. A playthrough starts from each flag's `initial`. `scope: 'thing'` is stored but behaves like `'game'` until the world/player/thing split. Old projects migrate on load (`format/migrate-flags.ts`); removing a flag a door, chest or state still names is refused. `findFlagUsages` (`format/flag-usages.ts`) lists every read and write per flag; Game › Flags shows that list, one row per place, each a link to the thing. - **`GameSaveStateComponent`** (session singleton) holds `flags`. `FlagSystem` folds `FLAG_SET` into it — the event `EventActionSystem` has emitted since the action list shipped, heard by nobody until now. - **`EntityStatesComponent`** is attached by the spawn pipeline when a definition declares `states`, carrying the authored states plus the entity's base actions. - **`StateSystem`** resolves the first matching state each tick and swaps the entity's action list, so `EventActionSystem` runs the new body unchanged. Per-tick and idempotent rather than event-driven: it covers entities spawned after a flag was set, needs no ordering agreement with `FlagSystem`, and cannot miss an event. Gated on `RuntimeModeComponent` — the editor always shows the base composition. diff --git a/packages/translations/de.po b/packages/translations/de.po index 67940c1e..9eb730c0 100644 --- a/packages/translations/de.po +++ b/packages/translations/de.po @@ -213,6 +213,9 @@ msgstr "Ein Merker ist" msgid "A flag is something the game remembers. Give it a name and say what it holds." msgstr "Eine Flagge ist etwas, das sich das Spiel merkt. Gib ihr einen Namen und sag, was sie speichert." +msgid "A flag is something your game remembers. It shows up here once you use one." +msgstr "Eine Flagge ist etwas, das sich dein Spiel merkt. Sie erscheint hier, sobald du eine benutzt." + msgid "A ground brush paints a whole area. You draw where it goes, and the edges and corners pick themselves." msgstr "Ein Boden-Pinsel malt eine ganze Fläche. Du zeichnest, wohin er soll, und Kanten und Ecken ergeben sich von selbst." @@ -509,6 +512,13 @@ msgstr "Ändere „%1$s“ um %2$s" msgid "Change “%1$s” by +%2$s" msgstr "Ändere „%1$s“ um +%2$s" +msgid "Changes it" +msgstr "Ändert sie" + +#, javascript-format +msgid "Changes it, on %s" +msgstr "Ändert sie, auf %s" + #. The host's detail header takes its title from here — also when the #. pane is not attached yet, so a roster that arrives during #. construction still names the header. @@ -521,6 +531,13 @@ msgstr "Figurenoptionen" msgid "Characters" msgstr "Figuren" +msgid "Checks it" +msgstr "Prüft sie" + +#, javascript-format +msgid "Checks it, on %s" +msgstr "Prüft sie, auf %s" + msgid "Checkup" msgstr "Prüfung" @@ -863,6 +880,9 @@ msgstr "Einzelne Teile korrigieren" msgid "Flag" msgstr "Flagge" +msgid "Flags" +msgstr "Flaggen" + msgid "Floor" msgstr "Boden" @@ -1369,6 +1389,9 @@ msgstr "Keine Tür führt dorthin, die Heldenfigur kann es also nicht erreichen. msgid "No file chosen" msgstr "Keine Datei gewählt" +msgid "No flags yet" +msgstr "Noch keine Flaggen" + msgid "No frames" msgstr "Keine Frames" @@ -1447,6 +1470,9 @@ msgstr "Wird nicht in deinem Spiel gespeichert." msgid "Not used by any map" msgstr "Von keiner Karte verwendet" +msgid "Not used yet" +msgstr "Noch nicht benutzt" + #, javascript-format msgid "Not: %1$s" msgstr "Nicht: %1$s" @@ -1770,12 +1796,19 @@ msgstr "Komponente entfernen" msgid "Remove condition" msgstr "Bedingung entfernen" +msgid "Remove flag" +msgstr "Flagge entfernen" + msgid "Remove from credits" msgstr "Aus den Mitwirkenden entfernen" msgid "Remove this shape" msgstr "Diese Form entfernen" +#, javascript-format +msgid "Removed flag “%s”" +msgstr "Flagge „%s“ entfernt" + #, javascript-format msgid "Removed “%s”" msgstr "„%s“ entfernt" @@ -2320,6 +2353,12 @@ msgstr[1] "Von %d Karten verwendet" msgid "Used by 1 character" msgstr "Von 1 Figur verwendet" +#, javascript-format +msgid "Used in %d place" +msgid_plural "Used in %d places" +msgstr[0] "In %d Stelle benutzt" +msgstr[1] "In %d Stellen benutzt" + msgid "Value" msgstr "Wert" @@ -2513,6 +2552,12 @@ msgstr "„%s“ ist schon in diesem Projekt" msgid "“%s” is still used in %d place(s) (characters or maps). Deleting it and its image may break them. This cannot be undone." msgstr "„%s“ wird noch an %d Stelle(n) verwendet (Figuren oder Karten). Löschen samt Bild kann diese beschädigen. Das lässt sich nicht rückgängig machen." +#, javascript-format +msgid "“%s” is still used in %d place. See Game › Flags." +msgid_plural "“%s” is still used in %d places. See Game › Flags." +msgstr[0] "„%s“ wird noch an %d Stelle benutzt. Siehe Spiel › Flaggen." +msgstr[1] "„%s“ wird noch an %d Stellen benutzt. Siehe Spiel › Flaggen." + #, javascript-format msgid "“%s” will be removed from the project. Characters using it lose their look until reassigned. This cannot be undone." msgstr "„%s“ wird aus dem Projekt entfernt. Figuren, die es verwenden, verlieren ihr Aussehen, bis ihnen ein neues zugewiesen wird. Das lässt sich nicht rückgängig machen." diff --git a/packages/translations/org.pixelrpg.maker.pot b/packages/translations/org.pixelrpg.maker.pot index eed1c124..5d59451c 100644 --- a/packages/translations/org.pixelrpg.maker.pot +++ b/packages/translations/org.pixelrpg.maker.pot @@ -214,6 +214,9 @@ msgstr "" msgid "A flag is something the game remembers. Give it a name and say what it holds." msgstr "" +msgid "A flag is something your game remembers. It shows up here once you use one." +msgstr "" + msgid "A ground brush paints a whole area. You draw where it goes, and the edges and corners pick themselves." msgstr "" @@ -510,6 +513,13 @@ msgstr "" msgid "Change “%1$s” by +%2$s" msgstr "" +msgid "Changes it" +msgstr "" + +#, javascript-format +msgid "Changes it, on %s" +msgstr "" + #. The host's detail header takes its title from here — also when the #. pane is not attached yet, so a roster that arrives during #. construction still names the header. @@ -522,6 +532,13 @@ msgstr "" msgid "Characters" msgstr "" +msgid "Checks it" +msgstr "" + +#, javascript-format +msgid "Checks it, on %s" +msgstr "" + msgid "Checkup" msgstr "" @@ -864,6 +881,9 @@ msgstr "" msgid "Flag" msgstr "" +msgid "Flags" +msgstr "" + msgid "Floor" msgstr "" @@ -1370,6 +1390,9 @@ msgstr "" msgid "No file chosen" msgstr "" +msgid "No flags yet" +msgstr "" + msgid "No frames" msgstr "" @@ -1448,6 +1471,9 @@ msgstr "" msgid "Not used by any map" msgstr "" +msgid "Not used yet" +msgstr "" + #, javascript-format msgid "Not: %1$s" msgstr "" @@ -1771,12 +1797,19 @@ msgstr "" msgid "Remove condition" msgstr "" +msgid "Remove flag" +msgstr "" + msgid "Remove from credits" msgstr "" msgid "Remove this shape" msgstr "" +#, javascript-format +msgid "Removed flag “%s”" +msgstr "" + #, javascript-format msgid "Removed “%s”" msgstr "" @@ -2321,6 +2354,12 @@ msgstr[1] "" msgid "Used by 1 character" msgstr "" +#, javascript-format +msgid "Used in %d place" +msgid_plural "Used in %d places" +msgstr[0] "" +msgstr[1] "" + msgid "Value" msgstr "" @@ -2514,6 +2553,12 @@ msgstr "" msgid "“%s” is still used in %d place(s) (characters or maps). Deleting it and its image may break them. This cannot be undone." msgstr "" +#, javascript-format +msgid "“%s” is still used in %d place. See Game › Flags." +msgid_plural "“%s” is still used in %d places. See Game › Flags." +msgstr[0] "" +msgstr[1] "" + #, javascript-format msgid "“%s” will be removed from the project. Characters using it lose their look until reassigned. This cannot be undone." msgstr "" diff --git a/scripts/capture-views.py b/scripts/capture-views.py index c0a6ec10..7f571261 100755 --- a/scripts/capture-views.py +++ b/scripts/capture-views.py @@ -33,6 +33,7 @@ LANG_SHOTS = ["25-game-languages", "25b-inspector-language-toggle"] FLAG_SHOTS = ["26-flag-picker", "26b-flag-picker-open", "26c-flag-new"] COND_SHOTS = ["27-condition-editor", "27b-change-counter"] +USAGE_SHOTS = ["28-game-flags", "28b-flag-usages-open", "28c-flag-usage-opened"] NEWMAP_SHOTS = ["18-new-map-dialog", "18b-new-map-created", "18c-new-map-shelf"] ap = argparse.ArgumentParser() @@ -44,7 +45,7 @@ args = ap.parse_args() CO, OUT = args.checkout, args.outdir ONLY = set(args.only.split(",")) if args.only else None -ALL_SHOTS = TIER_SHOTS + TERRAIN_SHOTS + CREDIT_SHOTS + SHELF_SHOTS + LIVE_SHOTS + GFX_SHOTS + ADDGFX_SHOTS + NEWMAP_SHOTS + DEPTH_SHOTS + NEWGAME_SHOTS + LANG_SHOTS + FLAG_SHOTS + COND_SHOTS +ALL_SHOTS = TIER_SHOTS + TERRAIN_SHOTS + CREDIT_SHOTS + SHELF_SHOTS + LIVE_SHOTS + GFX_SHOTS + ADDGFX_SHOTS + NEWMAP_SHOTS + DEPTH_SHOTS + NEWGAME_SHOTS + LANG_SHOTS + FLAG_SHOTS + COND_SHOTS + USAGE_SHOTS if ONLY and ONLY - set(ALL_SHOTS): ap.error("unknown shot id(s) %s; valid: %s" % (", ".join(sorted(ONLY - set(ALL_SHOTS))), ", ".join(ALL_SHOTS))) if args.lang: @@ -686,6 +687,44 @@ def capture_flags(tier, w, h): p.wait() +def capture_flag_usages(tier, w, h): + # Game > Flags on a project whose flags are used (see the fixture in the PR): + # the list, one flag expanded, then a usage row tapped. USAGE_CLICKS is + # "x,y;x,y" in window pixels: first the flag row, then its first usage row. + p = subprocess.Popen([BIN], env=ENV, stdout=log, stderr=log) + try: + if not wait(lambda s: s.get("mapped"), 90): + sys.exit("app never came up") + call("ResizeWindow", str(w), str(h)) + time.sleep(1.5) + call("OpenProject", PROJECT) + wait(lambda s: len(s.get("sceneIds", [])) > 0, 60) + time.sleep(2) + act("mode", "game") + act("game-section", "flags") + act("dismiss-toasts") + shot(tier, "28-game-flags") + clicks = [tuple(int(v) for v in c.split(",")) for c in os.environ.get("USAGE_CLICKS", "").split(";") if c] + if len(clicks) == 2: + mw, mh = (int(v) for v in os.environ.get("HEADLESS_RUN_SIZE", "1920x1200").split("x")) + ox, oy = (mw - w) // 2, (mh - h) // 2 + def tap(x, y): + subprocess.run(["gjs", "-m", os.path.join(os.environ["HEADLESS_RUN_LIB"], "headless-input.js"), + "click", str(ox + x), str(oy + y), "wait", "1200"], capture_output=True, text=True, timeout=60) + tap(*clicks[0]) + shot(tier, "28b-flag-usages-open") + tap(*clicks[1]) + time.sleep(2) + shot(tier, "28c-flag-usage-opened") + finally: + p.terminate() + try: + p.wait(10) + except subprocess.TimeoutExpired: + p.kill() + p.wait() + + def runtime_flags(): s = status() return ((s or {}).get("runtime") or {}).get("flags") @@ -775,3 +814,7 @@ def capture_conditions(tier, w, h): if ONLY and ONLY & set(LANG_SHOTS): for tier, w, h in [("phone-360", 360, 720), ("wide-1920", 1920, 1200)]: capture_languages(tier, w, h) + +if ONLY and ONLY & set(USAGE_SHOTS): + for tier, w, h in [("phone-360", 360, 720), ("wide-1920", 1920, 1200)]: + capture_flag_usages(tier, w, h)