/*
 * EasyPixelMap.jsx
 * Dockable After Effects ScriptUI Panel
 *
 * Generates a pixel-exact animated colour test grid / pixel map for any X x Y
 * resolution, with X and Y axis 100px (or custom step) rulers, checkerboard
 * modulation, major/minor gridlines, and a seamless 30-second hue loop.
 *
 * Install in:
 *   macOS:   /Applications/Adobe After Effects <version>/Scripts/ScriptUI Panels/
 *   Windows: C:\Program Files\Adobe\Adobe After Effects <version>\Support Files\Scripts\ScriptUI Panels\
 *
 * Open in After Effects:
 *   Window > EasyPixelMap.jsx
 */

(function (thisObj) {

    var SCRIPT_NAME = "EasyPixelMap";
    var FONT_NAME = "HelveticaNeue-CondensedBold";
    var ASSETS_FOLDER_NAME = "EasyPixelMap Assets";

    // ---------- Colour Helpers ----------

    function hsvToRgb(h, s, v) {
        h = ((h % 360) + 360) % 360;
        var c = v * s;
        var x = c * (1 - Math.abs(((h / 60) % 2) - 1));
        var m = v - c;
        var r = 0, g = 0, b = 0;
        if (h < 60) {
            r = c; g = x; b = 0;
        } else if (h < 120) {
            r = x; g = c; b = 0;
        } else if (h < 180) {
            r = 0; g = c; b = x;
        } else if (h < 240) {
            r = 0; g = x; b = c;
        } else if (h < 300) {
            r = x; g = 0; b = c;
        } else {
            r = c; g = 0; b = x;
        }
        return [r + m, g + m, b + m];
    }

    // ---------- AE Helpers ----------

    function getOrCreateFolder(name) {
        var proj = app.project;
        for (var i = 1; i <= proj.numItems; i++) {
            var item = proj.item(i);
            if (item instanceof FolderItem && item.name === name) {
                return item;
            }
        }
        return proj.items.addFolder(name);
    }

    function addRectToShapeLayer(shapeLayer, name, cx, cy, w, h, fillRGB, fillOpacity, roundness, strokeRGB, strokeWidth, strokeOpacity) {
        var contents = shapeLayer.property("ADBE Root Vectors Group");
        var grp = contents.addProperty("ADBE Vector Group");
        grp.name = name;
        var vecs = grp.property("ADBE Vectors Group");
        var rect = vecs.addProperty("ADBE Vector Shape - Rect");
        rect.property("ADBE Vector Rect Size").setValue([w, h]);
        rect.property("ADBE Vector Rect Position").setValue([cx, cy]);
        if (roundness && roundness > 0) {
            rect.property("ADBE Vector Rect Roundness").setValue(roundness);
        }
        if (fillRGB) {
            var fill = vecs.addProperty("ADBE Vector Graphic - Fill");
            fill.property("ADBE Vector Fill Color").setValue([fillRGB[0], fillRGB[1], fillRGB[2], 1]);
            if (fillOpacity !== undefined && fillOpacity !== null) {
                fill.property("ADBE Vector Fill Opacity").setValue(fillOpacity);
            }
        }
        if (strokeRGB && strokeWidth > 0) {
            var stroke = vecs.addProperty("ADBE Vector Graphic - Stroke");
            stroke.property("ADBE Vector Stroke Color").setValue([strokeRGB[0], strokeRGB[1], strokeRGB[2], 1]);
            stroke.property("ADBE Vector Stroke Width").setValue(strokeWidth);
            if (strokeOpacity !== undefined && strokeOpacity !== null) {
                stroke.property("ADBE Vector Stroke Opacity").setValue(strokeOpacity);
            }
        }
    }

    function addLineToShapeLayer(shapeLayer, name, p1, p2, strokeRGB, strokeWidth, strokeOpacity) {
        var contents = shapeLayer.property("ADBE Root Vectors Group");
        var grp = contents.addProperty("ADBE Vector Group");
        grp.name = name;
        var vecs = grp.property("ADBE Vectors Group");
        var pathProp = vecs.addProperty("ADBE Vector Shape - Group");
        var s = new Shape();
        s.vertices = [p1, p2];
        s.closed = false;
        pathProp.property("ADBE Vector Shape").setValue(s);
        var stroke = vecs.addProperty("ADBE Vector Graphic - Stroke");
        stroke.property("ADBE Vector Stroke Color").setValue([strokeRGB[0], strokeRGB[1], strokeRGB[2], 1]);
        stroke.property("ADBE Vector Stroke Width").setValue(strokeWidth);
        if (strokeOpacity !== undefined && strokeOpacity !== null) {
            stroke.property("ADBE Vector Stroke Opacity").setValue(strokeOpacity);
        }
    }

    function addTextLayer(comp, name, textStr, x, y, fontSize, rgb, justification, tracking) {
        var layer = comp.layers.addText(textStr);
        layer.name = name;
        var textProp = layer.property("ADBE Text Properties").property("ADBE Text Document");
        var td = textProp.value;
        td.text = textStr;
        try { td.font = FONT_NAME; } catch (e) {}
        td.fontSize = fontSize;
        td.fillColor = rgb;
        td.applyFill = true;
        td.applyStroke = false;
        td.justification = justification;
        if (tracking !== undefined && tracking !== null) {
            td.tracking = tracking;
        }
        textProp.setValue(td);

        var rect = layer.sourceRectAtTime(0, false);
        var ax;
        if (justification === ParagraphJustification.LEFT_JUSTIFY) {
            ax = rect.left;
        } else if (justification === ParagraphJustification.RIGHT_JUSTIFY) {
            ax = rect.left + rect.width;
        } else {
            ax = rect.left + rect.width / 2;
        }
        var ay = rect.top + rect.height / 2;
        var xf = layer.property("ADBE Transform Group");
        xf.property("ADBE Anchor Point").setValue([ax, ay]);
        xf.property("ADBE Position").setValue([x, y]);
        return layer;
    }

    function pad4(n) {
        var s = String(n);
        while (s.length < 4) { s = "0" + s; }
        return s;
    }

    // ---------- Core Pixel Map Generator ----------

    function buildEasyPixelMap(opts) {
        if (!app.project) {
            app.newProject();
        }

        var W = Math.max(200, Math.round(Number(opts.width) || 3840));
        var H = Math.max(200, Math.round(Number(opts.height) || 2160));
        var step = Math.max(20, Math.round(Number(opts.step) || 100));
        var fps = Math.max(1, Number(opts.fps) || 60);
        var dur = Math.max(1, Number(opts.duration) || 30);
        var cycles = Math.max(1, Math.round(Number(opts.cycles) || 5));
        var animateHue = (opts.animateHue !== undefined) ? !!opts.animateHue : true;
        var showChecker = (opts.showChecker !== undefined) ? !!opts.showChecker : true;
        var showXRulers = (opts.showXRulers !== undefined) ? !!opts.showXRulers : true;
        var showYRulers = (opts.showYRulers !== undefined) ? !!opts.showYRulers : true;
        var showYCenter = (opts.showYCenter !== undefined) ? !!opts.showYCenter : false;
        var showBadge = (opts.showBadge !== undefined) ? !!opts.showBadge : true;

        var compName = (opts.name && opts.name.replace(/^\s+|\s+$/g, "") !== "")
            ? opts.name.replace(/^\s+|\s+$/g, "")
            : ("EasyPixelMap " + W + "x" + H + " (" + dur + "s)");

        var xRulerH = 68;
        var yRulerW = 84;
        var major5 = step * 5;
        var major10 = step * 10;

        // Calculate X ruler Y-bands so Y rulers cleanly skip colliding labels
        var hasMidX = showXRulers && (H >= step * 6);
        var midRowY = Math.floor((H / 2) / step) * step;
        var midXCenterY = midRowY + step / 2;
        if (midXCenterY + xRulerH / 2 > H - xRulerH - 20) {
            midXCenterY = H / 2;
        }
        var xBands = [];
        if (showXRulers) {
            xBands.push([0, xRulerH]);
            if (hasMidX) {
                xBands.push([midXCenterY - xRulerH / 2, midXCenterY + xRulerH / 2]);
            }
            xBands.push([H - xRulerH, H]);
        }

        function yCollidesWithXRuler(yVal) {
            for (var b = 0; b < xBands.length; b++) {
                if (yVal + 14 > xBands[b][0] && yVal - 14 < xBands[b][1]) {
                    return true;
                }
            }
            return false;
        }

        app.beginUndoGroup("Build " + compName);
        try {
            var assetsFolder = getOrCreateFolder(ASSETS_FOLDER_NAME);
            var comp = app.project.items.addComp(compName, W, H, 1.0, dur, fps);
            comp.bgColor = [0, 0, 0];

            // 1. Colour Columns
            var colLayer = comp.layers.addShape();
            colLayer.name = "Colour Columns (" + step + "px)";
            colLayer.property("ADBE Transform Group").property("ADBE Position").setValue([0, 0]);

            var numCols = Math.ceil(W / step);
            for (var c = 0; c < numCols; c++) {
                var x0 = c * step;
                var cw = Math.min(step, W - x0);
                var hue = (c * 360) / numCols;
                var rgb = hsvToRgb(hue, 0.78, 0.72);
                var colLabel = "Col " + pad4(x0) + (cw < step ? (" (" + cw + "px)") : "");
                addRectToShapeLayer(colLayer, colLabel, x0 + cw / 2, H / 2, cw, H, rgb, 100);
            }

            if (animateHue) {
                var hls = colLayer.property("ADBE Effect Parade").addProperty("ADBE Color Balance (HLS)");
                hls.name = "Animated Hue Cycle";
                var hueProp = hls.property("ADBE Color Balance (HLS)-0001");
                hueProp.setValueAtTime(0, 0);
                hueProp.setValueAtTime(dur, -360 * cycles);
                hueProp.setInterpolationTypeAtKey(1, KeyframeInterpolationType.LINEAR, KeyframeInterpolationType.LINEAR);
                hueProp.setInterpolationTypeAtKey(2, KeyframeInterpolationType.LINEAR, KeyframeInterpolationType.LINEAR);
            }

            // 2. Checkerboard Overlay
            if (showChecker) {
                var checkerLayer = comp.layers.addSolid(
                    [0, 0, 0],
                    step + "px Checkerboard (" + W + "x" + H + ")",
                    W, H, 1.0, dur
                );
                checkerLayer.property("ADBE Transform Group").property("ADBE Position").setValue([W / 2, H / 2]);
                var chk = checkerLayer.property("ADBE Effect Parade").addProperty("ADBE Checkerboard");
                chk.name = "Checkerboard " + step + "px";
                chk.property("ADBE Checkerboard-0001").setValue([0, 0]);
                chk.property("ADBE Checkerboard-0002").setValue(2); // Width Slider
                chk.property("ADBE Checkerboard-0004").setValue(step);
                chk.property("ADBE Checkerboard-0010").setValue([1, 1, 1, 1]);
                chk.property("ADBE Checkerboard-0011").setValue(100);
                checkerLayer.blendingMode = BlendingMode.SOFT_LIGHT;
                checkerLayer.property("ADBE Transform Group").property("ADBE Opacity").setValue(28);
            }

            // 3. Horizontal Gridlines
            var hGrid = comp.layers.addShape();
            hGrid.name = "Horizontal Gridlines (" + step + "px)";
            hGrid.property("ADBE Transform Group").property("ADBE Position").setValue([0, 0]);
            for (var y = 0; y <= H; y += step) {
                var isEdgeY = (y === 0 || y === H);
                var isMajor10Y = (y > 0 && y < H && y % major10 === 0);
                var isMajor5Y = (y > 0 && y < H && y % major5 === 0);
                var strokeY = isMajor10Y ? [1, 0.9, 0.1] : [1, 1, 1];
                var widthY = isEdgeY ? 4 : (isMajor10Y ? 5 : (isMajor5Y ? 3.5 : 2));
                var opY = isEdgeY ? 100 : (isMajor10Y ? 95 : (isMajor5Y ? 80 : 55));
                addLineToShapeLayer(hGrid, "Y " + pad4(y), [0, y], [W, y], strokeY, widthY, opY);
            }
            if (H % step !== 0) {
                addLineToShapeLayer(hGrid, "Y " + pad4(H), [0, H], [W, H], [1, 1, 1], 4, 100);
            }

            // 4. Vertical Gridlines
            var vGrid = comp.layers.addShape();
            vGrid.name = "Vertical Gridlines (" + step + "px)";
            vGrid.property("ADBE Transform Group").property("ADBE Position").setValue([0, 0]);
            for (var x = 0; x <= W; x += step) {
                var isEdgeX = (x === 0 || x === W);
                var isMajor10X = (x > 0 && x < W && x % major10 === 0);
                var isMajor5X = (x > 0 && x < W && x % major5 === 0);
                var strokeX = isMajor10X ? [1, 0.9, 0.1] : [1, 1, 1];
                var widthX = isEdgeX ? 4 : (isMajor10X ? 6 : (isMajor5X ? 4 : 2));
                var opX = isEdgeX ? 100 : (isMajor10X ? 100 : (isMajor5X ? 95 : 75));
                addLineToShapeLayer(vGrid, "X " + pad4(x), [x, 0], [x, H], strokeX, widthX, opX);
            }
            if (W % step !== 0) {
                addLineToShapeLayer(vGrid, "X " + pad4(W), [W, 0], [W, H], [1, 1, 1], 4, 100);
            }

            // 5. Y-Axis Ruler Strip Precomp (placed behind X-Axis Rulers)
            if (showYRulers) {
                var yComp = app.project.items.addComp(
                    "Y Ruler Strip " + H + " (" + step + "px)",
                    yRulerW, H, 1.0, dur, fps
                );
                yComp.bgColor = [0, 0, 0];
                yComp.parentFolder = assetsFolder;

                var yBg = yComp.layers.addShape();
                yBg.name = "Ruler Background";
                yBg.property("ADBE Transform Group").property("ADBE Position").setValue([0, 0]);
                addRectToShapeLayer(yBg, "Bar", yRulerW / 2, H / 2, yRulerW, H, [0.04, 0.04, 0.05], 86);
                addLineToShapeLayer(yBg, "Left Border", [1, 0], [1, H], [1, 1, 1], 2, 70);
                addLineToShapeLayer(yBg, "Right Border", [yRulerW - 1, 0], [yRulerW - 1, H], [1, 1, 1], 2, 70);

                var yTicks = yComp.layers.addShape();
                yTicks.name = "Y Ticks (" + step + "px)";
                yTicks.property("ADBE Transform Group").property("ADBE Position").setValue([0, 0]);

                for (var yt = 0; yt <= H; yt += step) {
                    var isM10y = (yt > 0 && yt < H && yt % major10 === 0);
                    var isM5y = (yt > 0 && yt < H && yt % major5 === 0);
                    var tColY = isM10y ? [1, 0.9, 0.1] : [1, 1, 1];
                    var tWY = (yt === 0 || yt === H) ? 4 : (isM10y ? 5 : (isM5y ? 4 : 2));
                    var tLenY = isM10y ? 16 : (isM5y ? 14 : 11);
                    addLineToShapeLayer(yTicks, "L " + pad4(yt), [0, yt], [tLenY, yt], tColY, tWY, 95);
                    addLineToShapeLayer(yTicks, "R " + pad4(yt), [yRulerW - tLenY, yt], [yRulerW, yt], tColY, tWY, 95);

                    if (!yCollidesWithXRuler(yt)) {
                        var ySize = isM10y ? 30 : (isM5y ? 28 : 25);
                        var yClr = isM10y ? [1, 0.9, 0.1] : (isM5y ? [1, 1, 1] : [0.95, 0.95, 0.95]);
                        addTextLayer(
                            yComp,
                            "Y " + yt,
                            String(yt),
                            yRulerW / 2,
                            yt,
                            ySize,
                            yClr,
                            ParagraphJustification.CENTER_JUSTIFY
                        );
                    }
                }

                var yLeft = comp.layers.add(yComp);
                yLeft.name = "Y Ruler — Left (x=0.." + yRulerW + ")";
                yLeft.property("ADBE Transform Group").property("ADBE Position").setValue([yRulerW / 2, H / 2]);

                if (showYCenter && W >= step * 6) {
                    var midColX = Math.floor((W / 2) / step) * step;
                    var yMid = comp.layers.add(yComp);
                    yMid.name = "Y Ruler — Center";
                    yMid.property("ADBE Transform Group").property("ADBE Position").setValue([midColX + step / 2, H / 2]);
                }

                if (W >= yRulerW * 4) {
                    var yRight = comp.layers.add(yComp);
                    yRight.name = "Y Ruler — Right (x=" + (W - yRulerW) + ".." + W + ")";
                    yRight.property("ADBE Transform Group").property("ADBE Position").setValue([W - yRulerW / 2, H / 2]);
                }
            }

            // 6. X-Axis Ruler Strip Precomp
            if (showXRulers) {
                var xComp = app.project.items.addComp(
                    "X Ruler Strip " + W + " (" + step + "px)",
                    W, xRulerH, 1.0, dur, fps
                );
                xComp.bgColor = [0, 0, 0];
                xComp.parentFolder = assetsFolder;

                var xBg = xComp.layers.addShape();
                xBg.name = "Ruler Background";
                xBg.property("ADBE Transform Group").property("ADBE Position").setValue([0, 0]);
                addRectToShapeLayer(xBg, "Bar", W / 2, xRulerH / 2, W, xRulerH, [0.04, 0.04, 0.05], 88);
                addLineToShapeLayer(xBg, "Top Border", [0, 1], [W, 1], [1, 1, 1], 2, 70);
                addLineToShapeLayer(xBg, "Bottom Border", [0, xRulerH - 1], [W, xRulerH - 1], [1, 1, 1], 2, 70);

                var xTicks = xComp.layers.addShape();
                xTicks.name = "X Ticks (" + step + "px)";
                xTicks.property("ADBE Transform Group").property("ADBE Position").setValue([0, 0]);

                for (var xt = 0; xt <= W; xt += step) {
                    var isM10x = (xt > 0 && xt < W && xt % major10 === 0);
                    var isM5x = (xt > 0 && xt < W && xt % major5 === 0);
                    var tColX = isM10x ? [1, 0.9, 0.1] : [1, 1, 1];
                    var tWX = (xt === 0 || xt === W) ? 4 : (isM10x ? 6 : (isM5x ? 4 : 2));
                    var tLenX = isM10x ? 18 : (isM5x ? 15 : 12);
                    addLineToShapeLayer(xTicks, "T " + pad4(xt), [xt, 0], [xt, tLenX], tColX, tWX, 95);
                    addLineToShapeLayer(xTicks, "B " + pad4(xt), [xt, xRulerH - tLenX], [xt, xRulerH], tColX, tWX, 95);

                    if (xt === 0) {
                        addTextLayer(xComp, "X 0", "0", 8, xRulerH / 2, 28, [1, 1, 1], ParagraphJustification.LEFT_JUSTIFY);
                    } else if (W - xt >= 28) {
                        var xSize = isM10x ? 34 : (isM5x ? 30 : 27);
                        var xClr = isM10x ? [1, 0.9, 0.1] : (isM5x ? [1, 1, 1] : [0.95, 0.95, 0.95]);
                        addTextLayer(xComp, "X " + xt, String(xt), xt, xRulerH / 2, xSize, xClr, ParagraphJustification.CENTER_JUSTIFY);
                    }
                }
                if (W % step !== 0) {
                    addLineToShapeLayer(xTicks, "T " + pad4(W), [W, 0], [W, 14], [1, 1, 1], 4, 100);
                    addLineToShapeLayer(xTicks, "B " + pad4(W), [W, xRulerH - 14], [W, xRulerH], [1, 1, 1], 4, 100);
                }

                var xTop = comp.layers.add(xComp);
                xTop.name = "X Ruler — Top (y=0.." + xRulerH + ")";
                xTop.property("ADBE Transform Group").property("ADBE Position").setValue([W / 2, xRulerH / 2]);

                if (hasMidX) {
                    var xMid = comp.layers.add(xComp);
                    xMid.name = "X Ruler — Middle";
                    xMid.property("ADBE Transform Group").property("ADBE Position").setValue([W / 2, midXCenterY]);
                }

                var xBot = comp.layers.add(xComp);
                xBot.name = "X Ruler — Bottom (y=" + (H - xRulerH) + ".." + H + ")";
                xBot.property("ADBE Transform Group").property("ADBE Position").setValue([W / 2, H - xRulerH / 2]);
            }

            // 7. Info Badge
            if (showBadge) {
                var badgeY = hasMidX ? (midXCenterY + xRulerH / 2 + 54) : (H / 2);
                var badgeFontSize = (W < 1100) ? 24 : 34;
                var loopNote = animateHue ? ("  |  " + dur + "s LOOP") : "";
                var badgeStr = W + " \u00D7 " + H + "  |  " + step + "px PIXEL MAP" + loopNote;
                var badgeText = addTextLayer(
                    comp,
                    "Grid Info Label",
                    badgeStr,
                    W / 2,
                    badgeY,
                    badgeFontSize,
                    [1, 1, 1],
                    ParagraphJustification.CENTER_JUSTIFY,
                    30
                );
                var bRect = badgeText.sourceRectAtTime(0, false);
                var pillW = Math.min(W - 40, bRect.width + 56);
                var pillH = bRect.height + 30;
                var badgePill = comp.layers.addShape();
                badgePill.name = "Grid Info Pill";
                badgePill.property("ADBE Transform Group").property("ADBE Position").setValue([0, 0]);
                addRectToShapeLayer(
                    badgePill,
                    "Pill",
                    W / 2,
                    badgeY,
                    pillW,
                    pillH,
                    [0.04, 0.04, 0.05],
                    88,
                    12,
                    [1, 1, 1],
                    2,
                    65
                );
                badgePill.moveAfter(badgeText);
            }

            comp.openInViewer();
            return comp;
        } finally {
            app.endUndoGroup();
        }
    }

    // Expose globally so scripts / automation can also invoke directly
    $.global.buildEasyPixelMap = buildEasyPixelMap;

    // ---------- Dockable ScriptUI Panel ----------

    function buildUI(thisObj) {
        var win = (thisObj instanceof Panel)
            ? thisObj
            : new Window("palette", SCRIPT_NAME, undefined, { resizeable: true });

        win.orientation = "column";
        win.alignChildren = ["fill", "top"];
        win.spacing = 8;
        win.margins = 10;

        // COMP Panel
        var dimPanel = win.add("panel", undefined, "COMP");
        dimPanel.orientation = "column";
        dimPanel.alignChildren = ["fill", "top"];
        dimPanel.spacing = 6;
        dimPanel.margins = [8, 12, 8, 8];

        var rowName = dimPanel.add("group");
        rowName.orientation = "row";
        rowName.add("statictext", undefined, "Name:").preferredSize.width = 48;
        var inpName = rowName.add("edittext", undefined, "");
        inpName.alignment = ["fill", "center"];
        inpName.helpTip = "Leave blank to auto-name from resolution";

        var rowXY = dimPanel.add("group");
        rowXY.orientation = "row";
        rowXY.add("statictext", undefined, "X (W):").preferredSize.width = 42;
        var inpW = rowXY.add("edittext", undefined, "3840");
        inpW.preferredSize.width = 64;
        rowXY.add("statictext", undefined, "Y (H):").preferredSize.width = 42;
        var inpH = rowXY.add("edittext", undefined, "2160");
        inpH.preferredSize.width = 64;

        var rowStepFps = dimPanel.add("group");
        rowStepFps.orientation = "row";
        rowStepFps.add("statictext", undefined, "Step:").preferredSize.width = 42;
        var inpStep = rowStepFps.add("edittext", undefined, "100");
        inpStep.preferredSize.width = 64;
        rowStepFps.add("statictext", undefined, "FPS:").preferredSize.width = 42;
        var inpFps = rowStepFps.add("edittext", undefined, "60");
        inpFps.preferredSize.width = 64;

        // Build Button & Status
        var btnBuild = win.add("button", undefined, "Build Pixel Map");
        btnBuild.preferredSize.height = 30;
        var lblStatus = win.add("statictext", undefined, "Ready (30s seamless loop)");
        lblStatus.alignment = ["fill", "center"];

        btnBuild.onClick = function () {
            var w = parseInt(inpW.text, 10);
            var h = parseInt(inpH.text, 10);
            var st = parseInt(inpStep.text, 10);
            var fps = parseFloat(inpFps.text);

            if (isNaN(w) || w < 200 || isNaN(h) || h < 200) {
                alert("Please enter valid X and Y pixel dimensions (at least 200px).");
                return;
            }
            if (isNaN(st) || st < 20) {
                alert("Please enter a valid grid step (at least 20px).");
                return;
            }
            if (isNaN(fps) || fps <= 0) {
                alert("Please enter a valid FPS value.");
                return;
            }

            lblStatus.text = "Building " + w + "x" + h + "...";
            try {
                var c = buildEasyPixelMap({
                    name: inpName.text,
                    width: w,
                    height: h,
                    step: st,
                    fps: fps,
                    duration: 30,
                    cycles: 5,
                    animateHue: true,
                    showChecker: true,
                    showXRulers: true,
                    showYRulers: true,
                    showYCenter: false,
                    showBadge: true
                });
                lblStatus.text = "Built: " + c.name;
            } catch (err) {
                lblStatus.text = "Error: " + err.toString();
                alert("EasyPixelMap error:\n" + err.toString() + " (line " + err.line + ")");
            }
        };

        win.layout.layout(true);
        win.layout.resize();
        win.onResizing = win.onResize = function () {
            this.layout.resize();
        };
        return win;
    }

    // Only build UI when run interactively (skip if loaded purely as a library)
    if (!$.global.__EPM_NO_UI__) {
        var panel = buildUI(thisObj);
        if (panel instanceof Window) {
            panel.center();
            panel.show();
        }
    }

})(this);
