diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 918434c..35e8b3c 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -23,7 +23,7 @@ jobs: with: persist-credentials: false - name: Install test tools - run: sudo apt-get update && sudo apt-get install -y luajit python3 zip unzip jq + run: sudo apt-get update && sudo apt-get install -y luajit python3 zip unzip jq librsvg2-bin imagemagick fonts-dejavu-core - name: Set up pinned test libraries run: bash scripts/setup-test-libs.sh - name: Check out the matching Blizzard source @@ -37,6 +37,28 @@ jobs: run: python3 -B scripts/spell_catalog.py --fetch --check - name: Run all tests and addon syntax checks run: bash scripts/run-tests.sh --times -j + - name: Cache Blizzard interface art for UI proof + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .proof-art + key: proof-art-d23deaf8f44a7d280dc974a5c9d5321c013db59b-${{ hashFiles('tests/proof/*.lua') }} + restore-keys: proof-art-d23deaf8f44a7d280dc974a5c9d5321c013db59b- + - name: Render UI proof + env: + GITHUB_TOKEN: ${{ github.token }} + run: bash scripts/proof.sh + - name: Save UI proof + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: ui-proof + path: | + .proof/*.png + .proof/*.svg + .proof/index.html + include-hidden-files: true + if-no-files-found: error + retention-days: 14 - name: Save spell classification audit if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 diff --git a/.gitignore b/.gitignore index 22d415b..e4ecbca 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,5 @@ UnitFrames/Libs/ UnitFrames_Media/Libs/ /.release/ /.build/ +/.proof/ +/.proof-art/ diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 3303850..9da05cb 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -187,6 +187,7 @@ in source is needed before tagging. | `UnitFrames_Onboarding/` | Load-on-demand Getting started guide: preset looks, tweaks, extras and Workbench hand-off | | `UnitFrames_Media/` | Additional fonts and their licences | | `tests/` | Mocked client, API snapshot and regression specs | +| `wowproof/` | Standalone UI-proof renderer (no UnitFrames code; see its README) | | `scripts/` | Library fetching, installation and API snapshot generation | New runtime files belong in the relevant TOC in dependency order; tests @@ -227,6 +228,41 @@ a name ending in `.lua` exactly one file. `-t` and `--tag` narrow further. A run that selects no tests fails. The runner always checks addon Lua syntax. No external busted installation is needed. To see where a spec spends its time, use LuaJIT's profiler: `luajit -jp=F tests/run.lua clickgrid_spec.lua`. +The specs of the `wowproof/` package run with the suite as `wowproof/`. + +### UI proof + +The mocked client can render frames to images, for visual proof of a change: + +```sh +bash scripts/proof.sh # every scenario +bash scripts/proof.sh target clickgrid # scenario names containing the text +``` + +It writes `.proof/.svg`, `.png` and a contact sheet `.proof/index.html` +(ignored by Git; `UF_PROOF_DIR` picks another folder). PNGs need `rsvg-convert` +(librsvg); our own `.tga` textures need ImageMagick. Scenarios live in +`tests/proof/units.lua` and `tests/proof/workbench.lua`: each is a name and a +`build` that loads the addon, feeds sample values and returns the region to +render. `tests/proof/setup.lua` is the only coupling to the renderer: it hands +`wowproof` an adapter for the mock and maps our fonts and textures. A spec can +also call `Helpers.Snapshot(name, region)`, which renders only with +`UF_PROOF=1`. CI uploads the images as the `ui-proof` artifact. + +The images show real anchoring, sizes, colours, bar fill, text, clipping, +texture coordinates and paint order. Blizzard textures and icons +(`Interface\...`) are downloaded on demand from the public +[Gethe/wow-ui-textures](https://github.com/Gethe/wow-ui-textures) mirror, +pinned in `tests/proof/setup.lua`, into the ignored `.proof-art/` folder. Only +the files a render uses are fetched, and the cache is reused offline. Never +commit that art. `UF_PROOF_ART` picks another cache folder, and +`UF_PROOF_ART_FETCH=0` stays offline. Set `GH_TOKEN` or `GITHUB_TOKEN` if +GitHub's API rate limit bites. + +Still drawn as dashed placeholders: +- art the mirror lacks, listed in `.proof-art/missing-.txt` +- atlases (`SetAtlas`), which need Blizzard's atlas table +- portrait models ### Pull request checks diff --git a/scripts/proof.sh b/scripts/proof.sh new file mode 100755 index 0000000..32814d7 --- /dev/null +++ b/scripts/proof.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$repo_dir" +if [[ ! -f UnitFrames/Libs/LibStub/LibStub.lua ]]; then + echo 'Test libraries are missing. Run bash scripts/setup-test-libs.sh first.' >&2 + exit 1 +fi +command -v rsvg-convert >/dev/null || echo 'rsvg-convert not found: writing SVG only.' >&2 +command -v magick >/dev/null || command -v convert >/dev/null \ + || echo 'ImageMagick not found: addon textures render as placeholders.' >&2 +exec luajit tests/proof/run.lua "$@" diff --git a/tests/fixtures/api_snapshot.lua b/tests/fixtures/api_snapshot.lua index 3ec51c3..44287cf 100644 --- a/tests/fixtures/api_snapshot.lua +++ b/tests/fixtures/api_snapshot.lua @@ -1423,6 +1423,7 @@ return { [":update"] = "Interface/AddOns/Blizzard_GroupFinder/Mainline/PVEFrame.lua", API = "Interface/AddOns/Blizzard_ObjectAPI/Mainline/AsyncCallbackSystem.lua", AddPoint = "Interface/AddOns/Blizzard_LegacySystem/Blizzard_LegacySystem.lua", + BOTTOMRIGHT = "Interface/AddOns/Blizzard_Settings_Shared/Blizzard_ImplementationReadme.lua", BUTTON = "Interface/AddOns/Blizzard_Settings_Shared/Blizzard_Keybindings.lua", Chain = "Interface/AddOns/Blizzard_PTRFeedback/Blizzard_Reports.lua", ClearText = "Interface/AddOns/Blizzard_PlayerSpells/Blizzard_PlayerSpellsFrame.lua", @@ -1464,6 +1465,7 @@ return { SetupTextureCoordinates = "Interface/AddOns/Blizzard_SharedXML/NineSlice.lua", Show = "Interface/AddOns/Blizzard_EncounterWarnings/EncounterWarningsView.lua", T = "Interface/AddOns/Blizzard_ProfessionsTemplates/Blizzard_ProfessionsRecipeSchematicForm.lua", + TOPLEFT = "Interface/AddOns/Blizzard_Settings_Shared/Blizzard_ImplementationReadme.lua", UnitHasIncomingResurrection = "Interface/AddOns/Blizzard_UnitFrame/Shared/CompactUnitFrame.lua", Warrior = "Interface/AddOns/Blizzard_BoostTutorial/Blizzard_TutorialRacialData.lua", action = "Interface/AddOns/Blizzard_SharedXML/ScriptedAnimations/ScriptAnimatedModelScene.lua", @@ -1488,9 +1490,11 @@ return { children = "Interface/AddOns/Blizzard_GamepadSmartNavigation/Utility.lua", click = "Interface/AddOns/Blizzard_GamepadSharedUtility/InputHandlers/InputButtonUtility.lua", color = "Interface/AddOns/Blizzard_Menu/MenuTemplates.lua", + column = "Interface/AddOns/Blizzard_RestrictedAddOnEnvironment/SecureGroupHeaders.lua", comparison = "Interface/AddOns/Blizzard_GarrisonUI/Mainline/Blizzard_GarrisonShipyardUI.lua", condition = "Interface/AddOns/Blizzard_AuctionHouseUI/Shared/Blizzard_AuctionHouseItemList.lua", content = "Interface/AddOns/Blizzard_NamePlates/Blizzard_NamePlateConstants.lua", + coords = "Interface/AddOns/Blizzard_ArtifactUI/Blizzard_ArtifactPerks.lua", create = "Interface/AddOns/Blizzard_RestrictedAddOnEnvironment/SecureGroupHeaders.lua", data = "Interface/AddOns/Blizzard_StaticPopup_Glue/Mainline/GlueDialogDefs.lua", dataProvider = "Interface/AddOns/Blizzard_SharedXML/TableBuilder.lua", @@ -1537,6 +1541,8 @@ return { order = "Interface/AddOns/Blizzard_RestrictedAddOnEnvironment/SecureAuraHeader.lua", out = "Interface/AddOns/Blizzard_DeclensionFrame/Mainline/DeclensionFrame.lua", pass = "Interface/AddOns/Blizzard_SharedXML/MixinUtil.lua", + piece = "Interface/AddOns/Blizzard_SharedXML/NineSlice.lua", + pieces = "Interface/AddOns/Blizzard_SharedXML/NineSlice.lua", player = "Interface/AddOns/Blizzard_CooldownViewer/CooldownViewerAlert.lua", points = "Interface/AddOns/Blizzard_EncounterJournal/Mainline/Blizzard_MonthlyActivities.lua", policy = "Interface/AddOns/Blizzard_SharedXMLGame/Mainline/Localization.lua", diff --git a/tests/helpers.lua b/tests/helpers.lua index 831e319..4cd0cd8 100644 --- a/tests/helpers.lua +++ b/tests/helpers.lua @@ -156,4 +156,11 @@ function Helpers.LoadClickGrid(workbench, saved) return ns, cg, ns.Workbench end +local proof +function Helpers.Snapshot(name, region, options) + if os.getenv("UF_PROOF") ~= "1" then return nil end + proof = proof or dofile("tests/proof/setup.lua").Proof() + return proof:Snapshot(region, "spec-" .. name, options) +end + return Helpers diff --git a/tests/mock/wow.lua b/tests/mock/wow.lua index b0a7362..13408e3 100644 --- a/tests/mock/wow.lua +++ b/tests/mock/wow.lua @@ -201,7 +201,10 @@ end function Methods:SetRotation(radians) self.__state.rotation = radians end function Methods:GetFrameRef(label) return self.__state.frameRefs and self.__state.frameRefs[label] end -function Methods:SetScript(name, fn) self.__state.scripts[name] = fn end +function Methods:SetScript(name, fn) + if name == "OnSizeChanged" then self.__state.backdropSizeScript = false end + self.__state.scripts[name] = fn +end function Methods:GetScript(name) return self.__state.scripts[name] end function Methods:HookScript(name, fn) local previous = self.__state.scripts[name] @@ -288,7 +291,12 @@ local function Resize(self, width, height) local s = self.__state local changed = s.width ~= width or s.height ~= height s.width, s.height = width, height - if changed and s.scripts.OnSizeChanged and not Mock.HasLayoutAspect(self) then + if not changed or Mock.HasLayoutAspect(self) then return end + if s.backdropSizeScript and s.backdrop then + local setup = rawget(self, "SetupTextureCoordinates") or BackdropTemplateMixin.SetupTextureCoordinates + setup(self) + end + if s.scripts.OnSizeChanged then s.scripts.OnSizeChanged(self, width, height) end end @@ -586,16 +594,83 @@ function Methods:GetStringWidth() return 50 end -- Backdrop (BackdropTemplate) local borderPieces = { "TopLeftCorner", "TopRightCorner", "BottomLeftCorner", "BottomRightCorner", "TopEdge", "BottomEdge", "LeftEdge", "RightEdge" } + +local NINE_SLICE = { + { name = "TopLeftCorner", point = "TOPLEFT" }, + { name = "TopRightCorner", point = "TOPRIGHT" }, + { name = "BottomLeftCorner", point = "BOTTOMLEFT" }, + { name = "BottomRightCorner", point = "BOTTOMRIGHT" }, + { name = "TopEdge", point = "TOPLEFT", relativePoint = "TOPRIGHT", between = { "TopLeftCorner", "TopRightCorner" } }, + { name = "BottomEdge", point = "BOTTOMLEFT", relativePoint = "BOTTOMRIGHT", between = { "BottomLeftCorner", "BottomRightCorner" } }, + { name = "LeftEdge", point = "TOPLEFT", relativePoint = "BOTTOMLEFT", between = { "TopLeftCorner", "BottomLeftCorner" } }, + { name = "RightEdge", point = "TOPRIGHT", relativePoint = "BOTTOMRIGHT", between = { "TopRightCorner", "BottomRightCorner" } }, + { name = "Center" }, +} +local BACKDROP_COORD_START = 0.0625 +local BACKDROP_COORD_END = 1 - BACKDROP_COORD_START +local BACKDROP_UV_ORDER = { "ULx", "ULy", "LLx", "LLy", "URx", "URy", "LRx", "LRy" } +local BACKDROP_UVS = { + TopLeftCorner = { ULx = 0.5078125, ULy = BACKDROP_COORD_START, LLx = 0.5078125, LLy = BACKDROP_COORD_END, + URx = 0.6171875, URy = BACKDROP_COORD_START, LRx = 0.6171875, LRy = BACKDROP_COORD_END }, + TopRightCorner = { ULx = 0.6328125, ULy = BACKDROP_COORD_START, LLx = 0.6328125, LLy = BACKDROP_COORD_END, + URx = 0.7421875, URy = BACKDROP_COORD_START, LRx = 0.7421875, LRy = BACKDROP_COORD_END }, + BottomLeftCorner = { ULx = 0.7578125, ULy = BACKDROP_COORD_START, LLx = 0.7578125, LLy = BACKDROP_COORD_END, + URx = 0.8671875, URy = BACKDROP_COORD_START, LRx = 0.8671875, LRy = BACKDROP_COORD_END }, + BottomRightCorner = { ULx = 0.8828125, ULy = BACKDROP_COORD_START, LLx = 0.8828125, LLy = BACKDROP_COORD_END, + URx = 0.9921875, URy = BACKDROP_COORD_START, LRx = 0.9921875, LRy = BACKDROP_COORD_END }, + TopEdge = { ULx = 0.2578125, ULy = "repeatX", LLx = 0.3671875, LLy = "repeatX", + URx = 0.2578125, URy = BACKDROP_COORD_START, LRx = 0.3671875, LRy = BACKDROP_COORD_START }, + BottomEdge = { ULx = 0.3828125, ULy = "repeatX", LLx = 0.4921875, LLy = "repeatX", + URx = 0.3828125, URy = BACKDROP_COORD_START, LRx = 0.4921875, LRy = BACKDROP_COORD_START }, + LeftEdge = { ULx = 0.0078125, ULy = BACKDROP_COORD_START, LLx = 0.0078125, LLy = "repeatY", + URx = 0.1171875, URy = BACKDROP_COORD_START, LRx = 0.1171875, LRy = "repeatY" }, + RightEdge = { ULx = 0.1328125, ULy = BACKDROP_COORD_START, LLx = 0.1328125, LLy = "repeatY", + URx = 0.2421875, URy = BACKDROP_COORD_START, LRx = 0.2421875, LRy = "repeatY" }, + Center = { ULx = 0, ULy = 0, LLx = 0, LLy = "repeatY", URx = "repeatX", URy = 0, LRx = "repeatX", LRy = "repeatY" }, +} +local CORNER_SIZE = { TopLeftCorner = "both", TopRightCorner = "both", BottomLeftCorner = "both", + BottomRightCorner = "both", TopEdge = "height", BottomEdge = "height", LeftEdge = "width", RightEdge = "width" } + function Methods:SetBackdrop(info) if not info or not (info.edgeFile or info.bgFile) then self:ClearBackdrop(); return end -- BackdropTemplateMixin:SetBackdrop ignores the info table it already holds. if self.__state.backdrop == info then return end self.__state.backdrop = info - for _, key in ipairs(borderPieces) do - local texture = rawget(self, key) or self:CreateTexture(nil, "BORDER") - self[key] = texture - texture:SetTexture(info.edgeFile) + local edgeSize = self:GetEdgeSize() + local x, y, x1, y1 = 0, 0, 0, 0 + if info.bgFile then + local insets = info.insets or {} + x, y = -edgeSize + (insets.left or 0), edgeSize - (insets.top or 0) + x1, y1 = edgeSize - (insets.right or 0), -edgeSize + (insets.bottom or 0) + end + local pieces = self.__state.backdropPieces or {} + self.__state.backdropPieces = pieces + for _, setup in ipairs(NINE_SLICE) do + local center = setup.name == "Center" + local piece = rawget(self, setup.name) or self:CreateTexture(nil, center and "BACKGROUND" or "BORDER") + self[setup.name], pieces[setup.name] = piece, piece + piece:ClearAllPoints() + if center then + piece:SetPoint("TOPLEFT", pieces.TopLeftCorner, "BOTTOMRIGHT", x, y) + piece:SetPoint("BOTTOMRIGHT", pieces.BottomRightCorner, "TOPLEFT", x1, y1) + piece:SetTexture(info.bgFile) + piece:SetSize(0, 0) + else + if setup.between then + piece:SetPoint(setup.point, pieces[setup.between[1]], setup.relativePoint) + piece:SetPoint(setup.relativePoint, pieces[setup.between[2]], setup.point) + else + piece:SetPoint(setup.point, self, setup.point) + end + piece:SetTexture(info.edgeFile) + local size = CORNER_SIZE[setup.name] + piece:SetSize((size == "both" or size == "width") and edgeSize or 0, (size == "both" or size == "height") and edgeSize or 0) + end end + self:SetBackdropColor(1, 1, 1, 1) + self:SetBackdropBorderColor(1, 1, 1, 1) + local setupTextureCoordinates = rawget(self, "SetupTextureCoordinates") or BackdropTemplateMixin.SetupTextureCoordinates + setupTextureCoordinates(self) end function Methods:GetBackdrop() return self.__state.backdrop end function Methods:GetEdgeSize() @@ -604,12 +679,16 @@ function Methods:GetEdgeSize() end function Methods:ClearBackdrop() self.__state.backdrop = nil - for _, key in ipairs(borderPieces) do - local texture = rawget(self, key) + for _, setup in ipairs(NINE_SLICE) do + local texture = rawget(self, setup.name) if texture then texture:SetTexture(nil) end end end -function Methods:SetBackdropColor(r, g, b, a) self.__state.backdropColor = { r, g, b, a } end +function Methods:SetBackdropColor(r, g, b, a) + self.__state.backdropColor = { r, g, b, a } + local center = rawget(self, "Center") + if center then center:SetVertexColor(r, g, b, a) end +end function Methods:SetBackdropBorderColor(r, g, b, a) self.__state.backdropBorderColor = { r, g, b, a } for _, key in ipairs(borderPieces) do @@ -1088,6 +1167,7 @@ function Mock.Install() obj.__state.template = template if template and template:find("Secure", 1, true) then obj.__state.protected = true end if template and template:find(LAYOUT_ASPECT_TEMPLATE, 1, true) then obj.__state.layoutAspect = true end + if template and template:find("BackdropTemplate", 1, true) then obj.__state.backdropSizeScript = true end if parent and parent == rawget(_G, "Minimap") then rawset(obj, "__strict", true) end if frameType == "AuraContainer" then assert(not InCombatLockdown(), "Native aura containers cannot be created in combat") @@ -1191,7 +1271,12 @@ function Mock.Install() } Mock.spells = {} -- Blizzard_UnitFrame (always loaded): a sprite sheet cell of the raid icon sheet. - _G.SetRaidTargetIconTexture = function(texture, index) texture.__state.raidTargetIndex = index end + _G.SetRaidTargetIconTexture = function(texture, index) + texture.__state.raidTargetIndex = index + local cell = (Mock.IsSecret(index) and index.secretValue or index) - 1 + local column, row = cell % 4, math.floor(cell / 4) + texture.__state.texCoords = { column / 4, (column + 1) / 4, row / 4, (row + 1) / 4 } + end Mock.spellOverrides, Mock.unknownSpells, Mock.cooldowns, Mock.spellQueueWindow = {}, {}, {}, 400 -- Mock.latency = { home, world } in milliseconds. Mock.latency = { 40, 80 } @@ -1398,10 +1483,29 @@ function Mock.Install() _G.BackdropTemplateMixin = { SetupTextureCoordinates = function(self) local edgeSize, scale = self:GetEdgeSize(), self:GetEffectiveScale() + local width, height = self:GetWidth(), self:GetHeight() self.__state.backdropRepeat = { - math.max(0, self:GetWidth() / edgeSize * scale - 2), - math.max(0, self:GetHeight() / edgeSize * scale - 2), + math.max(0, width / edgeSize * scale - 2), + math.max(0, height / edgeSize * scale - 2), } + local edgeX = math.max(0, width / edgeSize * scale - 2 - BACKDROP_COORD_START) + local edgeY = math.max(0, height / edgeSize * scale - 2 - BACKDROP_COORD_START) + local info = self.__state.backdrop + for name, piece in pairs(self.__state.backdropPieces or {}) do + local repeatX, repeatY = edgeX, edgeY + if name == "Center" then + repeatX, repeatY = 1, 1 + local divisor = info and info.tile and (info.tileSize ~= 0 and info.tileSize or edgeSize) + if divisor and divisor ~= 0 then repeatX, repeatY = width / divisor * scale, height / divisor * scale end + end + local coords = {} + for index, key in ipairs(BACKDROP_UV_ORDER) do + local value = BACKDROP_UVS[name][key] + if value == "repeatX" then value = repeatX elseif value == "repeatY" then value = repeatY end + coords[index] = value + end + piece:SetTexCoord(unpack(coords)) + end end, } _G.AuraUtil = { diff --git a/tests/proof/run.lua b/tests/proof/run.lua new file mode 100644 index 0000000..0037a48 --- /dev/null +++ b/tests/proof/run.lua @@ -0,0 +1,20 @@ +local Setup = dofile("tests/proof/setup.lua") +local Runner = require("wowproof.runner") + +local SCENARIO_FILES = { "tests/proof/units.lua", "tests/proof/workbench.lua" } + +local write = io.write +local function Print(line) write(line, "\n") end + +local scenarios = {} +for _, file in ipairs(SCENARIO_FILES) do + for _, scenario in ipairs(dofile(file)) do scenarios[#scenarios + 1] = scenario end +end + +local _, failed = Runner.Run({ + proof = Setup.Proof(), + scenarios = scenarios, + filters = arg, + print = Print, +}) +os.exit(failed == 0 and 0 or 1, true) diff --git a/tests/proof/setup.lua b/tests/proof/setup.lua new file mode 100644 index 0000000..4f4faea --- /dev/null +++ b/tests/proof/setup.lua @@ -0,0 +1,98 @@ +package.path = "./tests/?.lua;./?.lua;./?/init.lua;" .. package.path + +local Helpers = require("helpers") +local Proof = require("wowproof") +local MockState = require("wowproof.adapters.mock_state") +local Raster = require("wowproof.raster") +local BlizzardArt = require("wowproof.sources.wow_ui_textures") + +local Mock = Helpers.Mock + +local ADDON_PREFIX = "interface\\addons\\" +local TEXTURE_EXTENSIONS = { "", ".tga", ".png" } +local FONT_DIR = "UnitFrames_Media/Fonts" +local FONT_FAMILY = "Roboto Condensed" +local FONT_WEIGHTS = { Light = 300, Regular = 400, Medium = 500, Bold = 700 } +local ART_REF = "d23deaf8f44a7d280dc974a5c9d5321c013db59b" + +local Setup = {} + +local blizzardArt = BlizzardArt({ + ref = ART_REF, + dir = os.getenv("UF_PROOF_ART") or ".proof-art", + fetch = os.getenv("UF_PROOF_ART_FETCH") ~= "0", + token = os.getenv("GITHUB_TOKEN") or os.getenv("GH_TOKEN"), +}) + +local function AddonFile(path) + if type(path) ~= "string" or path:lower():sub(1, #ADDON_PREFIX) ~= ADDON_PREFIX then return nil end + return (path:sub(#ADDON_PREFIX + 1):gsub("\\", "/")) +end + +function Setup.AddonTexture(path) + local file = AddonFile(path) + if not file then return nil end + for _, extension in ipairs(TEXTURE_EXTENSIONS) do + local candidate = file .. extension + if Raster.Exists(candidate) and candidate:lower():match("%.[tp][gn][ag]$") then return candidate end + end + return nil +end + +function Setup.Texture(path) + return Setup.AddonTexture(path) or blizzardArt(path) +end + +function Setup.Font(path) + local file = AddonFile(path) + local style = file and file:match("^" .. FONT_DIR .. "/RobotoCondensed%-(%a+)%.ttf$") + if style then return FONT_FAMILY, FONT_WEIGHTS[style] or 400 end + return nil +end + +function Setup.Adapter() + return MockState({ + isSecret = Mock.IsSecret, + reveal = function(value) return value.secretValue end, + objects = function() return Mock.objects end, + globals = _G, + }) +end + +local function BackdropGeometry(frame, width, height) + return setmetatable({ + GetWidth = function() return width end, + GetHeight = function() return height end, + GetEffectiveScale = function() return frame:GetEffectiveScale() end, + GetEdgeSize = function() return frame:GetEdgeSize() end, + }, { __index = frame }) +end + +function Setup.SettleBackdrops(layout) + for _, frame in ipairs(Mock.objects) do + local state = frame.__state + local rect = state.backdrop and state.backdropSizeScript and layout:Rect(frame) + if rect then + local scale = layout:Scale(frame) + local repeats = state.backdropRepeat + BackdropTemplateMixin.SetupTextureCoordinates(BackdropGeometry(frame, rect.width / scale, rect.height / scale)) + state.backdropRepeat = repeats + end + end +end + +function Setup.Proof(options) + options = options or {} + return Proof.New({ + adapter = Setup.Adapter(), + outDir = options.outDir or os.getenv("UF_PROOF_DIR") or ".proof", + title = options.title or "UnitFrames UI proof", + settle = Setup.SettleBackdrops, + assets = { + textures = Setup.Texture, + fonts = { dirs = { FONT_DIR }, family = Setup.Font, default = FONT_FAMILY, defaultWeight = 500 }, + }, + }) +end + +return Setup diff --git a/tests/proof/units.lua b/tests/proof/units.lua new file mode 100644 index 0000000..337092a --- /dev/null +++ b/tests/proof/units.lua @@ -0,0 +1,43 @@ +local Helpers = require("helpers") +local Mock = Helpers.Mock + +local function UnitFrame(unit, overrides, configure) + return function() + local ns = Helpers.LoadAddon(true, true) + Mock.InstallUI() + if configure then configure(ns) end + local frame = ns.Units.frames[unit] + frame:Show() + local values = ns.Units:GetSample(unit) + for key, value in pairs(overrides or {}) do values[key] = value end + ns.Units:ShowSample(frame.uf, values) + return frame + end +end + +local function EnableOverheal(ns) + ns.Config:SetUnitValue("player", "health.bar.overheal.enabled", true) +end + +local function TooltipBorder(ns) + ns.Config:SetUnitValue("player", "border.enabled", true) + ns.Config:SetUnitValue("player", "border.border", "Blizzard Tooltip") +end + +local function NoBorder(ns) + ns.Config:SetUnitValue("player", "border.enabled", false) +end + +return { + { name = "player", build = UnitFrame("player") }, + { name = "player-idle", build = UnitFrame("player", { showCast = false }) }, + { name = "player-tooltip-border", build = UnitFrame("player", { showCast = false }, TooltipBorder) }, + { name = "player-no-border", build = UnitFrame("player", { showCast = false }, NoBorder) }, + { name = "player-overheal", build = UnitFrame("player", { health = 22000, heal = 7000, showCast = false }, EnableOverheal) }, + { name = "target", build = UnitFrame("target") }, + { name = "target-35pct", build = UnitFrame("target", { health = 8400, showCast = false }) }, + { name = "targettarget", build = UnitFrame("targettarget") }, + { name = "focus", build = UnitFrame("focus") }, + { name = "focustarget", build = UnitFrame("focustarget") }, + { name = "pet", build = UnitFrame("pet") }, +} diff --git a/tests/proof/workbench.lua b/tests/proof/workbench.lua new file mode 100644 index 0000000..c42d115 --- /dev/null +++ b/tests/proof/workbench.lua @@ -0,0 +1,23 @@ +local Helpers = require("helpers") + +local function UnitPreview(entry) + return function() + local _, workbench = Helpers.LoadWorkbench() + workbench:Open(entry) + return workbench.handle.parts.uf:GetFrame() + end +end + +local function ClickGridPreview(entry) + return function() + local _, _, workbench = Helpers.LoadClickGrid(true) + workbench:Open(entry) + return workbench.handle.frame + end +end + +return { + { name = "workbench-player", build = UnitPreview("unit.player") }, + { name = "workbench-target", build = UnitPreview("unit.target") }, + { name = "clickgrid-panel", build = ClickGridPreview("clickgrid.panel") }, +} diff --git a/tests/run.lua b/tests/run.lua index a1a4065..0a05c32 100644 --- a/tests/run.lua +++ b/tests/run.lua @@ -280,7 +280,17 @@ local function Quote(text) end local SPEC_DIR = "tests/spec/" -package.path = "./tests/?.lua;" .. package.path +local PACKAGE_SPECS = { { prefix = "wowproof/", dir = "wowproof/spec/" } } +package.path = "./tests/?.lua;./?.lua;./?/init.lua;" .. package.path + +local function SpecPath(file) + for _, package in ipairs(PACKAGE_SPECS) do + if file:sub(1, #package.prefix) == package.prefix then + return package.dir .. file:sub(#package.prefix + 1) + end + end + return SPEC_DIR .. file +end -- Restores the globals a spec file assigned, so a serial run isolates files -- like the one-process-per-file parallel run does. @@ -300,7 +310,7 @@ local function RunFile(file) for name, value in pairs(_G) do globals[name] = value end root = { name = "", tests = {}, before = {}, after = {} } current = root - local ok, err = xpcall(function() dofile(SPEC_DIR .. file) end, debug.traceback) + local ok, err = xpcall(function() dofile(SpecPath(file)) end, debug.traceback) if ok then RunBlock(root, "") else @@ -379,6 +389,14 @@ for _, path in ipairs(ListFiles("find " .. SPEC_DIR .. " -name '*_spec.lua'")) d files[#files + 1] = file end end +for _, package in ipairs(PACKAGE_SPECS) do + for _, path in ipairs(ListFiles("find " .. package.dir .. " -name '*_spec.lua'")) do + local file = package.prefix .. path:sub(#package.dir + 1) + if SpecSelected(file) then + files[#files + 1] = file + end + end +end if jobs == 0 then jobs = tonumber(Lines("nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 1")[1]) or 1 @@ -395,7 +413,7 @@ if parallel then local dir = Lines("mktemp -d")[1] local order = {} for index, file in ipairs(files) do - local handle = assert(io.open(SPEC_DIR .. file)) + local handle = assert(io.open(SpecPath(file))) order[index] = { index = index, file = file, size = handle:seek("end") } handle:close() end diff --git a/tests/spec/components/backdrop_template_spec.lua b/tests/spec/components/backdrop_template_spec.lua new file mode 100644 index 0000000..f5ae186 --- /dev/null +++ b/tests/spec/components/backdrop_template_spec.lua @@ -0,0 +1,66 @@ +local Helpers = require("helpers") +local Mock = Helpers.Mock + +describe("Mock BackdropTemplate layout", function() + local frame + local INFO = { + bgFile = "Interface\\Buttons\\WHITE8X8", + edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", + edgeSize = 16, + tile = true, + tileSize = 16, + insets = { left = 3, right = 3, top = 3, bottom = 3 }, + } + + before_each(function() + Mock.Install() + Mock.InstallUI() + frame = CreateFrame("Frame", nil, UIParent, "BackdropTemplate") + frame:SetSize(160, 48) + frame:SetBackdrop(INFO) + end) + + local function Rounded(values) + local out = {} + for index, value in ipairs(values) do out[index] = math.floor(value * 10000 + 0.5) / 10000 end + return out + end + + it("anchors corners to the frame and edges and center between the corners", function() + assert.same({ "TOPLEFT", frame, "TOPLEFT", 0, 0 }, { frame.TopLeftCorner:GetPoint(1) }) + assert.same({ 16, 16 }, { frame.TopLeftCorner:GetSize() }) + assert.same({ "TOPLEFT", frame.TopLeftCorner, "TOPRIGHT", 0, 0 }, { frame.TopEdge:GetPoint(1) }) + assert.same({ "TOPRIGHT", frame.TopRightCorner, "TOPLEFT", 0, 0 }, { frame.TopEdge:GetPoint(2) }) + assert.same({ 0, 16 }, { frame.TopEdge:GetSize() }) + assert.same({ 16, 0 }, { frame.LeftEdge:GetSize() }) + assert.same({ "TOPLEFT", frame.TopLeftCorner, "BOTTOMRIGHT", -13, 13 }, { frame.Center:GetPoint(1) }) + assert.same({ "BOTTOMRIGHT", frame.BottomRightCorner, "TOPLEFT", 13, -13 }, { frame.Center:GetPoint(2) }) + assert.equals(INFO.edgeFile, frame.TopEdge:GetTexture()) + assert.equals(INFO.bgFile, frame.Center:GetTexture()) + end) + + it("sets Blizzard's edge strip coordinates, repeating with the frame size", function() + assert.same({ 0.5078, 0.0625, 0.5078, 0.9375, 0.6172, 0.0625, 0.6172, 0.9375 }, + Rounded(frame.TopLeftCorner.__state.texCoords)) + assert.same({ 0.2578, 7.9375, 0.3672, 7.9375, 0.2578, 0.0625, 0.3672, 0.0625 }, + Rounded(frame.TopEdge.__state.texCoords)) + assert.same({ 0, 0, 0, 3, 10, 0, 10, 3 }, Rounded(frame.Center.__state.texCoords)) + frame:SetSize(320, 48) + assert.same({ 0.2578, 17.9375, 0.3672, 17.9375, 0.2578, 0.0625, 0.3672, 0.0625 }, + Rounded(frame.TopEdge.__state.texCoords)) + end) + + it("tints the center with the backdrop colour and the edges with the border colour", function() + frame:SetBackdropColor(0, 0, 0, 0.8) + frame:SetBackdropBorderColor(0.5, 0.5, 0.5, 1) + assert.same({ 0, 0, 0, 0.8 }, frame.Center.__state.vertexColor) + assert.same({ 0.5, 0.5, 0.5, 1 }, frame.RightEdge.__state.vertexColor) + end) + + it("stops following size changes once a script replaces the template's OnSizeChanged", function() + frame:SetScript("OnSizeChanged", nil) + frame:SetSize(320, 48) + assert.same({ 0.2578, 7.9375, 0.3672, 7.9375, 0.2578, 0.0625, 0.3672, 0.0625 }, + Rounded(frame.TopEdge.__state.texCoords)) + end) +end) diff --git a/wowproof/README.md b/wowproof/README.md new file mode 100644 index 0000000..c65991a --- /dev/null +++ b/wowproof/README.md @@ -0,0 +1,112 @@ +# wowproof + +Visual proof for World of Warcraft addon tests. wowproof takes the frame tree +of a mocked client and renders it to SVG, PNG and an HTML contact sheet. It is +plain Lua 5.1 / LuaJIT and has no dependencies. Two external tools are optional: +`rsvg-convert` turns the SVGs into PNGs, and ImageMagick converts `.tga`/`.blp` +textures. + +It never touches a widget directly. Everything goes through an **adapter**, so +any mock (or any other frame model) can be rendered by writing one. + +## Use + +```lua +package.path = "./?.lua;./?/init.lua;" .. package.path +local Proof = require("wowproof") +local MockState = require("wowproof.adapters.mock_state") + +local proof = Proof.New({ + adapter = MockState({ + isSecret = Mock.IsSecret, + reveal = function(value) return value.secretValue end, + objects = function() return Mock.objects end, + globals = _G, + }), + outDir = ".proof", + assets = { + textures = function(path) return "MyAddon/Media/Glow.tga" end, + fonts = { dirs = { "MyAddon/Fonts" }, family = function(path) return "Roboto", 700 end, default = "Roboto" }, + }, +}) + +proof:Snapshot(MyFrame, "player-frame", { pad = 8, scale = 2, debug = false }) +proof:Sheet() +``` + +`settle = function(layout, region)` (optional) runs after layout and before +painting. It lets the host update state that depends on resolved sizes, such as +backdrop texture coordinates that the real engine recomputes on +`OnSizeChanged`. If `rsvg-convert` is installed but fails, the snapshot +raises an error instead of writing an empty PNG. + +To run named scenarios and get a contact sheet with failures included, use +`require("wowproof.runner").Run({ proof = proof, scenarios = { { name, build } }, filters = arg })`. + +## Adapter contract + +An adapter is a table of functions over the host's region objects. Values +must be plain Lua values. Unwrapping secrets or other host-specific values is +the adapter's job. + +| Function | Returns | +| --- | --- | +| `Parent(r)`, `Children(r)` | the parent region or nil; children in creation order | +| `Order(r)`, `Type(r)`, `Name(r)` | creation index; `Frame`, `StatusBar`, `Texture`, `FontString`, …; a name or nil | +| `Points(r)` | `{ point, relativeTo, relativePoint, x, y }` entries, or `{ all = true, relativeTo }` | +| `Size(r)`, `Scale(r)` | width, height; own scale | +| `Shown(r)`, `Alpha(r)`, `IgnoresParentAlpha(r)` | own shown state; own alpha; boolean | +| `Strata(r)`, `Level(r)`, `Layer(r)` | strata or nil (inherited); frame level; draw layer and sublevel | +| `Texture(r)` | `{ color, vertexColor, file, atlas, gradient = { orientation, from, to }, blend, slice }` | +| `Bar(r)` | nil, or for status bars `{ min, max, value, orientation, reverse, color }` | +| `Text(r)` | nil, or for font strings `{ text, font, size, flags, color, justifyH, justifyV }` | +| `FillOf(r)` *(optional)* | the status bar whose fill texture `r` is; the fill then gets its rect from the bar value | +| `ClipsChildren(r)` *(optional)* | whether the frame clips its children | + +`wowproof.scene` validates adapters and lists the strata and draw-layer order. +`wowproof.adapters.mock_state` covers mocks that keep widget state in +`obj.__state` and unimplemented calls in `obj.__calls`. + +## What it draws + +- **Layout:** anchors (single point plus size, two-point stretch, all points), offsets, scale and clipping. + The content is cropped to the snapshot region, everything it draws, and the screen. +- **Paint order:** strata, then frame level, then draw layer, then sublevel, then creation order. + Effective alpha and visibility are honoured. +- **Textures:** + - colour and gradient textures + - Blizzard's white textures, drawn as solid colour + - resolved image files, tinted by vertex colour, including nine-slice and + texture coordinates (crops, mirrors, rotations and tiling beyond 0–1, such as backdrop edges) + - anything else as a dashed placeholder titled with its path +- **Status bars and text:** status bar fills by value, and font strings with justification, outline and `|c` colour codes. + +Rendering is deterministic: the same scene gives the same SVG. + +## Blizzard art + +`wowproof.sources.wow_ui_textures` resolves `Interface\...` paths to PNGs from +the public [Gethe/wow-ui-textures](https://github.com/Gethe/wow-ui-textures) +mirror. It fetches only the files a render asks for, matches names +case-insensitively and caches everything under one pinned commit. Keep the +cache out of version control. It needs `curl` and `jq`. + +```lua +local art = require("wowproof.sources.wow_ui_textures")({ + ref = "d23deaf8f44a7d280dc974a5c9d5321c013db59b", + dir = ".proof-art", + fetch = true, + token = os.getenv("GITHUB_TOKEN"), +}) +assets.textures = function(path) return ownTexture(path) or art(path) end +``` + +Files the commit lacks are remembered in `missing-.txt` and never +requested again. Atlases (`SetAtlas`) still draw as placeholders: they need +Blizzard's atlas table. + +## Tests + +`spec/` holds busted-style specs (`describe`/`it`/`assert.*`) that need +nothing but this package. `spec/package_spec.lua` also fails if a file here +mentions the addon that hosts it. diff --git a/wowproof/adapters/mock_state.lua b/wowproof/adapters/mock_state.lua new file mode 100644 index 0000000..49d7a33 --- /dev/null +++ b/wowproof/adapters/mock_state.lua @@ -0,0 +1,203 @@ +return function(options) + options = options or {} + local isSecret = options.isSecret or function() return false end + local reveal = options.reveal or function(value) return value end + local objects = options.objects or function() return {} end + local globals = options.globals or {} + + local function Plain(value) + if isSecret(value) then return reveal(value) end + return value + end + + local function State(region) + return rawget(region, "__state") + end + + local function LastCall(region, name) + local calls = rawget(region, "__calls") or {} + for index = #calls, 1, -1 do + if calls[index][1] == name then return calls[index] end + end + end + + local function Color(color) + if not color then return nil end + return { Plain(color[1]), Plain(color[2]), Plain(color[3]), Plain(color[4]) } + end + + local function TexCoords(coords) + if type(coords) ~= "table" or #coords < 4 then return nil end + local plain = {} + for index, value in ipairs(coords) do plain[index] = Plain(value) end + return plain + end + + local order = setmetatable({}, { __mode = "k" }) + local function Order(region) + if not order[region] then + for index, object in ipairs(objects()) do order[object] = index end + end + return order[region] or 0 + end + + local adapter = {} + + function adapter.Parent(region) + local parent = State(region).parent + if type(parent) == "table" and rawget(parent, "__state") then return parent end + return nil + end + + function adapter.Children(region) + local state = State(region) + local children = {} + for child in pairs(state.kids or {}) do + if State(child).parent == region then children[#children + 1] = child end + end + table.sort(children, function(a, b) return Order(a) < Order(b) end) + return children + end + + adapter.Order = Order + + function adapter.ClipsChildren(region) + local call = LastCall(region, "SetClipsChildren") + return State(region).clipsChildren == true or (call ~= nil and call[2] == true) + end + + function adapter.FillOf(region) + local parent = adapter.Parent(region) + if parent and State(parent).fill == region then return parent end + return nil + end + + function adapter.Type(region) + return rawget(region, "__type") + end + + function adapter.Name(region) + return State(region).name + end + + function adapter.Points(region) + local points = {} + for _, point in ipairs(State(region).points or {}) do + if point[1] == "ALL" then + points[#points + 1] = { all = true, relativeTo = point[2] } + else + points[#points + 1] = { + point = point[1], + relativeTo = point[2], + relativePoint = point[3], + x = Plain(point[4]), + y = Plain(point[5]), + } + end + end + return points + end + + function adapter.Size(region) + local state = State(region) + return Plain(state.width) or 0, Plain(state.height) or 0 + end + + function adapter.Scale(region) + return Plain(State(region).scale) or 1 + end + + function adapter.Shown(region) + return Plain(State(region).shown) ~= false + end + + function adapter.Alpha(region) + local alpha = Plain(State(region).alpha) + if alpha == nil then return 1 end + return alpha + end + + function adapter.IgnoresParentAlpha(region) + return State(region).ignoreParentAlpha == true + end + + function adapter.Strata(region) + return State(region).strata + end + + function adapter.Level(region) + return Plain(State(region).level) or 0 + end + + function adapter.Layer(region) + local call = LastCall(region, "SetDrawLayer") + if call then return call[2], call[3] end + return State(region).layer, State(region).sublevel + end + + function adapter.Texture(region) + local state = State(region) + local gradient + if state.gradient then + gradient = { orientation = state.gradient[1], from = Color(state.gradient[2]), to = Color(state.gradient[3]) } + end + local bar = adapter.FillOf(region) + local barState = bar and State(bar) or {} + local file = state.texture or barState.texture + if file ~= nil and type(file) ~= "string" then file = tostring(file) end + if file and file:sub(1, 6) == "atlas:" then file = nil end + return { + color = Color(state.colorTexture), + vertexColor = Color(barState.color) or Color(state.vertexColor), + file = file, + atlas = state.atlas, + gradient = gradient, + blend = state.blendMode, + slice = state.sliceMargins, + texCoords = TexCoords(state.texCoords), + } + end + + function adapter.Bar(region) + if adapter.Type(region) ~= "StatusBar" then return nil end + local state = State(region) + local fill = state.fill and State(state.fill) or {} + return { + min = Plain(state.min), + max = Plain(state.max), + value = Plain(state.value), + orientation = state.orientation, + reverse = state.reverseFill == true, + color = Color(state.color) or Color(fill.vertexColor) or Color(fill.colorTexture), + file = state.texture, + } + end + + local function FontObject(value) + if type(value) == "string" then value = globals[value] end + if type(value) == "table" and rawget(value, "__state") then return value end + return nil + end + + function adapter.Text(region) + if adapter.Type(region) ~= "FontString" then return nil end + local state = State(region) + local font = state.font + local fontObject = FontObject(state.fontObject) + local inherited = fontObject and State(fontObject) + font = font or (inherited and inherited.font) or {} + local justifyH = state.justifyH or (LastCall(region, "SetJustifyH") or {})[2] + local justifyV = state.justifyV or (LastCall(region, "SetJustifyV") or {})[2] + return { + text = Plain(state.text), + font = font[1], + size = Plain(font[2]) or 12, + flags = font[3], + color = Color(state.textColor) or (inherited and Color(inherited.textColor)), + justifyH = justifyH, + justifyV = justifyV, + } + end + + return adapter +end diff --git a/wowproof/init.lua b/wowproof/init.lua new file mode 100644 index 0000000..19483de --- /dev/null +++ b/wowproof/init.lua @@ -0,0 +1,113 @@ +local Scene = require("wowproof.scene") +local Layout = require("wowproof.layout") +local Paint = require("wowproof.paint") +local Raster = require("wowproof.raster") +local Sheet = require("wowproof.sheet") + +local Proof = {} +Proof.__index = Proof +Proof.Scene, Proof.Layout, Proof.Paint, Proof.Raster, Proof.Sheet = Scene, Layout, Paint, Raster, Sheet + +function Proof.New(options) + options = options or {} + local assets = options.assets or {} + local outDir = options.outDir or ".proof" + return setmetatable({ + adapter = Scene.Validate(options.adapter), + assets = assets, + outDir = outDir, + cacheDir = outDir .. "/.cache", + screen = options.screen, + scale = options.scale or 2, + png = options.png ~= false, + title = options.title or "UI proof", + settle = options.settle, + entries = {}, + images = {}, + }, Proof) +end + +function Proof:Image(file) + local cached = self.images[file] + if cached == nil then + local resolve = self.assets.textures + local localFile = resolve and resolve(file) + local png = localFile and Raster.ToPng(localFile, self.cacheDir) + local uri = png and Raster.DataUri(png) + cached = false + if uri then + local width, height = Raster.PngSize(png) + cached = { uri = uri, width = width, height = height } + end + self.images[file] = cached + end + if not cached then return nil end + return cached.uri, cached.width, cached.height +end + +function Proof:Font(file) + local fonts = self.assets.fonts + if not fonts then return nil end + if fonts.family then + local family, weight = fonts.family(file) + if family then return family, weight end + end + return fonts.default, fonts.defaultWeight +end + +local function FileName(name) + return (name:gsub("[^%w%-_]+", "-")) +end + +function Proof:Render(region, options) + options = options or {} + local layout = Layout.New(self.adapter, self.screen) + if self.settle then self.settle(layout, region) end + return Paint.Render({ + adapter = self.adapter, + layout = layout, + root = region, + pad = options.pad, + debug = options.debug, + background = options.background, + image = function(file) return self:Image(file) end, + font = function(file) return self:Font(file) end, + }) +end + +function Proof:Snapshot(region, name, options) + options = options or {} + local svg, info = self:Render(region, options) + Raster.MakeDir(self.outDir) + local base = self.outDir .. "/" .. FileName(name) + local entry = { name = name, svg = base .. ".svg", width = info.width, height = info.height, regions = info.regions } + Raster.Write(entry.svg, svg) + if self.png then + local fonts = self.assets.fonts and self.assets.fonts.dirs + self.fontConfig = self.fontConfig or Raster.FontConfig(fonts, self.cacheDir) + if Raster.Has("rsvg-convert") then + entry.png = Raster.SvgToPng(entry.svg, base .. ".png", options.scale or self.scale, self.fontConfig) + if not entry.png then + os.remove(base .. ".png") + error("wowproof: rsvg-convert could not render " .. entry.svg, 2) + end + end + end + self.entries[#self.entries + 1] = entry + return entry +end + +function Proof:Fail(name, message) + local entry = { name = name, error = tostring(message) } + self.entries[#self.entries + 1] = entry + return entry +end + +function Proof:Sheet() + Raster.MakeDir(self.outDir) + local file = self.outDir .. "/index.html" + Raster.Write(file, Sheet.Render(self.title, self.entries)) + return file +end + +return Proof diff --git a/wowproof/layout.lua b/wowproof/layout.lua new file mode 100644 index 0000000..fb3d3cc --- /dev/null +++ b/wowproof/layout.lua @@ -0,0 +1,141 @@ +local Layout = {} +Layout.__index = Layout + +local FRACTIONS = { + TOPLEFT = { 0, 0 }, + TOP = { 0.5, 0 }, + TOPRIGHT = { 1, 0 }, + LEFT = { 0, 0.5 }, + CENTER = { 0.5, 0.5 }, + RIGHT = { 1, 0.5 }, + BOTTOMLEFT = { 0, 1 }, + BOTTOM = { 0.5, 1 }, + BOTTOMRIGHT = { 1, 1 }, +} +Layout.FRACTIONS = FRACTIONS + +local UNRESOLVED = false + +function Layout.New(adapter, screen) + screen = screen or { width = 1920, height = 1080 } + return setmetatable({ + adapter = adapter, + screen = { left = 0, top = 0, width = screen.width, height = screen.height }, + rects = {}, + scales = {}, + resolving = {}, + }, Layout) +end + +function Layout:Scale(region) + local cached = self.scales[region] + if cached then return cached end + local scale = self.adapter.Scale(region) or 1 + local parent = self.adapter.Parent(region) + if parent then scale = scale * self:Scale(parent) end + self.scales[region] = scale + return scale +end + +function Layout:Place(region, rect) + self.rects[region] = rect +end + +function Layout:Rect(region) + if region == nil then return self.screen end + local cached = self.rects[region] + if cached ~= nil then return cached or nil end + if self.resolving[region] then return nil end + self.resolving[region] = true + local rect = self:Resolve(region) + self.resolving[region] = nil + self.rects[region] = rect or UNRESOLVED + return rect +end + +local function Axis(anchors, size) + local low, high + for _, anchor in ipairs(anchors) do + if not low or anchor[1] < low[1] then low = anchor end + if not high or anchor[1] > high[1] then high = anchor end + end + if not low then return nil end + if low[1] ~= high[1] then + local span = (high[2] - low[2]) / (high[1] - low[1]) + return low[2] - low[1] * span, span + end + return low[2] - low[1] * size, size +end + +function Layout:IntrinsicSize(region, width, height) + if self.adapter.Type(region) ~= "FontString" then return width, height end + local text = self.adapter.Text(region) + local size = text and text.size or 12 + if width == 0 then width = #tostring(text and text.text or "") * size * 0.55 end + if height == 0 then height = size end + return width, height +end + +local function Clamp(value) + if value < 0 then return 0 end + if value > 1 then return 1 end + return value +end + +function Layout:FillRect(bar) + local rect = self:Rect(bar) + local info = rect and self.adapter.Bar(bar) + if not info then return nil end + local low, high, value = info.min or 0, info.max or 1, info.value or 0 + local fraction = high > low and Clamp((value - low) / (high - low)) or 0 + local fill = { left = rect.left, top = rect.top, width = rect.width, height = rect.height } + if info.orientation == "VERTICAL" then + fill.height = rect.height * fraction + if not info.reverse then fill.top = rect.top + rect.height - fill.height end + else + fill.width = rect.width * fraction + if info.reverse then fill.left = rect.left + rect.width - fill.width end + end + return fill +end + +function Layout:Resolve(region) + local adapter = self.adapter + local bar = adapter.FillOf and adapter.FillOf(region) + if bar then return self:FillRect(bar) end + local points = adapter.Points(region) + local parent = adapter.Parent(region) + if #points == 0 then + if parent then return nil end + return self.screen + end + local scale = self:Scale(region) + local width, height = adapter.Size(region) + width, height = self:IntrinsicSize(region, width or 0, height or 0) + width, height = width * scale, height * scale + local xs, ys = {}, {} + for _, point in ipairs(points) do + local relative = point.relativeTo or parent + local target = self:Rect(relative) + if not target then return nil end + if point.all then + xs[#xs + 1] = { 0, target.left } + xs[#xs + 1] = { 1, target.left + target.width } + ys[#ys + 1] = { 0, target.top } + ys[#ys + 1] = { 1, target.top + target.height } + else + local own = FRACTIONS[point.point] + local other = FRACTIONS[point.relativePoint or point.point] + if not own or not other then + error("unknown anchor point " .. tostring(point.point) .. "/" .. tostring(point.relativePoint), 2) + end + xs[#xs + 1] = { own[1], target.left + other[1] * target.width + (point.x or 0) * scale } + ys[#ys + 1] = { own[2], target.top + other[2] * target.height - (point.y or 0) * scale } + end + end + local left, resolvedWidth = Axis(xs, width) + local top, resolvedHeight = Axis(ys, height) + return { left = left, top = top, width = resolvedWidth, height = resolvedHeight } +end + +return Layout diff --git a/wowproof/paint.lua b/wowproof/paint.lua new file mode 100644 index 0000000..5a92018 --- /dev/null +++ b/wowproof/paint.lua @@ -0,0 +1,474 @@ +local Scene = require("wowproof.scene") + +local Paint = {} + +local DEFAULT_BAR_COLOR = { 0.2, 0.7, 0.3, 1 } +local DEFAULT_TEXT_COLOR = { 1, 1, 1, 1 } +local PLACEHOLDER_COLOR = { 0.42, 0.45, 0.5, 0.25 } + +local function Number(value) + if math.abs(value) < 0.005 then return "0" end + local text = string.format("%.2f", value):gsub("%.?0+$", "") + return text +end +Paint.Number = Number + +local function Escape(text) + return (tostring(text):gsub("&", "&"):gsub("<", "<"):gsub(">", ">"):gsub('"', """)) +end +Paint.Escape = Escape + +local function Clamp(value) + if value < 0 then return 0 end + if value > 1 then return 1 end + return value +end + +local function Rgb(color) + return string.format("rgb(%d,%d,%d)", + math.floor(Clamp(color[1] or 0) * 255 + 0.5), + math.floor(Clamp(color[2] or 0) * 255 + 0.5), + math.floor(Clamp(color[3] or 0) * 255 + 0.5)) +end + +local function Multiply(color, tint) + if not tint then return color end + return { + (color[1] or 1) * (tint[1] or 1), + (color[2] or 1) * (tint[2] or 1), + (color[3] or 1) * (tint[3] or 1), + (color[4] or 1) * (tint[4] or 1), + } +end + +local function RectAttributes(rect) + return string.format('x="%s" y="%s" width="%s" height="%s"', + Number(rect.left), Number(rect.top), Number(math.max(rect.width, 0)), Number(math.max(rect.height, 0))) +end + +local function Fill(color, alpha) + return string.format('fill="%s" fill-opacity="%s"', Rgb(color), Number(Clamp((color[4] or 1) * alpha))) +end + +local function Union(a, b) + if not a then return { left = b.left, top = b.top, width = b.width, height = b.height } end + local left, top = math.min(a.left, b.left), math.min(a.top, b.top) + local right = math.max(a.left + a.width, b.left + b.width) + local bottom = math.max(a.top + a.height, b.top + b.height) + return { left = left, top = top, width = right - left, height = bottom - top } +end + +local function Intersect(a, b) + local left, top = math.max(a.left, b.left), math.max(a.top, b.top) + local right = math.min(a.left + a.width, b.left + b.width) + local bottom = math.min(a.top + a.height, b.top + b.height) + if right <= left or bottom <= top then return nil end + return { left = left, top = top, width = right - left, height = bottom - top } +end + +local function Contains(outer, inner) + return inner.left >= outer.left and inner.top >= outer.top + and inner.left + inner.width <= outer.left + outer.width + and inner.top + inner.height <= outer.top + outer.height +end + +local Context = {} +Context.__index = Context + +function Context:Define(markup) + self.nextId = self.nextId + 1 + local id = "d" .. self.nextId + self.defs[#self.defs + 1] = markup:gsub("{id}", id) + return id +end + +function Context:Emit(markup) + self.body[#self.body + 1] = markup +end + +function Context:Visible(region) + local node = region + while node do + if not self.adapter.Shown(node) then return false end + if node == self.root then return true end + node = self.adapter.Parent(node) + end + return true +end + +function Context:EffectiveAlpha(region) + local alpha, node = 1, region + while node do + alpha = alpha * (self.adapter.Alpha(node) or 1) + if node == self.root or self.adapter.IgnoresParentAlpha(node) then break end + node = self.adapter.Parent(node) + end + return alpha +end + +function Context:Clip(region) + local cached = self.clips[region] + if cached ~= nil then return cached or nil end + local parent = region ~= self.root and self.adapter.Parent(region) + local clip + if parent then + clip = self:Clip(parent) + local parentRect = self.adapter.ClipsChildren and self.adapter.ClipsChildren(parent) and self.layout:Rect(parent) + if parentRect then + if clip then + clip = Intersect(clip, parentRect) or { left = parentRect.left, top = parentRect.top, width = 0, height = 0 } + else + clip = parentRect + end + end + end + self.clips[region] = clip or false + return clip +end + +function Context:ClipPath(clip) + local key = string.format("%s,%s,%s,%s", Number(clip.left), Number(clip.top), Number(clip.width), Number(clip.height)) + if not self.clipIds[key] then + self.clipIds[key] = self:Define(string.format('', RectAttributes(clip))) + end + return self.clipIds[key] +end + +function Context:Strata(region) + local node = region + while node do + local strata = self.adapter.Strata(node) + if strata then return Scene.STRATA_INDEX[strata] or Scene.STRATA_INDEX.MEDIUM end + node = self.adapter.Parent(node) + end + return Scene.STRATA_INDEX.MEDIUM +end + +function Context:SortKey(region) + local adapter = self.adapter + local isRegion = Scene.IsRegion(adapter, region) + local frame = isRegion and adapter.Parent(region) or region + local layer, sublevel = adapter.Layer(region) + if not isRegion then layer = "ARTWORK" end + return { + self:Strata(frame), + frame and adapter.Level(frame) or 0, + Scene.LAYER_INDEX[layer or "ARTWORK"] or Scene.LAYER_INDEX.ARTWORK, + sublevel or 0, + adapter.Order(region), + } +end + +local function CompareKeys(a, b) + for index = 1, #a.key do + if a.key[index] ~= b.key[index] then return a.key[index] < b.key[index] end + end + return false +end + +function Context:Collect(region, out) + out[#out + 1] = region + for _, child in ipairs(self.adapter.Children(region)) do self:Collect(child, out) end + return out +end + +local GRADIENT = '' + .. '' + .. '' + +function Context:ImageDef(file) + local cached = self.images[file] + if cached ~= nil then return cached or nil end + local href, width, height = self.image(file) + if not href then + self.images[file] = false + return nil + end + local id = self:Define(string.format('', + Number(width or 1), Number(height or 1), href)) + local image = { id = id, width = width, height = height } + self.images[file] = image + return image +end + +function Context:DrawImagePiece(image, target, source) + if target.width <= 0 or target.height <= 0 or source.width <= 0 or source.height <= 0 then return end + self:Emit(string.format('', + RectAttributes(target), Number(source.left), Number(source.top), Number(source.width), Number(source.height), image.id)) +end + +local function SourceRect(coords, width, height) + if not coords or #coords < 4 then return { left = 0, top = 0, width = width, height = height } end + local xs, ys = { coords[1], coords[2] }, { coords[3], coords[4] } + if #coords >= 8 then + xs = { coords[1], coords[3], coords[5], coords[7] } + ys = { coords[2], coords[4], coords[6], coords[8] } + end + local left, right = math.min(unpack(xs)), math.max(unpack(xs)) + local top, bottom = math.min(unpack(ys)), math.max(unpack(ys)) + return { left = left * width, top = top * height, width = (right - left) * width, height = (bottom - top) * height } +end +Paint.SourceRect = SourceRect + +local function Corners(coords) + if #coords >= 8 then + return { coords[1], coords[2] }, { coords[3], coords[4] }, { coords[5], coords[6] } + end + local left, right, top, bottom = coords[1], coords[2], coords[3], coords[4] + return { left, top }, { left, bottom }, { right, top } +end + +local function NeedsAffine(coords) + if not coords or #coords < 4 then return false end + for _, value in ipairs(coords) do + if value < 0 or value > 1 then return true end + end + local upperLeft, lowerLeft, upperRight = Corners(coords) + return upperLeft[2] ~= upperRight[2] or upperLeft[1] ~= lowerLeft[1] + or upperRight[1] < upperLeft[1] or lowerLeft[2] < upperLeft[2] +end +Paint.NeedsAffine = NeedsAffine + +local MAX_TILE = 8192 + +local function AffineTransform(rect, coords, width, height) + local upperLeft, lowerLeft, upperRight = Corners(coords) + local ax, ay = upperRight[1] - upperLeft[1], upperRight[2] - upperLeft[2] + local bx, by = lowerLeft[1] - upperLeft[1], lowerLeft[2] - upperLeft[2] + local det = ax * by - bx * ay + if math.abs(det) < 1e-9 then return nil end + local w, h = rect.width, rect.height + local tileWidth = math.sqrt((w * by / det) ^ 2 + (h * ay / det) ^ 2) + local tileHeight = math.sqrt((w * bx / det) ^ 2 + (h * ax / det) ^ 2) + if tileWidth < 0.01 or tileHeight < 0.01 or tileWidth > MAX_TILE or tileHeight > MAX_TILE then return nil end + return { + w * by / det / width, + h * -ay / det / width, + w * -bx / det / height, + h * ax / det / height, + rect.left - w * (by * upperLeft[1] - bx * upperLeft[2]) / det, + rect.top - h * (ax * upperLeft[2] - ay * upperLeft[1]) / det, + } +end +Paint.AffineTransform = AffineTransform + +local function SliceSpans(start, length, sourceLength, low, high) + local scale = math.min(1, length / math.max(low + high, 1)) + local lowTarget, highTarget = low * scale, high * scale + return { + { start, lowTarget, 0, low }, + { start + lowTarget, length - lowTarget - highTarget, low, sourceLength - low - high }, + { start + length - highTarget, highTarget, sourceLength - high, high }, + } +end + +function Context:DrawImageAffine(image, rect, coords) + if rect.width <= 0 or rect.height <= 0 then return end + local matrix = AffineTransform(rect, coords, image.width, image.height) + if not matrix then return end + local values = {} + for index, value in ipairs(matrix) do values[index] = string.format("%.6g", value) end + local id = self:Define(string.format( + '', + Number(image.width), Number(image.height), table.concat(values, " "), image.id)) + self:Emit(string.format('', RectAttributes(rect), id)) +end + +function Context:DrawNineSlice(image, slice, rect) + local columns = SliceSpans(rect.left, rect.width, image.width, slice[1] or 0, slice[3] or 0) + local rows = SliceSpans(rect.top, rect.height, image.height, slice[2] or 0, slice[4] or 0) + for _, row in ipairs(rows) do + for _, column in ipairs(columns) do + self:DrawImagePiece(image, + { left = column[1], top = row[1], width = column[2], height = row[2] }, + { left = column[3], top = row[3], width = column[4], height = row[4] }) + end + end +end + +function Context:DrawTexture(region, rect, alpha) + local texture = self.adapter.Texture(region) + if not texture then return end + local blend = texture.blend == "ADD" and ' style="mix-blend-mode:screen"' or "" + if texture.gradient then + local from, to = texture.gradient.from, texture.gradient.to + local vertical = texture.gradient.orientation == "VERTICAL" + local id = self:Define(string.format(GRADIENT, + "0", vertical and "1" or "0", vertical and "0" or "1", "0", + Rgb(from), Number(Clamp((from[4] or 1) * alpha)), Rgb(to), Number(Clamp((to[4] or 1) * alpha)))) + self:Emit(string.format('', RectAttributes(rect), id, blend)) + return + end + local solid = texture.color or (Scene.IsSolidFile(texture.file) and { 1, 1, 1, 1 }) + if solid then + self:Emit(string.format('', RectAttributes(rect), Fill(Multiply(solid, texture.vertexColor), alpha), blend)) + return + end + local image = texture.file and self:ImageDef(texture.file) + if image then + local filter = "" + local tint = texture.vertexColor + if tint then + local id = self:Define(string.format( + '', + Number(tint[1] or 1), Number(tint[2] or 1), Number(tint[3] or 1), Number(tint[4] or 1))) + filter = string.format(' filter="url(#%s)"', id) + end + self:Emit(string.format('', Number(Clamp(alpha)), filter, blend)) + if texture.slice and image.width then + self:DrawNineSlice(image, texture.slice, rect) + elseif NeedsAffine(texture.texCoords) and image.width then + self:DrawImageAffine(image, rect, texture.texCoords) + else + self:DrawImagePiece(image, rect, SourceRect(texture.texCoords, image.width or 1, image.height or 1)) + end + self:Emit("") + return + end + if texture.vertexColor and texture.file then + self:Emit(string.format('', RectAttributes(rect), Fill(texture.vertexColor, alpha), blend)) + return + end + if texture.file or texture.atlas then + self:Emit(string.format('%s', + RectAttributes(rect), Fill(PLACEHOLDER_COLOR, alpha), Rgb(PLACEHOLDER_COLOR), + Escape(texture.file or texture.atlas))) + end +end + +function Context:DrawBar(region, alpha) + local bar = self.adapter.Bar(region) + local fill = bar and self.layout:FillRect(region) + if not fill or fill.width <= 0 or fill.height <= 0 then return end + local color = bar.color or DEFAULT_BAR_COLOR + self:Emit(string.format('', RectAttributes(fill), Fill(color, alpha))) +end + +local ANCHORS = { LEFT = "start", CENTER = "middle", RIGHT = "end" } + +local function Segments(text, baseColor) + local segments, color, position = {}, baseColor, 1 + text = text:gsub("|T.-|t", ""):gsub("|A.-|a", ""):gsub("|n", "\n") + while position <= #text do + local start, finish, code = text:find("|c(%x%x%x%x%x%x%x%x)", position) + local reset = text:find("|r", position, true) + local nextStop = math.min(start or #text + 1, reset or #text + 1) + if nextStop > position then segments[#segments + 1] = { text:sub(position, nextStop - 1), color } end + if start and start == nextStop then + color = { + tonumber(code:sub(3, 4), 16) / 255, + tonumber(code:sub(5, 6), 16) / 255, + tonumber(code:sub(7, 8), 16) / 255, + tonumber(code:sub(1, 2), 16) / 255, + } + position = finish + 1 + elseif reset and reset == nextStop then + color = baseColor + position = reset + 2 + else + position = nextStop + end + end + return segments +end +Paint.Segments = Segments + +function Context:DrawText(region, rect, alpha) + local text = self.adapter.Text(region) + if not text or text.text == nil or tostring(text.text) == "" then return end + local size = text.size or 12 + local justify = text.justifyH or "CENTER" + local x = rect.left + if justify == "CENTER" then x = rect.left + rect.width / 2 elseif justify == "RIGHT" then x = rect.left + rect.width end + local y = rect.top + rect.height / 2 + if text.justifyV == "TOP" then y = rect.top + size / 2 elseif text.justifyV == "BOTTOM" then y = rect.top + rect.height - size / 2 end + local flags = text.flags or "" + local stroke = "" + if flags:find("OUTLINE", 1, true) then + stroke = string.format(' stroke="#000" stroke-width="%s" stroke-linejoin="round" paint-order="stroke"', + Number(flags:find("THICK", 1, true) and size * 0.2 or size * 0.12)) + end + local family, weight = self.font(text.font) + local spans = {} + for _, segment in ipairs(Segments(tostring(text.text), text.color or DEFAULT_TEXT_COLOR)) do + spans[#spans + 1] = string.format('%s', Fill(segment[2], alpha), Escape(segment[1])) + end + self:Emit(string.format( + '%s', + Number(x), Number(y), Escape(family or "sans-serif"), weight or 400, Number(size), + ANCHORS[justify] or "middle", stroke, table.concat(spans))) +end + +function Context:DrawOutline(region, rect) + self:Emit(string.format('%s', + RectAttributes(rect), Escape(self.adapter.Name(region) or self.adapter.Type(region)))) +end + +function Paint.Render(options) + local adapter, layout, root = options.adapter, options.layout, options.root + local context = setmetatable({ + adapter = adapter, + layout = layout, + root = root, + image = options.image or function() return nil end, + font = options.font or function() return nil end, + defs = {}, + body = {}, + images = {}, + clips = {}, + clipIds = {}, + nextId = 0, + }, Context) + local rootRect = layout:Rect(root) + if not rootRect then error("wowproof: the region has no resolvable position", 2) end + if not adapter.Shown(root) then error("wowproof: the region is hidden", 2) end + + local entries, bounds = {}, nil + for _, region in ipairs(context:Collect(root, {})) do + local rect = layout:Rect(region) + local clip = rect and context:Clip(region) + local shown = rect and (clip and Intersect(rect, clip) or (not clip and rect)) + if shown and shown.width > 0 and shown.height > 0 and context:Visible(region) then + local alpha = context:EffectiveAlpha(region) + if alpha > 0 then + entries[#entries + 1] = { region = region, rect = rect, clip = clip, alpha = alpha, key = context:SortKey(region) } + if Scene.IsRegion(adapter, region) or not adapter.FillOf then bounds = Union(bounds, shown) end + end + end + end + table.sort(entries, CompareKeys) + + for _, entry in ipairs(entries) do + local clipped = entry.clip and not Contains(entry.clip, entry.rect) + if clipped then context:Emit(string.format('', context:ClipPath(entry.clip))) end + local kind = adapter.Type(entry.region) + if kind == "Texture" then + context:DrawTexture(entry.region, entry.rect, entry.alpha) + elseif kind == "FontString" then + context:DrawText(entry.region, entry.rect, entry.alpha) + elseif not adapter.FillOf and not Scene.IsRegion(adapter, entry.region) then + context:DrawBar(entry.region, entry.alpha) + end + if clipped then context:Emit("") end + end + if options.debug then + for _, entry in ipairs(entries) do context:DrawOutline(entry.region, entry.rect) end + end + + local pad = options.pad or 8 + local view = Intersect(Union(bounds or rootRect, rootRect), layout.screen) or rootRect + view = { left = view.left - pad, top = view.top - pad, width = view.width + pad * 2, height = view.height + pad * 2 } + local width, height = math.ceil(view.width), math.ceil(view.height) + local out = { + string.format('', + width, height, Number(view.left), Number(view.top), Number(width), Number(height)), + } + if #context.defs > 0 then out[#out + 1] = "" .. table.concat(context.defs) .. "" end + out[#out + 1] = string.format('', + Number(view.left), Number(view.top), width, height, options.background or "#14171c") + for _, markup in ipairs(context.body) do out[#out + 1] = markup end + out[#out + 1] = "\n" + return table.concat(out, "\n"), { width = width, height = height, regions = #entries } +end + +return Paint diff --git a/wowproof/raster.lua b/wowproof/raster.lua new file mode 100644 index 0000000..c769ec2 --- /dev/null +++ b/wowproof/raster.lua @@ -0,0 +1,137 @@ +local Raster = {} + +local function Quote(text) + return "'" .. tostring(text):gsub("'", "'\\''") .. "'" +end +Raster.Quote = Quote + +local function Run(command) + local result = os.execute(command) + return result == 0 or result == true +end +Raster.Run = Run + +local tools = {} +function Raster.Has(tool) + if tools[tool] == nil then tools[tool] = Run("command -v " .. Quote(tool) .. " >/dev/null 2>&1") end + return tools[tool] +end + +function Raster.MakeDir(dir) + if not Run("mkdir -p " .. Quote(dir)) then error("wowproof: can't create " .. dir, 2) end +end + +function Raster.Exists(file) + local handle = io.open(file, "rb") + if not handle then return false end + handle:close() + return true +end + +function Raster.Write(file, content) + local handle = assert(io.open(file, "wb")) + handle:write(content) + handle:close() +end + +function Raster.Read(file) + local handle = io.open(file, "rb") + if not handle then return nil end + local content = handle:read("*a") + handle:close() + return content +end + +local ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + +function Raster.Base64(data) + local out = {} + for index = 1, #data, 3 do + local a, b, c = data:byte(index, index + 2) + local n = a * 65536 + (b or 0) * 256 + (c or 0) + local d1 = math.floor(n / 262144) % 64 + local d2 = math.floor(n / 4096) % 64 + local d3 = math.floor(n / 64) % 64 + local d4 = n % 64 + out[#out + 1] = ALPHABET:sub(d1 + 1, d1 + 1) .. ALPHABET:sub(d2 + 1, d2 + 1) + .. (b and ALPHABET:sub(d3 + 1, d3 + 1) or "=") + .. (c and ALPHABET:sub(d4 + 1, d4 + 1) or "=") + end + return table.concat(out) +end + +local function CacheName(file) + return (file:gsub("[^%w%-_.]+", "_")) .. ".png" +end + +function Raster.ImageTool() + if Raster.Has("magick") then return "magick" end + if Raster.Has("convert") then return "convert" end + return nil +end + +function Raster.ToPng(file, cacheDir) + if file:lower():match("%.png$") then return Raster.Exists(file) and file or nil end + local tool = Raster.ImageTool() + if not tool or not Raster.Exists(file) then return nil end + Raster.MakeDir(cacheDir) + local target = cacheDir .. "/" .. CacheName(file) + if Raster.Exists(target) then return target end + if not Run(tool .. " " .. Quote(file) .. " " .. Quote(target) .. " >/dev/null 2>&1") then return nil end + return target +end + +local function UInt32(data, offset) + local a, b, c, d = data:byte(offset, offset + 3) + return ((a * 256 + b) * 256 + c) * 256 + d +end + +function Raster.PngSize(png) + local data = Raster.Read(png) + if not data or #data < 24 or data:sub(13, 16) ~= "IHDR" then return nil end + return UInt32(data, 17), UInt32(data, 21) +end + +function Raster.DataUri(png) + local data = Raster.Read(png) + if not data then return nil end + return "data:image/png;base64," .. Raster.Base64(data) +end + +local FONTS_CONF = [[ + + +%s/etc/fonts/fonts.conf +%s + +]] + +local function Absolute(path) + if path:sub(1, 1) == "/" then return path end + local handle = io.popen("pwd") + local cwd = handle:read("*l") + handle:close() + return cwd .. "/" .. path +end +Raster.Absolute = Absolute + +function Raster.FontConfig(dirs, cacheDir) + Raster.MakeDir(cacheDir) + local entries = {} + for _, dir in ipairs(dirs or {}) do + entries[#entries + 1] = "" .. Absolute(dir) .. "\n" + end + local file = Absolute(cacheDir .. "/fonts.conf") + Raster.Write(file, string.format(FONTS_CONF, table.concat(entries), Absolute(cacheDir .. "/fontcache"))) + return file +end + +function Raster.SvgToPng(svg, png, scale, fontConfig) + if not Raster.Has("rsvg-convert") then return nil end + local env = fontConfig and ("FONTCONFIG_FILE=" .. Quote(fontConfig) .. " ") or "" + local command = string.format("%srsvg-convert -z %s -o %s %s", env, tostring(scale or 1), Quote(png), Quote(svg)) + if not Run(command) then return nil end + return png +end + +return Raster diff --git a/wowproof/runner.lua b/wowproof/runner.lua new file mode 100644 index 0000000..8cd58df --- /dev/null +++ b/wowproof/runner.lua @@ -0,0 +1,36 @@ +local Runner = {} + +local function Selected(name, filters) + if not filters or #filters == 0 then return true end + for _, filter in ipairs(filters) do + if name:find(filter, 1, true) then return true end + end + return false +end + +function Runner.Run(options) + local proof, print = options.proof, options.print or print + local passed, failed = 0, 0 + for _, scenario in ipairs(options.scenarios) do + if Selected(scenario.name, options.filters) then + local ok, err = xpcall(function() + local region = scenario.build() + local entry = proof:Snapshot(region, scenario.name, scenario.options) + print(string.format(" ok %-40s %s", scenario.name, entry.png or entry.svg)) + end, debug.traceback) + if ok then + passed = passed + 1 + else + failed = failed + 1 + proof:Fail(scenario.name, err) + print(string.format(" FAIL %s\n %s", scenario.name, tostring(err):gsub("\n", "\n "))) + end + if options.after then options.after(scenario) end + end + end + local sheet = proof:Sheet() + print(string.format("%d snapshots, %d failed: %s", passed, failed, sheet)) + return passed, failed, sheet +end + +return Runner diff --git a/wowproof/scene.lua b/wowproof/scene.lua new file mode 100644 index 0000000..3c40a6f --- /dev/null +++ b/wowproof/scene.lua @@ -0,0 +1,54 @@ +local Scene = {} + +Scene.REQUIRED = { + "Parent", "Children", "Order", "Type", "Name", + "Points", "Size", "Scale", "Shown", "Alpha", "IgnoresParentAlpha", + "Strata", "Level", "Layer", + "Texture", "Bar", "Text", +} + +Scene.OPTIONAL = { "FillOf", "ClipsChildren" } + +Scene.SOLID_FILES = { + ["interface\\buttons\\white8x8"] = true, + ["interface\\chatframe\\chatframebackground"] = true, + ["interface\\tooltips\\ui-tooltip-background"] = true, +} + +function Scene.IsSolidFile(file) + return type(file) == "string" and Scene.SOLID_FILES[file:lower()] == true +end + +Scene.REGION_TYPES ={ Texture = true, FontString = true, Line = true, MaskTexture = true } + +Scene.STRATA = { + "WORLD", "BACKGROUND", "LOW", "MEDIUM", "HIGH", "DIALOG", "FULLSCREEN", "FULLSCREEN_DIALOG", "TOOLTIP", +} + +Scene.LAYERS = { "BACKGROUND", "BORDER", "ARTWORK", "OVERLAY", "HIGHLIGHT" } + +local function Index(list) + local index = {} + for position, value in ipairs(list) do index[value] = position end + return index +end +Scene.STRATA_INDEX = Index(Scene.STRATA) +Scene.LAYER_INDEX = Index(Scene.LAYERS) + +function Scene.Validate(adapter) + if type(adapter) ~= "table" then error("wowproof: the adapter must be a table of functions", 2) end + local missing = {} + for _, name in ipairs(Scene.REQUIRED) do + if type(adapter[name]) ~= "function" then missing[#missing + 1] = name end + end + if #missing > 0 then + error("wowproof: the adapter is missing " .. table.concat(missing, ", "), 2) + end + return adapter +end + +function Scene.IsRegion(adapter, region) + return Scene.REGION_TYPES[adapter.Type(region)] == true +end + +return Scene diff --git a/wowproof/sheet.lua b/wowproof/sheet.lua new file mode 100644 index 0000000..bc170ca --- /dev/null +++ b/wowproof/sheet.lua @@ -0,0 +1,55 @@ +local Paint = require("wowproof.paint") + +local Sheet = {} + +local PAGE = [[ + + + +%s + + + +

%s

+

%s

+
+%s +
+ + +]] + +local function BaseName(path) + return path and path:match("([^/]+)$") +end + +function Sheet.Render(title, entries) + local figures, failed = {}, 0 + for _, entry in ipairs(entries) do + if entry.error then + failed = failed + 1 + figures[#figures + 1] = string.format('
%s
%s
', + Paint.Escape(entry.name), Paint.Escape(entry.error)) + else + local image = BaseName(entry.png) or BaseName(entry.svg) + figures[#figures + 1] = string.format( + '
%s
%ssvg
', + Paint.Escape(image), Paint.Escape(entry.name), Paint.Escape(entry.name), Paint.Escape(BaseName(entry.svg))) + end + end + local summary = string.format("%d snapshots, %d failed", #entries - failed, failed) + return string.format(PAGE, Paint.Escape(title), Paint.Escape(title), summary, table.concat(figures, "\n")) +end + +return Sheet diff --git a/wowproof/sources/wow_ui_textures.lua b/wowproof/sources/wow_ui_textures.lua new file mode 100644 index 0000000..df23ff0 --- /dev/null +++ b/wowproof/sources/wow_ui_textures.lua @@ -0,0 +1,133 @@ +local Raster = require("wowproof.raster") + +local DEFAULT_REPOSITORY = "Gethe/wow-ui-textures" + +local function UrlEncode(text) + return (text:gsub("[^%w%-_%.~/]", function(char) return string.format("%%%02X", char:byte()) end)) +end + +local function DirName(path) + return path:match("^(.*)/[^/]+$") or "." +end + +local function NonEmpty(file) + local handle = io.open(file, "rb") + if not handle then return false end + local size = handle:seek("end") + handle:close() + return size > 0 +end + +return function(options) + options = options or {} + local repository = options.repository or DEFAULT_REPOSITORY + local ref = options.ref or error("wowproof: pin the art source to a commit (ref)", 2) + local dir = options.dir or ".proof-art" + local fetch = options.fetch ~= false + local token = options.token + local treesDir = dir .. "/trees" + local filesDir = dir .. "/" .. ref + local missingFile = dir .. "/missing-" .. ref .. ".txt" + local trees, missing = {}, nil + + local function Download(url, target, api) + Raster.MakeDir(DirName(target)) + local partial = target .. ".part" + local headers = { "User-Agent: wowproof" } + if api then headers[#headers + 1] = "Accept: application/vnd.github+json" end + if api and token and token ~= "" then headers[#headers + 1] = "Authorization: Bearer " .. token end + local curl = io.popen("curl -fsSL --retry 2 --max-time 60 -H @- -o " .. Raster.Quote(partial) .. " " + .. Raster.Quote(url) .. " 2>/dev/null", "w") + curl:write(table.concat(headers, "\n"), "\n") + curl:close() + if not NonEmpty(partial) then + os.remove(partial) + return false + end + os.rename(partial, target) + return true + end + + local function Tree(sha) + if trees[sha] then return trees[sha] end + local file = treesDir .. "/" .. sha .. ".tsv" + if not Raster.Exists(file) then + if not fetch or not Raster.Has("curl") or not Raster.Has("jq") then return nil end + local json = file .. ".json" + if not Download(string.format("https://api.github.com/repos/%s/git/trees/%s", repository, sha), json, true) then + return nil + end + local ok = Raster.Run("jq -r '.tree[] | [.type, .sha, .path] | @tsv' " .. Raster.Quote(json) .. " > " + .. Raster.Quote(file .. ".part")) + os.remove(json) + if not ok then + os.remove(file .. ".part") + return nil + end + os.rename(file .. ".part", file) + end + local entries = {} + for line in io.lines(file) do + local kind, entrySha, name = line:match("^(%S+)\t(%S+)\t(.+)$") + if kind then entries[name:upper()] = { kind = kind, sha = entrySha, name = name } end + end + trees[sha] = entries + return entries + end + + local function Missing() + if missing then return missing end + missing = {} + if Raster.Exists(missingFile) then + for line in io.lines(missingFile) do missing[line] = true end + end + return missing + end + + local function MarkMissing(key) + Missing()[key] = true + Raster.MakeDir(dir) + local handle = io.open(missingFile, "a") + if handle then + handle:write(key, "\n") + handle:close() + end + end + + local function Locate(key) + local entries = Tree(ref) + if not entries then return nil, true end + local parts = {} + for part in key:gmatch("[^\\]+") do parts[#parts + 1] = part end + local names = {} + for index, part in ipairs(parts) do + local last = index == #parts + local entry = last and entries[part .. ".PNG"] or entries[part] + if not entry or entry.kind ~= (last and "blob" or "tree") then return nil, false end + names[#names + 1] = entry.name + if not last then + entries = Tree(entry.sha) + if not entries then return nil, true end + end + end + return table.concat(names, "/"), false + end + + return function(path) + if type(path) ~= "string" then return nil end + local relative = path:gsub("/", "\\"):match("^[Ii][Nn][Tt][Ee][Rr][Ff][Aa][Cc][Ee]\\(.+)$") + if not relative then return nil end + local key = relative:gsub("%.[BbTt][LlGg][PpAa]$", ""):upper() + local cached = filesDir .. "/" .. key:gsub("\\", "/") .. ".png" + if Raster.Exists(cached) then return cached end + if not fetch or Missing()[key] then return nil end + local remote, transient = Locate(key) + if not remote then + if not transient then MarkMissing(key) end + return nil + end + local url = string.format("https://raw.githubusercontent.com/%s/%s/%s", repository, ref, UrlEncode(remote)) + if not Download(url, cached) then return nil end + return cached + end +end diff --git a/wowproof/spec/fake_scene.lua b/wowproof/spec/fake_scene.lua new file mode 100644 index 0000000..5ba7b05 --- /dev/null +++ b/wowproof/spec/fake_scene.lua @@ -0,0 +1,40 @@ +local FakeScene = {} + +function FakeScene.New() + local scene = { nodes = {} } + + function scene.Node(kind, parent, fields) + local node = fields or {} + node.kind, node.parent, node.children = kind, parent, {} + node.points = node.points or {} + node.order = #scene.nodes + 1 + scene.nodes[#scene.nodes + 1] = node + if parent then parent.children[#parent.children + 1] = node end + return node + end + + scene.adapter = { + Parent = function(node) return node.parent end, + Children = function(node) return node.children end, + Order = function(node) return node.order end, + Type = function(node) return node.kind end, + Name = function(node) return node.name end, + Points = function(node) return node.points end, + Size = function(node) return node.width or 0, node.height or 0 end, + Scale = function(node) return node.scale or 1 end, + Shown = function(node) return node.shown ~= false end, + Alpha = function(node) return node.alpha or 1 end, + IgnoresParentAlpha = function(node) return node.ignoreParentAlpha == true end, + Strata = function(node) return node.strata end, + Level = function(node) return node.level or 0 end, + Layer = function(node) return node.layer, node.sublevel end, + Texture = function(node) return node.texture end, + Bar = function(node) return node.bar end, + Text = function(node) return node.text end, + } + + scene.screen = scene.Node("Frame", nil, { name = "Screen" }) + return scene +end + +return FakeScene diff --git a/wowproof/spec/layout_spec.lua b/wowproof/spec/layout_spec.lua new file mode 100644 index 0000000..a2d8369 --- /dev/null +++ b/wowproof/spec/layout_spec.lua @@ -0,0 +1,94 @@ +local Layout = require("wowproof.layout") +local FakeScene = require("wowproof.spec.fake_scene") + +describe("wowproof layout", function() + local scene, layout + + before_each(function() + scene = FakeScene.New() + layout = Layout.New(scene.adapter, { width = 1000, height = 500 }) + end) + + local function Rect(node) + local rect = layout:Rect(node) + return { rect.left, rect.top, rect.width, rect.height } + end + + it("fills the screen with a parentless region without points", function() + assert.same({ 0, 0, 1000, 500 }, Rect(scene.screen)) + end) + + it("places a single point with its size, y offsets going up", function() + local frame = scene.Node("Frame", scene.screen, { + width = 200, height = 40, + points = { { point = "TOPLEFT", relativePoint = "TOPLEFT", x = 10, y = -20 } }, + }) + assert.same({ 10, 20, 200, 40 }, Rect(frame)) + end) + + it("centers on the relative region's anchor", function() + local frame = scene.Node("Frame", scene.screen, { + width = 100, height = 50, points = { { point = "CENTER", x = 0, y = 50 } }, + }) + assert.same({ 450, 175, 100, 50 }, Rect(frame)) + end) + + it("stretches an axis between two points", function() + local frame = scene.Node("Frame", scene.screen, { + width = 300, height = 60, points = { { point = "CENTER" } }, + }) + local bar = scene.Node("StatusBar", frame, { + height = 20, + points = { + { point = "TOPLEFT", x = 5, y = -5 }, + { point = "TOPRIGHT", x = -5, y = -5 }, + }, + }) + assert.same({ 355, 225, 290, 20 }, Rect(bar)) + end) + + it("copies the relative rect for SetAllPoints", function() + local frame = scene.Node("Frame", scene.screen, { width = 80, height = 30, points = { { point = "TOPLEFT" } } }) + local texture = scene.Node("Texture", frame, { points = { { all = true } } }) + assert.same({ 0, 0, 80, 30 }, Rect(texture)) + end) + + it("anchors to another region than the parent", function() + local a = scene.Node("Frame", scene.screen, { width = 100, height = 20, points = { { point = "TOPLEFT" } } }) + local b = scene.Node("Frame", scene.screen, { + width = 50, height = 20, + points = { { point = "TOPLEFT", relativeTo = a, relativePoint = "BOTTOMLEFT", x = 0, y = -4 } }, + }) + assert.same({ 0, 24, 50, 20 }, Rect(b)) + end) + + it("applies the effective scale to size and offsets", function() + local frame = scene.Node("Frame", scene.screen, { + scale = 2, width = 100, height = 10, points = { { point = "TOPLEFT", x = 10, y = -10 } }, + }) + local child = scene.Node("Frame", frame, { width = 10, height = 10, points = { { point = "TOPLEFT", x = 5 } } }) + assert.same({ 20, 20, 200, 20 }, Rect(frame)) + assert.same({ 30, 20, 20, 20 }, Rect(child)) + end) + + it("leaves a parented region without points unresolved, and survives cycles", function() + local loose = scene.Node("Frame", scene.screen, { width = 10, height = 10 }) + assert.is_nil(layout:Rect(loose)) + local a = scene.Node("Frame", scene.screen, { width = 10, height = 10 }) + local b = scene.Node("Frame", scene.screen, { width = 10, height = 10, points = { { point = "LEFT", relativeTo = a } } }) + a.points = { { point = "LEFT", relativeTo = b } } + assert.is_nil(layout:Rect(a)) + end) + + it("sizes a font string from its text when it has no size", function() + local text = scene.Node("FontString", scene.screen, { + points = { { point = "TOPLEFT" } }, text = { text = "abcd", size = 10 }, + }) + assert.same({ 0, 0, 22, 10 }, Rect(text)) + end) + + it("rejects unknown anchor points", function() + local frame = scene.Node("Frame", scene.screen, { width = 1, height = 1, points = { { point = "MIDDLE" } } }) + assert.has_error(function() layout:Rect(frame) end) + end) +end) diff --git a/wowproof/spec/package_spec.lua b/wowproof/spec/package_spec.lua new file mode 100644 index 0000000..b01c3d7 --- /dev/null +++ b/wowproof/spec/package_spec.lua @@ -0,0 +1,84 @@ +local Proof = require("wowproof") +local Raster = require("wowproof.raster") +local MockState = require("wowproof.adapters.mock_state") +local FakeScene = require("wowproof.spec.fake_scene") + +local FORBIDDEN = { "Unit" .. "Frames", "%f[%w_]ns" .. "%.", "tests" .. "/" } + +local function PackageFiles() + local files = {} + local handle = io.popen("find wowproof -type f") + for file in handle:lines() do files[#files + 1] = file end + handle:close() + return files +end + +describe("wowproof package", function() + it("knows nothing about the addon that uses it", function() + for _, file in ipairs(PackageFiles()) do + local content = Raster.Read(file) + for _, pattern in ipairs(FORBIDDEN) do + assert.is_nil(content:find(pattern), file .. " mentions " .. pattern) + end + end + end) + + it("base64-encodes like the standard alphabet", function() + assert.equals("", Raster.Base64("")) + assert.equals("TQ==", Raster.Base64("M")) + assert.equals("TWE=", Raster.Base64("Ma")) + assert.equals("TWFu", Raster.Base64("Man")) + end) + + it("writes snapshots and a contact sheet", function() + local dir = io.popen("mktemp -d"):read("*l") + local scene = FakeScene.New() + local frame = scene.Node("Frame", scene.screen, { width = 20, height = 10, points = { { point = "CENTER" } } }) + scene.Node("Texture", frame, { points = { { all = true } }, texture = { color = { 1, 1, 1, 1 } } }) + local proof = Proof.New({ adapter = scene.adapter, outDir = dir, png = false, title = "Fake" }) + local entry = proof:Snapshot(frame, "white box") + proof:Fail("broken", "boom ") + local sheet = Raster.Read(proof:Sheet()) + assert.equals(dir .. "/white-box.svg", entry.svg) + assert.is_true(Raster.Exists(entry.svg)) + assert.is_not_nil(sheet:find("1 snapshots, 1 failed", 1, true)) + assert.is_not_nil(sheet:find("boom <here>", 1, true)) + os.execute("rm -rf " .. Raster.Quote(dir)) + end) + + it("reads the __state widget model through the mock_state adapter", function() + local secret = {} + local function Secret(value) return setmetatable({ value = value }, secret) end + local function Object(kind, parent, state) + state.parent, state.kids, state.points = parent, {}, state.points or {} + local object = { __type = kind, __state = state, __calls = {} } + if parent then parent.__state.kids[object] = true end + return object + end + local root = Object("Frame", nil, {}) + local bar = Object("StatusBar", root, { min = 0, max = Secret(10), value = Secret(4), shown = true }) + bar.__state.fill = Object("Texture", bar, { vertexColor = { 1, 0, 0, 1 } }) + local text = Object("FontString", bar, { text = Secret("40%"), fontObject = "Font" }) + text.__calls[1] = { "SetJustifyH", "RIGHT" } + local font = Object("Font", nil, { font = { "F.ttf", 11, "OUTLINE" } }) + local registry = { root, bar, bar.__state.fill, text, font } + local adapter = MockState({ + isSecret = function(value) return getmetatable(value) == secret end, + reveal = function(value) return value.value end, + objects = function() return registry end, + globals = { Font = font }, + }) + bar.__calls[1] = { "SetClipsChildren", true } + assert.same({ bar.__state.fill, text }, adapter.Children(bar)) + assert.equals(bar, adapter.FillOf(bar.__state.fill)) + assert.is_nil(adapter.FillOf(text)) + assert.is_true(adapter.ClipsChildren(bar)) + assert.is_false(adapter.ClipsChildren(root)) + assert.same({ min = 0, max = 10, value = 4, reverse = false, color = { 1, 0, 0, 1 } }, adapter.Bar(bar)) + local info = adapter.Text(text) + assert.equals("40%", info.text) + assert.equals(11, info.size) + assert.equals("RIGHT", info.justifyH) + assert.equals(4, adapter.Order(text)) + end) +end) diff --git a/wowproof/spec/paint_spec.lua b/wowproof/spec/paint_spec.lua new file mode 100644 index 0000000..d15ef97 --- /dev/null +++ b/wowproof/spec/paint_spec.lua @@ -0,0 +1,199 @@ +local Layout = require("wowproof.layout") +local Paint = require("wowproof.paint") +local Scene = require("wowproof.scene") +local FakeScene = require("wowproof.spec.fake_scene") + +describe("wowproof paint", function() + local scene, frame + + before_each(function() + scene = FakeScene.New() + frame = scene.Node("Frame", scene.screen, { + name = "Frame", width = 100, height = 20, points = { { point = "TOPLEFT", x = 10, y = -10 } }, + }) + end) + + local function Render(root, options) + options = options or {} + options.adapter, options.root = scene.adapter, root or frame + options.layout = Layout.New(scene.adapter, { width = 400, height = 300 }) + options.pad = options.pad or 0 + return Paint.Render(options) + end + + local function Has(svg, text) + return svg:find(text, 1, true) ~= nil + end + + local function Before(svg, first, second) + return svg:find(first, 1, true) < svg:find(second, 1, true) + end + + it("validates adapters", function() + assert.has_error(function() Scene.Validate({ Parent = function() end }) end) + assert.equals(scene.adapter, Scene.Validate(scene.adapter)) + end) + + it("crops to the region and draws colour textures", function() + scene.Node("Texture", frame, { points = { { all = true } }, texture = { color = { 1, 0, 0, 0.5 } } }) + local svg, info = Render() + assert.equals(100, info.width) + assert.equals(20, info.height) + assert.is_true(Has(svg, 'viewBox="10 10 100 20"')) + assert.is_true(Has(svg, '')) + end) + + it("fills status bars from their value, honouring reverse and vertical fill", function() + local bar = scene.Node("StatusBar", frame, { + points = { { all = true } }, bar = { min = 0, max = 200, value = 50, color = { 0, 1, 0, 1 } }, + }) + assert.is_true(Has(Render(), 'x="10" y="10" width="25" height="20" fill="rgb(0,255,0)"')) + bar.bar.reverse = true + assert.is_true(Has(Render(), 'x="85" y="10" width="25" height="20"')) + bar.bar.reverse, bar.bar.orientation = false, "VERTICAL" + assert.is_true(Has(Render(), 'x="10" y="25" width="100" height="5"')) + end) + + it("paints by strata, level, layer, sublevel, then creation order", function() + local over = scene.Node("Texture", frame, { points = { { all = true } }, layer = "OVERLAY", texture = { color = { 0, 0, 1, 1 } } }) + local back = scene.Node("Texture", frame, { points = { { all = true } }, layer = "BACKGROUND", texture = { color = { 1, 0, 0, 1 } } }) + local child = scene.Node("Frame", frame, { points = { { all = true } }, level = 5 }) + scene.Node("Texture", child, { points = { { all = true } }, layer = "BACKGROUND", texture = { color = { 0, 1, 0, 1 } } }) + local svg = Render() + assert.is_true(Before(svg, "rgb(255,0,0)", "rgb(0,0,255)")) + assert.is_true(Before(svg, "rgb(0,0,255)", "rgb(0,255,0)")) + child.strata, frame.strata = "LOW", "HIGH" + svg = Render() + assert.is_true(Before(svg, "rgb(0,255,0)", "rgb(255,0,0)")) + assert.is_not_nil(over) + assert.is_not_nil(back) + end) + + it("skips hidden and transparent regions and multiplies alpha down the tree", function() + local child = scene.Node("Frame", frame, { points = { { all = true } }, alpha = 0.5 }) + scene.Node("Texture", child, { points = { { all = true } }, texture = { color = { 1, 1, 1, 1 } }, alpha = 0.5 }) + scene.Node("Texture", frame, { points = { { all = true } }, texture = { color = { 1, 0, 0, 1 } }, shown = false }) + scene.Node("Texture", frame, { points = { { all = true } }, texture = { color = { 0, 0, 1, 1 } }, alpha = 0 }) + local svg = Render() + assert.is_true(Has(svg, 'fill="rgb(255,255,255)" fill-opacity="0.25"')) + assert.is_false(Has(svg, "rgb(255,0,0)")) + assert.is_false(Has(svg, "rgb(0,0,255)")) + end) + + it("refuses hidden or unplaced roots", function() + frame.shown = false + assert.has_error(function() Render() end) + local loose = scene.Node("Frame", scene.screen, { width = 1, height = 1 }) + assert.has_error(function() Render(loose) end) + end) + + it("draws text with justification, outline, colour codes and the font resolver", function() + scene.Node("FontString", frame, { + points = { { all = true } }, + text = { text = "HP |cffff0000low|r ", size = 10, font = "Fonts\\X.ttf", flags = "OUTLINE", justifyH = "LEFT" }, + }) + local svg = Render(nil, { font = function(file) if file == "Fonts\\X.ttf" then return "Roboto", 700 end end }) + assert.is_true(Has(svg, 'x="10" y="20" font-family="Roboto" font-weight="700" font-size="10" text-anchor="start"')) + assert.is_true(Has(svg, 'stroke="#000" stroke-width="1.2"')) + assert.is_true(Has(svg, 'low')) + assert.is_true(Has(svg, "<ok>")) + end) + + local function Image(file) + if file == "Own\\Glow.tga" then return "data:image/png;base64,AA", 32, 32 end + end + + it("embeds resolved images once, tints them, and marks unresolved files as placeholders", function() + scene.Node("Texture", frame, { points = { { all = true } }, texture = { file = "Own\\Glow.tga", vertexColor = { 1, 0.5, 0, 1 } } }) + scene.Node("Texture", frame, { points = { { all = true } }, texture = { file = "Own\\Glow.tga" } }) + scene.Node("Texture", frame, { points = { { all = true } }, texture = { file = "Interface\\Missing" } }) + local svg = Render(nil, { image = Image }) + local _, images = svg:gsub("base64,AA", "") + assert.equals(1, images) + assert.is_true(Has(svg, '')) + assert.is_true(Has(svg, 'values="1 0 0 0 0 0 0.5 0 0 0 0 0 0 0 0 0 0 0 1 0"')) + assert.is_true(Has(svg, '')) + assert.is_true(Has(svg, "Interface\\Missing")) + end) + + it("crops images to their texture coordinates", function() + scene.Node("Texture", frame, { + points = { { all = true } }, texture = { file = "Own\\Glow.tga", texCoords = { 0.25, 0.5, 0, 0.25 } }, + }) + assert.is_true(Has(Render(nil, { image = Image }), 'viewBox="8 0 8 8"')) + assert.same({ left = 0, top = 8, width = 32, height = 8 }, + Paint.SourceRect({ 0, 0.25, 0, 0.5, 1, 0.25, 1, 0.5 }, 32, 32)) + assert.same({ left = 0, top = 0, width = 32, height = 16 }, Paint.SourceRect(nil, 32, 16)) + end) + + it("maps rotated and tiled texture coordinates through a pattern transform", function() + local coords = { 0, 2, 1, 2, 0, 0, 1, 0 } + assert.is_true(Paint.NeedsAffine(coords)) + assert.is_false(Paint.NeedsAffine({ 0.1, 0.9, 0.1, 0.9 })) + assert.is_true(Paint.NeedsAffine({ 1, 0, 0, 1 })) + scene.Node("Texture", frame, { points = { { all = true } }, texture = { file = "Own\\Glow.tga", texCoords = coords } }) + local svg = Render(nil, { image = Image }) + assert.is_true(Has(svg, 'patternTransform="matrix(0 0.625 -1.5625 0 110 10)"')) + assert.is_true(Has(svg, '')) + end) + + it("skips texture coordinates that collapse the image", function() + assert.is_nil(Paint.AffineTransform({ left = 0, top = 0, width = 10, height = 10 }, { 0, 0, 0, 0, 0, 0, 0, 0 }, 16, 16)) + assert.is_nil(Paint.AffineTransform({ left = 0, top = 0, width = 200, height = 10 }, { 0, 0, 0, 0.0001, 1, 0, 1, 0.0001 }, 16, 16)) + end) + + it("paints Blizzard's white texture as a tinted solid", function() + scene.Node("Texture", frame, { + points = { { all = true } }, texture = { file = "Interface\\Buttons\\WHITE8X8", vertexColor = { 0, 0, 1, 0.5 } }, + }) + assert.is_true(Has(Render(), 'fill="rgb(0,0,255)" fill-opacity="0.5"')) + end) + + it("draws nine-slice textures with fixed corners", function() + scene.Node("Texture", frame, { points = { { all = true } }, texture = { file = "Own\\Glow.tga", slice = { 8, 8, 8, 8 } } }) + local svg = Render(nil, { image = Image }) + local _, pieces = svg:gsub('', "") + assert.equals(9, pieces) + assert.is_true(Has(svg, '')) + assert.is_true(Has(svg, '\n